summaryrefslogtreecommitdiff
path: root/neutron/tests/unit/test_attributes.py
blob: 2707af27f9e1be12970de033af062ca15bd99952 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
# Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import testtools

from neutron.api.v2 import attributes
from neutron.common import exceptions as n_exc
from neutron.tests import base


class TestAttributes(base.BaseTestCase):

    def _construct_dict_and_constraints(self):
        """Constructs a test dictionary and a definition of constraints.
        :return: A (dictionary, constraint) tuple
        """
        constraints = {'key1': {'type:values': ['val1', 'val2'],
                                'required': True},
                       'key2': {'type:string': None,
                                'required': False},
                       'key3': {'type:dict': {'k4': {'type:string': None,
                                                     'required': True}},
                                'required': True}}

        dictionary = {'key1': 'val1',
                      'key2': 'a string value',
                      'key3': {'k4': 'a string value'}}

        return dictionary, constraints

    def test_is_attr_set(self):
        data = attributes.ATTR_NOT_SPECIFIED
        self.assertIs(attributes.is_attr_set(data), False)

        data = None
        self.assertIs(attributes.is_attr_set(data), False)

        data = "I'm set"
        self.assertIs(attributes.is_attr_set(data), True)

    def test_validate_values(self):
        msg = attributes._validate_values(4, [4, 6])
        self.assertIsNone(msg)

        msg = attributes._validate_values(4, (4, 6))
        self.assertIsNone(msg)

        msg = attributes._validate_values(7, [4, 6])
        self.assertEqual(msg, "'7' is not in [4, 6]")

        msg = attributes._validate_values(7, (4, 6))
        self.assertEqual(msg, "'7' is not in (4, 6)")

    def test_validate_not_empty_string(self):
        msg = attributes._validate_not_empty_string('    ', None)
        self.assertEqual(msg, u"'    ' Blank strings are not permitted")

    def test_validate_not_empty_string_or_none(self):
        msg = attributes._validate_not_empty_string_or_none('    ', None)
        self.assertEqual(msg, u"'    ' Blank strings are not permitted")

        msg = attributes._validate_not_empty_string_or_none(None, None)
        self.assertIsNone(msg)

    def test_validate_string_or_none(self):
        msg = attributes._validate_not_empty_string_or_none('test', None)
        self.assertIsNone(msg)

        msg = attributes._validate_not_empty_string_or_none(None, None)
        self.assertIsNone(msg)

    def test_validate_string(self):
        msg = attributes._validate_string(None, None)
        self.assertEqual(msg, "'None' is not a valid string")

        # 0 == len(data) == max_len
        msg = attributes._validate_string("", 0)
        self.assertIsNone(msg)

        # 0 == len(data) < max_len
        msg = attributes._validate_string("", 9)
        self.assertIsNone(msg)

        # 0 < len(data) < max_len
        msg = attributes._validate_string("123456789", 10)
        self.assertIsNone(msg)

        # 0 < len(data) == max_len
        msg = attributes._validate_string("123456789", 9)
        self.assertIsNone(msg)

        # 0 < max_len < len(data)
        msg = attributes._validate_string("1234567890", 9)
        self.assertEqual(msg, "'1234567890' exceeds maximum length of 9")

        msg = attributes._validate_string("123456789", None)
        self.assertIsNone(msg)

    def test_validate_no_whitespace(self):
        data = 'no_white_space'
        result = attributes._validate_no_whitespace(data)
        self.assertEqual(result, data)

        self.assertRaises(n_exc.InvalidInput,
                          attributes._validate_no_whitespace,
                          'i have whitespace')

        self.assertRaises(n_exc.InvalidInput,
                          attributes._validate_no_whitespace,
                          'i\thave\twhitespace')

    def test_validate_range(self):
        msg = attributes._validate_range(1, [1, 9])
        self.assertIsNone(msg)

        msg = attributes._validate_range(5, [1, 9])
        self.assertIsNone(msg)

        msg = attributes._validate_range(9, [1, 9])
        self.assertIsNone(msg)

        msg = attributes._validate_range(1, (1, 9))
        self.assertIsNone(msg)

        msg = attributes._validate_range(5, (1, 9))
        self.assertIsNone(msg)

        msg = attributes._validate_range(9, (1, 9))
        self.assertIsNone(msg)

        msg = attributes._validate_range(0, [1, 9])
        self.assertEqual(msg, "'0' is too small - must be at least '1'")

        msg = attributes._validate_range(10, (1, 9))
        self.assertEqual(msg,
                         "'10' is too large - must be no larger than '9'")

        msg = attributes._validate_range("bogus", (1, 9))
        self.assertEqual(msg, "'bogus' is not an integer")

        msg = attributes._validate_range(10, (attributes.UNLIMITED,
                                              attributes.UNLIMITED))
        self.assertIsNone(msg)

        msg = attributes._validate_range(10, (1, attributes.UNLIMITED))
        self.assertIsNone(msg)

        msg = attributes._validate_range(1, (attributes.UNLIMITED, 9))
        self.assertIsNone(msg)

        msg = attributes._validate_range(-1, (0, attributes.UNLIMITED))
        self.assertEqual(msg, "'-1' is too small - must be at least '0'")

        msg = attributes._validate_range(10, (attributes.UNLIMITED, 9))
        self.assertEqual(msg,
                         "'10' is too large - must be no larger than '9'")

    def _test_validate_mac_address(self, validator, allow_none=False):
        mac_addr = "ff:16:3e:4f:00:00"
        msg = validator(mac_addr)
        self.assertIsNone(msg)

        mac_addr = "ffa:16:3e:4f:00:00"
        msg = validator(mac_addr)
        err_msg = "'%s' is not a valid MAC address"
        self.assertEqual(msg, err_msg % mac_addr)

        mac_addr = "123"
        msg = validator(mac_addr)
        self.assertEqual(msg, err_msg % mac_addr)

        mac_addr = None
        msg = validator(mac_addr)
        if allow_none:
            self.assertIsNone(msg)
        else:
            self.assertEqual(msg, err_msg % mac_addr)

    def test_validate_mac_address(self):
        self._test_validate_mac_address(attributes._validate_mac_address)

    def test_validate_mac_address_or_none(self):
        self._test_validate_mac_address(
            attributes._validate_mac_address_or_none, allow_none=True)

    def test_validate_ip_address(self):
        ip_addr = '1.1.1.1'
        msg = attributes._validate_ip_address(ip_addr)
        self.assertIsNone(msg)

        ip_addr = '1111.1.1.1'
        msg = attributes._validate_ip_address(ip_addr)
        self.assertEqual(msg, "'%s' is not a valid IP address" % ip_addr)

        ip_addr = '1.1.1.1 has whitespace'
        msg = attributes._validate_ip_address(ip_addr)
        self.assertEqual(msg, "'%s' is not a valid IP address" % ip_addr)

        ip_addr = '111.1.1.1\twhitespace'
        msg = attributes._validate_ip_address(ip_addr)
        self.assertEqual(msg, "'%s' is not a valid IP address" % ip_addr)

        ip_addr = '111.1.1.1\nwhitespace'
        msg = attributes._validate_ip_address(ip_addr)
        self.assertEqual(msg, "'%s' is not a valid IP address" % ip_addr)

    def test_validate_ip_pools(self):
        pools = [[{'end': '10.0.0.254'}],
                 [{'start': '10.0.0.254'}],
                 [{'start': '1000.0.0.254',
                   'end': '1.1.1.1'}],
                 [{'start': '10.0.0.2', 'end': '10.0.0.254',
                   'forza': 'juve'}],
                 [{'start': '10.0.0.2', 'end': '10.0.0.254'},
                  {'end': '10.0.0.254'}],
                 [None],
                 None]
        for pool in pools:
            msg = attributes._validate_ip_pools(pool)
            self.assertIsNotNone(msg)

        pools = [[{'end': '10.0.0.254', 'start': '10.0.0.2'},
                  {'start': '11.0.0.2', 'end': '11.1.1.1'}],
                 [{'start': '11.0.0.2', 'end': '11.0.0.100'}]]
        for pool in pools:
            msg = attributes._validate_ip_pools(pool)
            self.assertIsNone(msg)

    def test_validate_fixed_ips(self):
        fixed_ips = [
            {'data': [{'subnet_id': '00000000-ffff-ffff-ffff-000000000000',
                       'ip_address': '1111.1.1.1'}],
             'error_msg': "'1111.1.1.1' is not a valid IP address"},
            {'data': [{'subnet_id': 'invalid',
                       'ip_address': '1.1.1.1'}],
             'error_msg': "'invalid' is not a valid UUID"},
            {'data': None,
             'error_msg': "Invalid data format for fixed IP: 'None'"},
            {'data': "1.1.1.1",
             'error_msg': "Invalid data format for fixed IP: '1.1.1.1'"},
            {'data': ['00000000-ffff-ffff-ffff-000000000000', '1.1.1.1'],
             'error_msg': "Invalid data format for fixed IP: "
                          "'00000000-ffff-ffff-ffff-000000000000'"},
            {'data': [['00000000-ffff-ffff-ffff-000000000000', '1.1.1.1']],
             'error_msg': "Invalid data format for fixed IP: "
                          "'['00000000-ffff-ffff-ffff-000000000000', "
                          "'1.1.1.1']'"},
            {'data': [{'subnet_id': '00000000-0fff-ffff-ffff-000000000000',
                       'ip_address': '1.1.1.1'},
                      {'subnet_id': '00000000-ffff-ffff-ffff-000000000000',
                       'ip_address': '1.1.1.1'}],
             'error_msg': "Duplicate IP address '1.1.1.1'"}]
        for fixed in fixed_ips:
            msg = attributes._validate_fixed_ips(fixed['data'])
            self.assertEqual(msg, fixed['error_msg'])

        fixed_ips = [[{'subnet_id': '00000000-ffff-ffff-ffff-000000000000',
                       'ip_address': '1.1.1.1'}],
                     [{'subnet_id': '00000000-0fff-ffff-ffff-000000000000',
                       'ip_address': '1.1.1.1'},
                      {'subnet_id': '00000000-ffff-ffff-ffff-000000000000',
                       'ip_address': '1.1.1.2'}]]
        for fixed in fixed_ips:
            msg = attributes._validate_fixed_ips(fixed)
            self.assertIsNone(msg)

    def test_validate_nameservers(self):
        ns_pools = [['1.1.1.2', '1.1.1.2'],
                    ['www.hostname.com', 'www.hostname.com'],
                    ['1000.0.0.1'],
                    None]

        for ns in ns_pools:
            msg = attributes._validate_nameservers(ns, None)
            self.assertIsNotNone(msg)

        ns_pools = [['100.0.0.2'],
                    ['www.hostname.com'],
                    ['www.great.marathons.to.travel'],
                    ['valid'],
                    ['77.hostname.com'],
                    ['1' * 59],
                    ['www.internal.hostname.com']]

        for ns in ns_pools:
            msg = attributes._validate_nameservers(ns, None)
            self.assertIsNone(msg)

    def test_validate_hostroutes(self):
        hostroute_pools = [[{'destination': '100.0.0.0/24'}],
                           [{'nexthop': '10.0.2.20'}],
                           [{'nexthop': '10.0.2.20',
                             'forza': 'juve',
                             'destination': '100.0.0.0/8'}],
                           [{'nexthop': '1110.0.2.20',
                             'destination': '100.0.0.0/8'}],
                           [{'nexthop': '10.0.2.20',
                             'destination': '100.0.0.0'}],
                           [{'nexthop': '10.0.2.20',
                             'destination': '100.0.0.0/8'},
                            {'nexthop': '10.0.2.20',
                             'destination': '100.0.0.0/8'}],
                           [None],
                           None]
        for host_routes in hostroute_pools:
            msg = attributes._validate_hostroutes(host_routes, None)
            self.assertIsNotNone(msg)

        hostroute_pools = [[{'destination': '100.0.0.0/24',
                             'nexthop': '10.0.2.20'}],
                           [{'nexthop': '10.0.2.20',
                             'destination': '100.0.0.0/8'},
                            {'nexthop': '10.0.2.20',
                             'destination': '101.0.0.0/8'}]]
        for host_routes in hostroute_pools:
            msg = attributes._validate_hostroutes(host_routes, None)
            self.assertIsNone(msg)

    def test_validate_ip_address_or_none(self):
        ip_addr = None
        msg = attributes._validate_ip_address_or_none(ip_addr)
        self.assertIsNone(msg)

        ip_addr = '1.1.1.1'
        msg = attributes._validate_ip_address_or_none(ip_addr)
        self.assertIsNone(msg)

        ip_addr = '1111.1.1.1'
        msg = attributes._validate_ip_address_or_none(ip_addr)
        self.assertEqual(msg, "'%s' is not a valid IP address" % ip_addr)

    def test_hostname_pattern(self):
        bad_values = ['@openstack', 'ffff.abcdefg' * 26, 'f' * 80, '-hello',
                      'goodbye-', 'example..org']
        for data in bad_values:
            msg = attributes._validate_hostname(data)
            self.assertIsNotNone(msg)

        # All numeric hostnames are allowed per RFC 1123 section 2.1
        good_values = ['www.openstack.org', '1234x', '1234',
                       'openstack-1', 'v.xyz', '1' * 50, 'a1a',
                       'x.x1x', 'x.yz', 'example.org.']
        for data in good_values:
            msg = attributes._validate_hostname(data)
            self.assertIsNone(msg)

    def test_uuid_pattern(self):
        data = 'garbage'
        msg = attributes._validate_regex(data, attributes.UUID_PATTERN)
        self.assertIsNotNone(msg)

        data = '00000000-ffff-ffff-ffff-000000000000'
        msg = attributes._validate_regex(data, attributes.UUID_PATTERN)
        self.assertIsNone(msg)

    def test_mac_pattern(self):
        # Valid - 3 octets
        base_mac = "fa:16:3e:00:00:00"
        msg = attributes._validate_regex(base_mac,
                                         attributes.MAC_PATTERN)
        self.assertIsNone(msg)

        # Valid - 4 octets
        base_mac = "fa:16:3e:4f:00:00"
        msg = attributes._validate_regex(base_mac,
                                         attributes.MAC_PATTERN)
        self.assertIsNone(msg)

        # Invalid - not unicast
        base_mac = "01:16:3e:4f:00:00"
        msg = attributes._validate_regex(base_mac,
                                         attributes.MAC_PATTERN)
        self.assertIsNotNone(msg)

        # Invalid - invalid format
        base_mac = "a:16:3e:4f:00:00"
        msg = attributes._validate_regex(base_mac,
                                         attributes.MAC_PATTERN)
        self.assertIsNotNone(msg)

        # Invalid - invalid format
        base_mac = "ffa:16:3e:4f:00:00"
        msg = attributes._validate_regex(base_mac,
                                         attributes.MAC_PATTERN)
        self.assertIsNotNone(msg)

        # Invalid - invalid format
        base_mac = "01163e4f0000"
        msg = attributes._validate_regex(base_mac,
                                         attributes.MAC_PATTERN)
        self.assertIsNotNone(msg)

        # Invalid - invalid format
        base_mac = "01-16-3e-4f-00-00"
        msg = attributes._validate_regex(base_mac,
                                         attributes.MAC_PATTERN)
        self.assertIsNotNone(msg)

        # Invalid - invalid format
        base_mac = "00:16:3:f:00:00"
        msg = attributes._validate_regex(base_mac,
                                         attributes.MAC_PATTERN)
        self.assertIsNotNone(msg)

        # Invalid - invalid format
        base_mac = "12:3:4:5:67:89ab"
        msg = attributes._validate_regex(base_mac,
                                         attributes.MAC_PATTERN)
        self.assertIsNotNone(msg)

    def _test_validate_subnet(self, validator, allow_none=False):
        # Valid - IPv4
        cidr = "10.0.2.0/24"
        msg = validator(cidr, None)
        self.assertIsNone(msg)

        # Valid - IPv6 without final octets
        cidr = "fe80::/24"
        msg = validator(cidr, None)
        self.assertIsNone(msg)

        # Valid - IPv6 with final octets
        cidr = "fe80::/24"
        msg = validator(cidr, None)
        self.assertIsNone(msg)

        # Valid - uncompressed ipv6 address
        cidr = "fe80:0:0:0:0:0:0:0/128"
        msg = validator(cidr, None)
        self.assertIsNone(msg)

        # Valid - ipv6 address with multiple consecutive zero
        cidr = "2001:0db8:0:0:1::1/128"
        msg = validator(cidr, None)
        self.assertIsNone(msg)

        # Valid - ipv6 address with multiple consecutive zero
        cidr = "2001:0db8::1:0:0:1/128"
        msg = validator(cidr, None)
        self.assertIsNone(msg)

        # Valid - ipv6 address with multiple consecutive zero
        cidr = "2001::0:1:0:0:1100/120"
        msg = validator(cidr, None)
        self.assertIsNone(msg)

        # Valid - abbreviated ipv4 address
        cidr = "10/24"
        msg = validator(cidr, None)
        self.assertIsNone(msg)

        # Invalid - IPv4 missing mask
        cidr = "10.0.2.0"
        msg = validator(cidr, None)
        error = _("'%(data)s' isn't a recognized IP subnet cidr,"
                  " '%(cidr)s' is recommended") % {"data": cidr,
                                                   "cidr": "10.0.2.0/32"}
        self.assertEqual(msg, error)

        # Valid - IPv4 with non-zero masked bits is ok
        for i in range(1, 255):
            cidr = "192.168.1.%s/24" % i
            msg = validator(cidr, None)
            self.assertIsNone(msg)

        # Invalid - IPv6 without final octets, missing mask
        cidr = "fe80::"
        msg = validator(cidr, None)
        error = _("'%(data)s' isn't a recognized IP subnet cidr,"
                  " '%(cidr)s' is recommended") % {"data": cidr,
                                                   "cidr": "fe80::/128"}
        self.assertEqual(msg, error)

        # Invalid - IPv6 with final octets, missing mask
        cidr = "fe80::0"
        msg = validator(cidr, None)
        error = _("'%(data)s' isn't a recognized IP subnet cidr,"
                  " '%(cidr)s' is recommended") % {"data": cidr,
                                                   "cidr": "fe80::/128"}
        self.assertEqual(msg, error)

        # Invalid - Address format error
        cidr = 'invalid'
        msg = validator(cidr, None)
        error = "'%s' is not a valid IP subnet" % cidr
        self.assertEqual(msg, error)

        cidr = None
        msg = validator(cidr, None)
        if allow_none:
            self.assertIsNone(msg)
        else:
            error = "'%s' is not a valid IP subnet" % cidr
            self.assertEqual(msg, error)

    def test_validate_subnet(self):
        self._test_validate_subnet(attributes._validate_subnet)

    def test_validate_subnet_or_none(self):
        self._test_validate_subnet(attributes._validate_subnet_or_none,
                                   allow_none=True)

    def _test_validate_regex(self, validator, allow_none=False):
        pattern = '[hc]at'

        data = None
        msg = validator(data, pattern)
        if allow_none:
            self.assertIsNone(msg)
        else:
            self.assertEqual(msg, "'None' is not a valid input")

        data = 'bat'
        msg = validator(data, pattern)
        self.assertEqual(msg, "'%s' is not a valid input" % data)

        data = 'hat'
        msg = validator(data, pattern)
        self.assertIsNone(msg)

        data = 'cat'
        msg = validator(data, pattern)
        self.assertIsNone(msg)

    def test_validate_regex(self):
        self._test_validate_regex(attributes._validate_regex)

    def test_validate_regex_or_none(self):
        self._test_validate_regex(attributes._validate_regex_or_none,
                                  allow_none=True)

    def test_validate_uuid(self):
        msg = attributes._validate_uuid('garbage')
        self.assertEqual(msg, "'garbage' is not a valid UUID")

        msg = attributes._validate_uuid('00000000-ffff-ffff-ffff-000000000000')
        self.assertIsNone(msg)

    def test_validate_uuid_list(self):
        # check not a list
        uuids = [None,
                 123,
                 'e5069610-744b-42a7-8bd8-ceac1a229cd4',
                 '12345678123456781234567812345678',
                 {'uuid': 'e5069610-744b-42a7-8bd8-ceac1a229cd4'}]
        for uuid in uuids:
            msg = attributes._validate_uuid_list(uuid)
            error = "'%s' is not a list" % uuid
            self.assertEqual(msg, error)

        # check invalid uuid in a list
        invalid_uuid_lists = [[None],
                              [123],
                              [123, 'e5069610-744b-42a7-8bd8-ceac1a229cd4'],
                              ['123', '12345678123456781234567812345678'],
                              ['t5069610-744b-42a7-8bd8-ceac1a229cd4'],
                              ['e5069610-744b-42a7-8bd8-ceac1a229cd44'],
                              ['e50696100-744b-42a7-8bd8-ceac1a229cd4'],
                              ['e5069610-744bb-42a7-8bd8-ceac1a229cd4']]
        for uuid_list in invalid_uuid_lists:
            msg = attributes._validate_uuid_list(uuid_list)
            error = "'%s' is not a valid UUID" % uuid_list[0]
            self.assertEqual(msg, error)

        # check duplicate items in a list
        duplicate_uuids = ['e5069610-744b-42a7-8bd8-ceac1a229cd4',
                           'f3eeab00-8367-4524-b662-55e64d4cacb5',
                           'e5069610-744b-42a7-8bd8-ceac1a229cd4']
        msg = attributes._validate_uuid_list(duplicate_uuids)
        error = ("Duplicate items in the list: "
                 "'%s'" % ', '.join(duplicate_uuids))
        self.assertEqual(msg, error)

        # check valid uuid lists
        valid_uuid_lists = [['e5069610-744b-42a7-8bd8-ceac1a229cd4'],
                            ['f3eeab00-8367-4524-b662-55e64d4cacb5'],
                            ['e5069610-744b-42a7-8bd8-ceac1a229cd4',
                             'f3eeab00-8367-4524-b662-55e64d4cacb5']]
        for uuid_list in valid_uuid_lists:
            msg = attributes._validate_uuid_list(uuid_list)
            self.assertIsNone(msg)

    def test_validate_dict_type(self):
        for value in (None, True, '1', []):
            self.assertEqual(attributes._validate_dict(value),
                             "'%s' is not a dictionary" % value)

    def test_validate_dict_without_constraints(self):
        msg = attributes._validate_dict({})
        self.assertIsNone(msg)

        # Validate a dictionary without constraints.
        msg = attributes._validate_dict({'key': 'value'})
        self.assertIsNone(msg)

    def test_validate_a_valid_dict_with_constraints(self):
        dictionary, constraints = self._construct_dict_and_constraints()

        msg = attributes._validate_dict(dictionary, constraints)
        self.assertIsNone(msg, 'Validation of a valid dictionary failed.')

    def test_validate_dict_with_invalid_validator(self):
        dictionary, constraints = self._construct_dict_and_constraints()

        constraints['key1'] = {'type:unsupported': None, 'required': True}
        msg = attributes._validate_dict(dictionary, constraints)
        self.assertEqual(msg, "Validator 'type:unsupported' does not exist.")

    def test_validate_dict_not_required_keys(self):
        dictionary, constraints = self._construct_dict_and_constraints()

        del dictionary['key2']
        msg = attributes._validate_dict(dictionary, constraints)
        self.assertIsNone(msg, 'Field that was not required by the specs was'
                               'required by the validator.')

    def test_validate_dict_required_keys(self):
        dictionary, constraints = self._construct_dict_and_constraints()

        del dictionary['key1']
        msg = attributes._validate_dict(dictionary, constraints)
        self.assertIn('Expected keys:', msg)

    def test_validate_dict_wrong_values(self):
        dictionary, constraints = self._construct_dict_and_constraints()

        dictionary['key1'] = 'UNSUPPORTED'
        msg = attributes._validate_dict(dictionary, constraints)
        self.assertIsNotNone(msg)

    def test_validate_dict_convert_boolean(self):
        dictionary, constraints = self._construct_dict_and_constraints()

        constraints['key_bool'] = {
            'type:boolean': None,
            'required': False,
            'convert_to': attributes.convert_to_boolean}
        dictionary['key_bool'] = 'true'
        msg = attributes._validate_dict(dictionary, constraints)
        self.assertIsNone(msg)
        # Explicitly comparing with literal 'True' as assertTrue
        # succeeds also for 'true'
        self.assertIs(True, dictionary['key_bool'])

    def test_subdictionary(self):
        dictionary, constraints = self._construct_dict_and_constraints()

        del dictionary['key3']['k4']
        dictionary['key3']['k5'] = 'a string value'
        msg = attributes._validate_dict(dictionary, constraints)
        self.assertIn('Expected keys:', msg)

    def test_validate_dict_or_none(self):
        dictionary, constraints = self._construct_dict_and_constraints()

        # Check whether None is a valid value.
        msg = attributes._validate_dict_or_none(None, constraints)
        self.assertIsNone(msg, 'Validation of a None dictionary failed.')

        # Check validation of a regular dictionary.
        msg = attributes._validate_dict_or_none(dictionary, constraints)
        self.assertIsNone(msg, 'Validation of a valid dictionary failed.')

    def test_validate_dict_or_empty(self):
        dictionary, constraints = self._construct_dict_and_constraints()

        # Check whether an empty dictionary is valid.
        msg = attributes._validate_dict_or_empty({}, constraints)
        self.assertIsNone(msg, 'Validation of a None dictionary failed.')

        # Check validation of a regular dictionary.
        msg = attributes._validate_dict_or_none(dictionary, constraints)
        self.assertIsNone(msg, 'Validation of a valid dictionary failed.')
        self.assertIsNone(msg, 'Validation of a valid dictionary failed.')

    def test_validate_non_negative(self):
        for value in (-1, '-2'):
            self.assertEqual(attributes._validate_non_negative(value),
                             "'%s' should be non-negative" % value)

        for value in (0, 1, '2', True, False):
            msg = attributes._validate_non_negative(value)
            self.assertIsNone(msg)


