diff --git a/cli/tests/integration_tests.rs b/cli/tests/integration_tests.rs index fe41ae9aa911fc..fa21f84e1e9667 100644 --- a/cli/tests/integration_tests.rs +++ b/cli/tests/integration_tests.rs @@ -29,14 +29,14 @@ fn js_unit_tests() { let _g = util::http_server(); let mut deno = util::deno_cmd() .current_dir(util::root_path()) - .arg("run") + .arg("test") .arg("--unstable") + .arg("--location=http://js-unit-tests/foo/bar") .arg("-A") - .arg("cli/tests/unit/unit_test_runner.ts") - .arg("--master") - .arg("--verbose") + .arg(util::root_path().join("cli/tests/unit")) .spawn() .expect("failed to spawn script"); + let status = deno.wait().expect("failed to wait for the child process"); assert_eq!(Some(0), status.code()); assert!(status.success()); diff --git a/cli/tests/unit/README.md b/cli/tests/unit/README.md deleted file mode 100644 index 7f0b243fede173..00000000000000 --- a/cli/tests/unit/README.md +++ /dev/null @@ -1,78 +0,0 @@ -# Deno runtime tests - -Files in this directory are unit tests for Deno runtime. - -Testing Deno runtime code requires checking API under different runtime -permissions (ie. running with different `--allow-*` flags). To accomplish this -all tests exercised are created using `unitTest()` function. - -```ts -import { unitTest } from "./test_util.ts"; - -unitTest(function simpleTestFn(): void { - // test code here -}); - -unitTest( - { - ignore: Deno.build.os === "windows", - perms: { read: true, write: true }, - }, - function complexTestFn(): void { - // test code here - }, -); -``` - -`unitTest` is a wrapper function that enhances `Deno.test()` API in several -ways: - -- ability to conditionally skip tests using `UnitTestOptions.skip`. -- ability to register required set of permissions for given test case using - `UnitTestOptions.perms`. -- sanitization of resources - ensuring that tests close all opened resources - preventing interference between tests. -- sanitization of async ops - ensuring that tests don't leak async ops by - ensuring that all started async ops are done before test finishes. - -## Running tests - -`unit_test_runner.ts` is the main script used to run unit tests. - -Runner discovers required permissions combinations by loading -`cli/tests/unit/unit_tests.ts` and going through all registered instances of -`unitTest`. - -There are three ways to run `unit_test_runner.ts`: - -```sh -# Run all tests. Spawns worker processes for each discovered permission -# combination: -target/debug/deno run -A cli/tests/unit/unit_test_runner.ts --master - -# By default all output of worker processes is discarded; for debug purposes -# the --verbose flag preserves output from the worker. -target/debug/deno run -A cli/tests/unit/unit_test_runner.ts --master --verbose - -# Run subset of tests that don't require any permissions. -target/debug/deno run --unstable cli/tests/unit/unit_test_runner.ts - -# Run subset tests that require "net" and "read" permissions. -target/debug/deno run --unstable --allow-net --allow-read cli/tests/unit/unit_test_runner.ts - -# "worker" mode communicates with parent using TCP socket on provided address; -# after initial setup drops permissions to specified set. It shouldn't be used -# directly, only be "master" process. -target/debug/deno run -A cli/tests/unit/unit_test_runner.ts --worker --addr=127.0.0.1:4500 --perms=net,write,run - -# Run specific tests. -target/debug/deno run --unstable --allow-net cli/tests/unit/unit_test_runner.ts -- netTcpListenClose - -RUST_BACKTRACE=1 cargo run -- run --unstable --allow-read --allow-write cli/tests/unit/unit_test_runner.ts -- netUnixDialListen -``` - -### Http server - -`target/debug/test_server` is required to run when one's running unit tests. -During CI it's spawned automatically, but if you want to run tests manually make -sure that server is spawned otherwise there'll be cascade of test failures. diff --git a/cli/tests/unit/abort_controller_test.ts b/cli/tests/unit/abort_controller_test.ts index d89bcdd4458fc4..167cac88e8693f 100644 --- a/cli/tests/unit/abort_controller_test.ts +++ b/cli/tests/unit/abort_controller_test.ts @@ -1,6 +1,6 @@ -import { assert, assertEquals, unitTest } from "./test_util.ts"; +import { assert, assertEquals } from "./test_util.ts"; -unitTest(function basicAbortController() { +Deno.test("basicAbortController", function () { const controller = new AbortController(); assert(controller); const { signal } = controller; @@ -10,7 +10,7 @@ unitTest(function basicAbortController() { assertEquals(signal.aborted, true); }); -unitTest(function signalCallsOnabort() { +Deno.test("signalCallsOnabort", function () { const controller = new AbortController(); const { signal } = controller; let called = false; @@ -23,7 +23,7 @@ unitTest(function signalCallsOnabort() { assert(called); }); -unitTest(function signalEventListener() { +Deno.test("signalEventListener", function () { const controller = new AbortController(); const { signal } = controller; let called = false; @@ -36,7 +36,7 @@ unitTest(function signalEventListener() { assert(called); }); -unitTest(function onlyAbortsOnce() { +Deno.test("onlyAbortsOnce", function () { const controller = new AbortController(); const { signal } = controller; let called = 0; @@ -50,7 +50,7 @@ unitTest(function onlyAbortsOnce() { assertEquals(called, 2); }); -unitTest(function controllerHasProperToString() { +Deno.test("controllerHasProperToString", function () { const actual = Object.prototype.toString.call(new AbortController()); assertEquals(actual, "[object AbortController]"); }); diff --git a/cli/tests/unit/blob_test.ts b/cli/tests/unit/blob_test.ts index a3a8e06fd55a54..04ba0e407e1c5b 100644 --- a/cli/tests/unit/blob_test.ts +++ b/cli/tests/unit/blob_test.ts @@ -1,16 +1,16 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assert, assertEquals, unitTest } from "./test_util.ts"; +import { assert, assertEquals } from "./test_util.ts"; import { concat } from "../../../test_util/std/bytes/mod.ts"; import { decode } from "../../../test_util/std/encoding/utf8.ts"; -unitTest(function blobString(): void { +Deno.test("blobString", function (): void { const b1 = new Blob(["Hello World"]); const str = "Test"; const b2 = new Blob([b1, str]); assertEquals(b2.size, b1.size + str.length); }); -unitTest(function blobBuffer(): void { +Deno.test("blobBuffer", function (): void { const buffer = new ArrayBuffer(12); const u8 = new Uint8Array(buffer); const f1 = new Float32Array(buffer); @@ -20,7 +20,7 @@ unitTest(function blobBuffer(): void { assertEquals(b2.size, 3 * u8.length); }); -unitTest(function blobSlice(): void { +Deno.test("blobSlice", function (): void { const blob = new Blob(["Deno", "Foo"]); const b1 = blob.slice(0, 3, "Text/HTML"); assert(b1 instanceof Blob); @@ -34,7 +34,7 @@ unitTest(function blobSlice(): void { assertEquals(b4.size, blob.size); }); -unitTest(function blobInvalidType(): void { +Deno.test("blobInvalidType", function (): void { const blob = new Blob(["foo"], { type: "\u0521", }); @@ -42,7 +42,7 @@ unitTest(function blobInvalidType(): void { assertEquals(blob.type, ""); }); -unitTest(function blobShouldNotThrowError(): void { +Deno.test("blobShouldNotThrowError", function (): void { let hasThrown = false; try { @@ -62,7 +62,7 @@ unitTest(function blobShouldNotThrowError(): void { }); /* TODO https://github.com/denoland/deno/issues/7540 -unitTest(function nativeEndLine(): void { +Deno.test("nativeEndLine", function(): void { const options = { ending: "native", } as const; @@ -72,12 +72,12 @@ unitTest(function nativeEndLine(): void { }); */ -unitTest(async function blobText(): Promise { +Deno.test("blobText", async function (): Promise { const blob = new Blob(["Hello World"]); assertEquals(await blob.text(), "Hello World"); }); -unitTest(async function blobStream(): Promise { +Deno.test("blobStream", async function (): Promise { const blob = new Blob(["Hello World"]); const stream = blob.stream(); assert(stream instanceof ReadableStream); @@ -94,13 +94,13 @@ unitTest(async function blobStream(): Promise { assertEquals(decode(bytes), "Hello World"); }); -unitTest(async function blobArrayBuffer(): Promise { +Deno.test("blobArrayBuffer", async function (): Promise { const uint = new Uint8Array([102, 111, 111]); const blob = new Blob([uint]); assertEquals(await blob.arrayBuffer(), uint.buffer); }); -unitTest(function blobConstructorNameIsBlob(): void { +Deno.test("blobConstructorNameIsBlob", function (): void { const blob = new Blob(); assertEquals(blob.constructor.name, "Blob"); }); diff --git a/cli/tests/unit/body_test.ts b/cli/tests/unit/body_test.ts index 2c94bb5f5a50fd..fb2682250fe2b8 100644 --- a/cli/tests/unit/body_test.ts +++ b/cli/tests/unit/body_test.ts @@ -1,5 +1,5 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assert, assertEquals, unitTest } from "./test_util.ts"; +import { assert, assertEquals } from "./test_util.ts"; // just a hack to get a body object // deno-lint-ignore no-explicit-any @@ -22,7 +22,8 @@ const intArrays = [ Float32Array, Float64Array, ]; -unitTest(async function arrayBufferFromByteArrays(): Promise { + +Deno.test("arrayBufferFromByteArrays", async function (): Promise { const buffer = new TextEncoder().encode("ahoyhoy8").buffer; for (const type of intArrays) { @@ -33,53 +34,47 @@ unitTest(async function arrayBufferFromByteArrays(): Promise { }); //FormData -unitTest( - { perms: { net: true } }, - async function bodyMultipartFormData(): Promise { - const response = await fetch( - "http://localhost:4545/multipart_form_data.txt", - ); - assert(response.body instanceof ReadableStream); - - const text = await response.text(); - - const body = buildBody(text, response.headers); - - const formData = await body.formData(); - assert(formData.has("field_1")); - assertEquals(formData.get("field_1")!.toString(), "value_1 \r\n"); - assert(formData.has("field_2")); - }, -); - -unitTest( - { perms: { net: true } }, - async function bodyURLEncodedFormData(): Promise { - const response = await fetch( - "http://localhost:4545/cli/tests/subdir/form_urlencoded.txt", - ); - assert(response.body instanceof ReadableStream); - - const text = await response.text(); - - const body = buildBody(text, response.headers); - - const formData = await body.formData(); - assert(formData.has("field_1")); - assertEquals(formData.get("field_1")!.toString(), "Hi"); - assert(formData.has("field_2")); - assertEquals(formData.get("field_2")!.toString(), ""); - }, -); - -unitTest({ perms: {} }, async function bodyURLSearchParams(): Promise { +Deno.test("bodyMultipartFormData", async function (): Promise { + const response = await fetch( + "http://localhost:4545/multipart_form_data.txt", + ); + assert(response.body instanceof ReadableStream); + + const text = await response.text(); + + const body = buildBody(text, response.headers); + + const formData = await body.formData(); + assert(formData.has("field_1")); + assertEquals(formData.get("field_1")!.toString(), "value_1 \r\n"); + assert(formData.has("field_2")); +}); + +Deno.test("bodyURLEncodedFormData", async function (): Promise { + const response = await fetch( + "http://localhost:4545/cli/tests/subdir/form_urlencoded.txt", + ); + assert(response.body instanceof ReadableStream); + + const text = await response.text(); + + const body = buildBody(text, response.headers); + + const formData = await body.formData(); + assert(formData.has("field_1")); + assertEquals(formData.get("field_1")!.toString(), "Hi"); + assert(formData.has("field_2")); + assertEquals(formData.get("field_2")!.toString(), ""); +}); + +Deno.test("bodyURLSearchParams", async function (): Promise { const body = buildBody(new URLSearchParams({ hello: "world" })); const text = await body.text(); assertEquals(text, "hello=world"); }); -unitTest(async function bodyArrayBufferMultipleParts(): Promise { +Deno.test("bodyArrayBufferMultipleParts", async function (): Promise { const parts: Uint8Array[] = []; let size = 0; for (let i = 0; i <= 150000; i++) { diff --git a/cli/tests/unit/buffer_test.ts b/cli/tests/unit/buffer_test.ts index ed3698bc17a241..cc9c650291a5ab 100644 --- a/cli/tests/unit/buffer_test.ts +++ b/cli/tests/unit/buffer_test.ts @@ -8,7 +8,6 @@ import { assertEquals, assertThrows, assertThrowsAsync, - unitTest, } from "./test_util.ts"; const MAX_SIZE = 2 ** 32 - 2; @@ -85,7 +84,7 @@ function repeat(c: string, bytes: number): Uint8Array { return ui8; } -unitTest(function bufferNewBuffer(): void { +Deno.test("bufferNewBuffer", function (): void { init(); assert(testBytes); assert(testString); @@ -93,7 +92,7 @@ unitTest(function bufferNewBuffer(): void { check(buf, testString); }); -unitTest(async function bufferBasicOperations(): Promise { +Deno.test("bufferBasicOperations", async function (): Promise { init(); assert(testBytes); assert(testString); @@ -133,7 +132,7 @@ unitTest(async function bufferBasicOperations(): Promise { } }); -unitTest(async function bufferReadEmptyAtEOF(): Promise { +Deno.test("bufferReadEmptyAtEOF", async function (): Promise { // check that EOF of 'buf' is not reached (even though it's empty) if // results are written to buffer that has 0 length (ie. it can't store any data) const buf = new Deno.Buffer(); @@ -142,7 +141,7 @@ unitTest(async function bufferReadEmptyAtEOF(): Promise { assertEquals(result, 0); }); -unitTest(async function bufferLargeByteWrites(): Promise { +Deno.test("bufferLargeByteWrites", async function (): Promise { init(); const buf = new Deno.Buffer(); const limit = 9; @@ -153,7 +152,7 @@ unitTest(async function bufferLargeByteWrites(): Promise { check(buf, ""); }); -unitTest(async function bufferTooLargeByteWrites(): Promise { +Deno.test("bufferTooLargeByteWrites", async function (): Promise { init(); const tmp = new Uint8Array(72); const growLen = Number.MAX_VALUE; @@ -170,9 +169,10 @@ unitTest(async function bufferTooLargeByteWrites(): Promise { ); }); -unitTest( - { ignore: ignoreMaxSizeTests }, - function bufferGrowWriteMaxBuffer(): void { +Deno.test({ + name: "bufferGrowWriteMaxBuffer", + ignore: ignoreMaxSizeTests, + fn(): void { const bufSize = 16 * 1024; const capacities = [MAX_SIZE, MAX_SIZE - 1]; for (const capacity of capacities) { @@ -190,11 +190,12 @@ unitTest( assertEquals(written, capacity); } }, -); +}); -unitTest( - { ignore: ignoreMaxSizeTests }, - async function bufferGrowReadCloseMaxBufferPlus1(): Promise { +Deno.test({ + name: "bufferGrowReadCloseMaxBufferPlus1", + ignore: ignoreMaxSizeTests, + async fn(): Promise { const reader = new Deno.Buffer(new ArrayBuffer(MAX_SIZE + 1)); const buf = new Deno.Buffer(); @@ -206,11 +207,12 @@ unitTest( "grown beyond the maximum size", ); }, -); +}); -unitTest( - { ignore: ignoreMaxSizeTests }, - function bufferGrowReadSyncCloseMaxBufferPlus1(): void { +Deno.test({ + name: "bufferGrowReadSyncCloseMaxBufferPlus1", + ignore: ignoreMaxSizeTests, + fn(): void { const reader = new Deno.Buffer(new ArrayBuffer(MAX_SIZE + 1)); const buf = new Deno.Buffer(); @@ -222,25 +224,29 @@ unitTest( "grown beyond the maximum size", ); }, -); +}); -unitTest( - { ignore: ignoreMaxSizeTests }, - function bufferGrowReadSyncCloseToMaxBuffer(): void { - const capacities = [MAX_SIZE, MAX_SIZE - 1]; - for (const capacity of capacities) { - const reader = new Deno.Buffer(new ArrayBuffer(capacity)); - const buf = new Deno.Buffer(); - buf.readFromSync(reader); +Deno.test( + { + name: "bufferGrowReadSyncCloseToMaxBuffer", + ignore: ignoreMaxSizeTests, + fn(): void { + const capacities = [MAX_SIZE, MAX_SIZE - 1]; + for (const capacity of capacities) { + const reader = new Deno.Buffer(new ArrayBuffer(capacity)); + const buf = new Deno.Buffer(); + buf.readFromSync(reader); - assertEquals(buf.length, capacity); - } + assertEquals(buf.length, capacity); + } + }, }, ); -unitTest( - { ignore: ignoreMaxSizeTests }, - async function bufferGrowReadCloseToMaxBuffer(): Promise { +Deno.test({ + name: "bufferGrowReadCloseToMaxBuffer", + ignore: ignoreMaxSizeTests, + async fn(): Promise { const capacities = [MAX_SIZE, MAX_SIZE - 1]; for (const capacity of capacities) { const reader = new Deno.Buffer(new ArrayBuffer(capacity)); @@ -249,11 +255,12 @@ unitTest( assertEquals(buf.length, capacity); } }, -); +}); -unitTest( - { ignore: ignoreMaxSizeTests }, - async function bufferReadCloseToMaxBufferWithInitialGrow(): Promise { +Deno.test({ + name: "bufferReadCloseToMaxBufferWithInitialGrow", + ignore: ignoreMaxSizeTests, + async fn(): Promise { const capacities = [MAX_SIZE, MAX_SIZE - 1, MAX_SIZE - 512]; for (const capacity of capacities) { const reader = new Deno.Buffer(new ArrayBuffer(capacity)); @@ -263,9 +270,9 @@ unitTest( assertEquals(buf.length, capacity); } }, -); +}); -unitTest(async function bufferLargeByteReads(): Promise { +Deno.test("bufferLargeByteReads", async function (): Promise { init(); assert(testBytes); assert(testString); @@ -278,12 +285,12 @@ unitTest(async function bufferLargeByteReads(): Promise { check(buf, ""); }); -unitTest(function bufferCapWithPreallocatedSlice(): void { +Deno.test("bufferCapWithPreallocatedSlice", function (): void { const buf = new Deno.Buffer(new ArrayBuffer(10)); assertEquals(buf.capacity, 10); }); -unitTest(async function bufferReadFrom(): Promise { +Deno.test("bufferReadFrom", async function (): Promise { init(); assert(testBytes); assert(testString); @@ -305,7 +312,7 @@ unitTest(async function bufferReadFrom(): Promise { }); }); -unitTest(async function bufferReadFromSync(): Promise { +Deno.test("bufferReadFromSync", async function (): Promise { init(); assert(testBytes); assert(testString); @@ -327,7 +334,7 @@ unitTest(async function bufferReadFromSync(): Promise { }); }); -unitTest(async function bufferTestGrow(): Promise { +Deno.test("bufferTestGrow", async function (): Promise { const tmp = new Uint8Array(72); for (const startLen of [0, 100, 1000, 10000]) { const xBytes = repeat("x", startLen); @@ -351,7 +358,7 @@ unitTest(async function bufferTestGrow(): Promise { } }); -unitTest(async function testReadAll(): Promise { +Deno.test("testReadAll", async function (): Promise { init(); assert(testBytes); const reader = new Deno.Buffer(testBytes.buffer as ArrayBuffer); @@ -362,7 +369,7 @@ unitTest(async function testReadAll(): Promise { } }); -unitTest(function testReadAllSync(): void { +Deno.test("testReadAllSync", function (): void { init(); assert(testBytes); const reader = new Deno.Buffer(testBytes.buffer as ArrayBuffer); @@ -373,7 +380,7 @@ unitTest(function testReadAllSync(): void { } }); -unitTest(async function testWriteAll(): Promise { +Deno.test("testWriteAll", async function (): Promise { init(); assert(testBytes); const writer = new Deno.Buffer(); @@ -385,7 +392,7 @@ unitTest(async function testWriteAll(): Promise { } }); -unitTest(function testWriteAllSync(): void { +Deno.test("testWriteAllSync", function (): void { init(); assert(testBytes); const writer = new Deno.Buffer(); @@ -397,7 +404,7 @@ unitTest(function testWriteAllSync(): void { } }); -unitTest(function testBufferBytesArrayBufferLength(): void { +Deno.test("testBufferBytesArrayBufferLength", function (): void { // defaults to copy const args = [{}, { copy: undefined }, undefined, { copy: true }]; for (const arg of args) { @@ -416,7 +423,7 @@ unitTest(function testBufferBytesArrayBufferLength(): void { } }); -unitTest(function testBufferBytesCopyFalse(): void { +Deno.test("testBufferBytesCopyFalse", function (): void { const bufSize = 64 * 1024; const bytes = new TextEncoder().encode("a".repeat(bufSize)); const reader = new Deno.Buffer(); @@ -431,7 +438,7 @@ unitTest(function testBufferBytesCopyFalse(): void { assert(actualBytes.buffer.byteLength > actualBytes.byteLength); }); -unitTest(function testBufferBytesCopyFalseGrowExactBytes(): void { +Deno.test("testBufferBytesCopyFalseGrowExactBytes", function (): void { const bufSize = 64 * 1024; const bytes = new TextEncoder().encode("a".repeat(bufSize)); const reader = new Deno.Buffer(); diff --git a/cli/tests/unit/build_test.ts b/cli/tests/unit/build_test.ts index 731290326b6823..fa2c773088629c 100644 --- a/cli/tests/unit/build_test.ts +++ b/cli/tests/unit/build_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assert, unitTest } from "./test_util.ts"; +import { assert } from "./test_util.ts"; -unitTest(function buildInfo(): void { +Deno.test("buildInfo", function (): void { // Deno.build is injected by rollup at compile time. Here // we check it has been properly transformed. const { arch, os } = Deno.build; diff --git a/cli/tests/unit/chmod_test.ts b/cli/tests/unit/chmod_test.ts index 80f2401340c0d4..659d1f8d6276af 100644 --- a/cli/tests/unit/chmod_test.ts +++ b/cli/tests/unit/chmod_test.ts @@ -4,12 +4,12 @@ import { assertEquals, assertThrows, assertThrowsAsync, - unitTest, } from "./test_util.ts"; -unitTest( - { ignore: Deno.build.os === "windows", perms: { read: true, write: true } }, - function chmodSyncSuccess(): void { +Deno.test({ + name: "chmodSyncSuccess", + ignore: Deno.build.os === "windows", + fn(): void { const enc = new TextEncoder(); const data = enc.encode("Hello"); const tempDir = Deno.makeTempDirSync(); @@ -22,11 +22,12 @@ unitTest( assert(fileInfo.mode); assertEquals(fileInfo.mode & 0o777, 0o777); }, -); +}); -unitTest( - { ignore: Deno.build.os === "windows", perms: { read: true, write: true } }, - function chmodSyncUrl(): void { +Deno.test({ + name: "chmodSyncUrl", + ignore: Deno.build.os === "windows", + fn(): void { const enc = new TextEncoder(); const data = enc.encode("Hello"); const tempDir = Deno.makeTempDirSync(); @@ -41,15 +42,12 @@ unitTest( Deno.removeSync(tempDir, { recursive: true }); }, -); +}); -// Check symlink when not on windows -unitTest( - { - ignore: Deno.build.os === "windows", - perms: { read: true, write: true }, - }, - function chmodSyncSymlinkSuccess(): void { +Deno.test({ + name: "chmodSyncSymlinkSuccess", + ignore: Deno.build.os === "windows", + fn(): void { const enc = new TextEncoder(); const data = enc.encode("Hello"); const tempDir = Deno.makeTempDirSync(); @@ -73,24 +71,19 @@ unitTest( assert(symlinkInfo.mode); assertEquals(symlinkInfo.mode & 0o777, symlinkMode); }, -); +}); -unitTest({ perms: { write: true } }, function chmodSyncFailure(): void { +Deno.test("chmodSyncFailure", function (): void { assertThrows(() => { const filename = "/badfile.txt"; Deno.chmodSync(filename, 0o777); }, Deno.errors.NotFound); }); -unitTest({ perms: { write: false } }, function chmodSyncPerm(): void { - assertThrows(() => { - Deno.chmodSync("/somefile.txt", 0o777); - }, Deno.errors.PermissionDenied); -}); - -unitTest( - { ignore: Deno.build.os === "windows", perms: { read: true, write: true } }, - async function chmodSuccess(): Promise { +Deno.test({ + name: "chmodSuccess", + ignore: Deno.build.os === "windows", + async fn(): Promise { const enc = new TextEncoder(); const data = enc.encode("Hello"); const tempDir = Deno.makeTempDirSync(); @@ -103,11 +96,12 @@ unitTest( assert(fileInfo.mode); assertEquals(fileInfo.mode & 0o777, 0o777); }, -); +}); -unitTest( - { ignore: Deno.build.os === "windows", perms: { read: true, write: true } }, - async function chmodUrl(): Promise { +Deno.test({ + name: "chmodUrl", + ignore: Deno.build.os === "windows", + async fn(): Promise { const enc = new TextEncoder(); const data = enc.encode("Hello"); const tempDir = Deno.makeTempDirSync(); @@ -122,16 +116,12 @@ unitTest( Deno.removeSync(tempDir, { recursive: true }); }, -); - -// Check symlink when not on windows +}); -unitTest( - { - ignore: Deno.build.os === "windows", - perms: { read: true, write: true }, - }, - async function chmodSymlinkSuccess(): Promise { +Deno.test({ + name: "chmodSymlinkSuccess", + ignore: Deno.build.os === "windows", + async fn(): Promise { const enc = new TextEncoder(); const data = enc.encode("Hello"); const tempDir = Deno.makeTempDirSync(); @@ -155,9 +145,9 @@ unitTest( assert(symlinkInfo.mode); assertEquals(symlinkInfo.mode & 0o777, symlinkMode); }, -); +}); -unitTest({ perms: { write: true } }, async function chmodFailure(): Promise< +Deno.test("chmodFailure", async function (): Promise< void > { await assertThrowsAsync(async () => { @@ -166,9 +156,19 @@ unitTest({ perms: { write: true } }, async function chmodFailure(): Promise< }, Deno.errors.NotFound); }); -unitTest({ perms: { write: false } }, async function chmodPerm(): Promise< +Deno.test("chmodSyncPerm", async function (): Promise { + await Deno.permissions.revoke({ name: "write" }); + + assertThrows(() => { + Deno.chmodSync("/somefile.txt", 0o777); + }, Deno.errors.PermissionDenied); +}); + +Deno.test("chmodPerm", async function (): Promise< void > { + await Deno.permissions.revoke({ name: "write" }); + await assertThrowsAsync(async () => { await Deno.chmod("/somefile.txt", 0o777); }, Deno.errors.PermissionDenied); diff --git a/cli/tests/unit/chown_test.ts b/cli/tests/unit/chown_test.ts index 2fac679ce5dd60..5ce44d42b33829 100644 --- a/cli/tests/unit/chown_test.ts +++ b/cli/tests/unit/chown_test.ts @@ -1,10 +1,5 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { - assertEquals, - assertThrows, - assertThrowsAsync, - unitTest, -} from "./test_util.ts"; +import { assertEquals, assertThrows, assertThrowsAsync } from "./test_util.ts"; // chown on Windows is noop for now, so ignore its testing on Windows @@ -29,19 +24,10 @@ async function getUidAndGid(): Promise<{ uid: number; gid: number }> { return { uid, gid }; } -unitTest( - { ignore: Deno.build.os == "windows" }, - async function chownNoWritePermission(): Promise { - const filePath = "chown_test_file.txt"; - await assertThrowsAsync(async () => { - await Deno.chown(filePath, 1000, 1000); - }, Deno.errors.PermissionDenied); - }, -); - -unitTest( - { perms: { run: true, write: true }, ignore: Deno.build.os == "windows" }, - async function chownSyncFileNotExist(): Promise { +Deno.test({ + name: "chownSyncFileNotExist", + ignore: Deno.build.os == "windows", + async fn(): Promise { const { uid, gid } = await getUidAndGid(); const filePath = Deno.makeTempDirSync() + "/chown_test_file.txt"; @@ -49,11 +35,12 @@ unitTest( Deno.chownSync(filePath, uid, gid); }, Deno.errors.NotFound); }, -); +}); -unitTest( - { perms: { run: true, write: true }, ignore: Deno.build.os == "windows" }, - async function chownFileNotExist(): Promise { +Deno.test({ + name: "chownFileNotExist", + ignore: Deno.build.os == "windows", + async fn(): Promise { const { uid, gid } = await getUidAndGid(); const filePath = (await Deno.makeTempDir()) + "/chown_test_file.txt"; @@ -61,11 +48,12 @@ unitTest( await Deno.chown(filePath, uid, gid); }, Deno.errors.NotFound); }, -); +}); -unitTest( - { perms: { write: true }, ignore: Deno.build.os == "windows" }, - function chownSyncPermissionDenied(): void { +Deno.test({ + name: "chownSyncPermissionDenied", + ignore: Deno.build.os == "windows", + fn(): void { const dirPath = Deno.makeTempDirSync(); const filePath = dirPath + "/chown_test_file.txt"; Deno.writeTextFileSync(filePath, "Hello"); @@ -76,11 +64,12 @@ unitTest( }, Deno.errors.PermissionDenied); Deno.removeSync(dirPath, { recursive: true }); }, -); +}); -unitTest( - { perms: { write: true }, ignore: Deno.build.os == "windows" }, - async function chownPermissionDenied(): Promise { +Deno.test({ + name: "chownPermissionDenied", + ignore: Deno.build.os == "windows", + async fn(): Promise { const dirPath = await Deno.makeTempDir(); const filePath = dirPath + "/chown_test_file.txt"; await Deno.writeTextFile(filePath, "Hello"); @@ -91,11 +80,12 @@ unitTest( }, Deno.errors.PermissionDenied); await Deno.remove(dirPath, { recursive: true }); }, -); +}); -unitTest( - { perms: { run: true, write: true }, ignore: Deno.build.os == "windows" }, - async function chownSyncSucceed(): Promise { +Deno.test({ + name: "chownSyncSucceed", + ignore: Deno.build.os == "windows", + async fn(): Promise { // TODO(bartlomieju): when a file's owner is actually being changed, // chown only succeeds if run under priviledged user (root) // The test script has no such privilege, so need to find a better way to test this case @@ -111,11 +101,12 @@ unitTest( Deno.removeSync(dirPath, { recursive: true }); }, -); +}); -unitTest( - { perms: { run: true, write: true }, ignore: Deno.build.os == "windows" }, - async function chownSyncWithUrl(): Promise { +Deno.test({ + name: "chownSyncWithUrl", + ignore: Deno.build.os == "windows", + async fn(): Promise { const { uid, gid } = await getUidAndGid(); const dirPath = Deno.makeTempDirSync(); const fileUrl = new URL(`file://${dirPath}/chown_test_file.txt`); @@ -123,11 +114,12 @@ unitTest( Deno.chownSync(fileUrl, uid, gid); Deno.removeSync(dirPath, { recursive: true }); }, -); +}); -unitTest( - { perms: { run: true, write: true }, ignore: Deno.build.os == "windows" }, - async function chownSucceed(): Promise { +Deno.test({ + name: "chownSucceed", + ignore: Deno.build.os == "windows", + async fn(): Promise { const { uid, gid } = await getUidAndGid(); const dirPath = await Deno.makeTempDir(); const filePath = dirPath + "/chown_test_file.txt"; @@ -135,11 +127,12 @@ unitTest( await Deno.chown(filePath, uid, gid); Deno.removeSync(dirPath, { recursive: true }); }, -); +}); -unitTest( - { perms: { run: true, write: true }, ignore: Deno.build.os == "windows" }, - async function chownUidOnly(): Promise { +Deno.test({ + name: "chownUidOnly", + ignore: Deno.build.os == "windows", + async fn(): Promise { const { uid } = await getUidAndGid(); const dirPath = await Deno.makeTempDir(); const filePath = dirPath + "/chown_test_file.txt"; @@ -147,11 +140,12 @@ unitTest( await Deno.chown(filePath, uid, null); Deno.removeSync(dirPath, { recursive: true }); }, -); +}); -unitTest( - { perms: { run: true, write: true }, ignore: Deno.build.os == "windows" }, - async function chownWithUrl(): Promise { +Deno.test({ + name: "chownWithUrl", + ignore: Deno.build.os == "windows", + async fn(): Promise { // TODO(bartlomieju): same as chownSyncSucceed const { uid, gid } = await getUidAndGid(); @@ -167,4 +161,17 @@ unitTest( Deno.removeSync(dirPath, { recursive: true }); }, -); +}); + +Deno.test({ + name: "chownNoWritePermission", + ignore: Deno.build.os == "windows", + async fn(): Promise { + await Deno.permissions.revoke({ name: "write" }); + + const filePath = "chown_test_file.txt"; + await assertThrowsAsync(async () => { + await Deno.chown(filePath, 1000, 1000); + }, Deno.errors.PermissionDenied); + }, +}); diff --git a/cli/tests/unit/console_test.ts b/cli/tests/unit/console_test.ts index 402f448bcc00a9..eb52eebe581e0b 100644 --- a/cli/tests/unit/console_test.ts +++ b/cli/tests/unit/console_test.ts @@ -13,7 +13,6 @@ import { assertEquals, assertStringIncludes, assertThrows, - unitTest, } from "./test_util.ts"; import { stripColor } from "../../../test_util/std/fmt/colors.ts"; @@ -64,7 +63,7 @@ function cssToAnsiEsc(css: Css, prevCss: Css | null = null): string { // test cases from web-platform-tests // via https://github.com/web-platform-tests/wpt/blob/master/console/console-is-a-namespace.any.js -unitTest(function consoleShouldBeANamespace(): void { +Deno.test("consoleShouldBeANamespace", function (): void { const prototype1 = Object.getPrototypeOf(console); const prototype2 = Object.getPrototypeOf(prototype1); @@ -72,12 +71,12 @@ unitTest(function consoleShouldBeANamespace(): void { assertEquals(prototype2, Object.prototype); }); -unitTest(function consoleHasRightInstance(): void { +Deno.test("consoleHasRightInstance", function (): void { assert(console instanceof Console); assertEquals({} instanceof Console, false); }); -unitTest(function consoleTestAssertShouldNotThrowError(): void { +Deno.test("consoleTestAssertShouldNotThrowError", function (): void { mockConsole((console) => { console.assert(true); let hasThrown = undefined; @@ -91,40 +90,39 @@ unitTest(function consoleTestAssertShouldNotThrowError(): void { }); }); -unitTest(function consoleTestStringifyComplexObjects(): void { +Deno.test("consoleTestStringifyComplexObjects", function (): void { assertEquals(stringify("foo"), "foo"); assertEquals(stringify(["foo", "bar"]), `[ "foo", "bar" ]`); assertEquals(stringify({ foo: "bar" }), `{ foo: "bar" }`); }); -unitTest( - function consoleTestStringifyComplexObjectsWithEscapedSequences(): void { - assertEquals( - stringify( - ["foo\b", "foo\f", "foo\n", "foo\r", "foo\t", "foo\v", "foo\0"], - ), - `[ +Deno.test("consoleTestStringifyComplexObjectsWithEscapedSequences", function (): void { + assertEquals( + stringify( + ["foo\b", "foo\f", "foo\n", "foo\r", "foo\t", "foo\v", "foo\0"], + ), + `[ "foo\\b", "foo\\f", "foo\\n", "foo\\r", "foo\\t", "foo\\v", "foo\\x00" ]`, - ); - assertEquals( - stringify( - [ - Symbol(), - Symbol(""), - Symbol("foo\b"), - Symbol("foo\f"), - Symbol("foo\n"), - Symbol("foo\r"), - Symbol("foo\t"), - Symbol("foo\v"), - Symbol("foo\0"), - ], - ), - `[ + ); + assertEquals( + stringify( + [ + Symbol(), + Symbol(""), + Symbol("foo\b"), + Symbol("foo\f"), + Symbol("foo\n"), + Symbol("foo\r"), + Symbol("foo\t"), + Symbol("foo\v"), + Symbol("foo\0"), + ], + ), + `[ Symbol(), Symbol(""), Symbol("foo\\b"), @@ -135,46 +133,45 @@ unitTest( Symbol("foo\\v"), Symbol("foo\\x00") ]`, - ); - assertEquals( - stringify( - { "foo\b": "bar\n", "bar\r": "baz\t", "qux\0": "qux\0" }, - ), - `{ "foo\\b": "bar\\n", "bar\\r": "baz\\t", "qux\\x00": "qux\\x00" }`, - ); - assertEquals( - stringify( - { - [Symbol("foo\b")]: `Symbol("foo\n")`, - [Symbol("bar\n")]: `Symbol("bar\n")`, - [Symbol("bar\r")]: `Symbol("bar\r")`, - [Symbol("baz\t")]: `Symbol("baz\t")`, - [Symbol("qux\0")]: `Symbol("qux\0")`, - }, - ), - `{ + ); + assertEquals( + stringify( + { "foo\b": "bar\n", "bar\r": "baz\t", "qux\0": "qux\0" }, + ), + `{ "foo\\b": "bar\\n", "bar\\r": "baz\\t", "qux\\x00": "qux\\x00" }`, + ); + assertEquals( + stringify( + { + [Symbol("foo\b")]: `Symbol("foo\n")`, + [Symbol("bar\n")]: `Symbol("bar\n")`, + [Symbol("bar\r")]: `Symbol("bar\r")`, + [Symbol("baz\t")]: `Symbol("baz\t")`, + [Symbol("qux\0")]: `Symbol("qux\0")`, + }, + ), + `{ [Symbol("foo\\b")]: 'Symbol("foo\\n\")', [Symbol("bar\\n")]: 'Symbol("bar\\n\")', [Symbol("bar\\r")]: 'Symbol("bar\\r\")', [Symbol("baz\\t")]: 'Symbol("baz\\t\")', [Symbol("qux\\x00")]: 'Symbol(\"qux\\x00")' }`, - ); - assertEquals( - stringify(new Set(["foo\n", "foo\r", "foo\0"])), - `Set { "foo\\n", "foo\\r", "foo\\x00" }`, - ); - }, -); + ); + assertEquals( + stringify(new Set(["foo\n", "foo\r", "foo\0"])), + `Set { "foo\\n", "foo\\r", "foo\\x00" }`, + ); +}); -unitTest(function consoleTestStringifyQuotes(): void { +Deno.test("consoleTestStringifyQuotes", function (): void { assertEquals(stringify(["\\"]), `[ "\\\\" ]`); assertEquals(stringify(['\\,"']), `[ '\\\\,"' ]`); assertEquals(stringify([`\\,",'`]), `[ \`\\\\,",'\` ]`); assertEquals(stringify(["\\,\",',`"]), `[ "\\\\,\\",',\`" ]`); }); -unitTest(function consoleTestStringifyLongStrings(): void { +Deno.test("consoleTestStringifyLongStrings", function (): void { const veryLongString = "a".repeat(200); // If we stringify an object containing the long string, it gets abbreviated. let actual = stringify({ veryLongString }); @@ -185,7 +182,7 @@ unitTest(function consoleTestStringifyLongStrings(): void { assertEquals(actual, veryLongString); }); -unitTest(function consoleTestStringifyCircular(): void { +Deno.test("consoleTestStringifyCircular", function (): void { class Base { a = 1; m1() {} @@ -346,7 +343,7 @@ unitTest(function consoleTestStringifyCircular(): void { assertEquals(stripColor(Deno.inspect(nestedObj)), nestedObjExpected); }); -unitTest(function consoleTestStringifyFunctionWithPrototypeRemoved(): void { +Deno.test("consoleTestStringifyFunctionWithPrototypeRemoved", function (): void { const f = function f() {}; Reflect.setPrototypeOf(f, null); assertEquals(stringify(f), "[Function: f]"); @@ -361,7 +358,7 @@ unitTest(function consoleTestStringifyFunctionWithPrototypeRemoved(): void { assertEquals(stringify(agf), "[Function: agf]"); }); -unitTest(function consoleTestStringifyFunctionWithProperties(): void { +Deno.test("consoleTestStringifyFunctionWithProperties", function (): void { const f = () => "test"; f.x = () => "foo"; f.y = 3; @@ -405,7 +402,7 @@ unitTest(function consoleTestStringifyFunctionWithProperties(): void { ); }); -unitTest(function consoleTestStringifyWithDepth(): void { +Deno.test("consoleTestStringifyWithDepth", function (): void { // deno-lint-ignore no-explicit-any const nestedObj: any = { a: { b: { c: { d: { e: { f: 42 } } } } } }; assertEquals( @@ -428,7 +425,7 @@ unitTest(function consoleTestStringifyWithDepth(): void { ); }); -unitTest(function consoleTestStringifyLargeObject(): void { +Deno.test("consoleTestStringifyLargeObject", function (): void { const obj = { a: 2, o: { @@ -464,7 +461,7 @@ unitTest(function consoleTestStringifyLargeObject(): void { ); }); -unitTest(function consoleTestStringifyIterable() { +Deno.test("consoleTestStringifyIterable", function () { const shortArray = [1, 2, 3, 4, 5]; assertEquals(stringify(shortArray), "[ 1, 2, 3, 4, 5 ]"); @@ -760,7 +757,7 @@ unitTest(function consoleTestStringifyIterable() { */ }); -unitTest(function consoleTestStringifyIterableWhenGrouped(): void { +Deno.test("consoleTestStringifyIterableWhenGrouped", function (): void { const withOddNumberOfEls = new Float64Array( [ 2.1, @@ -838,7 +835,7 @@ unitTest(function consoleTestStringifyIterableWhenGrouped(): void { ); }); -unitTest(async function consoleTestStringifyPromises(): Promise { +Deno.test("consoleTestStringifyPromises", async function (): Promise { const pendingPromise = new Promise((_res, _rej) => {}); assertEquals(stringify(pendingPromise), "Promise { }"); @@ -861,7 +858,7 @@ unitTest(async function consoleTestStringifyPromises(): Promise { assertEquals(strLines[1], " Error: Whoops"); }); -unitTest(function consoleTestWithCustomInspector(): void { +Deno.test("consoleTestWithCustomInspector", function (): void { class A { [customInspect](): string { return "b"; @@ -871,7 +868,7 @@ unitTest(function consoleTestWithCustomInspector(): void { assertEquals(stringify(new A()), "b"); }); -unitTest(function consoleTestWithCustomInspectorError(): void { +Deno.test("consoleTestWithCustomInspectorError", function (): void { class A { [customInspect](): never { throw new Error("BOOM"); @@ -886,7 +883,7 @@ unitTest(function consoleTestWithCustomInspectorError(): void { ); }); -unitTest(function consoleTestWithCustomInspectFunction(): void { +Deno.test("consoleTestWithCustomInspectFunction", function (): void { function a() {} Object.assign(a, { [customInspect]() { @@ -897,7 +894,7 @@ unitTest(function consoleTestWithCustomInspectFunction(): void { assertEquals(stringify(a), "b"); }); -unitTest(function consoleTestWithIntegerFormatSpecifier(): void { +Deno.test("consoleTestWithIntegerFormatSpecifier", function (): void { assertEquals(stringify("%i"), "%i"); assertEquals(stringify("%i", 42.0), "42"); assertEquals(stringify("%i", 42), "42"); @@ -915,7 +912,7 @@ unitTest(function consoleTestWithIntegerFormatSpecifier(): void { ); }); -unitTest(function consoleTestWithFloatFormatSpecifier(): void { +Deno.test("consoleTestWithFloatFormatSpecifier", function (): void { assertEquals(stringify("%f"), "%f"); assertEquals(stringify("%f", 42.0), "42"); assertEquals(stringify("%f", 42), "42"); @@ -930,7 +927,7 @@ unitTest(function consoleTestWithFloatFormatSpecifier(): void { assertEquals(stringify("%f %f", 42), "42 %f"); }); -unitTest(function consoleTestWithStringFormatSpecifier(): void { +Deno.test("consoleTestWithStringFormatSpecifier", function (): void { assertEquals(stringify("%s"), "%s"); assertEquals(stringify("%s", undefined), "undefined"); assertEquals(stringify("%s", "foo"), "foo"); @@ -941,7 +938,7 @@ unitTest(function consoleTestWithStringFormatSpecifier(): void { assertEquals(stringify("%s", Symbol("foo")), "Symbol(foo)"); }); -unitTest(function consoleTestWithObjectFormatSpecifier(): void { +Deno.test("consoleTestWithObjectFormatSpecifier", function (): void { assertEquals(stringify("%o"), "%o"); assertEquals(stringify("%o", 42), "42"); assertEquals(stringify("%o", "foo"), `"foo"`); @@ -953,13 +950,13 @@ unitTest(function consoleTestWithObjectFormatSpecifier(): void { ); }); -unitTest(function consoleTestWithStyleSpecifier(): void { +Deno.test("consoleTestWithStyleSpecifier", function (): void { assertEquals(stringify("%cfoo%cbar"), "%cfoo%cbar"); assertEquals(stringify("%cfoo%cbar", ""), "foo%cbar"); assertEquals(stripColor(stringify("%cfoo%cbar", "", "color: red")), "foobar"); }); -unitTest(function consoleParseCssColor(): void { +Deno.test("consoleParseCssColor", function (): void { assertEquals(parseCssColor("black"), [0, 0, 0]); assertEquals(parseCssColor("darkmagenta"), [139, 0, 139]); assertEquals(parseCssColor("slateblue"), [106, 90, 205]); @@ -978,7 +975,7 @@ unitTest(function consoleParseCssColor(): void { ); }); -unitTest(function consoleParseCss(): void { +Deno.test("consoleParseCss", function (): void { assertEquals( parseCss("background-color: red"), { ...DEFAULT_CSS, backgroundColor: [255, 0, 0] }, @@ -1032,7 +1029,7 @@ unitTest(function consoleParseCss(): void { ); }); -unitTest(function consoleCssToAnsi(): void { +Deno.test("consoleCssToAnsi", function (): void { assertEquals( cssToAnsiEsc({ ...DEFAULT_CSS, backgroundColor: [200, 201, 202] }), "_[48;2;200;201;202m", @@ -1072,7 +1069,7 @@ unitTest(function consoleCssToAnsi(): void { ); }); -unitTest(function consoleTestWithVariousOrInvalidFormatSpecifier(): void { +Deno.test("consoleTestWithVariousOrInvalidFormatSpecifier", function (): void { assertEquals(stringify("%s:%s"), "%s:%s"); assertEquals(stringify("%i:%i"), "%i:%i"); assertEquals(stringify("%d:%d"), "%d:%d"); @@ -1088,7 +1085,7 @@ unitTest(function consoleTestWithVariousOrInvalidFormatSpecifier(): void { assertEquals(stringify("abc%", 1), "abc% 1"); }); -unitTest(function consoleTestCallToStringOnLabel(): void { +Deno.test("consoleTestCallToStringOnLabel", function (): void { const methods = ["count", "countReset", "time", "timeLog", "timeEnd"]; mockConsole((console) => { for (const method of methods) { @@ -1103,7 +1100,7 @@ unitTest(function consoleTestCallToStringOnLabel(): void { }); }); -unitTest(function consoleTestError(): void { +Deno.test("consoleTestError", function (): void { class MyError extends Error { constructor(errStr: string) { super(errStr); @@ -1121,7 +1118,7 @@ unitTest(function consoleTestError(): void { } }); -unitTest(function consoleTestClear(): void { +Deno.test("consoleTestClear", function (): void { mockConsole((console, out) => { console.clear(); assertEquals(out.toString(), "\x1b[1;1H" + "\x1b[0J"); @@ -1129,7 +1126,7 @@ unitTest(function consoleTestClear(): void { }); // Test bound this issue -unitTest(function consoleDetachedLog(): void { +Deno.test("consoleDetachedLog", function (): void { mockConsole((console) => { const log = console.log; const dir = console.dir; @@ -1202,7 +1199,7 @@ function mockConsole(f: ConsoleExamineFunc): void { } // console.group test -unitTest(function consoleGroup(): void { +Deno.test("consoleGroup", function (): void { mockConsole((console, out): void => { console.group("1"); console.log("2"); @@ -1227,7 +1224,7 @@ unitTest(function consoleGroup(): void { }); // console.group with console.warn test -unitTest(function consoleGroupWarn(): void { +Deno.test("consoleGroupWarn", function (): void { mockConsole((console, _out, _err, both): void => { assert(both); console.warn("1"); @@ -1257,7 +1254,7 @@ unitTest(function consoleGroupWarn(): void { }); // console.table test -unitTest(function consoleTable(): void { +Deno.test("consoleTable", function (): void { mockConsole((console, out): void => { console.table({ a: "test", b: 1 }); assertEquals( @@ -1472,7 +1469,7 @@ unitTest(function consoleTable(): void { }); // console.log(Error) test -unitTest(function consoleLogShouldNotThrowError(): void { +Deno.test("consoleLogShouldNotThrowError", function (): void { mockConsole((console) => { let result = 0; try { @@ -1492,7 +1489,7 @@ unitTest(function consoleLogShouldNotThrowError(): void { }); // console.log(Invalid Date) test -unitTest(function consoleLogShoultNotThrowErrorWhenInvalidDateIsPassed(): void { +Deno.test("consoleLogShoultNotThrowErrorWhenInvalidDateIsPassed", function (): void { mockConsole((console, out) => { const invalidDate = new Date("test"); console.log(invalidDate); @@ -1501,7 +1498,7 @@ unitTest(function consoleLogShoultNotThrowErrorWhenInvalidDateIsPassed(): void { }); // console.dir test -unitTest(function consoleDir(): void { +Deno.test("consoleDir", function (): void { mockConsole((console, out): void => { console.dir("DIR"); assertEquals(out.toString(), "DIR\n"); @@ -1513,7 +1510,7 @@ unitTest(function consoleDir(): void { }); // console.dir test -unitTest(function consoleDirXml(): void { +Deno.test("consoleDirXml", function (): void { mockConsole((console, out): void => { console.dirxml("DIRXML"); assertEquals(out.toString(), "DIRXML\n"); @@ -1525,7 +1522,7 @@ unitTest(function consoleDirXml(): void { }); // console.trace test -unitTest(function consoleTrace(): void { +Deno.test("consoleTrace", function (): void { mockConsole((console, _out, err): void => { console.trace("%s", "custom message"); assert(err); @@ -1533,7 +1530,7 @@ unitTest(function consoleTrace(): void { }); }); -unitTest(function inspectString(): void { +Deno.test("inspectString", function (): void { assertEquals( stripColor(Deno.inspect("\0")), `"\\x00"`, @@ -1544,7 +1541,7 @@ unitTest(function inspectString(): void { ); }); -unitTest(function inspectGetters(): void { +Deno.test("inspectGetters", function (): void { assertEquals( stripColor(Deno.inspect({ get foo() { @@ -1573,12 +1570,12 @@ unitTest(function inspectGetters(): void { ); }); -unitTest(function inspectPrototype(): void { +Deno.test("inspectPrototype", function (): void { class A {} assertEquals(Deno.inspect(A.prototype), "A {}"); }); -unitTest(function inspectSorted(): void { +Deno.test("inspectSorted", function (): void { assertEquals( stripColor(Deno.inspect({ b: 2, a: 1 }, { sorted: true })), "{ a: 1, b: 2 }", @@ -1599,7 +1596,7 @@ unitTest(function inspectSorted(): void { ); }); -unitTest(function inspectTrailingComma(): void { +Deno.test("inspectTrailingComma", function (): void { assertEquals( stripColor(Deno.inspect( [ @@ -1654,7 +1651,7 @@ unitTest(function inspectTrailingComma(): void { ); }); -unitTest(function inspectCompact(): void { +Deno.test("inspectCompact", function (): void { assertEquals( stripColor(Deno.inspect({ a: 1, b: 2 }, { compact: false })), `{ @@ -1664,7 +1661,7 @@ unitTest(function inspectCompact(): void { ); }); -unitTest(function inspectIterableLimit(): void { +Deno.test("inspectIterableLimit", function (): void { assertEquals( stripColor(Deno.inspect(["a", "b", "c"], { iterableLimit: 2 })), `[ "a", "b", ... 1 more items ]`, @@ -1686,7 +1683,7 @@ unitTest(function inspectIterableLimit(): void { ); }); -unitTest(function inspectProxy(): void { +Deno.test("inspectProxy", function (): void { assertEquals( stripColor(Deno.inspect( new Proxy([1, 2, 3], { get(): void {} }), @@ -1736,7 +1733,7 @@ unitTest(function inspectProxy(): void { ); }); -unitTest(function inspectColors(): void { +Deno.test("inspectColors", function (): void { assertEquals(Deno.inspect(1), "1"); assertStringIncludes(Deno.inspect(1, { colors: true }), "\x1b["); }); diff --git a/cli/tests/unit/copy_file_test.ts b/cli/tests/unit/copy_file_test.ts index 96d08b10e0e40a..575736f824225b 100644 --- a/cli/tests/unit/copy_file_test.ts +++ b/cli/tests/unit/copy_file_test.ts @@ -1,10 +1,5 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { - assertEquals, - assertThrows, - assertThrowsAsync, - unitTest, -} from "./test_util.ts"; +import { assertEquals, assertThrows, assertThrowsAsync } from "./test_util.ts"; function readFileString(filename: string | URL): string { const dataRead = Deno.readFileSync(filename); @@ -27,182 +22,155 @@ function assertSameContent( assertEquals(data1, data2); } -unitTest( - { perms: { read: true, write: true } }, - function copyFileSyncSuccess(): void { - const tempDir = Deno.makeTempDirSync(); - const fromFilename = tempDir + "/from.txt"; - const toFilename = tempDir + "/to.txt"; - writeFileString(fromFilename, "Hello world!"); +Deno.test("copyFileSyncSuccess", function (): void { + const tempDir = Deno.makeTempDirSync(); + const fromFilename = tempDir + "/from.txt"; + const toFilename = tempDir + "/to.txt"; + writeFileString(fromFilename, "Hello world!"); + Deno.copyFileSync(fromFilename, toFilename); + // No change to original file + assertEquals(readFileString(fromFilename), "Hello world!"); + // Original == Dest + assertSameContent(fromFilename, toFilename); + + Deno.removeSync(tempDir, { recursive: true }); +}); + +Deno.test("copyFileSyncByUrl", function (): void { + const tempDir = Deno.makeTempDirSync(); + const fromUrl = new URL( + `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/from.txt`, + ); + const toUrl = new URL( + `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/to.txt`, + ); + writeFileString(fromUrl, "Hello world!"); + Deno.copyFileSync(fromUrl, toUrl); + // No change to original file + assertEquals(readFileString(fromUrl), "Hello world!"); + // Original == Dest + assertSameContent(fromUrl, toUrl); + + Deno.removeSync(tempDir, { recursive: true }); +}); + +Deno.test("copyFileSyncFailure", function (): void { + const tempDir = Deno.makeTempDirSync(); + const fromFilename = tempDir + "/from.txt"; + const toFilename = tempDir + "/to.txt"; + // We skip initial writing here, from.txt does not exist + assertThrows(() => { Deno.copyFileSync(fromFilename, toFilename); - // No change to original file - assertEquals(readFileString(fromFilename), "Hello world!"); - // Original == Dest - assertSameContent(fromFilename, toFilename); - - Deno.removeSync(tempDir, { recursive: true }); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - function copyFileSyncByUrl(): void { - const tempDir = Deno.makeTempDirSync(); - const fromUrl = new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/from.txt`, - ); - const toUrl = new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/to.txt`, - ); - writeFileString(fromUrl, "Hello world!"); - Deno.copyFileSync(fromUrl, toUrl); - // No change to original file - assertEquals(readFileString(fromUrl), "Hello world!"); - // Original == Dest - assertSameContent(fromUrl, toUrl); - - Deno.removeSync(tempDir, { recursive: true }); - }, -); - -unitTest( - { perms: { write: true, read: true } }, - function copyFileSyncFailure(): void { - const tempDir = Deno.makeTempDirSync(); - const fromFilename = tempDir + "/from.txt"; - const toFilename = tempDir + "/to.txt"; - // We skip initial writing here, from.txt does not exist - assertThrows(() => { - Deno.copyFileSync(fromFilename, toFilename); - }, Deno.errors.NotFound); - - Deno.removeSync(tempDir, { recursive: true }); - }, -); - -unitTest( - { perms: { write: true, read: false } }, - function copyFileSyncPerm1(): void { - assertThrows(() => { - Deno.copyFileSync("/from.txt", "/to.txt"); - }, Deno.errors.PermissionDenied); - }, -); - -unitTest( - { perms: { write: false, read: true } }, - function copyFileSyncPerm2(): void { - assertThrows(() => { - Deno.copyFileSync("/from.txt", "/to.txt"); - }, Deno.errors.PermissionDenied); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - function copyFileSyncOverwrite(): void { - const tempDir = Deno.makeTempDirSync(); - const fromFilename = tempDir + "/from.txt"; - const toFilename = tempDir + "/to.txt"; - writeFileString(fromFilename, "Hello world!"); - // Make Dest exist and have different content - writeFileString(toFilename, "Goodbye!"); - Deno.copyFileSync(fromFilename, toFilename); - // No change to original file - assertEquals(readFileString(fromFilename), "Hello world!"); - // Original == Dest - assertSameContent(fromFilename, toFilename); - - Deno.removeSync(tempDir, { recursive: true }); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function copyFileSuccess(): Promise { - const tempDir = Deno.makeTempDirSync(); - const fromFilename = tempDir + "/from.txt"; - const toFilename = tempDir + "/to.txt"; - writeFileString(fromFilename, "Hello world!"); - await Deno.copyFile(fromFilename, toFilename); - // No change to original file - assertEquals(readFileString(fromFilename), "Hello world!"); - // Original == Dest - assertSameContent(fromFilename, toFilename); - - Deno.removeSync(tempDir, { recursive: true }); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function copyFileByUrl(): Promise { - const tempDir = Deno.makeTempDirSync(); - const fromUrl = new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/from.txt`, - ); - const toUrl = new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/to.txt`, - ); - writeFileString(fromUrl, "Hello world!"); - await Deno.copyFile(fromUrl, toUrl); - // No change to original file - assertEquals(readFileString(fromUrl), "Hello world!"); - // Original == Dest - assertSameContent(fromUrl, toUrl); - - Deno.removeSync(tempDir, { recursive: true }); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function copyFileFailure(): Promise { - const tempDir = Deno.makeTempDirSync(); - const fromFilename = tempDir + "/from.txt"; - const toFilename = tempDir + "/to.txt"; - // We skip initial writing here, from.txt does not exist - await assertThrowsAsync(async () => { - await Deno.copyFile(fromFilename, toFilename); - }, Deno.errors.NotFound); - - Deno.removeSync(tempDir, { recursive: true }); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function copyFileOverwrite(): Promise { - const tempDir = Deno.makeTempDirSync(); - const fromFilename = tempDir + "/from.txt"; - const toFilename = tempDir + "/to.txt"; - writeFileString(fromFilename, "Hello world!"); - // Make Dest exist and have different content - writeFileString(toFilename, "Goodbye!"); + }, Deno.errors.NotFound); + + Deno.removeSync(tempDir, { recursive: true }); +}); + +Deno.test("copyFileSyncOverwrite", function (): void { + const tempDir = Deno.makeTempDirSync(); + const fromFilename = tempDir + "/from.txt"; + const toFilename = tempDir + "/to.txt"; + writeFileString(fromFilename, "Hello world!"); + // Make Dest exist and have different content + writeFileString(toFilename, "Goodbye!"); + Deno.copyFileSync(fromFilename, toFilename); + // No change to original file + assertEquals(readFileString(fromFilename), "Hello world!"); + // Original == Dest + assertSameContent(fromFilename, toFilename); + + Deno.removeSync(tempDir, { recursive: true }); +}); + +Deno.test("copyFileSuccess", async function (): Promise { + const tempDir = Deno.makeTempDirSync(); + const fromFilename = tempDir + "/from.txt"; + const toFilename = tempDir + "/to.txt"; + writeFileString(fromFilename, "Hello world!"); + await Deno.copyFile(fromFilename, toFilename); + // No change to original file + assertEquals(readFileString(fromFilename), "Hello world!"); + // Original == Dest + assertSameContent(fromFilename, toFilename); + + Deno.removeSync(tempDir, { recursive: true }); +}); + +Deno.test("copyFileByUrl", async function (): Promise { + const tempDir = Deno.makeTempDirSync(); + const fromUrl = new URL( + `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/from.txt`, + ); + const toUrl = new URL( + `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/to.txt`, + ); + writeFileString(fromUrl, "Hello world!"); + await Deno.copyFile(fromUrl, toUrl); + // No change to original file + assertEquals(readFileString(fromUrl), "Hello world!"); + // Original == Dest + assertSameContent(fromUrl, toUrl); + + Deno.removeSync(tempDir, { recursive: true }); +}); + +Deno.test("copyFileFailure", async function (): Promise { + const tempDir = Deno.makeTempDirSync(); + const fromFilename = tempDir + "/from.txt"; + const toFilename = tempDir + "/to.txt"; + // We skip initial writing here, from.txt does not exist + await assertThrowsAsync(async () => { await Deno.copyFile(fromFilename, toFilename); - // No change to original file - assertEquals(readFileString(fromFilename), "Hello world!"); - // Original == Dest - assertSameContent(fromFilename, toFilename); - - Deno.removeSync(tempDir, { recursive: true }); - }, -); - -unitTest( - { perms: { read: false, write: true } }, - async function copyFilePerm1(): Promise { - await assertThrowsAsync(async () => { - await Deno.copyFile("/from.txt", "/to.txt"); - }, Deno.errors.PermissionDenied); - }, -); - -unitTest( - { perms: { read: true, write: false } }, - async function copyFilePerm2(): Promise { - await assertThrowsAsync(async () => { - await Deno.copyFile("/from.txt", "/to.txt"); - }, Deno.errors.PermissionDenied); - }, -); + }, Deno.errors.NotFound); + + Deno.removeSync(tempDir, { recursive: true }); +}); + +Deno.test("copyFileOverwrite", async function (): Promise { + const tempDir = Deno.makeTempDirSync(); + const fromFilename = tempDir + "/from.txt"; + const toFilename = tempDir + "/to.txt"; + writeFileString(fromFilename, "Hello world!"); + // Make Dest exist and have different content + writeFileString(toFilename, "Goodbye!"); + await Deno.copyFile(fromFilename, toFilename); + // No change to original file + assertEquals(readFileString(fromFilename), "Hello world!"); + // Original == Dest + assertSameContent(fromFilename, toFilename); + + Deno.removeSync(tempDir, { recursive: true }); +}); + +Deno.test("copyFilePerm1", async function (): Promise { + await Deno.permissions.revoke({ name: "read" }); + + await assertThrowsAsync(async () => { + await Deno.copyFile("/from.txt", "/to.txt"); + }, Deno.errors.PermissionDenied); +}); + +Deno.test("copyFileSyncPerm1", async function (): Promise { + await Deno.permissions.revoke({ name: "read" }); + + assertThrows(() => { + Deno.copyFileSync("/from.txt", "/to.txt"); + }, Deno.errors.PermissionDenied); +}); + +Deno.test("copyFilePerm2", async function (): Promise { + await Deno.permissions.revoke({ name: "write" }); + + await assertThrowsAsync(async () => { + await Deno.copyFile("/from.txt", "/to.txt"); + }, Deno.errors.PermissionDenied); +}); + + +Deno.test("copyFileSyncPerm2", async function (): Promise { + await Deno.permissions.revoke({ name: "write" }); + + assertThrows(() => { + Deno.copyFileSync("/from.txt", "/to.txt"); + }, Deno.errors.PermissionDenied); +}); diff --git a/cli/tests/unit/filter_function_test.ts b/cli/tests/unit/create_test_filter_test.ts similarity index 54% rename from cli/tests/unit/filter_function_test.ts rename to cli/tests/unit/create_test_filter_test.ts index 2c1d9a7c85491f..5538dff746debc 100644 --- a/cli/tests/unit/filter_function_test.ts +++ b/cli/tests/unit/create_test_filter_test.ts @@ -1,10 +1,10 @@ -import { assertEquals, unitTest } from "./test_util.ts"; +import { assertEquals } from "./test_util.ts"; // @ts-expect-error TypeScript (as of 3.7) does not support indexing namespaces by symbol -const { createFilterFn } = Deno[Deno.internal]; +const { createTestFilter } = Deno[Deno.internal]; -unitTest(function filterAsString(): void { - const filterFn = createFilterFn("my-test"); +Deno.test("filterAsString", function (): void { + const testFilter = createTestFilter("my-test"); const tests = [ { fn(): void {}, @@ -15,12 +15,12 @@ unitTest(function filterAsString(): void { name: "other-test", }, ]; - const filteredTests = tests.filter(filterFn); + const filteredTests = tests.filter(testFilter); assertEquals(filteredTests.length, 1); }); -unitTest(function filterAsREGEX(): void { - const filterFn = createFilterFn("/.+-test/"); +Deno.test("filterAsREGEX", function (): void { + const testFilter = createTestFilter("/.+-test/"); const tests = [ { fn(): void {}, @@ -31,12 +31,12 @@ unitTest(function filterAsREGEX(): void { name: "other-test", }, ]; - const filteredTests = tests.filter(filterFn); + const filteredTests = tests.filter(testFilter); assertEquals(filteredTests.length, 2); }); -unitTest(function filterAsEscapedREGEX(): void { - const filterFn = createFilterFn("/\\w+-test/"); +Deno.test("filterAsEscapedREGEX", function (): void { + const testFilter = createTestFilter("/\\w+-test/"); const tests = [ { fn(): void {}, @@ -47,6 +47,6 @@ unitTest(function filterAsEscapedREGEX(): void { name: "other-test", }, ]; - const filteredTests = tests.filter(filterFn); + const filteredTests = tests.filter(testFilter); assertEquals(filteredTests.length, 2); }); diff --git a/cli/tests/unit/custom_event_test.ts b/cli/tests/unit/custom_event_test.ts index 0db770056ea7d1..ce564d9ba0143e 100644 --- a/cli/tests/unit/custom_event_test.ts +++ b/cli/tests/unit/custom_event_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assertEquals, unitTest } from "./test_util.ts"; +import { assertEquals } from "./test_util.ts"; -unitTest(function customEventInitializedWithDetail(): void { +Deno.test("customEventInitializedWithDetail", function (): void { const type = "touchstart"; const detail = { message: "hello" }; const customEventInit = { @@ -20,7 +20,7 @@ unitTest(function customEventInitializedWithDetail(): void { assertEquals(event.type, type); }); -unitTest(function toStringShouldBeWebCompatibility(): void { +Deno.test("toStringShouldBeWebCompatibility", function (): void { const type = "touchstart"; const event = new CustomEvent(type, {}); assertEquals(event.toString(), "[object CustomEvent]"); diff --git a/cli/tests/unit/dir_test.ts b/cli/tests/unit/dir_test.ts index e64baf97bf6f01..ea9350946e0561 100644 --- a/cli/tests/unit/dir_test.ts +++ b/cli/tests/unit/dir_test.ts @@ -1,27 +1,24 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assert, assertEquals, assertThrows, unitTest } from "./test_util.ts"; +import { assert, assertEquals, assertThrows } from "./test_util.ts"; -unitTest({ perms: { read: true } }, function dirCwdNotNull(): void { +Deno.test("dirCwdNotNull", function (): void { assert(Deno.cwd() != null); }); -unitTest( - { perms: { read: true, write: true } }, - function dirCwdChdirSuccess(): void { - const initialdir = Deno.cwd(); - const path = Deno.makeTempDirSync(); - Deno.chdir(path); - const current = Deno.cwd(); - if (Deno.build.os === "darwin") { - assertEquals(current, "/private" + path); - } else { - assertEquals(current, path); - } - Deno.chdir(initialdir); - }, -); +Deno.test("dirCwdChdirSuccess", function (): void { + const initialdir = Deno.cwd(); + const path = Deno.makeTempDirSync(); + Deno.chdir(path); + const current = Deno.cwd(); + if (Deno.build.os === "darwin") { + assertEquals(current, "/private" + path); + } else { + assertEquals(current, path); + } + Deno.chdir(initialdir); +}); -unitTest({ perms: { read: true, write: true } }, function dirCwdError(): void { +Deno.test("dirCwdError", function (): void { // excluding windows since it throws resource busy, while removeSync if (["linux", "darwin"].includes(Deno.build.os)) { const initialdir = Deno.cwd(); @@ -38,7 +35,16 @@ unitTest({ perms: { read: true, write: true } }, function dirCwdError(): void { } }); -unitTest({ perms: { read: false } }, function dirCwdPermError(): void { +Deno.test("dirChdirError", function (): void { + const path = Deno.makeTempDirSync() + "test"; + assertThrows(() => { + Deno.chdir(path); + }, Deno.errors.NotFound); +}); + +Deno.test("dirCwdPermError", async function (): Promise { + await Deno.permissions.revoke({ name: "read" }); + assertThrows( () => { Deno.cwd(); @@ -48,12 +54,4 @@ unitTest({ perms: { read: false } }, function dirCwdPermError(): void { ); }); -unitTest( - { perms: { read: true, write: true } }, - function dirChdirError(): void { - const path = Deno.makeTempDirSync() + "test"; - assertThrows(() => { - Deno.chdir(path); - }, Deno.errors.NotFound); - }, -); + diff --git a/cli/tests/unit/dispatch_buffer_test.ts b/cli/tests/unit/dispatch_buffer_test.ts index 0e213fe3b66fbf..dece9e600c3574 100644 --- a/cli/tests/unit/dispatch_buffer_test.ts +++ b/cli/tests/unit/dispatch_buffer_test.ts @@ -1,10 +1,4 @@ -import { - assert, - assertEquals, - assertMatch, - unitTest, - unreachable, -} from "./test_util.ts"; +import { assert, assertEquals, assertMatch, unreachable } from "./test_util.ts"; const readErrorStackPattern = new RegExp( `^.* @@ -14,7 +8,7 @@ const readErrorStackPattern = new RegExp( "ms", ); -unitTest(async function sendAsyncStackTrace(): Promise { +Deno.test("sendAsyncStackTrace", async function (): Promise { const buf = new Uint8Array(10); const rid = 10; try { @@ -33,7 +27,7 @@ declare global { } } -unitTest(function bufferOpsHeaderTooShort(): void { +Deno.test("bufferOpsHeaderTooShort", function (): void { for (const op of ["op_read_sync", "op_read_async"]) { const readOpId = Deno.core.ops()[op]; const res = Deno.core.send( diff --git a/cli/tests/unit/dispatch_json_test.ts b/cli/tests/unit/dispatch_json_test.ts index c283e20c9928ff..f37c49cce318c8 100644 --- a/cli/tests/unit/dispatch_json_test.ts +++ b/cli/tests/unit/dispatch_json_test.ts @@ -1,4 +1,4 @@ -import { assertMatch, assertStrictEquals, unitTest } from "./test_util.ts"; +import { assertMatch, assertStrictEquals } from "./test_util.ts"; declare global { // deno-lint-ignore no-namespace @@ -8,7 +8,7 @@ declare global { } } -unitTest(function malformedJsonControlBuffer(): void { +Deno.test("malformedJsonControlBuffer", function (): void { const opId = Deno.core.ops()["op_open_sync"]; const argsBuf = new Uint8Array([1, 2, 3, 4, 5]); const resBuf = Deno.core.send(opId, argsBuf); @@ -19,7 +19,7 @@ unitTest(function malformedJsonControlBuffer(): void { assertMatch(resObj.err.message, /\bexpected value\b/); }); -unitTest(function invalidPromiseId(): void { +Deno.test("invalidPromiseId", function (): void { const opId = Deno.core.ops()["op_open_async"]; const reqBuf = new Uint8Array([0, 0, 0, 0, 0, 0, 0]); const resBuf = Deno.core.send(opId, reqBuf); diff --git a/cli/tests/unit/dom_iterable_test.ts b/cli/tests/unit/dom_iterable_test.ts index 4e94cfdba24243..5a60039dbdb448 100644 --- a/cli/tests/unit/dom_iterable_test.ts +++ b/cli/tests/unit/dom_iterable_test.ts @@ -1,6 +1,6 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assert, assertEquals, unitTest } from "./test_util.ts"; +import { assert, assertEquals } from "./test_util.ts"; // eslint-disable-next-line @typescript-eslint/explicit-function-return-type function setup() { @@ -26,7 +26,7 @@ function setup() { }; } -unitTest(function testDomIterable(): void { +Deno.test("testDomIterable", function (): void { const { DomIterable, Base } = setup(); const fixture: Array<[string, number]> = [ @@ -68,7 +68,7 @@ unitTest(function testDomIterable(): void { assertEquals(DomIterable.name, Base.name); }); -unitTest(function testDomIterableScope(): void { +Deno.test("testDomIterableScope", function (): void { const { DomIterable } = setup(); const domIterable = new DomIterable([["foo", 1]]); diff --git a/cli/tests/unit/error_stack_test.ts b/cli/tests/unit/error_stack_test.ts index 1445124e947c43..ee6645748db7c7 100644 --- a/cli/tests/unit/error_stack_test.ts +++ b/cli/tests/unit/error_stack_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assert, assertEquals, assertMatch, unitTest } from "./test_util.ts"; +import { assert, assertEquals, assertMatch } from "./test_util.ts"; -unitTest(function errorStackMessageLine(): void { +Deno.test("errorStackMessageLine", function (): void { const e1 = new Error(); e1.name = "Foo"; e1.message = "bar"; @@ -41,7 +41,7 @@ unitTest(function errorStackMessageLine(): void { assertMatch(e6.stack!, /^null: null\n/); }); -unitTest(function captureStackTrace(): void { +Deno.test("captureStackTrace", function (): void { function foo(): void { const error = new Error(); const stack1 = error.stack!; @@ -55,14 +55,18 @@ unitTest(function captureStackTrace(): void { // FIXME(bartlomieju): no longer works after migrating // to JavaScript runtime code -unitTest({ ignore: true }, function applySourceMap(): void { - const result = Deno.applySourceMap({ - fileName: "CLI_SNAPSHOT.js", - lineNumber: 23, - columnNumber: 0, - }); - Deno.core.print(`result: ${result}`, true); - assert(result.fileName.endsWith(".ts")); - assert(result.lineNumber != null); - assert(result.columnNumber != null); +Deno.test({ + name: "applySourceMap", + ignore: true, + fn(): void { + const result = Deno.applySourceMap({ + fileName: "CLI_SNAPSHOT.js", + lineNumber: 23, + columnNumber: 0, + }); + Deno.core.print(`result: ${result}`, true); + assert(result.fileName.endsWith(".ts")); + assert(result.lineNumber != null); + assert(result.columnNumber != null); + }, }); diff --git a/cli/tests/unit/event_target_test.ts b/cli/tests/unit/event_target_test.ts index 29de04c8cb2ee4..c9d9cce1e041ca 100644 --- a/cli/tests/unit/event_target_test.ts +++ b/cli/tests/unit/event_target_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assertEquals, unitTest } from "./test_util.ts"; +import { assertEquals } from "./test_util.ts"; -unitTest(function addEventListenerTest(): void { +Deno.test("addEventListenerTest", function (): void { const document = new EventTarget(); assertEquals(document.addEventListener("x", null, false), undefined); @@ -9,7 +9,7 @@ unitTest(function addEventListenerTest(): void { assertEquals(document.addEventListener("x", null), undefined); }); -unitTest(function constructedEventTargetCanBeUsedAsExpected(): void { +Deno.test("constructedEventTargetCanBeUsedAsExpected", function (): void { const target = new EventTarget(); const event = new Event("foo", { bubbles: true, cancelable: false }); let callCount = 0; @@ -32,7 +32,7 @@ unitTest(function constructedEventTargetCanBeUsedAsExpected(): void { assertEquals(callCount, 2); }); -unitTest(function anEventTargetCanBeSubclassed(): void { +Deno.test("anEventTargetCanBeSubclassed", function (): void { class NicerEventTarget extends EventTarget { on( type: string, @@ -66,14 +66,14 @@ unitTest(function anEventTargetCanBeSubclassed(): void { assertEquals(callCount, 0); }); -unitTest(function removingNullEventListenerShouldSucceed(): void { +Deno.test("removingNullEventListenerShouldSucceed", function (): void { const document = new EventTarget(); assertEquals(document.removeEventListener("x", null, false), undefined); assertEquals(document.removeEventListener("x", null, true), undefined); assertEquals(document.removeEventListener("x", null), undefined); }); -unitTest(function constructedEventTargetUseObjectPrototype(): void { +Deno.test("constructedEventTargetUseObjectPrototype", function (): void { const target = new EventTarget(); const event = new Event("toString", { bubbles: true, cancelable: false }); let callCount = 0; @@ -96,12 +96,12 @@ unitTest(function constructedEventTargetUseObjectPrototype(): void { assertEquals(callCount, 2); }); -unitTest(function toStringShouldBeWebCompatible(): void { +Deno.test("toStringShouldBeWebCompatible", function (): void { const target = new EventTarget(); assertEquals(target.toString(), "[object EventTarget]"); }); -unitTest(function dispatchEventShouldNotThrowError(): void { +Deno.test("dispatchEventShouldNotThrowError", function (): void { let hasThrown = false; try { @@ -120,7 +120,7 @@ unitTest(function dispatchEventShouldNotThrowError(): void { assertEquals(hasThrown, false); }); -unitTest(function eventTargetThisShouldDefaultToWindow(): void { +Deno.test("eventTargetThisShouldDefaultToWindow", function (): void { const { addEventListener, dispatchEvent, @@ -149,7 +149,7 @@ unitTest(function eventTargetThisShouldDefaultToWindow(): void { assertEquals(n, 1); }); -unitTest(function eventTargetShouldAcceptEventListenerObject(): void { +Deno.test("eventTargetShouldAcceptEventListenerObject", function (): void { const target = new EventTarget(); const event = new Event("foo", { bubbles: true, cancelable: false }); let callCount = 0; @@ -174,7 +174,7 @@ unitTest(function eventTargetShouldAcceptEventListenerObject(): void { assertEquals(callCount, 2); }); -unitTest(function eventTargetShouldAcceptAsyncFunction(): void { +Deno.test("eventTargetShouldAcceptAsyncFunction", function (): void { const target = new EventTarget(); const event = new Event("foo", { bubbles: true, cancelable: false }); let callCount = 0; @@ -197,33 +197,31 @@ unitTest(function eventTargetShouldAcceptAsyncFunction(): void { assertEquals(callCount, 2); }); -unitTest( - function eventTargetShouldAcceptAsyncFunctionForEventListenerObject(): void { - const target = new EventTarget(); - const event = new Event("foo", { bubbles: true, cancelable: false }); - let callCount = 0; +Deno.test("eventTargetShouldAcceptAsyncFunctionForEventListenerObject", function (): void { + const target = new EventTarget(); + const event = new Event("foo", { bubbles: true, cancelable: false }); + let callCount = 0; - const listener = { - handleEvent(e: Event): void { - assertEquals(e, event); - ++callCount; - }, - }; + const listener = { + handleEvent(e: Event): void { + assertEquals(e, event); + ++callCount; + }, + }; - target.addEventListener("foo", listener); + target.addEventListener("foo", listener); - target.dispatchEvent(event); - assertEquals(callCount, 1); + target.dispatchEvent(event); + assertEquals(callCount, 1); - target.dispatchEvent(event); - assertEquals(callCount, 2); + target.dispatchEvent(event); + assertEquals(callCount, 2); - target.removeEventListener("foo", listener); - target.dispatchEvent(event); - assertEquals(callCount, 2); - }, -); -unitTest(function eventTargetDispatchShouldSetTargetNoListener(): void { + target.removeEventListener("foo", listener); + target.dispatchEvent(event); + assertEquals(callCount, 2); +}); +Deno.test("eventTargetDispatchShouldSetTargetNoListener", function (): void { const target = new EventTarget(); const event = new Event("foo"); assertEquals(event.target, null); @@ -231,7 +229,7 @@ unitTest(function eventTargetDispatchShouldSetTargetNoListener(): void { assertEquals(event.target, target); }); -unitTest(function eventTargetDispatchShouldSetTargetInListener(): void { +Deno.test("eventTargetDispatchShouldSetTargetInListener", function (): void { const target = new EventTarget(); const event = new Event("foo"); assertEquals(event.target, null); diff --git a/cli/tests/unit/event_test.ts b/cli/tests/unit/event_test.ts index 9eb90fa36c3318..c165e23135c41e 100644 --- a/cli/tests/unit/event_test.ts +++ b/cli/tests/unit/event_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assert, assertEquals, unitTest } from "./test_util.ts"; +import { assert, assertEquals } from "./test_util.ts"; -unitTest(function eventInitializedWithType(): void { +Deno.test("eventInitializedWithType", function (): void { const type = "click"; const event = new Event(type); @@ -13,7 +13,7 @@ unitTest(function eventInitializedWithType(): void { assertEquals(event.cancelable, false); }); -unitTest(function eventInitializedWithTypeAndDict(): void { +Deno.test("eventInitializedWithTypeAndDict", function (): void { const init = "submit"; const eventInit = { bubbles: true, cancelable: true } as EventInit; const event = new Event(init, eventInit); @@ -26,7 +26,7 @@ unitTest(function eventInitializedWithTypeAndDict(): void { assertEquals(event.cancelable, true); }); -unitTest(function eventComposedPathSuccess(): void { +Deno.test("eventComposedPathSuccess", function (): void { const type = "click"; const event = new Event(type); const composedPath = event.composedPath(); @@ -34,7 +34,7 @@ unitTest(function eventComposedPathSuccess(): void { assertEquals(composedPath, []); }); -unitTest(function eventStopPropagationSuccess(): void { +Deno.test("eventStopPropagationSuccess", function (): void { const type = "click"; const event = new Event(type); @@ -43,7 +43,7 @@ unitTest(function eventStopPropagationSuccess(): void { assertEquals(event.cancelBubble, true); }); -unitTest(function eventStopImmediatePropagationSuccess(): void { +Deno.test("eventStopImmediatePropagationSuccess", function (): void { const type = "click"; const event = new Event(type); @@ -52,7 +52,7 @@ unitTest(function eventStopImmediatePropagationSuccess(): void { assertEquals(event.cancelBubble, true); }); -unitTest(function eventPreventDefaultSuccess(): void { +Deno.test("eventPreventDefaultSuccess", function (): void { const type = "click"; const event = new Event(type); @@ -67,7 +67,7 @@ unitTest(function eventPreventDefaultSuccess(): void { assertEquals(cancelableEvent.defaultPrevented, true); }); -unitTest(function eventInitializedWithNonStringType(): void { +Deno.test("eventInitializedWithNonStringType", function (): void { // deno-lint-ignore no-explicit-any const type: any = undefined; const event = new Event(type); @@ -81,7 +81,7 @@ unitTest(function eventInitializedWithNonStringType(): void { }); // ref https://github.com/web-platform-tests/wpt/blob/master/dom/events/Event-isTrusted.any.js -unitTest(function eventIsTrusted(): void { +Deno.test("eventIsTrusted", function (): void { const desc1 = Object.getOwnPropertyDescriptor(new Event("x"), "isTrusted"); assert(desc1); assertEquals(typeof desc1.get, "function"); @@ -93,7 +93,7 @@ unitTest(function eventIsTrusted(): void { assertEquals(desc1!.get, desc2!.get); }); -unitTest(function eventInspectOutput(): void { +Deno.test("eventInspectOutput", function (): void { // deno-lint-ignore no-explicit-any const cases: Array<[any, (event: any) => string]> = [ [ diff --git a/cli/tests/unit/fetch_test.ts b/cli/tests/unit/fetch_test.ts index fa013f0c5b31e2..5473d39e53da8b 100644 --- a/cli/tests/unit/fetch_test.ts +++ b/cli/tests/unit/fetch_test.ts @@ -6,10 +6,9 @@ import { assertThrowsAsync, fail, unimplemented, - unitTest, } from "./test_util.ts"; -unitTest({ perms: { net: true } }, async function fetchProtocolError(): Promise< +Deno.test("fetchProtocolError", async function (): Promise< void > { await assertThrowsAsync( @@ -45,46 +44,37 @@ function findClosedPortInRange( ); } -unitTest( - { perms: { net: true } }, - async function fetchConnectionError(): Promise { - const port = findClosedPortInRange(4000, 9999); - await assertThrowsAsync( - async (): Promise => { - await fetch(`http://localhost:${port}`); - }, - TypeError, - "error trying to connect", - ); - }, -); +Deno.test("fetchConnectionError", async function (): Promise { + const port = findClosedPortInRange(4000, 9999); + await assertThrowsAsync( + async (): Promise => { + await fetch(`http://localhost:${port}`); + }, + TypeError, + "error trying to connect", + ); +}); -unitTest( - { perms: { net: true } }, - async function fetchDnsError(): Promise { - await assertThrowsAsync( - async (): Promise => { - await fetch("http://nil/"); - }, - TypeError, - "error trying to connect", - ); - }, -); +Deno.test("fetchDnsError", async function (): Promise { + await assertThrowsAsync( + async (): Promise => { + await fetch("http://nil/"); + }, + TypeError, + "error trying to connect", + ); +}); -unitTest( - { perms: { net: true } }, - async function fetchInvalidUriError(): Promise { - await assertThrowsAsync( - async (): Promise => { - await fetch("http:///"); - }, - URIError, - ); - }, -); +Deno.test("fetchInvalidUriError", async function (): Promise { + await assertThrowsAsync( + async (): Promise => { + await fetch("http:///"); + }, + URIError, + ); +}); -unitTest({ perms: { net: true } }, async function fetchJsonSuccess(): Promise< +Deno.test("fetchJsonSuccess", async function (): Promise< void > { const response = await fetch("http://localhost:4545/cli/tests/fixture.json"); @@ -92,19 +82,13 @@ unitTest({ perms: { net: true } }, async function fetchJsonSuccess(): Promise< assertEquals(json.name, "deno"); }); -unitTest(async function fetchPerm(): Promise { - await assertThrowsAsync(async () => { - await fetch("http://localhost:4545/cli/tests/fixture.json"); - }, Deno.errors.PermissionDenied); -}); - -unitTest({ perms: { net: true } }, async function fetchUrl(): Promise { +Deno.test("fetchUrl", async function (): Promise { const response = await fetch("http://localhost:4545/cli/tests/fixture.json"); assertEquals(response.url, "http://localhost:4545/cli/tests/fixture.json"); const _json = await response.json(); }); -unitTest({ perms: { net: true } }, async function fetchURL(): Promise { +Deno.test("fetchURL", async function (): Promise { const response = await fetch( new URL("http://localhost:4545/cli/tests/fixture.json"), ); @@ -112,7 +96,7 @@ unitTest({ perms: { net: true } }, async function fetchURL(): Promise { const _json = await response.json(); }); -unitTest({ perms: { net: true } }, async function fetchHeaders(): Promise< +Deno.test("fetchHeaders", async function (): Promise< void > { const response = await fetch("http://localhost:4545/cli/tests/fixture.json"); @@ -121,7 +105,7 @@ unitTest({ perms: { net: true } }, async function fetchHeaders(): Promise< const _json = await response.json(); }); -unitTest({ perms: { net: true } }, async function fetchBlob(): Promise { +Deno.test("fetchBlob", async function (): Promise { const response = await fetch("http://localhost:4545/cli/tests/fixture.json"); const headers = response.headers; const blob = await response.blob(); @@ -129,7 +113,7 @@ unitTest({ perms: { net: true } }, async function fetchBlob(): Promise { assertEquals(blob.size, Number(headers.get("Content-Length"))); }); -unitTest({ perms: { net: true } }, async function fetchBodyUsed(): Promise< +Deno.test("fetchBodyUsed", async function (): Promise< void > { const response = await fetch("http://localhost:4545/cli/tests/fixture.json"); @@ -141,40 +125,34 @@ unitTest({ perms: { net: true } }, async function fetchBodyUsed(): Promise< assertEquals(response.bodyUsed, true); }); -unitTest( - { perms: { net: true } }, - async function fetchBodyUsedReader(): Promise { - const response = await fetch( - "http://localhost:4545/cli/tests/fixture.json", - ); - assert(response.body !== null); +Deno.test("fetchBodyUsedReader", async function (): Promise { + const response = await fetch( + "http://localhost:4545/cli/tests/fixture.json", + ); + assert(response.body !== null); - const reader = response.body.getReader(); - // Getting a reader should lock the stream but does not consume the body - // so bodyUsed should not be true - assertEquals(response.bodyUsed, false); - reader.releaseLock(); - await response.json(); - assertEquals(response.bodyUsed, true); - }, -); + const reader = response.body.getReader(); + // Getting a reader should lock the stream but does not consume the body + // so bodyUsed should not be true + assertEquals(response.bodyUsed, false); + reader.releaseLock(); + await response.json(); + assertEquals(response.bodyUsed, true); +}); -unitTest( - { perms: { net: true } }, - async function fetchBodyUsedCancelStream(): Promise { - const response = await fetch( - "http://localhost:4545/cli/tests/fixture.json", - ); - assert(response.body !== null); +Deno.test("fetchBodyUsedCancelStream", async function (): Promise { + const response = await fetch( + "http://localhost:4545/cli/tests/fixture.json", + ); + assert(response.body !== null); - assertEquals(response.bodyUsed, false); - const promise = response.body.cancel(); - assertEquals(response.bodyUsed, true); - await promise; - }, -); + assertEquals(response.bodyUsed, false); + const promise = response.body.cancel(); + assertEquals(response.bodyUsed, true); + await promise; +}); -unitTest({ perms: { net: true } }, async function fetchAsyncIterator(): Promise< +Deno.test("fetchAsyncIterator", async function (): Promise< void > { const response = await fetch("http://localhost:4545/cli/tests/fixture.json"); @@ -190,7 +168,7 @@ unitTest({ perms: { net: true } }, async function fetchAsyncIterator(): Promise< assertEquals(total, Number(headers.get("Content-Length"))); }); -unitTest({ perms: { net: true } }, async function fetchBodyReader(): Promise< +Deno.test("fetchBodyReader", async function (): Promise< void > { const response = await fetch("http://localhost:4545/cli/tests/fixture.json"); @@ -209,29 +187,26 @@ unitTest({ perms: { net: true } }, async function fetchBodyReader(): Promise< assertEquals(total, Number(headers.get("Content-Length"))); }); -unitTest( - { perms: { net: true } }, - async function fetchBodyReaderBigBody(): Promise { - const data = "a".repeat(10 << 10); // 10mb - const response = await fetch("http://localhost:4545/echo_server", { - method: "POST", - body: data, - }); - assert(response.body !== null); - const reader = await response.body.getReader(); - let total = 0; - while (true) { - const { done, value } = await reader.read(); - if (done) break; - assert(value); - total += value.length; - } +Deno.test("fetchBodyReaderBigBody", async function (): Promise { + const data = "a".repeat(10 << 10); // 10mb + const response = await fetch("http://localhost:4545/echo_server", { + method: "POST", + body: data, + }); + assert(response.body !== null); + const reader = await response.body.getReader(); + let total = 0; + while (true) { + const { done, value } = await reader.read(); + if (done) break; + assert(value); + total += value.length; + } - assertEquals(total, data.length); - }, -); + assertEquals(total, data.length); +}); -unitTest({ perms: { net: true } }, async function responseClone(): Promise< +Deno.test("responseClone", async function (): Promise< void > { const response = await fetch("http://localhost:4545/cli/tests/fixture.json"); @@ -246,265 +221,217 @@ unitTest({ perms: { net: true } }, async function responseClone(): Promise< } }); -unitTest( - { perms: { net: true } }, - async function fetchMultipartFormDataSuccess(): Promise { - const response = await fetch( - "http://localhost:4545/multipart_form_data.txt", - ); - const formData = await response.formData(); - assert(formData.has("field_1")); - assertEquals(formData.get("field_1")!.toString(), "value_1 \r\n"); - assert(formData.has("field_2")); - const file = formData.get("field_2") as File; - assertEquals(file.name, "file.js"); - - assertEquals(await file.text(), `console.log("Hi")`); - }, -); - -unitTest( - { perms: { net: true } }, - async function fetchMultipartFormBadContentType(): Promise { - const response = await fetch( - "http://localhost:4545/multipart_form_bad_content_type", - ); - assert(response.body !== null); - - await assertThrowsAsync( - async (): Promise => { - await response.formData(); - }, - TypeError, - "Invalid form data", - ); - await response.body.cancel(); - }, -); +Deno.test("fetchMultipartFormDataSuccess", async function (): Promise { + const response = await fetch( + "http://localhost:4545/multipart_form_data.txt", + ); + const formData = await response.formData(); + assert(formData.has("field_1")); + assertEquals(formData.get("field_1")!.toString(), "value_1 \r\n"); + assert(formData.has("field_2")); + const file = formData.get("field_2") as File; + assertEquals(file.name, "file.js"); + + assertEquals(await file.text(), `console.log("Hi")`); +}); -unitTest( - { perms: { net: true } }, - async function fetchURLEncodedFormDataSuccess(): Promise { - const response = await fetch( - "http://localhost:4545/cli/tests/subdir/form_urlencoded.txt", - ); - const formData = await response.formData(); - assert(formData.has("field_1")); - assertEquals(formData.get("field_1")!.toString(), "Hi"); - assert(formData.has("field_2")); - assertEquals(formData.get("field_2")!.toString(), ""); - }, -); +Deno.test("fetchMultipartFormBadContentType", async function (): Promise { + const response = await fetch( + "http://localhost:4545/multipart_form_bad_content_type", + ); + assert(response.body !== null); -unitTest( - { perms: { net: true } }, - async function fetchInitFormDataBinaryFileBody(): Promise { - // Some random bytes - // deno-fmt-ignore - const binaryFile = new Uint8Array([108,2,0,0,145,22,162,61,157,227,166,77,138,75,180,56,119,188,177,183]); - const response = await fetch("http://localhost:4545/echo_multipart_file", { - method: "POST", - body: binaryFile, - }); - const resultForm = await response.formData(); - const resultFile = resultForm.get("file") as File; + await assertThrowsAsync( + async (): Promise => { + await response.formData(); + }, + TypeError, + "Invalid form data", + ); + await response.body.cancel(); +}); - assertEquals(resultFile.type, "application/octet-stream"); - assertEquals(resultFile.name, "file.bin"); - assertEquals(new Uint8Array(await resultFile.arrayBuffer()), binaryFile); - }, -); +Deno.test("fetchURLEncodedFormDataSuccess", async function (): Promise { + const response = await fetch( + "http://localhost:4545/cli/tests/subdir/form_urlencoded.txt", + ); + const formData = await response.formData(); + assert(formData.has("field_1")); + assertEquals(formData.get("field_1")!.toString(), "Hi"); + assert(formData.has("field_2")); + assertEquals(formData.get("field_2")!.toString(), ""); +}); -unitTest( - { perms: { net: true } }, - async function fetchInitFormDataMultipleFilesBody(): Promise { - const files = [ - { - // deno-fmt-ignore - content: new Uint8Array([137,80,78,71,13,10,26,10, 137, 1, 25]), - type: "image/png", - name: "image", - fileName: "some-image.png", - }, - { - // deno-fmt-ignore - content: new Uint8Array([108,2,0,0,145,22,162,61,157,227,166,77,138,75,180,56,119,188,177,183]), - name: "file", - fileName: "file.bin", - expectedType: "application/octet-stream", - }, - { - content: new TextEncoder().encode("deno land"), - type: "text/plain", - name: "text", - fileName: "deno.txt", - }, - ]; - const form = new FormData(); - form.append("field", "value"); - for (const file of files) { - form.append( - file.name, - new Blob([file.content], { type: file.type }), - file.fileName, - ); - } - const response = await fetch("http://localhost:4545/echo_server", { - method: "POST", - body: form, - }); - const resultForm = await response.formData(); - assertEquals(form.get("field"), resultForm.get("field")); - for (const file of files) { - const inputFile = form.get(file.name) as File; - const resultFile = resultForm.get(file.name) as File; - assertEquals(inputFile.size, resultFile.size); - assertEquals(inputFile.name, resultFile.name); - assertEquals(file.expectedType || file.type, resultFile.type); - assertEquals( - new Uint8Array(await resultFile.arrayBuffer()), - file.content, - ); - } - }, -); +Deno.test("fetchInitFormDataBinaryFileBody", async function (): Promise { + // Some random bytes + // deno-fmt-ignore + const binaryFile = new Uint8Array([108,2,0,0,145,22,162,61,157,227,166,77,138,75,180,56,119,188,177,183]); + const response = await fetch("http://localhost:4545/echo_multipart_file", { + method: "POST", + body: binaryFile, + }); + const resultForm = await response.formData(); + const resultFile = resultForm.get("file") as File; -unitTest( - { - perms: { net: true }, - }, - async function fetchWithRedirection(): Promise { - const response = await fetch("http://localhost:4546/README.md"); - assertEquals(response.status, 200); - assertEquals(response.statusText, "OK"); - assertEquals(response.url, "http://localhost:4545/README.md"); - const body = await response.text(); - assert(body.includes("Deno")); - }, -); + assertEquals(resultFile.type, "application/octet-stream"); + assertEquals(resultFile.name, "file.bin"); + assertEquals(new Uint8Array(await resultFile.arrayBuffer()), binaryFile); +}); -unitTest( - { - perms: { net: true }, - }, - async function fetchWithRelativeRedirection(): Promise { - const response = await fetch( - "http://localhost:4545/cli/tests/001_hello.js", +Deno.test("fetchInitFormDataMultipleFilesBody", async function (): Promise< + void +> { + const files = [ + { + // deno-fmt-ignore + content: new Uint8Array([137,80,78,71,13,10,26,10, 137, 1, 25]), + type: "image/png", + name: "image", + fileName: "some-image.png", + }, + { + // deno-fmt-ignore + content: new Uint8Array([108,2,0,0,145,22,162,61,157,227,166,77,138,75,180,56,119,188,177,183]), + name: "file", + fileName: "file.bin", + expectedType: "application/octet-stream", + }, + { + content: new TextEncoder().encode("deno land"), + type: "text/plain", + name: "text", + fileName: "deno.txt", + }, + ]; + const form = new FormData(); + form.append("field", "value"); + for (const file of files) { + form.append( + file.name, + new Blob([file.content], { type: file.type }), + file.fileName, ); - assertEquals(response.status, 200); - assertEquals(response.statusText, "OK"); - const body = await response.text(); - assert(body.includes("Hello")); - }, -); + } + const response = await fetch("http://localhost:4545/echo_server", { + method: "POST", + body: form, + }); + const resultForm = await response.formData(); + assertEquals(form.get("field"), resultForm.get("field")); + for (const file of files) { + const inputFile = form.get(file.name) as File; + const resultFile = resultForm.get(file.name) as File; + assertEquals(inputFile.size, resultFile.size); + assertEquals(inputFile.name, resultFile.name); + assertEquals(file.expectedType || file.type, resultFile.type); + assertEquals( + new Uint8Array(await resultFile.arrayBuffer()), + file.content, + ); + } +}); -unitTest( - { - perms: { net: true }, - }, - async function fetchWithRelativeRedirectionUrl(): Promise { - const cases = [ - ["end", "http://localhost:4550/a/b/end"], - ["/end", "http://localhost:4550/end"], - ]; - for (const [loc, redUrl] of cases) { - const response = await fetch("http://localhost:4550/a/b/c", { - headers: new Headers([["x-location", loc]]), - }); - assertEquals(response.url, redUrl); - assertEquals(response.redirected, true); - assertEquals(response.status, 404); - assertEquals(await response.text(), ""); - } - }, -); +Deno.test("fetchWithRedirection", async function (): Promise { + const response = await fetch("http://localhost:4546/README.md"); + assertEquals(response.status, 200); + assertEquals(response.statusText, "OK"); + assertEquals(response.url, "http://localhost:4545/README.md"); + const body = await response.text(); + assert(body.includes("Deno")); +}); -unitTest( - { - perms: { net: true }, - }, - async function fetchWithInfRedirection(): Promise { - const response = await fetch("http://localhost:4549/cli/tests"); // will redirect to the same place - assertEquals(response.status, 0); // network error - assertEquals(response.type, "error"); - assertEquals(response.ok, false); - }, -); +Deno.test("fetchWithRelativeRedirection", async function (): Promise { + const response = await fetch( + "http://localhost:4545/cli/tests/001_hello.js", + ); + assertEquals(response.status, 200); + assertEquals(response.statusText, "OK"); + const body = await response.text(); + assert(body.includes("Hello")); +}); -unitTest( - { perms: { net: true } }, - async function fetchInitStringBody(): Promise { - const data = "Hello World"; - const response = await fetch("http://localhost:4545/echo_server", { - method: "POST", - body: data, +Deno.test("fetchWithRelativeRedirectionUrl", async function (): Promise { + const cases = [ + ["end", "http://localhost:4550/a/b/end"], + ["/end", "http://localhost:4550/end"], + ]; + for (const [loc, redUrl] of cases) { + const response = await fetch("http://localhost:4550/a/b/c", { + headers: new Headers([["x-location", loc]]), }); - const text = await response.text(); - assertEquals(text, data); - assert(response.headers.get("content-type")!.startsWith("text/plain")); - }, -); + assertEquals(response.url, redUrl); + assertEquals(response.redirected, true); + assertEquals(response.status, 404); + assertEquals(await response.text(), ""); + } +}); -unitTest( - { perms: { net: true } }, - async function fetchRequestInitStringBody(): Promise { - const data = "Hello World"; - const req = new Request("http://localhost:4545/echo_server", { - method: "POST", - body: data, - }); - const response = await fetch(req); - const text = await response.text(); - assertEquals(text, data); - }, -); +Deno.test("fetchWithInfRedirection", async function (): Promise { + const response = await fetch("http://localhost:4549/cli/tests"); // will redirect to the same place + assertEquals(response.status, 0); // network error + assertEquals(response.type, "error"); + assertEquals(response.ok, false); +}); -unitTest( - { perms: { net: true } }, - async function fetchInitTypedArrayBody(): Promise { - const data = "Hello World"; - const response = await fetch("http://localhost:4545/echo_server", { - method: "POST", - body: new TextEncoder().encode(data), - }); - const text = await response.text(); - assertEquals(text, data); - }, -); +Deno.test("fetchInitStringBody", async function (): Promise { + const data = "Hello World"; + const response = await fetch("http://localhost:4545/echo_server", { + method: "POST", + body: data, + }); + const text = await response.text(); + assertEquals(text, data); + assert(response.headers.get("content-type")!.startsWith("text/plain")); +}); -unitTest( - { perms: { net: true } }, - async function fetchInitArrayBufferBody(): Promise { - const data = "Hello World"; - const response = await fetch("http://localhost:4545/echo_server", { - method: "POST", - body: new TextEncoder().encode(data).buffer, - }); - const text = await response.text(); - assertEquals(text, data); - }, -); +Deno.test("fetchRequestInitStringBody", async function (): Promise { + const data = "Hello World"; + const req = new Request("http://localhost:4545/echo_server", { + method: "POST", + body: data, + }); + const response = await fetch(req); + const text = await response.text(); + assertEquals(text, data); +}); -unitTest( - { perms: { net: true } }, - async function fetchInitURLSearchParamsBody(): Promise { - const data = "param1=value1¶m2=value2"; - const params = new URLSearchParams(data); - const response = await fetch("http://localhost:4545/echo_server", { - method: "POST", - body: params, - }); - const text = await response.text(); - assertEquals(text, data); - assert( - response.headers - .get("content-type")! - .startsWith("application/x-www-form-urlencoded"), - ); - }, -); +Deno.test("fetchInitTypedArrayBody", async function (): Promise { + const data = "Hello World"; + const response = await fetch("http://localhost:4545/echo_server", { + method: "POST", + body: new TextEncoder().encode(data), + }); + const text = await response.text(); + assertEquals(text, data); +}); + +Deno.test("fetchInitArrayBufferBody", async function (): Promise { + const data = "Hello World"; + const response = await fetch("http://localhost:4545/echo_server", { + method: "POST", + body: new TextEncoder().encode(data).buffer, + }); + const text = await response.text(); + assertEquals(text, data); +}); -unitTest({ perms: { net: true } }, async function fetchInitBlobBody(): Promise< +Deno.test("fetchInitURLSearchParamsBody", async function (): Promise { + const data = "param1=value1¶m2=value2"; + const params = new URLSearchParams(data); + const response = await fetch("http://localhost:4545/echo_server", { + method: "POST", + body: params, + }); + const text = await response.text(); + assertEquals(text, data); + assert( + response.headers + .get("content-type")! + .startsWith("application/x-www-form-urlencoded"), + ); +}); + +Deno.test("fetchInitBlobBody", async function (): Promise< void > { const data = "const a = 1"; @@ -520,69 +447,62 @@ unitTest({ perms: { net: true } }, async function fetchInitBlobBody(): Promise< assert(response.headers.get("content-type")!.startsWith("text/javascript")); }); -unitTest( - { perms: { net: true } }, - async function fetchInitFormDataBody(): Promise { - const form = new FormData(); - form.append("field", "value"); - const response = await fetch("http://localhost:4545/echo_server", { - method: "POST", - body: form, - }); - const resultForm = await response.formData(); - assertEquals(form.get("field"), resultForm.get("field")); - }, -); +Deno.test("fetchInitFormDataBody", async function (): Promise { + const form = new FormData(); + form.append("field", "value"); + const response = await fetch("http://localhost:4545/echo_server", { + method: "POST", + body: form, + }); + const resultForm = await response.formData(); + assertEquals(form.get("field"), resultForm.get("field")); +}); -unitTest( - { perms: { net: true } }, - async function fetchInitFormDataBlobFilenameBody(): Promise { - const form = new FormData(); - form.append("field", "value"); - form.append("file", new Blob([new TextEncoder().encode("deno")])); - const response = await fetch("http://localhost:4545/echo_server", { - method: "POST", - body: form, - }); - const resultForm = await response.formData(); - assertEquals(form.get("field"), resultForm.get("field")); - const file = resultForm.get("file"); - assert(file instanceof File); - assertEquals(file.name, "blob"); - }, -); +Deno.test("fetchInitFormDataBlobFilenameBody", async function (): Promise< + void +> { + const form = new FormData(); + form.append("field", "value"); + form.append("file", new Blob([new TextEncoder().encode("deno")])); + const response = await fetch("http://localhost:4545/echo_server", { + method: "POST", + body: form, + }); + const resultForm = await response.formData(); + assertEquals(form.get("field"), resultForm.get("field")); + const file = resultForm.get("file"); + assert(file instanceof File); + assertEquals(file.name, "blob"); +}); -unitTest( - { perms: { net: true } }, - async function fetchInitFormDataTextFileBody(): Promise { - const fileContent = "deno land"; - const form = new FormData(); - form.append("field", "value"); - form.append( - "file", - new Blob([new TextEncoder().encode(fileContent)], { - type: "text/plain", - }), - "deno.txt", - ); - const response = await fetch("http://localhost:4545/echo_server", { - method: "POST", - body: form, - }); - const resultForm = await response.formData(); - assertEquals(form.get("field"), resultForm.get("field")); +Deno.test("fetchInitFormDataTextFileBody", async function (): Promise { + const fileContent = "deno land"; + const form = new FormData(); + form.append("field", "value"); + form.append( + "file", + new Blob([new TextEncoder().encode(fileContent)], { + type: "text/plain", + }), + "deno.txt", + ); + const response = await fetch("http://localhost:4545/echo_server", { + method: "POST", + body: form, + }); + const resultForm = await response.formData(); + assertEquals(form.get("field"), resultForm.get("field")); - const file = form.get("file") as File; - const resultFile = resultForm.get("file") as File; + const file = form.get("file") as File; + const resultFile = resultForm.get("file") as File; - assertEquals(file.size, resultFile.size); - assertEquals(file.name, resultFile.name); - assertEquals(file.type, resultFile.type); - assertEquals(await file.text(), await resultFile.text()); - }, -); + assertEquals(file.size, resultFile.size); + assertEquals(file.name, resultFile.name); + assertEquals(file.type, resultFile.type); + assertEquals(await file.text(), await resultFile.text()); +}); -unitTest({ perms: { net: true } }, async function fetchUserAgent(): Promise< +Deno.test("fetchUserAgent", async function (): Promise< void > { const data = "Hello World"; @@ -597,7 +517,7 @@ unitTest({ perms: { net: true } }, async function fetchUserAgent(): Promise< // TODO(ry) The following tests work but are flaky. There's a race condition // somewhere. Here is what one of these flaky failures looks like: // -// unitTest fetchPostBodyString_permW0N1E0R0 +// fetchPostBodyString_permW0N1E0R0 // assertEquals failed. actual = expected = POST /blah HTTP/1.1 // hello: World // foo: Bar @@ -640,165 +560,135 @@ function bufferServer(addr: string): Deno.Buffer { return buf; } -unitTest( - { - perms: { net: true }, - }, - async function fetchRequest(): Promise { - const addr = "127.0.0.1:4501"; - const buf = bufferServer(addr); - const response = await fetch(`http://${addr}/blah`, { - method: "POST", - headers: [ - ["Hello", "World"], - ["Foo", "Bar"], - ], - }); - await response.arrayBuffer(); - assertEquals(response.status, 404); - assertEquals(response.headers.get("Content-Length"), "2"); - - const actual = new TextDecoder().decode(buf.bytes()); - const expected = [ - "POST /blah HTTP/1.1\r\n", - "hello: World\r\n", - "foo: Bar\r\n", - "accept: */*\r\n", - `user-agent: Deno/${Deno.version.deno}\r\n`, - "accept-encoding: gzip, br\r\n", - `host: ${addr}\r\n\r\n`, - ].join(""); - assertEquals(actual, expected); - }, -); +Deno.test("fetchRequest", async function (): Promise { + const addr = "127.0.0.1:4501"; + const buf = bufferServer(addr); + const response = await fetch(`http://${addr}/blah`, { + method: "POST", + headers: [ + ["Hello", "World"], + ["Foo", "Bar"], + ], + }); + await response.arrayBuffer(); + assertEquals(response.status, 404); + assertEquals(response.headers.get("Content-Length"), "2"); + + const actual = new TextDecoder().decode(buf.bytes()); + const expected = [ + "POST /blah HTTP/1.1\r\n", + "hello: World\r\n", + "foo: Bar\r\n", + "accept: */*\r\n", + `user-agent: Deno/${Deno.version.deno}\r\n`, + "accept-encoding: gzip, br\r\n", + `host: ${addr}\r\n\r\n`, + ].join(""); + assertEquals(actual, expected); +}); -unitTest( - { - perms: { net: true }, - }, - async function fetchPostBodyString(): Promise { - const addr = "127.0.0.1:4502"; - const buf = bufferServer(addr); - const body = "hello world"; - const response = await fetch(`http://${addr}/blah`, { - method: "POST", - headers: [ - ["Hello", "World"], - ["Foo", "Bar"], - ], - body, - }); - await response.arrayBuffer(); - assertEquals(response.status, 404); - assertEquals(response.headers.get("Content-Length"), "2"); - - const actual = new TextDecoder().decode(buf.bytes()); - const expected = [ - "POST /blah HTTP/1.1\r\n", - "hello: World\r\n", - "foo: Bar\r\n", - "content-type: text/plain;charset=UTF-8\r\n", - "accept: */*\r\n", - `user-agent: Deno/${Deno.version.deno}\r\n`, - "accept-encoding: gzip, br\r\n", - `host: ${addr}\r\n`, - `content-length: ${body.length}\r\n\r\n`, - body, - ].join(""); - assertEquals(actual, expected); - }, -); +Deno.test("fetchPostBodyString", async function (): Promise { + const addr = "127.0.0.1:4502"; + const buf = bufferServer(addr); + const body = "hello world"; + const response = await fetch(`http://${addr}/blah`, { + method: "POST", + headers: [ + ["Hello", "World"], + ["Foo", "Bar"], + ], + body, + }); + await response.arrayBuffer(); + assertEquals(response.status, 404); + assertEquals(response.headers.get("Content-Length"), "2"); + + const actual = new TextDecoder().decode(buf.bytes()); + const expected = [ + "POST /blah HTTP/1.1\r\n", + "hello: World\r\n", + "foo: Bar\r\n", + "content-type: text/plain;charset=UTF-8\r\n", + "accept: */*\r\n", + `user-agent: Deno/${Deno.version.deno}\r\n`, + "accept-encoding: gzip, br\r\n", + `host: ${addr}\r\n`, + `content-length: ${body.length}\r\n\r\n`, + body, + ].join(""); + assertEquals(actual, expected); +}); -unitTest( - { - perms: { net: true }, - }, - async function fetchPostBodyTypedArray(): Promise { - const addr = "127.0.0.1:4503"; - const buf = bufferServer(addr); - const bodyStr = "hello world"; - const body = new TextEncoder().encode(bodyStr); - const response = await fetch(`http://${addr}/blah`, { - method: "POST", - headers: [ - ["Hello", "World"], - ["Foo", "Bar"], - ], - body, - }); - await response.arrayBuffer(); - assertEquals(response.status, 404); - assertEquals(response.headers.get("Content-Length"), "2"); - - const actual = new TextDecoder().decode(buf.bytes()); - const expected = [ - "POST /blah HTTP/1.1\r\n", - "hello: World\r\n", - "foo: Bar\r\n", - "accept: */*\r\n", - `user-agent: Deno/${Deno.version.deno}\r\n`, - "accept-encoding: gzip, br\r\n", - `host: ${addr}\r\n`, - `content-length: ${body.byteLength}\r\n\r\n`, - bodyStr, - ].join(""); - assertEquals(actual, expected); - }, -); +Deno.test("fetchPostBodyTypedArray", async function (): Promise { + const addr = "127.0.0.1:4503"; + const buf = bufferServer(addr); + const bodyStr = "hello world"; + const body = new TextEncoder().encode(bodyStr); + const response = await fetch(`http://${addr}/blah`, { + method: "POST", + headers: [ + ["Hello", "World"], + ["Foo", "Bar"], + ], + body, + }); + await response.arrayBuffer(); + assertEquals(response.status, 404); + assertEquals(response.headers.get("Content-Length"), "2"); + + const actual = new TextDecoder().decode(buf.bytes()); + const expected = [ + "POST /blah HTTP/1.1\r\n", + "hello: World\r\n", + "foo: Bar\r\n", + "accept: */*\r\n", + `user-agent: Deno/${Deno.version.deno}\r\n`, + "accept-encoding: gzip, br\r\n", + `host: ${addr}\r\n`, + `content-length: ${body.byteLength}\r\n\r\n`, + bodyStr, + ].join(""); + assertEquals(actual, expected); +}); -unitTest( - { - perms: { net: true }, - }, - async function fetchWithNonAsciiRedirection(): Promise { - const response = await fetch("http://localhost:4545/non_ascii_redirect", { - redirect: "manual", - }); - assertEquals(response.status, 301); - assertEquals(response.headers.get("location"), "/redirect®"); - await response.text(); - }, -); +Deno.test("fetchWithNonAsciiRedirection", async function (): Promise { + const response = await fetch("http://localhost:4545/non_ascii_redirect", { + redirect: "manual", + }); + assertEquals(response.status, 301); + assertEquals(response.headers.get("location"), "/redirect®"); + await response.text(); +}); -unitTest( - { - perms: { net: true }, - }, - async function fetchWithManualRedirection(): Promise { - const response = await fetch("http://localhost:4546/", { - redirect: "manual", - }); // will redirect to http://localhost:4545/ - assertEquals(response.status, 301); - assertEquals(response.url, "http://localhost:4546/"); - assertEquals(response.type, "default"); - assertEquals(response.headers.get("Location"), "http://localhost:4545/"); - }, -); +Deno.test("fetchWithManualRedirection", async function (): Promise { + const response = await fetch("http://localhost:4546/", { + redirect: "manual", + }); // will redirect to http://localhost:4545/ + assertEquals(response.status, 301); + assertEquals(response.url, "http://localhost:4546/"); + assertEquals(response.type, "default"); + assertEquals(response.headers.get("Location"), "http://localhost:4545/"); +}); -unitTest( - { - perms: { net: true }, - }, - async function fetchWithErrorRedirection(): Promise { - const response = await fetch("http://localhost:4546/", { - redirect: "error", - }); // will redirect to http://localhost:4545/ - assertEquals(response.status, 0); - assertEquals(response.statusText, ""); - assertEquals(response.url, ""); - assertEquals(response.type, "error"); - try { - await response.text(); - fail( - "Response.text() didn't throw on a filtered response without a body (type error)", - ); - } catch (e) { - return; - } - }, -); +Deno.test("fetchWithErrorRedirection", async function (): Promise { + const response = await fetch("http://localhost:4546/", { + redirect: "error", + }); // will redirect to http://localhost:4545/ + assertEquals(response.status, 0); + assertEquals(response.statusText, ""); + assertEquals(response.url, ""); + assertEquals(response.type, "error"); + try { + await response.text(); + fail( + "Response.text() didn't throw on a filtered response without a body (type error)", + ); + } catch (e) { + return; + } +}); -unitTest(function responseRedirect(): void { +Deno.test("responseRedirect", function (): void { const redir = Response.redirect("example.com/newLocation", 301); assertEquals(redir.status, 301); assertEquals(redir.statusText, ""); @@ -807,7 +697,7 @@ unitTest(function responseRedirect(): void { assertEquals(redir.type, "default"); }); -unitTest(async function responseWithoutBody(): Promise { +Deno.test("responseWithoutBody", async function (): Promise { const response = new Response(); assertEquals(await response.arrayBuffer(), new ArrayBuffer(0)); assertEquals(await response.blob(), new Blob([])); @@ -817,7 +707,7 @@ unitTest(async function responseWithoutBody(): Promise { }); }); -unitTest({ perms: { net: true } }, async function fetchBodyReadTwice(): Promise< +Deno.test("fetchBodyReadTwice", async function (): Promise< void > { const response = await fetch("http://localhost:4545/cli/tests/fixture.json"); @@ -840,98 +730,92 @@ unitTest({ perms: { net: true } }, async function fetchBodyReadTwice(): Promise< } }); -unitTest( - { perms: { net: true } }, - async function fetchBodyReaderAfterRead(): Promise { - const response = await fetch( - "http://localhost:4545/cli/tests/fixture.json", - ); - assert(response.body !== null); - const reader = await response.body.getReader(); - while (true) { - const { done, value } = await reader.read(); - if (done) break; - assert(value); - } +Deno.test("fetchBodyReaderAfterRead", async function (): Promise { + const response = await fetch( + "http://localhost:4545/cli/tests/fixture.json", + ); + assert(response.body !== null); + const reader = await response.body.getReader(); + while (true) { + const { done, value } = await reader.read(); + if (done) break; + assert(value); + } - try { - response.body.getReader(); - fail("The stream should've been locked."); - } catch { - // pass - } - }, -); + try { + response.body.getReader(); + fail("The stream should've been locked."); + } catch { + // pass + } +}); -unitTest( - { perms: { net: true } }, - async function fetchBodyReaderWithCancelAndNewReader(): Promise { - const data = "a".repeat(1 << 10); - const response = await fetch("http://localhost:4545/echo_server", { - method: "POST", - body: data, - }); - assert(response.body !== null); - const firstReader = await response.body.getReader(); +Deno.test("fetchBodyReaderWithCancelAndNewReader", async function (): Promise< + void +> { + const data = "a".repeat(1 << 10); + const response = await fetch("http://localhost:4545/echo_server", { + method: "POST", + body: data, + }); + assert(response.body !== null); + const firstReader = await response.body.getReader(); - // Acquire reader without reading & release - await firstReader.releaseLock(); + // Acquire reader without reading & release + await firstReader.releaseLock(); - const reader = await response.body.getReader(); + const reader = await response.body.getReader(); - let total = 0; - while (true) { - const { done, value } = await reader.read(); - if (done) break; - assert(value); - total += value.length; - } + let total = 0; + while (true) { + const { done, value } = await reader.read(); + if (done) break; + assert(value); + total += value.length; + } - assertEquals(total, data.length); - }, -); + assertEquals(total, data.length); +}); -unitTest( - { perms: { net: true } }, - async function fetchBodyReaderWithReadCancelAndNewReader(): Promise { - const data = "a".repeat(1 << 10); +Deno.test("fetchBodyReaderWithReadCancelAndNewReader", async function (): Promise< + void +> { + const data = "a".repeat(1 << 10); - const response = await fetch("http://localhost:4545/echo_server", { - method: "POST", - body: data, - }); - assert(response.body !== null); - const firstReader = await response.body.getReader(); - - // Do one single read with first reader - const { value: firstValue } = await firstReader.read(); - assert(firstValue); - await firstReader.releaseLock(); - - // Continue read with second reader - const reader = await response.body.getReader(); - let total = firstValue.length || 0; - while (true) { - const { done, value } = await reader.read(); - if (done) break; - assert(value); - total += value.length; - } - assertEquals(total, data.length); - }, -); + const response = await fetch("http://localhost:4545/echo_server", { + method: "POST", + body: data, + }); + assert(response.body !== null); + const firstReader = await response.body.getReader(); -unitTest( - { perms: { net: true } }, - async function fetchResourceCloseAfterStreamCancel(): Promise { - const res = await fetch("http://localhost:4545/cli/tests/fixture.json"); - assert(res.body !== null); + // Do one single read with first reader + const { value: firstValue } = await firstReader.read(); + assert(firstValue); + await firstReader.releaseLock(); - // After ReadableStream.cancel is called, resource handle must be closed - // The test should not fail with: Test case is leaking resources - await res.body.cancel(); - }, -); + // Continue read with second reader + const reader = await response.body.getReader(); + let total = firstValue.length || 0; + while (true) { + const { done, value } = await reader.read(); + if (done) break; + assert(value); + total += value.length; + } + assertEquals(total, data.length); +}); + +Deno.test("fetchResourceCloseAfterStreamCancel", async function (): Promise< + void +> { + const res = await fetch("http://localhost:4545/cli/tests/fixture.json"); + assert(res.body !== null); + + // After ReadableStream.cancel is called, resource handle must be closed + // The test should not fail with: Test case is leaking resources + await res.body.cancel(); +}); // FIXME(bartlomieju): for reasons unknown after working for // a few months without a problem; this test started failing @@ -939,44 +823,44 @@ unitTest( // TypeError: error sending request for url (http://localhost:4545/echo_server): // connection error: An established connection was aborted by // the software in your host machine. (os error 10053) -unitTest( - { perms: { net: true }, ignore: Deno.build.os == "windows" }, - async function fetchNullBodyStatus(): Promise { - const nullBodyStatus = [101, 204, 205, 304]; - - for (const status of nullBodyStatus) { - const headers = new Headers([["x-status", String(status)]]); - const res = await fetch("http://localhost:4545/echo_server", { - body: "deno", - method: "POST", - headers, - }); - assertEquals(res.body, null); - assertEquals(res.status, status); - } +Deno.test( + { + name: "fetchNullBodyStatus", + ignore: Deno.build.os == "windows", + async fn(): Promise { + const nullBodyStatus = [101, 204, 205, 304]; + + for (const status of nullBodyStatus) { + const headers = new Headers([["x-status", String(status)]]); + const res = await fetch("http://localhost:4545/echo_server", { + body: "deno", + method: "POST", + headers, + }); + assertEquals(res.body, null); + assertEquals(res.status, status); + } + }, }, ); -unitTest( - { perms: { net: true } }, - async function fetchResponseContentLength(): Promise { - const body = new Uint8Array(2 ** 16); - const headers = new Headers([["content-type", "application/octet-stream"]]); - const res = await fetch("http://localhost:4545/echo_server", { - body: body, - method: "POST", - headers, - }); - assertEquals(Number(res.headers.get("content-length")), body.byteLength); +Deno.test("fetchResponseContentLength", async function (): Promise { + const body = new Uint8Array(2 ** 16); + const headers = new Headers([["content-type", "application/octet-stream"]]); + const res = await fetch("http://localhost:4545/echo_server", { + body: body, + method: "POST", + headers, + }); + assertEquals(Number(res.headers.get("content-length")), body.byteLength); - const blob = await res.blob(); - // Make sure Body content-type is correctly set - assertEquals(blob.type, "application/octet-stream"); - assertEquals(blob.size, body.byteLength); - }, -); + const blob = await res.blob(); + // Make sure Body content-type is correctly set + assertEquals(blob.type, "application/octet-stream"); + assertEquals(blob.size, body.byteLength); +}); -unitTest(function fetchResponseConstructorNullBody(): void { +Deno.test("fetchResponseConstructorNullBody", function (): void { const nullBodyStatus = [204, 205, 304]; for (const status of nullBodyStatus) { @@ -993,7 +877,7 @@ unitTest(function fetchResponseConstructorNullBody(): void { } }); -unitTest(function fetchResponseConstructorInvalidStatus(): void { +Deno.test("fetchResponseConstructorInvalidStatus", function (): void { const invalidStatus = [101, 600, 199, null, "", NaN]; for (const status of invalidStatus) { @@ -1012,7 +896,7 @@ unitTest(function fetchResponseConstructorInvalidStatus(): void { } }); -unitTest(function fetchResponseEmptyConstructor(): void { +Deno.test("fetchResponseEmptyConstructor", function (): void { const response = new Response(); assertEquals(response.status, 200); assertEquals(response.body, null); @@ -1024,14 +908,12 @@ unitTest(function fetchResponseEmptyConstructor(): void { assertEquals([...response.headers], []); }); -unitTest( - { perms: { net: true } }, - async function fetchCustomHttpClientParamCertificateSuccess(): Promise< - void - > { - const client = Deno.createHttpClient( - { - caData: `-----BEGIN CERTIFICATE----- +Deno.test("fetchCustomHttpClientParamCertificateSuccess", async function (): Promise< + void +> { + const client = Deno.createHttpClient( + { + caData: `-----BEGIN CERTIFICATE----- MIIDIzCCAgugAwIBAgIJAMKPPW4tsOymMA0GCSqGSIb3DQEBCwUAMCcxCzAJBgNV BAYTAlVTMRgwFgYDVQQDDA9FeGFtcGxlLVJvb3QtQ0EwIBcNMTkxMDIxMTYyODIy WhgPMjExODA5MjcxNjI4MjJaMCcxCzAJBgNVBAYTAlVTMRgwFgYDVQQDDA9FeGFt @@ -1051,83 +933,84 @@ kyIWJwk2zJReKcJMgi1aIinDM9ao/dca1G99PHOw8dnr4oyoTiv8ao6PWiSRHHMi MNf4EgWfK+tZMnuqfpfO9740KzfcVoMNo4QJD4yn5YxroUOO/Azi -----END CERTIFICATE----- `, - }, - ); - const response = await fetch( - "https://localhost:5545/cli/tests/fixture.json", - { client }, - ); - const json = await response.json(); - assertEquals(json.name, "deno"); - client.close(); - }, -); + }, + ); + const response = await fetch( + "https://localhost:5545/cli/tests/fixture.json", + { client }, + ); + const json = await response.json(); + assertEquals(json.name, "deno"); + client.close(); +}); + +Deno.test("fetchCustomClientUserAgent", async function (): Promise< + void +> { + const data = "Hello World"; + const client = Deno.createHttpClient({}); + const response = await fetch("http://localhost:4545/echo_server", { + client, + method: "POST", + body: new TextEncoder().encode(data), + }); + assertEquals( + response.headers.get("user-agent"), + `Deno/${Deno.version.deno}`, + ); + await response.text(); + client.close(); +}); + +Deno.test("fetchPostBodyReadableStream", async function (): Promise { + const addr = "127.0.0.1:4502"; + const buf = bufferServer(addr); + const stream = new TransformStream(); + const writer = stream.writable.getWriter(); + // transformer writes don't resolve until they are read, so awaiting these + // will cause the transformer to hang, as the suspend the transformer, it + // is also illogical to await for the reads, as that is the whole point of + // streams is to have a "queue" which gets drained... + writer.write(new TextEncoder().encode("hello ")); + writer.write(new TextEncoder().encode("world")); + writer.close(); + const response = await fetch(`http://${addr}/blah`, { + method: "POST", + headers: [ + ["Hello", "World"], + ["Foo", "Bar"], + ], + body: stream.readable, + }); + await response.arrayBuffer(); + assertEquals(response.status, 404); + assertEquals(response.headers.get("Content-Length"), "2"); + + const actual = new TextDecoder().decode(buf.bytes()); + const expected = [ + "POST /blah HTTP/1.1\r\n", + "hello: World\r\n", + "foo: Bar\r\n", + "accept: */*\r\n", + `user-agent: Deno/${Deno.version.deno}\r\n`, + "accept-encoding: gzip, br\r\n", + `host: ${addr}\r\n`, + `transfer-encoding: chunked\r\n\r\n`, + "6\r\n", + "hello \r\n", + "5\r\n", + "world\r\n", + "0\r\n\r\n", + ].join(""); + assertEquals(actual, expected); +}); + +Deno.test("fetchPerm", async function (): Promise { + await Deno.permissions.revoke({ name: "net" }); + + await assertThrowsAsync(async () => { + await fetch("http://localhost:4545/cli/tests/fixture.json"); + }, Deno.errors.PermissionDenied); +}); -unitTest( - { perms: { net: true } }, - async function fetchCustomClientUserAgent(): Promise< - void - > { - const data = "Hello World"; - const client = Deno.createHttpClient({}); - const response = await fetch("http://localhost:4545/echo_server", { - client, - method: "POST", - body: new TextEncoder().encode(data), - }); - assertEquals( - response.headers.get("user-agent"), - `Deno/${Deno.version.deno}`, - ); - await response.text(); - client.close(); - }, -); -unitTest( - { - perms: { net: true }, - }, - async function fetchPostBodyReadableStream(): Promise { - const addr = "127.0.0.1:4502"; - const buf = bufferServer(addr); - const stream = new TransformStream(); - const writer = stream.writable.getWriter(); - // transformer writes don't resolve until they are read, so awaiting these - // will cause the transformer to hang, as the suspend the transformer, it - // is also illogical to await for the reads, as that is the whole point of - // streams is to have a "queue" which gets drained... - writer.write(new TextEncoder().encode("hello ")); - writer.write(new TextEncoder().encode("world")); - writer.close(); - const response = await fetch(`http://${addr}/blah`, { - method: "POST", - headers: [ - ["Hello", "World"], - ["Foo", "Bar"], - ], - body: stream.readable, - }); - await response.arrayBuffer(); - assertEquals(response.status, 404); - assertEquals(response.headers.get("Content-Length"), "2"); - - const actual = new TextDecoder().decode(buf.bytes()); - const expected = [ - "POST /blah HTTP/1.1\r\n", - "hello: World\r\n", - "foo: Bar\r\n", - "accept: */*\r\n", - `user-agent: Deno/${Deno.version.deno}\r\n`, - "accept-encoding: gzip, br\r\n", - `host: ${addr}\r\n`, - `transfer-encoding: chunked\r\n\r\n`, - "6\r\n", - "hello \r\n", - "5\r\n", - "world\r\n", - "0\r\n\r\n", - ].join(""); - assertEquals(actual, expected); - }, -); diff --git a/cli/tests/unit/file_test.ts b/cli/tests/unit/file_test.ts index eaafbae274b94b..7fba6ebc33f728 100644 --- a/cli/tests/unit/file_test.ts +++ b/cli/tests/unit/file_test.ts @@ -1,5 +1,5 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assert, assertEquals, unitTest } from "./test_util.ts"; +import { assert, assertEquals } from "./test_util.ts"; // deno-lint-ignore no-explicit-any function testFirstArgument(arg1: any[], expectedSize: number): void { @@ -10,47 +10,47 @@ function testFirstArgument(arg1: any[], expectedSize: number): void { assertEquals(file.type, ""); } -unitTest(function fileEmptyFileBits(): void { +Deno.test("fileEmptyFileBits", function (): void { testFirstArgument([], 0); }); -unitTest(function fileStringFileBits(): void { +Deno.test("fileStringFileBits", function (): void { testFirstArgument(["bits"], 4); }); -unitTest(function fileUnicodeStringFileBits(): void { +Deno.test("fileUnicodeStringFileBits", function (): void { testFirstArgument(["𝓽𝓮𝔁𝓽"], 16); }); -unitTest(function fileStringObjectFileBits(): void { +Deno.test("fileStringObjectFileBits", function (): void { testFirstArgument([new String("string object")], 13); }); -unitTest(function fileEmptyBlobFileBits(): void { +Deno.test("fileEmptyBlobFileBits", function (): void { testFirstArgument([new Blob()], 0); }); -unitTest(function fileBlobFileBits(): void { +Deno.test("fileBlobFileBits", function (): void { testFirstArgument([new Blob(["bits"])], 4); }); -unitTest(function fileEmptyFileFileBits(): void { +Deno.test("fileEmptyFileFileBits", function (): void { testFirstArgument([new File([], "world.txt")], 0); }); -unitTest(function fileFileFileBits(): void { +Deno.test("fileFileFileBits", function (): void { testFirstArgument([new File(["bits"], "world.txt")], 4); }); -unitTest(function fileArrayBufferFileBits(): void { +Deno.test("fileArrayBufferFileBits", function (): void { testFirstArgument([new ArrayBuffer(8)], 8); }); -unitTest(function fileTypedArrayFileBits(): void { +Deno.test("fileTypedArrayFileBits", function (): void { testFirstArgument([new Uint8Array([0x50, 0x41, 0x53, 0x53])], 4); }); -unitTest(function fileVariousFileBits(): void { +Deno.test("fileVariousFileBits", function (): void { testFirstArgument( [ "bits", @@ -64,15 +64,15 @@ unitTest(function fileVariousFileBits(): void { ); }); -unitTest(function fileNumberInFileBits(): void { +Deno.test("fileNumberInFileBits", function (): void { testFirstArgument([12], 2); }); -unitTest(function fileArrayInFileBits(): void { +Deno.test("fileArrayInFileBits", function (): void { testFirstArgument([[1, 2, 3]], 5); }); -unitTest(function fileObjectInFileBits(): void { +Deno.test("fileObjectInFileBits", function (): void { // "[object Object]" testFirstArgument([{}], 15); }); @@ -84,22 +84,22 @@ function testSecondArgument(arg2: any, expectedFileName: string): void { assertEquals(file.name, expectedFileName); } -unitTest(function fileUsingFileName(): void { +Deno.test("fileUsingFileName", function (): void { testSecondArgument("dummy", "dummy"); }); -unitTest(function fileUsingSpecialCharacterInFileName(): void { +Deno.test("fileUsingSpecialCharacterInFileName", function (): void { testSecondArgument("dummy/foo", "dummy:foo"); }); -unitTest(function fileUsingNullFileName(): void { +Deno.test("fileUsingNullFileName", function (): void { testSecondArgument(null, "null"); }); -unitTest(function fileUsingNumberFileName(): void { +Deno.test("fileUsingNumberFileName", function (): void { testSecondArgument(1, "1"); }); -unitTest(function fileUsingEmptyStringFileName(): void { +Deno.test("fileUsingEmptyStringFileName", function (): void { testSecondArgument("", ""); }); diff --git a/cli/tests/unit/filereader_test.ts b/cli/tests/unit/filereader_test.ts index 9bc8cda621acd9..22da2a74c7212a 100644 --- a/cli/tests/unit/filereader_test.ts +++ b/cli/tests/unit/filereader_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assertEquals, unitTest } from "./test_util.ts"; +import { assertEquals } from "./test_util.ts"; -unitTest(function fileReaderConstruct(): void { +Deno.test("fileReaderConstruct", function (): void { const fr = new FileReader(); assertEquals(fr.readyState, FileReader.EMPTY); @@ -10,7 +10,7 @@ unitTest(function fileReaderConstruct(): void { assertEquals(FileReader.DONE, 2); }); -unitTest(async function fileReaderLoadBlob(): Promise { +Deno.test("fileReaderLoadBlob", async function (): Promise { await new Promise((resolve) => { const fr = new FileReader(); const b1 = new Blob(["Hello World"]); @@ -77,7 +77,7 @@ unitTest(async function fileReaderLoadBlob(): Promise { }); }); -unitTest(async function fileReaderLoadBlobDouble(): Promise { +Deno.test("fileReaderLoadBlobDouble", async function (): Promise { // impl note from https://w3c.github.io/FileAPI/ // Event handler for the load or error events could have started another load, // if that happens the loadend event for the first load is not fired @@ -107,7 +107,7 @@ unitTest(async function fileReaderLoadBlobDouble(): Promise { }); }); -unitTest(async function fileReaderLoadBlobArrayBuffer(): Promise { +Deno.test("fileReaderLoadBlobArrayBuffer", async function (): Promise { await new Promise((resolve) => { const fr = new FileReader(); const b1 = new Blob(["Hello World"]); @@ -129,7 +129,7 @@ unitTest(async function fileReaderLoadBlobArrayBuffer(): Promise { }); }); -unitTest(async function fileReaderLoadBlobDataUrl(): Promise { +Deno.test("fileReaderLoadBlobDataUrl", async function (): Promise { await new Promise((resolve) => { const fr = new FileReader(); const b1 = new Blob(["Hello World"]); @@ -149,7 +149,7 @@ unitTest(async function fileReaderLoadBlobDataUrl(): Promise { }); }); -unitTest(async function fileReaderLoadBlobAbort(): Promise { +Deno.test("fileReaderLoadBlobAbort", async function (): Promise { await new Promise((resolve) => { const fr = new FileReader(); const b1 = new Blob(["Hello World"]); @@ -184,7 +184,7 @@ unitTest(async function fileReaderLoadBlobAbort(): Promise { }); }); -unitTest(async function fileReaderLoadBlobAbort(): Promise { +Deno.test("fileReaderLoadBlobAbort", async function (): Promise { await new Promise((resolve) => { const fr = new FileReader(); const b1 = new Blob(["Hello World"]); @@ -219,24 +219,24 @@ unitTest(async function fileReaderLoadBlobAbort(): Promise { }); }); -unitTest( - async function fileReaderDispatchesEventsInCorrectOrder(): Promise { - await new Promise((resolve) => { - const fr = new FileReader(); - const b1 = new Blob(["Hello World"]); - let out = ""; - fr.addEventListener("loadend", () => { - out += "1"; - }); - fr.onloadend = (ev): void => { - out += "2"; - }; - fr.addEventListener("loadend", () => { - assertEquals(out, "12"); - resolve(); - }); - - fr.readAsDataURL(b1); +Deno.test("fileReaderDispatchesEventsInCorrectOrder", async function (): Promise< + void +> { + await new Promise((resolve) => { + const fr = new FileReader(); + const b1 = new Blob(["Hello World"]); + let out = ""; + fr.addEventListener("loadend", () => { + out += "1"; }); - }, -); + fr.onloadend = (ev): void => { + out += "2"; + }; + fr.addEventListener("loadend", () => { + assertEquals(out, "12"); + resolve(); + }); + + fr.readAsDataURL(b1); + }); +}); diff --git a/cli/tests/unit/files_test.ts b/cli/tests/unit/files_test.ts index 152068004e0691..bc86831efe57cd 100644 --- a/cli/tests/unit/files_test.ts +++ b/cli/tests/unit/files_test.ts @@ -1,18 +1,13 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { - assert, - assertEquals, - assertThrowsAsync, - unitTest, -} from "./test_util.ts"; - -unitTest(function filesStdioFileDescriptors(): void { +import { assert, assertEquals, assertThrowsAsync } from "./test_util.ts"; + +Deno.test("filesStdioFileDescriptors", function (): void { assertEquals(Deno.stdin.rid, 0); assertEquals(Deno.stdout.rid, 1); assertEquals(Deno.stderr.rid, 2); }); -unitTest({ perms: { read: true } }, async function filesCopyToStdout(): Promise< +Deno.test("filesCopyToStdout", async function (): Promise< void > { const filename = "cli/tests/fixture.json"; @@ -24,7 +19,7 @@ unitTest({ perms: { read: true } }, async function filesCopyToStdout(): Promise< file.close(); }); -unitTest({ perms: { read: true } }, async function filesIter(): Promise { +Deno.test("filesIter", async function (): Promise { const filename = "cli/tests/hello.txt"; const file = await Deno.open(filename); @@ -37,26 +32,23 @@ unitTest({ perms: { read: true } }, async function filesIter(): Promise { file.close(); }); -unitTest( - { perms: { read: true } }, - async function filesIterCustomBufSize(): Promise { - const filename = "cli/tests/hello.txt"; - const file = await Deno.open(filename); - - let totalSize = 0; - let iterations = 0; - for await (const buf of Deno.iter(file, { bufSize: 6 })) { - totalSize += buf.byteLength; - iterations += 1; - } +Deno.test("filesIterCustomBufSize", async function (): Promise { + const filename = "cli/tests/hello.txt"; + const file = await Deno.open(filename); + + let totalSize = 0; + let iterations = 0; + for await (const buf of Deno.iter(file, { bufSize: 6 })) { + totalSize += buf.byteLength; + iterations += 1; + } - assertEquals(totalSize, 12); - assertEquals(iterations, 2); - file.close(); - }, -); + assertEquals(totalSize, 12); + assertEquals(iterations, 2); + file.close(); +}); -unitTest({ perms: { read: true } }, function filesIterSync(): void { +Deno.test("filesIterSync", function (): void { const filename = "cli/tests/hello.txt"; const file = Deno.openSync(filename); @@ -69,26 +61,23 @@ unitTest({ perms: { read: true } }, function filesIterSync(): void { file.close(); }); -unitTest( - { perms: { read: true } }, - function filesIterSyncCustomBufSize(): void { - const filename = "cli/tests/hello.txt"; - const file = Deno.openSync(filename); - - let totalSize = 0; - let iterations = 0; - for (const buf of Deno.iterSync(file, { bufSize: 6 })) { - totalSize += buf.byteLength; - iterations += 1; - } +Deno.test("filesIterSyncCustomBufSize", function (): void { + const filename = "cli/tests/hello.txt"; + const file = Deno.openSync(filename); - assertEquals(totalSize, 12); - assertEquals(iterations, 2); - file.close(); - }, -); + let totalSize = 0; + let iterations = 0; + for (const buf of Deno.iterSync(file, { bufSize: 6 })) { + totalSize += buf.byteLength; + iterations += 1; + } + + assertEquals(totalSize, 12); + assertEquals(iterations, 2); + file.close(); +}); -unitTest(async function readerIter(): Promise { +Deno.test("readerIter", async function (): Promise { // ref: https://github.com/denoland/deno/issues/2330 const encoder = new TextEncoder(); @@ -123,7 +112,7 @@ unitTest(async function readerIter(): Promise { assertEquals(totalSize, 12); }); -unitTest(async function readerIterSync(): Promise { +Deno.test("readerIterSync", async function (): Promise { // ref: https://github.com/denoland/deno/issues/2330 const encoder = new TextEncoder(); @@ -158,110 +147,73 @@ unitTest(async function readerIterSync(): Promise { assertEquals(totalSize, 12); }); -unitTest( - { - perms: { read: true, write: true }, - }, - function openSyncMode(): void { - const path = Deno.makeTempDirSync() + "/test_openSync.txt"; - const file = Deno.openSync(path, { - write: true, - createNew: true, - mode: 0o626, - }); - file.close(); - const pathInfo = Deno.statSync(path); - if (Deno.build.os !== "windows") { - assertEquals(pathInfo.mode! & 0o777, 0o626 & ~Deno.umask()); - } - }, -); - -unitTest( - { - perms: { read: true, write: true }, - }, - async function openMode(): Promise { - const path = (await Deno.makeTempDir()) + "/test_open.txt"; - const file = await Deno.open(path, { - write: true, - createNew: true, - mode: 0o626, - }); - file.close(); - const pathInfo = Deno.statSync(path); - if (Deno.build.os !== "windows") { - assertEquals(pathInfo.mode! & 0o777, 0o626 & ~Deno.umask()); - } - }, -); - -unitTest( - { - perms: { read: true, write: true }, - }, - function openSyncUrl(): void { - const tempDir = Deno.makeTempDirSync(); - const fileUrl = new URL( - `file://${ - Deno.build.os === "windows" ? "/" : "" - }${tempDir}/test_open.txt`, - ); - const file = Deno.openSync(fileUrl, { - write: true, - createNew: true, - mode: 0o626, - }); - file.close(); - const pathInfo = Deno.statSync(fileUrl); - if (Deno.build.os !== "windows") { - assertEquals(pathInfo.mode! & 0o777, 0o626 & ~Deno.umask()); - } +Deno.test("openSyncMode", function (): void { + const path = Deno.makeTempDirSync() + "/test_openSync.txt"; + const file = Deno.openSync(path, { + write: true, + createNew: true, + mode: 0o626, + }); + file.close(); + const pathInfo = Deno.statSync(path); + if (Deno.build.os !== "windows") { + assertEquals(pathInfo.mode! & 0o777, 0o626 & ~Deno.umask()); + } +}); - Deno.removeSync(tempDir, { recursive: true }); - }, -); - -unitTest( - { - perms: { read: true, write: true }, - }, - async function openUrl(): Promise { - const tempDir = await Deno.makeTempDir(); - const fileUrl = new URL( - `file://${ - Deno.build.os === "windows" ? "/" : "" - }${tempDir}/test_open.txt`, - ); - const file = await Deno.open(fileUrl, { - write: true, - createNew: true, - mode: 0o626, - }); - file.close(); - const pathInfo = Deno.statSync(fileUrl); - if (Deno.build.os !== "windows") { - assertEquals(pathInfo.mode! & 0o777, 0o626 & ~Deno.umask()); - } +Deno.test("openMode", async function (): Promise { + const path = (await Deno.makeTempDir()) + "/test_open.txt"; + const file = await Deno.open(path, { + write: true, + createNew: true, + mode: 0o626, + }); + file.close(); + const pathInfo = Deno.statSync(path); + if (Deno.build.os !== "windows") { + assertEquals(pathInfo.mode! & 0o777, 0o626 & ~Deno.umask()); + } +}); - Deno.removeSync(tempDir, { recursive: true }); - }, -); - -unitTest( - { perms: { write: false } }, - async function writePermFailure(): Promise { - const filename = "tests/hello.txt"; - const openOptions: Deno.OpenOptions[] = [{ write: true }, { append: true }]; - for (const options of openOptions) { - await assertThrowsAsync(async () => { - await Deno.open(filename, options); - }, Deno.errors.PermissionDenied); - } - }, -); +Deno.test("openSyncUrl", function (): void { + const tempDir = Deno.makeTempDirSync(); + const fileUrl = new URL( + `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test_open.txt`, + ); + const file = Deno.openSync(fileUrl, { + write: true, + createNew: true, + mode: 0o626, + }); + file.close(); + const pathInfo = Deno.statSync(fileUrl); + if (Deno.build.os !== "windows") { + assertEquals(pathInfo.mode! & 0o777, 0o626 & ~Deno.umask()); + } + + Deno.removeSync(tempDir, { recursive: true }); +}); + +Deno.test("openUrl", async function (): Promise { + const tempDir = await Deno.makeTempDir(); + const fileUrl = new URL( + `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test_open.txt`, + ); + const file = await Deno.open(fileUrl, { + write: true, + createNew: true, + mode: 0o626, + }); + file.close(); + const pathInfo = Deno.statSync(fileUrl); + if (Deno.build.os !== "windows") { + assertEquals(pathInfo.mode! & 0o777, 0o626 & ~Deno.umask()); + } + + Deno.removeSync(tempDir, { recursive: true }); +}); -unitTest(async function openOptions(): Promise { +Deno.test("openOptions", async function (): Promise { const filename = "cli/tests/fixture.json"; await assertThrowsAsync( async (): Promise => { @@ -296,242 +248,200 @@ unitTest(async function openOptions(): Promise { ); }); -unitTest({ perms: { read: false } }, async function readPermFailure(): Promise< - void -> { +Deno.test("writeNullBufferFailure", async function (): Promise { + const tempDir = Deno.makeTempDirSync(); + const filename = tempDir + "hello.txt"; + const w = { + write: true, + truncate: true, + create: true, + }; + const file = await Deno.open(filename, w); + + // writing null should throw an error + await assertThrowsAsync( + async (): Promise => { + // deno-lint-ignore no-explicit-any + await file.write(null as any); + }, + ); // TODO(bartlomieju): Check error kind when dispatch_minimal pipes errors properly + file.close(); + await Deno.remove(tempDir, { recursive: true }); +}); + +Deno.test("readNullBufferFailure", async function (): Promise { + const tempDir = Deno.makeTempDirSync(); + const filename = tempDir + "hello.txt"; + const file = await Deno.open(filename, { + read: true, + write: true, + truncate: true, + create: true, + }); + + // reading into an empty buffer should return 0 immediately + const bytesRead = await file.read(new Uint8Array(0)); + assert(bytesRead === 0); + + // reading file into null buffer should throw an error await assertThrowsAsync(async () => { - await Deno.open("package.json", { read: true }); - }, Deno.errors.PermissionDenied); + // deno-lint-ignore no-explicit-any + await file.read(null as any); + }, TypeError); + // TODO(bartlomieju): Check error kind when dispatch_minimal pipes errors properly + + file.close(); + await Deno.remove(tempDir, { recursive: true }); }); -unitTest( - { perms: { write: true } }, - async function writeNullBufferFailure(): Promise { - const tempDir = Deno.makeTempDirSync(); - const filename = tempDir + "hello.txt"; - const w = { - write: true, - truncate: true, - create: true, - }; - const file = await Deno.open(filename, w); - - // writing null should throw an error - await assertThrowsAsync( - async (): Promise => { - // deno-lint-ignore no-explicit-any - await file.write(null as any); - }, - ); // TODO(bartlomieju): Check error kind when dispatch_minimal pipes errors properly - file.close(); - await Deno.remove(tempDir, { recursive: true }); - }, -); - -unitTest( - { perms: { write: true, read: true } }, - async function readNullBufferFailure(): Promise { - const tempDir = Deno.makeTempDirSync(); - const filename = tempDir + "hello.txt"; - const file = await Deno.open(filename, { - read: true, - write: true, - truncate: true, - create: true, - }); - - // reading into an empty buffer should return 0 immediately - const bytesRead = await file.read(new Uint8Array(0)); - assert(bytesRead === 0); - - // reading file into null buffer should throw an error - await assertThrowsAsync(async () => { - // deno-lint-ignore no-explicit-any - await file.read(null as any); - }, TypeError); - // TODO(bartlomieju): Check error kind when dispatch_minimal pipes errors properly - - file.close(); - await Deno.remove(tempDir, { recursive: true }); - }, -); - -unitTest( - { perms: { write: false, read: false } }, - async function readWritePermFailure(): Promise { - const filename = "tests/hello.txt"; - await assertThrowsAsync(async () => { - await Deno.open(filename, { read: true }); - }, Deno.errors.PermissionDenied); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function createFile(): Promise { - const tempDir = await Deno.makeTempDir(); - const filename = tempDir + "/test.txt"; - const f = await Deno.create(filename); - let fileInfo = Deno.statSync(filename); - assert(fileInfo.isFile); - assert(fileInfo.size === 0); - const enc = new TextEncoder(); - const data = enc.encode("Hello"); - await f.write(data); - fileInfo = Deno.statSync(filename); - assert(fileInfo.size === 5); - f.close(); - - // TODO(bartlomieju): test different modes - await Deno.remove(tempDir, { recursive: true }); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function createFileWithUrl(): Promise { - const tempDir = await Deno.makeTempDir(); - const fileUrl = new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt`, - ); - const f = await Deno.create(fileUrl); - let fileInfo = Deno.statSync(fileUrl); - assert(fileInfo.isFile); - assert(fileInfo.size === 0); - const enc = new TextEncoder(); - const data = enc.encode("Hello"); - await f.write(data); - fileInfo = Deno.statSync(fileUrl); - assert(fileInfo.size === 5); - f.close(); - - await Deno.remove(tempDir, { recursive: true }); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function createSyncFile(): Promise { - const tempDir = await Deno.makeTempDir(); - const filename = tempDir + "/test.txt"; - const f = Deno.createSync(filename); - let fileInfo = Deno.statSync(filename); - assert(fileInfo.isFile); - assert(fileInfo.size === 0); - const enc = new TextEncoder(); - const data = enc.encode("Hello"); - await f.write(data); - fileInfo = Deno.statSync(filename); - assert(fileInfo.size === 5); - f.close(); - - // TODO(bartlomieju): test different modes - await Deno.remove(tempDir, { recursive: true }); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function createSyncFileWithUrl(): Promise { - const tempDir = await Deno.makeTempDir(); - const fileUrl = new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt`, - ); - const f = Deno.createSync(fileUrl); - let fileInfo = Deno.statSync(fileUrl); - assert(fileInfo.isFile); - assert(fileInfo.size === 0); - const enc = new TextEncoder(); - const data = enc.encode("Hello"); - await f.write(data); - fileInfo = Deno.statSync(fileUrl); - assert(fileInfo.size === 5); - f.close(); - - await Deno.remove(tempDir, { recursive: true }); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function openModeWrite(): Promise { - const tempDir = Deno.makeTempDirSync(); - const encoder = new TextEncoder(); - const filename = tempDir + "hello.txt"; - const data = encoder.encode("Hello world!\n"); - let file = await Deno.open(filename, { - create: true, - write: true, - truncate: true, - }); - // assert file was created - let fileInfo = Deno.statSync(filename); - assert(fileInfo.isFile); - assertEquals(fileInfo.size, 0); - // write some data - await file.write(data); - fileInfo = Deno.statSync(filename); - assertEquals(fileInfo.size, 13); - // assert we can't read from file - let thrown = false; - try { - const buf = new Uint8Array(20); - await file.read(buf); - } catch (e) { - thrown = true; - } finally { - assert(thrown, "'w' mode shouldn't allow to read file"); - } - file.close(); - // assert that existing file is truncated on open - file = await Deno.open(filename, { - write: true, - truncate: true, - }); - file.close(); - const fileSize = Deno.statSync(filename).size; - assertEquals(fileSize, 0); - await Deno.remove(tempDir, { recursive: true }); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function openModeWriteRead(): Promise { - const tempDir = Deno.makeTempDirSync(); - const encoder = new TextEncoder(); - const filename = tempDir + "hello.txt"; - const data = encoder.encode("Hello world!\n"); - - const file = await Deno.open(filename, { - write: true, - truncate: true, - create: true, - read: true, - }); - const seekPosition = 0; - // assert file was created - let fileInfo = Deno.statSync(filename); - assert(fileInfo.isFile); - assertEquals(fileInfo.size, 0); - // write some data - await file.write(data); - fileInfo = Deno.statSync(filename); - assertEquals(fileInfo.size, 13); +Deno.test("createFile", async function (): Promise { + const tempDir = await Deno.makeTempDir(); + const filename = tempDir + "/test.txt"; + const f = await Deno.create(filename); + let fileInfo = Deno.statSync(filename); + assert(fileInfo.isFile); + assert(fileInfo.size === 0); + const enc = new TextEncoder(); + const data = enc.encode("Hello"); + await f.write(data); + fileInfo = Deno.statSync(filename); + assert(fileInfo.size === 5); + f.close(); + + // TODO(bartlomieju): test different modes + await Deno.remove(tempDir, { recursive: true }); +}); + +Deno.test("createFileWithUrl", async function (): Promise { + const tempDir = await Deno.makeTempDir(); + const fileUrl = new URL( + `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt`, + ); + const f = await Deno.create(fileUrl); + let fileInfo = Deno.statSync(fileUrl); + assert(fileInfo.isFile); + assert(fileInfo.size === 0); + const enc = new TextEncoder(); + const data = enc.encode("Hello"); + await f.write(data); + fileInfo = Deno.statSync(fileUrl); + assert(fileInfo.size === 5); + f.close(); + + await Deno.remove(tempDir, { recursive: true }); +}); + +Deno.test("createSyncFile", async function (): Promise { + const tempDir = await Deno.makeTempDir(); + const filename = tempDir + "/test.txt"; + const f = Deno.createSync(filename); + let fileInfo = Deno.statSync(filename); + assert(fileInfo.isFile); + assert(fileInfo.size === 0); + const enc = new TextEncoder(); + const data = enc.encode("Hello"); + await f.write(data); + fileInfo = Deno.statSync(filename); + assert(fileInfo.size === 5); + f.close(); + + // TODO(bartlomieju): test different modes + await Deno.remove(tempDir, { recursive: true }); +}); + +Deno.test("createSyncFileWithUrl", async function (): Promise { + const tempDir = await Deno.makeTempDir(); + const fileUrl = new URL( + `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt`, + ); + const f = Deno.createSync(fileUrl); + let fileInfo = Deno.statSync(fileUrl); + assert(fileInfo.isFile); + assert(fileInfo.size === 0); + const enc = new TextEncoder(); + const data = enc.encode("Hello"); + await f.write(data); + fileInfo = Deno.statSync(fileUrl); + assert(fileInfo.size === 5); + f.close(); + + await Deno.remove(tempDir, { recursive: true }); +}); +Deno.test("openModeWrite", async function (): Promise { + const tempDir = Deno.makeTempDirSync(); + const encoder = new TextEncoder(); + const filename = tempDir + "hello.txt"; + const data = encoder.encode("Hello world!\n"); + let file = await Deno.open(filename, { + create: true, + write: true, + truncate: true, + }); + // assert file was created + let fileInfo = Deno.statSync(filename); + assert(fileInfo.isFile); + assertEquals(fileInfo.size, 0); + // write some data + await file.write(data); + fileInfo = Deno.statSync(filename); + assertEquals(fileInfo.size, 13); + // assert we can't read from file + let thrown = false; + try { const buf = new Uint8Array(20); - // seeking from beginning of a file - const cursorPosition = await file.seek(seekPosition, Deno.SeekMode.Start); - assertEquals(seekPosition, cursorPosition); - const result = await file.read(buf); - assertEquals(result, 13); - file.close(); - - await Deno.remove(tempDir, { recursive: true }); - }, -); - -unitTest({ perms: { read: true } }, async function seekStart(): Promise { + await file.read(buf); + } catch (e) { + thrown = true; + } finally { + assert(thrown, "'w' mode shouldn't allow to read file"); + } + file.close(); + // assert that existing file is truncated on open + file = await Deno.open(filename, { + write: true, + truncate: true, + }); + file.close(); + const fileSize = Deno.statSync(filename).size; + assertEquals(fileSize, 0); + await Deno.remove(tempDir, { recursive: true }); +}); + +Deno.test("openModeWriteRead", async function (): Promise { + const tempDir = Deno.makeTempDirSync(); + const encoder = new TextEncoder(); + const filename = tempDir + "hello.txt"; + const data = encoder.encode("Hello world!\n"); + + const file = await Deno.open(filename, { + write: true, + truncate: true, + create: true, + read: true, + }); + const seekPosition = 0; + // assert file was created + let fileInfo = Deno.statSync(filename); + assert(fileInfo.isFile); + assertEquals(fileInfo.size, 0); + // write some data + await file.write(data); + fileInfo = Deno.statSync(filename); + assertEquals(fileInfo.size, 13); + + const buf = new Uint8Array(20); + // seeking from beginning of a file + const cursorPosition = await file.seek(seekPosition, Deno.SeekMode.Start); + assertEquals(seekPosition, cursorPosition); + const result = await file.read(buf); + assertEquals(result, 13); + file.close(); + + await Deno.remove(tempDir, { recursive: true }); +}); + +Deno.test("seekStart", async function (): Promise { const filename = "cli/tests/hello.txt"; const file = await Deno.open(filename); const seekPosition = 6; @@ -548,7 +458,7 @@ unitTest({ perms: { read: true } }, async function seekStart(): Promise { file.close(); }); -unitTest({ perms: { read: true } }, function seekSyncStart(): void { +Deno.test("seekSyncStart", function (): void { const filename = "cli/tests/hello.txt"; const file = Deno.openSync(filename); const seekPosition = 6; @@ -565,7 +475,7 @@ unitTest({ perms: { read: true } }, function seekSyncStart(): void { file.close(); }); -unitTest({ perms: { read: true } }, async function seekCurrent(): Promise< +Deno.test("seekCurrent", async function (): Promise< void > { const filename = "cli/tests/hello.txt"; @@ -584,7 +494,7 @@ unitTest({ perms: { read: true } }, async function seekCurrent(): Promise< file.close(); }); -unitTest({ perms: { read: true } }, function seekSyncCurrent(): void { +Deno.test("seekSyncCurrent", function (): void { const filename = "cli/tests/hello.txt"; const file = Deno.openSync(filename); // Deliberately move 1 step forward @@ -601,7 +511,7 @@ unitTest({ perms: { read: true } }, function seekSyncCurrent(): void { file.close(); }); -unitTest({ perms: { read: true } }, async function seekEnd(): Promise { +Deno.test("seekEnd", async function (): Promise { const filename = "cli/tests/hello.txt"; const file = await Deno.open(filename); const seekPosition = -6; @@ -615,7 +525,7 @@ unitTest({ perms: { read: true } }, async function seekEnd(): Promise { file.close(); }); -unitTest({ perms: { read: true } }, function seekSyncEnd(): void { +Deno.test("seekSyncEnd", function (): void { const filename = "cli/tests/hello.txt"; const file = Deno.openSync(filename); const seekPosition = -6; @@ -629,7 +539,7 @@ unitTest({ perms: { read: true } }, function seekSyncEnd(): void { file.close(); }); -unitTest({ perms: { read: true } }, async function seekMode(): Promise { +Deno.test("seekMode", async function (): Promise { const filename = "cli/tests/hello.txt"; const file = await Deno.open(filename); await assertThrowsAsync( @@ -647,3 +557,37 @@ unitTest({ perms: { read: true } }, async function seekMode(): Promise { assertEquals(new TextDecoder().decode(buf), "H"); file.close(); }); + +Deno.test("readPermFailure", async function (): Promise< + void +> { + await Deno.permissions.revoke({ name: "read" }); + + await assertThrowsAsync(async () => { + await Deno.open("package.json", { read: true }); + }, Deno.errors.PermissionDenied); +}); + +Deno.test("writePermFailure", async function (): Promise { + await Deno.permissions.revoke({ name: "write" }); + + const filename = "tests/hello.txt"; + const openOptions: Deno.OpenOptions[] = [{ write: true }, { append: true }]; + for (const options of openOptions) { + await assertThrowsAsync(async () => { + await Deno.open(filename, options); + }, Deno.errors.PermissionDenied); + } +}); + +Deno.test("readWritePermFailure", async function (): Promise { + await Deno.permissions.revoke({ name: "read" }); + await Deno.permissions.revoke({ name: "write" }); + + const filename = "tests/hello.txt"; + await assertThrowsAsync(async () => { + await Deno.open(filename, { read: true }); + }, Deno.errors.PermissionDenied); +}); + + diff --git a/cli/tests/unit/form_data_test.ts b/cli/tests/unit/form_data_test.ts index 1a948631de3456..2a4b7f1f926433 100644 --- a/cli/tests/unit/form_data_test.ts +++ b/cli/tests/unit/form_data_test.ts @@ -1,22 +1,17 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { - assert, - assertEquals, - assertStringIncludes, - unitTest, -} from "./test_util.ts"; - -unitTest(function formDataHasCorrectNameProp(): void { +import { assert, assertEquals, assertStringIncludes } from "./test_util.ts"; + +Deno.test("formDataHasCorrectNameProp", function (): void { assertEquals(FormData.name, "FormData"); }); -unitTest(function formDataParamsAppendSuccess(): void { +Deno.test("formDataParamsAppendSuccess", function (): void { const formData = new FormData(); formData.append("a", "true"); assertEquals(formData.get("a"), "true"); }); -unitTest(function formDataParamsDeleteSuccess(): void { +Deno.test("formDataParamsDeleteSuccess", function (): void { const formData = new FormData(); formData.append("a", "true"); formData.append("b", "false"); @@ -26,7 +21,7 @@ unitTest(function formDataParamsDeleteSuccess(): void { assertEquals(formData.get("b"), null); }); -unitTest(function formDataParamsGetAllSuccess(): void { +Deno.test("formDataParamsGetAllSuccess", function (): void { const formData = new FormData(); formData.append("a", "true"); formData.append("b", "false"); @@ -36,7 +31,7 @@ unitTest(function formDataParamsGetAllSuccess(): void { assertEquals(formData.getAll("c"), []); }); -unitTest(function formDataParamsGetSuccess(): void { +Deno.test("formDataParamsGetSuccess", function (): void { const formData = new FormData(); formData.append("a", "true"); formData.append("b", "false"); @@ -52,7 +47,7 @@ unitTest(function formDataParamsGetSuccess(): void { assertEquals(formData.get("e"), "null"); }); -unitTest(function formDataParamsHasSuccess(): void { +Deno.test("formDataParamsHasSuccess", function (): void { const formData = new FormData(); formData.append("a", "true"); formData.append("b", "false"); @@ -61,7 +56,7 @@ unitTest(function formDataParamsHasSuccess(): void { assert(!formData.has("c")); }); -unitTest(function formDataParamsSetSuccess(): void { +Deno.test("formDataParamsSetSuccess", function (): void { const formData = new FormData(); formData.append("a", "true"); formData.append("b", "false"); @@ -78,7 +73,7 @@ unitTest(function formDataParamsSetSuccess(): void { assertEquals(formData.get("e"), "null"); }); -unitTest(function fromDataUseFile(): void { +Deno.test("fromDataUseFile", function (): void { const formData = new FormData(); const file = new File(["foo"], "bar", { type: "text/plain", @@ -87,7 +82,7 @@ unitTest(function fromDataUseFile(): void { assertEquals(formData.get("file"), file); }); -unitTest(function formDataSetEmptyBlobSuccess(): void { +Deno.test("formDataSetEmptyBlobSuccess", function (): void { const formData = new FormData(); formData.set("a", new Blob([]), "blank.txt"); formData.get("a"); @@ -99,7 +94,7 @@ unitTest(function formDataSetEmptyBlobSuccess(): void { */ }); -unitTest(function formDataBlobFilename(): void { +Deno.test("formDataBlobFilename", function (): void { const formData = new FormData(); const content = new TextEncoder().encode("deno"); formData.set("a", new Blob([content])); @@ -108,7 +103,7 @@ unitTest(function formDataBlobFilename(): void { assertEquals(file.name, "blob"); }); -unitTest(function formDataParamsForEachSuccess(): void { +Deno.test("formDataParamsForEachSuccess", function (): void { const init = [ ["a", "54"], ["b", "true"], @@ -127,7 +122,7 @@ unitTest(function formDataParamsForEachSuccess(): void { assertEquals(callNum, init.length); }); -unitTest(function formDataParamsArgumentsCheck(): void { +Deno.test("formDataParamsArgumentsCheck", function (): void { const methodRequireOneParam = [ "delete", "getAll", @@ -206,7 +201,7 @@ unitTest(function formDataParamsArgumentsCheck(): void { }); }); -unitTest(function toStringShouldBeWebCompatibility(): void { +Deno.test("toStringShouldBeWebCompatibility", function (): void { const formData = new FormData(); assertEquals(formData.toString(), "[object FormData]"); }); diff --git a/cli/tests/unit/format_error_test.ts b/cli/tests/unit/format_error_test.ts index 7d82499b770c49..d86f2cef6a4e53 100644 --- a/cli/tests/unit/format_error_test.ts +++ b/cli/tests/unit/format_error_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assert, unitTest } from "./test_util.ts"; +import { assert } from "./test_util.ts"; -unitTest(function formatDiagnosticBasic() { +Deno.test("formatDiagnosticBasic", function () { const fixture: Deno.Diagnostic[] = [ { start: { @@ -25,7 +25,7 @@ unitTest(function formatDiagnosticBasic() { assert(out.includes("test.ts")); }); -unitTest(function formatDiagnosticError() { +Deno.test("formatDiagnosticError", function () { let thrown = false; // deno-lint-ignore no-explicit-any const bad = ([{ hello: 123 }] as any) as Deno.Diagnostic[]; diff --git a/cli/tests/unit/fs_events_test.ts b/cli/tests/unit/fs_events_test.ts index 0b30a070d5a192..6b9f78c54a664a 100644 --- a/cli/tests/unit/fs_events_test.ts +++ b/cli/tests/unit/fs_events_test.ts @@ -1,15 +1,9 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. -import { assert, assertEquals, assertThrows, unitTest } from "./test_util.ts"; +import { assert, assertEquals, assertThrows } from "./test_util.ts"; // TODO(ry) Add more tests to specify format. -unitTest({ perms: { read: false } }, function watchFsPermissions() { - assertThrows(() => { - Deno.watchFs("."); - }, Deno.errors.PermissionDenied); -}); - -unitTest({ perms: { read: true } }, function watchFsInvalidPath() { +Deno.test("watchFsInvalidPath", function () { if (Deno.build.os === "windows") { assertThrows( () => { @@ -36,45 +30,49 @@ async function getTwoEvents( return events; } -unitTest( - { perms: { read: true, write: true } }, - async function watchFsBasic(): Promise { - const testDir = await Deno.makeTempDir(); - const iter = Deno.watchFs(testDir); +Deno.test("watchFsBasic", async function (): Promise { + const testDir = await Deno.makeTempDir(); + const iter = Deno.watchFs(testDir); + + // Asynchornously capture two fs events. + const eventsPromise = getTwoEvents(iter); - // Asynchornously capture two fs events. - const eventsPromise = getTwoEvents(iter); + // Make some random file system activity. + const file1 = testDir + "/file1.txt"; + const file2 = testDir + "/file2.txt"; + Deno.writeFileSync(file1, new Uint8Array([0, 1, 2])); + Deno.writeFileSync(file2, new Uint8Array([0, 1, 2])); + + // We should have gotten two fs events. + const events = await eventsPromise; + assert(events.length >= 2); + assert(events[0].kind == "create"); + assert(events[0].paths[0].includes(testDir)); + assert(events[1].kind == "create" || events[1].kind == "modify"); + assert(events[1].paths[0].includes(testDir)); +}); - // Make some random file system activity. - const file1 = testDir + "/file1.txt"; - const file2 = testDir + "/file2.txt"; - Deno.writeFileSync(file1, new Uint8Array([0, 1, 2])); - Deno.writeFileSync(file2, new Uint8Array([0, 1, 2])); +Deno.test("watchFsReturn", async function (): Promise { + const testDir = await Deno.makeTempDir(); + const iter = Deno.watchFs(testDir); - // We should have gotten two fs events. - const events = await eventsPromise; - assert(events.length >= 2); - assert(events[0].kind == "create"); - assert(events[0].paths[0].includes(testDir)); - assert(events[1].kind == "create" || events[1].kind == "modify"); - assert(events[1].paths[0].includes(testDir)); - }, -); + // Asynchronously loop events. + const eventsPromise = getTwoEvents(iter); -unitTest( - { perms: { read: true, write: true } }, - async function watchFsReturn(): Promise { - const testDir = await Deno.makeTempDir(); - const iter = Deno.watchFs(testDir); + // Close the watcher. + await iter.return!(); - // Asynchronously loop events. - const eventsPromise = getTwoEvents(iter); + // Expect zero events. + const events = await eventsPromise; + assertEquals(events, []); +}); + +Deno.test("watchFsPermissions", async function (): Promise { + await Deno.permissions.revoke({ name: "read" }); + + assertThrows(() => { + Deno.watchFs("."); + }, Deno.errors.PermissionDenied); +}); - // Close the watcher. - await iter.return!(); - // Expect zero events. - const events = await eventsPromise; - assertEquals(events, []); - }, -); diff --git a/cli/tests/unit/get_random_values_test.ts b/cli/tests/unit/get_random_values_test.ts index 3f9f311f68a83d..b8093fb082602e 100644 --- a/cli/tests/unit/get_random_values_test.ts +++ b/cli/tests/unit/get_random_values_test.ts @@ -1,49 +1,49 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assertNotEquals, assertStrictEquals, unitTest } from "./test_util.ts"; +import { assertNotEquals, assertStrictEquals } from "./test_util.ts"; -unitTest(function getRandomValuesInt8Array(): void { +Deno.test("getRandomValuesInt8Array", function (): void { const arr = new Int8Array(32); crypto.getRandomValues(arr); assertNotEquals(arr, new Int8Array(32)); }); -unitTest(function getRandomValuesUint8Array(): void { +Deno.test("getRandomValuesUint8Array", function (): void { const arr = new Uint8Array(32); crypto.getRandomValues(arr); assertNotEquals(arr, new Uint8Array(32)); }); -unitTest(function getRandomValuesUint8ClampedArray(): void { +Deno.test("getRandomValuesUint8ClampedArray", function (): void { const arr = new Uint8ClampedArray(32); crypto.getRandomValues(arr); assertNotEquals(arr, new Uint8ClampedArray(32)); }); -unitTest(function getRandomValuesInt16Array(): void { +Deno.test("getRandomValuesInt16Array", function (): void { const arr = new Int16Array(4); crypto.getRandomValues(arr); assertNotEquals(arr, new Int16Array(4)); }); -unitTest(function getRandomValuesUint16Array(): void { +Deno.test("getRandomValuesUint16Array", function (): void { const arr = new Uint16Array(4); crypto.getRandomValues(arr); assertNotEquals(arr, new Uint16Array(4)); }); -unitTest(function getRandomValuesInt32Array(): void { +Deno.test("getRandomValuesInt32Array", function (): void { const arr = new Int32Array(8); crypto.getRandomValues(arr); assertNotEquals(arr, new Int32Array(8)); }); -unitTest(function getRandomValuesUint32Array(): void { +Deno.test("getRandomValuesUint32Array", function (): void { const arr = new Uint32Array(8); crypto.getRandomValues(arr); assertNotEquals(arr, new Uint32Array(8)); }); -unitTest(function getRandomValuesReturnValue(): void { +Deno.test("getRandomValuesReturnValue", function (): void { const arr = new Uint32Array(8); const rtn = crypto.getRandomValues(arr); assertNotEquals(arr, new Uint32Array(8)); diff --git a/cli/tests/unit/globals_test.ts b/cli/tests/unit/globals_test.ts index ce43fddf197378..f8de9a75906ed9 100644 --- a/cli/tests/unit/globals_test.ts +++ b/cli/tests/unit/globals_test.ts @@ -1,72 +1,72 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assert, unitTest } from "./test_util.ts"; +import { assert } from "./test_util.ts"; -unitTest(function globalThisExists(): void { +Deno.test("globalThisExists", function (): void { assert(globalThis != null); }); -unitTest(function noInternalGlobals(): void { +Deno.test("noInternalGlobals", function (): void { // globalThis.__bootstrap should not be there. for (const key of Object.keys(globalThis)) { assert(!key.startsWith("_")); } }); -unitTest(function windowExists(): void { +Deno.test("windowExists", function (): void { assert(window != null); }); -unitTest(function selfExists(): void { +Deno.test("selfExists", function (): void { assert(self != null); }); -unitTest(function windowWindowExists(): void { +Deno.test("windowWindowExists", function (): void { assert(window.window === window); }); -unitTest(function windowSelfExists(): void { +Deno.test("windowSelfExists", function (): void { assert(window.self === window); }); -unitTest(function globalThisEqualsWindow(): void { +Deno.test("globalThisEqualsWindow", function (): void { assert(globalThis === window); }); -unitTest(function globalThisEqualsSelf(): void { +Deno.test("globalThisEqualsSelf", function (): void { assert(globalThis === self); }); -unitTest(function globalThisInstanceofWindow(): void { +Deno.test("globalThisInstanceofWindow", function (): void { assert(globalThis instanceof Window); }); -unitTest(function globalThisConstructorLength(): void { +Deno.test("globalThisConstructorLength", function (): void { assert(globalThis.constructor.length === 0); }); -unitTest(function globalThisInstanceofEventTarget(): void { +Deno.test("globalThisInstanceofEventTarget", function (): void { assert(globalThis instanceof EventTarget); }); -unitTest(function navigatorInstanceofNavigator(): void { +Deno.test("navigatorInstanceofNavigator", function (): void { // TODO(nayeemrmn): Add `Navigator` to deno_lint globals. // deno-lint-ignore no-undef assert(navigator instanceof Navigator); }); -unitTest(function DenoNamespaceExists(): void { +Deno.test("DenoNamespaceExists", function (): void { assert(Deno != null); }); -unitTest(function DenoNamespaceEqualsWindowDeno(): void { +Deno.test("DenoNamespaceEqualsWindowDeno", function (): void { assert(Deno === window.Deno); }); -unitTest(function DenoNamespaceIsFrozen(): void { +Deno.test("DenoNamespaceIsFrozen", function (): void { assert(Object.isFrozen(Deno)); }); -unitTest(function webAssemblyExists(): void { +Deno.test("webAssemblyExists", function (): void { assert(typeof WebAssembly.compile === "function"); }); @@ -78,7 +78,7 @@ declare global { } } -unitTest(function DenoNamespaceImmutable(): void { +Deno.test("DenoNamespaceImmutable", function (): void { const denoCopy = window.Deno; try { // deno-lint-ignore no-explicit-any @@ -133,7 +133,7 @@ unitTest(function DenoNamespaceImmutable(): void { assert(print === Deno.core.print); }); -unitTest(async function windowQueueMicrotask(): Promise { +Deno.test("windowQueueMicrotask", async function (): Promise { let resolve1: () => void | undefined; let resolve2: () => void | undefined; let microtaskDone = false; diff --git a/cli/tests/unit/headers_test.ts b/cli/tests/unit/headers_test.ts index 7f19cec1b637d3..ca4ee754653856 100644 --- a/cli/tests/unit/headers_test.ts +++ b/cli/tests/unit/headers_test.ts @@ -1,23 +1,18 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { - assert, - assertEquals, - assertStringIncludes, - unitTest, -} from "./test_util.ts"; +import { assert, assertEquals, assertStringIncludes } from "./test_util.ts"; const { inspectArgs, // @ts-expect-error TypeScript (as of 3.7) does not support indexing namespaces by symbol } = Deno[Deno.internal]; -unitTest(function headersHasCorrectNameProp(): void { +Deno.test("headersHasCorrectNameProp", function (): void { assertEquals(Headers.name, "Headers"); }); // Logic heavily copied from web-platform-tests, make // sure pass mostly header basic test // ref: https://github.com/web-platform-tests/wpt/blob/7c50c216081d6ea3c9afe553ee7b64534020a1b2/fetch/api/headers/headers-basic.html -unitTest(function newHeaderTest(): void { +Deno.test("newHeaderTest", function (): void { new Headers(); new Headers(undefined); new Headers({}); @@ -46,7 +41,7 @@ for (const name in headerDict) { headerSeq.push([name, headerDict[name]]); } -unitTest(function newHeaderWithSequence(): void { +Deno.test("newHeaderWithSequence", function (): void { const headers = new Headers(headerSeq); for (const name in headerDict) { assertEquals(headers.get(name), String(headerDict[name])); @@ -54,14 +49,14 @@ unitTest(function newHeaderWithSequence(): void { assertEquals(headers.get("length"), null); }); -unitTest(function newHeaderWithRecord(): void { +Deno.test("newHeaderWithRecord", function (): void { const headers = new Headers(headerDict); for (const name in headerDict) { assertEquals(headers.get(name), String(headerDict[name])); } }); -unitTest(function newHeaderWithHeadersInstance(): void { +Deno.test("newHeaderWithHeadersInstance", function (): void { const headers = new Headers(headerDict); const headers2 = new Headers(headers); for (const name in headerDict) { @@ -69,7 +64,7 @@ unitTest(function newHeaderWithHeadersInstance(): void { } }); -unitTest(function headerAppendSuccess(): void { +Deno.test("headerAppendSuccess", function (): void { const headers = new Headers(); for (const name in headerDict) { headers.append(name, headerDict[name]); @@ -77,7 +72,7 @@ unitTest(function headerAppendSuccess(): void { } }); -unitTest(function headerSetSuccess(): void { +Deno.test("headerSetSuccess", function (): void { const headers = new Headers(); for (const name in headerDict) { headers.set(name, headerDict[name]); @@ -85,7 +80,7 @@ unitTest(function headerSetSuccess(): void { } }); -unitTest(function headerHasSuccess(): void { +Deno.test("headerHasSuccess", function (): void { const headers = new Headers(headerDict); for (const name in headerDict) { assert(headers.has(name), "headers has name " + name); @@ -96,7 +91,7 @@ unitTest(function headerHasSuccess(): void { } }); -unitTest(function headerDeleteSuccess(): void { +Deno.test("headerDeleteSuccess", function (): void { const headers = new Headers(headerDict); for (const name in headerDict) { assert(headers.has(name), "headers have a header: " + name); @@ -105,7 +100,7 @@ unitTest(function headerDeleteSuccess(): void { } }); -unitTest(function headerGetSuccess(): void { +Deno.test("headerGetSuccess", function (): void { const headers = new Headers(headerDict); for (const name in headerDict) { assertEquals(headers.get(name), String(headerDict[name])); @@ -113,7 +108,7 @@ unitTest(function headerGetSuccess(): void { } }); -unitTest(function headerEntriesSuccess(): void { +Deno.test("headerEntriesSuccess", function (): void { const headers = new Headers(headerDict); const iterators = headers.entries(); for (const it of iterators) { @@ -124,7 +119,7 @@ unitTest(function headerEntriesSuccess(): void { } }); -unitTest(function headerKeysSuccess(): void { +Deno.test("headerKeysSuccess", function (): void { const headers = new Headers(headerDict); const iterators = headers.keys(); for (const it of iterators) { @@ -132,7 +127,7 @@ unitTest(function headerKeysSuccess(): void { } }); -unitTest(function headerValuesSuccess(): void { +Deno.test("headerValuesSuccess", function (): void { const headers = new Headers(headerDict); const iterators = headers.values(); const entries = headers.entries(); @@ -154,7 +149,7 @@ const headerEntriesDict: Record = { "Content-Types": "value6", }; -unitTest(function headerForEachSuccess(): void { +Deno.test("headerForEachSuccess", function (): void { const headers = new Headers(headerEntriesDict); const keys = Object.keys(headerEntriesDict); keys.forEach((key): void => { @@ -171,7 +166,7 @@ unitTest(function headerForEachSuccess(): void { assertEquals(callNum, keys.length); }); -unitTest(function headerSymbolIteratorSuccess(): void { +Deno.test("headerSymbolIteratorSuccess", function (): void { assert(Symbol.iterator in Headers.prototype); const headers = new Headers(headerEntriesDict); for (const header of headers) { @@ -182,7 +177,7 @@ unitTest(function headerSymbolIteratorSuccess(): void { } }); -unitTest(function headerTypesAvailable(): void { +Deno.test("headerTypesAvailable", function (): void { function newHeaders(): Headers { return new Headers(); } @@ -192,7 +187,7 @@ unitTest(function headerTypesAvailable(): void { // Modified from https://github.com/bitinn/node-fetch/blob/7d3293200a91ad52b5ca7962f9d6fd1c04983edb/test/test.js#L2001-L2014 // Copyright (c) 2016 David Frank. MIT License. -unitTest(function headerIllegalReject(): void { +Deno.test("headerIllegalReject", function (): void { let errorCount = 0; try { new Headers({ "He y": "ok" }); @@ -246,7 +241,7 @@ unitTest(function headerIllegalReject(): void { }); // If pair does not contain exactly two items,then throw a TypeError. -unitTest(function headerParamsShouldThrowTypeError(): void { +Deno.test("headerParamsShouldThrowTypeError", function (): void { let hasThrown = 0; try { @@ -263,7 +258,7 @@ unitTest(function headerParamsShouldThrowTypeError(): void { assertEquals(hasThrown, 2); }); -unitTest(function headerParamsArgumentsCheck(): void { +Deno.test("headerParamsArgumentsCheck", function (): void { const methodRequireOneParam = ["delete", "get", "has", "forEach"] as const; const methodRequireTwoParams = ["append", "set"] as const; @@ -336,7 +331,7 @@ unitTest(function headerParamsArgumentsCheck(): void { }); }); -unitTest(function headersInitMultiple(): void { +Deno.test("headersInitMultiple", function (): void { const headers = new Headers([ ["Set-Cookie", "foo=bar"], ["Set-Cookie", "bar=baz"], @@ -351,7 +346,7 @@ unitTest(function headersInitMultiple(): void { ]); }); -unitTest(function headersAppendMultiple(): void { +Deno.test("headersAppendMultiple", function (): void { const headers = new Headers([ ["Set-Cookie", "foo=bar"], ["X-Deno", "foo"], @@ -366,7 +361,7 @@ unitTest(function headersAppendMultiple(): void { ]); }); -unitTest(function headersAppendDuplicateSetCookieKey(): void { +Deno.test("headersAppendDuplicateSetCookieKey", function (): void { const headers = new Headers([["Set-Cookie", "foo=bar"]]); headers.append("set-Cookie", "foo=baz"); headers.append("Set-cookie", "baz=bar"); @@ -377,7 +372,7 @@ unitTest(function headersAppendDuplicateSetCookieKey(): void { ]); }); -unitTest(function headersSetDuplicateCookieKey(): void { +Deno.test("headersSetDuplicateCookieKey", function (): void { const headers = new Headers([["Set-Cookie", "foo=bar"]]); headers.set("set-Cookie", "foo=baz"); headers.set("set-cookie", "bar=qat"); @@ -388,7 +383,7 @@ unitTest(function headersSetDuplicateCookieKey(): void { ]); }); -unitTest(function headersGetSetCookie(): void { +Deno.test("headersGetSetCookie", function (): void { const headers = new Headers([ ["Set-Cookie", "foo=bar"], ["set-Cookie", "bar=qat"], @@ -396,7 +391,7 @@ unitTest(function headersGetSetCookie(): void { assertEquals(headers.get("SET-COOKIE"), "foo=bar, bar=qat"); }); -unitTest(function toStringShouldBeWebCompatibility(): void { +Deno.test("toStringShouldBeWebCompatibility", function (): void { const headers = new Headers(); assertEquals(headers.toString(), "[object Headers]"); }); @@ -405,7 +400,7 @@ function stringify(...args: unknown[]): string { return inspectArgs(args).replace(/\n$/, ""); } -unitTest(function customInspectReturnsCorrectHeadersFormat(): void { +Deno.test("customInspectReturnsCorrectHeadersFormat", function (): void { const blankHeaders = new Headers(); assertEquals(stringify(blankHeaders), "Headers {}"); const singleHeader = new Headers([["Content-Type", "application/json"]]); diff --git a/cli/tests/unit/internals_test.ts b/cli/tests/unit/internals_test.ts index 9a5820dec984e8..15bafa18e4f043 100644 --- a/cli/tests/unit/internals_test.ts +++ b/cli/tests/unit/internals_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assert, unitTest } from "./test_util.ts"; +import { assert } from "./test_util.ts"; -unitTest(function internalsExists(): void { +Deno.test("internalsExists", function (): void { const { inspectArgs, // @ts-expect-error TypeScript (as of 3.7) does not support indexing namespaces by symbol diff --git a/cli/tests/unit/io_test.ts b/cli/tests/unit/io_test.ts index ba9641fdccefa8..ff89054b4786a6 100644 --- a/cli/tests/unit/io_test.ts +++ b/cli/tests/unit/io_test.ts @@ -1,5 +1,5 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assertEquals, unitTest } from "./test_util.ts"; +import { assertEquals } from "./test_util.ts"; const DEFAULT_BUF_SIZE = 32 * 1024; @@ -27,7 +27,7 @@ function spyRead(obj: Deno.Buffer): Spy { return spy; } -unitTest(async function copyWithDefaultBufferSize() { +Deno.test("copyWithDefaultBufferSize", async function () { const xBytes = repeat("b", DEFAULT_BUF_SIZE); const reader = new Deno.Buffer(xBytes.buffer as ArrayBuffer); const write = new Deno.Buffer(); @@ -41,7 +41,7 @@ unitTest(async function copyWithDefaultBufferSize() { assertEquals(readSpy.calls, 2); // read with DEFAULT_BUF_SIZE bytes + read with 0 bytes }); -unitTest(async function copyWithCustomBufferSize() { +Deno.test("copyWithCustomBufferSize", async function () { const bufSize = 1024; const xBytes = repeat("b", DEFAULT_BUF_SIZE); const reader = new Deno.Buffer(xBytes.buffer as ArrayBuffer); @@ -56,7 +56,7 @@ unitTest(async function copyWithCustomBufferSize() { assertEquals(readSpy.calls, DEFAULT_BUF_SIZE / bufSize + 1); }); -unitTest({ perms: { write: true } }, async function copyBufferToFile() { +Deno.test("copyBufferToFile", async function () { const filePath = "test-file.txt"; // bigger than max File possible buffer 16kb const bufSize = 32 * 1024; diff --git a/cli/tests/unit/link_test.ts b/cli/tests/unit/link_test.ts index 86cd65bae6b07d..4bc68105fee91b 100644 --- a/cli/tests/unit/link_test.ts +++ b/cli/tests/unit/link_test.ts @@ -1,127 +1,115 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assert, assertEquals, assertThrows, unitTest } from "./test_util.ts"; +import { assert, assertEquals, assertThrows } from "./test_util.ts"; -unitTest( - { perms: { read: true, write: true } }, - function linkSyncSuccess(): void { - const testDir = Deno.makeTempDirSync(); - const oldData = "Hardlink"; - const oldName = testDir + "/oldname"; - const newName = testDir + "/newname"; - Deno.writeFileSync(oldName, new TextEncoder().encode(oldData)); - // Create the hard link. +Deno.test("linkSyncSuccess", function (): void { + const testDir = Deno.makeTempDirSync(); + const oldData = "Hardlink"; + const oldName = testDir + "/oldname"; + const newName = testDir + "/newname"; + Deno.writeFileSync(oldName, new TextEncoder().encode(oldData)); + // Create the hard link. + Deno.linkSync(oldName, newName); + // We should expect reading the same content. + const newData = new TextDecoder().decode(Deno.readFileSync(newName)); + assertEquals(oldData, newData); + // Writing to newname also affects oldname. + const newData2 = "Modified"; + Deno.writeFileSync(newName, new TextEncoder().encode(newData2)); + assertEquals( + newData2, + new TextDecoder().decode(Deno.readFileSync(oldName)), + ); + // Writing to oldname also affects newname. + const newData3 = "ModifiedAgain"; + Deno.writeFileSync(oldName, new TextEncoder().encode(newData3)); + assertEquals( + newData3, + new TextDecoder().decode(Deno.readFileSync(newName)), + ); + // Remove oldname. File still accessible through newname. + Deno.removeSync(oldName); + const newNameStat = Deno.statSync(newName); + assert(newNameStat.isFile); + assert(!newNameStat.isSymlink); // Not a symlink. + assertEquals( + newData3, + new TextDecoder().decode(Deno.readFileSync(newName)), + ); +}); + +Deno.test("linkSyncExists", function (): void { + const testDir = Deno.makeTempDirSync(); + const oldName = testDir + "/oldname"; + const newName = testDir + "/newname"; + Deno.writeFileSync(oldName, new TextEncoder().encode("oldName")); + // newname is already created. + Deno.writeFileSync(newName, new TextEncoder().encode("newName")); + + assertThrows(() => { + Deno.linkSync(oldName, newName); + }, Deno.errors.AlreadyExists); +}); + +Deno.test("linkSyncNotFound", function (): void { + const testDir = Deno.makeTempDirSync(); + const oldName = testDir + "/oldname"; + const newName = testDir + "/newname"; + + assertThrows(() => { Deno.linkSync(oldName, newName); - // We should expect reading the same content. - const newData = new TextDecoder().decode(Deno.readFileSync(newName)); - assertEquals(oldData, newData); - // Writing to newname also affects oldname. - const newData2 = "Modified"; - Deno.writeFileSync(newName, new TextEncoder().encode(newData2)); - assertEquals( - newData2, - new TextDecoder().decode(Deno.readFileSync(oldName)), - ); - // Writing to oldname also affects newname. - const newData3 = "ModifiedAgain"; - Deno.writeFileSync(oldName, new TextEncoder().encode(newData3)); - assertEquals( - newData3, - new TextDecoder().decode(Deno.readFileSync(newName)), - ); - // Remove oldname. File still accessible through newname. - Deno.removeSync(oldName); - const newNameStat = Deno.statSync(newName); - assert(newNameStat.isFile); - assert(!newNameStat.isSymlink); // Not a symlink. - assertEquals( - newData3, - new TextDecoder().decode(Deno.readFileSync(newName)), - ); - }, -); + }, Deno.errors.NotFound); +}); -unitTest( - { perms: { read: true, write: true } }, - function linkSyncExists(): void { - const testDir = Deno.makeTempDirSync(); - const oldName = testDir + "/oldname"; - const newName = testDir + "/newname"; - Deno.writeFileSync(oldName, new TextEncoder().encode("oldName")); - // newname is already created. - Deno.writeFileSync(newName, new TextEncoder().encode("newName")); +Deno.test("linkSuccess", async function (): Promise { + const testDir = Deno.makeTempDirSync(); + const oldData = "Hardlink"; + const oldName = testDir + "/oldname"; + const newName = testDir + "/newname"; + Deno.writeFileSync(oldName, new TextEncoder().encode(oldData)); + // Create the hard link. + await Deno.link(oldName, newName); + // We should expect reading the same content. + const newData = new TextDecoder().decode(Deno.readFileSync(newName)); + assertEquals(oldData, newData); + // Writing to newname also affects oldname. + const newData2 = "Modified"; + Deno.writeFileSync(newName, new TextEncoder().encode(newData2)); + assertEquals( + newData2, + new TextDecoder().decode(Deno.readFileSync(oldName)), + ); + // Writing to oldname also affects newname. + const newData3 = "ModifiedAgain"; + Deno.writeFileSync(oldName, new TextEncoder().encode(newData3)); + assertEquals( + newData3, + new TextDecoder().decode(Deno.readFileSync(newName)), + ); + // Remove oldname. File still accessible through newname. + Deno.removeSync(oldName); + const newNameStat = Deno.statSync(newName); + assert(newNameStat.isFile); + assert(!newNameStat.isSymlink); // Not a symlink. + assertEquals( + newData3, + new TextDecoder().decode(Deno.readFileSync(newName)), + ); +}); - assertThrows(() => { - Deno.linkSync(oldName, newName); - }, Deno.errors.AlreadyExists); - }, -); +Deno.test("linkSyncReadPerm", async function (): Promise { + await Deno.permissions.revoke({ name: "read" }); -unitTest( - { perms: { read: true, write: true } }, - function linkSyncNotFound(): void { - const testDir = Deno.makeTempDirSync(); - const oldName = testDir + "/oldname"; - const newName = testDir + "/newname"; + assertThrows(() => { + Deno.linkSync("oldbaddir", "newbaddir"); + }, Deno.errors.PermissionDenied); +}); - assertThrows(() => { - Deno.linkSync(oldName, newName); - }, Deno.errors.NotFound); - }, -); +Deno.test("linkSyncWritePerm", async function (): Promise { + await Deno.permissions.revoke({ name: "write" }); -unitTest( - { perms: { read: false, write: true } }, - function linkSyncReadPerm(): void { - assertThrows(() => { - Deno.linkSync("oldbaddir", "newbaddir"); - }, Deno.errors.PermissionDenied); - }, -); + assertThrows(() => { + Deno.linkSync("oldbaddir", "newbaddir"); + }, Deno.errors.PermissionDenied); +}); -unitTest( - { perms: { read: true, write: false } }, - function linkSyncWritePerm(): void { - assertThrows(() => { - Deno.linkSync("oldbaddir", "newbaddir"); - }, Deno.errors.PermissionDenied); - }, -); -unitTest( - { perms: { read: true, write: true } }, - async function linkSuccess(): Promise { - const testDir = Deno.makeTempDirSync(); - const oldData = "Hardlink"; - const oldName = testDir + "/oldname"; - const newName = testDir + "/newname"; - Deno.writeFileSync(oldName, new TextEncoder().encode(oldData)); - // Create the hard link. - await Deno.link(oldName, newName); - // We should expect reading the same content. - const newData = new TextDecoder().decode(Deno.readFileSync(newName)); - assertEquals(oldData, newData); - // Writing to newname also affects oldname. - const newData2 = "Modified"; - Deno.writeFileSync(newName, new TextEncoder().encode(newData2)); - assertEquals( - newData2, - new TextDecoder().decode(Deno.readFileSync(oldName)), - ); - // Writing to oldname also affects newname. - const newData3 = "ModifiedAgain"; - Deno.writeFileSync(oldName, new TextEncoder().encode(newData3)); - assertEquals( - newData3, - new TextDecoder().decode(Deno.readFileSync(newName)), - ); - // Remove oldname. File still accessible through newname. - Deno.removeSync(oldName); - const newNameStat = Deno.statSync(newName); - assert(newNameStat.isFile); - assert(!newNameStat.isSymlink); // Not a symlink. - assertEquals( - newData3, - new TextDecoder().decode(Deno.readFileSync(newName)), - ); - }, -); diff --git a/cli/tests/unit/make_temp_test.ts b/cli/tests/unit/make_temp_test.ts index b43d257e0398c2..62629552aeef69 100644 --- a/cli/tests/unit/make_temp_test.ts +++ b/cli/tests/unit/make_temp_test.ts @@ -4,10 +4,9 @@ import { assertEquals, assertThrows, assertThrowsAsync, - unitTest, } from "./test_util.ts"; -unitTest({ perms: { write: true } }, function makeTempDirSyncSuccess(): void { +Deno.test("makeTempDirSyncSuccess", function (): void { const dir1 = Deno.makeTempDirSync({ prefix: "hello", suffix: "world" }); const dir2 = Deno.makeTempDirSync({ prefix: "hello", suffix: "world" }); // Check that both dirs are different. @@ -28,60 +27,44 @@ unitTest({ perms: { write: true } }, function makeTempDirSyncSuccess(): void { }, Deno.errors.NotFound); }); -unitTest( - { perms: { read: true, write: true } }, - function makeTempDirSyncMode(): void { - const path = Deno.makeTempDirSync(); - const pathInfo = Deno.statSync(path); - if (Deno.build.os !== "windows") { - assertEquals(pathInfo.mode! & 0o777, 0o700 & ~Deno.umask()); - } - }, -); - -unitTest(function makeTempDirSyncPerm(): void { - // makeTempDirSync should require write permissions (for now). - assertThrows(() => { - Deno.makeTempDirSync({ dir: "/baddir" }); - }, Deno.errors.PermissionDenied); +Deno.test("makeTempDirSyncMode", function (): void { + const path = Deno.makeTempDirSync(); + const pathInfo = Deno.statSync(path); + if (Deno.build.os !== "windows") { + assertEquals(pathInfo.mode! & 0o777, 0o700 & ~Deno.umask()); + } }); -unitTest( - { perms: { write: true } }, - async function makeTempDirSuccess(): Promise { - const dir1 = await Deno.makeTempDir({ prefix: "hello", suffix: "world" }); - const dir2 = await Deno.makeTempDir({ prefix: "hello", suffix: "world" }); - // Check that both dirs are different. - assert(dir1 !== dir2); - for (const dir of [dir1, dir2]) { - // Check that the prefix and suffix are applied. - const lastPart = dir.replace(/^.*[\\\/]/, ""); - assert(lastPart.startsWith("hello")); - assert(lastPart.endsWith("world")); - } - // Check that the `dir` option works. - const dir3 = await Deno.makeTempDir({ dir: dir1 }); - assert(dir3.startsWith(dir1)); - assert(/^[\\\/]/.test(dir3.slice(dir1.length))); - // Check that creating a temp dir inside a nonexisting directory fails. - await assertThrowsAsync(async () => { - await Deno.makeTempDir({ dir: "/baddir" }); - }, Deno.errors.NotFound); - }, -); +Deno.test("makeTempDirSuccess", async function (): Promise { + const dir1 = await Deno.makeTempDir({ prefix: "hello", suffix: "world" }); + const dir2 = await Deno.makeTempDir({ prefix: "hello", suffix: "world" }); + // Check that both dirs are different. + assert(dir1 !== dir2); + for (const dir of [dir1, dir2]) { + // Check that the prefix and suffix are applied. + const lastPart = dir.replace(/^.*[\\\/]/, ""); + assert(lastPart.startsWith("hello")); + assert(lastPart.endsWith("world")); + } + // Check that the `dir` option works. + const dir3 = await Deno.makeTempDir({ dir: dir1 }); + assert(dir3.startsWith(dir1)); + assert(/^[\\\/]/.test(dir3.slice(dir1.length))); + // Check that creating a temp dir inside a nonexisting directory fails. + await assertThrowsAsync(async () => { + await Deno.makeTempDir({ dir: "/baddir" }); + }, Deno.errors.NotFound); +}); -unitTest( - { perms: { read: true, write: true } }, - async function makeTempDirMode(): Promise { - const path = await Deno.makeTempDir(); - const pathInfo = Deno.statSync(path); - if (Deno.build.os !== "windows") { - assertEquals(pathInfo.mode! & 0o777, 0o700 & ~Deno.umask()); - } - }, -); +Deno.test("makeTempDirMode", async function (): Promise { + const path = await Deno.makeTempDir(); + const pathInfo = Deno.statSync(path); + if (Deno.build.os !== "windows") { + assertEquals(pathInfo.mode! & 0o777, 0o700 & ~Deno.umask()); + } +}); -unitTest({ perms: { write: true } }, function makeTempFileSyncSuccess(): void { +Deno.test("makeTempFileSyncSuccess", function (): void { const file1 = Deno.makeTempFileSync({ prefix: "hello", suffix: "world" }); const file2 = Deno.makeTempFileSync({ prefix: "hello", suffix: "world" }); // Check that both dirs are different. @@ -103,56 +86,60 @@ unitTest({ perms: { write: true } }, function makeTempFileSyncSuccess(): void { }, Deno.errors.NotFound); }); -unitTest( - { perms: { read: true, write: true } }, - function makeTempFileSyncMode(): void { - const path = Deno.makeTempFileSync(); - const pathInfo = Deno.statSync(path); - if (Deno.build.os !== "windows") { - assertEquals(pathInfo.mode! & 0o777, 0o600 & ~Deno.umask()); - } - }, -); +Deno.test("makeTempFileSyncMode", function (): void { + const path = Deno.makeTempFileSync(); + const pathInfo = Deno.statSync(path); + if (Deno.build.os !== "windows") { + assertEquals(pathInfo.mode! & 0o777, 0o600 & ~Deno.umask()); + } +}); + +Deno.test("makeTempFileSuccess", async function (): Promise { + const file1 = await Deno.makeTempFile({ prefix: "hello", suffix: "world" }); + const file2 = await Deno.makeTempFile({ prefix: "hello", suffix: "world" }); + // Check that both dirs are different. + assert(file1 !== file2); + for (const dir of [file1, file2]) { + // Check that the prefix and suffix are applied. + const lastPart = dir.replace(/^.*[\\\/]/, ""); + assert(lastPart.startsWith("hello")); + assert(lastPart.endsWith("world")); + } + // Check that the `dir` option works. + const dir = Deno.makeTempDirSync({ prefix: "tempdir" }); + const file3 = await Deno.makeTempFile({ dir }); + assert(file3.startsWith(dir)); + assert(/^[\\\/]/.test(file3.slice(dir.length))); + // Check that creating a temp file inside a nonexisting directory fails. + await assertThrowsAsync(async () => { + await Deno.makeTempFile({ dir: "/baddir" }); + }, Deno.errors.NotFound); +}); + +Deno.test("makeTempFileMode", async function (): Promise { + const path = await Deno.makeTempFile(); + const pathInfo = Deno.statSync(path); + if (Deno.build.os !== "windows") { + assertEquals(pathInfo.mode! & 0o777, 0o600 & ~Deno.umask()); + } +}); + +Deno.test("makeTempFileSyncPerm", async function (): Promise { + await Deno.permissions.revoke({ name: "write" }); -unitTest(function makeTempFileSyncPerm(): void { // makeTempFileSync should require write permissions (for now). assertThrows(() => { Deno.makeTempFileSync({ dir: "/baddir" }); }, Deno.errors.PermissionDenied); }); -unitTest( - { perms: { write: true } }, - async function makeTempFileSuccess(): Promise { - const file1 = await Deno.makeTempFile({ prefix: "hello", suffix: "world" }); - const file2 = await Deno.makeTempFile({ prefix: "hello", suffix: "world" }); - // Check that both dirs are different. - assert(file1 !== file2); - for (const dir of [file1, file2]) { - // Check that the prefix and suffix are applied. - const lastPart = dir.replace(/^.*[\\\/]/, ""); - assert(lastPart.startsWith("hello")); - assert(lastPart.endsWith("world")); - } - // Check that the `dir` option works. - const dir = Deno.makeTempDirSync({ prefix: "tempdir" }); - const file3 = await Deno.makeTempFile({ dir }); - assert(file3.startsWith(dir)); - assert(/^[\\\/]/.test(file3.slice(dir.length))); - // Check that creating a temp file inside a nonexisting directory fails. - await assertThrowsAsync(async () => { - await Deno.makeTempFile({ dir: "/baddir" }); - }, Deno.errors.NotFound); - }, -); +Deno.test("makeTempDirSyncPerm", async function (): Promise { + await Deno.permissions.revoke({ name: "write" }); + + // makeTempDirSync should require write permissions (for now). + assertThrows(() => { + Deno.makeTempDirSync({ dir: "/baddir" }); + }, Deno.errors.PermissionDenied); +}); + -unitTest( - { perms: { read: true, write: true } }, - async function makeTempFileMode(): Promise { - const path = await Deno.makeTempFile(); - const pathInfo = Deno.statSync(path); - if (Deno.build.os !== "windows") { - assertEquals(pathInfo.mode! & 0o777, 0o600 & ~Deno.umask()); - } - }, -); diff --git a/cli/tests/unit/metrics_test.ts b/cli/tests/unit/metrics_test.ts index 525e5aae654948..aef16782200d19 100644 --- a/cli/tests/unit/metrics_test.ts +++ b/cli/tests/unit/metrics_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assert, unitTest } from "./test_util.ts"; +import { assert } from "./test_util.ts"; -unitTest(async function metrics(): Promise { +Deno.test("metrics", async function (): Promise { // Write to stdout to ensure a "data" message gets sent instead of just // control messages. const dataMsg = new Uint8Array([13, 13, 13]); // "\r\r\r", @@ -38,31 +38,25 @@ unitTest(async function metrics(): Promise { assert(m2OpWrite.bytesReceived > m1OpWrite.bytesReceived); }); -unitTest( - { perms: { write: true } }, - function metricsUpdatedIfNoResponseSync(): void { - const filename = Deno.makeTempDirSync() + "/test.txt"; +Deno.test("metricsUpdatedIfNoResponseSync", function (): void { + const filename = Deno.makeTempDirSync() + "/test.txt"; - const data = new Uint8Array([41, 42, 43]); - Deno.writeFileSync(filename, data, { mode: 0o666 }); + const data = new Uint8Array([41, 42, 43]); + Deno.writeFileSync(filename, data, { mode: 0o666 }); - const metrics = Deno.metrics(); - assert(metrics.opsDispatched === metrics.opsCompleted); - assert(metrics.opsDispatchedSync === metrics.opsCompletedSync); - }, -); + const metrics = Deno.metrics(); + assert(metrics.opsDispatched === metrics.opsCompleted); + assert(metrics.opsDispatchedSync === metrics.opsCompletedSync); +}); -unitTest( - { perms: { write: true } }, - async function metricsUpdatedIfNoResponseAsync(): Promise { - const filename = Deno.makeTempDirSync() + "/test.txt"; +Deno.test("metricsUpdatedIfNoResponseAsync", async function (): Promise { + const filename = Deno.makeTempDirSync() + "/test.txt"; - const data = new Uint8Array([41, 42, 43]); - await Deno.writeFile(filename, data, { mode: 0o666 }); + const data = new Uint8Array([41, 42, 43]); + await Deno.writeFile(filename, data, { mode: 0o666 }); - const metrics = Deno.metrics(); - assert(metrics.opsDispatched === metrics.opsCompleted); - assert(metrics.opsDispatchedSync === metrics.opsCompletedSync); - assert(metrics.opsDispatchedAsync === metrics.opsCompletedAsync); - }, -); + const metrics = Deno.metrics(); + assert(metrics.opsDispatched === metrics.opsCompleted); + assert(metrics.opsDispatchedSync === metrics.opsCompletedSync); + assert(metrics.opsDispatchedAsync === metrics.opsCompletedAsync); +}); diff --git a/cli/tests/unit/mkdir_test.ts b/cli/tests/unit/mkdir_test.ts index fd0328f57c38fa..452057d91464bc 100644 --- a/cli/tests/unit/mkdir_test.ts +++ b/cli/tests/unit/mkdir_test.ts @@ -5,7 +5,6 @@ import { assertThrows, assertThrowsAsync, pathToAbsoluteFileUrl, - unitTest, } from "./test_util.ts"; function assertDirectory(path: string, mode?: number): void { @@ -16,55 +15,43 @@ function assertDirectory(path: string, mode?: number): void { } } -unitTest( - { perms: { read: true, write: true } }, - function mkdirSyncSuccess(): void { - const path = Deno.makeTempDirSync() + "/dir"; - Deno.mkdirSync(path); - assertDirectory(path); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - function mkdirSyncMode(): void { - const path = Deno.makeTempDirSync() + "/dir"; - Deno.mkdirSync(path, { mode: 0o737 }); - assertDirectory(path, 0o737); - }, -); +Deno.test("mkdirSyncSuccess", function (): void { + const path = Deno.makeTempDirSync() + "/dir"; + Deno.mkdirSync(path); + assertDirectory(path); +}); -unitTest({ perms: { write: false } }, function mkdirSyncPerm(): void { +Deno.test("mkdirSyncMode", function (): void { + const path = Deno.makeTempDirSync() + "/dir"; + Deno.mkdirSync(path, { mode: 0o737 }); + assertDirectory(path, 0o737); +}); + +Deno.test("mkdirSyncPerm", function (): void { assertThrows(() => { Deno.mkdirSync("/baddir"); }, Deno.errors.PermissionDenied); }); -unitTest( - { perms: { read: true, write: true } }, - async function mkdirSuccess(): Promise { - const path = Deno.makeTempDirSync() + "/dir"; - await Deno.mkdir(path); - assertDirectory(path); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function mkdirMode(): Promise { - const path = Deno.makeTempDirSync() + "/dir"; - await Deno.mkdir(path, { mode: 0o737 }); - assertDirectory(path, 0o737); - }, -); +Deno.test("mkdirSuccess", async function (): Promise { + const path = Deno.makeTempDirSync() + "/dir"; + await Deno.mkdir(path); + assertDirectory(path); +}); + +Deno.test("mkdirMode", async function (): Promise { + const path = Deno.makeTempDirSync() + "/dir"; + await Deno.mkdir(path, { mode: 0o737 }); + assertDirectory(path, 0o737); +}); -unitTest({ perms: { write: true } }, function mkdirErrSyncIfExists(): void { +Deno.test("mkdirErrSyncIfExists", function (): void { assertThrows(() => { Deno.mkdirSync("."); }, Deno.errors.AlreadyExists); }); -unitTest({ perms: { write: true } }, async function mkdirErrIfExists(): Promise< +Deno.test("mkdirErrIfExists", async function (): Promise< void > { await assertThrowsAsync(async () => { @@ -72,159 +59,132 @@ unitTest({ perms: { write: true } }, async function mkdirErrIfExists(): Promise< }, Deno.errors.AlreadyExists); }); -unitTest( - { perms: { read: true, write: true } }, - function mkdirSyncRecursive(): void { - const path = Deno.makeTempDirSync() + "/nested/directory"; - Deno.mkdirSync(path, { recursive: true }); - assertDirectory(path); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function mkdirRecursive(): Promise { - const path = Deno.makeTempDirSync() + "/nested/directory"; - await Deno.mkdir(path, { recursive: true }); - assertDirectory(path); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - function mkdirSyncRecursiveMode(): void { - const nested = Deno.makeTempDirSync() + "/nested"; - const path = nested + "/dir"; - Deno.mkdirSync(path, { mode: 0o737, recursive: true }); - assertDirectory(path, 0o737); - assertDirectory(nested, 0o737); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function mkdirRecursiveMode(): Promise { - const nested = Deno.makeTempDirSync() + "/nested"; - const path = nested + "/dir"; - await Deno.mkdir(path, { mode: 0o737, recursive: true }); - assertDirectory(path, 0o737); - assertDirectory(nested, 0o737); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - function mkdirSyncRecursiveIfExists(): void { - const path = Deno.makeTempDirSync() + "/dir"; - Deno.mkdirSync(path, { mode: 0o737 }); - Deno.mkdirSync(path, { recursive: true }); - Deno.mkdirSync(path, { recursive: true, mode: 0o731 }); +Deno.test("mkdirSyncRecursive", function (): void { + const path = Deno.makeTempDirSync() + "/nested/directory"; + Deno.mkdirSync(path, { recursive: true }); + assertDirectory(path); +}); + +Deno.test("mkdirRecursive", async function (): Promise { + const path = Deno.makeTempDirSync() + "/nested/directory"; + await Deno.mkdir(path, { recursive: true }); + assertDirectory(path); +}); + +Deno.test("mkdirSyncRecursiveMode", function (): void { + const nested = Deno.makeTempDirSync() + "/nested"; + const path = nested + "/dir"; + Deno.mkdirSync(path, { mode: 0o737, recursive: true }); + assertDirectory(path, 0o737); + assertDirectory(nested, 0o737); +}); + +Deno.test("mkdirRecursiveMode", async function (): Promise { + const nested = Deno.makeTempDirSync() + "/nested"; + const path = nested + "/dir"; + await Deno.mkdir(path, { mode: 0o737, recursive: true }); + assertDirectory(path, 0o737); + assertDirectory(nested, 0o737); +}); + +Deno.test("mkdirSyncRecursiveIfExists", function (): void { + const path = Deno.makeTempDirSync() + "/dir"; + Deno.mkdirSync(path, { mode: 0o737 }); + Deno.mkdirSync(path, { recursive: true }); + Deno.mkdirSync(path, { recursive: true, mode: 0o731 }); + assertDirectory(path, 0o737); + if (Deno.build.os !== "windows") { + const pathLink = path + "Link"; + Deno.symlinkSync(path, pathLink); + Deno.mkdirSync(pathLink, { recursive: true }); + Deno.mkdirSync(pathLink, { recursive: true, mode: 0o731 }); assertDirectory(path, 0o737); - if (Deno.build.os !== "windows") { - const pathLink = path + "Link"; - Deno.symlinkSync(path, pathLink); - Deno.mkdirSync(pathLink, { recursive: true }); - Deno.mkdirSync(pathLink, { recursive: true, mode: 0o731 }); - assertDirectory(path, 0o737); - } - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function mkdirRecursiveIfExists(): Promise { - const path = Deno.makeTempDirSync() + "/dir"; - await Deno.mkdir(path, { mode: 0o737 }); - await Deno.mkdir(path, { recursive: true }); - await Deno.mkdir(path, { recursive: true, mode: 0o731 }); + } +}); + +Deno.test("mkdirRecursiveIfExists", async function (): Promise { + const path = Deno.makeTempDirSync() + "/dir"; + await Deno.mkdir(path, { mode: 0o737 }); + await Deno.mkdir(path, { recursive: true }); + await Deno.mkdir(path, { recursive: true, mode: 0o731 }); + assertDirectory(path, 0o737); + if (Deno.build.os !== "windows") { + const pathLink = path + "Link"; + Deno.symlinkSync(path, pathLink); + await Deno.mkdir(pathLink, { recursive: true }); + await Deno.mkdir(pathLink, { recursive: true, mode: 0o731 }); assertDirectory(path, 0o737); - if (Deno.build.os !== "windows") { - const pathLink = path + "Link"; - Deno.symlinkSync(path, pathLink); - await Deno.mkdir(pathLink, { recursive: true }); - await Deno.mkdir(pathLink, { recursive: true, mode: 0o731 }); - assertDirectory(path, 0o737); - } - }, -); - -unitTest( - { perms: { read: true, write: true } }, - function mkdirSyncErrors(): void { - const testDir = Deno.makeTempDirSync(); - const emptydir = testDir + "/empty"; - const fulldir = testDir + "/dir"; - const file = fulldir + "/file"; - Deno.mkdirSync(emptydir); - Deno.mkdirSync(fulldir); - Deno.createSync(file).close(); + } +}); + +Deno.test("mkdirSyncErrors", function (): void { + const testDir = Deno.makeTempDirSync(); + const emptydir = testDir + "/empty"; + const fulldir = testDir + "/dir"; + const file = fulldir + "/file"; + Deno.mkdirSync(emptydir); + Deno.mkdirSync(fulldir); + Deno.createSync(file).close(); + + assertThrows((): void => { + Deno.mkdirSync(emptydir, { recursive: false }); + }, Deno.errors.AlreadyExists); + assertThrows((): void => { + Deno.mkdirSync(fulldir, { recursive: false }); + }, Deno.errors.AlreadyExists); + assertThrows((): void => { + Deno.mkdirSync(file, { recursive: false }); + }, Deno.errors.AlreadyExists); + assertThrows((): void => { + Deno.mkdirSync(file, { recursive: true }); + }, Deno.errors.AlreadyExists); + if (Deno.build.os !== "windows") { + const fileLink = testDir + "/fileLink"; + const dirLink = testDir + "/dirLink"; + const danglingLink = testDir + "/danglingLink"; + Deno.symlinkSync(file, fileLink); + Deno.symlinkSync(emptydir, dirLink); + Deno.symlinkSync(testDir + "/nonexistent", danglingLink); + + assertThrows((): void => { + Deno.mkdirSync(dirLink, { recursive: false }); + }, Deno.errors.AlreadyExists); assertThrows((): void => { - Deno.mkdirSync(emptydir, { recursive: false }); + Deno.mkdirSync(fileLink, { recursive: false }); }, Deno.errors.AlreadyExists); assertThrows((): void => { - Deno.mkdirSync(fulldir, { recursive: false }); + Deno.mkdirSync(fileLink, { recursive: true }); }, Deno.errors.AlreadyExists); assertThrows((): void => { - Deno.mkdirSync(file, { recursive: false }); + Deno.mkdirSync(danglingLink, { recursive: false }); }, Deno.errors.AlreadyExists); assertThrows((): void => { - Deno.mkdirSync(file, { recursive: true }); + Deno.mkdirSync(danglingLink, { recursive: true }); }, Deno.errors.AlreadyExists); + } +}); + +Deno.test("mkdirSyncRelativeUrlPath", function (): void { + const testDir = Deno.makeTempDirSync(); + const nestedDir = testDir + "/nested"; + // Add trailing slash so base path is treated as a directory. pathToAbsoluteFileUrl removes trailing slashes. + const path = new URL("../dir", pathToAbsoluteFileUrl(nestedDir) + "/"); + + Deno.mkdirSync(nestedDir); + Deno.mkdirSync(path); - if (Deno.build.os !== "windows") { - const fileLink = testDir + "/fileLink"; - const dirLink = testDir + "/dirLink"; - const danglingLink = testDir + "/danglingLink"; - Deno.symlinkSync(file, fileLink); - Deno.symlinkSync(emptydir, dirLink); - Deno.symlinkSync(testDir + "/nonexistent", danglingLink); - - assertThrows((): void => { - Deno.mkdirSync(dirLink, { recursive: false }); - }, Deno.errors.AlreadyExists); - assertThrows((): void => { - Deno.mkdirSync(fileLink, { recursive: false }); - }, Deno.errors.AlreadyExists); - assertThrows((): void => { - Deno.mkdirSync(fileLink, { recursive: true }); - }, Deno.errors.AlreadyExists); - assertThrows((): void => { - Deno.mkdirSync(danglingLink, { recursive: false }); - }, Deno.errors.AlreadyExists); - assertThrows((): void => { - Deno.mkdirSync(danglingLink, { recursive: true }); - }, Deno.errors.AlreadyExists); - } - }, -); - -unitTest( - { perms: { read: true, write: true } }, - function mkdirSyncRelativeUrlPath(): void { - const testDir = Deno.makeTempDirSync(); - const nestedDir = testDir + "/nested"; - // Add trailing slash so base path is treated as a directory. pathToAbsoluteFileUrl removes trailing slashes. - const path = new URL("../dir", pathToAbsoluteFileUrl(nestedDir) + "/"); - - Deno.mkdirSync(nestedDir); - Deno.mkdirSync(path); - - assertDirectory(testDir + "/dir"); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function mkdirRelativeUrlPath(): Promise { - const testDir = Deno.makeTempDirSync(); - const nestedDir = testDir + "/nested"; - // Add trailing slash so base path is treated as a directory. pathToAbsoluteFileUrl removes trailing slashes. - const path = new URL("../dir", pathToAbsoluteFileUrl(nestedDir) + "/"); - - await Deno.mkdir(nestedDir); - await Deno.mkdir(path); - - assertDirectory(testDir + "/dir"); - }, -); + assertDirectory(testDir + "/dir"); +}); + +Deno.test("mkdirRelativeUrlPath", async function (): Promise { + const testDir = Deno.makeTempDirSync(); + const nestedDir = testDir + "/nested"; + // Add trailing slash so base path is treated as a directory. pathToAbsoluteFileUrl removes trailing slashes. + const path = new URL("../dir", pathToAbsoluteFileUrl(nestedDir) + "/"); + + await Deno.mkdir(nestedDir); + await Deno.mkdir(path); + + assertDirectory(testDir + "/dir"); +}); diff --git a/cli/tests/unit/net_test.ts b/cli/tests/unit/net_test.ts index 99af959cc3cefd..8a1b1253306a9e 100644 --- a/cli/tests/unit/net_test.ts +++ b/cli/tests/unit/net_test.ts @@ -6,10 +6,9 @@ import { assertThrows, assertThrowsAsync, deferred, - unitTest, } from "./test_util.ts"; -unitTest({ perms: { net: true } }, function netTcpListenClose(): void { +Deno.test("netTcpListenClose", function (): void { const listener = Deno.listen({ hostname: "127.0.0.1", port: 3500 }); assert(listener.addr.transport === "tcp"); assertEquals(listener.addr.hostname, "127.0.0.1"); @@ -18,26 +17,22 @@ unitTest({ perms: { net: true } }, function netTcpListenClose(): void { listener.close(); }); -unitTest( - { - perms: { net: true }, - }, - function netUdpListenClose(): void { - const socket = Deno.listenDatagram({ - hostname: "127.0.0.1", - port: 3500, - transport: "udp", - }); - assert(socket.addr.transport === "udp"); - assertEquals(socket.addr.hostname, "127.0.0.1"); - assertEquals(socket.addr.port, 3500); - socket.close(); - }, -); +Deno.test("netUdpListenClose", function (): void { + const socket = Deno.listenDatagram({ + hostname: "127.0.0.1", + port: 3500, + transport: "udp", + }); + assert(socket.addr.transport === "udp"); + assertEquals(socket.addr.hostname, "127.0.0.1"); + assertEquals(socket.addr.port, 3500); + socket.close(); +}); -unitTest( - { ignore: Deno.build.os === "windows", perms: { read: true, write: true } }, - function netUnixListenClose(): void { +Deno.test({ + name: "netUnixListenClose", + ignore: Deno.build.os === "windows", + fn(): void { const filePath = Deno.makeTempFileSync(); const socket = Deno.listen({ path: filePath, @@ -47,11 +42,12 @@ unitTest( assertEquals(socket.addr.path, filePath); socket.close(); }, -); +}); -unitTest( - { ignore: Deno.build.os === "windows", perms: { read: true, write: true } }, - function netUnixPacketListenClose(): void { +Deno.test({ + name: "netUnixPacletListenClose", + ignore: Deno.build.os === "windows", + fn(): void { const filePath = Deno.makeTempFileSync(); const socket = Deno.listenDatagram({ path: filePath, @@ -61,61 +57,25 @@ unitTest( assertEquals(socket.addr.path, filePath); socket.close(); }, -); - -unitTest( - { ignore: Deno.build.os === "windows", perms: { read: true } }, - function netUnixListenWritePermission(): void { - assertThrows(() => { - const filePath = Deno.makeTempFileSync(); - const socket = Deno.listen({ - path: filePath, - transport: "unix", - }); - assert(socket.addr.transport === "unix"); - assertEquals(socket.addr.path, filePath); - socket.close(); - }, Deno.errors.PermissionDenied); - }, -); - -unitTest( - { ignore: Deno.build.os === "windows", perms: { read: true } }, - function netUnixPacketListenWritePermission(): void { - assertThrows(() => { - const filePath = Deno.makeTempFileSync(); - const socket = Deno.listenDatagram({ - path: filePath, - transport: "unixpacket", - }); - assert(socket.addr.transport === "unixpacket"); - assertEquals(socket.addr.path, filePath); - socket.close(); - }, Deno.errors.PermissionDenied); - }, -); +}); -unitTest( - { - perms: { net: true }, - }, - async function netTcpCloseWhileAccept(): Promise { - const listener = Deno.listen({ port: 4501 }); - const p = listener.accept(); - listener.close(); - await assertThrowsAsync( - async (): Promise => { - await p; - }, - Deno.errors.BadResource, - "Listener has been closed", - ); - }, -); +Deno.test("netTcpCloseWhileAccept", async function (): Promise { + const listener = Deno.listen({ port: 4501 }); + const p = listener.accept(); + listener.close(); + await assertThrowsAsync( + async (): Promise => { + await p; + }, + Deno.errors.BadResource, + "Listener has been closed", + ); +}); -unitTest( - { ignore: Deno.build.os === "windows", perms: { read: true, write: true } }, - async function netUnixCloseWhileAccept(): Promise { +Deno.test({ + name: "netUnixCloseWhileAccept", + ignore: Deno.build.os === "windows", + async fn(): Promise { const filePath = await Deno.makeTempFile(); const listener = Deno.listen({ path: filePath, @@ -131,35 +91,33 @@ unitTest( "Listener has been closed", ); }, -); +}); -unitTest( - { perms: { net: true } }, - async function netTcpConcurrentAccept(): Promise { - const listener = Deno.listen({ port: 4502 }); - let acceptErrCount = 0; - const checkErr = (e: Error): void => { - if (e.message === "Listener has been closed") { - assertEquals(acceptErrCount, 1); - } else if (e.message === "Another accept task is ongoing") { - acceptErrCount++; - } else { - throw new Error("Unexpected error message"); - } - }; - const p = listener.accept().catch(checkErr); - const p1 = listener.accept().catch(checkErr); - await Promise.race([p, p1]); - listener.close(); - await Promise.all([p, p1]); - assertEquals(acceptErrCount, 1); - }, -); +Deno.test("netTcpConcurrentAccept", async function (): Promise { + const listener = Deno.listen({ port: 4502 }); + let acceptErrCount = 0; + const checkErr = (e: Error): void => { + if (e.message === "Listener has been closed") { + assertEquals(acceptErrCount, 1); + } else if (e.message === "Another accept task is ongoing") { + acceptErrCount++; + } else { + throw new Error("Unexpected error message"); + } + }; + const p = listener.accept().catch(checkErr); + const p1 = listener.accept().catch(checkErr); + await Promise.race([p, p1]); + listener.close(); + await Promise.all([p, p1]); + assertEquals(acceptErrCount, 1); +}); // TODO(jsouto): Enable when tokio updates mio to v0.7! -unitTest( - { ignore: true, perms: { read: true, write: true } }, - async function netUnixConcurrentAccept(): Promise { +Deno.test({ + name: "netUnixConcurrentAccept", + ignore: true, + async fn(): Promise { const filePath = await Deno.makeTempFile(); const listener = Deno.listen({ transport: "unix", path: filePath }); let acceptErrCount = 0; @@ -179,9 +137,9 @@ unitTest( await [p, p1]; assertEquals(acceptErrCount, 1); }, -); +}); -unitTest({ perms: { net: true } }, async function netTcpDialListen(): Promise< +Deno.test("netTcpDialListen", async function (): Promise< void > { const listener = Deno.listen({ port: 3500 }); @@ -218,9 +176,10 @@ unitTest({ perms: { net: true } }, async function netTcpDialListen(): Promise< conn.close(); }); -unitTest( - { ignore: Deno.build.os === "windows", perms: { read: true, write: true } }, - async function netUnixDialListen(): Promise { +Deno.test({ + name: "netUnixDialListen", + ignore: Deno.build.os === "windows", + async fn(): Promise { const filePath = await Deno.makeTempFile(); const listener = Deno.listen({ path: filePath, transport: "unix" }); listener.accept().then( @@ -252,80 +211,72 @@ unitTest( listener.close(); conn.close(); }, -); - -unitTest( - { perms: { net: true } }, - async function netUdpSendReceive(): Promise { - const alice = Deno.listenDatagram({ port: 3500, transport: "udp" }); - assert(alice.addr.transport === "udp"); - assertEquals(alice.addr.port, 3500); - assertEquals(alice.addr.hostname, "127.0.0.1"); - - const bob = Deno.listenDatagram({ port: 4501, transport: "udp" }); - assert(bob.addr.transport === "udp"); - assertEquals(bob.addr.port, 4501); - assertEquals(bob.addr.hostname, "127.0.0.1"); - - const sent = new Uint8Array([1, 2, 3]); - const byteLength = await alice.send(sent, bob.addr); - - assertEquals(byteLength, 3); +}); - const [recvd, remote] = await bob.receive(); - assert(remote.transport === "udp"); - assertEquals(remote.port, 3500); - assertEquals(recvd.length, 3); - assertEquals(1, recvd[0]); - assertEquals(2, recvd[1]); - assertEquals(3, recvd[2]); - alice.close(); - bob.close(); - }, -); +Deno.test("netUdpSendReceive", async function (): Promise { + const alice = Deno.listenDatagram({ port: 3500, transport: "udp" }); + assert(alice.addr.transport === "udp"); + assertEquals(alice.addr.port, 3500); + assertEquals(alice.addr.hostname, "127.0.0.1"); + + const bob = Deno.listenDatagram({ port: 4501, transport: "udp" }); + assert(bob.addr.transport === "udp"); + assertEquals(bob.addr.port, 4501); + assertEquals(bob.addr.hostname, "127.0.0.1"); + + const sent = new Uint8Array([1, 2, 3]); + const byteLength = await alice.send(sent, bob.addr); + + assertEquals(byteLength, 3); + + const [recvd, remote] = await bob.receive(); + assert(remote.transport === "udp"); + assertEquals(remote.port, 3500); + assertEquals(recvd.length, 3); + assertEquals(1, recvd[0]); + assertEquals(2, recvd[1]); + assertEquals(3, recvd[2]); + alice.close(); + bob.close(); +}); -unitTest( - { perms: { net: true } }, - async function netUdpConcurrentSendReceive(): Promise { - const socket = Deno.listenDatagram({ port: 3500, transport: "udp" }); - assert(socket.addr.transport === "udp"); - assertEquals(socket.addr.port, 3500); - assertEquals(socket.addr.hostname, "127.0.0.1"); +Deno.test("netUdpConcurrentSendReceive", async function (): Promise { + const socket = Deno.listenDatagram({ port: 3500, transport: "udp" }); + assert(socket.addr.transport === "udp"); + assertEquals(socket.addr.port, 3500); + assertEquals(socket.addr.hostname, "127.0.0.1"); - const recvPromise = socket.receive(); + const recvPromise = socket.receive(); - const sendBuf = new Uint8Array([1, 2, 3]); - const sendLen = await socket.send(sendBuf, socket.addr); - assertEquals(sendLen, 3); + const sendBuf = new Uint8Array([1, 2, 3]); + const sendLen = await socket.send(sendBuf, socket.addr); + assertEquals(sendLen, 3); - const [recvBuf, recvAddr] = await recvPromise; - assertEquals(recvBuf.length, 3); - assertEquals(1, recvBuf[0]); - assertEquals(2, recvBuf[1]); - assertEquals(3, recvBuf[2]); + const [recvBuf, recvAddr] = await recvPromise; + assertEquals(recvBuf.length, 3); + assertEquals(1, recvBuf[0]); + assertEquals(2, recvBuf[1]); + assertEquals(3, recvBuf[2]); - socket.close(); - }, -); + socket.close(); +}); -unitTest( - { perms: { net: true } }, - async function netUdpBorrowMutError(): Promise { - const socket = Deno.listenDatagram({ - port: 4501, - transport: "udp", - }); - // Panic happened on second send: BorrowMutError - const a = socket.send(new Uint8Array(), socket.addr); - const b = socket.send(new Uint8Array(), socket.addr); - await Promise.all([a, b]); - socket.close(); - }, -); +Deno.test("netUdpBorrowMutError", async function (): Promise { + const socket = Deno.listenDatagram({ + port: 4501, + transport: "udp", + }); + // Panic happened on second send: BorrowMutError + const a = socket.send(new Uint8Array(), socket.addr); + const b = socket.send(new Uint8Array(), socket.addr); + await Promise.all([a, b]); + socket.close(); +}); -unitTest( - { ignore: Deno.build.os === "windows", perms: { read: true, write: true } }, - async function netUnixPacketSendReceive(): Promise { +Deno.test({ + name: "netUnixPacketSendReceive", + ignore: Deno.build.os === "windows", + async fn(): Promise { const filePath = await Deno.makeTempFile(); const alice = Deno.listenDatagram({ path: filePath, @@ -355,12 +306,13 @@ unitTest( alice.close(); bob.close(); }, -); +}); // TODO(piscisaureus): Enable after Tokio v0.3/v1.0 upgrade. -unitTest( - { ignore: true, perms: { read: true, write: true } }, - async function netUnixPacketConcurrentSendReceive(): Promise { +Deno.test({ + name: "netUnixPacketConcurrentSendReceive", + ignore: true, + async fn(): Promise { const filePath = await Deno.makeTempFile(); const socket = Deno.listenDatagram({ path: filePath, @@ -383,73 +335,67 @@ unitTest( socket.close(); }, -); +}); -unitTest( - { perms: { net: true } }, - async function netTcpListenIteratorBreakClosesResource(): Promise { - const promise = deferred(); +Deno.test("netTcpListenIteratorBreakClosesResource", async function (): Promise< + void +> { + const promise = deferred(); - async function iterate(listener: Deno.Listener): Promise { - let i = 0; + async function iterate(listener: Deno.Listener): Promise { + let i = 0; - for await (const conn of listener) { - conn.close(); - i++; + for await (const conn of listener) { + conn.close(); + i++; - if (i > 1) { - break; - } + if (i > 1) { + break; } - - promise.resolve(); } - const addr = { hostname: "127.0.0.1", port: 8888 }; - const listener = Deno.listen(addr); - iterate(listener); + promise.resolve(); + } - await new Promise((resolve) => { - setTimeout(resolve, 100); - }); - const conn1 = await Deno.connect(addr); - conn1.close(); - const conn2 = await Deno.connect(addr); - conn2.close(); + const addr = { hostname: "127.0.0.1", port: 8888 }; + const listener = Deno.listen(addr); + iterate(listener); - await promise; - }, -); + await new Promise((resolve) => { + setTimeout(resolve, 100); + }); + const conn1 = await Deno.connect(addr); + conn1.close(); + const conn2 = await Deno.connect(addr); + conn2.close(); -unitTest( - { perms: { net: true } }, - async function netTcpListenCloseWhileIterating(): Promise { - const listener = Deno.listen({ port: 8000 }); - const nextWhileClosing = listener[Symbol.asyncIterator]().next(); - listener.close(); - assertEquals(await nextWhileClosing, { value: undefined, done: true }); + await promise; +}); - const nextAfterClosing = listener[Symbol.asyncIterator]().next(); - assertEquals(await nextAfterClosing, { value: undefined, done: true }); - }, -); +Deno.test("netTcpListenCloseWhileIterating", async function (): Promise { + const listener = Deno.listen({ port: 8000 }); + const nextWhileClosing = listener[Symbol.asyncIterator]().next(); + listener.close(); + assertEquals(await nextWhileClosing, { value: undefined, done: true }); -unitTest( - { perms: { net: true } }, - async function netUdpListenCloseWhileIterating(): Promise { - const socket = Deno.listenDatagram({ port: 8000, transport: "udp" }); - const nextWhileClosing = socket[Symbol.asyncIterator]().next(); - socket.close(); - assertEquals(await nextWhileClosing, { value: undefined, done: true }); + const nextAfterClosing = listener[Symbol.asyncIterator]().next(); + assertEquals(await nextAfterClosing, { value: undefined, done: true }); +}); - const nextAfterClosing = socket[Symbol.asyncIterator]().next(); - assertEquals(await nextAfterClosing, { value: undefined, done: true }); - }, -); +Deno.test("netUdpListenCloseWhileIterating", async function (): Promise { + const socket = Deno.listenDatagram({ port: 8000, transport: "udp" }); + const nextWhileClosing = socket[Symbol.asyncIterator]().next(); + socket.close(); + assertEquals(await nextWhileClosing, { value: undefined, done: true }); -unitTest( - { ignore: Deno.build.os === "windows", perms: { read: true, write: true } }, - async function netUnixListenCloseWhileIterating(): Promise { + const nextAfterClosing = socket[Symbol.asyncIterator]().next(); + assertEquals(await nextAfterClosing, { value: undefined, done: true }); +}); + +Deno.test({ + name: "netUnixListenCloseWhileIterating", + ignore: Deno.build.os === "windows", + async fn(): Promise { const filePath = Deno.makeTempFileSync(); const socket = Deno.listen({ path: filePath, transport: "unix" }); const nextWhileClosing = socket[Symbol.asyncIterator]().next(); @@ -459,11 +405,12 @@ unitTest( const nextAfterClosing = socket[Symbol.asyncIterator]().next(); assertEquals(await nextAfterClosing, { value: undefined, done: true }); }, -); +}); -unitTest( - { ignore: Deno.build.os === "windows", perms: { read: true, write: true } }, - async function netUnixPacketListenCloseWhileIterating(): Promise { +Deno.test({ + name: "netUnixPacketListenCloseWhileIterating", + ignore: Deno.build.os === "windows", + async fn(): Promise { const filePath = Deno.makeTempFileSync(); const socket = Deno.listenDatagram({ path: filePath, @@ -476,15 +423,13 @@ unitTest( const nextAfterClosing = socket[Symbol.asyncIterator]().next(); assertEquals(await nextAfterClosing, { value: undefined, done: true }); }, -); +}); -unitTest( - { - // FIXME(bartlomieju) - ignore: true, - perms: { net: true }, - }, - async function netListenAsyncIterator(): Promise { +Deno.test({ + name: "netListenAsyncIterator", + // FIXME(bartlomieju) + ignore: true, + async fn(): Promise { const addr = { hostname: "127.0.0.1", port: 3500 }; const listener = Deno.listen(addr); const runAsyncIterator = async (): Promise => { @@ -511,91 +456,116 @@ unitTest( listener.close(); conn.close(); }, -); +}); -unitTest( - { - perms: { net: true }, - }, - async function netCloseWriteSuccess() { - const addr = { hostname: "127.0.0.1", port: 3500 }; - const listener = Deno.listen(addr); - const closeDeferred = deferred(); - listener.accept().then(async (conn) => { - await conn.write(new Uint8Array([1, 2, 3])); - await closeDeferred; - conn.close(); - }); - const conn = await Deno.connect(addr); - conn.closeWrite(); // closing write - const buf = new Uint8Array(1024); - // Check read not impacted - const readResult = await conn.read(buf); - assertEquals(3, readResult); - assertEquals(1, buf[0]); - assertEquals(2, buf[1]); - assertEquals(3, buf[2]); - // Verify that the write end of the socket is closed. - // TODO(piscisaureus): assert that thrown error is of a specific type. - await assertThrowsAsync(async () => { - await conn.write(new Uint8Array([1, 2, 3])); - }); - closeDeferred.resolve(); - listener.close(); +Deno.test("netCloseWriteSuccess", async function () { + const addr = { hostname: "127.0.0.1", port: 3500 }; + const listener = Deno.listen(addr); + const closeDeferred = deferred(); + listener.accept().then(async (conn) => { + await conn.write(new Uint8Array([1, 2, 3])); + await closeDeferred; conn.close(); - }, -); + }); + const conn = await Deno.connect(addr); + conn.closeWrite(); // closing write + const buf = new Uint8Array(1024); + // Check read not impacted + const readResult = await conn.read(buf); + assertEquals(3, readResult); + assertEquals(1, buf[0]); + assertEquals(2, buf[1]); + assertEquals(3, buf[2]); + // Verify that the write end of the socket is closed. + // TODO(piscisaureus): assert that thrown error is of a specific type. + await assertThrowsAsync(async () => { + await conn.write(new Uint8Array([1, 2, 3])); + }); + closeDeferred.resolve(); + listener.close(); + conn.close(); +}); -unitTest( - { - perms: { net: true }, - }, - async function netHangsOnClose() { - let acceptedConn: Deno.Conn; - const resolvable = deferred(); - - async function iteratorReq(listener: Deno.Listener): Promise { - const p = new Uint8Array(10); - const conn = await listener.accept(); - acceptedConn = conn; - - try { - while (true) { - const nread = await conn.read(p); - if (nread === null) { - break; - } - await conn.write(new Uint8Array([1, 2, 3])); +Deno.test("netHangsOnClose", async function () { + let acceptedConn: Deno.Conn; + const resolvable = deferred(); + + async function iteratorReq(listener: Deno.Listener): Promise { + const p = new Uint8Array(10); + const conn = await listener.accept(); + acceptedConn = conn; + + try { + while (true) { + const nread = await conn.read(p); + if (nread === null) { + break; } - } catch (err) { - assert(!!err); - assert(err instanceof Deno.errors.BadResource); + await conn.write(new Uint8Array([1, 2, 3])); } - - resolvable.resolve(); + } catch (err) { + assert(!!err); + assert(err instanceof Deno.errors.BadResource); } - const addr = { hostname: "127.0.0.1", port: 3500 }; - const listener = Deno.listen(addr); - iteratorReq(listener); - const conn = await Deno.connect(addr); - await conn.write(new Uint8Array([1, 2, 3, 4])); - const buf = new Uint8Array(10); - await conn.read(buf); - conn!.close(); - acceptedConn!.close(); - listener.close(); - await resolvable; - }, -); + resolvable.resolve(); + } + + const addr = { hostname: "127.0.0.1", port: 3500 }; + const listener = Deno.listen(addr); + iteratorReq(listener); + const conn = await Deno.connect(addr); + await conn.write(new Uint8Array([1, 2, 3, 4])); + const buf = new Uint8Array(10); + await conn.read(buf); + conn!.close(); + acceptedConn!.close(); + listener.close(); + await resolvable; +}); -unitTest( - { - perms: { net: true }, +Deno.test("netExplicitUndefinedHostname", function () { + const listener = Deno.listen({ hostname: undefined, port: 8080 }); + assertEquals((listener.addr as Deno.NetAddr).hostname, "0.0.0.0"); + listener.close(); +}); + +Deno.test({ + name: "netUnixListenWritePermission", + ignore: Deno.build.os === "windows", + async fn(): Promise { + await Deno.permissions.revoke({ name: "write" }); + + assertThrows(() => { + const filePath = Deno.makeTempFileSync(); + const socket = Deno.listen({ + path: filePath, + transport: "unix", + }); + assert(socket.addr.transport === "unix"); + assertEquals(socket.addr.path, filePath); + socket.close(); + }, Deno.errors.PermissionDenied); }, - function netExplicitUndefinedHostname() { - const listener = Deno.listen({ hostname: undefined, port: 8080 }); - assertEquals((listener.addr as Deno.NetAddr).hostname, "0.0.0.0"); - listener.close(); +}); + +Deno.test({ + name: "netUnixListenWritePermission", + ignore: Deno.build.os === "windows", + async fn(): Promise { + await Deno.permissions.revoke({ name: "write" }); + + assertThrows(() => { + const filePath = Deno.makeTempFileSync(); + const socket = Deno.listenDatagram({ + path: filePath, + transport: "unixpacket", + }); + assert(socket.addr.transport === "unixpacket"); + assertEquals(socket.addr.path, filePath); + socket.close(); + }, Deno.errors.PermissionDenied); }, -); +}); + + diff --git a/cli/tests/unit/os_test.ts b/cli/tests/unit/os_test.ts index 9b0f71352b5429..777d52481ae066 100644 --- a/cli/tests/unit/os_test.ts +++ b/cli/tests/unit/os_test.ts @@ -4,10 +4,9 @@ import { assertEquals, assertNotEquals, assertThrows, - unitTest, } from "./test_util.ts"; -unitTest({ perms: { env: true } }, function envSuccess(): void { +Deno.test("envSuccess", function (): void { Deno.env.set("TEST_VAR", "A"); const env = Deno.env.toObject(); Deno.env.set("TEST_VAR", "B"); @@ -15,19 +14,19 @@ unitTest({ perms: { env: true } }, function envSuccess(): void { assertNotEquals(Deno.env.get("TEST_VAR"), env["TEST_VAR"]); }); -unitTest({ perms: { env: true } }, function envNotFound(): void { +Deno.test("envNotFound", function (): void { const r = Deno.env.get("env_var_does_not_exist!"); assertEquals(r, undefined); }); -unitTest({ perms: { env: true } }, function deleteEnv(): void { +Deno.test("deleteEnv", function (): void { Deno.env.set("TEST_VAR", "A"); assertEquals(Deno.env.get("TEST_VAR"), "A"); assertEquals(Deno.env.delete("TEST_VAR"), undefined); assertEquals(Deno.env.get("TEST_VAR"), undefined); }); -unitTest({ perms: { env: true } }, function avoidEmptyNamedEnv(): void { +Deno.test("avoidEmptyNamedEnv", function (): void { assertThrows(() => Deno.env.set("", "v"), TypeError); assertThrows(() => Deno.env.set("a=a", "v"), TypeError); assertThrows(() => Deno.env.set("a\0a", "v"), TypeError); @@ -42,27 +41,13 @@ unitTest({ perms: { env: true } }, function avoidEmptyNamedEnv(): void { assertThrows(() => Deno.env.delete("a\0a"), TypeError); }); -unitTest(function envPermissionDenied1(): void { - assertThrows(() => { - Deno.env.toObject(); - }, Deno.errors.PermissionDenied); -}); - -unitTest(function envPermissionDenied2(): void { - assertThrows(() => { - Deno.env.get("PATH"); - }, Deno.errors.PermissionDenied); -}); - // This test verifies that on Windows, environment variables are // case-insensitive. Case normalization needs be done using the collation // that Windows uses, rather than naively using String.toLowerCase(). -unitTest( - { - ignore: Deno.build.os !== "windows", - perms: { read: true, env: true, run: true }, - }, - async function envCaseInsensitive() { +Deno.test({ + name: "envCaseInsensitive", + ignore: Deno.build.os !== "windows", + async fn() { // Utility function that runs a Deno subprocess with the environment // specified in `inputEnv`. The subprocess reads the environment variables // which are in the keys of `expectedEnv` and writes them to stdout as JSON. @@ -120,80 +105,51 @@ unitTest( { [c2]: "Dz", [uc2]: "DZ", [lc2]: "DZ" }, ); }, -); +}); -unitTest(function osPid(): void { +Deno.test("osPid", function (): void { assert(Deno.pid > 0); }); -unitTest(function osPpid(): void { +Deno.test("osPpid", function (): void { assert(Deno.ppid > 0); }); -unitTest( - { perms: { run: true, read: true } }, - async function osPpidIsEqualToPidOfParentProcess(): Promise { - const decoder = new TextDecoder(); - const process = Deno.run({ - cmd: [Deno.execPath(), "eval", "-p", "--unstable", "Deno.ppid"], - stdout: "piped", - env: { NO_COLOR: "true" }, - }); - const output = await process.output(); - process.close(); - - const expected = Deno.pid; - const actual = parseInt(decoder.decode(output)); - assertEquals(actual, expected); - }, -); +Deno.test("osPpidIsEqualToPidOfParentProcess", async function (): Promise< + void +> { + const decoder = new TextDecoder(); + const process = Deno.run({ + cmd: [Deno.execPath(), "eval", "-p", "--unstable", "Deno.ppid"], + stdout: "piped", + env: { NO_COLOR: "true" }, + }); + const output = await process.output(); + process.close(); -unitTest({ perms: { read: true } }, function execPath(): void { - assertNotEquals(Deno.execPath(), ""); + const expected = Deno.pid; + const actual = parseInt(decoder.decode(output)); + assertEquals(actual, expected); }); -unitTest({ perms: { read: false } }, function execPathPerm(): void { - assertThrows( - () => { - Deno.execPath(); - }, - Deno.errors.PermissionDenied, - "Requires read access to , run again with the --allow-read flag", - ); +Deno.test("execPath", function (): void { + assertNotEquals(Deno.execPath(), ""); }); -unitTest({ perms: { env: true } }, function loadavgSuccess(): void { +Deno.test("loadavgSuccess", function (): void { const load = Deno.loadavg(); assertEquals(load.length, 3); }); -unitTest({ perms: { env: false } }, function loadavgPerm(): void { - assertThrows(() => { - Deno.loadavg(); - }, Deno.errors.PermissionDenied); -}); - -unitTest({ perms: { env: true } }, function hostnameDir(): void { +Deno.test("hostnameDir", function (): void { assertNotEquals(Deno.hostname(), ""); }); -unitTest({ perms: { env: false } }, function hostnamePerm(): void { - assertThrows(() => { - Deno.hostname(); - }, Deno.errors.PermissionDenied); -}); - -unitTest({ perms: { env: true } }, function releaseDir(): void { +Deno.test("releaseDir", function (): void { assertNotEquals(Deno.osRelease(), ""); }); -unitTest({ perms: { env: false } }, function releasePerm(): void { - assertThrows(() => { - Deno.osRelease(); - }, Deno.errors.PermissionDenied); -}); - -unitTest({ perms: { env: true } }, function systemMemoryInfo(): void { +Deno.test("systemMemoryInfo", function (): void { const info = Deno.systemMemoryInfo(); assert(info.total >= 0); assert(info.free >= 0); @@ -204,8 +160,62 @@ unitTest({ perms: { env: true } }, function systemMemoryInfo(): void { assert(info.swapFree >= 0); }); -unitTest({ perms: { env: true } }, function systemCpuInfo(): void { +Deno.test("systemCpuInfo", function (): void { const { cores, speed } = Deno.systemCpuInfo(); assert(cores === undefined || cores > 0); assert(speed === undefined || speed > 0); }); + +Deno.test("envPermissionDenied1", async function (): Promise { + await Deno.permissions.revoke({ name: "env" }); + + assertThrows(() => { + Deno.env.toObject(); + }, Deno.errors.PermissionDenied); +}); + +Deno.test("envPermissionDenied2", async function (): Promise { + await Deno.permissions.revoke({ name: "env" }); + + assertThrows(() => { + Deno.env.get("PATH"); + }, Deno.errors.PermissionDenied); +}); + +Deno.test("releasePerm", async function (): Promise { + await Deno.permissions.revoke({ name: "env" }); + + assertThrows(() => { + Deno.osRelease(); + }, Deno.errors.PermissionDenied); +}); + +Deno.test("loadavgPerm", async function (): Promise { + await Deno.permissions.revoke({ name: "env" }); + + assertThrows(() => { + Deno.loadavg(); + }, Deno.errors.PermissionDenied); +}); + +Deno.test("hostnamePerm", async function (): Promise { + await Deno.permissions.revoke({ name: "env" }); + + assertThrows(() => { + Deno.hostname(); + }, Deno.errors.PermissionDenied); +}); + +Deno.test("execPathPerm", async function (): Promise { + await Deno.permissions.revoke({ name: "read" }); + + assertThrows( + () => { + Deno.execPath(); + }, + Deno.errors.PermissionDenied, + "Requires read access to , run again with the --allow-read flag", + ); +}); + + diff --git a/cli/tests/unit/path_from_url_test.ts b/cli/tests/unit/path_from_url_test.ts index d086ce1dc5fcf4..ce2844beff0482 100644 --- a/cli/tests/unit/path_from_url_test.ts +++ b/cli/tests/unit/path_from_url_test.ts @@ -1,11 +1,12 @@ -import { assertEquals, assertThrows, unitTest } from "./test_util.ts"; +import { assertEquals, assertThrows } from "./test_util.ts"; // @ts-expect-error TypeScript (as of 3.7) does not support indexing namespaces by symbol const { pathFromURL } = Deno[Deno.internal]; -unitTest( - { ignore: Deno.build.os === "windows" }, - function pathFromURLPosix(): void { +Deno.test({ + name: "pathFromURLPosix", + ignore: Deno.build.os === "windows", + fn(): void { assertEquals( pathFromURL(new URL("file:///test/directory")), "/test/directory", @@ -13,11 +14,12 @@ unitTest( assertEquals(pathFromURL(new URL("file:///space_ .txt")), "/space_ .txt"); assertThrows(() => pathFromURL(new URL("https://deno.land/welcome.ts"))); }, -); +}); -unitTest( - { ignore: Deno.build.os !== "windows" }, - function pathFromURLWin32(): void { +Deno.test({ + name: "pathFromUrlWin32", + ignore: Deno.build.os !== "windows", + fn(): void { assertEquals( pathFromURL(new URL("file:///c:/windows/test")), "c:\\windows\\test", @@ -36,4 +38,4 @@ unitTest( * swapped_surrogate_pair_��.txt file:///D:/weird_names/swapped_surrogate_pair_%EF%BF%BD%EF%BF%BD.txt */ }, -); +}); diff --git a/cli/tests/unit/performance_test.ts b/cli/tests/unit/performance_test.ts index 229b38bb8ca5f5..ded10f4d4d1b5d 100644 --- a/cli/tests/unit/performance_test.ts +++ b/cli/tests/unit/performance_test.ts @@ -1,13 +1,7 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { - assert, - assertEquals, - assertThrows, - deferred, - unitTest, -} from "./test_util.ts"; +import { assert, assertEquals, assertThrows, deferred } from "./test_util.ts"; -unitTest({ perms: { hrtime: false } }, async function performanceNow(): Promise< +Deno.test("performanceNow", async function (): Promise< void > { const resolvable = deferred(); @@ -20,7 +14,7 @@ unitTest({ perms: { hrtime: false } }, async function performanceNow(): Promise< await resolvable; }); -unitTest(function performanceMark() { +Deno.test("performanceMark", function () { const mark = performance.mark("test"); assert(mark instanceof PerformanceMark); assertEquals(mark.detail, null); @@ -34,7 +28,7 @@ unitTest(function performanceMark() { assert(markEntries[markEntries.length - 1] === mark); }); -unitTest(function performanceMeasure() { +Deno.test("performanceMeasure", function () { const markName1 = "mark1"; const measureName1 = "measure1"; const measureName2 = "measure2"; @@ -81,17 +75,17 @@ unitTest(function performanceMeasure() { }); }); -unitTest(function performanceIllegalConstructor() { +Deno.test("performanceIllegalConstructor", function () { assertThrows(() => new Performance(), TypeError, "Illegal constructor."); assertEquals(Performance.length, 0); }); -unitTest(function performanceEntryIllegalConstructor() { +Deno.test("performanceEntryIllegalConstructor", function () { assertThrows(() => new PerformanceEntry(), TypeError, "Illegal constructor."); assertEquals(PerformanceEntry.length, 0); }); -unitTest(function performanceMeasureIllegalConstructor() { +Deno.test("performanceMeasureIllegalConstructor", function () { assertThrows( () => new PerformanceMeasure(), TypeError, diff --git a/cli/tests/unit/permissions_test.ts b/cli/tests/unit/permissions_test.ts index 8a6d7e9aa1744e..2efb89fb725c3d 100644 --- a/cli/tests/unit/permissions_test.ts +++ b/cli/tests/unit/permissions_test.ts @@ -4,23 +4,22 @@ import { assertEquals, assertThrows, assertThrowsAsync, - unitTest, } from "./test_util.ts"; -unitTest(async function permissionInvalidName(): Promise { +Deno.test("permissionInvalidName", async function (): Promise { await assertThrowsAsync(async () => { // deno-lint-ignore no-explicit-any await Deno.permissions.query({ name: "foo" as any }); }, TypeError); }); -unitTest(async function permissionNetInvalidHost(): Promise { +Deno.test("permissionNetInvalidHost", async function (): Promise { await assertThrowsAsync(async () => { await Deno.permissions.query({ name: "net", host: ":" }); }, URIError); }); -unitTest(async function permissionQueryReturnsEventTarget() { +Deno.test("permissionQueryReturnsEventTarget", async function () { const status = await Deno.permissions.query({ name: "hrtime" }); assert(["granted", "denied", "prompt"].includes(status.state)); let called = false; @@ -32,7 +31,7 @@ unitTest(async function permissionQueryReturnsEventTarget() { assert(status === (await Deno.permissions.query({ name: "hrtime" }))); }); -unitTest(async function permissionQueryForReadReturnsSameStatus() { +Deno.test("permissionQueryForReadReturnsSameStatus", async function () { const status1 = await Deno.permissions.query({ name: "read", path: ".", @@ -44,12 +43,12 @@ unitTest(async function permissionQueryForReadReturnsSameStatus() { assert(status1 === status2); }); -unitTest(function permissionsIllegalConstructor() { +Deno.test("permissionsIllegalConstructor", function () { assertThrows(() => new Deno.Permissions(), TypeError, "Illegal constructor."); assertEquals(Deno.Permissions.length, 0); }); -unitTest(function permissionStatusIllegalConstructor() { +Deno.test("permissionStatusIllegalConstructor", function () { assertThrows( () => new Deno.PermissionStatus(), TypeError, diff --git a/cli/tests/unit/process_test.ts b/cli/tests/unit/process_test.ts index 9bb4d7fc20c111..d90424d3f086a5 100644 --- a/cli/tests/unit/process_test.ts +++ b/cli/tests/unit/process_test.ts @@ -4,121 +4,96 @@ import { assertEquals, assertStringIncludes, assertThrows, - unitTest, } from "./test_util.ts"; -unitTest({ perms: { read: true } }, function runPermissions(): void { - assertThrows(() => { - Deno.run({ cmd: [Deno.execPath(), "eval", "console.log('hello world')"] }); - }, Deno.errors.PermissionDenied); +Deno.test("runSuccess", async function (): Promise { + const p = Deno.run({ + cmd: [Deno.execPath(), "eval", "console.log('hello world')"], + stdout: "piped", + stderr: "null", + }); + const status = await p.status(); + assertEquals(status.success, true); + assertEquals(status.code, 0); + assertEquals(status.signal, undefined); + p.stdout.close(); + p.close(); }); -unitTest( - { perms: { run: true, read: true } }, - async function runSuccess(): Promise { - const p = Deno.run({ - cmd: [Deno.execPath(), "eval", "console.log('hello world')"], - stdout: "piped", - stderr: "null", - }); - const status = await p.status(); - assertEquals(status.success, true); - assertEquals(status.code, 0); - assertEquals(status.signal, undefined); - p.stdout.close(); - p.close(); - }, -); +Deno.test("runUrl", async function (): Promise { + const p = Deno.run({ + cmd: [ + new URL(`file:///${Deno.execPath()}`), + "eval", + "console.log('hello world')", + ], + stdout: "piped", + stderr: "null", + }); + const status = await p.status(); + assertEquals(status.success, true); + assertEquals(status.code, 0); + assertEquals(status.signal, undefined); + p.stdout.close(); + p.close(); +}); -unitTest( - { perms: { run: true, read: true } }, - async function runUrl(): Promise { - const p = Deno.run({ - cmd: [ - new URL(`file:///${Deno.execPath()}`), - "eval", - "console.log('hello world')", - ], - stdout: "piped", - stderr: "null", - }); - const status = await p.status(); - assertEquals(status.success, true); - assertEquals(status.code, 0); - assertEquals(status.signal, undefined); - p.stdout.close(); - p.close(); - }, -); +Deno.test("runStdinRid0", async function (): Promise< + void +> { + const p = Deno.run({ + cmd: [Deno.execPath(), "eval", "console.log('hello world')"], + stdin: 0, + stdout: "piped", + stderr: "null", + }); + const status = await p.status(); + assertEquals(status.success, true); + assertEquals(status.code, 0); + assertEquals(status.signal, undefined); + p.stdout.close(); + p.close(); +}); -unitTest( - { perms: { run: true, read: true } }, - async function runStdinRid0(): Promise< - void - > { - const p = Deno.run({ +Deno.test("runInvalidStdio", function (): void { + assertThrows(() => + Deno.run({ cmd: [Deno.execPath(), "eval", "console.log('hello world')"], - stdin: 0, - stdout: "piped", - stderr: "null", - }); - const status = await p.status(); - assertEquals(status.success, true); - assertEquals(status.code, 0); - assertEquals(status.signal, undefined); - p.stdout.close(); - p.close(); - }, -); - -unitTest( - { perms: { run: true, read: true } }, - function runInvalidStdio(): void { - assertThrows(() => - Deno.run({ - cmd: [Deno.execPath(), "eval", "console.log('hello world')"], - // @ts-expect-error because Deno.run should throw on invalid stdin. - stdin: "a", - }) - ); - assertThrows(() => - Deno.run({ - cmd: [Deno.execPath(), "eval", "console.log('hello world')"], - // @ts-expect-error because Deno.run should throw on invalid stdout. - stdout: "b", - }) - ); - assertThrows(() => - Deno.run({ - cmd: [Deno.execPath(), "eval", "console.log('hello world')"], - // @ts-expect-error because Deno.run should throw on invalid stderr. - stderr: "c", - }) - ); - }, -); + // @ts-expect-error because Deno.run should throw on invalid stdin. + stdin: "a", + }) + ); + assertThrows(() => + Deno.run({ + cmd: [Deno.execPath(), "eval", "console.log('hello world')"], + // @ts-expect-error because Deno.run should throw on invalid stdout. + stdout: "b", + }) + ); + assertThrows(() => + Deno.run({ + cmd: [Deno.execPath(), "eval", "console.log('hello world')"], + // @ts-expect-error because Deno.run should throw on invalid stderr. + stderr: "c", + }) + ); +}); -unitTest( - { perms: { run: true, read: true } }, - async function runCommandFailedWithCode(): Promise { - const p = Deno.run({ - cmd: [Deno.execPath(), "eval", "Deno.exit(41 + 1)"], - }); - const status = await p.status(); - assertEquals(status.success, false); - assertEquals(status.code, 42); - assertEquals(status.signal, undefined); - p.close(); - }, -); +Deno.test("runCommandFailedWithCode", async function (): Promise { + const p = Deno.run({ + cmd: [Deno.execPath(), "eval", "Deno.exit(41 + 1)"], + }); + const status = await p.status(); + assertEquals(status.success, false); + assertEquals(status.code, 42); + assertEquals(status.signal, undefined); + p.close(); +}); -unitTest( - { - // No signals on windows. - ignore: Deno.build.os === "windows", - perms: { run: true, read: true }, - }, - async function runCommandFailedWithSignal(): Promise { +Deno.test({ + name: "runCommandFailedWithSignal", + ignore: Deno.build.os === "windows", + async fn(): Promise { const p = Deno.run({ cmd: [Deno.execPath(), "eval", "--unstable", "Deno.kill(Deno.pid, 9)"], }); @@ -128,9 +103,9 @@ unitTest( assertEquals(status.signal, 9); p.close(); }, -); +}); -unitTest({ perms: { run: true } }, function runNotFound(): void { +Deno.test("runNotFound", function (): void { let error; try { Deno.run({ cmd: ["this file hopefully doesn't exist"] }); @@ -141,15 +116,13 @@ unitTest({ perms: { run: true } }, function runNotFound(): void { assert(error instanceof Deno.errors.NotFound); }); -unitTest( - { perms: { write: true, run: true, read: true } }, - async function runWithCwdIsAsync(): Promise { - const enc = new TextEncoder(); - const cwd = await Deno.makeTempDir({ prefix: "deno_command_test" }); +Deno.test("runWithCwdIsAsync", async function (): Promise { + const enc = new TextEncoder(); + const cwd = await Deno.makeTempDir({ prefix: "deno_command_test" }); - const exitCodeFile = "deno_was_here"; - const programFile = "poll_exit.ts"; - const program = ` + const exitCodeFile = "deno_was_here"; + const programFile = "poll_exit.ts"; + const program = ` async function tryExit() { try { const code = parseInt(await Deno.readTextFile("${exitCodeFile}")); @@ -163,298 +136,267 @@ async function tryExit() { tryExit(); `; - Deno.writeFileSync(`${cwd}/${programFile}`, enc.encode(program)); - const p = Deno.run({ - cwd, - cmd: [Deno.execPath(), "run", "--allow-read", programFile], - }); + Deno.writeFileSync(`${cwd}/${programFile}`, enc.encode(program)); + const p = Deno.run({ + cwd, + cmd: [Deno.execPath(), "run", "--allow-read", programFile], + }); - // Write the expected exit code *after* starting deno. - // This is how we verify that `run()` is actually asynchronous. - const code = 84; - Deno.writeFileSync(`${cwd}/${exitCodeFile}`, enc.encode(`${code}`)); + // Write the expected exit code *after* starting deno. + // This is how we verify that `run()` is actually asynchronous. + const code = 84; + Deno.writeFileSync(`${cwd}/${exitCodeFile}`, enc.encode(`${code}`)); - const status = await p.status(); - assertEquals(status.success, false); - assertEquals(status.code, code); - assertEquals(status.signal, undefined); - p.close(); - }, -); + const status = await p.status(); + assertEquals(status.success, false); + assertEquals(status.code, code); + assertEquals(status.signal, undefined); + p.close(); +}); -unitTest( - { perms: { run: true, read: true } }, - async function runStdinPiped(): Promise< - void - > { - const p = Deno.run({ - cmd: [ - Deno.execPath(), - "eval", - "if (new TextDecoder().decode(await Deno.readAll(Deno.stdin)) !== 'hello') throw new Error('Expected \\'hello\\'')", - ], - stdin: "piped", - }); - assert(p.stdin); - assert(!p.stdout); - assert(!p.stderr); +Deno.test("runStdinPiped", async function (): Promise< + void +> { + const p = Deno.run({ + cmd: [ + Deno.execPath(), + "eval", + "if (new TextDecoder().decode(await Deno.readAll(Deno.stdin)) !== 'hello') throw new Error('Expected \\'hello\\'')", + ], + stdin: "piped", + }); + assert(p.stdin); + assert(!p.stdout); + assert(!p.stderr); - const msg = new TextEncoder().encode("hello"); - const n = await p.stdin.write(msg); - assertEquals(n, msg.byteLength); + const msg = new TextEncoder().encode("hello"); + const n = await p.stdin.write(msg); + assertEquals(n, msg.byteLength); - p.stdin.close(); + p.stdin.close(); - const status = await p.status(); - assertEquals(status.success, true); - assertEquals(status.code, 0); - assertEquals(status.signal, undefined); - p.close(); - }, -); + const status = await p.status(); + assertEquals(status.success, true); + assertEquals(status.code, 0); + assertEquals(status.signal, undefined); + p.close(); +}); -unitTest( - { perms: { run: true, read: true } }, - async function runStdoutPiped(): Promise< - void - > { - const p = Deno.run({ - cmd: [ - Deno.execPath(), - "eval", - "await Deno.stdout.write(new TextEncoder().encode('hello'))", - ], - stdout: "piped", - }); - assert(!p.stdin); - assert(!p.stderr); - - const data = new Uint8Array(10); - let r = await p.stdout.read(data); - if (r === null) { - throw new Error("p.stdout.read(...) should not be null"); - } - assertEquals(r, 5); - const s = new TextDecoder().decode(data.subarray(0, r)); - assertEquals(s, "hello"); - r = await p.stdout.read(data); - assertEquals(r, null); - p.stdout.close(); +Deno.test("runStdoutPiped", async function (): Promise< + void +> { + const p = Deno.run({ + cmd: [ + Deno.execPath(), + "eval", + "await Deno.stdout.write(new TextEncoder().encode('hello'))", + ], + stdout: "piped", + }); + assert(!p.stdin); + assert(!p.stderr); - const status = await p.status(); - assertEquals(status.success, true); - assertEquals(status.code, 0); - assertEquals(status.signal, undefined); - p.close(); - }, -); + const data = new Uint8Array(10); + let r = await p.stdout.read(data); + if (r === null) { + throw new Error("p.stdout.read(...) should not be null"); + } + assertEquals(r, 5); + const s = new TextDecoder().decode(data.subarray(0, r)); + assertEquals(s, "hello"); + r = await p.stdout.read(data); + assertEquals(r, null); + p.stdout.close(); + + const status = await p.status(); + assertEquals(status.success, true); + assertEquals(status.code, 0); + assertEquals(status.signal, undefined); + p.close(); +}); -unitTest( - { perms: { run: true, read: true } }, - async function runStderrPiped(): Promise< - void - > { - const p = Deno.run({ - cmd: [ - Deno.execPath(), - "eval", - "await Deno.stderr.write(new TextEncoder().encode('hello'))", - ], - stderr: "piped", - }); - assert(!p.stdin); - assert(!p.stdout); - - const data = new Uint8Array(10); - let r = await p.stderr.read(data); - if (r === null) { - throw new Error("p.stderr.read should not return null here"); - } - assertEquals(r, 5); - const s = new TextDecoder().decode(data.subarray(0, r)); - assertEquals(s, "hello"); - r = await p.stderr.read(data); - assertEquals(r, null); - p.stderr!.close(); +Deno.test("runStderrPiped", async function (): Promise< + void +> { + const p = Deno.run({ + cmd: [ + Deno.execPath(), + "eval", + "await Deno.stderr.write(new TextEncoder().encode('hello'))", + ], + stderr: "piped", + }); + assert(!p.stdin); + assert(!p.stdout); - const status = await p.status(); - assertEquals(status.success, true); - assertEquals(status.code, 0); - assertEquals(status.signal, undefined); - p.close(); - }, -); + const data = new Uint8Array(10); + let r = await p.stderr.read(data); + if (r === null) { + throw new Error("p.stderr.read should not return null here"); + } + assertEquals(r, 5); + const s = new TextDecoder().decode(data.subarray(0, r)); + assertEquals(s, "hello"); + r = await p.stderr.read(data); + assertEquals(r, null); + p.stderr!.close(); + + const status = await p.status(); + assertEquals(status.success, true); + assertEquals(status.code, 0); + assertEquals(status.signal, undefined); + p.close(); +}); -unitTest( - { perms: { run: true, read: true } }, - async function runOutput(): Promise { - const p = Deno.run({ - cmd: [ - Deno.execPath(), - "eval", - "await Deno.stdout.write(new TextEncoder().encode('hello'))", - ], - stdout: "piped", - }); - const output = await p.output(); - const s = new TextDecoder().decode(output); - assertEquals(s, "hello"); - p.close(); - }, -); +Deno.test("runOutput", async function (): Promise { + const p = Deno.run({ + cmd: [ + Deno.execPath(), + "eval", + "await Deno.stdout.write(new TextEncoder().encode('hello'))", + ], + stdout: "piped", + }); + const output = await p.output(); + const s = new TextDecoder().decode(output); + assertEquals(s, "hello"); + p.close(); +}); -unitTest( - { perms: { run: true, read: true } }, - async function runStderrOutput(): Promise< - void - > { - const p = Deno.run({ - cmd: [ - Deno.execPath(), - "eval", - "await Deno.stderr.write(new TextEncoder().encode('error'))", - ], - stderr: "piped", - }); - const error = await p.stderrOutput(); - const s = new TextDecoder().decode(error); - assertEquals(s, "error"); - p.close(); - }, -); - -unitTest( - { perms: { run: true, write: true, read: true } }, - async function runRedirectStdoutStderr(): Promise { - const tempDir = await Deno.makeTempDir(); - const fileName = tempDir + "/redirected_stdio.txt"; - const file = await Deno.open(fileName, { - create: true, - write: true, - }); +Deno.test("runStderrOutput", async function (): Promise< + void +> { + const p = Deno.run({ + cmd: [ + Deno.execPath(), + "eval", + "await Deno.stderr.write(new TextEncoder().encode('error'))", + ], + stderr: "piped", + }); + const error = await p.stderrOutput(); + const s = new TextDecoder().decode(error); + assertEquals(s, "error"); + p.close(); +}); - const p = Deno.run({ - cmd: [ - Deno.execPath(), - "eval", - "Deno.stderr.write(new TextEncoder().encode('error\\n')); Deno.stdout.write(new TextEncoder().encode('output\\n'));", - ], - stdout: file.rid, - stderr: file.rid, - }); +Deno.test("runRedirectStdoutStderr", async function (): Promise { + const tempDir = await Deno.makeTempDir(); + const fileName = tempDir + "/redirected_stdio.txt"; + const file = await Deno.open(fileName, { + create: true, + write: true, + }); - await p.status(); - p.close(); - file.close(); + const p = Deno.run({ + cmd: [ + Deno.execPath(), + "eval", + "Deno.stderr.write(new TextEncoder().encode('error\\n')); Deno.stdout.write(new TextEncoder().encode('output\\n'));", + ], + stdout: file.rid, + stderr: file.rid, + }); - const fileContents = await Deno.readFile(fileName); - const decoder = new TextDecoder(); - const text = decoder.decode(fileContents); + await p.status(); + p.close(); + file.close(); - assertStringIncludes(text, "error"); - assertStringIncludes(text, "output"); - }, -); + const fileContents = await Deno.readFile(fileName); + const decoder = new TextDecoder(); + const text = decoder.decode(fileContents); -unitTest( - { perms: { run: true, write: true, read: true } }, - async function runRedirectStdin(): Promise { - const tempDir = await Deno.makeTempDir(); - const fileName = tempDir + "/redirected_stdio.txt"; - const encoder = new TextEncoder(); - await Deno.writeFile(fileName, encoder.encode("hello")); - const file = await Deno.open(fileName); + assertStringIncludes(text, "error"); + assertStringIncludes(text, "output"); +}); - const p = Deno.run({ - cmd: [ - Deno.execPath(), - "eval", - "if (new TextDecoder().decode(await Deno.readAll(Deno.stdin)) !== 'hello') throw new Error('Expected \\'hello\\'')", - ], - stdin: file.rid, - }); +Deno.test("runRedirectStdin", async function (): Promise { + const tempDir = await Deno.makeTempDir(); + const fileName = tempDir + "/redirected_stdio.txt"; + const encoder = new TextEncoder(); + await Deno.writeFile(fileName, encoder.encode("hello")); + const file = await Deno.open(fileName); - const status = await p.status(); - assertEquals(status.code, 0); - p.close(); - file.close(); - }, -); + const p = Deno.run({ + cmd: [ + Deno.execPath(), + "eval", + "if (new TextDecoder().decode(await Deno.readAll(Deno.stdin)) !== 'hello') throw new Error('Expected \\'hello\\'')", + ], + stdin: file.rid, + }); -unitTest( - { perms: { run: true, read: true } }, - async function runEnv(): Promise { - const p = Deno.run({ - cmd: [ - Deno.execPath(), - "eval", - "Deno.stdout.write(new TextEncoder().encode(Deno.env.get('FOO') + Deno.env.get('BAR')))", - ], - env: { - FOO: "0123", - BAR: "4567", - }, - stdout: "piped", - }); - const output = await p.output(); - const s = new TextDecoder().decode(output); - assertEquals(s, "01234567"); - p.close(); - }, -); + const status = await p.status(); + assertEquals(status.code, 0); + p.close(); + file.close(); +}); -unitTest( - { perms: { run: true, read: true } }, - async function runClose(): Promise { - const p = Deno.run({ - cmd: [ - Deno.execPath(), - "eval", - "setTimeout(() => Deno.stdout.write(new TextEncoder().encode('error')), 10000)", - ], - stderr: "piped", - }); - assert(!p.stdin); - assert(!p.stdout); +Deno.test("runEnv", async function (): Promise { + const p = Deno.run({ + cmd: [ + Deno.execPath(), + "eval", + "Deno.stdout.write(new TextEncoder().encode(Deno.env.get('FOO') + Deno.env.get('BAR')))", + ], + env: { + FOO: "0123", + BAR: "4567", + }, + stdout: "piped", + }); + const output = await p.output(); + const s = new TextDecoder().decode(output); + assertEquals(s, "01234567"); + p.close(); +}); - p.close(); +Deno.test("runClose", async function (): Promise { + const p = Deno.run({ + cmd: [ + Deno.execPath(), + "eval", + "setTimeout(() => Deno.stdout.write(new TextEncoder().encode('error')), 10000)", + ], + stderr: "piped", + }); + assert(!p.stdin); + assert(!p.stdout); - const data = new Uint8Array(10); - const r = await p.stderr.read(data); - assertEquals(r, null); - p.stderr.close(); - }, -); + p.close(); -unitTest( - { perms: { run: true, read: true } }, - async function runKillAfterStatus(): Promise { - const p = Deno.run({ - cmd: [Deno.execPath(), "eval", 'console.log("hello")'], - }); - await p.status(); - - let error = null; - try { - p.kill(Deno.Signal.SIGTERM); - } catch (e) { - error = e; - } - - assert( - error instanceof Deno.errors.NotFound || - // On Windows, the underlying Windows API may return - // `ERROR_ACCESS_DENIED` when the process has exited, but hasn't been - // completely cleaned up yet and its `pid` is still valid. - (Deno.build.os === "windows" && - error instanceof Deno.errors.PermissionDenied), - ); + const data = new Uint8Array(10); + const r = await p.stderr.read(data); + assertEquals(r, null); + p.stderr.close(); +}); - p.close(); - }, -); +Deno.test("runKillAfterStatus", async function (): Promise { + const p = Deno.run({ + cmd: [Deno.execPath(), "eval", 'console.log("hello")'], + }); + await p.status(); + + let error = null; + try { + p.kill(Deno.Signal.SIGTERM); + } catch (e) { + error = e; + } + + assert( + error instanceof Deno.errors.NotFound || + // On Windows, the underlying Windows API may return + // `ERROR_ACCESS_DENIED` when the process has exited, but hasn't been + // completely cleaned up yet and its `pid` is still valid. + (Deno.build.os === "windows" && + error instanceof Deno.errors.PermissionDenied), + ); -unitTest(function signalNumbers(): void { + p.close(); +}); + +Deno.test("signalNumbers", function (): void { if (Deno.build.os === "darwin") { assertEquals(Deno.Signal.SIGSTOP, 17); } else if (Deno.build.os === "linux") { @@ -462,42 +404,29 @@ unitTest(function signalNumbers(): void { } }); -unitTest(function killPermissions(): void { - assertThrows(() => { - // Unlike the other test cases, we don't have permission to spawn a - // subprocess we can safely kill. Instead we send SIGCONT to the current - // process - assuming that Deno does not have a special handler set for it - // and will just continue even if a signal is erroneously sent. - Deno.kill(Deno.pid, Deno.Signal.SIGCONT); - }, Deno.errors.PermissionDenied); -}); - -unitTest( - { perms: { run: true, read: true } }, - async function killSuccess(): Promise { - const p = Deno.run({ - cmd: [Deno.execPath(), "eval", "setTimeout(() => {}, 10000)"], - }); +Deno.test("killSuccess", async function (): Promise { + const p = Deno.run({ + cmd: [Deno.execPath(), "eval", "setTimeout(() => {}, 10000)"], + }); - assertEquals(Deno.Signal.SIGINT, 2); - Deno.kill(p.pid, Deno.Signal.SIGINT); - const status = await p.status(); + assertEquals(Deno.Signal.SIGINT, 2); + Deno.kill(p.pid, Deno.Signal.SIGINT); + const status = await p.status(); - assertEquals(status.success, false); - try { - assertEquals(status.code, 128 + Deno.Signal.SIGINT); - assertEquals(status.signal, Deno.Signal.SIGINT); - } catch { - // TODO(nayeemrmn): On Windows sometimes the following values are given - // instead. Investigate and remove this catch when fixed. - assertEquals(status.code, 1); - assertEquals(status.signal, undefined); - } - p.close(); - }, -); + assertEquals(status.success, false); + try { + assertEquals(status.code, 128 + Deno.Signal.SIGINT); + assertEquals(status.signal, Deno.Signal.SIGINT); + } catch { + // TODO(nayeemrmn): On Windows sometimes the following values are given + // instead. Investigate and remove this catch when fixed. + assertEquals(status.code, 1); + assertEquals(status.signal, undefined); + } + p.close(); +}); -unitTest({ perms: { run: true, read: true } }, function killFailed(): void { +Deno.test("killFailed", function (): void { const p = Deno.run({ cmd: [Deno.execPath(), "eval", "setTimeout(() => {}, 10000)"], }); @@ -510,3 +439,25 @@ unitTest({ perms: { run: true, read: true } }, function killFailed(): void { p.close(); }); + +Deno.test("killPermissions", async function (): Promise { + await Deno.permissions.revoke({ name: "run" }); + + assertThrows(() => { + // Unlike the other test cases, we don't have permission to spawn a + // subprocess we can safely kill. Instead we send SIGCONT to the current + // process - assuming that Deno does not have a special handler set for it + // and will just continue even if a signal is erroneously sent. + Deno.kill(Deno.pid, Deno.Signal.SIGCONT); + }, Deno.errors.PermissionDenied); +}); + +Deno.test("runPermissions", async function (): Promise { + await Deno.permissions.revoke({ name: "run" }); + + assertThrows(() => { + Deno.run({ + cmd: [Deno.execPath(), "eval", "console.log('hello world')"], + }); + }, Deno.errors.PermissionDenied); +}); diff --git a/cli/tests/unit/progressevent_test.ts b/cli/tests/unit/progressevent_test.ts index 6f165de2cf1564..b1dcb2d569074e 100644 --- a/cli/tests/unit/progressevent_test.ts +++ b/cli/tests/unit/progressevent_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assertEquals, unitTest } from "./test_util.ts"; +import { assertEquals } from "./test_util.ts"; -unitTest(function progressEventConstruct(): void { +Deno.test("progressEventConstruct", function (): void { const progressEventDefs = new ProgressEvent("progressEventType", {}); assertEquals(progressEventDefs.lengthComputable, false); assertEquals(progressEventDefs.loaded, 0); diff --git a/cli/tests/unit/read_dir_test.ts b/cli/tests/unit/read_dir_test.ts index 829f7bfa22adaa..776e84ab780807 100644 --- a/cli/tests/unit/read_dir_test.ts +++ b/cli/tests/unit/read_dir_test.ts @@ -5,7 +5,6 @@ import { assertThrows, assertThrowsAsync, pathToAbsoluteFileUrl, - unitTest, } from "./test_util.ts"; function assertSameContent(files: Deno.DirEntry[]): void { @@ -21,35 +20,29 @@ function assertSameContent(files: Deno.DirEntry[]): void { assertEquals(counter, 1); } -unitTest({ perms: { read: true } }, function readDirSyncSuccess(): void { +Deno.test("readDirSyncSuccess", function (): void { const files = [...Deno.readDirSync("cli/tests/")]; assertSameContent(files); }); -unitTest({ perms: { read: true } }, function readDirSyncWithUrl(): void { +Deno.test("readDirSyncWithUrl", function (): void { const files = [...Deno.readDirSync(pathToAbsoluteFileUrl("cli/tests"))]; assertSameContent(files); }); -unitTest({ perms: { read: false } }, function readDirSyncPerm(): void { - assertThrows(() => { - Deno.readDirSync("tests/"); - }, Deno.errors.PermissionDenied); -}); - -unitTest({ perms: { read: true } }, function readDirSyncNotDir(): void { +Deno.test("readDirSyncNotDir", function (): void { assertThrows(() => { Deno.readDirSync("cli/tests/fixture.json"); }, Error); }); -unitTest({ perms: { read: true } }, function readDirSyncNotFound(): void { +Deno.test("readDirSyncNotFound", function (): void { assertThrows(() => { Deno.readDirSync("bad_dir_name"); }, Deno.errors.NotFound); }); -unitTest({ perms: { read: true } }, async function readDirSuccess(): Promise< +Deno.test("readDirSuccess", async function (): Promise< void > { const files = []; @@ -59,7 +52,7 @@ unitTest({ perms: { read: true } }, async function readDirSuccess(): Promise< assertSameContent(files); }); -unitTest({ perms: { read: true } }, async function readDirWithUrl(): Promise< +Deno.test("readDirWithUrl", async function (): Promise< void > { const files = []; @@ -71,30 +64,45 @@ unitTest({ perms: { read: true } }, async function readDirWithUrl(): Promise< assertSameContent(files); }); -unitTest({ perms: { read: false } }, async function readDirPerm(): Promise< - void -> { - await assertThrowsAsync(async () => { - await Deno.readDir("tests/")[Symbol.asyncIterator]().next(); - }, Deno.errors.PermissionDenied); -}); - -unitTest( - { perms: { read: true }, ignore: Deno.build.os == "windows" }, - async function readDirDevFd(): Promise< +Deno.test({ + name: "readDirDevFd", + ignore: Deno.build.os == "windows", + async fn(): Promise< void > { for await (const _ of Deno.readDir("/dev/fd")) { // We don't actually care whats in here; just that we don't panic on non regular entries } }, -); +}); -unitTest( - { perms: { read: true }, ignore: Deno.build.os == "windows" }, - function readDirDevFdSync(): void { +Deno.test({ + name: "readDirDevFdSync", + ignore: Deno.build.os == "windows", + fn(): void { for (const _ of Deno.readDirSync("/dev/fd")) { // We don't actually care whats in here; just that we don't panic on non regular file entries } }, -); +}); + +Deno.test("readDirPerm", async function (): Promise< + void +> { + await Deno.permissions.revoke({ name: "read" }); + + await assertThrowsAsync(async () => { + await Deno.readDir("tests/")[Symbol.asyncIterator]().next(); + }, Deno.errors.PermissionDenied); +}); + + +Deno.test("readDirSyncPerm", async function (): Promise { + await Deno.permissions.revoke({ name: "read" }); + + assertThrows(() => { + Deno.readDirSync("tests/"); + }, Deno.errors.PermissionDenied); +}); + + diff --git a/cli/tests/unit/read_file_test.ts b/cli/tests/unit/read_file_test.ts index 5594eb4ae3ae98..709a0540122a65 100644 --- a/cli/tests/unit/read_file_test.ts +++ b/cli/tests/unit/read_file_test.ts @@ -5,10 +5,9 @@ import { assertThrows, assertThrowsAsync, pathToAbsoluteFileUrl, - unitTest, } from "./test_util.ts"; -unitTest({ perms: { read: true } }, function readFileSyncSuccess(): void { +Deno.test("readFileSyncSuccess", function (): void { const data = Deno.readFileSync("cli/tests/fixture.json"); assert(data.byteLength > 0); const decoder = new TextDecoder("utf-8"); @@ -17,7 +16,7 @@ unitTest({ perms: { read: true } }, function readFileSyncSuccess(): void { assertEquals(pkg.name, "deno"); }); -unitTest({ perms: { read: true } }, function readFileSyncUrl(): void { +Deno.test("readFileSyncUrl", function (): void { const data = Deno.readFileSync( pathToAbsoluteFileUrl("cli/tests/fixture.json"), ); @@ -28,19 +27,13 @@ unitTest({ perms: { read: true } }, function readFileSyncUrl(): void { assertEquals(pkg.name, "deno"); }); -unitTest({ perms: { read: false } }, function readFileSyncPerm(): void { - assertThrows(() => { - Deno.readFileSync("cli/tests/fixture.json"); - }, Deno.errors.PermissionDenied); -}); - -unitTest({ perms: { read: true } }, function readFileSyncNotFound(): void { +Deno.test("readFileSyncNotFound", function (): void { assertThrows(() => { Deno.readFileSync("bad_filename"); }, Deno.errors.NotFound); }); -unitTest({ perms: { read: true } }, async function readFileUrl(): Promise< +Deno.test("readFileUrl", async function (): Promise< void > { const data = await Deno.readFile( @@ -53,7 +46,7 @@ unitTest({ perms: { read: true } }, async function readFileUrl(): Promise< assertEquals(pkg.name, "deno"); }); -unitTest({ perms: { read: true } }, async function readFileSuccess(): Promise< +Deno.test("readFileSuccess", async function (): Promise< void > { const data = await Deno.readFile("cli/tests/fixture.json"); @@ -64,16 +57,26 @@ unitTest({ perms: { read: true } }, async function readFileSuccess(): Promise< assertEquals(pkg.name, "deno"); }); -unitTest({ perms: { read: false } }, async function readFilePerm(): Promise< +Deno.test("readFileSyncLoop", function (): void { + for (let i = 0; i < 256; i++) { + Deno.readFileSync("cli/tests/fixture.json"); + } +}); + +Deno.test("readFileSyncPerm", async function (): Promise { + await Deno.permissions.revoke({ name: "read" }); + + assertThrows(() => { + Deno.readFileSync("cli/tests/fixture.json"); + }, Deno.errors.PermissionDenied); +}); + +Deno.test("readFilePerm", async function (): Promise< void > { + await Deno.permissions.revoke({ name: "read" }); + await assertThrowsAsync(async () => { await Deno.readFile("cli/tests/fixture.json"); }, Deno.errors.PermissionDenied); }); - -unitTest({ perms: { read: true } }, function readFileSyncLoop(): void { - for (let i = 0; i < 256; i++) { - Deno.readFileSync("cli/tests/fixture.json"); - } -}); diff --git a/cli/tests/unit/read_link_test.ts b/cli/tests/unit/read_link_test.ts index cab27cbdcfa679..b1e21de6f02aa7 100644 --- a/cli/tests/unit/read_link_test.ts +++ b/cli/tests/unit/read_link_test.ts @@ -4,85 +4,74 @@ import { assertThrows, assertThrowsAsync, pathToAbsoluteFileUrl, - unitTest, } from "./test_util.ts"; -unitTest( - { perms: { write: true, read: true } }, - function readLinkSyncSuccess(): void { - const testDir = Deno.makeTempDirSync(); - const target = testDir + - (Deno.build.os == "windows" ? "\\target" : "/target"); - const symlink = testDir + - (Deno.build.os == "windows" ? "\\symlink" : "/symlink"); - Deno.mkdirSync(target); - Deno.symlinkSync(target, symlink); - const targetPath = Deno.readLinkSync(symlink); - assertEquals(targetPath, target); - }, -); - -unitTest( - { perms: { write: true, read: true } }, - function readLinkSyncUrlSuccess(): void { - const testDir = Deno.makeTempDirSync(); - const target = testDir + - (Deno.build.os == "windows" ? "\\target" : "/target"); - const symlink = testDir + - (Deno.build.os == "windows" ? "\\symlink" : "/symlink"); - Deno.mkdirSync(target); - Deno.symlinkSync(target, symlink); - const targetPath = Deno.readLinkSync(pathToAbsoluteFileUrl(symlink)); - assertEquals(targetPath, target); - }, -); +Deno.test("readLinkSyncSuccess", function (): void { + const testDir = Deno.makeTempDirSync(); + const target = testDir + + (Deno.build.os == "windows" ? "\\target" : "/target"); + const symlink = testDir + + (Deno.build.os == "windows" ? "\\symlink" : "/symlink"); + Deno.mkdirSync(target); + Deno.symlinkSync(target, symlink); + const targetPath = Deno.readLinkSync(symlink); + assertEquals(targetPath, target); +}); -unitTest({ perms: { read: false } }, function readLinkSyncPerm(): void { - assertThrows(() => { - Deno.readLinkSync("/symlink"); - }, Deno.errors.PermissionDenied); +Deno.test("readLinkSyncUrlSuccess", function (): void { + const testDir = Deno.makeTempDirSync(); + const target = testDir + + (Deno.build.os == "windows" ? "\\target" : "/target"); + const symlink = testDir + + (Deno.build.os == "windows" ? "\\symlink" : "/symlink"); + Deno.mkdirSync(target); + Deno.symlinkSync(target, symlink); + const targetPath = Deno.readLinkSync(pathToAbsoluteFileUrl(symlink)); + assertEquals(targetPath, target); }); -unitTest({ perms: { read: true } }, function readLinkSyncNotFound(): void { +Deno.test("readLinkSyncNotFound", function (): void { assertThrows(() => { Deno.readLinkSync("bad_filename"); }, Deno.errors.NotFound); }); -unitTest( - { perms: { write: true, read: true } }, - async function readLinkSuccess(): Promise { - const testDir = Deno.makeTempDirSync(); - const target = testDir + - (Deno.build.os == "windows" ? "\\target" : "/target"); - const symlink = testDir + - (Deno.build.os == "windows" ? "\\symlink" : "/symlink"); - Deno.mkdirSync(target); - Deno.symlinkSync(target, symlink); - const targetPath = await Deno.readLink(symlink); - assertEquals(targetPath, target); - }, -); +Deno.test("readLinkSuccess", async function (): Promise { + const testDir = Deno.makeTempDirSync(); + const target = testDir + + (Deno.build.os == "windows" ? "\\target" : "/target"); + const symlink = testDir + + (Deno.build.os == "windows" ? "\\symlink" : "/symlink"); + Deno.mkdirSync(target); + Deno.symlinkSync(target, symlink); + const targetPath = await Deno.readLink(symlink); + assertEquals(targetPath, target); +}); + +Deno.test("readLinkUrlSuccess", async function (): Promise { + const testDir = Deno.makeTempDirSync(); + const target = testDir + + (Deno.build.os == "windows" ? "\\target" : "/target"); + const symlink = testDir + + (Deno.build.os == "windows" ? "\\symlink" : "/symlink"); + Deno.mkdirSync(target); + Deno.symlinkSync(target, symlink); + const targetPath = await Deno.readLink(pathToAbsoluteFileUrl(symlink)); + assertEquals(targetPath, target); +}); -unitTest( - { perms: { write: true, read: true } }, - async function readLinkUrlSuccess(): Promise { - const testDir = Deno.makeTempDirSync(); - const target = testDir + - (Deno.build.os == "windows" ? "\\target" : "/target"); - const symlink = testDir + - (Deno.build.os == "windows" ? "\\symlink" : "/symlink"); - Deno.mkdirSync(target); - Deno.symlinkSync(target, symlink); - const targetPath = await Deno.readLink(pathToAbsoluteFileUrl(symlink)); - assertEquals(targetPath, target); - }, -); +Deno.test("readLinkPerm", async function (): Promise { + await Deno.permissions.revoke({ name: "read" }); -unitTest({ perms: { read: false } }, async function readLinkPerm(): Promise< - void -> { await assertThrowsAsync(async () => { await Deno.readLink("/symlink"); }, Deno.errors.PermissionDenied); }); + +Deno.test("readLinkSyncPerm", async function (): Promise { + await Deno.permissions.revoke({ name: "read" }); + + assertThrows(() => { + Deno.readLinkSync("/symlink"); + }, Deno.errors.PermissionDenied); +}); diff --git a/cli/tests/unit/read_text_file_test.ts b/cli/tests/unit/read_text_file_test.ts index dc6a901bb6a7aa..688f2fc5686556 100644 --- a/cli/tests/unit/read_text_file_test.ts +++ b/cli/tests/unit/read_text_file_test.ts @@ -4,17 +4,16 @@ import { assertThrows, assertThrowsAsync, pathToAbsoluteFileUrl, - unitTest, } from "./test_util.ts"; -unitTest({ perms: { read: true } }, function readTextFileSyncSuccess(): void { +Deno.test("readTextFileSyncSuccess", function (): void { const data = Deno.readTextFileSync("cli/tests/fixture.json"); assert(data.length > 0); const pkg = JSON.parse(data); assertEquals(pkg.name, "deno"); }); -unitTest({ perms: { read: true } }, function readTextFileSyncByUrl(): void { +Deno.test("readTextFileSyncByUrl", function (): void { const data = Deno.readTextFileSync( pathToAbsoluteFileUrl("cli/tests/fixture.json"), ); @@ -23,29 +22,20 @@ unitTest({ perms: { read: true } }, function readTextFileSyncByUrl(): void { assertEquals(pkg.name, "deno"); }); -unitTest({ perms: { read: false } }, function readTextFileSyncPerm(): void { - assertThrows(() => { - Deno.readTextFileSync("cli/tests/fixture.json"); - }, Deno.errors.PermissionDenied); -}); - -unitTest({ perms: { read: true } }, function readTextFileSyncNotFound(): void { +Deno.test("readTextFileSyncNotFound", function (): void { assertThrows(() => { Deno.readTextFileSync("bad_filename"); }, Deno.errors.NotFound); }); -unitTest( - { perms: { read: true } }, - async function readTextFileSuccess(): Promise { - const data = await Deno.readTextFile("cli/tests/fixture.json"); - assert(data.length > 0); - const pkg = JSON.parse(data); - assertEquals(pkg.name, "deno"); - }, -); +Deno.test("readTextFileSuccess", async function (): Promise { + const data = await Deno.readTextFile("cli/tests/fixture.json"); + assert(data.length > 0); + const pkg = JSON.parse(data); + assertEquals(pkg.name, "deno"); +}); -unitTest({ perms: { read: true } }, async function readTextFileByUrl(): Promise< +Deno.test("readTextFileByUrl", async function (): Promise< void > { const data = await Deno.readTextFile( @@ -56,16 +46,27 @@ unitTest({ perms: { read: true } }, async function readTextFileByUrl(): Promise< assertEquals(pkg.name, "deno"); }); -unitTest({ perms: { read: false } }, async function readTextFilePerm(): Promise< +Deno.test("readTextFileSyncLoop", function (): void { + for (let i = 0; i < 256; i++) { + Deno.readTextFileSync("cli/tests/fixture.json"); + } +}); + +Deno.test("readTextFilePerm", async function (): Promise< void > { + await Deno.permissions.revoke({ name: "read" }); + await assertThrowsAsync(async () => { await Deno.readTextFile("cli/tests/fixture.json"); }, Deno.errors.PermissionDenied); }); -unitTest({ perms: { read: true } }, function readTextFileSyncLoop(): void { - for (let i = 0; i < 256; i++) { +Deno.test("readTextFileSyncPerm", async function (): Promise { + await Deno.permissions.revoke({ name: "read" }); + + assertThrows(() => { Deno.readTextFileSync("cli/tests/fixture.json"); - } + }, Deno.errors.PermissionDenied); }); + diff --git a/cli/tests/unit/real_path_test.ts b/cli/tests/unit/real_path_test.ts index fce28d80b5efa6..2f7cc31d05680e 100644 --- a/cli/tests/unit/real_path_test.ts +++ b/cli/tests/unit/real_path_test.ts @@ -4,10 +4,9 @@ import { assertMatch, assertThrows, assertThrowsAsync, - unitTest, } from "./test_util.ts"; -unitTest({ perms: { read: true } }, function realPathSyncSuccess(): void { +Deno.test("realPathSyncSuccess", function (): void { const relative = "cli/tests/fixture.json"; const realPath = Deno.realPathSync(relative); if (Deno.build.os !== "windows") { @@ -19,40 +18,29 @@ unitTest({ perms: { read: true } }, function realPathSyncSuccess(): void { } }); -unitTest( - { - perms: { read: true, write: true }, - }, - function realPathSyncSymlink(): void { - const testDir = Deno.makeTempDirSync(); - const target = testDir + "/target"; - const symlink = testDir + "/symln"; - Deno.mkdirSync(target); - Deno.symlinkSync(target, symlink); - const realPath = Deno.realPathSync(symlink); - if (Deno.build.os !== "windows") { - assert(realPath.startsWith("/")); - assert(realPath.endsWith("/target")); - } else { - assertMatch(realPath, /^[A-Z]:\\/); - assert(realPath.endsWith("\\target")); - } - }, -); - -unitTest({ perms: { read: false } }, function realPathSyncPerm(): void { - assertThrows(() => { - Deno.realPathSync("some_file"); - }, Deno.errors.PermissionDenied); +Deno.test("realPathSyncSymlink", function (): void { + const testDir = Deno.makeTempDirSync(); + const target = testDir + "/target"; + const symlink = testDir + "/symln"; + Deno.mkdirSync(target); + Deno.symlinkSync(target, symlink); + const realPath = Deno.realPathSync(symlink); + if (Deno.build.os !== "windows") { + assert(realPath.startsWith("/")); + assert(realPath.endsWith("/target")); + } else { + assertMatch(realPath, /^[A-Z]:\\/); + assert(realPath.endsWith("\\target")); + } }); -unitTest({ perms: { read: true } }, function realPathSyncNotFound(): void { +Deno.test("realPathSyncNotFound", function (): void { assertThrows(() => { Deno.realPathSync("bad_filename"); }, Deno.errors.NotFound); }); -unitTest({ perms: { read: true } }, async function realPathSuccess(): Promise< +Deno.test("realPathSuccess", async function (): Promise< void > { const relativePath = "cli/tests/fixture.json"; @@ -66,39 +54,46 @@ unitTest({ perms: { read: true } }, async function realPathSuccess(): Promise< } }); -unitTest( - { - perms: { read: true, write: true }, - }, - async function realPathSymlink(): Promise { - const testDir = Deno.makeTempDirSync(); - const target = testDir + "/target"; - const symlink = testDir + "/symln"; - Deno.mkdirSync(target); - Deno.symlinkSync(target, symlink); - const realPath = await Deno.realPath(symlink); - if (Deno.build.os !== "windows") { - assert(realPath.startsWith("/")); - assert(realPath.endsWith("/target")); - } else { - assertMatch(realPath, /^[A-Z]:\\/); - assert(realPath.endsWith("\\target")); - } - }, -); +Deno.test("realPathSymlink", async function (): Promise { + const testDir = Deno.makeTempDirSync(); + const target = testDir + "/target"; + const symlink = testDir + "/symln"; + Deno.mkdirSync(target); + Deno.symlinkSync(target, symlink); + const realPath = await Deno.realPath(symlink); + if (Deno.build.os !== "windows") { + assert(realPath.startsWith("/")); + assert(realPath.endsWith("/target")); + } else { + assertMatch(realPath, /^[A-Z]:\\/); + assert(realPath.endsWith("\\target")); + } +}); -unitTest({ perms: { read: false } }, async function realPathPerm(): Promise< +Deno.test("realPathNotFound", async function (): Promise< void > { await assertThrowsAsync(async () => { - await Deno.realPath("some_file"); + await Deno.realPath("bad_filename"); + }, Deno.errors.NotFound); +}); + +Deno.test("realPathSyncPerm", async function (): Promise { + await Deno.permissions.revoke({ name: "read" }); + + assertThrows(() => { + Deno.realPathSync("some_file"); }, Deno.errors.PermissionDenied); }); -unitTest({ perms: { read: true } }, async function realPathNotFound(): Promise< +Deno.test("realPathPerm", async function (): Promise< void > { + await Deno.permissions.revoke({ name: "read" }); + await assertThrowsAsync(async () => { - await Deno.realPath("bad_filename"); - }, Deno.errors.NotFound); + await Deno.realPath("some_file"); + }, Deno.errors.PermissionDenied); }); + + diff --git a/cli/tests/unit/remove_test.ts b/cli/tests/unit/remove_test.ts index 087cc3a73b5125..810aa2e74d02a0 100644 --- a/cli/tests/unit/remove_test.ts +++ b/cli/tests/unit/remove_test.ts @@ -1,247 +1,184 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { - assert, - assertThrows, - assertThrowsAsync, - unitTest, -} from "./test_util.ts"; +import { assert, assertThrows, assertThrowsAsync } from "./test_util.ts"; const REMOVE_METHODS = ["remove", "removeSync"] as const; -unitTest( - { perms: { write: true, read: true } }, - async function removeDirSuccess(): Promise { - for (const method of REMOVE_METHODS) { - // REMOVE EMPTY DIRECTORY - const path = Deno.makeTempDirSync() + "/subdir"; - Deno.mkdirSync(path); - const pathInfo = Deno.statSync(path); - assert(pathInfo.isDirectory); // check exist first - await Deno[method](path); // remove - // We then check again after remove - assertThrows(() => { - Deno.statSync(path); - }, Deno.errors.NotFound); - } - }, -); - -unitTest( - { perms: { write: true, read: true } }, - async function removeFileSuccess(): Promise { - for (const method of REMOVE_METHODS) { - // REMOVE FILE - const enc = new TextEncoder(); - const data = enc.encode("Hello"); - const filename = Deno.makeTempDirSync() + "/test.txt"; - Deno.writeFileSync(filename, data, { mode: 0o666 }); - const fileInfo = Deno.statSync(filename); - assert(fileInfo.isFile); // check exist first - await Deno[method](filename); // remove - // We then check again after remove - assertThrows(() => { - Deno.statSync(filename); - }, Deno.errors.NotFound); - } - }, -); - -unitTest( - { perms: { write: true, read: true } }, - async function removeFileByUrl(): Promise { - for (const method of REMOVE_METHODS) { - // REMOVE FILE - const enc = new TextEncoder(); - const data = enc.encode("Hello"); - - const tempDir = Deno.makeTempDirSync(); - const fileUrl = new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt`, - ); +Deno.test("removeDirSuccess", async function (): Promise { + for (const method of REMOVE_METHODS) { + // REMOVE EMPTY DIRECTORY + const path = Deno.makeTempDirSync() + "/subdir"; + Deno.mkdirSync(path); + const pathInfo = Deno.statSync(path); + assert(pathInfo.isDirectory); // check exist first + await Deno[method](path); // remove + // We then check again after remove + assertThrows(() => { + Deno.statSync(path); + }, Deno.errors.NotFound); + } +}); - Deno.writeFileSync(fileUrl, data, { mode: 0o666 }); - const fileInfo = Deno.statSync(fileUrl); - assert(fileInfo.isFile); // check exist first - await Deno[method](fileUrl); // remove - // We then check again after remove - assertThrows(() => { - Deno.statSync(fileUrl); - }, Deno.errors.NotFound); - } - }, -); +Deno.test("removeFileSuccess", async function (): Promise { + for (const method of REMOVE_METHODS) { + // REMOVE FILE + const enc = new TextEncoder(); + const data = enc.encode("Hello"); + const filename = Deno.makeTempDirSync() + "/test.txt"; + Deno.writeFileSync(filename, data, { mode: 0o666 }); + const fileInfo = Deno.statSync(filename); + assert(fileInfo.isFile); // check exist first + await Deno[method](filename); // remove + // We then check again after remove + assertThrows(() => { + Deno.statSync(filename); + }, Deno.errors.NotFound); + } +}); -unitTest( - { perms: { write: true, read: true } }, - async function removeFail(): Promise { - for (const method of REMOVE_METHODS) { - // NON-EMPTY DIRECTORY - const path = Deno.makeTempDirSync() + "/dir/subdir"; - const subPath = path + "/subsubdir"; - Deno.mkdirSync(path, { recursive: true }); - Deno.mkdirSync(subPath); - const pathInfo = Deno.statSync(path); - assert(pathInfo.isDirectory); // check exist first - const subPathInfo = Deno.statSync(subPath); - assert(subPathInfo.isDirectory); // check exist first +Deno.test("removeFileByUrl", async function (): Promise { + for (const method of REMOVE_METHODS) { + // REMOVE FILE + const enc = new TextEncoder(); + const data = enc.encode("Hello"); - await assertThrowsAsync(async () => { - await Deno[method](path); - }, Error); - // TODO(ry) Is Other really the error we should get here? What would Go do? + const tempDir = Deno.makeTempDirSync(); + const fileUrl = new URL( + `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt`, + ); - // NON-EXISTENT DIRECTORY/FILE - await assertThrowsAsync(async () => { - await Deno[method]("/baddir"); - }, Deno.errors.NotFound); - } - }, -); + Deno.writeFileSync(fileUrl, data, { mode: 0o666 }); + const fileInfo = Deno.statSync(fileUrl); + assert(fileInfo.isFile); // check exist first + await Deno[method](fileUrl); // remove + // We then check again after remove + assertThrows(() => { + Deno.statSync(fileUrl); + }, Deno.errors.NotFound); + } +}); -unitTest( - { perms: { write: true, read: true } }, - async function removeDanglingSymlinkSuccess(): Promise { - for (const method of REMOVE_METHODS) { - const danglingSymlinkPath = Deno.makeTempDirSync() + "/dangling_symlink"; - if (Deno.build.os === "windows") { - Deno.symlinkSync("unexistent_file", danglingSymlinkPath, { - type: "file", - }); - } else { - Deno.symlinkSync("unexistent_file", danglingSymlinkPath); - } - const pathInfo = Deno.lstatSync(danglingSymlinkPath); - assert(pathInfo.isSymlink); - await Deno[method](danglingSymlinkPath); - assertThrows(() => { - Deno.lstatSync(danglingSymlinkPath); - }, Deno.errors.NotFound); - } - }, -); +Deno.test("removeFail", async function (): Promise { + for (const method of REMOVE_METHODS) { + // NON-EMPTY DIRECTORY + const path = Deno.makeTempDirSync() + "/dir/subdir"; + const subPath = path + "/subsubdir"; + Deno.mkdirSync(path, { recursive: true }); + Deno.mkdirSync(subPath); + const pathInfo = Deno.statSync(path); + assert(pathInfo.isDirectory); // check exist first + const subPathInfo = Deno.statSync(subPath); + assert(subPathInfo.isDirectory); // check exist first -unitTest( - { perms: { write: true, read: true } }, - async function removeValidSymlinkSuccess(): Promise { - for (const method of REMOVE_METHODS) { - const encoder = new TextEncoder(); - const data = encoder.encode("Test"); - const tempDir = Deno.makeTempDirSync(); - const filePath = tempDir + "/test.txt"; - const validSymlinkPath = tempDir + "/valid_symlink"; - Deno.writeFileSync(filePath, data, { mode: 0o666 }); - if (Deno.build.os === "windows") { - Deno.symlinkSync(filePath, validSymlinkPath, { type: "file" }); - } else { - Deno.symlinkSync(filePath, validSymlinkPath); - } - const symlinkPathInfo = Deno.statSync(validSymlinkPath); - assert(symlinkPathInfo.isFile); - await Deno[method](validSymlinkPath); - assertThrows(() => { - Deno.statSync(validSymlinkPath); - }, Deno.errors.NotFound); - await Deno[method](filePath); - } - }, -); + await assertThrowsAsync(async () => { + await Deno[method](path); + }, Error); + // TODO(ry) Is Other really the error we should get here? What would Go do? -unitTest({ perms: { write: false } }, async function removePerm(): Promise< - void -> { - for (const method of REMOVE_METHODS) { + // NON-EXISTENT DIRECTORY/FILE await assertThrowsAsync(async () => { await Deno[method]("/baddir"); - }, Deno.errors.PermissionDenied); + }, Deno.errors.NotFound); } }); -unitTest( - { perms: { write: true, read: true } }, - async function removeAllDirSuccess(): Promise { - for (const method of REMOVE_METHODS) { - // REMOVE EMPTY DIRECTORY - let path = Deno.makeTempDirSync() + "/dir/subdir"; - Deno.mkdirSync(path, { recursive: true }); - let pathInfo = Deno.statSync(path); - assert(pathInfo.isDirectory); // check exist first - await Deno[method](path, { recursive: true }); // remove - // We then check again after remove - assertThrows( - () => { - Deno.statSync(path); - }, // Directory is gone - Deno.errors.NotFound, - ); - - // REMOVE NON-EMPTY DIRECTORY - path = Deno.makeTempDirSync() + "/dir/subdir"; - const subPath = path + "/subsubdir"; - Deno.mkdirSync(path, { recursive: true }); - Deno.mkdirSync(subPath); - pathInfo = Deno.statSync(path); - assert(pathInfo.isDirectory); // check exist first - const subPathInfo = Deno.statSync(subPath); - assert(subPathInfo.isDirectory); // check exist first - await Deno[method](path, { recursive: true }); // remove - // We then check parent directory again after remove - assertThrows(() => { - Deno.statSync(path); - }, Deno.errors.NotFound); - // Directory is gone +Deno.test("removeDanglingSymlinkSuccess", async function (): Promise { + for (const method of REMOVE_METHODS) { + const danglingSymlinkPath = Deno.makeTempDirSync() + "/dangling_symlink"; + if (Deno.build.os === "windows") { + Deno.symlinkSync("unexistent_file", danglingSymlinkPath, { + type: "file", + }); + } else { + Deno.symlinkSync("unexistent_file", danglingSymlinkPath); } - }, -); + const pathInfo = Deno.lstatSync(danglingSymlinkPath); + assert(pathInfo.isSymlink); + await Deno[method](danglingSymlinkPath); + assertThrows(() => { + Deno.lstatSync(danglingSymlinkPath); + }, Deno.errors.NotFound); + } +}); -unitTest( - { perms: { write: true, read: true } }, - async function removeAllFileSuccess(): Promise { - for (const method of REMOVE_METHODS) { - // REMOVE FILE - const enc = new TextEncoder(); - const data = enc.encode("Hello"); - const filename = Deno.makeTempDirSync() + "/test.txt"; - Deno.writeFileSync(filename, data, { mode: 0o666 }); - const fileInfo = Deno.statSync(filename); - assert(fileInfo.isFile); // check exist first - await Deno[method](filename, { recursive: true }); // remove - // We then check again after remove - assertThrows(() => { - Deno.statSync(filename); - }, Deno.errors.NotFound); - // File is gone +Deno.test("removeValidSymlinkSuccess", async function (): Promise { + for (const method of REMOVE_METHODS) { + const encoder = new TextEncoder(); + const data = encoder.encode("Test"); + const tempDir = Deno.makeTempDirSync(); + const filePath = tempDir + "/test.txt"; + const validSymlinkPath = tempDir + "/valid_symlink"; + Deno.writeFileSync(filePath, data, { mode: 0o666 }); + if (Deno.build.os === "windows") { + Deno.symlinkSync(filePath, validSymlinkPath, { type: "file" }); + } else { + Deno.symlinkSync(filePath, validSymlinkPath); } - }, -); + const symlinkPathInfo = Deno.statSync(validSymlinkPath); + assert(symlinkPathInfo.isFile); + await Deno[method](validSymlinkPath); + assertThrows(() => { + Deno.statSync(validSymlinkPath); + }, Deno.errors.NotFound); + await Deno[method](filePath); + } +}); -unitTest({ perms: { write: true } }, async function removeAllFail(): Promise< - void -> { +Deno.test("removeAllDirSuccess", async function (): Promise { for (const method of REMOVE_METHODS) { - // NON-EXISTENT DIRECTORY/FILE - await assertThrowsAsync(async () => { - // Non-existent - await Deno[method]("/baddir", { recursive: true }); + // REMOVE EMPTY DIRECTORY + let path = Deno.makeTempDirSync() + "/dir/subdir"; + Deno.mkdirSync(path, { recursive: true }); + let pathInfo = Deno.statSync(path); + assert(pathInfo.isDirectory); // check exist first + await Deno[method](path, { recursive: true }); // remove + // We then check again after remove + assertThrows( + () => { + Deno.statSync(path); + }, // Directory is gone + Deno.errors.NotFound, + ); + + // REMOVE NON-EMPTY DIRECTORY + path = Deno.makeTempDirSync() + "/dir/subdir"; + const subPath = path + "/subsubdir"; + Deno.mkdirSync(path, { recursive: true }); + Deno.mkdirSync(subPath); + pathInfo = Deno.statSync(path); + assert(pathInfo.isDirectory); // check exist first + const subPathInfo = Deno.statSync(subPath); + assert(subPathInfo.isDirectory); // check exist first + await Deno[method](path, { recursive: true }); // remove + // We then check parent directory again after remove + assertThrows(() => { + Deno.statSync(path); }, Deno.errors.NotFound); + // Directory is gone } }); -unitTest({ perms: { write: false } }, async function removeAllPerm(): Promise< - void -> { +Deno.test("removeAllFileSuccess", async function (): Promise { for (const method of REMOVE_METHODS) { - await assertThrowsAsync(async () => { - await Deno[method]("/baddir", { recursive: true }); - }, Deno.errors.PermissionDenied); + // REMOVE FILE + const enc = new TextEncoder(); + const data = enc.encode("Hello"); + const filename = Deno.makeTempDirSync() + "/test.txt"; + Deno.writeFileSync(filename, data, { mode: 0o666 }); + const fileInfo = Deno.statSync(filename); + assert(fileInfo.isFile); // check exist first + await Deno[method](filename, { recursive: true }); // remove + // We then check again after remove + assertThrows(() => { + Deno.statSync(filename); + }, Deno.errors.NotFound); + // File is gone } }); -unitTest( - { - ignore: Deno.build.os === "windows", - perms: { write: true, read: true }, - }, - async function removeUnixSocketSuccess(): Promise { +Deno.test({ + name: "removeUnixSocketSuccess", + ignore: Deno.build.os === "windows", + async fn(): Promise { for (const method of REMOVE_METHODS) { // MAKE TEMPORARY UNIX SOCKET const path = Deno.makeTempDirSync() + "/test.sock"; @@ -255,41 +192,71 @@ unitTest( }, Deno.errors.NotFound); } }, -); +}); if (Deno.build.os === "windows") { - unitTest( - { perms: { run: true, write: true, read: true } }, - async function removeFileSymlink(): Promise { - const symlink = Deno.run({ - cmd: ["cmd", "/c", "mklink", "file_link", "bar"], - stdout: "null", - }); + Deno.test("removeFileSymlink", async function (): Promise { + const symlink = Deno.run({ + cmd: ["cmd", "/c", "mklink", "file_link", "bar"], + stdout: "null", + }); - assert(await symlink.status()); - symlink.close(); - await Deno.remove("file_link"); - await assertThrowsAsync(async () => { - await Deno.lstat("file_link"); - }, Deno.errors.NotFound); - }, - ); + assert(await symlink.status()); + symlink.close(); + await Deno.remove("file_link"); + await assertThrowsAsync(async () => { + await Deno.lstat("file_link"); + }, Deno.errors.NotFound); + }); - unitTest( - { perms: { run: true, write: true, read: true } }, - async function removeDirSymlink(): Promise { - const symlink = Deno.run({ - cmd: ["cmd", "/c", "mklink", "/d", "dir_link", "bar"], - stdout: "null", - }); + Deno.test("removeDirSymlink", async function (): Promise { + const symlink = Deno.run({ + cmd: ["cmd", "/c", "mklink", "/d", "dir_link", "bar"], + stdout: "null", + }); - assert(await symlink.status()); - symlink.close(); + assert(await symlink.status()); + symlink.close(); - await Deno.remove("dir_link"); - await assertThrowsAsync(async () => { - await Deno.lstat("dir_link"); - }, Deno.errors.NotFound); - }, - ); + await Deno.remove("dir_link"); + await assertThrowsAsync(async () => { + await Deno.lstat("dir_link"); + }, Deno.errors.NotFound); + }); } + +Deno.test("removeAllFail", async function (): Promise< + void +> { + for (const method of REMOVE_METHODS) { + // NON-EXISTENT DIRECTORY/FILE + await assertThrowsAsync(async () => { + // Non-existent + await Deno[method]("/baddir", { recursive: true }); + }, Deno.errors.NotFound); + } +}); + +Deno.test("removePerm", async function (): Promise< + void +> { + await Deno.permissions.revoke({ name: "write" }); + + for (const method of REMOVE_METHODS) { + await assertThrowsAsync(async () => { + await Deno[method]("/baddir"); + }, Deno.errors.PermissionDenied); + } +}); + +Deno.test("removeAllPerm", async function (): Promise< + void +> { + await Deno.permissions.revoke({ name: "write" }); + + for (const method of REMOVE_METHODS) { + await assertThrowsAsync(async () => { + await Deno[method]("/baddir", { recursive: true }); + }, Deno.errors.PermissionDenied); + } +}); diff --git a/cli/tests/unit/rename_test.ts b/cli/tests/unit/rename_test.ts index 09633aed710de4..0a739d66d03647 100644 --- a/cli/tests/unit/rename_test.ts +++ b/cli/tests/unit/rename_test.ts @@ -1,5 +1,5 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assert, assertEquals, assertThrows, unitTest } from "./test_util.ts"; +import { assert, assertEquals, assertThrows } from "./test_util.ts"; function assertMissing(path: string): void { let caughtErr = false; @@ -27,53 +27,25 @@ function assertDirectory(path: string, mode?: number): void { } } -unitTest( - { perms: { read: true, write: true } }, - function renameSyncSuccess(): void { - const testDir = Deno.makeTempDirSync(); - const oldpath = testDir + "/oldpath"; - const newpath = testDir + "/newpath"; - Deno.mkdirSync(oldpath); - Deno.renameSync(oldpath, newpath); - assertDirectory(newpath); - assertMissing(oldpath); - }, -); - -unitTest( - { perms: { read: false, write: true } }, - function renameSyncReadPerm(): void { - assertThrows(() => { - const oldpath = "/oldbaddir"; - const newpath = "/newbaddir"; - Deno.renameSync(oldpath, newpath); - }, Deno.errors.PermissionDenied); - }, -); - -unitTest( - { perms: { read: true, write: false } }, - function renameSyncWritePerm(): void { - assertThrows(() => { - const oldpath = "/oldbaddir"; - const newpath = "/newbaddir"; - Deno.renameSync(oldpath, newpath); - }, Deno.errors.PermissionDenied); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function renameSuccess(): Promise { - const testDir = Deno.makeTempDirSync(); - const oldpath = testDir + "/oldpath"; - const newpath = testDir + "/newpath"; - Deno.mkdirSync(oldpath); - await Deno.rename(oldpath, newpath); - assertDirectory(newpath); - assertMissing(oldpath); - }, -); +Deno.test("renameSyncSuccess", function (): void { + const testDir = Deno.makeTempDirSync(); + const oldpath = testDir + "/oldpath"; + const newpath = testDir + "/newpath"; + Deno.mkdirSync(oldpath); + Deno.renameSync(oldpath, newpath); + assertDirectory(newpath); + assertMissing(oldpath); +}); + +Deno.test("renameSuccess", async function (): Promise { + const testDir = Deno.makeTempDirSync(); + const oldpath = testDir + "/oldpath"; + const newpath = testDir + "/newpath"; + Deno.mkdirSync(oldpath); + await Deno.rename(oldpath, newpath); + assertDirectory(newpath); + assertMissing(oldpath); +}); function readFileString(filename: string): string { const dataRead = Deno.readFileSync(filename); @@ -87,9 +59,10 @@ function writeFileString(filename: string, s: string): void { Deno.writeFileSync(filename, data, { mode: 0o666 }); } -unitTest( - { ignore: Deno.build.os === "windows", perms: { read: true, write: true } }, - function renameSyncErrorsUnix(): void { +Deno.test({ + name: "renameSyncErrorsUnix", + ignore: Deno.build.os === "windows", + fn(): void { const testDir = Deno.makeTempDirSync(); const oldfile = testDir + "/oldfile"; const olddir = testDir + "/olddir"; @@ -160,11 +133,12 @@ unitTest( assertFile(danglingLink); assertEquals("Hello", readFileString(danglingLink)); }, -); +}); -unitTest( - { ignore: Deno.build.os !== "windows", perms: { read: true, write: true } }, - function renameSyncErrorsWin(): void { +Deno.test({ + name: "renameSyncErrorsWin", + ignore: Deno.build.os !== "windows", + fn(): void { const testDir = Deno.makeTempDirSync(); const oldfile = testDir + "/oldfile"; const olddir = testDir + "/olddir"; @@ -203,4 +177,24 @@ unitTest( Deno.renameSync(olddir, file); assertDirectory(file); }, -); +}); + +Deno.test("renameSyncReadPerm", async function (): Promise { + await Deno.permissions.revoke({ name: "read" }); + + assertThrows(() => { + const oldpath = "/oldbaddir"; + const newpath = "/newbaddir"; + Deno.renameSync(oldpath, newpath); + }, Deno.errors.PermissionDenied); +}); + +Deno.test("renameSyncWritePerm", async function (): Promise { + await Deno.permissions.revoke({ name: "write" }); + + assertThrows(() => { + const oldpath = "/oldbaddir"; + const newpath = "/newbaddir"; + Deno.renameSync(oldpath, newpath); + }, Deno.errors.PermissionDenied); +}); diff --git a/cli/tests/unit/request_test.ts b/cli/tests/unit/request_test.ts index a8cbed37031493..637198633b7163 100644 --- a/cli/tests/unit/request_test.ts +++ b/cli/tests/unit/request_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assertEquals, unitTest } from "./test_util.ts"; +import { assertEquals } from "./test_util.ts"; -unitTest(async function fromInit(): Promise { +Deno.test("fromInit", async function (): Promise { const req = new Request("http://foo/", { body: "ahoyhoy", method: "POST", @@ -15,7 +15,7 @@ unitTest(async function fromInit(): Promise { assertEquals(req.headers.get("test-header"), "value"); }); -unitTest(async function fromRequest(): Promise { +Deno.test("fromRequest", async function (): Promise { const r = new Request("http://foo/", { body: "ahoyhoy" }); r.headers.set("test-header", "value"); @@ -26,7 +26,7 @@ unitTest(async function fromRequest(): Promise { assertEquals(req.headers.get("test-header"), r.headers.get("test-header")); }); -unitTest(function requestNonString(): void { +Deno.test("requestNonString", function (): void { const nonString = { toString() { return "http://foo/"; @@ -37,18 +37,18 @@ unitTest(function requestNonString(): void { assertEquals(new Request(nonString).url, "http://foo/"); }); -unitTest(function methodNonString(): void { +Deno.test("methodNonString", function (): void { assertEquals(new Request("http://foo/", { method: undefined }).method, "GET"); }); -unitTest(function requestRelativeUrl(): void { +Deno.test("requestRelativeUrl", function (): void { assertEquals( new Request("relative-url").url, "http://js-unit-tests/foo/relative-url", ); }); -unitTest(async function cloneRequestBodyStream(): Promise { +Deno.test("cloneRequestBodyStream", async function (): Promise { // hack to get a stream const stream = new Request("http://foo/", { body: "a test body" }).body; const r1 = new Request("http://foo/", { diff --git a/cli/tests/unit/resources_test.ts b/cli/tests/unit/resources_test.ts index 96fd4ff2c01582..703bc8799379b3 100644 --- a/cli/tests/unit/resources_test.ts +++ b/cli/tests/unit/resources_test.ts @@ -1,13 +1,13 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assert, assertEquals, assertThrows, unitTest } from "./test_util.ts"; +import { assert, assertEquals, assertThrows } from "./test_util.ts"; -unitTest(function resourcesCloseBadArgs(): void { +Deno.test("resourcesCloseBadArgs", function (): void { assertThrows(() => { Deno.close((null as unknown) as number); }, TypeError); }); -unitTest(function resourcesStdio(): void { +Deno.test("resourcesStdio", function (): void { const res = Deno.resources(); assertEquals(res[0], "stdin"); @@ -15,7 +15,7 @@ unitTest(function resourcesStdio(): void { assertEquals(res[2], "stderr"); }); -unitTest({ perms: { net: true } }, async function resourcesNet(): Promise< +Deno.test("resourcesNet", async function (): Promise< void > { const listener = Deno.listen({ port: 4501 }); @@ -37,7 +37,7 @@ unitTest({ perms: { net: true } }, async function resourcesNet(): Promise< listener.close(); }); -unitTest({ perms: { read: true } }, async function resourcesFile(): Promise< +Deno.test("resourcesFile", async function (): Promise< void > { const resourcesBefore = Deno.resources(); diff --git a/cli/tests/unit/response_test.ts b/cli/tests/unit/response_test.ts index 5a5f8fdfff6a11..55ca82c9b44cf0 100644 --- a/cli/tests/unit/response_test.ts +++ b/cli/tests/unit/response_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assert, assertEquals, unitTest } from "./test_util.ts"; +import { assert, assertEquals } from "./test_util.ts"; -unitTest(async function responseText() { +Deno.test("responseText", async function () { const response = new Response("hello world"); const textPromise = response.text(); assert(textPromise instanceof Promise); @@ -10,7 +10,7 @@ unitTest(async function responseText() { assertEquals(text, "hello world"); }); -unitTest(async function responseArrayBuffer() { +Deno.test("responseArrayBuffer", async function () { const response = new Response(new Uint8Array([1, 2, 3])); const arrayBufferPromise = response.arrayBuffer(); assert(arrayBufferPromise instanceof Promise); @@ -19,7 +19,7 @@ unitTest(async function responseArrayBuffer() { assertEquals(new Uint8Array(arrayBuffer), new Uint8Array([1, 2, 3])); }); -unitTest(async function responseJson() { +Deno.test("responseJson", async function () { const response = new Response('{"hello": "world"}'); const jsonPromise = response.json(); assert(jsonPromise instanceof Promise); @@ -28,7 +28,7 @@ unitTest(async function responseJson() { assertEquals(json, { hello: "world" }); }); -unitTest(async function responseBlob() { +Deno.test("responseBlob", async function () { const response = new Response(new Uint8Array([1, 2, 3])); const blobPromise = response.blob(); assert(blobPromise instanceof Promise); @@ -37,7 +37,7 @@ unitTest(async function responseBlob() { assertEquals(blob, new Blob([new Uint8Array([1, 2, 3])])); }); -unitTest(async function responseFormData() { +Deno.test("responseFormData", async function () { const input = new FormData(); input.append("hello", "world"); const response = new Response(input, { diff --git a/cli/tests/unit/signal_test.ts b/cli/tests/unit/signal_test.ts index 801e15d8b6b372..ac963ea93a6cd9 100644 --- a/cli/tests/unit/signal_test.ts +++ b/cli/tests/unit/signal_test.ts @@ -1,11 +1,5 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { - assert, - assertEquals, - assertThrows, - deferred, - unitTest, -} from "./test_util.ts"; +import { assert, assertEquals, assertThrows, deferred } from "./test_util.ts"; function defer(n: number): Promise { return new Promise((resolve: () => void, _) => { @@ -13,9 +7,10 @@ function defer(n: number): Promise { }); } -unitTest( - { ignore: Deno.build.os !== "windows" }, - function signalsNotImplemented(): void { +Deno.test({ + name: "signalsNotImplemented", + ignore: Deno.build.os !== "windows", + fn(): void { assertThrows( () => { Deno.signal(1); @@ -101,11 +96,12 @@ unitTest( "not implemented", ); }, -); +}); -unitTest( - { ignore: Deno.build.os === "windows", perms: { run: true, net: true } }, - async function signalStreamTest(): Promise { +Deno.test({ + name: "signalStreamTest", + ignore: Deno.build.os === "windows", + async fn(): Promise { const resolvable = deferred(); // This prevents the program from exiting. const t = setInterval(() => {}, 1000); @@ -132,11 +128,12 @@ unitTest( clearInterval(t); await resolvable; }, -); +}); -unitTest( - { ignore: Deno.build.os === "windows", perms: { run: true } }, - async function signalPromiseTest(): Promise { +Deno.test({ + name: "signalPromiseTest", + ignore: Deno.build.os === "windows", + async fn(): Promise { const resolvable = deferred(); // This prevents the program from exiting. const t = setInterval(() => {}, 1000); @@ -152,11 +149,12 @@ unitTest( clearInterval(t); await resolvable; }, -); +}); -unitTest( - { ignore: Deno.build.os === "windows", perms: { run: true } }, - function signalShorthandsTest(): void { +Deno.test({ + name: "signalShorthandsTest", + ignore: Deno.build.os === "windows", + fn(): void { let s: Deno.SignalStream; s = Deno.signals.alarm(); // for SIGALRM assert(s instanceof Deno.SignalStream); @@ -192,4 +190,4 @@ unitTest( assert(s instanceof Deno.SignalStream); s.dispose(); }, -); +}); diff --git a/cli/tests/unit/stat_test.ts b/cli/tests/unit/stat_test.ts index d75eb22ebc7c3e..ac254eb50ee939 100644 --- a/cli/tests/unit/stat_test.ts +++ b/cli/tests/unit/stat_test.ts @@ -5,10 +5,9 @@ import { assertThrows, assertThrowsAsync, pathToAbsoluteFileUrl, - unitTest, } from "./test_util.ts"; -unitTest({ perms: { read: true } }, function fstatSyncSuccess(): void { +Deno.test("fstatSyncSuccess", function (): void { const file = Deno.openSync("README.md"); const fileInfo = Deno.fstatSync(file.rid); assert(fileInfo.isFile); @@ -23,7 +22,7 @@ unitTest({ perms: { read: true } }, function fstatSyncSuccess(): void { Deno.close(file.rid); }); -unitTest({ perms: { read: true } }, async function fstatSuccess(): Promise< +Deno.test("fstatSuccess", async function (): Promise< void > { const file = await Deno.open("README.md"); @@ -40,82 +39,73 @@ unitTest({ perms: { read: true } }, async function fstatSuccess(): Promise< Deno.close(file.rid); }); -unitTest( - { perms: { read: true, write: true } }, - function statSyncSuccess(): void { - const packageInfo = Deno.statSync("README.md"); - assert(packageInfo.isFile); - assert(!packageInfo.isSymlink); - - const modulesInfo = Deno.statSync("cli/tests/symlink_to_subdir"); - assert(modulesInfo.isDirectory); - assert(!modulesInfo.isSymlink); - - const testsInfo = Deno.statSync("cli/tests"); - assert(testsInfo.isDirectory); - assert(!testsInfo.isSymlink); - - const tempFile = Deno.makeTempFileSync(); - const tempInfo = Deno.statSync(tempFile); - let now = Date.now(); - assert(tempInfo.atime !== null && now - tempInfo.atime.valueOf() < 1000); - assert(tempInfo.mtime !== null && now - tempInfo.mtime.valueOf() < 1000); - assert( - tempInfo.birthtime === null || now - tempInfo.birthtime.valueOf() < 1000, - ); - - const packageInfoByUrl = Deno.statSync(pathToAbsoluteFileUrl("README.md")); - assert(packageInfoByUrl.isFile); - assert(!packageInfoByUrl.isSymlink); - - const modulesInfoByUrl = Deno.statSync( - pathToAbsoluteFileUrl("cli/tests/symlink_to_subdir"), - ); - assert(modulesInfoByUrl.isDirectory); - assert(!modulesInfoByUrl.isSymlink); - - const testsInfoByUrl = Deno.statSync(pathToAbsoluteFileUrl("cli/tests")); - assert(testsInfoByUrl.isDirectory); - assert(!testsInfoByUrl.isSymlink); - - const tempFileForUrl = Deno.makeTempFileSync(); - const tempInfoByUrl = Deno.statSync( - new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempFileForUrl}`, - ), - ); - now = Date.now(); - assert( - tempInfoByUrl.atime !== null && - now - tempInfoByUrl.atime.valueOf() < 1000, - ); - assert( - tempInfoByUrl.mtime !== null && - now - tempInfoByUrl.mtime.valueOf() < 1000, - ); - assert( - tempInfoByUrl.birthtime === null || - now - tempInfoByUrl.birthtime.valueOf() < 1000, - ); - - Deno.removeSync(tempFile, { recursive: true }); - Deno.removeSync(tempFileForUrl, { recursive: true }); - }, -); +Deno.test("statSyncSuccess", function (): void { + const packageInfo = Deno.statSync("README.md"); + assert(packageInfo.isFile); + assert(!packageInfo.isSymlink); -unitTest({ perms: { read: false } }, function statSyncPerm(): void { - assertThrows(() => { - Deno.statSync("README.md"); - }, Deno.errors.PermissionDenied); + const modulesInfo = Deno.statSync("cli/tests/symlink_to_subdir"); + assert(modulesInfo.isDirectory); + assert(!modulesInfo.isSymlink); + + const testsInfo = Deno.statSync("cli/tests"); + assert(testsInfo.isDirectory); + assert(!testsInfo.isSymlink); + + const tempFile = Deno.makeTempFileSync(); + const tempInfo = Deno.statSync(tempFile); + let now = Date.now(); + assert(tempInfo.atime !== null && now - tempInfo.atime.valueOf() < 1000); + assert(tempInfo.mtime !== null && now - tempInfo.mtime.valueOf() < 1000); + assert( + tempInfo.birthtime === null || now - tempInfo.birthtime.valueOf() < 1000, + ); + + const packageInfoByUrl = Deno.statSync(pathToAbsoluteFileUrl("README.md")); + assert(packageInfoByUrl.isFile); + assert(!packageInfoByUrl.isSymlink); + + const modulesInfoByUrl = Deno.statSync( + pathToAbsoluteFileUrl("cli/tests/symlink_to_subdir"), + ); + assert(modulesInfoByUrl.isDirectory); + assert(!modulesInfoByUrl.isSymlink); + + const testsInfoByUrl = Deno.statSync(pathToAbsoluteFileUrl("cli/tests")); + assert(testsInfoByUrl.isDirectory); + assert(!testsInfoByUrl.isSymlink); + + const tempFileForUrl = Deno.makeTempFileSync(); + const tempInfoByUrl = Deno.statSync( + new URL( + `file://${Deno.build.os === "windows" ? "/" : ""}${tempFileForUrl}`, + ), + ); + now = Date.now(); + assert( + tempInfoByUrl.atime !== null && + now - tempInfoByUrl.atime.valueOf() < 1000, + ); + assert( + tempInfoByUrl.mtime !== null && + now - tempInfoByUrl.mtime.valueOf() < 1000, + ); + assert( + tempInfoByUrl.birthtime === null || + now - tempInfoByUrl.birthtime.valueOf() < 1000, + ); + + Deno.removeSync(tempFile, { recursive: true }); + Deno.removeSync(tempFileForUrl, { recursive: true }); }); -unitTest({ perms: { read: true } }, function statSyncNotFound(): void { +Deno.test("statSyncNotFound", function (): void { assertThrows(() => { Deno.statSync("bad_file_name"); }, Deno.errors.NotFound); }); -unitTest({ perms: { read: true } }, function lstatSyncSuccess(): void { +Deno.test("lstatSyncSuccess", function (): void { const packageInfo = Deno.lstatSync("README.md"); assert(packageInfo.isFile); assert(!packageInfo.isSymlink); @@ -143,91 +133,76 @@ unitTest({ perms: { read: true } }, function lstatSyncSuccess(): void { assert(!coreInfoByUrl.isSymlink); }); -unitTest({ perms: { read: false } }, function lstatSyncPerm(): void { - assertThrows(() => { - Deno.lstatSync("README.md"); - }, Deno.errors.PermissionDenied); -}); - -unitTest({ perms: { read: true } }, function lstatSyncNotFound(): void { +Deno.test("lstatSyncNotFound", function (): void { assertThrows(() => { Deno.lstatSync("bad_file_name"); }, Deno.errors.NotFound); }); -unitTest( - { perms: { read: true, write: true } }, - async function statSuccess(): Promise { - const packageInfo = await Deno.stat("README.md"); - assert(packageInfo.isFile); - assert(!packageInfo.isSymlink); - - const packageInfoByUrl = await Deno.stat( - pathToAbsoluteFileUrl("README.md"), - ); - assert(packageInfoByUrl.isFile); - assert(!packageInfoByUrl.isSymlink); - - const modulesInfo = await Deno.stat("cli/tests/symlink_to_subdir"); - assert(modulesInfo.isDirectory); - assert(!modulesInfo.isSymlink); - - const modulesInfoByUrl = await Deno.stat( - pathToAbsoluteFileUrl("cli/tests/symlink_to_subdir"), - ); - assert(modulesInfoByUrl.isDirectory); - assert(!modulesInfoByUrl.isSymlink); - - const testsInfo = await Deno.stat("cli/tests"); - assert(testsInfo.isDirectory); - assert(!testsInfo.isSymlink); - - const testsInfoByUrl = await Deno.stat(pathToAbsoluteFileUrl("cli/tests")); - assert(testsInfoByUrl.isDirectory); - assert(!testsInfoByUrl.isSymlink); - - const tempFile = await Deno.makeTempFile(); - const tempInfo = await Deno.stat(tempFile); - let now = Date.now(); - assert(tempInfo.atime !== null && now - tempInfo.atime.valueOf() < 1000); - assert(tempInfo.mtime !== null && now - tempInfo.mtime.valueOf() < 1000); - - assert( - tempInfo.birthtime === null || now - tempInfo.birthtime.valueOf() < 1000, - ); - - const tempFileForUrl = await Deno.makeTempFile(); - const tempInfoByUrl = await Deno.stat( - new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempFileForUrl}`, - ), - ); - now = Date.now(); - assert( - tempInfoByUrl.atime !== null && - now - tempInfoByUrl.atime.valueOf() < 1000, - ); - assert( - tempInfoByUrl.mtime !== null && - now - tempInfoByUrl.mtime.valueOf() < 1000, - ); - assert( - tempInfoByUrl.birthtime === null || - now - tempInfoByUrl.birthtime.valueOf() < 1000, - ); - - Deno.removeSync(tempFile, { recursive: true }); - Deno.removeSync(tempFileForUrl, { recursive: true }); - }, -); +Deno.test("statSuccess", async function (): Promise { + const packageInfo = await Deno.stat("README.md"); + assert(packageInfo.isFile); + assert(!packageInfo.isSymlink); -unitTest({ perms: { read: false } }, async function statPerm(): Promise { - await assertThrowsAsync(async () => { - await Deno.stat("README.md"); - }, Deno.errors.PermissionDenied); + const packageInfoByUrl = await Deno.stat( + pathToAbsoluteFileUrl("README.md"), + ); + assert(packageInfoByUrl.isFile); + assert(!packageInfoByUrl.isSymlink); + + const modulesInfo = await Deno.stat("cli/tests/symlink_to_subdir"); + assert(modulesInfo.isDirectory); + assert(!modulesInfo.isSymlink); + + const modulesInfoByUrl = await Deno.stat( + pathToAbsoluteFileUrl("cli/tests/symlink_to_subdir"), + ); + assert(modulesInfoByUrl.isDirectory); + assert(!modulesInfoByUrl.isSymlink); + + const testsInfo = await Deno.stat("cli/tests"); + assert(testsInfo.isDirectory); + assert(!testsInfo.isSymlink); + + const testsInfoByUrl = await Deno.stat(pathToAbsoluteFileUrl("cli/tests")); + assert(testsInfoByUrl.isDirectory); + assert(!testsInfoByUrl.isSymlink); + + const tempFile = await Deno.makeTempFile(); + const tempInfo = await Deno.stat(tempFile); + let now = Date.now(); + assert(tempInfo.atime !== null && now - tempInfo.atime.valueOf() < 1000); + assert(tempInfo.mtime !== null && now - tempInfo.mtime.valueOf() < 1000); + + assert( + tempInfo.birthtime === null || now - tempInfo.birthtime.valueOf() < 1000, + ); + + const tempFileForUrl = await Deno.makeTempFile(); + const tempInfoByUrl = await Deno.stat( + new URL( + `file://${Deno.build.os === "windows" ? "/" : ""}${tempFileForUrl}`, + ), + ); + now = Date.now(); + assert( + tempInfoByUrl.atime !== null && + now - tempInfoByUrl.atime.valueOf() < 1000, + ); + assert( + tempInfoByUrl.mtime !== null && + now - tempInfoByUrl.mtime.valueOf() < 1000, + ); + assert( + tempInfoByUrl.birthtime === null || + now - tempInfoByUrl.birthtime.valueOf() < 1000, + ); + + Deno.removeSync(tempFile, { recursive: true }); + Deno.removeSync(tempFileForUrl, { recursive: true }); }); -unitTest({ perms: { read: true } }, async function statNotFound(): Promise< +Deno.test("statNotFound", async function (): Promise< void > { await assertThrowsAsync( @@ -237,7 +212,7 @@ unitTest({ perms: { read: true } }, async function statNotFound(): Promise< ); }); -unitTest({ perms: { read: true } }, async function lstatSuccess(): Promise< +Deno.test("lstatSuccess", async function (): Promise< void > { const packageInfo = await Deno.lstat("README.md"); @@ -267,13 +242,7 @@ unitTest({ perms: { read: true } }, async function lstatSuccess(): Promise< assert(!coreInfoByUrl.isSymlink); }); -unitTest({ perms: { read: false } }, async function lstatPerm(): Promise { - await assertThrowsAsync(async () => { - await Deno.lstat("README.md"); - }, Deno.errors.PermissionDenied); -}); - -unitTest({ perms: { read: true } }, async function lstatNotFound(): Promise< +Deno.test("lstatNotFound", async function (): Promise< void > { await assertThrowsAsync(async () => { @@ -281,9 +250,10 @@ unitTest({ perms: { read: true } }, async function lstatNotFound(): Promise< }, Deno.errors.NotFound); }); -unitTest( - { ignore: Deno.build.os !== "windows", perms: { read: true, write: true } }, - function statNoUnixFields(): void { +Deno.test({ + name: "statNoUnixFields", + ignore: Deno.build.os !== "windows", + fn(): void { const enc = new TextEncoder(); const data = enc.encode("Hello"); const tempDir = Deno.makeTempDirSync(); @@ -300,11 +270,12 @@ unitTest( assert(s.blksize === null); assert(s.blocks === null); }, -); +}); -unitTest( - { ignore: Deno.build.os === "windows", perms: { read: true, write: true } }, - function statUnixFields(): void { +Deno.test({ + name: "statUnixFields", + ignore: Deno.build.os === "windows", + fn(): void { const enc = new TextEncoder(); const data = enc.encode("Hello"); const tempDir = Deno.makeTempDirSync(); @@ -324,4 +295,36 @@ unitTest( assert(s.blksize !== null); assert(s.blocks !== null); }, -); +}); + +Deno.test("statSyncPerm", async function (): Promise { + await Deno.permissions.revoke({ name: "read" }); + + assertThrows(() => { + Deno.statSync("README.md"); + }, Deno.errors.PermissionDenied); +}); + +Deno.test("lstatSyncPerm", async function (): Promise { + await Deno.permissions.revoke({ name: "read" }); + + assertThrows(() => { + Deno.lstatSync("README.md"); + }, Deno.errors.PermissionDenied); +}); + +Deno.test("statPerm", async function (): Promise { + await Deno.permissions.revoke({ name: "read" }); + + await assertThrowsAsync(async () => { + await Deno.stat("README.md"); + }, Deno.errors.PermissionDenied); +}); + +Deno.test("lstatPerm", async function (): Promise { + await Deno.permissions.revoke({ name: "read" }); + + await assertThrowsAsync(async () => { + await Deno.lstat("README.md"); + }, Deno.errors.PermissionDenied); +}); diff --git a/cli/tests/unit/stdio_test.ts b/cli/tests/unit/stdio_test.ts index 628f3f5613c301..2fc32854863f42 100644 --- a/cli/tests/unit/stdio_test.ts +++ b/cli/tests/unit/stdio_test.ts @@ -1,32 +1,32 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assertEquals, unitTest } from "./test_util.ts"; +import { assertEquals } from "./test_util.ts"; -unitTest(async function stdioStdinRead() { +Deno.test("stdioStdinRead", async function () { const nread = await Deno.stdin.read(new Uint8Array(0)); assertEquals(nread, 0); }); -unitTest(function stdioStdinReadSync() { +Deno.test("stdioStdinReadSync", function () { const nread = Deno.stdin.readSync(new Uint8Array(0)); assertEquals(nread, 0); }); -unitTest(async function stdioStdoutWrite() { +Deno.test("stdioStdoutWrite", async function () { const nwritten = await Deno.stdout.write(new Uint8Array(0)); assertEquals(nwritten, 0); }); -unitTest(function stdioStdoutWriteSync() { +Deno.test("stdioStdoutWriteSync", function () { const nwritten = Deno.stdout.writeSync(new Uint8Array(0)); assertEquals(nwritten, 0); }); -unitTest(async function stdioStderrWrite() { +Deno.test("stdioStderrWrite", async function () { const nwritten = await Deno.stderr.write(new Uint8Array(0)); assertEquals(nwritten, 0); }); -unitTest(function stdioStderrWriteSync() { +Deno.test("stdioStderrWriteSync", function () { const nwritten = Deno.stderr.writeSync(new Uint8Array(0)); assertEquals(nwritten, 0); }); diff --git a/cli/tests/unit/streams_deprecated.ts b/cli/tests/unit/streams_deprecated.ts index 77750072c95340..878afccd5a2ba8 100644 --- a/cli/tests/unit/streams_deprecated.ts +++ b/cli/tests/unit/streams_deprecated.ts @@ -1,7 +1,7 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assertEquals, unitTest } from "./test_util.ts"; +import { assertEquals } from "./test_util.ts"; -unitTest(async function symlinkSyncPerm() { +Deno.test("symlinkSyncPerm", async function () { const rs = new ReadableStream({ start(controller) { controller.enqueue("hello "); diff --git a/cli/tests/unit/symlink_test.ts b/cli/tests/unit/symlink_test.ts index 19e83660bb31cd..2aff28800f4aaf 100644 --- a/cli/tests/unit/symlink_test.ts +++ b/cli/tests/unit/symlink_test.ts @@ -1,38 +1,34 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assert, assertThrows, unitTest } from "./test_util.ts"; +import { assert, assertThrows } from "./test_util.ts"; -unitTest( - { perms: { read: true, write: true } }, - function symlinkSyncSuccess(): void { - const testDir = Deno.makeTempDirSync(); - const oldname = testDir + "/oldname"; - const newname = testDir + "/newname"; - Deno.mkdirSync(oldname); - Deno.symlinkSync(oldname, newname); - const newNameInfoLStat = Deno.lstatSync(newname); - const newNameInfoStat = Deno.statSync(newname); - assert(newNameInfoLStat.isSymlink); - assert(newNameInfoStat.isDirectory); - }, -); +Deno.test("symlinkSyncSuccess", function (): void { + const testDir = Deno.makeTempDirSync(); + const oldname = testDir + "/oldname"; + const newname = testDir + "/newname"; + Deno.mkdirSync(oldname); + Deno.symlinkSync(oldname, newname); + const newNameInfoLStat = Deno.lstatSync(newname); + const newNameInfoStat = Deno.statSync(newname); + assert(newNameInfoLStat.isSymlink); + assert(newNameInfoStat.isDirectory); +}); + +Deno.test("symlinkSuccess", async function (): Promise { + const testDir = Deno.makeTempDirSync(); + const oldname = testDir + "/oldname"; + const newname = testDir + "/newname"; + Deno.mkdirSync(oldname); + await Deno.symlink(oldname, newname); + const newNameInfoLStat = Deno.lstatSync(newname); + const newNameInfoStat = Deno.statSync(newname); + assert(newNameInfoLStat.isSymlink, "NOT SYMLINK"); + assert(newNameInfoStat.isDirectory, "NOT DIRECTORY"); +}); + +Deno.test("symlinkSyncPerm", async function (): Promise { + await Deno.permissions.revoke({ name: "write" }); -unitTest(function symlinkSyncPerm(): void { assertThrows(() => { Deno.symlinkSync("oldbaddir", "newbaddir"); }, Deno.errors.PermissionDenied); }); - -unitTest( - { perms: { read: true, write: true } }, - async function symlinkSuccess(): Promise { - const testDir = Deno.makeTempDirSync(); - const oldname = testDir + "/oldname"; - const newname = testDir + "/newname"; - Deno.mkdirSync(oldname); - await Deno.symlink(oldname, newname); - const newNameInfoLStat = Deno.lstatSync(newname); - const newNameInfoStat = Deno.statSync(newname); - assert(newNameInfoLStat.isSymlink, "NOT SYMLINK"); - assert(newNameInfoStat.isDirectory, "NOT DIRECTORY"); - }, -); diff --git a/cli/tests/unit/sync_test.ts b/cli/tests/unit/sync_test.ts index 98b2f4bd98ccaa..15db3dc9ddb1e2 100644 --- a/cli/tests/unit/sync_test.ts +++ b/cli/tests/unit/sync_test.ts @@ -1,74 +1,62 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assertEquals, unitTest } from "./test_util.ts"; +import { assertEquals } from "./test_util.ts"; -unitTest( - { perms: { read: true, write: true } }, - function fdatasyncSyncSuccess(): void { - const filename = Deno.makeTempDirSync() + "/test_fdatasyncSync.txt"; - const file = Deno.openSync(filename, { - read: true, - write: true, - create: true, - }); - const data = new Uint8Array(64); - Deno.writeSync(file.rid, data); - Deno.fdatasyncSync(file.rid); - assertEquals(Deno.readFileSync(filename), data); - Deno.close(file.rid); - Deno.removeSync(filename); - }, -); +Deno.test("fdatasyncSyncSuccess", function (): void { + const filename = Deno.makeTempDirSync() + "/test_fdatasyncSync.txt"; + const file = Deno.openSync(filename, { + read: true, + write: true, + create: true, + }); + const data = new Uint8Array(64); + Deno.writeSync(file.rid, data); + Deno.fdatasyncSync(file.rid); + assertEquals(Deno.readFileSync(filename), data); + Deno.close(file.rid); + Deno.removeSync(filename); +}); -unitTest( - { perms: { read: true, write: true } }, - async function fdatasyncSuccess(): Promise { - const filename = (await Deno.makeTempDir()) + "/test_fdatasync.txt"; - const file = await Deno.open(filename, { - read: true, - write: true, - create: true, - }); - const data = new Uint8Array(64); - await Deno.write(file.rid, data); - await Deno.fdatasync(file.rid); - assertEquals(await Deno.readFile(filename), data); - Deno.close(file.rid); - await Deno.remove(filename); - }, -); +Deno.test("fdatasyncSuccess", async function (): Promise { + const filename = (await Deno.makeTempDir()) + "/test_fdatasync.txt"; + const file = await Deno.open(filename, { + read: true, + write: true, + create: true, + }); + const data = new Uint8Array(64); + await Deno.write(file.rid, data); + await Deno.fdatasync(file.rid); + assertEquals(await Deno.readFile(filename), data); + Deno.close(file.rid); + await Deno.remove(filename); +}); -unitTest( - { perms: { read: true, write: true } }, - function fsyncSyncSuccess(): void { - const filename = Deno.makeTempDirSync() + "/test_fsyncSync.txt"; - const file = Deno.openSync(filename, { - read: true, - write: true, - create: true, - }); - const size = 64; - Deno.ftruncateSync(file.rid, size); - Deno.fsyncSync(file.rid); - assertEquals(Deno.statSync(filename).size, size); - Deno.close(file.rid); - Deno.removeSync(filename); - }, -); +Deno.test("fsyncSyncSuccess", function (): void { + const filename = Deno.makeTempDirSync() + "/test_fsyncSync.txt"; + const file = Deno.openSync(filename, { + read: true, + write: true, + create: true, + }); + const size = 64; + Deno.ftruncateSync(file.rid, size); + Deno.fsyncSync(file.rid); + assertEquals(Deno.statSync(filename).size, size); + Deno.close(file.rid); + Deno.removeSync(filename); +}); -unitTest( - { perms: { read: true, write: true } }, - async function fsyncSuccess(): Promise { - const filename = (await Deno.makeTempDir()) + "/test_fsync.txt"; - const file = await Deno.open(filename, { - read: true, - write: true, - create: true, - }); - const size = 64; - await Deno.ftruncate(file.rid, size); - await Deno.fsync(file.rid); - assertEquals((await Deno.stat(filename)).size, size); - Deno.close(file.rid); - await Deno.remove(filename); - }, -); +Deno.test("fsyncSuccess", async function (): Promise { + const filename = (await Deno.makeTempDir()) + "/test_fsync.txt"; + const file = await Deno.open(filename, { + read: true, + write: true, + create: true, + }); + const size = 64; + await Deno.ftruncate(file.rid, size); + await Deno.fsync(file.rid); + assertEquals((await Deno.stat(filename)).size, size); + Deno.close(file.rid); + await Deno.remove(filename); +}); diff --git a/cli/tests/unit/test_util.ts b/cli/tests/unit/test_util.ts index e6adc6583c06ca..a5290bc645e3fd 100644 --- a/cli/tests/unit/test_util.ts +++ b/cli/tests/unit/test_util.ts @@ -24,343 +24,8 @@ export { deferred } from "../../../test_util/std/async/deferred.ts"; export { readLines } from "../../../test_util/std/io/bufio.ts"; export { parse as parseArgs } from "../../../test_util/std/flags/mod.ts"; -export interface Permissions { - read: boolean; - write: boolean; - net: boolean; - env: boolean; - run: boolean; - plugin: boolean; - hrtime: boolean; -} - -export function fmtPerms(perms: Permissions): string { - const p = Object.keys(perms) - .filter((e): boolean => perms[e as keyof Permissions] === true) - .map((key) => `--allow-${key}`); - - if (p.length) { - return p.join(" "); - } - - return ""; -} - -const isGranted = async (name: Deno.PermissionName): Promise => - (await Deno.permissions.query({ name })).state === "granted"; - -export async function getProcessPermissions(): Promise { - return { - run: await isGranted("run"), - read: await isGranted("read"), - write: await isGranted("write"), - net: await isGranted("net"), - env: await isGranted("env"), - plugin: await isGranted("plugin"), - hrtime: await isGranted("hrtime"), - }; -} - -export function permissionsMatch( - processPerms: Permissions, - requiredPerms: Permissions, -): boolean { - for (const permName in processPerms) { - if ( - processPerms[permName as keyof Permissions] !== - requiredPerms[permName as keyof Permissions] - ) { - return false; - } - } - - return true; -} - -export const permissionCombinations: Map = new Map(); - -function permToString(perms: Permissions): string { - const r = perms.read ? 1 : 0; - const w = perms.write ? 1 : 0; - const n = perms.net ? 1 : 0; - const e = perms.env ? 1 : 0; - const u = perms.run ? 1 : 0; - const p = perms.plugin ? 1 : 0; - const h = perms.hrtime ? 1 : 0; - return `permR${r}W${w}N${n}E${e}U${u}P${p}H${h}`; -} - -function registerPermCombination(perms: Permissions): void { - const key = permToString(perms); - if (!permissionCombinations.has(key)) { - permissionCombinations.set(key, perms); - } -} - -export async function registerUnitTests(): Promise { - const processPerms = await getProcessPermissions(); - - const onlyTests = REGISTERED_UNIT_TESTS.filter(({ only }) => only); - const unitTests = onlyTests.length > 0 ? onlyTests : REGISTERED_UNIT_TESTS; - for (const unitTestDefinition of unitTests) { - if (!permissionsMatch(processPerms, unitTestDefinition.perms)) { - continue; - } - - Deno.test(unitTestDefinition); - } -} - -function normalizeTestPermissions(perms: UnitTestPermissions): Permissions { - return { - read: !!perms.read, - write: !!perms.write, - net: !!perms.net, - run: !!perms.run, - env: !!perms.env, - plugin: !!perms.plugin, - hrtime: !!perms.hrtime, - }; -} - -interface UnitTestPermissions { - read?: boolean; - write?: boolean; - net?: boolean; - env?: boolean; - run?: boolean; - plugin?: boolean; - hrtime?: boolean; -} - -interface UnitTestOptions { - ignore?: boolean; - only?: boolean; - perms?: UnitTestPermissions; -} - -interface UnitTestDefinition extends Deno.TestDefinition { - ignore: boolean; - only: boolean; - perms: Permissions; -} - -type TestFunction = () => void | Promise; - -export const REGISTERED_UNIT_TESTS: UnitTestDefinition[] = []; - -export function unitTest(fn: TestFunction): void; -export function unitTest(options: UnitTestOptions, fn: TestFunction): void; -export function unitTest( - optionsOrFn: UnitTestOptions | TestFunction, - maybeFn?: TestFunction, -): void { - assert(optionsOrFn, "At least one argument is required"); - - let options: UnitTestOptions; - let name: string; - let fn: TestFunction; - - if (typeof optionsOrFn === "function") { - options = {}; - fn = optionsOrFn; - name = fn.name; - assert(name, "Missing test function name"); - } else { - options = optionsOrFn; - assert(maybeFn, "Missing test function definition"); - assert( - typeof maybeFn === "function", - "Second argument should be test function definition", - ); - fn = maybeFn; - name = fn.name; - assert(name, "Missing test function name"); - } - - const normalizedPerms = normalizeTestPermissions(options.perms || {}); - registerPermCombination(normalizedPerms); - - const unitTestDefinition: UnitTestDefinition = { - name, - fn, - ignore: !!options.ignore, - only: !!options.only, - perms: normalizedPerms, - }; - - REGISTERED_UNIT_TESTS.push(unitTestDefinition); -} - -const encoder = new TextEncoder(); - -// Replace functions with null, errors with their stack strings, and JSONify. -// deno-lint-ignore no-explicit-any -function serializeTestMessage(message: any): string { - return JSON.stringify({ - start: message.start && { - ...message.start, - tests: message.start.tests.map((test: Deno.TestDefinition) => ({ - ...test, - fn: null, - })), - }, - testStart: message.testStart && { ...message.testStart, fn: null }, - testEnd: message.testEnd && { - ...message.testEnd, - error: String(message.testEnd.error?.stack), - }, - end: message.end && { - ...message.end, - // deno-lint-ignore no-explicit-any - results: message.end.results.map((result: any) => ({ - ...result, - error: result.error?.stack, - })), - }, - }); -} - -export async function reportToConn( - conn: Deno.Conn, - // deno-lint-ignore no-explicit-any - message: any, -): Promise { - const line = serializeTestMessage(message); - const encodedMsg = encoder.encode(line + (message.end == null ? "\n" : "")); - await Deno.writeAll(conn, encodedMsg); - if (message.end != null) { - conn.closeWrite(); - } -} - -unitTest(function permissionsMatches(): void { - assert( - permissionsMatch( - { - read: true, - write: false, - net: false, - env: false, - run: false, - plugin: false, - hrtime: false, - }, - normalizeTestPermissions({ read: true }), - ), - ); - - assert( - permissionsMatch( - { - read: false, - write: false, - net: false, - env: false, - run: false, - plugin: false, - hrtime: false, - }, - normalizeTestPermissions({}), - ), - ); - - assertEquals( - permissionsMatch( - { - read: false, - write: true, - net: true, - env: true, - run: true, - plugin: true, - hrtime: true, - }, - normalizeTestPermissions({ read: true }), - ), - false, - ); - - assertEquals( - permissionsMatch( - { - read: true, - write: false, - net: true, - env: false, - run: false, - plugin: false, - hrtime: false, - }, - normalizeTestPermissions({ read: true }), - ), - false, - ); - - assert( - permissionsMatch( - { - read: true, - write: true, - net: true, - env: true, - run: true, - plugin: true, - hrtime: true, - }, - { - read: true, - write: true, - net: true, - env: true, - run: true, - plugin: true, - hrtime: true, - }, - ), - ); -}); - -/* - * Ensure all unit test files (e.g. xxx_test.ts) are present as imports in - * cli/tests/unit/unit_tests.ts as it is easy to miss this out - */ -unitTest( - { perms: { read: true } }, - function assertAllUnitTestFilesImported(): void { - const directoryTestFiles = [...Deno.readDirSync("./cli/tests/unit/")] - .map((k) => k.name) - .filter( - (file) => - file!.endsWith(".ts") && - !file!.endsWith("unit_tests.ts") && - !file!.endsWith("test_util.ts") && - !file!.endsWith("unit_test_runner.ts"), - ); - const unitTestsFile: Uint8Array = Deno.readFileSync( - "./cli/tests/unit/unit_tests.ts", - ); - const importLines = new TextDecoder("utf-8") - .decode(unitTestsFile) - .split("\n") - .filter((line) => line.startsWith("import")); - const importedTestFiles = importLines.map( - (relativeFilePath) => relativeFilePath.match(/\/([^\/]+)";/)![1], - ); - - directoryTestFiles.forEach((dirFile) => { - if (!importedTestFiles.includes(dirFile!)) { - throw new Error( - "cil/tests/unit/unit_tests.ts is missing import of test file: cli/js/" + - dirFile, - ); - } - }); - }, -); - export function pathToAbsoluteFileUrl(path: string): URL { - path = resolve(path); - - return new URL(`file://${Deno.build.os === "windows" ? "/" : ""}${path}`); + return new URL( + `file://${Deno.build.os === "windows" ? "/" : ""}${resolve(path)}`, + ); } diff --git a/cli/tests/unit/testing_test.ts b/cli/tests/unit/testing_test.ts deleted file mode 100644 index 4789dbfa7fa3d8..00000000000000 --- a/cli/tests/unit/testing_test.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assertThrows, unitTest } from "./test_util.ts"; - -unitTest(function testFnOverloading(): void { - // just verifying that you can use this test definition syntax - Deno.test("test fn overloading", (): void => {}); -}); - -unitTest(function nameOfTestCaseCantBeEmpty(): void { - assertThrows( - () => { - Deno.test("", () => {}); - }, - TypeError, - "The test name can't be empty", - ); - assertThrows( - () => { - Deno.test({ - name: "", - fn: () => {}, - }); - }, - TypeError, - "The test name can't be empty", - ); -}); diff --git a/cli/tests/unit/text_encoding_test.ts b/cli/tests/unit/text_encoding_test.ts index c7c07f9373c2cf..445d14bb0e8505 100644 --- a/cli/tests/unit/text_encoding_test.ts +++ b/cli/tests/unit/text_encoding_test.ts @@ -1,19 +1,19 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assert, assertEquals, assertThrows, unitTest } from "./test_util.ts"; +import { assert, assertEquals, assertThrows } from "./test_util.ts"; -unitTest(function btoaSuccess(): void { +Deno.test("btoaSuccess", function (): void { const text = "hello world"; const encoded = btoa(text); assertEquals(encoded, "aGVsbG8gd29ybGQ="); }); -unitTest(function atobSuccess(): void { +Deno.test("atobSuccess", function (): void { const encoded = "aGVsbG8gd29ybGQ="; const decoded = atob(encoded); assertEquals(decoded, "hello world"); }); -unitTest(function atobWithAsciiWhitespace(): void { +Deno.test("atobWithAsciiWhitespace", function (): void { const encodedList = [ " aGVsbG8gd29ybGQ=", " aGVsbG8gd29ybGQ=", @@ -30,7 +30,7 @@ unitTest(function atobWithAsciiWhitespace(): void { } }); -unitTest(function atobThrows(): void { +Deno.test("atobThrows", function (): void { let threw = false; try { atob("aGVsbG8gd29ybGQ=="); @@ -40,7 +40,7 @@ unitTest(function atobThrows(): void { assert(threw); }); -unitTest(function atobThrows2(): void { +Deno.test("atobThrows2", function (): void { let threw = false; try { atob("aGVsbG8gd29ybGQ==="); @@ -50,7 +50,7 @@ unitTest(function atobThrows2(): void { assert(threw); }); -unitTest(function atobThrows3(): void { +Deno.test("atobThrows3", function (): void { let threw = false; try { atob("foobar!!"); @@ -65,14 +65,14 @@ unitTest(function atobThrows3(): void { assert(threw); }); -unitTest(function btoaFailed(): void { +Deno.test("btoaFailed", function (): void { const text = "你好"; assertThrows(() => { btoa(text); }, DOMException); }); -unitTest(function textDecoder2(): void { +Deno.test("textDecoder2", function (): void { // deno-fmt-ignore const fixture = new Uint8Array([ 0xf0, 0x9d, 0x93, 0xbd, @@ -86,13 +86,13 @@ unitTest(function textDecoder2(): void { // ignoreBOM is tested through WPT -unitTest(function textDecoderASCII(): void { +Deno.test("textDecoderASCII", function (): void { const fixture = new Uint8Array([0x89, 0x95, 0x9f, 0xbf]); const decoder = new TextDecoder("ascii"); assertEquals(decoder.decode(fixture), "‰•Ÿ¿"); }); -unitTest(function textDecoderErrorEncoding(): void { +Deno.test("textDecoderErrorEncoding", function (): void { let didThrow = false; try { new TextDecoder("Foo"); @@ -103,7 +103,7 @@ unitTest(function textDecoderErrorEncoding(): void { assert(didThrow); }); -unitTest(function textEncoder(): void { +Deno.test("textEncoder", function (): void { const fixture = "𝓽𝓮𝔁𝓽"; const encoder = new TextEncoder(); // deno-fmt-ignore @@ -115,7 +115,7 @@ unitTest(function textEncoder(): void { ]); }); -unitTest(function textEncodeInto(): void { +Deno.test("textEncodeInto", function (): void { const fixture = "text"; const encoder = new TextEncoder(); const bytes = new Uint8Array(5); @@ -128,7 +128,7 @@ unitTest(function textEncodeInto(): void { ]); }); -unitTest(function textEncodeInto2(): void { +Deno.test("textEncodeInto2", function (): void { const fixture = "𝓽𝓮𝔁𝓽"; const encoder = new TextEncoder(); const bytes = new Uint8Array(17); @@ -144,7 +144,7 @@ unitTest(function textEncodeInto2(): void { ]); }); -unitTest(function textEncodeInto3(): void { +Deno.test("textEncodeInto3", function (): void { const fixture = "𝓽𝓮𝔁𝓽"; const encoder = new TextEncoder(); const bytes = new Uint8Array(5); @@ -157,7 +157,7 @@ unitTest(function textEncodeInto3(): void { ]); }); -unitTest(function textDecoderSharedUint8Array(): void { +Deno.test("textDecoderSharedUint8Array", function (): void { const ab = new SharedArrayBuffer(6); const dataView = new DataView(ab); const charCodeA = "A".charCodeAt(0); @@ -170,7 +170,7 @@ unitTest(function textDecoderSharedUint8Array(): void { assertEquals(actual, "ABCDEF"); }); -unitTest(function textDecoderSharedInt32Array(): void { +Deno.test("textDecoderSharedInt32Array", function (): void { const ab = new SharedArrayBuffer(8); const dataView = new DataView(ab); const charCodeA = "A".charCodeAt(0); @@ -183,14 +183,14 @@ unitTest(function textDecoderSharedInt32Array(): void { assertEquals(actual, "ABCDEFGH"); }); -unitTest(function toStringShouldBeWebCompatibility(): void { +Deno.test("toStringShouldBeWebCompatibility", function (): void { const encoder = new TextEncoder(); assertEquals(encoder.toString(), "[object TextEncoder]"); const decoder = new TextDecoder(); assertEquals(decoder.toString(), "[object TextDecoder]"); }); -unitTest(function textEncoderShouldCoerceToString(): void { +Deno.test("textEncoderShouldCoerceToString", function (): void { const encoder = new TextEncoder(); const fixutreText = "text"; const fixture = { diff --git a/cli/tests/unit/timers_test.ts b/cli/tests/unit/timers_test.ts index 7276b3e35e1307..34b177df99ecb2 100644 --- a/cli/tests/unit/timers_test.ts +++ b/cli/tests/unit/timers_test.ts @@ -4,14 +4,13 @@ import { assertEquals, assertNotEquals, deferred, - unitTest, } from "./test_util.ts"; function waitForMs(ms: number): Promise { return new Promise((resolve): number => setTimeout(resolve, ms)); } -unitTest(async function functionParameterBindingSuccess(): Promise { +Deno.test("functionParameterBindingSuccess", async function (): Promise { const promise = deferred(); let count = 0; @@ -28,7 +27,7 @@ unitTest(async function functionParameterBindingSuccess(): Promise { assertEquals(count, 1); }); -unitTest(async function stringifyAndEvalNonFunctions(): Promise { +Deno.test("stringifyAndEvalNonFunctions", async function (): Promise { // eval can only access global scope const global = globalThis as unknown as { globalPromise: ReturnType; @@ -52,7 +51,7 @@ unitTest(async function stringifyAndEvalNonFunctions(): Promise { Reflect.deleteProperty(global, "globalCount"); }); -unitTest(async function timeoutSuccess(): Promise { +Deno.test("timeoutSuccess", async function (): Promise { const promise = deferred(); let count = 0; setTimeout((): void => { @@ -64,7 +63,7 @@ unitTest(async function timeoutSuccess(): Promise { assertEquals(count, 1); }); -unitTest(async function timeoutArgs(): Promise { +Deno.test("timeoutArgs", async function (): Promise { const promise = deferred(); const arg = 1; setTimeout( @@ -82,7 +81,7 @@ unitTest(async function timeoutArgs(): Promise { await promise; }); -unitTest(async function timeoutCancelSuccess(): Promise { +Deno.test("timeoutCancelSuccess", async function (): Promise { let count = 0; const id = setTimeout((): void => { count++; @@ -93,7 +92,7 @@ unitTest(async function timeoutCancelSuccess(): Promise { assertEquals(count, 0); }); -unitTest(async function timeoutCancelMultiple(): Promise { +Deno.test("timeoutCancelMultiple", async function (): Promise { function uncalled(): never { throw new Error("This function should not be called."); } @@ -118,7 +117,7 @@ unitTest(async function timeoutCancelMultiple(): Promise { await waitForMs(50); }); -unitTest(async function timeoutCancelInvalidSilentFail(): Promise { +Deno.test("timeoutCancelInvalidSilentFail", async function (): Promise { // Expect no panic const promise = deferred(); let count = 0; @@ -135,7 +134,7 @@ unitTest(async function timeoutCancelInvalidSilentFail(): Promise { clearTimeout(2147483647); }); -unitTest(async function intervalSuccess(): Promise { +Deno.test("intervalSuccess", async function (): Promise { const promise = deferred(); let count = 0; const id = setInterval((): void => { @@ -153,7 +152,7 @@ unitTest(async function intervalSuccess(): Promise { await waitForMs(0); }); -unitTest(async function intervalCancelSuccess(): Promise { +Deno.test("intervalCancelSuccess", async function (): Promise { let count = 0; const id = setInterval((): void => { count++; @@ -163,7 +162,7 @@ unitTest(async function intervalCancelSuccess(): Promise { assertEquals(count, 0); }); -unitTest(async function intervalOrdering(): Promise { +Deno.test("intervalOrdering", async function (): Promise { const timers: number[] = []; let timeouts = 0; function onTimeout(): void { @@ -179,12 +178,12 @@ unitTest(async function intervalOrdering(): Promise { assertEquals(timeouts, 1); }); -unitTest(function intervalCancelInvalidSilentFail(): void { +Deno.test("intervalCancelInvalidSilentFail", function (): void { // Should silently fail (no panic) clearInterval(2147483647); }); -unitTest(async function fireCallbackImmediatelyWhenDelayOverMaxValue(): Promise< +Deno.test("fireCallbackImmediatelyWhenDelayOverMaxValue", async function (): Promise< void > { let count = 0; @@ -195,7 +194,7 @@ unitTest(async function fireCallbackImmediatelyWhenDelayOverMaxValue(): Promise< assertEquals(count, 1); }); -unitTest(async function timeoutCallbackThis(): Promise { +Deno.test("timeoutCallbackThis", async function (): Promise { const promise = deferred(); const obj = { foo(): void { @@ -207,7 +206,7 @@ unitTest(async function timeoutCallbackThis(): Promise { await promise; }); -unitTest(async function timeoutBindThis(): Promise { +Deno.test("timeoutBindThis", async function (): Promise { const thisCheckPassed = [null, undefined, window, globalThis]; const thisCheckFailed = [ @@ -255,7 +254,7 @@ unitTest(async function timeoutBindThis(): Promise { } }); -unitTest(function clearTimeoutShouldConvertToNumber(): void { +Deno.test("clearTimeoutShouldConvertToNumber", function (): void { let called = false; const obj = { valueOf(): number { @@ -267,7 +266,7 @@ unitTest(function clearTimeoutShouldConvertToNumber(): void { assert(called); }); -unitTest(function setTimeoutShouldThrowWithBigint(): void { +Deno.test("setTimeoutShouldThrowWithBigint", function (): void { let hasThrown = 0; try { setTimeout((): void => {}, (1n as unknown) as number); @@ -282,7 +281,7 @@ unitTest(function setTimeoutShouldThrowWithBigint(): void { assertEquals(hasThrown, 2); }); -unitTest(function clearTimeoutShouldThrowWithBigint(): void { +Deno.test("clearTimeoutShouldThrowWithBigint", function (): void { let hasThrown = 0; try { clearTimeout((1n as unknown) as number); @@ -297,23 +296,23 @@ unitTest(function clearTimeoutShouldThrowWithBigint(): void { assertEquals(hasThrown, 2); }); -unitTest(function testFunctionName(): void { +Deno.test("testFunctionName", function (): void { assertEquals(clearTimeout.name, "clearTimeout"); assertEquals(clearInterval.name, "clearInterval"); }); -unitTest(function testFunctionParamsLength(): void { +Deno.test("testFunctionParamsLength", function (): void { assertEquals(setTimeout.length, 1); assertEquals(setInterval.length, 1); assertEquals(clearTimeout.length, 0); assertEquals(clearInterval.length, 0); }); -unitTest(function clearTimeoutAndClearIntervalNotBeEquals(): void { +Deno.test("clearTimeoutAndClearIntervalNotBeEquals", function (): void { assertNotEquals(clearTimeout, clearInterval); }); -unitTest(async function timerMaxCpuBug(): Promise { +Deno.test("timerMaxCpuBug", async function (): Promise { // There was a bug where clearing a timeout would cause Deno to use 100% CPU. clearTimeout(setTimeout(() => {}, 1000)); // We can check this by counting how many ops have triggered in the interim. @@ -324,7 +323,7 @@ unitTest(async function timerMaxCpuBug(): Promise { assert(opsDispatched_ - opsDispatched < 10); }); -unitTest(async function timerBasicMicrotaskOrdering(): Promise { +Deno.test("timerBasicMicrotaskOrdering", async function (): Promise { let s = ""; let count = 0; const promise = deferred(); @@ -348,7 +347,7 @@ unitTest(async function timerBasicMicrotaskOrdering(): Promise { assertEquals(s, "deno"); }); -unitTest(async function timerNestedMicrotaskOrdering(): Promise { +Deno.test("timerNestedMicrotaskOrdering", async function (): Promise { let s = ""; const promise = deferred(); s += "0"; @@ -384,11 +383,11 @@ unitTest(async function timerNestedMicrotaskOrdering(): Promise { assertEquals(s, "0123456789AB"); }); -unitTest(function testQueueMicrotask() { +Deno.test("testQueueMicrotask", function () { assertEquals(typeof queueMicrotask, "function"); }); -unitTest(async function timerIgnoresDateOverride(): Promise { +Deno.test("timerIgnoresDateOverride", async function (): Promise { const OriginalDate = Date; const promise = deferred(); let hasThrown = 0; @@ -422,51 +421,45 @@ unitTest(async function timerIgnoresDateOverride(): Promise { assertEquals(hasThrown, 1); }); -unitTest({ perms: { hrtime: true } }, function sleepSync(): void { +Deno.test("sleepSync", function (): void { const start = performance.now(); Deno.sleepSync(10); const after = performance.now(); assert(after - start >= 10); }); -unitTest( - { perms: { hrtime: true } }, - async function sleepSyncShorterPromise(): Promise { - const perf = performance; - const short = 5; - const long = 10; - - const start = perf.now(); - const p = sleepAsync(short).then(() => { - const after = perf.now(); - // pending promises should resolve after the main thread comes out of sleep - assert(after - start >= long); - }); - Deno.sleepSync(long); - - await p; - }, -); - -unitTest( - { perms: { hrtime: true } }, - async function sleepSyncLongerPromise(): Promise { - const perf = performance; - const short = 5; - const long = 10; - - const start = perf.now(); - const p = sleepAsync(long).then(() => { - const after = perf.now(); - // sleeping for less than the duration of a promise should have no impact - // on the resolution of that promise - assert(after - start >= long); - }); - Deno.sleepSync(short); +Deno.test("sleepSyncShorterPromise", async function (): Promise { + const perf = performance; + const short = 5; + const long = 10; - await p; - }, -); + const start = perf.now(); + const p = sleepAsync(short).then(() => { + const after = perf.now(); + // pending promises should resolve after the main thread comes out of sleep + assert(after - start >= long); + }); + Deno.sleepSync(long); + + await p; +}); + +Deno.test("sleepSyncLongerPromise", async function (): Promise { + const perf = performance; + const short = 5; + const long = 10; + + const start = perf.now(); + const p = sleepAsync(long).then(() => { + const after = perf.now(); + // sleeping for less than the duration of a promise should have no impact + // on the resolution of that promise + assert(after - start >= long); + }); + Deno.sleepSync(short); + + await p; +}); function sleepAsync(delay: number): Promise { return new Promise((resolve) => { diff --git a/cli/tests/unit/tls_test.ts b/cli/tests/unit/tls_test.ts index fa869037e29bcf..7212941c172e39 100644 --- a/cli/tests/unit/tls_test.ts +++ b/cli/tests/unit/tls_test.ts @@ -6,7 +6,6 @@ import { assertThrows, assertThrowsAsync, deferred, - unitTest, } from "./test_util.ts"; import { BufReader, BufWriter } from "../../../test_util/std/io/bufio.ts"; import { TextProtoReader } from "../../../test_util/std/textproto/mod.ts"; @@ -14,192 +13,148 @@ import { TextProtoReader } from "../../../test_util/std/textproto/mod.ts"; const encoder = new TextEncoder(); const decoder = new TextDecoder(); -unitTest(async function connectTLSNoPerm(): Promise { +Deno.test("connectTLSInvalidHost", async function (): Promise { + const listener = await Deno.listenTls({ + hostname: "localhost", + port: 3567, + certFile: "cli/tests/tls/localhost.crt", + keyFile: "cli/tests/tls/localhost.key", + }); + await assertThrowsAsync(async () => { - await Deno.connectTls({ hostname: "github.com", port: 443 }); - }, Deno.errors.PermissionDenied); -}); + await Deno.connectTls({ hostname: "127.0.0.1", port: 3567 }); + }, Error); -unitTest( - { perms: { read: true, net: true } }, - async function connectTLSInvalidHost(): Promise { - const listener = await Deno.listenTls({ - hostname: "localhost", - port: 3567, - certFile: "cli/tests/tls/localhost.crt", - keyFile: "cli/tests/tls/localhost.key", - }); + listener.close(); +}); - await assertThrowsAsync(async () => { - await Deno.connectTls({ hostname: "127.0.0.1", port: 3567 }); - }, Error); +Deno.test("listenTLSNonExistentCertKeyFiles", function (): void { + const options = { + hostname: "localhost", + port: 3500, + certFile: "cli/tests/tls/localhost.crt", + keyFile: "cli/tests/tls/localhost.key", + }; - listener.close(); - }, -); + assertThrows(() => { + Deno.listenTls({ + ...options, + certFile: "./non/existent/file", + }); + }, Deno.errors.NotFound); -unitTest(async function connectTLSCertFileNoReadPerm(): Promise { - await assertThrowsAsync(async () => { - await Deno.connectTls({ - hostname: "github.com", - port: 443, - certFile: "cli/tests/tls/RootCA.crt", + assertThrows(() => { + Deno.listenTls({ + ...options, + keyFile: "./non/existent/file", }); - }, Deno.errors.PermissionDenied); + }, Deno.errors.NotFound); }); -unitTest( - { perms: { read: true, net: true } }, - function listenTLSNonExistentCertKeyFiles(): void { - const options = { - hostname: "localhost", - port: 3500, - certFile: "cli/tests/tls/localhost.crt", - keyFile: "cli/tests/tls/localhost.key", - }; - - assertThrows(() => { - Deno.listenTls({ - ...options, - certFile: "./non/existent/file", - }); - }, Deno.errors.NotFound); - - assertThrows(() => { - Deno.listenTls({ - ...options, - keyFile: "./non/existent/file", - }); - }, Deno.errors.NotFound); - }, -); - -unitTest({ perms: { net: true } }, function listenTLSNoReadPerm(): void { +Deno.test("listenTLSEmptyKeyFile", function (): void { + const options = { + hostname: "localhost", + port: 3500, + certFile: "cli/tests/tls/localhost.crt", + keyFile: "cli/tests/tls/localhost.key", + }; + + const testDir = Deno.makeTempDirSync(); + const keyFilename = testDir + "/key.pem"; + Deno.writeFileSync(keyFilename, new Uint8Array([]), { + mode: 0o666, + }); + assertThrows(() => { Deno.listenTls({ - hostname: "localhost", - port: 3500, - certFile: "cli/tests/tls/localhost.crt", - keyFile: "cli/tests/tls/localhost.key", + ...options, + keyFile: keyFilename, }); - }, Deno.errors.PermissionDenied); + }, Error); }); -unitTest( - { - perms: { read: true, write: true, net: true }, - }, - function listenTLSEmptyKeyFile(): void { - const options = { - hostname: "localhost", - port: 3500, - certFile: "cli/tests/tls/localhost.crt", - keyFile: "cli/tests/tls/localhost.key", - }; +Deno.test("listenTLSEmptyCertFile", function (): void { + const options = { + hostname: "localhost", + port: 3500, + certFile: "cli/tests/tls/localhost.crt", + keyFile: "cli/tests/tls/localhost.key", + }; - const testDir = Deno.makeTempDirSync(); - const keyFilename = testDir + "/key.pem"; - Deno.writeFileSync(keyFilename, new Uint8Array([]), { - mode: 0o666, + const testDir = Deno.makeTempDirSync(); + const certFilename = testDir + "/cert.crt"; + Deno.writeFileSync(certFilename, new Uint8Array([]), { + mode: 0o666, + }); + + assertThrows(() => { + Deno.listenTls({ + ...options, + certFile: certFilename, }); + }, Error); +}); - assertThrows(() => { - Deno.listenTls({ - ...options, - keyFile: keyFilename, - }); - }, Error); - }, -); - -unitTest( - { perms: { read: true, write: true, net: true } }, - function listenTLSEmptyCertFile(): void { - const options = { - hostname: "localhost", - port: 3500, - certFile: "cli/tests/tls/localhost.crt", - keyFile: "cli/tests/tls/localhost.key", - }; +Deno.test("dialAndListenTLS", async function (): Promise { + const resolvable = deferred(); + const hostname = "localhost"; + const port = 3500; - const testDir = Deno.makeTempDirSync(); - const certFilename = testDir + "/cert.crt"; - Deno.writeFileSync(certFilename, new Uint8Array([]), { - mode: 0o666, - }); + const listener = Deno.listenTls({ + hostname, + port, + certFile: "cli/tests/tls/localhost.crt", + keyFile: "cli/tests/tls/localhost.key", + }); - assertThrows(() => { - Deno.listenTls({ - ...options, - certFile: certFilename, - }); - }, Error); - }, -); - -unitTest( - { perms: { read: true, net: true } }, - async function dialAndListenTLS(): Promise { - const resolvable = deferred(); - const hostname = "localhost"; - const port = 3500; - - const listener = Deno.listenTls({ - hostname, - port, - certFile: "cli/tests/tls/localhost.crt", - keyFile: "cli/tests/tls/localhost.key", - }); + const response = encoder.encode( + "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n", + ); - const response = encoder.encode( - "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n", - ); - - listener.accept().then( - async (conn): Promise => { - assert(conn.remoteAddr != null); - assert(conn.localAddr != null); - await conn.write(response); - // TODO(bartlomieju): this might be a bug - setTimeout(() => { - conn.close(); - resolvable.resolve(); - }, 0); - }, - ); - - const conn = await Deno.connectTls({ - hostname, - port, - certFile: "cli/tests/tls/RootCA.pem", - }); - assert(conn.rid > 0); - const w = new BufWriter(conn); - const r = new BufReader(conn); - const body = `GET / HTTP/1.1\r\nHost: ${hostname}:${port}\r\n\r\n`; - const writeResult = await w.write(encoder.encode(body)); - assertEquals(body.length, writeResult); - await w.flush(); - const tpr = new TextProtoReader(r); - const statusLine = await tpr.readLine(); - assert(statusLine !== null, `line must be read: ${String(statusLine)}`); - const m = statusLine.match(/^(.+?) (.+?) (.+?)$/); - assert(m !== null, "must be matched"); - const [_, proto, status, ok] = m; - assertEquals(proto, "HTTP/1.1"); - assertEquals(status, "200"); - assertEquals(ok, "OK"); - const headers = await tpr.readMIMEHeader(); - assert(headers !== null); - const contentLength = parseInt(headers.get("content-length")!); - const bodyBuf = new Uint8Array(contentLength); - await r.readFull(bodyBuf); - assertEquals(decoder.decode(bodyBuf), "Hello World\n"); - conn.close(); - listener.close(); - await resolvable; - }, -); + listener.accept().then( + async (conn): Promise => { + assert(conn.remoteAddr != null); + assert(conn.localAddr != null); + await conn.write(response); + // TODO(bartlomieju): this might be a bug + setTimeout(() => { + conn.close(); + resolvable.resolve(); + }, 0); + }, + ); + + const conn = await Deno.connectTls({ + hostname, + port, + certFile: "cli/tests/tls/RootCA.pem", + }); + assert(conn.rid > 0); + const w = new BufWriter(conn); + const r = new BufReader(conn); + const body = `GET / HTTP/1.1\r\nHost: ${hostname}:${port}\r\n\r\n`; + const writeResult = await w.write(encoder.encode(body)); + assertEquals(body.length, writeResult); + await w.flush(); + const tpr = new TextProtoReader(r); + const statusLine = await tpr.readLine(); + assert(statusLine !== null, `line must be read: ${String(statusLine)}`); + const m = statusLine.match(/^(.+?) (.+?) (.+?)$/); + assert(m !== null, "must be matched"); + const [_, proto, status, ok] = m; + assertEquals(proto, "HTTP/1.1"); + assertEquals(status, "200"); + assertEquals(ok, "OK"); + const headers = await tpr.readMIMEHeader(); + assert(headers !== null); + const contentLength = parseInt(headers.get("content-length")!); + const bodyBuf = new Uint8Array(contentLength); + await r.readFull(bodyBuf); + assertEquals(decoder.decode(bodyBuf), "Hello World\n"); + conn.close(); + listener.close(); + await resolvable; +}); async function tlsPair(port: number): Promise<[Deno.Conn, Deno.Conn]> { const listener = Deno.listenTls({ @@ -300,97 +255,115 @@ async function receiveAlotSendNothing(conn: Deno.Conn): Promise { conn.close(); } -unitTest( - { perms: { read: true, net: true } }, - async function tlsServerStreamHalfClose(): Promise { - const [serverConn, clientConn] = await tlsPair(3501); - await Promise.all([ - sendCloseWrite(serverConn), - receiveCloseWrite(clientConn), - ]); - }, -); - -unitTest( - { perms: { read: true, net: true } }, - async function tlsClientStreamHalfClose(): Promise { - const [serverConn, clientConn] = await tlsPair(3502); - await Promise.all([ - sendCloseWrite(clientConn), - receiveCloseWrite(serverConn), - ]); - }, -); - -unitTest( - { perms: { read: true, net: true } }, - async function tlsServerStreamCancelRead(): Promise { - const [serverConn, clientConn] = await tlsPair(3503); - await Promise.all([ - sendAlotReceiveNothing(serverConn), - receiveAlotSendNothing(clientConn), - ]); - }, -); - -unitTest( - { perms: { read: true, net: true } }, - async function tlsClientStreamCancelRead(): Promise { - const [serverConn, clientConn] = await tlsPair(3504); - await Promise.all([ - sendAlotReceiveNothing(clientConn), - receiveAlotSendNothing(serverConn), - ]); - }, -); - -unitTest( - { perms: { read: true, net: true } }, - async function startTls(): Promise { - const hostname = "smtp.gmail.com"; - const port = 587; - const encoder = new TextEncoder(); - - let conn = await Deno.connect({ - hostname, - port, - }); +Deno.test("tlsServerStreamHalfClose", async function (): Promise { + const [serverConn, clientConn] = await tlsPair(3501); + await Promise.all([ + sendCloseWrite(serverConn), + receiveCloseWrite(clientConn), + ]); +}); + +Deno.test("tlsClientStreamHalfClose", async function (): Promise { + const [serverConn, clientConn] = await tlsPair(3502); + await Promise.all([ + sendCloseWrite(clientConn), + receiveCloseWrite(serverConn), + ]); +}); + +Deno.test("tlsServerStreamCancelRead", async function (): Promise { + const [serverConn, clientConn] = await tlsPair(3503); + await Promise.all([ + sendAlotReceiveNothing(serverConn), + receiveAlotSendNothing(clientConn), + ]); +}); + +Deno.test("tlsClientStreamCancelRead", async function (): Promise { + const [serverConn, clientConn] = await tlsPair(3504); + await Promise.all([ + sendAlotReceiveNothing(clientConn), + receiveAlotSendNothing(serverConn), + ]); +}); + +Deno.test("startTls", async function (): Promise { + const hostname = "smtp.gmail.com"; + const port = 587; + const encoder = new TextEncoder(); + + let conn = await Deno.connect({ + hostname, + port, + }); + + let writer = new BufWriter(conn); + let reader = new TextProtoReader(new BufReader(conn)); - let writer = new BufWriter(conn); - let reader = new TextProtoReader(new BufReader(conn)); + let line: string | null = (await reader.readLine()) as string; + assert(line.startsWith("220")); - let line: string | null = (await reader.readLine()) as string; - assert(line.startsWith("220")); + await writer.write(encoder.encode(`EHLO ${hostname}\r\n`)); + await writer.flush(); - await writer.write(encoder.encode(`EHLO ${hostname}\r\n`)); - await writer.flush(); + while ((line = (await reader.readLine()) as string)) { + assert(line.startsWith("250")); + if (line.startsWith("250 ")) break; + } + + await writer.write(encoder.encode("STARTTLS\r\n")); + await writer.flush(); + + line = await reader.readLine(); + + // Received the message that the server is ready to establish TLS + assertEquals(line, "220 2.0.0 Ready to start TLS"); - while ((line = (await reader.readLine()) as string)) { - assert(line.startsWith("250")); - if (line.startsWith("250 ")) break; - } + conn = await Deno.startTls(conn, { hostname }); + writer = new BufWriter(conn); + reader = new TextProtoReader(new BufReader(conn)); - await writer.write(encoder.encode("STARTTLS\r\n")); - await writer.flush(); + // After that use TLS communication again + await writer.write(encoder.encode(`EHLO ${hostname}\r\n`)); + await writer.flush(); - line = await reader.readLine(); + while ((line = (await reader.readLine()) as string)) { + assert(line.startsWith("250")); + if (line.startsWith("250 ")) break; + } + + conn.close(); +}); - // Received the message that the server is ready to establish TLS - assertEquals(line, "220 2.0.0 Ready to start TLS"); +Deno.test("connectTLSCertFileNoReadPerm", async function (): Promise { + await Deno.permissions.revoke({ name: "read" }); + + await assertThrowsAsync(async () => { + await Deno.connectTls({ + hostname: "github.com", + port: 443, + certFile: "cli/tests/tls/RootCA.crt", + }); + }, Deno.errors.PermissionDenied); +}); - conn = await Deno.startTls(conn, { hostname }); - writer = new BufWriter(conn); - reader = new TextProtoReader(new BufReader(conn)); +Deno.test("connectTLSNoPerm", async function (): Promise { + await Deno.permissions.revoke({ name: "net" }); - // After that use TLS communication again - await writer.write(encoder.encode(`EHLO ${hostname}\r\n`)); - await writer.flush(); + await assertThrowsAsync(async () => { + await Deno.connectTls({ hostname: "github.com", port: 443 }); + }, Deno.errors.PermissionDenied); +}); - while ((line = (await reader.readLine()) as string)) { - assert(line.startsWith("250")); - if (line.startsWith("250 ")) break; - } +Deno.test("listenTLSNoReadPerm", async function (): Promise { + await Deno.permissions.revoke({ name: "read" }); - conn.close(); - }, -); + assertThrows(() => { + Deno.listenTls({ + hostname: "localhost", + port: 3500, + certFile: "cli/tests/tls/localhost.crt", + keyFile: "cli/tests/tls/localhost.key", + }); + }, Deno.errors.PermissionDenied); +}); diff --git a/cli/tests/unit/truncate_test.ts b/cli/tests/unit/truncate_test.ts index 19cb9328a40be7..d81e7558647422 100644 --- a/cli/tests/unit/truncate_test.ts +++ b/cli/tests/unit/truncate_test.ts @@ -1,94 +1,81 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { - assertEquals, - assertThrows, - assertThrowsAsync, - unitTest, -} from "./test_util.ts"; +import { assertEquals, assertThrows, assertThrowsAsync } from "./test_util.ts"; -unitTest( - { perms: { read: true, write: true } }, - function ftruncateSyncSuccess(): void { - const filename = Deno.makeTempDirSync() + "/test_ftruncateSync.txt"; - const file = Deno.openSync(filename, { - create: true, - read: true, - write: true, - }); +Deno.test("ftruncateSyncSuccess", function (): void { + const filename = Deno.makeTempDirSync() + "/test_ftruncateSync.txt"; + const file = Deno.openSync(filename, { + create: true, + read: true, + write: true, + }); - Deno.ftruncateSync(file.rid, 20); - assertEquals(Deno.readFileSync(filename).byteLength, 20); - Deno.ftruncateSync(file.rid, 5); - assertEquals(Deno.readFileSync(filename).byteLength, 5); - Deno.ftruncateSync(file.rid, -5); - assertEquals(Deno.readFileSync(filename).byteLength, 0); + Deno.ftruncateSync(file.rid, 20); + assertEquals(Deno.readFileSync(filename).byteLength, 20); + Deno.ftruncateSync(file.rid, 5); + assertEquals(Deno.readFileSync(filename).byteLength, 5); + Deno.ftruncateSync(file.rid, -5); + assertEquals(Deno.readFileSync(filename).byteLength, 0); - Deno.close(file.rid); - Deno.removeSync(filename); - }, -); + Deno.close(file.rid); + Deno.removeSync(filename); +}); + +Deno.test("ftruncateSuccess", async function (): Promise { + const filename = Deno.makeTempDirSync() + "/test_ftruncate.txt"; + const file = await Deno.open(filename, { + create: true, + read: true, + write: true, + }); -unitTest( - { perms: { read: true, write: true } }, - async function ftruncateSuccess(): Promise { - const filename = Deno.makeTempDirSync() + "/test_ftruncate.txt"; - const file = await Deno.open(filename, { - create: true, - read: true, - write: true, - }); + await Deno.ftruncate(file.rid, 20); + assertEquals((await Deno.readFile(filename)).byteLength, 20); + await Deno.ftruncate(file.rid, 5); + assertEquals((await Deno.readFile(filename)).byteLength, 5); + await Deno.ftruncate(file.rid, -5); + assertEquals((await Deno.readFile(filename)).byteLength, 0); - await Deno.ftruncate(file.rid, 20); - assertEquals((await Deno.readFile(filename)).byteLength, 20); - await Deno.ftruncate(file.rid, 5); - assertEquals((await Deno.readFile(filename)).byteLength, 5); - await Deno.ftruncate(file.rid, -5); - assertEquals((await Deno.readFile(filename)).byteLength, 0); + Deno.close(file.rid); + await Deno.remove(filename); +}); - Deno.close(file.rid); - await Deno.remove(filename); - }, -); +Deno.test("truncateSyncSuccess", function (): void { + const filename = Deno.makeTempDirSync() + "/test_truncateSync.txt"; + Deno.writeFileSync(filename, new Uint8Array(5)); + Deno.truncateSync(filename, 20); + assertEquals(Deno.readFileSync(filename).byteLength, 20); + Deno.truncateSync(filename, 5); + assertEquals(Deno.readFileSync(filename).byteLength, 5); + Deno.truncateSync(filename, -5); + assertEquals(Deno.readFileSync(filename).byteLength, 0); + Deno.removeSync(filename); +}); -unitTest( - { perms: { read: true, write: true } }, - function truncateSyncSuccess(): void { - const filename = Deno.makeTempDirSync() + "/test_truncateSync.txt"; - Deno.writeFileSync(filename, new Uint8Array(5)); - Deno.truncateSync(filename, 20); - assertEquals(Deno.readFileSync(filename).byteLength, 20); - Deno.truncateSync(filename, 5); - assertEquals(Deno.readFileSync(filename).byteLength, 5); - Deno.truncateSync(filename, -5); - assertEquals(Deno.readFileSync(filename).byteLength, 0); - Deno.removeSync(filename); - }, -); +Deno.test("truncateSuccess", async function (): Promise { + const filename = Deno.makeTempDirSync() + "/test_truncate.txt"; + await Deno.writeFile(filename, new Uint8Array(5)); + await Deno.truncate(filename, 20); + assertEquals((await Deno.readFile(filename)).byteLength, 20); + await Deno.truncate(filename, 5); + assertEquals((await Deno.readFile(filename)).byteLength, 5); + await Deno.truncate(filename, -5); + assertEquals((await Deno.readFile(filename)).byteLength, 0); + await Deno.remove(filename); +}); -unitTest( - { perms: { read: true, write: true } }, - async function truncateSuccess(): Promise { - const filename = Deno.makeTempDirSync() + "/test_truncate.txt"; - await Deno.writeFile(filename, new Uint8Array(5)); - await Deno.truncate(filename, 20); - assertEquals((await Deno.readFile(filename)).byteLength, 20); - await Deno.truncate(filename, 5); - assertEquals((await Deno.readFile(filename)).byteLength, 5); - await Deno.truncate(filename, -5); - assertEquals((await Deno.readFile(filename)).byteLength, 0); - await Deno.remove(filename); - }, -); +Deno.test("truncateSyncPerm", async function (): Promise { + await Deno.permissions.revoke({ name: "write" }); -unitTest({ perms: { write: false } }, function truncateSyncPerm(): void { assertThrows(() => { Deno.truncateSync("/test_truncateSyncPermission.txt"); }, Deno.errors.PermissionDenied); }); -unitTest({ perms: { write: false } }, async function truncatePerm(): Promise< +Deno.test("truncatePerm", async function (): Promise< void > { + await Deno.permissions.revoke({ name: "write" }); + await assertThrowsAsync(async () => { await Deno.truncate("/test_truncatePermission.txt"); }, Deno.errors.PermissionDenied); diff --git a/cli/tests/unit/tty_test.ts b/cli/tests/unit/tty_test.ts index 8f9b953729a3c7..e016bb2ecbc259 100644 --- a/cli/tests/unit/tty_test.ts +++ b/cli/tests/unit/tty_test.ts @@ -1,9 +1,9 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assert, assertThrows, unitTest } from "./test_util.ts"; +import { assert, assertThrows } from "./test_util.ts"; // Note tests for Deno.setRaw is in integration tests. -unitTest({ perms: { read: true } }, function consoleSizeFile(): void { +Deno.test("consoleSizeFile", function (): void { const file = Deno.openSync("cli/tests/hello.txt"); assertThrows(() => { Deno.consoleSize(file.rid); @@ -11,21 +11,21 @@ unitTest({ perms: { read: true } }, function consoleSizeFile(): void { file.close(); }); -unitTest(function consoleSizeError(): void { +Deno.test("consoleSizeError", function (): void { assertThrows(() => { // Absurdly large rid. Deno.consoleSize(0x7fffffff); }, Deno.errors.BadResource); }); -unitTest({ perms: { read: true } }, function isatty(): void { +Deno.test("isatty", function (): void { // CI not under TTY, so cannot test stdin/stdout/stderr. const f = Deno.openSync("cli/tests/hello.txt"); assert(!Deno.isatty(f.rid)); f.close(); }); -unitTest(function isattyError(): void { +Deno.test("isattyError", function (): void { let caught = false; try { // Absurdly large rid. diff --git a/cli/tests/unit/umask_test.ts b/cli/tests/unit/umask_test.ts index aa10b15eb8d2b0..8484578d6c3c43 100644 --- a/cli/tests/unit/umask_test.ts +++ b/cli/tests/unit/umask_test.ts @@ -1,15 +1,14 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assertEquals, unitTest } from "./test_util.ts"; +import { assertEquals } from "./test_util.ts"; -unitTest( - { - ignore: Deno.build.os === "windows", - }, - function umaskSuccess(): void { +Deno.test({ + name: "umaskSuccess", + ignore: Deno.build.os === "windows", + fn(): void { const prevMask = Deno.umask(0o020); const newMask = Deno.umask(prevMask); const finalMask = Deno.umask(); assertEquals(newMask, 0o020); assertEquals(finalMask, prevMask); }, -); +}); diff --git a/cli/tests/unit/unit_test_runner.ts b/cli/tests/unit/unit_test_runner.ts deleted file mode 100755 index 6b039f5977efb6..00000000000000 --- a/cli/tests/unit/unit_test_runner.ts +++ /dev/null @@ -1,319 +0,0 @@ -#!/usr/bin/env -S deno run --reload --allow-run -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import "./unit_tests.ts"; -import { - colors, - fmtPerms, - parseArgs, - permissionCombinations, - Permissions, - readLines, - REGISTERED_UNIT_TESTS, - registerUnitTests, - reportToConn, -} from "./test_util.ts"; - -// @ts-expect-error TypeScript (as of 3.7) does not support indexing namespaces by symbol -const internalObj = Deno[Deno.internal]; -// deno-lint-ignore no-explicit-any -const reportToConsole = internalObj.reportToConsole as (message: any) => void; -// deno-lint-ignore no-explicit-any -const runTests = internalObj.runTests as (options: any) => Promise; - -interface PermissionSetTestResult { - perms: Permissions; - passed: boolean; - // deno-lint-ignore no-explicit-any - endMessage: any; - permsStr: string; -} - -const PERMISSIONS: Deno.PermissionName[] = [ - "read", - "write", - "net", - "env", - "run", - "plugin", - "hrtime", -]; - -/** - * Take a list of permissions and revoke missing permissions. - */ -async function dropWorkerPermissions( - requiredPermissions: Deno.PermissionName[], -): Promise { - const permsToDrop = PERMISSIONS.filter((p): boolean => { - return !requiredPermissions.includes(p); - }); - - for (const perm of permsToDrop) { - await Deno.permissions.revoke({ name: perm }); - } -} - -async function workerRunnerMain( - addrStr: string, - permsStr: string, - filter?: string, -): Promise { - const [hostname, port] = addrStr.split(":"); - const addr = { hostname, port: Number(port) }; - - let perms: Deno.PermissionName[] = []; - if (permsStr.length > 0) { - perms = permsStr.split(",") as Deno.PermissionName[]; - } - // Setup reporter - const conn = await Deno.connect(addr); - // Drop current process permissions to requested set - await dropWorkerPermissions(perms); - // Register unit tests that match process permissions - await registerUnitTests(); - // Execute tests - await runTests({ - exitOnFail: false, - filter, - reportToConsole: false, - onMessage: reportToConn.bind(null, conn), - }); -} - -function spawnWorkerRunner( - verbose: boolean, - addr: string, - perms: Permissions, - filter?: string, -): Deno.Process { - // run subsequent tests using same deno executable - const permStr = Object.keys(perms) - .filter((permName): boolean => { - return perms[permName as Deno.PermissionName] === true; - }) - .join(","); - - const cmd = [ - Deno.execPath(), - "run", - "--unstable", // TODO(ry) be able to test stable vs unstable - "--location=http://js-unit-tests/foo/bar", - "-A", - "cli/tests/unit/unit_test_runner.ts", - "--worker", - `--addr=${addr}`, - `--perms=${permStr}`, - ]; - - if (filter) { - cmd.push("--"); - cmd.push(filter); - } - - const ioMode = verbose ? "inherit" : "null"; - - const p = Deno.run({ - cmd, - stdin: ioMode, - stdout: ioMode, - stderr: ioMode, - }); - - return p; -} - -async function runTestsForPermissionSet( - listener: Deno.Listener, - addrStr: string, - verbose: boolean, - perms: Permissions, - filter?: string, -): Promise { - const permsFmt = fmtPerms(perms); - console.log(`Running tests for: ${permsFmt}`); - const workerProcess = spawnWorkerRunner(verbose, addrStr, perms, filter); - // Wait for worker subprocess to go online - const conn = await listener.accept(); - - let expectedPassedTests; - // deno-lint-ignore no-explicit-any - let endMessage: any; - - try { - for await (const line of readLines(conn)) { - // deno-lint-ignore no-explicit-any - const message = JSON.parse(line) as any; - reportToConsole(message); - if (message.start != null) { - expectedPassedTests = message.start.tests.length; - } else if (message.end != null) { - endMessage = message.end; - } - } - } finally { - // Close socket to worker. - conn.close(); - } - - if (expectedPassedTests == null) { - throw new Error("Worker runner didn't report start"); - } - - if (endMessage == null) { - throw new Error("Worker runner didn't report end"); - } - - const workerStatus = await workerProcess.status(); - if (!workerStatus.success) { - throw new Error( - `Worker runner exited with status code: ${workerStatus.code}`, - ); - } - - workerProcess.close(); - - const passed = expectedPassedTests === endMessage.passed + endMessage.ignored; - - return { - perms, - passed, - permsStr: permsFmt, - endMessage, - }; -} - -async function masterRunnerMain( - verbose: boolean, - filter?: string, -): Promise { - console.log( - "Discovered permission combinations for tests:", - permissionCombinations.size, - ); - - for (const perms of permissionCombinations.values()) { - console.log("\t" + fmtPerms(perms)); - } - - const testResults = new Set(); - const addr = { hostname: "127.0.0.1", port: 4510 }; - const addrStr = `${addr.hostname}:${addr.port}`; - const listener = Deno.listen(addr); - - for (const perms of permissionCombinations.values()) { - const result = await runTestsForPermissionSet( - listener, - addrStr, - verbose, - perms, - filter, - ); - testResults.add(result); - } - - // if any run tests returned non-zero status then whole test - // run should fail - let testsPassed = true; - - for (const testResult of testResults) { - const { permsStr, endMessage } = testResult; - console.log(`Summary for ${permsStr}`); - reportToConsole({ end: endMessage }); - testsPassed = testsPassed && testResult.passed; - } - - if (!testsPassed) { - console.error("Unit tests failed"); - Deno.exit(1); - } - - console.log("Unit tests passed"); - - if (REGISTERED_UNIT_TESTS.find(({ only }) => only)) { - console.error( - `\n${colors.red("FAILED")} because the "only" option was used`, - ); - Deno.exit(1); - } -} - -const HELP = `Unit test runner - -Run tests matching current process permissions: - - deno --allow-write unit_test_runner.ts - - deno --allow-net --allow-hrtime unit_test_runner.ts - - deno --allow-write unit_test_runner.ts -- testWriteFile - -Run "master" process that creates "worker" processes -for each discovered permission combination: - - deno -A unit_test_runner.ts --master - -Run worker process for given permissions: - - deno -A unit_test_runner.ts --worker --perms=net,read,write --addr=127.0.0.1:4500 - - -OPTIONS: - --master - Run in master mode, spawning worker processes for - each discovered permission combination - - --worker - Run in worker mode, requires "perms" and "addr" flags, - should be run with "-A" flag; after setup worker will - drop permissions to required set specified in "perms" - - --perms=... - Set of permissions this process should run tests with, - - --addr= - Address of TCP socket for reporting - -ARGS: - -- ... - Run only tests with names matching filter, must - be used after "--" -`; - -function assertOrHelp(expr: unknown): asserts expr { - if (!expr) { - console.log(HELP); - Deno.exit(1); - } -} - -async function main(): Promise { - const args = parseArgs(Deno.args, { - boolean: ["master", "worker", "verbose"], - "--": true, - }); - - if (args.help) { - console.log(HELP); - return; - } - - const filter = args["--"][0]; - - // Master mode - if (args.master) { - return masterRunnerMain(args.verbose, filter); - } - - // Worker mode - if (args.worker) { - assertOrHelp(typeof args.addr === "string"); - assertOrHelp(typeof args.perms === "string"); - return workerRunnerMain(args.addr, args.perms, filter); - } - - // Running tests matching current process permissions - await registerUnitTests(); - await runTests({ filter }); -} - -main(); diff --git a/cli/tests/unit/unit_tests.ts b/cli/tests/unit/unit_tests.ts deleted file mode 100644 index 6277abdfe171a9..00000000000000 --- a/cli/tests/unit/unit_tests.ts +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. - -// This test is executed as part of unit test suite. -// -// Test runner automatically spawns subprocesses for each required permissions combination. - -import "./abort_controller_test.ts"; -import "./blob_test.ts"; -import "./body_test.ts"; -import "./buffer_test.ts"; -import "./build_test.ts"; -import "./chmod_test.ts"; -import "./chown_test.ts"; -import "./console_test.ts"; -import "./copy_file_test.ts"; -import "./custom_event_test.ts"; -import "./dir_test.ts"; -import "./dispatch_buffer_test.ts"; -import "./dispatch_json_test.ts"; -import "./error_stack_test.ts"; -import "./event_test.ts"; -import "./event_target_test.ts"; -import "./fetch_test.ts"; -import "./file_test.ts"; -import "./filereader_test.ts"; -import "./files_test.ts"; -import "./filter_function_test.ts"; -import "./form_data_test.ts"; -import "./format_error_test.ts"; -import "./fs_events_test.ts"; -import "./get_random_values_test.ts"; -import "./globals_test.ts"; -import "./headers_test.ts"; -import "./internals_test.ts"; -import "./io_test.ts"; -import "./link_test.ts"; -import "./make_temp_test.ts"; -import "./metrics_test.ts"; -import "./dom_iterable_test.ts"; -import "./mkdir_test.ts"; -import "./net_test.ts"; -import "./os_test.ts"; -import "./permissions_test.ts"; -import "./path_from_url_test.ts"; -import "./process_test.ts"; -import "./progressevent_test.ts"; -import "./real_path_test.ts"; -import "./read_dir_test.ts"; -import "./read_text_file_test.ts"; -import "./read_file_test.ts"; -import "./read_link_test.ts"; -import "./remove_test.ts"; -import "./rename_test.ts"; -import "./request_test.ts"; -import "./resources_test.ts"; -import "./response_test.ts"; -import "./signal_test.ts"; -import "./stat_test.ts"; -import "./stdio_test.ts"; -import "./streams_deprecated.ts"; -import "./symlink_test.ts"; -import "./sync_test.ts"; -import "./text_encoding_test.ts"; -import "./testing_test.ts"; -import "./timers_test.ts"; -import "./tls_test.ts"; -import "./truncate_test.ts"; -import "./tty_test.ts"; -import "./umask_test.ts"; -import "./url_test.ts"; -import "./url_search_params_test.ts"; -import "./utime_test.ts"; -import "./worker_types.ts"; -import "./write_file_test.ts"; -import "./write_text_file_test.ts"; -import "./performance_test.ts"; -import "./version_test.ts"; -import "./websocket_test.ts"; -import "./webgpu_test.ts"; diff --git a/cli/tests/unit/url_search_params_test.ts b/cli/tests/unit/url_search_params_test.ts index c4df86a7f1b16d..873c20830c3c86 100644 --- a/cli/tests/unit/url_search_params_test.ts +++ b/cli/tests/unit/url_search_params_test.ts @@ -1,13 +1,13 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assert, assertEquals, unitTest } from "./test_util.ts"; +import { assert, assertEquals } from "./test_util.ts"; -unitTest(function urlSearchParamsWithMultipleSpaces(): void { +Deno.test("urlSearchParamsWithMultipleSpaces", function (): void { const init = { str: "this string has spaces in it" }; const searchParams = new URLSearchParams(init).toString(); assertEquals(searchParams, "str=this+string+has+spaces+in+it"); }); -unitTest(function urlSearchParamsWithExclamation(): void { +Deno.test("urlSearchParamsWithExclamation", function (): void { const init = [ ["str", "hello, world!"], ]; @@ -15,7 +15,7 @@ unitTest(function urlSearchParamsWithExclamation(): void { assertEquals(searchParams, "str=hello%2C+world%21"); }); -unitTest(function urlSearchParamsWithQuotes(): void { +Deno.test("urlSearchParamsWithQuotes", function (): void { const init = [ ["str", "'hello world'"], ]; @@ -23,7 +23,7 @@ unitTest(function urlSearchParamsWithQuotes(): void { assertEquals(searchParams, "str=%27hello+world%27"); }); -unitTest(function urlSearchParamsWithBraket(): void { +Deno.test("urlSearchParamsWithBraket", function (): void { const init = [ ["str", "(hello world)"], ]; @@ -31,7 +31,7 @@ unitTest(function urlSearchParamsWithBraket(): void { assertEquals(searchParams, "str=%28hello+world%29"); }); -unitTest(function urlSearchParamsWithTilde(): void { +Deno.test("urlSearchParamsWithTilde", function (): void { const init = [ ["str", "hello~world"], ]; @@ -39,7 +39,7 @@ unitTest(function urlSearchParamsWithTilde(): void { assertEquals(searchParams, "str=hello%7Eworld"); }); -unitTest(function urlSearchParamsInitString(): void { +Deno.test("urlSearchParamsInitString", function (): void { const init = "c=4&a=2&b=3&%C3%A1=1"; const searchParams = new URLSearchParams(init); assert( @@ -48,7 +48,7 @@ unitTest(function urlSearchParamsInitString(): void { ); }); -unitTest(function urlSearchParamsInitStringWithPlusCharacter(): void { +Deno.test("urlSearchParamsInitStringWithPlusCharacter", function (): void { let params = new URLSearchParams("q=a+b"); assertEquals(params.toString(), "q=a+b"); assertEquals(params.get("q"), "a b"); @@ -58,7 +58,7 @@ unitTest(function urlSearchParamsInitStringWithPlusCharacter(): void { assertEquals(params.get("q"), "a b c"); }); -unitTest(function urlSearchParamsInitStringWithMalformedParams(): void { +Deno.test("urlSearchParamsInitStringWithMalformedParams", function (): void { // These test cases are copied from Web Platform Tests // https://github.com/web-platform-tests/wpt/blob/54c6d64/url/urlsearchparams-constructor.any.js#L60-L80 let params = new URLSearchParams("id=0&value=%"); @@ -84,7 +84,7 @@ unitTest(function urlSearchParamsInitStringWithMalformedParams(): void { assertEquals(params.get("b"), "%*"); }); -unitTest(function urlSearchParamsInitIterable(): void { +Deno.test("urlSearchParamsInitIterable", function (): void { const init = [ ["a", "54"], ["b", "true"], @@ -93,13 +93,13 @@ unitTest(function urlSearchParamsInitIterable(): void { assertEquals(searchParams.toString(), "a=54&b=true"); }); -unitTest(function urlSearchParamsInitRecord(): void { +Deno.test("urlSearchParamsInitRecord", function (): void { const init = { a: "54", b: "true" }; const searchParams = new URLSearchParams(init); assertEquals(searchParams.toString(), "a=54&b=true"); }); -unitTest(function urlSearchParamsInit(): void { +Deno.test("urlSearchParamsInit", function (): void { const params1 = new URLSearchParams("a=b"); assertEquals(params1.toString(), "a=b"); // deno-lint-ignore no-explicit-any @@ -107,20 +107,20 @@ unitTest(function urlSearchParamsInit(): void { assertEquals(params2.toString(), "a=b"); }); -unitTest(function urlSearchParamsAppendSuccess(): void { +Deno.test("urlSearchParamsAppendSuccess", function (): void { const searchParams = new URLSearchParams(); searchParams.append("a", "true"); assertEquals(searchParams.toString(), "a=true"); }); -unitTest(function urlSearchParamsDeleteSuccess(): void { +Deno.test("urlSearchParamsDeleteSuccess", function (): void { const init = "a=54&b=true"; const searchParams = new URLSearchParams(init); searchParams.delete("b"); assertEquals(searchParams.toString(), "a=54"); }); -unitTest(function urlSearchParamsGetAllSuccess(): void { +Deno.test("urlSearchParamsGetAllSuccess", function (): void { const init = "a=54&b=true&a=true"; const searchParams = new URLSearchParams(init); assertEquals(searchParams.getAll("a"), ["54", "true"]); @@ -128,7 +128,7 @@ unitTest(function urlSearchParamsGetAllSuccess(): void { assertEquals(searchParams.getAll("c"), []); }); -unitTest(function urlSearchParamsGetSuccess(): void { +Deno.test("urlSearchParamsGetSuccess", function (): void { const init = "a=54&b=true&a=true"; const searchParams = new URLSearchParams(init); assertEquals(searchParams.get("a"), "54"); @@ -136,7 +136,7 @@ unitTest(function urlSearchParamsGetSuccess(): void { assertEquals(searchParams.get("c"), null); }); -unitTest(function urlSearchParamsHasSuccess(): void { +Deno.test("urlSearchParamsHasSuccess", function (): void { const init = "a=54&b=true&a=true"; const searchParams = new URLSearchParams(init); assert(searchParams.has("a")); @@ -144,28 +144,28 @@ unitTest(function urlSearchParamsHasSuccess(): void { assert(!searchParams.has("c")); }); -unitTest(function urlSearchParamsSetReplaceFirstAndRemoveOthers(): void { +Deno.test("urlSearchParamsSetReplaceFirstAndRemoveOthers", function (): void { const init = "a=54&b=true&a=true"; const searchParams = new URLSearchParams(init); searchParams.set("a", "false"); assertEquals(searchParams.toString(), "a=false&b=true"); }); -unitTest(function urlSearchParamsSetAppendNew(): void { +Deno.test("urlSearchParamsSetAppendNew", function (): void { const init = "a=54&b=true&a=true"; const searchParams = new URLSearchParams(init); searchParams.set("c", "foo"); assertEquals(searchParams.toString(), "a=54&b=true&a=true&c=foo"); }); -unitTest(function urlSearchParamsSortSuccess(): void { +Deno.test("urlSearchParamsSortSuccess", function (): void { const init = "c=4&a=2&b=3&a=1"; const searchParams = new URLSearchParams(init); searchParams.sort(); assertEquals(searchParams.toString(), "a=2&a=1&b=3&c=4"); }); -unitTest(function urlSearchParamsForEachSuccess(): void { +Deno.test("urlSearchParamsForEachSuccess", function (): void { const init = [ ["a", "54"], ["b", "true"], @@ -181,34 +181,34 @@ unitTest(function urlSearchParamsForEachSuccess(): void { assertEquals(callNum, init.length); }); -unitTest(function urlSearchParamsMissingName(): void { +Deno.test("urlSearchParamsMissingName", function (): void { const init = "=4"; const searchParams = new URLSearchParams(init); assertEquals(searchParams.get(""), "4"); assertEquals(searchParams.toString(), "=4"); }); -unitTest(function urlSearchParamsMissingValue(): void { +Deno.test("urlSearchParamsMissingValue", function (): void { const init = "4="; const searchParams = new URLSearchParams(init); assertEquals(searchParams.get("4"), ""); assertEquals(searchParams.toString(), "4="); }); -unitTest(function urlSearchParamsMissingEqualSign(): void { +Deno.test("urlSearchParamsMissingEqualSign", function (): void { const init = "4"; const searchParams = new URLSearchParams(init); assertEquals(searchParams.get("4"), ""); assertEquals(searchParams.toString(), "4="); }); -unitTest(function urlSearchParamsMissingPair(): void { +Deno.test("urlSearchParamsMissingPair", function (): void { const init = "c=4&&a=54&"; const searchParams = new URLSearchParams(init); assertEquals(searchParams.toString(), "c=4&a=54"); }); -unitTest(function urlSearchParamsForShortEncodedChar(): void { +Deno.test("urlSearchParamsForShortEncodedChar", function (): void { const init = { linefeed: "\n", tab: "\t" }; const searchParams = new URLSearchParams(init); assertEquals(searchParams.toString(), "linefeed=%0A&tab=%09"); @@ -216,7 +216,7 @@ unitTest(function urlSearchParamsForShortEncodedChar(): void { // If pair does not contain exactly two items, then throw a TypeError. // ref https://url.spec.whatwg.org/#interface-urlsearchparams -unitTest(function urlSearchParamsShouldThrowTypeError(): void { +Deno.test("urlSearchParamsShouldThrowTypeError", function (): void { let hasThrown = 0; try { @@ -246,7 +246,7 @@ unitTest(function urlSearchParamsShouldThrowTypeError(): void { assertEquals(hasThrown, 2); }); -unitTest(function urlSearchParamsAppendArgumentsCheck(): void { +Deno.test("urlSearchParamsAppendArgumentsCheck", function (): void { const methodRequireOneParam = ["delete", "getAll", "get", "has", "forEach"]; const methodRequireTwoParams = ["append", "set"]; @@ -289,7 +289,7 @@ unitTest(function urlSearchParamsAppendArgumentsCheck(): void { }); // ref: https://github.com/web-platform-tests/wpt/blob/master/url/urlsearchparams-delete.any.js -unitTest(function urlSearchParamsDeletingAppendedMultiple(): void { +Deno.test("urlSearchParamsDeletingAppendedMultiple", function (): void { const params = new URLSearchParams(); params.append("first", (1 as unknown) as string); assert(params.has("first")); @@ -303,7 +303,7 @@ unitTest(function urlSearchParamsDeletingAppendedMultiple(): void { }); // ref: https://github.com/web-platform-tests/wpt/blob/master/url/urlsearchparams-constructor.any.js#L176-L182 -unitTest(function urlSearchParamsCustomSymbolIterator(): void { +Deno.test("urlSearchParamsCustomSymbolIterator", function (): void { const params = new URLSearchParams(); params[Symbol.iterator] = function* (): IterableIterator<[string, string]> { yield ["a", "b"]; @@ -312,39 +312,35 @@ unitTest(function urlSearchParamsCustomSymbolIterator(): void { assertEquals(params1.get("a"), "b"); }); -unitTest( - function urlSearchParamsCustomSymbolIteratorWithNonStringParams(): void { - const params = {}; - // deno-lint-ignore no-explicit-any - (params as any)[Symbol.iterator] = function* (): IterableIterator< - [number, number] - > { - yield [1, 2]; - }; - const params1 = new URLSearchParams((params as unknown) as string[][]); - assertEquals(params1.get("1"), "2"); - }, -); +Deno.test("urlSearchParamsCustomSymbolIteratorWithNonStringParams", function (): void { + const params = {}; + // deno-lint-ignore no-explicit-any + (params as any)[Symbol.iterator] = function* (): IterableIterator< + [number, number] + > { + yield [1, 2]; + }; + const params1 = new URLSearchParams((params as unknown) as string[][]); + assertEquals(params1.get("1"), "2"); +}); // If a class extends URLSearchParams, override one method should not change another's behavior. -unitTest( - function urlSearchParamsOverridingAppendNotChangeConstructorAndSet(): void { - let overridedAppendCalled = 0; - class CustomSearchParams extends URLSearchParams { - append(name: string, value: string): void { - ++overridedAppendCalled; - super.append(name, value); - } +Deno.test("urlSearchParamsOverridingAppendNotChangeConstructorAndSet", function (): void { + let overridedAppendCalled = 0; + class CustomSearchParams extends URLSearchParams { + append(name: string, value: string): void { + ++overridedAppendCalled; + super.append(name, value); } - new CustomSearchParams("foo=bar"); - new CustomSearchParams([["foo", "bar"]]); - new CustomSearchParams(new CustomSearchParams({ foo: "bar" })); - new CustomSearchParams().set("foo", "bar"); - assertEquals(overridedAppendCalled, 0); - }, -); - -unitTest(function urlSearchParamsOverridingEntriesNotChangeForEach(): void { + } + new CustomSearchParams("foo=bar"); + new CustomSearchParams([["foo", "bar"]]); + new CustomSearchParams(new CustomSearchParams({ foo: "bar" })); + new CustomSearchParams().set("foo", "bar"); + assertEquals(overridedAppendCalled, 0); +}); + +Deno.test("urlSearchParamsOverridingEntriesNotChangeForEach", function (): void { class CustomSearchParams extends URLSearchParams { *entries(): IterableIterator<[string, string]> { yield* []; diff --git a/cli/tests/unit/url_test.ts b/cli/tests/unit/url_test.ts index 8d280ccb5abb29..70b8d69ce03263 100644 --- a/cli/tests/unit/url_test.ts +++ b/cli/tests/unit/url_test.ts @@ -4,10 +4,9 @@ import { assertEquals, assertStrictEquals, assertThrows, - unitTest, } from "./test_util.ts"; -unitTest(function urlParsing(): void { +Deno.test("urlParsing", function (): void { const url = new URL( "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat", ); @@ -33,7 +32,7 @@ unitTest(function urlParsing(): void { ); }); -unitTest(function urlProtocolParsing(): void { +Deno.test("urlProtocolParsing", function (): void { assertEquals(new URL("Aa+-.1://foo").protocol, "aa+-.1:"); assertEquals(new URL("aA+-.1://foo").protocol, "aa+-.1:"); assertThrows(() => new URL("1://foo"), TypeError, "Invalid URL"); @@ -50,7 +49,7 @@ unitTest(function urlProtocolParsing(): void { assertThrows(() => new URL("*://foo"), TypeError, "Invalid URL"); }); -unitTest(function urlAuthenticationParsing(): void { +Deno.test("urlAuthenticationParsing", function (): void { const specialUrl = new URL("http://foo:bar@baz"); assertEquals(specialUrl.username, "foo"); assertEquals(specialUrl.password, "bar"); @@ -62,7 +61,7 @@ unitTest(function urlAuthenticationParsing(): void { assertEquals(nonSpecialUrl.hostname, "baz"); }); -unitTest(function urlHostnameParsing(): void { +Deno.test("urlHostnameParsing", function (): void { // IPv6. assertEquals(new URL("http://[::1]").hostname, "[::1]"); assertEquals(new URL("file://[::1]").hostname, "[::1]"); @@ -102,7 +101,7 @@ unitTest(function urlHostnameParsing(): void { assertThrows(() => new URL("http://4294967296"), TypeError, "Invalid URL"); }); -unitTest(function urlPortParsing(): void { +Deno.test("urlPortParsing", function (): void { const specialUrl = new URL("http://foo:8000"); assertEquals(specialUrl.hostname, "foo"); assertEquals(specialUrl.port, "8000"); @@ -112,7 +111,7 @@ unitTest(function urlPortParsing(): void { assertEquals(nonSpecialUrl.port, "8000"); }); -unitTest(function urlModifications(): void { +Deno.test("urlModifications", function (): void { const url = new URL( "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat", ); @@ -167,7 +166,7 @@ unitTest(function urlModifications(): void { ); }); -unitTest(function urlModifyHref(): void { +Deno.test("urlModifyHref", function (): void { const url = new URL("http://example.com/"); url.href = "https://foo:bar@example.com:8080/baz/qat#qux"; assertEquals(url.protocol, "https:"); @@ -179,13 +178,13 @@ unitTest(function urlModifyHref(): void { assertEquals(url.hash, "#qux"); }); -unitTest(function urlNormalize(): void { +Deno.test("urlNormalize", function (): void { const url = new URL("http://example.com"); assertEquals(url.pathname, "/"); assertEquals(url.href, "http://example.com/"); }); -unitTest(function urlModifyPathname(): void { +Deno.test("urlModifyPathname", function (): void { const url = new URL("http://foo.bar/baz%qat/qux%quux"); assertEquals(url.pathname, "/baz%qat/qux%quux"); // Self-assignment is to invoke the setter. @@ -201,7 +200,7 @@ unitTest(function urlModifyPathname(): void { assertEquals(url.pathname, "/a/b/c"); }); -unitTest(function urlModifyHash(): void { +Deno.test("urlModifyHash", function (): void { const url = new URL("http://foo.bar"); url.hash = "%foo bar/qat%qux#bar"; assertEquals(url.hash, "#%foo%20bar/qat%qux#bar"); @@ -210,7 +209,7 @@ unitTest(function urlModifyHash(): void { assertEquals(url.hash, "#%foo%20bar/qat%qux#bar"); }); -unitTest(function urlSearchParamsReuse(): void { +Deno.test("urlSearchParamsReuse", function (): void { const url = new URL( "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat", ); @@ -219,7 +218,7 @@ unitTest(function urlSearchParamsReuse(): void { assert(sp === url.searchParams, "Search params should be reused."); }); -unitTest(function urlBackSlashes(): void { +Deno.test("urlBackSlashes", function (): void { const url = new URL( "https:\\\\foo:bar@baz.qat:8000\\qux\\quux?foo=bar&baz=12#qat", ); @@ -229,7 +228,7 @@ unitTest(function urlBackSlashes(): void { ); }); -unitTest(function urlProtocolSlashes(): void { +Deno.test("urlProtocolSlashes", function (): void { assertEquals(new URL("http:foo").href, "http://foo/"); assertEquals(new URL("http://foo").href, "http://foo/"); assertEquals(new URL("file:foo").href, "file:///foo"); @@ -238,7 +237,7 @@ unitTest(function urlProtocolSlashes(): void { assertEquals(new URL("abcd://foo").href, "abcd://foo"); }); -unitTest(function urlRequireHost(): void { +Deno.test("urlRequireHost", function (): void { assertEquals(new URL("file:///").href, "file:///"); assertThrows(() => new URL("ftp:///"), TypeError, "Invalid URL"); assertThrows(() => new URL("http:///"), TypeError, "Invalid URL"); @@ -247,7 +246,7 @@ unitTest(function urlRequireHost(): void { assertThrows(() => new URL("wss:///"), TypeError, "Invalid URL"); }); -unitTest(function urlDriveLetter() { +Deno.test("urlDriveLetter", function () { assertEquals(new URL("file:///C:").href, "file:///C:"); assertEquals(new URL("file:///C:/").href, "file:///C:/"); assertEquals(new URL("file:///C:/..").href, "file:///C:/"); @@ -269,28 +268,28 @@ unitTest(function urlDriveLetter() { // assertEquals(new URL("abcd://foo/C:/..").href, "abcd://foo/"); }); -unitTest(function urlHostnameUpperCase() { +Deno.test("urlHostnameUpperCase", function () { assertEquals(new URL("http://EXAMPLE.COM").href, "http://example.com/"); assertEquals(new URL("abcd://EXAMPLE.COM").href, "abcd://EXAMPLE.COM"); }); -unitTest(function urlEmptyPath() { +Deno.test("urlEmptyPath", function () { assertEquals(new URL("http://foo").pathname, "/"); assertEquals(new URL("file://foo").pathname, "/"); assertEquals(new URL("abcd://foo").pathname, ""); }); -unitTest(function urlPathRepeatedSlashes() { +Deno.test("urlPathRepeatedSlashes", function () { assertEquals(new URL("http://foo//bar//").pathname, "//bar//"); assertEquals(new URL("file://foo///bar//").pathname, "/bar//"); assertEquals(new URL("abcd://foo//bar//").pathname, "//bar//"); }); -unitTest(function urlTrim() { +Deno.test("urlTrim", function () { assertEquals(new URL(" http://example.com ").href, "http://example.com/"); }); -unitTest(function urlEncoding() { +Deno.test("urlEncoding", function () { assertEquals( new URL("http://a !$&*()=,;+'\"@example.com").username, "a%20!$&*()%3D,%3B+'%22", @@ -320,7 +319,7 @@ unitTest(function urlEncoding() { ); }); -unitTest(function urlBase(): void { +Deno.test("urlBase", function (): void { assertEquals(new URL("d", new URL("http://foo/a?b#c")).href, "http://foo/d"); assertEquals(new URL("", "http://foo/a/b?c#d").href, "http://foo/a/b?c"); @@ -362,12 +361,12 @@ unitTest(function urlBase(): void { assertEquals(new URL("/foo", "abcd:/").href, "abcd:/foo"); }); -unitTest(function urlDriveLetterBase() { +Deno.test("urlDriveLetterBase", function () { assertEquals(new URL("/b", "file:///C:/a/b").href, "file:///C:/b"); assertEquals(new URL("/D:", "file:///C:/a/b").href, "file:///D:"); }); -unitTest(function urlSameProtocolBase() { +Deno.test("urlSameProtocolBase", function () { assertEquals(new URL("http:", "http://foo/a").href, "http://foo/a"); assertEquals(new URL("file:", "file://foo/a").href, "file://foo/a"); assertEquals(new URL("abcd:", "abcd://foo/a").href, "abcd:"); @@ -377,7 +376,7 @@ unitTest(function urlSameProtocolBase() { assertEquals(new URL("abcd:b", "abcd://foo/a").href, "abcd:b"); }); -unitTest(function deletingAllParamsRemovesQuestionMarkFromURL(): void { +Deno.test("deletingAllParamsRemovesQuestionMarkFromURL", function (): void { const url = new URL("http://example.com/?param1¶m2"); url.searchParams.delete("param1"); url.searchParams.delete("param2"); @@ -385,7 +384,7 @@ unitTest(function deletingAllParamsRemovesQuestionMarkFromURL(): void { assertEquals(url.search, ""); }); -unitTest(function removingNonExistentParamRemovesQuestionMarkFromURL(): void { +Deno.test("removingNonExistentParamRemovesQuestionMarkFromURL", function (): void { const url = new URL("http://example.com/?"); assertEquals(url.href, "http://example.com/?"); url.searchParams.delete("param1"); @@ -393,7 +392,7 @@ unitTest(function removingNonExistentParamRemovesQuestionMarkFromURL(): void { assertEquals(url.search, ""); }); -unitTest(function sortingNonExistentParamRemovesQuestionMarkFromURL(): void { +Deno.test("sortingNonExistentParamRemovesQuestionMarkFromURL", function (): void { const url = new URL("http://example.com/?"); assertEquals(url.href, "http://example.com/?"); url.searchParams.sort(); @@ -401,7 +400,7 @@ unitTest(function sortingNonExistentParamRemovesQuestionMarkFromURL(): void { assertEquals(url.search, ""); }); -unitTest(function customInspectFunction(): void { +Deno.test("customInspectFunction", function (): void { const url = new URL("http://example.com/?"); assertEquals( Deno.inspect(url), @@ -421,14 +420,14 @@ unitTest(function customInspectFunction(): void { ); }); -unitTest(function protocolNotHttpOrFile() { +Deno.test("protocolNotHttpOrFile", function () { const url = new URL("about:blank"); assertEquals(url.href, "about:blank"); assertEquals(url.protocol, "about:"); assertEquals(url.origin, "null"); }); -unitTest(function throwForInvalidPortConstructor(): void { +Deno.test("throwForInvalidPortConstructor", function (): void { const urls = [ // If port is greater than 2^16 − 1, validation error, return failure. `https://baz.qat:${2 ** 16}`, @@ -447,7 +446,7 @@ unitTest(function throwForInvalidPortConstructor(): void { new URL("https://baz.qat:0"); }); -unitTest(function doNotOverridePortIfInvalid(): void { +Deno.test("doNotOverridePortIfInvalid", function (): void { const initialPort = "3000"; const url = new URL(`https://deno.land:${initialPort}`); // If port is greater than 2^16 − 1, validation error, return failure. @@ -455,7 +454,7 @@ unitTest(function doNotOverridePortIfInvalid(): void { assertEquals(url.port, initialPort); }); -unitTest(function emptyPortForSchemeDefaultPort(): void { +Deno.test("emptyPortForSchemeDefaultPort", function (): void { const nonDefaultPort = "3500"; const url = new URL("ftp://baz.qat:21"); @@ -477,7 +476,7 @@ unitTest(function emptyPortForSchemeDefaultPort(): void { assertEquals(url2.port, ""); }); -unitTest(function assigningPortPropertyAffectsReceiverOnly() { +Deno.test("assigningPortPropertyAffectsReceiverOnly", function () { // Setting `.port` should update only the receiver. const u1 = new URL("http://google.com/"); // deno-lint-ignore no-explicit-any @@ -487,7 +486,7 @@ unitTest(function assigningPortPropertyAffectsReceiverOnly() { assertStrictEquals(u2.port, "123"); }); -unitTest(function urlSearchParamsIdentityPreserved() { +Deno.test("urlSearchParamsIdentityPreserved", function () { // URLSearchParams identity should not be lost when URL is updated. const u = new URL("http://foo.com/"); const sp1 = u.searchParams; diff --git a/cli/tests/unit/utime_test.ts b/cli/tests/unit/utime_test.ts index 4e56ff1939b6bc..376ae43716a078 100644 --- a/cli/tests/unit/utime_test.ts +++ b/cli/tests/unit/utime_test.ts @@ -1,251 +1,194 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { - assertEquals, - assertThrows, - assertThrowsAsync, - unitTest, -} from "./test_util.ts"; - -unitTest( - { perms: { read: true, write: true } }, - async function futimeSyncSuccess(): Promise { - const testDir = await Deno.makeTempDir(); - const filename = testDir + "/file.txt"; - const file = await Deno.open(filename, { - create: true, - write: true, - }); - - const atime = 1000; - const mtime = 50000; - await Deno.futime(file.rid, atime, mtime); - await Deno.fdatasync(file.rid); - - const fileInfo = Deno.statSync(filename); - assertEquals(fileInfo.atime, new Date(atime * 1000)); - assertEquals(fileInfo.mtime, new Date(mtime * 1000)); - file.close(); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - function futimeSyncSuccess(): void { - const testDir = Deno.makeTempDirSync(); - const filename = testDir + "/file.txt"; - const file = Deno.openSync(filename, { - create: true, - write: true, - }); - - const atime = 1000; - const mtime = 50000; - Deno.futimeSync(file.rid, atime, mtime); - Deno.fdatasyncSync(file.rid); - - const fileInfo = Deno.statSync(filename); - assertEquals(fileInfo.atime, new Date(atime * 1000)); - assertEquals(fileInfo.mtime, new Date(mtime * 1000)); - file.close(); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - function utimeSyncFileSuccess(): void { - const testDir = Deno.makeTempDirSync(); - const filename = testDir + "/file.txt"; - Deno.writeFileSync(filename, new TextEncoder().encode("hello"), { - mode: 0o666, - }); - - const atime = 1000; - const mtime = 50000; - Deno.utimeSync(filename, atime, mtime); - - const fileInfo = Deno.statSync(filename); - assertEquals(fileInfo.atime, new Date(atime * 1000)); - assertEquals(fileInfo.mtime, new Date(mtime * 1000)); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - function utimeSyncDirectorySuccess(): void { - const testDir = Deno.makeTempDirSync(); - - const atime = 1000; - const mtime = 50000; - Deno.utimeSync(testDir, atime, mtime); - - const dirInfo = Deno.statSync(testDir); - assertEquals(dirInfo.atime, new Date(atime * 1000)); - assertEquals(dirInfo.mtime, new Date(mtime * 1000)); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - function utimeSyncDateSuccess(): void { - const testDir = Deno.makeTempDirSync(); - - const atime = new Date(1000_000); - const mtime = new Date(50000_000); - Deno.utimeSync(testDir, atime, mtime); - - const dirInfo = Deno.statSync(testDir); - assertEquals(dirInfo.atime, atime); - assertEquals(dirInfo.mtime, mtime); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - function utimeSyncFileDateSuccess() { - const testDir = Deno.makeTempDirSync(); - const filename = testDir + "/file.txt"; - Deno.writeFileSync(filename, new TextEncoder().encode("hello"), { - mode: 0o666, - }); - const atime = new Date(); - const mtime = new Date(); - Deno.utimeSync(filename, atime, mtime); - - const fileInfo = Deno.statSync(filename); - assertEquals(fileInfo.atime, atime); - assertEquals(fileInfo.mtime, mtime); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - function utimeSyncLargeNumberSuccess(): void { - const testDir = Deno.makeTempDirSync(); - - // There are Rust side caps (might be fs relate), - // so JUST make them slightly larger than UINT32_MAX. - const atime = 0x100000001; - const mtime = 0x100000002; - Deno.utimeSync(testDir, atime, mtime); - - const dirInfo = Deno.statSync(testDir); - assertEquals(dirInfo.atime, new Date(atime * 1000)); - assertEquals(dirInfo.mtime, new Date(mtime * 1000)); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - function utimeSyncNotFound(): void { - const atime = 1000; - const mtime = 50000; - - assertThrows(() => { - Deno.utimeSync("/baddir", atime, mtime); - }, Deno.errors.NotFound); - }, -); - -unitTest( - { perms: { read: true, write: false } }, - function utimeSyncPerm(): void { - const atime = 1000; - const mtime = 50000; - - assertThrows(() => { - Deno.utimeSync("/some_dir", atime, mtime); - }, Deno.errors.PermissionDenied); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function utimeFileSuccess(): Promise { - const testDir = Deno.makeTempDirSync(); - const filename = testDir + "/file.txt"; - Deno.writeFileSync(filename, new TextEncoder().encode("hello"), { - mode: 0o666, - }); - - const atime = 1000; - const mtime = 50000; - await Deno.utime(filename, atime, mtime); - - const fileInfo = Deno.statSync(filename); - assertEquals(fileInfo.atime, new Date(atime * 1000)); - assertEquals(fileInfo.mtime, new Date(mtime * 1000)); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function utimeDirectorySuccess(): Promise { - const testDir = Deno.makeTempDirSync(); - - const atime = 1000; - const mtime = 50000; - await Deno.utime(testDir, atime, mtime); - - const dirInfo = Deno.statSync(testDir); - assertEquals(dirInfo.atime, new Date(atime * 1000)); - assertEquals(dirInfo.mtime, new Date(mtime * 1000)); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function utimeDateSuccess(): Promise { - const testDir = Deno.makeTempDirSync(); - - const atime = new Date(100_000); - const mtime = new Date(5000_000); - await Deno.utime(testDir, atime, mtime); - - const dirInfo = Deno.statSync(testDir); - assertEquals(dirInfo.atime, atime); - assertEquals(dirInfo.mtime, mtime); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function utimeFileDateSuccess(): Promise { - const testDir = Deno.makeTempDirSync(); - const filename = testDir + "/file.txt"; - Deno.writeFileSync(filename, new TextEncoder().encode("hello"), { - mode: 0o666, - }); - - const atime = new Date(); - const mtime = new Date(); - await Deno.utime(filename, atime, mtime); - - const fileInfo = Deno.statSync(filename); - assertEquals(fileInfo.atime, atime); - assertEquals(fileInfo.mtime, mtime); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function utimeNotFound(): Promise { - const atime = 1000; - const mtime = 50000; - - await assertThrowsAsync(async () => { - await Deno.utime("/baddir", atime, mtime); - }, Deno.errors.NotFound); - }, -); - -unitTest( - { perms: { read: true, write: false } }, - async function utimeSyncPerm(): Promise { - const atime = 1000; - const mtime = 50000; - - await assertThrowsAsync(async () => { - await Deno.utime("/some_dir", atime, mtime); - }, Deno.errors.PermissionDenied); - }, -); +import { assertEquals, assertThrows, assertThrowsAsync } from "./test_util.ts"; + +Deno.test("futimeSyncSuccess", async function (): Promise { + const testDir = await Deno.makeTempDir(); + const filename = testDir + "/file.txt"; + const file = await Deno.open(filename, { + create: true, + write: true, + }); + + const atime = 1000; + const mtime = 50000; + await Deno.futime(file.rid, atime, mtime); + await Deno.fdatasync(file.rid); + + const fileInfo = Deno.statSync(filename); + assertEquals(fileInfo.atime, new Date(atime * 1000)); + assertEquals(fileInfo.mtime, new Date(mtime * 1000)); + file.close(); +}); + +Deno.test("futimeSyncSuccess", function (): void { + const testDir = Deno.makeTempDirSync(); + const filename = testDir + "/file.txt"; + const file = Deno.openSync(filename, { + create: true, + write: true, + }); + + const atime = 1000; + const mtime = 50000; + Deno.futimeSync(file.rid, atime, mtime); + Deno.fdatasyncSync(file.rid); + + const fileInfo = Deno.statSync(filename); + assertEquals(fileInfo.atime, new Date(atime * 1000)); + assertEquals(fileInfo.mtime, new Date(mtime * 1000)); + file.close(); +}); + +Deno.test("utimeSyncFileSuccess", function (): void { + const testDir = Deno.makeTempDirSync(); + const filename = testDir + "/file.txt"; + Deno.writeFileSync(filename, new TextEncoder().encode("hello"), { + mode: 0o666, + }); + + const atime = 1000; + const mtime = 50000; + Deno.utimeSync(filename, atime, mtime); + + const fileInfo = Deno.statSync(filename); + assertEquals(fileInfo.atime, new Date(atime * 1000)); + assertEquals(fileInfo.mtime, new Date(mtime * 1000)); +}); + +Deno.test("utimeSyncDirectorySuccess", function (): void { + const testDir = Deno.makeTempDirSync(); + + const atime = 1000; + const mtime = 50000; + Deno.utimeSync(testDir, atime, mtime); + + const dirInfo = Deno.statSync(testDir); + assertEquals(dirInfo.atime, new Date(atime * 1000)); + assertEquals(dirInfo.mtime, new Date(mtime * 1000)); +}); + +Deno.test("utimeSyncDateSuccess", function (): void { + const testDir = Deno.makeTempDirSync(); + + const atime = new Date(1000_000); + const mtime = new Date(50000_000); + Deno.utimeSync(testDir, atime, mtime); + + const dirInfo = Deno.statSync(testDir); + assertEquals(dirInfo.atime, atime); + assertEquals(dirInfo.mtime, mtime); +}); + +Deno.test("utimeSyncFileDateSuccess", function () { + const testDir = Deno.makeTempDirSync(); + const filename = testDir + "/file.txt"; + Deno.writeFileSync(filename, new TextEncoder().encode("hello"), { + mode: 0o666, + }); + const atime = new Date(); + const mtime = new Date(); + Deno.utimeSync(filename, atime, mtime); + + const fileInfo = Deno.statSync(filename); + assertEquals(fileInfo.atime, atime); + assertEquals(fileInfo.mtime, mtime); +}); + +Deno.test("utimeSyncLargeNumberSuccess", function (): void { + const testDir = Deno.makeTempDirSync(); + + // There are Rust side caps (might be fs relate), + // so JUST make them slightly larger than UINT32_MAX. + const atime = 0x100000001; + const mtime = 0x100000002; + Deno.utimeSync(testDir, atime, mtime); + + const dirInfo = Deno.statSync(testDir); + assertEquals(dirInfo.atime, new Date(atime * 1000)); + assertEquals(dirInfo.mtime, new Date(mtime * 1000)); +}); + +Deno.test("utimeSyncNotFound", function (): void { + const atime = 1000; + const mtime = 50000; + + assertThrows(() => { + Deno.utimeSync("/baddir", atime, mtime); + }, Deno.errors.NotFound); +}); + +Deno.test("utimeFileSuccess", async function (): Promise { + const testDir = Deno.makeTempDirSync(); + const filename = testDir + "/file.txt"; + Deno.writeFileSync(filename, new TextEncoder().encode("hello"), { + mode: 0o666, + }); + + const atime = 1000; + const mtime = 50000; + await Deno.utime(filename, atime, mtime); + + const fileInfo = Deno.statSync(filename); + assertEquals(fileInfo.atime, new Date(atime * 1000)); + assertEquals(fileInfo.mtime, new Date(mtime * 1000)); +}); + +Deno.test("utimeDirectorySuccess", async function (): Promise { + const testDir = Deno.makeTempDirSync(); + + const atime = 1000; + const mtime = 50000; + await Deno.utime(testDir, atime, mtime); + + const dirInfo = Deno.statSync(testDir); + assertEquals(dirInfo.atime, new Date(atime * 1000)); + assertEquals(dirInfo.mtime, new Date(mtime * 1000)); +}); + +Deno.test("utimeDateSuccess", async function (): Promise { + const testDir = Deno.makeTempDirSync(); + + const atime = new Date(100_000); + const mtime = new Date(5000_000); + await Deno.utime(testDir, atime, mtime); + + const dirInfo = Deno.statSync(testDir); + assertEquals(dirInfo.atime, atime); + assertEquals(dirInfo.mtime, mtime); +}); + +Deno.test("utimeFileDateSuccess", async function (): Promise { + const testDir = Deno.makeTempDirSync(); + const filename = testDir + "/file.txt"; + Deno.writeFileSync(filename, new TextEncoder().encode("hello"), { + mode: 0o666, + }); + + const atime = new Date(); + const mtime = new Date(); + await Deno.utime(filename, atime, mtime); + + const fileInfo = Deno.statSync(filename); + assertEquals(fileInfo.atime, atime); + assertEquals(fileInfo.mtime, mtime); +}); + +Deno.test("utimeNotFound", async function (): Promise { + const atime = 1000; + const mtime = 50000; + + await assertThrowsAsync(async () => { + await Deno.utime("/baddir", atime, mtime); + }, Deno.errors.NotFound); +}); + +Deno.test("utimeSyncPerm", async function (): Promise { + await Deno.permissions.revoke({ name: "write" }); + + const atime = 1000; + const mtime = 50000; + + await assertThrowsAsync(async () => { + await Deno.utime("/some_dir", atime, mtime); + }, Deno.errors.PermissionDenied); +}); diff --git a/cli/tests/unit/version_test.ts b/cli/tests/unit/version_test.ts index 91bbb260f4485b..4b08ecb999683e 100644 --- a/cli/tests/unit/version_test.ts +++ b/cli/tests/unit/version_test.ts @@ -1,6 +1,6 @@ -import { assert, unitTest } from "./test_util.ts"; +import { assert } from "./test_util.ts"; -unitTest(function version(): void { +Deno.test("version", function (): void { const pattern = /^\d+\.\d+\.\d+/; assert(pattern.test(Deno.version.deno)); assert(pattern.test(Deno.version.v8)); diff --git a/cli/tests/unit/webgpu_test.ts b/cli/tests/unit/webgpu_test.ts index d40851dfa4d70c..c771630ab3c295 100644 --- a/cli/tests/unit/webgpu_test.ts +++ b/cli/tests/unit/webgpu_test.ts @@ -1,4 +1,4 @@ -import { assert, assertEquals, unitTest } from "./test_util.ts"; +import { assert, assertEquals } from "./test_util.ts"; let isCI: boolean; try { @@ -9,214 +9,219 @@ try { // Skip this test on linux CI, because the vulkan emulator is not good enough // yet, and skip on macOS because these do not have virtual GPUs. -unitTest({ - perms: { read: true, env: true }, +Deno.test({ + name: "webgpuComputePass", ignore: (Deno.build.os === "linux" || Deno.build.os === "darwin") && isCI, -}, async function webgpuComputePass() { - const adapter = await navigator.gpu.requestAdapter(); - assert(adapter); + async fn() { + const adapter = await navigator.gpu.requestAdapter(); + assert(adapter); - const numbers = [1, 4, 3, 295]; + const numbers = [1, 4, 3, 295]; - const device = await adapter.requestDevice(); - assert(device); + const device = await adapter.requestDevice(); + assert(device); - const shaderCode = await Deno.readTextFile( - "cli/tests/webgpu_computepass_shader.wgsl", - ); + const shaderCode = await Deno.readTextFile( + "cli/tests/webgpu_computepass_shader.wgsl", + ); - const shaderModule = device.createShaderModule({ - code: shaderCode, - }); + const shaderModule = device.createShaderModule({ + code: shaderCode, + }); - const size = new Uint32Array(numbers).byteLength; + const size = new Uint32Array(numbers).byteLength; - const stagingBuffer = device.createBuffer({ - size: size, - usage: 1 | 8, - }); + const stagingBuffer = device.createBuffer({ + size: size, + usage: 1 | 8, + }); - const storageBuffer = device.createBuffer({ - label: "Storage Buffer", - size: size, - usage: 0x80 | 8 | 4, - mappedAtCreation: true, - }); + const storageBuffer = device.createBuffer({ + label: "Storage Buffer", + size: size, + usage: 0x80 | 8 | 4, + mappedAtCreation: true, + }); - const buf = new Uint32Array(storageBuffer.getMappedRange()); + const buf = new Uint32Array(storageBuffer.getMappedRange()); - buf.set(numbers); + buf.set(numbers); - storageBuffer.unmap(); + storageBuffer.unmap(); - const bindGroupLayout = device.createBindGroupLayout({ - entries: [ - { - binding: 0, - visibility: 4, - buffer: { - type: "storage", - minBindingSize: 4, + const bindGroupLayout = device.createBindGroupLayout({ + entries: [ + { + binding: 0, + visibility: 4, + buffer: { + type: "storage", + minBindingSize: 4, + }, }, - }, - ], - }); + ], + }); - const bindGroup = device.createBindGroup({ - layout: bindGroupLayout, - entries: [ - { - binding: 0, - resource: { - buffer: storageBuffer, + const bindGroup = device.createBindGroup({ + layout: bindGroupLayout, + entries: [ + { + binding: 0, + resource: { + buffer: storageBuffer, + }, }, - }, - ], - }); + ], + }); - const pipelineLayout = device.createPipelineLayout({ - bindGroupLayouts: [bindGroupLayout], - }); + const pipelineLayout = device.createPipelineLayout({ + bindGroupLayouts: [bindGroupLayout], + }); - const computePipeline = device.createComputePipeline({ - layout: pipelineLayout, - compute: { - module: shaderModule, - entryPoint: "main", - }, - }); + const computePipeline = device.createComputePipeline({ + layout: pipelineLayout, + compute: { + module: shaderModule, + entryPoint: "main", + }, + }); - const encoder = device.createCommandEncoder(); + const encoder = device.createCommandEncoder(); - const computePass = encoder.beginComputePass(); - computePass.setPipeline(computePipeline); - computePass.setBindGroup(0, bindGroup); - computePass.insertDebugMarker("compute collatz iterations"); - computePass.dispatch(numbers.length); - computePass.endPass(); + const computePass = encoder.beginComputePass(); + computePass.setPipeline(computePipeline); + computePass.setBindGroup(0, bindGroup); + computePass.insertDebugMarker("compute collatz iterations"); + computePass.dispatch(numbers.length); + computePass.endPass(); - encoder.copyBufferToBuffer(storageBuffer, 0, stagingBuffer, 0, size); + encoder.copyBufferToBuffer(storageBuffer, 0, stagingBuffer, 0, size); - device.queue.submit([encoder.finish()]); + device.queue.submit([encoder.finish()]); - await stagingBuffer.mapAsync(1); + await stagingBuffer.mapAsync(1); - const data = stagingBuffer.getMappedRange(); + const data = stagingBuffer.getMappedRange(); - assertEquals(new Uint32Array(data), new Uint32Array([0, 2, 7, 55])); + assertEquals(new Uint32Array(data), new Uint32Array([0, 2, 7, 55])); - stagingBuffer.unmap(); + stagingBuffer.unmap(); - device.destroy(); + device.destroy(); - // TODO(lucacasonato): webgpu spec should add a explicit destroy method for - // adapters. - const resources = Object.keys(Deno.resources()); - Deno.close(Number(resources[resources.length - 1])); + // TODO(lucacasonato): webgpu spec should add a explicit destroy method for + // adapters. + const resources = Object.keys(Deno.resources()); + Deno.close(Number(resources[resources.length - 1])); + }, }); // Skip this test on linux CI, because the vulkan emulator is not good enough // yet, and skip on macOS because these do not have virtual GPUs. -unitTest({ - perms: { read: true, env: true }, +Deno.test({ + name: "webgpuHelloTriangle", ignore: (Deno.build.os === "linux" || Deno.build.os === "darwin") && isCI, -}, async function webgpuHelloTriangle() { - const adapter = await navigator.gpu.requestAdapter(); - assert(adapter); - - const device = await adapter.requestDevice(); - assert(device); - - const shaderCode = await Deno.readTextFile( - "cli/tests/webgpu_hellotriangle_shader.wgsl", - ); - - const shaderModule = device.createShaderModule({ - code: shaderCode, - }); - - const pipelineLayout = device.createPipelineLayout({ - bindGroupLayouts: [], - }); - - const renderPipeline = device.createRenderPipeline({ - layout: pipelineLayout, - vertex: { - module: shaderModule, - entryPoint: "vs_main", - }, - fragment: { - module: shaderModule, - entryPoint: "fs_main", - targets: [ + async fn() { + const adapter = await navigator.gpu.requestAdapter(); + assert(adapter); + + const device = await adapter.requestDevice(); + assert(device); + + const shaderCode = await Deno.readTextFile( + "cli/tests/webgpu_hellotriangle_shader.wgsl", + ); + + const shaderModule = device.createShaderModule({ + code: shaderCode, + }); + + const pipelineLayout = device.createPipelineLayout({ + bindGroupLayouts: [], + }); + + const renderPipeline = device.createRenderPipeline({ + layout: pipelineLayout, + vertex: { + module: shaderModule, + entryPoint: "vs_main", + }, + fragment: { + module: shaderModule, + entryPoint: "fs_main", + targets: [ + { + format: "rgba8unorm-srgb", + }, + ], + }, + }); + + const dimensions = { + width: 200, + height: 200, + }; + const unpaddedBytesPerRow = dimensions.width * 4; + const align = 256; + const paddedBytesPerRowPadding = (align - unpaddedBytesPerRow % align) % + align; + const paddedBytesPerRow = unpaddedBytesPerRow + paddedBytesPerRowPadding; + + const outputBuffer = device.createBuffer({ + label: "Capture", + size: paddedBytesPerRow * dimensions.height, + usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST, + }); + const texture = device.createTexture({ + label: "Capture", + size: dimensions, + format: "rgba8unorm-srgb", + usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC, + }); + + const encoder = device.createCommandEncoder(); + const renderPass = encoder.beginRenderPass({ + colorAttachments: [ { - format: "rgba8unorm-srgb", + view: texture.createView(), + storeOp: "store", + loadValue: [0, 1, 0, 1], }, ], - }, - }); - - const dimensions = { - width: 200, - height: 200, - }; - const unpaddedBytesPerRow = dimensions.width * 4; - const align = 256; - const paddedBytesPerRowPadding = (align - unpaddedBytesPerRow % align) % - align; - const paddedBytesPerRow = unpaddedBytesPerRow + paddedBytesPerRowPadding; - - const outputBuffer = device.createBuffer({ - label: "Capture", - size: paddedBytesPerRow * dimensions.height, - usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST, - }); - const texture = device.createTexture({ - label: "Capture", - size: dimensions, - format: "rgba8unorm-srgb", - usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC, - }); - - const encoder = device.createCommandEncoder(); - const renderPass = encoder.beginRenderPass({ - colorAttachments: [ + }); + renderPass.setPipeline(renderPipeline); + renderPass.draw(3, 1); + renderPass.endPass(); + + encoder.copyTextureToBuffer( { - view: texture.createView(), - storeOp: "store", - loadValue: [0, 1, 0, 1], + texture, }, - ], - }); - renderPass.setPipeline(renderPipeline); - renderPass.draw(3, 1); - renderPass.endPass(); - - encoder.copyTextureToBuffer( - { - texture, - }, - { - buffer: outputBuffer, - bytesPerRow: paddedBytesPerRow, - rowsPerImage: 0, - }, - dimensions, - ); - - device.queue.submit([encoder.finish()]); - - await outputBuffer.mapAsync(1); - const data = new Uint8Array(outputBuffer.getMappedRange()); - - assertEquals(data, await Deno.readFile("cli/tests/webgpu_hellotriangle.out")); - - outputBuffer.unmap(); - - device.destroy(); - - // TODO(lucacasonato): webgpu spec should add a explicit destroy method for - // adapters. - const resources = Object.keys(Deno.resources()); - Deno.close(Number(resources[resources.length - 1])); + { + buffer: outputBuffer, + bytesPerRow: paddedBytesPerRow, + rowsPerImage: 0, + }, + dimensions, + ); + + device.queue.submit([encoder.finish()]); + + await outputBuffer.mapAsync(1); + const data = new Uint8Array(outputBuffer.getMappedRange()); + + assertEquals( + data, + await Deno.readFile("cli/tests/webgpu_hellotriangle.out"), + ); + + outputBuffer.unmap(); + + device.destroy(); + + // TODO(lucacasonato): webgpu spec should add a explicit destroy method for + // adapters. + const resources = Object.keys(Deno.resources()); + Deno.close(Number(resources[resources.length - 1])); + }, }); diff --git a/cli/tests/unit/websocket_test.ts b/cli/tests/unit/websocket_test.ts index ecc86029dd2c45..2799a36d803e71 100644 --- a/cli/tests/unit/websocket_test.ts +++ b/cli/tests/unit/websocket_test.ts @@ -1,7 +1,9 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assertThrows, unitTest } from "./test_util.ts"; +import { assertThrows } from "./test_util.ts"; + +Deno.test("websocketPermissionless", async function (): Promise { + await Deno.permissions.revoke({ name: "net" }); -unitTest(function websocketPermissionless() { assertThrows( () => new WebSocket("ws://localhost"), Deno.errors.PermissionDenied, diff --git a/cli/tests/unit/worker_types.ts b/cli/tests/unit/worker_types.ts index d7dd87c54014f7..e57106c595ceb0 100644 --- a/cli/tests/unit/worker_types.ts +++ b/cli/tests/unit/worker_types.ts @@ -1,14 +1,11 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assert, unitTest } from "./test_util.ts"; +import { assert } from "./test_util.ts"; -unitTest( - { perms: { read: true } }, - function utimeSyncFileSuccess() { - const w = new Worker( - new URL("../workers/worker_types.ts", import.meta.url).href, - { type: "module" }, - ); - assert(w); - w.terminate(); - }, -); +Deno.test("utimeSyncFileSuccess", function () { + const w = new Worker( + new URL("../workers/worker_types.ts", import.meta.url).href, + { type: "module" }, + ); + assert(w); + w.terminate(); +}); diff --git a/cli/tests/unit/write_file_test.ts b/cli/tests/unit/write_file_test.ts index e63183c4c38eb8..0c610e4f191ef4 100644 --- a/cli/tests/unit/write_file_test.ts +++ b/cli/tests/unit/write_file_test.ts @@ -1,241 +1,206 @@ // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { - assertEquals, - assertThrows, - assertThrowsAsync, - unitTest, -} from "./test_util.ts"; - -unitTest( - { perms: { read: true, write: true } }, - function writeFileSyncSuccess(): void { - const enc = new TextEncoder(); - const data = enc.encode("Hello"); - const filename = Deno.makeTempDirSync() + "/test.txt"; - Deno.writeFileSync(filename, data); - const dataRead = Deno.readFileSync(filename); - const dec = new TextDecoder("utf-8"); - const actual = dec.decode(dataRead); - assertEquals("Hello", actual); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - function writeFileSyncUrl(): void { - const enc = new TextEncoder(); - const data = enc.encode("Hello"); - const tempDir = Deno.makeTempDirSync(); - const fileUrl = new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt`, - ); - Deno.writeFileSync(fileUrl, data); - const dataRead = Deno.readFileSync(fileUrl); - const dec = new TextDecoder("utf-8"); - const actual = dec.decode(dataRead); - assertEquals("Hello", actual); - - Deno.removeSync(tempDir, { recursive: true }); - }, -); - -unitTest({ perms: { write: true } }, function writeFileSyncFail(): void { +import { assertEquals, assertThrows, assertThrowsAsync } from "./test_util.ts"; + +Deno.test("writeFileSyncSuccess", function (): void { const enc = new TextEncoder(); const data = enc.encode("Hello"); - const filename = "/baddir/test.txt"; - // The following should fail because /baddir doesn't exist (hopefully). - assertThrows(() => { - Deno.writeFileSync(filename, data); - }, Deno.errors.NotFound); + const filename = Deno.makeTempDirSync() + "/test.txt"; + Deno.writeFileSync(filename, data); + const dataRead = Deno.readFileSync(filename); + const dec = new TextDecoder("utf-8"); + const actual = dec.decode(dataRead); + assertEquals("Hello", actual); }); -unitTest({ perms: { write: false } }, function writeFileSyncPerm(): void { +Deno.test("writeFileSyncUrl", function (): void { + const enc = new TextEncoder(); + const data = enc.encode("Hello"); + const tempDir = Deno.makeTempDirSync(); + const fileUrl = new URL( + `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt`, + ); + Deno.writeFileSync(fileUrl, data); + const dataRead = Deno.readFileSync(fileUrl); + const dec = new TextDecoder("utf-8"); + const actual = dec.decode(dataRead); + assertEquals("Hello", actual); + + Deno.removeSync(tempDir, { recursive: true }); +}); + +Deno.test("writeFileSyncFail", function (): void { const enc = new TextEncoder(); const data = enc.encode("Hello"); const filename = "/baddir/test.txt"; - // The following should fail due to no write permission + // The following should fail because /baddir doesn't exist (hopefully). assertThrows(() => { Deno.writeFileSync(filename, data); - }, Deno.errors.PermissionDenied); + }, Deno.errors.NotFound); }); -unitTest( - { perms: { read: true, write: true } }, - function writeFileSyncUpdateMode(): void { - if (Deno.build.os !== "windows") { - const enc = new TextEncoder(); - const data = enc.encode("Hello"); - const filename = Deno.makeTempDirSync() + "/test.txt"; - Deno.writeFileSync(filename, data, { mode: 0o755 }); - assertEquals(Deno.statSync(filename).mode! & 0o777, 0o755); - Deno.writeFileSync(filename, data, { mode: 0o666 }); - assertEquals(Deno.statSync(filename).mode! & 0o777, 0o666); - } - }, -); - -unitTest( - { perms: { read: true, write: true } }, - function writeFileSyncCreate(): void { +Deno.test("writeFileSyncUpdateMode", function (): void { + if (Deno.build.os !== "windows") { const enc = new TextEncoder(); const data = enc.encode("Hello"); const filename = Deno.makeTempDirSync() + "/test.txt"; - // if create turned off, the file won't be created - assertThrows(() => { - Deno.writeFileSync(filename, data, { create: false }); - }, Deno.errors.NotFound); + Deno.writeFileSync(filename, data, { mode: 0o755 }); + assertEquals(Deno.statSync(filename).mode! & 0o777, 0o755); + Deno.writeFileSync(filename, data, { mode: 0o666 }); + assertEquals(Deno.statSync(filename).mode! & 0o777, 0o666); + } +}); - // Turn on create, should have no error - Deno.writeFileSync(filename, data, { create: true }); +Deno.test("writeFileSyncCreate", function (): void { + const enc = new TextEncoder(); + const data = enc.encode("Hello"); + const filename = Deno.makeTempDirSync() + "/test.txt"; + // if create turned off, the file won't be created + assertThrows(() => { Deno.writeFileSync(filename, data, { create: false }); - const dataRead = Deno.readFileSync(filename); - const dec = new TextDecoder("utf-8"); - const actual = dec.decode(dataRead); - assertEquals("Hello", actual); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - function writeFileSyncAppend(): void { - const enc = new TextEncoder(); - const data = enc.encode("Hello"); - const filename = Deno.makeTempDirSync() + "/test.txt"; - Deno.writeFileSync(filename, data); - Deno.writeFileSync(filename, data, { append: true }); - let dataRead = Deno.readFileSync(filename); - const dec = new TextDecoder("utf-8"); - let actual = dec.decode(dataRead); - assertEquals("HelloHello", actual); - // Now attempt overwrite - Deno.writeFileSync(filename, data, { append: false }); - dataRead = Deno.readFileSync(filename); - actual = dec.decode(dataRead); - assertEquals("Hello", actual); - // append not set should also overwrite - Deno.writeFileSync(filename, data); - dataRead = Deno.readFileSync(filename); - actual = dec.decode(dataRead); - assertEquals("Hello", actual); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function writeFileSuccess(): Promise { - const enc = new TextEncoder(); - const data = enc.encode("Hello"); - const filename = Deno.makeTempDirSync() + "/test.txt"; + }, Deno.errors.NotFound); + + // Turn on create, should have no error + Deno.writeFileSync(filename, data, { create: true }); + Deno.writeFileSync(filename, data, { create: false }); + const dataRead = Deno.readFileSync(filename); + const dec = new TextDecoder("utf-8"); + const actual = dec.decode(dataRead); + assertEquals("Hello", actual); +}); + +Deno.test("writeFileSyncAppend", function (): void { + const enc = new TextEncoder(); + const data = enc.encode("Hello"); + const filename = Deno.makeTempDirSync() + "/test.txt"; + Deno.writeFileSync(filename, data); + Deno.writeFileSync(filename, data, { append: true }); + let dataRead = Deno.readFileSync(filename); + const dec = new TextDecoder("utf-8"); + let actual = dec.decode(dataRead); + assertEquals("HelloHello", actual); + // Now attempt overwrite + Deno.writeFileSync(filename, data, { append: false }); + dataRead = Deno.readFileSync(filename); + actual = dec.decode(dataRead); + assertEquals("Hello", actual); + // append not set should also overwrite + Deno.writeFileSync(filename, data); + dataRead = Deno.readFileSync(filename); + actual = dec.decode(dataRead); + assertEquals("Hello", actual); +}); + +Deno.test("writeFileSuccess", async function (): Promise { + const enc = new TextEncoder(); + const data = enc.encode("Hello"); + const filename = Deno.makeTempDirSync() + "/test.txt"; + await Deno.writeFile(filename, data); + const dataRead = Deno.readFileSync(filename); + const dec = new TextDecoder("utf-8"); + const actual = dec.decode(dataRead); + assertEquals("Hello", actual); +}); + +Deno.test("writeFileUrl", async function (): Promise { + const enc = new TextEncoder(); + const data = enc.encode("Hello"); + const tempDir = await Deno.makeTempDir(); + const fileUrl = new URL( + `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt`, + ); + await Deno.writeFile(fileUrl, data); + const dataRead = Deno.readFileSync(fileUrl); + const dec = new TextDecoder("utf-8"); + const actual = dec.decode(dataRead); + assertEquals("Hello", actual); + + Deno.removeSync(tempDir, { recursive: true }); +}); + +Deno.test("writeFileNotFound", async function (): Promise { + const enc = new TextEncoder(); + const data = enc.encode("Hello"); + const filename = "/baddir/test.txt"; + // The following should fail because /baddir doesn't exist (hopefully). + await assertThrowsAsync(async () => { await Deno.writeFile(filename, data); - const dataRead = Deno.readFileSync(filename); - const dec = new TextDecoder("utf-8"); - const actual = dec.decode(dataRead); - assertEquals("Hello", actual); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function writeFileUrl(): Promise { - const enc = new TextEncoder(); - const data = enc.encode("Hello"); - const tempDir = await Deno.makeTempDir(); - const fileUrl = new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt`, - ); - await Deno.writeFile(fileUrl, data); - const dataRead = Deno.readFileSync(fileUrl); - const dec = new TextDecoder("utf-8"); - const actual = dec.decode(dataRead); - assertEquals("Hello", actual); - - Deno.removeSync(tempDir, { recursive: true }); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function writeFileNotFound(): Promise { - const enc = new TextEncoder(); - const data = enc.encode("Hello"); - const filename = "/baddir/test.txt"; - // The following should fail because /baddir doesn't exist (hopefully). - await assertThrowsAsync(async () => { - await Deno.writeFile(filename, data); - }, Deno.errors.NotFound); - }, -); - -unitTest( - { perms: { read: true, write: false } }, - async function writeFilePerm(): Promise { - const enc = new TextEncoder(); - const data = enc.encode("Hello"); - const filename = "/baddir/test.txt"; - // The following should fail due to no write permission - await assertThrowsAsync(async () => { - await Deno.writeFile(filename, data); - }, Deno.errors.PermissionDenied); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function writeFileUpdateMode(): Promise { - if (Deno.build.os !== "windows") { - const enc = new TextEncoder(); - const data = enc.encode("Hello"); - const filename = Deno.makeTempDirSync() + "/test.txt"; - await Deno.writeFile(filename, data, { mode: 0o755 }); - assertEquals(Deno.statSync(filename).mode! & 0o777, 0o755); - await Deno.writeFile(filename, data, { mode: 0o666 }); - assertEquals(Deno.statSync(filename).mode! & 0o777, 0o666); - } - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function writeFileCreate(): Promise { + }, Deno.errors.NotFound); +}); + +Deno.test("writeFileUpdateMode", async function (): Promise { + if (Deno.build.os !== "windows") { const enc = new TextEncoder(); const data = enc.encode("Hello"); const filename = Deno.makeTempDirSync() + "/test.txt"; - // if create turned off, the file won't be created - await assertThrowsAsync(async () => { - await Deno.writeFile(filename, data, { create: false }); - }, Deno.errors.NotFound); + await Deno.writeFile(filename, data, { mode: 0o755 }); + assertEquals(Deno.statSync(filename).mode! & 0o777, 0o755); + await Deno.writeFile(filename, data, { mode: 0o666 }); + assertEquals(Deno.statSync(filename).mode! & 0o777, 0o666); + } +}); - // Turn on create, should have no error - await Deno.writeFile(filename, data, { create: true }); +Deno.test("writeFileCreate", async function (): Promise { + const enc = new TextEncoder(); + const data = enc.encode("Hello"); + const filename = Deno.makeTempDirSync() + "/test.txt"; + // if create turned off, the file won't be created + await assertThrowsAsync(async () => { await Deno.writeFile(filename, data, { create: false }); - const dataRead = Deno.readFileSync(filename); - const dec = new TextDecoder("utf-8"); - const actual = dec.decode(dataRead); - assertEquals("Hello", actual); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function writeFileAppend(): Promise { - const enc = new TextEncoder(); - const data = enc.encode("Hello"); - const filename = Deno.makeTempDirSync() + "/test.txt"; - await Deno.writeFile(filename, data); - await Deno.writeFile(filename, data, { append: true }); - let dataRead = Deno.readFileSync(filename); - const dec = new TextDecoder("utf-8"); - let actual = dec.decode(dataRead); - assertEquals("HelloHello", actual); - // Now attempt overwrite - await Deno.writeFile(filename, data, { append: false }); - dataRead = Deno.readFileSync(filename); - actual = dec.decode(dataRead); - assertEquals("Hello", actual); - // append not set should also overwrite + }, Deno.errors.NotFound); + + // Turn on create, should have no error + await Deno.writeFile(filename, data, { create: true }); + await Deno.writeFile(filename, data, { create: false }); + const dataRead = Deno.readFileSync(filename); + const dec = new TextDecoder("utf-8"); + const actual = dec.decode(dataRead); + assertEquals("Hello", actual); +}); + +Deno.test("writeFileAppend", async function (): Promise { + const enc = new TextEncoder(); + const data = enc.encode("Hello"); + const filename = Deno.makeTempDirSync() + "/test.txt"; + await Deno.writeFile(filename, data); + await Deno.writeFile(filename, data, { append: true }); + let dataRead = Deno.readFileSync(filename); + const dec = new TextDecoder("utf-8"); + let actual = dec.decode(dataRead); + assertEquals("HelloHello", actual); + // Now attempt overwrite + await Deno.writeFile(filename, data, { append: false }); + dataRead = Deno.readFileSync(filename); + actual = dec.decode(dataRead); + assertEquals("Hello", actual); + // append not set should also overwrite + await Deno.writeFile(filename, data); + dataRead = Deno.readFileSync(filename); + actual = dec.decode(dataRead); + assertEquals("Hello", actual); +}); + +Deno.test("writeFileSyncPerm", async function (): Promise { + await Deno.permissions.revoke({ name: "write" }); + + const enc = new TextEncoder(); + const data = enc.encode("Hello"); + const filename = "/baddir/test.txt"; + // The following should fail due to no write permission + assertThrows(() => { + Deno.writeFileSync(filename, data); + }, Deno.errors.PermissionDenied); +}); + +Deno.test("writeFilePerm", async function (): Promise { + await Deno.permissions.revoke({ name: "write" }); + + const enc = new TextEncoder(); + const data = enc.encode("Hello"); + const filename = "/baddir/test.txt"; + // The following should fail due to no write permission + await assertThrowsAsync(async () => { await Deno.writeFile(filename, data); - dataRead = Deno.readFileSync(filename); - actual = dec.decode(dataRead); - assertEquals("Hello", actual); - }, -); + }, Deno.errors.PermissionDenied); +}); + + diff --git a/cli/tests/unit/write_text_file_test.ts b/cli/tests/unit/write_text_file_test.ts index f41f8f663387b9..9bd9fc7b474c93 100644 --- a/cli/tests/unit/write_text_file_test.ts +++ b/cli/tests/unit/write_text_file_test.ts @@ -3,35 +3,28 @@ import { assertEquals, assertThrows, assertThrowsAsync, - unitTest, } from "./test_util.ts"; -unitTest( - { perms: { read: true, write: true } }, - function writeTextFileSyncSuccess(): void { - const filename = Deno.makeTempDirSync() + "/test.txt"; - Deno.writeTextFileSync(filename, "Hello"); - const dataRead = Deno.readTextFileSync(filename); - assertEquals("Hello", dataRead); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - function writeTextFileSyncByUrl(): void { - const tempDir = Deno.makeTempDirSync(); - const fileUrl = new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt`, - ); - Deno.writeTextFileSync(fileUrl, "Hello"); - const dataRead = Deno.readTextFileSync(fileUrl); - assertEquals("Hello", dataRead); - - Deno.removeSync(fileUrl, { recursive: true }); - }, -); - -unitTest({ perms: { write: true } }, function writeTextFileSyncFail(): void { +Deno.test("writeTextFileSyncSuccess", function (): void { + const filename = Deno.makeTempDirSync() + "/test.txt"; + Deno.writeTextFileSync(filename, "Hello"); + const dataRead = Deno.readTextFileSync(filename); + assertEquals("Hello", dataRead); +}); + +Deno.test("writeTextFileSyncByUrl", function (): void { + const tempDir = Deno.makeTempDirSync(); + const fileUrl = new URL( + `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt`, + ); + Deno.writeTextFileSync(fileUrl, "Hello"); + const dataRead = Deno.readTextFileSync(fileUrl); + assertEquals("Hello", dataRead); + + Deno.removeSync(fileUrl, { recursive: true }); +}); + +Deno.test("writeTextFileSyncFail", function (): void { const filename = "/baddir/test.txt"; // The following should fail because /baddir doesn't exist (hopefully). assertThrows(() => { @@ -39,7 +32,124 @@ unitTest({ perms: { write: true } }, function writeTextFileSyncFail(): void { }, Deno.errors.NotFound); }); -unitTest({ perms: { write: false } }, function writeTextFileSyncPerm(): void { +Deno.test("writeTextFileSyncUpdateMode", function (): void { + if (Deno.build.os !== "windows") { + const data = "Hello"; + const filename = Deno.makeTempDirSync() + "/test.txt"; + Deno.writeTextFileSync(filename, data, { mode: 0o755 }); + assertEquals(Deno.statSync(filename).mode! & 0o777, 0o755); + Deno.writeTextFileSync(filename, data, { mode: 0o666 }); + assertEquals(Deno.statSync(filename).mode! & 0o777, 0o666); + } +}); + +Deno.test("writeTextFileSyncCreate", function (): void { + const data = "Hello"; + const filename = Deno.makeTempDirSync() + "/test.txt"; + let caughtError = false; + // if create turned off, the file won't be created + try { + Deno.writeTextFileSync(filename, data, { create: false }); + } catch (e) { + caughtError = true; + assert(e instanceof Deno.errors.NotFound); + } + assert(caughtError); + + // Turn on create, should have no error + Deno.writeTextFileSync(filename, data, { create: true }); + Deno.writeTextFileSync(filename, data, { create: false }); + assertEquals("Hello", Deno.readTextFileSync(filename)); +}); + +Deno.test("writeTextFileSyncAppend", function (): void { + const data = "Hello"; + const filename = Deno.makeTempDirSync() + "/test.txt"; + Deno.writeTextFileSync(filename, data); + Deno.writeTextFileSync(filename, data, { append: true }); + assertEquals("HelloHello", Deno.readTextFileSync(filename)); + // Now attempt overwrite + Deno.writeTextFileSync(filename, data, { append: false }); + assertEquals("Hello", Deno.readTextFileSync(filename)); + // append not set should also overwrite + Deno.writeTextFileSync(filename, data); + assertEquals("Hello", Deno.readTextFileSync(filename)); +}); + +Deno.test("writeTextFileSuccess", async function (): Promise { + const filename = Deno.makeTempDirSync() + "/test.txt"; + await Deno.writeTextFile(filename, "Hello"); + const dataRead = Deno.readTextFileSync(filename); + assertEquals("Hello", dataRead); +}); + +Deno.test("writeTextFileByUrl", async function (): Promise { + const tempDir = Deno.makeTempDirSync(); + const fileUrl = new URL( + `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt`, + ); + await Deno.writeTextFile(fileUrl, "Hello"); + const dataRead = Deno.readTextFileSync(fileUrl); + assertEquals("Hello", dataRead); + + Deno.removeSync(fileUrl, { recursive: true }); +}); + +Deno.test("writeTextFileNotFound", async function (): Promise { + const filename = "/baddir/test.txt"; + // The following should fail because /baddir doesn't exist (hopefully). + await assertThrowsAsync(async () => { + await Deno.writeTextFile(filename, "Hello"); + }, Deno.errors.NotFound); +}); + +Deno.test("writeTextFileUpdateMode", async function (): Promise { + if (Deno.build.os !== "windows") { + const data = "Hello"; + const filename = Deno.makeTempDirSync() + "/test.txt"; + await Deno.writeTextFile(filename, data, { mode: 0o755 }); + assertEquals(Deno.statSync(filename).mode! & 0o777, 0o755); + await Deno.writeTextFile(filename, data, { mode: 0o666 }); + assertEquals(Deno.statSync(filename).mode! & 0o777, 0o666); + } +}); + +Deno.test("writeTextFileCreate", async function (): Promise { + const data = "Hello"; + const filename = Deno.makeTempDirSync() + "/test.txt"; + let caughtError = false; + // if create turned off, the file won't be created + try { + await Deno.writeTextFile(filename, data, { create: false }); + } catch (e) { + caughtError = true; + assert(e instanceof Deno.errors.NotFound); + } + assert(caughtError); + + // Turn on create, should have no error + await Deno.writeTextFile(filename, data, { create: true }); + await Deno.writeTextFile(filename, data, { create: false }); + assertEquals("Hello", Deno.readTextFileSync(filename)); +}); + +Deno.test("writeTextFileAppend", async function (): Promise { + const data = "Hello"; + const filename = Deno.makeTempDirSync() + "/test.txt"; + await Deno.writeTextFile(filename, data); + await Deno.writeTextFile(filename, data, { append: true }); + assertEquals("HelloHello", Deno.readTextFileSync(filename)); + // Now attempt overwrite + await Deno.writeTextFile(filename, data, { append: false }); + assertEquals("Hello", Deno.readTextFileSync(filename)); + // append not set should also overwrite + await Deno.writeTextFile(filename, data); + assertEquals("Hello", Deno.readTextFileSync(filename)); +}); + +Deno.test("writeTextFileSyncPerm", async function (): Promise { + await Deno.permissions.revoke({ name: "write" }); + const filename = "/baddir/test.txt"; // The following should fail due to no write permission assertThrows(() => { @@ -47,155 +157,22 @@ unitTest({ perms: { write: false } }, function writeTextFileSyncPerm(): void { }, Deno.errors.PermissionDenied); }); -unitTest( - { perms: { read: true, write: true } }, - function writeTextFileSyncUpdateMode(): void { - if (Deno.build.os !== "windows") { - const data = "Hello"; - const filename = Deno.makeTempDirSync() + "/test.txt"; - Deno.writeTextFileSync(filename, data, { mode: 0o755 }); - assertEquals(Deno.statSync(filename).mode! & 0o777, 0o755); - Deno.writeTextFileSync(filename, data, { mode: 0o666 }); - assertEquals(Deno.statSync(filename).mode! & 0o777, 0o666); - } - }, -); - -unitTest( - { perms: { read: true, write: true } }, - function writeTextFileSyncCreate(): void { - const data = "Hello"; - const filename = Deno.makeTempDirSync() + "/test.txt"; - let caughtError = false; - // if create turned off, the file won't be created - try { - Deno.writeTextFileSync(filename, data, { create: false }); - } catch (e) { - caughtError = true; - assert(e instanceof Deno.errors.NotFound); - } - assert(caughtError); - - // Turn on create, should have no error - Deno.writeTextFileSync(filename, data, { create: true }); - Deno.writeTextFileSync(filename, data, { create: false }); - assertEquals("Hello", Deno.readTextFileSync(filename)); - }, -); +Deno.test("writeTextFilePerm", async function (): Promise { + await Deno.permissions.revoke({ name: "write" }); -unitTest( - { perms: { read: true, write: true } }, - function writeTextFileSyncAppend(): void { - const data = "Hello"; - const filename = Deno.makeTempDirSync() + "/test.txt"; - Deno.writeTextFileSync(filename, data); - Deno.writeTextFileSync(filename, data, { append: true }); - assertEquals("HelloHello", Deno.readTextFileSync(filename)); - // Now attempt overwrite - Deno.writeTextFileSync(filename, data, { append: false }); - assertEquals("Hello", Deno.readTextFileSync(filename)); - // append not set should also overwrite - Deno.writeTextFileSync(filename, data); - assertEquals("Hello", Deno.readTextFileSync(filename)); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function writeTextFileSuccess(): Promise { - const filename = Deno.makeTempDirSync() + "/test.txt"; + const filename = "/baddir/test.txt"; + // The following should fail due to no write permission + await assertThrowsAsync(async () => { await Deno.writeTextFile(filename, "Hello"); - const dataRead = Deno.readTextFileSync(filename); - assertEquals("Hello", dataRead); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function writeTextFileByUrl(): Promise { - const tempDir = Deno.makeTempDirSync(); - const fileUrl = new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt`, - ); - await Deno.writeTextFile(fileUrl, "Hello"); - const dataRead = Deno.readTextFileSync(fileUrl); - assertEquals("Hello", dataRead); - - Deno.removeSync(fileUrl, { recursive: true }); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function writeTextFileNotFound(): Promise { - const filename = "/baddir/test.txt"; - // The following should fail because /baddir doesn't exist (hopefully). - await assertThrowsAsync(async () => { - await Deno.writeTextFile(filename, "Hello"); - }, Deno.errors.NotFound); - }, -); - -unitTest( - { perms: { write: false } }, - async function writeTextFilePerm(): Promise { - const filename = "/baddir/test.txt"; - // The following should fail due to no write permission - await assertThrowsAsync(async () => { - await Deno.writeTextFile(filename, "Hello"); - }, Deno.errors.PermissionDenied); - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function writeTextFileUpdateMode(): Promise { - if (Deno.build.os !== "windows") { - const data = "Hello"; - const filename = Deno.makeTempDirSync() + "/test.txt"; - await Deno.writeTextFile(filename, data, { mode: 0o755 }); - assertEquals(Deno.statSync(filename).mode! & 0o777, 0o755); - await Deno.writeTextFile(filename, data, { mode: 0o666 }); - assertEquals(Deno.statSync(filename).mode! & 0o777, 0o666); - } - }, -); - -unitTest( - { perms: { read: true, write: true } }, - async function writeTextFileCreate(): Promise { - const data = "Hello"; - const filename = Deno.makeTempDirSync() + "/test.txt"; - let caughtError = false; - // if create turned off, the file won't be created - try { - await Deno.writeTextFile(filename, data, { create: false }); - } catch (e) { - caughtError = true; - assert(e instanceof Deno.errors.NotFound); - } - assert(caughtError); - - // Turn on create, should have no error - await Deno.writeTextFile(filename, data, { create: true }); - await Deno.writeTextFile(filename, data, { create: false }); - assertEquals("Hello", Deno.readTextFileSync(filename)); - }, -); + }, Deno.errors.PermissionDenied); +}); + +Deno.test("writeTextFilePerm", async function (): Promise { + const filename = "/baddir/test.txt"; + // The following should fail due to no write permission + await assertThrowsAsync(async () => { + await Deno.writeTextFile(filename, "Hello"); + }, Deno.errors.PermissionDenied); +}); + -unitTest( - { perms: { read: true, write: true } }, - async function writeTextFileAppend(): Promise { - const data = "Hello"; - const filename = Deno.makeTempDirSync() + "/test.txt"; - await Deno.writeTextFile(filename, data); - await Deno.writeTextFile(filename, data, { append: true }); - assertEquals("HelloHello", Deno.readTextFileSync(filename)); - // Now attempt overwrite - await Deno.writeTextFile(filename, data, { append: false }); - assertEquals("Hello", Deno.readTextFileSync(filename)); - // append not set should also overwrite - await Deno.writeTextFile(filename, data); - assertEquals("Hello", Deno.readTextFileSync(filename)); - }, -); diff --git a/runtime/js/40_testing.js b/runtime/js/40_testing.js index 1d0296240b6d86..be6a80c272719b 100644 --- a/runtime/js/40_testing.js +++ b/runtime/js/40_testing.js @@ -206,7 +206,9 @@ finishing test case.`; filter = null, } = {}) { const only = tests.filter((test) => test.only); - const pending = (only.length > 0 ? only : tests).filter(createTestFilter(filter)); + const pending = (only.length > 0 ? only : tests).filter( + createTestFilter(filter), + ); sendTestMessage("plan", { filtered: tests.length - pending.length, pending: pending.length, @@ -220,6 +222,7 @@ finishing test case.`; window.__bootstrap.internals = { ...window.__bootstrap.internals ?? {}, + createTestFilter, runTests, };