| 1 |
// An initial implementation for a feature that will hopefully exist in tap |
| 2 |
// https://github.com/tapjs/node-tap/issues/789 |
| 3 |
// This file is only used in tests but it is still tested itself. |
| 4 |
// Hopefully it can be removed for a feature in tap in the future |
| 5 |
|
| 6 |
const sep = '.' |
| 7 |
const escapeSep = '"' |
| 8 |
const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k) |
| 9 |
const opd = (o, k) => Object.getOwnPropertyDescriptor(o, k) |
| 10 |
const po = (o) => Object.getPrototypeOf(o) |
| 11 |
const pojo = (o) => Object.prototype.toString.call(o) === '[object Object]' |
| 12 |
const last = (arr) => arr[arr.length - 1] |
| 13 |
const dupes = (arr) => arr.filter((k, i) => arr.indexOf(k) !== i) |
| 14 |
const dupesStartsWith = (arr) => arr.filter((k1) => arr.some((k2) => k2.startsWith(k1 + sep))) |
| 15 |
|
| 16 |
const splitLastSep = (str) => { |
| 17 |
let escaped = false |
| 18 |
for (let i = str.length - 1; i >= 0; i--) { |
| 19 |
const c = str[i] |
| 20 |
const cp = str[i + 1] |
| 21 |
const cn = str[i - 1] |
| 22 |
if (!escaped && c === escapeSep && (cp == null || cp === sep)) { |
| 23 |
escaped = true |
| 24 |
continue |
| 25 |
} |
| 26 |
if (escaped && c === escapeSep && cn === sep) { |
| 27 |
escaped = false |
| 28 |
continue |
| 29 |
} |
| 30 |
if (!escaped && c === sep) { |
| 31 |
return [ |
| 32 |
str.slice(0, i), |
| 33 |
str.slice(i + 1).replace(new RegExp(`^${escapeSep}(.*)${escapeSep}$`), '$1'), |
| 34 |
] |
| 35 |
} |
| 36 |
} |
| 37 |
return [str] |
| 38 |
} |
| 39 |
|
| 40 |
// A weird getter that can look up keys on nested objects but also |
| 41 |
// match keys with dots in their names, eg { 'process.env': { TERM: 'a' } } |
| 42 |
// can be looked up with the key 'process.env.TERM' |
| 43 |
const get = (obj, key, childKey = '') => { |
| 44 |
if (has(obj, key)) { |
| 45 |
return childKey ? get(obj[key], childKey) : obj[key] |
| 46 |
} |
| 47 |
const split = splitLastSep(key) |
| 48 |
if (split.length === 2) { |
| 49 |
const [parentKey, prefix] = split |
| 50 |
return get( |
| 51 |
obj, |
| 52 |
parentKey, |
| 53 |
prefix + (childKey && sep + childKey) |
| 54 |
) |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
// Map an object to an array of nested keys separated by dots |
| 59 |
// { a: 1, b: { c: 2, d: [1] } } => ['a', 'b.c', 'b.d'] |
| 60 |
const getKeys = (values, p = '', acc = []) => |
| 61 |
Object.entries(values).reduce((memo, [k, value]) => { |
| 62 |
const key = p ? [p, k].join(sep) : k |
| 63 |
return pojo(value) ? getKeys(value, key, memo) : memo.concat(key) |
| 64 |
}, acc) |
| 65 |
|
| 66 |
// Walk prototype chain to get first available descriptor. This is necessary |
| 67 |
// to get the current property descriptor for things like `process.on`. |
| 68 |
// Since `opd(process, 'on') === undefined` but if you |
| 69 |
// walk up the prototype chain you get the original descriptor |
| 70 |
// `opd(po(po(process)), 'on') === { value, ... }` |
| 71 |
const protoDescriptor = (obj, key) => { |
| 72 |
let descriptor |
| 73 |
// i always wanted to assign variables in a while loop's condition |
| 74 |
// i thought it would feel better than this |
| 75 |
while (!(descriptor = opd(obj, key))) { |
| 76 |
if (!(obj = po(obj))) { |
| 77 |
break |
| 78 |
} |
| 79 |
} |
| 80 |
return descriptor |
| 81 |
} |
| 82 |
|
| 83 |
// Path can be different cases across platform so get the original case |
| 84 |
// of the path before anything is changed |
| 85 |
// XXX: other special cases to handle? |
| 86 |
const specialCaseKeys = (() => { |
| 87 |
const originalKeys = { |
| 88 |
PATH: process.env.PATH ? 'PATH' : process.env.Path ? 'Path' : 'path', |
| 89 |
} |
| 90 |
return (key) => { |
| 91 |
switch (key.toLowerCase()) { |
| 92 |
case 'process.env.path': |
| 93 |
return originalKeys.PATH |
| 94 |
} |
| 95 |
} |
| 96 |
})() |
| 97 |
|
| 98 |
const _setGlobal = Symbol('setGlobal') |
| 99 |
const _nextDescriptor = Symbol('nextDescriptor') |
| 100 |
|
| 101 |
class DescriptorStack { |
| 102 |
#stack = [] |
| 103 |
#global = null |
| 104 |
#valueKey = null |
| 105 |
#defaultDescriptor = { configurable: true, writable: true, enumerable: true } |
| 106 |
#delete = () => ({ DELETE: true }) |
| 107 |
#isDelete = (o) => o && o.DELETE === true |
| 108 |
|
| 109 |
constructor (key) { |
| 110 |
const keys = splitLastSep(key) |
| 111 |
this.#global = keys.length === 1 ? global : get(global, keys[0]) |
| 112 |
this.#valueKey = specialCaseKeys(key) || last(keys) |
| 113 |
// If the global object doesnt return a descriptor for the key |
| 114 |
// then we mark it for deletion on teardown |
| 115 |
this.#stack = [ |
| 116 |
protoDescriptor(this.#global, this.#valueKey) || this.#delete(), |
| 117 |
] |
| 118 |
} |
| 119 |
|
| 120 |
add (value) { |
| 121 |
// This must be a unique object so we can find it later via indexOf |
| 122 |
// That's why delete/nextDescriptor create new objects |
| 123 |
const nextDescriptor = this[_nextDescriptor](value) |
| 124 |
this.#stack.push(this[_setGlobal](nextDescriptor)) |
| 125 |
|
| 126 |
return () => { |
| 127 |
const index = this.#stack.indexOf(nextDescriptor) |
| 128 |
// If the stack doesnt contain the descriptor anymore |
| 129 |
// than do nothing. This keeps the reset function idempotent |
| 130 |
if (index > -1) { |
| 131 |
// Resetting removes a descriptor from the stack |
| 132 |
this.#stack.splice(index, 1) |
| 133 |
// But we always reset to what is now the most recent in case |
| 134 |
// resets are being called manually out of order |
| 135 |
this[_setGlobal](last(this.#stack)) |
| 136 |
} |
| 137 |
} |
| 138 |
} |
| 139 |
|
| 140 |
reset () { |
| 141 |
// Everything could be reset manually so only |
| 142 |
// teardown if we have an initial descriptor left |
| 143 |
// and then delete the rest of the stack |
| 144 |
if (this.#stack.length) { |
| 145 |
this[_setGlobal](this.#stack[0]) |
| 146 |
this.#stack.length = 0 |
| 147 |
} |
| 148 |
} |
| 149 |
|
| 150 |
[_setGlobal] (d) { |
| 151 |
if (this.#isDelete(d)) { |
| 152 |
delete this.#global[this.#valueKey] |
| 153 |
} else { |
| 154 |
Object.defineProperty(this.#global, this.#valueKey, d) |
| 155 |
} |
| 156 |
return d |
| 157 |
} |
| 158 |
|
| 159 |
[_nextDescriptor] (value) { |
| 160 |
if (value === undefined) { |
| 161 |
return this.#delete() |
| 162 |
} |
| 163 |
const d = last(this.#stack) |
| 164 |
return { |
| 165 |
// If the previous descriptor was one to delete the property |
| 166 |
// then use the default descriptor as the base |
| 167 |
...(this.#isDelete(d) ? this.#defaultDescriptor : d), |
| 168 |
...(d && d.get ? { get: () => value } : { value }), |
| 169 |
} |
| 170 |
} |
| 171 |
} |
| 172 |
|
| 173 |
class MockGlobals { |
| 174 |
#descriptors = {} |
| 175 |
|
| 176 |
register (globals, { replace = false } = {}) { |
| 177 |
// Replace means don't merge in object values but replace them instead |
| 178 |
// so we only get top level keys instead of walking the obj |
| 179 |
const keys = replace ? Object.keys(globals) : getKeys(globals) |
| 180 |
|
| 181 |
// An error state where due to object mode there are multiple global |
| 182 |
// values to be set with the same key |
| 183 |
const duplicates = dupes(keys) |
| 184 |
if (duplicates.length) { |
| 185 |
throw new Error(`mockGlobals was called with duplicate keys: ${duplicates}`) |
| 186 |
} |
| 187 |
|
| 188 |
// Another error where when in replace mode overlapping keys are set like |
| 189 |
// process and process.stdout which would cause unexpected behavior |
| 190 |
const overlapping = dupesStartsWith(keys) |
| 191 |
if (overlapping.length) { |
| 192 |
const message = overlapping |
| 193 |
.map((k) => `${k} -> ${keys.filter((kk) => kk.startsWith(k + sep))}`) |
| 194 |
throw new Error(`mockGlobals was called with overlapping keys: ${message}`) |
| 195 |
} |
| 196 |
|
| 197 |
// Set each property passed in and return fns to reset them |
| 198 |
// Return an object with each path as a key for manually resetting in each test |
| 199 |
return keys.reduce((acc, key) => { |
| 200 |
const desc = this.#descriptors[key] || (this.#descriptors[key] = new DescriptorStack(key)) |
| 201 |
acc[key] = desc.add(get(globals, key)) |
| 202 |
return acc |
| 203 |
}, {}) |
| 204 |
} |
| 205 |
|
| 206 |
teardown (key) { |
| 207 |
if (!key) { |
| 208 |
Object.values(this.#descriptors).forEach((d) => d.reset()) |
| 209 |
return |
| 210 |
} |
| 211 |
this.#descriptors[key].reset() |
| 212 |
} |
| 213 |
} |
| 214 |
|
| 215 |
// Each test has one instance of MockGlobals so it can be called multiple times per test |
| 216 |
// Its a weak map so that it can be garbage collected along with the tap tests without |
| 217 |
// needing to explicitly call cache.delete |
| 218 |
const cache = new WeakMap() |
| 219 |
|
| 220 |
module.exports = (t, globals, options) => { |
| 221 |
let instance = cache.get(t) |
| 222 |
if (!instance) { |
| 223 |
instance = cache.set(t, new MockGlobals()).get(t) |
| 224 |
// Teardown only needs to be initialized once. The instance |
| 225 |
// will keep track of its own state during the test |
| 226 |
t.teardown(() => instance.teardown()) |
| 227 |
} |
| 228 |
|
| 229 |
return { |
| 230 |
// Reset contains only the functions to reset the globals |
| 231 |
// set by this function call |
| 232 |
reset: instance.register(globals, options), |
| 233 |
// Teardown will reset across all calls tied to this test |
| 234 |
teardown: () => instance.teardown(), |
| 235 |
} |
| 236 |
} |