summaryrefslogtreecommitdiff
path: root/heat/tests/test_stack.py
blob: ec9534a9512c211fd2efdba20fd9c32d524da441 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
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
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
#
#    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 collections
import copy
import json
import time

import mock
import mox
from oslo_config import cfg
import six

from heat.common import context
from heat.common import exception
from heat.common import template_format
from heat.db import api as db_api
from heat.engine.clients.os import keystone
from heat.engine.clients.os import nova
from heat.engine import environment
from heat.engine import resource
from heat.engine import scheduler
from heat.engine import stack
from heat.engine import template
from heat.objects import stack as stack_object
from heat.objects import user_creds as ucreds_object
from heat.tests import common
from heat.tests import fakes
from heat.tests import generic_resource as generic_rsrc
from heat.tests import utils

empty_template = template_format.parse('''{
  "HeatTemplateFormatVersion" : "2012-12-12",
}''')


class StackTest(common.HeatTestCase):
    def setUp(self):
        super(StackTest, self).setUp()

        self.tmpl = template.Template(copy.deepcopy(empty_template))
        self.ctx = utils.dummy_context()

        resource._register_class('GenericResourceType',
                                 generic_rsrc.GenericResource)
        resource._register_class('StackResourceType',
                                 generic_rsrc.StackResourceType)
        resource._register_class('ResourceWithPropsType',
                                 generic_rsrc.ResourceWithProps)
        resource._register_class('ResWithComplexPropsAndAttrs',
                                 generic_rsrc.ResWithComplexPropsAndAttrs)

    def test_stack_reads_tenant(self):
        self.stack = stack.Stack(self.ctx, 'test_stack', self.tmpl,
                                 tenant_id='bar')
        self.assertEqual('bar', self.stack.tenant_id)

    def test_stack_reads_tenant_from_context_if_empty(self):
        self.ctx.tenant_id = 'foo'
        self.stack = stack.Stack(self.ctx, 'test_stack', self.tmpl,
                                 tenant_id=None)
        self.assertEqual('foo', self.stack.tenant_id)

    def test_stack_reads_username(self):
        self.stack = stack.Stack(self.ctx, 'test_stack', self.tmpl,
                                 username='bar')
        self.assertEqual('bar', self.stack.username)

    def test_stack_reads_username_from_context_if_empty(self):
        self.ctx.username = 'foo'
        self.stack = stack.Stack(self.ctx, 'test_stack', self.tmpl,
                                 username=None)
        self.assertEqual('foo', self.stack.username)

    def test_stack_string_repr(self):
        self.stack = stack.Stack(self.ctx, 'test_stack', self.tmpl)
        expected = 'Stack "%s" [%s]' % (self.stack.name, self.stack.id)
        observed = str(self.stack)
        self.assertEqual(expected, observed)

    def test_state_defaults(self):
        self.stack = stack.Stack(self.ctx, 'test_stack', self.tmpl)
        self.assertEqual(('CREATE', 'IN_PROGRESS'), self.stack.state)
        self.assertEqual('', self.stack.status_reason)

    def test_timeout_secs_default(self):
        cfg.CONF.set_override('stack_action_timeout', 1000)
        self.stack = stack.Stack(self.ctx, 'test_stack', self.tmpl)
        self.assertIsNone(self.stack.timeout_mins)
        self.assertEqual(1000, self.stack.timeout_secs())

    def test_timeout_secs(self):
        self.stack = stack.Stack(self.ctx, 'test_stack', self.tmpl,
                                 timeout_mins=10)
        self.assertEqual(600, self.stack.timeout_secs())

    def test_no_auth_token(self):
        ctx = utils.dummy_context()
        ctx.auth_token = None
        self.stub_auth()

        self.m.ReplayAll()
        self.stack = stack.Stack(ctx, 'test_stack', self.tmpl)
        self.assertEqual('abcd1234',
                         self.stack.clients.client('keystone').auth_token)

        self.m.VerifyAll()

    def test_state(self):
        self.stack = stack.Stack(self.ctx, 'test_stack', self.tmpl,
                                 action=stack.Stack.CREATE,
                                 status=stack.Stack.IN_PROGRESS)
        self.assertEqual((stack.Stack.CREATE, stack.Stack.IN_PROGRESS),
                         self.stack.state)
        self.stack.state_set(stack.Stack.CREATE, stack.Stack.COMPLETE, 'test')
        self.assertEqual((stack.Stack.CREATE, stack.Stack.COMPLETE),
                         self.stack.state)
        self.stack.state_set(stack.Stack.DELETE, stack.Stack.COMPLETE, 'test')
        self.assertEqual((stack.Stack.DELETE, stack.Stack.COMPLETE),
                         self.stack.state)

    def test_state_deleted(self):
        self.stack = stack.Stack(self.ctx, 'test_stack', self.tmpl,
                                 action=stack.Stack.CREATE,
                                 status=stack.Stack.IN_PROGRESS)
        self.stack.id = '1234'

        # Simulate a deleted stack
        self.m.StubOutWithMock(stack_object.Stack, 'get_by_id')
        stack_object.Stack.get_by_id(self.stack.context,
                                     self.stack.id).AndReturn(None)

        self.m.ReplayAll()

        self.assertIsNone(self.stack.state_set(stack.Stack.CREATE,
                                               stack.Stack.COMPLETE,
                                               'test'))
        self.m.VerifyAll()

    def test_state_bad(self):
        self.stack = stack.Stack(self.ctx, 'test_stack', self.tmpl,
                                 action=stack.Stack.CREATE,
                                 status=stack.Stack.IN_PROGRESS)
        self.assertEqual((stack.Stack.CREATE, stack.Stack.IN_PROGRESS),
                         self.stack.state)
        self.assertRaises(ValueError, self.stack.state_set,
                          'baad', stack.Stack.COMPLETE, 'test')
        self.assertRaises(ValueError, self.stack.state_set,
                          stack.Stack.CREATE, 'oops', 'test')

    def test_status_reason(self):
        self.stack = stack.Stack(self.ctx, 'test_stack', self.tmpl,
                                 status_reason='quux')
        self.assertEqual('quux', self.stack.status_reason)
        self.stack.state_set(stack.Stack.CREATE, stack.Stack.IN_PROGRESS,
                             'wibble')
        self.assertEqual('wibble', self.stack.status_reason)

    def test_load_nonexistant_id(self):
        self.assertRaises(exception.NotFound, stack.Stack.load,
                          None, -1)

    def test_total_resources_empty(self):
        self.stack = stack.Stack(self.ctx, 'test_stack', self.tmpl,
                                 status_reason='flimflam')
        self.stack.store()
        self.assertEqual(0, self.stack.total_resources(self.stack.id))
        self.assertEqual(0, self.stack.total_resources())

    def test_total_resources_not_found(self):
        self.stack = stack.Stack(self.ctx, 'test_stack', self.tmpl,
                                 status_reason='flimflam')

        self.assertEqual(0, self.stack.total_resources('1234'))

    @mock.patch.object(db_api, 'stack_count_total_resources')
    def test_total_resources_generic(self, sctr):
        tpl = {'HeatTemplateFormatVersion': '2012-12-12',
               'Resources':
               {'A': {'Type': 'GenericResourceType'}}}
        self.stack = stack.Stack(self.ctx, 'test_stack',
                                 template.Template(tpl),
                                 status_reason='blarg')
        self.stack.store()
        sctr.return_value = 1
        self.assertEqual(1, self.stack.total_resources(self.stack.id))
        self.assertEqual(1, self.stack.total_resources())

    def test_iter_resources(self):
        tpl = {'HeatTemplateFormatVersion': '2012-12-12',
               'Resources':
               {'A': {'Type': 'StackResourceType'},
                'B': {'Type': 'GenericResourceType'}}}
        self.stack = stack.Stack(self.ctx, 'test_stack',
                                 template.Template(tpl),
                                 status_reason='blarg')

        def get_more(nested_depth=0):
            yield 'X'
            yield 'Y'
            yield 'Z'

        self.stack['A'].nested = mock.MagicMock()
        self.stack['A'].nested.return_value.iter_resources = mock.MagicMock(
            side_effect=get_more)

        resource_generator = self.stack.iter_resources()
        self.assertIsNot(resource_generator, list)

        first_level_resources = list(resource_generator)
        self.assertEqual(2, len(first_level_resources))
        all_resources = list(self.stack.iter_resources(1))
        self.assertEqual(5, len(all_resources))

    def test_load_parent_resource(self):
        self.stack = stack.Stack(self.ctx, 'load_parent_resource', self.tmpl,
                                 parent_resource='parent')
        self.stack.store()
        stk = stack_object.Stack.get_by_id(self.ctx, self.stack.id)

        t = template.Template.load(self.ctx, stk.raw_template_id)
        self.m.StubOutWithMock(template.Template, 'load')
        template.Template.load(
            self.ctx, stk.raw_template_id, stk.raw_template
        ).AndReturn(t)

        self.m.StubOutWithMock(stack.Stack, '__init__')
        stack.Stack.__init__(self.ctx, stk.name, t, stack_id=stk.id,
                             action=stk.action, status=stk.status,
                             status_reason=stk.status_reason,
                             timeout_mins=stk.timeout, resolve_data=True,
                             disable_rollback=stk.disable_rollback,
                             parent_resource='parent', owner_id=None,
                             stack_user_project_id=None,
                             created_time=mox.IgnoreArg(),
                             updated_time=None,
                             user_creds_id=stk.user_creds_id,
                             tenant_id='test_tenant_id',
                             use_stored_context=False,
                             username=mox.IgnoreArg(),
                             convergence=False,
                             current_traversal=None)

        self.m.ReplayAll()
        stack.Stack.load(self.ctx, stack_id=self.stack.id)

        self.m.VerifyAll()

    def test_identifier(self):
        self.stack = stack.Stack(self.ctx, 'identifier_test', self.tmpl)
        self.stack.store()
        identifier = self.stack.identifier()
        self.assertEqual(self.stack.tenant_id, identifier.tenant)
        self.assertEqual('identifier_test', identifier.stack_name)
        self.assertTrue(identifier.stack_id)
        self.assertFalse(identifier.path)

    def test_get_stack_abandon_data(self):
        tpl = {'HeatTemplateFormatVersion': '2012-12-12',
               'Parameters': {'param1': {'Type': 'String'}},
               'Resources':
               {'A': {'Type': 'GenericResourceType'},
                'B': {'Type': 'GenericResourceType'}}}
        resources = '''{"A": {"status": "COMPLETE", "name": "A",
        "resource_data": {}, "resource_id": null, "action": "INIT",
        "type": "GenericResourceType", "metadata": {}},
        "B": {"status": "COMPLETE", "name": "B", "resource_data": {},
        "resource_id": null, "action": "INIT", "type": "GenericResourceType",
        "metadata": {}}}'''
        env = environment.Environment({'parameters': {'param1': 'test'}})
        self.stack = stack.Stack(self.ctx, 'stack_details_test',
                                 template.Template(tpl, env=env),
                                 tenant_id='123',
                                 stack_user_project_id='234')
        self.stack.store()
        info = self.stack.prepare_abandon()
        self.assertEqual('CREATE', info['action'])
        self.assertIn('id', info)
        self.assertEqual('stack_details_test', info['name'])
        self.assertEqual(json.loads(resources), info['resources'])
        self.assertEqual('IN_PROGRESS', info['status'])
        self.assertEqual(tpl, info['template'])
        self.assertEqual('123', info['project_id'])
        self.assertEqual('234', info['stack_user_project_id'])
        self.assertEqual(env.params, info['environment']['parameters'])

    def test_set_param_id(self):
        self.stack = stack.Stack(self.ctx, 'param_arn_test', self.tmpl)
        exp_prefix = ('arn:openstack:heat::test_tenant_id'
                      ':stacks/param_arn_test/')
        self.assertEqual(self.stack.parameters['AWS::StackId'],
                         exp_prefix + 'None')
        self.stack.store()
        identifier = self.stack.identifier()
        self.assertEqual(exp_prefix + self.stack.id,
                         self.stack.parameters['AWS::StackId'])
        self.assertEqual(self.stack.parameters['AWS::StackId'],
                         identifier.arn())
        self.m.VerifyAll()

    def test_set_param_id_update(self):
        tmpl = {'HeatTemplateFormatVersion': '2012-12-12',
                'Resources': {
                    'AResource': {'Type': 'ResourceWithPropsType',
                                  'Metadata': {'Bar': {'Ref': 'AWS::StackId'}},
                                  'Properties': {'Foo': 'abc'}}}}

        self.stack = stack.Stack(self.ctx, 'update_stack_arn_test',
                                 template.Template(tmpl))
        self.stack.store()
        self.stack.create()
        self.assertEqual((stack.Stack.CREATE, stack.Stack.COMPLETE),
                         self.stack.state)

        stack_arn = self.stack.parameters['AWS::StackId']

        tmpl2 = {'HeatTemplateFormatVersion': '2012-12-12',
                 'Resources': {
                     'AResource': {'Type': 'ResourceWithPropsType',
                                   'Metadata': {'Bar':
                                                {'Ref': 'AWS::StackId'}},
                                   'Properties': {'Foo': 'xyz'}}}}

        updated_stack = stack.Stack(self.ctx, 'updated_stack',
                                    template.Template(tmpl2))

        self.stack.update(updated_stack)
        self.assertEqual((stack.Stack.UPDATE, stack.Stack.COMPLETE),
                         self.stack.state)
        self.assertEqual('xyz', self.stack['AResource'].properties['Foo'])

        self.assertEqual(
            stack_arn, self.stack['AResource'].metadata_get()['Bar'])

    def test_load_param_id(self):
        self.stack = stack.Stack(self.ctx, 'param_load_arn_test', self.tmpl)
        self.stack.store()
        identifier = self.stack.identifier()
        self.assertEqual(self.stack.parameters['AWS::StackId'],
                         identifier.arn())

        newstack = stack.Stack.load(self.ctx, stack_id=self.stack.id)
        self.assertEqual(identifier.arn(), newstack.parameters['AWS::StackId'])

    def test_load_reads_tenant_id(self):
        self.ctx.tenant_id = 'foobar'
        self.stack = stack.Stack(self.ctx, 'stack_name', self.tmpl)
        self.stack.store()
        stack_id = self.stack.id
        self.ctx.tenant_id = None
        self.stack = stack.Stack.load(self.ctx, stack_id=stack_id)
        self.assertEqual('foobar', self.stack.tenant_id)

    def test_load_reads_username_from_db(self):
        self.ctx.username = 'foobar'
        self.stack = stack.Stack(self.ctx, 'stack_name', self.tmpl)
        self.stack.store()
        stack_id = self.stack.id

        self.ctx.username = None
        stk = stack.Stack.load(self.ctx, stack_id=stack_id)
        self.assertEqual('foobar', stk.username)

        self.ctx.username = 'not foobar'
        stk = stack.Stack.load(self.ctx, stack_id=stack_id)
        self.assertEqual('foobar', stk.username)

    def test_load_all(self):
        stack1 = stack.Stack(self.ctx, 'stack1', self.tmpl)
        stack1.store()
        stack2 = stack.Stack(self.ctx, 'stack2', self.tmpl)
        stack2.store()

        stacks = list(stack.Stack.load_all(self.ctx))
        self.assertEqual(2, len(stacks))

        # Add another, nested, stack
        stack3 = stack.Stack(self.ctx, 'stack3', self.tmpl,
                             owner_id=stack2.id)
        stack3.store()

        # Should still be 2 without show_nested
        stacks = list(stack.Stack.load_all(self.ctx))
        self.assertEqual(2, len(stacks))

        stacks = list(stack.Stack.load_all(self.ctx, show_nested=True))
        self.assertEqual(3, len(stacks))

        # A backup stack should not be returned
        stack1._backup_stack()
        stacks = list(stack.Stack.load_all(self.ctx))
        self.assertEqual(2, len(stacks))

        stacks = list(stack.Stack.load_all(self.ctx, show_nested=True))
        self.assertEqual(3, len(stacks))

    def test_created_time(self):
        self.stack = stack.Stack(self.ctx, 'creation_time_test', self.tmpl)
        self.assertIsNone(self.stack.created_time)
        self.stack.store()
        self.assertIsNotNone(self.stack.created_time)

    def test_updated_time(self):
        self.stack = stack.Stack(self.ctx, 'updated_time_test',
                                 self.tmpl)
        self.assertIsNone(self.stack.updated_time)
        self.stack.store()
        self.stack.create()

        tmpl = {'HeatTemplateFormatVersion': '2012-12-12',
                'Resources': {'R1': {'Type': 'GenericResourceType'}}}
        newstack = stack.Stack(self.ctx, 'updated_time_test',
                               template.Template(tmpl))
        self.stack.update(newstack)
        self.assertIsNotNone(self.stack.updated_time)

    def test_access_policy_update(self):
        tmpl = {'HeatTemplateFormatVersion': '2012-12-12',
                'Resources': {
                    'R1': {'Type': 'GenericResourceType'},
                    'Policy': {
                        'Type': 'OS::Heat::AccessPolicy',
                        'Properties': {
                            'AllowedResources': ['R1']
                        }}}}

        self.stack = stack.Stack(self.ctx, 'update_stack_access_policy_test',
                                 template.Template(tmpl))
        self.stack.store()
        self.stack.create()
        self.assertEqual((stack.Stack.CREATE, stack.Stack.COMPLETE),
                         self.stack.state)

        tmpl2 = {'HeatTemplateFormatVersion': '2012-12-12',
                 'Resources': {
                     'R1': {'Type': 'GenericResourceType'},
                     'R2': {'Type': 'GenericResourceType'},
                     'Policy': {
                         'Type': 'OS::Heat::AccessPolicy',
                         'Properties': {
                             'AllowedResources': ['R1', 'R2'],
                         }}}}

        updated_stack = stack.Stack(self.ctx, 'updated_stack',
                                    template.Template(tmpl2))

        self.stack.update(updated_stack)
        self.assertEqual((stack.Stack.UPDATE, stack.Stack.COMPLETE),
                         self.stack.state)

    def test_abandon_nodelete_project(self):
        self.stack = stack.Stack(self.ctx, 'delete_trust', self.tmpl)
        stack_id = self.stack.store()

        self.stack.set_stack_user_project_id(project_id='aproject456')

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNotNone(db_s)

        self.stack.delete(abandon=True)

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNone(db_s)
        self.assertEqual((stack.Stack.DELETE, stack.Stack.COMPLETE),
                         self.stack.state)

    def test_suspend_resume(self):
        self.m.ReplayAll()
        tmpl = {'HeatTemplateFormatVersion': '2012-12-12',
                'Resources': {'AResource': {'Type': 'GenericResourceType'}}}
        self.stack = stack.Stack(self.ctx, 'suspend_test',
                                 template.Template(tmpl))
        self.stack.store()
        self.stack.create()
        self.assertEqual((self.stack.CREATE, self.stack.COMPLETE),
                         self.stack.state)
        self.assertIsNone(self.stack.updated_time)

        self.stack.suspend()

        self.assertEqual((self.stack.SUSPEND, self.stack.COMPLETE),
                         self.stack.state)
        stack_suspend_time = self.stack.updated_time
        self.assertIsNotNone(stack_suspend_time)

        self.stack.resume()

        self.assertEqual((self.stack.RESUME, self.stack.COMPLETE),
                         self.stack.state)
        self.assertNotEqual(stack_suspend_time, self.stack.updated_time)

        self.m.VerifyAll()

    def test_suspend_stack_suspended_ok(self):
        tmpl = {'HeatTemplateFormatVersion': '2012-12-12',
                'Resources': {'AResource': {'Type': 'GenericResourceType'}}}
        self.stack = stack.Stack(self.ctx, 'suspend_test',
                                 template.Template(tmpl))
        self.stack.store()
        self.stack.create()
        self.assertEqual((self.stack.CREATE, self.stack.COMPLETE),
                         self.stack.state)

        self.stack.suspend()
        self.assertEqual((self.stack.SUSPEND, self.stack.COMPLETE),
                         self.stack.state)

        # unexpected to call Resource.suspend
        self.m.StubOutWithMock(generic_rsrc.GenericResource, 'suspend')
        self.m.ReplayAll()

        self.stack.suspend()
        self.assertEqual((self.stack.SUSPEND, self.stack.COMPLETE),
                         self.stack.state)
        self.m.VerifyAll()

    def test_resume_stack_resumeed_ok(self):
        tmpl = {'HeatTemplateFormatVersion': '2012-12-12',
                'Resources': {'AResource': {'Type': 'GenericResourceType'}}}
        self.stack = stack.Stack(self.ctx, 'suspend_test',
                                 template.Template(tmpl))
        self.stack.store()
        self.stack.create()
        self.assertEqual((self.stack.CREATE, self.stack.COMPLETE),
                         self.stack.state)

        self.stack.suspend()
        self.assertEqual((self.stack.SUSPEND, self.stack.COMPLETE),
                         self.stack.state)

        self.stack.resume()
        self.assertEqual((self.stack.RESUME, self.stack.COMPLETE),
                         self.stack.state)

        # unexpected to call Resource.resume
        self.m.StubOutWithMock(generic_rsrc.GenericResource, 'resume')
        self.m.ReplayAll()

        self.stack.resume()
        self.assertEqual((self.stack.RESUME, self.stack.COMPLETE),
                         self.stack.state)
        self.m.VerifyAll()

    def test_suspend_fail(self):
        tmpl = {'HeatTemplateFormatVersion': '2012-12-12',
                'Resources': {'AResource': {'Type': 'GenericResourceType'}}}
        self.m.StubOutWithMock(generic_rsrc.GenericResource, 'handle_suspend')
        exc = Exception('foo')
        generic_rsrc.GenericResource.handle_suspend().AndRaise(exc)
        self.m.ReplayAll()

        self.stack = stack.Stack(self.ctx, 'suspend_test_fail',
                                 template.Template(tmpl))

        self.stack.store()
        self.stack.create()
        self.assertEqual((self.stack.CREATE, self.stack.COMPLETE),
                         self.stack.state)

        self.stack.suspend()

        self.assertEqual((self.stack.SUSPEND, self.stack.FAILED),
                         self.stack.state)
        self.assertEqual('Resource SUSPEND failed: Exception: '
                         'resources.AResource: foo',
                         self.stack.status_reason)
        self.m.VerifyAll()

    def test_resume_fail(self):
        tmpl = {'HeatTemplateFormatVersion': '2012-12-12',
                'Resources': {'AResource': {'Type': 'GenericResourceType'}}}
        self.m.StubOutWithMock(generic_rsrc.GenericResource, 'handle_resume')
        generic_rsrc.GenericResource.handle_resume().AndRaise(Exception('foo'))
        self.m.ReplayAll()

        self.stack = stack.Stack(self.ctx, 'resume_test_fail',
                                 template.Template(tmpl))

        self.stack.store()
        self.stack.create()
        self.assertEqual((self.stack.CREATE, self.stack.COMPLETE),
                         self.stack.state)

        self.stack.suspend()

        self.assertEqual((self.stack.SUSPEND, self.stack.COMPLETE),
                         self.stack.state)

        self.stack.resume()

        self.assertEqual((self.stack.RESUME, self.stack.FAILED),
                         self.stack.state)
        self.assertEqual('Resource RESUME failed: Exception: '
                         'resources.AResource: foo',
                         self.stack.status_reason)
        self.m.VerifyAll()

    def test_suspend_timeout(self):
        tmpl = {'HeatTemplateFormatVersion': '2012-12-12',
                'Resources': {'AResource': {'Type': 'GenericResourceType'}}}
        self.m.StubOutWithMock(generic_rsrc.GenericResource, 'handle_suspend')
        exc = scheduler.Timeout('foo', 0)
        generic_rsrc.GenericResource.handle_suspend().AndRaise(exc)
        self.m.ReplayAll()

        self.stack = stack.Stack(self.ctx, 'suspend_test_fail_timeout',
                                 template.Template(tmpl))

        self.stack.store()
        self.stack.create()
        self.assertEqual((self.stack.CREATE, self.stack.COMPLETE),
                         self.stack.state)

        self.stack.suspend()

        self.assertEqual((self.stack.SUSPEND, self.stack.FAILED),
                         self.stack.state)
        self.assertEqual('Suspend timed out', self.stack.status_reason)
        self.m.VerifyAll()

    def test_resume_timeout(self):
        tmpl = {'HeatTemplateFormatVersion': '2012-12-12',
                'Resources': {'AResource': {'Type': 'GenericResourceType'}}}
        self.m.StubOutWithMock(generic_rsrc.GenericResource, 'handle_resume')
        exc = scheduler.Timeout('foo', 0)
        generic_rsrc.GenericResource.handle_resume().AndRaise(exc)
        self.m.ReplayAll()

        self.stack = stack.Stack(self.ctx, 'resume_test_fail_timeout',
                                 template.Template(tmpl))

        self.stack.store()
        self.stack.create()
        self.assertEqual((self.stack.CREATE, self.stack.COMPLETE),
                         self.stack.state)

        self.stack.suspend()

        self.assertEqual((self.stack.SUSPEND, self.stack.COMPLETE),
                         self.stack.state)

        self.stack.resume()

        self.assertEqual((self.stack.RESUME, self.stack.FAILED),
                         self.stack.state)

        self.assertEqual('Resume timed out', self.stack.status_reason)
        self.m.VerifyAll()

    def _get_stack_to_check(self, name):
        tpl = {"HeatTemplateFormatVersion": "2012-12-12",
               "Resources": {
                   "A": {"Type": "GenericResourceType"},
                   "B": {"Type": "GenericResourceType"}}}
        self.stack = stack.Stack(self.ctx, name, template.Template(tpl),
                                 status_reason=name)
        self.stack.store()

        def _mock_check(res):
            res.handle_check = mock.Mock()

        [_mock_check(res) for res in self.stack.resources.values()]
        return self.stack

    def test_check_supported(self):
        stack1 = self._get_stack_to_check('check-supported')
        stack1.check()

        self.assertEqual(stack1.COMPLETE, stack1.status)
        self.assertEqual(stack1.CHECK, stack1.action)
        [self.assertTrue(res.handle_check.called)
         for res in stack1.resources.values()]
        self.assertNotIn('not fully supported', stack1.status_reason)

    def test_check_not_supported(self):
        stack1 = self._get_stack_to_check('check-not-supported')
        del stack1['B'].handle_check
        stack1.check()

        self.assertEqual(stack1.COMPLETE, stack1.status)
        self.assertEqual(stack1.CHECK, stack1.action)
        self.assertTrue(stack1['A'].handle_check.called)
        self.assertIn('not fully supported', stack1.status_reason)

    def test_check_fail(self):
        stk = self._get_stack_to_check('check-fail')
        stk['A'].handle_check.side_effect = Exception('fail-A')
        stk['B'].handle_check.side_effect = Exception('fail-B')
        stk.check()

        self.assertEqual(stk.FAILED, stk.status)
        self.assertEqual(stk.CHECK, stk.action)
        self.assertTrue(stk['A'].handle_check.called)
        self.assertTrue(stk['B'].handle_check.called)
        self.assertIn('fail-A', stk.status_reason)
        self.assertIn('fail-B', stk.status_reason)

    def test_adopt_stack(self):
        adopt_data = '''{
        "action": "CREATE",
        "status": "COMPLETE",
        "name": "my-test-stack-name",
        "resources": {
        "AResource": {
        "status": "COMPLETE",
        "name": "AResource",
        "resource_data": {},
        "metadata": {},
        "resource_id": "test-res-id",
        "action": "CREATE",
        "type": "GenericResourceType"
          }
         }
        }'''

        tmpl = {
            'HeatTemplateFormatVersion': '2012-12-12',
            'Resources': {'AResource': {'Type': 'GenericResourceType'}},
            'Outputs': {'TestOutput': {'Value': {
                'Fn::GetAtt': ['AResource', 'Foo']}}
            }
        }

        self.stack = stack.Stack(utils.dummy_context(), 'test_stack',
                                 template.Template(tmpl),
                                 adopt_stack_data=json.loads(adopt_data))
        self.stack.store()
        self.stack.adopt()
        res = self.stack['AResource']
        self.assertEqual(u'test-res-id', res.resource_id)
        self.assertEqual('AResource', res.name)
        self.assertEqual('COMPLETE', res.status)
        self.assertEqual('ADOPT', res.action)
        self.assertEqual((self.stack.ADOPT, self.stack.COMPLETE),
                         self.stack.state)
        self.assertEqual('AResource', self.stack.output('TestOutput'))

        loaded_stack = stack.Stack.load(self.ctx, self.stack.id)
        self.assertEqual({}, loaded_stack['AResource']._stored_properties_data)

    def test_adopt_stack_fails(self):
        adopt_data = '''{
                "action": "CREATE",
                "status": "COMPLETE",
                "name": "my-test-stack-name",
                "resources": {}
                }'''

        tmpl = template.Template({
            'HeatTemplateFormatVersion': '2012-12-12',
            'Resources': {
                'foo': {'Type': 'GenericResourceType'},

            }
        })
        self.stack = stack.Stack(utils.dummy_context(), 'test_stack',
                                 tmpl,
                                 adopt_stack_data=json.loads(adopt_data))
        self.stack.store()
        self.stack.adopt()
        self.assertEqual((self.stack.ADOPT, self.stack.FAILED),
                         self.stack.state)
        expected = ('Resource ADOPT failed: Exception: resources.foo: '
                    'Resource ID was not provided.')
        self.assertEqual(expected, self.stack.status_reason)

    def test_adopt_stack_rollback(self):
        adopt_data = '''{
                "name": "my-test-stack-name",
                "resources": {}
                }'''

        tmpl = template.Template({
            'HeatTemplateFormatVersion': '2012-12-12',
            'Resources': {
                'foo': {'Type': 'GenericResourceType'},

            }
        })
        self.stack = stack.Stack(utils.dummy_context(),
                                 'test_stack',
                                 tmpl,
                                 disable_rollback=False,
                                 adopt_stack_data=json.loads(adopt_data))
        self.stack.store()
        with mock.patch.object(self.stack, 'delete',
                               side_effect=self.stack.delete) as mock_delete:
            self.stack.adopt()
            self.assertEqual((self.stack.ROLLBACK, self.stack.COMPLETE),
                             self.stack.state)
            mock_delete.assert_called_once_with(action=self.stack.ROLLBACK,
                                                abandon=True)

    def test_resource_by_refid(self):
        tmpl = {'HeatTemplateFormatVersion': '2012-12-12',
                'Resources': {'AResource': {'Type': 'GenericResourceType'}}}

        self.stack = stack.Stack(self.ctx, 'resource_by_refid_stack',
                                 template.Template(tmpl))
        self.stack.store()
        self.stack.create()
        self.assertEqual((stack.Stack.CREATE, stack.Stack.COMPLETE),
                         self.stack.state)
        self.assertIn('AResource', self.stack)
        rsrc = self.stack['AResource']
        rsrc.resource_id_set('aaaa')
        self.assertIsNotNone(resource)

        for action, status in (
                (rsrc.INIT, rsrc.COMPLETE),
                (rsrc.CREATE, rsrc.IN_PROGRESS),
                (rsrc.CREATE, rsrc.COMPLETE),
                (rsrc.RESUME, rsrc.IN_PROGRESS),
                (rsrc.RESUME, rsrc.COMPLETE),
                (rsrc.UPDATE, rsrc.IN_PROGRESS),
                (rsrc.UPDATE, rsrc.COMPLETE)):
            rsrc.state_set(action, status)
            self.assertEqual(rsrc, self.stack.resource_by_refid('aaaa'))

        rsrc.state_set(rsrc.DELETE, rsrc.IN_PROGRESS)
        try:
            self.assertIsNone(self.stack.resource_by_refid('aaaa'))
            self.assertIsNone(self.stack.resource_by_refid('bbbb'))
        finally:
            rsrc.state_set(rsrc.CREATE, rsrc.COMPLETE)

    def test_create_failure_recovery(self):
        '''
        assertion:
        check that rollback still works with dynamic metadata
        this test fails the second instance
        '''

        class ResourceTypeA(generic_rsrc.ResourceWithProps):
            count = 0

            def handle_create(self):
                ResourceTypeA.count += 1
                self.resource_id_set('%s%d' % (self.name, self.count))

            def handle_delete(self):
                return super(ResourceTypeA, self).handle_delete()

        resource._register_class('ResourceTypeA', ResourceTypeA)

        tmpl = {'HeatTemplateFormatVersion': '2012-12-12',
                'Resources': {
                    'AResource': {'Type': 'ResourceTypeA',
                                  'Properties': {'Foo': 'abc'}},
                    'BResource': {'Type': 'ResourceWithPropsType',
                                  'Properties': {
                                      'Foo': {'Ref': 'AResource'}}}}}
        self.stack = stack.Stack(self.ctx, 'update_test_stack',
                                 template.Template(tmpl),
                                 disable_rollback=True)

        self.m.StubOutWithMock(generic_rsrc.ResourceWithProps, 'handle_create')
        self.m.StubOutWithMock(generic_rsrc.ResourceWithProps, 'handle_delete')
        self.m.StubOutWithMock(ResourceTypeA, 'handle_delete')

        # create
        generic_rsrc.ResourceWithProps.handle_create().AndRaise(Exception)

        # update
        generic_rsrc.ResourceWithProps.handle_delete()
        generic_rsrc.ResourceWithProps.handle_create()

        self.m.ReplayAll()

        self.stack.store()
        self.stack.create()

        self.assertEqual((stack.Stack.CREATE, stack.Stack.FAILED),
                         self.stack.state)
        self.assertEqual('abc', self.stack['AResource'].properties['Foo'])

        updated_stack = stack.Stack(self.ctx, 'updated_stack',
                                    template.Template(tmpl),
                                    disable_rollback=True)
        self.stack.update(updated_stack)
        self.assertEqual((stack.Stack.UPDATE, stack.Stack.COMPLETE),
                         self.stack.state)
        self.assertEqual('abc', self.stack['AResource'].properties['Foo'])
        self.assertEqual('AResource1',
                         self.stack['BResource'].properties['Foo'])

        self.m.VerifyAll()

    def test_create_bad_attribute(self):
        tmpl = {'HeatTemplateFormatVersion': '2012-12-12',
                'Resources': {
                    'AResource': {'Type': 'GenericResourceType'},
                    'BResource': {'Type': 'ResourceWithPropsType',
                                  'Properties': {
                                      'Foo': {'Fn::GetAtt': ['AResource',
                                                             'Foo']}}}}}
        self.stack = stack.Stack(self.ctx, 'bad_attr_test_stack',
                                 template.Template(tmpl),
                                 disable_rollback=True)

        self.m.StubOutWithMock(generic_rsrc.ResourceWithProps,
                               '_update_stored_properties')

        generic_rsrc.ResourceWithProps._update_stored_properties().AndRaise(
            exception.InvalidTemplateAttribute(resource='a', key='foo'))

        self.m.ReplayAll()

        self.stack.store()
        self.stack.create()

        self.assertEqual((stack.Stack.CREATE, stack.Stack.FAILED),
                         self.stack.state)
        self.assertEqual('Resource CREATE failed: The Referenced Attribute '
                         '(a foo) is incorrect.', self.stack.status_reason)
        self.m.VerifyAll()

    def test_stack_create_timeout(self):
        self.m.StubOutWithMock(scheduler.DependencyTaskGroup, '__call__')
        self.m.StubOutWithMock(scheduler, 'wallclock')

        stk = stack.Stack(self.ctx, 's', self.tmpl)

        def dummy_task():
            while True:
                yield

        start_time = time.time()
        scheduler.wallclock().AndReturn(start_time)
        scheduler.wallclock().AndReturn(start_time + 1)
        scheduler.DependencyTaskGroup.__call__().AndReturn(dummy_task())
        scheduler.wallclock().AndReturn(start_time + stk.timeout_secs() + 1)

        self.m.ReplayAll()

        stk.create()

        self.assertEqual((stack.Stack.CREATE, stack.Stack.FAILED), stk.state)
        self.assertEqual('Create timed out', stk.status_reason)

        self.m.VerifyAll()

    def test_stack_name_valid(self):
        stk = stack.Stack(self.ctx, 's', self.tmpl)
        self.assertIsInstance(stk, stack.Stack)
        stk = stack.Stack(self.ctx, 'stack123', self.tmpl)
        self.assertIsInstance(stk, stack.Stack)
        stk = stack.Stack(self.ctx, 'test.stack', self.tmpl)
        self.assertIsInstance(stk, stack.Stack)
        stk = stack.Stack(self.ctx, 'test_stack', self.tmpl)
        self.assertIsInstance(stk, stack.Stack)
        stk = stack.Stack(self.ctx, 'TEST', self.tmpl)
        self.assertIsInstance(stk, stack.Stack)
        stk = stack.Stack(self.ctx, 'test-stack', self.tmpl)
        self.assertIsInstance(stk, stack.Stack)

    def test_stack_name_invalid(self):
        stack_names = ['_foo', '1bad', '.kcats', 'test stack', ' teststack',
                       '^-^', '"stack"', '1234', 'cat|dog', '$(foo)',
                       'test/stack', 'test\stack', 'test::stack', 'test;stack',
                       'test~stack', '#test']
        for stack_name in stack_names:
            self.assertRaises(exception.StackValidationFailed, stack.Stack,
                              self.ctx, stack_name, self.tmpl)

    def test_resource_state_get_att(self):
        tmpl = {
            'HeatTemplateFormatVersion': '2012-12-12',
            'Resources': {'AResource': {'Type': 'GenericResourceType'}},
            'Outputs': {'TestOutput': {'Value': {
                'Fn::GetAtt': ['AResource', 'Foo']}}
            }
        }

        self.stack = stack.Stack(self.ctx, 'resource_state_get_att',
                                 template.Template(tmpl))
        self.stack.store()
        self.stack.create()
        self.assertEqual((stack.Stack.CREATE, stack.Stack.COMPLETE),
                         self.stack.state)
        self.assertIn('AResource', self.stack)
        rsrc = self.stack['AResource']
        rsrc.resource_id_set('aaaa')
        self.assertEqual('AResource', rsrc.FnGetAtt('Foo'))

        for action, status in (
                (rsrc.CREATE, rsrc.IN_PROGRESS),
                (rsrc.CREATE, rsrc.COMPLETE),
                (rsrc.CREATE, rsrc.FAILED),
                (rsrc.SUSPEND, rsrc.IN_PROGRESS),
                (rsrc.SUSPEND, rsrc.COMPLETE),
                (rsrc.RESUME, rsrc.IN_PROGRESS),
                (rsrc.RESUME, rsrc.COMPLETE),
                (rsrc.UPDATE, rsrc.IN_PROGRESS),
                (rsrc.UPDATE, rsrc.FAILED),
                (rsrc.UPDATE, rsrc.COMPLETE)):
            rsrc.state_set(action, status)
            self.assertEqual('AResource', self.stack.output('TestOutput'))
        for action, status in (
                (rsrc.DELETE, rsrc.IN_PROGRESS),
                (rsrc.DELETE, rsrc.FAILED),
                (rsrc.DELETE, rsrc.COMPLETE)):
            rsrc.state_set(action, status)
            self.assertIsNone(self.stack.output('TestOutput'))

    def test_resource_required_by(self):
        tmpl = {'HeatTemplateFormatVersion': '2012-12-12',
                'Resources': {'AResource': {'Type': 'GenericResourceType'},
                              'BResource': {'Type': 'GenericResourceType',
                                            'DependsOn': 'AResource'},
                              'CResource': {'Type': 'GenericResourceType',
                                            'DependsOn': 'BResource'},
                              'DResource': {'Type': 'GenericResourceType',
                                            'DependsOn': 'BResource'}}}

        self.stack = stack.Stack(self.ctx, 'depends_test_stack',
                                 template.Template(tmpl))
        self.stack.store()
        self.stack.create()
        self.assertEqual((stack.Stack.CREATE, stack.Stack.COMPLETE),
                         self.stack.state)

        self.assertEqual(['BResource'],
                         self.stack['AResource'].required_by())
        self.assertEqual([],
                         self.stack['CResource'].required_by())
        required_by = self.stack['BResource'].required_by()
        self.assertEqual(2, len(required_by))
        for r in ['CResource', 'DResource']:
            self.assertIn(r, required_by)

    def test_resource_multi_required_by(self):
        tmpl = {'HeatTemplateFormatVersion': '2012-12-12',
                'Resources': {'AResource': {'Type': 'GenericResourceType'},
                              'BResource': {'Type': 'GenericResourceType'},
                              'CResource': {'Type': 'GenericResourceType'},
                              'DResource': {'Type': 'GenericResourceType',
                                            'DependsOn': ['AResource',
                                                          'BResource',
                                                          'CResource']}}}

        self.stack = stack.Stack(self.ctx, 'depends_test_stack',
                                 template.Template(tmpl))
        self.stack.store()
        self.stack.create()
        self.assertEqual((stack.Stack.CREATE, stack.Stack.COMPLETE),
                         self.stack.state)

        for r in ['AResource', 'BResource', 'CResource']:
            self.assertEqual(['DResource'],
                             self.stack[r].required_by())

    def test_store_saves_owner(self):
        """
        The owner_id attribute of Store is saved to the database when stored.
        """
        self.stack = stack.Stack(self.ctx, 'owner_stack', self.tmpl)
        stack_ownee = stack.Stack(self.ctx, 'ownee_stack', self.tmpl,
                                  owner_id=self.stack.id)
        stack_ownee.store()
        db_stack = stack_object.Stack.get_by_id(self.ctx, stack_ownee.id)
        self.assertEqual(self.stack.id, db_stack.owner_id)

    def test_init_user_creds_id(self):
        ctx_init = utils.dummy_context(user='my_user',
                                       password='my_pass')
        ctx_init.request_id = self.ctx.request_id
        creds = ucreds_object.UserCreds.create(ctx_init)
        self.stack = stack.Stack(self.ctx, 'creds_init', self.tmpl,
                                 user_creds_id=creds.id)
        self.stack.store()
        self.assertEqual(creds.id, self.stack.user_creds_id)
        ctx_expected = ctx_init.to_dict()
        ctx_expected['auth_token'] = None
        self.assertEqual(ctx_expected, self.stack.stored_context().to_dict())

    def test_store_saves_creds(self):
        """
        A user_creds entry is created on first stack store
        """
        cfg.CONF.set_default('deferred_auth_method', 'password')
        self.stack = stack.Stack(self.ctx, 'creds_stack', self.tmpl)
        self.stack.store()

        # The store should've created a user_creds row and set user_creds_id
        db_stack = stack_object.Stack.get_by_id(self.ctx, self.stack.id)
        user_creds_id = db_stack.user_creds_id
        self.assertIsNotNone(user_creds_id)

        # should've stored the username/password in the context
        user_creds = ucreds_object.UserCreds.get_by_id(user_creds_id)
        self.assertEqual(self.ctx.username, user_creds.get('username'))
        self.assertEqual(self.ctx.password, user_creds.get('password'))
        self.assertIsNone(user_creds.get('trust_id'))
        self.assertIsNone(user_creds.get('trustor_user_id'))

        # Check the stored_context is as expected
        expected_context = context.RequestContext.from_dict(self.ctx.to_dict())
        expected_context.auth_token = None
        stored_context = self.stack.stored_context().to_dict()
        self.assertEqual(expected_context.to_dict(), stored_context)

        # Store again, ID should not change
        self.stack.store()
        self.assertEqual(user_creds_id, db_stack.user_creds_id)

    def test_store_saves_creds_trust(self):
        """
        A user_creds entry is created on first stack store
        """
        cfg.CONF.set_override('deferred_auth_method', 'trusts')

        self.m.StubOutWithMock(keystone.KeystoneClientPlugin, '_create')
        keystone.KeystoneClientPlugin._create().AndReturn(
            fakes.FakeKeystoneClient(user_id='auser123'))
        self.m.ReplayAll()

        self.stack = stack.Stack(self.ctx, 'creds_stack', self.tmpl)
        self.stack.store()

        # The store should've created a user_creds row and set user_creds_id
        db_stack = stack_object.Stack.get_by_id(self.ctx, self.stack.id)
        user_creds_id = db_stack.user_creds_id
        self.assertIsNotNone(user_creds_id)

        # should've stored the trust_id and trustor_user_id returned from
        # FakeKeystoneClient.create_trust_context, username/password should
        # not have been stored
        user_creds = ucreds_object.UserCreds.get_by_id(user_creds_id)
        self.assertIsNone(user_creds.get('username'))
        self.assertIsNone(user_creds.get('password'))
        self.assertEqual('atrust', user_creds.get('trust_id'))
        self.assertEqual('auser123', user_creds.get('trustor_user_id'))

        # Check the stored_context is as expected
        expected_context = context.RequestContext(
            trust_id='atrust', trustor_user_id='auser123',
            request_id=self.ctx.request_id, is_admin=False).to_dict()
        stored_context = self.stack.stored_context().to_dict()
        self.assertEqual(expected_context, stored_context)

        # Store again, ID should not change
        self.stack.store()
        self.assertEqual(user_creds_id, db_stack.user_creds_id)

    def test_backup_copies_user_creds_id(self):
        ctx_init = utils.dummy_context(user='my_user',
                                       password='my_pass')
        ctx_init.request_id = self.ctx.request_id
        creds = ucreds_object.UserCreds.create(ctx_init)
        self.stack = stack.Stack(self.ctx, 'creds_init', self.tmpl,
                                 user_creds_id=creds.id)
        self.stack.store()
        self.assertEqual(creds.id, self.stack.user_creds_id)
        backup = self.stack._backup_stack()
        self.assertEqual(creds.id, backup.user_creds_id)

    def test_stored_context_err(self):
        """
        Test stored_context error path.
        """
        self.stack = stack.Stack(self.ctx, 'creds_stack', self.tmpl)
        ex = self.assertRaises(exception.Error, self.stack.stored_context)
        expected_err = 'Attempt to use stored_context with no user_creds'
        self.assertEqual(expected_err, six.text_type(ex))

    def test_store_gets_username_from_stack(self):
        self.stack = stack.Stack(self.ctx, 'username_stack',
                                 self.tmpl, username='foobar')
        self.ctx.username = 'not foobar'
        self.stack.store()
        db_stack = stack_object.Stack.get_by_id(self.ctx, self.stack.id)
        self.assertEqual('foobar', db_stack.username)

    def test_store_backup_true(self):
        self.stack = stack.Stack(self.ctx, 'username_stack',
                                 self.tmpl, username='foobar')
        self.ctx.username = 'not foobar'
        self.stack.store(backup=True)
        db_stack = stack_object.Stack.get_by_id(self.ctx, self.stack.id)
        self.assertTrue(db_stack.backup)

    def test_store_backup_false(self):
        self.stack = stack.Stack(self.ctx, 'username_stack',
                                 self.tmpl, username='foobar')
        self.ctx.username = 'not foobar'
        self.stack.store(backup=False)
        db_stack = stack_object.Stack.get_by_id(self.ctx, self.stack.id)
        self.assertFalse(db_stack.backup)

    def test_init_stored_context_false(self):
        ctx_init = utils.dummy_context(user='mystored_user',
                                       password='mystored_pass')
        ctx_init.request_id = self.ctx.request_id
        creds = ucreds_object.UserCreds.create(ctx_init)
        self.stack = stack.Stack(self.ctx, 'creds_store1', self.tmpl,
                                 user_creds_id=creds.id,
                                 use_stored_context=False)
        ctx_expected = self.ctx.to_dict()
        self.assertEqual(ctx_expected, self.stack.context.to_dict())
        self.stack.store()
        self.assertEqual(ctx_expected, self.stack.context.to_dict())

    def test_init_stored_context_true(self):
        ctx_init = utils.dummy_context(user='mystored_user',
                                       password='mystored_pass')
        ctx_init.request_id = self.ctx.request_id
        creds = ucreds_object.UserCreds.create(ctx_init)
        self.stack = stack.Stack(self.ctx, 'creds_store2', self.tmpl,
                                 user_creds_id=creds.id,
                                 use_stored_context=True)
        ctx_expected = ctx_init.to_dict()
        ctx_expected['auth_token'] = None
        self.assertEqual(ctx_expected, self.stack.context.to_dict())
        self.stack.store()
        self.assertEqual(ctx_expected, self.stack.context.to_dict())

    def test_load_stored_context_false(self):
        ctx_init = utils.dummy_context(user='mystored_user',
                                       password='mystored_pass')
        ctx_init.request_id = self.ctx.request_id
        creds = ucreds_object.UserCreds.create(ctx_init)
        self.stack = stack.Stack(self.ctx, 'creds_store3', self.tmpl,
                                 user_creds_id=creds.id)
        self.stack.store()

        load_stack = stack.Stack.load(self.ctx, stack_id=self.stack.id,
                                      use_stored_context=False)
        self.assertEqual(self.ctx.to_dict(), load_stack.context.to_dict())

    def test_load_stored_context_true(self):
        ctx_init = utils.dummy_context(user='mystored_user',
                                       password='mystored_pass')
        ctx_init.request_id = self.ctx.request_id
        creds = ucreds_object.UserCreds.create(ctx_init)
        self.stack = stack.Stack(self.ctx, 'creds_store4', self.tmpl,
                                 user_creds_id=creds.id)
        self.stack.store()
        ctx_expected = ctx_init.to_dict()
        ctx_expected['auth_token'] = None

        load_stack = stack.Stack.load(self.ctx, stack_id=self.stack.id,
                                      use_stored_context=True)
        self.assertEqual(ctx_expected, load_stack.context.to_dict())

    def test_load_honors_owner(self):
        """
        Loading a stack from the database will set the owner_id of the
        resultant stack appropriately.
        """
        self.stack = stack.Stack(self.ctx, 'owner_stack', self.tmpl)
        stack_ownee = stack.Stack(self.ctx, 'ownee_stack', self.tmpl,
                                  owner_id=self.stack.id)
        stack_ownee.store()

        saved_stack = stack.Stack.load(self.ctx, stack_id=stack_ownee.id)
        self.assertEqual(self.stack.id, saved_stack.owner_id)

    def test_requires_deferred_auth(self):
        tmpl = {'HeatTemplateFormatVersion': '2012-12-12',
                'Resources': {'AResource': {'Type': 'GenericResourceType'},
                              'BResource': {'Type': 'GenericResourceType'},
                              'CResource': {'Type': 'GenericResourceType'}}}

        self.stack = stack.Stack(self.ctx, 'update_test_stack',
                                 template.Template(tmpl),
                                 disable_rollback=False)

        self.assertFalse(self.stack.requires_deferred_auth())

        self.stack['CResource'].requires_deferred_auth = True
        self.assertTrue(self.stack.requires_deferred_auth())

    def test_stack_user_project_id_default(self):
        self.stack = stack.Stack(self.ctx, 'user_project_none', self.tmpl)
        self.stack.store()
        self.assertIsNone(self.stack.stack_user_project_id)
        db_stack = stack_object.Stack.get_by_id(self.ctx, self.stack.id)
        self.assertIsNone(db_stack.stack_user_project_id)

    def test_stack_user_project_id_constructor(self):
        self.stub_keystoneclient()
        self.m.ReplayAll()

        self.stack = stack.Stack(self.ctx, 'user_project_init',
                                 self.tmpl,
                                 stack_user_project_id='aproject1234')
        self.stack.store()
        self.assertEqual('aproject1234', self.stack.stack_user_project_id)
        db_stack = stack_object.Stack.get_by_id(self.ctx, self.stack.id)
        self.assertEqual('aproject1234', db_stack.stack_user_project_id)

        self.stack.delete()
        self.assertEqual((stack.Stack.DELETE, stack.Stack.COMPLETE),
                         self.stack.state)
        self.m.VerifyAll()

    def test_stack_user_project_id_setter(self):
        self.stub_keystoneclient()
        self.m.ReplayAll()

        self.stack = stack.Stack(self.ctx, 'user_project_init', self.tmpl)
        self.stack.store()
        self.assertIsNone(self.stack.stack_user_project_id)
        self.stack.set_stack_user_project_id(project_id='aproject456')
        self.assertEqual('aproject456', self.stack.stack_user_project_id)
        db_stack = stack_object.Stack.get_by_id(self.ctx, self.stack.id)
        self.assertEqual('aproject456', db_stack.stack_user_project_id)

        self.stack.delete()
        self.assertEqual((stack.Stack.DELETE, stack.Stack.COMPLETE),
                         self.stack.state)
        self.m.VerifyAll()

    def test_stack_user_project_id_create(self):
        self.stub_keystoneclient()
        self.m.ReplayAll()

        self.stack = stack.Stack(self.ctx, 'user_project_init', self.tmpl)
        self.stack.store()
        self.assertIsNone(self.stack.stack_user_project_id)
        self.stack.create_stack_user_project_id()

        self.assertEqual('aprojectid', self.stack.stack_user_project_id)
        db_stack = stack_object.Stack.get_by_id(self.ctx, self.stack.id)
        self.assertEqual('aprojectid', db_stack.stack_user_project_id)

        self.stack.delete()
        self.assertEqual((stack.Stack.DELETE, stack.Stack.COMPLETE),
                         self.stack.state)
        self.m.VerifyAll()

    def test_preview_resources_returns_list_of_resource_previews(self):
        tmpl = {'HeatTemplateFormatVersion': '2012-12-12',
                'Resources': {'AResource': {'Type': 'GenericResourceType'}}}
        self.stack = stack.Stack(self.ctx, 'preview_stack',
                                 template.Template(tmpl))
        res = mock.Mock()
        res.preview.return_value = 'foo'
        self.stack._resources = {'r1': res}

        resources = self.stack.preview_resources()
        self.assertEqual(['foo'], resources)

    def test_correct_outputs(self):
        tmpl = {'HeatTemplateFormatVersion': '2012-12-12',
                'Resources': {
                    'AResource': {'Type': 'ResourceWithPropsType',
                                  'Properties': {'Foo': 'abc'}},
                    'BResource': {'Type': 'ResourceWithPropsType',
                                  'Properties': {'Foo': 'def'}}},
                'Outputs': {
                    'Resource_attr': {
                        'Value': {
                            'Fn::GetAtt': ['AResource', 'Foo']}}}}

        self.stack = stack.Stack(self.ctx, 'stack_with_correct_outputs',
                                 template.Template(tmpl))

        self.stack.store()
        self.stack.create()

        self.assertEqual((stack.Stack.CREATE, stack.Stack.COMPLETE),
                         self.stack.state)
        self.assertEqual('abc', self.stack['AResource'].properties['Foo'])
        # According _resolve_attribute method in GenericResource output
        # value will be equal with name AResource.
        self.assertEqual('AResource', self.stack.output('Resource_attr'))

        self.stack.delete()

        self.assertEqual((self.stack.DELETE, self.stack.COMPLETE),
                         self.stack.state)

    def test_incorrect_outputs(self):
        tmpl = {'HeatTemplateFormatVersion': '2012-12-12',
                'Resources': {
                    'AResource': {'Type': 'ResourceWithPropsType',
                                  'Properties': {'Foo': 'abc'}}},
                'Outputs': {
                    'Resource_attr': {
                        'Value': {
                            'Fn::GetAtt': ['AResource', 'Bar']}}}}

        self.stack = stack.Stack(self.ctx, 'stack_with_incorrect_outputs',
                                 template.Template(tmpl))

        self.stack.store()
        self.stack.create()

        self.assertEqual((stack.Stack.CREATE, stack.Stack.COMPLETE),
                         self.stack.state)

        self.assertIsNone(self.stack.output('Resource_attr'))
        self.assertEqual('The Referenced Attribute (AResource Bar) is '
                         'incorrect.',
                         self.stack.outputs['Resource_attr']['error_msg'])

        self.stack.delete()

        self.assertEqual((self.stack.DELETE, self.stack.COMPLETE),
                         self.stack.state)

    def test_stack_load_no_param_value_validation(self):
        '''
        Test stack loading with disabled parameter value validation.
        '''
        tmpl = template_format.parse('''
        heat_template_version: 2013-05-23
        parameters:
            flavor:
                type: string
                description: A flavor.
                constraints:
                    - custom_constraint: nova.flavor
        resources:
            a_resource:
                type: GenericResourceType
        ''')

        # Mock objects so the query for flavors in server.FlavorConstraint
        # works for stack creation
        fc = fakes.FakeClient()
        self.m.StubOutWithMock(nova.NovaClientPlugin, '_create')
        nova.NovaClientPlugin._create().AndReturn(fc)

        fc.flavors = self.m.CreateMockAnything()
        flavor = collections.namedtuple("Flavor", ["id", "name"])
        flavor.id = "1234"
        flavor.name = "dummy"
        fc.flavors.list().AndReturn([flavor])

        self.m.ReplayAll()

        test_env = environment.Environment({'flavor': 'dummy'})
        self.stack = stack.Stack(self.ctx, 'stack_with_custom_constraint',
                                 template.Template(tmpl, env=test_env))

        self.stack.validate()
        self.stack.store()
        self.stack.create()
        stack_id = self.stack.id

        self.m.VerifyAll()

        self.assertEqual((stack.Stack.CREATE, stack.Stack.COMPLETE),
                         self.stack.state)

        loaded_stack = stack.Stack.load(self.ctx, stack_id=self.stack.id)
        self.assertEqual(stack_id, loaded_stack.parameters['OS::stack_id'])

        # verify that fc.flavors.list() has not been called, i.e. verify that
        # parameter value validation did not happen and FlavorConstraint was
        # not invoked
        self.m.VerifyAll()

    def test_snapshot_delete(self):
        snapshots = []

        class ResourceDeleteSnapshot(generic_rsrc.ResourceWithProps):

            def handle_delete_snapshot(self, data):
                snapshots.append(data)

        resource._register_class(
            'ResourceDeleteSnapshot', ResourceDeleteSnapshot)
        tmpl = {'HeatTemplateFormatVersion': '2012-12-12',
                'Resources': {'AResource': {'Type': 'ResourceDeleteSnapshot'}}}

        self.stack = stack.Stack(self.ctx, 'snapshot_stack',
                                 template.Template(tmpl))
        data = self.stack.prepare_abandon()
        fake_snapshot = collections.namedtuple('Snapshot', ('data',))(data)
        self.stack.delete_snapshot(fake_snapshot)
        self.assertEqual([data['resources']['AResource']], snapshots)

    def test_delete_snapshot_without_data(self):
        tmpl = {'HeatTemplateFormatVersion': '2012-12-12',
                'Resources': {'R1': {'Type': 'GenericResourceType'}}}
        self.stack = stack.Stack(self.ctx, 'snapshot_stack',
                                 template.Template(tmpl))
        fake_snapshot = collections.namedtuple('Snapshot', ('data',))(None)
        self.assertIsNone(self.stack.delete_snapshot(fake_snapshot))

    def test_incorrect_outputs_cfn_get_attr(self):
        tmpl = {'HeatTemplateFormatVersion': '2012-12-12',
                'Resources': {
                    'AResource': {'Type': 'ResourceWithPropsType',
                                  'Properties': {'Foo': 'abc'}}},
                'Outputs': {
                    'Resource_attr': {
                        'Value': {
                            'Fn::GetAtt': ['AResource', 'Bar']}}}}

        self.stack = stack.Stack(self.ctx, 'stack_with_correct_outputs',
                                 template.Template(tmpl))

        ex = self.assertRaises(exception.StackValidationFailed,
                               self.stack.validate)

        self.assertEqual('Output validation error: '
                         'The Referenced Attribute '
                         '(AResource Bar) is incorrect.',
                         six.text_type(ex))

    def test_incorrect_outputs_cfn_incorrect_reference(self):
        tmpl = template_format.parse("""
        HeatTemplateFormatVersion: '2012-12-12'
        Outputs:
          Output:
            Value:
              Fn::GetAtt:
                - Resource
                - Foo
        """)
        self.stack = stack.Stack(self.ctx, 'stack_with_incorrect_outputs',
                                 template.Template(tmpl))

        ex = self.assertRaises(exception.StackValidationFailed,
                               self.stack.validate)

        self.assertIn('The specified reference "Resource" '
                      '(in unknown) is incorrect.', six.text_type(ex))

    def test_incorrect_outputs_incorrect_reference(self):
        tmpl = template_format.parse("""
        heat_template_version: 2013-05-23
        outputs:
          output:
            value: { get_attr: [resource, foo] }
        """)
        self.stack = stack.Stack(self.ctx, 'stack_with_incorrect_outputs',
                                 template.Template(tmpl))

        ex = self.assertRaises(exception.StackValidationFailed,
                               self.stack.validate)

        self.assertIn('The specified reference "resource" '
                      '(in unknown) is incorrect.', six.text_type(ex))

    def test_incorrect_outputs_cfn_missing_value(self):
        tmpl = template_format.parse("""
        HeatTemplateFormatVersion: '2012-12-12'
        Resources:
          AResource:
            Type: ResourceWithPropsType
            Properties:
              Foo: abc
        Outputs:
          Resource_attr:
            Description: the attr
        """)
        self.stack = stack.Stack(self.ctx, 'stack_with_correct_outputs',
                                 template.Template(tmpl))

        ex = self.assertRaises(exception.StackValidationFailed,
                               self.stack.validate)

        self.assertIn('Each Output must contain a Value key.',
                      six.text_type(ex))

    def test_incorrect_outputs_cfn_empty_value(self):
        tmpl = template_format.parse("""
        HeatTemplateFormatVersion: '2012-12-12'
        Resources:
          AResource:
            Type: ResourceWithPropsType
            Properties:
              Foo: abc
        Outputs:
          Resource_attr:
            Value: ''
        """)
        self.stack = stack.Stack(self.ctx, 'stack_with_correct_outputs',
                                 template.Template(tmpl))

        self.assertIsNone(self.stack.validate())

    def test_incorrect_outputs_cfn_none_value(self):
        tmpl = template_format.parse("""
        HeatTemplateFormatVersion: '2012-12-12'
        Resources:
          AResource:
            Type: ResourceWithPropsType
            Properties:
              Foo: abc
        Outputs:
          Resource_attr:
            Value:
        """)
        self.stack = stack.Stack(self.ctx, 'stack_with_correct_outputs',
                                 template.Template(tmpl))

        self.assertIsNone(self.stack.validate())

    def test_incorrect_outputs_cfn_string_data(self):
        tmpl = template_format.parse("""
        HeatTemplateFormatVersion: '2012-12-12'
        Resources:
          AResource:
            Type: ResourceWithPropsType
            Properties:
              Foo: abc
        Outputs:
          Resource_attr:
            This is wrong data
        """)
        self.stack = stack.Stack(self.ctx, 'stack_with_correct_outputs',
                                 template.Template(tmpl))

        ex = self.assertRaises(exception.StackValidationFailed,
                               self.stack.validate)

        self.assertIn('Outputs must contain Output. '
                      'Found a [%s] instead' % six.text_type,
                      six.text_type(ex))

    def test_prop_validate_value(self):
        tmpl = template_format.parse("""
        HeatTemplateFormatVersion: '2012-12-12'
        Resources:
          AResource:
            Type: ResourceWithPropsType
            Properties:
              FooInt: notanint
        """)
        self.stack = stack.Stack(self.ctx, 'stack_with_bad_property',
                                 template.Template(tmpl))

        ex = self.assertRaises(exception.StackValidationFailed,
                               self.stack.validate)

        self.assertIn("'notanint' is not an integer",
                      six.text_type(ex))

        self.stack.strict_validate = False
        self.assertIsNone(self.stack.validate())

    def test_param_validate_value(self):
        tmpl = template_format.parse("""
        HeatTemplateFormatVersion: '2012-12-12'
        Parameters:
          foo:
            Type: Number
        """)

        env1 = environment.Environment({'parameters': {'foo': 'abc'}})
        self.stack = stack.Stack(self.ctx, 'stack_with_bad_param',
                                 template.Template(tmpl, env=env1))

        ex = self.assertRaises(exception.StackValidationFailed,
                               self.stack.validate)

        self.assertEqual("Parameter 'foo' is invalid: could not convert "
                         "string to float: abc", six.text_type(ex))

        self.stack.strict_validate = False
        self.assertIsNone(self.stack.validate())

    def test_incorrect_outputs_cfn_list_data(self):
        tmpl = template_format.parse("""
        HeatTemplateFormatVersion: '2012-12-12'
        Resources:
          AResource:
            Type: ResourceWithPropsType
            Properties:
              Foo: abc
        Outputs:
          Resource_attr:
            - Data is not what it seems
        """)
        self.stack = stack.Stack(self.ctx, 'stack_with_correct_outputs',
                                 template.Template(tmpl))

        ex = self.assertRaises(exception.StackValidationFailed,
                               self.stack.validate)

        self.assertIn('Outputs must contain Output. '
                      'Found a [%s] instead' % type([]), six.text_type(ex))

    def test_incorrect_outputs_hot_get_attr(self):
        tmpl = {'heat_template_version': '2013-05-23',
                'resources': {
                    'AResource': {'type': 'ResourceWithPropsType',
                                  'properties': {'Foo': 'abc'}}},
                'outputs': {
                    'resource_attr': {
                        'value': {
                            'get_attr': ['AResource', 'Bar']}}}}

        self.stack = stack.Stack(self.ctx, 'stack_with_correct_outputs',
                                 template.Template(tmpl))

        ex = self.assertRaises(exception.StackValidationFailed,
                               self.stack.validate)

        self.assertEqual('Output validation error: '
                         'The Referenced Attribute '
                         '(AResource Bar) is incorrect.',
                         six.text_type(ex))

    def test_restore(self):
        tmpl = {'HeatTemplateFormatVersion': '2012-12-12',
                'Resources': {
                    'A': {'Type': 'GenericResourceType'},
                    'B': {'Type': 'GenericResourceType'}}}
        self.stack = stack.Stack(self.ctx, 'stack_details_test',
                                 template.Template(tmpl))
        self.stack.store()
        self.stack.create()

        data = copy.deepcopy(self.stack.prepare_abandon())
        fake_snapshot = collections.namedtuple(
            'Snapshot', ('data', 'stack_id'))(data, self.stack.id)

        new_tmpl = {'HeatTemplateFormatVersion': '2012-12-12',
                    'Resources': {'A': {'Type': 'GenericResourceType'}}}
        updated_stack = stack.Stack(self.ctx, 'updated_stack',
                                    template.Template(new_tmpl))
        self.stack.update(updated_stack)
        self.assertEqual(1, len(self.stack.resources))

        self.stack.restore(fake_snapshot)

        self.assertEqual((stack.Stack.RESTORE, stack.Stack.COMPLETE),
                         self.stack.state)
        self.assertEqual(2, len(self.stack.resources))

    def test_restore_with_original_env(self):
        tmpl = {
            'heat_template_version': '2013-05-23',
            'parameters': {
                'foo': {'type': 'string'}
            },
            'resources': {
                'A': {
                    'type': 'ResourceWithPropsType',
                    'properties': {'Foo': {'get_param': 'foo'}}
                }
            }
        }
        self.stack = stack.Stack(self.ctx, 'stack_restore_test',
                                 template.Template(
                                     tmpl,
                                     env=environment.Environment(
                                         {'foo': 'abc'})))
        self.stack.store()
        self.stack.create()
        self.assertEqual('abc',
                         self.stack.resources['A'].properties['Foo'])

        data = copy.deepcopy(self.stack.prepare_abandon())
        fake_snapshot = collections.namedtuple(
            'Snapshot', ('data', 'stack_id'))(data, self.stack.id)

        updated_stack = stack.Stack(self.ctx, 'updated_stack',
                                    template.Template(
                                        tmpl,
                                        env=environment.Environment(
                                            {'foo': 'xyz'})))
        self.stack.update(updated_stack)
        self.assertEqual('xyz',
                         self.stack.resources['A'].properties['Foo'])

        self.stack.restore(fake_snapshot)
        self.assertEqual((stack.Stack.RESTORE, stack.Stack.COMPLETE),
                         self.stack.state)
        self.assertEqual('abc',
                         self.stack.resources['A'].properties['Foo'])

    def test_hot_restore(self):

        class ResourceWithRestore(generic_rsrc.ResWithComplexPropsAndAttrs):

            def handle_restore(self, defn, data):
                props = dict(
                    (key, value) for (key, value) in
                    six.iteritems(defn.properties(self.properties_schema))
                    if value is not None)
                value = data['resource_data']['a_string']
                props['a_string'] = value
                return defn.freeze(properties=props)

        resource._register_class('ResourceWithRestore', ResourceWithRestore)
        tpl = {'heat_template_version': '2013-05-23',
               'resources':
               {'A': {'type': 'ResourceWithRestore'}}}
        self.stack = stack.Stack(self.ctx, 'stack_details_test',
                                 template.Template(tpl))
        self.stack.store()
        self.stack.create()

        data = self.stack.prepare_abandon()
        data['resources']['A']['resource_data']['a_string'] = 'foo'
        fake_snapshot = collections.namedtuple(
            'Snapshot', ('data', 'stack_id'))(data, self.stack.id)

        self.stack.restore(fake_snapshot)

        self.assertEqual((stack.Stack.RESTORE, stack.Stack.COMPLETE),
                         self.stack.state)

        self.assertEqual(
            'foo', self.stack.resources['A'].properties['a_string'])


