File: test_resource.py

package info (click to toggle)
python-openstacksdk 0.8.1-2~bpo8%2B1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 2,748 kB
  • sloc: python: 15,505; makefile: 156; sh: 46
file content (1533 lines) | stat: -rw-r--r-- 53,273 bytes parent folder | download | duplicates (2)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
# 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 copy
import json
import os

from keystoneauth1 import session
import mock
import requests
from testtools import matchers

from openstack import exceptions
from openstack import format
from openstack import resource
from openstack.tests.unit import base
from openstack import utils


fake_parent = 'robert'
fake_name = 'rey'
fake_id = 99
fake_attr1 = 'lana'
fake_attr2 = 'del'

fake_resource = 'fake'
fake_resources = 'fakes'
fake_arguments = {'parent_name': fake_parent}
fake_base_path = '/fakes/%(parent_name)s/data'
fake_path = '/fakes/rey/data'

fake_data = {'id': fake_id,
             'enabled': True,
             'name': fake_name,
             'parent': fake_parent,
             'attr1': fake_attr1,
             'attr2': fake_attr2,
             'status': None}
fake_body = {fake_resource: fake_data}


class FakeParent(resource.Resource):
    id_attribute = "name"
    name = resource.prop('name')


class FakeResource(resource.Resource):

    resource_key = fake_resource
    resources_key = fake_resources
    base_path = fake_base_path

    allow_create = allow_retrieve = allow_update = True
    allow_delete = allow_list = allow_head = True

    enabled = resource.prop('enabled', type=format.BoolStr)
    name = resource.prop('name')
    parent = resource.prop('parent_name')
    first = resource.prop('attr1')
    second = resource.prop('attr2')
    third = resource.prop('attr3', alias='attr_three')
    status = resource.prop('status')


class FakeResourceNoKeys(FakeResource):

    resource_key = None
    resources_key = None


class PropTests(base.TestCase):

    def test_with_alias_and_type(self):
        class Test(resource.Resource):
            attr = resource.prop("attr1", alias="attr2", type=bool)

        t = Test(attrs={"attr2": 500})

        # Don't test with assertTrue because 500 evaluates to True.
        # Need to test that bool(500) happened and attr2 *is* True.
        self.assertIs(t.attr, True)

    def test_defaults(self):
        new_default = "new_default"

        class Test(resource.Resource):
            attr1 = resource.prop("attr1")
            attr2 = resource.prop("attr2", default=new_default)

        t = Test()

        self.assertIsNone(t.attr1)
        self.assertEqual(new_default, t.attr2)

        # When the default value is passed in, it is left untouched.
        # Check that attr2 is literally the same object we set as default.
        t.attr2 = new_default
        self.assertIs(new_default, t.attr2)

        not_default = 'not default'
        t2 = Test({'attr2': not_default})
        self.assertEqual(not_default, t2.attr2)

        # Assert that if the default is passed in, it overrides the previously
        # set value (bug #1425996)
        t2.attr2 = new_default
        self.assertEqual(new_default, t2.attr2)

    def test_get_without_instance(self):
        self.assertIsNone(FakeResource.name)

    def test_set_ValueError(self):
        class Test(resource.Resource):
            attr = resource.prop("attr", type=int)

        t = Test()

        def should_raise():
            t.attr = "this is not an int"

        self.assertThat(should_raise, matchers.raises(ValueError))

    def test_set_TypeError(self):
        class Type(object):
            def __init__(self):
                pass

        class Test(resource.Resource):
            attr = resource.prop("attr", type=Type)

        t = Test()

        def should_raise():
            t.attr = "this type takes no args"

        self.assertThat(should_raise, matchers.raises(TypeError))

    def test_resource_type(self):
        class FakestResource(resource.Resource):
            shortstop = resource.prop("shortstop", type=FakeResource)
            third_base = resource.prop("third_base", type=FakeResource)

        sot = FakestResource()
        id1 = "Ernie Banks"
        id2 = "Ron Santo"
        sot.shortstop = id1
        sot.third_base = id2

        resource1 = FakeResource.new(id=id1)
        self.assertEqual(resource1, sot.shortstop)
        self.assertEqual(id1, sot.shortstop.id)
        self.assertEqual(FakeResource, type(sot.shortstop))

        resource2 = FakeResource.new(id=id2)
        self.assertEqual(resource2, sot.third_base)
        self.assertEqual(id2, sot.third_base.id)
        self.assertEqual(FakeResource, type(sot.third_base))

        sot2 = FakestResource()
        sot2.shortstop = resource1
        sot2.third_base = resource2
        self.assertEqual(resource1, sot2.shortstop)
        self.assertEqual(id1, sot2.shortstop.id)
        self.assertEqual(FakeResource, type(sot2.shortstop))
        self.assertEqual(resource2, sot2.third_base)
        self.assertEqual(id2, sot2.third_base.id)
        self.assertEqual(FakeResource, type(sot2.third_base))

        body = {
            "shortstop": id1,
            "third_base": id2
        }
        sot3 = FakestResource(body)
        self.assertEqual(FakeResource({"id": id1}), sot3.shortstop)
        self.assertEqual(FakeResource({"id": id2}), sot3.third_base)

    def test_set_alias_same_name(self):
        class Test(resource.Resource):
            attr = resource.prop("something", alias="attr")

        val = "hey"
        args = {"something": val}
        sot = Test(args)

        self.assertEqual(val, sot._attrs["something"])
        self.assertEqual(val, sot.attr)

    def test_property_is_none(self):
        class Test(resource.Resource):
            attr = resource.prop("something", type=dict)

        args = {"something": None}
        sot = Test(args)

        self.assertIsNone(sot._attrs["something"])
        self.assertIsNone(sot.attr)


