forked from microsoft/typespec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsample-snapshot-testing.ts
227 lines (204 loc) · 6.86 KB
/
sample-snapshot-testing.ts
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
import {
CompilerHost,
NodeHost,
ResolveCompilerOptionsOptions,
compile,
getDirectoryPath,
getRelativePathFromDirectory,
joinPaths,
resolveCompilerOptions,
resolvePath,
} from "@typespec/compiler";
import { expectDiagnosticEmpty } from "@typespec/compiler/testing";
import { fail, ok, strictEqual } from "assert";
import { readdirSync } from "fs";
import { mkdir, readFile, readdir, rm, writeFile } from "fs/promises";
import { File, Suite, afterAll, beforeAll, it } from "vitest";
const shouldUpdateSnapshots = process.env.RECORD === "true";
export interface SampleSnapshotTestOptions {
/** Sample root directory. */
sampleDir: string;
/** Output directory for snapshots. */
outputDir: string;
/** Folders to exclude from testing. */
exclude?: string[];
/** Override the emitters to use. */
emit?: string[];
}
export interface TestContext {
runCount: number;
registerSnapshot(filename: string): void;
}
export function defineSampleSnaphotTests(config: SampleSnapshotTestOptions) {
const samples = resolveSamples(config);
let existingSnapshots: string[];
const writtenSnapshots: string[] = [];
const context = {
runCount: 0,
registerSnapshot(filename: string) {
writtenSnapshots.push(filename);
},
};
beforeAll(async () => {
existingSnapshots = await readFilesInDirRecursively(config.outputDir);
});
afterAll(async function (context: Readonly<Suite | File>) {
if (context.tasks.length !== samples.length) {
return; // Not running the full test suite, so don't bother checking snapshots.
}
const missingSnapshots = new Set<string>(existingSnapshots);
for (const writtenSnapshot of writtenSnapshots) {
missingSnapshots.delete(writtenSnapshot);
}
if (missingSnapshots.size > 0) {
if (shouldUpdateSnapshots) {
for (const file of [...missingSnapshots].map((x) => joinPaths(config.outputDir, x))) {
await rm(file);
}
} else {
const snapshotList = [...missingSnapshots].map((x) => ` ${x}`).join("\n");
fail(
`The following snapshot are still present in the output dir but were not generated:\n${snapshotList}\n Run with RECORD=true to regenerate them.`
);
}
}
});
samples.forEach((samples) => defineSampleSnaphotTest(context, config, samples));
}
function defineSampleSnaphotTest(
context: TestContext,
config: SampleSnapshotTestOptions,
sample: Sample
) {
it(sample.name, async () => {
context.runCount++;
const host = createSampleSnapshotTestHost(config);
const outputDir = resolvePath(config.outputDir, sample.name);
const overrides: Partial<ResolveCompilerOptionsOptions["overrides"]> = {
outputDir,
};
if (config.emit) {
overrides.emit = config.emit;
}
const [options, diagnostics] = await resolveCompilerOptions(host, {
cwd: process.cwd(),
entrypoint: sample.fullPath,
overrides,
});
expectDiagnosticEmpty(diagnostics);
const emit = options.emit;
if (emit === undefined || emit.length === 0) {
fail(
`No emitters configured for sample "${sample.name}". Make sure the config at: "${options.config}" is correct.`
);
}
const program = await compile(host, sample.fullPath, options);
expectDiagnosticEmpty(program.diagnostics);
if (shouldUpdateSnapshots) {
try {
await host.rm(outputDir, { recursive: true });
} catch (e) {}
await mkdir(outputDir, { recursive: true });
for (const [snapshotPath, content] of host.outputs.entries()) {
const relativePath = getRelativePathFromDirectory(outputDir, snapshotPath, false);
try {
await mkdir(getDirectoryPath(snapshotPath), { recursive: true });
await writeFile(snapshotPath, content);
context.registerSnapshot(resolvePath(sample.name, relativePath));
} catch (e) {
throw new Error(`Failure to write snapshot: "${snapshotPath}"\n Error: ${e}`);
}
}
} else {
for (const [snapshotPath, content] of host.outputs.entries()) {
const relativePath = getRelativePathFromDirectory(outputDir, snapshotPath, false);
let existingContent;
try {
existingContent = await readFile(snapshotPath);
} catch (e: unknown) {
if (isEnoentError(e)) {
fail(`Snapshot "${snapshotPath}" is missing. Run with RECORD=true to regenerate it.`);
}
throw e;
}
context.registerSnapshot(resolvePath(sample.name, relativePath));
strictEqual(content, existingContent.toString());
}
for (const filename of await readFilesInDirRecursively(outputDir)) {
const snapshotPath = resolvePath(outputDir, filename);
ok(
host.outputs.has(snapshotPath),
`Snapshot for "${snapshotPath}" was not emitted. Run with RECORD=true to remove it.`
);
}
}
});
}
interface SampleSnapshotTestHost extends CompilerHost {
outputs: Map<string, string>;
}
function createSampleSnapshotTestHost(config: SampleSnapshotTestOptions): SampleSnapshotTestHost {
const outputs = new Map<string, string>();
return {
...NodeHost,
outputs,
mkdirp: (path: string) => Promise.resolve(path),
rm: (path: string) => Promise.resolve(),
writeFile: async (path: string, content: string) => {
outputs.set(path, content);
},
};
}
async function readFilesInDirRecursively(dir: string): Promise<string[]> {
let entries;
try {
entries = await readdir(dir, { withFileTypes: true });
} catch (e) {
if (isEnoentError(e)) {
return [];
} else {
throw new Error(`Failed to read dir "${dir}"\n Error: ${e}`);
}
}
const files: string[] = [];
for (const entry of entries) {
if (entry.isDirectory()) {
for (const file of await readFilesInDirRecursively(resolvePath(dir, entry.name))) {
files.push(resolvePath(entry.name, file));
}
} else {
files.push(entry.name);
}
}
return files;
}
interface Sample {
name: string;
/** Sample folder */
fullPath: string;
}
function resolveSamples(config: SampleSnapshotTestOptions): Sample[] {
const samples: Sample[] = [];
const excludes = new Set(config.exclude);
walk("");
return samples;
function walk(relativeDir: string) {
if (excludes.has(relativeDir)) {
return;
}
const fullDir = joinPaths(config.sampleDir, relativeDir);
for (const entry of readdirSync(fullDir, { withFileTypes: true })) {
if (entry.isDirectory()) {
walk(joinPaths(relativeDir, entry.name));
} else if (relativeDir && (entry.name === "main.tsp" || entry.name === "package.json")) {
samples.push({
name: relativeDir,
fullPath: joinPaths(config.sampleDir, relativeDir),
});
}
}
}
}
function isEnoentError(e: unknown): e is { code: "ENOENT" } {
return typeof e === "object" && e !== null && "code" in e;
}