-
Notifications
You must be signed in to change notification settings - Fork 742
Expand file tree
/
Copy pathtest_utils.tsx
More file actions
343 lines (297 loc) · 8.69 KB
/
test_utils.tsx
File metadata and controls
343 lines (297 loc) · 8.69 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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
import type { App } from "../src/app.ts";
import { launch, type Page } from "@astral/astral";
import * as colors from "@std/fmt/colors";
import { DOMParser, HTMLElement } from "linkedom";
import { Builder, type BuildOptions } from "../src/dev/builder.ts";
import { TextLineStream } from "@std/streams/text-line-stream";
import * as path from "@std/path";
import type { ComponentChildren } from "preact";
import { expect } from "@std/expect";
import { mergeReadableStreams } from "@std/streams";
const browser = await launch({
args: [
"--window-size=1280,720",
...((Deno.env.get("CI") && Deno.build.os === "linux")
? ["--no-sandbox"]
: []),
],
headless: Deno.env.get("HEADLESS") !== "false",
});
export const charset = <meta charset="utf-8" />;
export const favicon = (
<link
href="data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQEAYAAABPYyMiAAAABmJLR0T///////8JWPfcAAAACXBIWXMAAABIAAAASABGyWs+AAAAF0lEQVRIx2NgGAWjYBSMglEwCkbBSAcACBAAAeaR9cIAAAAASUVORK5CYII="
rel="icon"
type="image/x-icon"
/>
);
export function Doc(props: { children?: ComponentChildren; title?: string }) {
return (
<html>
<head>
{charset}
<title>{props.title ?? "Test"}</title>
{favicon}
</head>
<body>
{props.children}
</body>
</html>
);
}
export const ALL_ISLAND_DIR = path.join(
import.meta.dirname!,
"fixtures_islands",
);
export const ISLAND_GROUP_DIR = path.join(
import.meta.dirname!,
"fixture_island_groups",
);
export async function buildProd(
options: Omit<BuildOptions, "outDir">,
): Promise<<T>(app: App<T>) => void> {
const outDir = await Deno.makeTempDir();
const builder = new Builder({ outDir, ...options });
return await builder.build({ mode: "production", snapshot: "memory" });
}
export async function withBrowserApp(
app: App<unknown>,
fn: (page: Page, address: string) => void | Promise<void>,
) {
const aborter = new AbortController();
await using server = Deno.serve({
hostname: "localhost",
port: 0,
signal: aborter.signal,
onListen: () => {}, // Don't spam terminal with "Listening on..."
}, app.handler());
try {
await using page = await browser.newPage();
await fn(page, `http://localhost:${server.addr.port}`);
} finally {
aborter.abort();
}
}
export async function withBrowser(fn: (page: Page) => void | Promise<void>) {
await using page = await browser.newPage();
try {
await fn(page);
} catch (err) {
const raw = await page.content();
const doc = parseHtml(raw);
const html = prettyDom(doc);
// deno-lint-ignore no-console
console.log(html);
throw err;
}
}
export async function withChildProcessServer(
dir: string,
args: string[],
fn: (address: string) => void | Promise<void>,
) {
const aborter = new AbortController();
const cp = await new Deno.Command(Deno.execPath(), {
args,
stdin: "null",
stdout: "piped",
stderr: "piped",
cwd: dir,
signal: aborter.signal,
}).spawn();
const linesStdout: ReadableStream<string> = cp.stdout
.pipeThrough(new TextDecoderStream())
.pipeThrough(new TextLineStream());
const linesStderr: ReadableStream<string> = cp.stderr
.pipeThrough(new TextDecoderStream())
.pipeThrough(new TextLineStream());
const lines = mergeReadableStreams(linesStdout, linesStderr);
const output: string[] = [];
let address = "";
let found = false;
// @ts-ignore yes it does
for await (const line of lines.values({ preventCancel: true })) {
output.push(line);
const match = line.match(
/https?:\/\/[^:]+:\d+(\/\w+[-\w]*)*/g,
);
if (match) {
address = match[0];
found = true;
break;
}
}
if (!found) {
// deno-lint-ignore no-console
console.log(output);
throw new Error(`Could not find server address`);
}
try {
await fn(address);
} finally {
aborter.abort();
await cp.status;
for await (const _ of lines) { /* noop */ }
}
}
export const VOID_ELEMENTS =
/^(?:area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)$/;
function prettyDom(doc: Document) {
let out = colors.dim(`<!DOCTYPE ${doc.doctype?.name ?? ""}>\n`);
const node = doc.documentElement;
out += _printDomNode(node, 0);
return out;
}
function _printDomNode(
node: HTMLElement | Text | Node,
indent: number,
) {
const space = " ".repeat(indent);
if (node.nodeType === 3) {
return space + colors.dim(node.textContent ?? "") + "\n";
} else if (node.nodeType === 8) {
return space + colors.dim(`<--${(node as Text).data}-->`) + "\n";
}
let out = space;
if (node instanceof HTMLElement || node instanceof HTMLMetaElement) {
out += colors.dim(colors.cyan("<"));
out += colors.cyan(node.localName);
for (let i = 0; i < node.attributes.length; i++) {
const attr = node.attributes.item(i);
if (attr === null) continue;
out += " " + colors.yellow(attr.name);
out += colors.dim("=");
out += colors.green(`"${attr.value}"`);
}
if (VOID_ELEMENTS.test(node.localName)) {
out += colors.dim(colors.cyan(">")) + "\n";
return out;
}
out += colors.dim(colors.cyan(">"));
if (node.childNodes.length) {
out += "\n";
for (let i = 0; i < node.childNodes.length; i++) {
const child = node.childNodes[i];
out += _printDomNode(child, indent + 1);
}
out += space;
}
out += colors.dim(colors.cyan("</"));
out += colors.cyan(node.localName);
out += colors.dim(colors.cyan(">"));
out += "\n";
}
return out;
}
export interface TestDocument extends Document {
debug(): void;
}
export function parseHtml(input: string): TestDocument {
// deno-lint-ignore no-explicit-any
const doc = new DOMParser().parseFromString(input, "text/html") as any;
Object.defineProperty(doc, "debug", {
// deno-lint-ignore no-console
value: () => console.log(prettyDom(doc)),
enumerable: false,
});
return doc;
}
export function assertSelector(doc: Document, selector: string) {
if (doc.querySelector(selector) === null) {
const html = prettyDom(doc);
throw new Error(
`Selector "${selector}" not found in document.\n\n${html}`,
);
}
}
export function assertNotSelector(doc: Document, selector: string) {
if (doc.querySelector(selector) !== null) {
const html = prettyDom(doc);
throw new Error(
`Selector "${selector}" found in document.\n\n${html}`,
);
}
}
export function assertMetaContent(
doc: Document,
nameOrProperty: string,
expected: string,
) {
let el = doc.querySelector(`meta[name="${nameOrProperty}"]`) as
| HTMLMetaElement
| null;
if (el === null) {
el = doc.querySelector(`meta[property="${nameOrProperty}"]`) as
| HTMLMetaElement
| null;
}
if (el === null) {
// deno-lint-ignore no-console
console.log(prettyDom(doc));
throw new Error(
`No <meta>-tag found with content "${expected}"`,
);
}
expect(el.content).toEqual(expected);
}
export async function waitForText(
page: Page,
selector: string,
text: string,
) {
await page.waitForSelector(selector);
try {
await page.waitForFunction(
(sel: string, value: string) => {
const el = document.querySelector(sel);
if (el === null) return false;
return el.textContent === value;
},
{ args: [selector, String(text)] },
);
} catch (err) {
const body = await page.content();
// deno-lint-ignore no-explicit-any
const pretty = prettyDom(parseHtml(body) as any);
// deno-lint-ignore no-console
console.log(
`Text "${text}" not found on selector "${selector}" in html:\n\n${pretty}`,
);
throw err;
}
}
export async function waitFor(
fn: () => Promise<unknown> | unknown,
): Promise<void> {
let now = Date.now();
const limit = now + 2000;
while (now < limit) {
try {
if (await fn()) return;
} catch (err) {
if (now > limit) {
throw err;
}
} finally {
await new Promise((r) => setTimeout(r, 250));
now = Date.now();
}
}
throw new Error(`Timed out`);
}
export function getStdOutput(
out: Deno.CommandOutput,
): { stdout: string; stderr: string } {
const decoder = new TextDecoder();
const stdout = colors.stripAnsiCode(decoder.decode(out.stdout));
const decoderErr = new TextDecoder();
const stderr = colors.stripAnsiCode(decoderErr.decode(out.stderr));
return { stdout, stderr };
}
const ISLAND_FIXTURE_DIR = path.join(import.meta.dirname!, "fixtures_islands");
const allIslandBuilder = new Builder({});
for await (const entry of Deno.readDirSync(ISLAND_FIXTURE_DIR)) {
if (entry.name.endsWith(".json")) continue;
const spec = path.join(ISLAND_FIXTURE_DIR, entry.name);
allIslandBuilder.registerIsland(spec);
}