class HeaderTests(base.TestCase):
    class Test(resource.Resource):
        base_path = "/ramones"
        service = "punk"
        allow_create = True
        allow_update = True
        hey = resource.header("vocals")
        ho = resource.header("guitar")
        letsgo = resource.header("bass")

    def test_get(self):
        val = "joey"
        args = {"vocals": val}
        sot = HeaderTests.Test({'headers': args})
        self.assertEqual(val, sot.hey)
        self.assertIsNone(sot.ho)
        self.assertIsNone(sot.letsgo)

    def test_set_new(self):
        args = {"vocals": "joey", "bass": "deedee"}
        sot = HeaderTests.Test({'headers': args})
        sot._reset_dirty()
        sot.ho = "johnny"
        self.assertEqual("johnny", sot.ho)
        self.assertTrue(sot.is_dirty)

    def test_set_old(self):
        args = {"vocals": "joey", "bass": "deedee"}
        sot = HeaderTests.Test({'headers': args})
        sot._reset_dirty()
        sot.letsgo = "cj"
        self.assertEqual("cj", sot.letsgo)
        self.assertTrue(sot.is_dirty)

    def test_set_brand_new(self):
        sot = HeaderTests.Test({'headers': {}})
        sot._reset_dirty()
        sot.ho = "johnny"
        self.assertEqual("johnny", sot.ho)
        self.assertTrue(sot.is_dirty)
        self.assertEqual({'headers': {"guitar": "johnny"}}, sot)

    def test_1428342(self):
        sot = HeaderTests.Test({'headers':
                               requests.structures.CaseInsensitiveDict()})

        self.assertIsNone(sot.hey)

    def test_create_update_headers(self):
        sot = HeaderTests.Test()
        sot._reset_dirty()
        sot.ho = "johnny"
        sot.letsgo = "deedee"
        response = mock.Mock()
        response_body = {'id': 1}
        response.json = mock.Mock(return_value=response_body)
        response.headers = None
        sess = mock.Mock()
        sess.post = mock.Mock(return_value=response)
        sess.put = mock.Mock(return_value=response)

        sot.create(sess)
        headers = {'guitar': 'johnny', 'bass': 'deedee'}
        sess.post.assert_called_with(HeaderTests.Test.base_path,
                                     endpoint_filter=HeaderTests.Test.service,
                                     headers=headers,
                                     json={})

        sot['id'] = 1
        sot.letsgo = "cj"
        headers = {'guitar': 'johnny', 'bass': 'cj'}
        sot.update(sess)
        sess.put.assert_called_with('ramones/1',
                                    endpoint_filter=HeaderTests.Test.service,
                                    headers=headers,
                                    json={})


