-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.ts
109 lines (99 loc) · 2.3 KB
/
test.ts
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
import {
assertThrowsAsync,
createHttpError,
RouterContext,
ServerRequest,
httpErrors,
Request,
} from "./deps.ts";
import {
coreMiddleware,
} from "./mod.ts";
const encoder = new TextEncoder();
function createMockBodyReader(body: string): Deno.Reader {
const buf = encoder.encode(body);
let offset = 0;
return {
async read(p: Uint8Array): Promise<number | null> {
if (offset >= buf.length) {
return null;
}
const chunkSize = Math.min(p.length, buf.length - offset);
p.set(buf);
offset += chunkSize;
return chunkSize;
},
};
}
interface MockServerRequestOptions {
url?: string;
host?: string;
body?: string;
headerValues?: Record<string, string>;
proto?: string;
}
function createMockServerRequest(
{
url = "/",
host = "localhost",
body = "",
headerValues = {},
proto = "HTTP/1.1",
}: MockServerRequestOptions = {},
): ServerRequest {
const headers = new Headers();
headers.set("host", host);
for (const [key, value] of Object.entries(headerValues)) {
headers.set(key, value);
}
if (body.length && !headers.has("content-length")) {
headers.set("content-length", String(body.length));
}
return {
headers,
method: "GET",
url,
proto,
body: createMockBodyReader(body),
async respond() { },
} as any;
}
const mockContext = (
params: Record<string, string> = {},
body: string = "",
bodyType: string = "application/json",
): RouterContext => {
const request = new Request(createMockServerRequest({
url: createMockUrl(params),
body,
headerValues: {
"Content-Type": bodyType,
},
}));
const result = {
params,
request,
throw: (status: number, msg: string) => {
throw createHttpError(status, msg);
},
};
return result as unknown as RouterContext;
};
const mockNext = () => {
return new Promise<void>((resolve) => {
resolve();
});
};
const createMockUrl = (object: Record<string, string>) => {
let result = `http://foo.bar/?`;
for (let [key, value] of Object.entries(object)) {
result += `&${key}=${value}`;
}
result = result.replace("?&", "?");
result = result.endsWith("?") ? result.slice(undefined, -1) : result;
return result;
};
const tests: any[] = [];
for await (const test of tests) {
Deno.test(test);
}