src/vs/base/test/common/snapshot.ts

187 LOC · 180 covered · 7 uncovered · 45 ranges · 686 concepts · 13 introducers · 306 tests

File neighbourhood

The centred file is linked to every concept that introduces one of its ranges, every test that runs code from the file, and the gray connector concepts standing between those tests and the file's own introducer concepts. Undirected links join concepts to every file where they introduce source and concepts to the tests they introduce; arrows show specialization between the displayed concepts and bridge only concepts omitted from this view. Concept colors match the source ranges below; connector concepts have no source color and are shown in gray.

Focused file, its introducer and connector concepts, their introduced files, and tests that run code from the file

In the embedded map, ordinary wheel input scrolls the page; use the visible controls to zoom and drag to pan. Open the full-screen map for canvas navigation: wheel pans, Ctrl/Command plus wheel zooms, and arrow keys pan when this region is focused. On touch screens, open the full-screen map to pan or pinch. If JavaScript or WebGL is unavailable, use the related-file, concept, and source links on this page.

Graph controls are ready.

Interactive rendering requires JavaScript and WebGL. Use the related-file, concept, and source links on this page while the interactive map is unavailable.

1 > /*--------------------------------------------------------------------------------------------- snapshot.ts ×5
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { Lazy } from '../../common/lazy.js';
7 > import { FileAccess } from '../../common/network.js';
8 > import { URI } from '../../common/uri.js';
9 >
10 > declare const __readFileInTests: (path: string) => Promise<string>;
11 > declare const __writeFileInTests: (path: string, contents: string) => Promise<void>;
12 > declare const __readDirInTests: (path: string) => Promise<string[]>;
13 > declare const __unlinkInTests: (path: string) => Promise<void>;
14 > declare const __mkdirPInTests: (path: string) => Promise<void>;
15 >
16 > // setup on import so assertSnapshot has the current context without explicit passing
17 > let context: Lazy<SnapshotContext> | undefined;
18 > const sanitizeName = (name: string) => name.replace(/[^a-z0-9_-]/gi, '_');
19 > const normalizeCrlf = (str: string) => str.replace(/\r\n/g, '\n');
20 >
21 > export interface ISnapshotOptions {
22 > /** Name for snapshot file, rather than an incremented number */
23 > name?: string;
24 > /** Extension name of the snapshot file, defaults to `.snap` */
25 > extension?: string;
26 > }
27 >
28 > /**
29 > * This is exported only for tests against the snapshotting itself! Use
30 > * {@link assertSnapshot} as a consumer!
31 > */
32 > export class SnapshotContext {
33 > private nextIndex = 0;
34 > protected snapshotsDir: URI;
35 > private readonly namePrefix: string;
36 > private readonly usedNames = new Set();
37 >
38 > constructor(private readonly test: Mocha.Test | undefined) {
39 > if (!test) { snapshot.ts ×12
40 throw new Error('assertSnapshot can only be used in a test');
41 }
43 > if (!test.file) {
44 throw new Error('currentTest.file is not set, please open an issue with the test you\'re trying to run');
45 }
47 > const src = URI.joinPath(FileAccess.asFileUri(''), '../src');
48 > const parts = test.file.split(/[/\\]/g);
49 >
50 > this.namePrefix = sanitizeName(test.fullTitle()) + '.';
51 > this.snapshotsDir = URI.joinPath(src, ...[...parts.slice(0, -1), '__snapshots__']);
52 > }
54 > public async assert(value: unknown, options?: ISnapshotOptions) {
55 > const originalStack = new Error().stack!; // save to make the stack nicer on failure snapshot.ts ×12
56 > const nameOrIndex = (options?.name ? sanitizeName(options.name) : this.nextIndex++);
57 > const fileName = this.namePrefix + nameOrIndex + '.' + (options?.extension || 'snap');
58 > this.usedNames.add(fileName);
59 >
60 > const fpath = URI.joinPath(this.snapshotsDir, fileName).fsPath;
61 > const actual = formatValue(value);
62 > let expected: string;
63 > try {
64 > expected = await __readFileInTests(fpath);
65 > } catch {
66 > console.info(`Creating new snapshot in: ${fpath}`); snapshot.ts ×1
67 > await __mkdirPInTests(this.snapshotsDir.fsPath);
68 > await __writeFileInTests(fpath, actual);
69 > return;
70 > }
72 > if (normalizeCrlf(expected) !== normalizeCrlf(actual)) {
73 > await __writeFileInTests(fpath + '.actual', actual); utils.ts ×2
74 > const err: any = new Error(`Snapshot #${nameOrIndex} does not match expected output`);
75 > err.expected = expected;
76 > err.actual = actual;
77 > err.snapshotPath = fpath;
78 > err.stack = (err.stack as string)
79 > .split('\n')
80 > // remove all frames from the async stack and keep the original caller's frame
81 > .slice(0, 1)
82 > .concat(originalStack.split('\n').slice(3))
83 > .join('\n');
84 > throw err;
85 > }
88 > public async removeOldSnapshots() {
89 > const contents = await __readDirInTests(this.snapshotsDir.fsPath); snapshot.ts ×5
90 > const toDelete = contents.filter(f => f.startsWith(this.namePrefix) && !this.usedNames.has(f));
91 > if (toDelete.length) {
92 > console.info(`Deleting ${toDelete.length} old snapshots for ${this.test?.fullTitle()}`); snapshot.ts ×1
93 > }
95 > await Promise.all(toDelete.map(f => __unlinkInTests(URI.joinPath(this.snapshotsDir, f).fsPath)));
96 > }
98 >
99 > const debugDescriptionSymbol = Symbol.for('debug.description');
100 >
101 > function formatValue(value: unknown, level = 0, seen: unknown[] = []): string { snapshot.ts ×12
102 > switch (typeof value) {
103 > case 'bigint':
104 > case 'boolean':
105 > case 'number':
106 > case 'symbol':
107 > case 'undefined':
108 > return String(value); snapshot.ts ×7
109 > case 'string': snapshot.ts ×12
110 > return level === 0 ? value : JSON.stringify(value); snapshot.ts ×5
111 > case 'function': snapshot.ts ×12
112 > return `[Function ${value.name}]`; snapshot.ts ×6
113 > case 'object': { snapshot.ts ×12
114 > if (value === null) { snapshot.ts ×7
115 > return 'null'; snapshot.ts ×6
116 > }
117 > if (value instanceof RegExp) { snapshot.ts ×7
118 > return String(value); snapshot.ts ×6
119 > }
120 > if (seen.includes(value)) { snapshot.ts ×7
121 > return '[Circular]'; snapshot.ts ×6
122 > }
123 > // eslint-disable-next-line local/code-no-any-casts snapshot.ts ×7
124 > if (debugDescriptionSymbol in value && typeof (value as any)[debugDescriptionSymbol] === 'function') {
125 > // eslint-disable-next-line local/code-no-any-casts snapshot.ts ×1
126 > return (value as any)[debugDescriptionSymbol]();
127 > }
128 > const oi = ' '.repeat(level); snapshot.ts ×7
129 > const ci = ' '.repeat(level + 1);
130 > if (Array.isArray(value)) {
131 > const children = value.map(v => formatValue(v, level + 1, [...seen, value])); snapshot.ts ×1
132 > const multiline = children.some(c => c.includes('\n')) || children.join(', ').length > 80;
133 > return multiline ? `[\n${ci}${children.join(`,\n${ci}`)}\n${oi}]` : `[ ${children.join(', ')} ]`;
134 > }
136 > let entries;
137 > let prefix = '';
138 > if (value instanceof Map) {
139 > prefix = 'Map '; snapshot.ts ×6
140 > entries = [...value.entries()];
141 > } else if (value instanceof Set) { snapshot.ts ×3
142 > prefix = 'Set '; snapshot.ts ×6
143 > entries = [...value.entries()];
144 > } else { snapshot.ts ×3
145 > entries = Object.entries(value);
146 > }
147 >
148 > const lines = entries.map(([k, v]) => `${k}: ${formatValue(v, level + 1, [...seen, value])}`);
149 > return prefix + (lines.length > 1
150 > ? `{\n${ci}${lines.join(`,\n${ci}`)}\n${oi}}` snapshot.ts ×1
151 > : `{ ${lines.join(',\n')} }`); snapshot.ts ×1
152 > } snapshot.ts ×7
153 > default: snapshot.ts ×12
154 throw new Error(`Unknown type ${value}`);
156 > }
158 > setup(function () {
159 > const currentTest = this.currentTest;
160 > context = new Lazy(() => new SnapshotContext(currentTest));
161 > });
162 > teardown(async function () {
163 > if (this.currentTest?.state === 'passed') {
164 > await context?.rawValue?.removeOldSnapshots();
165 > }
166 > context = undefined;
167 > });
168 >
169 > /**
170 > * Implements a snapshot testing utility. ⚠️ This is async! ⚠️
171 > *
172 > * The first time a snapshot test is run, it'll record the value it's called
173 > * with as the expected value. Subsequent runs will fail if the value differs,
174 > * but the snapshot can be regenerated by hand or using the Selfhost Test
175 > * Provider Extension which'll offer to update it.
176 > *
177 > * The snapshot will be associated with the currently running test and stored
178 > * in a `__snapshots__` directory next to the test file, which is expected to
179 > * be the first `.test.js` file in the callstack.
180 > */
181 > export function assertSnapshot(value: unknown, options?: ISnapshotOptions): Promise<void> {
182 > if (!context) { snapshot.ts ×5
183 throw new Error('assertSnapshot can only be used in a test');
184 }
186 > return context.value.assert(value, options);
187 > }