-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_codegen.py
More file actions
614 lines (473 loc) · 19.8 KB
/
Copy pathtest_codegen.py
File metadata and controls
614 lines (473 loc) · 19.8 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
# fixture and parameter have the same name
# pylint: disable=redefined-outer-name,protected-access
import xml.etree.ElementTree as ET
from pathlib import Path
from shutil import copyfile
from unittest.mock import MagicMock, Mock, patch
import yaml
import pytest
from rpdk.core.exceptions import InternalError, SysExitRecommendedError
from rpdk.core.project import Project
from rpdk.java.__init__ import __version__
from rpdk.java.codegen import (
InvalidMavenPOMError,
JavaArchiveNotFoundError,
JavaLanguagePlugin,
JavaPluginNotFoundError,
JavaPluginVersionNotSupportedError,
)
RESOURCE = "DZQWCC"
HOOK = "CCWQZD"
TEST_TARGET_INFO = {
"My::Example::Resource": {
"TargetName": "My::Example::Resource",
"TargetType": "RESOURCE",
"Schema": {
"typeName": "My::Example::Resource",
"additionalProperties": False,
"properties": {
"Id": {"type": "string"},
"Tags": {
"type": "array",
"uniqueItems": False,
"items": {"$ref": "#/definitions/Tag"},
},
},
"required": [],
"definitions": {
"Tag": {
"type": "object",
"additionalProperties": False,
"properties": {
"Value": {"type": "string"},
"Key": {"type": "string"},
},
"required": ["Value", "Key"],
}
},
},
"ProvisioningType": "FULLY_MUTTABLE",
"IsCfnRegistrySupportedType": True,
"SchemaFileAvailable": True,
},
"My::Other::Resource": {
"TargetName": "My::Other::Resource",
"TargetType": "RESOURCE",
"Schema": {
"typeName": "My::Other::Resource",
"additionalProperties": False,
"properties": {
"Id": {"type": "string"},
"Tags": {
"type": "array",
"uniqueItems": False,
"items": {"$ref": "#/definitions/Tag"},
},
},
"required": [],
"definitions": {
"Tag": {
"type": "object",
"additionalProperties": False,
"properties": {
"Value": {"type": "string"},
"Key": {"type": "string"},
},
"required": ["Value", "Key"],
}
},
},
"ProvisioningType": "NOT_PROVISIONABLE",
"IsCfnRegistrySupportedType": False,
"SchemaFileAvailable": True,
},
}
@pytest.fixture(params=["1", "2"])
def project(tmpdir, request):
def mock_input_with_validation(prompt, validate): # pylint: disable=unused-argument
if prompt.startswith("Enter a package name"):
return ("software", "amazon", "foo", RESOURCE.lower())
if prompt.startswith("Choose codegen model"):
return request.param
return ""
project = Project(root=tmpdir)
mock_cli = MagicMock(side_effect=mock_input_with_validation)
with patch.dict(
"rpdk.core.plugin_registry.PLUGIN_REGISTRY",
{"test": lambda: JavaLanguagePlugin},
clear=True,
), patch("rpdk.java.codegen.input_with_validation", new=mock_cli):
project.init(f"AWS::Foo::{RESOURCE}", "test")
return project
@pytest.fixture(params=["1", "2"])
def hook_project(tmpdir, request):
def mock_input_with_validation(prompt, validate): # pylint: disable=unused-argument
if prompt.startswith("Enter a package name"):
return ("software", "amazon", "foo", HOOK.lower())
if prompt.startswith("Choose codegen model"):
return request.param
return ""
hook_project = Project(root=tmpdir)
mock_cli = MagicMock(side_effect=mock_input_with_validation)
with patch.dict(
"rpdk.core.plugin_registry.PLUGIN_REGISTRY",
{"test": lambda: JavaLanguagePlugin},
clear=True,
), patch("rpdk.java.codegen.input_with_validation", new=mock_cli):
hook_project.init_hook(f"AWS::Foo::{RESOURCE}", "test")
return hook_project
def test_java_language_plugin_module_is_set():
plugin = JavaLanguagePlugin()
assert plugin.MODULE_NAME
def test_initialize(project):
expected_group_id = f"software.amazon.foo.{RESOURCE.lower()}"
handler = f"{expected_group_id}.HandlerWrapper::handleRequest"
assert_test_initialize(project, handler, expected_group_id)
def test_hook_initialize(hook_project):
expected_group_id = f"software.amazon.foo.{HOOK.lower()}"
handler = f"{expected_group_id}.HookHandlerWrapper::handleRequest"
assert_test_initialize(hook_project, handler, expected_group_id)
def assert_test_initialize(
test_project, handler, expected_group_id
): # pylint: disable=protected-access
assert (test_project.root / "README.md").is_file()
pom_tree = ET.parse(str(test_project.root / "pom.xml"))
namespace = {"maven": "http://maven.apache.org/POM/4.0.0"}
actual_group_id = pom_tree.find("maven:groupId", namespace)
assert actual_group_id.text == expected_group_id
path = test_project.root / "template.yml"
with path.open("r", encoding="utf-8") as f:
template = yaml.safe_load(f)
handler_properties = template["Resources"]["TypeFunction"]["Properties"]
code_uri = f"./target/{test_project.hypenated_name}-handler-1.0-SNAPSHOT.jar"
assert handler_properties["CodeUri"] == code_uri
assert handler_properties["Handler"] == handler
assert handler_properties["Runtime"] == test_project._plugin.RUNTIME
def test_generate(project):
project.load_schema()
assert_generate_test(project, RESOURCE)
def test_hook_generate(hook_project):
with patch.object(hook_project, "_load_target_info", return_value=TEST_TARGET_INFO):
hook_project.load_hook_schema()
assert_generate_test(hook_project, HOOK)
def assert_generate_test(test_project, test_type): # pylint: disable=protected-access
generated_root = test_project._plugin._get_generated_root(test_project)
generated_tests_root = test_project._plugin._get_generated_tests_root(test_project)
# generated root shouldn't be present
assert not generated_root.is_dir()
assert not generated_tests_root.is_dir()
test_project.generate()
src_file = generated_root / "test"
src_file.touch()
test_file = generated_tests_root / "test"
test_file.touch()
test_project.generate()
# assert TypeConfigurationModel is added to generated directory
type_configuration_model_file = (
generated_root
/ "software"
/ "amazon"
/ "foo"
/ test_type.lower()
/ "TypeConfigurationModel.java"
)
assert type_configuration_model_file.is_file()
# asserts we remove existing files in the tree
assert not src_file.is_file()
assert not test_file.is_file()
def test_generate_with_type_configuration(project, tmpdir):
copyfile(
str(Path.cwd() / "tests/data/schema-with-typeconfiguration.json"),
str(tmpdir / "schema-with-typeconfiguration.json"),
)
project.type_info = ("schema", "with", "typeconfiguration")
project.load_schema()
project.load_configuration_schema()
project.generate()
generated_root = project._plugin._get_generated_root(project)
# assert TypeConfigurationModel is added to generated directory
type_configuration_model_file = (
generated_root
/ "software"
/ "amazon"
/ "foo"
/ RESOURCE.lower()
/ "TypeConfigurationModel.java"
)
type_configuration_schema_file = (
generated_root / "schema-with-typeconfiguration-configuration.json"
)
assert type_configuration_model_file.is_file()
assert type_configuration_schema_file.is_file()
def test_generate_with_out_type_configuration(project, tmpdir):
copyfile(
str(Path.cwd() / "tests/data/schema-without-typeconfiguration.json"),
str(tmpdir / "schema-without-typeconfiguration.json"),
)
project.type_info = ("schema", "without", "typeconfiguration")
project.load_schema()
project.load_configuration_schema()
project.generate()
generated_root = project._plugin._get_generated_root(project)
# assert TypeConfigurationModel is added to generated directory
type_configuration_model_file = (
generated_root
/ "software"
/ "amazon"
/ "foo"
/ RESOURCE.lower()
/ "TypeConfigurationModel.java"
)
type_configuration_schema_file = (
generated_root / "schema-without-typeconfiguration-configuration.json"
)
assert type_configuration_model_file.is_file()
assert not type_configuration_schema_file.is_file()
def test_hook_generate_with_type_configuration(hook_project, tmpdir):
copyfile(
str(Path.cwd() / "tests/data/hook-schema-with-typeconfiguration.json"),
str(tmpdir / "hook-schema-with-typeconfiguration.json"),
)
with patch.object(hook_project, "_load_target_info", return_value=TEST_TARGET_INFO):
hook_project.type_info = ("hook", "schema", "with", "typeconfiguration")
hook_project.load_hook_schema()
hook_project.load_configuration_schema()
hook_project.generate()
generated_root = hook_project._plugin._get_generated_root(hook_project)
# assert TypeConfigurationModel is added to generated directory
type_configuration_model_file = (
generated_root
/ "software"
/ "amazon"
/ "foo"
/ HOOK.lower()
/ "TypeConfigurationModel.java"
)
type_configuration_schema_file = (
generated_root / "hook-schema-with-typeconfiguration-configuration.json"
)
assert type_configuration_model_file.is_file()
assert type_configuration_schema_file.is_file()
def test_hook_generate_with_non_registry_targets(hook_project, tmpdir):
copyfile(
str(Path.cwd() / "tests/data/hook-schema-with-typeconfiguration.json"),
str(tmpdir / "hook-schema-with-typeconfiguration.json"),
)
test_target_info = dict(TEST_TARGET_INFO)
test_target_info["My::Unreleased::Resource"] = {
"TargetName": "My::Unreleased::Resource",
"TargetType": "RESOURCE",
"Schema": {},
"ProvisioningType": "NOT_PROVISIONABLE",
"IsCfnRegistrySupportedType": False,
"SchemaFileAvailable": False,
}
with patch.object(hook_project, "_load_target_info", return_value=test_target_info):
hook_project.type_info = ("hook", "schema", "with", "typeconfiguration")
hook_project.load_hook_schema()
hook_project.load_configuration_schema()
hook_project.generate()
generated_root = hook_project._plugin._get_generated_root(hook_project)
# assert TypeConfigurationModel is added to generated directory
non_registry_target_model_file = (
generated_root
/ "software"
/ "amazon"
/ "foo"
/ HOOK.lower()
/ "model"
/ "my"
/ "unreleased"
/ "resource"
/ "MyUnreleasedResourceTargetModel.java"
)
assert non_registry_target_model_file.is_file()
def test_protocol_version_is_set(project):
assert project.settings["protocolVersion"] == "2.0.0"
def test_generate_low_protocol_version_is_updated(project):
project.settings["protocolVersion"] = "1.0.0"
project.generate()
assert project.settings["protocolVersion"] == "2.0.0"
def update_pom_with_plugin_version(project, version_id):
pom_tree = ET.parse(project.root / "pom.xml")
root = pom_tree.getroot()
namespace = {"mvn": "http://maven.apache.org/POM/4.0.0"}
version = root.find(
"./mvn:dependencies/mvn:dependency"
"/[mvn:artifactId='aws-cloudformation-rpdk-java-plugin']/mvn:version",
namespace,
)
version.text = version_id
pom_tree.write(project.root / "pom.xml")
def test_generate_with_not_support_version(project):
update_pom_with_plugin_version(project, "1.0.0")
with pytest.raises(JavaPluginVersionNotSupportedError):
project.generate()
def make_target(project, count):
target = project.root / "target"
target.mkdir(exist_ok=True)
jar_paths = []
for i in range(count):
jar_path = target / f"{project.hypenated_name}-{i}.0-SNAPSHOT.jar"
jar_path.touch()
jar_paths.append(jar_path)
return jar_paths
def test__find_jar_zero(project):
make_target(project, 0)
with pytest.raises(JavaArchiveNotFoundError) as excinfo:
project._plugin._find_jar(project)
assert isinstance(excinfo.value, SysExitRecommendedError)
def test__find_jar_one(project):
jar_path, *_ = make_target(project, 1)
assert project._plugin._find_jar(project) == jar_path
def test__find_jar_two(project):
make_target(project, 2)
with pytest.raises(InternalError):
project._plugin._find_jar(project)
def make_pom_xml_without_plugin(project):
pom_tree = ET.parse(project.root / "pom.xml")
root = pom_tree.getroot()
namespace = {"mvn": "http://maven.apache.org/POM/4.0.0"}
plugin = root.find(
".//mvn:dependency/[mvn:artifactId='aws-cloudformation-rpdk-java-plugin']",
namespace,
)
dependencies = root.find("mvn:dependencies", namespace)
dependencies.remove(plugin)
pom_tree.write(project.root / "pom.xml")
def test__get_plugin_version_not_found(project):
make_pom_xml_without_plugin(project)
with pytest.raises(JavaPluginNotFoundError):
project._plugin._get_java_plugin_dependency_version(project)
def test_generate_without_java_plugin_in_pom_should_not_fail(project):
make_pom_xml_without_plugin(project)
project.generate()
assert project.settings["protocolVersion"] == "2.0.0"
def test__get_plugin_version_invalid_pom(project):
with open(project.root / "pom.xml", "w", encoding="utf-8") as pom:
pom.write("invalid pom")
pom.close()
with pytest.raises(InvalidMavenPOMError):
project._plugin._get_java_plugin_dependency_version(project)
def test_package(project):
project.load_schema()
project.generate()
make_target(project, 1)
zip_file = Mock()
project._plugin.package(project, zip_file)
writes = []
for call in zip_file.write.call_args_list:
args, _kwargs = call
writes.append(str(args[1])) # relative path
assert len(writes) > 10
assert "pom.xml" in writes
def test__prompt_for_namespace_aws_default():
project = Mock(type_info=("AWS", "Clown", "Service"), settings={})
plugin = JavaLanguagePlugin()
with patch("rpdk.core.utils.init_utils.input", return_value="") as mock_input:
plugin._prompt_for_namespace(project)
mock_input.assert_called_once()
assert project.settings == {"namespace": ("software", "amazon", "clown", "service")}
def test__prompt_for_namespace_aws_overwritten():
project = Mock(type_info=("AWS", "Clown", "Service"), settings={})
plugin = JavaLanguagePlugin()
with patch(
"rpdk.core.utils.init_utils.input", return_value="com.red.clown.service"
) as mock_input:
plugin._prompt_for_namespace(project)
mock_input.assert_called_once()
assert project.settings == {"namespace": ("com", "red", "clown", "service")}
def test__prompt_for_namespace_other_default():
project = Mock(type_info=("Balloon", "Clown", "Service"), settings={})
plugin = JavaLanguagePlugin()
with patch("rpdk.core.utils.init_utils.input", return_value="") as mock_input:
plugin._prompt_for_namespace(project)
mock_input.assert_called_once()
assert project.settings == {"namespace": ("com", "balloon", "clown", "service")}
def test__prompt_for_namespace_other_overwritten():
project = Mock(type_info=("Balloon", "Clown", "Service"), settings={})
plugin = JavaLanguagePlugin()
with patch(
"rpdk.core.utils.init_utils.input", return_value="com.ball.clown.service"
) as mock_input:
plugin._prompt_for_namespace(project)
mock_input.assert_called_once()
assert project.settings == {"namespace": ("com", "ball", "clown", "service")}
def test__namespace_from_project_new_settings():
namespace = ("com", "ball", "clown", "service")
project = Mock(settings={"namespace": namespace})
plugin = JavaLanguagePlugin()
plugin._namespace_from_project(project)
assert plugin.namespace == namespace
assert plugin.package_name == "com.ball.clown.service"
def test__namespace_from_project_old_settings():
project = Mock(type_info=("Balloon", "Clown", "Service"), settings={})
plugin = JavaLanguagePlugin()
plugin._namespace_from_project(project)
assert plugin.namespace == ("com", "balloon", "clown", "service")
assert plugin.package_name == "com.balloon.clown.service"
def test__prompt_for_codegen_model_no_selection():
project = Mock(type_info=("AWS", "Clown", "Service"), settings={})
plugin = JavaLanguagePlugin()
with patch("rpdk.core.utils.init_utils.input", return_value="") as mock_input:
plugin._prompt_for_codegen_model(project)
mock_input.assert_called_once()
assert project.settings == {"codegen_template_path": "default"}
def test__prompt_for_codegen_model_default():
project = Mock(type_info=("AWS", "Clown", "Service"), settings={})
plugin = JavaLanguagePlugin()
with patch("rpdk.core.utils.init_utils.input", return_value="1") as mock_input:
plugin._prompt_for_codegen_model(project)
mock_input.assert_called_once()
assert project.settings == {"codegen_template_path": "default"}
def test__prompt_for_codegen_model_guided_aws():
project = Mock(type_info=("AWS", "Clown", "Service"), settings={})
plugin = JavaLanguagePlugin()
with patch("rpdk.core.utils.init_utils.input", return_value="2") as mock_input:
plugin._prompt_for_codegen_model(project)
mock_input.assert_called_once()
assert project.settings == {"codegen_template_path": "guided_aws"}
def test_generate_image_build_config(project):
make_target(project, 1)
config = project._plugin.generate_image_build_config(project)
assert "executable_name" in config
assert "project_path" in config
assert "dockerfile_path" in config
def test_generate_executable_entrypoint_specified(project):
project.executable_entrypoint = "entrypoint"
project.generate()
assert project.executable_entrypoint == "entrypoint"
def test_generate_executable_entrypoint_not_specified(project):
project.executable_entrypoint = None
project.generate()
plugin = JavaLanguagePlugin()
plugin._namespace_from_project(project)
assert (
project.executable_entrypoint
== plugin.package_name + ".HandlerWrapperExecutable"
)
def test_generate_hook_executable_entrypoint_not_specified(hook_project):
hook_project.executable_entrypoint = None
with patch.object(hook_project, "_load_target_info", return_value=TEST_TARGET_INFO):
hook_project.generate()
plugin = JavaLanguagePlugin()
plugin._namespace_from_project(hook_project)
assert (
hook_project.executable_entrypoint
== plugin.package_name + ".HookHandlerWrapperExecutable"
)
def test_generate_executable_entrypoint_old_project_version(project):
# If the cli version does not contain the new executable_entrypoint
# we will not add it
del project.executable_entrypoint
project.generate()
plugin = JavaLanguagePlugin()
plugin._namespace_from_project(project)
assert not hasattr(project, "executable_entrypoint")
def test_get_plugin_information(project):
plugin_information = project._plugin.get_plugin_information(project)
assert plugin_information["plugin-tool-version"] == __version__
assert plugin_information["plugin-name"] == "java"
assert plugin_information[
"plugin-version"
] == JavaLanguagePlugin._get_java_plugin_dependency_version(project)