-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrun.js
325 lines (290 loc) · 10.6 KB
/
run.js
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
/* eslint-disable no-prototype-builtins */
import engine, { createArbitrary } from './methods.js'
import { parse } from './parser/dsl.js'
import { serialize, snapshot } from './snapshot.js'
import { hash } from './hash.js'
import { SpecialHoF, ConstantFunc } from './symbols.js'
import { failure, parseFailure, success, testRuntimeFailure, snapshotsUnused } from './outputs.js'
import fc from 'fast-check'
import { argumentsToArbitraries } from './utils.js'
import { always, once } from 'ramda'
import url from 'url'
// Todo: Add support for other locales.
import { Faker, en } from '@faker-js/faker'
const init = once(() => {
// Adding in each of the Faker Methods as Arbitrary Generators
const realms = Object.keys(ArbitraryFaker).filter(i => !i.startsWith('_') && !i.includes('efinition') && !i.includes('helpers'))
for (const realm of realms) {
const definitions = Object.keys(ArbitraryFaker[realm]).reduce((acc, method) => {
const fn = ArbitraryFaker[realm][method]
if (typeof fn === 'function') {
const key = `${realm}.${method}`
acc[key] = (...args) => fc.nat().noShrink().map(() => fn(...args))
}
return acc
}, {})
addDefinitions(() => definitions)
}
})
// Global Log Injection //
if (!global.currentLog) global.currentLog = ''
global.log = (v, file, line, expr) => {
// get cwd
const cwd = process.cwd()
let extract = i => i
if (expr !== '@') {
try {
const func = engine.fallback.build(parse(expr.trim(), { startRule: 'Expression' }))
extract = data => func({ data })
} catch (e) {}
}
try {
global.currentLog += `${file.replace(cwd, '.')}:${line}: ${serialize(extract(v))}\n`
} catch (e) {
global.currentLog += `${file.replace(cwd, '.')}:${line}: ${extract(v)}\n`
}
return v
}
export function flush () {
if (global.currentLog) console.log(global.currentLog)
global.currentLog = ''
}
// End Global Log Injection //
const ArbitraryFaker = new Faker({ locale: [en] })
const snap = snapshotManager()
function snapshotManager () {
const snapshots = {}
/**
* @param {string} file
*/
const result = (file) => {
file = url.fileURLToPath(`${file.substring(0, file.lastIndexOf(':'))}.psnap`)
if (!snapshots[file]) snapshots[file] = snapshot(file)
return snapshots[file]
}
result.check = async (mode = false) => {
const tests = []
for (const file in snapshots) {
const remaining = await snapshots[file].notAccessed
if (mode === 'clean') {
for (const item of Array.from(remaining).filter(i => {
if (i.endsWith('.meta')) {
// todo: make this clean up when the original is gone from the snapshot via manual edit
return remaining.has(
i.substring(0, i.lastIndexOf('.meta'))
)
}
return true
})) await snapshots[file].remove(item)
} else if (remaining.size) {
tests.push(...Array.from(remaining).map(item => [file, item]).filter(([, item]) => {
return !item.endsWith('.meta')
}))
}
}
if (tests.length) {
snapshotsUnused(tests, mode)
// if strict, return 1, otherwise 0
return +mode
}
return 0
}
return result
}
export const check = snap.check
/**
* Adds a method to the Pineapple JSON Logic Engine.
* @param {string} name
* @param {(...args: any[]) => any} fn
*/
export function addMethod (name, fn) {
engine.addMethod(name, data => fn(...[].concat(data)), {
sync: fn.constructor.name !== 'AsyncFunction'
})
}
/**
* Adds a faker method to the Pineapple JSON Logic Engine.
* @param {string} name
* @param {(...args: any[]) => any} fn
*/
export function addFaker (name, fn) {
return addDefinitions(() => ({
[name]: (...args) => fc.nat().noShrink().map(() => fn(ArbitraryFaker, ...args))
}))
}
/**
* Executes the method passed in, and adds the arbitraries to the engine.
* @param {(...args: any[]) => ({ [key: string]: any })} fn
* @param {string} category
*/
export function addDefinitions (fn, category = '') {
const definitions = fn()
category = category.trim() ? `${category}.` : ''
Object.keys(definitions).forEach(key => {
if (typeof definitions[key] === 'function') {
return engine.addMethod(`#${category}${key}`, createArbitrary(definitions[key]), { sync: true })
}
// todo: come up with a better way to detect that it's an arbitrary; there's probably a much better way
if (definitions[key] instanceof fc.Arbitrary || (definitions[key].constructor && definitions[key].constructor.toString().includes('extends Arbitrary'))) {
return engine.addMethod(`#${category}${key}`, always(definitions[key]), { sync: true })
}
const func = always(fc.constant(definitions[key]))
func[ConstantFunc] = true
return engine.addMethod(`#${category}${key}`, func, { sync: true })
})
}
/**
* Just executes the expression, used for "before" / "beforeEach" / "after" / "afterEach".
* @param {string} input
*/
export async function execute (input) {
const ast = parse(input, { startRule: 'Expression' })
await engine.run(ast)
}
class FuzzError extends Error {
constructor (counterExample, seed, message, shrunk) {
super()
this.counterExample = counterExample
this.seed = seed
this.shrunk = shrunk
this.message = message
}
}
/**
* Runs the tests in the Pineapple JSON Logic Engine.
* @param {string} input
* @param {string} id
* @param {(...args: any[]) => any} func
* @param {string} file
*/
export async function run (input, id, func, file) {
// This will run any necessary setup code.
init()
/**
* @param {string} input
* @param {string} id
* @param {(...args: any[]) => any} func
* @returns {Promise<[any, boolean] | [any, false, string]>}
*/
async function internalRun (input, func) {
const script = parse(input)
const h = hash(input)
let result = [func]
let lastSpecial = false
for (const step of script) {
// Override to break the special "hof" class thing.
if (lastSpecial) {
if (!Object.values(step)[0][0].special && typeof result[0].result === 'function') result[0] = result[0].result
}
const [current] = result
if (typeof result[0] !== 'function') return [result[0], false, 'Does not return a function.']
const key = Object.keys(step)[0]
const [inputs, expectation] = step[key]
const arbs = await argumentsToArbitraries({ data: current.result }, ...inputs)
let numRuns = +process.env.FAST_CHECK_NUM_RUNS || 100
// If the arguments are absolutely constant, run once
if (arbs.constant) numRuns = 1
// if there's only one argument and it has a fixed size, set the size to that.
else if (arbs.length === 1 && arbs[0].size) numRuns = arbs[0].size
// otherwise, reduce the number of runs for a snapshot
// todo: make this configurable
else if (key === 'snapshot') numRuns = +process.env.SNAPSHOT_FAST_CHECK_NUM_RUNS || 10
let failed = null
try {
let count = 0
const snapshot = snap(file)
if (key === 'snapshot') ArbitraryFaker.seed(parseInt(h.substring(0, 16), 16))
await fc.assert(fc.asyncProperty(...arbs, async (...args) => {
count++
// Hijack the seed for now, keep it simple
const countStr = count > 1 ? `.${count}` : ''
result = await engine.run({
[key]: [{ preserve: args }, expectation]
}, { func: current, id: (`${id}(${input})${countStr}`), snap: snapshot, hash: h, rule: input, file, args, context: current.instance, fuzzed: !arbs.constant })
if (!result[1]) failed = result
return result[1]
}), {
// If it's a snapshot, or there is more than one step in the test, make it consistent.
seed: (key === 'snapshot' || script.length > 1) ? parseInt(h.substring(0, 16), 16) : undefined,
numRuns,
// If this is a snapshot test, but the snapshot does not exist, do not time out.
...(process.env.TEST_TIMEOUT && (key !== 'snapshot' || await snapshot.find(`${id}(${input})`).exists) && {
markInterruptAsFailure: true,
interruptAfterTimeLimit: +process.env.TEST_TIMEOUT
}),
reporter (out) {
if (out.failed) {
if (out.interrupted) throw new FuzzError(out.counterexample, out.seed, 'Test timed out.', out.numShrinks)
throw new FuzzError(out.counterexample, out.seed, out.error, out.numShrinks)
}
}
})
} catch (e) {
if (!failed) return [e, false, 'An unexpected issue was encountered.']
if (e instanceof FuzzError && !arbs.constant) {
failed[2] = (failed[2] || '') + `\nFailing Example: ${serialize(e.counterExample)}\nShrunk ${e.shrunk} times.\nSeed: ${e.seed}`
}
}
const [data, success, message] = result
if (failed) return failed
if (!success) return [data, false, message]
// Special Override for the Class-Based HoF thing.
if (current[SpecialHoF]) {
if (typeof result[0] !== 'function') result[0] = current
lastSpecial = true
} else lastSpecial = false
}
return result
}
try {
const [data, success, message] = await internalRun(input, func)
if (!success) {
failure({ name: id, input, message, file, data })
flush()
return 1
}
} catch (err) {
if (err.expected) {
const { message } = err
parseFailure(id, input, message, file)
} else testRuntimeFailure(err)
flush()
return 1
}
success(id, input, file)
flush()
return 0
}
/**
* Tries to invoke "new" to construct a class,
* otherwise falls back to executing the function.
* @param {(...args: any) => any} ClassToUse
* @param {any[]} args
*/
function forceConstruct (ClassToUse, ...args) {
try {
return new ClassToUse(...args)
} catch (err) {
return ClassToUse(...args)
}
}
/**
* A way to turn a class into a higher-order function chain for testing purposes.
* @param {*} ClassToUse
* @param {boolean} staticClass
*/
export function hof (ClassToUse, staticClass = false) {
if (typeof ClassToUse !== 'function') ClassToUse = always(ClassToUse)
return (...args) => {
const instance = staticClass ? ClassToUse : forceConstruct(ClassToUse, ...args)
const f = (method, ...args) => {
if (!(method in instance && (instance.hasOwnProperty(method) || ClassToUse.prototype.hasOwnProperty(method)))) { throw new Error(`'${method}' is not a method of '${ClassToUse.name}'`) }
f.result = instance[method](...args)
return f
}
f[SpecialHoF] = true
f.instance = instance
if (staticClass) return f(...args)
return f
}
}