class ResourceTests(base.TestCase):

    def setUp(self):
        super(ResourceTests, self).setUp()
        self.session = mock.Mock(spec=session.Session)
        self.session.get_filter = mock.Mock(return_value={})

    def assertCalledURL(self, method, url):
        # call_args gives a tuple of *args and tuple of **kwargs.
        # Check that the first arg in *args (the URL) has our url.
        self.assertEqual(method.call_args[0][0], url)

    def test_empty_id(self):
        resp = mock.Mock()
        resp.json = mock.Mock(return_value=fake_body)
        self.session.get.return_value = resp

        obj = FakeResource.new(**fake_arguments)
        self.assertEqual(obj, obj.get(self.session))

        self.assertEqual(fake_id, obj.id)
        self.assertEqual(fake_name, obj['name'])
        self.assertEqual(fake_attr1, obj['attr1'])
        self.assertEqual(fake_attr2, obj['attr2'])

        self.assertEqual(fake_name, obj.name)
        self.assertEqual(fake_attr1, obj.first)
        self.assertEqual(fake_attr2, obj.second)

    def test_not_allowed(self):
        class Nope(resource.Resource):
            allow_create = allow_retrieve = allow_update = False
            allow_delete = allow_list = allow_head = False

        nope = Nope()

        def cant_create():
            nope.create_by_id(1, 2)

        def cant_retrieve():
            nope.get_data_by_id(1, 2)

        def cant_update():
            nope.update_by_id(1, 2, 3)

        def cant_delete():
            nope.delete_by_id(1, 2)

        def cant_list():
            for i in nope.list(1):
                pass

        def cant_head():
            nope.head_data_by_id(1, 2)

        self.assertThat(cant_create,
                        matchers.raises(exceptions.MethodNotSupported))
        self.assertThat(cant_retrieve,
                        matchers.raises(exceptions.MethodNotSupported))
        self.assertThat(cant_update,
                        matchers.raises(exceptions.MethodNotSupported))
        self.assertThat(cant_delete,
                        matchers.raises(exceptions.MethodNotSupported))
        self.assertThat(cant_list,
                        matchers.raises(exceptions.MethodNotSupported))
        self.assertThat(cant_head,
                        matchers.raises(exceptions.MethodNotSupported))

    def _test_create_by_id(self, key, response_value, response_body,
                           attrs, json_body, response_headers=None):

        class FakeResource2(FakeResource):
            resource_key = key
            service = "my_service"

        response = mock.Mock()
        response.json = mock.Mock(return_value=response_body)
        response.headers = response_headers
        expected_resp = response_value.copy()
        if response_headers:
            expected_resp.update({'headers': response_headers})

        sess = mock.Mock()
        sess.put = mock.Mock(return_value=response)
        sess.post = mock.Mock(return_value=response)

        resp = FakeResource2.create_by_id(sess, attrs)
        self.assertEqual(expected_resp, resp)
        sess.post.assert_called_with(FakeResource2.base_path,
                                     endpoint_filter=FakeResource2.service,
                                     json=json_body)

        r_id = "my_id"
        resp = FakeResource2.create_by_id(sess, attrs, resource_id=r_id)
        self.assertEqual(response_value, resp)
        sess.put.assert_called_with(
            utils.urljoin(FakeResource2.base_path, r_id),
            endpoint_filter=FakeResource2.service,
            json=json_body)

        path_args = {"parent_name": "my_name"}
        resp = FakeResource2.create_by_id(sess, attrs, path_args=path_args)
        self.assertEqual(response_value, resp)
        sess.post.assert_called_with(FakeResource2.base_path % path_args,
                                     endpoint_filter=FakeResource2.service,
                                     json=json_body)

        resp = FakeResource2.create_by_id(sess, attrs, resource_id=r_id,
                                          path_args=path_args)
        self.assertEqual(response_value, resp)
        sess.put.assert_called_with(
            utils.urljoin(FakeResource2.base_path % path_args, r_id),
            endpoint_filter=FakeResource2.service,
            json=json_body)

    def test_create_without_resource_key(self):
        key = None
        response_value = {"a": 1, "b": 2, "c": 3}
        response_body = response_value
        attrs = response_value
        json_body = attrs
        self._test_create_by_id(key, response_value, response_body,
                                attrs, json_body)

    def test_create_with_response_headers(self):
        key = None
        response_value = {"a": 1, "b": 2, "c": 3}
        response_body = response_value
        response_headers = {'location': 'foo'}
        attrs = response_value.copy()
        json_body = attrs
        self._test_create_by_id(key, response_value, response_body,
                                attrs, json_body,
                                response_headers=response_headers)

    def test_create_with_resource_key(self):
        key = "my_key"
        response_value = {"a": 1, "b": 2, "c": 3}
        response_body = {key: response_value}
        attrs = response_body
        json_body = {key: attrs}
        self._test_create_by_id(key, response_value, response_body,
                                attrs, json_body)

    def _test_get_data_by_id(self, key, response_value, response_body):
        class FakeResource2(FakeResource):
            resource_key = key
            service = "my_service"

        response = mock.Mock()
        response.json = mock.Mock(return_value=response_body)

        sess = mock.Mock()
        sess.get = mock.Mock(return_value=response)

        r_id = "my_id"
        resp = FakeResource2.get_data_by_id(sess, resource_id=r_id)
        self.assertEqual(response_value, resp)
        sess.get.assert_called_with(
            utils.urljoin(FakeResource2.base_path, r_id),
            endpoint_filter=FakeResource2.service)

        path_args = {"parent_name": "my_name"}
        resp = FakeResource2.get_data_by_id(sess, resource_id=r_id,
                                            path_args=path_args)
        self.assertEqual(response_value, resp)
        sess.get.assert_called_with(
            utils.urljoin(FakeResource2.base_path % path_args, r_id),
            endpoint_filter=FakeResource2.service)

    def test_get_data_without_resource_key(self):
        key = None
        response_value = {"a": 1, "b": 2, "c": 3}
        response_body = response_value
        self._test_get_data_by_id(key, response_value, response_body)

    def test_get_data_with_resource_key(self):
        key = "my_key"
        response_value = {"a": 1, "b": 2, "c": 3}
        response_body = {key: response_value}
        self._test_get_data_by_id(key, response_value, response_body)

    def _test_head_data_by_id(self, key, response_value):
        class FakeResource2(FakeResource):
            resource_key = key
            service = "my_service"

        response = mock.Mock()
        response.headers = response_value

        sess = mock.Mock()
        sess.head = mock.Mock(return_value=response)

        r_id = "my_id"
        resp = FakeResource2.head_data_by_id(sess, resource_id=r_id)
        self.assertEqual({'headers': response_value}, resp)
        headers = {'Accept': ''}
        sess.head.assert_called_with(
            utils.urljoin(FakeResource2.base_path, r_id),
            endpoint_filter=FakeResource2.service,
            headers=headers)

        path_args = {"parent_name": "my_name"}
        resp = FakeResource2.head_data_by_id(sess, resource_id=r_id,
                                             path_args=path_args)
        self.assertEqual({'headers': response_value}, resp)
        headers = {'Accept': ''}
        sess.head.assert_called_with(
            utils.urljoin(FakeResource2.base_path % path_args, r_id),
            endpoint_filter=FakeResource2.service,
            headers=headers)

    def test_head_data_without_resource_key(self):
        key = None
        response_value = {"key1": "value1", "key2": "value2"}
        self._test_head_data_by_id(key, response_value)

    def test_head_data_with_resource_key(self):
        key = "my_key"
        response_value = {"key1": "value1", "key2": "value2"}
        self._test_head_data_by_id(key, response_value)

    def _test_update_by_id(self, key, response_value, response_body,
                           attrs, json_body, response_headers=None):

        class FakeResource2(FakeResource):
            patch_update = True
            resource_key = key
            service = "my_service"

        response = mock.Mock()
        response.json = mock.Mock(return_value=response_body)
        response.headers = response_headers
        expected_resp = response_value.copy()
        if response_headers:
            expected_resp.update({'headers': response_headers})

        sess = mock.Mock()
        sess.patch = mock.Mock(return_value=response)

        r_id = "my_id"
        resp = FakeResource2.update_by_id(sess, r_id, attrs)
        self.assertEqual(expected_resp, resp)
        sess.patch.assert_called_with(
            utils.urljoin(FakeResource2.base_path, r_id),
            endpoint_filter=FakeResource2.service,
            json=json_body)

        path_args = {"parent_name": "my_name"}
        resp = FakeResource2.update_by_id(sess, r_id, attrs,
                                          path_args=path_args)
        self.assertEqual(expected_resp, resp)
        sess.patch.assert_called_with(
            utils.urljoin(FakeResource2.base_path % path_args, r_id),
            endpoint_filter=FakeResource2.service,
            json=json_body)

    def test_update_without_resource_key(self):
        key = None
        response_value = {"a": 1, "b": 2, "c": 3}
        response_body = response_value
        attrs = response_value
        json_body = attrs
        self._test_update_by_id(key, response_value, response_body,
                                attrs, json_body)

    def test_update_with_resource_key(self):
        key = "my_key"
        response_value = {"a": 1, "b": 2, "c": 3}
        response_body = {key: response_value}
        attrs = response_value
        json_body = {key: attrs}
        self._test_update_by_id(key, response_value, response_body,
                                attrs, json_body)

    def test_update_with_response_headers(self):
        key = "my_key"
        response_value = {"a": 1, "b": 2, "c": 3}
        response_body = {key: response_value}
        response_headers = {'location': 'foo'}
        attrs = response_value.copy()
        json_body = {key: attrs}
        self._test_update_by_id(key, response_value, response_body,
                                attrs, json_body,
                                response_headers=response_headers)

    def test_delete_by_id(self):
        class FakeResource2(FakeResource):
            service = "my_service"

        sess = mock.Mock()
        sess.delete = mock.Mock(return_value=None)

        r_id = "my_id"
        resp = FakeResource2.delete_by_id(sess, r_id)
        self.assertIsNone(resp)
        headers = {'Accept': ''}
        sess.delete.assert_called_with(
            utils.urljoin(FakeResource2.base_path, r_id),
            endpoint_filter=FakeResource2.service,
            headers=headers)

        path_args = {"parent_name": "my_name"}
        resp = FakeResource2.delete_by_id(sess, r_id, path_args=path_args)
        self.assertIsNone(resp)
        headers = {'Accept': ''}
        sess.delete.assert_called_with(
            utils.urljoin(FakeResource2.base_path % path_args, r_id),
            endpoint_filter=FakeResource2.service,
            headers=headers)

    def test_create(self):
        resp = mock.Mock()
        resp.json = mock.Mock(return_value=fake_body)
        resp.headers = {'location': 'foo'}
        self.session.post = mock.Mock(return_value=resp)

        # Create resource with subset of attributes in order to
        # verify create refreshes all attributes from response.
        obj = FakeResource.new(parent_name=fake_parent,
                               name=fake_name,
                               enabled=True,
                               attr1=fake_attr1)

        self.assertEqual(obj, obj.create(self.session))
        self.assertFalse(obj.is_dirty)

        last_req = self.session.post.call_args[1]["json"][
            FakeResource.resource_key]

        self.assertEqual(4, len(last_req))
        self.assertTrue(last_req['enabled'])
        self.assertEqual(fake_parent, last_req['parent_name'])
        self.assertEqual(fake_name, last_req['name'])
        self.assertEqual(fake_attr1, last_req['attr1'])

        self.assertTrue(obj['enabled'])
        self.assertEqual(fake_name, obj['name'])
        self.assertEqual(fake_parent, obj['parent_name'])
        self.assertEqual(fake_attr1, obj['attr1'])
        self.assertEqual(fake_attr2, obj['attr2'])
        self.assertIsNone(obj['status'])

        self.assertTrue(obj.enabled)
        self.assertEqual(fake_id, obj.id)
        self.assertEqual(fake_name, obj.name)
        self.assertEqual(fake_parent, obj.parent_name)
        self.assertEqual(fake_parent, obj.parent)
        self.assertEqual(fake_attr1, obj.first)
        self.assertEqual(fake_attr1, obj.attr1)
        self.assertEqual(fake_attr2, obj.second)
        self.assertEqual(fake_attr2, obj.attr2)
        self.assertIsNone(obj.status)
        self.assertEqual('foo', obj.location)

    def test_get(self):
        resp = mock.Mock()
        resp.json = mock.Mock(return_value=fake_body)
        resp.headers = {'location': 'foo'}
        self.session.get = mock.Mock(return_value=resp)

        # Create resource with subset of attributes in order to
        # verify get refreshes all attributes from response.
        obj = FakeResource.from_id(str(fake_id))
        obj['parent_name'] = fake_parent

        self.assertEqual(obj, obj.get(self.session))

        # Check that the proper URL is being built.
        self.assertCalledURL(self.session.get,
                             os.path.join(fake_base_path % fake_arguments,
                                          str(fake_id))[1:])

        self.assertTrue(obj['enabled'])
        self.assertEqual(fake_name, obj['name'])
        self.assertEqual(fake_parent, obj['parent_name'])
        self.assertEqual(fake_attr1, obj['attr1'])
        self.assertEqual(fake_attr2, obj['attr2'])
        self.assertIsNone(obj['status'])

        self.assertTrue(obj.enabled)
        self.assertEqual(fake_id, obj.id)
        self.assertEqual(fake_name, obj.name)
        self.assertEqual(fake_parent, obj.parent_name)
        self.assertEqual(fake_parent, obj.parent)
        self.assertEqual(fake_attr1, obj.first)
        self.assertEqual(fake_attr1, obj.attr1)
        self.assertEqual(fake_attr2, obj.second)
        self.assertEqual(fake_attr2, obj.attr2)
        self.assertIsNone(obj.status)
        self.assertIsNone(obj.location)

    def test_get_by_id(self):
        resp = mock.Mock()
        resp.json = mock.Mock(return_value=fake_body)
        self.session.get = mock.Mock(return_value=resp)

        obj = FakeResource.get_by_id(self.session, fake_id,
                                     path_args=fake_arguments)

        # Check that the proper URL is being built.
        self.assertCalledURL(self.session.get,
                             os.path.join(fake_base_path % fake_arguments,
                                          str(fake_id))[1:])

        self.assertEqual(fake_id, obj.id)
        self.assertEqual(fake_name, obj['name'])
        self.assertEqual(fake_attr1, obj['attr1'])
        self.assertEqual(fake_attr2, obj['attr2'])

        self.assertEqual(fake_name, obj.name)
        self.assertEqual(fake_attr1, obj.first)
        self.assertEqual(fake_attr2, obj.second)

    def test_get_by_id_with_headers(self):
        header1 = "fake-value1"
        header2 = "fake-value2"
        headers = {"header1": header1,
                   "header2": header2}

        resp = mock.Mock(headers=headers)
        resp.json = mock.Mock(return_value=fake_body)
        self.session.get = mock.Mock(return_value=resp)

        class FakeResource2(FakeResource):
            header1 = resource.header("header1")
            header2 = resource.header("header2")

        obj = FakeResource2.get_by_id(self.session, fake_id,
                                      path_args=fake_arguments,
                                      include_headers=True)

        self.assertCalledURL(self.session.get,
                             os.path.join(fake_base_path % fake_arguments,
                                          str(fake_id))[1:])

        self.assertEqual(fake_id, obj.id)
        self.assertEqual(fake_name, obj['name'])
        self.assertEqual(fake_attr1, obj['attr1'])
        self.assertEqual(fake_attr2, obj['attr2'])
        self.assertEqual(header1, obj['headers']['header1'])
        self.assertEqual(header2, obj['headers']['header2'])

        self.assertEqual(fake_name, obj.name)
        self.assertEqual(fake_attr1, obj.first)
        self.assertEqual(fake_attr2, obj.second)
        self.assertEqual(header1, obj.header1)
        self.assertEqual(header2, obj.header2)

    def test_head_by_id(self):
        class FakeResource2(FakeResource):
            header1 = resource.header("header1")
            header2 = resource.header("header2")

        resp = mock.Mock(headers={"header1": "one", "header2": "two"})
        self.session.head = mock.Mock(return_value=resp)

        obj = FakeResource2.head_by_id(self.session, fake_id,
                                       path_args=fake_arguments)

        self.assertCalledURL(self.session.head,
                             os.path.join(fake_base_path % fake_arguments,
                                          str(fake_id))[1:])

        self.assertEqual('one', obj['headers']['header1'])
        self.assertEqual('two', obj['headers']['header2'])

        self.assertEqual('one', obj.header1)
        self.assertEqual('two', obj.header2)

    def test_patch_update(self):
        class FakeResourcePatch(FakeResource):
            patch_update = True

        resp = mock.Mock()
        resp.json = mock.Mock(return_value=fake_body)
        resp.headers = {'location': 'foo'}
        self.session.patch = mock.Mock(return_value=resp)

        # Create resource with subset of attributes in order to
        # verify update refreshes all attributes from response.
        obj = FakeResourcePatch.new(id=fake_id, parent_name=fake_parent,
                                    name=fake_name, attr1=fake_attr1)
        self.assertTrue(obj.is_dirty)

        self.assertEqual(obj, obj.update(self.session))
        self.assertFalse(obj.is_dirty)

        self.assertCalledURL(self.session.patch,
                             os.path.join(fake_base_path % fake_arguments,
                                          str(fake_id))[1:])

        last_req = self.session.patch.call_args[1]["json"][
            FakeResource.resource_key]

        self.assertEqual(3, len(last_req))
        self.assertEqual(fake_parent, last_req['parent_name'])
        self.assertEqual(fake_name, last_req['name'])
        self.assertEqual(fake_attr1, last_req['attr1'])

        self.assertTrue(obj['enabled'])
        self.assertEqual(fake_name, obj['name'])
        self.assertEqual(fake_parent, obj['parent_name'])
        self.assertEqual(fake_attr1, obj['attr1'])
        self.assertEqual(fake_attr2, obj['attr2'])
        self.assertIsNone(obj['status'])

        self.assertTrue(obj.enabled)
        self.assertEqual(fake_id, obj.id)
        self.assertEqual(fake_name, obj.name)
        self.assertEqual(fake_parent, obj.parent_name)
        self.assertEqual(fake_parent, obj.parent)
        self.assertEqual(fake_attr1, obj.first)
        self.assertEqual(fake_attr1, obj.attr1)
        self.assertEqual(fake_attr2, obj.second)
        self.assertEqual(fake_attr2, obj.attr2)
        self.assertIsNone(obj.status)
        self.assertEqual('foo', obj.location)

    def test_put_update(self):
        class FakeResourcePut(FakeResource):
            # This is False by default, but explicit for this test.
            patch_update = False

        resp = mock.Mock()
        resp.json = mock.Mock(return_value=fake_body)
        resp.headers = {'location': 'foo'}
        self.session.put = mock.Mock(return_value=resp)

        # Create resource with subset of attributes in order to
        # verify update refreshes all attributes from response.
        obj = FakeResourcePut.new(id=fake_id, parent_name=fake_parent,
                                  name=fake_name, attr1=fake_attr1)
        self.assertTrue(obj.is_dirty)

        self.assertEqual(obj, obj.update(self.session))
        self.assertFalse(obj.is_dirty)

        self.assertCalledURL(self.session.put,
                             os.path.join(fake_base_path % fake_arguments,
                                          str(fake_id))[1:])

        last_req = self.session.put.call_args[1]["json"][
            FakeResource.resource_key]

        self.assertEqual(3, len(last_req))
        self.assertEqual(fake_parent, last_req['parent_name'])
        self.assertEqual(fake_name, last_req['name'])
        self.assertEqual(fake_attr1, last_req['attr1'])

        self.assertTrue(obj['enabled'])
        self.assertEqual(fake_name, obj['name'])
        self.assertEqual(fake_parent, obj['parent_name'])
        self.assertEqual(fake_attr1, obj['attr1'])
        self.assertEqual(fake_attr2, obj['attr2'])
        self.assertIsNone(obj['status'])

        self.assertTrue(obj.enabled)
        self.assertEqual(fake_id, obj.id)
        self.assertEqual(fake_name, obj.name)
        self.assertEqual(fake_parent, obj.parent_name)
        self.assertEqual(fake_parent, obj.parent)
        self.assertEqual(fake_attr1, obj.first)
        self.assertEqual(fake_attr1, obj.attr1)
        self.assertEqual(fake_attr2, obj.second)
        self.assertEqual(fake_attr2, obj.attr2)
        self.assertIsNone(obj.status)
        self.assertEqual('foo', obj.location)

    def test_update_early_exit(self):
        obj = FakeResource()
        obj._dirty = []  # Bail out early if there's nothing to update.

        self.assertIsNone(obj.update("session"))

    def test_update_no_id_attribute(self):
        obj = FakeResource.existing(id=1, attr="value1",
                                    parent_name=fake_parent)
        obj.first = "value2"  # Make it dirty
        obj.update_by_id = mock.Mock(return_value=dict())
        # If no id_attribute is returned in the update response, make sure
        # we handle the resulting KeyError.
        self.assertEqual(obj, obj.update("session"))

    def test_delete(self):
        obj = FakeResource({"id": fake_id, "parent_name": fake_parent})
        obj.delete(self.session)

        self.assertCalledURL(self.session.delete,
                             os.path.join(fake_base_path % fake_arguments,
                                          str(fake_id))[1:])

    def _test_list(self, resource_class):
        results = [fake_data.copy(), fake_data.copy(), fake_data.copy()]
        for i in range(len(results)):
            results[i]['id'] = fake_id + i
        if resource_class.resources_key is not None:
            body = {resource_class.resources_key:
                    self._get_expected_results()}
            sentinel = {resource_class.resources_key: []}
        else:
            body = self._get_expected_results()
            sentinel = []
        resp1 = mock.Mock()
        resp1.json = mock.Mock(return_value=body)
        resp2 = mock.Mock()
        resp2.json = mock.Mock(return_value=sentinel)
        self.session.get.side_effect = [resp1, resp2]

        objs = list(resource_class.list(self.session, path_args=fake_arguments,
                                        paginated=True))

        params = {'limit': 3, 'marker': results[-1]['id']}
        self.assertEqual(params, self.session.get.call_args[1]['params'])
        self.assertEqual(3, len(objs))
        for obj in objs:
            self.assertIn(obj.id, range(fake_id, fake_id + 3))
            self.assertEqual(fake_name, obj['name'])
            self.assertEqual(fake_name, obj.name)
            self.assertIsInstance(obj, FakeResource)

    def _get_expected_results(self):
        results = [fake_data.copy(), fake_data.copy(), fake_data.copy()]
        for i in range(len(results)):
            results[i]['id'] = fake_id + i
        return results

    def test_list_keyed_resource(self):
        self._test_list(FakeResource)

    def test_list_non_keyed_resource(self):
        self._test_list(FakeResourceNoKeys)

    def _test_list_call_count(self, paginated):
        # Test that we've only made one call to receive all data
        results = [fake_data.copy(), fake_data.copy(), fake_data.copy()]
        resp = mock.Mock()
        resp.json = mock.Mock(return_value={fake_resources: results})
        attrs = {"get.return_value": resp}
        session = mock.Mock(**attrs)

        list(FakeResource.list(session, params={'limit': len(results) + 1},
                               path_args=fake_arguments,
                               paginated=paginated))

        # Ensure we only made one call to complete this.
        self.assertEqual(1, session.get.call_count)

    def test_list_bail_out(self):
        # When we get less data than limit, make sure we made one call
        self._test_list_call_count(True)

    def test_list_nonpaginated(self):
        # When we call with paginated=False, make sure we made one call
        self._test_list_call_count(False)

    def test_determine_limit(self):
        full_page = [fake_data.copy(), fake_data.copy(), fake_data.copy()]
        last_page = [fake_data.copy()]

        session = mock.Mock()
        session.get = mock.Mock()
        full_response = mock.Mock()
        response_body = {FakeResource.resources_key: full_page}
        full_response.json = mock.Mock(return_value=response_body)
        last_response = mock.Mock()
        response_body = {FakeResource.resources_key: last_page}
        last_response.json = mock.Mock(return_value=response_body)
        pages = [full_response, full_response, last_response]
        session.get.side_effect = pages

        # Don't specify a limit. Resource.list will determine the limit
        # is 3 based on the first `full_page`.
        results = list(FakeResource.list(session, path_args=fake_arguments,
                       paginated=True))

        self.assertEqual(session.get.call_count, len(pages))
        self.assertEqual(len(full_page + full_page + last_page), len(results))

    def test_empty_list(self):
        page = []

        session = mock.Mock()
        session.get = mock.Mock()
        full_response = mock.Mock()
        response_body = {FakeResource.resources_key: page}
        full_response.json = mock.Mock(return_value=response_body)
        pages = [full_response]
        session.get.side_effect = pages

        results = list(FakeResource.list(session, path_args=fake_arguments,
                       paginated=True))

        self.assertEqual(session.get.call_count, len(pages))
        self.assertEqual(len(page), len(results))

    def test_attrs_name(self):
        obj = FakeResource()

        self.assertIsNone(obj.name)
        del obj.name

    def test_to_dict(self):
        kwargs = {
            'enabled': True,
            'name': 'FOO',
            'parent': 'dad',
            'attr1': 'BAR',
            'attr2': ['ZOO', 'BAZ'],
            'status': 'Active',
            'headers': {
                'key': 'value'
            }
        }
        obj = FakeResource(kwargs)
        res = obj.to_dict()
        self.assertIsInstance(res, dict)
        self.assertTrue(res['enabled'])
        self.assertEqual('FOO', res['name'])
        self.assertEqual('dad', res['parent'])
        self.assertEqual('BAR', res['attr1'])
        self.assertEqual(['ZOO', 'BAZ'], res['attr2'])
        self.assertEqual('Active', res['status'])
        self.assertNotIn('headers', res)

    def test_composite_attr_happy(self):
        obj = FakeResource.existing(**{'attr3': '3'})

        try:
            self.assertEqual('3', obj.third)
        except AttributeError:
            self.fail("third was not found as expected")

    def test_composite_attr_fallback(self):
        obj = FakeResource.existing(**{'attr_three': '3'})

        try:
            self.assertEqual('3', obj.third)
        except AttributeError:
            self.fail("third was not found in fallback as expected")

    def test_id_del(self):

        class Test(resource.Resource):
            id_attribute = "my_id"

        attrs = {"my_id": 100}
        t = Test(attrs=attrs)

        self.assertEqual(attrs["my_id"], t.id)
        del t.id
        self.assertTrue(Test.id_attribute not in t._attrs)

    def test_from_name_with_name(self):
        name = "Ernie Banks"

        obj = FakeResource.from_name(name)
        self.assertEqual(name, obj.name)

    def test_from_id_with_name(self):
        name = "Sandy Koufax"

        obj = FakeResource.from_id(name)
        self.assertEqual(name, obj.id)

    def test_from_id_with_object(self):
        name = "Mickey Mantle"
        obj = FakeResource.new(name=name)

        new_obj = FakeResource.from_id(obj)
        self.assertIs(new_obj, obj)
        self.assertEqual(obj.name, new_obj.name)

    def test_from_id_with_bad_value(self):
        def should_raise():
            FakeResource.from_id(3.14)

        self.assertThat(should_raise, matchers.raises(ValueError))

    def test_dirty_list(self):
        class Test(resource.Resource):
            attr = resource.prop("attr")

        # Check if dirty after setting by prop
        sot1 = Test()
        self.assertFalse(sot1.is_dirty)
        sot1.attr = 1
        self.assertTrue(sot1.is_dirty)

        # Check if dirty after setting by mapping
        sot2 = Test()
        sot2["attr"] = 1
        self.assertTrue(sot1.is_dirty)

        # Check if dirty after creation
        sot3 = Test({"attr": 1})
        self.assertTrue(sot3.is_dirty)

    def test_update_attrs(self):
        class Test(resource.Resource):
            moe = resource.prop("the-attr")
            larry = resource.prop("the-attr2")
            curly = resource.prop("the-attr3", type=int)
            shemp = resource.prop("the-attr4")

        value1 = "one"
        value2 = "two"
        value3 = "3"
        value4 = "fore"
        value5 = "fiver"

        sot = Test({"the-attr": value1})

        sot.update_attrs({"the-attr2": value2, "notprop": value4})
        self.assertTrue(sot.is_dirty)
        self.assertEqual(value1, sot.moe)
        self.assertEqual(value1, sot["the-attr"])
        self.assertEqual(value2, sot.larry)
        self.assertEqual(value4, sot.notprop)

        sot._reset_dirty()

        sot.update_attrs(curly=value3)
        self.assertTrue(sot.is_dirty)
        self.assertEqual(int, type(sot.curly))
        self.assertEqual(int(value3), sot.curly)

        sot._reset_dirty()

        sot.update_attrs(**{"the-attr4": value5})
        self.assertTrue(sot.is_dirty)
        self.assertEqual(value5, sot.shemp)

    def test_get_id(self):
        class Test(resource.Resource):
            pass

        ID = "an id"
        res = Test({"id": ID})

        self.assertEqual(ID, resource.Resource.get_id(ID))
        self.assertEqual(ID, resource.Resource.get_id(res))

    def test_convert_ids(self):
        class TestResourceFoo(resource.Resource):
            pass

        class TestResourceBar(resource.Resource):
            pass

        resfoo = TestResourceFoo({'id': 'FAKEFOO'})
        resbar = TestResourceBar({'id': 'FAKEBAR'})

        self.assertIsNone(resource.Resource.convert_ids(None))
        attrs = {
            'key1': 'value1'
        }
        self.assertEqual(attrs, resource.Resource.convert_ids(attrs))

        attrs = {
            'foo': resfoo,
            'bar': resbar,
            'other': 'whatever',
        }
        res = resource.Resource.convert_ids(attrs)
        self.assertEqual('FAKEFOO', res['foo'])
        self.assertEqual('FAKEBAR', res['bar'])
        self.assertEqual('whatever', res['other'])

    def test_repr(self):
        fr = FakeResource()
        fr._loaded = False
        fr.first = "hey"
        fr.second = "hi"
        fr.third = "nah"
        the_repr = repr(fr)
        the_repr = the_repr.replace('openstack.tests.unit.test_resource.', '')
        result = eval(the_repr)
        self.assertEqual(fr._loaded, result._loaded)
        self.assertEqual(fr.first, result.first)
        self.assertEqual(fr.second, result.second)
        self.assertEqual(fr.third, result.third)

    def test_id_attribute(self):
        faker = FakeResource(fake_data)
        self.assertEqual(fake_id, faker.id)
        faker.id_attribute = 'name'
        self.assertEqual(fake_name, faker.id)
        faker.id_attribute = 'attr1'
        self.assertEqual(fake_attr1, faker.id)
        faker.id_attribute = 'attr2'
        self.assertEqual(fake_attr2, faker.id)
        faker.id_attribute = 'id'
        self.assertEqual(fake_id, faker.id)

    def test_name_attribute(self):
        class Person_ES(resource.Resource):
            name_attribute = "nombre"
            nombre = resource.prop('nombre')

        name = "Brian"
        args = {'nombre': name}

        person = Person_ES(args)
        self.assertEqual(name, person.nombre)
        self.assertEqual(name, person.name)

        new_name = "Julien"
        person.name = new_name
        self.assertEqual(new_name, person.nombre)
        self.assertEqual(new_name, person.name)

    def test_boolstr_prop(self):
        faker = FakeResource(fake_data)
        self.assertTrue(faker.enabled)
        self.assertTrue(faker['enabled'])

        faker._attrs['enabled'] = False
        self.assertFalse(faker.enabled)
        self.assertFalse(faker['enabled'])

        # should fail fast
        def set_invalid():
            faker.enabled = 'INVALID'
        self.assertRaises(ValueError, set_invalid)


