Skip to content

Commit 177173e

Browse files
committed
fix: automatically clean up unit test assemblies
The CDK framework creates a temporary directory in `/tmp` for every unit test, and never cleans those up. In this PR, register all temporary assembly directories created by doing `new Stack()` or `new App()` without an `outdir`, and delete them when the Node process exits. This will only affect unit tests: if the `outdir` property is set explicitly, or the CDK App is being synthesized by the CLI (and `$CDK_OUTDIR` is set), the assembly directory will not be cleaned.
1 parent 2eee0a9 commit 177173e

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

packages/aws-cdk-lib/core/lib/stack.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -439,7 +439,6 @@ export class Stack extends Construct implements ITaggable {
439439
// as the parent because apps implement much of the synthesis logic.
440440
scope = scope ?? new App({
441441
autoSynth: false,
442-
outdir: FileSystem.mkdtemp('cdk-test-app-'),
443442
});
444443

445444
// "Default" is a "hidden id" from a `node.uniqueId` perspective

packages/aws-cdk-lib/cx-api/lib/cloud-assembly.ts

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -476,7 +476,14 @@ function ignore(_x: any) {
476476
* Turn the given optional output directory into a fixed output directory
477477
*/
478478
function determineOutputDirectory(outdir?: string) {
479-
return outdir ?? fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'cdk.out'));
479+
if (outdir) {
480+
return outdir;
481+
}
482+
483+
// Make a temporary directory; clean it up automatically if this is done for testing.
484+
const tmpDir = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'cdk.out'));
485+
TEMPORARY_ASSEMBLY_DIRS.push(tmpDir);
486+
return outdir ?? tmpDir;
480487
}
481488

482489
function ensureDirSync(dir: string) {
@@ -488,3 +495,11 @@ function ensureDirSync(dir: string) {
488495
fs.mkdirSync(dir, { recursive: true });
489496
}
490497
}
498+
499+
// On process exit, delete all temporary assembly directories
500+
const TEMPORARY_ASSEMBLY_DIRS: string[] = [];
501+
process.on('exit', () => {
502+
for (const dir of TEMPORARY_ASSEMBLY_DIRS) {
503+
fs.rmSync(dir, { recursive: true, force: true });
504+
}
505+
});

0 commit comments

Comments
 (0)