-
Notifications
You must be signed in to change notification settings - Fork 172
Expand file tree
/
Copy pathtest_project.py
More file actions
2627 lines (2208 loc) · 92.6 KB
/
test_project.py
File metadata and controls
2627 lines (2208 loc) · 92.6 KB
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
# fixture and parameter have the same name
# pylint: disable=redefined-outer-name,useless-super-delegation,protected-access
# pylint: disable=too-many-lines
import json
import logging
import os
import random
import string
import sys
import zipfile
from contextlib import contextmanager
from io import StringIO
from pathlib import Path
from shutil import copyfile
from unittest.mock import ANY, MagicMock, Mock, call, patch
import pytest
import yaml
from botocore.exceptions import ClientError, WaiterError
from rpdk.core.data_loaders import resource_json, resource_stream
from rpdk.core.exceptions import (
DownstreamError,
FragmentValidationError,
InternalError,
InvalidProjectError,
SpecValidationError,
)
from rpdk.core.plugin_base import LanguagePlugin
from rpdk.core.project import (
CFN_METADATA_FILENAME,
CONFIGURATION_SCHEMA_UPLOAD_FILENAME,
OVERRIDES_FILENAME,
SCHEMA_UPLOAD_FILENAME,
SETTINGS_FILENAME,
TARGET_INFO_FILENAME,
Project,
escape_markdown,
)
from rpdk.core.test import empty_hook_override, empty_override
from rpdk.core.type_schema_loader import TypeSchemaLoader
from rpdk.core.upload import Uploader
from .utils import CONTENTS_UTF8, UnclosingBytesIO
ARTIFACT_TYPE_RESOURCE = "RESOURCE"
ARTIFACT_TYPE_MODULE = "MODULE"
ARTIFACT_TYPE_HOOK = "HOOK"
LANGUAGE = "BQHDBC"
TYPE_NAME = "AWS::Color::Red"
MODULE_TYPE_NAME = "AWS::Color::Red::MODULE"
HOOK_TYPE_NAME = "AWS::CFN::HOOK"
REGION = "us-east-1"
PROFILE = "sandbox"
ENDPOINT = "cloudformation.beta.com"
RUNTIME = random.choice(
[
"noexec", # cannot be executed, schema only
"java8",
"java11",
"go1.x",
"python3.8",
"python3.9",
"dotnetcore2.1",
"nodejs10.x",
"nodejs12.x",
"nodejs14.x",
"nodejs16.x",
]
)
BLANK_CLIENT_ERROR = {"Error": {"Code": "", "Message": ""}}
LOG = logging.getLogger(__name__)
REGISTRATION_TOKEN = "foo"
TYPE_ARN = "arn:aws:cloudformation:us-east-1:123456789012:type/resource/Foo-Bar-Foo"
TYPE_VERSION_ARN = (
"arn:aws:cloudformation:us-east-1:123456789012:type/resource/Foo-Bar-Foo/00000001"
)
DESCRIBE_TYPE_COMPLETE_RETURN = {
"TypeArn": TYPE_ARN,
"TypeVersionArn": TYPE_VERSION_ARN,
"Description": "Some detailed progress message.",
"ProgressStatus": "COMPLETE",
}
DESCRIBE_TYPE_FAILED_RETURN = {
"Description": "Some detailed progress message.",
"ProgressStatus": "FAILED",
}
CREATE_INPUTS_FILE = "inputs/inputs_1_create.json"
UPDATE_INPUTS_FILE = "inputs/inputs_1_update.json"
INVALID_INPUTS_FILE = "inputs/inputs_1_invalid.json"
PRE_CREATE_INPUTS_FILE = "inputs/inputs_1_pre_create.json"
PRE_UPDATE_INPUTS_FILE = "inputs/inputs_1_pre_update.json"
INVALID_PRE_DELETE_INPUTS_FILE = "inputs/inputs_1_invalid_pre_delete.json"
README_INPUTS_FILE = "inputs/README.md"
PLUGIN_INFORMATION = {
"plugin-version": "2.1.3",
"plugin-tool-version": "2.0.8",
"plugin-name": "java",
}
@pytest.mark.parametrize("string", ["^[a-z]$", "([a-z])", ".*", "*."])
def test_escape_markdown_with_regex_names(string):
assert escape_markdown(string).startswith("\\")
def test_escape_markdown_with_empty_string():
assert escape_markdown("") == ""
assert escape_markdown(None) is None
@pytest.mark.parametrize("string", ["Hello", "SomeProperty"])
def test_escape_markdown(string):
assert escape_markdown(string) == string
@pytest.fixture
def session():
return Mock(spec_set=["client", "region_name", "get_credentials"])
@pytest.fixture
def project(tmpdir):
unique_dir = "".join(random.choices(string.ascii_uppercase, k=12))
return Project(root=tmpdir.mkdir(unique_dir))
@contextmanager
def patch_settings(project, data):
with patch.object(project, "settings_path", autospec=True) as mock_path:
mock_path.open.return_value.__enter__.return_value = StringIO(data)
yield mock_path.open
def test_load_settings_invalid_json(project):
with patch_settings(project, "") as mock_open:
with pytest.raises(InvalidProjectError):
project.load_settings()
mock_open.assert_called_once_with("r", encoding="utf-8")
def test_load_settings_invalid_settings(project):
with patch_settings(project, "{}") as mock_open:
with pytest.raises(InvalidProjectError):
project.load_settings()
mock_open.assert_called_once_with("r", encoding="utf-8")
def test_load_settings_invalid_modules_settings(project):
with patch_settings(project, '{"artifact_type": "MODULE"}') as mock_open:
with pytest.raises(InvalidProjectError):
project.load_settings()
mock_open.assert_called_once_with("r", encoding="utf-8")
def test_load_settings_invalid_hooks_settings(project):
with patch_settings(project, '{"artifact_type": "HOOK"}') as mock_open:
with pytest.raises(InvalidProjectError):
project.load_settings()
mock_open.assert_called_once_with("r", encoding="utf-8")
def test_load_settings_valid_json_for_resource(project):
plugin = object()
data = json.dumps(
{
"artifact_type": "RESOURCE",
"typeName": TYPE_NAME,
"language": LANGUAGE,
"runtime": RUNTIME,
"entrypoint": None,
"testEntrypoint": None,
"futureProperty": "value",
}
)
patch_load = patch(
"rpdk.core.project.load_plugin", autospec=True, return_value=plugin
)
with patch_settings(project, data) as mock_open, patch_load as mock_load:
project.load_settings()
mock_open.assert_called_once_with("r", encoding="utf-8")
mock_load.assert_called_once_with(LANGUAGE)
assert project.type_info == ("AWS", "Color", "Red")
assert project.type_name == TYPE_NAME
assert project.language == LANGUAGE
assert project.artifact_type == ARTIFACT_TYPE_RESOURCE
assert project._plugin is plugin
assert project.settings == {}
def test_load_settings_valid_json_for_resource_backward_compatible(project):
plugin = object()
data = json.dumps(
{
"typeName": TYPE_NAME,
"language": LANGUAGE,
"runtime": RUNTIME,
"entrypoint": None,
"testEntrypoint": None,
}
)
patch_load = patch(
"rpdk.core.project.load_plugin", autospec=True, return_value=plugin
)
with patch_settings(project, data) as mock_open, patch_load as mock_load:
project.load_settings()
mock_open.assert_called_once_with("r", encoding="utf-8")
mock_load.assert_called_once_with(LANGUAGE)
assert project.type_info == ("AWS", "Color", "Red")
assert project.type_name == TYPE_NAME
assert project.language == LANGUAGE
assert project.artifact_type == ARTIFACT_TYPE_RESOURCE
assert project._plugin is plugin
assert project.settings == {}
def test_load_settings_valid_json_for_module(project):
plugin = object()
data = json.dumps(
{
"artifact_type": "MODULE",
"typeName": MODULE_TYPE_NAME,
}
)
patch_load = patch(
"rpdk.core.project.load_plugin", autospec=True, return_value=plugin
)
with patch_settings(project, data) as mock_open, patch_load as mock_load:
project.load_settings()
mock_open.assert_called_once_with("r", encoding="utf-8")
mock_load.assert_not_called()
assert project.type_info == ("AWS", "Color", "Red", "MODULE")
assert project.type_name == MODULE_TYPE_NAME
assert project.language is None
assert project.artifact_type == ARTIFACT_TYPE_MODULE
assert project._plugin is None
assert project.settings == {}
def test_generate_for_modules_succeeds(project):
project.type_info = ("AWS", "Color", "Red", "MODULE")
project.artifact_type = ARTIFACT_TYPE_MODULE
project.generate()
project.generate_docs()
def test_load_settings_valid_json_for_hook(project):
plugin = object()
data = json.dumps(
{
"artifact_type": "HOOK",
"typeName": HOOK_TYPE_NAME,
"language": LANGUAGE,
"runtime": RUNTIME,
"entrypoint": None,
"testEntrypoint": None,
}
)
patch_load = patch(
"rpdk.core.project.load_plugin", autospec=True, return_value=plugin
)
with patch_settings(project, data) as mock_open, patch_load as mock_load:
project.load_settings()
mock_open.assert_called_once_with("r", encoding="utf-8")
mock_load.assert_called_once_with(LANGUAGE)
assert project.type_info == ("AWS", "CFN", "HOOK")
assert project.type_name == HOOK_TYPE_NAME
assert project.language == LANGUAGE
assert project.artifact_type == ARTIFACT_TYPE_HOOK
assert project._plugin is plugin
assert project.settings == {}
def test_load_schema_settings_not_loaded(project):
with pytest.raises(InternalError):
project.load_schema()
def test_load_hook_schema_settings_not_loaded(project):
with pytest.raises(InternalError):
project.load_hook_schema()
def test_load_schema_example(project):
project.type_name = "AWS::Color::Blue"
project._write_example_schema()
project.load_schema()
def test_load_configuration_schema_schema_not_loaded(project):
with pytest.raises(InternalError):
project.load_configuration_schema()
def test_load_configuration_schema():
schema_path = str(Path.cwd() / "tests/data/schema/valid")
project = Project(root=schema_path)
project.type_info = ("test", "schema", "validtypeconfiguration")
project.load_schema()
project.load_configuration_schema()
assert project.configuration_schema is not None
def test_load_schema_without_type_configuration():
schema_path = str(Path.cwd() / "tests/data/schema/valid")
project = Project(root=schema_path)
project.type_info = ("test", "schema", "without", "typeconfiguration")
project.load_schema()
project.load_configuration_schema()
assert project.configuration_schema is None
def test_write_configuration_schema():
mock_path = MagicMock(spec=Path)
project = Project(root=mock_path)
project.type_info = ("test", "validTypeConfiguration")
project.write_configuration_schema(mock_path)
mock_path.open.assert_called_once_with("w", encoding="utf-8")
mock_f = mock_path.open.return_value.__enter__.return_value
mock_f.write.assert_has_calls([call("null"), call("\n")])
def test_configuration_schema_filename(project):
project.type_name = "Vendor::Service::Type"
assert (
project.configuration_schema_filename
== "vendor-service-type-configuration.json"
)
def test_load_schema_with_typeconfiguration(project):
patch_settings = patch.object(project, "load_settings")
patch_schema = patch.object(project, "load_schema")
patch_configuration_schema = patch.object(project, "load_configuration_schema")
with patch_settings as mock_settings, patch_schema as mock_schema, patch_configuration_schema as mock_configuration_schema:
project.load()
mock_settings.assert_called_once_with()
mock_schema.assert_called_once_with()
mock_configuration_schema.assert_called_once_with()
def test_overwrite():
mock_path = MagicMock(spec=Path)
Project.overwrite(mock_path, LANGUAGE)
mock_path.open.assert_called_once_with("w", encoding="utf-8")
mock_f = mock_path.open.return_value.__enter__.return_value
mock_f.write.assert_called_once_with(LANGUAGE)
def test_safewrite_overwrite(project):
path = object()
contents = object()
patch_attr = patch.object(project, "overwrite_enabled", True)
patch_meth = patch.object(project, "overwrite", autospec=True)
with patch_attr, patch_meth as mock_overwrite:
project.safewrite(path, contents)
mock_overwrite.assert_called_once_with(path, contents)
def test_safewrite_doesnt_exist(project, tmpdir):
path = Path(tmpdir.join("test")).resolve()
with patch.object(project, "overwrite_enabled", False):
project.safewrite(path, CONTENTS_UTF8)
with path.open("r", encoding="utf-8") as f:
assert f.read() == CONTENTS_UTF8
def test_safewrite_exists(project, tmpdir, caplog):
caplog.set_level(logging.INFO)
path = Path(tmpdir.join("test")).resolve()
with path.open("w", encoding="utf-8") as f:
f.write(CONTENTS_UTF8)
with patch.object(project, "overwrite_enabled", False):
project.safewrite(path, CONTENTS_UTF8)
last_record = caplog.records[-1]
assert last_record.levelname == "INFO"
assert str(path) in last_record.message
def test_generate_no_handlers(project):
project.schema = {}
mock_plugin = MagicMock(spec=["generate"])
with patch.object(project, "_plugin", mock_plugin):
project.generate()
project.generate_docs()
mock_plugin.generate.assert_called_once_with(project)
@pytest.mark.parametrize(
"schema_path,path",
[
("data/schema/valid/valid_no_type.json", "generate_with_no_type_defined"),
(
"data/schema/valid/valid_type_complex.json",
"generate_with_docs_type_complex",
),
(
"data/schema/valid/valid_pattern_properties.json",
"generate_with_docs_pattern_properties",
),
(
"data/schema/valid/valid_no_properties.json",
"generate_with_docs_no_properties",
),
(
"data/schema/valid/valid_nested_property_object.json",
"generate_with_docs_nested_object",
),
(
"data/schema/valid/valid_type_composite_primary_identifier.json",
"generate_with_docs_composite_primary_identifier",
),
],
)
def test_generate_with_docs(project, tmp_path_factory, schema_path, path):
project.schema = resource_json(__name__, schema_path)
project.type_name = "AWS::Color::Red"
# tmpdir conflicts with other tests, make a unique one
project.root = tmp_path_factory.mktemp(path)
mock_plugin = MagicMock(spec=["generate"])
with patch.object(project, "_plugin", mock_plugin):
project.generate()
project.generate_docs()
mock_plugin.generate.assert_called_once_with(project)
docs_dir = project.root / "docs"
readme_file = project.root / "docs" / "README.md"
assert docs_dir.is_dir()
assert readme_file.is_file()
with patch.object(project, "_plugin", mock_plugin):
project.generate()
readme_contents = readme_file.read_text(encoding="utf-8")
assert project.type_name in readme_contents
@pytest.mark.parametrize(
"schema_path,path",
[
(
"data/schema/hook/valid/valid_hook_configuration.json",
"generate_docs_with_one_property",
),
(
"data/schema/hook/valid/valid_hook_configuration_multiple_properties.json",
"generate_docs_with_multiple_properties",
),
(
"data/schema/hook/valid/valid_hook_configuration_no_properties.json",
"generate_docs_with_no_properties",
),
(
"data/schema/hook/valid/valid_hook_configuration_with_object_property.json",
"generate_docs_with_object_property",
),
(
"data/schema/hook/valid/valid_hook_configuration_with_nested_property.json",
"generate_docs_with_nested_property",
),
(
"data/schema/hook/valid/valid_hook_configuration_with_complex_properties.json",
"generate_docs_with_complex_properties",
),
],
)
def test_generate_docs_for_hook(project, tmp_path_factory, session, schema_path, path):
project.schema = resource_json(__name__, schema_path)
project.type_name = "AWS::FooBar::Hook"
project.artifact_type = ARTIFACT_TYPE_HOOK
project.load_configuration_schema()
# tmpdir conflicts with other tests, make a unique one
project.root = tmp_path_factory.mktemp(path)
mock_plugin = MagicMock(spec=["generate"])
patch_session = patch("rpdk.core.boto_helpers.Boto3Session")
def get_test_schema():
return {
"typeName": "AWS::S3::Bucket",
"description": "test schema",
"properties": {"foo": {"type": "string"}},
"primaryIdentifier": ["/properties/foo"],
"additionalProperties": False,
}
mock_cfn_client = MagicMock(spec=["describe_type"])
with patch.object(project, "_plugin", mock_plugin), patch_session as mock_session:
mock_cfn_client.describe_type.return_value = {
"Schema": json.dumps(get_test_schema()),
"Type": "",
"ProvisioningType": "",
}
session.client.side_effect = [mock_cfn_client, MagicMock()]
mock_session.return_value = session
project.generate()
project.generate_docs()
mock_plugin.generate.assert_called_once_with(project)
docs_dir = project.root / "docs"
readme_file = project.root / "docs" / "README.md"
assert docs_dir.is_dir()
assert readme_file.is_file()
with patch.object(project, "_plugin", mock_plugin), patch_session as mock_session:
session.client.side_effect = [mock_cfn_client, MagicMock()]
mock_session.return_value = session
project.generate()
readme_contents = readme_file.read_text(encoding="utf-8")
assert project.type_name in readme_contents
def test_generate_docs_with_multityped_property(project, tmp_path_factory, session):
project.schema = resource_json(
__name__, "data/schema/valid/valid_multityped_property.json"
)
project.type_name = "AWS::Color::Red"
# tmpdir conflicts with other tests, make a unique one
project.root = tmp_path_factory.mktemp("generate_with_docs_type_complex")
mock_plugin = MagicMock(spec=["generate"])
patch_session = patch("rpdk.core.boto_helpers.Boto3Session")
with patch.object(project, "_plugin", mock_plugin), patch_session as mock_session:
mock_session.return_value = session
project.generate()
project.generate_docs()
mock_plugin.generate.assert_called_once_with(project)
docs_dir = project.root / "docs"
readme_file = project.root / "docs" / "README.md"
assert docs_dir.is_dir()
assert readme_file.is_file()
with patch.object(project, "_plugin", mock_plugin):
project.generate()
readme_contents = readme_file.read_text(encoding="utf-8")
readme_contents_target = resource_stream(
__name__, "data/schema/target_output/multityped.md"
)
read_me_stripped = readme_contents.strip().replace(" ", "")
read_me_target_stripped = readme_contents_target.read().strip().replace(" ", "")
LOG.debug("read_me_stripped %s", read_me_stripped)
LOG.debug("read_me_target_stripped %s", read_me_target_stripped)
assert project.type_name in readme_contents
assert read_me_stripped == read_me_target_stripped
def test_generate_docs_with_multiref_property(project, tmp_path_factory):
project.schema = resource_json(
__name__, "data/schema/valid/valid_multiref_property.json"
)
project.type_name = "AWS::Color::Red"
# tmpdir conflicts with other tests, make a unique one
project.root = tmp_path_factory.mktemp("generate_with_docs_type_complex")
mock_plugin = MagicMock(spec=["generate"])
with patch.object(project, "_plugin", mock_plugin):
project.generate()
project.generate_docs()
mock_plugin.generate.assert_called_once_with(project)
docs_dir = project.root / "docs"
readme_file = project.root / "docs" / "README.md"
assert docs_dir.is_dir()
assert readme_file.is_file()
with patch.object(project, "_plugin", mock_plugin):
project.generate()
readme_contents = readme_file.read_text(encoding="utf-8")
readme_contents_target = resource_stream(
__name__, "data/schema/target_output/multiref.md"
)
read_me_stripped = readme_contents.strip().replace(" ", "")
read_me_target_stripped = readme_contents_target.read().strip().replace(" ", "")
LOG.debug("read_me_stripped %s", read_me_stripped)
LOG.debug("read_me_target_stripped %s", read_me_target_stripped)
assert project.type_name in readme_contents
assert read_me_stripped == read_me_target_stripped
def test_generate_with_docs_invalid_property_type(project, tmp_path_factory):
project.schema = resource_json(
__name__, "data/schema/invalid/invalid_property_type_invalid.json"
)
project.type_name = "AWS::Color::Red"
# tmpdir conflicts with other tests, make a unique one
project.root = tmp_path_factory.mktemp("generate_with_docs_invalid_property_type")
mock_plugin = MagicMock(spec=["generate"])
with patch.object(project, "_plugin", mock_plugin):
# skip actual generation
project.generate_docs()
docs_dir = project.root / "docs"
readme_file = project.root / "docs" / "README.md"
assert docs_dir.is_dir()
assert readme_file.is_file()
with patch.object(project, "_plugin", mock_plugin):
project.generate()
project.generate_docs()
readme_contents = readme_file.read_text(encoding="utf-8")
assert project.type_name in readme_contents
def test_generate_with_docs_no_type(project, tmp_path_factory):
project.schema = {"properties": {}}
# tmpdir conflicts with other tests, make a unique one
project.root = tmp_path_factory.mktemp("generate_with_docs_no_type")
mock_plugin = MagicMock(spec=["generate"])
with patch.object(project, "_plugin", mock_plugin):
project.generate()
project.generate_docs()
mock_plugin.generate.assert_called_once_with(project)
docs_dir = project.root / "docs"
assert not docs_dir.is_dir()
def test_generate_with_docs_twice(project, tmp_path_factory):
project.schema = {"properties": {}}
project.type_name = "AWS::Color::Red"
# tmpdir conflicts with other tests, make a unique one
project.root = tmp_path_factory.mktemp("generate_with_docs_twice")
mock_plugin = MagicMock(spec=["generate"])
with patch.object(project, "_plugin", mock_plugin):
project.generate()
project.generate_docs()
mock_plugin.generate.assert_called_once_with(project)
docs_dir = project.root / "docs"
readme_file = docs_dir / "README.md"
assert docs_dir.is_dir()
assert readme_file.is_file()
with patch.object(project, "_plugin", mock_plugin):
project.generate()
project.generate_docs()
assert docs_dir.is_dir()
assert readme_file.is_file()
with patch.object(project, "_plugin", mock_plugin):
project.generate()
project.generate_docs()
readme_contents = readme_file.read_text(encoding="utf-8")
assert project.type_name in readme_contents
def test_generate_handlers(project, tmpdir):
project.type_name = "Test::Handler::Test"
expected_actions = {"createAction", "readAction"}
project.schema = {
"handlers": {
"create": {"permissions": ["createAction", "readAction"]},
"read": {"permissions": ["readAction", ""]},
}
}
project.root = tmpdir
mock_plugin = MagicMock(spec=["generate"])
with patch.object(project, "_plugin", mock_plugin):
project.generate()
role_path = project.root / "resource-role.yaml"
with role_path.open("r", encoding="utf-8") as f:
template = yaml.safe_load(f.read())
action_list = template["Resources"]["ExecutionRole"]["Properties"]["Policies"][0][
"PolicyDocument"
]["Statement"][0]["Action"]
assert all(action in expected_actions for action in action_list)
assert len(action_list) == len(expected_actions)
assert template["Outputs"]["ExecutionRoleArn"]
mock_plugin.generate.assert_called_once_with(project)
@pytest.mark.parametrize(
"schema",
({"handlers": {"create": {"permissions": [""]}}}, {"handlers": {"create": {}}}),
)
def test_generate_handlers_deny_all(project, tmpdir, schema):
project.type_name = "Test::Handler::Test"
project.schema = schema
project.root = tmpdir
mock_plugin = MagicMock(spec=["generate"])
with patch.object(project, "_plugin", mock_plugin):
project.generate()
role_path = project.root / "resource-role.yaml"
with role_path.open("r", encoding="utf-8") as f:
template = yaml.safe_load(f.read())
statement = template["Resources"]["ExecutionRole"]["Properties"]["Policies"][0][
"PolicyDocument"
]["Statement"][0]
assert statement["Effect"] == "Deny"
assert statement["Action"][0] == "*"
mock_plugin.generate.assert_called_once_with(project)
@pytest.mark.parametrize(
"schema,result",
(
({"handlers": {"create": {"timeoutInMinutes": 720}}}, 43200),
({"handlers": {"create": {"timeoutInMinutes": 2}}}, 3600),
({"handlers": {"create": {"timeoutInMinutes": 90}}}, 6300),
(
{
"handlers": {
"create": {"timeoutInMinutes": 70},
"update": {"timeoutInMinutes": 90},
}
},
6300,
),
({"handlers": {"create": {}}}, 8400),
({"handlers": {"create": {"timeoutInMinutes": 90}, "read": {}}}, 8400),
),
)
def test_generate_handlers_role_session_timeout(project, tmpdir, schema, result):
project.type_name = "Test::Handler::Test"
project.schema = schema
project.root = tmpdir
mock_plugin = MagicMock(spec=["generate"])
with patch.object(project, "_plugin", mock_plugin):
project.generate()
role_path = project.root / "resource-role.yaml"
with role_path.open("r", encoding="utf-8") as f:
template = yaml.safe_load(f.read())
max_session_timeout = template["Resources"]["ExecutionRole"]["Properties"][
"MaxSessionDuration"
]
assert max_session_timeout == result
mock_plugin.generate.assert_called_once_with(project)
def test_init_resource(project):
type_name = "AWS::Color::Red"
mock_plugin = MagicMock(spec=["init"])
patch_load_plugin = patch(
"rpdk.core.project.load_plugin", autospec=True, return_value=mock_plugin
)
with patch_load_plugin as mock_load_plugin:
project.init(type_name, LANGUAGE)
mock_load_plugin.assert_called_once_with(LANGUAGE)
mock_plugin.init.assert_called_once_with(project)
assert project.type_info == ("AWS", "Color", "Red")
assert project.type_name == type_name
assert project.language == LANGUAGE
assert project.artifact_type == ARTIFACT_TYPE_RESOURCE
assert project._plugin is mock_plugin
assert project.settings == {}
with project.settings_path.open("r", encoding="utf-8") as f:
assert json.load(f)
# ends with newline
with project.settings_path.open("rb") as f:
f.seek(-1, os.SEEK_END)
assert f.read() == b"\n"
with project.schema_path.open("r", encoding="utf-8") as f:
assert json.load(f)
for file_inputs in (
"inputs_1_create.json",
"inputs_1_update.json",
"inputs_1_invalid.json",
):
path_file = project.example_inputs_path / file_inputs
with path_file.open("r", encoding="utf-8") as f:
assert json.load(f)
# ends with newline
with project.schema_path.open("rb") as f:
f.seek(-1, os.SEEK_END)
assert f.read() == b"\n"
def test_generate_hook_handlers(project, tmpdir, session):
project.type_name = "Test::Handler::Test"
project.artifact_type = ARTIFACT_TYPE_HOOK
expected_actions = {"preCreateAction", "preDeleteAction"}
project.schema = {
"handlers": {
"preCreate": {"permissions": ["preCreateAction", "preDeleteAction"]},
"preDelete": {"permissions": ["preDeleteAction", ""]},
}
}
project.root = tmpdir
mock_plugin = MagicMock(spec=["generate"])
patch_session = patch_session = patch("rpdk.core.boto_helpers.Boto3Session")
with patch.object(project, "_plugin", mock_plugin), patch_session as mock_session:
mock_session.return_value = session
project.generate()
role_path = project.root / "hook-role.yaml"
with role_path.open("r", encoding="utf-8") as f:
template = yaml.safe_load(f.read())
action_list = template["Resources"]["ExecutionRole"]["Properties"]["Policies"][0][
"PolicyDocument"
]["Statement"][0]["Action"]
assert all(action in expected_actions for action in action_list)
assert len(action_list) == len(expected_actions)
assert template["Outputs"]["ExecutionRoleArn"]
mock_plugin.generate.assert_called_once_with(project)
@pytest.mark.parametrize(
"schema",
(
{"handlers": {"preCreate": {"permissions": [""]}}},
{"handlers": {"preCreate": {}}},
),
)
def test_generate_hook_handlers_deny_all(project, tmpdir, schema):
project.type_name = "Test::Handler::Test"
project.artifact_type = ARTIFACT_TYPE_HOOK
project.schema = schema
project.root = tmpdir
mock_plugin = MagicMock(spec=["generate"])
with patch.object(project, "_plugin", mock_plugin), patch(
"rpdk.core.boto_helpers.Boto3Session"
) as session:
session.return_value = session()
project.generate()
role_path = project.root / "hook-role.yaml"
with role_path.open("r", encoding="utf-8") as f:
template = yaml.safe_load(f.read())
statement = template["Resources"]["ExecutionRole"]["Properties"]["Policies"][0][
"PolicyDocument"
]["Statement"][0]
assert statement["Effect"] == "Deny"
assert statement["Action"][0] == "*"
mock_plugin.generate.assert_called_once_with(project)
@pytest.mark.parametrize(
"schema,result",
(
({"handlers": {"preCreate": {"timeoutInMinutes": 720}}}, 43200),
({"handlers": {"preCreate": {"timeoutInMinutes": 2}}}, 3600),
({"handlers": {"preCreate": {"timeoutInMinutes": 90}}}, 6300),
(
{
"handlers": {
"preCreate": {"timeoutInMinutes": 70},
"preUpdate": {"timeoutInMinutes": 90},
}
},
6300,
),
({"handlers": {"preCreate": {}}}, 8400),
({"handlers": {"preCreate": {"timeoutInMinutes": 90}, "preDelete": {}}}, 8400),
),
)
def test_generate__hook_handlers_role_session_timeout(
project, tmpdir, schema, result, session
):
project.type_name = "Test::Handler::Test"
project.artifact_type = ARTIFACT_TYPE_HOOK
project.schema = schema
project.root = tmpdir
mock_plugin = MagicMock(spec=["generate"])
patch_session = patch("rpdk.core.boto_helpers.Boto3Session")
with patch.object(project, "_plugin", mock_plugin), patch_session as mock_session:
mock_session.return_value = session
project.generate()
role_path = project.root / "hook-role.yaml"
with role_path.open("r", encoding="utf-8") as f:
template = yaml.safe_load(f.read())
max_session_timeout = template["Resources"]["ExecutionRole"]["Properties"][
"MaxSessionDuration"
]
assert max_session_timeout == result
mock_plugin.generate.assert_called_once_with(project)
def test_init_hook(project):
type_name = "AWS::CFN::HOOK"
mock_plugin = MagicMock(spec=["init"])
patch_load_plugin = patch(
"rpdk.core.project.load_plugin", autospec=True, return_value=mock_plugin
)
with patch_load_plugin as mock_load_plugin:
project.init_hook(type_name, LANGUAGE)
mock_load_plugin.assert_called_once_with(LANGUAGE)
mock_plugin.init.assert_called_once_with(project)
assert project.type_info == ("AWS", "CFN", "HOOK")
assert project.type_name == type_name
assert project.language == LANGUAGE
assert project.artifact_type == ARTIFACT_TYPE_HOOK
assert project._plugin is mock_plugin
assert project.settings == {}
with project.settings_path.open("r", encoding="utf-8") as f:
assert json.load(f)
# ends with newline
with project.settings_path.open("rb") as f:
f.seek(-1, os.SEEK_END)
assert f.read() == b"\n"
with project.schema_path.open("r", encoding="utf-8") as f:
assert json.load(f)
# ends with newline
with project.schema_path.open("rb") as f:
f.seek(-1, os.SEEK_END)
assert f.read() == b"\n"
def test_init_module(project):
type_name = "AWS::Color::Red"
mock_plugin = MagicMock(spec=["init"])
patch_load_plugin = patch(
"rpdk.core.project.load_plugin", autospec=True, return_value=mock_plugin
)
with patch_load_plugin as mock_load_plugin:
project.init_module(type_name)
mock_load_plugin.assert_not_called()
mock_plugin.init.assert_not_called()
assert project.type_info == ("AWS", "Color", "Red")
assert project.type_name == type_name
assert project.language is None
assert project.artifact_type == ARTIFACT_TYPE_MODULE
assert project._plugin is None
assert project.settings == {}
with project.settings_path.open("r", encoding="utf-8") as f:
assert json.load(f)
# ends with newline
with project.settings_path.open("rb") as f:
f.seek(-1, os.SEEK_END)
assert f.read() == b"\n"
def test_load_invalid_schema(project):
patch_settings = patch.object(project, "load_settings")
patch_schema = patch.object(
project, "load_schema", side_effect=SpecValidationError("")
)
with patch_settings as mock_settings, patch_schema as mock_schema, pytest.raises(
InvalidProjectError
) as excinfo:
project.load()
mock_settings.assert_called_once_with()
mock_schema.assert_called_once_with()
assert "invalid" in str(excinfo.value)
def test_load_invalid_hook_schema(project):