Debian Codegraph @

neutron_lib/tests/unit/api/definitions/base.py

raw
1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
11 # under the License.
12
13 import importlib.util
14 import os
15 import types
16
17 from neutron_lib.api import definitions
18 from neutron_lib.api.definitions import base
19 from neutron_lib.api import validators
20 from neutron_lib import constants
21 from neutron_lib.tests import _base as test_base
22
23
24 def assert_bool(tester, attribute, attribute_dict, keyword, value):
25 tester.assertIsInstance(
26 value, bool,
27 f'{keyword} must be a boolean for {attribute}.')
28
29
30 def assert_converter(tester, attribute, attribute_dict, keyword, value):
31 if ('default' not in attribute_dict or
32 attribute_dict['default'] is constants.ATTR_NOT_SPECIFIED or
33 attribute_dict.get(constants.DICT_POPULATE_DEFAULTS)):
34 return
35 try:
36 attribute_dict['convert_to'](attribute_dict['default'])
37 except KeyError:
38 try:
39 attribute_dict['convert_list_to'](attribute_dict['default'])
40 except KeyError:
41 if validators.is_attr_set(value) and not isinstance(
42 value, str | list):
43 tester.fail(f"Default value '{value}' cannot be converted for "
44 f"attribute {attribute}.")
45
46
47 def assert_true(tester, attribute, attribute_dict, keyword, value):
48 tester.assertTrue(
49 value, f'{keyword} must be True for {attribute}.')
50
51
52 def assert_validator(tester, attribute, attribute_dict, keyword, value):
53 tester.assertIn(list(value)[0], validators.validators,
54 f'{value} is not a known validator for {attribute}.')
55
56
57 ASSERT_FUNCTIONS = {
58 'allow_post': assert_bool,
59 'allow_put': assert_bool,
60 'convert_to': assert_converter,
61 'convert_list_to': assert_converter,
62 'default': assert_converter,
63 'enforce_policy': assert_bool,
64 'is_filter': assert_bool,
65 'is_sort_key': assert_bool,
66 'is_visible': assert_bool,
67 'primary_key': assert_true,
68 'required_by_policy': assert_bool,
69 'validate': assert_validator,
70 'default_overrides_none': assert_bool,
71 'dict_populate_defaults': assert_bool,
72 }
73
74
75 class DefinitionBaseTestCase(test_base.BaseTestCase):
76
77 extension_module: types.ModuleType | None = None
78 extension_resources: tuple[str, ...] = ()
79 extension_subresources: tuple[str, ...] = ()
80 extension_attributes: tuple[str, ...] = ()
81
82 def setUp(self):
83 super().setUp()
84 if not self.extension_module:
85 self.fail("Missing extension module definition.")
86 self.alias = self.extension_module.ALIAS
87 self.is_shim_extension = self.extension_module.IS_SHIM_EXTENSION
88 self.is_standard_attr_extension = (
89 self.extension_module.IS_STANDARD_ATTR_EXTENSION)
90 self.name = self.extension_module.NAME
91 self.description = self.extension_module.DESCRIPTION
92 self.resource_map = self.extension_module.RESOURCE_ATTRIBUTE_MAP
93 self.subresource_map = self.extension_module.SUB_RESOURCE_ATTRIBUTE_MAP
94 self.action_map = self.extension_module.ACTION_MAP
95 self.action_status = self.extension_module.ACTION_STATUS
96 self.required_extensions = self.extension_module.REQUIRED_EXTENSIONS
97 self.optional_extensions = self.extension_module.OPTIONAL_EXTENSIONS
98
99 def test_shim_extension(self):
100 if self.is_shim_extension is True:
101 self.assertFalse(self.extension_resources)
102 self.assertFalse(self.extension_attributes)
103 self.assertFalse(self.resource_map)
104 self.assertFalse(self.action_map)
105 self.assertFalse(self.action_status)
106
107 def test_is_standard_attr_extension(self):
108 if self.is_standard_attr_extension:
109 self.assertIn('standard-attr-', self.alias)
110 else:
111 self.skipTest('API definition is not related to standardattr.')
112
113 def test_resource_map(self):
114 if (not self.resource_map and not self.subresource_map and
115 not self.is_shim_extension and not self.action_map):
116 self.fail('Missing resource map, subresource map, '
117 'and action map, what is this extension doing?')
118 elif self.is_shim_extension:
119 self.skipTest('Shim extension with no API changes.')
120
121 for resource in self.resource_map:
122 self.assertIn(
123 resource, base.KNOWN_RESOURCES + self.extension_resources,
124 'Resource is unknown, check for typos.')
125 self.assertParams(self.resource_map[resource])
126
127 def assertParams(self, resource):
128 for attribute in resource.keys():
129 self.assertIn(
130 attribute,
131 base.KNOWN_ATTRIBUTES + self.extension_attributes,
132 'Attribute is unknown, check for typos.')
133 for keyword in resource[attribute]:
134 self.assertIn(keyword, base.KNOWN_KEYWORDS,
135 'Keyword is unknown, check for typos.')
136 value = resource[attribute][keyword]
137 assert_f = ASSERT_FUNCTIONS[keyword]
138 assert_f(self, attribute,
139 resource[attribute],
140 keyword, value)
141
142 def _assert_subresource(self, subresource):
143 self.assertIn(
144 self.subresource_map[subresource]['parent']['collection_name'],
145 base.KNOWN_RESOURCES + self.extension_resources,
146 'Sub-resource parent is unknown, check for typos.')
147 self.assertIn('member_name',
148 self.subresource_map[subresource]['parent'],
149 'Incorrect parent definition, check for typos.')
150 self.assertParams(self.subresource_map[subresource]['parameters'])
151
152 def test_subresource_map(self):
153 if not self.subresource_map:
154 self.skipTest('API extension has no subresource map.')
155 for subresource in self.subresource_map:
156 self.assertIn(
157 subresource,
158 self.extension_subresources + base.KNOWN_RESOURCES,
159 'Sub-resource is unknown, check for typos.')
160 sub_attrmap = self.subresource_map[subresource]
161 if 'parent' in sub_attrmap:
162 self.assertEqual(2, len(sub_attrmap.keys()))
163 self.assertIn('parent', sub_attrmap)
164 self.assertIn('parameters', sub_attrmap)
165 self._assert_subresource(subresource)
166 else:
167 self.assertEqual(
168 ['parameters'], list(sub_attrmap.keys()),
169 'When extending sub-resources only use the parameters '
170 'keyword')
171 self.assertParams(sub_attrmap['parameters'])
172
173 def test_action_map(self):
174 self.assertIsInstance(self.action_map, dict)
175 if not self.action_map:
176 self.skipTest('API definition has no action map.')
177
178 for key in self.action_map:
179 for action in self.action_map[key].values():
180 self.assertIn(action, base.KNOWN_HTTP_ACTIONS,
181 'HTTP verb is unknown, check for typos.')
182
183 def test_action_status(self):
184 if not self.action_status:
185 self.skipTest('API definition has no action status.')
186
187 for status in self.action_status.values():
188 self.assertIn(status, base.KNOWN_ACTION_STATUSES,
189 'HTTP status is unknown, check for typos.')
190
191 def test_required_extensions(self):
192 self.assertIsInstance(self.required_extensions, list)
193 if not self.required_extensions:
194 self.skipTest('API definition has no required extensions.')
195
196 for ext in self.required_extensions:
197 self.assertIn(ext, base.KNOWN_EXTENSIONS,
198 'Required extension is unknown, check for typos.')
199
200 def test_optional_extensions(self):
201 self.assertIsInstance(self.optional_extensions, list)
202 if not self.optional_extensions:
203 self.skipTest('API definition has no optional extensions.')
204
205 for ext in self.optional_extensions:
206 self.assertIn(ext, base.KNOWN_EXTENSIONS,
207 'Optional extension is unknown, check for typos.')
208
209 def _load_module(self, name, path):
210 module_spec = importlib.util.spec_from_file_location(
211 name, path
212 )
213 module = importlib.util.module_from_spec(module_spec)
214 module_spec.loader.exec_module(module)
215 return module
216
217 def test_all_api_definitions_list(self):
218 # ensure _ALL_API_DEFINITIONS contains all public api-defs
219 ext_aliases = []
220 api_def_path = 'neutron_lib/api/definitions'
221 for f in sorted(os.listdir(api_def_path)):
222 mod_name, file_ext = os.path.splitext(os.path.split(f)[-1])
223 ext_path = os.path.join(api_def_path, f)
224 if file_ext.lower() == '.py' and not mod_name.startswith('_'):
225 mod = self._load_module(mod_name, ext_path)
226 ext_alias = getattr(mod, 'ALIAS', None)
227 if not ext_alias:
228 continue
229 ext_aliases.append(ext_alias)
230
231 self.assertEqual(sorted(ext_aliases),
232 sorted([d.ALIAS for d in
233 definitions._ALL_API_DEFINITIONS]))