class StackKwargsForCloningTest(common.HeatTestCase):
    scenarios = [
        ('default', dict(keep_status=False, only_db=False,
                         not_included=['action', 'status', 'status_reason'])),
        ('only_db', dict(keep_status=False, only_db=True,
                         not_included=['action', 'status', 'status_reason',
                                       'strict_validate'])),
        ('keep_status', dict(keep_status=True, only_db=False,
                             not_included=[])),
        ('status_db', dict(keep_status=True, only_db=True,
                           not_included=['strict_validate'])),
    ]

    def test_kwargs(self):
        tmpl = template.Template(copy.deepcopy(empty_template))
        ctx = utils.dummy_context()
        test_data = dict(action='x', status='y',
                         status_reason='z', timeout_mins=33,
                         disable_rollback=True, parent_resource='fred',
                         owner_id=32, stack_user_project_id=569,
                         user_creds_id=123, tenant_id='some-uuid',
                         username='jo', nested_depth=3,
                         strict_validate=True, convergence=False,
                         current_traversal=45)
        db_map = {'parent_resource': 'parent_resource_name',
                  'tenant_id': 'tenant', 'timeout_mins': 'timeout'}
        test_db_data = {}
        for key in test_data:
            dbkey = db_map.get(key, key)
            test_db_data[dbkey] = test_data[key]

        self.stack = stack.Stack(ctx, utils.random_name(), tmpl,
                                 **test_data)
        res = self.stack.get_kwargs_for_cloning(keep_status=self.keep_status,
                                                only_db=self.only_db)
        for key in self.not_included:
            self.assertNotIn(key, res)

        for key in test_data:
            if key not in self.not_included:
                dbkey = db_map.get(key, key)
                if self.only_db:
                    self.assertEqual(test_data[key], res[dbkey])
                else:
                    self.assertEqual(test_data[key], res[key])

        if not self.only_db:
            # just make sure that the kwargs are valid
            # (no exception should be raised)
            stack.Stack(ctx, utils.random_name(), tmpl, **res)


