@cdktn/hcl2cdk 0.25.0-pre.9 → 0.25.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/README.md +12 -0
  2. package/build/coerceType.js +21 -11
  3. package/build/dynamic-blocks.js +3 -3
  4. package/build/expressions.js +24 -17
  5. package/build/generation.js +34 -24
  6. package/build/index.js +27 -17
  7. package/build/iteration.js +6 -7
  8. package/build/jsii-rosetta-workarounds.js +5 -6
  9. package/build/partialCode.js +20 -11
  10. package/build/provider.js +3 -4
  11. package/build/references.js +5 -6
  12. package/build/schema.js +18 -8
  13. package/build/terraformSchema.js +4 -4
  14. package/build/utils.js +3 -3
  15. package/build/variables.js +21 -12
  16. package/package.json +18 -17
  17. package/.spec.swcrc +0 -22
  18. package/build/__tests__/coerceType.test.d.ts +0 -2
  19. package/build/__tests__/coerceType.test.js +0 -165
  20. package/build/__tests__/expressionToTs.test.d.ts +0 -6
  21. package/build/__tests__/expressionToTs.test.js +0 -693
  22. package/build/__tests__/expressions.test.d.ts +0 -4
  23. package/build/__tests__/expressions.test.js +0 -415
  24. package/build/__tests__/findExpressionType.test.d.ts +0 -6
  25. package/build/__tests__/findExpressionType.test.js +0 -105
  26. package/build/__tests__/functions.test.d.ts +0 -6
  27. package/build/__tests__/functions.test.js +0 -605
  28. package/build/__tests__/generation.test.d.ts +0 -6
  29. package/build/__tests__/generation.test.js +0 -45
  30. package/build/__tests__/jsii-rosetta-workarounds.test.d.ts +0 -2
  31. package/build/__tests__/jsii-rosetta-workarounds.test.js +0 -86
  32. package/build/__tests__/partialCode.test.d.ts +0 -6
  33. package/build/__tests__/partialCode.test.js +0 -390
  34. package/build/__tests__/terraformSchema.test.d.ts +0 -6
  35. package/build/__tests__/terraformSchema.test.js +0 -105
  36. package/build/__tests__/testHelpers.d.ts +0 -7
  37. package/build/__tests__/testHelpers.js +0 -16
  38. package/jest.config.js +0 -25
  39. package/package.sh +0 -9
  40. package/src/__tests__/coerceType.test.ts +0 -207
  41. package/src/__tests__/expressionToTs.test.ts +0 -1167
  42. package/src/__tests__/expressions.test.ts +0 -541
  43. package/src/__tests__/findExpressionType.test.ts +0 -112
  44. package/src/__tests__/functions.test.ts +0 -768
  45. package/src/__tests__/generation.test.ts +0 -72
  46. package/src/__tests__/jsii-rosetta-workarounds.test.ts +0 -145
  47. package/src/__tests__/partialCode.test.ts +0 -432
  48. package/src/__tests__/terraformSchema.test.ts +0 -107
  49. package/src/__tests__/testHelpers.ts +0 -11
  50. package/src/coerceType.ts +0 -261
  51. package/src/dynamic-blocks.ts +0 -61
  52. package/src/expressions.ts +0 -968
  53. package/src/function-bindings/functions.generated.ts +0 -1211
  54. package/src/function-bindings/functions.ts +0 -104
  55. package/src/generation.ts +0 -1189
  56. package/src/index.ts +0 -584
  57. package/src/iteration.ts +0 -156
  58. package/src/jsii-rosetta-workarounds.ts +0 -145
  59. package/src/partialCode.ts +0 -132
  60. package/src/provider.ts +0 -60
  61. package/src/references.ts +0 -193
  62. package/src/schema.ts +0 -74
  63. package/src/terraformSchema.ts +0 -182
  64. package/src/types.ts +0 -58
  65. package/src/utils.ts +0 -19
  66. package/src/variables.ts +0 -214
  67. package/test/__snapshots__/backends.test.ts.snap +0 -70
  68. package/test/__snapshots__/externals.test.ts.snap +0 -37
  69. package/test/__snapshots__/granular-imports.test.ts.snap +0 -180
  70. package/test/__snapshots__/imports.test.ts.snap +0 -159
  71. package/test/__snapshots__/iteration.test.ts.snap +0 -532
  72. package/test/__snapshots__/jsiiLanguage.test.ts.snap +0 -347
  73. package/test/__snapshots__/locals.test.ts.snap +0 -55
  74. package/test/__snapshots__/modules.test.ts.snap +0 -127
  75. package/test/__snapshots__/outputs.test.ts.snap +0 -77
  76. package/test/__snapshots__/partialCode.test.ts.snap +0 -120
  77. package/test/__snapshots__/provider.test.ts.snap +0 -128
  78. package/test/__snapshots__/references.test.ts.snap +0 -376
  79. package/test/__snapshots__/resource-meta-properties.test.ts.snap +0 -342
  80. package/test/__snapshots__/resources.test.ts.snap +0 -613
  81. package/test/__snapshots__/tfExpressions.test.ts.snap +0 -537
  82. package/test/__snapshots__/typeCoercion.test.ts.snap +0 -253
  83. package/test/__snapshots__/variables.test.ts.snap +0 -150
  84. package/test/backends.test.ts +0 -75
  85. package/test/convertProject.test.ts +0 -257
  86. package/test/externals.test.ts +0 -35
  87. package/test/globalSetup.ts +0 -224
  88. package/test/globalTeardown.ts +0 -11
  89. package/test/granular-imports.test.ts +0 -161
  90. package/test/hcl2cdk.test.ts +0 -88
  91. package/test/helpers/convert.ts +0 -544
  92. package/test/helpers/tmp.ts +0 -40
  93. package/test/imports.test.ts +0 -141
  94. package/test/iteration.test.ts +0 -342
  95. package/test/jsiiLanguage.test.ts +0 -73
  96. package/test/locals.test.ts +0 -47
  97. package/test/modules.test.ts +0 -143
  98. package/test/outputs.test.ts +0 -69
  99. package/test/partialCode.test.ts +0 -25
  100. package/test/provider.test.ts +0 -106
  101. package/test/references.test.ts +0 -287
  102. package/test/resource-meta-properties.test.ts +0 -288
  103. package/test/resources.test.ts +0 -551
  104. package/test/tfExpressions.test.ts +0 -300
  105. package/test/typeCoercion.test.ts +0 -154
  106. package/test/variables.test.ts +0 -96
  107. package/tsconfig.json +0 -43
