-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
222 lines (197 loc) · 7.17 KB
/
index.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
// in the browser, require returns an empty object
const env = typeof window === "object" ? "browser" : "node";
if (env === "browser") {
window.require = () => ({});
window.process = { env: {} };
}
const { deepStrictEqual } = require("assert");
const { readFileSync } = require("fs");
const DEEP_STRICT_EQUAL_ERROR_MESSAGE = "AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:";
const TIME_MS = 250;
const COLORS = { BLUE: "\x1b[34m", GREEN: "\x1b[32m", YELLOW: "\x1b[33m", PURPLE: "\x1b[35m", RED: "\x1b[31m", OFF: "\x1B[39m" };
const PLUS = COLORS.YELLOW + "+" + COLORS.OFF;
const MINUS = COLORS.PURPLE + "-" + COLORS.OFF;
/** print out caller file path on top of each */
const queue = [];
const complete = [];
const sleep_seconds = duration =>
new Promise(resolve => {
setTimeout(() => resolve(), duration * 1000);
});
let ran = 0;
const run = async ({ name, cb, caller }) => {
let savedActual, savedExpected;
const eq = function (actual, expected) {
if (arguments.length === 1) {
throw new Error("[flug] you only supplied one argument");
}
savedActual = actual;
savedExpected = expected;
if (deepStrictEqual) {
return deepStrictEqual(actual, expected);
} else if (JSON.stringify(actual) !== JSON.stringify(expected)) {
console.log("%c failed: " + name, "color: red");
console.log("%c\texpected:", "color: purple", expected);
console.log("%c\treceived:", "color: rgb(200, 200, 0)", actual);
throw new Error("");
}
};
try {
const GAP_TIME = Number(process.env.TEST_GAP_TIME || 0);
const start_time = performance.now();
// we use all these setTimeout calls
// to mitigate the ability of side-effects
// to block the main thread
await new Promise((resolve, reject) => {
setTimeout(async () => {
if (ran >= 1 && GAP_TIME) {
await sleep_seconds(GAP_TIME);
}
try {
await cb({ eq });
} catch (error) {
reject(error);
}
setTimeout(() => {
resolve();
}, 1);
}, 1);
});
if (caller !== complete[complete.length - 1]) {
// console.log("\n\n" + caller.split(":")[0]);
}
const end_time = performance.now();
const test_time = Math.round(end_time - start_time).toLocaleString() + "ms";
const TIMED = ["True", "TRUE", "true", "t", "1", "", true, 1].includes(process.env.TEST_TIMED);
if (env === "browser") {
console.log("%c success" + (TIMED ? " (" + test_time + ")" : "") + ": " + name, "color: green");
} else {
console.log(COLORS.GREEN + "%s\x1b[0m", "success" + (TIMED ? " (" + test_time + ")" : "") + ": " + name);
}
} catch (error) {
console.error("\n" + COLORS.RED + "%s\x1b[0m", "failed: " + name);
let msg = error.toString();
const stack_lines = typeof error.stack === "string" ? error.stack.split("\n") : [];
const filtered_lines = stack_lines
.slice(
stack_lines.findIndex(ln => ln.trim().startsWith("at")),
stack_lines.findIndex(ln => ln.includes("node:internal"))
)
.filter(ln => !ln.includes("flug/index") && !ln.includes("runMicrotasks (<anonymous>)"));
const new_stack = filtered_lines.join("\n");
if (msg.startsWith(DEEP_STRICT_EQUAL_ERROR_MESSAGE)) {
let output;
output = msg.split("\n").slice(3).join("\n").replaceAll("\x1B[32m+\x1B[39m", ` ${PLUS}:`).replaceAll("\x1B[31m-\x1B[39m", ` ${MINUS}:`);
let stringable = false;
try {
stringable = JSON.stringify(savedActual).length < 200 && JSON.stringify(savedExpected).length < 200;
} catch (error) {}
if (stringable) {
output = `${COLORS.PURPLE}expected:${COLORS.OFF} ${JSON.stringify(savedExpected)}\n${COLORS.YELLOW}received:${COLORS.OFF} ${JSON.stringify(savedActual)}\n`;
} else if (`${savedActual}`.indexOf("[object") === -1 && `${savedExpected}`.indexOf("[object") === -1) {
output = `${COLORS.PURPLE}expected:${COLORS.OFF} ${savedExpected}\n${COLORS.YELLOW}received:${COLORS.OFF} ${savedActual}\n`;
} else if (output.includes(PLUS) || output.includes(MINUS)) {
output += `\nkey: ${COLORS.YELLOW}received +${COLORS.OFF} ${COLORS.PURPLE}expected: -${COLORS.OFF}\n`;
}
try {
const ln = filtered_lines[0];
const [filepath, row, col] = ln.replace("at", "").trim().split(":");
const text = readFileSync(filepath, "utf-8")
.split(/\n\r?/g)
[row - 1].substring(col - 1);
output += `${COLORS.BLUE}line:${COLORS.OFF} "${text}"`;
} catch (e) {
// pass
}
output += "\n\n";
if (new_stack.length > 0) {
output += new_stack;
output += "\n\n";
}
console.error(output);
} else {
let output = msg;
output += "\n\n";
if (new_stack.length > 0) {
output += new_stack;
output += "\n\n";
}
console.error(output);
}
if (env === "node") {
process.exit(1);
}
}
ran++;
};
const skip = name => {
if (!["false", "False", "FALSE", "0"].includes(process.env.LOG_SKIP)) {
if (env === "browser") {
console.log("%c skipped: " + name, "color: rgb(200, 200, 0)");
} else {
console.log(COLORS.YELLOW + "skipped: " + name + COLORS.OFF);
}
}
};
const test = (name, cb) => {
let caller;
try {
const lines = Error().stack.split(/ *\n\r? */g);
const ln = lines[2];
if (env === "browser") {
// in Browser, at http://localhost:8080/test.html:8:12
caller = ln.replace("at ", "").trim();
} else {
// in NodeJS, at Object.<anonymous> (/path/to/file.js:3:1)
caller = ln.substring(ln.indexOf("(") + 1, ln.lastIndexOf(")"));
}
} catch (error) {
caller = undefined;
}
if (process.env.TEST_NAME) {
const testName = process.env.TEST_NAME.trim();
if (testName.includes("*")) {
const re = new RegExp("^" + testName.replace(/\./g, "\\.").replace(/\*/g, ".*").replace(/\[/, "\\[").replace(/\]/, "\\]") + "$", "g");
if (!re.test(name)) {
return skip(name);
}
} else if (testName !== name) {
return skip(name);
}
}
if (process.env.TEST_FILE || process.env.TEST_DIR) {
if ((process.env.TEST_FILE && process.env.TEST_FILE !== caller.split("/").slice(-1)[0].split(":")[0]) || (process.env.TEST_DIR && process.env.TEST_DIR !== caller.split("/").slice(-2, -1)[0])) return skip(name);
}
queue.push({ name, caller });
const proceed = async () => {
if (queue[0].name === name && queue[0].caller === caller) {
await Promise.resolve(run({ name, cb, caller }));
complete.push(queue.shift()); // remove first test in queue
} else {
setTimeout(proceed, TIME_MS);
}
};
setTimeout(proceed, TIME_MS);
// checkQueue keeps the main thread alive
// until the queue is complete
const checkQueue = () => {
if (queue.length > 0) {
setTimeout(checkQueue, TIME_MS);
}
};
checkQueue();
};
if (typeof define === "function" && define.amd) {
define(function () {
return test;
});
}
if (typeof module === "object") {
// seem to be in NodeJS
module.exports = test;
module.exports.default = test;
}
if (typeof window == "object") {
// seem to be in a browser
window.flug = { test };
}