summaryrefslogtreecommitdiff
path: root/ironic/tests/unit/common/test_args.py
blob: 5695bb8fc119176f8630afcc7c01e37adc357241 (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
#    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.

from oslo_utils import uuidutils

from ironic.common import args
from ironic.common import exception
from ironic.tests import base


class ArgsDecorated(object):

    @args.validate(one=args.string,
                   two=args.boolean,
                   three=args.uuid,
                   four=args.uuid_or_name)
    def method(self, one, two, three, four):
        return one, two, three, four

    @args.validate(one=args.string)
    def needs_string(self, one):
        return one

    @args.validate(one=args.boolean)
    def needs_boolean(self, one):
        return one

    @args.validate(one=args.uuid)
    def needs_uuid(self, one):
        return one

    @args.validate(one=args.name)
    def needs_name(self, one):
        return one

    @args.validate(one=args.uuid_or_name)
    def needs_uuid_or_name(self, one):
        return one

    @args.validate(one=args.string_list)
    def needs_string_list(self, one):
        return one

    @args.validate(one=args.integer)
    def needs_integer(self, one):
        return one

    @args.validate(one=args.mac_address)
    def needs_mac_address(self, one):
        return one

    @args.validate(one=args.schema({
        'type': 'array',
        'items': {
            'type': 'object',
            'properties': {
                'name': {'type': 'string'},
                'count': {'type': 'integer', 'minimum': 0},
            },
            'additionalProperties': False,
            'required': ['name'],
        }
    }))
    def needs_schema(self, one):
        return one

    @args.validate(one=args.string, two=args.string, the_rest=args.schema({
        'type': 'object',
        'properties': {
            'three': {'type': 'string'},
            'four': {'type': 'string', 'maxLength': 4},
            'five': {'type': 'string'},
        },
        'additionalProperties': False,
        'required': ['three']
    }))
    def needs_schema_kwargs(self, one, two, **the_rest):
        return one, two, the_rest

    @args.validate(one=args.string, two=args.string, the_rest=args.schema({
        'type': 'array',
        'items': {'type': 'string'}
    }))
    def needs_schema_args(self, one, two=None, *the_rest):
        return one, two, the_rest

    @args.validate(one=args.string, two=args.string, args=args.schema({
        'type': 'array',
        'items': {'type': 'string'}
    }), kwargs=args.schema({
        'type': 'object',
        'properties': {
            'four': {'type': 'string'},
        },
    }))
    def needs_schema_mixed(self, one, two=None, *args, **kwargs):
        return one, two, args, kwargs

    @args.validate(one=args.string)
    def needs_mixed_unvalidated(self, one, two=None, *args, **kwargs):
        return one, two, args, kwargs

    @args.validate(body=args.patch)
    def patch(self, body):
        return body


class BaseTest(base.TestCase):

    def setUp(self):
        super(BaseTest, self).setUp()
        self.decorated = ArgsDecorated()


class ValidateDecoratorTest(BaseTest):

    def test_decorated_args(self):
        uuid = uuidutils.generate_uuid()
        self.assertEqual((
            'a',
            True,
            uuid,
            'a_name',
        ), self.decorated.method(
            'a',
            True,
            uuid,
            'a_name',
        ))

    def test_decorated_kwargs(self):
        uuid = uuidutils.generate_uuid()
        self.assertEqual((
            'a',
            True,
            uuid,
            'a_name',
        ), self.decorated.method(
            one='a',
            two=True,
            three=uuid,
            four='a_name',
        ))

    def test_decorated_args_kwargs(self):
        uuid = uuidutils.generate_uuid()
        self.assertEqual((
            'a',
            True,
            uuid,
            'a_name',
        ), self.decorated.method(
            'a',
            True,
            uuid,
            four='a_name',
        ))

    def test_decorated_function(self):

        @args.validate(one=args.string,
                       two=args.boolean,
                       three=args.uuid,
                       four=args.uuid_or_name)
        def func(one, two, three, four):
            return one, two, three, four

        uuid = uuidutils.generate_uuid()
        self.assertEqual((
            'a',
            True,
            uuid,
            'a_name',
        ), func(
            'a',
            'yes',
            uuid,
            four='a_name',
        ))

    def test_unexpected_args(self):
        uuid = uuidutils.generate_uuid()
        e = self.assertRaises(
            exception.InvalidParameterValue,
            self.decorated.method,
            one='a',
            two=True,
            three=uuid,
            four='a_name',
            five='5',
            six=6
        )
        self.assertIn('Unexpected arguments: ', str(e))
        self.assertIn('five', str(e))
        self.assertIn('six', str(e))

    def test_string(self):
        self.assertEqual('foo', self.decorated.needs_string('foo'))
        self.assertIsNone(self.decorated.needs_string(None))
        self.assertRaises(exception.InvalidParameterValue,
                          self.decorated.needs_string, 123)

    def test_boolean(self):
        self.assertTrue(self.decorated.needs_boolean('yes'))
        self.assertTrue(self.decorated.needs_boolean('true'))
        self.assertTrue(self.decorated.needs_boolean(True))

        self.assertFalse(self.decorated.needs_boolean('no'))
        self.assertFalse(self.decorated.needs_boolean('false'))
        self.assertFalse(self.decorated.needs_boolean(False))

        self.assertIsNone(self.decorated.needs_boolean(None))
        self.assertRaises(exception.InvalidParameterValue,
                          self.decorated.needs_boolean,
                          'yeah nah yeah nah')

    def test_uuid(self):
        uuid = uuidutils.generate_uuid()
        self.assertEqual(uuid, self.decorated.needs_uuid(uuid))
        self.assertIsNone(self.decorated.needs_uuid(None))
        self.assertRaises(exception.InvalidParameterValue,
                          self.decorated.needs_uuid, uuid + 'XXX')

    def test_name(self):
        self.assertEqual('foo', self.decorated.needs_name('foo'))
        self.assertIsNone(self.decorated.needs_name(None))
        self.assertRaises(exception.InvalidParameterValue,
                          self.decorated.needs_name, 'I am a name')

    def test_uuid_or_name(self):
        uuid = uuidutils.generate_uuid()
        self.assertEqual(uuid, self.decorated.needs_uuid_or_name(uuid))
        self.assertEqual('foo', self.decorated.needs_uuid_or_name('foo'))
        self.assertIsNone(self.decorated.needs_uuid_or_name(None))
        self.assertRaises(exception.InvalidParameterValue,
                          self.decorated.needs_uuid_or_name,
                          'I am a name')

    def test_string_list(self):
        self.assertEqual([
            'foo', 'bar', 'baz'
        ], self.decorated.needs_string_list('foo, bar ,bAZ'))
        self.assertIsNone(self.decorated.needs_name(None))
        self.assertRaises(exception.InvalidParameterValue,
                          self.decorated.needs_name, True)

    def test_integer(self):
        self.assertEqual(123, self.decorated.needs_integer(123))
        self.assertIsNone(self.decorated.needs_integer(None))
        self.assertRaises(exception.InvalidParameterValue,
                          self.decorated.needs_integer,
                          'more than a number')

    def test_mac_address(self):
        self.assertEqual('02:ce:20:50:68:6f',
                         self.decorated.needs_mac_address('02:cE:20:50:68:6F'))
        self.assertIsNone(self.decorated.needs_mac_address(None))
        self.assertRaises(exception.InvalidParameterValue,
                          self.decorated.needs_mac_address,
                          'big:mac')

    def test_mixed_unvalidated(self):
        # valid
        self.assertEqual((
            'one', 'two', ('three', 'four', 'five'), {}
        ), self.decorated.needs_mixed_unvalidated(
            'one', 'two', 'three', 'four', 'five',
        ))
        self.assertEqual((
            'one', 'two', ('three',), {'four': 'four', 'five': 'five'}
        ), self.decorated.needs_mixed_unvalidated(
            'one', 'two', 'three', four='four', five='five',
        ))
        self.assertEqual((
            'one', 'two', (), {}
        ), self.decorated.needs_mixed_unvalidated(
            'one', 'two',
        ))
        self.assertEqual((
            'one', None, (), {}
        ), self.decorated.needs_mixed_unvalidated(
            'one',
        ))

        # wrong type in one
        self.assertRaises(exception.InvalidParameterValue,
                          self.decorated.needs_mixed_unvalidated, 1)

    def test_mandatory(self):

        @args.validate(foo=args.string)
        def doit(foo):
            return foo

        @args.validate(foo=args.string)
        def doit_maybe(foo='baz'):
            return foo

        # valid
        self.assertEqual('bar', doit('bar'))

        # invalid, argument not provided
        self.assertRaises(exception.InvalidParameterValue, doit)

        # valid, not mandatory
        self.assertEqual('baz', doit_maybe())

    def test_or(self):

        @args.validate(foo=args.or_valid(
            args.string,
            args.integer,
            args.boolean
        ))
        def doit(foo):
            return foo

        # valid
        self.assertEqual('bar', doit('bar'))
        self.assertEqual(1, doit(1))
        self.assertEqual(True, doit(True))

        # invalid, wrong type
        self.assertRaises(exception.InvalidParameterValue, doit, {})

    def test_and(self):

        @args.validate(foo=args.and_valid(
            args.string,
            args.name
        ))
        def doit(foo):
            return foo

        # valid
        self.assertEqual('bar', doit('bar'))

        # invalid, not a string
        self.assertRaises(exception.InvalidParameterValue, doit, 2)

        # invalid, not a name
        self.assertRaises(exception.InvalidParameterValue, doit, 'not a name')


class ValidateSchemaTest(BaseTest):

    def test_schema(self):
        valid = [
            {'name': 'zero'},
            {'name': 'one', 'count': 1},
            {'name': 'two', 'count': 2}
        ]
        invalid_count = [
            {'name': 'neg', 'count': -1},
            {'name': 'one', 'count': 1},
            {'name': 'two', 'count': 2}
        ]
        invalid_root = {}
        self.assertEqual(valid, self.decorated.needs_schema(valid))
        self.assertRaises(exception.InvalidParameterValue,
                          self.decorated.needs_schema,
                          invalid_count)
        self.assertRaises(exception.InvalidParameterValue,
                          self.decorated.needs_schema,
                          invalid_root)

    def test_schema_needs_kwargs(self):
        # valid
        self.assertEqual((
            'one', 'two', {
                'three': 'three',
                'four': 'four',
                'five': 'five',
            }
        ), self.decorated.needs_schema_kwargs(
            one='one',
            two='two',
            three='three',
            four='four',
            five='five',
        ))
        self.assertEqual((
            'one', 'two', {
                'three': 'three',
            }
        ), self.decorated.needs_schema_kwargs(
            one='one',
            two='two',
            three='three',
        ))
        self.assertEqual((
            'one', 'two', {}
        ), self.decorated.needs_schema_kwargs(
            one='one',
            two='two',
        ))

        # missing mandatory 'three'
        self.assertRaises(exception.InvalidParameterValue,
                          self.decorated.needs_schema_kwargs,
                          one='one', two='two', four='four', five='five')

        # 'four' value exceeds length
        self.assertRaises(exception.InvalidParameterValue,
                          self.decorated.needs_schema_kwargs,
                          one='one', two='two', three='three',
                          four='beforefore', five='five')

    def test_schema_needs_args(self):
        # valid
        self.assertEqual((
            'one', 'two', ('three', 'four', 'five')
        ), self.decorated.needs_schema_args(
            'one', 'two', 'three', 'four', 'five',
        ))
        self.assertEqual((
            'one', 'two', ('three',)
        ), self.decorated.needs_schema_args(
            'one', 'two', 'three',
        ))
        self.assertEqual((
            'one', 'two', ()
        ), self.decorated.needs_schema_args(
            'one', 'two',
        ))
        self.assertEqual((
            'one', None, ()
        ), self.decorated.needs_schema_args(
            'one',
        ))

        # failed, non string *the_rest value
        self.assertRaises(exception.InvalidParameterValue,
                          self.decorated.needs_schema_args,
                          'one', 'two', 'three', 4, False)

    def test_schema_needs_mixed(self):
        # valid
        self.assertEqual((
            'one', 'two', ('three', 'four', 'five'), {}
        ), self.decorated.needs_schema_mixed(
            'one', 'two', 'three', 'four', 'five',
        ))
        self.assertEqual((
            'one', 'two', ('three', ), {'four': 'four'}
        ), self.decorated.needs_schema_mixed(
            'one', 'two', 'three', four='four',
        ))
        self.assertEqual((
            'one', 'two', (), {'four': 'four'}
        ), self.decorated.needs_schema_mixed(
            'one', 'two', four='four',
        ))
        self.assertEqual((
            'one', None, (), {}
        ), self.decorated.needs_schema_mixed(
            'one',
        ))

        # wrong type in *args
        self.assertRaises(exception.InvalidParameterValue,
                          self.decorated.needs_schema_mixed,
                          'one', 'two', 3, four='four')
        # wrong type in *kwargs
        self.assertRaises(exception.InvalidParameterValue,
                          self.decorated.needs_schema_mixed,
                          'one', 'two', 'three', four=4)


class ValidatePatchSchemaTest(BaseTest):

    def test_patch(self):
        data = [{
            'path': '/foo',
            'op': 'replace',
            'value': 'bar'
        }, {
            'path': '/foo/bar',
            'op': 'add',
            'value': True
        }, {
            'path': '/foo/bar/baz',
            'op': 'remove',
            'value': 123
        }]

        self.assertEqual(
            data,
            self.decorated.patch(data)
        )

    def assertValidationFailed(self, data, error_snippets=None):
        e = self.assertRaises(exception.InvalidParameterValue,
                              self.decorated.patch, data)
        if error_snippets:
            for s in error_snippets:
                self.assertIn(s, str(e))

    def test_patch_validation_failed(self):
        self.assertValidationFailed(
            {},
            ["Schema error for body:",
             "{} is not of type 'array'"])
        self.assertValidationFailed(
            [{
                'path': '/foo/bar/baz',
                'op': 'fribble',
                'value': 123
            }],
            ["Schema error for body:",
             "'fribble' is not one of ['add', 'replace', 'remove']"])
        self.assertValidationFailed(
            [{
                'path': '/',
                'op': 'add',
                'value': 123
            }],
            ["Schema error for body:",
             "'/' does not match"])
        self.assertValidationFailed(
            [{
                'path': 'foo/',
                'op': 'add',
                'value': 123
            }],
            ["Schema error for body:",
             "'foo/' does not match"])
        self.assertValidationFailed(
            [{
                'path': '/foo bar',
                'op': 'add',
                'value': 123
            }],
            ["Schema error for body:",
             "'/foo bar' does not match"])


class ValidateDictTest(BaseTest):

    def test_dict_valid(self):
        uuid = uuidutils.generate_uuid()

        @args.validate(foo=args.dict_valid(
            bar=args.uuid
        ))
        def doit(foo):
            return foo

        # validate passes
        doit(foo={'bar': uuid})

        # tolerate other keys
        doit(foo={'bar': uuid, 'baz': 'baz'})

        # key missing
        doit({})

        # value fails validation
        e = self.assertRaises(exception.InvalidParameterValue,
                              doit, {'bar': uuid + 'XXX'})
        self.assertIn('Expected UUID for bar:', str(e))

        # not a dict
        e = self.assertRaises(exception.InvalidParameterValue,
                              doit, 'asdf')
        self.assertIn("Expected types <class 'dict'> for foo: asdf", str(e))

    def test_dict_valid_colon_key_name(self):
        uuid = uuidutils.generate_uuid()

        @args.validate(foo=args.dict_valid(**{
            'bar:baz': args.uuid
        }
        ))
        def doit(foo):
            return foo

        # validate passes
        doit(foo={'bar:baz': uuid})

        # value fails validation
        e = self.assertRaises(exception.InvalidParameterValue,
                              doit, {'bar:baz': uuid + 'XXX'})
        self.assertIn('Expected UUID for bar:', str(e))


class ValidateTypesTest(BaseTest):

    def test_types(self):

        @args.validate(foo=args.types(None, dict, str))
        def doit(foo):
            return foo

        # valid None
        self.assertIsNone(doit(None))

        # valid dict
        self.assertEqual({'foo': 'bar'}, doit({'foo': 'bar'}))

        # valid string
        self.assertEqual('foo', doit('foo'))

        # invalid integer
        e = self.assertRaises(exception.InvalidParameterValue,
                              doit, 123)
        self.assertIn("Expected types "
                      "<class 'NoneType'>, <class 'dict'>, <class 'str'> "
                      "for foo: 123", str(e))