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