Debian Codegraph @

neutron_lib/tests/unit/api/test_attributes.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 from oslo_utils import uuidutils
14 import testtools
15 from webob import exc
16
17 from neutron_lib.api import attributes
18 from neutron_lib.api import converters
19 from neutron_lib.api.definitions import network
20 from neutron_lib.api.definitions import port
21 from neutron_lib.api.definitions import subnet
22 from neutron_lib.api.definitions import subnetpool
23 from neutron_lib import constants
24 from neutron_lib import context
25 from neutron_lib import exceptions
26
27 from neutron_lib.tests import _base as base
28
29
30 class TestPopulateProjectInfo(base.BaseTestCase):
31
32 def test_populate_project_info_add_project(self):
33 attrs_in = {'tenant_id': uuidutils.generate_uuid()}
34 attrs_out = attributes.populate_project_info(attrs_in)
35 self.assertIn('project_id', attrs_out)
36 self.assertEqual(attrs_in['tenant_id'], attrs_out['project_id'])
37 self.assertEqual(2, len(attrs_out))
38
39 def test_populate_project_info_add_tenant(self):
40 attrs_in = {'project_id': uuidutils.generate_uuid()}
41 attrs_out = attributes.populate_project_info(attrs_in)
42 self.assertIn('tenant_id', attrs_out)
43 self.assertEqual(attrs_in['project_id'], attrs_out['tenant_id'])
44 self.assertEqual(2, len(attrs_out))
45
46 def test_populate_project_info_ids_match(self):
47 project_id = uuidutils.generate_uuid()
48 attrs_in = {'project_id': project_id, 'tenant_id': project_id}
49 attrs_out = attributes.populate_project_info(attrs_in)
50 self.assertEqual(attrs_in, attrs_out)
51
52 def test_populate_project_info_id_mismatch(self):
53 attrs = {
54 'project_id': uuidutils.generate_uuid(),
55 'tenant_id': uuidutils.generate_uuid()
56 }
57 self.assertRaises(exc.HTTPBadRequest,
58 attributes.populate_project_info, attrs)
59
60
61 class TestAttributeInfo(base.BaseTestCase):
62
63 class _MyException(Exception):
64 pass
65
66 _EXC_CLS = _MyException
67 _RESOURCE_NAME = 'thing'
68 _RESOURCE_ATTRS = {'name': {}, 'type': {}}
69 _RESOURCE_MAP = {_RESOURCE_NAME: _RESOURCE_ATTRS}
70 _ATTRS_INSTANCE = attributes.AttributeInfo(_RESOURCE_MAP)
71
72 def test_create_from_attribute_info_instance(self):
73 cloned_attrs = attributes.AttributeInfo(
74 TestAttributeInfo._ATTRS_INSTANCE)
75
76 self.assertEqual(TestAttributeInfo._ATTRS_INSTANCE.attributes,
77 cloned_attrs.attributes)
78
79 def test_create_from_api_def(self):
80 self.assertEqual(
81 port.RESOURCE_ATTRIBUTE_MAP,
82 attributes.AttributeInfo(port.RESOURCE_ATTRIBUTE_MAP).attributes)
83
84 def _test_fill_default_value(self, attr_inst, expected, res_dict,
85 check_allow_post=True):
86 attr_inst.fill_post_defaults(
87 res_dict, check_allow_post=check_allow_post)
88 self.assertEqual(expected, res_dict)
89
90 def test_fill_default_value_ok(self):
91 attr_info = {
92 'key': {
93 'allow_post': True,
94 'default': constants.ATTR_NOT_SPECIFIED,
95 },
96 }
97 attr_inst = attributes.AttributeInfo(attr_info)
98 self._test_fill_default_value(attr_inst, {'key': 'X'}, {'key': 'X'})
99 self._test_fill_default_value(
100 attr_inst, {'key': constants.ATTR_NOT_SPECIFIED}, {})
101
102 def test_override_no_allow_post(self):
103 attr_info = {
104 'key': {
105 'allow_post': False,
106 'default': constants.ATTR_NOT_SPECIFIED,
107 },
108 }
109 attr_inst = attributes.AttributeInfo(attr_info)
110 self._test_fill_default_value(attr_inst, {'key': 'X'}, {'key': 'X'},
111 check_allow_post=False)
112
113 def test_fill_no_default_value_allow_post(self):
114 attr_info = {
115 'key': {
116 'allow_post': True,
117 },
118 }
119 attr_inst = attributes.AttributeInfo(attr_info)
120 self._test_fill_default_value(attr_inst, {'key': 'X'}, {'key': 'X'})
121 self.assertRaises(exceptions.InvalidInput,
122 self._test_fill_default_value,
123 attr_inst, {'key': 'X'}, {})
124 self.assertRaises(self._EXC_CLS, attr_inst.fill_post_defaults,
125 {}, self._EXC_CLS)
126
127 def test_fill_no_default_value_no_allow_post(self):
128 attr_info = {
129 'key': {
130 'allow_post': False,
131 },
132 }
133 attr_inst = attributes.AttributeInfo(attr_info)
134 self.assertRaises(exceptions.InvalidInput,
135 self._test_fill_default_value,
136 attr_inst, {'key': 'X'}, {'key': 'X'})
137 self._test_fill_default_value(attr_inst, {}, {})
138 self.assertRaises(self._EXC_CLS, attr_inst.fill_post_defaults,
139 {'key': 'X'}, self._EXC_CLS)
140
141 def test_fill_none_overridden_by_default(self):
142 attr_info = {
143 'key': {
144 'allow_post': True,
145 'default': 42,
146 'default_overrides_none': True,
147 },
148 }
149 attr_inst = attributes.AttributeInfo(attr_info)
150 self._test_fill_default_value(attr_inst, {'key': 42}, {'key': None})
151
152 def _test_convert_value(self, attr_inst, expected, res_dict):
153 attr_inst.convert_values(res_dict)
154 self.assertEqual(expected, res_dict)
155
156 def test_convert_value(self):
157 attr_info = {
158 'key': {
159 },
160 }
161 attr_inst = attributes.AttributeInfo(attr_info)
162 self._test_convert_value(attr_inst,
163 {'key': constants.ATTR_NOT_SPECIFIED},
164 {'key': constants.ATTR_NOT_SPECIFIED})
165 self._test_convert_value(attr_inst, {'key': 'X'}, {'key': 'X'})
166 self._test_convert_value(attr_inst,
167 {'other_key': 'X'}, {'other_key': 'X'})
168
169 attr_info = {
170 'key': {
171 'convert_to': converters.convert_to_int,
172 },
173 }
174 attr_inst = attributes.AttributeInfo(attr_info)
175 self._test_convert_value(attr_inst,
176 {'key': constants.ATTR_NOT_SPECIFIED},
177 {'key': constants.ATTR_NOT_SPECIFIED})
178 self._test_convert_value(attr_inst, {'key': 1}, {'key': '1'})
179 self._test_convert_value(attr_inst, {'key': 1}, {'key': 1})
180 self.assertRaises(exceptions.InvalidInput, self._test_convert_value,
181 attr_inst, {'key': 1}, {'key': 'a'})
182
183 attr_info = {
184 'key': {
185 'validate': {'type:uuid': None},
186 },
187 }
188 attr_inst = attributes.AttributeInfo(attr_info)
189 self._test_convert_value(attr_inst,
190 {'key': constants.ATTR_NOT_SPECIFIED},
191 {'key': constants.ATTR_NOT_SPECIFIED})
192 uuid_str = '01234567-1234-1234-1234-1234567890ab'
193 self._test_convert_value(attr_inst,
194 {'key': uuid_str}, {'key': uuid_str})
195 self.assertRaises(exceptions.InvalidInput, self._test_convert_value,
196 attr_inst, {'key': 1}, {'key': 1})
197 self.assertRaises(self._EXC_CLS, attr_inst.convert_values,
198 {'key': 1}, self._EXC_CLS)
199
200 def test_populate_project_id_admin_req(self):
201 project_id_1 = uuidutils.generate_uuid()
202 project_id_2 = uuidutils.generate_uuid()
203 # non-admin users can't create a res on behalf of another project
204 ctx = context.Context(user_id=None, project_id=project_id_1)
205 res_dict = {'project_id': project_id_2}
206 attr_inst = attributes.AttributeInfo({})
207 self.assertRaises(exc.HTTPBadRequest,
208 attr_inst.populate_project_id,
209 ctx, res_dict, None)
210 # but admin users can
211 ctx.is_admin = True
212 attr_inst.populate_project_id(ctx, res_dict, is_create=False)
213
214 def test_populate_project_id_from_context(self):
215 project_id = uuidutils.generate_uuid()
216 ctx = context.Context(user_id=None, project_id=project_id)
217 # for each create request, for the resources which require project_id,
218 # it should be added to the req body
219 res_dict = {}
220 attr_inst = attributes.AttributeInfo(
221 {'project_id': {'allow_post': True}})
222 attr_inst.populate_project_id(ctx, res_dict, is_create=True)
223 self.assertEqual(
224 {'tenant_id': ctx.project_id, 'project_id': ctx.project_id},
225 res_dict)
226
227 def test_populate_project_id_mandatory_not_specified(self):
228 project_id = uuidutils.generate_uuid()
229 ctx = context.Context(user_id=None, project_id=project_id)
230 # if the project_id is mandatory for the resource and not specified
231 # in the request nor in the context, an exception should be raised
232 res_dict = {}
233 attr_info = {'project_id': {'allow_post': True}}
234 ctx.project_id = None
235 attr_inst = attributes.AttributeInfo(attr_info)
236 self.assertRaises(exc.HTTPBadRequest,
237 attr_inst.populate_project_id,
238 ctx, res_dict, True)
239
240 def test_populate_project_id_not_mandatory(self):
241 ctx = context.Context(user_id=None)
242 # if the project_id is not mandatory for the resource it should be
243 # OK if it is not in the request.
244 res_dict = {'name': 'test_port'}
245 attr_inst = attributes.AttributeInfo({})
246 ctx.project_id = None
247 attr_inst.populate_project_id(ctx, res_dict, True)
248 self.assertEqual({'name': 'test_port'}, res_dict)
249
250 def test_verify_attributes_null(self):
251 attributes.AttributeInfo({}).verify_attributes({})
252
253 def test_verify_attributes_ok_with_project_id(self):
254 attributes.AttributeInfo(
255 {'tenant_id': 'foo', 'project_id': 'foo'}).verify_attributes(
256 {'project_id': 'foo'})
257
258 def test_verify_attributes_ok_subset(self):
259 attributes.AttributeInfo(
260 {'attr1': 'foo', 'attr2': 'bar'}).verify_attributes(
261 {'attr1': 'foo'})
262
263 def test_verify_attributes_unrecognized(self):
264 with testtools.ExpectedException(exc.HTTPBadRequest) as bad_req:
265 attributes.AttributeInfo(
266 {'attr1': 'foo'}).verify_attributes(
267 {'attr1': 'foo', 'attr2': 'bar'})
268 self.assertEqual(bad_req.message,
269 "Unrecognized attribute(s) 'attr2'")
270
271
272 class TestCoreResources(base.BaseTestCase):
273
274 CORE_DEFS = [network, port, subnet, subnetpool]
275
276 def test_core_resource_names(self):
277 self.assertEqual(
278 sorted([r.COLLECTION_NAME for r in TestCoreResources.CORE_DEFS]),
279 sorted(attributes.RESOURCES.keys()))
280
281 def test_core_resource_attrs(self):
282 for r in TestCoreResources.CORE_DEFS:
283 self.assertIs(r.RESOURCE_ATTRIBUTE_MAP[r.COLLECTION_NAME],
284 attributes.RESOURCES[r.COLLECTION_NAME])
285
286
287 class TestValidatePriviliges(base.BaseTestCase):
288
289 def test__validate_privileges_same_tenant(self):
290 project_id = 'fake_project'
291 ctx = context.Context(project_id=project_id)
292 res_dict = {'project_id': project_id}
293 try:
294 attributes._validate_privileges(ctx, res_dict)
295 except exc.HTTPBadRequest:
296 self.fail("HTTPBadRequest exception should not be raised.")
297
298 def test__validate_privileges_user_other_tenant(self):
299 project_id = 'fake_project'
300 ctx = context.Context(project_id='fake_project2')
301 res_dict = {'project_id': project_id}
302 self.assertRaises(
303 exc.HTTPBadRequest,
304 attributes._validate_privileges,
305 ctx, res_dict)
306
307 def test__validate_privileges_admin_other_tenant(self):
308 project_id = 'fake_project'
309 ctx = context.Context(project_id='fake_project2',
310 is_admin=True)
311 res_dict = {'project_id': project_id}
312 try:
313 attributes._validate_privileges(ctx, res_dict)
314 except exc.HTTPBadRequest:
315 self.fail("HTTPBadRequest exception should not be raised.")
316
317 def test__validate_privileges_advsvc_other_tenant(self):
318 project_id = 'fake_project'
319 ctx = context.Context(project_id='fake_project2',
320 is_advsvc=True)
321 res_dict = {'project_id': project_id}
322 try:
323 attributes._validate_privileges(ctx, res_dict)
324 except exc.HTTPBadRequest:
325 self.fail("HTTPBadRequest exception should not be raised.")
326
327 def test__validate_privileges_service_role_other_tenant(self):
328 project_id = 'fake_project'
329 ctx = context.Context(project_id='fake_project2',
330 roles=['service'])
331 res_dict = {'project_id': project_id}
332 try:
333 attributes._validate_privileges(ctx, res_dict)
334 except exc.HTTPBadRequest:
335 self.fail("HTTPBadRequest exception should not be raised.")
336
337
338 class TestRetrieveValidSortKeys(base.BaseTestCase):
339
340 def test_retrieve_valid_sort_keys(self):
341 attr_info = {
342 "id": {
343 "visible": True,
344 "is_sort_key": True
345 },
346 "name": {
347 "is_sort_key": True
348 },
349 "created_at": {
350 "is_sort_key": False
351 },
352 "tenant_id": {
353 "visible": True,
354 },
355 "project_id": {
356 "visible": True,
357 }
358 }
359 expect_val = {"id", "name"}
360 actual_val = attributes.retrieve_valid_sort_keys(attr_info)
361 self.assertEqual(expect_val, actual_val)