class TestConvertToBoolean(base.BaseTestCase):

    def test_convert_to_boolean_bool(self):
        self.assertIs(attributes.convert_to_boolean(True), True)
        self.assertIs(attributes.convert_to_boolean(False), False)

    def test_convert_to_boolean_int(self):
        self.assertIs(attributes.convert_to_boolean(0), False)
        self.assertIs(attributes.convert_to_boolean(1), True)
        self.assertRaises(n_exc.InvalidInput,
                          attributes.convert_to_boolean,
                          7)

    def test_convert_to_boolean_str(self):
        self.assertIs(attributes.convert_to_boolean('True'), True)
        self.assertIs(attributes.convert_to_boolean('true'), True)
        self.assertIs(attributes.convert_to_boolean('False'), False)
        self.assertIs(attributes.convert_to_boolean('false'), False)
        self.assertIs(attributes.convert_to_boolean('0'), False)
        self.assertIs(attributes.convert_to_boolean('1'), True)
        self.assertRaises(n_exc.InvalidInput,
                          attributes.convert_to_boolean,
                          '7')


class TestConvertToInt(base.BaseTestCase):

    def test_convert_to_int_int(self):
        self.assertEqual(attributes.convert_to_int(-1), -1)
        self.assertEqual(attributes.convert_to_int(0), 0)
        self.assertEqual(attributes.convert_to_int(1), 1)

    def test_convert_to_int_str(self):
        self.assertEqual(attributes.convert_to_int('4'), 4)
        self.assertEqual(attributes.convert_to_int('6'), 6)
        self.assertRaises(n_exc.InvalidInput,
                          attributes.convert_to_int,
                          'garbage')

    def test_convert_to_int_none(self):
        self.assertRaises(n_exc.InvalidInput,
                          attributes.convert_to_int,
                          None)

    def test_convert_none_to_empty_list_none(self):
        self.assertEqual(
            [], attributes.convert_none_to_empty_list(None))

    def test_convert_none_to_empty_dict(self):
        self.assertEqual(
            {}, attributes.convert_none_to_empty_dict(None))

    def test_convert_none_to_empty_list_value(self):
        values = ['1', 3, [], [1], {}, {'a': 3}]
        for value in values:
            self.assertEqual(
                value, attributes.convert_none_to_empty_list(value))