class ResourceMapping(base.TestCase):

    def test__getitem(self):
        value = 10

        class Test(resource.Resource):
            attr = resource.prop("attr")

        t = Test(attrs={"attr": value})

        self.assertEqual(value, t["attr"])

    def test__setitem__existing_item_changed(self):

        class Test(resource.Resource):
            pass

        t = Test()
        key = "attr"
        value = 1
        t[key] = value

        self.assertEqual(value, t._attrs[key])
        self.assertTrue(key in t._dirty)

    def test__setitem__existing_item_unchanged(self):

        class Test(resource.Resource):
            pass

        key = "attr"
        value = 1
        t = Test(attrs={key: value})
        t._reset_dirty()  # Clear dirty list so this checks as unchanged.
        t[key] = value

        self.assertEqual(value, t._attrs[key])
        self.assertTrue(key not in t._dirty)

    def test__setitem__new_item(self):

        class Test(resource.Resource):
            pass

        t = Test()
        key = "attr"
        value = 1
        t[key] = value

        self.assertEqual(value, t._attrs[key])
        self.assertTrue(key in t._dirty)

    def test__delitem__(self):

        class Test(resource.Resource):
            pass

        key = "attr"
        value = 1
        t = Test(attrs={key: value})

        del t[key]

        self.assertTrue(key not in t._attrs)
        self.assertTrue(key in t._dirty)

    def test__len__(self):

        class Test(resource.Resource):
            pass

        attrs = {"a": 1, "b": 2, "c": 3}
        t = Test(attrs=attrs)

        self.assertEqual(len(attrs.keys()), len(t))

    def test__iter__(self):

        class Test(resource.Resource):
            pass

        attrs = {"a": 1, "b": 2, "c": 3}
        t = Test(attrs=attrs)

        for attr in t:
            self.assertEqual(attrs[attr], t[attr])

    def _test_resource_serialization(self, session_method, resource_method):
        attr_type = resource.Resource

        class Test(resource.Resource):
            allow_create = True
            attr = resource.prop("attr", type=attr_type)

        the_id = 123
        sot = Test()
        sot.attr = resource.Resource({"id": the_id})
        self.assertEqual(attr_type, type(sot.attr))

        def fake_call(*args, **kwargs):
            attrs = kwargs["json"]
            try:
                json.dumps(attrs)
            except TypeError as e:
                self.fail("Unable to serialize _attrs: %s" % e)
            resp = mock.Mock()
            resp.json = mock.Mock(return_value=attrs)
            return resp

        session = mock.Mock()
        setattr(session, session_method, mock.Mock(side_effect=fake_call))

        if resource_method == "create_by_id":
            session.create_by_id(session, sot._attrs)
        elif resource_method == "update_by_id":
            session.update_by_id(session, None, sot._attrs)

    def test_create_serializes_resource_types(self):
        self._test_resource_serialization("post", "create_by_id")

    def test_update_serializes_resource_types(self):
        self._test_resource_serialization("patch", "update_by_id")


