Debian Codegraph @

neutron_lib/tests/unit/api/validators/test_validators.py

raw
1 #
2 # Licensed under the Apache License, Version 2.0 (the "License"); you may
3 # not use this file except in compliance with the License. You may obtain
4 # a copy of the License at
5 #
6 # http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
10 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
11 # License for the specific language governing permissions and limitations
12 # under the License.
13
14 import string
15 from unittest import mock
16
17 import netaddr
18
19 from neutron_lib._i18n import _
20 from neutron_lib.api import converters
21 from neutron_lib.api.definitions import extra_dhcp_opt
22 from neutron_lib.api import validators
23 from neutron_lib import constants
24 from neutron_lib import exceptions as n_exc
25 from neutron_lib import fixture
26 from neutron_lib.plugins import directory
27 from neutron_lib.tests import _base as base
28
29
30 def dummy_validator(data, valid_values=None):
31 pass
32
33
34 class TestAttributeValidation(base.BaseTestCase):
35
36 def _construct_dict_and_constraints(self):
37 """Constructs a test dictionary and a definition of constraints.
38
39 :return: A (dictionary, constraint) tuple
40 """
41
42 constraints = {'key1': {'type:values': ['val1', 'val2'],
43 'required': True},
44 'key2': {'type:string': None,
45 'required': False},
46 'key3': {'type:dict': {'k4': {'type:string': None,
47 'required': True}},
48 'required': True}}
49
50 dictionary = {'key1': 'val1',
51 'key2': 'a string value',
52 'key3': {'k4': 'a string value'}}
53
54 return dictionary, constraints
55
56 def test_type_prefixing(self):
57 validators.add_validator('type:prefixed_type', dummy_validator)
58 validators.add_validator('unprefixed_type', dummy_validator)
59 self.assertEqual(dummy_validator,
60 validators.get_validator('type:prefixed_type'))
61 self.assertEqual(dummy_validator,
62 validators.get_validator('prefixed_type'))
63 self.assertEqual(dummy_validator,
64 validators.get_validator('type:unprefixed_type'))
65 self.assertEqual(dummy_validator,
66 validators.get_validator('unprefixed_type'))
67
68 def test_adding_validator(self):
69 validators.add_validator('new_type', dummy_validator)
70 self.assertIn('type:new_type', validators.validators)
71 self.assertEqual(dummy_validator,
72 validators.validators['type:new_type'])
73
74 def test_get_validator_default(self):
75 self.assertEqual(dummy_validator,
76 validators.get_validator('nope',
77 default=dummy_validator))
78
79 def test_fail_adding_duplicate_validator(self):
80 self.assertRaises(KeyError,
81 validators.add_validator,
82 'dict', lambda x: x)
83
84 def test_success_adding_duplicate_validator(self):
85 validators.add_validator('dummy', dummy_validator)
86 validators.add_validator('dummy', dummy_validator)
87 self.assertEqual(dummy_validator, validators.get_validator('dummy'))
88
89 def test_is_attr_set(self):
90 data = constants.ATTR_NOT_SPECIFIED
91 self.assertIs(validators.is_attr_set(data), False)
92
93 data = None
94 self.assertIs(validators.is_attr_set(data), False)
95
96 data = "I'm set"
97 self.assertIs(validators.is_attr_set(data), True)
98
99 def test_validate_values(self):
100 # Check that validation is not performed if valid_values is not set
101 msg = validators.validate_values(4)
102 self.assertIsNone(msg)
103
104 # Check that value is within valid_values
105 msg = validators.validate_values(4, [4, 6])
106 self.assertIsNone(msg)
107
108 # Check that value is within valid_values
109 msg = validators.validate_values(4, (4, 6))
110 self.assertIsNone(msg)
111
112 # Check that value is within valid_values with strings
113 msg = validators.validate_values("1", ["2", "1", "4", "5"])
114 self.assertIsNone(msg)
115
116 # Check that value is not compatible for comparison
117 response = "'valid_values' does not support membership operations"
118 self.assertRaisesRegex(TypeError, response,
119 validators.validate_values, data=None,
120 valid_values=True)
121
122 def test_validate_values_display(self):
123 # Check that value is NOT within valid_values and report values
124 msg = validators.validate_values(7, [4, 6],
125 valid_values_display="[4, 6]")
126 self.assertEqual("7 is not in [4, 6]", msg)
127
128 # Check that value is NOT within valid_values and report values
129 msg = validators.validate_values(7, (4, 6),
130 valid_values_display="(4, 6)")
131 self.assertEqual("7 is not in (4, 6)", msg)
132
133 # Check values with a range function showing a custom string
134 msg = validators.validate_values(8, range(8),
135 valid_values_display="[0..7]")
136 self.assertEqual("8 is not in [0..7]", msg)
137
138 # Check that value is not within valid_values and custom string
139 msg = validators.validate_values(1, [2, 3, 4, 5],
140 valid_values_display="[2, 3, 4, 5]")
141 self.assertEqual("1 is not in [2, 3, 4, 5]", msg)
142
143 # Check that value is not within valid_values and custom string
144 msg = validators.validate_values("1", ["2", "3", "4", "5"],
145 valid_values_display="'valid_values"
146 "_to_show'")
147 self.assertEqual("1 is not in 'valid_values_to_show'", msg)
148
149 # Check that value is not comparable to valid_values and got Exception
150 data = 1
151 valid_values = '[2, 3, 4, 5]'
152 response = (f"'data' of type '{type(data)}' and 'valid_values' of "
153 f"type '{type(valid_values)}' are not compatible for "
154 "comparison")
155 self.assertRaisesRegex(TypeError, response,
156 validators.validate_values, data,
157 valid_values,
158 valid_values_display="[2, 3, 4, 5]")
159
160 def test_validate_not_empty_string(self):
161 msg = validators.validate_not_empty_string(' ', None)
162 self.assertEqual("' ' Blank strings are not permitted", msg)
163 msg = validators.validate_not_empty_string(123, None)
164 self.assertEqual("'123' is not a valid string", msg)
165
166 def test_validate_not_empty_string_or_none(self):
167 msg = validators.validate_not_empty_string_or_none(' ', None)
168 self.assertEqual("' ' Blank strings are not permitted", msg)
169
170 msg = validators.validate_not_empty_string_or_none(None, None)
171 self.assertIsNone(msg)
172
173 def test_validate_string_or_none(self):
174 msg = validators.validate_string_or_none('test', None)
175 self.assertIsNone(msg)
176
177 msg = validators.validate_string_or_none(None, None)
178 self.assertIsNone(msg)
179
180 def test_validate_string(self):
181 msg = validators.validate_string(None, None)
182 self.assertEqual("'None' is not a valid string", msg)
183
184 # 0 == len(data) == max_len
185 msg = validators.validate_string("", 0)
186 self.assertIsNone(msg)
187
188 # 0 == len(data) < max_len
189 msg = validators.validate_string("", 9)
190 self.assertIsNone(msg)
191
192 # 0 < len(data) < max_len
193 msg = validators.validate_string("123456789", 10)
194 self.assertIsNone(msg)
195
196 # 0 < len(data) == max_len
197 msg = validators.validate_string("123456789", 9)
198 self.assertIsNone(msg)
199
200 # 0 < max_len < len(data)
201 msg = validators.validate_string("1234567890", 9)
202 self.assertEqual("'1234567890' exceeds maximum length of 9", msg)
203
204 msg = validators.validate_string("123456789", None)
205 self.assertIsNone(msg)
206
207 def test_validate_list_of_unique_strings(self):
208 data = "TEST"
209 msg = validators.validate_list_of_unique_strings(data, None)
210 self.assertEqual("'TEST' is not a list", msg)
211
212 data = ["TEST01", "TEST02", "TEST01"]
213 msg = validators.validate_list_of_unique_strings(data, None)
214 self.assertEqual(
215 "Duplicate items in the list: 'TEST01'", msg)
216
217 data = ["12345678", "123456789"]
218 msg = validators.validate_list_of_unique_strings(data, 8)
219 self.assertEqual("'123456789' exceeds maximum length of 8", msg)
220
221 data = ["TEST01", "TEST02", "TEST03"]
222 msg = validators.validate_list_of_unique_strings(data, None)
223 self.assertIsNone(msg)
224
225 def test_validate_oneline_not_empty_string(self):
226 data = "Test"
227 msg = validators.validate_oneline_not_empty_string(data, None)
228 self.assertIsNone(msg)
229
230 data = "Test but this is too long"
231 max_len = 4
232 msg = validators.validate_oneline_not_empty_string(data, max_len)
233 self.assertEqual(
234 f"'{data}' exceeds maximum length of {max_len}",
235 msg)
236
237 data = "First line\nsecond line"
238 msg = validators.validate_oneline_not_empty_string(data, None)
239 self.assertEqual(
240 f"Multi-line string is not allowed: '{data}'",
241 msg)
242
243 data = ""
244 msg = validators.validate_oneline_not_empty_string(data, None)
245 self.assertEqual(
246 f"'{data}' Blank strings are not permitted",
247 msg)
248
249 def test_validate_oneline_not_empty_string_or_none(self):
250 data = "Test"
251 msg = validators.validate_oneline_not_empty_string_or_none(data, None)
252 self.assertIsNone(msg)
253
254 data = None
255 msg = validators.validate_oneline_not_empty_string_or_none(data, None)
256 self.assertIsNone(msg)
257
258 data = "Test but this is too long"
259 max_len = 4
260 msg = validators.validate_oneline_not_empty_string_or_none(
261 data, max_len)
262 self.assertEqual(
263 f"'{data}' exceeds maximum length of {max_len}",
264 msg)
265
266 data = "First line\nsecond line"
267 msg = validators.validate_oneline_not_empty_string_or_none(data, None)
268 self.assertEqual(
269 f"Multi-line string is not allowed: '{data}'",
270 msg)
271
272 data = ""
273 msg = validators.validate_oneline_not_empty_string(data, None)
274 self.assertEqual(
275 f"'{data}' Blank strings are not permitted",
276 msg)
277
278 def test_validate_boolean(self):
279 msg = validators.validate_boolean(True)
280 self.assertIsNone(msg)
281 msg = validators.validate_boolean(0)
282 self.assertIsNone(msg)
283 msg = validators.validate_boolean("false")
284 self.assertIsNone(msg)
285 msg = validators.validate_boolean("fasle")
286 self.assertEqual("'fasle' is not a valid boolean value", msg)
287
288 def test_validate_integer(self):
289 msg = validators.validate_integer(1)
290 self.assertIsNone(msg)
291 msg = validators.validate_integer(0.1)
292 self.assertEqual("'0.1' is not an integer", msg)
293 msg = validators.validate_integer("1")
294 self.assertIsNone(msg)
295 msg = validators.validate_integer("0.1")
296 self.assertEqual("'0.1' is not an integer", msg)
297 msg = validators.validate_integer(True)
298 self.assertEqual("'True' is not an integer:boolean", msg)
299 msg = validators.validate_integer(False)
300 self.assertEqual("'False' is not an integer:boolean", msg)
301 msg = validators.validate_integer(float('Inf'))
302 self.assertEqual("'inf' is not an integer", msg)
303 msg = validators.validate_integer(None)
304 self.assertEqual("'None' is not an integer", msg)
305
306 def test_validate_integer_values(self):
307 msg = validators.validate_integer(2, [2, 3, 4, 5])
308 self.assertIsNone(msg)
309 msg = validators.validate_integer(1, [2, 3, 4, 5])
310 self.assertEqual("1 is not in valid_values", msg)
311
312 def test_validate_no_whitespace(self):
313 data = 'no_white_space'
314 result = validators.validate_no_whitespace(data)
315 self.assertEqual(data, result)
316
317 self.assertRaises(n_exc.InvalidInput,
318 validators.validate_no_whitespace,
319 'i have whitespace')
320
321 self.assertRaises(n_exc.InvalidInput,
322 validators.validate_no_whitespace,
323 'i\thave\twhitespace')
324
325 for ws in string.whitespace:
326 self.assertRaises(n_exc.InvalidInput,
327 validators.validate_no_whitespace,
328 f'{ws}whitespace-at-head')
329 self.assertRaises(n_exc.InvalidInput,
330 validators.validate_no_whitespace,
331 f'whitespace-at-tail{ws}')
332
333 def test_validate_range(self):
334 msg = validators.validate_range(1, [1, 9])
335 self.assertIsNone(msg)
336
337 msg = validators.validate_range(5, [1, 9])
338 self.assertIsNone(msg)
339
340 msg = validators.validate_range(9, [1, 9])
341 self.assertIsNone(msg)
342
343 msg = validators.validate_range(1, (1, 9))
344 self.assertIsNone(msg)
345
346 msg = validators.validate_range(5, (1, 9))
347 self.assertIsNone(msg)
348
349 msg = validators.validate_range(9, (1, 9))
350 self.assertIsNone(msg)
351
352 msg = validators.validate_range(0, [1, 9])
353 self.assertEqual("'0' is too small - must be at least '1'", msg)
354
355 msg = validators.validate_range(10, (1, 9))
356 self.assertEqual("'10' is too large - must be no larger than '9'", msg)
357
358 msg = validators.validate_range("bogus", (1, 9))
359 self.assertEqual("'bogus' is not an integer", msg)
360
361 msg = validators.validate_range(10, (validators.UNLIMITED,
362 validators.UNLIMITED))
363 self.assertIsNone(msg)
364
365 msg = validators.validate_range(10, (1, validators.UNLIMITED))
366 self.assertIsNone(msg)
367
368 msg = validators.validate_range(1, (validators.UNLIMITED, 9))
369 self.assertIsNone(msg)
370
371 msg = validators.validate_range(-1, (0, validators.UNLIMITED))
372 self.assertEqual("'-1' is too small - must be at least '0'", msg)
373
374 msg = validators.validate_range(10, (validators.UNLIMITED, 9))
375 self.assertEqual("'10' is too large - must be no larger than '9'", msg)
376
377 @mock.patch("neutron_lib.api.validators.validate_range")
378 def test_validate_range_or_none(self, mock_validate_range):
379 msg = validators.validate_range_or_none(None, [1, 9])
380 self.assertFalse(mock_validate_range.called)
381 self.assertIsNone(msg)
382
383 validators.validate_range_or_none(1, [1, 9])
384 mock_validate_range.assert_called_once_with(1, [1, 9])
385
386 def _test_validate_mac_address(self, validator, allow_none=False):
387 mac_addr = "ff:16:3e:4f:00:00"
388 msg = validator(mac_addr)
389 self.assertIsNone(msg)
390
391 mac_addr = "ffa:16:3e:4f:00:00"
392 msg = validator(mac_addr)
393 err_msg = "'%s' is not a valid MAC address"
394 self.assertEqual(err_msg % mac_addr, msg)
395
396 for invalid_mac_addr in constants.INVALID_MAC_ADDRESSES:
397 msg = validator(invalid_mac_addr)
398 self.assertEqual(err_msg % invalid_mac_addr, msg)
399
400 mac_addr = "123"
401 msg = validator(mac_addr)
402 self.assertEqual(err_msg % mac_addr, msg)
403
404 mac_addr = None
405 msg = validator(mac_addr)
406 if allow_none:
407 self.assertIsNone(msg)
408 else:
409 self.assertEqual(err_msg % mac_addr, msg)
410
411 mac_addr = "ff:16:3e:4f:00:00\r"
412 msg = validator(mac_addr)
413 self.assertEqual(err_msg % mac_addr, msg)
414
415 def test_validate_mac_address(self):
416 self._test_validate_mac_address(validators.validate_mac_address)
417
418 def test_validate_mac_address_or_none(self):
419 self._test_validate_mac_address(
420 validators.validate_mac_address_or_none, allow_none=True)
421
422 def test_validate_ip_address(self):
423 ip_addr = '1.1.1.1'
424 msg = validators.validate_ip_address(ip_addr)
425 self.assertIsNone(msg)
426
427 ip_addr = '1111.1.1.1'
428 msg = validators.validate_ip_address(ip_addr)
429 self.assertEqual(f"'{ip_addr}' is not a valid IP address", msg)
430
431 # Depending on platform to run UTs, this case might or might not be
432 # an equivalent to test_validate_ip_address_bsd.
433 ip_addr = '1' * 59
434 msg = validators.validate_ip_address(ip_addr)
435 self.assertEqual(f"'{ip_addr}' is not a valid IP address", msg)
436
437 ip_addr = '1.1.1.1 has whitespace'
438 msg = validators.validate_ip_address(ip_addr)
439 self.assertEqual(f"'{ip_addr}' is not a valid IP address", msg)
440
441 ip_addr = '111.1.1.1\twhitespace'
442 msg = validators.validate_ip_address(ip_addr)
443 self.assertEqual(f"'{ip_addr}' is not a valid IP address", msg)
444
445 ip_addr = '111.1.1.1\nwhitespace'
446 msg = validators.validate_ip_address(ip_addr)
447 self.assertEqual(f"'{ip_addr}' is not a valid IP address", msg)
448
449 for ws in string.whitespace:
450 ip_addr = f'{ws}111.1.1.1'
451 msg = validators.validate_ip_address(ip_addr)
452 self.assertEqual(f"'{ip_addr}' is not a valid IP address", msg)
453
454 for ws in string.whitespace:
455 ip_addr = f'111.1.1.1{ws}'
456 msg = validators.validate_ip_address(ip_addr)
457 self.assertEqual(f"'{ip_addr}' is not a valid IP address", msg)
458
459 def test_validate_ip_address_with_leading_zero(self):
460 ip_addr = '1.1.1.01'
461 expected_msg = ("'%(data)s' is not an accepted IP address, "
462 "'%(ip)s' is recommended")
463 msg = validators.validate_ip_address(ip_addr)
464 self.assertEqual(expected_msg % {"data": ip_addr, "ip": '1.1.1.1'},
465 msg)
466
467 ip_addr = '1.1.1.011'
468 msg = validators.validate_ip_address(ip_addr)
469 self.assertEqual(expected_msg % {"data": ip_addr, "ip": '1.1.1.11'},
470 msg)
471
472 ip_addr = '1.1.1.09'
473 msg = validators.validate_ip_address(ip_addr)
474 self.assertEqual(expected_msg % {"data": ip_addr, "ip": '1.1.1.9'},
475 msg)
476
477 ip_addr = "fe80:0:0:0:0:0:0:0001"
478 msg = validators.validate_ip_address(ip_addr)
479 self.assertIsNone(msg)
480
481 def test_validate_ip_address_bsd(self):
482 # NOTE(yamamoto): On NetBSD and OS X, netaddr.IPAddress() accepts
483 # '1' * 59 as a valid address. The behaviour is inherited from
484 # libc behaviour there. This test ensures that our validator reject
485 # such addresses on such platforms by mocking netaddr to emulate
486 # the behaviour.
487 ip_addr = '1' * 59
488 with mock.patch('netaddr.IPAddress') as ip_address_cls:
489 msg = validators.validate_ip_address(ip_addr)
490 ip_address_cls.assert_called_once_with(ip_addr,
491 flags=netaddr.core.ZEROFILL)
492 self.assertEqual(f"'{ip_addr}' is not a valid IP address", msg)
493
494 def test_validate_ip_pools(self):
495 pools = [[{'end': '10.0.0.254'}],
496 [{'start': '10.0.0.254'}],
497 [{'start': '1000.0.0.254',
498 'end': '1.1.1.1'}],
499 [{'start': '10.0.0.2', 'end': '10.0.0.254',
500 'forza': 'juve'}],
501 [{'start': '10.0.0.2', 'end': '10.0.0.254'},
502 {'end': '10.0.0.254'}],
503 [None],
504 None]
505 for pool in pools:
506 msg = validators.validate_ip_pools(pool)
507 self.assertIsNotNone(msg)
508
509 pools = [[{'end': '10.0.0.254', 'start': '10.0.0.2'},
510 {'start': '11.0.0.2', 'end': '11.1.1.1'}],
511 [{'start': '11.0.0.2', 'end': '11.0.0.100'}]]
512 for pool in pools:
513 msg = validators.validate_ip_pools(pool)
514 self.assertIsNone(msg)
515
516 invalid_ip = '10.0.0.2\r'
517 pools = [[{'end': '10.0.0.254', 'start': invalid_ip}]]
518 for pool in pools:
519 msg = validators.validate_ip_pools(pool)
520 self.assertEqual(f"'{invalid_ip}' is not a valid IP address",
521 msg)
522
523 def test_validate_fixed_ips(self):
524 fixed_ips = [
525 {'data': [{'subnet_id': '00000000-ffff-ffff-ffff-000000000000',
526 'ip_address': '1111.1.1.1'}],
527 'error_msg': "'1111.1.1.1' is not a valid IP address"},
528 {'data': [{'subnet_id': 'invalid',
529 'ip_address': '1.1.1.1'}],
530 'error_msg': "'invalid' is not a valid UUID"},
531 {'data': None,
532 'error_msg': "Invalid data format for fixed IP: 'None'"},
533 {'data': "1.1.1.1",
534 'error_msg': "Invalid data format for fixed IP: '1.1.1.1'"},
535 {'data': ['00000000-ffff-ffff-ffff-000000000000', '1.1.1.1'],
536 'error_msg': "Invalid data format for fixed IP: "
537 "'00000000-ffff-ffff-ffff-000000000000'"},
538 {'data': [['00000000-ffff-ffff-ffff-000000000000', '1.1.1.1']],
539 'error_msg': "Invalid data format for fixed IP: "
540 "'['00000000-ffff-ffff-ffff-000000000000', "
541 "'1.1.1.1']'"},
542 {'data': [{'subnet_id': '00000000-0fff-ffff-ffff-000000000000',
543 'ip_address': '1.1.1.1'},
544 {'subnet_id': '00000000-ffff-ffff-ffff-000000000000',
545 'ip_address': '1.1.1.1'}],
546 'error_msg': "Duplicate IP address '1.1.1.1'"}]
547 for fixed in fixed_ips:
548 msg = validators.validate_fixed_ips(fixed['data'])
549 self.assertEqual(fixed['error_msg'], msg)
550
551 fixed_ips = [[{'subnet_id': '00000000-ffff-ffff-ffff-000000000000',
552 'ip_address': '1.1.1.1'}],
553 [{'subnet_id': '00000000-0fff-ffff-ffff-000000000000',
554 'ip_address': '1.1.1.1'},
555 {'subnet_id': '00000000-ffff-ffff-ffff-000000000000',
556 'ip_address': '1.1.1.2'}]]
557 for fixed in fixed_ips:
558 msg = validators.validate_fixed_ips(fixed)
559 self.assertIsNone(msg)
560
561 def test_validate_nameservers(self):
562 ns_pools = [['1.1.1.2', '1.1.1.2'],
563 ['www.hostname.com', 'www.hostname.com'],
564 ['1000.0.0.1'],
565 ['www.hostname.com'],
566 ['www.great.marathons.to.travel'],
567 ['valid'],
568 ['77.hostname.com'],
569 ['1' * 59],
570 ['www.internal.hostname.com'],
571 None]
572
573 for ns in ns_pools:
574 msg = validators.validate_nameservers(ns, None)
575 self.assertIsNotNone(msg)
576
577 ns_pools = [['100.0.0.2'],
578 ['1.1.1.1', '1.1.1.2']]
579
580 for ns in ns_pools:
581 msg = validators.validate_nameservers(ns, None)
582 self.assertIsNone(msg)
583
584 def test_validate_hostroutes(self):
585 hostroute_pools = [[{'destination': '100.0.0.0/24'}],
586 [{'nexthop': '10.0.2.20'}],
587 [{'nexthop': '10.0.2.20',
588 'forza': 'juve',
589 'destination': '100.0.0.0/8'}],
590 [{'nexthop': '1110.0.2.20',
591 'destination': '100.0.0.0/8'}],
592 [{'nexthop': '10.0.2.20',
593 'destination': '100.0.0.0'}],
594 [{'nexthop': '10.0.2.20',
595 'destination': '100.0.0.0/8'},
596 {'nexthop': '10.0.2.20',
597 'destination': '100.0.0.0/8'}],
598 [None],
599 None]
600 for host_routes in hostroute_pools:
601 msg = validators.validate_hostroutes(host_routes, None)
602 self.assertIsNotNone(msg)
603
604 hostroute_pools = [[{'destination': '100.0.0.0/24',
605 'nexthop': '10.0.2.20'}],
606 [{'nexthop': '10.0.2.20',
607 'destination': '100.0.0.0/8'},
608 {'nexthop': '10.0.2.20',
609 'destination': '101.0.0.0/8'}]]
610 for host_routes in hostroute_pools:
611 msg = validators.validate_hostroutes(host_routes, None)
612 self.assertIsNone(msg)
613
614 def test_validate_ip_address_or_none(self):
615 ip_addr = None
616 msg = validators.validate_ip_address_or_none(ip_addr)
617 self.assertIsNone(msg)
618
619 ip_addr = '1.1.1.1'
620 msg = validators.validate_ip_address_or_none(ip_addr)
621 self.assertIsNone(msg)
622
623 ip_addr = '1111.1.1.1'
624 msg = validators.validate_ip_address_or_none(ip_addr)
625 self.assertEqual(f"'{ip_addr}' is not a valid IP address", msg)
626
627 def test_uuid_pattern(self):
628 data = 'garbage'
629 msg = validators.validate_regex(data, constants.UUID_PATTERN)
630 self.assertIsNotNone(msg)
631
632 data = '00000000-ffff-ffff-ffff-000000000000'
633 msg = validators.validate_regex(data, constants.UUID_PATTERN)
634 self.assertIsNone(msg)
635
636 def test_mac_pattern(self):
637 # Valid - 3 octets
638 base_mac = "fa:16:3e:00:00:00"
639 msg = validators.validate_regex(base_mac, validators.MAC_PATTERN)
640 self.assertIsNone(msg)
641
642 # Valid - 4 octets
643 base_mac = "fa:16:3e:4f:00:00"
644 msg = validators.validate_regex(base_mac, validators.MAC_PATTERN)
645 self.assertIsNone(msg)
646
647 # Invalid - not unicast
648 base_mac = "01:16:3e:4f:00:00"
649 msg = validators.validate_regex(base_mac, validators.MAC_PATTERN)
650 self.assertIsNotNone(msg)
651
652 # Invalid - invalid format
653 base_mac = "a:16:3e:4f:00:00"
654 msg = validators.validate_regex(base_mac, validators.MAC_PATTERN)
655 self.assertIsNotNone(msg)
656
657 # Invalid - invalid format
658 base_mac = "ffa:16:3e:4f:00:00"
659 msg = validators.validate_regex(base_mac, validators.MAC_PATTERN)
660 self.assertIsNotNone(msg)
661
662 # Invalid - invalid format
663 base_mac = "01163e4f0000"
664 msg = validators.validate_regex(base_mac, validators.MAC_PATTERN)
665 self.assertIsNotNone(msg)
666
667 # Invalid - invalid format
668 base_mac = "01-16-3e-4f-00-00"
669 msg = validators.validate_regex(base_mac, validators.MAC_PATTERN)
670 self.assertIsNotNone(msg)
671
672 # Invalid - invalid format
673 base_mac = "00:16:3:f:00:00"
674 msg = validators.validate_regex(base_mac, validators.MAC_PATTERN)
675 self.assertIsNotNone(msg)
676
677 # Invalid - invalid format
678 base_mac = "12:3:4:5:67:89ab"
679 msg = validators.validate_regex(base_mac, validators.MAC_PATTERN)
680 self.assertIsNotNone(msg)
681
682 def _test_validate_subnet(self, validator, allow_none=False):
683 # Valid - IPv4
684 cidr = "10.0.2.0/24"
685 msg = validator(cidr, None)
686 self.assertIsNone(msg)
687
688 # Valid - IPv6 without final octets
689 cidr = "fe80::/24"
690 msg = validator(cidr, None)
691 self.assertIsNone(msg)
692
693 # Valid - IPv6 with final octets
694 cidr = "fe80::/24"
695 msg = validator(cidr, None)
696 self.assertIsNone(msg)
697
698 # Valid - uncompressed ipv6 address
699 cidr = "fe80:0:0:0:0:0:0:0/128"
700 msg = validator(cidr, None)
701 self.assertIsNone(msg)
702
703 # Valid - ipv6 address with multiple consecutive zero
704 cidr = "2001:0db8:0:0:1::1/128"
705 msg = validator(cidr, None)
706 self.assertIsNone(msg)
707
708 # Valid - ipv6 address with multiple consecutive zero
709 cidr = "2001:0db8::1:0:0:1/128"
710 msg = validator(cidr, None)
711 self.assertIsNone(msg)
712
713 # Valid - ipv6 address with multiple consecutive zero
714 cidr = "2001::0:1:0:0:1100/120"
715 msg = validator(cidr, None)
716 self.assertIsNone(msg)
717
718 # Invalid - abbreviated ipv4 address
719 cidr = "10/24"
720 msg = validator(cidr, None)
721 error = f"'{cidr}' is not a valid IP subnet"
722 self.assertEqual(error, msg)
723
724 # Invalid - IPv4 missing mask
725 cidr = "10.0.2.0"
726 msg = validator(cidr, None)
727 error = f"'{cidr}' is not a valid IP subnet"
728 self.assertEqual(error, msg)
729
730 # Valid - IPv4 with non-zero masked bits is ok
731 for i in range(1, 255):
732 cidr = f"192.168.1.{i}/24"
733 msg = validator(cidr, None)
734 self.assertIsNone(msg)
735
736 # Invalid - IPv6 without final octets, missing mask
737 cidr = "fe80::"
738 msg = validator(cidr, None)
739 error = f"'{cidr}' is not a valid IP subnet"
740 self.assertEqual(error, msg)
741
742 # Invalid - IPv6 with final octets, missing mask
743 cidr = "fe80::0"
744 msg = validator(cidr, None)
745 error = f"'{cidr}' is not a valid IP subnet"
746 self.assertEqual(error, msg)
747
748 # Invalid - Address format error
749 cidr = 'invalid'
750 msg = validator(cidr, None)
751 error = f"'{cidr}' is not a valid IP subnet"
752 self.assertEqual(error, msg)
753
754 cidr = None
755 msg = validator(cidr, None)
756 if allow_none:
757 self.assertIsNone(msg)
758 else:
759 error = f"'{cidr}' is not a valid IP subnet"
760 self.assertEqual(error, msg)
761
762 # Invalid - IPv4 with trailing CR
763 cidr = "10.0.2.0/24\r"
764 msg = validator(cidr, None)
765 error = f"'{cidr}' is not a valid IP subnet"
766 self.assertEqual(error, msg)
767
768 def test_validate_subnet(self):
769 self._test_validate_subnet(validators.validate_subnet)
770
771 def test_validate_route_cidr(self):
772 # Valid - CIDR
773 cidr = "10.0.0.0/8"
774 msg = validators.validate_route_cidr(cidr, None)
775 self.assertIsNone(msg)
776
777 # Valid - CIDR
778 cidr = "192.168.1.1/32"
779 msg = validators.validate_route_cidr(cidr, None)
780 self.assertIsNone(msg)
781
782 # Invalid - CIDR
783 cidr = "192.168.1.1/8"
784 msg = validators.validate_route_cidr(cidr, None)
785 error = f"'{cidr}' is not a valid CIDR"
786 self.assertEqual(error, msg)
787
788 # Invalid - loopback CIDR
789 cidr = "127.0.0.0/8"
790 msg = validators.validate_route_cidr(cidr, None)
791 error = _("'%(data)s' is not a routable CIDR") % {"data": cidr}
792 self.assertEqual(error, msg)
793
794 # Invalid - CIDR format error
795 cidr = 'invalid'
796 msg = validators.validate_route_cidr(cidr, None)
797 error = f"'{cidr}' is not a valid CIDR"
798 self.assertEqual(error, msg)
799
800 def test_validate_subnet_or_none(self):
801 self._test_validate_subnet(validators.validate_subnet_or_none,
802 allow_none=True)
803
804 def test_validate_subnet_list(self):
805 msg = validators.validate_subnet_list('abc')
806 self.assertEqual("'abc' is not a list", msg)
807 msg = validators.validate_subnet_list(['10.1.0.0/24',
808 '10.2.0.0/24',
809 '10.1.0.0/24'])
810 self.assertEqual("Duplicate items in the list: '10.1.0.0/24'", msg)
811
812 cidrs = ['10.1.0.0/24', '10.2.0.0']
813 msg = validators.validate_subnet_list(cidrs)
814 error = f"'{cidrs[1]}' is not a valid IP subnet"
815 self.assertEqual(error, msg)
816
817 def _test_validate_regex(self, validator, allow_none=False):
818 pattern = '[hc]at'
819
820 data = None
821 msg = validator(data, pattern)
822 if allow_none:
823 self.assertIsNone(msg)
824 else:
825 self.assertEqual("'None' is not a valid input", msg)
826
827 data = 'bat'
828 msg = validator(data, pattern)
829 self.assertEqual(f"'{data}' is not a valid input", msg)
830
831 data = 'hat'
832 msg = validator(data, pattern)
833 self.assertIsNone(msg)
834
835 data = 'cat'
836 msg = validator(data, pattern)
837 self.assertIsNone(msg)
838
839 def test_validate_regex(self):
840 self._test_validate_regex(validators.validate_regex)
841
842 def test_validate_regex_or_none(self):
843 self._test_validate_regex(validators.validate_regex_or_none,
844 allow_none=True)
845
846 def test_validate_list_of_regex_or_none(self):
847 pattern = '[hc]at|^$'
848
849 list_of_regex = ['hat', 'cat', '']
850 msg = validators.validate_list_of_regex_or_none(list_of_regex, pattern)
851 self.assertIsNone(msg)
852
853 list_of_regex = ['bat', 'hat', 'cat', '']
854 msg = validators.validate_list_of_regex_or_none(list_of_regex, pattern)
855 self.assertEqual("'bat' is not a valid input", msg)
856
857 empty_list = []
858 msg = validators.validate_list_of_regex_or_none(empty_list, pattern)
859
860 def test_validate_subnetpool_id(self):
861 msg = validators.validate_subnetpool_id(constants.IPV6_PD_POOL_ID)
862 self.assertIsNone(msg)
863
864 msg = validators.validate_subnetpool_id(
865 '00000000-ffff-ffff-ffff-000000000000')
866 self.assertIsNone(msg)
867
868 def test_validate_subnetpool_id_or_none(self):
869 msg = validators.validate_subnetpool_id_or_none(None)
870 self.assertIsNone(msg)
871
872 msg = validators.validate_subnetpool_id_or_none(
873 '00000000-ffff-ffff-ffff-000000000000')
874 self.assertIsNone(msg)
875
876 def test_validate_uuid(self):
877 invalid_uuids = [None,
878 123,
879 '123',
880 't5069610-744b-42a7-8bd8-ceac1a229cd4',
881 'e5069610-744bb-42a7-8bd8-ceac1a229cd4']
882 for uuid in invalid_uuids:
883 msg = validators.validate_uuid(uuid)
884 error = f"'{uuid}' is not a valid UUID"
885 self.assertEqual(error, msg)
886
887 msg = validators.validate_uuid('00000000-ffff-ffff-ffff-000000000000')
888 self.assertIsNone(msg)
889
890 def test_validate_uuid_list(self):
891 bad_uuid_list = ['00000000-ffff-ffff-ffff-000000000000',
892 '00000000-ffff-ffff-ffff-000000000001',
893 '123']
894 msg = validators.validate_uuid_list(bad_uuid_list,
895 valid_values='parameter not used')
896 error = f"'{bad_uuid_list[2]}' is not a valid UUID"
897 self.assertEqual(error, msg)
898
899 good_uuid_list = ['00000000-ffff-ffff-ffff-000000000000',
900 '00000000-ffff-ffff-ffff-000000000001']
901 msg = validators.validate_uuid_list(good_uuid_list,
902 valid_values='parameter not used')
903 self.assertIsNone(msg)
904
905 def test__validate_list_of_items(self):
906 # check not a list
907 items = [None,
908 123,
909 'e5069610-744b-42a7-8bd8-ceac1a229cd4',
910 '12345678123456781234567812345678',
911 {'uuid': 'e5069610-744b-42a7-8bd8-ceac1a229cd4'}]
912 for item in items:
913 msg = validators._validate_list_of_items(mock.Mock(), item)
914 error = f"'{item}' is not a list"
915 self.assertEqual(error, msg)
916
917 # check duplicate items in a list
918 duplicate_items = ['e5069610-744b-42a7-8bd8-ceac1a229cd4',
919 'f3eeab00-8367-4524-b662-55e64d4cacb5',
920 'e5069610-744b-42a7-8bd8-ceac1a229cd4']
921 msg = validators._validate_list_of_items(mock.Mock(), duplicate_items)
922 error = ("Duplicate items in the list: "
923 "'e5069610-744b-42a7-8bd8-ceac1a229cd4'")
924 self.assertEqual(error, msg)
925
926 # check valid lists
927 valid_lists = [[],
928 [1, 2, 3],
929 ['a', 'b', 'c']]
930 for list_obj in valid_lists:
931 msg = validators._validate_list_of_items(
932 mock.Mock(return_value=None), list_obj)
933 self.assertIsNone(msg)
934
935 def test__test__validate_list_of_items_non_empty(self):
936 items = None
937 msg = validators._validate_list_of_items_non_empty(mock.Mock(), items)
938 error = f"'{items}' is not a list"
939 self.assertEqual(error, msg)
940
941 items = []
942 msg = validators._validate_list_of_items_non_empty(mock.Mock(), items)
943 self.assertEqual("List should not be empty", msg)
944
945 def test__validate_list_of_items_collect_duplicates(self):
946 items = ['a', 'b', 'duplicate_1', 'duplicate_2', 'duplicate_1',
947 'duplicate_2', 'duplicate_2', 'c']
948 msg = validators._validate_list_of_items(mock.Mock(), items)
949 error = ("Duplicate items in the list: '{}'".format(
950 'duplicate_1, duplicate_2'))
951 self.assertEqual(error, msg)
952
953 items = [['a', 'b'], ['c', 'd'], ['a', 'b']]
954 msg = validators._validate_list_of_items(mock.Mock(), items)
955 error = "Duplicate items in the list: '{}'".format(str(['a', 'b']))
956 self.assertEqual(error, msg)
957
958 items = [{'a': 'b'}, {'c': 'd'}, {'a': 'b'}]
959 msg = validators._validate_list_of_items(mock.Mock(), items)
960 error = "Duplicate items in the list: '{}'".format(str({'a': 'b'}))
961 self.assertEqual(error, msg)
962
963 def test_validate_dict_type(self):
964 for value in (None, True, '1', []):
965 self.assertEqual(f"'{value}' is not a dictionary",
966 validators.validate_dict(value))
967
968 def test_validate_dict_without_constraints(self):
969 msg = validators.validate_dict({})
970 self.assertIsNone(msg)
971
972 # Validate a dictionary without constraints.
973 msg = validators.validate_dict({'key': 'value'})
974 self.assertIsNone(msg)
975
976 def test_validate_a_valid_dict_with_constraints(self):
977 dictionary, constraints = self._construct_dict_and_constraints()
978
979 msg = validators.validate_dict(dictionary, constraints)
980 self.assertIsNone(msg, 'Validation of a valid dictionary failed.')
981
982 def test_validate_dict_with_invalid_validator(self):
983 dictionary, constraints = self._construct_dict_and_constraints()
984
985 constraints['key1'] = {'type:unsupported': None, 'required': True}
986 msg = validators.validate_dict(dictionary, constraints)
987 self.assertEqual("Validator 'type:unsupported' does not exist", msg)
988
989 def test_validate_dict_not_required_keys(self):
990 dictionary, constraints = self._construct_dict_and_constraints()
991
992 del dictionary['key2']
993 msg = validators.validate_dict(dictionary, constraints)
994 self.assertIsNone(msg, 'Field that was not required by the specs was'
995 'required by the validator.')
996
997 def test_validate_dict_required_keys(self):
998 dictionary, constraints = self._construct_dict_and_constraints()
999
1000 del dictionary['key1']
1001 msg = validators.validate_dict(dictionary, constraints)
1002 self.assertIn('Expected keys:', msg)
1003
1004 def test_validate_dict_wrong_values(self):
1005 dictionary, constraints = self._construct_dict_and_constraints()
1006
1007 dictionary['key1'] = 'UNSUPPORTED'
1008 msg = validators.validate_dict(dictionary, constraints)
1009 self.assertIsNotNone(msg)
1010
1011 def test_validate_dict_unexpected_keys(self):
1012 dictionary, constraints = self._construct_dict_and_constraints()
1013
1014 dictionary['unexpected_key'] = 'val'
1015 msg = validators.validate_dict(dictionary, constraints)
1016 self.assertIn('Unexpected keys supplied:', msg)
1017
1018 def test_validate_dict_convert_boolean(self):
1019 dictionary, constraints = self._construct_dict_and_constraints()
1020
1021 constraints['key_bool'] = {
1022 'type:boolean': None,
1023 'required': False,
1024 'convert_to': converters.convert_to_boolean}
1025 dictionary['key_bool'] = 'true'
1026 msg = validators.validate_dict(dictionary, constraints)
1027 self.assertIsNone(msg)
1028 # Explicitly comparing with literal 'True' as assertTrue
1029 # succeeds also for 'true'
1030 self.assertIs(True, dictionary['key_bool'])
1031
1032 def test_subdictionary(self):
1033 dictionary, constraints = self._construct_dict_and_constraints()
1034
1035 del dictionary['key3']['k4']
1036 dictionary['key3']['k5'] = 'a string value'
1037 msg = validators.validate_dict(dictionary, constraints)
1038 self.assertIn('Expected keys:', msg)
1039
1040 def test_validate_dict_or_none(self):
1041 dictionary, constraints = self._construct_dict_and_constraints()
1042
1043 # Check whether None is a valid value.
1044 msg = validators.validate_dict_or_none(None, constraints)
1045 self.assertIsNone(msg, 'Validation of a None dictionary failed.')
1046
1047 # Check validation of a regular dictionary.
1048 msg = validators.validate_dict_or_none(dictionary, constraints)
1049 self.assertIsNone(msg, 'Validation of a valid dictionary failed.')
1050
1051 def test_validate_dict_or_empty(self):
1052 dictionary, constraints = self._construct_dict_and_constraints()
1053
1054 # Check whether an empty dictionary is valid.
1055 msg = validators.validate_dict_or_empty({}, constraints)
1056 self.assertIsNone(msg, 'Validation of a None dictionary failed.')
1057
1058 # Check validation of a regular dictionary.
1059 msg = validators.validate_dict_or_empty(dictionary, constraints)
1060 self.assertIsNone(msg, 'Validation of a valid dictionary failed.')
1061
1062 def test_validate_dict_or_nodata(self):
1063 dictionary, constraints = self._construct_dict_and_constraints()
1064
1065 # Check whether no data is a valid value.
1066 msg = validators.validate_dict_or_nodata(None, constraints)
1067 self.assertIsNone(msg, 'Validation of None for no-data failed.')
1068 msg = validators.validate_dict_or_nodata({}, constraints)
1069 self.assertIsNone(msg, 'Validation of empty dict for no-data failed.')
1070
1071 # Check validation of a regular dictionary.
1072 msg = validators.validate_dict_or_nodata(dictionary, constraints)
1073 self.assertIsNone(msg, 'Validation of a valid dictionary failed.')
1074
1075 def test_validate_non_negative(self):
1076 msg = validators.validate_non_negative('abc')
1077 self.assertEqual("'abc' is not an integer", msg)
1078
1079 for value in (-1, '-2'):
1080 self.assertEqual(f"'{value}' should be non-negative",
1081 validators.validate_non_negative(value))
1082
1083 for value in (0, 1, '2', True, False):
1084 msg = validators.validate_non_negative(value)
1085 self.assertIsNone(msg)
1086
1087 def test_validate_subports_invalid_body(self):
1088 self.assertIsNotNone(validators.validate_subports(None))
1089
1090 def test_validate_subports_invalid_subport_object(self):
1091 self.assertIsNotNone(validators.validate_subports(['foo_port']))
1092
1093 def test_validate_subports_invalid_port_uuid(self):
1094 body = [{'port_id': 'foo_port'}]
1095 self.assertIsNotNone(validators.validate_subports(body))
1096
1097 def test_validate_subports_invalid_missing_port_id(self):
1098 body = [{'poort_id': 'foo_port'}]
1099 self.assertIsNotNone(validators.validate_subports(body))
1100
1101 def test_validate_subports_invalid_duplicate_port_ids(self):
1102 body = [
1103 {'port_id': '00000000-ffff-ffff-ffff-000000000000'},
1104 {'port_id': '00000000-ffff-ffff-ffff-000000000000'}
1105 ]
1106 self.assertIsNotNone(validators.validate_subports(body))
1107
1108 def test_validate_subports_invalid_incomplete_segmentation_details(self):
1109 body = [
1110 {'port_id': '00000000-ffff-ffff-ffff-000000000000',
1111 'segmentation_id': '3'}
1112 ]
1113 self.assertIsNotNone(validators.validate_subports(body))
1114
1115 def test_validate_subports_invalid_unknown_paramenter(self):
1116 body = [
1117 {'port_id': '00000000-ffff-ffff-ffff-000000000000',
1118 'segmentation_id': '3', 'segmeNAtion_type': 'vlan'}
1119 ]
1120 self.assertIsNotNone(validators.validate_subports(body))
1121
1122 def test_validate_subports_invalid_duplicate_segmentation_id(self):
1123 body = [
1124 {'port_id': '00000000-ffff-ffff-ffff-000000000000',
1125 'segmentation_id': 0, 'segmentation_type': 'vlan'},
1126 {'port_id': '11111111-ffff-ffff-ffff-000000000000',
1127 'segmentation_id': 0, 'segmentation_type': 'vlan'}
1128 ]
1129 self.assertIsNotNone(validators.validate_subports(body))
1130
1131 def test_validate_subports_with_segmentation_id_0(self):
1132 body = [
1133 {'port_id': '00000000-ffff-ffff-ffff-000000000000',
1134 'segmentation_id': '0', 'segmentation_type': 'vlan'}
1135 ]
1136 self.assertIsNone(validators.validate_subports(body))
1137
1138 def test_validate_subports_inherit_segmentation_details(self):
1139 body = [
1140 {'port_id': '00000000-ffff-ffff-ffff-000000000000',
1141 'segmentation_type': 'inherit'}
1142 ]
1143 self.assertIsNone(validators.validate_subports(body))
1144
1145 def test_validate_subports_valid_unique_segmentation_id(self):
1146 body = [
1147 {'port_id': '00000000-ffff-ffff-ffff-000000000000',
1148 'segmentation_id': '3', 'segmentation_type': 'vlan'},
1149 {'port_id': '11111111-ffff-ffff-ffff-000000000000',
1150 'segmentation_id': '3', 'segmentation_type': 'vxlan'}
1151 ]
1152 self.assertIsNone(validators.validate_subports(body))
1153
1154 def test_validate_subports_valid_empty_body(self):
1155 self.assertIsNone(validators.validate_subports([]))
1156
1157 def test_validate_subports_valid_subports_with_segmentation_details(self):
1158 body = [
1159 {'port_id': '00000000-ffff-ffff-ffff-000000000000',
1160 'segmentation_id': '3', 'segmentation_type': 'vlan'},
1161 {'port_id': '11111111-ffff-ffff-ffff-000000000000',
1162 'segmentation_id': '5', 'segmentation_type': 'vlan'}
1163 ]
1164 self.assertIsNone(validators.validate_subports(body))
1165
1166 def test_validate_subports_valid_subports(self):
1167 body = [
1168 {'port_id': '00000000-ffff-ffff-ffff-000000000000'},
1169 {'port_id': '11111111-ffff-ffff-ffff-000000000000'},
1170 ]
1171 self.assertIsNone(validators.validate_subports(body))
1172
1173 @mock.patch('oslo_config.cfg.CONF')
1174 def test_validate_ethertype_valid_string_new(self, CONF):
1175 CONF.sg_filter_ethertypes = True
1176 self.assertIsNone(validators.validate_ethertype('IPv4'))
1177 self.assertIsNone(validators.validate_ethertype('IPv6'))
1178
1179 @mock.patch('oslo_config.cfg.CONF')
1180 def test_validate_ethertype_valid_string_old(self, CONF):
1181 CONF.sg_filter_ethertypes = False
1182 self.assertIsNone(validators.validate_ethertype('IPv4'))
1183 self.assertIsNone(validators.validate_ethertype('IPv6'))
1184
1185 @mock.patch('oslo_config.cfg.CONF')
1186 def test_validate_ethertype_invalid_string(self, CONF):
1187 CONF.sg_filter_ethertypes = False
1188 self.assertEqual(('Ethertype 0x4008 is not a valid ethertype, must be '
1189 'one of IPv4,IPv6.'),
1190 validators.validate_ethertype('0x4008'))
1191
1192 @mock.patch('oslo_config.cfg.CONF')
1193 def test_validate_ethertype_extended_valid_string(self, CONF):
1194 CONF.sg_filter_ethertypes = True
1195 self.assertIsNone(validators.validate_ethertype('0x4008'))
1196
1197 @mock.patch('oslo_config.cfg.CONF')
1198 def test_validate_ethertype_extended_valid_hexint(self, CONF):
1199 CONF.sg_filter_ethertypes = True
1200 self.assertIsNone(validators.validate_ethertype(0x4008))
1201
1202 @mock.patch('oslo_config.cfg.CONF')
1203 def test_validate_ethertype_extended_invalid_negative(self, CONF):
1204 CONF.sg_filter_ethertypes = True
1205 self.assertEqual(("Ethertype -16392 is not a two octet "
1206 "hexadecimal number or ethertype name."),
1207 validators.validate_ethertype('-0x4008'))
1208
1209 @mock.patch('oslo_config.cfg.CONF')
1210 def test_validate_ethertype_extended_invalid_nonhex(self, CONF):
1211 CONF.sg_filter_ethertypes = True
1212 self.assertEqual(("Ethertype invalid is not a two octet "
1213 "hexadecimal number or ethertype name."),
1214 validators.validate_ethertype('invalid'))
1215
1216 @mock.patch('oslo_config.cfg.CONF')
1217 def test_validate_ethertype_extended_invalid_toobig(self, CONF):
1218 CONF.sg_filter_ethertypes = True
1219 self.assertEqual(("Ethertype 3735928559 is not a two octet "
1220 "hexadecimal number or ethertype name."),
1221 validators.validate_ethertype('0xdeadbeef'))
1222
1223
1224 class TestValidateIPSubnetNone(base.BaseTestCase):
1225
1226 def test_validate_none(self):
1227 self.assertIsNone(validators.validate_ip_or_subnet_or_none(None))
1228
1229 def test_validate_ipv4(self):
1230 testdata = "172.0.0.1"
1231 self.assertIsNone(validators.validate_ip_or_subnet_or_none(testdata))
1232
1233 def test_validate_ipv4_subnet(self):
1234 testdata = "172.0.0.1/24"
1235 self.assertIsNone(validators.validate_ip_or_subnet_or_none(testdata))
1236
1237 def test_validate_ipv6(self):
1238 testdata = "2001:0db8:0a0b:12f0:0000:0000:0000:0001"
1239 self.assertIsNone(validators.validate_ip_or_subnet_or_none(testdata))
1240
1241 def test_validate_ipv6_subnet(self):
1242 testdata = "::1/128"
1243 self.assertIsNone(validators.validate_ip_or_subnet_or_none(testdata))
1244
1245 def test_validate_ipv4_invalid(self):
1246 testdata = "300.0.0.1"
1247 self.assertEqual(("'300.0.0.1' is neither a valid IP address, nor is "
1248 "it a valid IP subnet"),
1249 validators.validate_ip_or_subnet_or_none(testdata))
1250
1251 def test_validate_ipv4_subnet_invalid(self):
1252 testdata = "172.0.0.1/45"
1253 self.assertEqual(("'172.0.0.1/45' is neither a valid IP address, nor "
1254 "is it a valid IP subnet"),
1255 validators.validate_ip_or_subnet_or_none(testdata))
1256
1257 def test_validate_ipv6_invalid(self):
1258 testdata = "xxxx:0db8:0a0b:12f0:0000:0000:0000:0001"
1259 self.assertEqual(("'xxxx:0db8:0a0b:12f0:0000:0000:0000:0001' is "
1260 "neither a valid IP address, nor is it a valid IP "
1261 "subnet"),
1262 validators.validate_ip_or_subnet_or_none(testdata))
1263
1264 def test_validate_ipv6_subnet_invalid(self):
1265 testdata = "::1/2048"
1266 self.assertEqual(("'::1/2048' is neither a valid IP address, nor is "
1267 "it a valid IP subnet"),
1268 validators.validate_ip_or_subnet_or_none(testdata))
1269
1270
1271 class TestPortRangeValidation(base.BaseTestCase):
1272
1273 def test_valid_port_specific_range(self):
1274 result = validators.validate_port_range_or_none("4:5",
1275 [1, 65535])
1276 self.assertIsNone(result)
1277
1278 def test_invalid_port_specific_range(self):
1279 result = validators.validate_port_range_or_none("4:500000",
1280 [1, 65535])
1281 self.assertEqual("Invalid port: 500000", result)
1282
1283 def test_invalid_port_for_specific_range(self):
1284 result = validators.validate_port_range_or_none("0:10",
1285 [1, 65535])
1286 self.assertEqual("Invalid port: 0, the port must be in"
1287 " the range [1, 65535]", result)
1288
1289 def test_valid_port(self):
1290 result = validators.validate_port_range_or_none("80")
1291 self.assertIsNone(result)
1292
1293 def test_valid_port_integer(self):
1294 result = validators.validate_port_range_or_none(80)
1295 self.assertIsNone(result)
1296
1297 def test_valid_range(self):
1298 # NOTE(huntxu): This case would fail when ports are compared as
1299 # strings, since '9' > '1111'.
1300 result = validators.validate_port_range_or_none("9:1111")
1301 self.assertIsNone(result)
1302
1303 def test_port_too_high(self):
1304 result = validators.validate_port_range_or_none("99999")
1305 self.assertEqual("Invalid port: 99999", result)
1306
1307 def test_port_too_low(self):
1308 result = validators.validate_port_range_or_none("-1")
1309 self.assertEqual("Invalid port: -1", result)
1310
1311 def test_range_too_high(self):
1312 result = validators.validate_port_range_or_none("80:99999")
1313 self.assertEqual("Invalid port: 99999", result)
1314
1315 def test_range_too_low(self):
1316 result = validators.validate_port_range_or_none("-1:8888")
1317 self.assertEqual("Invalid port: -1", result)
1318
1319 def test_range_wrong_way(self):
1320 # NOTE(huntxu): This case would fail when ports are compared as
1321 # strings, since '1111' < '9'.
1322 result = validators.validate_port_range_or_none("1111:9")
1323 self.assertEqual("First port in a port range must be lower than the "
1324 "second port", result)
1325
1326 def test_range_invalid(self):
1327 result = validators.validate_port_range_or_none("DEAD:BEEF")
1328 self.assertEqual("Invalid port: DEAD", result)
1329
1330 def test_range_bad_input(self):
1331 result = validators.validate_port_range_or_none(['a', 'b', 'c'])
1332 self.assertEqual("Invalid port: ['a', 'b', 'c']", result)
1333
1334 def test_range_colon(self):
1335 result = validators.validate_port_range_or_none(":")
1336 self.assertEqual("Port range must be two integers separated by a "
1337 "colon", result)
1338
1339 def test_too_many_colons(self):
1340 result = validators.validate_port_range_or_none("80:888:8888")
1341 self.assertEqual("Port range must be two integers separated by a "
1342 "colon", result)
1343
1344
1345 class TestAnyKeySpecs(base.BaseTestCase):
1346
1347 def test_data_is_none(self):
1348 self.assertIsNone(
1349 validators.validate_any_key_specs_or_none(None, key_specs={}))
1350
1351 def test_data_is_not_list(self):
1352 for t in [{}, set(), 'abc', 1, True]:
1353 self.assertRaises(
1354 n_exc.InvalidInput,
1355 validators.validate_any_key_specs_or_none, t, key_specs={})
1356
1357 def test_data_invalid_keys(self):
1358 data = [{'opt_name': 'a', 'opt_value': 'A'},
1359 {'opt_name': 'b', 'opt_valuee': 'B'}]
1360 self.assertRaisesRegex(
1361 n_exc.InvalidInput,
1362 "No valid key specs",
1363 validators.validate_any_key_specs_or_none,
1364 data, key_specs=extra_dhcp_opt.EXTRA_DHCP_OPT_KEY_SPECS)
1365
1366 def test_data_optional_key(self):
1367 data = [{'opt_name': 'a', 'opt_value': 'A'},
1368 {'opt_name': 'b', 'opt_value': 'B', 'ip_version': '4'}]
1369 self.assertIsNone(
1370 validators.validate_any_key_specs_or_none(
1371 data, key_specs=extra_dhcp_opt.EXTRA_DHCP_OPT_KEY_SPECS))
1372
1373 def test_data_optional_key_invalid(self):
1374 data = [{'opt_name': 'a', 'opt_value': 'A'},
1375 {'opt_name': 'b', 'opt_value': 'B', 'ip_version': '3'}]
1376 self.assertRaisesRegex(
1377 n_exc.InvalidInput,
1378 "No valid key specs",
1379 validators.validate_any_key_specs_or_none,
1380 data, key_specs=extra_dhcp_opt.EXTRA_DHCP_OPT_KEY_SPECS)
1381
1382 def test_data_conditional_spec(self):
1383 data = [{'opt_name': 'router', 'opt_value': None},
1384 {'opt_name': 'b', 'opt_value': 'B', 'ip_version': '4'}]
1385 self.assertIsNone(
1386 validators.validate_any_key_specs_or_none(
1387 data, key_specs=extra_dhcp_opt.EXTRA_DHCP_OPT_KEY_SPECS))
1388
1389
1390 class TestServicePluginType(base.BaseTestCase):
1391
1392 def setUp(self):
1393 super().setUp()
1394 self._plugins = directory._PluginDirectory()
1395 self._plugins.add_plugin('stype', mock.Mock())
1396 self.useFixture(fixture.PluginDirectoryFixture(
1397 plugin_directory=self._plugins))
1398
1399 def test_valid_plugin_type(self):
1400 self.assertIsNone(validators.validate_service_plugin_type('stype'))
1401
1402 def test_invalid_plugin_type(self):
1403 self.assertRaisesRegex(
1404 n_exc.InvalidServiceType,
1405 'Invalid service type',
1406 validators.validate_service_plugin_type, 'ntype')