class TestConvertKvp(base.BaseTestCase):

    def test_convert_kvp_list_to_dict_succeeds_for_missing_values(self):
        result = attributes.convert_kvp_list_to_dict(['True'])
        self.assertEqual({}, result)

    def test_convert_kvp_list_to_dict_succeeds_for_multiple_values(self):
        result = attributes.convert_kvp_list_to_dict(
            ['a=b', 'a=c', 'a=c', 'b=a'])
        self.assertEqual({'a': ['c', 'b'], 'b': ['a']}, result)

    def test_convert_kvp_list_to_dict_succeeds_for_values(self):
        result = attributes.convert_kvp_list_to_dict(['a=b', 'c=d'])
        self.assertEqual({'a': ['b'], 'c': ['d']}, result)

    def test_convert_kvp_str_to_list_fails_for_missing_key(self):
        with testtools.ExpectedException(n_exc.InvalidInput):
            attributes.convert_kvp_str_to_list('=a')

    def test_convert_kvp_str_to_list_fails_for_missing_equals(self):
        with testtools.ExpectedException(n_exc.InvalidInput):
            attributes.convert_kvp_str_to_list('a')

    def test_convert_kvp_str_to_list_succeeds_for_one_equals(self):
        result = attributes.convert_kvp_str_to_list('a=')
        self.assertEqual(['a', ''], result)

    def test_convert_kvp_str_to_list_succeeds_for_two_equals(self):
        result = attributes.convert_kvp_str_to_list('a=a=a')
        self.assertEqual(['a', 'a=a'], result)


class TestConvertToList(base.BaseTestCase):

    def test_convert_to_empty_list(self):
        for item in (None, [], (), {}):
            self.assertEqual(attributes.convert_to_list(item), [])

    def test_convert_to_list_string(self):
        for item in ('', 'foo'):
            self.assertEqual(attributes.convert_to_list(item), [item])

    def test_convert_to_list_iterable(self):
        for item in ([None], [1, 2, 3], (1, 2, 3), set([1, 2, 3]), ['foo']):
            self.assertEqual(attributes.convert_to_list(item), list(item))

    def test_convert_to_list_non_iterable(self):
        for item in (True, False, 1, 1.2, object()):
            self.assertEqual(attributes.convert_to_list(item), [item])