class ResetStateOnErrorTest(common.HeatTestCase):
    class DummyStack(object):

        (COMPLETE, IN_PROGRESS, FAILED) = range(3)
        action = 'something'
        status = COMPLETE

        def __init__(self):
            self.state_set = mock.MagicMock()

        @stack.reset_state_on_error
        def raise_exception(self):
            self.status = self.IN_PROGRESS
            raise ValueError('oops')

        @stack.reset_state_on_error
        def raise_exit_exception(self):
            self.status = self.IN_PROGRESS
            raise BaseException('bye')

        @stack.reset_state_on_error
        def succeed(self):
            return 'Hello world'

        @stack.reset_state_on_error
        def fail(self):
            self.status = self.FAILED
            return 'Hello world'

    def test_success(self):
        dummy = self.DummyStack()

        self.assertEqual('Hello world', dummy.succeed())
        self.assertFalse(dummy.state_set.called)

    def test_failure(self):
        dummy = self.DummyStack()

        self.assertEqual('Hello world', dummy.fail())
        self.assertFalse(dummy.state_set.called)

    def test_reset_state_exception(self):
        dummy = self.DummyStack()

        exc = self.assertRaises(ValueError, dummy.raise_exception)
        self.assertIn('oops', str(exc))
        self.assertTrue(dummy.state_set.called)

    def test_reset_state_exit_exception(self):
        dummy = self.DummyStack()

        exc = self.assertRaises(BaseException, dummy.raise_exit_exception)
        self.assertIn('bye', str(exc))
        self.assertTrue(dummy.state_set.called)