-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfuzzy.test.js
More file actions
311 lines (270 loc) · 8.06 KB
/
fuzzy.test.js
File metadata and controls
311 lines (270 loc) · 8.06 KB
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
const jsonPath = require("./");
const assert = require("node:assert");
const set = require("lodash/set");
const toPath = require("lodash/toPath");
const { test } = require("node:test");
const util = require("node:util");
/**
* Reproducible RNG: Mulberry32
* @param {number} seed
*/
function rng(seed) {
let a = seed >>> 0;
return function next() {
a |= 0;
a = (a + 0x6d2b79f5) | 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const seed = (process.env.SEED ? Number(process.env.SEED) : Date.now()) >>> 0;
const rand = rng(seed);
const ITERS = process.env.ITERS ? Number(process.env.ITERS) : 200_000;
// Keep generation JSON-safe on purpose (POJO fuzzer)
const JSON_TYPES = ["null", "boolean", "number", "string", "object", "array"];
const protoKeys = [
"__proto__",
"constructor",
"prototype",
"toString",
"hasOwnProperty",
];
const possibleObjectKeys = (() => {
// Include keys that stress path parsing (dots/brackets/etc)
const specials = [
"a",
"b",
"c",
"0",
"00",
"01",
"-1",
"x.y",
"x..y",
"x[y]",
"x[0]",
"x]y",
"x[y",
"",
" ",
" ",
"__proto__",
"constructor",
"prototype",
"toString",
"hasOwnProperty",
];
const randoms = new Set();
while (randoms.size < 30) {
randoms.add(Math.floor(rand() * 1e9).toString(36));
}
return specials.concat([...randoms]);
})();
test.skip("fuzzy: null path is not supported", () => {});
test.skip("fuzzy: proto keys in path are not supported", () => {});
test.skip("fuzzy: proto keys in value are dropped", () => {});
test("fuzzy set vs lodash/set (seeded)", () => {
for (let i = 0; i < ITERS; i++) {
try {
doTest(i);
} catch (e) {
// enrich error with seed + iteration for replay
e.message = `Seed=${seed} Iter=${i}\n` + (e.message || String(e));
throw e;
}
}
});
function cloneDeep(obj) {
return JSON.parse(JSON.stringify(obj));
}
function freezeDeep(obj) {
if (obj && typeof obj === "object") {
Object.freeze(obj);
for (const key of Object.keys(obj)) {
freezeDeep(obj[key]);
}
}
return obj;
}
function doTest(iter) {
let [object, path, value] = generateTestArgs();
if (path == null) return;
if (jsonPath.tokenize(path)?.some((key) => protoKeys.includes(key))) return;
if (/"__proto__"/.test(JSON.stringify(value))) return;
object = freezeDeep(cloneDeep(object));
value = freezeDeep(cloneDeep(value));
const result = jsonPath.set(object, path, value);
const ref = cloneDeep(lodashRef(object, path, value));
assert.deepStrictEqual(
result,
cloneDeep(ref),
getAssertMessage({ seed, iter, object, path, value, result, ref }),
);
}
function lodashRef(input, path, value) {
if (path === undefined || path === "") {
// mimic your semantics: if no path, return value (deep cloned)
return cloneDeep(value);
}
const base = input === null || typeof input !== "object" ? {} : input;
const out = cloneDeep(base);
const resolvedPath = toPath(path);
set(out, resolvedPath, value);
return out;
}
function generateTestArgs() {
const object = generateValue(6, ["object", "array"]);
const path = generatePath();
const value = generateValue(6, JSON_TYPES); // JSON-safe only
return [object, path, value];
}
/**
* @param {number} remainingDepth
* @param {string[]} allowedTypes
*/
function generateValue(remainingDepth, allowedTypes = JSON_TYPES) {
const type = allowedTypes[(rand() * allowedTypes.length) | 0];
switch (type) {
case "null":
return null;
case "boolean":
return rand() > 0.5;
case "number":
return generateNumberValue();
case "string":
return generateStringValue();
case "object":
return remainingDepth > 0 ? generateObjectValue(remainingDepth) : {};
case "array":
return remainingDepth > 0 ? generateArrayValue(remainingDepth) : [];
default:
throw new Error(`unknown type: ${type}`);
}
}
function generateNumberValue() {
// include edge-y numbers, but still JSON-safe (no NaN/Infinity)
const r = rand();
if (r < 0.05) return 0;
if (r < 0.1) return -0; // yep, JSON-stringify loses sign, but structuredClone keeps -0
if (r < 0.15) return 1;
if (r < 0.2) return -1;
if (r < 0.25) return 2147483647;
if (r < 0.3) return -2147483648;
return (rand() - 0.5) * 1e6;
}
function generateStringValue() {
const r = rand();
if (r < 0.1) return "";
if (r < 0.2) return "0";
if (r < 0.3) return ".";
if (r < 0.4) return "[]";
if (r < 0.5) return "__proto__";
if (r < 0.6) return "a.b";
return Math.floor(rand() * 1e12).toString(36);
}
/**
* @param {number} remainingDepth
*/
function generateObjectValue(remainingDepth) {
const obj = {};
const keys = (rand() * 8) | 0;
for (let i = 0; i < keys; i++) {
const nextDepth = remainingDepth - (1 + ((rand() * 3) | 0));
const k = generateKey();
// sometimes explicitly place null / primitive to force "overwrite mid path"
if (rand() < 0.15) {
obj[k] =
rand() < 0.5 ? null : generateValue(0, ["string", "number", "boolean"]);
} else {
obj[k] = nextDepth > 0 ? generateValue(nextDepth) : generateValue(0);
}
}
return obj;
}
/**
* @param {number} remainingDepth
*/
function generateArrayValue(remainingDepth) {
const len = (rand() * 8) | 0;
const arr = new Array(len);
for (let i = 0; i < len; i++) {
const nextDepth = remainingDepth - (1 + ((rand() * 3) | 0));
if (rand() < 0.2) {
// create holes sometimes
continue;
}
arr[i] = nextDepth > 0 ? generateValue(nextDepth) : generateValue(0);
}
return arr;
}
function generateKey() {
return possibleObjectKeys[(rand() * possibleObjectKeys.length) | 0];
}
function generatePath() {
// sometimes undefined / empty to test your special-case behavior
const r = rand();
if (r < 0.1) return undefined;
if (r < 0.15) return "";
const segments = [];
const depth = 1 + ((rand() * 10) | 0);
for (let i = 0; i < depth; i++) {
if (rand() < 0.5) {
// object segment
segments.push({ t: "key", v: generateKey() });
} else {
// array segment (including larger and negative)
const rr = rand();
let idx;
if (rr < 0.7) idx = (rand() * 10) | 0;
else if (rr < 0.9) idx = (rand() * 200) | 0;
else idx = -((rand() * 5) | 0);
segments.push({ t: "idx", v: idx });
}
}
// sometimes return path array directly to test non-string inputs
if (rand() < 0.2) {
return segments.map((segment) =>
segment.t === "idx" ? segment.v : String(segment.v),
);
}
// Build lodash-style path string with brackets for idx.
// For keys containing dots/brackets, lodash/set supports bracket-quoted form.
// We'll sometimes emit that to stress parsing.
let out = "";
for (let i = 0; i < segments.length; i++) {
const s = segments[i];
if (s.t === "idx") {
out += `[${s.v}]`;
continue;
}
const key = String(s.v);
const needsQuote = /[.\[\]\s]|^$/.test(key);
if (needsQuote && rand() < 0.5) {
// bracket quoted: ["a.b"]
out += `["${escapeForDoubleQuotes(key)}"]`;
} else {
// dot form, even if weird (lets you discover differences)
if (out && out[out.length - 1] !== "]") out += ".";
out += key;
}
}
// extra weirdness: occasionally add leading dot or trailing dot
if (rand() < 0.02) out = "." + out;
if (rand() < 0.02) out = out + ".";
return out;
}
function escapeForDoubleQuotes(s) {
return s.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
}
function getAssertMessage(ctx) {
// keep it readable + replayable
return (
`Seed=${ctx.seed} Iter=${ctx.iter} Path=${util.inspect(ctx.path, { depth: 1024 })}\n\n` +
`== path ==\n${util.inspect(jsonPath.tokenize(ctx.path), { depth: 1024 })}\n\n` +
`== object ==\n${util.inspect(ctx.object, { depth: 1024 })}\n\n` +
`== value ==\n${util.inspect(ctx.value, { depth: 1024 })}\n\n` +
`== result ==\n${util.inspect(ctx.result, { depth: 1024 })}\n\n` +
`== ref ==\n${util.inspect(ctx.ref, { depth: 1024 })}\n`
);
}