class FakeResponse(object):
    def __init__(self, response):
        self.body = response

    def json(self):
        return self.body


class TestFind(base.TestCase):
    NAME = 'matrix'
    ID = 'Fishburne'
    PROP = 'attribute2'

    def setUp(self):
        super(TestFind, self).setUp()
        self.mock_session = mock.Mock()
        self.mock_get = mock.Mock()
        self.mock_session.get = self.mock_get
        self.matrix = {'id': self.ID, 'name': self.NAME, 'prop': self.PROP}

    def test_name(self):
        self.mock_get.side_effect = [
            exceptions.NotFoundException(),
            FakeResponse({FakeResource.resources_key: [self.matrix]})
        ]

        result = FakeResource.find(self.mock_session, self.NAME,
                                   path_args=fake_arguments)

        self.assertEqual(self.NAME, result.name)
        self.assertEqual(self.PROP, result.prop)

    def test_id(self):
        self.mock_get.side_effect = [
            FakeResponse({FakeResource.resource_key: self.matrix})
        ]

        result = FakeResource.find(self.mock_session, self.ID,
                                   path_args=fake_arguments)

        self.assertEqual(self.ID, result.id)
        self.assertEqual(self.PROP, result.prop)

        path = "fakes/" + fake_parent + "/data/" + self.ID
        self.mock_get.assert_any_call(path, endpoint_filter=None)

    def test_id_no_retrieve(self):
        self.mock_get.side_effect = [
            FakeResponse({FakeResource.resources_key: [self.matrix]})
        ]

        class NoRetrieveResource(FakeResource):
            allow_retrieve = False

        result = NoRetrieveResource.find(self.mock_session, self.ID,
                                         path_args=fake_arguments)

        self.assertEqual(self.ID, result.id)
        self.assertEqual(self.PROP, result.prop)

    def test_dups(self):
        dupe = self.matrix.copy()
        dupe['id'] = 'different'
        self.mock_get.side_effect = [
            # Raise a 404 first so we get out of the ID search and into name.
            exceptions.NotFoundException(),
            FakeResponse({FakeResource.resources_key: [self.matrix, dupe]})
        ]

        self.assertRaises(exceptions.DuplicateResource, FakeResource.find,
                          self.mock_session, self.NAME)

    def test_id_attribute_find(self):
        floater = {'ip_address': "127.0.0.1", 'prop': self.PROP}
        self.mock_get.side_effect = [
            FakeResponse({FakeResource.resource_key: floater})
        ]

        FakeResource.id_attribute = 'ip_address'
        FakeResource.id_attribute = 'ip_address'
        result = FakeResource.find(self.mock_session, "127.0.0.1",
                                   path_args=fake_arguments)
        self.assertEqual("127.0.0.1", result.id)
        self.assertEqual(self.PROP, result.prop)

        FakeResource.id_attribute = 'id'

        p = {'ip_address': "127.0.0.1"}
        path = fake_path + "?limit=2"
        self.mock_get.called_once_with(path, params=p, endpoint_filter=None)

    def test_nada(self):
        self.mock_get.side_effect = [
            exceptions.NotFoundException(),
            FakeResponse({FakeResource.resources_key: []})
        ]

        self.assertIsNone(FakeResource.find(self.mock_session, self.NAME))

    def test_no_name(self):
        self.mock_get.side_effect = [
            exceptions.NotFoundException(),
            FakeResponse({FakeResource.resources_key: [self.matrix]})
        ]
        FakeResource.name_attribute = None

        self.assertIsNone(FakeResource.find(self.mock_session, self.NAME))

    def test_nada_not_ignored(self):
        self.mock_get.side_effect = [
            exceptions.NotFoundException(),
            FakeResponse({FakeResource.resources_key: []})
        ]

        self.assertRaises(exceptions.ResourceNotFound, FakeResource.find,
                          self.mock_session, self.NAME, ignore_missing=False)


