aboutsummaryrefslogtreecommitdiff
path: root/test/js/deno/harness.ts
blob: ab8e35527a0512eb6528a4e04457d61062eb4b32 (plain) (blame)
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
344
345
346
347
348
349
350
351
352
353
import type { Server } from "bun";
import { serve, deepEquals, concatArrayBuffers } from "bun";
import { hideFromStackTrace } from "harness";
import resources from "./resources.json";

type Fn = () => void | Promise<unknown>;
type Options = {
  permissions?:
    | "none"
    | {
        net?: boolean;
        read?: boolean;
      };
  ignore?: boolean;
};

/**
 * @example
 * const { test, assert } = createDenoTest(import.meta.path);
 * test(function testAssert() {
 *   assert(true);
 * });
 */
export function createDenoTest(path: string) {
  const { expect, test, beforeAll, afterAll } = Bun.jest(path);

  let server: Server;

  beforeAll(() => {
    server = serve({
      port: 4545,
      fetch(request: Request): Response {
        const { url } = request;
        const { pathname, search } = new URL(url);
        if (pathname === "/echo_server") {
          return new Response(request.body, request);
        }
        const target = new URL(`${pathname}${search}`, resources.baseUrl);
        return Response.redirect(target.toString());
      },
    });
  });

  afterAll(() => {
    if (server) {
      server.stop(true);
    }
  });

  // https://deno.land/api@v1.31.2?s=Deno.test

  const denoTest = (arg0: Fn | Options, arg1?: Fn) => {
    if (typeof arg0 === "function") {
      test(arg0.name, arg0);
    } else if (typeof arg1 === "function") {
      if (
        arg0?.ignore === true ||
        arg0?.permissions === "none" ||
        arg0?.permissions?.net === false ||
        arg0?.permissions?.read === false
      ) {
        test.skip(arg1.name, arg1);
      } else {
        test(arg1.name, arg1);
      }
    } else {
      unimplemented(`test(${typeof arg0}, ${typeof arg1})`);
    }
  };

  denoTest.ignore = (arg0: Fn | Options, arg1?: Fn) => {
    if (typeof arg0 === "function") {
      test.skip(arg0.name, arg0);
    } else if (typeof arg1 === "function") {
      test.skip(arg1.name, arg1);
    } else {
      unimplemented(`test.ignore(${typeof arg0}, ${typeof arg1})`);
    }
  };

  // Deno's assertions implemented using expect().
  // https://github.com/denoland/deno/blob/main/cli/tests/unit/test_util.ts

  const assert = (condition: unknown, message?: string) => {
    expect(condition).toBeTruthy();
  };

  const assertFalse = (condition: unknown, message?: string) => {
    expect(condition).toBeFalsy();
  };

  const assertEquals = (actual: unknown, expected: unknown, message?: string) => {
    expect(actual).toEqual(expected);
  };

  const assertExists = (value: unknown, message?: string) => {
    expect(value).toBeDefined();
  };

  const assertNotEquals = (actual: unknown, expected: unknown, message?: string) => {
    expect(actual).not.toEqual(expected);
  };

  const assertStrictEquals = (actual: unknown, expected: unknown, message?: string) => {
    expect(actual).toStrictEqual(expected);
  };

  const assertNotStrictEquals = (actual: unknown, expected: unknown, message?: string) => {
    expect(actual).not.toStrictEqual(expected);
  };

  const assertAlmostEquals = (actual: unknown, expected: number, epsilon: number = 1e-7, message?: string) => {
    if (typeof actual === "number") {
      // TODO: toBeCloseTo()
      expect(Math.abs(actual - expected)).toBeLessThanOrEqual(epsilon);
    } else {
      expect(typeof actual).toBe("number");
    }
  };

  const assertInstanceOf = (actual: unknown, expected: unknown, message?: string) => {
    expect(actual).toBeInstanceOf(expected);
  };

  const assertNotInstanceOf = (actual: unknown, expected: unknown, message?: string) => {
    expect(actual).not.toBeInstanceOf(expected);
  };

  const assertStringIncludes = (actual: unknown, expected: string, message?: string) => {
    if (typeof actual === "string") {
      expect(actual).toContain(expected);
    } else {
      expect(typeof actual).toBe("string");
    }
  };

  const assertArrayIncludes = (actual: unknown, expected: unknown[], message?: string) => {
    if (Array.isArray(actual)) {
      for (const value of expected) {
        expect(actual).toContain(value);
      }
    } else {
      expect(Array.isArray(actual)).toBe(true);
    }
  };

  const assertMatch = (actual: unknown, expected: RegExp, message?: string) => {
    if (typeof actual === "string") {
      expect(expected.test(actual)).toBe(true);
    } else {
      expect(typeof actual).toBe("string");
    }
  };

  const assertNotMatch = (actual: unknown, expected: RegExp, message?: string) => {
    if (typeof actual === "string") {
      expect(expected.test(actual)).toBe(false);
    } else {
      expect(typeof actual).toBe("string");
    }
  };

  const assertObjectMatch = (actual: unknown, expected: Record<PropertyKey, unknown>, message?: string) => {
    if (typeof actual === "object") {
      // TODO: toMatchObject()
      if (actual !== null) {
        const expectedKeys = Object.keys(expected);
        for (const key of Object.keys(actual)) {
          if (!expectedKeys.includes(key)) {
            // @ts-ignore
            delete actual[key];
          }
        }
        expect(actual).toEqual(expected);
      } else {
        expect(actual).not.toBeNull();
      }
    } else {
      expect(typeof actual).toBe("object");
    }
  };

  const assertThrows = (fn: () => void, message?: string) => {
    try {
      fn();
    } catch (error) {
      expect(error).toBeDefined();
      return;
    }
    throw new Error("Expected an error to be thrown");
  };

  const assertRejects = async (fn: () => Promise<unknown>, message?: string) => {
    try {
      await fn();
    } catch (error) {
      expect(error).toBeDefined();
      return;
    }
    throw new Error("Expected an error to be thrown");
  };

  const equal = (a: unknown, b: unknown) => {
    return deepEquals(a, b);
  };

  const fail = (message: string): never => {
    throw new Error(message);
  };

  const unimplemented = (message: string): never => {
    throw new Error(`Unimplemented: ${message}`);
  };

  const unreachable = (): never => {
    throw new Error("Unreachable");
  };

  // Copyright 2018+ the Deno authors. All rights reserved. MIT license.
  // https://github.com/denoland/deno/blob/main/ext/node/polyfills/_util/async.ts

  const deferred = () => {
    let methods;
    let state = "pending";
    const promise = new Promise((resolve, reject) => {
      methods = {
        async resolve(value: unknown) {
          await value;
          state = "fulfilled";
          resolve(value);
        },
        reject(reason?: unknown) {
          state = "rejected";
          reject(reason);
        },
      };
    });
    Object.defineProperty(promise, "state", { get: () => state });
    return Object.assign(promise, methods);
  };

  const delay = async (ms: number, options: { signal?: AbortSignal } = {}) => {
    const { signal } = options;
    if (signal?.aborted) {
      return Promise.reject(new DOMException("Delay was aborted.", "AbortError"));
    }
    return new Promise<void>((resolve, reject) => {
      const abort = () => {
        clearTimeout(i);
        reject(new DOMException("Delay was aborted.", "AbortError"));
      };
      const done = () => {
        signal?.removeEventListener("abort", abort);
        resolve();
      };
      const i = setTimeout(done, ms);
      signal?.addEventListener("abort", abort, { once: true });
    });
  };

  // https://deno.land/std@0.171.0/bytes/concat.ts

  const concat = (...buffers: Uint8Array[]): Uint8Array => {
    return new Uint8Array(concatArrayBuffers(buffers));
  };

  // https://deno.land/api@v1.31.1?s=Deno.readTextFile

  const readTextFile = async (path: string): Promise<string> => {
    const url = new URL(path, resources.baseUrl);
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`${response.status}: ${response.url}`);
    }
    return response.text();
  };

  // Globals

  const window = {
    crypto,
  };

  // @ts-ignore
  globalThis.window = window;

  const internal = Symbol("Deno[internal]");
  const mockInternal = {
    get(target: unknown, property: unknown) {
      if (property === "inspectArgs") {
        return {};
      }
      throw new Error(`Deno[Deno.internal].${property}`);
    },
  };
  hideFromStackTrace(mockInternal.get);

  const mockInspect = () => {
    throw new Error("Deno.inspect()");
  };
  hideFromStackTrace(mockInspect);

  const Deno = {
    test: denoTest,
    readTextFile,
    internal,
    [internal]: new Proxy({}, mockInternal),
    inspect: mockInspect,
  };

  // @ts-ignore
  globalThis.Deno = Deno;

  const exports = {
    test: denoTest,
    assert,
    assertFalse,
    assertEquals,
    assertExists,
    assertNotEquals,
    assertStrictEquals,
    assertNotStrictEquals,
    assertAlmostEquals,
    assertInstanceOf,
    assertNotInstanceOf,
    assertStringIncludes,
    assertArrayIncludes,
    assertMatch,
    assertNotMatch,
    assertObjectMatch,
    assertThrows,
    assertRejects,
    equal,
    fail,
    unimplemented,
    unreachable,
    deferred,
    delay,
    concat,
  };

  for (const property of [...Object.values(exports), ...Object.values(Deno)]) {
    if (typeof property === "function") {
      hideFromStackTrace(property);
    }
  }

  return exports;
}

declare namespace Bun {
  function jest(path: string): typeof import("bun:test");
}