summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorNayeem Rahman <nayeemrmn99@gmail.com>2020-06-12 20:23:38 +0100
committerGitHub <noreply@github.com>2020-06-12 15:23:38 -0400
commit1fff6f55c3ba98a10018c6d374795e612061e9b6 (patch)
tree12074b6d44736b11513d857e437f9e30a6bf65a4
parent26bf56afdaf16634ffbaa23684faf3a44cc10f62 (diff)
refactor: Don't destructure the Deno namespace (#6268)
-rw-r--r--cli/tests/cat.ts10
-rw-r--r--cli/tests/compiler_api_test.ts50
-rw-r--r--cli/tests/complex_permissions_test.ts12
-rw-r--r--cli/tests/echo_server.ts7
-rw-r--r--cli/tests/permission_test.ts16
-rw-r--r--cli/tests/unbuffered_stderr.ts4
-rw-r--r--cli/tests/unbuffered_stdout.ts4
-rw-r--r--cli/tests/unit/buffer_test.ts55
-rw-r--r--cli/tests/unit/process_test.ts67
-rw-r--r--docs/contributing/architecture.md7
-rw-r--r--std/_util/assert_test.ts8
-rw-r--r--std/_util/deep_assign_test.ts3
-rw-r--r--std/encoding/_yaml/example/sample_document.ts4
-rw-r--r--std/encoding/_yaml/type/binary.ts7
-rw-r--r--std/encoding/base64_test.ts10
-rw-r--r--std/encoding/base64url_test.ts8
-rw-r--r--std/examples/chat/server_test.ts6
-rw-r--r--std/examples/flags.ts3
-rw-r--r--std/examples/test.ts3
-rw-r--r--std/examples/tests/xeval_test.ts15
-rw-r--r--std/examples/xeval.ts12
-rw-r--r--std/flags/README.md8
-rw-r--r--std/flags/mod.ts5
-rw-r--r--std/fs/empty_dir.ts14
-rw-r--r--std/fs/ensure_dir.ts9
-rw-r--r--std/fs/ensure_file.ts9
-rw-r--r--std/fs/exists.ts5
-rw-r--r--std/fs/expand_glob.ts10
-rw-r--r--std/fs/expand_glob_test.ts7
-rw-r--r--std/fs/walk.ts9
-rw-r--r--std/fs/walk_test.ts34
-rw-r--r--std/hash/_fnv/util_test.ts6
-rw-r--r--std/hash/fnv_test.ts18
-rw-r--r--std/hash/md5_test.ts6
-rw-r--r--std/hash/sha1_test.ts7
-rw-r--r--std/hash/sha256_test.ts14
-rw-r--r--std/hash/sha3_test.ts57
-rw-r--r--std/hash/sha512_test.ts16
-rw-r--r--std/http/_io_test.ts125
-rw-r--r--std/http/cookie_test.ts7
-rwxr-xr-xstd/http/file_server.ts22
-rw-r--r--std/http/file_server_test.ts81
-rw-r--r--std/http/racing_server_test.ts7
-rw-r--r--std/http/server.ts24
-rw-r--r--std/http/server_test.ts169
-rw-r--r--std/io/bufio_test.ts19
-rw-r--r--std/io/ioutil_test.ts8
-rw-r--r--std/io/readers.ts12
-rw-r--r--std/io/readers_test.ts13
-rw-r--r--std/io/util.ts9
-rw-r--r--std/io/util_test.ts7
-rw-r--r--std/io/writers_test.ts5
-rw-r--r--std/log/handlers.ts20
-rw-r--r--std/log/handlers_test.ts31
-rw-r--r--std/log/logger_test.ts233
-rw-r--r--std/log/mod_test.ts5
-rw-r--r--std/log/test.ts11
-rw-r--r--std/mime/multipart.ts36
-rw-r--r--std/mime/multipart_test.ts47
-rw-r--r--std/node/_fs/_fs_appendFile_test.ts19
-rw-r--r--std/node/_fs/_fs_chmod_test.ts5
-rw-r--r--std/node/_fs/_fs_chown_test.ts5
-rw-r--r--std/node/_fs/_fs_close_test.ts11
-rw-r--r--std/node/_fs/_fs_copy_test.ts8
-rw-r--r--std/node/_fs/_fs_dir_test.ts17
-rw-r--r--std/node/_fs/_fs_dirent_test.ts11
-rw-r--r--std/node/_fs/_fs_exists_test.ts7
-rw-r--r--std/node/_fs/_fs_link_test.ts8
-rw-r--r--std/node/_fs/_fs_mkdir_test.ts7
-rw-r--r--std/node/_fs/_fs_readFile.ts8
-rw-r--r--std/node/_fs/_fs_readFile_test.ts13
-rw-r--r--std/node/_fs/_fs_readlink.ts6
-rw-r--r--std/node/_fs/_fs_readlink_test.ts9
-rw-r--r--std/node/_fs/_fs_writeFile_test.ts271
-rw-r--r--std/node/_fs/promises/_fs_readFile_test.ts9
-rw-r--r--std/node/_fs/promises/_fs_writeFile_test.ts146
-rw-r--r--std/node/_util/_util_callbackify_test.ts334
-rw-r--r--std/node/_util/_util_promisify_test.ts141
-rw-r--r--std/node/_util/_util_types_test.ts156
-rw-r--r--std/node/events_test.ts61
-rw-r--r--std/node/module_test.ts14
-rw-r--r--std/node/os_test.ts33
-rw-r--r--std/node/process.ts32
-rw-r--r--std/node/process_test.ts19
-rw-r--r--std/node/querystring_test.ts5
-rw-r--r--std/node/util_test.ts33
-rw-r--r--std/path/_globrex_test.ts38
-rw-r--r--std/path/basename_test.ts6
-rw-r--r--std/path/common_test.ts9
-rw-r--r--std/path/dirname_test.ts6
-rw-r--r--std/path/extname_test.ts6
-rw-r--r--std/path/glob_test.ts25
-rw-r--r--std/path/isabsolute_test.ts6
-rw-r--r--std/path/join_test.ts5
-rw-r--r--std/path/parse_format_test.ts18
-rw-r--r--std/path/relative_test.ts6
-rw-r--r--std/path/resolve_test.ts10
-rw-r--r--std/path/zero_length_strings_test.ts14
-rw-r--r--std/permissions/test.ts13
-rw-r--r--std/signal/test.ts7
-rw-r--r--std/testing/asserts_test.ts44
-rw-r--r--std/testing/bench.ts6
-rw-r--r--std/testing/bench_test.ts23
-rw-r--r--std/testing/diff_test.ts21
-rw-r--r--std/textproto/test.ts26
-rw-r--r--std/uuid/tests/isNil.ts3
-rw-r--r--std/uuid/tests/v1/generate.ts7
-rw-r--r--std/uuid/tests/v4/generate.ts5
-rw-r--r--std/uuid/tests/v5/generate.ts11
-rw-r--r--std/ws/mod.ts17
-rw-r--r--std/ws/test.ts225
111 files changed, 1659 insertions, 1722 deletions
diff --git a/cli/tests/cat.ts b/cli/tests/cat.ts
index bd6b5af06..a5b38fccd 100644
--- a/cli/tests/cat.ts
+++ b/cli/tests/cat.ts
@@ -1,10 +1,8 @@
-const { stdout, open, copy, args } = Deno;
-
async function main(): Promise<void> {
- for (let i = 1; i < args.length; i++) {
- const filename = args[i];
- const file = await open(filename);
- await copy(file, stdout);
+ for (let i = 1; i < Deno.args.length; i++) {
+ const filename = Deno.args[i];
+ const file = await Deno.open(filename);
+ await Deno.copy(file, Deno.stdout);
}
}
diff --git a/cli/tests/compiler_api_test.ts b/cli/tests/compiler_api_test.ts
index cdc2be6d2..967220cb4 100644
--- a/cli/tests/compiler_api_test.ts
+++ b/cli/tests/compiler_api_test.ts
@@ -1,10 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
import { assert, assertEquals } from "../../std/testing/asserts.ts";
-const { compile, transpileOnly, bundle, test } = Deno;
-test("compilerApiCompileSources", async function () {
- const [diagnostics, actual] = await compile("/foo.ts", {
+Deno.test("compilerApiCompileSources", async function () {
+ const [diagnostics, actual] = await Deno.compile("/foo.ts", {
"/foo.ts": `import * as bar from "./bar.ts";\n\nconsole.log(bar);\n`,
"/bar.ts": `export const bar = "bar";\n`,
});
@@ -18,8 +16,8 @@ test("compilerApiCompileSources", async function () {
]);
});
-test("compilerApiCompileNoSources", async function () {
- const [diagnostics, actual] = await compile("./subdir/mod1.ts");
+Deno.test("compilerApiCompileNoSources", async function () {
+ const [diagnostics, actual] = await Deno.compile("./subdir/mod1.ts");
assert(diagnostics == null);
assert(actual);
const keys = Object.keys(actual);
@@ -28,8 +26,8 @@ test("compilerApiCompileNoSources", async function () {
assert(keys[1].endsWith("print_hello.js"));
});
-test("compilerApiCompileOptions", async function () {
- const [diagnostics, actual] = await compile(
+Deno.test("compilerApiCompileOptions", async function () {
+ const [diagnostics, actual] = await Deno.compile(
"/foo.ts",
{
"/foo.ts": `export const foo = "foo";`,
@@ -45,8 +43,8 @@ test("compilerApiCompileOptions", async function () {
assert(actual["/foo.js"].startsWith("define("));
});
-test("compilerApiCompileLib", async function () {
- const [diagnostics, actual] = await compile(
+Deno.test("compilerApiCompileLib", async function () {
+ const [diagnostics, actual] = await Deno.compile(
"/foo.ts",
{
"/foo.ts": `console.log(document.getElementById("foo"));
@@ -61,8 +59,8 @@ test("compilerApiCompileLib", async function () {
assertEquals(Object.keys(actual), ["/foo.js.map", "/foo.js"]);
});
-test("compilerApiCompileTypes", async function () {
- const [diagnostics, actual] = await compile(
+Deno.test("compilerApiCompileTypes", async function () {
+ const [diagnostics, actual] = await Deno.compile(
"/foo.ts",
{
"/foo.ts": `console.log(Foo.bar);`,
@@ -76,8 +74,8 @@ test("compilerApiCompileTypes", async function () {
assertEquals(Object.keys(actual), ["/foo.js.map", "/foo.js"]);
});
-test("transpileOnlyApi", async function () {
- const actual = await transpileOnly({
+Deno.test("transpileOnlyApi", async function () {
+ const actual = await Deno.transpileOnly({
"foo.ts": `export enum Foo { Foo, Bar, Baz };\n`,
});
assert(actual);
@@ -86,8 +84,8 @@ test("transpileOnlyApi", async function () {
assert(actual["foo.ts"].map);
});
-test("transpileOnlyApiConfig", async function () {
- const actual = await transpileOnly(
+Deno.test("transpileOnlyApiConfig", async function () {
+ const actual = await Deno.transpileOnly(
{
"foo.ts": `export enum Foo { Foo, Bar, Baz };\n`,
},
@@ -102,8 +100,8 @@ test("transpileOnlyApiConfig", async function () {
assert(actual["foo.ts"].map == null);
});
-test("bundleApiSources", async function () {
- const [diagnostics, actual] = await bundle("/foo.ts", {
+Deno.test("bundleApiSources", async function () {
+ const [diagnostics, actual] = await Deno.bundle("/foo.ts", {
"/foo.ts": `export * from "./bar.ts";\n`,
"/bar.ts": `export const bar = "bar";\n`,
});
@@ -112,15 +110,15 @@ test("bundleApiSources", async function () {
assert(actual.includes(`__exp["bar"]`));
});
-test("bundleApiNoSources", async function () {
- const [diagnostics, actual] = await bundle("./subdir/mod1.ts");
+Deno.test("bundleApiNoSources", async function () {
+ const [diagnostics, actual] = await Deno.bundle("./subdir/mod1.ts");
assert(diagnostics == null);
assert(actual.includes(`__instantiate("mod1")`));
assert(actual.includes(`__exp["printHello3"]`));
});
-test("bundleApiConfig", async function () {
- const [diagnostics, actual] = await bundle(
+Deno.test("bundleApiConfig", async function () {
+ const [diagnostics, actual] = await Deno.bundle(
"/foo.ts",
{
"/foo.ts": `// random comment\nexport * from "./bar.ts";\n`,
@@ -134,8 +132,8 @@ test("bundleApiConfig", async function () {
assert(!actual.includes(`random`));
});
-test("bundleApiJsModules", async function () {
- const [diagnostics, actual] = await bundle("/foo.js", {
+Deno.test("bundleApiJsModules", async function () {
+ const [diagnostics, actual] = await Deno.bundle("/foo.js", {
"/foo.js": `export * from "./bar.js";\n`,
"/bar.js": `export const bar = "bar";\n`,
});
@@ -143,8 +141,8 @@ test("bundleApiJsModules", async function () {
assert(actual.includes(`System.register("bar",`));
});
-test("diagnosticsTest", async function () {
- const [diagnostics] = await compile("/foo.ts", {
+Deno.test("diagnosticsTest", async function () {
+ const [diagnostics] = await Deno.compile("/foo.ts", {
"/foo.ts": `document.getElementById("foo");`,
});
assert(Array.isArray(diagnostics));
diff --git a/cli/tests/complex_permissions_test.ts b/cli/tests/complex_permissions_test.ts
index 55b4ead35..ad8b5302c 100644
--- a/cli/tests/complex_permissions_test.ts
+++ b/cli/tests/complex_permissions_test.ts
@@ -1,14 +1,12 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
-const { args, readFileSync, writeFileSync, exit } = Deno;
-
-const name = args[0];
+const name = Deno.args[0];
const test: { [key: string]: Function } = {
read(files: string[]): void {
- files.forEach((file) => readFileSync(file));
+ files.forEach((file) => Deno.readFileSync(file));
},
write(files: string[]): void {
files.forEach((file) =>
- writeFileSync(file, new Uint8Array(0), { append: true })
+ Deno.writeFileSync(file, new Uint8Array(0), { append: true })
);
},
netFetch(hosts: string[]): void {
@@ -40,7 +38,7 @@ const test: { [key: string]: Function } = {
if (!test[name]) {
console.log("Unknown test:", name);
- exit(1);
+ Deno.exit(1);
}
-test[name](args.slice(1));
+test[name](Deno.args.slice(1));
diff --git a/cli/tests/echo_server.ts b/cli/tests/echo_server.ts
index 5c6b5954b..48b43aca6 100644
--- a/cli/tests/echo_server.ts
+++ b/cli/tests/echo_server.ts
@@ -1,11 +1,10 @@
-const { args, listen, copy } = Deno;
-const addr = args[1] || "0.0.0.0:4544";
+const addr = Deno.args[1] || "0.0.0.0:4544";
const [hostname, port] = addr.split(":");
-const listener = listen({ hostname, port: Number(port) });
+const listener = Deno.listen({ hostname, port: Number(port) });
console.log("listening on", addr);
listener.accept().then(
async (conn): Promise<void> => {
- await copy(conn, conn);
+ await Deno.copy(conn, conn);
conn.close();
listener.close();
}
diff --git a/cli/tests/permission_test.ts b/cli/tests/permission_test.ts
index bcfb840bf..399c757d3 100644
--- a/cli/tests/permission_test.ts
+++ b/cli/tests/permission_test.ts
@@ -1,23 +1,21 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
-const { args, listen, env, exit, makeTempDirSync, readFileSync, run } = Deno;
-
-const name = args[0];
+const name = Deno.args[0];
const test: { [key: string]: Function } = {
readRequired(): Promise<void> {
- readFileSync("README.md");
+ Deno.readFileSync("README.md");
return Promise.resolve();
},
writeRequired(): void {
- makeTempDirSync();
+ Deno.makeTempDirSync();
},
envRequired(): void {
- env.get("home");
+ Deno.env.get("home");
},
netRequired(): void {
- listen({ transport: "tcp", port: 4541 });
+ Deno.listen({ transport: "tcp", port: 4541 });
},
runRequired(): void {
- run({
+ Deno.run({
cmd: [
"python",
"-c",
@@ -29,7 +27,7 @@ const test: { [key: string]: Function } = {
if (!test[name]) {
console.log("Unknown test:", name);
- exit(1);
+ Deno.exit(1);
}
test[name]();
diff --git a/cli/tests/unbuffered_stderr.ts b/cli/tests/unbuffered_stderr.ts
index f4bceb1fc..0f1d2a999 100644
--- a/cli/tests/unbuffered_stderr.ts
+++ b/cli/tests/unbuffered_stderr.ts
@@ -1,3 +1 @@
-const { stderr } = Deno;
-
-stderr.write(new TextEncoder().encode("x"));
+Deno.stderr.write(new TextEncoder().encode("x"));
diff --git a/cli/tests/unbuffered_stdout.ts b/cli/tests/unbuffered_stdout.ts
index fdb1a0e23..9f1e07a97 100644
--- a/cli/tests/unbuffered_stdout.ts
+++ b/cli/tests/unbuffered_stdout.ts
@@ -1,3 +1 @@
-const { stdout } = Deno;
-
-stdout.write(new TextEncoder().encode("a"));
+Deno.stdout.write(new TextEncoder().encode("a"));
diff --git a/cli/tests/unit/buffer_test.ts b/cli/tests/unit/buffer_test.ts
index 23e655a05..c5a63b5c8 100644
--- a/cli/tests/unit/buffer_test.ts
+++ b/cli/tests/unit/buffer_test.ts
@@ -12,9 +12,6 @@ import {
unitTest,
} from "./test_util.ts";
-const { Buffer, readAll, readAllSync, writeAll, writeAllSync } = Deno;
-type Buffer = Deno.Buffer;
-
// N controls how many iterations of certain checks are performed.
const N = 100;
let testBytes: Uint8Array | null;
@@ -44,7 +41,7 @@ function check(buf: Deno.Buffer, s: string): void {
// The initial contents of buf corresponds to the string s;
// the result is the final contents of buf returned as a string.
async function fillBytes(
- buf: Buffer,
+ buf: Deno.Buffer,
s: string,
n: number,
fub: Uint8Array
@@ -62,7 +59,11 @@ async function fillBytes(
// Empty buf through repeated reads into fub.
// The initial contents of buf corresponds to the string s.
-async function empty(buf: Buffer, s: string, fub: Uint8Array): Promise<void> {
+async function empty(
+ buf: Deno.Buffer,
+ s: string,
+ fub: Uint8Array
+): Promise<void> {
check(buf, s);
while (true) {
const r = await buf.read(fub);
@@ -86,7 +87,7 @@ unitTest(function bufferNewBuffer(): void {
init();
assert(testBytes);
assert(testString);
- const buf = new Buffer(testBytes.buffer as ArrayBuffer);
+ const buf = new Deno.Buffer(testBytes.buffer as ArrayBuffer);
check(buf, testString);
});
@@ -94,7 +95,7 @@ unitTest(async function bufferBasicOperations(): Promise<void> {
init();
assert(testBytes);
assert(testString);
- const buf = new Buffer();
+ const buf = new Deno.Buffer();
for (let i = 0; i < 5; i++) {
check(buf, "");
@@ -133,7 +134,7 @@ unitTest(async function bufferBasicOperations(): Promise<void> {
unitTest(async function bufferReadEmptyAtEOF(): Promise<void> {
// 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 Buffer();
+ const buf = new Deno.Buffer();
const zeroLengthTmp = new Uint8Array(0);
const result = await buf.read(zeroLengthTmp);
assertEquals(result, 0);
@@ -141,7 +142,7 @@ unitTest(async function bufferReadEmptyAtEOF(): Promise<void> {
unitTest(async function bufferLargeByteWrites(): Promise<void> {
init();
- const buf = new Buffer();
+ const buf = new Deno.Buffer();
const limit = 9;
for (let i = 3; i < limit; i += 3) {
const s = await fillBytes(buf, "", 5, testBytes!);
@@ -155,7 +156,7 @@ unitTest(async function bufferTooLargeByteWrites(): Promise<void> {
const tmp = new Uint8Array(72);
const growLen = Number.MAX_VALUE;
const xBytes = repeat("x", 0);
- const buf = new Buffer(xBytes.buffer as ArrayBuffer);
+ const buf = new Deno.Buffer(xBytes.buffer as ArrayBuffer);
await buf.read(tmp);
let err;
@@ -173,7 +174,7 @@ unitTest(async function bufferLargeByteReads(): Promise<void> {
init();
assert(testBytes);
assert(testString);
- const buf = new Buffer();
+ const buf = new Deno.Buffer();
for (let i = 3; i < 30; i += 3) {
const n = Math.floor(testBytes.byteLength / i);
const s = await fillBytes(buf, "", 5, testBytes.subarray(0, n));
@@ -183,7 +184,7 @@ unitTest(async function bufferLargeByteReads(): Promise<void> {
});
unitTest(function bufferCapWithPreallocatedSlice(): void {
- const buf = new Buffer(new ArrayBuffer(10));
+ const buf = new Deno.Buffer(new ArrayBuffer(10));
assertEquals(buf.capacity, 10);
});
@@ -191,7 +192,7 @@ unitTest(async function bufferReadFrom(): Promise<void> {
init();
assert(testBytes);
assert(testString);
- const buf = new Buffer();
+ const buf = new Deno.Buffer();
for (let i = 3; i < 30; i += 3) {
const s = await fillBytes(
buf,
@@ -199,13 +200,13 @@ unitTest(async function bufferReadFrom(): Promise<void> {
5,
testBytes.subarray(0, Math.floor(testBytes.byteLength / i))
);
- const b = new Buffer();
+ const b = new Deno.Buffer();
await b.readFrom(buf);
const fub = new Uint8Array(testString.length);
await empty(b, s, fub);
}
assertThrowsAsync(async function () {
- await new Buffer().readFrom(null!);
+ await new Deno.Buffer().readFrom(null!);
});
});
@@ -213,7 +214,7 @@ unitTest(async function bufferReadFromSync(): Promise<void> {
init();
assert(testBytes);
assert(testString);
- const buf = new Buffer();
+ const buf = new Deno.Buffer();
for (let i = 3; i < 30; i += 3) {
const s = await fillBytes(
buf,
@@ -221,13 +222,13 @@ unitTest(async function bufferReadFromSync(): Promise<void> {
5,
testBytes.subarray(0, Math.floor(testBytes.byteLength / i))
);
- const b = new Buffer();
+ const b = new Deno.Buffer();
b.readFromSync(buf);
const fub = new Uint8Array(testString.length);
await empty(b, s, fub);
}
assertThrows(function () {
- new Buffer().readFromSync(null!);
+ new Deno.Buffer().readFromSync(null!);
});
});
@@ -236,7 +237,7 @@ unitTest(async function bufferTestGrow(): Promise<void> {
for (const startLen of [0, 100, 1000, 10000, 100000]) {
const xBytes = repeat("x", startLen);
for (const growLen of [0, 100, 1000, 10000, 100000]) {
- const buf = new Buffer(xBytes.buffer as ArrayBuffer);
+ const buf = new Deno.Buffer(xBytes.buffer as ArrayBuffer);
// If we read, this affects buf.off, which is good to test.
const nread = (await buf.read(tmp)) ?? 0;
buf.grow(growLen);
@@ -258,8 +259,8 @@ unitTest(async function bufferTestGrow(): Promise<void> {
unitTest(async function testReadAll(): Promise<void> {
init();
assert(testBytes);
- const reader = new Buffer(testBytes.buffer as ArrayBuffer);
- const actualBytes = await readAll(reader);
+ const reader = new Deno.Buffer(testBytes.buffer as ArrayBuffer);
+ const actualBytes = await Deno.readAll(reader);
assertEquals(testBytes.byteLength, actualBytes.byteLength);
for (let i = 0; i < testBytes.length; ++i) {
assertEquals(testBytes[i], actualBytes[i]);
@@ -269,8 +270,8 @@ unitTest(async function testReadAll(): Promise<void> {
unitTest(function testReadAllSync(): void {
init();
assert(testBytes);
- const reader = new Buffer(testBytes.buffer as ArrayBuffer);
- const actualBytes = readAllSync(reader);
+ const reader = new Deno.Buffer(testBytes.buffer as ArrayBuffer);
+ const actualBytes = Deno.readAllSync(reader);
assertEquals(testBytes.byteLength, actualBytes.byteLength);
for (let i = 0; i < testBytes.length; ++i) {
assertEquals(testBytes[i], actualBytes[i]);
@@ -280,8 +281,8 @@ unitTest(function testReadAllSync(): void {
unitTest(async function testWriteAll(): Promise<void> {
init();
assert(testBytes);
- const writer = new Buffer();
- await writeAll(writer, testBytes);
+ const writer = new Deno.Buffer();
+ await Deno.writeAll(writer, testBytes);
const actualBytes = writer.bytes();
assertEquals(testBytes.byteLength, actualBytes.byteLength);
for (let i = 0; i < testBytes.length; ++i) {
@@ -292,8 +293,8 @@ unitTest(async function testWriteAll(): Promise<void> {
unitTest(function testWriteAllSync(): void {
init();
assert(testBytes);
- const writer = new Buffer();
- writeAllSync(writer, testBytes);
+ const writer = new Deno.Buffer();
+ Deno.writeAllSync(writer, testBytes);
const actualBytes = writer.bytes();
assertEquals(testBytes.byteLength, actualBytes.byteLength);
for (let i = 0; i < testBytes.length; ++i) {
diff --git a/cli/tests/unit/process_test.ts b/cli/tests/unit/process_test.ts
index c6503b2e0..cf512eea5 100644
--- a/cli/tests/unit/process_test.ts
+++ b/cli/tests/unit/process_test.ts
@@ -5,20 +5,11 @@ import {
assertStringContains,
unitTest,
} from "./test_util.ts";
-const {
- kill,
- run,
- readFile,
- open,
- makeTempDir,
- writeFile,
- writeFileSync,
-} = Deno;
unitTest(function runPermissions(): void {
let caughtError = false;
try {
- run({ cmd: ["python", "-c", "print('hello world')"] });
+ Deno.run({ cmd: ["python", "-c", "print('hello world')"] });
} catch (e) {
caughtError = true;
assert(e instanceof Deno.errors.PermissionDenied);
@@ -27,7 +18,7 @@ unitTest(function runPermissions(): void {
});
unitTest({ perms: { run: true } }, async function runSuccess(): Promise<void> {
- const p = run({
+ const p = Deno.run({
cmd: ["python", "-c", "print('hello world')"],
stdout: "piped",
stderr: "null",
@@ -43,7 +34,7 @@ unitTest({ perms: { run: true } }, async function runSuccess(): Promise<void> {
unitTest(
{ perms: { run: true } },
async function runCommandFailedWithCode(): Promise<void> {
- const p = run({
+ const p = Deno.run({
cmd: ["python", "-c", "import sys;sys.exit(41 + 1)"],
});
const status = await p.status();
@@ -61,7 +52,7 @@ unitTest(
perms: { run: true },
},
async function runCommandFailedWithSignal(): Promise<void> {
- const p = run({
+ const p = Deno.run({
cmd: ["python", "-c", "import os;os.kill(os.getpid(), 9)"],
});
const status = await p.status();
@@ -75,7 +66,7 @@ unitTest(
unitTest({ perms: { run: true } }, function runNotFound(): void {
let error;
try {
- run({ cmd: ["this file hopefully doesn't exist"] });
+ Deno.run({ cmd: ["this file hopefully doesn't exist"] });
} catch (e) {
error = e;
}
@@ -87,7 +78,7 @@ unitTest(
{ perms: { write: true, run: true } },
async function runWithCwdIsAsync(): Promise<void> {
const enc = new TextEncoder();
- const cwd = await makeTempDir({ prefix: "deno_command_test" });
+ const cwd = await Deno.makeTempDir({ prefix: "deno_command_test" });
const exitCodeFile = "deno_was_here";
const pyProgramFile = "poll_exit.py";
@@ -107,8 +98,8 @@ while True:
pass
`;
- writeFileSync(`${cwd}/${pyProgramFile}.py`, enc.encode(pyProgram));
- const p = run({
+ Deno.writeFileSync(`${cwd}/${pyProgramFile}.py`, enc.encode(pyProgram));
+ const p = Deno.run({
cwd,
cmd: ["python", `${pyProgramFile}.py`],
});
@@ -116,7 +107,7 @@ while True:
// Write the expected exit code *after* starting python.
// This is how we verify that `run()` is actually asynchronous.
const code = 84;
- writeFileSync(`${cwd}/${exitCodeFile}`, enc.encode(`${code}`));
+ Deno.writeFileSync(`${cwd}/${exitCodeFile}`, enc.encode(`${code}`));
const status = await p.status();
assertEquals(status.success, false);
@@ -129,7 +120,7 @@ while True:
unitTest({ perms: { run: true } }, async function runStdinPiped(): Promise<
void
> {
- const p = run({
+ const p = Deno.run({
cmd: ["python", "-c", "import sys; assert 'hello' == sys.stdin.read();"],
stdin: "piped",
});
@@ -153,7 +144,7 @@ unitTest({ perms: { run: true } }, async function runStdinPiped(): Promise<
unitTest({ perms: { run: true } }, async function runStdoutPiped(): Promise<
void
> {
- const p = run({
+ const p = Deno.run({
cmd: ["python", "-c", "import sys; sys.stdout.write('hello')"],
stdout: "piped",
});
@@ -182,7 +173,7 @@ unitTest({ perms: { run: true } }, async function runStdoutPiped(): Promise<
unitTest({ perms: { run: true } }, async function runStderrPiped(): Promise<
void
> {
- const p = run({
+ const p = Deno.run({
cmd: ["python", "-c", "import sys; sys.stderr.write('hello')"],
stderr: "piped",
});
@@ -209,7 +200,7 @@ unitTest({ perms: { run: true } }, async function runStderrPiped(): Promise<
});
unitTest({ perms: { run: true } }, async function runOutput(): Promise<void> {
- const p = run({
+ const p = Deno.run({
cmd: ["python", "-c", "import sys; sys.stdout.write('hello')"],
stdout: "piped",
});
@@ -222,7 +213,7 @@ unitTest({ perms: { run: true } }, async function runOutput(): Promise<void> {
unitTest({ perms: { run: true } }, async function runStderrOutput(): Promise<
void
> {
- const p = run({
+ const p = Deno.run({
cmd: ["python", "-c", "import sys; sys.stderr.write('error')"],
stderr: "piped",
});
@@ -235,14 +226,14 @@ unitTest({ perms: { run: true } }, async function runStderrOutput(): Promise<
unitTest(
{ perms: { run: true, write: true, read: true } },
async function runRedirectStdoutStderr(): Promise<void> {
- const tempDir = await makeTempDir();
+ const tempDir = await Deno.makeTempDir();
const fileName = tempDir + "/redirected_stdio.txt";
- const file = await open(fileName, {
+ const file = await Deno.open(fileName, {
create: true,
write: true,
});
- const p = run({
+ const p = Deno.run({
cmd: [
"python",
"-c",
@@ -256,7 +247,7 @@ unitTest(
p.close();
file.close();
- const fileContents = await readFile(fileName);
+ const fileContents = await Deno.readFile(fileName);
const decoder = new TextDecoder();
const text = decoder.decode(fileContents);
@@ -268,13 +259,13 @@ unitTest(
unitTest(
{ perms: { run: true, write: true, read: true } },
async function runRedirectStdin(): Promise<void> {
- const tempDir = await makeTempDir();
+ const tempDir = await Deno.makeTempDir();
const fileName = tempDir + "/redirected_stdio.txt";
const encoder = new TextEncoder();
- await writeFile(fileName, encoder.encode("hello"));
- const file = await open(fileName);
+ await Deno.writeFile(fileName, encoder.encode("hello"));
+ const file = await Deno.open(fileName);
- const p = run({
+ const p = Deno.run({
cmd: ["python", "-c", "import sys; assert 'hello' == sys.stdin.read();"],
stdin: file.rid,
});
@@ -287,7 +278,7 @@ unitTest(
);
unitTest({ perms: { run: true } }, async function runEnv(): Promise<void> {
- const p = run({
+ const p = Deno.run({
cmd: [
"python",
"-c",
@@ -306,7 +297,7 @@ unitTest({ perms: { run: true } }, async function runEnv(): Promise<void> {
});
unitTest({ perms: { run: true } }, async function runClose(): Promise<void> {
- const p = run({
+ const p = Deno.run({
cmd: [
"python",
"-c",
@@ -340,7 +331,7 @@ unitTest(function killPermissions(): void {
// 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.
- kill(Deno.pid, Deno.Signal.SIGCONT);
+ Deno.kill(Deno.pid, Deno.Signal.SIGCONT);
} catch (e) {
caughtError = true;
assert(e instanceof Deno.errors.PermissionDenied);
@@ -349,12 +340,12 @@ unitTest(function killPermissions(): void {
});
unitTest({ perms: { run: true } }, async function killSuccess(): Promise<void> {
- const p = run({
+ const p = Deno.run({
cmd: ["python", "-c", "from time import sleep; sleep(10000)"],
});
assertEquals(Deno.Signal.SIGINT, 2);
- kill(p.pid, Deno.Signal.SIGINT);
+ Deno.kill(p.pid, Deno.Signal.SIGINT);
const status = await p.status();
assertEquals(status.success, false);
@@ -371,7 +362,7 @@ unitTest({ perms: { run: true } }, async function killSuccess(): Promise<void> {
});
unitTest({ perms: { run: true } }, function killFailed(): void {
- const p = run({
+ const p = Deno.run({
cmd: ["python", "-c", "from time import sleep; sleep(10000)"],
});
assert(!p.stdin);
@@ -379,7 +370,7 @@ unitTest({ perms: { run: true } }, function killFailed(): void {
let err;
try {
- kill(p.pid, 12345);
+ Deno.kill(p.pid, 12345);
} catch (e) {
err = e;
}
diff --git a/docs/contributing/architecture.md b/docs/contributing/architecture.md
index 511bb52e0..8600b5eae 100644
--- a/docs/contributing/architecture.md
+++ b/docs/contributing/architecture.md
@@ -20,11 +20,10 @@ would be good to be able to query the system for how many open resources there
are.
```ts
-const { resources, close } = Deno;
-console.log(resources());
+console.log(Deno.resources());
// { 0: "stdin", 1: "stdout", 2: "stderr" }
-close(0);
-console.log(resources());
+Deno.close(0);
+console.log(Deno.resources());
// { 1: "stdout", 2: "stderr" }
```
diff --git a/std/_util/assert_test.ts b/std/_util/assert_test.ts
index 38aeae91b..2c94f8bca 100644
--- a/std/_util/assert_test.ts
+++ b/std/_util/assert_test.ts
@@ -1,16 +1,14 @@
import { assert, DenoStdInternalError } from "./assert.ts";
import { assertThrows } from "../testing/asserts.ts";
-const { test } = Deno;
-
-test({
+Deno.test({
name: "assert valid scenario",
fn(): void {
assert(true);
},
});
-test({
+Deno.test({
name: "assert invalid scenario, no message",
fn(): void {
assertThrows(() => {
@@ -18,7 +16,7 @@ test({
}, DenoStdInternalError);
},
});
-test({
+Deno.test({
name: "assert invalid scenario, with message",
fn(): void {
assertThrows(
diff --git a/std/_util/deep_assign_test.ts b/std/_util/deep_assign_test.ts
index f1a56e1ad..14e81348d 100644
--- a/std/_util/deep_assign_test.ts
+++ b/std/_util/deep_assign_test.ts
@@ -1,9 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-const { test } = Deno;
import { assertEquals, assert } from "../testing/asserts.ts";
import { deepAssign } from "./deep_assign.ts";
-test("deepAssignTest", function (): void {
+Deno.test("deepAssignTest", function (): void {
const date = new Date("1979-05-27T07:32:00Z");
const reg = RegExp(/DENOWOWO/);
const obj1 = { deno: { bar: { deno: ["is", "not", "node"] } } };
diff --git a/std/encoding/_yaml/example/sample_document.ts b/std/encoding/_yaml/example/sample_document.ts
index da969d679..f66b3c417 100644
--- a/std/encoding/_yaml/example/sample_document.ts
+++ b/std/encoding/_yaml/example/sample_document.ts
@@ -3,10 +3,8 @@
import { parse } from "../../yaml.ts";
-const { readFileSync, cwd } = Deno;
-
(() => {
- const yml = readFileSync(`${cwd()}/example/sample_document.yml`);
+ const yml = Deno.readFileSync(`${Deno.cwd()}/example/sample_document.yml`);
const document = new TextDecoder().decode(yml);
const obj = parse(document) as object;
diff --git a/std/encoding/_yaml/type/binary.ts b/std/encoding/_yaml/type/binary.ts
index f4823b3f7..1a321afe8 100644
--- a/std/encoding/_yaml/type/binary.ts
+++ b/std/encoding/_yaml/type/binary.ts
@@ -2,12 +2,9 @@
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
import { Type } from "../type.ts";
import { Any } from "../utils.ts";
-const { Buffer } = Deno;
-
// [ 64, 65, 66 ] -> [ padding, CR, LF ]
const BASE64_MAP =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";
@@ -72,7 +69,7 @@ function constructYamlBinary(data: string): Deno.Buffer {
result.push((bits >> 4) & 0xff);
}
- return new Buffer(new Uint8Array(result));
+ return new Deno.Buffer(new Uint8Array(result));
}
function representYamlBinary(object: Uint8Array): string {
@@ -119,7 +116,7 @@ function representYamlBinary(object: Uint8Array): string {
}
function isBinary(obj: Any): obj is Deno.Buffer {
- const buf = new Buffer();
+ const buf = new Deno.Buffer();
try {
if (0 > buf.readFromSync(obj as Deno.Buffer)) return true;
return false;
diff --git a/std/encoding/base64_test.ts b/std/encoding/base64_test.ts
index bd559140a..9e549c698 100644
--- a/std/encoding/base64_test.ts
+++ b/std/encoding/base64_test.ts
@@ -1,6 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
-const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts";
import { encode, decode, decodeString } from "./base64.ts";
@@ -21,25 +19,25 @@ const testsetBinary = [
[new TextEncoder().encode("\x00\x00\x00\x00"), "AAAAAA=="],
];
-test("[encoding/base64] testBase64EncodeString", () => {
+Deno.test("[encoding/base64] testBase64EncodeString", () => {
for (const [input, output] of testsetString) {
assertEquals(encode(input), output);
}
});
-test("[encoding/base64] testBase64DecodeString", () => {
+Deno.test("[encoding/base64] testBase64DecodeString", () => {
for (const [input, output] of testsetString) {
assertEquals(decodeString(output), input);
}
});
-test("[encoding/base64] testBase64EncodeBinary", () => {
+Deno.test("[encoding/base64] testBase64EncodeBinary", () => {
for (const [input, output] of testsetBinary) {
assertEquals(encode(input), output);
}
});
-test("[encoding/base64] testBase64DecodeBinary", () => {
+Deno.test("[encoding/base64] testBase64DecodeBinary", () => {
for (const [input, output] of testsetBinary) {
const outputBinary = new Uint8Array(decode(output as string));
assertEquals(outputBinary, input as Uint8Array);
diff --git a/std/encoding/base64url_test.ts b/std/encoding/base64url_test.ts
index 2af9096a4..9a864a87c 100644
--- a/std/encoding/base64url_test.ts
+++ b/std/encoding/base64url_test.ts
@@ -1,6 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
-const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts";
import { encode, decode } from "./base64url.ts";
@@ -22,19 +20,19 @@ const testsetBinary = [
[new TextEncoder().encode("\x00\x00\x00\x00"), "AAAAAA"],
];
-test("[encoding/base64url] testBase64urlEncodeString", () => {
+Deno.test("[encoding/base64url] testBase64urlEncodeString", () => {
for (const [input, output] of testsetString) {
assertEquals(encode(input), output);
}
});
-test("[encoding/base64url] testBase64urlEncodeBinary", () => {
+Deno.test("[encoding/base64url] testBase64urlEncodeBinary", () => {
for (const [input, output] of testsetBinary) {
assertEquals(encode(input), output);
}
});
-test("[encoding/base64ur] testBase64urDecodeBinary", () => {
+Deno.test("[encoding/base64ur] testBase64urDecodeBinary", () => {
for (const [input, output] of testsetBinary) {
const outputBinary = new Uint8Array(decode(output as string));
assertEquals(outputBinary, input as Uint8Array);
diff --git a/std/examples/chat/server_test.ts b/std/examples/chat/server_test.ts
index 8e04b71d8..872f4ee12 100644
--- a/std/examples/chat/server_test.ts
+++ b/std/examples/chat/server_test.ts
@@ -5,8 +5,6 @@ import { BufReader } from "../../io/bufio.ts";
import { connectWebSocket, WebSocket } from "../../ws/mod.ts";
import { delay } from "../../async/delay.ts";
-const { test } = Deno;
-
async function startServer(): Promise<
Deno.Process<Deno.RunOptions & { stdout: "piped" }>
> {
@@ -36,7 +34,7 @@ async function startServer(): Promise<
return server;
}
-test({
+Deno.test({
name: "[examples/chat] GET / should serve html",
async fn() {
const server = await startServer();
@@ -54,7 +52,7 @@ test({
},
});
-test({
+Deno.test({
name: "[examples/chat] GET /ws should upgrade conn to ws",
async fn() {
const server = await startServer();
diff --git a/std/examples/flags.ts b/std/examples/flags.ts
index 4625b8c96..d7f0fc650 100644
--- a/std/examples/flags.ts
+++ b/std/examples/flags.ts
@@ -1,7 +1,6 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-const { args } = Deno;
import { parse } from "../flags/mod.ts";
if (import.meta.main) {
- console.dir(parse(args));
+ console.dir(parse(Deno.args));
}
diff --git a/std/examples/test.ts b/std/examples/test.ts
index acda9293d..20db3fb1d 100644
--- a/std/examples/test.ts
+++ b/std/examples/test.ts
@@ -1,5 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-const { run } = Deno;
import { assertEquals } from "../testing/asserts.ts";
/** Example of how to do basic tests */
@@ -13,7 +12,7 @@ Deno.test("t2", function (): void {
/** A more complicated test that runs a subprocess. */
Deno.test("catSmoke", async function (): Promise<void> {
- const p = run({
+ const p = Deno.run({
cmd: [
Deno.execPath(),
"run",
diff --git a/std/examples/tests/xeval_test.ts b/std/examples/tests/xeval_test.ts
index f86e27866..9f7c5db9e 100644
--- a/std/examples/tests/xeval_test.ts
+++ b/std/examples/tests/xeval_test.ts
@@ -7,7 +7,6 @@ import {
assertStringContains,
assert,
} from "../../testing/asserts.ts";
-const { execPath, run } = Deno;
Deno.test("xevalSuccess", async function (): Promise<void> {
const chunks: string[] = [];
@@ -32,8 +31,14 @@ const xevalPath = "examples/xeval.ts";
Deno.test({
name: "xevalCliReplvar",
fn: async function (): Promise<void> {
- const p = run({
- cmd: [execPath(), "run", xevalPath, "--replvar=abc", "console.log(abc)"],
+ const p = Deno.run({
+ cmd: [
+ Deno.execPath(),
+ "run",
+ xevalPath,
+ "--replvar=abc",
+ "console.log(abc)",
+ ],
stdin: "piped",
stdout: "piped",
stderr: "null",
@@ -48,8 +53,8 @@ Deno.test({
});
Deno.test("xevalCliSyntaxError", async function (): Promise<void> {
- const p = run({
- cmd: [execPath(), "run", xevalPath, "("],
+ const p = Deno.run({
+ cmd: [Deno.execPath(), "run", xevalPath, "("],
stdin: "null",
stdout: "piped",
stderr: "piped",
diff --git a/std/examples/xeval.ts b/std/examples/xeval.ts
index d688a6bf7..814d306cd 100644
--- a/std/examples/xeval.ts
+++ b/std/examples/xeval.ts
@@ -1,7 +1,5 @@
import { parse } from "../flags/mod.ts";
import { readStringDelim } from "../io/bufio.ts";
-const { args, exit, stdin } = Deno;
-type Reader = Deno.Reader;
/* eslint-disable-next-line max-len */
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction.
@@ -40,7 +38,7 @@ export interface XevalOptions {
const DEFAULT_DELIMITER = "\n";
export async function xeval(
- reader: Reader,
+ reader: Deno.Reader,
xevalFunc: XevalFunc,
{ delimiter = DEFAULT_DELIMITER }: XevalOptions = {}
): Promise<void> {
@@ -53,7 +51,7 @@ export async function xeval(
}
async function main(): Promise<void> {
- const parsedArgs = parse(args, {
+ const parsedArgs = parse(Deno.args, {
boolean: ["help"],
string: ["delim", "replvar"],
alias: {
@@ -69,7 +67,7 @@ async function main(): Promise<void> {
if (parsedArgs._.length != 1) {
console.error(HELP_MSG);
console.log(parsedArgs._);
- exit(1);
+ Deno.exit(1);
}
if (parsedArgs.help) {
return console.log(HELP_MSG);
@@ -82,12 +80,12 @@ async function main(): Promise<void> {
// new AsyncFunction()'s error message for this particular case isn't great.
if (!replVar.match(/^[_$A-z][_$A-z0-9]*$/)) {
console.error(`Bad replvar identifier: "${replVar}"`);
- exit(1);
+ Deno.exit(1);
}
const xEvalFunc = new AsyncFunction(replVar, code);
- await xeval(stdin, xEvalFunc, { delimiter });
+ await xeval(Deno.stdin, xEvalFunc, { delimiter });
}
if (import.meta.main) {
diff --git a/std/flags/README.md b/std/flags/README.md
index 0b7f7fa65..ebfc346e1 100644
--- a/std/flags/README.md
+++ b/std/flags/README.md
@@ -5,10 +5,9 @@ Command line arguments parser for Deno based on minimist
# Example
```ts
-const { args } = Deno;
import { parse } from "https://deno.land/std/flags/mod.ts";
-console.dir(parse(args));
+console.dir(parse(Deno.args));
```
```
@@ -57,11 +56,10 @@ options can be:
example:
```ts
// $ deno run example.ts -- a arg1
- const { args } = Deno;
import { parse } from "https://deno.land/std/flags/mod.ts";
- console.dir(parse(args, { "--": false }));
+ console.dir(parse(Deno.args, { "--": false }));
// output: { _: [ "a", "arg1" ] }
- console.dir(parse(args, { "--": true }));
+ console.dir(parse(Deno.args, { "--": true }));
// output: { _: [], --: [ "a", "arg1" ] }
```
- `options.unknown` - a function which is invoked with a command line parameter
diff --git a/std/flags/mod.ts b/std/flags/mod.ts
index 5c8fcc0d9..a961e6c68 100644
--- a/std/flags/mod.ts
+++ b/std/flags/mod.ts
@@ -15,11 +15,10 @@ export interface ArgParsingOptions {
* the result `['--']` with everything after the `--`. Here's an example:
*
* // $ deno run example.ts -- a arg1
- * const { args } = Deno;
* import { parse } from "https://deno.land/std/flags/mod.ts";
- * console.dir(parse(args, { "--": false }));
+ * console.dir(parse(Deno.args, { "--": false }));
* // output: { _: [ "a", "arg1" ] }
- * console.dir(parse(args, { "--": true }));
+ * console.dir(parse(Deno.args, { "--": true }));
* // output: { _: [], --: [ "a", "arg1" ] }
*
* Defaults to `false`.
diff --git a/std/fs/empty_dir.ts b/std/fs/empty_dir.ts
index 2f5d2deeb..dea09b5c0 100644
--- a/std/fs/empty_dir.ts
+++ b/std/fs/empty_dir.ts
@@ -1,6 +1,6 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { join } from "../path/mod.ts";
-const { readDir, readDirSync, mkdir, mkdirSync, remove, removeSync } = Deno;
+
/**
* Ensures that a directory is empty.
* Deletes directory contents if the directory is not empty.
@@ -11,7 +11,7 @@ const { readDir, readDirSync, mkdir, mkdirSync, remove, removeSync } = Deno;
export async function emptyDir(dir: string): Promise<void> {
try {
const items = [];
- for await (const dirEntry of readDir(dir)) {
+ for await (const dirEntry of Deno.readDir(dir)) {
items.push(dirEntry);
}
@@ -19,7 +19,7 @@ export async function emptyDir(dir: string): Promise<void> {
const item = items.shift();
if (item && item.name) {
const filepath = join(dir, item.name);
- await remove(filepath, { recursive: true });
+ await Deno.remove(filepath, { recursive: true });
}
}
} catch (err) {
@@ -28,7 +28,7 @@ export async function emptyDir(dir: string): Promise<void> {
}
// if not exist. then create it
- await mkdir(dir, { recursive: true });
+ await Deno.mkdir(dir, { recursive: true });
}
}
@@ -41,14 +41,14 @@ export async function emptyDir(dir: string): Promise<void> {
*/
export function emptyDirSync(dir: string): void {
try {
- const items = [...readDirSync(dir)];
+ const items = [...Deno.readDirSync(dir)];
// If the directory exists, remove all entries inside it.
while (items.length) {
const item = items.shift();
if (item && item.name) {
const filepath = join(dir, item.name);
- removeSync(filepath, { recursive: true });
+ Deno.removeSync(filepath, { recursive: true });
}
}
} catch (err) {
@@ -56,7 +56,7 @@ export function emptyDirSync(dir: string): void {
throw err;
}
// if not exist. then create it
- mkdirSync(dir, { recursive: true });
+ Deno.mkdirSync(dir, { recursive: true });
return;
}
}
diff --git a/std/fs/ensure_dir.ts b/std/fs/ensure_dir.ts
index 43b230ae1..961476028 100644
--- a/std/fs/ensure_dir.ts
+++ b/std/fs/ensure_dir.ts
@@ -1,6 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { getFileInfoType } from "./_util.ts";
-const { lstat, lstatSync, mkdir, mkdirSync } = Deno;
/**
* Ensures that the directory exists.
@@ -9,7 +8,7 @@ const { lstat, lstatSync, mkdir, mkdirSync } = Deno;
*/
export async function ensureDir(dir: string): Promise<void> {
try {
- const fileInfo = await lstat(dir);
+ const fileInfo = await Deno.lstat(dir);
if (!fileInfo.isDirectory) {
throw new Error(
`Ensure path exists, expected 'dir', got '${getFileInfoType(fileInfo)}'`
@@ -18,7 +17,7 @@ export async function ensureDir(dir: string): Promise<void> {
} catch (err) {
if (err instanceof Deno.errors.NotFound) {
// if dir not exists. then create it.
- await mkdir(dir, { recursive: true });
+ await Deno.mkdir(dir, { recursive: true });
return;
}
throw err;
@@ -32,7 +31,7 @@ export async function ensureDir(dir: string): Promise<void> {
*/
export function ensureDirSync(dir: string): void {
try {
- const fileInfo = lstatSync(dir);
+ const fileInfo = Deno.lstatSync(dir);
if (!fileInfo.isDirectory) {
throw new Error(
`Ensure path exists, expected 'dir', got '${getFileInfoType(fileInfo)}'`
@@ -41,7 +40,7 @@ export function ensureDirSync(dir: string): void {
} catch (err) {
if (err instanceof Deno.errors.NotFound) {
// if dir not exists. then create it.
- mkdirSync(dir, { recursive: true });
+ Deno.mkdirSync(dir, { recursive: true });
return;
}
throw err;
diff --git a/std/fs/ensure_file.ts b/std/fs/ensure_file.ts
index a1476b657..b36379b3d 100644
--- a/std/fs/ensure_file.ts
+++ b/std/fs/ensure_file.ts
@@ -2,7 +2,6 @@
import * as path from "../path/mod.ts";
import { ensureDir, ensureDirSync } from "./ensure_dir.ts";
import { getFileInfoType } from "./_util.ts";
-const { lstat, lstatSync, writeFile, writeFileSync } = Deno;
/**
* Ensures that the file exists.
@@ -15,7 +14,7 @@ const { lstat, lstatSync, writeFile, writeFileSync } = Deno;
export async function ensureFile(filePath: string): Promise<void> {
try {
// if file exists
- const stat = await lstat(filePath);
+ const stat = await Deno.lstat(filePath);
if (!stat.isFile) {
throw new Error(
`Ensure path exists, expected 'file', got '${getFileInfoType(stat)}'`
@@ -27,7 +26,7 @@ export async function ensureFile(filePath: string): Promise<void> {
// ensure dir exists
await ensureDir(path.dirname(filePath));
// create file
- await writeFile(filePath, new Uint8Array());
+ await Deno.writeFile(filePath, new Uint8Array());
return;
}
@@ -46,7 +45,7 @@ export async function ensureFile(filePath: string): Promise<void> {
export function ensureFileSync(filePath: string): void {
try {
// if file exists
- const stat = lstatSync(filePath);
+ const stat = Deno.lstatSync(filePath);
if (!stat.isFile) {
throw new Error(
`Ensure path exists, expected 'file', got '${getFileInfoType(stat)}'`
@@ -58,7 +57,7 @@ export function ensureFileSync(filePath: string): void {
// ensure dir exists
ensureDirSync(path.dirname(filePath));
// create file
- writeFileSync(filePath, new Uint8Array());
+ Deno.writeFileSync(filePath, new Uint8Array());
return;
}
throw err;
diff --git a/std/fs/exists.ts b/std/fs/exists.ts
index f9e5a0925..a79455b2d 100644
--- a/std/fs/exists.ts
+++ b/std/fs/exists.ts
@@ -1,11 +1,10 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-const { lstat, lstatSync } = Deno;
/**
* Test whether or not the given path exists by checking with the file system
*/
export async function exists(filePath: string): Promise<boolean> {
try {
- await lstat(filePath);
+ await Deno.lstat(filePath);
return true;
} catch (err) {
if (err instanceof Deno.errors.NotFound) {
@@ -21,7 +20,7 @@ export async function exists(filePath: string): Promise<boolean> {
*/
export function existsSync(filePath: string): boolean {
try {
- lstatSync(filePath);
+ Deno.lstatSync(filePath);
return true;
} catch (err) {
if (err instanceof Deno.errors.NotFound) {
diff --git a/std/fs/expand_glob.ts b/std/fs/expand_glob.ts
index 4b7b11885..949f58f92 100644
--- a/std/fs/expand_glob.ts
+++ b/std/fs/expand_glob.ts
@@ -15,8 +15,6 @@ import {
walkSync,
} from "./walk.ts";
import { assert } from "../_util/assert.ts";
-const { cwd } = Deno;
-type FileInfo = Deno.FileInfo;
const isWindows = Deno.build.os == "windows";
@@ -68,7 +66,7 @@ function comparePath(a: WalkEntry, b: WalkEntry): number {
export async function* expandGlob(
glob: string,
{
- root = cwd(),
+ root = Deno.cwd(),
exclude = [],
includeDirs = true,
extended = false,
@@ -78,7 +76,7 @@ export async function* expandGlob(
const globOptions: GlobOptions = { extended, globstar };
const absRoot = isAbsolute(root)
? normalize(root)
- : joinGlobs([cwd(), root], globOptions);
+ : joinGlobs([Deno.cwd(), root], globOptions);
const resolveFromRoot = (path: string): string =>
isAbsolute(path)
? normalize(path)
@@ -167,7 +165,7 @@ export async function* expandGlob(
export function* expandGlobSync(
glob: string,
{
- root = cwd(),
+ root = Deno.cwd(),
exclude = [],
includeDirs = true,
extended = false,
@@ -177,7 +175,7 @@ export function* expandGlobSync(
const globOptions: GlobOptions = { extended, globstar };
const absRoot = isAbsolute(root)
? normalize(root)
- : joinGlobs([cwd(), root], globOptions);
+ : joinGlobs([Deno.cwd(), root], globOptions);
const resolveFromRoot = (path: string): string =>
isAbsolute(path)
? normalize(path)
diff --git a/std/fs/expand_glob_test.ts b/std/fs/expand_glob_test.ts
index 7d60d024e..1eec4df42 100644
--- a/std/fs/expand_glob_test.ts
+++ b/std/fs/expand_glob_test.ts
@@ -1,4 +1,3 @@
-const { cwd, execPath, run } = Deno;
import { decode } from "../encoding/utf8.ts";
import {
assert,
@@ -32,7 +31,7 @@ async function expandGlobArray(
);
pathsSync.sort();
assertEquals(paths, pathsSync);
- const root = normalize(options.root || cwd());
+ const root = normalize(options.root || Deno.cwd());
for (const path of paths) {
assert(path.startsWith(root));
}
@@ -118,8 +117,8 @@ Deno.test("expandGlobIncludeDirs", async function (): Promise<void> {
Deno.test("expandGlobPermError", async function (): Promise<void> {
const exampleUrl = new URL("testdata/expand_wildcard.js", import.meta.url);
- const p = run({
- cmd: [execPath(), "run", "--unstable", exampleUrl.toString()],
+ const p = Deno.run({
+ cmd: [Deno.execPath(), "run", "--unstable", exampleUrl.toString()],
stdin: "null",
stdout: "piped",
stderr: "piped",
diff --git a/std/fs/walk.ts b/std/fs/walk.ts
index 553e52b2e..0292b77ef 100644
--- a/std/fs/walk.ts
+++ b/std/fs/walk.ts
@@ -3,12 +3,11 @@
// Copyright 2009 The Go Authors. All rights reserved. BSD license.
import { assert } from "../_util/assert.ts";
import { basename, join, normalize } from "../path/mod.ts";
-const { readDir, readDirSync, stat, statSync } = Deno;
export function createWalkEntrySync(path: string): WalkEntry {
path = normalize(path);
const name = basename(path);
- const info = statSync(path);
+ const info = Deno.statSync(path);
return {
path,
name,
@@ -21,7 +20,7 @@ export function createWalkEntrySync(path: string): WalkEntry {
export async function createWalkEntry(path: string): Promise<WalkEntry> {
path = normalize(path);
const name = basename(path);
- const info = await stat(path);
+ const info = await Deno.stat(path);
return {
path,
name,
@@ -103,7 +102,7 @@ export async function* walk(
if (maxDepth < 1 || !include(root, undefined, undefined, skip)) {
return;
}
- for await (const entry of readDir(root)) {
+ for await (const entry of Deno.readDir(root)) {
if (entry.isSymlink) {
if (followSymlinks) {
// TODO(ry) Re-enable followSymlinks.
@@ -156,7 +155,7 @@ export function* walkSync(
if (maxDepth < 1 || !include(root, undefined, undefined, skip)) {
return;
}
- for (const entry of readDirSync(root)) {
+ for (const entry of Deno.readDirSync(root)) {
if (entry.isSymlink) {
if (followSymlinks) {
throw new Error("unimplemented");
diff --git a/std/fs/walk_test.ts b/std/fs/walk_test.ts
index 8bd4577b9..e992aebcf 100644
--- a/std/fs/walk_test.ts
+++ b/std/fs/walk_test.ts
@@ -1,5 +1,3 @@
-const { cwd, chdir, makeTempDir, mkdir, create, symlink } = Deno;
-const { remove } = Deno;
import { walk, walkSync, WalkOptions, WalkEntry } from "./walk.ts";
import { assert, assertEquals, assertThrowsAsync } from "../testing/asserts.ts";
@@ -10,15 +8,15 @@ export function testWalk(
): void {
const name = t.name;
async function fn(): Promise<void> {
- const origCwd = cwd();
- const d = await makeTempDir();
- chdir(d);
+ const origCwd = Deno.cwd();
+ const d = await Deno.makeTempDir();
+ Deno.chdir(d);
try {
await setup(d);
await t();
} finally {
- chdir(origCwd);
- await remove(d, { recursive: true });
+ Deno.chdir(origCwd);
+ await Deno.remove(d, { recursive: true });
}
}
Deno.test({ ignore, name: `[walk] ${name}`, fn });
@@ -44,7 +42,7 @@ export async function walkArray(
}
export async function touch(path: string): Promise<void> {
- const f = await create(path);
+ const f = await Deno.create(path);
f.close();
}
@@ -56,7 +54,7 @@ function assertReady(expectedLength: number): void {
testWalk(
async (d: string): Promise<void> => {
- await mkdir(d + "/empty");
+ await Deno.mkdir(d + "/empty");
},
async function emptyDir(): Promise<void> {
const arr = await walkArray(".");
@@ -93,7 +91,7 @@ testWalk(
testWalk(
async (d: string): Promise<void> => {
- await mkdir(d + "/a");
+ await Deno.mkdir(d + "/a");
await touch(d + "/a/x");
},
async function nestedSingleFile(): Promise<void> {
@@ -104,7 +102,7 @@ testWalk(
testWalk(
async (d: string): Promise<void> => {
- await mkdir(d + "/a/b/c/d", { recursive: true });
+ await Deno.mkdir(d + "/a/b/c/d", { recursive: true });
await touch(d + "/a/b/c/d/x");
},
async function depth(): Promise<void> {
@@ -119,7 +117,7 @@ testWalk(
testWalk(
async (d: string): Promise<void> => {
await touch(d + "/a");
- await mkdir(d + "/b");
+ await Deno.mkdir(d + "/b");
await touch(d + "/b/c");
},
async function includeDirs(): Promise<void> {
@@ -132,7 +130,7 @@ testWalk(
testWalk(
async (d: string): Promise<void> => {
await touch(d + "/a");
- await mkdir(d + "/b");
+ await Deno.mkdir(d + "/b");
await touch(d + "/b/c");
},
async function includeFiles(): Promise<void> {
@@ -219,8 +217,8 @@ testWalk(
testWalk(
async (d: string): Promise<void> => {
- await mkdir(d + "/a");
- await mkdir(d + "/b");
+ await Deno.mkdir(d + "/a");
+ await Deno.mkdir(d + "/b");
await touch(d + "/a/x");
await touch(d + "/a/y");
await touch(d + "/b/z");
@@ -244,13 +242,13 @@ testWalk(
// TODO(ry) Re-enable followSymlinks
testWalk(
async (d: string): Promise<void> => {
- await mkdir(d + "/a");
- await mkdir(d + "/b");
+ await Deno.mkdir(d + "/a");
+ await Deno.mkdir(d + "/b");
await touch(d + "/a/x");
await touch(d + "/a/y");
await touch(d + "/b/z");
try {
- await symlink(d + "/b", d + "/a/bb");
+ await Deno.symlink(d + "/b", d + "/a/bb");
} catch (err) {
assert(Deno.build.os == "windows");
assertEquals(err.message, "Not implemented");
diff --git a/std/hash/_fnv/util_test.ts b/std/hash/_fnv/util_test.ts
index 3b16d83cb..5e31a98bd 100644
--- a/std/hash/_fnv/util_test.ts
+++ b/std/hash/_fnv/util_test.ts
@@ -1,10 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
-const { test } = Deno;
import { assertEquals } from "../../testing/asserts.ts";
import { mul32, mul64 } from "./util.ts";
-test("[hash/fnv/util] mul32", () => {
+Deno.test("[hash/fnv/util] mul32", () => {
assertEquals(mul32(0xffffffff, 0xffffffff), 1);
assertEquals(mul32(0x12345678, 0xdeadbeef), 0x5621ca08);
assertEquals(mul32(0xf626f430, 0xff7469f1), 0x2a939130);
@@ -19,7 +17,7 @@ test("[hash/fnv/util] mul32", () => {
assertEquals(mul32(0xc60898cc, 0xbfe7dcc4), 0x15f84c30);
});
-test("[hash/fnv/util] mul64", () => {
+Deno.test("[hash/fnv/util] mul64", () => {
assertEquals(mul64([0xffffffff, 0xffffffff], [0xffffffff, 0xffffffff]), [
0,
1,
diff --git a/std/hash/fnv_test.ts b/std/hash/fnv_test.ts
index 6c2d66f9a..20209703a 100644
--- a/std/hash/fnv_test.ts
+++ b/std/hash/fnv_test.ts
@@ -3,8 +3,6 @@
// Copyright 2011 The Go Authors. All rights reserved. BSD license.
// https://github.com/golang/go/blob/master/LICENSE
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
-const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts";
import { Fnv32, Fnv32a, Fnv64, Fnv64a } from "./fnv.ts";
@@ -40,7 +38,7 @@ const golden64a = [
["deno", [0xa5, 0xd9, 0xfb, 0x67, 0x42, 0x6e, 0x48, 0xb1]],
];
-test("[hash/fnv] testFnv32", () => {
+Deno.test("[hash/fnv] testFnv32", () => {
for (const [input, output] of golden32) {
const fnv = new Fnv32();
fnv.write(new TextEncoder().encode(input as string));
@@ -48,7 +46,7 @@ test("[hash/fnv] testFnv32", () => {
}
});
-test("[hash/fnv] testFnv32a", () => {
+Deno.test("[hash/fnv] testFnv32a", () => {
for (const [input, output] of golden32a) {
const fnv = new Fnv32a();
fnv.write(new TextEncoder().encode(input as string));
@@ -56,7 +54,7 @@ test("[hash/fnv] testFnv32a", () => {
}
});
-test("[hash/fnv] testFnv64", () => {
+Deno.test("[hash/fnv] testFnv64", () => {
for (const [input, output] of golden64) {
const fnv = new Fnv64();
fnv.write(new TextEncoder().encode(input as string));
@@ -64,7 +62,7 @@ test("[hash/fnv] testFnv64", () => {
}
});
-test("[hash/fnv] testFnv64a", () => {
+Deno.test("[hash/fnv] testFnv64a", () => {
for (const [input, output] of golden64a) {
const fnv = new Fnv64a();
fnv.write(new TextEncoder().encode(input as string));
@@ -72,7 +70,7 @@ test("[hash/fnv] testFnv64a", () => {
}
});
-test("[hash/fnv] testFnv32WriteChain", () => {
+Deno.test("[hash/fnv] testFnv32WriteChain", () => {
const fnv = new Fnv32();
fnv
.write(new TextEncoder().encode("d"))
@@ -82,7 +80,7 @@ test("[hash/fnv] testFnv32WriteChain", () => {
assertEquals(fnv.sum(), [0x6e, 0xd5, 0xa7, 0xa9]);
});
-test("[hash/fnv] testFnv32aWriteChain", () => {
+Deno.test("[hash/fnv] testFnv32aWriteChain", () => {
const fnv = new Fnv32a();
fnv
.write(new TextEncoder().encode("d"))
@@ -92,7 +90,7 @@ test("[hash/fnv] testFnv32aWriteChain", () => {
assertEquals(fnv.sum(), [0x8e, 0xf6, 0x47, 0x11]);
});
-test("[hash/fnv] testFnv64WriteChain", () => {
+Deno.test("[hash/fnv] testFnv64WriteChain", () => {
const fnv = new Fnv64();
fnv
.write(new TextEncoder().encode("d"))
@@ -102,7 +100,7 @@ test("[hash/fnv] testFnv64WriteChain", () => {
assertEquals(fnv.sum(), [0x14, 0xed, 0xb2, 0x7e, 0xec, 0xda, 0xad, 0xc9]);
});
-test("[hash/fnv] testFnv64aWriteChain", () => {
+Deno.test("[hash/fnv] testFnv64aWriteChain", () => {
const fnv = new Fnv64a();
fnv
.write(new TextEncoder().encode("d"))
diff --git a/std/hash/md5_test.ts b/std/hash/md5_test.ts
index 050c5ae91..89bd249ab 100644
--- a/std/hash/md5_test.ts
+++ b/std/hash/md5_test.ts
@@ -1,6 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
-const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts";
import { Md5 } from "./md5.ts";
@@ -41,14 +39,14 @@ const testSetBase64 = [
[millionAs, "dwfWrk4CfHDuoqk1wilvIQ=="],
];
-test("[hash/md5] testMd5Hex", () => {
+Deno.test("[hash/md5] testMd5Hex", () => {
for (const [input, output] of testSetHex) {
const md5 = new Md5();
assertEquals(md5.update(input).toString(), output);
}
});
-test("[hash/md5] testMd5Base64", () => {
+Deno.test("[hash/md5] testMd5Base64", () => {
for (const [input, output] of testSetBase64) {
const md5 = new Md5();
assertEquals(md5.update(input).toString("base64"), output);
diff --git a/std/hash/sha1_test.ts b/std/hash/sha1_test.ts
index 36702d55a..2c78bb1c8 100644
--- a/std/hash/sha1_test.ts
+++ b/std/hash/sha1_test.ts
@@ -1,5 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts";
import { Sha1, Message } from "./sha1.ts";
import { join, resolve } from "../path/mod.ts";
@@ -70,7 +69,7 @@ for (const method of methods) {
for (const [name, tests] of Object.entries(fixtures.sha1)) {
let i = 1;
for (const [expected, message] of Object.entries(tests)) {
- test({
+ Deno.test({
name: `sha1.${method}() - ${name} - #${i++}`,
fn() {
const algorithm = new Sha1();
@@ -90,7 +89,7 @@ for (const method of methods) {
for (const [name, tests] of Object.entries(fixtures.sha1)) {
let i = 1;
for (const [expected, message] of Object.entries(tests)) {
- test({
+ Deno.test({
name: `sha1.${method}() - ${name} - #${i++}`,
fn() {
const algorithm = new Sha1(true);
@@ -106,7 +105,7 @@ for (const method of methods) {
}
}
-test("[hash/sha1] test Uint8Array from Reader", async () => {
+Deno.test("[hash/sha1] test Uint8Array from Reader", async () => {
const data = await Deno.readFile(join(testdataDir, "hashtest"));
const hash = new Sha1().update(data).hex();
diff --git a/std/hash/sha256_test.ts b/std/hash/sha256_test.ts
index 68c67b5ee..3cf4cbdf2 100644
--- a/std/hash/sha256_test.ts
+++ b/std/hash/sha256_test.ts
@@ -3,8 +3,6 @@ import { Sha256, HmacSha256, Message } from "./sha256.ts";
import { assertEquals } from "../testing/asserts.ts";
import { join, resolve } from "../path/mod.ts";
-const { test } = Deno;
-
const testdataDir = resolve("hash", "testdata");
/** Handy function to convert an array/array buffer to a string of hex values. */
@@ -178,7 +176,7 @@ fixtures.sha256.ArrayBuffer = {
// deno-fmt-ignore
fixtures.sha224.Uint8Array = {
'e17541396a3ecd1cd5a2b968b84e597e8eae3b0ea3127963bf48dd3b': new Uint8Array([211, 212]),
- '730e109bd7a8a32b1cb9d9a09aa2325d2430587ddbc0c38bad911525': new Uint8Array([84, 104, 101, 32, 113, 117, 105, 99, 107, 32, 98, 114, 111, 119, 110, 32, 102, 111, 120, 32, 106, 117, 109, 112, 115, 32, 111, 118, 101, 114, 32, 116, 104, 101, 32, 108, 97, 122, 121, 32, 100, 111, 103])
+ '730e109bd7a8a32b1cb9d9a09aa2325d2430587ddbc0c38bad911525': new Uint8Array([84, 104, 101, 32, 113, 117, 105, 99, 107, 32, 98, 114, 111, 119, 110, 32, 102, 111, 120, 32, 106, 117, 109, 112, 115, 32, 111, 118, 101, 114, 32, 116, 104, 101, 32, 108, 97, 122, 121, 32, 100, 111, 103])
};
// prettier-ignore
// deno-fmt-ignore
@@ -222,7 +220,7 @@ for (const method of methods) {
for (const [name, tests] of Object.entries(fixtures.sha256)) {
let i = 1;
for (const [expected, message] of Object.entries(tests)) {
- test({
+ Deno.test({
name: `sha256.${method}() - ${name} - #${i++}`,
fn() {
const algorithm = new Sha256();
@@ -242,7 +240,7 @@ for (const method of methods) {
for (const [name, tests] of Object.entries(fixtures.sha224)) {
let i = 1;
for (const [expected, message] of Object.entries(tests)) {
- test({
+ Deno.test({
name: `sha224.${method}() - ${name} - #${i++}`,
fn() {
const algorithm = new Sha256(true);
@@ -262,7 +260,7 @@ for (const method of methods) {
for (const [name, tests] of Object.entries(fixtures.sha256Hmac)) {
let i = 1;
for (const [expected, [key, message]] of Object.entries(tests)) {
- test({
+ Deno.test({
name: `hmacSha256.${method}() - ${name} - #${i++}`,
fn() {
const algorithm = new HmacSha256(key);
@@ -282,7 +280,7 @@ for (const method of methods) {
for (const [name, tests] of Object.entries(fixtures.sha224Hmac)) {
let i = 1;
for (const [expected, [key, message]] of Object.entries(tests)) {
- test({
+ Deno.test({
name: `hmacSha224.${method}() - ${name} - #${i++}`,
fn() {
const algorithm = new HmacSha256(key, true);
@@ -298,7 +296,7 @@ for (const method of methods) {
}
}
-test("[hash/sha256] test Uint8Array from Reader", async () => {
+Deno.test("[hash/sha256] test Uint8Array from Reader", async () => {
const data = await Deno.readFile(join(testdataDir, "hashtest"));
const hash = new Sha256().update(data).hex();
diff --git a/std/hash/sha3_test.ts b/std/hash/sha3_test.ts
index 6812f6209..64e426385 100644
--- a/std/hash/sha3_test.ts
+++ b/std/hash/sha3_test.ts
@@ -1,8 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
/* eslint-disable @typescript-eslint/camelcase */
-
-const { test } = Deno;
import { assertEquals, assertThrows } from "../testing/asserts.ts";
import {
Keccak224,
@@ -262,7 +259,7 @@ function s2b(data: string): Uint8Array {
return new TextEncoder().encode(data);
}
-test("[hash/sha3] testSha3-224Raw", () => {
+Deno.test("[hash/sha3] testSha3-224Raw", () => {
const sha3sum = (data: ArrayBuffer): ArrayBuffer => {
const sha3 = new Sha3_224();
return sha3.update(data).digest();
@@ -274,7 +271,7 @@ test("[hash/sha3] testSha3-224Raw", () => {
}
});
-test("[hash/sha3] testSha3-224String", () => {
+Deno.test("[hash/sha3] testSha3-224String", () => {
const sha3sum = (data: string): string => {
const sha3 = new Sha3_224();
return sha3.update(data).toString();
@@ -285,7 +282,7 @@ test("[hash/sha3] testSha3-224String", () => {
}
});
-test("[hash/sha3] testSha3-256Raw", () => {
+Deno.test("[hash/sha3] testSha3-256Raw", () => {
const sha3sum = (data: ArrayBuffer): ArrayBuffer => {
const sha3 = new Sha3_256();
return sha3.update(data).digest();
@@ -297,7 +294,7 @@ test("[hash/sha3] testSha3-256Raw", () => {
}
});
-test("[hash/sha3] testSha3-256String", () => {
+Deno.test("[hash/sha3] testSha3-256String", () => {
const sha3sum = (data: string): string => {
const sha3 = new Sha3_256();
return sha3.update(data).toString();
@@ -308,7 +305,7 @@ test("[hash/sha3] testSha3-256String", () => {
}
});
-test("[hash/sha3] testSha3-384Raw", () => {
+Deno.test("[hash/sha3] testSha3-384Raw", () => {
const sha3sum = (data: ArrayBuffer): ArrayBuffer => {
const sha3 = new Sha3_384();
return sha3.update(data).digest();
@@ -320,7 +317,7 @@ test("[hash/sha3] testSha3-384Raw", () => {
}
});
-test("[hash/sha3] testSha3-384String", () => {
+Deno.test("[hash/sha3] testSha3-384String", () => {
const sha3sum = (data: string): string => {
const sha3 = new Sha3_384();
return sha3.update(data).toString();
@@ -331,7 +328,7 @@ test("[hash/sha3] testSha3-384String", () => {
}
});
-test("[hash/sha3] testSha3-512Raw", () => {
+Deno.test("[hash/sha3] testSha3-512Raw", () => {
const sha3sum = (data: ArrayBuffer): ArrayBuffer => {
const sha3 = new Sha3_512();
return sha3.update(data).digest();
@@ -343,7 +340,7 @@ test("[hash/sha3] testSha3-512Raw", () => {
}
});
-test("[hash/sha3] testSha3-512String", () => {
+Deno.test("[hash/sha3] testSha3-512String", () => {
const sha3sum = (data: string): string => {
const sha3 = new Sha3_512();
return sha3.update(data).toString();
@@ -354,7 +351,7 @@ test("[hash/sha3] testSha3-512String", () => {
}
});
-test("[hash/sha3] testKeccak-224Raw", () => {
+Deno.test("[hash/sha3] testKeccak-224Raw", () => {
const keccakSum = (data: ArrayBuffer): ArrayBuffer => {
const keccak = new Keccak224();
return keccak.update(data).digest();
@@ -366,7 +363,7 @@ test("[hash/sha3] testKeccak-224Raw", () => {
}
});
-test("[hash/sha3] testKeccak-224String", () => {
+Deno.test("[hash/sha3] testKeccak-224String", () => {
const keccakSum = (data: string): string => {
const keccak = new Keccak224();
return keccak.update(data).toString();
@@ -377,7 +374,7 @@ test("[hash/sha3] testKeccak-224String", () => {
}
});
-test("[hash/sha3] testKeccak-256Raw", () => {
+Deno.test("[hash/sha3] testKeccak-256Raw", () => {
const keccakSum = (data: ArrayBuffer): ArrayBuffer => {
const keccak = new Keccak256();
return keccak.update(data).digest();
@@ -389,7 +386,7 @@ test("[hash/sha3] testKeccak-256Raw", () => {
}
});
-test("[hash/sha3] testKeccak-256String", () => {
+Deno.test("[hash/sha3] testKeccak-256String", () => {
const keccakSum = (data: string): string => {
const keccak = new Keccak256();
return keccak.update(data).toString();
@@ -400,7 +397,7 @@ test("[hash/sha3] testKeccak-256String", () => {
}
});
-test("[hash/sha3] testKeccak-384Raw", () => {
+Deno.test("[hash/sha3] testKeccak-384Raw", () => {
const keccakSum = (data: ArrayBuffer): ArrayBuffer => {
const keccak = new Keccak384();
return keccak.update(data).digest();
@@ -412,7 +409,7 @@ test("[hash/sha3] testKeccak-384Raw", () => {
}
});
-test("[hash/sha3] testKeccak-384String", () => {
+Deno.test("[hash/sha3] testKeccak-384String", () => {
const keccakSum = (data: string): string => {
const keccak = new Keccak384();
return keccak.update(data).toString();
@@ -423,7 +420,7 @@ test("[hash/sha3] testKeccak-384String", () => {
}
});
-test("[hash/sha3] testKeccak-512Raw", () => {
+Deno.test("[hash/sha3] testKeccak-512Raw", () => {
const keccakSum = (data: ArrayBuffer): ArrayBuffer => {
const keccak = new Keccak512();
return keccak.update(data).digest();
@@ -435,7 +432,7 @@ test("[hash/sha3] testKeccak-512Raw", () => {
}
});
-test("[hash/sha3] testKeccak-512String", () => {
+Deno.test("[hash/sha3] testKeccak-512String", () => {
const keccakSum = (data: string): string => {
const keccak = new Keccak512();
return keccak.update(data).toString();
@@ -446,7 +443,7 @@ test("[hash/sha3] testKeccak-512String", () => {
}
});
-test("[hash/sha3] testSHAKE-128Raw", () => {
+Deno.test("[hash/sha3] testSHAKE-128Raw", () => {
const shakeSum = (data: ArrayBuffer): ArrayBuffer => {
const shake = new Shake128(128);
return shake.update(data).digest();
@@ -458,7 +455,7 @@ test("[hash/sha3] testSHAKE-128Raw", () => {
}
});
-test("[hash/sha3] testSHAKE-128String", () => {
+Deno.test("[hash/sha3] testSHAKE-128String", () => {
const shakeSum = (data: string): string => {
const shake = new Shake128(128);
return shake.update(data).toString();
@@ -469,7 +466,7 @@ test("[hash/sha3] testSHAKE-128String", () => {
}
});
-test("[hash/sha3] testSHAKE-128-224Raw", () => {
+Deno.test("[hash/sha3] testSHAKE-128-224Raw", () => {
const shakeSum = (data: ArrayBuffer): ArrayBuffer => {
const shake = new Shake128(224);
return shake.update(data).digest();
@@ -481,7 +478,7 @@ test("[hash/sha3] testSHAKE-128-224Raw", () => {
}
});
-test("[hash/sha3] testSHAKE-128-224String", () => {
+Deno.test("[hash/sha3] testSHAKE-128-224String", () => {
const shakeSum = (data: string): string => {
const shake = new Shake128(224);
return shake.update(data).toString();
@@ -492,7 +489,7 @@ test("[hash/sha3] testSHAKE-128-224String", () => {
}
});
-test("[hash/sha3] testSHAKE-128-2048", () => {
+Deno.test("[hash/sha3] testSHAKE-128-2048", () => {
const shakeSum = (data: string): string => {
const shake = new Shake128(2048);
return shake.update(data).toString();
@@ -503,7 +500,7 @@ test("[hash/sha3] testSHAKE-128-2048", () => {
}
});
-test("[hash/sha3] testSHAKE-256", () => {
+Deno.test("[hash/sha3] testSHAKE-256", () => {
const shakeSum = (data: string): string => {
const shake = new Shake256(256);
return shake.update(data).toString();
@@ -514,7 +511,7 @@ test("[hash/sha3] testSHAKE-256", () => {
}
});
-test("[hash/sha3] testSHAKE-256-128", () => {
+Deno.test("[hash/sha3] testSHAKE-256-128", () => {
const shakeSum = (data: string): string => {
const shake = new Shake256(128);
return shake.update(data).toString();
@@ -525,7 +522,7 @@ test("[hash/sha3] testSHAKE-256-128", () => {
}
});
-test("[hash/sha3] testSHAKE-256-384", () => {
+Deno.test("[hash/sha3] testSHAKE-256-384", () => {
const shakeSum = (data: string): string => {
const shake = new Shake256(384);
return shake.update(data).toString();
@@ -536,7 +533,7 @@ test("[hash/sha3] testSHAKE-256-384", () => {
}
});
-test("[hash/sha3] testSHAKE-256-512", () => {
+Deno.test("[hash/sha3] testSHAKE-256-512", () => {
const shakeSum = (data: string): string => {
const shake = new Shake256(512);
return shake.update(data).toString();
@@ -547,7 +544,7 @@ test("[hash/sha3] testSHAKE-256-512", () => {
}
});
-test("[hash/sha3] testSha3-256Chain", () => {
+Deno.test("[hash/sha3] testSha3-256Chain", () => {
const sha3 = new Sha3_256();
const output = sha3
.update(s2b("a"))
@@ -561,7 +558,7 @@ test("[hash/sha3] testSha3-256Chain", () => {
);
});
-test("[hash/sha3] testSha3UpdateFinalized", () => {
+Deno.test("[hash/sha3] testSha3UpdateFinalized", () => {
assertThrows(
() => {
const sha3 = new Sha3_256();
diff --git a/std/hash/sha512_test.ts b/std/hash/sha512_test.ts
index d17df3230..c656731a3 100644
--- a/std/hash/sha512_test.ts
+++ b/std/hash/sha512_test.ts
@@ -3,8 +3,6 @@ import { Sha512, HmacSha512, Message } from "./sha512.ts";
import { assertEquals } from "../testing/asserts.ts";
import { join, resolve } from "../path/mod.ts";
-const { test } = Deno;
-
const testdataDir = resolve("hash", "testdata");
/** Handy function to convert an array/array buffer to a string of hex values. */
@@ -282,7 +280,7 @@ for (const method of methods) {
for (const [name, tests] of Object.entries(fixtures.sha512bits224)) {
let i = 1;
for (const [expected, message] of Object.entries(tests)) {
- test({
+ Deno.test({
name: `sha512/224.${method}() - ${name} - #${i++}`,
fn() {
const algorithm = new Sha512(224);
@@ -302,7 +300,7 @@ for (const method of methods) {
for (const [name, tests] of Object.entries(fixtures.sha512bits256)) {
let i = 1;
for (const [expected, message] of Object.entries(tests)) {
- test({
+ Deno.test({
name: `sha512/256.${method}() - ${name} - #${i++}`,
fn() {
const algorithm = new Sha512(256);
@@ -322,7 +320,7 @@ for (const method of methods) {
for (const [name, tests] of Object.entries(fixtures.sha512)) {
let i = 1;
for (const [expected, message] of Object.entries(tests)) {
- test({
+ Deno.test({
name: `sha512.${method}() - ${name} - #${i++}`,
fn() {
const algorithm = new Sha512();
@@ -342,7 +340,7 @@ for (const method of methods) {
for (const [name, tests] of Object.entries(fixtures.hmacSha512bits224)) {
let i = 1;
for (const [expected, [key, message]] of Object.entries(tests)) {
- test({
+ Deno.test({
name: `hmacSha512/224.${method}() - ${name} - #${i++}`,
fn() {
const algorithm = new HmacSha512(key, 224);
@@ -362,7 +360,7 @@ for (const method of methods) {
for (const [name, tests] of Object.entries(fixtures.hmacSha512bits256)) {
let i = 1;
for (const [expected, [key, message]] of Object.entries(tests)) {
- test({
+ Deno.test({
name: `hmacSha512/256.${method}() - ${name} - #${i++}`,
fn() {
const algorithm = new HmacSha512(key, 256);
@@ -382,7 +380,7 @@ for (const method of methods) {
for (const [name, tests] of Object.entries(fixtures.hmacSha512)) {
let i = 1;
for (const [expected, [key, message]] of Object.entries(tests)) {
- test({
+ Deno.test({
name: `hmacSha512.${method}() - ${name} - #${i++}`,
fn() {
const algorithm = new HmacSha512(key);
@@ -398,7 +396,7 @@ for (const method of methods) {
}
}
-test("[hash/sha512] test Uint8Array from Reader", async () => {
+Deno.test("[hash/sha512] test Uint8Array from Reader", async () => {
const data = await Deno.readFile(join(testdataDir, "hashtest"));
const hash = new Sha512().update(data).hex();
assertEquals(
diff --git a/std/http/_io_test.ts b/std/http/_io_test.ts
index 3b385d013..473c40637 100644
--- a/std/http/_io_test.ts
+++ b/std/http/_io_test.ts
@@ -18,11 +18,13 @@ import { BufReader, ReadLineResult } from "../io/bufio.ts";
import { ServerRequest, Response } from "./server.ts";
import { StringReader } from "../io/readers.ts";
import { mockConn } from "./_mock_conn.ts";
-const { Buffer, test, readAll } = Deno;
-test("bodyReader", async () => {
+Deno.test("bodyReader", async () => {
const text = "Hello, Deno";
- const r = bodyReader(text.length, new BufReader(new Buffer(encode(text))));
+ const r = bodyReader(
+ text.length,
+ new BufReader(new Deno.Buffer(encode(text)))
+ );
assertEquals(decode(await Deno.readAll(r)), text);
});
function chunkify(n: number, char: string): string {
@@ -31,7 +33,7 @@ function chunkify(n: number, char: string): string {
.join("");
return `${n.toString(16)}\r\n${v}\r\n`;
}
-test("chunkedBodyReader", async () => {
+Deno.test("chunkedBodyReader", async () => {
const body = [
chunkify(3, "a"),
chunkify(5, "b"),
@@ -40,11 +42,11 @@ test("chunkedBodyReader", async () => {
chunkify(0, ""),
].join("");
const h = new Headers();
- const r = chunkedBodyReader(h, new BufReader(new Buffer(encode(body))));
+ const r = chunkedBodyReader(h, new BufReader(new Deno.Buffer(encode(body))));
let result: number | null;
// Use small buffer as some chunks exceed buffer size
const buf = new Uint8Array(5);
- const dest = new Buffer();
+ const dest = new Deno.Buffer();
while ((result = await r.read(buf)) !== null) {
const len = Math.min(buf.byteLength, result);
await dest.write(buf.subarray(0, len));
@@ -53,7 +55,7 @@ test("chunkedBodyReader", async () => {
assertEquals(new TextDecoder().decode(dest.bytes()), exp);
});
-test("chunkedBodyReader with trailers", async () => {
+Deno.test("chunkedBodyReader with trailers", async () => {
const body = [
chunkify(3, "a"),
chunkify(5, "b"),
@@ -67,7 +69,7 @@ test("chunkedBodyReader with trailers", async () => {
const h = new Headers({
trailer: "deno,node",
});
- const r = chunkedBodyReader(h, new BufReader(new Buffer(encode(body))));
+ const r = chunkedBodyReader(h, new BufReader(new Deno.Buffer(encode(body))));
assertEquals(h.has("trailer"), true);
assertEquals(h.has("deno"), false);
assertEquals(h.has("node"), false);
@@ -79,54 +81,63 @@ test("chunkedBodyReader with trailers", async () => {
assertEquals(h.get("node"), "js");
});
-test("readTrailers", async () => {
+Deno.test("readTrailers", async () => {
const h = new Headers({
trailer: "Deno, Node",
});
const trailer = ["deno: land", "node: js", "", ""].join("\r\n");
- await readTrailers(h, new BufReader(new Buffer(encode(trailer))));
+ await readTrailers(h, new BufReader(new Deno.Buffer(encode(trailer))));
assertEquals(h.has("trailer"), false);
assertEquals(h.get("deno"), "land");
assertEquals(h.get("node"), "js");
});
-test("readTrailer should throw if undeclared headers found in trailer", async () => {
- const patterns = [
- ["deno,node", "deno: land\r\nnode: js\r\ngo: lang\r\n\r\n"],
- ["deno", "node: js\r\n\r\n"],
- ["deno", "node:js\r\ngo: lang\r\n\r\n"],
- ];
- for (const [header, trailer] of patterns) {
- const h = new Headers({
- trailer: header,
- });
- await assertThrowsAsync(
- async () => {
- await readTrailers(h, new BufReader(new Buffer(encode(trailer))));
- },
- Deno.errors.InvalidData,
- `Undeclared trailers: [ "`
- );
+Deno.test(
+ "readTrailer should throw if undeclared headers found in trailer",
+ async () => {
+ const patterns = [
+ ["deno,node", "deno: land\r\nnode: js\r\ngo: lang\r\n\r\n"],
+ ["deno", "node: js\r\n\r\n"],
+ ["deno", "node:js\r\ngo: lang\r\n\r\n"],
+ ];
+ for (const [header, trailer] of patterns) {
+ const h = new Headers({
+ trailer: header,
+ });
+ await assertThrowsAsync(
+ async () => {
+ await readTrailers(
+ h,
+ new BufReader(new Deno.Buffer(encode(trailer)))
+ );
+ },
+ Deno.errors.InvalidData,
+ `Undeclared trailers: [ "`
+ );
+ }
}
-});
-
-test("readTrailer should throw if trailer contains prohibited fields", async () => {
- for (const f of ["Content-Length", "Trailer", "Transfer-Encoding"]) {
- const h = new Headers({
- trailer: f,
- });
- await assertThrowsAsync(
- async () => {
- await readTrailers(h, new BufReader(new Buffer()));
- },
- Deno.errors.InvalidData,
- `Prohibited trailer names: [ "`
- );
+);
+
+Deno.test(
+ "readTrailer should throw if trailer contains prohibited fields",
+ async () => {
+ for (const f of ["Content-Length", "Trailer", "Transfer-Encoding"]) {
+ const h = new Headers({
+ trailer: f,
+ });
+ await assertThrowsAsync(
+ async () => {
+ await readTrailers(h, new BufReader(new Deno.Buffer()));
+ },
+ Deno.errors.InvalidData,
+ `Prohibited trailer names: [ "`
+ );
+ }
}
-});
+);
-test("writeTrailer", async () => {
- const w = new Buffer();
+Deno.test("writeTrailer", async () => {
+ const w = new Deno.Buffer();
await writeTrailers(
w,
new Headers({ "transfer-encoding": "chunked", trailer: "deno,node" }),
@@ -138,8 +149,8 @@ test("writeTrailer", async () => {
);
});
-test("writeTrailer should throw", async () => {
- const w = new Buffer();
+Deno.test("writeTrailer should throw", async () => {
+ const w = new Deno.Buffer();
await assertThrowsAsync(
() => {
return writeTrailers(w, new Headers(), new Headers());
@@ -181,7 +192,7 @@ test("writeTrailer should throw", async () => {
});
// Ported from https://github.com/golang/go/blob/f5c43b9/src/net/http/request_test.go#L535-L565
-test("parseHttpVersion", (): void => {
+Deno.test("parseHttpVersion", (): void => {
const testCases = [
{ in: "HTTP/0.9", want: [0, 9] },
{ in: "HTTP/1.0", want: [1, 0] },
@@ -212,7 +223,7 @@ test("parseHttpVersion", (): void => {
}
});
-test("writeUint8ArrayResponse", async function (): Promise<void> {
+Deno.test("writeUint8ArrayResponse", async function (): Promise<void> {
const shortText = "Hello";
const body = new TextEncoder().encode(shortText);
@@ -248,7 +259,7 @@ test("writeUint8ArrayResponse", async function (): Promise<void> {
assertEquals(eof, null);
});
-test("writeStringResponse", async function (): Promise<void> {
+Deno.test("writeStringResponse", async function (): Promise<void> {
const body = "Hello";
const res: Response = { body };
@@ -283,7 +294,7 @@ test("writeStringResponse", async function (): Promise<void> {
assertEquals(eof, null);
});
-test("writeStringReaderResponse", async function (): Promise<void> {
+Deno.test("writeStringReaderResponse", async function (): Promise<void> {
const shortText = "Hello";
const body = new StringReader(shortText);
@@ -326,8 +337,8 @@ test("writeStringReaderResponse", async function (): Promise<void> {
assertEquals(r.more, false);
});
-test("writeResponse with trailer", async () => {
- const w = new Buffer();
+Deno.test("writeResponse with trailer", async () => {
+ const w = new Deno.Buffer();
const body = new StringReader("Hello");
await writeResponse(w, {
status: 200,
@@ -356,18 +367,18 @@ test("writeResponse with trailer", async () => {
assertEquals(ret, exp);
});
-test("writeResponseShouldNotModifyOriginHeaders", async () => {
+Deno.test("writeResponseShouldNotModifyOriginHeaders", async () => {
const headers = new Headers();
const buf = new Deno.Buffer();
await writeResponse(buf, { body: "foo", headers });
- assert(decode(await readAll(buf)).includes("content-length: 3"));
+ assert(decode(await Deno.readAll(buf)).includes("content-length: 3"));
await writeResponse(buf, { body: "hello", headers });
- assert(decode(await readAll(buf)).includes("content-length: 5"));
+ assert(decode(await Deno.readAll(buf)).includes("content-length: 5"));
});
-test("readRequestError", async function (): Promise<void> {
+Deno.test("readRequestError", async function (): Promise<void> {
const input = `GET / HTTP/1.1
malformedHeader
`;
@@ -385,7 +396,7 @@ malformedHeader
// Ported from Go
// https://github.com/golang/go/blob/go1.12.5/src/net/http/request_test.go#L377-L443
// TODO(zekth) fix tests
-test("testReadRequestError", async function (): Promise<void> {
+Deno.test("testReadRequestError", async function (): Promise<void> {
const testCases = [
{
in: "GET / HTTP/1.1\r\nheader: foo\r\n\r\n",
diff --git a/std/http/cookie_test.ts b/std/http/cookie_test.ts
index e221b3363..0b412d8e4 100644
--- a/std/http/cookie_test.ts
+++ b/std/http/cookie_test.ts
@@ -2,9 +2,8 @@
import { ServerRequest, Response } from "./server.ts";
import { getCookies, deleteCookie, setCookie } from "./cookie.ts";
import { assert, assertEquals } from "../testing/asserts.ts";
-const { test } = Deno;
-test({
+Deno.test({
name: "Cookie parser",
fn(): void {
const req = new ServerRequest();
@@ -32,7 +31,7 @@ test({
},
});
-test({
+Deno.test({
name: "Cookie Delete",
fn(): void {
const res: Response = {};
@@ -44,7 +43,7 @@ test({
},
});
-test({
+Deno.test({
name: "Cookie Set",
fn(): void {
const res: Response = {};
diff --git a/std/http/file_server.ts b/std/http/file_server.ts
index d9ed56236..8a14e95be 100755
--- a/std/http/file_server.ts
+++ b/std/http/file_server.ts
@@ -6,7 +6,6 @@
// TODO Add tests like these:
// https://github.com/indexzero/http-server/blob/master/test/http-server-test.js
-const { args, stat, readDir, open, exit } = Deno;
import { posix, extname } from "../path/mod.ts";
import { listenAndServe, ServerRequest, Response } from "./server.ts";
import { parse } from "../flags/mod.ts";
@@ -33,7 +32,7 @@ interface FileServerArgs {
const encoder = new TextEncoder();
-const serverArgs = parse(args) as FileServerArgs;
+const serverArgs = parse(Deno.args) as FileServerArgs;
const target = posix.resolve(serverArgs._[0] ?? "");
const MEDIA_TYPES: Record<string, string> = {
@@ -100,7 +99,10 @@ export async function serveFile(
req: ServerRequest,
filePath: string
): Promise<Response> {
- const [file, fileInfo] = await Promise.all([open(filePath), stat(filePath)]);
+ const [file, fileInfo] = await Promise.all([
+ Deno.open(filePath),
+ Deno.stat(filePath),
+ ]);
const headers = new Headers();
headers.set("content-length", fileInfo.size.toString());
const contentTypeValue = contentType(filePath);
@@ -124,7 +126,7 @@ async function serveDir(
): Promise<Response> {
const dirUrl = `/${posix.relative(target, dirPath)}`;
const listEntry: EntryInfo[] = [];
- for await (const entry of readDir(dirPath)) {
+ for await (const entry of Deno.readDir(dirPath)) {
const filePath = posix.join(dirPath, entry.name);
const fileUrl = posix.join(dirUrl, entry.name);
if (entry.name === "index.html" && entry.isFile) {
@@ -134,7 +136,7 @@ async function serveDir(
// Yuck!
let fileInfo = null;
try {
- fileInfo = await stat(filePath);
+ fileInfo = await Deno.stat(filePath);
} catch (e) {
// Pass
}
@@ -307,18 +309,18 @@ function main(): void {
if (serverArgs.h ?? serverArgs.help) {
console.log(`Deno File Server
Serves a local directory in HTTP.
-
+
INSTALL:
deno install --allow-net --allow-read https://deno.land/std/http/file_server.ts
-
+
USAGE:
file_server [path] [options]
-
+
OPTIONS:
-h, --help Prints help information
-p, --port <PORT> Set port
--cors Enable CORS via the "Access-Control-Allow-Origin" header`);
- exit();
+ Deno.exit();
}
listenAndServe(
@@ -336,7 +338,7 @@ function main(): void {
let response: Response | undefined;
try {
- const fileInfo = await stat(fsPath);
+ const fileInfo = await Deno.stat(fsPath);
if (fileInfo.isDirectory) {
response = await serveDir(req, fsPath);
} else {
diff --git a/std/http/file_server_test.ts b/std/http/file_server_test.ts
index ceea566fa..66c1d7d04 100644
--- a/std/http/file_server_test.ts
+++ b/std/http/file_server_test.ts
@@ -4,7 +4,6 @@ import { BufReader } from "../io/bufio.ts";
import { TextProtoReader } from "../textproto/mod.ts";
import { ServerRequest } from "./server.ts";
import { serveFile } from "./file_server.ts";
-const { test } = Deno;
let fileServer: Deno.Process<Deno.RunOptions & { stdout: "piped" }>;
type FileServerCfg = {
@@ -68,42 +67,48 @@ async function killFileServer(): Promise<void> {
fileServer.stdout!.close();
}
-test("file_server serveFile in ./", async (): Promise<void> => {
- await startFileServer();
- try {
- const res = await fetch("http://localhost:4507/README.md");
- assert(res.headers.has("access-control-allow-origin"));
- assert(res.headers.has("access-control-allow-headers"));
- assertEquals(res.headers.get("content-type"), "text/markdown");
- const downloadedFile = await res.text();
- const localFile = new TextDecoder().decode(
- await Deno.readFile("README.md")
- );
- assertEquals(downloadedFile, localFile);
- } finally {
- await killFileServer();
+Deno.test(
+ "file_server serveFile in ./",
+ async (): Promise<void> => {
+ await startFileServer();
+ try {
+ const res = await fetch("http://localhost:4507/README.md");
+ assert(res.headers.has("access-control-allow-origin"));
+ assert(res.headers.has("access-control-allow-headers"));
+ assertEquals(res.headers.get("content-type"), "text/markdown");
+ const downloadedFile = await res.text();
+ const localFile = new TextDecoder().decode(
+ await Deno.readFile("README.md")
+ );
+ assertEquals(downloadedFile, localFile);
+ } finally {
+ await killFileServer();
+ }
}
-});
+);
-test("file_server serveFile in ./http", async (): Promise<void> => {
- await startFileServer({ target: "./http" });
- try {
- const res = await fetch("http://localhost:4507/README.md");
- assert(res.headers.has("access-control-allow-origin"));
- assert(res.headers.has("access-control-allow-headers"));
- assertEquals(res.headers.get("content-type"), "text/markdown");
- const downloadedFile = await res.text();
- const localFile = new TextDecoder().decode(
- await Deno.readFile("./http/README.md")
- );
- console.log(downloadedFile, localFile);
- assertEquals(downloadedFile, localFile);
- } finally {
- await killFileServer();
+Deno.test(
+ "file_server serveFile in ./http",
+ async (): Promise<void> => {
+ await startFileServer({ target: "./http" });
+ try {
+ const res = await fetch("http://localhost:4507/README.md");
+ assert(res.headers.has("access-control-allow-origin"));
+ assert(res.headers.has("access-control-allow-headers"));
+ assertEquals(res.headers.get("content-type"), "text/markdown");
+ const downloadedFile = await res.text();
+ const localFile = new TextDecoder().decode(
+ await Deno.readFile("./http/README.md")
+ );
+ console.log(downloadedFile, localFile);
+ assertEquals(downloadedFile, localFile);
+ } finally {
+ await killFileServer();
+ }
}
-});
+);
-test("serveDirectory", async function (): Promise<void> {
+Deno.test("serveDirectory", async function (): Promise<void> {
await startFileServer();
try {
const res = await fetch("http://localhost:4507/");
@@ -125,7 +130,7 @@ test("serveDirectory", async function (): Promise<void> {
}
});
-test("serveFallback", async function (): Promise<void> {
+Deno.test("serveFallback", async function (): Promise<void> {
await startFileServer();
try {
const res = await fetch("http://localhost:4507/badfile.txt");
@@ -138,7 +143,7 @@ test("serveFallback", async function (): Promise<void> {
}
});
-test("serveWithUnorthodoxFilename", async function (): Promise<void> {
+Deno.test("serveWithUnorthodoxFilename", async function (): Promise<void> {
await startFileServer();
try {
let res = await fetch("http://localhost:4507/http/testdata/%");
@@ -156,7 +161,7 @@ test("serveWithUnorthodoxFilename", async function (): Promise<void> {
}
});
-test("printHelp", async function (): Promise<void> {
+Deno.test("printHelp", async function (): Promise<void> {
const helpProcess = Deno.run({
cmd: [
Deno.execPath(),
@@ -177,7 +182,7 @@ test("printHelp", async function (): Promise<void> {
helpProcess.stdout.close();
});
-test("contentType", async () => {
+Deno.test("contentType", async () => {
const request = new ServerRequest();
const response = await serveFile(request, "http/testdata/hello.html");
const contentType = response.headers!.get("content-type");
@@ -185,7 +190,7 @@ test("contentType", async () => {
(response.body as Deno.File).close();
});
-test("file_server running as library", async function (): Promise<void> {
+Deno.test("file_server running as library", async function (): Promise<void> {
await startFileServerAsLibrary();
try {
const res = await fetch("http://localhost:8000");
diff --git a/std/http/racing_server_test.ts b/std/http/racing_server_test.ts
index 054dfc385..7e510f13d 100644
--- a/std/http/racing_server_test.ts
+++ b/std/http/racing_server_test.ts
@@ -1,11 +1,10 @@
import { assert, assertEquals } from "../testing/asserts.ts";
import { BufReader, BufWriter } from "../io/bufio.ts";
import { TextProtoReader } from "../textproto/mod.ts";
-const { connect, run, test } = Deno;
let server: Deno.Process<Deno.RunOptions & { stdout: "piped" }>;
async function startServer(): Promise<void> {
- server = run({
+ server = Deno.run({
// TODO(lucacasonato): remove unstable when stabilized
cmd: [Deno.execPath(), "run", "--unstable", "-A", "http/racing_server.ts"],
stdout: "piped",
@@ -59,10 +58,10 @@ content-length: 6
Step7
`;
-test("serverPipelineRace", async function (): Promise<void> {
+Deno.test("serverPipelineRace", async function (): Promise<void> {
await startServer();
- const conn = await connect({ port: 4501 });
+ const conn = await Deno.connect({ port: 4501 });
const r = new TextProtoReader(new BufReader(conn));
const w = new BufWriter(conn);
await w.write(new TextEncoder().encode(input));
diff --git a/std/http/server.ts b/std/http/server.ts
index d2736cb43..effa7b4b9 100644
--- a/std/http/server.ts
+++ b/std/http/server.ts
@@ -10,10 +10,6 @@ import {
writeResponse,
readRequest,
} from "./_io.ts";
-import Listener = Deno.Listener;
-import Conn = Deno.Conn;
-import Reader = Deno.Reader;
-const { listen, listenTls } = Deno;
export class ServerRequest {
url!: string;
@@ -22,7 +18,7 @@ export class ServerRequest {
protoMinor!: number;
protoMajor!: number;
headers!: Headers;
- conn!: Conn;
+ conn!: Deno.Conn;
r!: BufReader;
w!: BufWriter;
done: Deferred<Error | undefined> = deferred();
@@ -119,9 +115,9 @@ export class ServerRequest {
export class Server implements AsyncIterable<ServerRequest> {
private closing = false;
- private connections: Conn[] = [];
+ private connections: Deno.Conn[] = [];
- constructor(public listener: Listener) {}
+ constructor(public listener: Deno.Listener) {}
close(): void {
this.closing = true;
@@ -140,7 +136,7 @@ export class Server implements AsyncIterable<ServerRequest> {
// Yields all HTTP requests on a single TCP connection.
private async *iterateHttpRequests(
- conn: Conn
+ conn: Deno.Conn
): AsyncIterableIterator<ServerRequest> {
const reader = new BufReader(conn);
const writer = new BufWriter(conn);
@@ -191,11 +187,11 @@ export class Server implements AsyncIterable<ServerRequest> {
}
}
- private trackConnection(conn: Conn): void {
+ private trackConnection(conn: Deno.Conn): void {
this.connections.push(conn);
}
- private untrackConnection(conn: Conn): void {
+ private untrackConnection(conn: Deno.Conn): void {
const index = this.connections.indexOf(conn);
if (index !== -1) {
this.connections.splice(index, 1);
@@ -211,7 +207,7 @@ export class Server implements AsyncIterable<ServerRequest> {
): AsyncIterableIterator<ServerRequest> {
if (this.closing) return;
// Wait for a new connection.
- let conn: Conn;
+ let conn: Deno.Conn;
try {
conn = await this.listener.accept();
} catch (error) {
@@ -257,7 +253,7 @@ export function serve(addr: string | HTTPOptions): Server {
addr = { hostname, port: Number(port) };
}
- const listener = listen(addr);
+ const listener = Deno.listen(addr);
return new Server(listener);
}
@@ -309,7 +305,7 @@ export function serveTLS(options: HTTPSOptions): Server {
...options,
transport: "tcp",
};
- const listener = listenTls(tlsOptions);
+ const listener = Deno.listenTls(tlsOptions);
return new Server(listener);
}
@@ -349,6 +345,6 @@ export async function listenAndServeTLS(
export interface Response {
status?: number;
headers?: Headers;
- body?: Uint8Array | Reader | string;
+ body?: Uint8Array | Deno.Reader | string;
trailers?: () => Promise<Headers> | Headers;
}
diff --git a/std/http/server_test.ts b/std/http/server_test.ts
index 2d911c450..340d9fa73 100644
--- a/std/http/server_test.ts
+++ b/std/http/server_test.ts
@@ -19,8 +19,6 @@ import { delay } from "../async/delay.ts";
import { encode, decode } from "../encoding/utf8.ts";
import { mockConn } from "./_mock_conn.ts";
-const { Buffer, test } = Deno;
-
interface ResponseTest {
response: Response;
raw: string;
@@ -43,7 +41,7 @@ const responseTests: ResponseTest[] = [
{
response: {
status: 200,
- body: new Buffer(new TextEncoder().encode("abcdef")),
+ body: new Deno.Buffer(new TextEncoder().encode("abcdef")),
},
raw:
@@ -53,9 +51,9 @@ const responseTests: ResponseTest[] = [
},
];
-test("responseWrite", async function (): Promise<void> {
+Deno.test("responseWrite", async function (): Promise<void> {
for (const testCase of responseTests) {
- const buf = new Buffer();
+ const buf = new Deno.Buffer();
const bufw = new BufWriter(buf);
const request = new ServerRequest();
request.w = bufw;
@@ -68,13 +66,13 @@ test("responseWrite", async function (): Promise<void> {
}
});
-test("requestContentLength", function (): void {
+Deno.test("requestContentLength", function (): void {
// Has content length
{
const req = new ServerRequest();
req.headers = new Headers();
req.headers.set("content-length", "5");
- const buf = new Buffer(encode("Hello"));
+ const buf = new Deno.Buffer(encode("Hello"));
req.r = new BufReader(buf);
assertEquals(req.contentLength, 5);
}
@@ -96,7 +94,7 @@ test("requestContentLength", function (): void {
chunkOffset += chunkSize;
}
chunksData += "0\r\n\r\n";
- const buf = new Buffer(encode(chunksData));
+ const buf = new Deno.Buffer(encode(chunksData));
req.r = new BufReader(buf);
assertEquals(req.contentLength, null);
}
@@ -121,12 +119,12 @@ function totalReader(r: Deno.Reader): TotalReader {
},
};
}
-test("requestBodyWithContentLength", async function (): Promise<void> {
+Deno.test("requestBodyWithContentLength", async function (): Promise<void> {
{
const req = new ServerRequest();
req.headers = new Headers();
req.headers.set("content-length", "5");
- const buf = new Buffer(encode("Hello"));
+ const buf = new Deno.Buffer(encode("Hello"));
req.r = new BufReader(buf);
const body = decode(await Deno.readAll(req.body));
assertEquals(body, "Hello");
@@ -138,59 +136,65 @@ test("requestBodyWithContentLength", async function (): Promise<void> {
const req = new ServerRequest();
req.headers = new Headers();
req.headers.set("Content-Length", "5000");
- const buf = new Buffer(encode(longText));
+ const buf = new Deno.Buffer(encode(longText));
req.r = new BufReader(buf);
const body = decode(await Deno.readAll(req.body));
assertEquals(body, longText);
}
// Handler ignored to consume body
});
-test("ServerRequest.finalize() should consume unread body / content-length", async () => {
- const text = "deno.land";
- const req = new ServerRequest();
- req.headers = new Headers();
- req.headers.set("content-length", "" + text.length);
- const tr = totalReader(new Buffer(encode(text)));
- req.r = new BufReader(tr);
- req.w = new BufWriter(new Buffer());
- await req.respond({ status: 200, body: "ok" });
- assertEquals(tr.total, 0);
- await req.finalize();
- assertEquals(tr.total, text.length);
-});
-test("ServerRequest.finalize() should consume unread body / chunked, trailers", async () => {
- const text = [
- "5",
- "Hello",
- "4",
- "Deno",
- "0",
- "",
- "deno: land",
- "node: js",
- "",
- "",
- ].join("\r\n");
- const req = new ServerRequest();
- req.headers = new Headers();
- req.headers.set("transfer-encoding", "chunked");
- req.headers.set("trailer", "deno,node");
- const body = encode(text);
- const tr = totalReader(new Buffer(body));
- req.r = new BufReader(tr);
- req.w = new BufWriter(new Buffer());
- await req.respond({ status: 200, body: "ok" });
- assertEquals(tr.total, 0);
- assertEquals(req.headers.has("trailer"), true);
- assertEquals(req.headers.has("deno"), false);
- assertEquals(req.headers.has("node"), false);
- await req.finalize();
- assertEquals(tr.total, body.byteLength);
- assertEquals(req.headers.has("trailer"), false);
- assertEquals(req.headers.get("deno"), "land");
- assertEquals(req.headers.get("node"), "js");
-});
-test("requestBodyWithTransferEncoding", async function (): Promise<void> {
+Deno.test(
+ "ServerRequest.finalize() should consume unread body / content-length",
+ async () => {
+ const text = "deno.land";
+ const req = new ServerRequest();
+ req.headers = new Headers();
+ req.headers.set("content-length", "" + text.length);
+ const tr = totalReader(new Deno.Buffer(encode(text)));
+ req.r = new BufReader(tr);
+ req.w = new BufWriter(new Deno.Buffer());
+ await req.respond({ status: 200, body: "ok" });
+ assertEquals(tr.total, 0);
+ await req.finalize();
+ assertEquals(tr.total, text.length);
+ }
+);
+Deno.test(
+ "ServerRequest.finalize() should consume unread body / chunked, trailers",
+ async () => {
+ const text = [
+ "5",
+ "Hello",
+ "4",
+ "Deno",
+ "0",
+ "",
+ "deno: land",
+ "node: js",
+ "",
+ "",
+ ].join("\r\n");
+ const req = new ServerRequest();
+ req.headers = new Headers();
+ req.headers.set("transfer-encoding", "chunked");
+ req.headers.set("trailer", "deno,node");
+ const body = encode(text);
+ const tr = totalReader(new Deno.Buffer(body));
+ req.r = new BufReader(tr);
+ req.w = new BufWriter(new Deno.Buffer());
+ await req.respond({ status: 200, body: "ok" });
+ assertEquals(tr.total, 0);
+ assertEquals(req.headers.has("trailer"), true);
+ assertEquals(req.headers.has("deno"), false);
+ assertEquals(req.headers.has("node"), false);
+ await req.finalize();
+ assertEquals(tr.total, body.byteLength);
+ assertEquals(req.headers.has("trailer"), false);
+ assertEquals(req.headers.get("deno"), "land");
+ assertEquals(req.headers.get("node"), "js");
+ }
+);
+Deno.test("requestBodyWithTransferEncoding", async function (): Promise<void> {
{
const shortText = "Hello";
const req = new ServerRequest();
@@ -208,7 +212,7 @@ test("requestBodyWithTransferEncoding", async function (): Promise<void> {
chunkOffset += chunkSize;
}
chunksData += "0\r\n\r\n";
- const buf = new Buffer(encode(chunksData));
+ const buf = new Deno.Buffer(encode(chunksData));
req.r = new BufReader(buf);
const body = decode(await Deno.readAll(req.body));
assertEquals(body, shortText);
@@ -232,20 +236,22 @@ test("requestBodyWithTransferEncoding", async function (): Promise<void> {
chunkOffset += chunkSize;
}
chunksData += "0\r\n\r\n";
- const buf = new Buffer(encode(chunksData));
+ const buf = new Deno.Buffer(encode(chunksData));
req.r = new BufReader(buf);
const body = decode(await Deno.readAll(req.body));
assertEquals(body, longText);
}
});
-test("requestBodyReaderWithContentLength", async function (): Promise<void> {
+Deno.test("requestBodyReaderWithContentLength", async function (): Promise<
+ void
+> {
{
const shortText = "Hello";
const req = new ServerRequest();
req.headers = new Headers();
req.headers.set("content-length", "" + shortText.length);
- const buf = new Buffer(encode(shortText));
+ const buf = new Deno.Buffer(encode(shortText));
req.r = new BufReader(buf);
const readBuf = new Uint8Array(6);
let offset = 0;
@@ -266,7 +272,7 @@ test("requestBodyReaderWithContentLength", async function (): Promise<void> {
const req = new ServerRequest();
req.headers = new Headers();
req.headers.set("Content-Length", "5000");
- const buf = new Buffer(encode(longText));
+ const buf = new Deno.Buffer(encode(longText));
req.r = new BufReader(buf);
const readBuf = new Uint8Array(1000);
let offset = 0;
@@ -282,7 +288,9 @@ test("requestBodyReaderWithContentLength", async function (): Promise<void> {
}
});
-test("requestBodyReaderWithTransferEncoding", async function (): Promise<void> {
+Deno.test("requestBodyReaderWithTransferEncoding", async function (): Promise<
+ void
+> {
{
const shortText = "Hello";
const req = new ServerRequest();
@@ -300,7 +308,7 @@ test("requestBodyReaderWithTransferEncoding", async function (): Promise<void> {
chunkOffset += chunkSize;
}
chunksData += "0\r\n\r\n";
- const buf = new Buffer(encode(chunksData));
+ const buf = new Deno.Buffer(encode(chunksData));
req.r = new BufReader(buf);
const readBuf = new Uint8Array(6);
let offset = 0;
@@ -333,7 +341,7 @@ test("requestBodyReaderWithTransferEncoding", async function (): Promise<void> {
chunkOffset += chunkSize;
}
chunksData += "0\r\n\r\n";
- const buf = new Buffer(encode(chunksData));
+ const buf = new Deno.Buffer(encode(chunksData));
req.r = new BufReader(buf);
const readBuf = new Uint8Array(1000);
let offset = 0;
@@ -349,7 +357,7 @@ test("requestBodyReaderWithTransferEncoding", async function (): Promise<void> {
}
});
-test({
+Deno.test({
name: "destroyed connection",
fn: async (): Promise<void> => {
// Runs a simple server as another process
@@ -393,7 +401,7 @@ test({
},
});
-test({
+Deno.test({
name: "serveTLS",
fn: async (): Promise<void> => {
// Runs a simple server as another process
@@ -450,17 +458,20 @@ test({
},
});
-test("close server while iterating", async (): Promise<void> => {
- const server = serve(":8123");
- const nextWhileClosing = server[Symbol.asyncIterator]().next();
- server.close();
- assertEquals(await nextWhileClosing, { value: undefined, done: true });
+Deno.test(
+ "close server while iterating",
+ async (): Promise<void> => {
+ const server = serve(":8123");
+ const nextWhileClosing = server[Symbol.asyncIterator]().next();
+ server.close();
+ assertEquals(await nextWhileClosing, { value: undefined, done: true });
- const nextAfterClosing = server[Symbol.asyncIterator]().next();
- assertEquals(await nextAfterClosing, { value: undefined, done: true });
-});
+ const nextAfterClosing = server[Symbol.asyncIterator]().next();
+ assertEquals(await nextAfterClosing, { value: undefined, done: true });
+ }
+);
-test({
+Deno.test({
name: "[http] close server while connection is open",
async fn(): Promise<void> {
async function iteratorReq(server: Server): Promise<void> {
@@ -491,7 +502,7 @@ test({
},
});
-test({
+Deno.test({
name: "respond error closes connection",
async fn(): Promise<void> {
const serverRoutine = async (): Promise<void> => {
@@ -522,7 +533,7 @@ test({
},
});
-test({
+Deno.test({
name: "[http] request error gets 400 response",
async fn(): Promise<void> {
const server = serve(":8124");
@@ -546,7 +557,7 @@ test({
},
});
-test({
+Deno.test({
name: "serveTLS Invalid Cert",
fn: async (): Promise<void> => {
async function iteratorReq(server: Server): Promise<void> {
diff --git a/std/io/bufio_test.ts b/std/io/bufio_test.ts
index 92119e4db..2a32ba135 100644
--- a/std/io/bufio_test.ts
+++ b/std/io/bufio_test.ts
@@ -2,9 +2,6 @@
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-
-const { Buffer } = Deno;
-type Reader = Deno.Reader;
import { assert, assertEquals, fail } from "../testing/asserts.ts";
import {
BufReader,
@@ -47,11 +44,11 @@ Deno.test("bufioReaderSimple", async function (): Promise<void> {
interface ReadMaker {
name: string;
- fn: (r: Reader) => Reader;
+ fn: (r: Deno.Reader) => Deno.Reader;
}
const readMakers: ReadMaker[] = [
- { name: "full", fn: (r): Reader => r },
+ { name: "full", fn: (r): Deno.Reader => r },
{
name: "byte",
fn: (r): iotest.OneByteReader => new iotest.OneByteReader(r),
@@ -190,7 +187,7 @@ const testInputrn = encoder.encode(
const testOutput = encoder.encode("0123456789abcdefghijklmnopqrstuvwxy");
// TestReader wraps a Uint8Array and returns reads of a specific length.
-class TestReader implements Reader {
+class TestReader implements Deno.Reader {
constructor(private data: Uint8Array, private stride: number) {}
read(buf: Uint8Array): Promise<number | null> {
@@ -337,7 +334,7 @@ Deno.test("bufioWriter", async function (): Promise<void> {
data[i] = charCode(" ") + (i % (charCode("~") - charCode(" ")));
}
- const w = new Buffer();
+ const w = new Deno.Buffer();
for (const nwrite of bufsizes) {
for (const bs of bufsizes) {
// Write nwrite bytes using buffer size bs.
@@ -371,7 +368,7 @@ Deno.test("bufioWriterSync", function (): void {
data[i] = charCode(" ") + (i % (charCode("~") - charCode(" ")));
}
- const w = new Buffer();
+ const w = new Deno.Buffer();
for (const nwrite of bufsizes) {
for (const bs of bufsizes) {
// Write nwrite bytes using buffer size bs.
@@ -401,7 +398,7 @@ Deno.test("bufReaderReadFull", async function (): Promise<void> {
const enc = new TextEncoder();
const dec = new TextDecoder();
const text = "Hello World";
- const data = new Buffer(enc.encode(text));
+ const data = new Deno.Buffer(enc.encode(text));
const bufr = new BufReader(data, 3);
{
const buf = new Uint8Array(6);
@@ -426,7 +423,7 @@ Deno.test("bufReaderReadFull", async function (): Promise<void> {
Deno.test("readStringDelimAndLines", async function (): Promise<void> {
const enc = new TextEncoder();
- const data = new Buffer(
+ const data = new Deno.Buffer(
enc.encode("Hello World\tHello World 2\tHello World 3")
);
const chunks_ = [];
@@ -438,7 +435,7 @@ Deno.test("readStringDelimAndLines", async function (): Promise<void> {
assertEquals(chunks_.length, 3);
assertEquals(chunks_, ["Hello World", "Hello World 2", "Hello World 3"]);
- const linesData = new Buffer(enc.encode("0\n1\n2\n3\n4\n5\n6\n7\n8\n9"));
+ const linesData = new Deno.Buffer(enc.encode("0\n1\n2\n3\n4\n5\n6\n7\n8\n9"));
const lines_ = [];
for await (const l of readLines(linesData)) {
diff --git a/std/io/ioutil_test.ts b/std/io/ioutil_test.ts
index 977c7022c..dfdda23fb 100644
--- a/std/io/ioutil_test.ts
+++ b/std/io/ioutil_test.ts
@@ -1,6 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-const { Buffer } = Deno;
-type Reader = Deno.Reader;
import { assertEquals } from "../testing/asserts.ts";
import {
copyN,
@@ -14,7 +12,7 @@ import { BufReader } from "./bufio.ts";
import { tempFile } from "./util.ts";
import * as path from "../path/mod.ts";
-class BinaryReader implements Reader {
+class BinaryReader implements Deno.Reader {
index = 0;
constructor(private bytes: Uint8Array = new Uint8Array(0)) {}
@@ -73,7 +71,7 @@ Deno.test("testSliceLongToBytes2", function (): void {
});
Deno.test("testCopyN1", async function (): Promise<void> {
- const w = new Buffer();
+ const w = new Deno.Buffer();
const r = new StringReader("abcdefghij");
const n = await copyN(r, w, 3);
assertEquals(n, 3);
@@ -81,7 +79,7 @@ Deno.test("testCopyN1", async function (): Promise<void> {
});
Deno.test("testCopyN2", async function (): Promise<void> {
- const w = new Buffer();
+ const w = new Deno.Buffer();
const r = new StringReader("abcdefghij");
const n = await copyN(r, w, 11);
assertEquals(n, 10);
diff --git a/std/io/readers.ts b/std/io/readers.ts
index d43655263..83115ee19 100644
--- a/std/io/readers.ts
+++ b/std/io/readers.ts
@@ -1,27 +1,23 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
// Based on https://github.com/golang/go/blob/0452f9460f50f0f0aba18df43dc2b31906fb66cc/src/io/io.go
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-
-type Reader = Deno.Reader;
import { encode } from "../encoding/utf8.ts";
-const { Buffer } = Deno;
/** Reader utility for strings */
-export class StringReader extends Buffer {
+export class StringReader extends Deno.Buffer {
constructor(private readonly s: string) {
super(encode(s).buffer);
}
}
/** Reader utility for combining multiple readers */
-export class MultiReader implements Reader {
- private readonly readers: Reader[];
+export class MultiReader implements Deno.Reader {
+ private readonly readers: Deno.Reader[];
private currentIndex = 0;
- constructor(...readers: Reader[]) {
+ constructor(...readers: Deno.Reader[]) {
this.readers = readers;
}
diff --git a/std/io/readers_test.ts b/std/io/readers_test.ts
index 04e9b7488..d608877c1 100644
--- a/std/io/readers_test.ts
+++ b/std/io/readers_test.ts
@@ -1,11 +1,10 @@
-const { copy, test } = Deno;
import { assertEquals } from "../testing/asserts.ts";
import { LimitedReader, MultiReader, StringReader } from "./readers.ts";
import { StringWriter } from "./writers.ts";
import { copyN } from "./ioutil.ts";
import { decode } from "../encoding/utf8.ts";
-test("ioStringReader", async function (): Promise<void> {
+Deno.test("ioStringReader", async function (): Promise<void> {
const r = new StringReader("abcdef");
const res0 = await r.read(new Uint8Array(6));
assertEquals(res0, 6);
@@ -13,7 +12,7 @@ test("ioStringReader", async function (): Promise<void> {
assertEquals(res1, null);
});
-test("ioStringReader", async function (): Promise<void> {
+Deno.test("ioStringReader", async function (): Promise<void> {
const r = new StringReader("abcdef");
const buf = new Uint8Array(3);
const res1 = await r.read(buf);
@@ -27,17 +26,17 @@ test("ioStringReader", async function (): Promise<void> {
assertEquals(decode(buf), "def");
});
-test("ioMultiReader", async function (): Promise<void> {
+Deno.test("ioMultiReader", async function (): Promise<void> {
const r = new MultiReader(new StringReader("abc"), new StringReader("def"));
const w = new StringWriter();
const n = await copyN(r, w, 4);
assertEquals(n, 4);
assertEquals(w.toString(), "abcd");
- await copy(r, w);
+ await Deno.copy(r, w);
assertEquals(w.toString(), "abcdef");
});
-test("ioLimitedReader", async function (): Promise<void> {
+Deno.test("ioLimitedReader", async function (): Promise<void> {
let sr = new StringReader("abc");
let r = new LimitedReader(sr, 2);
let buffer = await Deno.readAll(r);
@@ -55,7 +54,7 @@ test("ioLimitedReader", async function (): Promise<void> {
assertEquals((await Deno.readAll(r)).length, 0);
});
-test("ioLimitedReader", async function (): Promise<void> {
+Deno.test("ioLimitedReader", async function (): Promise<void> {
const rb = new StringReader("abc");
const wb = new StringWriter();
await Deno.copy(new LimitedReader(rb, -1), wb);
diff --git a/std/io/util.ts b/std/io/util.ts
index 47e48a981..22ecb1331 100644
--- a/std/io/util.ts
+++ b/std/io/util.ts
@@ -1,7 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-const { mkdir, open } = Deno;
-type File = Deno.File;
-type Reader = Deno.Reader;
import * as path from "../path/mod.ts";
/**
@@ -36,13 +33,13 @@ export async function tempFile(
prefix?: string;
postfix?: string;
} = { prefix: "", postfix: "" }
-): Promise<{ file: File; filepath: string }> {
+): Promise<{ file: Deno.File; filepath: string }> {
const r = Math.floor(Math.random() * 1000000);
const filepath = path.resolve(
`${dir}/${opts.prefix || ""}${r}${opts.postfix || ""}`
);
- await mkdir(path.dirname(filepath), { recursive: true });
- const file = await open(filepath, {
+ await Deno.mkdir(path.dirname(filepath), { recursive: true });
+ const file = await Deno.open(filepath, {
create: true,
read: true,
write: true,
diff --git a/std/io/util_test.ts b/std/io/util_test.ts
index 68a398bd1..d33a328d6 100644
--- a/std/io/util_test.ts
+++ b/std/io/util_test.ts
@@ -1,10 +1,9 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-const { remove, test } = Deno;
import { assert, assertEquals } from "../testing/asserts.ts";
import * as path from "../path/mod.ts";
import { copyBytes, tempFile } from "./util.ts";
-test("[io/tuil] copyBytes", function (): void {
+Deno.test("[io/tuil] copyBytes", function (): void {
const dst = new Uint8Array(4);
dst.fill(0);
@@ -38,7 +37,7 @@ test("[io/tuil] copyBytes", function (): void {
assertEquals(dst, Uint8Array.of(3, 4, 0, 0));
});
-test({
+Deno.test({
name: "[io/util] tempfile",
fn: async function (): Promise<void> {
const f = await tempFile(".", {
@@ -48,6 +47,6 @@ test({
const base = path.basename(f.filepath);
assert(!!base.match(/^prefix-.+?-postfix$/));
f.file.close();
- await remove(f.filepath);
+ await Deno.remove(f.filepath);
},
});
diff --git a/std/io/writers_test.ts b/std/io/writers_test.ts
index f27885f81..13b95a8d5 100644
--- a/std/io/writers_test.ts
+++ b/std/io/writers_test.ts
@@ -1,15 +1,14 @@
-const { copy, test } = Deno;
import { assertEquals } from "../testing/asserts.ts";
import { StringWriter } from "./writers.ts";
import { StringReader } from "./readers.ts";
import { copyN } from "./ioutil.ts";
-test("ioStringWriter", async function (): Promise<void> {
+Deno.test("ioStringWriter", async function (): Promise<void> {
const w = new StringWriter("base");
const r = new StringReader("0123456789");
await copyN(r, w, 4);
assertEquals(w.toString(), "base0123");
- await copy(r, w);
+ await Deno.copy(r, w);
assertEquals(w.toString(), "base0123456789");
});
diff --git a/std/log/handlers.ts b/std/log/handlers.ts
index 5e72ff582..1b152c273 100644
--- a/std/log/handlers.ts
+++ b/std/log/handlers.ts
@@ -1,8 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-const { open, openSync, close, renameSync, stat } = Deno;
-type File = Deno.File;
-type Writer = Deno.Writer;
-type OpenOptions = Deno.OpenOptions;
import { getLevelByName, LevelName, LogLevels } from "./levels.ts";
import { LogRecord } from "./logger.ts";
import { red, yellow, blue, bold } from "../fmt/colors.ts";
@@ -88,7 +84,7 @@ export class ConsoleHandler extends BaseHandler {
}
export abstract class WriterHandler extends BaseHandler {
- protected _writer!: Writer;
+ protected _writer!: Deno.Writer;
#encoder = new TextEncoder();
abstract log(msg: string): void;
@@ -100,11 +96,11 @@ interface FileHandlerOptions extends HandlerOptions {
}
export class FileHandler extends WriterHandler {
- protected _file: File | undefined;
+ protected _file: Deno.File | undefined;
protected _buf!: BufWriterSync;
protected _filename: string;
protected _mode: LogMode;
- protected _openOptions: OpenOptions;
+ protected _openOptions: Deno.OpenOptions;
protected _encoder = new TextEncoder();
#unloadCallback = (): Promise<void> => this.destroy();
@@ -123,7 +119,7 @@ export class FileHandler extends WriterHandler {
}
async setup(): Promise<void> {
- this._file = await open(this._filename, this._openOptions);
+ this._file = await Deno.open(this._filename, this._openOptions);
this._writer = this._file;
this._buf = new BufWriterSync(this._file);
@@ -204,7 +200,7 @@ export class RotatingFileHandler extends FileHandler {
}
}
} else {
- this.#currentFileSize = (await stat(this._filename)).size;
+ this.#currentFileSize = (await Deno.stat(this._filename)).size;
}
}
@@ -222,18 +218,18 @@ export class RotatingFileHandler extends FileHandler {
rotateLogFiles(): void {
this._buf.flush();
- close(this._file!.rid);
+ Deno.close(this._file!.rid);
for (let i = this.#maxBackupCount - 1; i >= 0; i--) {
const source = this._filename + (i === 0 ? "" : "." + i);
const dest = this._filename + "." + (i + 1);
if (existsSync(source)) {
- renameSync(source, dest);
+ Deno.renameSync(source, dest);
}
}
- this._file = openSync(this._filename, this._openOptions);
+ this._file = Deno.openSync(this._filename, this._openOptions);
this._writer = this._file;
this._buf = new BufWriterSync(this._file);
}
diff --git a/std/log/handlers_test.ts b/std/log/handlers_test.ts
index cb73fa56f..f7714dae3 100644
--- a/std/log/handlers_test.ts
+++ b/std/log/handlers_test.ts
@@ -1,5 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-const { test } = Deno;
import {
assert,
assertEquals,
@@ -27,7 +26,7 @@ class TestHandler extends BaseHandler {
}
}
-test("simpleHandler", function (): void {
+Deno.test("simpleHandler", function (): void {
const cases = new Map<number, string[]>([
[
LogLevels.DEBUG,
@@ -73,7 +72,7 @@ test("simpleHandler", function (): void {
}
});
-test("testFormatterAsString", function (): void {
+Deno.test("testFormatterAsString", function (): void {
const handler = new TestHandler("DEBUG", {
formatter: "test {levelName} {msg}",
});
@@ -83,7 +82,7 @@ test("testFormatterAsString", function (): void {
assertEquals(handler.messages, ["test DEBUG Hello, world!"]);
});
-test("testFormatterAsFunction", function (): void {
+Deno.test("testFormatterAsFunction", function (): void {
const handler = new TestHandler("DEBUG", {
formatter: (logRecord): string =>
`fn formatter ${logRecord.levelName} ${logRecord.msg}`,
@@ -94,7 +93,7 @@ test("testFormatterAsFunction", function (): void {
assertEquals(handler.messages, ["fn formatter ERROR Hello, world!"]);
});
-test({
+Deno.test({
name: "FileHandler with mode 'w' will wipe clean existing log file",
async fn() {
const fileHandler = new FileHandler("WARNING", {
@@ -117,7 +116,7 @@ test({
},
});
-test({
+Deno.test({
name: "FileHandler with mode 'x' will throw if log file already exists",
async fn() {
const fileHandler = new FileHandler("WARNING", {
@@ -136,7 +135,7 @@ test({
},
});
-test({
+Deno.test({
name:
"RotatingFileHandler with mode 'w' will wipe clean existing log file and remove others",
async fn() {
@@ -172,7 +171,7 @@ test({
},
});
-test({
+Deno.test({
name:
"RotatingFileHandler with mode 'x' will throw if any log file already exists",
async fn() {
@@ -200,7 +199,7 @@ test({
},
});
-test({
+Deno.test({
name: "RotatingFileHandler with first rollover, monitor step by step",
async fn() {
const fileHandler = new RotatingFileHandler("WARNING", {
@@ -229,7 +228,7 @@ test({
},
});
-test({
+Deno.test({
name: "RotatingFileHandler with first rollover, check all at once",
async fn() {
const fileHandler = new RotatingFileHandler("WARNING", {
@@ -254,7 +253,7 @@ test({
},
});
-test({
+Deno.test({
name: "RotatingFileHandler with all backups rollover",
async fn() {
Deno.writeFileSync(LOG_FILE, new TextEncoder().encode("original log file"));
@@ -304,7 +303,7 @@ test({
},
});
-test({
+Deno.test({
name: "RotatingFileHandler maxBytes cannot be less than 1",
async fn() {
await assertThrowsAsync(
@@ -323,7 +322,7 @@ test({
},
});
-test({
+Deno.test({
name: "RotatingFileHandler maxBackupCount cannot be less than 1",
async fn() {
await assertThrowsAsync(
@@ -342,7 +341,7 @@ test({
},
});
-test({
+Deno.test({
name: "Window unload flushes buffer",
async fn() {
const fileHandler = new FileHandler("WARNING", {
@@ -360,7 +359,7 @@ test({
},
});
-test({
+Deno.test({
name: "RotatingFileHandler: rotate on byte length, not msg length",
async fn() {
const fileHandler = new RotatingFileHandler("WARNING", {
@@ -394,7 +393,7 @@ test({
},
});
-test({
+Deno.test({
name: "FileHandler: Critical logs trigger immediate flush",
async fn() {
const fileHandler = new FileHandler("WARNING", {
diff --git a/std/log/logger_test.ts b/std/log/logger_test.ts
index b2e3cdab1..2425c15e6 100644
--- a/std/log/logger_test.ts
+++ b/std/log/logger_test.ts
@@ -1,5 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-const { test } = Deno;
import { assertEquals, assert } from "../testing/asserts.ts";
import { LogRecord, Logger } from "./logger.ts";
import { LogLevels, LevelName } from "./levels.ts";
@@ -19,7 +18,7 @@ class TestHandler extends BaseHandler {
}
}
-test("simpleLogger", function (): void {
+Deno.test("simpleLogger", function (): void {
const handler = new TestHandler("DEBUG");
let logger = new Logger("DEBUG");
@@ -32,7 +31,7 @@ test("simpleLogger", function (): void {
assertEquals(logger.handlers, [handler]);
});
-test("customHandler", function (): void {
+Deno.test("customHandler", function (): void {
const handler = new TestHandler("DEBUG");
const logger = new Logger("DEBUG", [handler]);
@@ -48,7 +47,7 @@ test("customHandler", function (): void {
assertEquals(inlineData!, "foo");
});
-test("logFunctions", function (): void {
+Deno.test("logFunctions", function (): void {
const doLog = (level: LevelName): TestHandler => {
const handler = new TestHandler(level);
const logger = new Logger(level, [handler]);
@@ -98,22 +97,29 @@ test("logFunctions", function (): void {
assertEquals(handler.messages, ["CRITICAL doo"]);
});
-test("String resolver fn will not execute if msg will not be logged", function (): void {
- const handler = new TestHandler("ERROR");
- const logger = new Logger("ERROR", [handler]);
- let called = false;
-
- const expensiveFunction = (): string => {
- called = true;
- return "expensive function result";
- };
-
- const inlineData: string | undefined = logger.debug(expensiveFunction, 1, 2);
- assert(!called);
- assertEquals(inlineData, undefined);
-});
+Deno.test(
+ "String resolver fn will not execute if msg will not be logged",
+ function (): void {
+ const handler = new TestHandler("ERROR");
+ const logger = new Logger("ERROR", [handler]);
+ let called = false;
+
+ const expensiveFunction = (): string => {
+ called = true;
+ return "expensive function result";
+ };
+
+ const inlineData: string | undefined = logger.debug(
+ expensiveFunction,
+ 1,
+ 2
+ );
+ assert(!called);
+ assertEquals(inlineData, undefined);
+ }
+);
-test("String resolver fn resolves as expected", function (): void {
+Deno.test("String resolver fn resolves as expected", function (): void {
const handler = new TestHandler("ERROR");
const logger = new Logger("ERROR", [handler]);
const expensiveFunction = (x: number): string => {
@@ -126,96 +132,99 @@ test("String resolver fn resolves as expected", function (): void {
assertEquals(secondInlineData, "expensive function result 12");
});
-test("All types map correctly to log strings and are returned as is", function (): void {
- const handler = new TestHandler("DEBUG");
- const logger = new Logger("DEBUG", [handler]);
- const sym = Symbol();
- const syma = Symbol("a");
- const fn = (): string => {
- return "abc";
- };
-
- // string
- const data1: string = logger.debug("abc");
- assertEquals(data1, "abc");
- const data2: string = logger.debug("def", 1);
- assertEquals(data2, "def");
- assertEquals(handler.messages[0], "DEBUG abc");
- assertEquals(handler.messages[1], "DEBUG def");
-
- // null
- const data3: null = logger.info(null);
- assertEquals(data3, null);
- const data4: null = logger.info(null, 1);
- assertEquals(data4, null);
- assertEquals(handler.messages[2], "INFO null");
- assertEquals(handler.messages[3], "INFO null");
-
- // number
- const data5: number = logger.warning(3);
- assertEquals(data5, 3);
- const data6: number = logger.warning(3, 1);
- assertEquals(data6, 3);
- assertEquals(handler.messages[4], "WARNING 3");
- assertEquals(handler.messages[5], "WARNING 3");
-
- // bigint
- const data7: bigint = logger.error(5n);
- assertEquals(data7, 5n);
- const data8: bigint = logger.error(5n, 1);
- assertEquals(data8, 5n);
- assertEquals(handler.messages[6], "ERROR 5");
- assertEquals(handler.messages[7], "ERROR 5");
-
- // boolean
- const data9: boolean = logger.critical(true);
- assertEquals(data9, true);
- const data10: boolean = logger.critical(false, 1);
- assertEquals(data10, false);
- assertEquals(handler.messages[8], "CRITICAL true");
- assertEquals(handler.messages[9], "CRITICAL false");
-
- // undefined
- const data11: undefined = logger.debug(undefined);
- assertEquals(data11, undefined);
- const data12: undefined = logger.debug(undefined, 1);
- assertEquals(data12, undefined);
- assertEquals(handler.messages[10], "DEBUG undefined");
- assertEquals(handler.messages[11], "DEBUG undefined");
-
- // symbol
- const data13: symbol = logger.info(sym);
- assertEquals(data13, sym);
- const data14: symbol = logger.info(syma, 1);
- assertEquals(data14, syma);
- assertEquals(handler.messages[12], "INFO Symbol()");
- assertEquals(handler.messages[13], "INFO Symbol(a)");
-
- // function
- const data15: string | undefined = logger.warning(fn);
- assertEquals(data15, "abc");
- const data16: string | undefined = logger.warning(fn, 1);
- assertEquals(data16, "abc");
- assertEquals(handler.messages[14], "WARNING abc");
- assertEquals(handler.messages[15], "WARNING abc");
-
- // object
- const data17: { payload: string; other: number } = logger.error({
- payload: "data",
- other: 123,
- });
- assertEquals(data17, {
- payload: "data",
- other: 123,
- });
- const data18: { payload: string; other: number } = logger.error(
- { payload: "data", other: 123 },
- 1
- );
- assertEquals(data18, {
- payload: "data",
- other: 123,
- });
- assertEquals(handler.messages[16], 'ERROR {"payload":"data","other":123}');
- assertEquals(handler.messages[17], 'ERROR {"payload":"data","other":123}');
-});
+Deno.test(
+ "All types map correctly to log strings and are returned as is",
+ function (): void {
+ const handler = new TestHandler("DEBUG");
+ const logger = new Logger("DEBUG", [handler]);
+ const sym = Symbol();
+ const syma = Symbol("a");
+ const fn = (): string => {
+ return "abc";
+ };
+
+ // string
+ const data1: string = logger.debug("abc");
+ assertEquals(data1, "abc");
+ const data2: string = logger.debug("def", 1);
+ assertEquals(data2, "def");
+ assertEquals(handler.messages[0], "DEBUG abc");
+ assertEquals(handler.messages[1], "DEBUG def");
+
+ // null
+ const data3: null = logger.info(null);
+ assertEquals(data3, null);
+ const data4: null = logger.info(null, 1);
+ assertEquals(data4, null);
+ assertEquals(handler.messages[2], "INFO null");
+ assertEquals(handler.messages[3], "INFO null");
+
+ // number
+ const data5: number = logger.warning(3);
+ assertEquals(data5, 3);
+ const data6: number = logger.warning(3, 1);
+ assertEquals(data6, 3);
+ assertEquals(handler.messages[4], "WARNING 3");
+ assertEquals(handler.messages[5], "WARNING 3");
+
+ // bigint
+ const data7: bigint = logger.error(5n);
+ assertEquals(data7, 5n);
+ const data8: bigint = logger.error(5n, 1);
+ assertEquals(data8, 5n);
+ assertEquals(handler.messages[6], "ERROR 5");
+ assertEquals(handler.messages[7], "ERROR 5");
+
+ // boolean
+ const data9: boolean = logger.critical(true);
+ assertEquals(data9, true);
+ const data10: boolean = logger.critical(false, 1);
+ assertEquals(data10, false);
+ assertEquals(handler.messages[8], "CRITICAL true");
+ assertEquals(handler.messages[9], "CRITICAL false");
+
+ // undefined
+ const data11: undefined = logger.debug(undefined);
+ assertEquals(data11, undefined);
+ const data12: undefined = logger.debug(undefined, 1);
+ assertEquals(data12, undefined);
+ assertEquals(handler.messages[10], "DEBUG undefined");
+ assertEquals(handler.messages[11], "DEBUG undefined");
+
+ // symbol
+ const data13: symbol = logger.info(sym);
+ assertEquals(data13, sym);
+ const data14: symbol = logger.info(syma, 1);
+ assertEquals(data14, syma);
+ assertEquals(handler.messages[12], "INFO Symbol()");
+ assertEquals(handler.messages[13], "INFO Symbol(a)");
+
+ // function
+ const data15: string | undefined = logger.warning(fn);
+ assertEquals(data15, "abc");
+ const data16: string | undefined = logger.warning(fn, 1);
+ assertEquals(data16, "abc");
+ assertEquals(handler.messages[14], "WARNING abc");
+ assertEquals(handler.messages[15], "WARNING abc");
+
+ // object
+ const data17: { payload: string; other: number } = logger.error({
+ payload: "data",
+ other: 123,
+ });
+ assertEquals(data17, {
+ payload: "data",
+ other: 123,
+ });
+ const data18: { payload: string; other: number } = logger.error(
+ { payload: "data", other: 123 },
+ 1
+ );
+ assertEquals(data18, {
+ payload: "data",
+ other: 123,
+ });
+ assertEquals(handler.messages[16], 'ERROR {"payload":"data","other":123}');
+ assertEquals(handler.messages[17], 'ERROR {"payload":"data","other":123}');
+ }
+);
diff --git a/std/log/mod_test.ts b/std/log/mod_test.ts
index 21b944fb5..98ac093c8 100644
--- a/std/log/mod_test.ts
+++ b/std/log/mod_test.ts
@@ -1,5 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-const { test } = Deno;
import { assert, assertEquals } from "../testing/asserts.ts";
import { getLogger, debug, info, warning, error, critical } from "./mod.ts";
import { Logger } from "./logger.ts";
@@ -13,11 +12,11 @@ try {
// Pass
}
-test("logger is initialized", function (): void {
+Deno.test("logger is initialized", function (): void {
assert(logger instanceof Logger);
});
-test("default loggers work as expected", function (): void {
+Deno.test("default loggers work as expected", function (): void {
const sym = Symbol("a");
const debugData: string = debug("foo");
const debugResolver: string | undefined = debug(() => "foo");
diff --git a/std/log/test.ts b/std/log/test.ts
index 2a51de6b5..0c0ab0703 100644
--- a/std/log/test.ts
+++ b/std/log/test.ts
@@ -1,5 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-const { test } = Deno;
import { assertEquals, assertThrows } from "../testing/asserts.ts";
import * as log from "./mod.ts";
import {
@@ -17,7 +16,7 @@ class TestHandler extends log.handlers.BaseHandler {
}
}
-test("defaultHandlers", async function (): Promise<void> {
+Deno.test("defaultHandlers", async function (): Promise<void> {
const loggers: {
[key: string]: (msg: string, ...args: unknown[]) => void;
} = {
@@ -55,7 +54,7 @@ test("defaultHandlers", async function (): Promise<void> {
}
});
-test("getLogger", async function (): Promise<void> {
+Deno.test("getLogger", async function (): Promise<void> {
const handler = new TestHandler("DEBUG");
await log.setup({
@@ -76,7 +75,7 @@ test("getLogger", async function (): Promise<void> {
assertEquals(logger.handlers, [handler]);
});
-test("getLoggerWithName", async function (): Promise<void> {
+Deno.test("getLoggerWithName", async function (): Promise<void> {
const fooHandler = new TestHandler("DEBUG");
await log.setup({
@@ -97,7 +96,7 @@ test("getLoggerWithName", async function (): Promise<void> {
assertEquals(logger.handlers, [fooHandler]);
});
-test("getLoggerUnknown", async function (): Promise<void> {
+Deno.test("getLoggerUnknown", async function (): Promise<void> {
await log.setup({
handlers: {},
loggers: {},
@@ -109,7 +108,7 @@ test("getLoggerUnknown", async function (): Promise<void> {
assertEquals(logger.handlers, []);
});
-test("getInvalidLoggerLevels", function (): void {
+Deno.test("getInvalidLoggerLevels", function (): void {
assertThrows(() => getLevelByName("FAKE_LOG_LEVEL" as LevelName));
assertThrows(() => getLevelName(5000));
});
diff --git a/std/mime/multipart.ts b/std/mime/multipart.ts
index 73a6544b5..42be47895 100644
--- a/std/mime/multipart.ts
+++ b/std/mime/multipart.ts
@@ -1,10 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
-const { Buffer, copy, remove } = Deno;
-const { min, max } = Math;
-type Closer = Deno.Closer;
-type Reader = Deno.Reader;
-type Writer = Deno.Writer;
import { equal, findIndex, findLastIndex, hasPrefix } from "../bytes/mod.ts";
import { copyN } from "../io/ioutil.ts";
import { MultiReader } from "../io/readers.ts";
@@ -150,7 +144,7 @@ export function scanUntilBoundary(
return buf.length;
}
-class PartReader implements Reader, Closer {
+class PartReader implements Deno.Reader, Deno.Closer {
n: number | null = 0;
total = 0;
@@ -163,7 +157,7 @@ class PartReader implements Reader, Closer {
// or we find a reason to stop (boundary or EOF).
let peekLength = 1;
while (this.n === 0) {
- peekLength = max(peekLength, br.buffered());
+ peekLength = Math.max(peekLength, br.buffered());
const peekBuf = await br.peek(peekLength);
if (peekBuf === null) {
throw new Deno.errors.UnexpectedEof();
@@ -187,7 +181,7 @@ class PartReader implements Reader, Closer {
return null;
}
- const nread = min(p.length, this.n);
+ const nread = Math.min(p.length, this.n);
const buf = p.subarray(0, nread);
const r = await br.readFull(buf);
assert(r === buf);
@@ -272,7 +266,7 @@ export class MultipartReader {
readonly dashBoundary = encoder.encode(`--${this.boundary}`);
readonly bufReader: BufReader;
- constructor(reader: Reader, private boundary: string) {
+ constructor(reader: Deno.Reader, private boundary: string) {
this.bufReader = new BufReader(reader);
}
@@ -287,7 +281,7 @@ export class MultipartReader {
const fileMap = new Map<string, FormFile | FormFile[]>();
const valueMap = new Map<string, string>();
let maxValueBytes = maxMemory + (10 << 20);
- const buf = new Buffer(new Uint8Array(maxValueBytes));
+ const buf = new Deno.Buffer(new Uint8Array(maxValueBytes));
for (;;) {
const p = await this.nextPart();
if (p === null) {
@@ -321,7 +315,7 @@ export class MultipartReader {
postfix: ext,
});
try {
- const size = await copy(new MultiReader(buf, p), file);
+ const size = await Deno.copy(new MultiReader(buf, p), file);
file.close();
formFile = {
@@ -331,7 +325,7 @@ export class MultipartReader {
size,
};
} catch (e) {
- await remove(filepath);
+ await Deno.remove(filepath);
throw e;
}
} else {
@@ -465,13 +459,13 @@ function multipatFormData(
};
}
-class PartWriter implements Writer {
+class PartWriter implements Deno.Writer {
closed = false;
private readonly partHeader: string;
private headersWritten = false;
constructor(
- private writer: Writer,
+ private writer: Deno.Writer,
readonly boundary: string,
public headers: Headers,
isFirstBoundary: boolean
@@ -531,7 +525,7 @@ export class MultipartWriter {
private bufWriter: BufWriter;
private isClosed = false;
- constructor(private readonly writer: Writer, boundary?: string) {
+ constructor(private readonly writer: Deno.Writer, boundary?: string) {
if (boundary !== void 0) {
this._boundary = checkBoundary(boundary);
} else {
@@ -544,7 +538,7 @@ export class MultipartWriter {
return `multipart/form-data; boundary=${this.boundary}`;
}
- private createPart(headers: Headers): Writer {
+ private createPart(headers: Headers): Deno.Writer {
if (this.isClosed) {
throw new Error("multipart: writer is closed");
}
@@ -561,7 +555,7 @@ export class MultipartWriter {
return part;
}
- createFormFile(field: string, filename: string): Writer {
+ createFormFile(field: string, filename: string): Deno.Writer {
const h = new Headers();
h.set(
"Content-Disposition",
@@ -571,7 +565,7 @@ export class MultipartWriter {
return this.createPart(h);
}
- createFormField(field: string): Writer {
+ createFormField(field: string): Deno.Writer {
const h = new Headers();
h.set("Content-Disposition", `form-data; name="${field}"`);
h.set("Content-Type", "application/octet-stream");
@@ -586,10 +580,10 @@ export class MultipartWriter {
async writeFile(
field: string,
filename: string,
- file: Reader
+ file: Deno.Reader
): Promise<void> {
const f = await this.createFormFile(field, filename);
- await copy(file, f);
+ await Deno.copy(file, f);
}
private flush(): Promise<void> {
diff --git a/std/mime/multipart_test.ts b/std/mime/multipart_test.ts
index 858dc3919..c0282ee3b 100644
--- a/std/mime/multipart_test.ts
+++ b/std/mime/multipart_test.ts
@@ -1,6 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
-const { Buffer, open, test } = Deno;
import {
assert,
assertEquals,
@@ -23,7 +21,7 @@ const dashBoundary = e.encode("--" + boundary);
const nlDashBoundary = e.encode("\r\n--" + boundary);
const testdataDir = path.resolve("mime", "testdata");
-test("multipartScanUntilBoundary1", function (): void {
+Deno.test("multipartScanUntilBoundary1", function (): void {
const data = `--${boundary}`;
const n = scanUntilBoundary(
e.encode(data),
@@ -35,7 +33,7 @@ test("multipartScanUntilBoundary1", function (): void {
assertEquals(n, null);
});
-test("multipartScanUntilBoundary2", function (): void {
+Deno.test("multipartScanUntilBoundary2", function (): void {
const data = `foo\r\n--${boundary}`;
const n = scanUntilBoundary(
e.encode(data),
@@ -47,7 +45,7 @@ test("multipartScanUntilBoundary2", function (): void {
assertEquals(n, 3);
});
-test("multipartScanUntilBoundary3", function (): void {
+Deno.test("multipartScanUntilBoundary3", function (): void {
const data = `foobar`;
const n = scanUntilBoundary(
e.encode(data),
@@ -59,7 +57,7 @@ test("multipartScanUntilBoundary3", function (): void {
assertEquals(n, data.length);
});
-test("multipartScanUntilBoundary4", function (): void {
+Deno.test("multipartScanUntilBoundary4", function (): void {
const data = `foo\r\n--`;
const n = scanUntilBoundary(
e.encode(data),
@@ -71,30 +69,30 @@ test("multipartScanUntilBoundary4", function (): void {
assertEquals(n, 3);
});
-test("multipartMatchAfterPrefix1", function (): void {
+Deno.test("multipartMatchAfterPrefix1", function (): void {
const data = `${boundary}\r`;
const v = matchAfterPrefix(e.encode(data), e.encode(boundary), false);
assertEquals(v, 1);
});
-test("multipartMatchAfterPrefix2", function (): void {
+Deno.test("multipartMatchAfterPrefix2", function (): void {
const data = `${boundary}hoge`;
const v = matchAfterPrefix(e.encode(data), e.encode(boundary), false);
assertEquals(v, -1);
});
-test("multipartMatchAfterPrefix3", function (): void {
+Deno.test("multipartMatchAfterPrefix3", function (): void {
const data = `${boundary}`;
const v = matchAfterPrefix(e.encode(data), e.encode(boundary), false);
assertEquals(v, 0);
});
-test("multipartMultipartWriter", async function (): Promise<void> {
- const buf = new Buffer();
+Deno.test("multipartMultipartWriter", async function (): Promise<void> {
+ const buf = new Deno.Buffer();
const mw = new MultipartWriter(buf);
await mw.writeField("foo", "foo");
await mw.writeField("bar", "bar");
- const f = await open(path.resolve("./mime/testdata/sample.txt"), {
+ const f = await Deno.open(path.resolve("./mime/testdata/sample.txt"), {
read: true,
});
await mw.writeFile("file", "sample.txt", f);
@@ -102,7 +100,7 @@ test("multipartMultipartWriter", async function (): Promise<void> {
f.close();
});
-test("multipartMultipartWriter2", function (): void {
+Deno.test("multipartMultipartWriter2", function (): void {
const w = new StringWriter();
assertThrows(
(): MultipartWriter => new MultipartWriter(w, ""),
@@ -131,7 +129,7 @@ test("multipartMultipartWriter2", function (): void {
);
});
-test("multipartMultipartWriter3", async function (): Promise<void> {
+Deno.test("multipartMultipartWriter3", async function (): Promise<void> {
const w = new StringWriter();
const mw = new MultipartWriter(w);
await mw.writeField("foo", "foo");
@@ -174,10 +172,10 @@ test("multipartMultipartWriter3", async function (): Promise<void> {
);
});
-test({
+Deno.test({
name: "[mime/multipart] readForm() basic",
async fn() {
- const o = await open(path.resolve("./mime/testdata/sample.txt"));
+ const o = await Deno.open(path.resolve("./mime/testdata/sample.txt"));
const mr = new MultipartReader(
o,
"--------------------------434049563556637648550474"
@@ -196,18 +194,21 @@ test({
},
});
-test({
+Deno.test({
name:
"[mime/multipart] readForm() should store big file completely in temp file",
async fn() {
const multipartFile = path.join(testdataDir, "form-data.dat");
const sampleFile = await Deno.makeTempFile();
- const writer = await open(multipartFile, { write: true, create: true });
+ const writer = await Deno.open(multipartFile, {
+ write: true,
+ create: true,
+ });
const size = 1 << 24; // 16mb
await Deno.truncate(sampleFile, size);
- const bigFile = await open(sampleFile, { read: true });
+ const bigFile = await Deno.open(sampleFile, { read: true });
const mw = new MultipartWriter(writer);
await mw.writeField("deno", "land");
@@ -243,10 +244,10 @@ test({
},
});
-test({
+Deno.test({
name: "[mime/multipart] removeAll() should remove all tempfiles",
async fn() {
- const o = await open(path.resolve("./mime/testdata/sample.txt"));
+ const o = await Deno.open(path.resolve("./mime/testdata/sample.txt"));
const mr = new MultipartReader(
o,
"--------------------------434049563556637648550474"
@@ -270,10 +271,10 @@ test({
},
});
-test({
+Deno.test({
name: "[mime/multipart] entries()",
async fn() {
- const o = await open(path.resolve("./mime/testdata/sample.txt"));
+ const o = await Deno.open(path.resolve("./mime/testdata/sample.txt"));
const mr = new MultipartReader(
o,
"--------------------------434049563556637648550474"
diff --git a/std/node/_fs/_fs_appendFile_test.ts b/std/node/_fs/_fs_appendFile_test.ts
index 402ac1c10..1286ff900 100644
--- a/std/node/_fs/_fs_appendFile_test.ts
+++ b/std/node/_fs/_fs_appendFile_test.ts
@@ -1,12 +1,11 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-const { test } = Deno;
import { assertEquals, assertThrows, fail } from "../../testing/asserts.ts";
import { appendFile, appendFileSync } from "./_fs_appendFile.ts";
import { fromFileUrl } from "../path.ts";
const decoder = new TextDecoder("utf-8");
-test({
+Deno.test({
name: "No callback Fn results in Error",
fn() {
assertThrows(
@@ -19,7 +18,7 @@ test({
},
});
-test({
+Deno.test({
name: "Unsupported encoding results in error()",
fn() {
assertThrows(
@@ -57,7 +56,7 @@ test({
},
});
-test({
+Deno.test({
name: "Async: Data is written to passed in rid",
async fn() {
const tempFile: string = await Deno.makeTempFile();
@@ -86,7 +85,7 @@ test({
},
});
-test({
+Deno.test({
name: "Async: Data is written to passed in file path",
async fn() {
const openResourcesBeforeAppend: Deno.ResourceMap = Deno.resources();
@@ -110,7 +109,7 @@ test({
},
});
-test({
+Deno.test({
name: "Async: Data is written to passed in URL",
async fn() {
const openResourcesBeforeAppend: Deno.ResourceMap = Deno.resources();
@@ -135,7 +134,7 @@ test({
},
});
-test({
+Deno.test({
name:
"Async: Callback is made with error if attempting to append data to an existing file with 'ax' flag",
async fn() {
@@ -159,7 +158,7 @@ test({
},
});
-test({
+Deno.test({
name: "Sync: Data is written to passed in rid",
fn() {
const tempFile: string = Deno.makeTempFileSync();
@@ -176,7 +175,7 @@ test({
},
});
-test({
+Deno.test({
name: "Sync: Data is written to passed in file path",
fn() {
const openResourcesBeforeAppend: Deno.ResourceMap = Deno.resources();
@@ -188,7 +187,7 @@ test({
},
});
-test({
+Deno.test({
name:
"Sync: error thrown if attempting to append data to an existing file with 'ax' flag",
fn() {
diff --git a/std/node/_fs/_fs_chmod_test.ts b/std/node/_fs/_fs_chmod_test.ts
index e43f09788..de4981a8c 100644
--- a/std/node/_fs/_fs_chmod_test.ts
+++ b/std/node/_fs/_fs_chmod_test.ts
@@ -1,9 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-const { test } = Deno;
import { fail, assert } from "../../testing/asserts.ts";
import { chmod, chmodSync } from "./_fs_chmod.ts";
-test({
+Deno.test({
name: "ASYNC: Permissions are changed (non-Windows)",
ignore: Deno.build.os === "windows",
async fn() {
@@ -29,7 +28,7 @@ test({
},
});
-test({
+Deno.test({
name: "SYNC: Permissions are changed (non-Windows)",
ignore: Deno.build.os === "windows",
fn() {
diff --git a/std/node/_fs/_fs_chown_test.ts b/std/node/_fs/_fs_chown_test.ts
index 1c1393ac4..de7dd992f 100644
--- a/std/node/_fs/_fs_chown_test.ts
+++ b/std/node/_fs/_fs_chown_test.ts
@@ -1,5 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-const { test } = Deno;
import { fail, assertEquals } from "../../testing/asserts.ts";
import { chown, chownSync } from "./_fs_chown.ts";
@@ -7,7 +6,7 @@ import { chown, chownSync } from "./_fs_chown.ts";
// id again
const ignore = Deno.build.os == "windows";
-test({
+Deno.test({
ignore,
name: "ASYNC: setting existing uid/gid works as expected (non-Windows)",
async fn() {
@@ -35,7 +34,7 @@ test({
},
});
-test({
+Deno.test({
ignore,
name: "SYNC: setting existing uid/gid works as expected (non-Windows)",
fn() {
diff --git a/std/node/_fs/_fs_close_test.ts b/std/node/_fs/_fs_close_test.ts
index 1ea324cb4..feaf92ab8 100644
--- a/std/node/_fs/_fs_close_test.ts
+++ b/std/node/_fs/_fs_close_test.ts
@@ -1,9 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-const { test } = Deno;
import { fail, assert, assertThrows } from "../../testing/asserts.ts";
import { close, closeSync } from "./_fs_close.ts";
-test({
+Deno.test({
name: "ASYNC: File is closed",
async fn() {
const tempFile: string = await Deno.makeTempFile();
@@ -28,7 +27,7 @@ test({
},
});
-test({
+Deno.test({
name: "ASYNC: Invalid fd",
async fn() {
await new Promise((resolve, reject) => {
@@ -40,7 +39,7 @@ test({
},
});
-test({
+Deno.test({
name: "close callback should be asynchronous",
async fn() {
const tempFile: string = Deno.makeTempFileSync();
@@ -60,7 +59,7 @@ test({
},
});
-test({
+Deno.test({
name: "SYNC: File is closed",
fn() {
const tempFile: string = Deno.makeTempFileSync();
@@ -73,7 +72,7 @@ test({
},
});
-test({
+Deno.test({
name: "SYNC: Invalid fd",
fn() {
assertThrows(() => closeSync(-1));
diff --git a/std/node/_fs/_fs_copy_test.ts b/std/node/_fs/_fs_copy_test.ts
index f7ce0e279..891e80784 100644
--- a/std/node/_fs/_fs_copy_test.ts
+++ b/std/node/_fs/_fs_copy_test.ts
@@ -1,13 +1,11 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
+import { assert } from "../../testing/asserts.ts";
import { copyFile, copyFileSync } from "./_fs_copy.ts";
import { existsSync } from "./_fs_exists.ts";
-import { assert } from "../../testing/asserts.ts";
-const { test } = Deno;
-
const destFile = "./destination.txt";
-test({
+Deno.test({
name: "[std/node/fs] copy file",
fn: async () => {
const sourceFile = Deno.makeTempFileSync();
@@ -21,7 +19,7 @@ test({
},
});
-test({
+Deno.test({
name: "[std/node/fs] copy file sync",
fn: () => {
const sourceFile = Deno.makeTempFileSync();
diff --git a/std/node/_fs/_fs_dir_test.ts b/std/node/_fs/_fs_dir_test.ts
index 5b3336201..e89912772 100644
--- a/std/node/_fs/_fs_dir_test.ts
+++ b/std/node/_fs/_fs_dir_test.ts
@@ -1,9 +1,8 @@
-const { test } = Deno;
import { assert, assertEquals, fail } from "../../testing/asserts.ts";
import Dir from "./_fs_dir.ts";
import Dirent from "./_fs_dirent.ts";
-test({
+Deno.test({
name: "Closing current directory with callback is successful",
fn() {
let calledBack = false;
@@ -16,21 +15,21 @@ test({
},
});
-test({
+Deno.test({
name: "Closing current directory without callback returns void Promise",
async fn() {
await new Dir(".").close();
},
});
-test({
+Deno.test({
name: "Closing current directory synchronously works",
fn() {
new Dir(".").closeSync();
},
});
-test({
+Deno.test({
name: "Path is correctly returned",
fn() {
assertEquals(new Dir("std/node").path, "std/node");
@@ -40,7 +39,7 @@ test({
},
});
-test({
+Deno.test({
name: "read returns null for empty directory",
async fn() {
const testDir: string = Deno.makeTempDirSync();
@@ -67,7 +66,7 @@ test({
},
});
-test({
+Deno.test({
name: "Async read returns one file at a time",
async fn() {
const testDir: string = Deno.makeTempDirSync();
@@ -108,7 +107,7 @@ test({
},
});
-test({
+Deno.test({
name: "Sync read returns one file at a time",
fn() {
const testDir: string = Deno.makeTempDirSync();
@@ -139,7 +138,7 @@ test({
},
});
-test({
+Deno.test({
name: "Async iteration over existing directory",
async fn() {
const testDir: string = Deno.makeTempDirSync();
diff --git a/std/node/_fs/_fs_dirent_test.ts b/std/node/_fs/_fs_dirent_test.ts
index 43becedd1..8c4b98214 100644
--- a/std/node/_fs/_fs_dirent_test.ts
+++ b/std/node/_fs/_fs_dirent_test.ts
@@ -1,4 +1,3 @@
-const { test } = Deno;
import { assert, assertEquals, assertThrows } from "../../testing/asserts.ts";
import Dirent from "./_fs_dirent.ts";
@@ -9,7 +8,7 @@ class DirEntryMock implements Deno.DirEntry {
isSymlink = false;
}
-test({
+Deno.test({
name: "Directories are correctly identified",
fn() {
const entry: DirEntryMock = new DirEntryMock();
@@ -22,7 +21,7 @@ test({
},
});
-test({
+Deno.test({
name: "Files are correctly identified",
fn() {
const entry: DirEntryMock = new DirEntryMock();
@@ -35,7 +34,7 @@ test({
},
});
-test({
+Deno.test({
name: "Symlinks are correctly identified",
fn() {
const entry: DirEntryMock = new DirEntryMock();
@@ -48,7 +47,7 @@ test({
},
});
-test({
+Deno.test({
name: "File name is correct",
fn() {
const entry: DirEntryMock = new DirEntryMock();
@@ -57,7 +56,7 @@ test({
},
});
-test({
+Deno.test({
name: "Socket and FIFO pipes aren't yet available",
fn() {
const entry: DirEntryMock = new DirEntryMock();
diff --git a/std/node/_fs/_fs_exists_test.ts b/std/node/_fs/_fs_exists_test.ts
index b4885c87f..d7d2f7f29 100644
--- a/std/node/_fs/_fs_exists_test.ts
+++ b/std/node/_fs/_fs_exists_test.ts
@@ -1,11 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
import { assertEquals } from "../../testing/asserts.ts";
import { exists, existsSync } from "./_fs_exists.ts";
-const { test } = Deno;
-
-test("existsFile", async function () {
+Deno.test("existsFile", async function () {
const availableFile = await new Promise((resolve) => {
const tmpFilePath = Deno.makeTempFileSync();
exists(tmpFilePath, (exists: boolean) => {
@@ -20,7 +17,7 @@ test("existsFile", async function () {
assertEquals(notAvailableFile, false);
});
-test("existsSyncFile", function () {
+Deno.test("existsSyncFile", function () {
const tmpFilePath = Deno.makeTempFileSync();
assertEquals(existsSync(tmpFilePath), true);
Deno.removeSync(tmpFilePath);
diff --git a/std/node/_fs/_fs_link_test.ts b/std/node/_fs/_fs_link_test.ts
index e59984c8c..0251e55fb 100644
--- a/std/node/_fs/_fs_link_test.ts
+++ b/std/node/_fs/_fs_link_test.ts
@@ -1,11 +1,11 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-const { test } = Deno;
import { fail, assertEquals } from "../../testing/asserts.ts";
import { link, linkSync } from "./_fs_link.ts";
import { assert } from "https://deno.land/std@v0.50.0/testing/asserts.ts";
+
const isWindows = Deno.build.os === "windows";
-test({
+Deno.test({
ignore: isWindows,
name: "ASYNC: hard linking files works as expected",
async fn() {
@@ -30,7 +30,7 @@ test({
},
});
-test({
+Deno.test({
ignore: isWindows,
name: "ASYNC: hard linking files passes error to callback",
async fn() {
@@ -52,7 +52,7 @@ test({
},
});
-test({
+Deno.test({
ignore: isWindows,
name: "SYNC: hard linking files works as expected",
fn() {
diff --git a/std/node/_fs/_fs_mkdir_test.ts b/std/node/_fs/_fs_mkdir_test.ts
index 7e9d4859f..8909d85de 100644
--- a/std/node/_fs/_fs_mkdir_test.ts
+++ b/std/node/_fs/_fs_mkdir_test.ts
@@ -1,14 +1,11 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
import { assert } from "../../testing/asserts.ts";
import { mkdir, mkdirSync } from "./_fs_mkdir.ts";
import { existsSync } from "./_fs_exists.ts";
-const { test } = Deno;
-
const tmpDir = "./tmpdir";
-test({
+Deno.test({
name: "[node/fs] mkdir",
fn: async () => {
const result = await new Promise((resolve) => {
@@ -22,7 +19,7 @@ test({
},
});
-test({
+Deno.test({
name: "[node/fs] mkdirSync",
fn: () => {
mkdirSync(tmpDir);
diff --git a/std/node/_fs/_fs_readFile.ts b/std/node/_fs/_fs_readFile.ts
index 448045fd2..d4093ff7f 100644
--- a/std/node/_fs/_fs_readFile.ts
+++ b/std/node/_fs/_fs_readFile.ts
@@ -1,13 +1,9 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
import { intoCallbackAPIWithIntercept, MaybeEmpty } from "../_utils.ts";
-
import { getEncoding, FileOptions } from "./_fs_common.ts";
import { Buffer } from "../buffer.ts";
import { fromFileUrl } from "../path.ts";
-const { readFile: denoReadFile, readFileSync: denoReadFileSync } = Deno;
-
type ReadFileCallback = (
err: MaybeEmpty<Error>,
data: MaybeEmpty<string | Buffer>
@@ -38,7 +34,7 @@ export function readFile(
const encoding = getEncoding(optOrCallback);
intoCallbackAPIWithIntercept<Uint8Array, string | Buffer>(
- denoReadFile,
+ Deno.readFile,
(data: Uint8Array): string | Buffer => maybeDecode(data, encoding),
cb,
path
@@ -50,5 +46,5 @@ export function readFileSync(
opt?: FileOptions | string
): string | Buffer {
path = path instanceof URL ? fromFileUrl(path) : path;
- return maybeDecode(denoReadFileSync(path), getEncoding(opt));
+ return maybeDecode(Deno.readFileSync(path), getEncoding(opt));
}
diff --git a/std/node/_fs/_fs_readFile_test.ts b/std/node/_fs/_fs_readFile_test.ts
index 1a850c91a..02e4c3745 100644
--- a/std/node/_fs/_fs_readFile_test.ts
+++ b/std/node/_fs/_fs_readFile_test.ts
@@ -1,4 +1,3 @@
-const { test } = Deno;
import { readFile, readFileSync } from "./_fs_readFile.ts";
import * as path from "../../path/mod.ts";
import { assertEquals, assert } from "../../testing/asserts.ts";
@@ -7,7 +6,7 @@ const testData = path.resolve(
path.join("node", "_fs", "testdata", "hello.txt")
);
-test("readFileSuccess", async function () {
+Deno.test("readFileSuccess", async function () {
const data = await new Promise((res, rej) => {
readFile(testData, (err, data) => {
if (err) {
@@ -21,7 +20,7 @@ test("readFileSuccess", async function () {
assertEquals(new TextDecoder().decode(data as Uint8Array), "hello world");
});
-test("readFileEncodeUtf8Success", async function () {
+Deno.test("readFileEncodeUtf8Success", async function () {
const data = await new Promise((res, rej) => {
readFile(testData, { encoding: "utf8" }, (err, data) => {
if (err) {
@@ -35,7 +34,7 @@ test("readFileEncodeUtf8Success", async function () {
assertEquals(data as string, "hello world");
});
-test("readFileEncodingAsString", async function () {
+Deno.test("readFileEncodingAsString", async function () {
const data = await new Promise((res, rej) => {
readFile(testData, "utf8", (err, data) => {
if (err) {
@@ -49,19 +48,19 @@ test("readFileEncodingAsString", async function () {
assertEquals(data as string, "hello world");
});
-test("readFileSyncSuccess", function () {
+Deno.test("readFileSyncSuccess", function () {
const data = readFileSync(testData);
assert(data instanceof Uint8Array);
assertEquals(new TextDecoder().decode(data as Uint8Array), "hello world");
});
-test("readFileEncodeUtf8Success", function () {
+Deno.test("readFileEncodeUtf8Success", function () {
const data = readFileSync(testData, { encoding: "utf8" });
assertEquals(typeof data, "string");
assertEquals(data as string, "hello world");
});
-test("readFileEncodeAsString", function () {
+Deno.test("readFileEncodeAsString", function () {
const data = readFileSync(testData, "utf8");
assertEquals(typeof data, "string");
assertEquals(data as string, "hello world");
diff --git a/std/node/_fs/_fs_readlink.ts b/std/node/_fs/_fs_readlink.ts
index d461cf390..11ce43f55 100644
--- a/std/node/_fs/_fs_readlink.ts
+++ b/std/node/_fs/_fs_readlink.ts
@@ -6,8 +6,6 @@ import {
} from "../_utils.ts";
import { fromFileUrl } from "../path.ts";
-const { readLink: denoReadlink, readLinkSync: denoReadlinkSync } = Deno;
-
type ReadlinkCallback = (
err: MaybeEmpty<Error>,
linkString: MaybeEmpty<string | Uint8Array>
@@ -66,7 +64,7 @@ export function readlink(
const encoding = getEncoding(optOrCallback);
intoCallbackAPIWithIntercept<string, Uint8Array | string>(
- denoReadlink,
+ Deno.readLink,
(data: string): string | Uint8Array => maybeEncode(data, encoding),
cb,
path
@@ -79,5 +77,5 @@ export function readlinkSync(
): string | Uint8Array {
path = path instanceof URL ? fromFileUrl(path) : path;
- return maybeEncode(denoReadlinkSync(path), getEncoding(opt));
+ return maybeEncode(Deno.readLinkSync(path), getEncoding(opt));
}
diff --git a/std/node/_fs/_fs_readlink_test.ts b/std/node/_fs/_fs_readlink_test.ts
index 77ce60a3f..437873494 100644
--- a/std/node/_fs/_fs_readlink_test.ts
+++ b/std/node/_fs/_fs_readlink_test.ts
@@ -1,4 +1,3 @@
-const { test } = Deno;
import { readlink, readlinkSync } from "./_fs_readlink.ts";
import { assertEquals, assert } from "../../testing/asserts.ts";
import * as path from "../path.ts";
@@ -13,7 +12,7 @@ if (Deno.build.os === "windows") {
Deno.symlinkSync(oldname, newname);
}
-test({
+Deno.test({
name: "readlinkSuccess",
async fn() {
const data = await new Promise((res, rej) => {
@@ -30,7 +29,7 @@ test({
},
});
-test({
+Deno.test({
name: "readlinkEncodeBufferSuccess",
async fn() {
const data = await new Promise((res, rej) => {
@@ -47,7 +46,7 @@ test({
},
});
-test({
+Deno.test({
name: "readlinkSyncSuccess",
fn() {
const data = readlinkSync(newname);
@@ -56,7 +55,7 @@ test({
},
});
-test({
+Deno.test({
name: "readlinkEncodeBufferSuccess",
fn() {
const data = readlinkSync(newname, { encoding: "buffer" });
diff --git a/std/node/_fs/_fs_writeFile_test.ts b/std/node/_fs/_fs_writeFile_test.ts
index 486c55fa1..81913d0b0 100644
--- a/std/node/_fs/_fs_writeFile_test.ts
+++ b/std/node/_fs/_fs_writeFile_test.ts
@@ -1,6 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-const { test } = Deno;
-
import {
assert,
assertEquals,
@@ -13,7 +11,7 @@ import * as path from "../../path/mod.ts";
const testDataDir = path.resolve(path.join("node", "_fs", "testdata"));
const decoder = new TextDecoder("utf-8");
-test("Callback must be a function error", function fn() {
+Deno.test("Callback must be a function error", function fn() {
assertThrows(
() => {
writeFile("some/path", "some data", "utf8");
@@ -23,7 +21,7 @@ test("Callback must be a function error", function fn() {
);
});
-test("Invalid encoding results in error()", function testEncodingErrors() {
+Deno.test("Invalid encoding results in error()", function testEncodingErrors() {
assertThrows(
() => {
writeFile("some/path", "some data", "made-up-encoding", () => {});
@@ -66,82 +64,91 @@ test("Invalid encoding results in error()", function testEncodingErrors() {
);
});
-test("Unsupported encoding results in error()", function testUnsupportedEncoding() {
- assertThrows(
- () => {
- writeFile("some/path", "some data", "hex", () => {});
- },
- Error,
- `Not implemented: "hex" encoding`
- );
-
- assertThrows(
- () => {
- writeFileSync("some/path", "some data", "hex");
- },
- Error,
- `Not implemented: "hex" encoding`
- );
-
- assertThrows(
- () => {
- writeFile(
- "some/path",
- "some data",
- {
+Deno.test(
+ "Unsupported encoding results in error()",
+ function testUnsupportedEncoding() {
+ assertThrows(
+ () => {
+ writeFile("some/path", "some data", "hex", () => {});
+ },
+ Error,
+ `Not implemented: "hex" encoding`
+ );
+
+ assertThrows(
+ () => {
+ writeFileSync("some/path", "some data", "hex");
+ },
+ Error,
+ `Not implemented: "hex" encoding`
+ );
+
+ assertThrows(
+ () => {
+ writeFile(
+ "some/path",
+ "some data",
+ {
+ encoding: "base64",
+ },
+ () => {}
+ );
+ },
+ Error,
+ `Not implemented: "base64" encoding`
+ );
+
+ assertThrows(
+ () => {
+ writeFileSync("some/path", "some data", {
encoding: "base64",
- },
- () => {}
- );
- },
- Error,
- `Not implemented: "base64" encoding`
- );
+ });
+ },
+ Error,
+ `Not implemented: "base64" encoding`
+ );
+ }
+);
+
+Deno.test(
+ "Data is written to correct rid",
+ async function testCorrectWriteUsingRid() {
+ const tempFile: string = await Deno.makeTempFile();
+ const file: Deno.File = await Deno.open(tempFile, {
+ create: true,
+ write: true,
+ read: true,
+ });
- assertThrows(
- () => {
- writeFileSync("some/path", "some data", {
- encoding: "base64",
+ await new Promise((resolve, reject) => {
+ writeFile(file.rid, "hello world", (err) => {
+ if (err) return reject(err);
+ resolve();
});
- },
- Error,
- `Not implemented: "base64" encoding`
- );
-});
-
-test("Data is written to correct rid", async function testCorrectWriteUsingRid() {
- const tempFile: string = await Deno.makeTempFile();
- const file: Deno.File = await Deno.open(tempFile, {
- create: true,
- write: true,
- read: true,
- });
-
- await new Promise((resolve, reject) => {
- writeFile(file.rid, "hello world", (err) => {
- if (err) return reject(err);
- resolve();
});
- });
- Deno.close(file.rid);
-
- const data = await Deno.readFile(tempFile);
- await Deno.remove(tempFile);
- assertEquals(decoder.decode(data), "hello world");
-});
-
-test("Data is written to correct file", async function testCorrectWriteUsingPath() {
- const res = await new Promise((resolve) => {
- writeFile("_fs_writeFile_test_file.txt", "hello world", resolve);
- });
+ Deno.close(file.rid);
+
+ const data = await Deno.readFile(tempFile);
+ await Deno.remove(tempFile);
+ assertEquals(decoder.decode(data), "hello world");
+ }
+);
+
+Deno.test(
+ "Data is written to correct file",
+ async function testCorrectWriteUsingPath() {
+ const res = await new Promise((resolve) => {
+ writeFile("_fs_writeFile_test_file.txt", "hello world", resolve);
+ });
- const data = await Deno.readFile("_fs_writeFile_test_file.txt");
- await Deno.remove("_fs_writeFile_test_file.txt");
- assertEquals(res, null);
- assertEquals(decoder.decode(data), "hello world");
-});
+ const data = await Deno.readFile("_fs_writeFile_test_file.txt");
+ await Deno.remove("_fs_writeFile_test_file.txt");
+ assertEquals(res, null);
+ assertEquals(decoder.decode(data), "hello world");
+ }
+);
-test("Path can be an URL", async function testCorrectWriteUsingURL() {
+Deno.test("Path can be an URL", async function testCorrectWriteUsingURL() {
const url = new URL(
Deno.build.os === "windows"
? "file:///" +
@@ -162,7 +169,7 @@ test("Path can be an URL", async function testCorrectWriteUsingURL() {
assertEquals(decoder.decode(data), "hello world");
});
-test("Mode is correctly set", async function testCorrectFileMode() {
+Deno.test("Mode is correctly set", async function testCorrectFileMode() {
if (Deno.build.os === "windows") return;
const filename = "_fs_writeFile_test_file.txt";
@@ -177,57 +184,66 @@ test("Mode is correctly set", async function testCorrectFileMode() {
assertEquals(fileInfo.mode & 0o777, 0o777);
});
-test("Mode is not set when rid is passed", async function testCorrectFileModeRid() {
- if (Deno.build.os === "windows") return;
-
- const filename: string = await Deno.makeTempFile();
- const file: Deno.File = await Deno.open(filename, {
- create: true,
- write: true,
- read: true,
- });
+Deno.test(
+ "Mode is not set when rid is passed",
+ async function testCorrectFileModeRid() {
+ if (Deno.build.os === "windows") return;
- await new Promise((resolve, reject) => {
- writeFile(file.rid, "hello world", { mode: 0o777 }, (err) => {
- if (err) return reject(err);
- resolve();
+ const filename: string = await Deno.makeTempFile();
+ const file: Deno.File = await Deno.open(filename, {
+ create: true,
+ write: true,
+ read: true,
});
- });
- Deno.close(file.rid);
- const fileInfo = await Deno.stat(filename);
- await Deno.remove(filename);
- assert(fileInfo.mode);
- assertNotEquals(fileInfo.mode & 0o777, 0o777);
-});
-
-test("Data is written synchronously to correct rid", function testCorrectWriteSyncUsingRid() {
- const tempFile: string = Deno.makeTempFileSync();
- const file: Deno.File = Deno.openSync(tempFile, {
- create: true,
- write: true,
- read: true,
- });
+ await new Promise((resolve, reject) => {
+ writeFile(file.rid, "hello world", { mode: 0o777 }, (err) => {
+ if (err) return reject(err);
+ resolve();
+ });
+ });
+ Deno.close(file.rid);
+
+ const fileInfo = await Deno.stat(filename);
+ await Deno.remove(filename);
+ assert(fileInfo.mode);
+ assertNotEquals(fileInfo.mode & 0o777, 0o777);
+ }
+);
+
+Deno.test(
+ "Data is written synchronously to correct rid",
+ function testCorrectWriteSyncUsingRid() {
+ const tempFile: string = Deno.makeTempFileSync();
+ const file: Deno.File = Deno.openSync(tempFile, {
+ create: true,
+ write: true,
+ read: true,
+ });
- writeFileSync(file.rid, "hello world");
- Deno.close(file.rid);
+ writeFileSync(file.rid, "hello world");
+ Deno.close(file.rid);
- const data = Deno.readFileSync(tempFile);
- Deno.removeSync(tempFile);
- assertEquals(decoder.decode(data), "hello world");
-});
+ const data = Deno.readFileSync(tempFile);
+ Deno.removeSync(tempFile);
+ assertEquals(decoder.decode(data), "hello world");
+ }
+);
-test("Data is written synchronously to correct file", function testCorrectWriteSyncUsingPath() {
- const file = "_fs_writeFileSync_test_file";
+Deno.test(
+ "Data is written synchronously to correct file",
+ function testCorrectWriteSyncUsingPath() {
+ const file = "_fs_writeFileSync_test_file";
- writeFileSync(file, "hello world");
+ writeFileSync(file, "hello world");
- const data = Deno.readFileSync(file);
- Deno.removeSync(file);
- assertEquals(decoder.decode(data), "hello world");
-});
+ const data = Deno.readFileSync(file);
+ Deno.removeSync(file);
+ assertEquals(decoder.decode(data), "hello world");
+ }
+);
-test("sync: Path can be an URL", function testCorrectWriteSyncUsingURL() {
+Deno.test("sync: Path can be an URL", function testCorrectWriteSyncUsingURL() {
const filePath = path.join(
testDataDir,
"_fs_writeFileSync_test_file_url.txt"
@@ -244,14 +260,17 @@ test("sync: Path can be an URL", function testCorrectWriteSyncUsingURL() {
assertEquals(decoder.decode(data), "hello world");
});
-test("Mode is correctly set when writing synchronously", function testCorrectFileModeSync() {
- if (Deno.build.os === "windows") return;
- const filename = "_fs_writeFileSync_test_file.txt";
+Deno.test(
+ "Mode is correctly set when writing synchronously",
+ function testCorrectFileModeSync() {
+ if (Deno.build.os === "windows") return;
+ const filename = "_fs_writeFileSync_test_file.txt";
- writeFileSync(filename, "hello world", { mode: 0o777 });
+ writeFileSync(filename, "hello world", { mode: 0o777 });
- const fileInfo = Deno.statSync(filename);
- Deno.removeSync(filename);
- assert(fileInfo && fileInfo.mode);
- assertEquals(fileInfo.mode & 0o777, 0o777);
-});
+ const fileInfo = Deno.statSync(filename);
+ Deno.removeSync(filename);
+ assert(fileInfo && fileInfo.mode);
+ assertEquals(fileInfo.mode & 0o777, 0o777);
+ }
+);
diff --git a/std/node/_fs/promises/_fs_readFile_test.ts b/std/node/_fs/promises/_fs_readFile_test.ts
index ac3c8fdda..c92907fec 100644
--- a/std/node/_fs/promises/_fs_readFile_test.ts
+++ b/std/node/_fs/promises/_fs_readFile_test.ts
@@ -1,4 +1,3 @@
-const { test } = Deno;
import { readFile } from "./_fs_readFile.ts";
import * as path from "../../../path/mod.ts";
import { assertEquals, assert } from "../../../testing/asserts.ts";
@@ -7,28 +6,28 @@ const testData = path.resolve(
path.join("node", "_fs", "testdata", "hello.txt")
);
-test("readFileSuccess", async function () {
+Deno.test("readFileSuccess", async function () {
const data = await readFile(testData);
assert(data instanceof Uint8Array);
assertEquals(new TextDecoder().decode(data as Uint8Array), "hello world");
});
-test("readFileEncodeUtf8Success", async function () {
+Deno.test("readFileEncodeUtf8Success", async function () {
const data = await readFile(testData, { encoding: "utf8" });
assertEquals(typeof data, "string");
assertEquals(data as string, "hello world");
});
-test("readFileEncodingAsString", async function () {
+Deno.test("readFileEncodingAsString", async function () {
const data = await readFile(testData, "utf8");
assertEquals(typeof data, "string");
assertEquals(data as string, "hello world");
});
-test("readFileError", async function () {
+Deno.test("readFileError", async function () {
try {
await readFile("invalid-file", "utf8");
} catch (e) {
diff --git a/std/node/_fs/promises/_fs_writeFile_test.ts b/std/node/_fs/promises/_fs_writeFile_test.ts
index 171dbeb2c..574bbfc35 100644
--- a/std/node/_fs/promises/_fs_writeFile_test.ts
+++ b/std/node/_fs/promises/_fs_writeFile_test.ts
@@ -1,6 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-const { test } = Deno;
-
import {
assert,
assertEquals,
@@ -11,7 +9,7 @@ import { writeFile } from "./_fs_writeFile.ts";
const decoder = new TextDecoder("utf-8");
-test("Invalid encoding results in error()", function testEncodingErrors() {
+Deno.test("Invalid encoding results in error()", function testEncodingErrors() {
assertThrowsAsync(
async () => {
await writeFile("some/path", "some data", "made-up-encoding");
@@ -30,53 +28,62 @@ test("Invalid encoding results in error()", function testEncodingErrors() {
);
});
-test("Unsupported encoding results in error()", function testUnsupportedEncoding() {
- assertThrowsAsync(
- async () => {
- await writeFile("some/path", "some data", "hex");
- },
- Error,
- `Not implemented: "hex" encoding`
- );
- assertThrowsAsync(
- async () => {
- await writeFile("some/path", "some data", {
- encoding: "base64",
- });
- },
- Error,
- `Not implemented: "base64" encoding`
- );
-});
-
-test("Data is written to correct rid", async function testCorrectWriteUsingRid() {
- const tempFile: string = await Deno.makeTempFile();
- const file: Deno.File = await Deno.open(tempFile, {
- create: true,
- write: true,
- read: true,
- });
-
- await writeFile(file.rid, "hello world");
- Deno.close(file.rid);
-
- const data = await Deno.readFile(tempFile);
- await Deno.remove(tempFile);
- assertEquals(decoder.decode(data), "hello world");
-});
-
-test("Data is written to correct file", async function testCorrectWriteUsingPath() {
- const openResourcesBeforeWrite: Deno.ResourceMap = Deno.resources();
-
- await writeFile("_fs_writeFile_test_file.txt", "hello world");
-
- assertEquals(Deno.resources(), openResourcesBeforeWrite);
- const data = await Deno.readFile("_fs_writeFile_test_file.txt");
- await Deno.remove("_fs_writeFile_test_file.txt");
- assertEquals(decoder.decode(data), "hello world");
-});
-
-test("Mode is correctly set", async function testCorrectFileMode() {
+Deno.test(
+ "Unsupported encoding results in error()",
+ function testUnsupportedEncoding() {
+ assertThrowsAsync(
+ async () => {
+ await writeFile("some/path", "some data", "hex");
+ },
+ Error,
+ `Not implemented: "hex" encoding`
+ );
+ assertThrowsAsync(
+ async () => {
+ await writeFile("some/path", "some data", {
+ encoding: "base64",
+ });
+ },
+ Error,
+ `Not implemented: "base64" encoding`
+ );
+ }
+);
+
+Deno.test(
+ "Data is written to correct rid",
+ async function testCorrectWriteUsingRid() {
+ const tempFile: string = await Deno.makeTempFile();
+ const file: Deno.File = await Deno.open(tempFile, {
+ create: true,
+ write: true,
+ read: true,
+ });
+
+ await writeFile(file.rid, "hello world");
+ Deno.close(file.rid);
+
+ const data = await Deno.readFile(tempFile);
+ await Deno.remove(tempFile);
+ assertEquals(decoder.decode(data), "hello world");
+ }
+);
+
+Deno.test(
+ "Data is written to correct file",
+ async function testCorrectWriteUsingPath() {
+ const openResourcesBeforeWrite: Deno.ResourceMap = Deno.resources();
+
+ await writeFile("_fs_writeFile_test_file.txt", "hello world");
+
+ assertEquals(Deno.resources(), openResourcesBeforeWrite);
+ const data = await Deno.readFile("_fs_writeFile_test_file.txt");
+ await Deno.remove("_fs_writeFile_test_file.txt");
+ assertEquals(decoder.decode(data), "hello world");
+ }
+);
+
+Deno.test("Mode is correctly set", async function testCorrectFileMode() {
if (Deno.build.os === "windows") return;
const filename = "_fs_writeFile_test_file.txt";
await writeFile(filename, "hello world", { mode: 0o777 });
@@ -87,21 +94,24 @@ test("Mode is correctly set", async function testCorrectFileMode() {
assertEquals(fileInfo.mode & 0o777, 0o777);
});
-test("Mode is not set when rid is passed", async function testCorrectFileModeRid() {
- if (Deno.build.os === "windows") return;
-
- const filename: string = await Deno.makeTempFile();
- const file: Deno.File = await Deno.open(filename, {
- create: true,
- write: true,
- read: true,
- });
-
- await writeFile(file.rid, "hello world", { mode: 0o777 });
- Deno.close(file.rid);
-
- const fileInfo = await Deno.stat(filename);
- await Deno.remove(filename);
- assert(fileInfo.mode);
- assertNotEquals(fileInfo.mode & 0o777, 0o777);
-});
+Deno.test(
+ "Mode is not set when rid is passed",
+ async function testCorrectFileModeRid() {
+ if (Deno.build.os === "windows") return;
+
+ const filename: string = await Deno.makeTempFile();
+ const file: Deno.File = await Deno.open(filename, {
+ create: true,
+ write: true,
+ read: true,
+ });
+
+ await writeFile(file.rid, "hello world", { mode: 0o777 });
+ Deno.close(file.rid);
+
+ const fileInfo = await Deno.stat(filename);
+ await Deno.remove(filename);
+ assert(fileInfo.mode);
+ assertNotEquals(fileInfo.mode & 0o777, 0o777);
+ }
+);
diff --git a/std/node/_util/_util_callbackify_test.ts b/std/node/_util/_util_callbackify_test.ts
index 630e4d0e7..d6a5d8664 100644
--- a/std/node/_util/_util_callbackify_test.ts
+++ b/std/node/_util/_util_callbackify_test.ts
@@ -20,8 +20,6 @@
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-const { test } = Deno;
import { assert, assertStrictEquals } from "../../testing/asserts.ts";
import { callbackify } from "./_util_callbackify.ts";
@@ -76,159 +74,174 @@ class TestQueue {
}
}
-test("callbackify passes the resolution value as the second argument to the callback", async () => {
- const testQueue = new TestQueue();
+Deno.test(
+ "callbackify passes the resolution value as the second argument to the callback",
+ async () => {
+ const testQueue = new TestQueue();
- for (const value of values) {
- // eslint-disable-next-line require-await
- async function asyncFn(): Promise<typeof value> {
- return value;
- }
- const cbAsyncFn = callbackify(asyncFn);
- testQueue.enqueue((done) => {
- cbAsyncFn((err: unknown, ret: unknown) => {
- assertStrictEquals(err, null);
- assertStrictEquals(ret, value);
- done();
+ for (const value of values) {
+ // eslint-disable-next-line require-await
+ async function asyncFn(): Promise<typeof value> {
+ return value;
+ }
+ const cbAsyncFn = callbackify(asyncFn);
+ testQueue.enqueue((done) => {
+ cbAsyncFn((err: unknown, ret: unknown) => {
+ assertStrictEquals(err, null);
+ assertStrictEquals(ret, value);
+ done();
+ });
});
- });
- function promiseFn(): Promise<typeof value> {
- return Promise.resolve(value);
- }
- const cbPromiseFn = callbackify(promiseFn);
- testQueue.enqueue((done) => {
- cbPromiseFn((err: unknown, ret: unknown) => {
- assertStrictEquals(err, null);
- assertStrictEquals(ret, value);
- done();
+ function promiseFn(): Promise<typeof value> {
+ return Promise.resolve(value);
+ }
+ const cbPromiseFn = callbackify(promiseFn);
+ testQueue.enqueue((done) => {
+ cbPromiseFn((err: unknown, ret: unknown) => {
+ assertStrictEquals(err, null);
+ assertStrictEquals(ret, value);
+ done();
+ });
});
- });
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- function thenableFn(): PromiseLike<any> {
- return {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- then(onfulfilled): PromiseLike<any> {
- assert(onfulfilled);
- onfulfilled(value);
- return this;
- },
- };
- }
- const cbThenableFn = callbackify(thenableFn);
- testQueue.enqueue((done) => {
- cbThenableFn((err: unknown, ret: unknown) => {
- assertStrictEquals(err, null);
- assertStrictEquals(ret, value);
- done();
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ function thenableFn(): PromiseLike<any> {
+ return {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ then(onfulfilled): PromiseLike<any> {
+ assert(onfulfilled);
+ onfulfilled(value);
+ return this;
+ },
+ };
+ }
+ const cbThenableFn = callbackify(thenableFn);
+ testQueue.enqueue((done) => {
+ cbThenableFn((err: unknown, ret: unknown) => {
+ assertStrictEquals(err, null);
+ assertStrictEquals(ret, value);
+ done();
+ });
});
- });
- }
+ }
- await testQueue.waitForCompletion();
-});
+ await testQueue.waitForCompletion();
+ }
+);
-test("callbackify passes the rejection value as the first argument to the callback", async () => {
- const testQueue = new TestQueue();
+Deno.test(
+ "callbackify passes the rejection value as the first argument to the callback",
+ async () => {
+ const testQueue = new TestQueue();
- for (const value of values) {
- // eslint-disable-next-line require-await
- async function asyncFn(): Promise<never> {
- return Promise.reject(value);
- }
- const cbAsyncFn = callbackify(asyncFn);
- assertStrictEquals(cbAsyncFn.length, 1);
- assertStrictEquals(cbAsyncFn.name, "asyncFnCallbackified");
- testQueue.enqueue((done) => {
- cbAsyncFn((err: unknown, ret: unknown) => {
- assertStrictEquals(ret, undefined);
- if (err instanceof Error) {
- if ("reason" in err) {
- assert(!value);
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- assertStrictEquals((err as any).code, "ERR_FALSY_VALUE_REJECTION");
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- assertStrictEquals((err as any).reason, value);
+ for (const value of values) {
+ // eslint-disable-next-line require-await
+ async function asyncFn(): Promise<never> {
+ return Promise.reject(value);
+ }
+ const cbAsyncFn = callbackify(asyncFn);
+ assertStrictEquals(cbAsyncFn.length, 1);
+ assertStrictEquals(cbAsyncFn.name, "asyncFnCallbackified");
+ testQueue.enqueue((done) => {
+ cbAsyncFn((err: unknown, ret: unknown) => {
+ assertStrictEquals(ret, undefined);
+ if (err instanceof Error) {
+ if ("reason" in err) {
+ assert(!value);
+ assertStrictEquals(
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (err as any).code,
+ "ERR_FALSY_VALUE_REJECTION"
+ );
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ assertStrictEquals((err as any).reason, value);
+ } else {
+ assertStrictEquals(String(value).endsWith(err.message), true);
+ }
} else {
- assertStrictEquals(String(value).endsWith(err.message), true);
+ assertStrictEquals(err, value);
}
- } else {
- assertStrictEquals(err, value);
- }
- done();
+ done();
+ });
});
- });
- function promiseFn(): Promise<never> {
- return Promise.reject(value);
- }
- const obj = {};
- Object.defineProperty(promiseFn, "name", {
- value: obj,
- writable: false,
- enumerable: false,
- configurable: true,
- });
+ function promiseFn(): Promise<never> {
+ return Promise.reject(value);
+ }
+ const obj = {};
+ Object.defineProperty(promiseFn, "name", {
+ value: obj,
+ writable: false,
+ enumerable: false,
+ configurable: true,
+ });
- const cbPromiseFn = callbackify(promiseFn);
- assertStrictEquals(promiseFn.name, obj);
- testQueue.enqueue((done) => {
- cbPromiseFn((err: unknown, ret: unknown) => {
- assertStrictEquals(ret, undefined);
- if (err instanceof Error) {
- if ("reason" in err) {
- assert(!value);
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- assertStrictEquals((err as any).code, "ERR_FALSY_VALUE_REJECTION");
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- assertStrictEquals((err as any).reason, value);
+ const cbPromiseFn = callbackify(promiseFn);
+ assertStrictEquals(promiseFn.name, obj);
+ testQueue.enqueue((done) => {
+ cbPromiseFn((err: unknown, ret: unknown) => {
+ assertStrictEquals(ret, undefined);
+ if (err instanceof Error) {
+ if ("reason" in err) {
+ assert(!value);
+ assertStrictEquals(
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (err as any).code,
+ "ERR_FALSY_VALUE_REJECTION"
+ );
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ assertStrictEquals((err as any).reason, value);
+ } else {
+ assertStrictEquals(String(value).endsWith(err.message), true);
+ }
} else {
- assertStrictEquals(String(value).endsWith(err.message), true);
+ assertStrictEquals(err, value);
}
- } else {
- assertStrictEquals(err, value);
- }
- done();
+ done();
+ });
});
- });
-
- function thenableFn(): PromiseLike<never> {
- return {
- then(onfulfilled, onrejected): PromiseLike<never> {
- assert(onrejected);
- onrejected(value);
- return this;
- },
- };
- }
- const cbThenableFn = callbackify(thenableFn);
- testQueue.enqueue((done) => {
- cbThenableFn((err: unknown, ret: unknown) => {
- assertStrictEquals(ret, undefined);
- if (err instanceof Error) {
- if ("reason" in err) {
- assert(!value);
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- assertStrictEquals((err as any).code, "ERR_FALSY_VALUE_REJECTION");
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- assertStrictEquals((err as any).reason, value);
+ function thenableFn(): PromiseLike<never> {
+ return {
+ then(onfulfilled, onrejected): PromiseLike<never> {
+ assert(onrejected);
+ onrejected(value);
+ return this;
+ },
+ };
+ }
+
+ const cbThenableFn = callbackify(thenableFn);
+ testQueue.enqueue((done) => {
+ cbThenableFn((err: unknown, ret: unknown) => {
+ assertStrictEquals(ret, undefined);
+ if (err instanceof Error) {
+ if ("reason" in err) {
+ assert(!value);
+ assertStrictEquals(
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (err as any).code,
+ "ERR_FALSY_VALUE_REJECTION"
+ );
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ assertStrictEquals((err as any).reason, value);
+ } else {
+ assertStrictEquals(String(value).endsWith(err.message), true);
+ }
} else {
- assertStrictEquals(String(value).endsWith(err.message), true);
+ assertStrictEquals(err, value);
}
- } else {
- assertStrictEquals(err, value);
- }
- done();
+ done();
+ });
});
- });
- }
+ }
- await testQueue.waitForCompletion();
-});
+ await testQueue.waitForCompletion();
+ }
+);
-test("callbackify passes arguments to the original", async () => {
+Deno.test("callbackify passes arguments to the original", async () => {
const testQueue = new TestQueue();
for (const value of values) {
@@ -276,7 +289,7 @@ test("callbackify passes arguments to the original", async () => {
await testQueue.waitForCompletion();
});
-test("callbackify preserves the `this` binding", async () => {
+Deno.test("callbackify preserves the `this` binding", async () => {
const testQueue = new TestQueue();
for (const value of values) {
@@ -325,7 +338,7 @@ test("callbackify preserves the `this` binding", async () => {
await testQueue.waitForCompletion();
});
-test("callbackify throws with non-function inputs", () => {
+Deno.test("callbackify throws with non-function inputs", () => {
["foo", null, undefined, false, 0, {}, Symbol(), []].forEach((value) => {
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -344,31 +357,34 @@ test("callbackify throws with non-function inputs", () => {
});
});
-test("callbackify returns a function that throws if the last argument is not a function", () => {
- // eslint-disable-next-line require-await
- async function asyncFn(): Promise<number> {
- return 42;
- }
+Deno.test(
+ "callbackify returns a function that throws if the last argument is not a function",
+ () => {
+ // eslint-disable-next-line require-await
+ async function asyncFn(): Promise<number> {
+ return 42;
+ }
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const cb = callbackify(asyncFn) as any;
- const args: unknown[] = [];
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const cb = callbackify(asyncFn) as any;
+ const args: unknown[] = [];
- ["foo", null, undefined, false, 0, {}, Symbol(), []].forEach((value) => {
- args.push(value);
+ ["foo", null, undefined, false, 0, {}, Symbol(), []].forEach((value) => {
+ args.push(value);
- try {
- cb(...args);
- throw Error("We should never reach this error");
- } catch (err) {
- assert(err instanceof TypeError);
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- assertStrictEquals((err as any).code, "ERR_INVALID_ARG_TYPE");
- assertStrictEquals(err.name, "TypeError");
- assertStrictEquals(
- err.message,
- "The last argument must be of type function."
- );
- }
- });
-});
+ try {
+ cb(...args);
+ throw Error("We should never reach this error");
+ } catch (err) {
+ assert(err instanceof TypeError);
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ assertStrictEquals((err as any).code, "ERR_INVALID_ARG_TYPE");
+ assertStrictEquals(err.name, "TypeError");
+ assertStrictEquals(
+ err.message,
+ "The last argument must be of type function."
+ );
+ }
+ });
+ }
+);
diff --git a/std/node/_util/_util_promisify_test.ts b/std/node/_util/_util_promisify_test.ts
index a583d8cfe..c6dbbd45a 100644
--- a/std/node/_util/_util_promisify_test.ts
+++ b/std/node/_util/_util_promisify_test.ts
@@ -20,27 +20,26 @@
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
import {
assert,
assertEquals,
assertStrictEquals,
assertThrowsAsync,
} from "../../testing/asserts.ts";
-
import { promisify } from "./_util_promisify.ts";
import * as fs from "../fs.ts";
-const { test } = Deno;
-
const readFile = promisify(fs.readFile);
const customPromisifyArgs = Symbol.for("deno.nodejs.util.promisify.customArgs");
-test("Errors should reject the promise", async function testPromiseRejection() {
- await assertThrowsAsync(() => readFile("/dontexist"), Deno.errors.NotFound);
-});
+Deno.test(
+ "Errors should reject the promise",
+ async function testPromiseRejection() {
+ await assertThrowsAsync(() => readFile("/dontexist"), Deno.errors.NotFound);
+ }
+);
-test("Promisify.custom", async function testPromisifyCustom() {
+Deno.test("Promisify.custom", async function testPromisifyCustom() {
function fn(): void {}
function promisifedFn(): void {}
@@ -56,7 +55,7 @@ test("Promisify.custom", async function testPromisifyCustom() {
await promisifiedFnB;
});
-test("promiisfy.custom symbol", function testPromisifyCustomSymbol() {
+Deno.test("promiisfy.custom symbol", function testPromisifyCustomSymbol() {
function fn(): void {}
function promisifiedFn(): void {}
@@ -72,7 +71,7 @@ test("promiisfy.custom symbol", function testPromisifyCustomSymbol() {
assertStrictEquals(promisify(promisify(fn)), promisifiedFn);
});
-test("Invalid argument should throw", function testThrowInvalidArgument() {
+Deno.test("Invalid argument should throw", function testThrowInvalidArgument() {
function fn(): void {}
// @ts-ignore TypeScript (as of 3.7) does not support indexing namespaces by symbol
fn[promisify.custom] = 42;
@@ -84,7 +83,7 @@ test("Invalid argument should throw", function testThrowInvalidArgument() {
}
});
-test("Custom promisify args", async function testPromisifyCustomArgs() {
+Deno.test("Custom promisify args", async function testPromisifyCustomArgs() {
const firstValue = 5;
const secondValue = 17;
@@ -99,50 +98,65 @@ test("Custom promisify args", async function testPromisifyCustomArgs() {
assertEquals(obj, { first: firstValue, second: secondValue });
});
-test("Multiple callback args without custom promisify args", async function testPromisifyWithoutCustomArgs() {
- function fn(callback: Function): void {
- callback(null, "foo", "bar");
+Deno.test(
+ "Multiple callback args without custom promisify args",
+ async function testPromisifyWithoutCustomArgs() {
+ function fn(callback: Function): void {
+ callback(null, "foo", "bar");
+ }
+ const value = await promisify(fn)();
+ assertStrictEquals(value, "foo");
}
- const value = await promisify(fn)();
- assertStrictEquals(value, "foo");
-});
+);
-test("Undefined resolved value", async function testPromisifyWithUndefinedResolvedValue() {
- function fn(callback: Function): void {
- callback(null);
+Deno.test(
+ "Undefined resolved value",
+ async function testPromisifyWithUndefinedResolvedValue() {
+ function fn(callback: Function): void {
+ callback(null);
+ }
+ const value = await promisify(fn)();
+ assertStrictEquals(value, undefined);
}
- const value = await promisify(fn)();
- assertStrictEquals(value, undefined);
-});
+);
-test("Undefined resolved value II", async function testPromisifyWithUndefinedResolvedValueII() {
- function fn(callback: Function): void {
- callback();
+Deno.test(
+ "Undefined resolved value II",
+ async function testPromisifyWithUndefinedResolvedValueII() {
+ function fn(callback: Function): void {
+ callback();
+ }
+ const value = await promisify(fn)();
+ assertStrictEquals(value, undefined);
}
- const value = await promisify(fn)();
- assertStrictEquals(value, undefined);
-});
+);
-test("Resolved value: number", async function testPromisifyWithNumberResolvedValue() {
- function fn(err: Error | null, val: number, callback: Function): void {
- callback(err, val);
+Deno.test(
+ "Resolved value: number",
+ async function testPromisifyWithNumberResolvedValue() {
+ function fn(err: Error | null, val: number, callback: Function): void {
+ callback(err, val);
+ }
+ const value = await promisify(fn)(null, 42);
+ assertStrictEquals(value, 42);
}
- const value = await promisify(fn)(null, 42);
- assertStrictEquals(value, 42);
-});
+);
-test("Rejected value", async function testPromisifyWithNumberRejectedValue() {
- function fn(err: Error | null, val: null, callback: Function): void {
- callback(err, val);
+Deno.test(
+ "Rejected value",
+ async function testPromisifyWithNumberRejectedValue() {
+ function fn(err: Error | null, val: null, callback: Function): void {
+ callback(err, val);
+ }
+ await assertThrowsAsync(
+ () => promisify(fn)(new Error("oops"), null),
+ Error,
+ "oops"
+ );
}
- await assertThrowsAsync(
- () => promisify(fn)(new Error("oops"), null),
- Error,
- "oops"
- );
-});
+);
-test("Rejected value", async function testPromisifyWithAsObjectMethod() {
+Deno.test("Rejected value", async function testPromisifyWithAsObjectMethod() {
const o: { fn?: Function } = {};
const fn = promisify(function (cb: Function): void {
// @ts-ignore TypeScript
@@ -155,21 +169,26 @@ test("Rejected value", async function testPromisifyWithAsObjectMethod() {
assert(val);
});
-test("Multiple callback", async function testPromisifyWithMultipleCallback() {
- const err = new Error("Should not have called the callback with the error.");
- const stack = err.stack;
-
- const fn = promisify(function (cb: Function): void {
- cb(null);
- cb(err);
- });
-
- await fn();
- await Promise.resolve();
- return assertStrictEquals(stack, err.stack);
-});
+Deno.test(
+ "Multiple callback",
+ async function testPromisifyWithMultipleCallback() {
+ const err = new Error(
+ "Should not have called the callback with the error."
+ );
+ const stack = err.stack;
+
+ const fn = promisify(function (cb: Function): void {
+ cb(null);
+ cb(err);
+ });
+
+ await fn();
+ await Promise.resolve();
+ return assertStrictEquals(stack, err.stack);
+ }
+);
-test("Promisify a promise", function testPromisifyPromise() {
+Deno.test("Promisify a promise", function testPromisifyPromise() {
function c(): void {}
const a = promisify(function (): void {});
const b = promisify(a);
@@ -177,7 +196,7 @@ test("Promisify a promise", function testPromisifyPromise() {
assertStrictEquals(a, b);
});
-test("Test error", async function testInvalidArguments() {
+Deno.test("Test error", async function testInvalidArguments() {
let errToThrow;
const thrower = promisify(function (
@@ -198,7 +217,7 @@ test("Test error", async function testInvalidArguments() {
}
});
-test("Test invalid arguments", function testInvalidArguments() {
+Deno.test("Test invalid arguments", function testInvalidArguments() {
[undefined, null, true, 0, "str", {}, [], Symbol()].forEach((input) => {
try {
// @ts-ignore TypeScript
diff --git a/std/node/_util/_util_types_test.ts b/std/node/_util/_util_types_test.ts
index 2d4307e77..f6dfcfe89 100644
--- a/std/node/_util/_util_types_test.ts
+++ b/std/node/_util/_util_types_test.ts
@@ -20,8 +20,6 @@
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-const { test } = Deno;
import { assertStrictEquals } from "../../testing/asserts.ts";
import {
isDate,
@@ -68,19 +66,19 @@ import {
import * as testModuleNamespaceOpbject from "./_util_types.ts";
// isAnyArrayBuffer
-test("Should return true for valid ArrayBuffer types", () => {
+Deno.test("Should return true for valid ArrayBuffer types", () => {
assertStrictEquals(isAnyArrayBuffer(new ArrayBuffer(0)), true);
assertStrictEquals(isAnyArrayBuffer(new SharedArrayBuffer(0)), true);
});
-test("Should return false for invalid ArrayBuffer types", () => {
+Deno.test("Should return false for invalid ArrayBuffer types", () => {
assertStrictEquals(isAnyArrayBuffer({}), false);
assertStrictEquals(isAnyArrayBuffer([]), false);
assertStrictEquals(isAnyArrayBuffer(new Error()), false);
});
// isArrayBufferView
-test("Should return true for valid ArrayBufferView types", () => {
+Deno.test("Should return true for valid ArrayBufferView types", () => {
assertStrictEquals(isArrayBufferView(new Int8Array(0)), true);
assertStrictEquals(isArrayBufferView(new Uint8Array(0)), true);
assertStrictEquals(isArrayBufferView(new Uint8ClampedArray(0)), true);
@@ -93,7 +91,7 @@ test("Should return true for valid ArrayBufferView types", () => {
assertStrictEquals(isArrayBufferView(new DataView(new ArrayBuffer(0))), true);
});
-test("Should return false for invalid ArrayBufferView types", () => {
+Deno.test("Should return false for invalid ArrayBufferView types", () => {
assertStrictEquals(isArrayBufferView({}), false);
assertStrictEquals(isArrayBufferView([]), false);
assertStrictEquals(isArrayBufferView(new Error()), false);
@@ -103,18 +101,18 @@ test("Should return false for invalid ArrayBufferView types", () => {
// isArgumentsObject
// Note: not testable in TS
-test("Should return false for invalid Argument types", () => {
+Deno.test("Should return false for invalid Argument types", () => {
assertStrictEquals(isArgumentsObject({}), false);
assertStrictEquals(isArgumentsObject([]), false);
assertStrictEquals(isArgumentsObject(new Error()), false);
});
// isArrayBuffer
-test("Should return true for valid ArrayBuffer types", () => {
+Deno.test("Should return true for valid ArrayBuffer types", () => {
assertStrictEquals(isArrayBuffer(new ArrayBuffer(0)), true);
});
-test("Should return false for invalid ArrayBuffer types", () => {
+Deno.test("Should return false for invalid ArrayBuffer types", () => {
assertStrictEquals(isArrayBuffer(new SharedArrayBuffer(0)), false);
assertStrictEquals(isArrayBuffer({}), false);
assertStrictEquals(isArrayBuffer([]), false);
@@ -122,12 +120,12 @@ test("Should return false for invalid ArrayBuffer types", () => {
});
// isAsyncFunction
-test("Should return true for valid async function types", () => {
+Deno.test("Should return true for valid async function types", () => {
const asyncFunction = async (): Promise<void> => {};
assertStrictEquals(isAsyncFunction(asyncFunction), true);
});
-test("Should return false for invalid async function types", () => {
+Deno.test("Should return false for invalid async function types", () => {
const syncFunction = (): void => {};
assertStrictEquals(isAsyncFunction(syncFunction), false);
assertStrictEquals(isAsyncFunction({}), false);
@@ -136,34 +134,34 @@ test("Should return false for invalid async function types", () => {
});
// isBigInt64Array
-test("Should return true for valid BigInt64Array types", () => {
+Deno.test("Should return true for valid BigInt64Array types", () => {
assertStrictEquals(isBigInt64Array(new BigInt64Array()), true);
});
-test("Should return false for invalid BigInt64Array types", () => {
+Deno.test("Should return false for invalid BigInt64Array types", () => {
assertStrictEquals(isBigInt64Array(new BigUint64Array()), false);
assertStrictEquals(isBigInt64Array(new Float32Array()), false);
assertStrictEquals(isBigInt64Array(new Int32Array()), false);
});
// isBigUint64Array
-test("Should return true for valid isBigUint64Array types", () => {
+Deno.test("Should return true for valid isBigUint64Array types", () => {
assertStrictEquals(isBigUint64Array(new BigUint64Array()), true);
});
-test("Should return false for invalid isBigUint64Array types", () => {
+Deno.test("Should return false for invalid isBigUint64Array types", () => {
assertStrictEquals(isBigUint64Array(new BigInt64Array()), false);
assertStrictEquals(isBigUint64Array(new Float32Array()), false);
assertStrictEquals(isBigUint64Array(new Int32Array()), false);
});
// isBooleanObject
-test("Should return true for valid Boolean object types", () => {
+Deno.test("Should return true for valid Boolean object types", () => {
assertStrictEquals(isBooleanObject(new Boolean(false)), true);
assertStrictEquals(isBooleanObject(new Boolean(true)), true);
});
-test("Should return false for invalid isBigUint64Array types", () => {
+Deno.test("Should return false for invalid isBigUint64Array types", () => {
assertStrictEquals(isBooleanObject(false), false);
assertStrictEquals(isBooleanObject(true), false);
assertStrictEquals(isBooleanObject(Boolean(false)), false);
@@ -171,35 +169,35 @@ test("Should return false for invalid isBigUint64Array types", () => {
});
// isBoxedPrimitive
-test("Should return true for valid boxed primitive values", () => {
+Deno.test("Should return true for valid boxed primitive values", () => {
assertStrictEquals(isBoxedPrimitive(new Boolean(false)), true);
assertStrictEquals(isBoxedPrimitive(Object(Symbol("foo"))), true);
assertStrictEquals(isBoxedPrimitive(Object(BigInt(5))), true);
assertStrictEquals(isBoxedPrimitive(new String("foo")), true);
});
-test("Should return false for invalid boxed primitive values", () => {
+Deno.test("Should return false for invalid boxed primitive values", () => {
assertStrictEquals(isBoxedPrimitive(false), false);
assertStrictEquals(isBoxedPrimitive(Symbol("foo")), false);
});
// isDateView
-test("Should return true for valid DataView types", () => {
+Deno.test("Should return true for valid DataView types", () => {
assertStrictEquals(isDataView(new DataView(new ArrayBuffer(0))), true);
});
-test("Should return false for invalid DataView types", () => {
+Deno.test("Should return false for invalid DataView types", () => {
assertStrictEquals(isDataView(new Float64Array(0)), false);
});
// isDate
-test("Should return true for valid date types", () => {
+Deno.test("Should return true for valid date types", () => {
assertStrictEquals(isDate(new Date()), true);
assertStrictEquals(isDate(new Date(0)), true);
assertStrictEquals(isDate(new (eval("Date"))()), true);
});
-test("Should return false for invalid date types", () => {
+Deno.test("Should return false for invalid date types", () => {
assertStrictEquals(isDate(Date()), false);
assertStrictEquals(isDate({}), false);
assertStrictEquals(isDate([]), false);
@@ -208,34 +206,34 @@ test("Should return false for invalid date types", () => {
});
// isFloat32Array
-test("Should return true for valid Float32Array types", () => {
+Deno.test("Should return true for valid Float32Array types", () => {
assertStrictEquals(isFloat32Array(new Float32Array(0)), true);
});
-test("Should return false for invalid Float32Array types", () => {
+Deno.test("Should return false for invalid Float32Array types", () => {
assertStrictEquals(isFloat32Array(new ArrayBuffer(0)), false);
assertStrictEquals(isFloat32Array(new Float64Array(0)), false);
});
// isFloat64Array
-test("Should return true for valid Float64Array types", () => {
+Deno.test("Should return true for valid Float64Array types", () => {
assertStrictEquals(isFloat64Array(new Float64Array(0)), true);
});
-test("Should return false for invalid Float64Array types", () => {
+Deno.test("Should return false for invalid Float64Array types", () => {
assertStrictEquals(isFloat64Array(new ArrayBuffer(0)), false);
assertStrictEquals(isFloat64Array(new Uint8Array(0)), false);
});
// isGeneratorFunction
-test("Should return true for valid generator functions", () => {
+Deno.test("Should return true for valid generator functions", () => {
assertStrictEquals(
isGeneratorFunction(function* foo() {}),
true
);
});
-test("Should return false for invalid generator functions", () => {
+Deno.test("Should return false for invalid generator functions", () => {
assertStrictEquals(
isGeneratorFunction(function foo() {}),
false
@@ -243,12 +241,12 @@ test("Should return false for invalid generator functions", () => {
});
// isGeneratorObject
-test("Should return true for valid generator object types", () => {
+Deno.test("Should return true for valid generator object types", () => {
function* foo(): Iterator<void> {}
assertStrictEquals(isGeneratorObject(foo()), true);
});
-test("Should return false for invalid generation object types", () => {
+Deno.test("Should return false for invalid generation object types", () => {
assertStrictEquals(
isGeneratorObject(function* foo() {}),
false
@@ -256,52 +254,52 @@ test("Should return false for invalid generation object types", () => {
});
// isInt8Array
-test("Should return true for valid Int8Array types", () => {
+Deno.test("Should return true for valid Int8Array types", () => {
assertStrictEquals(isInt8Array(new Int8Array(0)), true);
});
-test("Should return false for invalid Int8Array types", () => {
+Deno.test("Should return false for invalid Int8Array types", () => {
assertStrictEquals(isInt8Array(new ArrayBuffer(0)), false);
assertStrictEquals(isInt8Array(new Float64Array(0)), false);
});
// isInt16Array
-test("Should return true for valid Int16Array types", () => {
+Deno.test("Should return true for valid Int16Array types", () => {
assertStrictEquals(isInt16Array(new Int16Array(0)), true);
});
-test("Should return false for invalid Int16Array type", () => {
+Deno.test("Should return false for invalid Int16Array type", () => {
assertStrictEquals(isInt16Array(new ArrayBuffer(0)), false);
assertStrictEquals(isInt16Array(new Float64Array(0)), false);
});
// isInt32Array
-test("Should return true for valid isInt32Array types", () => {
+Deno.test("Should return true for valid isInt32Array types", () => {
assertStrictEquals(isInt32Array(new Int32Array(0)), true);
});
-test("Should return false for invalid isInt32Array type", () => {
+Deno.test("Should return false for invalid isInt32Array type", () => {
assertStrictEquals(isInt32Array(new ArrayBuffer(0)), false);
assertStrictEquals(isInt32Array(new Float64Array(0)), false);
});
// isStringObject
-test("Should return true for valid String types", () => {
+Deno.test("Should return true for valid String types", () => {
assertStrictEquals(isStringObject(new String("")), true);
assertStrictEquals(isStringObject(new String("Foo")), true);
});
-test("Should return false for invalid String types", () => {
+Deno.test("Should return false for invalid String types", () => {
assertStrictEquals(isStringObject(""), false);
assertStrictEquals(isStringObject("Foo"), false);
});
// isMap
-test("Should return true for valid Map types", () => {
+Deno.test("Should return true for valid Map types", () => {
assertStrictEquals(isMap(new Map()), true);
});
-test("Should return false for invalid Map types", () => {
+Deno.test("Should return false for invalid Map types", () => {
assertStrictEquals(isMap({}), false);
assertStrictEquals(isMap([]), false);
assertStrictEquals(isMap(new Date()), false);
@@ -309,7 +307,7 @@ test("Should return false for invalid Map types", () => {
});
// isMapIterator
-test("Should return true for valid Map Iterator types", () => {
+Deno.test("Should return true for valid Map Iterator types", () => {
const map = new Map();
assertStrictEquals(isMapIterator(map.keys()), true);
assertStrictEquals(isMapIterator(map.values()), true);
@@ -317,7 +315,7 @@ test("Should return true for valid Map Iterator types", () => {
assertStrictEquals(isMapIterator(map[Symbol.iterator]()), true);
});
-test("Should return false for invalid Map iterator types", () => {
+Deno.test("Should return false for invalid Map iterator types", () => {
assertStrictEquals(isMapIterator(new Map()), false);
assertStrictEquals(isMapIterator([]), false);
assertStrictEquals(isMapIterator(new Date()), false);
@@ -325,70 +323,70 @@ test("Should return false for invalid Map iterator types", () => {
});
// isModuleNamespaceObject
-test("Should return true for valid module namespace objects", () => {
+Deno.test("Should return true for valid module namespace objects", () => {
assertStrictEquals(isModuleNamespaceObject(testModuleNamespaceOpbject), true);
});
-test("Should return false for invalid module namespace objects", () => {
+Deno.test("Should return false for invalid module namespace objects", () => {
assertStrictEquals(isModuleNamespaceObject(assertStrictEquals), false);
});
// isNativeError
-test("Should return true for valid Error types", () => {
+Deno.test("Should return true for valid Error types", () => {
assertStrictEquals(isNativeError(new Error()), true);
assertStrictEquals(isNativeError(new TypeError()), true);
assertStrictEquals(isNativeError(new RangeError()), true);
});
-test("Should return false for invalid Error types", () => {
+Deno.test("Should return false for invalid Error types", () => {
assertStrictEquals(isNativeError(null), false);
assertStrictEquals(isNativeError(NaN), false);
});
// isNumberObject
-test("Should return true for valid number objects", () => {
+Deno.test("Should return true for valid number objects", () => {
assertStrictEquals(isNumberObject(new Number(0)), true);
});
-test("Should return false for invalid number types", () => {
+Deno.test("Should return false for invalid number types", () => {
assertStrictEquals(isNumberObject(0), false);
});
// isBigIntObject
-test("Should return true for valid number objects", () => {
+Deno.test("Should return true for valid number objects", () => {
assertStrictEquals(isBigIntObject(new Object(BigInt(42))), true);
});
-test("Should return false for invalid number types", () => {
+Deno.test("Should return false for invalid number types", () => {
assertStrictEquals(isBigIntObject(BigInt(42)), false);
});
// isPromise
-test("Should return true for valid Promise types", () => {
+Deno.test("Should return true for valid Promise types", () => {
assertStrictEquals(isPromise(Promise.resolve(42)), true);
});
-test("Should return false for invalid Promise types", () => {
+Deno.test("Should return false for invalid Promise types", () => {
assertStrictEquals(isPromise(new Object()), false);
});
// isRegExp
-test("Should return true for valid RegExp", () => {
+Deno.test("Should return true for valid RegExp", () => {
assertStrictEquals(isRegExp(/abc/), true);
assertStrictEquals(isRegExp(new RegExp("abc")), true);
});
-test("Should return false for invalid RegExp types", () => {
+Deno.test("Should return false for invalid RegExp types", () => {
assertStrictEquals(isRegExp({}), false);
assertStrictEquals(isRegExp("/abc/"), false);
});
// isSet
-test("Should return true for valid Set types", () => {
+Deno.test("Should return true for valid Set types", () => {
assertStrictEquals(isSet(new Set()), true);
});
-test("Should return false for invalid Set types", () => {
+Deno.test("Should return false for invalid Set types", () => {
assertStrictEquals(isSet({}), false);
assertStrictEquals(isSet([]), false);
assertStrictEquals(isSet(new Map()), false);
@@ -396,7 +394,7 @@ test("Should return false for invalid Set types", () => {
});
// isSetIterator
-test("Should return true for valid Set Iterator types", () => {
+Deno.test("Should return true for valid Set Iterator types", () => {
const set = new Set();
assertStrictEquals(isSetIterator(set.keys()), true);
assertStrictEquals(isSetIterator(set.values()), true);
@@ -404,7 +402,7 @@ test("Should return true for valid Set Iterator types", () => {
assertStrictEquals(isSetIterator(set[Symbol.iterator]()), true);
});
-test("Should return false for invalid Set Iterator types", () => {
+Deno.test("Should return false for invalid Set Iterator types", () => {
assertStrictEquals(isSetIterator(new Set()), false);
assertStrictEquals(isSetIterator([]), false);
assertStrictEquals(isSetIterator(new Map()), false);
@@ -412,100 +410,100 @@ test("Should return false for invalid Set Iterator types", () => {
});
// isSharedArrayBuffer
-test("Should return true for valid SharedArrayBuffer types", () => {
+Deno.test("Should return true for valid SharedArrayBuffer types", () => {
assertStrictEquals(isSharedArrayBuffer(new SharedArrayBuffer(0)), true);
});
-test("Should return false for invalid SharedArrayBuffer types", () => {
+Deno.test("Should return false for invalid SharedArrayBuffer types", () => {
assertStrictEquals(isSharedArrayBuffer(new ArrayBuffer(0)), false);
});
// isStringObject
-test("Should return true for valid String Object types", () => {
+Deno.test("Should return true for valid String Object types", () => {
assertStrictEquals(isStringObject(new String("")), true);
assertStrictEquals(isStringObject(new String("Foo")), true);
});
-test("Should return false for invalid String Object types", () => {
+Deno.test("Should return false for invalid String Object types", () => {
assertStrictEquals(isStringObject(""), false);
assertStrictEquals(isStringObject("Foo"), false);
});
// isSymbolObject
-test("Should return true for valid Symbol types", () => {
+Deno.test("Should return true for valid Symbol types", () => {
assertStrictEquals(isSymbolObject(Object(Symbol("foo"))), true);
});
-test("Should return false for invalid Symbol types", () => {
+Deno.test("Should return false for invalid Symbol types", () => {
assertStrictEquals(isSymbolObject(Symbol("foo")), false);
});
// isTypedArray
-test("Should return true for valid TypedArray types", () => {
+Deno.test("Should return true for valid TypedArray types", () => {
assertStrictEquals(isTypedArray(new Uint8Array(0)), true);
assertStrictEquals(isTypedArray(new Float64Array(0)), true);
});
-test("Should return false for invalid TypedArray types", () => {
+Deno.test("Should return false for invalid TypedArray types", () => {
assertStrictEquals(isTypedArray(new ArrayBuffer(0)), false);
});
// isUint8Array
-test("Should return true for valid Uint8Array types", () => {
+Deno.test("Should return true for valid Uint8Array types", () => {
assertStrictEquals(isUint8Array(new Uint8Array(0)), true);
});
-test("Should return false for invalid Uint8Array types", () => {
+Deno.test("Should return false for invalid Uint8Array types", () => {
assertStrictEquals(isUint8Array(new ArrayBuffer(0)), false);
assertStrictEquals(isUint8Array(new Float64Array(0)), false);
});
// isUint8ClampedArray
-test("Should return true for valid Uint8ClampedArray types", () => {
+Deno.test("Should return true for valid Uint8ClampedArray types", () => {
assertStrictEquals(isUint8ClampedArray(new Uint8ClampedArray(0)), true);
});
-test("Should return false for invalid Uint8Array types", () => {
+Deno.test("Should return false for invalid Uint8Array types", () => {
assertStrictEquals(isUint8ClampedArray(new ArrayBuffer(0)), false);
assertStrictEquals(isUint8ClampedArray(new Float64Array(0)), false);
});
// isUint16Array
-test("Should return true for valid isUint16Array types", () => {
+Deno.test("Should return true for valid isUint16Array types", () => {
assertStrictEquals(isUint16Array(new Uint16Array(0)), true);
});
-test("Should return false for invalid Uint16Array types", () => {
+Deno.test("Should return false for invalid Uint16Array types", () => {
assertStrictEquals(isUint16Array(new ArrayBuffer(0)), false);
assertStrictEquals(isUint16Array(new Float64Array(0)), false);
});
// isUint32Array
-test("Should return true for valid Uint32Array types", () => {
+Deno.test("Should return true for valid Uint32Array types", () => {
assertStrictEquals(isUint32Array(new Uint32Array(0)), true);
});
-test("Should return false for invalid isUint16Array types", () => {
+Deno.test("Should return false for invalid isUint16Array types", () => {
assertStrictEquals(isUint32Array(new ArrayBuffer(0)), false);
assertStrictEquals(isUint32Array(new Float64Array(0)), false);
});
// isWeakMap
-test("Should return true for valid WeakMap types", () => {
+Deno.test("Should return true for valid WeakMap types", () => {
assertStrictEquals(isWeakMap(new WeakMap()), true);
});
-test("Should return false for invalid WeakMap types", () => {
+Deno.test("Should return false for invalid WeakMap types", () => {
assertStrictEquals(isWeakMap(new Set()), false);
assertStrictEquals(isWeakMap(new Map()), false);
});
// isWeakSet
-test("Should return true for valid WeakSet types", () => {
+Deno.test("Should return true for valid WeakSet types", () => {
assertStrictEquals(isWeakSet(new WeakSet()), true);
});
-test("Should return false for invalid WeakSet types", () => {
+Deno.test("Should return false for invalid WeakSet types", () => {
assertStrictEquals(isWeakSet(new Set()), false);
assertStrictEquals(isWeakSet(new Map()), false);
});
diff --git a/std/node/events_test.ts b/std/node/events_test.ts
index 4b47686f4..58025ce84 100644
--- a/std/node/events_test.ts
+++ b/std/node/events_test.ts
@@ -1,4 +1,3 @@
-const { test } = Deno;
import {
assert,
assertEquals,
@@ -11,7 +10,7 @@ const shouldNeverBeEmitted: Function = () => {
fail("Should never be called");
};
-test({
+Deno.test({
name:
'When adding a new event, "eventListener" event is fired before adding the listener',
fn() {
@@ -32,7 +31,7 @@ test({
},
});
-test({
+Deno.test({
name:
'When removing a listenert, "removeListener" event is fired after removal',
fn() {
@@ -52,7 +51,7 @@ test({
},
});
-test({
+Deno.test({
name:
"Default max listeners is 10, but can be changed by direct assignment only",
fn() {
@@ -65,7 +64,7 @@ test({
},
});
-test({
+Deno.test({
name: "addListener adds a listener, and listener count is correct",
fn() {
const testEmitter = new EventEmitter();
@@ -76,7 +75,7 @@ test({
},
});
-test({
+Deno.test({
name: "Emitted events are called synchronously in the order they were added",
fn() {
const testEmitter = new EventEmitter();
@@ -103,7 +102,7 @@ test({
},
});
-test({
+Deno.test({
name: "Registered event names are returned as strings or Sybols",
fn() {
const testEmitter = new EventEmitter();
@@ -115,7 +114,7 @@ test({
},
});
-test({
+Deno.test({
name: "You can set and get max listeners",
fn() {
const testEmitter = new EventEmitter();
@@ -125,7 +124,7 @@ test({
},
});
-test({
+Deno.test({
name: "You can retrieve registered functions for an event",
fn() {
const testEmitter = new EventEmitter();
@@ -140,7 +139,7 @@ test({
},
});
-test({
+Deno.test({
name: "Off is alias for removeListener",
fn() {
const testEmitter = new EventEmitter();
@@ -151,7 +150,7 @@ test({
},
});
-test({
+Deno.test({
name: "Event registration can be chained",
fn() {
const testEmitter = new EventEmitter();
@@ -162,7 +161,7 @@ test({
},
});
-test({
+Deno.test({
name: "Events can be registered to only fire once",
fn() {
let eventsFired: string[] = [];
@@ -186,7 +185,7 @@ test({
},
});
-test({
+Deno.test({
name:
"You can inject a listener into the start of the stack, rather than at the end",
fn() {
@@ -206,7 +205,7 @@ test({
},
});
-test({
+Deno.test({
name: 'You can prepend a "once" listener',
fn() {
const eventsFired: string[] = [];
@@ -226,7 +225,7 @@ test({
},
});
-test({
+Deno.test({
name: "Remove all listeners, which can also be chained",
fn() {
const testEmitter = new EventEmitter();
@@ -245,7 +244,7 @@ test({
},
});
-test({
+Deno.test({
name: "Provide a non-existent event to removeAllListeners will do nothing",
fn() {
const testEmitter = new EventEmitter();
@@ -264,7 +263,7 @@ test({
},
});
-test({
+Deno.test({
name: "Remove individual listeners, which can also be chained",
fn() {
const testEmitter = new EventEmitter();
@@ -287,7 +286,7 @@ test({
},
});
-test({
+Deno.test({
name: "It is OK to try to remove non-existent listener",
fn() {
const testEmitter = new EventEmitter();
@@ -306,7 +305,7 @@ test({
},
});
-test({
+Deno.test({
name: "all listeners complete execution even if removed before execution",
fn() {
const testEmitter = new EventEmitter();
@@ -329,7 +328,7 @@ test({
},
});
-test({
+Deno.test({
name: 'Raw listener will return event listener or wrapped "once" function',
fn() {
const testEmitter = new EventEmitter();
@@ -352,7 +351,7 @@ test({
},
});
-test({
+Deno.test({
name:
"Once wrapped raw listeners may be executed multiple times, until the wrapper is executed",
fn() {
@@ -375,7 +374,7 @@ test({
},
});
-test({
+Deno.test({
name: "Can add once event listener to EventEmitter via standalone function",
async fn() {
const ee = new EventEmitter();
@@ -388,7 +387,7 @@ test({
},
});
-test({
+Deno.test({
name: "Can add once event listener to EventTarget via standalone function",
async fn() {
const et: EventTarget = new EventTarget();
@@ -402,7 +401,7 @@ test({
},
});
-test({
+Deno.test({
name: "Only valid integers are allowed for max listeners",
fn() {
const ee = new EventEmitter();
@@ -424,7 +423,7 @@ test({
},
});
-test({
+Deno.test({
name: "ErrorMonitor can spy on error events without consuming them",
fn() {
const ee = new EventEmitter();
@@ -462,7 +461,7 @@ test({
},
});
-test({
+Deno.test({
name: "asynchronous iteration of events are handled as expected",
async fn() {
const ee = new EventEmitter();
@@ -490,7 +489,7 @@ test({
},
});
-test({
+Deno.test({
name: "asynchronous error handling of emitted events works as expected",
async fn() {
const ee = new EventEmitter();
@@ -515,7 +514,7 @@ test({
},
});
-test({
+Deno.test({
name: "error thrown during asynchronous processing of events is handled",
async fn() {
const ee = new EventEmitter();
@@ -544,7 +543,7 @@ test({
},
});
-test({
+Deno.test({
name:
"error thrown in processing loop of asynchronous event prevents processing of additional events",
async fn() {
@@ -570,7 +569,7 @@ test({
},
});
-test({
+Deno.test({
name: "asynchronous iterator next() works as expected",
async fn() {
const ee = new EventEmitter();
@@ -610,7 +609,7 @@ test({
},
});
-test({
+Deno.test({
name: "async iterable throw handles various scenarios",
async fn() {
const ee = new EventEmitter();
diff --git a/std/node/module_test.ts b/std/node/module_test.ts
index b1a22c0f6..30441a58d 100644
--- a/std/node/module_test.ts
+++ b/std/node/module_test.ts
@@ -1,6 +1,4 @@
/* eslint-disable @typescript-eslint/no-var-requires */
-
-const { test } = Deno;
import {
assertEquals,
assert,
@@ -10,7 +8,7 @@ import { createRequire } from "./module.ts";
const require = createRequire(import.meta.url);
-test("requireSuccess", function () {
+Deno.test("requireSuccess", function () {
// Relative to import.meta.url
const result = require("./tests/cjs/cjs_a.js");
assert("helloA" in result);
@@ -23,14 +21,14 @@ test("requireSuccess", function () {
assertEquals(result.leftPad("pad", 4), " pad");
});
-test("requireCycle", function () {
+Deno.test("requireCycle", function () {
const resultA = require("./tests/cjs/cjs_cycle_a");
const resultB = require("./tests/cjs/cjs_cycle_b");
assert(resultA);
assert(resultB);
});
-test("requireBuiltin", function () {
+Deno.test("requireBuiltin", function () {
const fs = require("fs");
assert("readFileSync" in fs);
const { readFileSync, isNull, extname } = require("./tests/cjs/cjs_builtin");
@@ -42,18 +40,18 @@ test("requireBuiltin", function () {
assertEquals(extname("index.html"), ".html");
});
-test("requireIndexJS", function () {
+Deno.test("requireIndexJS", function () {
const { isIndex } = require("./tests/cjs");
assert(isIndex);
});
-test("requireNodeOs", function () {
+Deno.test("requireNodeOs", function () {
const os = require("os");
assert(os.arch);
assert(typeof os.arch() == "string");
});
-test("requireStack", function () {
+Deno.test("requireStack", function () {
const { hello } = require("./tests/cjs/cjs_throw");
try {
hello();
diff --git a/std/node/os_test.ts b/std/node/os_test.ts
index f0b9ca79d..11de777a9 100644
--- a/std/node/os_test.ts
+++ b/std/node/os_test.ts
@@ -1,50 +1,49 @@
-const { test } = Deno;
import { assert, assertThrows, assertEquals } from "../testing/asserts.ts";
import * as os from "./os.ts";
-test({
+Deno.test({
name: "build architecture is a string",
fn() {
assertEquals(typeof os.arch(), "string");
},
});
-test({
+Deno.test({
name: "home directory is a string",
fn() {
assertEquals(typeof os.homedir(), "string");
},
});
-test({
+Deno.test({
name: "tmp directory is a string",
fn() {
assertEquals(typeof os.tmpdir(), "string");
},
});
-test({
+Deno.test({
name: "hostname is a string",
fn() {
assertEquals(typeof os.hostname(), "string");
},
});
-test({
+Deno.test({
name: "platform is a string",
fn() {
assertEquals(typeof os.platform(), "string");
},
});
-test({
+Deno.test({
name: "release is a string",
fn() {
assertEquals(typeof os.release(), "string");
},
});
-test({
+Deno.test({
name: "getPriority(): PID must be a 32 bit integer",
fn() {
assertThrows(
@@ -64,7 +63,7 @@ test({
},
});
-test({
+Deno.test({
name: "setPriority(): PID must be a 32 bit integer",
fn() {
assertThrows(
@@ -84,7 +83,7 @@ test({
},
});
-test({
+Deno.test({
name: "setPriority(): priority must be an integer between -20 and 19",
fn() {
assertThrows(
@@ -118,7 +117,7 @@ test({
},
});
-test({
+Deno.test({
name:
"setPriority(): if only one argument specified, then this is the priority, NOT the pid",
fn() {
@@ -153,7 +152,7 @@ test({
},
});
-test({
+Deno.test({
name: "Signals are as expected",
fn() {
// Test a few random signals for equality
@@ -163,21 +162,21 @@ test({
},
});
-test({
+Deno.test({
name: "EOL is as expected",
fn() {
assert(os.EOL == "\r\n" || os.EOL == "\n");
},
});
-test({
+Deno.test({
name: "Endianness is determined",
fn() {
assert(["LE", "BE"].includes(os.endianness()));
},
});
-test({
+Deno.test({
name: "Load average is an array of 3 numbers",
fn() {
const result = os.loadavg();
@@ -188,7 +187,7 @@ test({
},
});
-test({
+Deno.test({
name: "Primitive coercion works as expected",
fn() {
assertEquals(`${os.arch}`, os.arch());
@@ -199,7 +198,7 @@ test({
},
});
-test({
+Deno.test({
name: "APIs not yet implemented",
fn() {
assertThrows(
diff --git a/std/node/process.ts b/std/node/process.ts
index 9da41b45b..cad72a00a 100644
--- a/std/node/process.ts
+++ b/std/node/process.ts
@@ -1,32 +1,22 @@
import { notImplemented } from "./_utils.ts";
-const version = `v${Deno.version.deno}`;
-
-const versions = {
- node: Deno.version.deno,
- ...Deno.version,
-};
-
-const platform = Deno.build.os === "windows" ? "win32" : Deno.build.os;
-
-const { arch } = Deno.build;
-
-const { pid, cwd, chdir, exit } = Deno;
-
function on(_event: string, _callback: Function): void {
// TODO(rsp): to be implemented
notImplemented();
}
export const process = {
- version,
- versions,
- platform,
- arch,
- pid,
- cwd,
- chdir,
- exit,
+ version: `v${Deno.version.deno}`,
+ versions: {
+ node: Deno.version.deno,
+ ...Deno.version,
+ },
+ platform: Deno.build.os === "windows" ? "win32" : Deno.build.os,
+ arch: Deno.build.arch,
+ pid: Deno.pid,
+ cwd: Deno.cwd,
+ chdir: Deno.chdir,
+ exit: Deno.exit,
on,
get env(): { [index: string]: string } {
// using getter to avoid --allow-env unless it's used
diff --git a/std/node/process_test.ts b/std/node/process_test.ts
index 3afaa4cdf..058105a4a 100644
--- a/std/node/process_test.ts
+++ b/std/node/process_test.ts
@@ -1,11 +1,10 @@
-const { test } = Deno;
import { assert, assertThrows, assertEquals } from "../testing/asserts.ts";
import { process } from "./process.ts";
// NOTE: Deno.execPath() (and thus process.argv) currently requires --allow-env
// (Also Deno.env.toObject() (and process.env) requires --allow-env but it's more obvious)
-test({
+Deno.test({
name: "process.cwd and process.chdir success",
fn() {
// this should be run like other tests from directory up
@@ -17,7 +16,7 @@ test({
},
});
-test({
+Deno.test({
name: "process.chdir failure",
fn() {
assertThrows(
@@ -33,7 +32,7 @@ test({
},
});
-test({
+Deno.test({
name: "process.version",
fn() {
assertEquals(typeof process, "object");
@@ -43,14 +42,14 @@ test({
},
});
-test({
+Deno.test({
name: "process.platform",
fn() {
assertEquals(typeof process.platform, "string");
},
});
-test({
+Deno.test({
name: "process.arch",
fn() {
assertEquals(typeof process.arch, "string");
@@ -59,7 +58,7 @@ test({
},
});
-test({
+Deno.test({
name: "process.pid",
fn() {
assertEquals(typeof process.pid, "number");
@@ -67,7 +66,7 @@ test({
},
});
-test({
+Deno.test({
name: "process.on",
fn() {
assertEquals(typeof process.on, "function");
@@ -81,7 +80,7 @@ test({
},
});
-test({
+Deno.test({
name: "process.argv",
fn() {
assert(Array.isArray(process.argv));
@@ -93,7 +92,7 @@ test({
},
});
-test({
+Deno.test({
name: "process.env",
fn() {
assertEquals(typeof process.env.PATH, "string");
diff --git a/std/node/querystring_test.ts b/std/node/querystring_test.ts
index 0a37eee6b..63abf471b 100644
--- a/std/node/querystring_test.ts
+++ b/std/node/querystring_test.ts
@@ -1,8 +1,7 @@
-const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts";
import { stringify, parse } from "./querystring.ts";
-test({
+Deno.test({
name: "stringify",
fn() {
assertEquals(
@@ -17,7 +16,7 @@ test({
},
});
-test({
+Deno.test({
name: "parse",
fn() {
assertEquals(parse("a=hello&b=5&c=true&d=foo&d=bar"), {
diff --git a/std/node/util_test.ts b/std/node/util_test.ts
index b64396441..cedd85a87 100644
--- a/std/node/util_test.ts
+++ b/std/node/util_test.ts
@@ -1,8 +1,7 @@
-const { test } = Deno;
import { assert } from "../testing/asserts.ts";
import * as util from "./util.ts";
-test({
+Deno.test({
name: "[util] isBoolean",
fn() {
assert(util.isBoolean(true));
@@ -14,7 +13,7 @@ test({
},
});
-test({
+Deno.test({
name: "[util] isNull",
fn() {
let n;
@@ -25,7 +24,7 @@ test({
},
});
-test({
+Deno.test({
name: "[util] isNullOrUndefined",
fn() {
let n;
@@ -36,7 +35,7 @@ test({
},
});
-test({
+Deno.test({
name: "[util] isNumber",
fn() {
assert(util.isNumber(666));
@@ -46,7 +45,7 @@ test({
},
});
-test({
+Deno.test({
name: "[util] isString",
fn() {
assert(util.isString("deno"));
@@ -55,7 +54,7 @@ test({
},
});
-test({
+Deno.test({
name: "[util] isSymbol",
fn() {
assert(util.isSymbol(Symbol()));
@@ -64,7 +63,7 @@ test({
},
});
-test({
+Deno.test({
name: "[util] isUndefined",
fn() {
let t;
@@ -74,7 +73,7 @@ test({
},
});
-test({
+Deno.test({
name: "[util] isObject",
fn() {
const dio = { stand: "Za Warudo" };
@@ -84,7 +83,7 @@ test({
},
});
-test({
+Deno.test({
name: "[util] isError",
fn() {
const java = new Error();
@@ -96,7 +95,7 @@ test({
},
});
-test({
+Deno.test({
name: "[util] isFunction",
fn() {
const f = function (): void {};
@@ -106,7 +105,7 @@ test({
},
});
-test({
+Deno.test({
name: "[util] isRegExp",
fn() {
assert(util.isRegExp(new RegExp(/f/)));
@@ -116,7 +115,7 @@ test({
},
});
-test({
+Deno.test({
name: "[util] isArray",
fn() {
assert(util.isArray([]));
@@ -125,7 +124,7 @@ test({
},
});
-test({
+Deno.test({
name: "[util] isPrimitive",
fn() {
const stringType = "hasti";
@@ -149,7 +148,7 @@ test({
},
});
-test({
+Deno.test({
name: "[util] TextDecoder",
fn() {
assert(util.TextDecoder === TextDecoder);
@@ -158,7 +157,7 @@ test({
},
});
-test({
+Deno.test({
name: "[util] TextEncoder",
fn() {
assert(util.TextEncoder === TextEncoder);
@@ -167,7 +166,7 @@ test({
},
});
-test({
+Deno.test({
name: "[util] isDate",
fn() {
// Test verifies the method is exposed. See _util/_util_types_test for details
diff --git a/std/path/_globrex_test.ts b/std/path/_globrex_test.ts
index 2974b4719..67a58cc64 100644
--- a/std/path/_globrex_test.ts
+++ b/std/path/_globrex_test.ts
@@ -1,8 +1,6 @@
// This file is ported from globrex@0.1.2
// MIT License
// Copyright (c) 2018 Terkel Gjervig Nielsen
-
-const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts";
import { GlobrexOptions, globrex } from "./_globrex.ts";
@@ -27,7 +25,7 @@ function match(
return !!match;
}
-test({
+Deno.test({
name: "globrex: standard",
fn(): void {
const res = globrex("*.js");
@@ -37,7 +35,7 @@ test({
},
});
-test({
+Deno.test({
name: "globrex: Standard * matching",
fn(): void {
t.equal(match("*", "foo"), true, "match everything");
@@ -67,7 +65,7 @@ test({
},
});
-test({
+Deno.test({
name: "globrex: advance * matching",
fn(): void {
t.equal(
@@ -178,7 +176,7 @@ test({
},
});
-test({
+Deno.test({
name: "globrex: ? match one character, no more and no less",
fn(): void {
t.equal(match("f?o", "foo", { extended: true }), true);
@@ -218,7 +216,7 @@ test({
},
});
-test({
+Deno.test({
name: "globrex: [] match a character range",
fn(): void {
t.equal(match("fo[oz]", "foo", { extended: true }), true);
@@ -249,7 +247,7 @@ test({
},
});
-test({
+Deno.test({
name: "globrex: [] extended character ranges",
fn(): void {
t.equal(
@@ -307,7 +305,7 @@ test({
},
});
-test({
+Deno.test({
name: "globrex: {} match a choice of different substrings",
fn(): void {
t.equal(match("foo{bar,baaz}", "foobaaz", { extended: true }), true);
@@ -355,7 +353,7 @@ test({
},
});
-test({
+Deno.test({
name: "globrex: complex extended matches",
fn(): void {
t.equal(
@@ -447,7 +445,7 @@ test({
},
});
-test({
+Deno.test({
name: "globrex: standard globstar",
fn(): void {
const tester = (globstar: boolean): void => {
@@ -482,7 +480,7 @@ test({
},
});
-test({
+Deno.test({
name: "globrex: remaining chars should match themself",
fn(): void {
const tester = (globstar: boolean): void => {
@@ -499,7 +497,7 @@ test({
},
});
-test({
+Deno.test({
name: "globrex: globstar advance testing",
fn(): void {
t.equal(match("/foo/*", "/foo/bar.txt", { globstar: true }), true);
@@ -639,7 +637,7 @@ test({
},
});
-test({
+Deno.test({
name: "globrex: extended extglob ?",
fn(): void {
t.equal(match("(foo).txt", "(foo).txt", { extended: true }), true);
@@ -692,7 +690,7 @@ test({
},
});
-test({
+Deno.test({
name: "globrex: extended extglob *",
fn(): void {
t.equal(match("*(foo).txt", "foo.txt", { extended: true }), true);
@@ -729,7 +727,7 @@ test({
},
});
-test({
+Deno.test({
name: "globrex: extended extglob +",
fn(): void {
t.equal(match("+(foo).txt", "foo.txt", { extended: true }), true);
@@ -739,7 +737,7 @@ test({
},
});
-test({
+Deno.test({
name: "globrex: extended extglob @",
fn(): void {
t.equal(match("@(foo).txt", "foo.txt", { extended: true }), true);
@@ -760,7 +758,7 @@ test({
},
});
-test({
+Deno.test({
name: "globrex: extended extglob !",
fn(): void {
t.equal(match("!(boo).txt", "foo.txt", { extended: true }), true);
@@ -777,7 +775,7 @@ test({
},
});
-test({
+Deno.test({
name: "globrex: strict",
fn(): void {
t.equal(match("foo//bar.txt", "foo/bar.txt"), true);
@@ -786,7 +784,7 @@ test({
},
});
-test({
+Deno.test({
name: "globrex: stress testing",
fn(): void {
t.equal(
diff --git a/std/path/basename_test.ts b/std/path/basename_test.ts
index 8ec70eb08..b0694de20 100644
--- a/std/path/basename_test.ts
+++ b/std/path/basename_test.ts
@@ -1,11 +1,9 @@
// Copyright the Browserify authors. MIT License.
// Ported from https://github.com/browserify/path-browserify/
-
-const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts";
import * as path from "./mod.ts";
-test("basename", function () {
+Deno.test("basename", function () {
assertEquals(path.basename(".js", ".js"), "");
assertEquals(path.basename(""), "");
assertEquals(path.basename("/dir/basename.ext"), "basename.ext");
@@ -50,7 +48,7 @@ test("basename", function () {
);
});
-test("basenameWin32", function () {
+Deno.test("basenameWin32", function () {
assertEquals(path.win32.basename("\\dir\\basename.ext"), "basename.ext");
assertEquals(path.win32.basename("\\basename.ext"), "basename.ext");
assertEquals(path.win32.basename("basename.ext"), "basename.ext");
diff --git a/std/path/common_test.ts b/std/path/common_test.ts
index 63dba38b8..921cf1c99 100644
--- a/std/path/common_test.ts
+++ b/std/path/common_test.ts
@@ -1,11 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
-const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts";
-
import { common } from "./mod.ts";
-test({
+Deno.test({
name: "path - common - basic usage",
fn() {
const actual = common(
@@ -20,7 +17,7 @@ test({
},
});
-test({
+Deno.test({
name: "path - common - no shared",
fn() {
const actual = common(
@@ -31,7 +28,7 @@ test({
},
});
-test({
+Deno.test({
name: "path - common - windows sep",
fn() {
const actual = common(
diff --git a/std/path/dirname_test.ts b/std/path/dirname_test.ts
index a00c8bc46..bdf3391a9 100644
--- a/std/path/dirname_test.ts
+++ b/std/path/dirname_test.ts
@@ -1,11 +1,9 @@
// Copyright the Browserify authors. MIT License.
// Ported from https://github.com/browserify/path-browserify/
-
-const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts";
import * as path from "./mod.ts";
-test("dirname", function () {
+Deno.test("dirname", function () {
assertEquals(path.posix.dirname("/a/b/"), "/a");
assertEquals(path.posix.dirname("/a/b"), "/a");
assertEquals(path.posix.dirname("/a"), "/");
@@ -16,7 +14,7 @@ test("dirname", function () {
assertEquals(path.posix.dirname("foo"), ".");
});
-test("dirnameWin32", function () {
+Deno.test("dirnameWin32", function () {
assertEquals(path.win32.dirname("c:\\"), "c:\\");
assertEquals(path.win32.dirname("c:\\foo"), "c:\\");
assertEquals(path.win32.dirname("c:\\foo\\"), "c:\\");
diff --git a/std/path/extname_test.ts b/std/path/extname_test.ts
index d5c54a6de..7e1abf4bc 100644
--- a/std/path/extname_test.ts
+++ b/std/path/extname_test.ts
@@ -1,7 +1,5 @@
// Copyright the Browserify authors. MIT License.
// Ported from https://github.com/browserify/path-browserify/
-
-const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts";
import * as path from "./mod.ts";
@@ -52,7 +50,7 @@ const pairs = [
["file.//", "."],
];
-test("extname", function () {
+Deno.test("extname", function () {
pairs.forEach(function (p) {
const input = p[0];
const expected = p[1];
@@ -70,7 +68,7 @@ test("extname", function () {
assertEquals(path.posix.extname("file.\\\\"), ".\\\\");
});
-test("extnameWin32", function () {
+Deno.test("extnameWin32", function () {
pairs.forEach(function (p) {
const input = p[0].replace(slashRE, "\\");
const expected = p[1];
diff --git a/std/path/glob_test.ts b/std/path/glob_test.ts
index 1ab3d9240..1c90e765a 100644
--- a/std/path/glob_test.ts
+++ b/std/path/glob_test.ts
@@ -1,10 +1,9 @@
-const { mkdir, test } = Deno;
import { assert, assertEquals } from "../testing/asserts.ts";
import { testWalk, touch, walkArray } from "../fs/walk_test.ts";
import { globToRegExp, isGlob, joinGlobs, normalizeGlob } from "./glob.ts";
import { SEP, join } from "./mod.ts";
-test({
+Deno.test({
name: "glob: glob to regex",
fn(): void {
assertEquals(globToRegExp("unicorn.*") instanceof RegExp, true);
@@ -47,8 +46,8 @@ test({
testWalk(
async (d: string): Promise<void> => {
- await mkdir(d + "/a");
- await mkdir(d + "/b");
+ await Deno.mkdir(d + "/a");
+ await Deno.mkdir(d + "/b");
await touch(d + "/a/x.ts");
await touch(d + "/b/z.ts");
await touch(d + "/b/z.js");
@@ -65,8 +64,8 @@ testWalk(
testWalk(
async (d: string): Promise<void> => {
- await mkdir(d + "/a");
- await mkdir(d + "/a/yo");
+ await Deno.mkdir(d + "/a");
+ await Deno.mkdir(d + "/a/yo");
await touch(d + "/a/yo/x.ts");
},
async function globInWalkFolderWildcard(): Promise<void> {
@@ -85,10 +84,10 @@ testWalk(
testWalk(
async (d: string): Promise<void> => {
- await mkdir(d + "/a");
- await mkdir(d + "/a/unicorn");
- await mkdir(d + "/a/deno");
- await mkdir(d + "/a/raptor");
+ await Deno.mkdir(d + "/a");
+ await Deno.mkdir(d + "/a/unicorn");
+ await Deno.mkdir(d + "/a/deno");
+ await Deno.mkdir(d + "/a/raptor");
await touch(d + "/a/raptor/x.ts");
await touch(d + "/a/deno/x.ts");
await touch(d + "/a/unicorn/x.ts");
@@ -124,7 +123,7 @@ testWalk(
}
);
-test({
+Deno.test({
name: "isGlob: pattern to test",
fn(): void {
// should be true if valid glob pattern
@@ -239,10 +238,10 @@ test({
},
});
-test("normalizeGlobGlobstar", function (): void {
+Deno.test("normalizeGlobGlobstar", function (): void {
assertEquals(normalizeGlob(`**${SEP}..`, { globstar: true }), `**${SEP}..`);
});
-test("joinGlobsGlobstar", function (): void {
+Deno.test("joinGlobsGlobstar", function (): void {
assertEquals(joinGlobs(["**", ".."], { globstar: true }), `**${SEP}..`);
});
diff --git a/std/path/isabsolute_test.ts b/std/path/isabsolute_test.ts
index b1614d3de..88ed54417 100644
--- a/std/path/isabsolute_test.ts
+++ b/std/path/isabsolute_test.ts
@@ -1,18 +1,16 @@
// Copyright the Browserify authors. MIT License.
// Ported from https://github.com/browserify/path-browserify/
-
-const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts";
import * as path from "./mod.ts";
-test("isAbsolute", function () {
+Deno.test("isAbsolute", function () {
assertEquals(path.posix.isAbsolute("/home/foo"), true);
assertEquals(path.posix.isAbsolute("/home/foo/.."), true);
assertEquals(path.posix.isAbsolute("bar/"), false);
assertEquals(path.posix.isAbsolute("./baz"), false);
});
-test("isAbsoluteWin32", function () {
+Deno.test("isAbsoluteWin32", function () {
assertEquals(path.win32.isAbsolute("/"), true);
assertEquals(path.win32.isAbsolute("//"), true);
assertEquals(path.win32.isAbsolute("//server"), true);
diff --git a/std/path/join_test.ts b/std/path/join_test.ts
index 6e70eba5b..b7311406f 100644
--- a/std/path/join_test.ts
+++ b/std/path/join_test.ts
@@ -1,4 +1,3 @@
-const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts";
import * as path from "./mod.ts";
@@ -106,7 +105,7 @@ const windowsJoinTests = [
[["c:", "file"], "c:\\file"],
];
-test("join", function () {
+Deno.test("join", function () {
joinTests.forEach(function (p) {
const _p = p[0] as string[];
const actual = path.posix.join.apply(null, _p);
@@ -114,7 +113,7 @@ test("join", function () {
});
});
-test("joinWin32", function () {
+Deno.test("joinWin32", function () {
joinTests.forEach(function (p) {
const _p = p[0] as string[];
const actual = path.win32.join.apply(null, _p).replace(backslashRE, "/");
diff --git a/std/path/parse_format_test.ts b/std/path/parse_format_test.ts
index bc58679cf..80692a84d 100644
--- a/std/path/parse_format_test.ts
+++ b/std/path/parse_format_test.ts
@@ -1,12 +1,10 @@
// Copyright the Browserify authors. MIT License.
// Ported from https://github.com/browserify/path-browserify/
-
-// TODO(kt3k): fix any types in this file
-
-const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts";
import * as path from "./mod.ts";
+// TODO(kt3k): fix any types in this file
+
const winPaths = [
// [path, root]
["C:\\path\\dir\\index.html", "C:\\"],
@@ -116,20 +114,20 @@ function checkFormat(path: any, testCases: unknown[][]): void {
});
}
-test("parseWin32", function () {
+Deno.test("parseWin32", function () {
checkParseFormat(path.win32, winPaths);
checkSpecialCaseParseFormat(path.win32, winSpecialCaseParseTests);
});
-test("parse", function () {
+Deno.test("parse", function () {
checkParseFormat(path.posix, unixPaths);
});
-test("formatWin32", function () {
+Deno.test("formatWin32", function () {
checkFormat(path.win32, winSpecialCaseFormatTests);
});
-test("format", function () {
+Deno.test("format", function () {
checkFormat(path.posix, unixSpecialCaseFormatTests);
});
@@ -165,7 +163,7 @@ const posixTrailingTests = [
],
];
-test("parseTrailingWin32", function () {
+Deno.test("parseTrailingWin32", function () {
windowsTrailingTests.forEach(function (p) {
const actual = path.win32.parse(p[0] as string);
const expected = p[1];
@@ -173,7 +171,7 @@ test("parseTrailingWin32", function () {
});
});
-test("parseTrailing", function () {
+Deno.test("parseTrailing", function () {
posixTrailingTests.forEach(function (p) {
const actual = path.posix.parse(p[0] as string);
const expected = p[1];
diff --git a/std/path/relative_test.ts b/std/path/relative_test.ts
index 18b6930e8..e00e16d73 100644
--- a/std/path/relative_test.ts
+++ b/std/path/relative_test.ts
@@ -1,7 +1,5 @@
// Copyright the Browserify authors. MIT License.
// Ported from https://github.com/browserify/path-browserify/
-
-const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts";
import * as path from "./mod.ts";
@@ -50,7 +48,7 @@ const relativeTests = {
],
};
-test("relative", function () {
+Deno.test("relative", function () {
relativeTests.posix.forEach(function (p) {
const expected = p[2];
const actual = path.posix.relative(p[0], p[1]);
@@ -58,7 +56,7 @@ test("relative", function () {
});
});
-test("relativeWin32", function () {
+Deno.test("relativeWin32", function () {
relativeTests.win32.forEach(function (p) {
const expected = p[2];
const actual = path.win32.relative(p[0], p[1]);
diff --git a/std/path/resolve_test.ts b/std/path/resolve_test.ts
index 36a537b7a..dec032f47 100644
--- a/std/path/resolve_test.ts
+++ b/std/path/resolve_test.ts
@@ -1,7 +1,5 @@
// Copyright the Browserify authors. MIT License.
// Ported from https://github.com/browserify/path-browserify/
-
-const { cwd, test } = Deno;
import { assertEquals } from "../testing/asserts.ts";
import * as path from "./mod.ts";
@@ -28,13 +26,13 @@ const posixTests =
[
[["/var/lib", "../", "file/"], "/var/file"],
[["/var/lib", "/../", "file/"], "/file"],
- [["a/b/c/", "../../.."], cwd()],
- [["."], cwd()],
+ [["a/b/c/", "../../.."], Deno.cwd()],
+ [["."], Deno.cwd()],
[["/some/dir", ".", "/absolute/"], "/absolute"],
[["/foo/tmp.3/", "../tmp.3/cycles/root.js"], "/foo/tmp.3/cycles/root.js"],
];
-test("resolve", function () {
+Deno.test("resolve", function () {
posixTests.forEach(function (p) {
const _p = p[0] as string[];
const actual = path.posix.resolve.apply(null, _p);
@@ -42,7 +40,7 @@ test("resolve", function () {
});
});
-test("resolveWin32", function () {
+Deno.test("resolveWin32", function () {
windowsTests.forEach(function (p) {
const _p = p[0] as string[];
const actual = path.win32.resolve.apply(null, _p);
diff --git a/std/path/zero_length_strings_test.ts b/std/path/zero_length_strings_test.ts
index 771395a8c..e2ec466a5 100644
--- a/std/path/zero_length_strings_test.ts
+++ b/std/path/zero_length_strings_test.ts
@@ -1,13 +1,11 @@
// Copyright the Browserify authors. MIT License.
// Ported from https://github.com/browserify/path-browserify/
-
-const { cwd, test } = Deno;
import { assertEquals } from "../testing/asserts.ts";
import * as path from "./mod.ts";
-const pwd = cwd();
+const pwd = Deno.cwd();
-test("joinZeroLength", function () {
+Deno.test("joinZeroLength", function () {
// join will internally ignore all the zero-length strings and it will return
// '.' if the joined string is a zero-length string.
assertEquals(path.posix.join(""), ".");
@@ -18,28 +16,28 @@ test("joinZeroLength", function () {
assertEquals(path.join(pwd, ""), pwd);
});
-test("normalizeZeroLength", function () {
+Deno.test("normalizeZeroLength", function () {
// normalize will return '.' if the input is a zero-length string
assertEquals(path.posix.normalize(""), ".");
if (path.win32) assertEquals(path.win32.normalize(""), ".");
assertEquals(path.normalize(pwd), pwd);
});
-test("isAbsoluteZeroLength", function () {
+Deno.test("isAbsoluteZeroLength", function () {
// Since '' is not a valid path in any of the common environments,
// return false
assertEquals(path.posix.isAbsolute(""), false);
if (path.win32) assertEquals(path.win32.isAbsolute(""), false);
});
-test("resolveZeroLength", function () {
+Deno.test("resolveZeroLength", function () {
// resolve, internally ignores all the zero-length strings and returns the
// current working directory
assertEquals(path.resolve(""), pwd);
assertEquals(path.resolve("", ""), pwd);
});
-test("relativeZeroLength", function () {
+Deno.test("relativeZeroLength", function () {
// relative, internally calls resolve. So, '' is actually the current
// directory
assertEquals(path.relative("", pwd), "");
diff --git a/std/permissions/test.ts b/std/permissions/test.ts
index 6a9955b6a..6622cc761 100644
--- a/std/permissions/test.ts
+++ b/std/permissions/test.ts
@@ -1,11 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
import { grant, grantOrThrow } from "./mod.ts";
import { assert, assertEquals } from "../testing/asserts.ts";
-const { test } = Deno;
-
-test({
+Deno.test({
name: "grant basic",
async fn() {
assertEquals(await grant({ name: "net" }, { name: "env" }), [
@@ -15,7 +12,7 @@ test({
},
});
-test({
+Deno.test({
name: "grant array",
async fn() {
assertEquals(await grant([{ name: "net" }, { name: "env" }]), [
@@ -25,21 +22,21 @@ test({
},
});
-test({
+Deno.test({
name: "grant logic",
async fn() {
assert(await grant({ name: "net" }));
},
});
-test({
+Deno.test({
name: "grantOrThrow basic",
async fn() {
await grantOrThrow({ name: "net" }, { name: "env" });
},
});
-test({
+Deno.test({
name: "grantOrThrow array",
async fn() {
await grantOrThrow([{ name: "net" }, { name: "env" }]);
diff --git a/std/signal/test.ts b/std/signal/test.ts
index ef79a303b..4c8aa82e0 100644
--- a/std/signal/test.ts
+++ b/std/signal/test.ts
@@ -1,9 +1,8 @@
-const { test } = Deno;
import { assertEquals, assertThrows } from "../testing/asserts.ts";
import { delay } from "../async/delay.ts";
import { signal, onSignal } from "./mod.ts";
-test({
+Deno.test({
name: "signal() throws when called with empty signals",
ignore: Deno.build.os === "windows",
fn() {
@@ -18,7 +17,7 @@ test({
},
});
-test({
+Deno.test({
name: "signal() iterates for multiple signals",
ignore: Deno.build.os === "windows",
fn: async (): Promise<void> => {
@@ -59,7 +58,7 @@ test({
},
});
-test({
+Deno.test({
name: "onSignal() registers and disposes of event handler",
ignore: Deno.build.os === "windows",
async fn() {
diff --git a/std/testing/asserts_test.ts b/std/testing/asserts_test.ts
index feb4d097d..7f2d978ea 100644
--- a/std/testing/asserts_test.ts
+++ b/std/testing/asserts_test.ts
@@ -1,5 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
import {
assert,
assertNotEquals,
@@ -17,9 +16,8 @@ import {
unreachable,
} from "./asserts.ts";
import { red, green, gray, bold, yellow } from "../fmt/colors.ts";
-const { test } = Deno;
-test("testingEqual", function (): void {
+Deno.test("testingEqual", function (): void {
assert(equal("world", "world"));
assert(!equal("hello", "world"));
assert(equal(5, 5));
@@ -116,7 +114,7 @@ test("testingEqual", function (): void {
assert(!equal(new Uint8Array([1, 2, 3, 4]), new Uint8Array([2, 1, 4, 3])));
});
-test("testingNotEquals", function (): void {
+Deno.test("testingNotEquals", function (): void {
const a = { foo: "bar" };
const b = { bar: "foo" };
assertNotEquals(a, b);
@@ -132,7 +130,7 @@ test("testingNotEquals", function (): void {
assertEquals(didThrow, true);
});
-test("testingAssertStringContains", function (): void {
+Deno.test("testingAssertStringContains", function (): void {
assertStringContains("Denosaurus", "saur");
assertStringContains("Denosaurus", "Deno");
assertStringContains("Denosaurus", "rus");
@@ -147,7 +145,7 @@ test("testingAssertStringContains", function (): void {
assertEquals(didThrow, true);
});
-test("testingArrayContains", function (): void {
+Deno.test("testingArrayContains", function (): void {
const fixture = ["deno", "iz", "luv"];
const fixtureObject = [{ deno: "luv" }, { deno: "Js" }];
assertArrayContains(fixture, ["deno"]);
@@ -159,7 +157,7 @@ test("testingArrayContains", function (): void {
);
});
-test("testingAssertStringContainsThrow", function (): void {
+Deno.test("testingAssertStringContainsThrow", function (): void {
let didThrow = false;
try {
assertStringContains("Denosaurus from Jurassic", "Raptor");
@@ -174,11 +172,11 @@ test("testingAssertStringContainsThrow", function (): void {
assert(didThrow);
});
-test("testingAssertStringMatching", function (): void {
+Deno.test("testingAssertStringMatching", function (): void {
assertMatch("foobar@deno.com", RegExp(/[a-zA-Z]+@[a-zA-Z]+.com/));
});
-test("testingAssertStringMatchingThrows", function (): void {
+Deno.test("testingAssertStringMatchingThrows", function (): void {
let didThrow = false;
try {
assertMatch("Denosaurus from Jurassic", RegExp(/Raptor/));
@@ -193,7 +191,7 @@ test("testingAssertStringMatchingThrows", function (): void {
assert(didThrow);
});
-test("testingAssertsUnimplemented", function (): void {
+Deno.test("testingAssertsUnimplemented", function (): void {
let didThrow = false;
try {
unimplemented();
@@ -205,7 +203,7 @@ test("testingAssertsUnimplemented", function (): void {
assert(didThrow);
});
-test("testingAssertsUnreachable", function (): void {
+Deno.test("testingAssertsUnreachable", function (): void {
let didThrow = false;
try {
unreachable();
@@ -217,7 +215,7 @@ test("testingAssertsUnreachable", function (): void {
assert(didThrow);
});
-test("testingAssertFail", function (): void {
+Deno.test("testingAssertFail", function (): void {
assertThrows(fail, AssertionError, "Failed assertion.");
assertThrows(
(): void => {
@@ -228,7 +226,7 @@ test("testingAssertFail", function (): void {
);
});
-test("testingAssertFailWithWrongErrorClass", function (): void {
+Deno.test("testingAssertFailWithWrongErrorClass", function (): void {
assertThrows(
(): void => {
//This next assertThrows will throw an AssertionError due to the wrong
@@ -246,14 +244,14 @@ test("testingAssertFailWithWrongErrorClass", function (): void {
);
});
-test("testingAssertThrowsWithReturnType", () => {
+Deno.test("testingAssertThrowsWithReturnType", () => {
assertThrows(() => {
throw new Error();
return "a string";
});
});
-test("testingAssertThrowsAsyncWithReturnType", () => {
+Deno.test("testingAssertThrowsAsyncWithReturnType", () => {
assertThrowsAsync(() => {
throw new Error();
return Promise.resolve("a Promise<string>");
@@ -273,7 +271,7 @@ const createHeader = (): string[] => [
const added: (s: string) => string = (s: string): string => green(bold(s));
const removed: (s: string) => string = (s: string): string => red(bold(s));
-test({
+Deno.test({
name: "pass case",
fn(): void {
assertEquals({ a: 10 }, { a: 10 });
@@ -284,7 +282,7 @@ test({
},
});
-test({
+Deno.test({
name: "failed with number",
fn(): void {
assertThrows(
@@ -301,7 +299,7 @@ test({
},
});
-test({
+Deno.test({
name: "failed with number vs string",
fn(): void {
assertThrows(
@@ -317,7 +315,7 @@ test({
},
});
-test({
+Deno.test({
name: "failed with array",
fn(): void {
assertThrows(
@@ -334,7 +332,7 @@ test({
},
});
-test({
+Deno.test({
name: "failed with object",
fn(): void {
assertThrows(
@@ -355,7 +353,7 @@ test({
},
});
-test({
+Deno.test({
name: "strict pass case",
fn(): void {
assertStrictEquals(true, true);
@@ -372,7 +370,7 @@ test({
},
});
-test({
+Deno.test({
name: "strict failed with structure diff",
fn(): void {
assertThrows(
@@ -389,7 +387,7 @@ test({
},
});
-test({
+Deno.test({
name: "strict failed with reference diff",
fn(): void {
assertThrows(
diff --git a/std/testing/bench.ts b/std/testing/bench.ts
index a5e6490ac..366d6ec1b 100644
--- a/std/testing/bench.ts
+++ b/std/testing/bench.ts
@@ -1,8 +1,6 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { deepAssign } from "../_util/deep_assign.ts";
-const { noColor } = Deno;
-
interface BenchmarkClock {
start: number;
stop: number;
@@ -98,11 +96,11 @@ export class BenchmarkRunError extends Error {
}
function red(text: string): string {
- return noColor ? text : `\x1b[31m${text}\x1b[0m`;
+ return Deno.noColor ? text : `\x1b[31m${text}\x1b[0m`;
}
function blue(text: string): string {
- return noColor ? text : `\x1b[34m${text}\x1b[0m`;
+ return Deno.noColor ? text : `\x1b[34m${text}\x1b[0m`;
}
function verifyOr1Run(runs?: number): number {
diff --git a/std/testing/bench_test.ts b/std/testing/bench_test.ts
index 0b101c22f..b6d64ab89 100644
--- a/std/testing/bench_test.ts
+++ b/std/testing/bench_test.ts
@@ -1,4 +1,3 @@
-const { test } = Deno;
import {
bench,
runBenchmarks,
@@ -14,7 +13,7 @@ import {
assertThrowsAsync,
} from "./asserts.ts";
-test({
+Deno.test({
name: "benching",
fn: async function (): Promise<void> {
@@ -101,7 +100,7 @@ test({
},
});
-test({
+Deno.test({
name: "Bench without name should throw",
fn() {
assertThrows(
@@ -114,7 +113,7 @@ test({
},
});
-test({
+Deno.test({
name: "Bench without stop should throw",
fn: async function (): Promise<void> {
await assertThrowsAsync(
@@ -131,7 +130,7 @@ test({
},
});
-test({
+Deno.test({
name: "Bench without start should throw",
fn: async function (): Promise<void> {
await assertThrowsAsync(
@@ -148,7 +147,7 @@ test({
},
});
-test({
+Deno.test({
name: "Bench with stop before start should throw",
fn: async function (): Promise<void> {
await assertThrowsAsync(
@@ -166,7 +165,7 @@ test({
},
});
-test({
+Deno.test({
name: "clearBenchmarks should clear all candidates",
fn: async function (): Promise<void> {
dummyBench("test");
@@ -179,7 +178,7 @@ test({
},
});
-test({
+Deno.test({
name: "clearBenchmarks with only as option",
fn: async function (): Promise<void> {
// to reset candidates
@@ -197,7 +196,7 @@ test({
},
});
-test({
+Deno.test({
name: "clearBenchmarks with skip as option",
fn: async function (): Promise<void> {
// to reset candidates
@@ -215,7 +214,7 @@ test({
},
});
-test({
+Deno.test({
name: "clearBenchmarks with only and skip as option",
fn: async function (): Promise<void> {
// to reset candidates
@@ -236,7 +235,7 @@ test({
},
});
-test({
+Deno.test({
name: "progressCallback of runBenchmarks",
fn: async function (): Promise<void> {
clearBenchmarks();
@@ -338,7 +337,7 @@ test({
},
});
-test({
+Deno.test({
name: "async progressCallback",
fn: async function (): Promise<void> {
clearBenchmarks();
diff --git a/std/testing/diff_test.ts b/std/testing/diff_test.ts
index 317dc0db8..072f39622 100644
--- a/std/testing/diff_test.ts
+++ b/std/testing/diff_test.ts
@@ -1,15 +1,14 @@
import diff from "./diff.ts";
import { assertEquals } from "../testing/asserts.ts";
-const { test } = Deno;
-test({
+Deno.test({
name: "empty",
fn(): void {
assertEquals(diff([], []), []);
},
});
-test({
+Deno.test({
name: '"a" vs "b"',
fn(): void {
assertEquals(diff(["a"], ["b"]), [
@@ -19,28 +18,28 @@ test({
},
});
-test({
+Deno.test({
name: '"a" vs "a"',
fn(): void {
assertEquals(diff(["a"], ["a"]), [{ type: "common", value: "a" }]);
},
});
-test({
+Deno.test({
name: '"a" vs ""',
fn(): void {
assertEquals(diff(["a"], []), [{ type: "removed", value: "a" }]);
},
});
-test({
+Deno.test({
name: '"" vs "a"',
fn(): void {
assertEquals(diff([], ["a"]), [{ type: "added", value: "a" }]);
},
});
-test({
+Deno.test({
name: '"a" vs "a, b"',
fn(): void {
assertEquals(diff(["a"], ["a", "b"]), [
@@ -50,7 +49,7 @@ test({
},
});
-test({
+Deno.test({
name: '"strength" vs "string"',
fn(): void {
assertEquals(diff(Array.from("strength"), Array.from("string")), [
@@ -67,7 +66,7 @@ test({
},
});
-test({
+Deno.test({
name: '"strength" vs ""',
fn(): void {
assertEquals(diff(Array.from("strength"), Array.from("")), [
@@ -83,7 +82,7 @@ test({
},
});
-test({
+Deno.test({
name: '"" vs "strength"',
fn(): void {
assertEquals(diff(Array.from(""), Array.from("strength")), [
@@ -99,7 +98,7 @@ test({
},
});
-test({
+Deno.test({
name: '"abc", "c" vs "abc", "bcd", "c"',
fn(): void {
assertEquals(diff(["abc", "c"], ["abc", "bcd", "c"]), [
diff --git a/std/textproto/test.ts b/std/textproto/test.ts
index 7539e9779..a7109410b 100644
--- a/std/textproto/test.ts
+++ b/std/textproto/test.ts
@@ -2,18 +2,16 @@
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-
import { BufReader } from "../io/bufio.ts";
import { TextProtoReader } from "./mod.ts";
import { StringReader } from "../io/readers.ts";
import { assert, assertEquals, assertThrows } from "../testing/asserts.ts";
-const { test } = Deno;
function reader(s: string): TextProtoReader {
return new TextProtoReader(new BufReader(new StringReader(s)));
}
-test({
+Deno.test({
ignore: true,
name: "[textproto] Reader : DotBytes",
fn(): Promise<void> {
@@ -23,13 +21,13 @@ test({
},
});
-test("[textproto] ReadEmpty", async () => {
+Deno.test("[textproto] ReadEmpty", async () => {
const r = reader("");
const m = await r.readMIMEHeader();
assertEquals(m, null);
});
-test("[textproto] Reader", async () => {
+Deno.test("[textproto] Reader", async () => {
const r = reader("line1\nline2\n");
let s = await r.readLine();
assertEquals(s, "line1");
@@ -41,7 +39,7 @@ test("[textproto] Reader", async () => {
assert(s === null);
});
-test({
+Deno.test({
name: "[textproto] Reader : MIME Header",
async fn(): Promise<void> {
const input =
@@ -55,7 +53,7 @@ test({
},
});
-test({
+Deno.test({
name: "[textproto] Reader : MIME Header Single",
async fn(): Promise<void> {
const input = "Foo: bar\n\n";
@@ -66,7 +64,7 @@ test({
},
});
-test({
+Deno.test({
name: "[textproto] Reader : MIME Header No Key",
async fn(): Promise<void> {
const input = ": bar\ntest-1: 1\n\n";
@@ -77,7 +75,7 @@ test({
},
});
-test({
+Deno.test({
name: "[textproto] Reader : Large MIME Header",
async fn(): Promise<void> {
const data: string[] = [];
@@ -95,7 +93,7 @@ test({
// Test that we don't read MIME headers seen in the wild,
// with spaces before colons, and spaces in keys.
-test({
+Deno.test({
name: "[textproto] Reader : MIME Header Non compliant",
async fn(): Promise<void> {
const input =
@@ -119,7 +117,7 @@ test({
},
});
-test({
+Deno.test({
name: "[textproto] Reader : MIME Header Malformed",
async fn(): Promise<void> {
const input = [
@@ -142,7 +140,7 @@ test({
},
});
-test({
+Deno.test({
name: "[textproto] Reader : MIME Header Trim Continued",
async fn(): Promise<void> {
const input =
@@ -164,7 +162,7 @@ test({
},
});
-test({
+Deno.test({
name: "[textproto] #409 issue : multipart form boundary",
async fn(): Promise<void> {
const input = [
@@ -181,7 +179,7 @@ test({
},
});
-test({
+Deno.test({
name: "[textproto] #4521 issue",
async fn() {
const input = "abcdefghijklmnopqrstuvwxyz";
diff --git a/std/uuid/tests/isNil.ts b/std/uuid/tests/isNil.ts
index 1f0db416e..4877a9da4 100644
--- a/std/uuid/tests/isNil.ts
+++ b/std/uuid/tests/isNil.ts
@@ -1,9 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { assert } from "../../testing/asserts.ts";
-const { test } = Deno;
import { NIL_UUID, isNil } from "../mod.ts";
-test({
+Deno.test({
name: "[UUID] isNil",
fn(): void {
const nil = NIL_UUID;
diff --git a/std/uuid/tests/v1/generate.ts b/std/uuid/tests/v1/generate.ts
index 1e60d91c1..548b81403 100644
--- a/std/uuid/tests/v1/generate.ts
+++ b/std/uuid/tests/v1/generate.ts
@@ -1,9 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { assert, assertEquals } from "../../../testing/asserts.ts";
-const { test } = Deno;
import { generate, validate } from "../../v1.ts";
-test({
+Deno.test({
name: "[UUID] test_uuid_v1",
fn(): void {
const u = generate();
@@ -12,7 +11,7 @@ test({
},
});
-test({
+Deno.test({
name: "[UUID] test_uuid_v1_format",
fn(): void {
for (let i = 0; i < 10000; i++) {
@@ -22,7 +21,7 @@ test({
},
});
-test({
+Deno.test({
name: "[UUID] test_uuid_v1_static",
fn(): void {
const v1options = {
diff --git a/std/uuid/tests/v4/generate.ts b/std/uuid/tests/v4/generate.ts
index 897a53fde..181d63ff4 100644
--- a/std/uuid/tests/v4/generate.ts
+++ b/std/uuid/tests/v4/generate.ts
@@ -1,9 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { assert, assertEquals } from "../../../testing/asserts.ts";
-const { test } = Deno;
import { generate, validate } from "../../v4.ts";
-test({
+Deno.test({
name: "[UUID] test_uuid_v4",
fn(): void {
const u = generate();
@@ -12,7 +11,7 @@ test({
},
});
-test({
+Deno.test({
name: "[UUID] test_uuid_v4_format",
fn(): void {
for (let i = 0; i < 10000; i++) {
diff --git a/std/uuid/tests/v5/generate.ts b/std/uuid/tests/v5/generate.ts
index c869ef505..4e73489d0 100644
--- a/std/uuid/tests/v5/generate.ts
+++ b/std/uuid/tests/v5/generate.ts
@@ -1,9 +1,10 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { assert, assertEquals } from "../../../testing/asserts.ts";
-const { test } = Deno;
import { generate, validate } from "../../v5.ts";
+
const NAMESPACE = "1b671a64-40d5-491e-99b0-da01ff1f3341";
-test({
+
+Deno.test({
name: "[UUID] test_uuid_v5",
fn(): void {
const u = generate({ value: "", namespace: NAMESPACE });
@@ -12,7 +13,7 @@ test({
},
});
-test({
+Deno.test({
name: "[UUID] test_uuid_v5_format",
fn(): void {
for (let i = 0; i < 10000; i++) {
@@ -22,7 +23,7 @@ test({
},
});
-test({
+Deno.test({
name: "[UUID] test_uuid_v5_option",
fn(): void {
const v5Options = {
@@ -34,7 +35,7 @@ test({
},
});
-test({
+Deno.test({
name: "[UUID] test_uuid_v5_buf_offset",
fn(): void {
const buf = [
diff --git a/std/ws/mod.ts b/std/ws/mod.ts
index 4d3f79f74..e2151a53e 100644
--- a/std/ws/mod.ts
+++ b/std/ws/mod.ts
@@ -1,5 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-
import { decode, encode } from "../encoding/utf8.ts";
import { hasOwnProperty } from "../_util/has_own_property.ts";
import { BufReader, BufWriter } from "../io/bufio.ts";
@@ -10,8 +9,6 @@ import { TextProtoReader } from "../textproto/mod.ts";
import { Deferred, deferred } from "../async/deferred.ts";
import { assert } from "../_util/assert.ts";
import { concat } from "../bytes/mod.ts";
-import Conn = Deno.Conn;
-import Writer = Deno.Writer;
export enum OpCode {
Continue = 0x0,
@@ -66,7 +63,7 @@ export interface WebSocketFrame {
}
export interface WebSocket extends AsyncIterable<WebSocketEvent> {
- readonly conn: Conn;
+ readonly conn: Deno.Conn;
readonly isClosed: boolean;
[Symbol.asyncIterator](): AsyncIterableIterator<WebSocketEvent>;
@@ -108,7 +105,7 @@ export function unmask(payload: Uint8Array, mask?: Uint8Array): void {
/** Write websocket frame to given writer */
export async function writeFrame(
frame: WebSocketFrame,
- writer: Writer
+ writer: Deno.Writer
): Promise<void> {
const payloadLength = frame.payload.byteLength;
let header: Uint8Array;
@@ -200,7 +197,7 @@ function createMask(): Uint8Array {
}
class WebSocketImpl implements WebSocket {
- readonly conn: Conn;
+ readonly conn: Deno.Conn;
private readonly mask?: Uint8Array;
private readonly bufReader: BufReader;
private readonly bufWriter: BufWriter;
@@ -215,7 +212,7 @@ class WebSocketImpl implements WebSocket {
bufWriter,
mask,
}: {
- conn: Conn;
+ conn: Deno.Conn;
bufReader?: BufReader;
bufWriter?: BufWriter;
mask?: Uint8Array;
@@ -418,7 +415,7 @@ export function createSecAccept(nonce: string): string {
/** Upgrade given TCP connection into websocket connection */
export async function acceptWebSocket(req: {
- conn: Conn;
+ conn: Deno.Conn;
bufWriter: BufWriter;
bufReader: BufReader;
headers: Headers;
@@ -526,7 +523,7 @@ export async function connectWebSocket(
): Promise<WebSocket> {
const url = new URL(endpoint);
const { hostname } = url;
- let conn: Conn;
+ let conn: Deno.Conn;
if (url.protocol === "http:" || url.protocol === "ws:") {
const port = parseInt(url.port || "80");
conn = await Deno.connect({ hostname, port });
@@ -553,7 +550,7 @@ export async function connectWebSocket(
}
export function createWebSocket(params: {
- conn: Conn;
+ conn: Deno.Conn;
bufWriter?: BufWriter;
bufReader?: BufReader;
mask?: Uint8Array;
diff --git a/std/ws/test.ts b/std/ws/test.ts
index 9ef6ff94b..ad6b6256c 100644
--- a/std/ws/test.ts
+++ b/std/ws/test.ts
@@ -1,7 +1,6 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { BufReader, BufWriter } from "../io/bufio.ts";
import { assert, assertEquals, assertThrowsAsync } from "../testing/asserts.ts";
-const { test } = Deno;
import { TextProtoReader } from "../textproto/mod.ts";
import * as bytes from "../bytes/mod.ts";
import {
@@ -17,29 +16,27 @@ import {
createWebSocket,
} from "./mod.ts";
import { encode, decode } from "../encoding/utf8.ts";
-import Writer = Deno.Writer;
-import Reader = Deno.Reader;
-import Conn = Deno.Conn;
-import Buffer = Deno.Buffer;
import { delay } from "../async/delay.ts";
-test("[ws] read unmasked text frame", async () => {
+Deno.test("[ws] read unmasked text frame", async () => {
// unmasked single text frame with payload "Hello"
const buf = new BufReader(
- new Buffer(new Uint8Array([0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f]))
+ new Deno.Buffer(new Uint8Array([0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f]))
);
const frame = await readFrame(buf);
assertEquals(frame.opcode, OpCode.TextFrame);
assertEquals(frame.mask, undefined);
- const actual = new TextDecoder().decode(new Buffer(frame.payload).bytes());
+ const actual = new TextDecoder().decode(
+ new Deno.Buffer(frame.payload).bytes()
+ );
assertEquals(actual, "Hello");
assertEquals(frame.isLastFrame, true);
});
-test("[ws] read masked text frame", async () => {
+Deno.test("[ws] read masked text frame", async () => {
// a masked single text frame with payload "Hello"
const buf = new BufReader(
- new Buffer(
+ new Deno.Buffer(
new Uint8Array([
0x81,
0x85,
@@ -58,59 +55,65 @@ test("[ws] read masked text frame", async () => {
const frame = await readFrame(buf);
assertEquals(frame.opcode, OpCode.TextFrame);
unmask(frame.payload, frame.mask);
- const actual = new TextDecoder().decode(new Buffer(frame.payload).bytes());
+ const actual = new TextDecoder().decode(
+ new Deno.Buffer(frame.payload).bytes()
+ );
assertEquals(actual, "Hello");
assertEquals(frame.isLastFrame, true);
});
-test("[ws] read unmasked split text frames", async () => {
+Deno.test("[ws] read unmasked split text frames", async () => {
const buf1 = new BufReader(
- new Buffer(new Uint8Array([0x01, 0x03, 0x48, 0x65, 0x6c]))
+ new Deno.Buffer(new Uint8Array([0x01, 0x03, 0x48, 0x65, 0x6c]))
);
const buf2 = new BufReader(
- new Buffer(new Uint8Array([0x80, 0x02, 0x6c, 0x6f]))
+ new Deno.Buffer(new Uint8Array([0x80, 0x02, 0x6c, 0x6f]))
);
const [f1, f2] = await Promise.all([readFrame(buf1), readFrame(buf2)]);
assertEquals(f1.isLastFrame, false);
assertEquals(f1.mask, undefined);
assertEquals(f1.opcode, OpCode.TextFrame);
- const actual1 = new TextDecoder().decode(new Buffer(f1.payload).bytes());
+ const actual1 = new TextDecoder().decode(new Deno.Buffer(f1.payload).bytes());
assertEquals(actual1, "Hel");
assertEquals(f2.isLastFrame, true);
assertEquals(f2.mask, undefined);
assertEquals(f2.opcode, OpCode.Continue);
- const actual2 = new TextDecoder().decode(new Buffer(f2.payload).bytes());
+ const actual2 = new TextDecoder().decode(new Deno.Buffer(f2.payload).bytes());
assertEquals(actual2, "lo");
});
-test("[ws] read unmasked ping / pong frame", async () => {
+Deno.test("[ws] read unmasked ping / pong frame", async () => {
// unmasked ping with payload "Hello"
const buf = new BufReader(
- new Buffer(new Uint8Array([0x89, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f]))
+ new Deno.Buffer(new Uint8Array([0x89, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f]))
);
const ping = await readFrame(buf);
assertEquals(ping.opcode, OpCode.Ping);
- const actual1 = new TextDecoder().decode(new Buffer(ping.payload).bytes());
+ const actual1 = new TextDecoder().decode(
+ new Deno.Buffer(ping.payload).bytes()
+ );
assertEquals(actual1, "Hello");
// prettier-ignore
const pongFrame= [0x8a, 0x85, 0x37, 0xfa, 0x21, 0x3d, 0x7f, 0x9f, 0x4d, 0x51, 0x58]
- const buf2 = new BufReader(new Buffer(new Uint8Array(pongFrame)));
+ const buf2 = new BufReader(new Deno.Buffer(new Uint8Array(pongFrame)));
const pong = await readFrame(buf2);
assertEquals(pong.opcode, OpCode.Pong);
assert(pong.mask !== undefined);
unmask(pong.payload, pong.mask);
- const actual2 = new TextDecoder().decode(new Buffer(pong.payload).bytes());
+ const actual2 = new TextDecoder().decode(
+ new Deno.Buffer(pong.payload).bytes()
+ );
assertEquals(actual2, "Hello");
});
-test("[ws] read unmasked big binary frame", async () => {
+Deno.test("[ws] read unmasked big binary frame", async () => {
const payloadLength = 0x100;
const a = [0x82, 0x7e, 0x01, 0x00];
for (let i = 0; i < payloadLength; i++) {
a.push(i);
}
- const buf = new BufReader(new Buffer(new Uint8Array(a)));
+ const buf = new BufReader(new Deno.Buffer(new Uint8Array(a)));
const bin = await readFrame(buf);
assertEquals(bin.opcode, OpCode.BinaryFrame);
assertEquals(bin.isLastFrame, true);
@@ -118,13 +121,13 @@ test("[ws] read unmasked big binary frame", async () => {
assertEquals(bin.payload.length, payloadLength);
});
-test("[ws] read unmasked bigger binary frame", async () => {
+Deno.test("[ws] read unmasked bigger binary frame", async () => {
const payloadLength = 0x10000;
const a = [0x82, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00];
for (let i = 0; i < payloadLength; i++) {
a.push(i);
}
- const buf = new BufReader(new Buffer(new Uint8Array(a)));
+ const buf = new BufReader(new Deno.Buffer(new Uint8Array(a)));
const bin = await readFrame(buf);
assertEquals(bin.opcode, OpCode.BinaryFrame);
assertEquals(bin.isLastFrame, true);
@@ -132,13 +135,13 @@ test("[ws] read unmasked bigger binary frame", async () => {
assertEquals(bin.payload.length, payloadLength);
});
-test("[ws] createSecAccept", () => {
+Deno.test("[ws] createSecAccept", () => {
const nonce = "dGhlIHNhbXBsZSBub25jZQ==";
const d = createSecAccept(nonce);
assertEquals(d, "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=");
});
-test("[ws] acceptable", () => {
+Deno.test("[ws] acceptable", () => {
const ret = acceptable({
headers: new Headers({
upgrade: "websocket",
@@ -164,7 +167,7 @@ test("[ws] acceptable", () => {
);
});
-test("[ws] acceptable should return false when headers invalid", () => {
+Deno.test("[ws] acceptable should return false when headers invalid", () => {
assertEquals(
acceptable({
headers: new Headers({ "sec-websocket-key": "aaa" }),
@@ -191,20 +194,21 @@ test("[ws] acceptable should return false when headers invalid", () => {
);
});
-test("[ws] connectWebSocket should throw invalid scheme of url", async (): Promise<
- void
-> => {
- await assertThrowsAsync(
- async (): Promise<void> => {
- await connectWebSocket("file://hoge/hoge");
- }
- );
-});
+Deno.test(
+ "[ws] connectWebSocket should throw invalid scheme of url",
+ async (): Promise<void> => {
+ await assertThrowsAsync(
+ async (): Promise<void> => {
+ await connectWebSocket("file://hoge/hoge");
+ }
+ );
+ }
+);
-test("[ws] write and read masked frame", async () => {
+Deno.test("[ws] write and read masked frame", async () => {
const mask = new Uint8Array([0, 1, 2, 3]);
const msg = "hello";
- const buf = new Buffer();
+ const buf = new Deno.Buffer();
const r = new BufReader(buf);
await writeFrame(
{
@@ -223,9 +227,9 @@ test("[ws] write and read masked frame", async () => {
assertEquals(frame.payload, encode(msg));
});
-test("[ws] handshake should not send search when it's empty", async () => {
- const writer = new Buffer();
- const reader = new Buffer(encode("HTTP/1.1 400\r\n"));
+Deno.test("[ws] handshake should not send search when it's empty", async () => {
+ const writer = new Deno.Buffer();
+ const reader = new Deno.Buffer(encode("HTTP/1.1 400\r\n"));
await assertThrowsAsync(
async (): Promise<void> => {
@@ -244,31 +248,32 @@ test("[ws] handshake should not send search when it's empty", async () => {
assertEquals(statusLine, "GET / HTTP/1.1");
});
-test("[ws] handshake should send search correctly", async function wsHandshakeWithSearch(): Promise<
- void
-> {
- const writer = new Buffer();
- const reader = new Buffer(encode("HTTP/1.1 400\r\n"));
-
- await assertThrowsAsync(
- async (): Promise<void> => {
- await handshake(
- new URL("ws://example.com?a=1"),
- new Headers(),
- new BufReader(reader),
- new BufWriter(writer)
- );
- }
- );
+Deno.test(
+ "[ws] handshake should send search correctly",
+ async function wsHandshakeWithSearch(): Promise<void> {
+ const writer = new Deno.Buffer();
+ const reader = new Deno.Buffer(encode("HTTP/1.1 400\r\n"));
+
+ await assertThrowsAsync(
+ async (): Promise<void> => {
+ await handshake(
+ new URL("ws://example.com?a=1"),
+ new Headers(),
+ new BufReader(reader),
+ new BufWriter(writer)
+ );
+ }
+ );
- const tpReader = new TextProtoReader(new BufReader(writer));
- const statusLine = await tpReader.readLine();
+ const tpReader = new TextProtoReader(new BufReader(writer));
+ const statusLine = await tpReader.readLine();
- assertEquals(statusLine, "GET /?a=1 HTTP/1.1");
-});
+ assertEquals(statusLine, "GET /?a=1 HTTP/1.1");
+ }
+);
-test("[ws] ws.close() should use 1000 as close code", async () => {
- const buf = new Buffer();
+Deno.test("[ws] ws.close() should use 1000 as close code", async () => {
+ const buf = new Deno.Buffer();
const bufr = new BufReader(buf);
const conn = dummyConn(buf, buf);
const ws = createWebSocket({ conn });
@@ -279,7 +284,7 @@ test("[ws] ws.close() should use 1000 as close code", async () => {
assertEquals(code, 1000);
});
-function dummyConn(r: Reader, w: Writer): Conn {
+function dummyConn(r: Deno.Reader, w: Deno.Writer): Deno.Conn {
return {
rid: -1,
closeWrite: (): void => {},
@@ -291,7 +296,7 @@ function dummyConn(r: Reader, w: Writer): Conn {
};
}
-function delayedWriter(ms: number, dest: Writer): Writer {
+function delayedWriter(ms: number, dest: Deno.Writer): Deno.Writer {
return {
write(p: Uint8Array): Promise<number> {
return new Promise<number>((resolve) => {
@@ -302,11 +307,11 @@ function delayedWriter(ms: number, dest: Writer): Writer {
},
};
}
-test({
+Deno.test({
name: "[ws] WebSocket.send(), WebSocket.ping() should be exclusive",
fn: async (): Promise<void> => {
- const buf = new Buffer();
- const conn = dummyConn(new Buffer(), delayedWriter(1, buf));
+ const buf = new Deno.Buffer();
+ const conn = dummyConn(new Deno.Buffer(), delayedWriter(1, buf));
const sock = createWebSocket({ conn });
// Ensure send call
await Promise.all([
@@ -330,51 +335,57 @@ test({
},
});
-test("[ws] createSecKeyHasCorrectLength", () => {
+Deno.test("[ws] createSecKeyHasCorrectLength", () => {
// Note: relies on --seed=86 being passed to deno to reproduce failure in
// #4063.
const secKey = createSecKey();
assertEquals(atob(secKey).length, 16);
});
-test("[ws] WebSocket should throw `Deno.errors.ConnectionReset` when peer closed connection without close frame", async () => {
- const buf = new Buffer();
- const eofReader: Deno.Reader = {
- read(_: Uint8Array): Promise<number | null> {
- return Promise.resolve(null);
- },
- };
- const conn = dummyConn(eofReader, buf);
- const sock = createWebSocket({ conn });
- sock.closeForce();
- await assertThrowsAsync(
- () => sock.send("hello"),
- Deno.errors.ConnectionReset
- );
- await assertThrowsAsync(() => sock.ping(), Deno.errors.ConnectionReset);
- await assertThrowsAsync(() => sock.close(0), Deno.errors.ConnectionReset);
-});
-
-test("[ws] WebSocket shouldn't throw `Deno.errors.UnexpectedEof`", async () => {
- const buf = new Buffer();
- const eofReader: Deno.Reader = {
- read(_: Uint8Array): Promise<number | null> {
- return Promise.resolve(null);
- },
- };
- const conn = dummyConn(eofReader, buf);
- const sock = createWebSocket({ conn });
- const it = sock[Symbol.asyncIterator]();
- const { value, done } = await it.next();
- assertEquals(value, undefined);
- assertEquals(done, true);
-});
+Deno.test(
+ "[ws] WebSocket should throw `Deno.errors.ConnectionReset` when peer closed connection without close frame",
+ async () => {
+ const buf = new Deno.Buffer();
+ const eofReader: Deno.Reader = {
+ read(_: Uint8Array): Promise<number | null> {
+ return Promise.resolve(null);
+ },
+ };
+ const conn = dummyConn(eofReader, buf);
+ const sock = createWebSocket({ conn });
+ sock.closeForce();
+ await assertThrowsAsync(
+ () => sock.send("hello"),
+ Deno.errors.ConnectionReset
+ );
+ await assertThrowsAsync(() => sock.ping(), Deno.errors.ConnectionReset);
+ await assertThrowsAsync(() => sock.close(0), Deno.errors.ConnectionReset);
+ }
+);
+
+Deno.test(
+ "[ws] WebSocket shouldn't throw `Deno.errors.UnexpectedEof`",
+ async () => {
+ const buf = new Deno.Buffer();
+ const eofReader: Deno.Reader = {
+ read(_: Uint8Array): Promise<number | null> {
+ return Promise.resolve(null);
+ },
+ };
+ const conn = dummyConn(eofReader, buf);
+ const sock = createWebSocket({ conn });
+ const it = sock[Symbol.asyncIterator]();
+ const { value, done } = await it.next();
+ assertEquals(value, undefined);
+ assertEquals(done, true);
+ }
+);
-test({
+Deno.test({
name:
"[ws] WebSocket should reject sending promise when connection reset forcely",
fn: async () => {
- const buf = new Buffer();
+ const buf = new Deno.Buffer();
let timer: number | undefined;
const lazyWriter: Deno.Writer = {
write(_: Uint8Array): Promise<number> {
@@ -404,7 +415,7 @@ test({
},
});
-test("[ws] WebSocket should act as asyncIterator", async () => {
+Deno.test("[ws] WebSocket should act as asyncIterator", async () => {
const pingHello = new Uint8Array([0x89, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f]);
const hello = new Uint8Array([0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f]);
const close = new Uint8Array([0x88, 0x04, 0x03, 0xf3, 0x34, 0x32]);
@@ -418,7 +429,7 @@ test("[ws] WebSocket should act as asyncIterator", async () => {
let frame = Frames.ping;
- const reader: Reader = {
+ const reader: Deno.Reader = {
read(p: Uint8Array): Promise<number | null> {
if (frame === Frames.ping) {
frame = Frames.hello;
@@ -442,7 +453,7 @@ test("[ws] WebSocket should act as asyncIterator", async () => {
},
};
- const conn = dummyConn(reader, new Buffer());
+ const conn = dummyConn(reader, new Deno.Buffer());
const sock = createWebSocket({ conn });
const events = [];