Debian Codegraph @

oslo_limit/tests/test_limit.py

raw symbols SCIP
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 """
14 test_limit
15 ----------------------------------
16 Tests for `limit` module.
17 """
18
19 from collections.abc import Iterable
20 from typing import Any
21 from unittest import mock
22 import uuid
23
24 from openstack import exceptions as os_exceptions
25 from openstack.identity.v3 import endpoint
26 from openstack.identity.v3 import limit as klimit
27 from openstack.identity.v3 import region
28 from openstack.identity.v3 import registered_limit
29 from openstack.identity.v3 import service
30 from oslo_config import cfg
31 from oslo_config import fixture as config_fixture
32 from oslotest import base
33
34 from oslo_limit import exception
35 from oslo_limit import fixture
36 from oslo_limit import limit
37 from oslo_limit import opts
38
39 CONF = cfg.CONF
40
41
42 class TestEnforcer(base.BaseTestCase):
43 def setUp(self):
44 super().setUp()
45 self.deltas = dict()
46 self.config_fixture = self.useFixture(config_fixture.Config(CONF))
47 self.config_fixture.config(group='oslo_limit', auth_type='password')
48 self.config_fixture.config(
49 group='oslo_limit', endpoint_id='ENDPOINT_ID'
50 )
51 opts.register_opts(CONF)
52 self.config_fixture.config(
53 group='oslo_limit', auth_url='http://identity.example.com'
54 )
55
56 limit._SDK_CONNECTION = mock.MagicMock()
57 json = mock.MagicMock()
58 json.json.return_value = {"model": {"name": "flat"}}
59 limit._SDK_CONNECTION.get.return_value = json
60
61 def _get_usage_for_project(self, project_id, resource_names):
62 return {"a": 1}
63
64 def test_usage_callback_must_be_callable(self):
65 invalid_callback_types = [uuid.uuid4().hex, 5, 5.1]
66
67 for invalid_callback in invalid_callback_types:
68 self.assertRaises(ValueError, limit.Enforcer, invalid_callback)
69
70 def test_deltas_must_be_a_dictionary(self):
71 project_id = uuid.uuid4().hex
72 invalid_delta_types = [uuid.uuid4().hex, 5, 5.1, True, [], None, {}]
73 enforcer = limit.Enforcer(self._get_usage_for_project)
74
75 for invalid_delta in invalid_delta_types:
76 self.assertRaises(
77 ValueError, enforcer.enforce, project_id, invalid_delta
78 )
79
80 def test_project_id_must_be_a_string(self):
81 enforcer = limit.Enforcer(self._get_usage_for_project)
82 invalid_delta_types = [{}, 5, 5.1, True, False, [], None, ""]
83 for invalid_project_id in invalid_delta_types:
84 self.assertRaises(
85 ValueError, enforcer.enforce, invalid_project_id, {}
86 )
87
88 def test_set_model_impl(self):
89 enforcer = limit.Enforcer(self._get_usage_for_project)
90 self.assertIsInstance(enforcer.model, limit._FlatEnforcer)
91
92 def test_get_model_impl(self):
93 json = mock.MagicMock()
94 limit._SDK_CONNECTION.get.return_value = json # type: ignore
95
96 json.json.return_value = {"model": {"name": "flat"}}
97 enforcer = limit.Enforcer(self._get_usage_for_project)
98 flat_impl = enforcer._get_model_impl(self._get_usage_for_project)
99 self.assertIsInstance(flat_impl, limit._FlatEnforcer)
100
101 json.json.return_value = {"model": {"name": "strict-two-level"}}
102 flat_impl = enforcer._get_model_impl(self._get_usage_for_project)
103 self.assertIsInstance(flat_impl, limit._StrictTwoLevelEnforcer)
104
105 json.json.return_value = {"model": {"name": "foo"}}
106 e = self.assertRaises(
107 ValueError, enforcer._get_model_impl, self._get_usage_for_project
108 )
109 self.assertEqual("enforcement model foo is not supported", str(e))
110
111 @mock.patch.object(limit._FlatEnforcer, "enforce")
112 def test_enforce(self, mock_enforce):
113 enforcer = limit.Enforcer(self._get_usage_for_project)
114 project_id = uuid.uuid4().hex
115 deltas = {"a": 1}
116
117 enforcer.enforce(project_id, deltas)
118
119 mock_enforce.assert_called_once_with(project_id, deltas)
120
121 @mock.patch.object(limit._EnforcerUtils, "get_project_limits")
122 def test_calculate_usage(self, mock_get_limits):
123 mock_usage = mock.MagicMock()
124 mock_usage.return_value = {'a': 1, 'b': 2}
125
126 project_id = uuid.uuid4().hex
127 mock_get_limits.return_value = [('a', 10), ('b', 5)]
128
129 expected = {
130 'a': limit.ProjectUsage(10, 1),
131 'b': limit.ProjectUsage(5, 2),
132 }
133
134 enforcer = limit.Enforcer(mock_usage)
135 self.assertEqual(
136 expected, enforcer.calculate_usage(project_id, ['a', 'b'])
137 )
138
139 @mock.patch.object(limit._EnforcerUtils, "_get_project_limit")
140 @mock.patch.object(limit._EnforcerUtils, "_get_registered_limit")
141 def test_calculate_and_enforce_some_missing(
142 self, mock_get_reglimit, mock_get_limit
143 ):
144 # Registered and project limits for a and b, c is unregistered
145 reg_limits = {
146 'a': mock.MagicMock(default_limit=10),
147 'b': mock.MagicMock(default_limit=10),
148 }
149 prj_limits = {('bar', 'b'): mock.MagicMock(resource_limit=6)}
150 mock_get_reglimit.side_effect = lambda r: reg_limits.get(r)
151 mock_get_limit.side_effect = lambda p, r: prj_limits.get((p, r))
152
153 # Regardless, we have usage for all three
154 mock_usage = mock.MagicMock()
155 mock_usage.return_value = {'a': 5, 'b': 5, 'c': 5}
156
157 enforcer = limit.Enforcer(mock_usage)
158
159 # When we calculate usage, we should expect the default limit
160 # of zero for the unregistered limit
161 expected = {
162 'a': limit.ProjectUsage(10, 5),
163 'b': limit.ProjectUsage(6, 5),
164 'c': limit.ProjectUsage(0, 5),
165 }
166 self.assertEqual(
167 expected, enforcer.calculate_usage('bar', ['a', 'b', 'c'])
168 )
169
170 # Make sure that if we enforce, we get the expected behavior
171 # of c being considered to be zero
172 self.assertRaises(
173 exception.ProjectOverLimit,
174 enforcer.enforce,
175 'bar',
176 {'a': 1, 'b': 0, 'c': 1},
177 )
178
179 def test_calculate_usage_bad_params(self):
180 enforcer = limit.Enforcer(mock.MagicMock())
181
182 # Non-string project_id
183 self.assertRaises(ValueError, enforcer.calculate_usage, 123, ['foo'])
184
185 # Zero-length resources_to_check
186 self.assertRaises(ValueError, enforcer.calculate_usage, 'project', [])
187
188 # Non-sequence resources_to_check
189 self.assertRaises(ValueError, enforcer.calculate_usage, 'project', 123)
190
191 # Invalid non-string value in resources_to_check
192 self.assertRaises(
193 ValueError, enforcer.calculate_usage, 'project', ['a', 123, 'b']
194 )
195
196 @mock.patch.object(limit._EnforcerUtils, "get_registered_limits")
197 def test_get_registered_limits(self, mock_get_limits):
198 mock_get_limits.return_value = [("a", 1), ("b", 0), ("c", 2)]
199
200 enforcer = limit.Enforcer(lambda: None) # type: ignore
201 limits = enforcer.get_registered_limits(["a", "b", "c"])
202
203 mock_get_limits.assert_called_once_with(["a", "b", "c"])
204 self.assertEqual(mock_get_limits.return_value, limits)
205
206 @mock.patch.object(limit._EnforcerUtils, "get_project_limits")
207 def test_get_project_limits(self, mock_get_limits):
208 project_id = uuid.uuid4().hex
209 mock_get_limits.return_value = [("a", 1), ("b", 0), ("c", 2)]
210
211 enforcer = limit.Enforcer(lambda: None) # type: ignore
212 limits = enforcer.get_project_limits(project_id, ["a", "b", "c"])
213
214 mock_get_limits.assert_called_once_with(project_id, ["a", "b", "c"])
215 self.assertEqual(mock_get_limits.return_value, limits)
216
217 def test_calculate_usage_cache(self, cache=True):
218 project_id = uuid.uuid4().hex
219 fix = self.useFixture(
220 fixture.LimitFixture(
221 {'a': 5, 'b': 7, 'c': 8, 'd': 3},
222 {project_id: {'a': 2, 'b': 4}, 'other': {'a': 1, 'b': 2}},
223 )
224 )
225 mock_usage = mock.MagicMock()
226 mock_usage.return_value = {'a': 1, 'b': 3, 'c': 2, 'd': 0}
227
228 enforcer = limit.Enforcer(mock_usage, cache=cache)
229 expected = {
230 'a': limit.ProjectUsage(2, 1),
231 'b': limit.ProjectUsage(4, 3),
232 'c': limit.ProjectUsage(8, 2),
233 'd': limit.ProjectUsage(3, 0),
234 }
235 self.assertEqual(
236 expected,
237 enforcer.calculate_usage(project_id, ['a', 'b', 'c', 'd']),
238 )
239
240 # If caching is enabled, there should be three calls to the GET /limits
241 # API: one for 'a' and 'b' and two because of cache misses for 'c' and
242 # 'd' (the project_id has not set a per-project limit for 'c' or 'd',
243 # so they will not be cached for the project).
244 # If caching is disabled, there should be four calls to the GET
245 # /limits API, one for each of 'a', 'b', 'c', and 'd'.
246 expected_count = 3 if cache else 4
247 self.assertEqual(expected_count, fix.mock_conn.limits.call_count)
248
249 # If caching is enabled, there should be one call to the GET
250 # /registered_limits API for 'c' and 'd'.
251 # If caching is disabled, there should be two calls to the GET
252 # /registered_limits API, one for each of 'c' and 'd'.
253 expected_count = 1 if cache else 2
254 self.assertEqual(
255 expected_count, fix.mock_conn.registered_limits.call_count
256 )
257
258 def test_calculate_usage_no_cache(self):
259 self.test_calculate_usage_cache(cache=False)
260
261
262 class TestFlatEnforcer(base.BaseTestCase):
263 def setUp(self):
264 super().setUp()
265 self.config_fixture = self.useFixture(config_fixture.Config(CONF))
266 self.config_fixture.config(
267 group='oslo_limit', endpoint_id='ENDPOINT_ID'
268 )
269 opts.register_opts(CONF)
270 self.mock_conn = mock.MagicMock()
271 limit._SDK_CONNECTION = self.mock_conn
272
273 @mock.patch.object(limit._EnforcerUtils, "get_registered_limits")
274 def test_get_registered_limits(self, mock_get_limits):
275 mock_get_limits.return_value = [("a", 1), ("b", 0), ("c", 2)]
276
277 enforcer = limit._FlatEnforcer(lambda: None) # type: ignore
278 limits = enforcer.get_registered_limits(["a", "b", "c"])
279
280 mock_get_limits.assert_called_once_with(["a", "b", "c"])
281 self.assertEqual(mock_get_limits.return_value, limits)
282
283 @mock.patch.object(limit._EnforcerUtils, "get_project_limits")
284 def test_get_project_limits(self, mock_get_limits):
285 project_id = uuid.uuid4().hex
286 mock_get_limits.return_value = [("a", 1), ("b", 0), ("c", 2)]
287
288 enforcer = limit._FlatEnforcer(lambda: None) # type: ignore
289 limits = enforcer.get_project_limits(project_id, ["a", "b", "c"])
290
291 mock_get_limits.assert_called_once_with(project_id, ["a", "b", "c"])
292 self.assertEqual(mock_get_limits.return_value, limits)
293
294 @mock.patch.object(limit._EnforcerUtils, "get_project_limits")
295 def test_enforce(self, mock_get_limits):
296 mock_usage = mock.MagicMock()
297
298 project_id = uuid.uuid4().hex
299 deltas = {"a": 1, "b": 1}
300 mock_get_limits.return_value = [("a", 1), ("b", 2)]
301 mock_usage.return_value = {"a": 0, "b": 1}
302
303 enforcer = limit._FlatEnforcer(mock_usage)
304 enforcer.enforce(project_id, deltas)
305
306 self.mock_conn.get_endpoint.assert_called_once_with('ENDPOINT_ID')
307 mock_get_limits.assert_called_once_with(project_id, ["a", "b"])
308 mock_usage.assert_called_once_with(project_id, ["a", "b"])
309
310 @mock.patch.object(limit._EnforcerUtils, "get_project_limits")
311 def test_enforce_raises_on_over(self, mock_get_limits):
312 mock_usage = mock.MagicMock()
313
314 project_id = uuid.uuid4().hex
315 deltas = {"a": 2, "b": 1}
316 mock_get_limits.return_value = [("a", 1), ("b", 2)]
317 mock_usage.return_value = {"a": 0, "b": 1}
318
319 enforcer = limit._FlatEnforcer(mock_usage)
320 e = self.assertRaises(
321 exception.ProjectOverLimit, enforcer.enforce, project_id, deltas
322 )
323 expected = (
324 "Project %s is over a limit for "
325 "[Resource a is over limit of 1 due to current usage 0 "
326 "and delta 2]"
327 )
328 self.assertEqual(expected % project_id, str(e))
329 self.assertEqual(project_id, e.project_id)
330 self.assertEqual(1, len(e.over_limit_info_list))
331 over_a = e.over_limit_info_list[0]
332 self.assertEqual("a", over_a.resource_name)
333 self.assertEqual(1, over_a.limit)
334 self.assertEqual(0, over_a.current_usage)
335 self.assertEqual(2, over_a.delta)
336
337 @mock.patch.object(limit._EnforcerUtils, "_get_project_limit")
338 @mock.patch.object(limit._EnforcerUtils, "_get_registered_limit")
339 def test_enforce_raises_on_missing_limit(
340 self, mock_get_reglimit, mock_get_limit
341 ):
342 def mock_usage(*a):
343 return {'a': 1, 'b': 1}
344
345 project_id = uuid.uuid4().hex
346 deltas = {"a": 0, "b": 0}
347 mock_get_reglimit.return_value = None
348 mock_get_limit.return_value = None
349
350 enforcer = limit._FlatEnforcer(mock_usage)
351 self.assertRaises(
352 exception.ProjectOverLimit, enforcer.enforce, project_id, deltas
353 )
354
355 self.assertRaises(
356 exception.ProjectOverLimit, enforcer.enforce, None, deltas
357 )
358
359
360 class TestEnforcerUtils(base.BaseTestCase):
361 def setUp(self):
362 super().setUp()
363 self.config_fixture = self.useFixture(config_fixture.Config(CONF))
364 self.config_fixture.config(
365 group='oslo_limit', endpoint_id='ENDPOINT_ID'
366 )
367 opts.register_opts(CONF)
368 self.mock_conn = mock.MagicMock()
369 limit._SDK_CONNECTION = self.mock_conn
370
371 def test_get_endpoint(self):
372 fake_endpoint = endpoint.Endpoint()
373 self.mock_conn.get_endpoint.return_value = fake_endpoint
374
375 utils = limit._EnforcerUtils()
376
377 self.assertEqual(fake_endpoint, utils._endpoint)
378 self.mock_conn.get_endpoint.assert_called_once_with('ENDPOINT_ID')
379 self.mock_conn.services.assert_not_called()
380 self.mock_conn.endpoints.assert_not_called()
381
382 def test_get_endpoint_no_id(self):
383 self.config_fixture.config(group='oslo_limit', endpoint_id=None)
384 self.mock_conn.get_endpoint.side_effect = (
385 os_exceptions.ResourceNotFound
386 )
387
388 self.assertRaises(ValueError, limit._EnforcerUtils)
389 self.mock_conn.get_endpoint.assert_not_called()
390 self.mock_conn.services.assert_not_called()
391 self.mock_conn.endpoints.assert_not_called()
392
393 def test_get_endpoint_missing(self):
394 self.mock_conn.get_endpoint.side_effect = (
395 os_exceptions.ResourceNotFound
396 )
397
398 self.assertRaises(ValueError, limit._EnforcerUtils)
399 self.mock_conn.get_endpoint.assert_called_once_with('ENDPOINT_ID')
400 self.mock_conn.services.assert_not_called()
401 self.mock_conn.endpoints.assert_not_called()
402
403 def test_get_endpoint_lookup_without_service_opts(self):
404 self.config_fixture.config(group='oslo_limit', endpoint_id=None)
405
406 self.assertRaises(ValueError, limit._EnforcerUtils)
407
408 self.mock_conn.get_endpoint.assert_not_called()
409 self.mock_conn.services.assert_not_called()
410 self.mock_conn.endpoints.assert_not_called()
411
412 def test_get_endpoint_lookup(self):
413 self.config_fixture.config(group='oslo_limit', endpoint_id=None)
414 self.config_fixture.config(
415 group='oslo_limit', endpoint_service_type='SERVICE_TYPE'
416 )
417 self.config_fixture.config(
418 group='oslo_limit', endpoint_service_name='SERVICE_NAME'
419 )
420 fake_service = service.Service(id='SERVICE_ID')
421 self.mock_conn.services.return_value = [fake_service]
422 fake_endpoint = endpoint.Endpoint()
423 self.mock_conn.endpoints.return_value = [fake_endpoint]
424
425 utils = limit._EnforcerUtils()
426
427 self.assertEqual(fake_endpoint, utils._endpoint)
428 self.mock_conn.get_endpoint.assert_not_called()
429 self.mock_conn.services.assert_called_once_with(
430 type='SERVICE_TYPE', name='SERVICE_NAME'
431 )
432 self.mock_conn.endpoints.assert_called_once_with(
433 service_id='SERVICE_ID', region_id=None, interface='public'
434 )
435
436 def test_get_endpoint_lookup_multiple_endpoints(self):
437 self.config_fixture.config(group='oslo_limit', endpoint_id=None)
438 self.config_fixture.config(
439 group='oslo_limit', endpoint_service_type='SERVICE_TYPE'
440 )
441 self.config_fixture.config(
442 group='oslo_limit', endpoint_service_name='SERVICE_NAME'
443 )
444 fake_service = service.Service(id='SERVICE_ID')
445 self.mock_conn.services.return_value = [fake_service]
446 self.mock_conn.endpoints.return_value = [
447 endpoint.Endpoint(),
448 endpoint.Endpoint(),
449 ]
450
451 self.assertRaises(ValueError, limit._EnforcerUtils)
452
453 self.mock_conn.get_endpoint.assert_not_called()
454 self.mock_conn.services.assert_called_once_with(
455 type='SERVICE_TYPE', name='SERVICE_NAME'
456 )
457 self.mock_conn.endpoints.assert_called_once_with(
458 service_id='SERVICE_ID', region_id=None, interface='public'
459 )
460
461 def test_get_endpoint_lookup_endpoint_not_found(self):
462 self.config_fixture.config(group='oslo_limit', endpoint_id=None)
463 self.config_fixture.config(
464 group='oslo_limit', endpoint_service_type='SERVICE_TYPE'
465 )
466 self.config_fixture.config(
467 group='oslo_limit', endpoint_service_name='SERVICE_NAME'
468 )
469 fake_service = service.Service(id='SERVICE_ID')
470 self.mock_conn.services.return_value = [fake_service]
471 self.mock_conn.endpoints.return_value = []
472
473 self.assertRaises(ValueError, limit._EnforcerUtils)
474
475 self.mock_conn.get_endpoint.assert_not_called()
476 self.mock_conn.services.assert_called_once_with(
477 type='SERVICE_TYPE', name='SERVICE_NAME'
478 )
479 self.mock_conn.endpoints.assert_called_once_with(
480 service_id='SERVICE_ID', region_id=None, interface='public'
481 )
482
483 def test_get_endpoint_lookup_multiple_service(self):
484 self.config_fixture.config(group='oslo_limit', endpoint_id=None)
485 self.config_fixture.config(
486 group='oslo_limit', endpoint_service_type='SERVICE_TYPE'
487 )
488 self.config_fixture.config(
489 group='oslo_limit', endpoint_service_name='SERVICE_NAME'
490 )
491 self.mock_conn.services.side_effect = [
492 service.Service(id='SERVICE_ID1'),
493 service.Service(id='SERVICE_ID2'),
494 ]
495
496 self.assertRaises(ValueError, limit._EnforcerUtils)
497
498 self.mock_conn.get_endpoint.assert_not_called()
499 self.mock_conn.services.assert_called_once_with(
500 type='SERVICE_TYPE', name='SERVICE_NAME'
501 )
502 self.mock_conn.endpoints.assert_not_called()
503
504 def test_get_endpoint_lookup_service_not_found(self):
505 self.config_fixture.config(group='oslo_limit', endpoint_id=None)
506 self.config_fixture.config(
507 group='oslo_limit', endpoint_service_type='SERVICE_TYPE'
508 )
509 self.config_fixture.config(
510 group='oslo_limit', endpoint_service_name='SERVICE_NAME'
511 )
512 self.mock_conn.services.return_value = []
513
514 self.assertRaises(ValueError, limit._EnforcerUtils)
515
516 self.mock_conn.get_endpoint.assert_not_called()
517 self.mock_conn.services.assert_called_once_with(
518 type='SERVICE_TYPE', name='SERVICE_NAME'
519 )
520 self.mock_conn.endpoints.assert_not_called()
521
522 def test_get_endpoint_lookup_with_region(self):
523 self.config_fixture.config(group='oslo_limit', endpoint_id=None)
524 self.config_fixture.config(
525 group='oslo_limit', endpoint_service_type='SERVICE_TYPE'
526 )
527 self.config_fixture.config(
528 group='oslo_limit', endpoint_service_name='SERVICE_NAME'
529 )
530 self.config_fixture.config(
531 group='oslo_limit', endpoint_region_name='regionOne'
532 )
533 fake_service = service.Service(id='SERVICE_ID')
534 self.mock_conn.services.return_value = [fake_service]
535 fake_endpoint = endpoint.Endpoint()
536 self.mock_conn.endpoints.return_value = [fake_endpoint]
537 fake_region = region.Region(id='REGION_ID')
538 self.mock_conn.get_region.return_value = fake_region
539
540 utils = limit._EnforcerUtils()
541
542 self.assertEqual(fake_endpoint, utils._endpoint)
543 self.mock_conn.get_endpoint.assert_not_called()
544 self.mock_conn.services.assert_called_once_with(
545 type='SERVICE_TYPE', name='SERVICE_NAME'
546 )
547 self.mock_conn.get_region.assert_called_once_with('regionOne')
548 self.mock_conn.endpoints.assert_called_once_with(
549 service_id='SERVICE_ID', region_id='REGION_ID', interface='public'
550 )
551
552 def test_get_endpoint_lookup_with_region_not_found(self):
553 self.config_fixture.config(group='oslo_limit', endpoint_id=None)
554 self.config_fixture.config(
555 group='oslo_limit', endpoint_service_type='SERVICE_TYPE'
556 )
557 self.config_fixture.config(
558 group='oslo_limit', endpoint_service_name='SERVICE_NAME'
559 )
560 self.config_fixture.config(
561 group='oslo_limit', endpoint_region_name='regionOne'
562 )
563 fake_service = service.Service(id='SERVICE_ID')
564 self.mock_conn.services.return_value = [fake_service]
565 fake_endpoint = endpoint.Endpoint()
566 self.mock_conn.endpoints.return_value = [fake_endpoint]
567 self.mock_conn.get_region.side_effect = os_exceptions.ResourceNotFound
568
569 self.assertRaises(ValueError, limit._EnforcerUtils)
570
571 self.mock_conn.get_endpoint.assert_not_called()
572 self.mock_conn.services.assert_called_once_with(
573 type='SERVICE_TYPE', name='SERVICE_NAME'
574 )
575 self.mock_conn.get_region.assert_called_once_with('regionOne')
576 self.mock_conn.endpoints.assert_not_called()
577
578 def test_get_registered_limit_empty(self):
579 self.mock_conn.registered_limits.return_value = iter([])
580
581 utils = limit._EnforcerUtils()
582 reg_limit = utils._get_registered_limit("foo")
583
584 self.assertIsNone(reg_limit)
585
586 def test_get_registered_limit(self):
587 foo = registered_limit.RegisteredLimit()
588 foo.resource_name = "foo"
589 self.mock_conn.registered_limits.return_value = iter([foo])
590
591 utils = limit._EnforcerUtils()
592 reg_limit = utils._get_registered_limit("foo")
593
594 self.assertEqual(foo, reg_limit)
595
596 def test_get_registered_limits(self):
597 fake_endpoint = endpoint.Endpoint(
598 service_id='service_id', region_id='region_id'
599 )
600 self.mock_conn.get_endpoint.return_value = fake_endpoint
601
602 # a and c have limits, b doesn't have one
603 empty_iterator: Iterable[Any] = iter([])
604
605 a = registered_limit.RegisteredLimit()
606 a.resource_name = "a"
607 a.default_limit = 1
608 a_iterator = iter([a])
609
610 c = registered_limit.RegisteredLimit()
611 c.resource_name = "c"
612 c.default_limit = 2
613 c_iterator = iter([c])
614
615 self.mock_conn.registered_limits.side_effect = [
616 a_iterator,
617 empty_iterator,
618 c_iterator,
619 ]
620
621 utils = limit._EnforcerUtils()
622 limits = utils.get_registered_limits(["a", "b", "c"])
623 self.assertEqual([('a', 1), ('b', 0), ('c', 2)], limits)
624
625 def test_get_project_limits(self):
626 fake_endpoint = endpoint.Endpoint(
627 service_id='service_id', region_id='region_id'
628 )
629 self.mock_conn.get_endpoint.return_value = fake_endpoint
630 project_id = uuid.uuid4().hex
631
632 # a is a project limit, b, c and d don't have one
633 empty_iterator: Iterable[Any] = iter([])
634
635 a = klimit.Limit()
636 a.resource_name = "a"
637 a.resource_limit = 1
638 a_iterator = iter([a])
639
640 self.mock_conn.limits.side_effect = [
641 a_iterator,
642 empty_iterator,
643 empty_iterator,
644 empty_iterator,
645 ]
646
647 # b has a limit, but c and d doesn't, a isn't ever checked
648 b = registered_limit.RegisteredLimit()
649 b.resource_name = "b"
650 b.default_limit = 2
651 b_iterator = iter([b])
652
653 self.mock_conn.registered_limits.side_effect = [
654 b_iterator,
655 empty_iterator,
656 empty_iterator,
657 ]
658
659 utils = limit._EnforcerUtils()
660 limits = utils.get_project_limits(project_id, ["a", "b"])
661 self.assertEqual([('a', 1), ('b', 2)], limits)
662
663 limits = utils.get_project_limits(project_id, ["c", "d"])
664 self.assertEqual([('c', 0), ('d', 0)], limits)
665
666 def test__get_project_limit_cache(self, cache=True):
667 # Registered limit = 5 and project limit = 3
668 project_id = uuid.uuid4().hex
669 fix = self.useFixture(
670 fixture.LimitFixture({'foo': 5}, {project_id: {'foo': 3}})
671 )
672
673 utils = limit._EnforcerUtils(cache=cache)
674 foo_limit = utils._get_project_limit(project_id, 'foo')
675
676 assert foo_limit is not None # narrow type
677 self.assertEqual(3, foo_limit.resource_limit)
678 self.assertEqual(1, fix.mock_conn.limits.call_count)
679
680 # Second call should be cached, so call_count for project limits should
681 # remain 1. When cache is disabled, it should increase to 2
682 foo_limit = utils._get_project_limit(project_id, 'foo')
683 count = 1 if cache else 2
684 self.assertEqual(count, fix.mock_conn.limits.call_count)
685
686 def test__get_project_limit_cache_no_cache(self):
687 self.test__get_project_limit_cache(cache=False)
688
689 def test__get_registered_limit_cache(self, cache=True):
690 # Registered limit = 5 and project limit = 3
691 project_id = uuid.uuid4().hex
692 fix = self.useFixture(
693 fixture.LimitFixture({'foo': 5}, {project_id: {'foo': 3}})
694 )
695
696 utils = limit._EnforcerUtils(cache=cache)
697 foo_limit = utils._get_registered_limit('foo')
698
699 assert foo_limit is not None # narrow type
700 self.assertEqual(5, foo_limit.default_limit)
701 self.assertEqual(1, fix.mock_conn.registered_limits.call_count)
702
703 # Second call should be cached, so call_count for project limits should
704 # remain 1. When cache is disabled, it should increase to 2
705 foo_limit = utils._get_registered_limit('foo')
706 count = 1 if cache else 2
707 self.assertEqual(count, fix.mock_conn.registered_limits.call_count)
708
709 def test__get_registered_limit_cache_no_cache(self):
710 self.test__get_registered_limit_cache(cache=False)
711
712 def test_get_limit_cache(self, cache=True):
713 # No project limit and registered limit = 5
714 fix = self.useFixture(fixture.LimitFixture({'foo': 5}, {}))
715 project_id = uuid.uuid4().hex
716
717 utils = limit._EnforcerUtils(cache=cache)
718 foo_limit = utils._get_limit(project_id, 'foo')
719
720 self.assertEqual(5, foo_limit)
721 self.assertEqual(1, fix.mock_conn.registered_limits.call_count)
722
723 # Second call should be cached, so call_count for registered limits
724 # should remain 1. When cache is disabled, it should increase to 2
725 foo_limit = utils._get_limit(project_id, 'foo')
726 self.assertEqual(5, foo_limit)
727 count = 1 if cache else 2
728 self.assertEqual(count, fix.mock_conn.registered_limits.call_count)
729
730 # Add a project limit = 1
731 fix.projlimits[project_id] = {'foo': 1}
732
733 foo_limit = utils._get_limit(project_id, 'foo')
734
735 self.assertEqual(1, foo_limit)
736 # Project limits should have been queried 3 times total, once per
737 # _get_limit call
738 self.assertEqual(3, fix.mock_conn.limits.call_count)
739
740 # Fourth call should be cached, so call_count for project limits should
741 # remain 3. When cache is disabled, it should increase to 4
742 foo_limit = utils._get_limit(project_id, 'foo')
743 self.assertEqual(1, foo_limit)
744 count = 3 if cache else 4
745 self.assertEqual(count, fix.mock_conn.limits.call_count)
746
747 def test_get_limit_no_cache(self):
748 self.test_get_limit_cache(cache=False)
749
750 def test_get_limit(self):
751 utils = limit._EnforcerUtils(cache=False)
752
753 mgpl = mock.MagicMock()
754 mgrl = mock.MagicMock()
755 with mock.patch.multiple(
756 utils, _get_project_limit=mgpl, _get_registered_limit=mgrl
757 ):
758 # With a project, we expect the project limit to be
759 # fetched. If present, we never check the registered limit.
760 utils._get_limit('project', 'foo')
761 mgrl.assert_not_called()
762 mgpl.assert_called_once_with('project', 'foo')
763
764 mgrl.reset_mock()
765 mgpl.reset_mock()
766
767 # With a project, we expect the project limit to be
768 # fetched. If absent, we check the registered limit.
769 mgpl.return_value = None
770 utils._get_limit('project', 'foo')
771 mgrl.assert_called_once_with('foo')
772 mgpl.assert_called_once_with('project', 'foo')
773
774 mgrl.reset_mock()
775 mgpl.reset_mock()
776
777 # With no project, we expect to get registered limit but
778 # not project limit
779 utils._get_limit(None, 'foo')
780 mgrl.assert_called_once_with('foo')
781 mgpl.assert_not_called()
782
783 def test_get_registered_limits_resource_names_none(self):
784 fix = self.useFixture(fixture.LimitFixture({'foo': 5, 'bar': 7}, {}))
785
786 utils = limit._EnforcerUtils()
787 limits = utils.get_registered_limits(None)
788
789 self.assertEqual([('foo', 5), ('bar', 7)], limits)
790 fix.mock_conn.registered_limits.assert_called_once()
791
792 # Call again with resource names to test caching.
793 limits = utils.get_registered_limits(['foo', 'bar'])
794
795 self.assertEqual([('foo', 5), ('bar', 7)], limits)
796 fix.mock_conn.registered_limits.assert_called_once()
797
798 def test_get_registered_limits_resource_names_none_no_cache(self):
799 fix = self.useFixture(fixture.LimitFixture({'foo': 5, 'bar': 7}, {}))
800
801 utils = limit._EnforcerUtils(cache=False)
802 limits = utils.get_registered_limits(None)
803
804 self.assertEqual([('foo', 5), ('bar', 7)], limits)
805 fix.mock_conn.registered_limits.assert_called_once()
806
807 # Call again with resource names to test caching.
808 limits = utils.get_registered_limits(['foo', 'bar'])
809
810 self.assertEqual([('foo', 5), ('bar', 7)], limits)
811 # First call gets all limits, then one call per resource name.
812 self.assertEqual(3, fix.mock_conn.registered_limits.call_count)
813
814 def test_get_registered_limits_resource_names(self):
815 fix = self.useFixture(fixture.LimitFixture({'foo': 5, 'bar': 7}, {}))
816
817 utils = limit._EnforcerUtils()
818 limits = utils.get_registered_limits(['foo', 'bar'])
819
820 self.assertEqual([('foo', 5), ('bar', 7)], limits)
821 fix.mock_conn.registered_limits.assert_called_once()
822
823 def test_get_registered_limits_resource_names_no_cache(self):
824 fix = self.useFixture(fixture.LimitFixture({'foo': 5, 'bar': 7}, {}))
825
826 utils = limit._EnforcerUtils(cache=False)
827 limits = utils.get_registered_limits(['foo', 'bar'])
828
829 self.assertEqual([('foo', 5), ('bar', 7)], limits)
830 self.assertEqual(2, fix.mock_conn.registered_limits.call_count)
831
832 def test_get_project_limits_resource_names_none_project_id_none(self):
833 # We consider project_id None to be invalid for "get_project_limits"
834 # because it would require us to make the return format for getting
835 # project limits different than the format for registered limits.
836 # [(name, limit), (name, limit), ...]
837 utils = limit._EnforcerUtils()
838 self.assertRaises(ValueError, utils.get_project_limits, None, None)
839
840 def test_get_project_limits_resource_names_none(self):
841 project_id = uuid.uuid4().hex
842 fix = self.useFixture(
843 fixture.LimitFixture(
844 {'foo': 5, 'bar': 7},
845 {
846 project_id: {'foo': 2, 'bar': 4},
847 'other': {'foo': 1, 'bar': 2},
848 },
849 )
850 )
851
852 utils = limit._EnforcerUtils()
853 limits = utils.get_project_limits(project_id, None)
854
855 self.assertEqual([('foo', 2), ('bar', 4)], limits)
856 fix.mock_conn.limits.assert_called_once()
857
858 # Call again with resource names to test caching.
859 limits = utils.get_project_limits(project_id, ['foo', 'bar'])
860
861 self.assertEqual([('foo', 2), ('bar', 4)], limits)
862 fix.mock_conn.limits.assert_called_once()
863
864 def test_get_project_limits_resource_names_none_no_cache(self):
865 project_id = uuid.uuid4().hex
866 fix = self.useFixture(
867 fixture.LimitFixture(
868 {'foo': 5, 'bar': 7},
869 {
870 project_id: {'foo': 2, 'bar': 4},
871 'other': {'foo': 1, 'bar': 2},
872 },
873 )
874 )
875
876 utils = limit._EnforcerUtils(cache=False)
877 limits = utils.get_project_limits(project_id, None)
878
879 self.assertEqual([('foo', 2), ('bar', 4)], limits)
880 fix.mock_conn.limits.assert_called_once()
881
882 # Call again with resource names to test caching.
883 limits = utils.get_project_limits(project_id, ['foo', 'bar'])
884
885 self.assertEqual([('foo', 2), ('bar', 4)], limits)
886 # First call gets all limits, then one call per resource name.
887 self.assertEqual(3, fix.mock_conn.limits.call_count)
888
889 def test_get_project_limits_resource_names(self):
890 project_id = uuid.uuid4().hex
891 fix = self.useFixture(
892 fixture.LimitFixture(
893 {'foo': 5, 'bar': 7},
894 {
895 project_id: {'foo': 2, 'bar': 4},
896 'other': {'foo': 1, 'bar': 2},
897 },
898 )
899 )
900
901 utils = limit._EnforcerUtils()
902 limits = utils.get_project_limits(project_id, ['foo', 'bar'])
903
904 self.assertEqual([('foo', 2), ('bar', 4)], limits)
905 fix.mock_conn.limits.assert_called_once()
906
907 def test_get_project_limits_resource_names_no_cache(self):
908 project_id = uuid.uuid4().hex
909 fix = self.useFixture(
910 fixture.LimitFixture(
911 {'foo': 5, 'bar': 7},
912 {
913 project_id: {'foo': 2, 'bar': 4},
914 'other': {'foo': 1, 'bar': 2},
915 },
916 )
917 )
918
919 utils = limit._EnforcerUtils(cache=False)
920 limits = utils.get_project_limits(project_id, ['foo', 'bar'])
921
922 self.assertEqual([('foo', 2), ('bar', 4)], limits)
923 self.assertEqual(2, fix.mock_conn.limits.call_count)