class TestWaitForStatus(base.TestCase):

    def __init__(self, *args, **kwargs):
        super(TestWaitForStatus, self).__init__(*args, **kwargs)
        self.build = FakeResponse(self.body_with_status(fake_body, 'BUILD'))
        self.active = FakeResponse(self.body_with_status(fake_body, 'ACTIVE'))
        self.error = FakeResponse(self.body_with_status(fake_body, 'ERROR'))

    def setUp(self):
        super(TestWaitForStatus, self).setUp()
        self.sess = mock.Mock()

    def body_with_status(self, body, status):
        body_copy = copy.deepcopy(body)
        body_copy[fake_resource]['status'] = status
        return body_copy

    def test_wait_for_status_nothing(self):
        self.sess.get = mock.Mock()
        sot = FakeResource.new(**fake_data)
        sot.status = 'ACTIVE'

        self.assertEqual(sot, resource.wait_for_status(
            self.sess, sot, 'ACTIVE', [], 1, 2))
        self.assertEqual([], self.sess.get.call_args_list)

    def test_wait_for_status(self):
        self.sess.get = mock.Mock()
        self.sess.get.side_effect = [self.build, self.active]
        sot = FakeResource.new(**fake_data)

        self.assertEqual(sot, resource.wait_for_status(
            self.sess, sot, 'ACTIVE', [], 1, 2))

    def test_wait_for_status_timeout(self):
        self.sess.get = mock.Mock()
        self.sess.get.side_effect = [self.build, self.build]
        sot = FakeResource.new(**fake_data)

        self.assertRaises(exceptions.ResourceTimeout, resource.wait_for_status,
                          self.sess, sot, 'ACTIVE', ['ERROR'], 1, 2)

    def test_wait_for_status_failures(self):
        self.sess.get = mock.Mock()
        self.sess.get.side_effect = [self.build, self.error]
        sot = FakeResource.new(**fake_data)

        self.assertRaises(exceptions.ResourceFailure, resource.wait_for_status,
                          self.sess, sot, 'ACTIVE', ['ERROR'], 1, 2)

    def test_wait_for_status_no_status(self):
        class FakeResourceNoStatus(resource.Resource):
            allow_retrieve = True

        sot = FakeResourceNoStatus.new(id=123)

        self.assertRaises(AttributeError, resource.wait_for_status,
                          self.sess, sot, 'ACTIVE', ['ERROR'], 1, 2)


class TestWaitForDelete(base.TestCase):

    def test_wait_for_delete(self):
        sess = mock.Mock()
        sot = FakeResource.new(**fake_data)
        sot.get = mock.Mock()
        sot.get.side_effect = [
            sot,
            exceptions.NotFoundException()]

        self.assertEqual(sot, resource.wait_for_delete(sess, sot, 1, 2))

    def test_wait_for_delete_fail(self):
        sess = mock.Mock()
        sot = FakeResource.new(**fake_data)
        sot.get = mock.Mock(return_value=sot)

        self.assertRaises(exceptions.ResourceTimeout, resource.wait_for_delete,
                          sess, sot, 1, 2)