-
Notifications
You must be signed in to change notification settings - Fork 197
/
test_resource.py
3116 lines (2441 loc) · 104 KB
/
test_resource.py
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
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 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 itertools
import json
from keystoneauth1 import adapter
import mock
import munch
import requests
import six
from openstack import exceptions
from openstack import format
from openstack import resource
from openstack.tests.unit import base
class FakeResponse(object):
def __init__(self, response, status_code=200, headers=None):
self.body = response
self.status_code = status_code
headers = headers if headers else {'content-type': 'application/json'}
self.headers = requests.structures.CaseInsensitiveDict(headers)
def json(self):
return self.body
class TestComponent(base.TestCase):
class ExampleComponent(resource._BaseComponent):
key = "_example"
# Since we're testing ExampleComponent, which is as isolated as we
# can test _BaseComponent due to it's needing to be a data member
# of a class that has an attribute on the parent class named `key`,
# each test has to implement a class with a name that is the same
# as ExampleComponent.key, which should be a dict containing the
# keys and values to test against.
def test_implementations(self):
self.assertEqual("_body", resource.Body.key)
self.assertEqual("_header", resource.Header.key)
self.assertEqual("_uri", resource.URI.key)
def test_creation(self):
sot = resource._BaseComponent(
"name", type=int, default=1, alternate_id=True, aka="alias")
self.assertEqual("name", sot.name)
self.assertEqual(int, sot.type)
self.assertEqual(1, sot.default)
self.assertEqual("alias", sot.aka)
self.assertTrue(sot.alternate_id)
def test_get_no_instance(self):
sot = resource._BaseComponent("test")
# Test that we short-circuit everything when given no instance.
result = sot.__get__(None, None)
self.assertIs(sot, result)
# NOTE: Some tests will use a default=1 setting when testing result
# values that should be None because the default-for-default is also None.
def test_get_name_None(self):
name = "name"
class Parent(object):
_example = {name: None}
instance = Parent()
sot = TestComponent.ExampleComponent(name, default=1)
# Test that we short-circuit any typing of a None value.
result = sot.__get__(instance, None)
self.assertIsNone(result)
def test_get_default(self):
expected_result = 123
class Parent(object):
_example = {}
instance = Parent()
# NOTE: type=dict but the default value is an int. If we didn't
# short-circuit the typing part of __get__ it would fail.
sot = TestComponent.ExampleComponent("name", type=dict,
default=expected_result)
# Test that we directly return any default value.
result = sot.__get__(instance, None)
self.assertEqual(expected_result, result)
def test_get_name_untyped(self):
name = "name"
expected_result = 123
class Parent(object):
_example = {name: expected_result}
instance = Parent()
sot = TestComponent.ExampleComponent("name")
# Test that we return any the value as it is set.
result = sot.__get__(instance, None)
self.assertEqual(expected_result, result)
# The code path for typing after a raw value has been found is the same.
def test_get_name_typed(self):
name = "name"
value = "123"
class Parent(object):
_example = {name: value}
instance = Parent()
sot = TestComponent.ExampleComponent("name", type=int)
# Test that we run the underlying value through type conversion.
result = sot.__get__(instance, None)
self.assertEqual(int(value), result)
def test_get_name_formatter(self):
name = "name"
value = "123"
expected_result = "one hundred twenty three"
class Parent(object):
_example = {name: value}
class FakeFormatter(format.Formatter):
@classmethod
def deserialize(cls, value):
return expected_result
instance = Parent()
sot = TestComponent.ExampleComponent("name", type=FakeFormatter)
# Mock out issubclass rather than having an actual format.Formatter
# This can't be mocked via decorator, isolate it to wrapping the call.
result = sot.__get__(instance, None)
self.assertEqual(expected_result, result)
def test_set_name_untyped(self):
name = "name"
expected_value = "123"
class Parent(object):
_example = {}
instance = Parent()
sot = TestComponent.ExampleComponent("name")
# Test that we don't run the value through type conversion.
sot.__set__(instance, expected_value)
self.assertEqual(expected_value, instance._example[name])
def test_set_name_typed(self):
expected_value = "123"
class Parent(object):
_example = {}
instance = Parent()
# The type we give to ExampleComponent has to be an actual type,
# not an instance, so we can't get the niceties of a mock.Mock
# instance that would allow us to call `assert_called_once_with` to
# ensure that we're sending the value through the type.
# Instead, we use this tiny version of a similar thing.
class FakeType(object):
calls = []
def __init__(self, arg):
FakeType.calls.append(arg)
sot = TestComponent.ExampleComponent("name", type=FakeType)
# Test that we run the value through type conversion.
sot.__set__(instance, expected_value)
self.assertEqual([expected_value], FakeType.calls)
def test_set_name_formatter(self):
expected_value = "123"
class Parent(object):
_example = {}
instance = Parent()
# As with test_set_name_typed, create a pseudo-Mock to track what
# gets called on the type.
class FakeFormatter(format.Formatter):
calls = []
@classmethod
def serialize(cls, arg):
FakeFormatter.calls.append(arg)
@classmethod
def deserialize(cls, arg):
FakeFormatter.calls.append(arg)
sot = TestComponent.ExampleComponent("name", type=FakeFormatter)
# Test that we run the value through type conversion.
sot.__set__(instance, expected_value)
self.assertEqual([expected_value], FakeFormatter.calls)
def test_delete_name(self):
name = "name"
expected_value = "123"
class Parent(object):
_example = {name: expected_value}
instance = Parent()
sot = TestComponent.ExampleComponent("name")
sot.__delete__(instance)
self.assertNotIn(name, instance._example)
def test_delete_name_doesnt_exist(self):
name = "name"
expected_value = "123"
class Parent(object):
_example = {"what": expected_value}
instance = Parent()
sot = TestComponent.ExampleComponent(name)
sot.__delete__(instance)
self.assertNotIn(name, instance._example)
class TestComponentManager(base.TestCase):
def test_create_basic(self):
sot = resource._ComponentManager()
self.assertEqual(dict(), sot.attributes)
self.assertEqual(set(), sot._dirty)
def test_create_unsynced(self):
attrs = {"hey": 1, "hi": 2, "hello": 3}
sync = False
sot = resource._ComponentManager(attributes=attrs, synchronized=sync)
self.assertEqual(attrs, sot.attributes)
self.assertEqual(set(attrs.keys()), sot._dirty)
def test_create_synced(self):
attrs = {"hey": 1, "hi": 2, "hello": 3}
sync = True
sot = resource._ComponentManager(attributes=attrs, synchronized=sync)
self.assertEqual(attrs, sot.attributes)
self.assertEqual(set(), sot._dirty)
def test_getitem(self):
key = "key"
value = "value"
attrs = {key: value}
sot = resource._ComponentManager(attributes=attrs)
self.assertEqual(value, sot.__getitem__(key))
def test_setitem_new(self):
key = "key"
value = "value"
sot = resource._ComponentManager()
sot.__setitem__(key, value)
self.assertIn(key, sot.attributes)
self.assertIn(key, sot.dirty)
def test_setitem_unchanged(self):
key = "key"
value = "value"
attrs = {key: value}
sot = resource._ComponentManager(attributes=attrs, synchronized=True)
# This shouldn't end up in the dirty list since we're just re-setting.
sot.__setitem__(key, value)
self.assertEqual(value, sot.attributes[key])
self.assertNotIn(key, sot.dirty)
def test_delitem(self):
key = "key"
value = "value"
attrs = {key: value}
sot = resource._ComponentManager(attributes=attrs, synchronized=True)
sot.__delitem__(key)
self.assertIsNone(sot.dirty[key])
def test_iter(self):
attrs = {"key": "value"}
sot = resource._ComponentManager(attributes=attrs)
self.assertCountEqual(iter(attrs), sot.__iter__())
def test_len(self):
attrs = {"key": "value"}
sot = resource._ComponentManager(attributes=attrs)
self.assertEqual(len(attrs), sot.__len__())
def test_dirty(self):
key = "key"
key2 = "key2"
value = "value"
attrs = {key: value}
sot = resource._ComponentManager(attributes=attrs, synchronized=False)
self.assertEqual({key: value}, sot.dirty)
sot.__setitem__(key2, value)
self.assertEqual({key: value, key2: value}, sot.dirty)
def test_clean(self):
key = "key"
value = "value"
attrs = {key: value}
sot = resource._ComponentManager(attributes=attrs, synchronized=False)
self.assertEqual(attrs, sot.dirty)
sot.clean()
self.assertEqual(dict(), sot.dirty)
class Test_Request(base.TestCase):
def test_create(self):
uri = 1
body = 2
headers = 3
sot = resource._Request(uri, body, headers)
self.assertEqual(uri, sot.url)
self.assertEqual(body, sot.body)
self.assertEqual(headers, sot.headers)
class TestQueryParameters(base.TestCase):
def test_create(self):
location = "location"
mapping = {"first_name": "first-name",
"second_name": {"name": "second-name"},
"third_name": {"name": "third", "type": int}}
sot = resource.QueryParameters(location, **mapping)
self.assertEqual({"location": "location",
"first_name": "first-name",
"second_name": {"name": "second-name"},
"third_name": {"name": "third", "type": int},
"limit": "limit",
"marker": "marker"},
sot._mapping)
def test_transpose_unmapped(self):
def _type(value, rtype):
self.assertIs(rtype, mock.sentinel.resource_type)
return value * 10
location = "location"
mapping = {"first_name": "first-name",
"pet_name": {"name": "pet"},
"answer": {"name": "answer", "type": int},
"complex": {"type": _type}}
sot = resource.QueryParameters(location, **mapping)
result = sot._transpose({"location": "Brooklyn",
"first_name": "Brian",
"pet_name": "Meow",
"answer": "42",
"last_name": "Curtin",
"complex": 1},
mock.sentinel.resource_type)
# last_name isn't mapped and shouldn't be included
self.assertEqual({"location": "Brooklyn", "first-name": "Brian",
"pet": "Meow", "answer": 42, "complex": 10},
result)
def test_transpose_not_in_query(self):
location = "location"
mapping = {"first_name": "first-name",
"pet_name": {"name": "pet"},
"answer": {"name": "answer", "type": int}}
sot = resource.QueryParameters(location, **mapping)
result = sot._transpose({"location": "Brooklyn"},
mock.sentinel.resource_type)
# first_name not being in the query shouldn't affect results
self.assertEqual({"location": "Brooklyn"},
result)
class TestResource(base.TestCase):
def test_initialize_basic(self):
body = {"body": 1}
header = {"header": 2, "Location": "somewhere"}
uri = {"uri": 3}
computed = {"computed": 4}
everything = dict(itertools.chain(
body.items(),
header.items(),
uri.items(),
computed.items(),
))
mock_collect = mock.Mock()
mock_collect.return_value = body, header, uri, computed
with mock.patch.object(resource.Resource,
"_collect_attrs", mock_collect):
sot = resource.Resource(_synchronized=False, **everything)
mock_collect.assert_called_once_with(everything)
self.assertIsNone(sot.location)
self.assertIsInstance(sot._body, resource._ComponentManager)
self.assertEqual(body, sot._body.dirty)
self.assertIsInstance(sot._header, resource._ComponentManager)
self.assertEqual(header, sot._header.dirty)
self.assertIsInstance(sot._uri, resource._ComponentManager)
self.assertEqual(uri, sot._uri.dirty)
self.assertFalse(sot.allow_create)
self.assertFalse(sot.allow_fetch)
self.assertFalse(sot.allow_commit)
self.assertFalse(sot.allow_delete)
self.assertFalse(sot.allow_list)
self.assertFalse(sot.allow_head)
self.assertEqual('PUT', sot.commit_method)
self.assertEqual('POST', sot.create_method)
def test_repr(self):
a = {"a": 1}
b = {"b": 2}
c = {"c": 3}
d = {"d": 4}
class Test(resource.Resource):
def __init__(self):
self._body = mock.Mock()
self._body.attributes.items = mock.Mock(
return_value=a.items())
self._header = mock.Mock()
self._header.attributes.items = mock.Mock(
return_value=b.items())
self._uri = mock.Mock()
self._uri.attributes.items = mock.Mock(
return_value=c.items())
self._computed = mock.Mock()
self._computed.attributes.items = mock.Mock(
return_value=d.items())
the_repr = repr(Test())
# Don't test the arguments all together since the dictionary order
# they're rendered in can't be depended on, nor does it matter.
self.assertIn("openstack.tests.unit.test_resource.Test", the_repr)
self.assertIn("a=1", the_repr)
self.assertIn("b=2", the_repr)
self.assertIn("c=3", the_repr)
self.assertIn("d=4", the_repr)
def test_equality(self):
class Example(resource.Resource):
x = resource.Body("x")
y = resource.Header("y")
z = resource.URI("z")
e1 = Example(x=1, y=2, z=3)
e2 = Example(x=1, y=2, z=3)
e3 = Example(x=0, y=0, z=0)
self.assertEqual(e1, e2)
self.assertNotEqual(e1, e3)
self.assertNotEqual(e1, None)
def test__update(self):
sot = resource.Resource()
body = "body"
header = "header"
uri = "uri"
computed = "computed"
sot._collect_attrs = mock.Mock(
return_value=(body, header, uri, computed))
sot._body.update = mock.Mock()
sot._header.update = mock.Mock()
sot._uri.update = mock.Mock()
sot._computed.update = mock.Mock()
args = {"arg": 1}
sot._update(**args)
sot._collect_attrs.assert_called_once_with(args)
sot._body.update.assert_called_once_with(body)
sot._header.update.assert_called_once_with(header)
sot._uri.update.assert_called_once_with(uri)
sot._computed.update.assert_called_with(computed)
def test__consume_attrs(self):
serverside_key1 = "someKey1"
clientside_key1 = "some_key1"
serverside_key2 = "someKey2"
clientside_key2 = "some_key2"
value1 = "value1"
value2 = "value2"
mapping = {serverside_key1: clientside_key1,
serverside_key2: clientside_key2}
other_key = "otherKey"
other_value = "other"
attrs = {clientside_key1: value1,
serverside_key2: value2,
other_key: other_value}
sot = resource.Resource()
result = sot._consume_attrs(mapping, attrs)
# Make sure that the expected key was consumed and we're only
# left with the other stuff.
self.assertDictEqual({other_key: other_value}, attrs)
# Make sure that after we've popped our relevant client-side
# key off that we are returning it keyed off of its server-side
# name.
self.assertDictEqual({serverside_key1: value1,
serverside_key2: value2}, result)
def test__mapping_defaults(self):
# Check that even on an empty class, we get the expected
# built-in attributes.
self.assertIn("location", resource.Resource._computed_mapping())
self.assertIn("name", resource.Resource._body_mapping())
self.assertIn("id", resource.Resource._body_mapping())
def test__mapping_overrides(self):
# Iterating through the MRO used to wipe out overrides of mappings
# found in base classes.
new_name = "MyName"
new_id = "MyID"
class Test(resource.Resource):
name = resource.Body(new_name)
id = resource.Body(new_id)
mapping = Test._body_mapping()
self.assertEqual("name", mapping["MyName"])
self.assertEqual("id", mapping["MyID"])
def test__body_mapping(self):
class Test(resource.Resource):
x = resource.Body("x")
y = resource.Body("y")
z = resource.Body("z")
self.assertIn("x", Test._body_mapping())
self.assertIn("y", Test._body_mapping())
self.assertIn("z", Test._body_mapping())
def test__header_mapping(self):
class Test(resource.Resource):
x = resource.Header("x")
y = resource.Header("y")
z = resource.Header("z")
self.assertIn("x", Test._header_mapping())
self.assertIn("y", Test._header_mapping())
self.assertIn("z", Test._header_mapping())
def test__uri_mapping(self):
class Test(resource.Resource):
x = resource.URI("x")
y = resource.URI("y")
z = resource.URI("z")
self.assertIn("x", Test._uri_mapping())
self.assertIn("y", Test._uri_mapping())
self.assertIn("z", Test._uri_mapping())
def test__getattribute__id_in_body(self):
id = "lol"
sot = resource.Resource(id=id)
result = getattr(sot, "id")
self.assertEqual(result, id)
def test__getattribute__id_with_alternate(self):
id = "lol"
class Test(resource.Resource):
blah = resource.Body("blah", alternate_id=True)
sot = Test(blah=id)
result = getattr(sot, "id")
self.assertEqual(result, id)
def test__getattribute__id_without_alternate(self):
class Test(resource.Resource):
id = None
sot = Test()
self.assertIsNone(sot.id)
def test__alternate_id_None(self):
self.assertEqual("", resource.Resource._alternate_id())
def test__alternate_id(self):
class Test(resource.Resource):
alt = resource.Body("the_alt", alternate_id=True)
self.assertEqual("the_alt", Test._alternate_id())
value1 = "lol"
sot = Test(alt=value1)
self.assertEqual(sot.alt, value1)
self.assertEqual(sot.id, value1)
value2 = "rofl"
sot = Test(the_alt=value2)
self.assertEqual(sot.alt, value2)
self.assertEqual(sot.id, value2)
def test__alternate_id_from_other_property(self):
class Test(resource.Resource):
foo = resource.Body("foo")
bar = resource.Body("bar", alternate_id=True)
# NOTE(redrobot): My expectation looking at the Test class defined
# in this test is that because the alternate_id parameter is
# is being set to True on the "bar" property of the Test class,
# then the _alternate_id() method should return the name of that "bar"
# property.
self.assertEqual("bar", Test._alternate_id())
sot = Test(bar='bunnies')
self.assertEqual(sot.id, 'bunnies')
self.assertEqual(sot.bar, 'bunnies')
sot = Test(id='chickens', bar='bunnies')
self.assertEqual(sot.id, 'chickens')
self.assertEqual(sot.bar, 'bunnies')
def test__get_id_instance(self):
class Test(resource.Resource):
id = resource.Body("id")
value = "id"
sot = Test(id=value)
self.assertEqual(value, sot._get_id(sot))
def test__get_id_instance_alternate(self):
class Test(resource.Resource):
attr = resource.Body("attr", alternate_id=True)
value = "id"
sot = Test(attr=value)
self.assertEqual(value, sot._get_id(sot))
def test__get_id_value(self):
value = "id"
self.assertEqual(value, resource.Resource._get_id(value))
def test__attributes(self):
class Test(resource.Resource):
foo = resource.Header('foo')
bar = resource.Body('bar', aka='_bar')
bar_local = resource.Body('bar_remote')
sot = Test()
self.assertEqual(
sorted(['foo', 'bar', '_bar', 'bar_local',
'id', 'name', 'location']),
sorted(sot._attributes())
)
self.assertEqual(
sorted(['foo', 'bar', 'bar_local', 'id', 'name', 'location']),
sorted(sot._attributes(include_aliases=False))
)
self.assertEqual(
sorted(['foo', 'bar', '_bar', 'bar_remote',
'id', 'name', 'location']),
sorted(sot._attributes(remote_names=True))
)
self.assertEqual(
sorted(['bar', '_bar', 'bar_local', 'id', 'name', 'location']),
sorted(sot._attributes(
components=tuple([resource.Body, resource.Computed])))
)
self.assertEqual(
('foo',),
tuple(sot._attributes(components=tuple([resource.Header])))
)
def test__attributes_iterator(self):
class Parent(resource.Resource):
foo = resource.Header('foo')
bar = resource.Body('bar', aka='_bar')
class Child(Parent):
foo1 = resource.Header('foo1')
bar1 = resource.Body('bar1')
sot = Child()
expected = ['foo', 'bar', 'foo1', 'bar1']
for attr, component in sot._attributes_iterator():
if attr in expected:
expected.remove(attr)
self.assertEqual([], expected)
expected = ['foo', 'foo1']
# Check we iterate only over headers
for attr, component in sot._attributes_iterator(
components=tuple([resource.Header])):
if attr in expected:
expected.remove(attr)
self.assertEqual([], expected)
def test_to_dict(self):
class Test(resource.Resource):
foo = resource.Header('foo')
bar = resource.Body('bar', aka='_bar')
res = Test(id='FAKE_ID')
expected = {
'id': 'FAKE_ID',
'name': None,
'location': None,
'foo': None,
'bar': None,
'_bar': None
}
self.assertEqual(expected, res.to_dict())
def test_to_dict_nested(self):
class Test(resource.Resource):
foo = resource.Header('foo')
bar = resource.Body('bar')
a_list = resource.Body('a_list')
class Sub(resource.Resource):
sub = resource.Body('foo')
sub = Sub(id='ANOTHER_ID', foo='bar')
res = Test(
id='FAKE_ID',
bar=sub,
a_list=[sub])
expected = {
'id': 'FAKE_ID',
'name': None,
'location': None,
'foo': None,
'bar': {
'id': 'ANOTHER_ID',
'name': None,
'sub': 'bar',
'location': None,
},
'a_list': [{
'id': 'ANOTHER_ID',
'name': None,
'sub': 'bar',
'location': None,
}],
}
self.assertEqual(expected, res.to_dict())
a_munch = res.to_dict(_to_munch=True)
self.assertEqual(a_munch.bar.id, 'ANOTHER_ID')
self.assertEqual(a_munch.bar.sub, 'bar')
self.assertEqual(a_munch.a_list[0].id, 'ANOTHER_ID')
self.assertEqual(a_munch.a_list[0].sub, 'bar')
def test_to_dict_no_body(self):
class Test(resource.Resource):
foo = resource.Header('foo')
bar = resource.Body('bar')
res = Test(id='FAKE_ID')
expected = {
'location': None,
'foo': None,
}
self.assertEqual(expected, res.to_dict(body=False))
def test_to_dict_no_header(self):
class Test(resource.Resource):
foo = resource.Header('foo')
bar = resource.Body('bar')
res = Test(id='FAKE_ID')
expected = {
'id': 'FAKE_ID',
'name': None,
'bar': None,
'location': None,
}
self.assertEqual(expected, res.to_dict(headers=False))
def test_to_dict_ignore_none(self):
class Test(resource.Resource):
foo = resource.Header('foo')
bar = resource.Body('bar')
res = Test(id='FAKE_ID', bar='BAR')
expected = {
'id': 'FAKE_ID',
'bar': 'BAR',
}
self.assertEqual(expected, res.to_dict(ignore_none=True))
def test_to_dict_with_mro(self):
class Parent(resource.Resource):
foo = resource.Header('foo')
bar = resource.Body('bar', aka='_bar')
class Child(Parent):
foo_new = resource.Header('foo_baz_server')
bar_new = resource.Body('bar_baz_server')
res = Child(id='FAKE_ID', bar='test')
expected = {
'foo': None,
'bar': 'test',
'_bar': 'test',
'foo_new': None,
'bar_new': None,
'id': 'FAKE_ID',
'location': None,
'name': None
}
self.assertEqual(expected, res.to_dict())
def test_json_dumps_from_resource(self):
class Test(resource.Resource):
foo = resource.Body('foo_remote')
res = Test(foo='bar')
expected = '{"foo": "bar", "id": null, "location": null, "name": null}'
actual = json.dumps(res, sort_keys=True)
self.assertEqual(expected, actual)
response = FakeResponse({
'foo': 'new_bar'})
res._translate_response(response)
expected = ('{"foo": "new_bar", "id": null, '
'"location": null, "name": null}')
actual = json.dumps(res, sort_keys=True)
self.assertEqual(expected, actual)
def test_items(self):
class Test(resource.Resource):
foo = resource.Body('foo')
bar = resource.Body('bar')
foot = resource.Body('foot')
data = {
'foo': 'bar',
'bar': 'foo\n',
'foot': 'a:b:c:d'
}
res = Test(**data)
for k, v in res.items():
expected = data.get(k)
if expected:
self.assertEqual(v, expected)
def test_access_by_aka(self):
class Test(resource.Resource):
foo = resource.Header('foo_remote', aka='foo_alias')
res = Test(foo='bar', name='test')
self.assertEqual('bar', res['foo_alias'])
self.assertEqual('bar', res.foo_alias)
self.assertTrue('foo' in res.keys())
self.assertTrue('foo_alias' in res.keys())
expected = munch.Munch({
'id': None,
'name': 'test',
'location': None,
'foo': 'bar',
'foo_alias': 'bar'
})
actual = munch.Munch(res)
self.assertEqual(expected, actual)
self.assertEqual(expected, res.toDict())
self.assertEqual(expected, res.to_dict())
self.assertDictEqual(expected, res)
self.assertDictEqual(expected, dict(res))
def test_to_dict_value_error(self):
class Test(resource.Resource):
foo = resource.Header('foo')
bar = resource.Body('bar')
res = Test(id='FAKE_ID')
err = self.assertRaises(
ValueError,
res.to_dict,
body=False, headers=False, computed=False)
self.assertEqual(
'At least one of `body`, `headers` or `computed` must be True',
six.text_type(err))
def test_to_dict_with_mro_no_override(self):
class Parent(resource.Resource):
header = resource.Header('HEADER')
body = resource.Body('BODY')
class Child(Parent):
# The following two properties are not supposed to be overridden
# by the parent class property values.
header = resource.Header('ANOTHER_HEADER')
body = resource.Body('ANOTHER_BODY')
res = Child(id='FAKE_ID', body='BODY_VALUE', header='HEADER_VALUE')
expected = {
'body': 'BODY_VALUE',
'header': 'HEADER_VALUE',
'id': 'FAKE_ID',
'location': None,
'name': None
}
self.assertEqual(expected, res.to_dict())
def test_new(self):
class Test(resource.Resource):
attr = resource.Body("attr")
value = "value"
sot = Test.new(attr=value)
self.assertIn("attr", sot._body.dirty)
self.assertEqual(value, sot.attr)
def test_existing(self):
class Test(resource.Resource):
attr = resource.Body("attr")