@@ -1,88 +0,0 @@
1
- // Copyright (c) HashiCorp, Inc
2
- // SPDX-License-Identifier: MPL-2.0
3
- import { convert } from "../src/index";
4
-
5
- describe("convert", () => {
6
- it("exposes stats for telemetry", async () => {
7
- const { stats } = await convert(
8
- `
9
- resource "aws_kms_key" "examplekms" {
10
- description = "KMS key 1"
11
- deletion_window_in_days = 7
12
- }
13
-
14
- resource "aws_s3_bucket" "examplebucket" {
15
- bucket = "examplebuckettftest"
16
- acl = "private"
17
- }
18
- resource "aws_s3_bucket" "examplebucket_two" {
19
- bucket = "examplebuckettftest"
20
- acl = "private"
21
- }
22
- resource "aws_s3_bucket" "examplebucket_three" {
23
- bucket = "examplebuckettftest"
24
- acl = "private"
25
- }
26
- resource "internal_cloud_s3_bucket" "examplebucket" {
27
- bucket = "examplebuckettftest"
28
- acl = "private"
29
- }
30
- resource "internal_cloud_s3_bucket_object" "examplebucket_two" {
31
- bucket = "examplebuckettftest"
32
- acl = "private"
33
- }
34
-
35
- resource "aws_s3_bucket_object" "examplebucket_object" {
36
- key = "someobject"
37
- bucket = element(aws_s3_bucket.examplebucket, 0).id
38
- source = "index.html"
39
- kms_key_id = aws_kms_key.examplekms.arn
40
- }
41
- resource "aws_s3_bucket_object" "examplebucket_object_two" {
42
- key = "someobject"
43
- bucket = element(aws_s3_bucket.examplebucket, 0).id
44
- source = "index.html"
45
- kms_key_id = aws_kms_key.examplekms.arn
46
- }
47
- resource "google_compute_autoscaler" "example" {
48
- name = "example-autoscaler"
49
- zone = "us-east1-b"
50
-
51
- autoscaling_policy = {
52
- max_replicas = 8
53
- min_replicas = 2
54
- cooldown_period = 60
55
-
56
- cpu_utilization = {
57
- target = 0.5
58
- }
59
- }
60
- }
61
- `,
62
- { language: "typescript", providerSchema: {} },
63
- );
64
-
65
- expect(stats).toMatchInlineSnapshot(`
66
- {
67
- "convertedLines": 54,
68
- "data": {},
69
- "language": "typescript",
70
- "numberOfModules": 0,
71
- "numberOfProviders": 3,
72
- "resources": {
73
- "aws": {
74
- "kms_key": 1,
75
- "s3_bucket": 3,
76
- "s3_bucket_object": 2,
77
- },
78
- "google": {
79
- "compute_autoscaler": 1,
80
- },
81
- "other": {
82
- "other": 1,
83
- },
84
- },
85
- }
86
- `);
87
- });
88
- });
@@ -1,544 +0,0 @@
1
- // Copyright (c) HashiCorp, Inc
2
- // SPDX-License-Identifier: MPL-2.0
3
- import { convert } from "../../src/index";
4
- import * as fs from "fs-extra";
5
- import * as path from "path";
6
- import execa from "execa";
7
- import {
8
- LANGUAGES,
9
- TerraformModuleConstraint,
10
- TerraformProviderConstraint,
11
- } from "@cdktn/commons";
12
- import { readSchema } from "@cdktn/provider-schema";
13
- import type { FixturesManifest } from "../globalSetup";
14
- import { createTmpHelper } from "./tmp";
15
-
16
- const tmp = createTmpHelper();
17
-
18
- // Tests `process.chdir(projectDir)` for jsii-rosetta. If a test leaves cwd inside a projectDir that tmp()'s afterAll later removes, the worker's next test load sees uv_cwd ENOENT.
19
- const _originalCwd = process.cwd();
20
- if (typeof afterEach === "function") {
21
- afterEach(() => process.chdir(_originalCwd));
22
- }
23
-
24
- const includeSynthTests = Boolean(process.env.CI);
25
-
26
- // Load pre-generated fixtures manifest from globalSetup
27
- let _manifest: FixturesManifest | undefined;
28
- function getManifest(): FixturesManifest {
29
- if (_manifest) return _manifest;
30
- const manifestPath = process.env.HCL2CDK_FIXTURES_MANIFEST;
31
- if (!manifestPath) {
32
- throw new Error(
33
- "HCL2CDK_FIXTURES_MANIFEST env var not set. Ensure globalSetup ran successfully.",
34
- );
35
- }
36
- _manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
37
- return _manifest!;
38
- }
39
-
40
- export enum Synth {
41
- yes_all_languages, // Synth and snapshot all languages
42
- yes,
43
- yes_but_only_typescript_right_now_because_it_breaks,
44
- no_cant_resolve_construct,
45
- no_missing_map_access, // See https://github.com/hashicorp/terraform-cdk/issues/2670
46
- no_missing_type_coercion, // We don't type coerce numbers yet
47
- never, // Some examples are built so that they will never synth but test a specific generation edge case
48
- }
49
- export enum Snapshot {
50
- yes_all_languages, // Synth and snapshot all languages
51
- yes,
52
- }
53
-
54
- type PathToCopy = string;
55
- type ProviderFqn = string;
56
- enum ProviderType {
57
- provider,
58
- module,
59
- }
60
-
61
- type ProviderDefinition = {
62
- fqn: ProviderFqn;
63
- type: ProviderType;
64
- path: PathToCopy;
65
- };
66
-
67
- type SchemaFilter = {
68
- resources?: string[];
69
- dataSources?: string[];
70
- };
71
-
72
- const cdktnBin = path.join(__dirname, "../../../../cdktn-cli/bin/cdktn");
73
- const cdktnDist = path.join(__dirname, "../../../../../dist");
74
- const tsxPkgJsonPath = require.resolve("tsx/package.json");
75
- const tsxBin = path.join(
76
- path.dirname(tsxPkgJsonPath),
77
- fs.readJsonSync(tsxPkgJsonPath).bin,
78
- );
79
-
80
- export const binding = {
81
- aws: {
82
- fqn: "hashicorp/aws@=5.11.0",
83
- type: ProviderType.provider,
84
- path: "providers/aws",
85
- },
86
- docker: {
87
- fqn: "kreuzwerker/docker@=3.0.1",
88
- type: ProviderType.provider,
89
- path: "providers/docker",
90
- },
91
- null: {
92
- fqn: "hashicorp/null@=3.2.1",
93
- type: ProviderType.provider,
94
- path: "providers/null",
95
- },
96
- google: {
97
- fqn: "hashicorp/google@=4.55.0",
98
- type: ProviderType.provider,
99
- path: "providers/google",
100
- },
101
- azuread: {
102
- fqn: "hashicorp/azuread@=2.36.0",
103
- type: ProviderType.provider,
104
- path: "providers/azuread",
105
- },
106
- local: {
107
- fqn: "hashicorp/local@=2.3.0",
108
- type: ProviderType.provider,
109
- path: "providers/local",
110
- },
111
- auth0: {
112
- fqn: "alexkappa/auth0@=0.26.2",
113
- type: ProviderType.provider,
114
- path: "providers/auth0",
115
- },
116
- datadog: {
117
- fqn: "DataDog/datadog@=3.21.0",
118
- type: ProviderType.provider,
119
- path: "providers/datadog",
120
- },
121
- kubernetes: {
122
- fqn: "hashicorp/kubernetes@=2.18.0",
123
- type: ProviderType.provider,
124
- path: "providers/kubernetes",
125
- },
126
- scaleway: {
127
- fqn: "scaleway/scaleway@ ~>2.10.0",
128
- type: ProviderType.provider,
129
- path: "providers/scaleway",
130
- },
131
- external: {
132
- fqn: "hashicorp/external@=2.3.1",
133
- type: ProviderType.provider,
134
- path: "providers/external",
135
- },
136
- awsVpc: {
137
- fqn: "terraform-aws-modules/vpc/aws@=3.19.0",
138
- type: ProviderType.module,
139
- path: "modules/terraform-aws-modules/aws",
140
- },
141
- };
142
-
143
- type AbsolutePath = string;
144
-
145
- async function copyBindingsForProvider(
146
- binding: ProviderDefinition,
147
- targetDirectory: AbsolutePath,
148
- ) {
149
- const manifest = getManifest();
150
- const absoluteBindingPath = manifest.providerBindings[binding.fqn];
151
- if (!absoluteBindingPath) {
152
- throw new Error(
153
- `No pre-generated binding found for ${binding.fqn}. Ensure globalSetup generates it.`,
154
- );
155
- }
156
-
157
- const target = path.resolve(targetDirectory, ".gen", binding.path);
158
- await fs.mkdirp(target);
159
- await fs.copy(absoluteBindingPath, target);
160
- }
161
-
162
- /**
163
- * Provisions `projectDir` from `baseDir`.
164
- *
165
- * Copies everything except `node_modules`, then drops a directory symlink in its place. `node_modules` is the heavy
166
- * bit of the base project (hundreds of MB) and the test runner only reads from it — sharing it across tests avoids
167
- * per-test copy cost. The base project must therefore be treated as read-only for the lifetime of the test suite.
168
- *
169
- * @param baseDir Source project (output of `cdktn init`) created once in globalSetup.
170
- * @param projectDir Destination for this test's project.
171
- */
172
- async function copyBaseProject(baseDir: string, projectDir: string) {
173
- await fs.copy(baseDir, projectDir, {
174
- filter: (src) => path.basename(src) !== "node_modules",
175
- });
176
- await fs.symlink(
177
- path.join(baseDir, "node_modules"),
178
- path.join(projectDir, "node_modules"),
179
- // A "dir" symlink needs Developer Mode or an elevated shell on Windows and
180
- // otherwise fails with EPERM. A junction is created without either and
181
- // resolves the same way for reads, which is all this shared, read-only
182
- // node_modules is used for. Junctions require an absolute target, which
183
- // baseDir always is.
184
- process.platform === "win32" ? "junction" : "dir",
185
- );
186
- }
187
-
188
- const fileEndings: Record<string, string> = {
189
- typescript: ".ts",
190
- python: ".py",
191
- csharp: ".cs",
192
- };
193
-
194
- const getFileContent: Record<
195
- string,
196
- (
197
- code: { all: string; code: string; imports: string },
198
- stackName: string,
199
- ) => string
200
- > = {
201
- typescript: ({ all }, stackName) => `
202
- ${all}
203
- import { App } from "cdktn";
204
- const app = new App();
205
- new MyConvertedCode(app, "${stackName}");
206
- app.synth();`,
207
- python: ({ all }, stackName) => `
208
- ${all}
209
-
210
- app = App()
211
- MyConvertedCode(app, "${stackName}")
212
- app.synth()
213
- `,
214
-
215
- csharp: ({ all }, stackName) => {
216
- const endOfStack = all.lastIndexOf("}");
217
- const stack = all.substring(0, endOfStack);
218
- return `
219
- ${stack}
220
- public static void Main(string[] args)
221
- {
222
- App app = new App();
223
- new MyConvertedCode(app, "${stackName}");
224
- app.Synth();
225
- }
226
- }
227
- `;
228
- },
229
- };
230
-
231
- const getAppCommand: Record<string, (stackName: string) => string> = {
232
- typescript: (stackName) => `${tsxBin} ${stackName}.ts`,
233
- python: (stackName) => `pipenv run python ${stackName}.py`,
234
- csharp: (stackName) => `dotnet run --project ${stackName}.csproj`,
235
- };
236
-
237
- const preSynth: Record<
238
- string,
239
- (
240
- stackName: string,
241
- projectDir: string,
242
- providers: ProviderDefinition[],
243
- ) => Promise<void> | undefined
244
- > = {
245
- csharp: async (stackName, projectDir, providers) => {
246
- await fs.writeFile(
247
- path.join(projectDir, `${stackName}.csproj`),
248
- `<Project Sdk="Microsoft.NET.Sdk">
249
-
250
- <PropertyGroup>
251
- <OutputType>Exe</OutputType>
252
- <TargetFramework>net6.0</TargetFramework>
253
- </PropertyGroup>
254
-
255
- <ItemGroup>
256
- <PackageReference Include="Io.Cdktn" Version="0.0.0" />
257
- </ItemGroup>
258
-
259
- <ItemGroup>
260
- ${providers
261
- .map((provider) => {
262
- const [, name] = provider.fqn.split("@")[0].split("/");
263
- return `<ProjectReference Include=".gen\\${
264
- provider.type === ProviderType.provider ? "providers" : "modules"
265
- }\\${name}.csproj" />`;
266
- })
267
- .join("\n")}
268
- </ItemGroup>
269
-
270
- </Project>`,
271
- "utf8",
272
- );
273
-
274
- await fs.writeFile(
275
- path.join(projectDir, "NuGet.Config"),
276
- `<?xml version="1.0" encoding="utf-8"?>
277
- <configuration>
278
- <packageSources>
279
- <add key="Locally Distributed Packages" value="${cdktnDist}/dotnet/" />
280
- <add key="NuGet official package source" value="https://api.nuget.org/v3/index.json" />
281
- </packageSources>
282
- </configuration>
283
- `,
284
- "utf8",
285
- );
286
- },
287
- };
288
-
289
- /**
290
- * Writes the converted code to a project directory and spawns `cdktn synth`
291
- * against it, asserting that synth reports success on stdout.
292
- *
293
- * @param language Target language for the synth (typescript, python, csharp).
294
- * @param name Human-readable test-case name.
295
- * @param code Output of `convert()` for the HCL input
296
- * @param providers Provider bindings the converted code imports.
297
- * @param projectDir An existing project dir to reuse.
298
- */
299
- async function synthForLanguage(
300
- language: string,
301
- name: string,
302
- code: { all: string; code: string; imports: string },
303
- providers: ProviderDefinition[] = [],
304
- projectDir?: string,
305
- ) {
306
- const stackName = name.replace(/\s/g, "-");
307
- if (!projectDir) {
308
- projectDir = await getProjectDirectory(language, providers);
309
- }
310
-
311
- // Have a before all somewhere above bootstrap a TS project
312
- // __dirname should be replaceed by the bootstrapped directory
313
- const pathToThisProjectsFile = path.join(
314
- projectDir,
315
- stackName + fileEndings[language],
316
- );
317
- const fileContent = getFileContent[language](code, stackName);
318
-
319
- fs.writeFileSync(pathToThisProjectsFile, fileContent, "utf8");
320
-
321
- const runBeforeSynth = preSynth[language];
322
- if (runBeforeSynth) {
323
- await runBeforeSynth(stackName, projectDir, providers);
324
- }
325
-
326
- const { all } = await execa(
327
- cdktnBin,
328
- [
329
- "synth",
330
- "-a",
331
- `'${getAppCommand[language](stackName)}'`,
332
- "-o",
333
- `./${stackName}-output`,
334
- ],
335
- { cwd: projectDir, all: true, shell: true },
336
- );
337
-
338
- expect(all!).toEqual(
339
- expect.stringContaining(`Generated Terraform code for the stacks`),
340
- );
341
- }
342
-
343
- // getProviderSchema(Object.values(binding));
344
-
345
- async function getProjectDirectory(
346
- language: string,
347
- providers: ProviderDefinition[],
348
- ) {
349
- const manifest = getManifest();
350
- const baseDir = manifest.baseProjects[language];
351
- if (!baseDir) {
352
- throw new Error(
353
- `Unsupported language used to synthesize code: ${language}`,
354
- );
355
- }
356
- const projectDir = tmp("cdktf-convert-test-");
357
-
358
- await Promise.all([
359
- copyBaseProject(baseDir, projectDir),
360
- ...providers.map((provider) =>
361
- copyBindingsForProvider(provider, projectDir),
362
- ),
363
- ]);
364
-
365
- // We only copy the TS bindings, but we need to run cdktn get for the language specific ones
366
- if (language !== "typescript") {
367
- await fs.writeFile(
368
- path.resolve(projectDir, "cdktf.json"),
369
- JSON.stringify(
370
- {
371
- language,
372
- app: "echo 'app command should be overwritten'",
373
- terraformProviders: providers
374
- .filter((binding) => binding.type === ProviderType.provider)
375
- .map((binding) => binding.fqn),
376
- terraformModules: providers
377
- .filter((binding) => binding.type === ProviderType.module)
378
- .map((binding) => binding.fqn),
379
- },
380
- null,
381
- 2,
382
- ),
383
- );
384
- await execa(cdktnBin, ["get", "--force"], { cwd: projectDir });
385
- }
386
-
387
- return projectDir;
388
- }
389
-
390
- async function getProviderSchema(providers: ProviderDefinition[]) {
391
- const constraints = providers.map(
392
- (provider) =>
393
- ProviderType.provider === provider.type
394
- ? new TerraformProviderConstraint(provider.fqn)
395
- : new TerraformModuleConstraint(provider.fqn),
396
- LANGUAGES[0],
397
- );
398
-
399
- const schemaCacheDir =
400
- process.env.CDKTF_EXPERIMENTAL_PROVIDER_SCHEMA_CACHE_PATH ||
401
- getManifest().schemaCacheDir;
402
-
403
- return await readSchema(constraints, schemaCacheDir);
404
- }
405
-
406
- function filterSchema(
407
- providerSchema: any,
408
- schemaFilter: SchemaFilter | undefined,
409
- ) {
410
- if (!schemaFilter) return providerSchema;
411
-
412
- const { resources, dataSources } = schemaFilter;
413
-
414
- const providerSchemaKey = Object.keys(providerSchema.provider_schemas)[0];
415
- const actualSchema = providerSchema.provider_schemas[providerSchemaKey];
416
-
417
- let filteredDataSourceSchemas = {};
418
- let filteredResourceSchemas = {};
419
-
420
- if (resources && resources.length > 0) {
421
- filteredResourceSchemas = Object.fromEntries(
422
- Object.entries(actualSchema.resource_schemas).filter(([resourceName]) =>
423
- resources?.includes(resourceName),
424
- ),
425
- );
426
- }
427
-
428
- if (dataSources && dataSources.length > 0) {
429
- filteredDataSourceSchemas = Object.fromEntries(
430
- Object.entries(actualSchema.data_source_schemas).filter(
431
- ([dataSourceName]) => dataSources?.includes(dataSourceName),
432
- ),
433
- );
434
- }
435
-
436
- return {
437
- provider_schemas: {
438
- [providerSchemaKey]: {
439
- provider: providerSchema.provider_schemas[providerSchemaKey].provider,
440
- resource_schemas: filteredResourceSchemas,
441
- data_source_schemas: filteredDataSourceSchemas,
442
- },
443
- },
444
- };
445
- }
446
-
447
- const createTestCase =
448
- (opts: { skip?: true; only?: true }) =>
449
- (
450
- name: string,
451
- hcl: string,
452
- providers: ProviderDefinition[],
453
- shouldSnapshot: Snapshot,
454
- shouldSynth: Synth,
455
- schemaFilter?: SchemaFilter,
456
- ) => {
457
- if (opts.skip) {
458
- describe.skip(name, () => {});
459
- return;
460
- }
461
-
462
- async function runConvert(language: string) {
463
- let { providerSchema } = await getProviderSchema(providers);
464
- if (schemaFilter) {
465
- // TODO: Re-enable once we can trick Terraform CLI Checksums
466
- providerSchema = filterSchema(providerSchema, undefined);
467
- }
468
- return await convert(hcl, {
469
- language: language as any,
470
- providerSchema: providerSchema || {
471
- format_version: "0.1",
472
- },
473
- codeContainer: "cdktn.TerraformStack",
474
- });
475
- }
476
-
477
- const testBody = () => {
478
- describe("snapshot", () => {
479
- it.each(
480
- shouldSnapshot === Snapshot.yes_all_languages
481
- ? ["typescript", "python", "csharp", "java", "go"]
482
- : ["typescript"],
483
- )(
484
- "%s",
485
- async (language) => {
486
- const projectDir = await getProjectDirectory(
487
- // We need the typescript project directory to start the convert so JSII has the right types
488
- "typescript",
489
- providers,
490
- );
491
- process.chdir(projectDir); // JSII rosetta needs to be run in the project directory with bindings included
492
- const convertResult = await runConvert(language);
493
- expect(convertResult.all).toMatchSnapshot();
494
- },
495
- 500_000,
496
- );
497
- });
498
-
499
- if (
500
- includeSynthTests &&
501
- [Synth.yes_all_languages, Synth.yes].includes(shouldSynth)
502
- ) {
503
- describe("synth", () => {
504
- it.each(
505
- shouldSynth === Synth.yes_all_languages
506
- ? ["typescript", "python", "csharp"]
507
- : ["typescript"],
508
- )(
509
- "%s",
510
- async (language) => {
511
- const projectDir = await getProjectDirectory(
512
- "typescript",
513
- providers,
514
- );
515
- process.chdir(projectDir); // JSII rosetta needs to be run in the project directory with bindings included
516
- const convertResult = await runConvert(language);
517
- await synthForLanguage(
518
- language,
519
- name,
520
- convertResult,
521
- providers,
522
- projectDir,
523
- );
524
- },
525
- 500_000,
526
- );
527
- });
528
- } else {
529
- describe.skip("synth", () => {});
530
- }
531
- };
532
-
533
- if (opts.only) {
534
- describe.only(name, testBody);
535
- return;
536
- }
537
- describe(name, testBody);
538
- };
539
-
540
- export const testCase = {
541
- test: createTestCase({}),
542
- skip: createTestCase({ skip: true }),
543
- only: createTestCase({ only: true }),
544
- };
@@ -1,40 +0,0 @@
1
- // Copyright (c) HashiCorp, Inc
2
- // SPDX-License-Identifier: MPL-2.0
3
- import * as fs from "fs";
4
- import * as os from "os";
5
- import * as path from "path";
6
-
7
- /**
8
- * Creates a per-test-file temp-dir helper.
9
- *
10
- * Returns a `tmp(prefix)` function that creates a uniquely-named directory
11
- * under `os.tmpdir()` and tracks it. An `afterAll` hook is registered on
12
- * the calling test file's scope; when the file finishes running, every
13
- * tracked directory is removed (recursively, force).
14
- */
15
- export function createTmpHelper(): (prefix: string) => string {
16
- const dirs: string[] = [];
17
- afterAll(() => {
18
- for (const d of dirs) {
19
- try {
20
- // Windows frequently holds transient handles on just-written files
21
- // (search indexer, AV scanners), which surfaces as EBUSY/EPERM. Retry,
22
- // and never let cleanup of a temp directory fail the suite itself --
23
- // these live under os.tmpdir() and the OS reclaims them regardless.
24
- fs.rmSync(d, {
25
- recursive: true,
26
- force: true,
27
- maxRetries: 5,
28
- retryDelay: 100,
29
- });
30
- } catch (e) {
31
- console.warn(`Could not remove temp dir ${d}: ${(e as Error).message}`);
32
- }
33
- }
34
- });
35
- return (prefix: string) => {
36
- const d = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
37
- dirs.push(d);
38
- return d;
39
- };
40
- }