|
| 1 | +'use strict'; |
| 2 | +const { |
| 3 | + ArrayPrototypeJoin, |
| 4 | + ArrayPrototypeMap, |
| 5 | + ArrayPrototypeSort, |
| 6 | + JSONStringify, |
| 7 | + ObjectKeys, |
| 8 | + SafeMap, |
| 9 | + String, |
| 10 | + StringPrototypeReplaceAll, |
| 11 | +} = primordials; |
| 12 | +const { |
| 13 | + codes: { |
| 14 | + ERR_INVALID_STATE, |
| 15 | + }, |
| 16 | +} = require('internal/errors'); |
| 17 | +const { emitExperimentalWarning, kEmptyObject } = require('internal/util'); |
| 18 | +let debug = require('internal/util/debuglog').debuglog('test_runner', (fn) => { |
| 19 | + debug = fn; |
| 20 | +}); |
| 21 | +const { |
| 22 | + validateArray, |
| 23 | + validateFunction, |
| 24 | + validateObject, |
| 25 | +} = require('internal/validators'); |
| 26 | +const { strictEqual } = require('assert'); |
| 27 | +const { mkdirSync, readFileSync, writeFileSync } = require('fs'); |
| 28 | +const { dirname } = require('path'); |
| 29 | +const { createContext, runInContext } = require('vm'); |
| 30 | +const kExperimentalWarning = 'Snapshot testing'; |
| 31 | +const kMissingSnapshotTip = 'Missing snapshots can be generated by rerunning ' + |
| 32 | + 'the command with the --test-update-snapshots flag.'; |
| 33 | +const defaultSerializers = [ |
| 34 | + (value) => { return JSONStringify(value, null, 2); }, |
| 35 | +]; |
| 36 | + |
| 37 | +function defaultResolveSnapshotPath(testPath) { |
| 38 | + if (typeof testPath !== 'string') { |
| 39 | + return testPath; |
| 40 | + } |
| 41 | + |
| 42 | + return `${testPath}.snapshot`; |
| 43 | +} |
| 44 | + |
| 45 | +let resolveSnapshotPathFn = defaultResolveSnapshotPath; |
| 46 | +let serializerFns = defaultSerializers; |
| 47 | + |
| 48 | +function setResolveSnapshotPath(fn) { |
| 49 | + emitExperimentalWarning(kExperimentalWarning); |
| 50 | + validateFunction(fn, 'fn'); |
| 51 | + resolveSnapshotPathFn = fn; |
| 52 | +} |
| 53 | + |
| 54 | +function setDefaultSerializers(serializers) { |
| 55 | + emitExperimentalWarning(kExperimentalWarning); |
| 56 | + validateFunctionArray(serializers, 'serializers'); |
| 57 | + serializerFns = ArrayPrototypeMap(serializers, (fn) => { |
| 58 | + return fn; |
| 59 | + }); |
| 60 | +} |
| 61 | + |
| 62 | +class SnapshotManager { |
| 63 | + constructor(entryFile, updateSnapshots) { |
| 64 | + this.entryFile = entryFile; |
| 65 | + this.snapshotFile = undefined; |
| 66 | + this.snapshots = { __proto__: null }; |
| 67 | + this.nameCounts = new SafeMap(); |
| 68 | + // A manager instance will only read or write snapshot files based on the |
| 69 | + // updateSnapshots argument. |
| 70 | + this.loaded = updateSnapshots; |
| 71 | + this.updateSnapshots = updateSnapshots; |
| 72 | + } |
| 73 | + |
| 74 | + resolveSnapshotFile() { |
| 75 | + if (this.snapshotFile === undefined) { |
| 76 | + const resolved = resolveSnapshotPathFn(this.entryFile); |
| 77 | + |
| 78 | + if (typeof resolved !== 'string') { |
| 79 | + const err = new ERR_INVALID_STATE('Invalid snapshot filename.'); |
| 80 | + err.filename = resolved; |
| 81 | + throw err; |
| 82 | + } |
| 83 | + |
| 84 | + this.snapshotFile = resolved; |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + serialize(input, serializers = serializerFns) { |
| 89 | + try { |
| 90 | + let value = input; |
| 91 | + |
| 92 | + for (let i = 0; i < serializers.length; ++i) { |
| 93 | + const fn = serializers[i]; |
| 94 | + value = fn(value); |
| 95 | + } |
| 96 | + |
| 97 | + return `\n${templateEscape(value)}\n`; |
| 98 | + } catch (err) { |
| 99 | + const error = new ERR_INVALID_STATE( |
| 100 | + 'The provided serializers did not generate a string.', |
| 101 | + ); |
| 102 | + error.input = input; |
| 103 | + error.cause = err; |
| 104 | + throw error; |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + getSnapshot(id) { |
| 109 | + if (!(id in this.snapshots)) { |
| 110 | + const err = new ERR_INVALID_STATE(`Snapshot '${id}' not found in ` + |
| 111 | + `'${this.snapshotFile}.' ${kMissingSnapshotTip}`); |
| 112 | + err.snapshot = id; |
| 113 | + err.filename = this.snapshotFile; |
| 114 | + throw err; |
| 115 | + } |
| 116 | + |
| 117 | + return this.snapshots[id]; |
| 118 | + } |
| 119 | + |
| 120 | + setSnapshot(id, value) { |
| 121 | + this.snapshots[templateEscape(id)] = value; |
| 122 | + } |
| 123 | + |
| 124 | + nextId(name) { |
| 125 | + const count = this.nameCounts.get(name) ?? 1; |
| 126 | + |
| 127 | + this.nameCounts.set(name, count + 1); |
| 128 | + return `${name} ${count}`; |
| 129 | + } |
| 130 | + |
| 131 | + readSnapshotFile() { |
| 132 | + if (this.loaded) { |
| 133 | + debug('skipping read of snapshot file'); |
| 134 | + return; |
| 135 | + } |
| 136 | + |
| 137 | + try { |
| 138 | + const source = readFileSync(this.snapshotFile, 'utf8'); |
| 139 | + const context = { __proto__: null, exports: { __proto__: null } }; |
| 140 | + |
| 141 | + createContext(context); |
| 142 | + runInContext(source, context); |
| 143 | + |
| 144 | + if (context.exports === null || typeof context.exports !== 'object') { |
| 145 | + throw new ERR_INVALID_STATE( |
| 146 | + `Malformed snapshot file '${this.snapshotFile}'.`, |
| 147 | + ); |
| 148 | + } |
| 149 | + |
| 150 | + this.snapshots = context.exports; |
| 151 | + this.loaded = true; |
| 152 | + } catch (err) { |
| 153 | + let msg = `Cannot read snapshot file '${this.snapshotFile}.'`; |
| 154 | + |
| 155 | + if (err?.code === 'ENOENT') { |
| 156 | + msg += ` ${kMissingSnapshotTip}`; |
| 157 | + } |
| 158 | + |
| 159 | + const error = new ERR_INVALID_STATE(msg); |
| 160 | + error.cause = err; |
| 161 | + error.filename = this.snapshotFile; |
| 162 | + throw error; |
| 163 | + } |
| 164 | + } |
| 165 | + |
| 166 | + writeSnapshotFile() { |
| 167 | + if (!this.updateSnapshots) { |
| 168 | + debug('skipping write of snapshot file'); |
| 169 | + return; |
| 170 | + } |
| 171 | + |
| 172 | + const keys = ArrayPrototypeSort(ObjectKeys(this.snapshots)); |
| 173 | + const snapshotStrings = ArrayPrototypeMap(keys, (key) => { |
| 174 | + return `exports[\`${key}\`] = \`${this.snapshots[key]}\`;\n`; |
| 175 | + }); |
| 176 | + const output = ArrayPrototypeJoin(snapshotStrings, '\n'); |
| 177 | + mkdirSync(dirname(this.snapshotFile), { __proto__: null, recursive: true }); |
| 178 | + writeFileSync(this.snapshotFile, output, 'utf8'); |
| 179 | + } |
| 180 | + |
| 181 | + createAssert() { |
| 182 | + const manager = this; |
| 183 | + |
| 184 | + return function snapshotAssertion(actual, options = kEmptyObject) { |
| 185 | + emitExperimentalWarning(kExperimentalWarning); |
| 186 | + // Resolve the snapshot file here so that any resolution errors are |
| 187 | + // surfaced as early as possible. |
| 188 | + manager.resolveSnapshotFile(); |
| 189 | + |
| 190 | + const { fullName } = this; |
| 191 | + const id = manager.nextId(fullName); |
| 192 | + |
| 193 | + validateObject(options, 'options'); |
| 194 | + |
| 195 | + const { |
| 196 | + serializers = serializerFns, |
| 197 | + } = options; |
| 198 | + |
| 199 | + validateFunctionArray(serializers, 'options.serializers'); |
| 200 | + |
| 201 | + const value = manager.serialize(actual, serializers); |
| 202 | + |
| 203 | + if (manager.updateSnapshots) { |
| 204 | + manager.setSnapshot(id, value); |
| 205 | + } else { |
| 206 | + manager.readSnapshotFile(); |
| 207 | + strictEqual(value, manager.getSnapshot(id)); |
| 208 | + } |
| 209 | + }; |
| 210 | + } |
| 211 | +} |
| 212 | + |
| 213 | +function validateFunctionArray(fns, name) { |
| 214 | + validateArray(fns, name); |
| 215 | + for (let i = 0; i < fns.length; ++i) { |
| 216 | + validateFunction(fns[i], `${name}[${i}]`); |
| 217 | + } |
| 218 | +} |
| 219 | + |
| 220 | +function templateEscape(str) { |
| 221 | + let result = String(str); |
| 222 | + result = StringPrototypeReplaceAll(result, '\\', '\\\\'); |
| 223 | + result = StringPrototypeReplaceAll(result, '`', '\\`'); |
| 224 | + result = StringPrototypeReplaceAll(result, '${', '\\${'); |
| 225 | + return result; |
| 226 | +} |
| 227 | + |
| 228 | +module.exports = { |
| 229 | + SnapshotManager, |
| 230 | + defaultResolveSnapshotPath, // Exported for testing only. |
| 231 | + defaultSerializers, // Exported for testing only. |
| 232 | + setDefaultSerializers, |
| 233 | + setResolveSnapshotPath, |
| 234 | +}; |
0 commit comments