1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-21 23:04:45 -05:00

chore(cli): Migrate some unit tests to "Promise.withResolvers()" (#21128)

Migrate to use `Promise.withResolvers()` instead of `deferred` in some
of the tests in `cli/tests/unit/`.
Issue: #21041
This commit is contained in:
Tareque Md Hanif 2023-11-11 03:29:09 +06:00 committed by GitHub
parent df14835b83
commit eff3e43296
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 123 additions and 114 deletions

View file

@ -1,6 +1,5 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
import { assertEquals } from "../../../test_util/std/testing/asserts.ts";
import { deferred } from "../../../test_util/std/async/deferred.ts";
Deno.test("BroadcastChannel worker", async () => {
const intercom = new BroadcastChannel("intercom");
@ -12,7 +11,7 @@ Deno.test("BroadcastChannel worker", async () => {
const worker = new Worker(url, { type: "module", name: "worker" });
worker.onmessage = () => intercom.postMessage(++count);
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
intercom.onmessage = function (e) {
assertEquals(count, e.data);
@ -21,7 +20,7 @@ Deno.test("BroadcastChannel worker", async () => {
} else {
worker.terminate();
intercom.close();
promise.resolve();
resolve();
}
};

View file

@ -1,5 +1,5 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
import { assertEquals, assertThrows, deferred } from "./test_util.ts";
import { assertEquals, assertThrows } from "./test_util.ts";
const sleep = (time: number) => new Promise((r) => setTimeout(r, time));
@ -151,12 +151,12 @@ Deno.test(async function basicTest() {
Deno.env.set("DENO_CRON_TEST_SCHEDULE_OFFSET", "100");
let count = 0;
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const ac = new AbortController();
const c = Deno.cron("abc", "*/20 * * * *", () => {
count++;
if (count > 5) {
promise.resolve();
resolve();
}
}, { signal: ac.signal });
try {
@ -172,19 +172,23 @@ Deno.test(async function multipleCrons() {
let count0 = 0;
let count1 = 0;
const promise0 = deferred();
const promise1 = deferred();
const { promise: promise0, resolve: resolve0 } = Promise.withResolvers<
void
>();
const { promise: promise1, resolve: resolve1 } = Promise.withResolvers<
void
>();
const ac = new AbortController();
const c0 = Deno.cron("abc", "*/20 * * * *", () => {
count0++;
if (count0 > 5) {
promise0.resolve();
resolve0();
}
}, { signal: ac.signal });
const c1 = Deno.cron("xyz", "*/20 * * * *", () => {
count1++;
if (count1 > 5) {
promise1.resolve();
resolve1();
}
}, { signal: ac.signal });
try {
@ -201,11 +205,15 @@ Deno.test(async function overlappingExecutions() {
Deno.env.set("DENO_CRON_TEST_SCHEDULE_OFFSET", "100");
let count = 0;
const promise0 = deferred();
const promise1 = deferred();
const { promise: promise0, resolve: resolve0 } = Promise.withResolvers<
void
>();
const { promise: promise1, resolve: resolve1 } = Promise.withResolvers<
void
>();
const ac = new AbortController();
const c = Deno.cron("abc", "*/20 * * * *", async () => {
promise0.resolve();
resolve0();
count++;
await promise1;
}, { signal: ac.signal });
@ -213,7 +221,7 @@ Deno.test(async function overlappingExecutions() {
await promise0;
} finally {
await sleep(2000);
promise1.resolve();
resolve1();
ac.abort();
await c;
}

View file

@ -3,7 +3,6 @@ import {
assert,
assertEquals,
assertRejects,
deferred,
delay,
fail,
unimplemented,
@ -1260,13 +1259,13 @@ Deno.test(
Deno.test(
{ permissions: { net: true } },
async function fetchNoServerReadableStreamBody() {
const done = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const body = new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array([1]));
setTimeout(() => {
controller.enqueue(new Uint8Array([2]));
done.resolve();
resolve();
}, 1000);
},
});
@ -1274,7 +1273,7 @@ Deno.test(
await assertRejects(async () => {
await fetch(nonExistentHostname, { body, method: "POST" });
}, TypeError);
await done;
await promise;
},
);

View file

@ -1,21 +1,16 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
import {
assert,
assertEquals,
assertNotEquals,
deferred,
} from "./test_util.ts";
import { assert, assertEquals, assertNotEquals } from "./test_util.ts";
Deno.test({
sanitizeOps: false,
sanitizeResources: false,
}, async function queueTestNoDbClose() {
const db: Deno.Kv = await Deno.openKv(":memory:");
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
let dequeuedMessage: unknown = null;
db.listenQueue((msg) => {
dequeuedMessage = msg;
promise.resolve();
resolve();
});
const res = await db.enqueue("test");
assert(res.ok);

View file

@ -5,7 +5,6 @@ import {
assert,
assertEquals,
} from "../../../test_util/std/testing/asserts.ts";
import { deferred } from "../../../test_util/std/async/deferred.ts";
Deno.test("messagechannel", async () => {
const mc = new MessageChannel();
@ -13,14 +12,14 @@ Deno.test("messagechannel", async () => {
assert(mc.port1);
assert(mc.port2);
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
mc.port2.onmessage = (e) => {
assertEquals(e.data, "hello");
assertEquals(e.ports.length, 1);
assert(e.ports[0] instanceof MessagePort);
e.ports[0].close();
promise.resolve();
resolve();
};
mc.port1.postMessage("hello", [mc2.port1]);
@ -38,7 +37,7 @@ Deno.test("messagechannel clone port", async () => {
assert(mc.port1);
assert(mc.port2);
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
mc.port2.onmessage = (e) => {
const { port } = e.data;
@ -46,7 +45,7 @@ Deno.test("messagechannel clone port", async () => {
assert(e.ports[0] instanceof MessagePort);
assertEquals(e.ports[0], port);
e.ports[0].close();
promise.resolve();
resolve();
};
mc.port1.postMessage({ port: mc2.port1 }, [mc2.port1]);

View file

@ -5,7 +5,6 @@ import {
assertNotEquals,
assertRejects,
assertThrows,
deferred,
delay,
execCode,
execCode2,
@ -795,10 +794,10 @@ Deno.test(
async function netCloseWriteSuccess() {
const addr = { hostname: "127.0.0.1", port: listenPort };
const listener = Deno.listen(addr);
const closeDeferred = deferred();
const { promise: closePromise, resolve } = Promise.withResolvers<void>();
listener.accept().then(async (conn) => {
await conn.write(new Uint8Array([1, 2, 3]));
await closeDeferred;
await closePromise;
conn.close();
});
const conn = await Deno.connect(addr);
@ -815,7 +814,7 @@ Deno.test(
await assertRejects(async () => {
await conn.write(new Uint8Array([1, 2, 3]));
});
closeDeferred.resolve();
resolve();
listener.close();
conn.close();
},

View file

@ -5,19 +5,18 @@ import {
assertNotStrictEquals,
assertStringIncludes,
assertThrows,
deferred,
} from "./test_util.ts";
Deno.test({ permissions: { hrtime: false } }, async function performanceNow() {
const resolvable = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const start = performance.now();
let totalTime = 0;
setTimeout(() => {
const end = performance.now();
totalTime = end - start;
resolvable.resolve();
resolve();
}, 10);
await resolvable;
await promise;
assert(totalTime >= 10);
});

View file

@ -1,5 +1,5 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
import { assertEquals, assertThrows, deferred, delay } from "./test_util.ts";
import { assertEquals, assertThrows, delay } from "./test_util.ts";
Deno.test(
{ ignore: Deno.build.os !== "windows" },
@ -110,7 +110,7 @@ Deno.test(
permissions: { run: true },
},
async function signalListenerTest() {
const resolvable = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
let c = 0;
const listener = () => {
c += 1;
@ -124,10 +124,10 @@ Deno.test(
}
await delay(20);
Deno.removeSignalListener("SIGUSR1", listener);
resolvable.resolve();
resolve();
});
await resolvable;
await promise;
assertEquals(c, 3);
},
);
@ -138,7 +138,7 @@ Deno.test(
permissions: { run: true },
},
async function multipleSignalListenerTest() {
const resolvable = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
let c = "";
const listener0 = () => {
c += "0";
@ -169,10 +169,10 @@ Deno.test(
}
await delay(20);
Deno.removeSignalListener("SIGUSR2", listener0);
resolvable.resolve();
resolve();
});
await resolvable;
await promise;
// The first 3 events are handled by both handlers
// The last 3 events are handled only by handler0
assertEquals(c, "010101000");

View file

@ -1,5 +1,5 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
import { assertEquals, Deferred, deferred, fail } from "./test_util.ts";
import { assertEquals, fail } from "./test_util.ts";
const {
core,
@ -11,8 +11,10 @@ const LOREM =
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
// Hello world, with optional close
// deno-lint-ignore no-explicit-any
function helloWorldStream(close?: boolean, completion?: Deferred<any>) {
function helloWorldStream(
close?: boolean,
cancelResolve?: (value: unknown) => void,
) {
return new ReadableStream({
start(controller) {
controller.enqueue("hello, world");
@ -21,7 +23,9 @@ function helloWorldStream(close?: boolean, completion?: Deferred<any>) {
}
},
cancel(reason) {
completion?.resolve(reason);
if (cancelResolve != undefined) {
cancelResolve(reason);
}
},
}).pipeThrough(new TextEncoderStream());
}
@ -61,8 +65,7 @@ function longStream() {
}
// Long stream with Lorem Ipsum text.
// deno-lint-ignore no-explicit-any
function longAsyncStream(completion?: Deferred<any>) {
function longAsyncStream(cancelResolve?: (value: unknown) => void) {
let currentTimeout: number | undefined = undefined;
return new ReadableStream({
async start(controller) {
@ -74,7 +77,9 @@ function longAsyncStream(completion?: Deferred<any>) {
controller.close();
},
cancel(reason) {
completion?.resolve(reason);
if (cancelResolve != undefined) {
cancelResolve(reason);
}
if (currentTimeout !== undefined) {
clearTimeout(currentTimeout);
}
@ -185,40 +190,44 @@ Deno.test(async function readableStream() {
// Close the stream after reading everything
Deno.test(async function readableStreamClose() {
const cancel = deferred();
const rid = resourceForReadableStream(helloWorldStream(false, cancel));
const { promise: cancelPromise, resolve: cancelResolve } = Promise
.withResolvers();
const rid = resourceForReadableStream(helloWorldStream(false, cancelResolve));
const buffer = new Uint8Array(1024);
const nread = await core.ops.op_read(rid, buffer);
assertEquals(nread, 12);
core.ops.op_close(rid);
assertEquals(await cancel, "resource closed");
assertEquals(await cancelPromise, "resource closed");
});
// Close the stream without reading everything
Deno.test(async function readableStreamClosePartialRead() {
const cancel = deferred();
const rid = resourceForReadableStream(helloWorldStream(false, cancel));
const { promise: cancelPromise, resolve: cancelResolve } = Promise
.withResolvers();
const rid = resourceForReadableStream(helloWorldStream(false, cancelResolve));
const buffer = new Uint8Array(5);
const nread = await core.ops.op_read(rid, buffer);
assertEquals(nread, 5);
core.ops.op_close(rid);
assertEquals(await cancel, "resource closed");
assertEquals(await cancelPromise, "resource closed");
});
// Close the stream without reading anything
Deno.test(async function readableStreamCloseWithoutRead() {
const cancel = deferred();
const rid = resourceForReadableStream(helloWorldStream(false, cancel));
const { promise: cancelPromise, resolve: cancelResolve } = Promise
.withResolvers();
const rid = resourceForReadableStream(helloWorldStream(false, cancelResolve));
core.ops.op_close(rid);
assertEquals(await cancel, "resource closed");
assertEquals(await cancelPromise, "resource closed");
});
// Close the stream without reading anything
Deno.test(async function readableStreamCloseWithoutRead2() {
const cancel = deferred();
const rid = resourceForReadableStream(longAsyncStream(cancel));
const { promise: cancelPromise, resolve: cancelResolve } = Promise
.withResolvers();
const rid = resourceForReadableStream(longAsyncStream(cancelResolve));
core.ops.op_close(rid);
assertEquals(await cancel, "resource closed");
assertEquals(await cancelPromise, "resource closed");
});
Deno.test(async function readableStreamPartial() {
@ -432,7 +441,8 @@ function createStreamTest(
Deno.test(async function readableStreamWithAggressiveResourceClose() {
let first = true;
const reasonPromise = deferred();
const { promise: reasonPromise, resolve: reasonResolve } = Promise
.withResolvers();
const rid = resourceForReadableStream(
new ReadableStream({
pull(controller) {
@ -446,7 +456,7 @@ Deno.test(async function readableStreamWithAggressiveResourceClose() {
}
},
cancel(reason) {
reasonPromise.resolve(reason);
reasonResolve(reason);
},
}),
);

View file

@ -3,20 +3,18 @@ import {
assert,
assertEquals,
assertNotEquals,
Deferred,
deferred,
delay,
execCode,
unreachable,
} from "./test_util.ts";
Deno.test(async function functionParameterBindingSuccess() {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
let count = 0;
const nullProto = (newCount: number) => {
count = newCount;
promise.resolve();
resolve();
};
Reflect.setPrototypeOf(nullProto, null);
@ -30,10 +28,11 @@ Deno.test(async function functionParameterBindingSuccess() {
Deno.test(async function stringifyAndEvalNonFunctions() {
// eval can only access global scope
const global = globalThis as unknown as {
globalPromise: ReturnType<typeof deferred>;
globalPromise: ReturnType<typeof Promise.withResolvers<void>>;
globalCount: number;
};
global.globalPromise = deferred();
global.globalPromise = Promise.withResolvers<void>();
global.globalCount = 0;
const notAFunction =
@ -42,7 +41,7 @@ Deno.test(async function stringifyAndEvalNonFunctions() {
setTimeout(notAFunction, 500);
await global.globalPromise;
await global.globalPromise.promise;
// count should be incremented
assertEquals(global.globalCount, 1);
@ -52,11 +51,11 @@ Deno.test(async function stringifyAndEvalNonFunctions() {
});
Deno.test(async function timeoutSuccess() {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
let count = 0;
setTimeout(() => {
count++;
promise.resolve();
resolve();
}, 500);
await promise;
// count should increment
@ -66,9 +65,9 @@ Deno.test(async function timeoutSuccess() {
Deno.test(async function timeoutEvalNoScopeLeak() {
// eval can only access global scope
const global = globalThis as unknown as {
globalPromise: Deferred<Error>;
globalPromise: ReturnType<typeof Promise.withResolvers<Error>>;
};
global.globalPromise = deferred();
global.globalPromise = Promise.withResolvers();
setTimeout(
`
try {
@ -79,16 +78,16 @@ Deno.test(async function timeoutEvalNoScopeLeak() {
}` as unknown as () => void,
0,
);
const error = await global.globalPromise;
const error = await global.globalPromise.promise;
assertEquals(error.name, "ReferenceError");
Reflect.deleteProperty(global, "globalPromise");
});
Deno.test(async function evalPrimordial() {
const global = globalThis as unknown as {
globalPromise: ReturnType<typeof deferred>;
globalPromise: ReturnType<typeof Promise.withResolvers<void>>;
};
global.globalPromise = deferred();
global.globalPromise = Promise.withResolvers<void>();
const originalEval = globalThis.eval;
let wasCalled = false;
globalThis.eval = (argument) => {
@ -99,20 +98,20 @@ Deno.test(async function evalPrimordial() {
"globalThis.globalPromise.resolve();" as unknown as () => void,
0,
);
await global.globalPromise;
await global.globalPromise.promise;
assert(!wasCalled);
Reflect.deleteProperty(global, "globalPromise");
globalThis.eval = originalEval;
});
Deno.test(async function timeoutArgs() {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const arg = 1;
let capturedArgs: unknown[] = [];
setTimeout(
function () {
capturedArgs = [...arguments];
promise.resolve();
resolve();
},
10,
arg,
@ -165,13 +164,13 @@ Deno.test(async function timeoutCancelMultiple() {
Deno.test(async function timeoutCancelInvalidSilentFail() {
// Expect no panic
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
let count = 0;
const id = setTimeout(() => {
count++;
// Should have no effect
clearTimeout(id);
promise.resolve();
resolve();
}, 500);
await promise;
assertEquals(count, 1);
@ -181,12 +180,12 @@ Deno.test(async function timeoutCancelInvalidSilentFail() {
});
Deno.test(async function intervalSuccess() {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
let count = 0;
const id = setInterval(() => {
count++;
clearInterval(id);
promise.resolve();
resolve();
}, 100);
await promise;
// Clear interval
@ -230,7 +229,7 @@ Deno.test(function intervalCancelInvalidSilentFail() {
});
Deno.test(async function callbackTakesLongerThanInterval() {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
let timeEndOfFirstCallback: number | undefined;
const interval = setInterval(() => {
@ -242,7 +241,7 @@ Deno.test(async function callbackTakesLongerThanInterval() {
// Second callback
assert(Date.now() - 100 >= timeEndOfFirstCallback);
clearInterval(interval);
promise.resolve();
resolve();
}
}, 100);
@ -251,10 +250,10 @@ Deno.test(async function callbackTakesLongerThanInterval() {
// https://github.com/denoland/deno/issues/11398
Deno.test(async function clearTimeoutAfterNextTimerIsDue1() {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
setTimeout(() => {
promise.resolve();
resolve();
}, 300);
const interval = setInterval(() => {
@ -268,12 +267,12 @@ Deno.test(async function clearTimeoutAfterNextTimerIsDue1() {
// https://github.com/denoland/deno/issues/11398
Deno.test(async function clearTimeoutAfterNextTimerIsDue2() {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const timeout1 = setTimeout(unreachable, 100);
setTimeout(() => {
promise.resolve();
resolve();
}, 200);
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 300);
@ -293,12 +292,12 @@ Deno.test(async function fireCallbackImmediatelyWhenDelayOverMaxValue() {
});
Deno.test(async function timeoutCallbackThis() {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
let capturedThis: unknown;
const obj = {
foo() {
capturedThis = this;
promise.resolve();
resolve();
},
};
setTimeout(obj.foo, 1);
@ -322,10 +321,10 @@ Deno.test(async function timeoutBindThis() {
];
for (const thisArg of thisCheckPassed) {
const resolvable = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
let hasThrown = 0;
try {
setTimeout.call(thisArg, () => resolvable.resolve(), 1);
setTimeout.call(thisArg, () => resolve(), 1);
hasThrown = 1;
} catch (err) {
if (err instanceof TypeError) {
@ -334,7 +333,7 @@ Deno.test(async function timeoutBindThis() {
hasThrown = 3;
}
}
await resolvable;
await promise;
assertEquals(hasThrown, 1);
}
@ -414,12 +413,12 @@ Deno.test(function clearTimeoutAndClearIntervalNotBeEquals() {
Deno.test(async function timerOrdering() {
const array: number[] = [];
const donePromise = deferred();
const { promise: donePromise, resolve } = Promise.withResolvers<void>();
function push(n: number) {
array.push(n);
if (array.length === 6) {
donePromise.resolve();
resolve();
}
}
@ -444,13 +443,13 @@ Deno.test(async function timerOrdering() {
Deno.test(async function timerBasicMicrotaskOrdering() {
let s = "";
let count = 0;
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
setTimeout(() => {
Promise.resolve().then(() => {
count++;
s += "de";
if (count === 2) {
promise.resolve();
resolve();
}
});
});
@ -458,7 +457,7 @@ Deno.test(async function timerBasicMicrotaskOrdering() {
count++;
s += "no";
if (count === 2) {
promise.resolve();
resolve();
}
});
await promise;
@ -467,7 +466,7 @@ Deno.test(async function timerBasicMicrotaskOrdering() {
Deno.test(async function timerNestedMicrotaskOrdering() {
let s = "";
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
s += "0";
setTimeout(() => {
s += "4";
@ -476,7 +475,7 @@ Deno.test(async function timerNestedMicrotaskOrdering() {
.then(() => {
setTimeout(() => {
s += "B";
promise.resolve();
resolve();
});
})
.then(() => {
@ -507,11 +506,11 @@ Deno.test(function testQueueMicrotask() {
Deno.test(async function timerIgnoresDateOverride() {
const OriginalDate = Date;
const promise = deferred();
const { promise, resolve, reject } = Promise.withResolvers<void>();
let hasThrown = 0;
try {
const overrideCalled: () => number = () => {
promise.reject("global Date override used over original Date object");
reject("global Date override used over original Date object");
return 0;
};
const DateOverride = () => {
@ -521,7 +520,9 @@ Deno.test(async function timerIgnoresDateOverride() {
globalThis.Date.now = overrideCalled;
globalThis.Date.UTC = overrideCalled;
globalThis.Date.parse = overrideCalled;
queueMicrotask(promise.resolve);
queueMicrotask(() => {
resolve();
});
await promise;
hasThrown = 1;
} catch (err) {
@ -748,11 +749,11 @@ Deno.test({
Deno.test({
name: "regression for #20367",
fn: async () => {
const promise = deferred<number>();
const { promise, resolve } = Promise.withResolvers<number>();
const start = performance.now();
setTimeout(() => {
const end = performance.now();
promise.resolve(end - start);
resolve(end - start);
}, 1000);
clearTimeout(setTimeout(() => {}, 1000));

View file

@ -1,10 +1,10 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
import { assertEquals, deferred } from "./test_util.ts";
import { assertEquals } from "./test_util.ts";
Deno.test(
{ permissions: { env: true, read: true } },
async function workerEnvArrayPermissions() {
const promise = deferred<boolean[]>();
const { promise, resolve } = Promise.withResolvers<boolean[]>();
const worker = new Worker(
import.meta.resolve(
@ -14,7 +14,7 @@ Deno.test(
);
worker.onmessage = ({ data }) => {
promise.resolve(data.permissions);
resolve(data.permissions);
};
worker.postMessage({