1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-22 15:06:54 -05:00

refactor: Don't destructure the Deno namespace (#6268)

This commit is contained in:
Nayeem Rahman 2020-06-12 20:23:38 +01:00 committed by GitHub
parent 26bf56afda
commit 1fff6f55c3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
111 changed files with 1632 additions and 1695 deletions

View file

@ -1,10 +1,8 @@
const { stdout, open, copy, args } = Deno;
async function main(): Promise<void> { async function main(): Promise<void> {
for (let i = 1; i < args.length; i++) { for (let i = 1; i < Deno.args.length; i++) {
const filename = args[i]; const filename = Deno.args[i];
const file = await open(filename); const file = await Deno.open(filename);
await copy(file, stdout); await Deno.copy(file, Deno.stdout);
} }
} }

View file

@ -1,10 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { assert, assertEquals } from "../../std/testing/asserts.ts"; import { assert, assertEquals } from "../../std/testing/asserts.ts";
const { compile, transpileOnly, bundle, test } = Deno;
test("compilerApiCompileSources", async function () { Deno.test("compilerApiCompileSources", async function () {
const [diagnostics, actual] = await compile("/foo.ts", { const [diagnostics, actual] = await Deno.compile("/foo.ts", {
"/foo.ts": `import * as bar from "./bar.ts";\n\nconsole.log(bar);\n`, "/foo.ts": `import * as bar from "./bar.ts";\n\nconsole.log(bar);\n`,
"/bar.ts": `export const bar = "bar";\n`, "/bar.ts": `export const bar = "bar";\n`,
}); });
@ -18,8 +16,8 @@ test("compilerApiCompileSources", async function () {
]); ]);
}); });
test("compilerApiCompileNoSources", async function () { Deno.test("compilerApiCompileNoSources", async function () {
const [diagnostics, actual] = await compile("./subdir/mod1.ts"); const [diagnostics, actual] = await Deno.compile("./subdir/mod1.ts");
assert(diagnostics == null); assert(diagnostics == null);
assert(actual); assert(actual);
const keys = Object.keys(actual); const keys = Object.keys(actual);
@ -28,8 +26,8 @@ test("compilerApiCompileNoSources", async function () {
assert(keys[1].endsWith("print_hello.js")); assert(keys[1].endsWith("print_hello.js"));
}); });
test("compilerApiCompileOptions", async function () { Deno.test("compilerApiCompileOptions", async function () {
const [diagnostics, actual] = await compile( const [diagnostics, actual] = await Deno.compile(
"/foo.ts", "/foo.ts",
{ {
"/foo.ts": `export const foo = "foo";`, "/foo.ts": `export const foo = "foo";`,
@ -45,8 +43,8 @@ test("compilerApiCompileOptions", async function () {
assert(actual["/foo.js"].startsWith("define(")); assert(actual["/foo.js"].startsWith("define("));
}); });
test("compilerApiCompileLib", async function () { Deno.test("compilerApiCompileLib", async function () {
const [diagnostics, actual] = await compile( const [diagnostics, actual] = await Deno.compile(
"/foo.ts", "/foo.ts",
{ {
"/foo.ts": `console.log(document.getElementById("foo")); "/foo.ts": `console.log(document.getElementById("foo"));
@ -61,8 +59,8 @@ test("compilerApiCompileLib", async function () {
assertEquals(Object.keys(actual), ["/foo.js.map", "/foo.js"]); assertEquals(Object.keys(actual), ["/foo.js.map", "/foo.js"]);
}); });
test("compilerApiCompileTypes", async function () { Deno.test("compilerApiCompileTypes", async function () {
const [diagnostics, actual] = await compile( const [diagnostics, actual] = await Deno.compile(
"/foo.ts", "/foo.ts",
{ {
"/foo.ts": `console.log(Foo.bar);`, "/foo.ts": `console.log(Foo.bar);`,
@ -76,8 +74,8 @@ test("compilerApiCompileTypes", async function () {
assertEquals(Object.keys(actual), ["/foo.js.map", "/foo.js"]); assertEquals(Object.keys(actual), ["/foo.js.map", "/foo.js"]);
}); });
test("transpileOnlyApi", async function () { Deno.test("transpileOnlyApi", async function () {
const actual = await transpileOnly({ const actual = await Deno.transpileOnly({
"foo.ts": `export enum Foo { Foo, Bar, Baz };\n`, "foo.ts": `export enum Foo { Foo, Bar, Baz };\n`,
}); });
assert(actual); assert(actual);
@ -86,8 +84,8 @@ test("transpileOnlyApi", async function () {
assert(actual["foo.ts"].map); assert(actual["foo.ts"].map);
}); });
test("transpileOnlyApiConfig", async function () { Deno.test("transpileOnlyApiConfig", async function () {
const actual = await transpileOnly( const actual = await Deno.transpileOnly(
{ {
"foo.ts": `export enum Foo { Foo, Bar, Baz };\n`, "foo.ts": `export enum Foo { Foo, Bar, Baz };\n`,
}, },
@ -102,8 +100,8 @@ test("transpileOnlyApiConfig", async function () {
assert(actual["foo.ts"].map == null); assert(actual["foo.ts"].map == null);
}); });
test("bundleApiSources", async function () { Deno.test("bundleApiSources", async function () {
const [diagnostics, actual] = await bundle("/foo.ts", { const [diagnostics, actual] = await Deno.bundle("/foo.ts", {
"/foo.ts": `export * from "./bar.ts";\n`, "/foo.ts": `export * from "./bar.ts";\n`,
"/bar.ts": `export const bar = "bar";\n`, "/bar.ts": `export const bar = "bar";\n`,
}); });
@ -112,15 +110,15 @@ test("bundleApiSources", async function () {
assert(actual.includes(`__exp["bar"]`)); assert(actual.includes(`__exp["bar"]`));
}); });
test("bundleApiNoSources", async function () { Deno.test("bundleApiNoSources", async function () {
const [diagnostics, actual] = await bundle("./subdir/mod1.ts"); const [diagnostics, actual] = await Deno.bundle("./subdir/mod1.ts");
assert(diagnostics == null); assert(diagnostics == null);
assert(actual.includes(`__instantiate("mod1")`)); assert(actual.includes(`__instantiate("mod1")`));
assert(actual.includes(`__exp["printHello3"]`)); assert(actual.includes(`__exp["printHello3"]`));
}); });
test("bundleApiConfig", async function () { Deno.test("bundleApiConfig", async function () {
const [diagnostics, actual] = await bundle( const [diagnostics, actual] = await Deno.bundle(
"/foo.ts", "/foo.ts",
{ {
"/foo.ts": `// random comment\nexport * from "./bar.ts";\n`, "/foo.ts": `// random comment\nexport * from "./bar.ts";\n`,
@ -134,8 +132,8 @@ test("bundleApiConfig", async function () {
assert(!actual.includes(`random`)); assert(!actual.includes(`random`));
}); });
test("bundleApiJsModules", async function () { Deno.test("bundleApiJsModules", async function () {
const [diagnostics, actual] = await bundle("/foo.js", { const [diagnostics, actual] = await Deno.bundle("/foo.js", {
"/foo.js": `export * from "./bar.js";\n`, "/foo.js": `export * from "./bar.js";\n`,
"/bar.js": `export const bar = "bar";\n`, "/bar.js": `export const bar = "bar";\n`,
}); });
@ -143,8 +141,8 @@ test("bundleApiJsModules", async function () {
assert(actual.includes(`System.register("bar",`)); assert(actual.includes(`System.register("bar",`));
}); });
test("diagnosticsTest", async function () { Deno.test("diagnosticsTest", async function () {
const [diagnostics] = await compile("/foo.ts", { const [diagnostics] = await Deno.compile("/foo.ts", {
"/foo.ts": `document.getElementById("foo");`, "/foo.ts": `document.getElementById("foo");`,
}); });
assert(Array.isArray(diagnostics)); assert(Array.isArray(diagnostics));

View file

@ -1,14 +1,12 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
const { args, readFileSync, writeFileSync, exit } = Deno; const name = Deno.args[0];
const name = args[0];
const test: { [key: string]: Function } = { const test: { [key: string]: Function } = {
read(files: string[]): void { read(files: string[]): void {
files.forEach((file) => readFileSync(file)); files.forEach((file) => Deno.readFileSync(file));
}, },
write(files: string[]): void { write(files: string[]): void {
files.forEach((file) => files.forEach((file) =>
writeFileSync(file, new Uint8Array(0), { append: true }) Deno.writeFileSync(file, new Uint8Array(0), { append: true })
); );
}, },
netFetch(hosts: string[]): void { netFetch(hosts: string[]): void {
@ -40,7 +38,7 @@ const test: { [key: string]: Function } = {
if (!test[name]) { if (!test[name]) {
console.log("Unknown test:", name); console.log("Unknown test:", name);
exit(1); Deno.exit(1);
} }
test[name](args.slice(1)); test[name](Deno.args.slice(1));

View file

@ -1,11 +1,10 @@
const { args, listen, copy } = Deno; const addr = Deno.args[1] || "0.0.0.0:4544";
const addr = args[1] || "0.0.0.0:4544";
const [hostname, port] = addr.split(":"); 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); console.log("listening on", addr);
listener.accept().then( listener.accept().then(
async (conn): Promise<void> => { async (conn): Promise<void> => {
await copy(conn, conn); await Deno.copy(conn, conn);
conn.close(); conn.close();
listener.close(); listener.close();
} }

View file

@ -1,23 +1,21 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
const { args, listen, env, exit, makeTempDirSync, readFileSync, run } = Deno; const name = Deno.args[0];
const name = args[0];
const test: { [key: string]: Function } = { const test: { [key: string]: Function } = {
readRequired(): Promise<void> { readRequired(): Promise<void> {
readFileSync("README.md"); Deno.readFileSync("README.md");
return Promise.resolve(); return Promise.resolve();
}, },
writeRequired(): void { writeRequired(): void {
makeTempDirSync(); Deno.makeTempDirSync();
}, },
envRequired(): void { envRequired(): void {
env.get("home"); Deno.env.get("home");
}, },
netRequired(): void { netRequired(): void {
listen({ transport: "tcp", port: 4541 }); Deno.listen({ transport: "tcp", port: 4541 });
}, },
runRequired(): void { runRequired(): void {
run({ Deno.run({
cmd: [ cmd: [
"python", "python",
"-c", "-c",
@ -29,7 +27,7 @@ const test: { [key: string]: Function } = {
if (!test[name]) { if (!test[name]) {
console.log("Unknown test:", name); console.log("Unknown test:", name);
exit(1); Deno.exit(1);
} }
test[name](); test[name]();

View file

@ -1,3 +1 @@
const { stderr } = Deno; Deno.stderr.write(new TextEncoder().encode("x"));
stderr.write(new TextEncoder().encode("x"));

View file

@ -1,3 +1 @@
const { stdout } = Deno; Deno.stdout.write(new TextEncoder().encode("a"));
stdout.write(new TextEncoder().encode("a"));

View file

@ -12,9 +12,6 @@ import {
unitTest, unitTest,
} from "./test_util.ts"; } 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. // N controls how many iterations of certain checks are performed.
const N = 100; const N = 100;
let testBytes: Uint8Array | null; 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 initial contents of buf corresponds to the string s;
// the result is the final contents of buf returned as a string. // the result is the final contents of buf returned as a string.
async function fillBytes( async function fillBytes(
buf: Buffer, buf: Deno.Buffer,
s: string, s: string,
n: number, n: number,
fub: Uint8Array fub: Uint8Array
@ -62,7 +59,11 @@ async function fillBytes(
// Empty buf through repeated reads into fub. // Empty buf through repeated reads into fub.
// The initial contents of buf corresponds to the string s. // 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); check(buf, s);
while (true) { while (true) {
const r = await buf.read(fub); const r = await buf.read(fub);
@ -86,7 +87,7 @@ unitTest(function bufferNewBuffer(): void {
init(); init();
assert(testBytes); assert(testBytes);
assert(testString); assert(testString);
const buf = new Buffer(testBytes.buffer as ArrayBuffer); const buf = new Deno.Buffer(testBytes.buffer as ArrayBuffer);
check(buf, testString); check(buf, testString);
}); });
@ -94,7 +95,7 @@ unitTest(async function bufferBasicOperations(): Promise<void> {
init(); init();
assert(testBytes); assert(testBytes);
assert(testString); assert(testString);
const buf = new Buffer(); const buf = new Deno.Buffer();
for (let i = 0; i < 5; i++) { for (let i = 0; i < 5; i++) {
check(buf, ""); check(buf, "");
@ -133,7 +134,7 @@ unitTest(async function bufferBasicOperations(): Promise<void> {
unitTest(async function bufferReadEmptyAtEOF(): Promise<void> { unitTest(async function bufferReadEmptyAtEOF(): Promise<void> {
// check that EOF of 'buf' is not reached (even though it's empty) if // 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) // 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 zeroLengthTmp = new Uint8Array(0);
const result = await buf.read(zeroLengthTmp); const result = await buf.read(zeroLengthTmp);
assertEquals(result, 0); assertEquals(result, 0);
@ -141,7 +142,7 @@ unitTest(async function bufferReadEmptyAtEOF(): Promise<void> {
unitTest(async function bufferLargeByteWrites(): Promise<void> { unitTest(async function bufferLargeByteWrites(): Promise<void> {
init(); init();
const buf = new Buffer(); const buf = new Deno.Buffer();
const limit = 9; const limit = 9;
for (let i = 3; i < limit; i += 3) { for (let i = 3; i < limit; i += 3) {
const s = await fillBytes(buf, "", 5, testBytes!); const s = await fillBytes(buf, "", 5, testBytes!);
@ -155,7 +156,7 @@ unitTest(async function bufferTooLargeByteWrites(): Promise<void> {
const tmp = new Uint8Array(72); const tmp = new Uint8Array(72);
const growLen = Number.MAX_VALUE; const growLen = Number.MAX_VALUE;
const xBytes = repeat("x", 0); 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); await buf.read(tmp);
let err; let err;
@ -173,7 +174,7 @@ unitTest(async function bufferLargeByteReads(): Promise<void> {
init(); init();
assert(testBytes); assert(testBytes);
assert(testString); assert(testString);
const buf = new Buffer(); const buf = new Deno.Buffer();
for (let i = 3; i < 30; i += 3) { for (let i = 3; i < 30; i += 3) {
const n = Math.floor(testBytes.byteLength / i); const n = Math.floor(testBytes.byteLength / i);
const s = await fillBytes(buf, "", 5, testBytes.subarray(0, n)); const s = await fillBytes(buf, "", 5, testBytes.subarray(0, n));
@ -183,7 +184,7 @@ unitTest(async function bufferLargeByteReads(): Promise<void> {
}); });
unitTest(function bufferCapWithPreallocatedSlice(): void { unitTest(function bufferCapWithPreallocatedSlice(): void {
const buf = new Buffer(new ArrayBuffer(10)); const buf = new Deno.Buffer(new ArrayBuffer(10));
assertEquals(buf.capacity, 10); assertEquals(buf.capacity, 10);
}); });
@ -191,7 +192,7 @@ unitTest(async function bufferReadFrom(): Promise<void> {
init(); init();
assert(testBytes); assert(testBytes);
assert(testString); assert(testString);
const buf = new Buffer(); const buf = new Deno.Buffer();
for (let i = 3; i < 30; i += 3) { for (let i = 3; i < 30; i += 3) {
const s = await fillBytes( const s = await fillBytes(
buf, buf,
@ -199,13 +200,13 @@ unitTest(async function bufferReadFrom(): Promise<void> {
5, 5,
testBytes.subarray(0, Math.floor(testBytes.byteLength / i)) testBytes.subarray(0, Math.floor(testBytes.byteLength / i))
); );
const b = new Buffer(); const b = new Deno.Buffer();
await b.readFrom(buf); await b.readFrom(buf);
const fub = new Uint8Array(testString.length); const fub = new Uint8Array(testString.length);
await empty(b, s, fub); await empty(b, s, fub);
} }
assertThrowsAsync(async function () { 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(); init();
assert(testBytes); assert(testBytes);
assert(testString); assert(testString);
const buf = new Buffer(); const buf = new Deno.Buffer();
for (let i = 3; i < 30; i += 3) { for (let i = 3; i < 30; i += 3) {
const s = await fillBytes( const s = await fillBytes(
buf, buf,
@ -221,13 +222,13 @@ unitTest(async function bufferReadFromSync(): Promise<void> {
5, 5,
testBytes.subarray(0, Math.floor(testBytes.byteLength / i)) testBytes.subarray(0, Math.floor(testBytes.byteLength / i))
); );
const b = new Buffer(); const b = new Deno.Buffer();
b.readFromSync(buf); b.readFromSync(buf);
const fub = new Uint8Array(testString.length); const fub = new Uint8Array(testString.length);
await empty(b, s, fub); await empty(b, s, fub);
} }
assertThrows(function () { 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]) { for (const startLen of [0, 100, 1000, 10000, 100000]) {
const xBytes = repeat("x", startLen); const xBytes = repeat("x", startLen);
for (const growLen of [0, 100, 1000, 10000, 100000]) { 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. // If we read, this affects buf.off, which is good to test.
const nread = (await buf.read(tmp)) ?? 0; const nread = (await buf.read(tmp)) ?? 0;
buf.grow(growLen); buf.grow(growLen);
@ -258,8 +259,8 @@ unitTest(async function bufferTestGrow(): Promise<void> {
unitTest(async function testReadAll(): Promise<void> { unitTest(async function testReadAll(): Promise<void> {
init(); init();
assert(testBytes); assert(testBytes);
const reader = new Buffer(testBytes.buffer as ArrayBuffer); const reader = new Deno.Buffer(testBytes.buffer as ArrayBuffer);
const actualBytes = await readAll(reader); const actualBytes = await Deno.readAll(reader);
assertEquals(testBytes.byteLength, actualBytes.byteLength); assertEquals(testBytes.byteLength, actualBytes.byteLength);
for (let i = 0; i < testBytes.length; ++i) { for (let i = 0; i < testBytes.length; ++i) {
assertEquals(testBytes[i], actualBytes[i]); assertEquals(testBytes[i], actualBytes[i]);
@ -269,8 +270,8 @@ unitTest(async function testReadAll(): Promise<void> {
unitTest(function testReadAllSync(): void { unitTest(function testReadAllSync(): void {
init(); init();
assert(testBytes); assert(testBytes);
const reader = new Buffer(testBytes.buffer as ArrayBuffer); const reader = new Deno.Buffer(testBytes.buffer as ArrayBuffer);
const actualBytes = readAllSync(reader); const actualBytes = Deno.readAllSync(reader);
assertEquals(testBytes.byteLength, actualBytes.byteLength); assertEquals(testBytes.byteLength, actualBytes.byteLength);
for (let i = 0; i < testBytes.length; ++i) { for (let i = 0; i < testBytes.length; ++i) {
assertEquals(testBytes[i], actualBytes[i]); assertEquals(testBytes[i], actualBytes[i]);
@ -280,8 +281,8 @@ unitTest(function testReadAllSync(): void {
unitTest(async function testWriteAll(): Promise<void> { unitTest(async function testWriteAll(): Promise<void> {
init(); init();
assert(testBytes); assert(testBytes);
const writer = new Buffer(); const writer = new Deno.Buffer();
await writeAll(writer, testBytes); await Deno.writeAll(writer, testBytes);
const actualBytes = writer.bytes(); const actualBytes = writer.bytes();
assertEquals(testBytes.byteLength, actualBytes.byteLength); assertEquals(testBytes.byteLength, actualBytes.byteLength);
for (let i = 0; i < testBytes.length; ++i) { for (let i = 0; i < testBytes.length; ++i) {
@ -292,8 +293,8 @@ unitTest(async function testWriteAll(): Promise<void> {
unitTest(function testWriteAllSync(): void { unitTest(function testWriteAllSync(): void {
init(); init();
assert(testBytes); assert(testBytes);
const writer = new Buffer(); const writer = new Deno.Buffer();
writeAllSync(writer, testBytes); Deno.writeAllSync(writer, testBytes);
const actualBytes = writer.bytes(); const actualBytes = writer.bytes();
assertEquals(testBytes.byteLength, actualBytes.byteLength); assertEquals(testBytes.byteLength, actualBytes.byteLength);
for (let i = 0; i < testBytes.length; ++i) { for (let i = 0; i < testBytes.length; ++i) {

View file

@ -5,20 +5,11 @@ import {
assertStringContains, assertStringContains,
unitTest, unitTest,
} from "./test_util.ts"; } from "./test_util.ts";
const {
kill,
run,
readFile,
open,
makeTempDir,
writeFile,
writeFileSync,
} = Deno;
unitTest(function runPermissions(): void { unitTest(function runPermissions(): void {
let caughtError = false; let caughtError = false;
try { try {
run({ cmd: ["python", "-c", "print('hello world')"] }); Deno.run({ cmd: ["python", "-c", "print('hello world')"] });
} catch (e) { } catch (e) {
caughtError = true; caughtError = true;
assert(e instanceof Deno.errors.PermissionDenied); assert(e instanceof Deno.errors.PermissionDenied);
@ -27,7 +18,7 @@ unitTest(function runPermissions(): void {
}); });
unitTest({ perms: { run: true } }, async function runSuccess(): Promise<void> { unitTest({ perms: { run: true } }, async function runSuccess(): Promise<void> {
const p = run({ const p = Deno.run({
cmd: ["python", "-c", "print('hello world')"], cmd: ["python", "-c", "print('hello world')"],
stdout: "piped", stdout: "piped",
stderr: "null", stderr: "null",
@ -43,7 +34,7 @@ unitTest({ perms: { run: true } }, async function runSuccess(): Promise<void> {
unitTest( unitTest(
{ perms: { run: true } }, { perms: { run: true } },
async function runCommandFailedWithCode(): Promise<void> { async function runCommandFailedWithCode(): Promise<void> {
const p = run({ const p = Deno.run({
cmd: ["python", "-c", "import sys;sys.exit(41 + 1)"], cmd: ["python", "-c", "import sys;sys.exit(41 + 1)"],
}); });
const status = await p.status(); const status = await p.status();
@ -61,7 +52,7 @@ unitTest(
perms: { run: true }, perms: { run: true },
}, },
async function runCommandFailedWithSignal(): Promise<void> { async function runCommandFailedWithSignal(): Promise<void> {
const p = run({ const p = Deno.run({
cmd: ["python", "-c", "import os;os.kill(os.getpid(), 9)"], cmd: ["python", "-c", "import os;os.kill(os.getpid(), 9)"],
}); });
const status = await p.status(); const status = await p.status();
@ -75,7 +66,7 @@ unitTest(
unitTest({ perms: { run: true } }, function runNotFound(): void { unitTest({ perms: { run: true } }, function runNotFound(): void {
let error; let error;
try { try {
run({ cmd: ["this file hopefully doesn't exist"] }); Deno.run({ cmd: ["this file hopefully doesn't exist"] });
} catch (e) { } catch (e) {
error = e; error = e;
} }
@ -87,7 +78,7 @@ unitTest(
{ perms: { write: true, run: true } }, { perms: { write: true, run: true } },
async function runWithCwdIsAsync(): Promise<void> { async function runWithCwdIsAsync(): Promise<void> {
const enc = new TextEncoder(); 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 exitCodeFile = "deno_was_here";
const pyProgramFile = "poll_exit.py"; const pyProgramFile = "poll_exit.py";
@ -107,8 +98,8 @@ while True:
pass pass
`; `;
writeFileSync(`${cwd}/${pyProgramFile}.py`, enc.encode(pyProgram)); Deno.writeFileSync(`${cwd}/${pyProgramFile}.py`, enc.encode(pyProgram));
const p = run({ const p = Deno.run({
cwd, cwd,
cmd: ["python", `${pyProgramFile}.py`], cmd: ["python", `${pyProgramFile}.py`],
}); });
@ -116,7 +107,7 @@ while True:
// Write the expected exit code *after* starting python. // Write the expected exit code *after* starting python.
// This is how we verify that `run()` is actually asynchronous. // This is how we verify that `run()` is actually asynchronous.
const code = 84; const code = 84;
writeFileSync(`${cwd}/${exitCodeFile}`, enc.encode(`${code}`)); Deno.writeFileSync(`${cwd}/${exitCodeFile}`, enc.encode(`${code}`));
const status = await p.status(); const status = await p.status();
assertEquals(status.success, false); assertEquals(status.success, false);
@ -129,7 +120,7 @@ while True:
unitTest({ perms: { run: true } }, async function runStdinPiped(): Promise< unitTest({ perms: { run: true } }, async function runStdinPiped(): Promise<
void void
> { > {
const p = run({ const p = Deno.run({
cmd: ["python", "-c", "import sys; assert 'hello' == sys.stdin.read();"], cmd: ["python", "-c", "import sys; assert 'hello' == sys.stdin.read();"],
stdin: "piped", stdin: "piped",
}); });
@ -153,7 +144,7 @@ unitTest({ perms: { run: true } }, async function runStdinPiped(): Promise<
unitTest({ perms: { run: true } }, async function runStdoutPiped(): Promise< unitTest({ perms: { run: true } }, async function runStdoutPiped(): Promise<
void void
> { > {
const p = run({ const p = Deno.run({
cmd: ["python", "-c", "import sys; sys.stdout.write('hello')"], cmd: ["python", "-c", "import sys; sys.stdout.write('hello')"],
stdout: "piped", stdout: "piped",
}); });
@ -182,7 +173,7 @@ unitTest({ perms: { run: true } }, async function runStdoutPiped(): Promise<
unitTest({ perms: { run: true } }, async function runStderrPiped(): Promise< unitTest({ perms: { run: true } }, async function runStderrPiped(): Promise<
void void
> { > {
const p = run({ const p = Deno.run({
cmd: ["python", "-c", "import sys; sys.stderr.write('hello')"], cmd: ["python", "-c", "import sys; sys.stderr.write('hello')"],
stderr: "piped", stderr: "piped",
}); });
@ -209,7 +200,7 @@ unitTest({ perms: { run: true } }, async function runStderrPiped(): Promise<
}); });
unitTest({ perms: { run: true } }, async function runOutput(): Promise<void> { 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')"], cmd: ["python", "-c", "import sys; sys.stdout.write('hello')"],
stdout: "piped", stdout: "piped",
}); });
@ -222,7 +213,7 @@ unitTest({ perms: { run: true } }, async function runOutput(): Promise<void> {
unitTest({ perms: { run: true } }, async function runStderrOutput(): Promise< unitTest({ perms: { run: true } }, async function runStderrOutput(): Promise<
void void
> { > {
const p = run({ const p = Deno.run({
cmd: ["python", "-c", "import sys; sys.stderr.write('error')"], cmd: ["python", "-c", "import sys; sys.stderr.write('error')"],
stderr: "piped", stderr: "piped",
}); });
@ -235,14 +226,14 @@ unitTest({ perms: { run: true } }, async function runStderrOutput(): Promise<
unitTest( unitTest(
{ perms: { run: true, write: true, read: true } }, { perms: { run: true, write: true, read: true } },
async function runRedirectStdoutStderr(): Promise<void> { async function runRedirectStdoutStderr(): Promise<void> {
const tempDir = await makeTempDir(); const tempDir = await Deno.makeTempDir();
const fileName = tempDir + "/redirected_stdio.txt"; const fileName = tempDir + "/redirected_stdio.txt";
const file = await open(fileName, { const file = await Deno.open(fileName, {
create: true, create: true,
write: true, write: true,
}); });
const p = run({ const p = Deno.run({
cmd: [ cmd: [
"python", "python",
"-c", "-c",
@ -256,7 +247,7 @@ unitTest(
p.close(); p.close();
file.close(); file.close();
const fileContents = await readFile(fileName); const fileContents = await Deno.readFile(fileName);
const decoder = new TextDecoder(); const decoder = new TextDecoder();
const text = decoder.decode(fileContents); const text = decoder.decode(fileContents);
@ -268,13 +259,13 @@ unitTest(
unitTest( unitTest(
{ perms: { run: true, write: true, read: true } }, { perms: { run: true, write: true, read: true } },
async function runRedirectStdin(): Promise<void> { async function runRedirectStdin(): Promise<void> {
const tempDir = await makeTempDir(); const tempDir = await Deno.makeTempDir();
const fileName = tempDir + "/redirected_stdio.txt"; const fileName = tempDir + "/redirected_stdio.txt";
const encoder = new TextEncoder(); const encoder = new TextEncoder();
await writeFile(fileName, encoder.encode("hello")); await Deno.writeFile(fileName, encoder.encode("hello"));
const file = await open(fileName); const file = await Deno.open(fileName);
const p = run({ const p = Deno.run({
cmd: ["python", "-c", "import sys; assert 'hello' == sys.stdin.read();"], cmd: ["python", "-c", "import sys; assert 'hello' == sys.stdin.read();"],
stdin: file.rid, stdin: file.rid,
}); });
@ -287,7 +278,7 @@ unitTest(
); );
unitTest({ perms: { run: true } }, async function runEnv(): Promise<void> { unitTest({ perms: { run: true } }, async function runEnv(): Promise<void> {
const p = run({ const p = Deno.run({
cmd: [ cmd: [
"python", "python",
"-c", "-c",
@ -306,7 +297,7 @@ unitTest({ perms: { run: true } }, async function runEnv(): Promise<void> {
}); });
unitTest({ perms: { run: true } }, async function runClose(): Promise<void> { unitTest({ perms: { run: true } }, async function runClose(): Promise<void> {
const p = run({ const p = Deno.run({
cmd: [ cmd: [
"python", "python",
"-c", "-c",
@ -340,7 +331,7 @@ unitTest(function killPermissions(): void {
// subprocess we can safely kill. Instead we send SIGCONT to the current // 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 // process - assuming that Deno does not have a special handler set for it
// and will just continue even if a signal is erroneously sent. // 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) { } catch (e) {
caughtError = true; caughtError = true;
assert(e instanceof Deno.errors.PermissionDenied); assert(e instanceof Deno.errors.PermissionDenied);
@ -349,12 +340,12 @@ unitTest(function killPermissions(): void {
}); });
unitTest({ perms: { run: true } }, async function killSuccess(): Promise<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)"], cmd: ["python", "-c", "from time import sleep; sleep(10000)"],
}); });
assertEquals(Deno.Signal.SIGINT, 2); assertEquals(Deno.Signal.SIGINT, 2);
kill(p.pid, Deno.Signal.SIGINT); Deno.kill(p.pid, Deno.Signal.SIGINT);
const status = await p.status(); const status = await p.status();
assertEquals(status.success, false); assertEquals(status.success, false);
@ -371,7 +362,7 @@ unitTest({ perms: { run: true } }, async function killSuccess(): Promise<void> {
}); });
unitTest({ perms: { run: true } }, function killFailed(): void { unitTest({ perms: { run: true } }, function killFailed(): void {
const p = run({ const p = Deno.run({
cmd: ["python", "-c", "from time import sleep; sleep(10000)"], cmd: ["python", "-c", "from time import sleep; sleep(10000)"],
}); });
assert(!p.stdin); assert(!p.stdin);
@ -379,7 +370,7 @@ unitTest({ perms: { run: true } }, function killFailed(): void {
let err; let err;
try { try {
kill(p.pid, 12345); Deno.kill(p.pid, 12345);
} catch (e) { } catch (e) {
err = e; err = e;
} }

View file

@ -20,11 +20,10 @@ would be good to be able to query the system for how many open resources there
are. are.
```ts ```ts
const { resources, close } = Deno; console.log(Deno.resources());
console.log(resources());
// { 0: "stdin", 1: "stdout", 2: "stderr" } // { 0: "stdin", 1: "stdout", 2: "stderr" }
close(0); Deno.close(0);
console.log(resources()); console.log(Deno.resources());
// { 1: "stdout", 2: "stderr" } // { 1: "stdout", 2: "stderr" }
``` ```

View file

@ -1,16 +1,14 @@
import { assert, DenoStdInternalError } from "./assert.ts"; import { assert, DenoStdInternalError } from "./assert.ts";
import { assertThrows } from "../testing/asserts.ts"; import { assertThrows } from "../testing/asserts.ts";
const { test } = Deno; Deno.test({
test({
name: "assert valid scenario", name: "assert valid scenario",
fn(): void { fn(): void {
assert(true); assert(true);
}, },
}); });
test({ Deno.test({
name: "assert invalid scenario, no message", name: "assert invalid scenario, no message",
fn(): void { fn(): void {
assertThrows(() => { assertThrows(() => {
@ -18,7 +16,7 @@ test({
}, DenoStdInternalError); }, DenoStdInternalError);
}, },
}); });
test({ Deno.test({
name: "assert invalid scenario, with message", name: "assert invalid scenario, with message",
fn(): void { fn(): void {
assertThrows( assertThrows(

View file

@ -1,9 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { test } = Deno;
import { assertEquals, assert } from "../testing/asserts.ts"; import { assertEquals, assert } from "../testing/asserts.ts";
import { deepAssign } from "./deep_assign.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 date = new Date("1979-05-27T07:32:00Z");
const reg = RegExp(/DENOWOWO/); const reg = RegExp(/DENOWOWO/);
const obj1 = { deno: { bar: { deno: ["is", "not", "node"] } } }; const obj1 = { deno: { bar: { deno: ["is", "not", "node"] } } };

View file

@ -3,10 +3,8 @@
import { parse } from "../../yaml.ts"; 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 document = new TextDecoder().decode(yml);
const obj = parse(document) as object; const obj = parse(document) as object;

View file

@ -2,12 +2,9 @@
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license. // Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da // https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { Type } from "../type.ts"; import { Type } from "../type.ts";
import { Any } from "../utils.ts"; import { Any } from "../utils.ts";
const { Buffer } = Deno;
// [ 64, 65, 66 ] -> [ padding, CR, LF ] // [ 64, 65, 66 ] -> [ padding, CR, LF ]
const BASE64_MAP = const BASE64_MAP =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r"; "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";
@ -72,7 +69,7 @@ function constructYamlBinary(data: string): Deno.Buffer {
result.push((bits >> 4) & 0xff); result.push((bits >> 4) & 0xff);
} }
return new Buffer(new Uint8Array(result)); return new Deno.Buffer(new Uint8Array(result));
} }
function representYamlBinary(object: Uint8Array): string { function representYamlBinary(object: Uint8Array): string {
@ -119,7 +116,7 @@ function representYamlBinary(object: Uint8Array): string {
} }
function isBinary(obj: Any): obj is Deno.Buffer { function isBinary(obj: Any): obj is Deno.Buffer {
const buf = new Buffer(); const buf = new Deno.Buffer();
try { try {
if (0 > buf.readFromSync(obj as Deno.Buffer)) return true; if (0 > buf.readFromSync(obj as Deno.Buffer)) return true;
return false; return false;

View file

@ -1,6 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { encode, decode, decodeString } from "./base64.ts"; import { encode, decode, decodeString } from "./base64.ts";
@ -21,25 +19,25 @@ const testsetBinary = [
[new TextEncoder().encode("\x00\x00\x00\x00"), "AAAAAA=="], [new TextEncoder().encode("\x00\x00\x00\x00"), "AAAAAA=="],
]; ];
test("[encoding/base64] testBase64EncodeString", () => { Deno.test("[encoding/base64] testBase64EncodeString", () => {
for (const [input, output] of testsetString) { for (const [input, output] of testsetString) {
assertEquals(encode(input), output); assertEquals(encode(input), output);
} }
}); });
test("[encoding/base64] testBase64DecodeString", () => { Deno.test("[encoding/base64] testBase64DecodeString", () => {
for (const [input, output] of testsetString) { for (const [input, output] of testsetString) {
assertEquals(decodeString(output), input); assertEquals(decodeString(output), input);
} }
}); });
test("[encoding/base64] testBase64EncodeBinary", () => { Deno.test("[encoding/base64] testBase64EncodeBinary", () => {
for (const [input, output] of testsetBinary) { for (const [input, output] of testsetBinary) {
assertEquals(encode(input), output); assertEquals(encode(input), output);
} }
}); });
test("[encoding/base64] testBase64DecodeBinary", () => { Deno.test("[encoding/base64] testBase64DecodeBinary", () => {
for (const [input, output] of testsetBinary) { for (const [input, output] of testsetBinary) {
const outputBinary = new Uint8Array(decode(output as string)); const outputBinary = new Uint8Array(decode(output as string));
assertEquals(outputBinary, input as Uint8Array); assertEquals(outputBinary, input as Uint8Array);

View file

@ -1,6 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { encode, decode } from "./base64url.ts"; import { encode, decode } from "./base64url.ts";
@ -22,19 +20,19 @@ const testsetBinary = [
[new TextEncoder().encode("\x00\x00\x00\x00"), "AAAAAA"], [new TextEncoder().encode("\x00\x00\x00\x00"), "AAAAAA"],
]; ];
test("[encoding/base64url] testBase64urlEncodeString", () => { Deno.test("[encoding/base64url] testBase64urlEncodeString", () => {
for (const [input, output] of testsetString) { for (const [input, output] of testsetString) {
assertEquals(encode(input), output); assertEquals(encode(input), output);
} }
}); });
test("[encoding/base64url] testBase64urlEncodeBinary", () => { Deno.test("[encoding/base64url] testBase64urlEncodeBinary", () => {
for (const [input, output] of testsetBinary) { for (const [input, output] of testsetBinary) {
assertEquals(encode(input), output); assertEquals(encode(input), output);
} }
}); });
test("[encoding/base64ur] testBase64urDecodeBinary", () => { Deno.test("[encoding/base64ur] testBase64urDecodeBinary", () => {
for (const [input, output] of testsetBinary) { for (const [input, output] of testsetBinary) {
const outputBinary = new Uint8Array(decode(output as string)); const outputBinary = new Uint8Array(decode(output as string));
assertEquals(outputBinary, input as Uint8Array); assertEquals(outputBinary, input as Uint8Array);

View file

@ -5,8 +5,6 @@ import { BufReader } from "../../io/bufio.ts";
import { connectWebSocket, WebSocket } from "../../ws/mod.ts"; import { connectWebSocket, WebSocket } from "../../ws/mod.ts";
import { delay } from "../../async/delay.ts"; import { delay } from "../../async/delay.ts";
const { test } = Deno;
async function startServer(): Promise< async function startServer(): Promise<
Deno.Process<Deno.RunOptions & { stdout: "piped" }> Deno.Process<Deno.RunOptions & { stdout: "piped" }>
> { > {
@ -36,7 +34,7 @@ async function startServer(): Promise<
return server; return server;
} }
test({ Deno.test({
name: "[examples/chat] GET / should serve html", name: "[examples/chat] GET / should serve html",
async fn() { async fn() {
const server = await startServer(); const server = await startServer();
@ -54,7 +52,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "[examples/chat] GET /ws should upgrade conn to ws", name: "[examples/chat] GET /ws should upgrade conn to ws",
async fn() { async fn() {
const server = await startServer(); const server = await startServer();

View file

@ -1,7 +1,6 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { args } = Deno;
import { parse } from "../flags/mod.ts"; import { parse } from "../flags/mod.ts";
if (import.meta.main) { if (import.meta.main) {
console.dir(parse(args)); console.dir(parse(Deno.args));
} }

View file

@ -1,5 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { run } = Deno;
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
/** Example of how to do basic tests */ /** Example of how to do basic tests */
@ -13,7 +12,7 @@ Deno.test("t2", function (): void {
/** A more complicated test that runs a subprocess. */ /** A more complicated test that runs a subprocess. */
Deno.test("catSmoke", async function (): Promise<void> { Deno.test("catSmoke", async function (): Promise<void> {
const p = run({ const p = Deno.run({
cmd: [ cmd: [
Deno.execPath(), Deno.execPath(),
"run", "run",

View file

@ -7,7 +7,6 @@ import {
assertStringContains, assertStringContains,
assert, assert,
} from "../../testing/asserts.ts"; } from "../../testing/asserts.ts";
const { execPath, run } = Deno;
Deno.test("xevalSuccess", async function (): Promise<void> { Deno.test("xevalSuccess", async function (): Promise<void> {
const chunks: string[] = []; const chunks: string[] = [];
@ -32,8 +31,14 @@ const xevalPath = "examples/xeval.ts";
Deno.test({ Deno.test({
name: "xevalCliReplvar", name: "xevalCliReplvar",
fn: async function (): Promise<void> { fn: async function (): Promise<void> {
const p = run({ const p = Deno.run({
cmd: [execPath(), "run", xevalPath, "--replvar=abc", "console.log(abc)"], cmd: [
Deno.execPath(),
"run",
xevalPath,
"--replvar=abc",
"console.log(abc)",
],
stdin: "piped", stdin: "piped",
stdout: "piped", stdout: "piped",
stderr: "null", stderr: "null",
@ -48,8 +53,8 @@ Deno.test({
}); });
Deno.test("xevalCliSyntaxError", async function (): Promise<void> { Deno.test("xevalCliSyntaxError", async function (): Promise<void> {
const p = run({ const p = Deno.run({
cmd: [execPath(), "run", xevalPath, "("], cmd: [Deno.execPath(), "run", xevalPath, "("],
stdin: "null", stdin: "null",
stdout: "piped", stdout: "piped",
stderr: "piped", stderr: "piped",

View file

@ -1,7 +1,5 @@
import { parse } from "../flags/mod.ts"; import { parse } from "../flags/mod.ts";
import { readStringDelim } from "../io/bufio.ts"; import { readStringDelim } from "../io/bufio.ts";
const { args, exit, stdin } = Deno;
type Reader = Deno.Reader;
/* eslint-disable-next-line max-len */ /* eslint-disable-next-line max-len */
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction. // 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"; const DEFAULT_DELIMITER = "\n";
export async function xeval( export async function xeval(
reader: Reader, reader: Deno.Reader,
xevalFunc: XevalFunc, xevalFunc: XevalFunc,
{ delimiter = DEFAULT_DELIMITER }: XevalOptions = {} { delimiter = DEFAULT_DELIMITER }: XevalOptions = {}
): Promise<void> { ): Promise<void> {
@ -53,7 +51,7 @@ export async function xeval(
} }
async function main(): Promise<void> { async function main(): Promise<void> {
const parsedArgs = parse(args, { const parsedArgs = parse(Deno.args, {
boolean: ["help"], boolean: ["help"],
string: ["delim", "replvar"], string: ["delim", "replvar"],
alias: { alias: {
@ -69,7 +67,7 @@ async function main(): Promise<void> {
if (parsedArgs._.length != 1) { if (parsedArgs._.length != 1) {
console.error(HELP_MSG); console.error(HELP_MSG);
console.log(parsedArgs._); console.log(parsedArgs._);
exit(1); Deno.exit(1);
} }
if (parsedArgs.help) { if (parsedArgs.help) {
return console.log(HELP_MSG); 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. // new AsyncFunction()'s error message for this particular case isn't great.
if (!replVar.match(/^[_$A-z][_$A-z0-9]*$/)) { if (!replVar.match(/^[_$A-z][_$A-z0-9]*$/)) {
console.error(`Bad replvar identifier: "${replVar}"`); console.error(`Bad replvar identifier: "${replVar}"`);
exit(1); Deno.exit(1);
} }
const xEvalFunc = new AsyncFunction(replVar, code); const xEvalFunc = new AsyncFunction(replVar, code);
await xeval(stdin, xEvalFunc, { delimiter }); await xeval(Deno.stdin, xEvalFunc, { delimiter });
} }
if (import.meta.main) { if (import.meta.main) {

View file

@ -5,10 +5,9 @@ Command line arguments parser for Deno based on minimist
# Example # Example
```ts ```ts
const { args } = Deno;
import { parse } from "https://deno.land/std/flags/mod.ts"; 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: example:
```ts ```ts
// $ deno run example.ts -- a arg1 // $ deno run example.ts -- a arg1
const { args } = Deno;
import { parse } from "https://deno.land/std/flags/mod.ts"; import { parse } from "https://deno.land/std/flags/mod.ts";
console.dir(parse(args, { "--": false })); console.dir(parse(Deno.args, { "--": false }));
// output: { _: [ "a", "arg1" ] } // output: { _: [ "a", "arg1" ] }
console.dir(parse(args, { "--": true })); console.dir(parse(Deno.args, { "--": true }));
// output: { _: [], --: [ "a", "arg1" ] } // output: { _: [], --: [ "a", "arg1" ] }
``` ```
- `options.unknown` - a function which is invoked with a command line parameter - `options.unknown` - a function which is invoked with a command line parameter

View file

@ -15,11 +15,10 @@ export interface ArgParsingOptions {
* the result `['--']` with everything after the `--`. Here's an example: * the result `['--']` with everything after the `--`. Here's an example:
* *
* // $ deno run example.ts -- a arg1 * // $ deno run example.ts -- a arg1
* const { args } = Deno;
* import { parse } from "https://deno.land/std/flags/mod.ts"; * import { parse } from "https://deno.land/std/flags/mod.ts";
* console.dir(parse(args, { "--": false })); * console.dir(parse(Deno.args, { "--": false }));
* // output: { _: [ "a", "arg1" ] } * // output: { _: [ "a", "arg1" ] }
* console.dir(parse(args, { "--": true })); * console.dir(parse(Deno.args, { "--": true }));
* // output: { _: [], --: [ "a", "arg1" ] } * // output: { _: [], --: [ "a", "arg1" ] }
* *
* Defaults to `false`. * Defaults to `false`.

View file

@ -1,6 +1,6 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { join } from "../path/mod.ts"; import { join } from "../path/mod.ts";
const { readDir, readDirSync, mkdir, mkdirSync, remove, removeSync } = Deno;
/** /**
* Ensures that a directory is empty. * Ensures that a directory is empty.
* Deletes directory contents if the directory is not 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> { export async function emptyDir(dir: string): Promise<void> {
try { try {
const items = []; const items = [];
for await (const dirEntry of readDir(dir)) { for await (const dirEntry of Deno.readDir(dir)) {
items.push(dirEntry); items.push(dirEntry);
} }
@ -19,7 +19,7 @@ export async function emptyDir(dir: string): Promise<void> {
const item = items.shift(); const item = items.shift();
if (item && item.name) { if (item && item.name) {
const filepath = join(dir, item.name); const filepath = join(dir, item.name);
await remove(filepath, { recursive: true }); await Deno.remove(filepath, { recursive: true });
} }
} }
} catch (err) { } catch (err) {
@ -28,7 +28,7 @@ export async function emptyDir(dir: string): Promise<void> {
} }
// if not exist. then create it // 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 { export function emptyDirSync(dir: string): void {
try { try {
const items = [...readDirSync(dir)]; const items = [...Deno.readDirSync(dir)];
// If the directory exists, remove all entries inside it. // If the directory exists, remove all entries inside it.
while (items.length) { while (items.length) {
const item = items.shift(); const item = items.shift();
if (item && item.name) { if (item && item.name) {
const filepath = join(dir, item.name); const filepath = join(dir, item.name);
removeSync(filepath, { recursive: true }); Deno.removeSync(filepath, { recursive: true });
} }
} }
} catch (err) { } catch (err) {
@ -56,7 +56,7 @@ export function emptyDirSync(dir: string): void {
throw err; throw err;
} }
// if not exist. then create it // if not exist. then create it
mkdirSync(dir, { recursive: true }); Deno.mkdirSync(dir, { recursive: true });
return; return;
} }
} }

View file

@ -1,6 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { getFileInfoType } from "./_util.ts"; import { getFileInfoType } from "./_util.ts";
const { lstat, lstatSync, mkdir, mkdirSync } = Deno;
/** /**
* Ensures that the directory exists. * Ensures that the directory exists.
@ -9,7 +8,7 @@ const { lstat, lstatSync, mkdir, mkdirSync } = Deno;
*/ */
export async function ensureDir(dir: string): Promise<void> { export async function ensureDir(dir: string): Promise<void> {
try { try {
const fileInfo = await lstat(dir); const fileInfo = await Deno.lstat(dir);
if (!fileInfo.isDirectory) { if (!fileInfo.isDirectory) {
throw new Error( throw new Error(
`Ensure path exists, expected 'dir', got '${getFileInfoType(fileInfo)}'` `Ensure path exists, expected 'dir', got '${getFileInfoType(fileInfo)}'`
@ -18,7 +17,7 @@ export async function ensureDir(dir: string): Promise<void> {
} catch (err) { } catch (err) {
if (err instanceof Deno.errors.NotFound) { if (err instanceof Deno.errors.NotFound) {
// if dir not exists. then create it. // if dir not exists. then create it.
await mkdir(dir, { recursive: true }); await Deno.mkdir(dir, { recursive: true });
return; return;
} }
throw err; throw err;
@ -32,7 +31,7 @@ export async function ensureDir(dir: string): Promise<void> {
*/ */
export function ensureDirSync(dir: string): void { export function ensureDirSync(dir: string): void {
try { try {
const fileInfo = lstatSync(dir); const fileInfo = Deno.lstatSync(dir);
if (!fileInfo.isDirectory) { if (!fileInfo.isDirectory) {
throw new Error( throw new Error(
`Ensure path exists, expected 'dir', got '${getFileInfoType(fileInfo)}'` `Ensure path exists, expected 'dir', got '${getFileInfoType(fileInfo)}'`
@ -41,7 +40,7 @@ export function ensureDirSync(dir: string): void {
} catch (err) { } catch (err) {
if (err instanceof Deno.errors.NotFound) { if (err instanceof Deno.errors.NotFound) {
// if dir not exists. then create it. // if dir not exists. then create it.
mkdirSync(dir, { recursive: true }); Deno.mkdirSync(dir, { recursive: true });
return; return;
} }
throw err; throw err;

View file

@ -2,7 +2,6 @@
import * as path from "../path/mod.ts"; import * as path from "../path/mod.ts";
import { ensureDir, ensureDirSync } from "./ensure_dir.ts"; import { ensureDir, ensureDirSync } from "./ensure_dir.ts";
import { getFileInfoType } from "./_util.ts"; import { getFileInfoType } from "./_util.ts";
const { lstat, lstatSync, writeFile, writeFileSync } = Deno;
/** /**
* Ensures that the file exists. * Ensures that the file exists.
@ -15,7 +14,7 @@ const { lstat, lstatSync, writeFile, writeFileSync } = Deno;
export async function ensureFile(filePath: string): Promise<void> { export async function ensureFile(filePath: string): Promise<void> {
try { try {
// if file exists // if file exists
const stat = await lstat(filePath); const stat = await Deno.lstat(filePath);
if (!stat.isFile) { if (!stat.isFile) {
throw new Error( throw new Error(
`Ensure path exists, expected 'file', got '${getFileInfoType(stat)}'` `Ensure path exists, expected 'file', got '${getFileInfoType(stat)}'`
@ -27,7 +26,7 @@ export async function ensureFile(filePath: string): Promise<void> {
// ensure dir exists // ensure dir exists
await ensureDir(path.dirname(filePath)); await ensureDir(path.dirname(filePath));
// create file // create file
await writeFile(filePath, new Uint8Array()); await Deno.writeFile(filePath, new Uint8Array());
return; return;
} }
@ -46,7 +45,7 @@ export async function ensureFile(filePath: string): Promise<void> {
export function ensureFileSync(filePath: string): void { export function ensureFileSync(filePath: string): void {
try { try {
// if file exists // if file exists
const stat = lstatSync(filePath); const stat = Deno.lstatSync(filePath);
if (!stat.isFile) { if (!stat.isFile) {
throw new Error( throw new Error(
`Ensure path exists, expected 'file', got '${getFileInfoType(stat)}'` `Ensure path exists, expected 'file', got '${getFileInfoType(stat)}'`
@ -58,7 +57,7 @@ export function ensureFileSync(filePath: string): void {
// ensure dir exists // ensure dir exists
ensureDirSync(path.dirname(filePath)); ensureDirSync(path.dirname(filePath));
// create file // create file
writeFileSync(filePath, new Uint8Array()); Deno.writeFileSync(filePath, new Uint8Array());
return; return;
} }
throw err; throw err;

View file

@ -1,11 +1,10 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // 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 * Test whether or not the given path exists by checking with the file system
*/ */
export async function exists(filePath: string): Promise<boolean> { export async function exists(filePath: string): Promise<boolean> {
try { try {
await lstat(filePath); await Deno.lstat(filePath);
return true; return true;
} catch (err) { } catch (err) {
if (err instanceof Deno.errors.NotFound) { if (err instanceof Deno.errors.NotFound) {
@ -21,7 +20,7 @@ export async function exists(filePath: string): Promise<boolean> {
*/ */
export function existsSync(filePath: string): boolean { export function existsSync(filePath: string): boolean {
try { try {
lstatSync(filePath); Deno.lstatSync(filePath);
return true; return true;
} catch (err) { } catch (err) {
if (err instanceof Deno.errors.NotFound) { if (err instanceof Deno.errors.NotFound) {

View file

@ -15,8 +15,6 @@ import {
walkSync, walkSync,
} from "./walk.ts"; } from "./walk.ts";
import { assert } from "../_util/assert.ts"; import { assert } from "../_util/assert.ts";
const { cwd } = Deno;
type FileInfo = Deno.FileInfo;
const isWindows = Deno.build.os == "windows"; const isWindows = Deno.build.os == "windows";
@ -68,7 +66,7 @@ function comparePath(a: WalkEntry, b: WalkEntry): number {
export async function* expandGlob( export async function* expandGlob(
glob: string, glob: string,
{ {
root = cwd(), root = Deno.cwd(),
exclude = [], exclude = [],
includeDirs = true, includeDirs = true,
extended = false, extended = false,
@ -78,7 +76,7 @@ export async function* expandGlob(
const globOptions: GlobOptions = { extended, globstar }; const globOptions: GlobOptions = { extended, globstar };
const absRoot = isAbsolute(root) const absRoot = isAbsolute(root)
? normalize(root) ? normalize(root)
: joinGlobs([cwd(), root], globOptions); : joinGlobs([Deno.cwd(), root], globOptions);
const resolveFromRoot = (path: string): string => const resolveFromRoot = (path: string): string =>
isAbsolute(path) isAbsolute(path)
? normalize(path) ? normalize(path)
@ -167,7 +165,7 @@ export async function* expandGlob(
export function* expandGlobSync( export function* expandGlobSync(
glob: string, glob: string,
{ {
root = cwd(), root = Deno.cwd(),
exclude = [], exclude = [],
includeDirs = true, includeDirs = true,
extended = false, extended = false,
@ -177,7 +175,7 @@ export function* expandGlobSync(
const globOptions: GlobOptions = { extended, globstar }; const globOptions: GlobOptions = { extended, globstar };
const absRoot = isAbsolute(root) const absRoot = isAbsolute(root)
? normalize(root) ? normalize(root)
: joinGlobs([cwd(), root], globOptions); : joinGlobs([Deno.cwd(), root], globOptions);
const resolveFromRoot = (path: string): string => const resolveFromRoot = (path: string): string =>
isAbsolute(path) isAbsolute(path)
? normalize(path) ? normalize(path)

View file

@ -1,4 +1,3 @@
const { cwd, execPath, run } = Deno;
import { decode } from "../encoding/utf8.ts"; import { decode } from "../encoding/utf8.ts";
import { import {
assert, assert,
@ -32,7 +31,7 @@ async function expandGlobArray(
); );
pathsSync.sort(); pathsSync.sort();
assertEquals(paths, pathsSync); assertEquals(paths, pathsSync);
const root = normalize(options.root || cwd()); const root = normalize(options.root || Deno.cwd());
for (const path of paths) { for (const path of paths) {
assert(path.startsWith(root)); assert(path.startsWith(root));
} }
@ -118,8 +117,8 @@ Deno.test("expandGlobIncludeDirs", async function (): Promise<void> {
Deno.test("expandGlobPermError", async function (): Promise<void> { Deno.test("expandGlobPermError", async function (): Promise<void> {
const exampleUrl = new URL("testdata/expand_wildcard.js", import.meta.url); const exampleUrl = new URL("testdata/expand_wildcard.js", import.meta.url);
const p = run({ const p = Deno.run({
cmd: [execPath(), "run", "--unstable", exampleUrl.toString()], cmd: [Deno.execPath(), "run", "--unstable", exampleUrl.toString()],
stdin: "null", stdin: "null",
stdout: "piped", stdout: "piped",
stderr: "piped", stderr: "piped",

View file

@ -3,12 +3,11 @@
// Copyright 2009 The Go Authors. All rights reserved. BSD license. // Copyright 2009 The Go Authors. All rights reserved. BSD license.
import { assert } from "../_util/assert.ts"; import { assert } from "../_util/assert.ts";
import { basename, join, normalize } from "../path/mod.ts"; import { basename, join, normalize } from "../path/mod.ts";
const { readDir, readDirSync, stat, statSync } = Deno;
export function createWalkEntrySync(path: string): WalkEntry { export function createWalkEntrySync(path: string): WalkEntry {
path = normalize(path); path = normalize(path);
const name = basename(path); const name = basename(path);
const info = statSync(path); const info = Deno.statSync(path);
return { return {
path, path,
name, name,
@ -21,7 +20,7 @@ export function createWalkEntrySync(path: string): WalkEntry {
export async function createWalkEntry(path: string): Promise<WalkEntry> { export async function createWalkEntry(path: string): Promise<WalkEntry> {
path = normalize(path); path = normalize(path);
const name = basename(path); const name = basename(path);
const info = await stat(path); const info = await Deno.stat(path);
return { return {
path, path,
name, name,
@ -103,7 +102,7 @@ export async function* walk(
if (maxDepth < 1 || !include(root, undefined, undefined, skip)) { if (maxDepth < 1 || !include(root, undefined, undefined, skip)) {
return; return;
} }
for await (const entry of readDir(root)) { for await (const entry of Deno.readDir(root)) {
if (entry.isSymlink) { if (entry.isSymlink) {
if (followSymlinks) { if (followSymlinks) {
// TODO(ry) Re-enable followSymlinks. // TODO(ry) Re-enable followSymlinks.
@ -156,7 +155,7 @@ export function* walkSync(
if (maxDepth < 1 || !include(root, undefined, undefined, skip)) { if (maxDepth < 1 || !include(root, undefined, undefined, skip)) {
return; return;
} }
for (const entry of readDirSync(root)) { for (const entry of Deno.readDirSync(root)) {
if (entry.isSymlink) { if (entry.isSymlink) {
if (followSymlinks) { if (followSymlinks) {
throw new Error("unimplemented"); throw new Error("unimplemented");

View file

@ -1,5 +1,3 @@
const { cwd, chdir, makeTempDir, mkdir, create, symlink } = Deno;
const { remove } = Deno;
import { walk, walkSync, WalkOptions, WalkEntry } from "./walk.ts"; import { walk, walkSync, WalkOptions, WalkEntry } from "./walk.ts";
import { assert, assertEquals, assertThrowsAsync } from "../testing/asserts.ts"; import { assert, assertEquals, assertThrowsAsync } from "../testing/asserts.ts";
@ -10,15 +8,15 @@ export function testWalk(
): void { ): void {
const name = t.name; const name = t.name;
async function fn(): Promise<void> { async function fn(): Promise<void> {
const origCwd = cwd(); const origCwd = Deno.cwd();
const d = await makeTempDir(); const d = await Deno.makeTempDir();
chdir(d); Deno.chdir(d);
try { try {
await setup(d); await setup(d);
await t(); await t();
} finally { } finally {
chdir(origCwd); Deno.chdir(origCwd);
await remove(d, { recursive: true }); await Deno.remove(d, { recursive: true });
} }
} }
Deno.test({ ignore, name: `[walk] ${name}`, fn }); Deno.test({ ignore, name: `[walk] ${name}`, fn });
@ -44,7 +42,7 @@ export async function walkArray(
} }
export async function touch(path: string): Promise<void> { export async function touch(path: string): Promise<void> {
const f = await create(path); const f = await Deno.create(path);
f.close(); f.close();
} }
@ -56,7 +54,7 @@ function assertReady(expectedLength: number): void {
testWalk( testWalk(
async (d: string): Promise<void> => { async (d: string): Promise<void> => {
await mkdir(d + "/empty"); await Deno.mkdir(d + "/empty");
}, },
async function emptyDir(): Promise<void> { async function emptyDir(): Promise<void> {
const arr = await walkArray("."); const arr = await walkArray(".");
@ -93,7 +91,7 @@ testWalk(
testWalk( testWalk(
async (d: string): Promise<void> => { async (d: string): Promise<void> => {
await mkdir(d + "/a"); await Deno.mkdir(d + "/a");
await touch(d + "/a/x"); await touch(d + "/a/x");
}, },
async function nestedSingleFile(): Promise<void> { async function nestedSingleFile(): Promise<void> {
@ -104,7 +102,7 @@ testWalk(
testWalk( testWalk(
async (d: string): Promise<void> => { 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"); await touch(d + "/a/b/c/d/x");
}, },
async function depth(): Promise<void> { async function depth(): Promise<void> {
@ -119,7 +117,7 @@ testWalk(
testWalk( testWalk(
async (d: string): Promise<void> => { async (d: string): Promise<void> => {
await touch(d + "/a"); await touch(d + "/a");
await mkdir(d + "/b"); await Deno.mkdir(d + "/b");
await touch(d + "/b/c"); await touch(d + "/b/c");
}, },
async function includeDirs(): Promise<void> { async function includeDirs(): Promise<void> {
@ -132,7 +130,7 @@ testWalk(
testWalk( testWalk(
async (d: string): Promise<void> => { async (d: string): Promise<void> => {
await touch(d + "/a"); await touch(d + "/a");
await mkdir(d + "/b"); await Deno.mkdir(d + "/b");
await touch(d + "/b/c"); await touch(d + "/b/c");
}, },
async function includeFiles(): Promise<void> { async function includeFiles(): Promise<void> {
@ -219,8 +217,8 @@ testWalk(
testWalk( testWalk(
async (d: string): Promise<void> => { async (d: string): Promise<void> => {
await mkdir(d + "/a"); await Deno.mkdir(d + "/a");
await mkdir(d + "/b"); await Deno.mkdir(d + "/b");
await touch(d + "/a/x"); await touch(d + "/a/x");
await touch(d + "/a/y"); await touch(d + "/a/y");
await touch(d + "/b/z"); await touch(d + "/b/z");
@ -244,13 +242,13 @@ testWalk(
// TODO(ry) Re-enable followSymlinks // TODO(ry) Re-enable followSymlinks
testWalk( testWalk(
async (d: string): Promise<void> => { async (d: string): Promise<void> => {
await mkdir(d + "/a"); await Deno.mkdir(d + "/a");
await mkdir(d + "/b"); await Deno.mkdir(d + "/b");
await touch(d + "/a/x"); await touch(d + "/a/x");
await touch(d + "/a/y"); await touch(d + "/a/y");
await touch(d + "/b/z"); await touch(d + "/b/z");
try { try {
await symlink(d + "/b", d + "/a/bb"); await Deno.symlink(d + "/b", d + "/a/bb");
} catch (err) { } catch (err) {
assert(Deno.build.os == "windows"); assert(Deno.build.os == "windows");
assertEquals(err.message, "Not implemented"); assertEquals(err.message, "Not implemented");

View file

@ -1,10 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { test } = Deno;
import { assertEquals } from "../../testing/asserts.ts"; import { assertEquals } from "../../testing/asserts.ts";
import { mul32, mul64 } from "./util.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(0xffffffff, 0xffffffff), 1);
assertEquals(mul32(0x12345678, 0xdeadbeef), 0x5621ca08); assertEquals(mul32(0x12345678, 0xdeadbeef), 0x5621ca08);
assertEquals(mul32(0xf626f430, 0xff7469f1), 0x2a939130); assertEquals(mul32(0xf626f430, 0xff7469f1), 0x2a939130);
@ -19,7 +17,7 @@ test("[hash/fnv/util] mul32", () => {
assertEquals(mul32(0xc60898cc, 0xbfe7dcc4), 0x15f84c30); assertEquals(mul32(0xc60898cc, 0xbfe7dcc4), 0x15f84c30);
}); });
test("[hash/fnv/util] mul64", () => { Deno.test("[hash/fnv/util] mul64", () => {
assertEquals(mul64([0xffffffff, 0xffffffff], [0xffffffff, 0xffffffff]), [ assertEquals(mul64([0xffffffff, 0xffffffff], [0xffffffff, 0xffffffff]), [
0, 0,
1, 1,

View file

@ -3,8 +3,6 @@
// Copyright 2011 The Go Authors. All rights reserved. BSD license. // Copyright 2011 The Go Authors. All rights reserved. BSD license.
// https://github.com/golang/go/blob/master/LICENSE // https://github.com/golang/go/blob/master/LICENSE
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { Fnv32, Fnv32a, Fnv64, Fnv64a } from "./fnv.ts"; import { Fnv32, Fnv32a, Fnv64, Fnv64a } from "./fnv.ts";
@ -40,7 +38,7 @@ const golden64a = [
["deno", [0xa5, 0xd9, 0xfb, 0x67, 0x42, 0x6e, 0x48, 0xb1]], ["deno", [0xa5, 0xd9, 0xfb, 0x67, 0x42, 0x6e, 0x48, 0xb1]],
]; ];
test("[hash/fnv] testFnv32", () => { Deno.test("[hash/fnv] testFnv32", () => {
for (const [input, output] of golden32) { for (const [input, output] of golden32) {
const fnv = new Fnv32(); const fnv = new Fnv32();
fnv.write(new TextEncoder().encode(input as string)); 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) { for (const [input, output] of golden32a) {
const fnv = new Fnv32a(); const fnv = new Fnv32a();
fnv.write(new TextEncoder().encode(input as string)); 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) { for (const [input, output] of golden64) {
const fnv = new Fnv64(); const fnv = new Fnv64();
fnv.write(new TextEncoder().encode(input as string)); 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) { for (const [input, output] of golden64a) {
const fnv = new Fnv64a(); const fnv = new Fnv64a();
fnv.write(new TextEncoder().encode(input as string)); 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(); const fnv = new Fnv32();
fnv fnv
.write(new TextEncoder().encode("d")) .write(new TextEncoder().encode("d"))
@ -82,7 +80,7 @@ test("[hash/fnv] testFnv32WriteChain", () => {
assertEquals(fnv.sum(), [0x6e, 0xd5, 0xa7, 0xa9]); assertEquals(fnv.sum(), [0x6e, 0xd5, 0xa7, 0xa9]);
}); });
test("[hash/fnv] testFnv32aWriteChain", () => { Deno.test("[hash/fnv] testFnv32aWriteChain", () => {
const fnv = new Fnv32a(); const fnv = new Fnv32a();
fnv fnv
.write(new TextEncoder().encode("d")) .write(new TextEncoder().encode("d"))
@ -92,7 +90,7 @@ test("[hash/fnv] testFnv32aWriteChain", () => {
assertEquals(fnv.sum(), [0x8e, 0xf6, 0x47, 0x11]); assertEquals(fnv.sum(), [0x8e, 0xf6, 0x47, 0x11]);
}); });
test("[hash/fnv] testFnv64WriteChain", () => { Deno.test("[hash/fnv] testFnv64WriteChain", () => {
const fnv = new Fnv64(); const fnv = new Fnv64();
fnv fnv
.write(new TextEncoder().encode("d")) .write(new TextEncoder().encode("d"))
@ -102,7 +100,7 @@ test("[hash/fnv] testFnv64WriteChain", () => {
assertEquals(fnv.sum(), [0x14, 0xed, 0xb2, 0x7e, 0xec, 0xda, 0xad, 0xc9]); assertEquals(fnv.sum(), [0x14, 0xed, 0xb2, 0x7e, 0xec, 0xda, 0xad, 0xc9]);
}); });
test("[hash/fnv] testFnv64aWriteChain", () => { Deno.test("[hash/fnv] testFnv64aWriteChain", () => {
const fnv = new Fnv64a(); const fnv = new Fnv64a();
fnv fnv
.write(new TextEncoder().encode("d")) .write(new TextEncoder().encode("d"))

View file

@ -1,6 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { Md5 } from "./md5.ts"; import { Md5 } from "./md5.ts";
@ -41,14 +39,14 @@ const testSetBase64 = [
[millionAs, "dwfWrk4CfHDuoqk1wilvIQ=="], [millionAs, "dwfWrk4CfHDuoqk1wilvIQ=="],
]; ];
test("[hash/md5] testMd5Hex", () => { Deno.test("[hash/md5] testMd5Hex", () => {
for (const [input, output] of testSetHex) { for (const [input, output] of testSetHex) {
const md5 = new Md5(); const md5 = new Md5();
assertEquals(md5.update(input).toString(), output); assertEquals(md5.update(input).toString(), output);
} }
}); });
test("[hash/md5] testMd5Base64", () => { Deno.test("[hash/md5] testMd5Base64", () => {
for (const [input, output] of testSetBase64) { for (const [input, output] of testSetBase64) {
const md5 = new Md5(); const md5 = new Md5();
assertEquals(md5.update(input).toString("base64"), output); assertEquals(md5.update(input).toString("base64"), output);

View file

@ -1,5 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { Sha1, Message } from "./sha1.ts"; import { Sha1, Message } from "./sha1.ts";
import { join, resolve } from "../path/mod.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)) { for (const [name, tests] of Object.entries(fixtures.sha1)) {
let i = 1; let i = 1;
for (const [expected, message] of Object.entries(tests)) { for (const [expected, message] of Object.entries(tests)) {
test({ Deno.test({
name: `sha1.${method}() - ${name} - #${i++}`, name: `sha1.${method}() - ${name} - #${i++}`,
fn() { fn() {
const algorithm = new Sha1(); const algorithm = new Sha1();
@ -90,7 +89,7 @@ for (const method of methods) {
for (const [name, tests] of Object.entries(fixtures.sha1)) { for (const [name, tests] of Object.entries(fixtures.sha1)) {
let i = 1; let i = 1;
for (const [expected, message] of Object.entries(tests)) { for (const [expected, message] of Object.entries(tests)) {
test({ Deno.test({
name: `sha1.${method}() - ${name} - #${i++}`, name: `sha1.${method}() - ${name} - #${i++}`,
fn() { fn() {
const algorithm = new Sha1(true); 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 data = await Deno.readFile(join(testdataDir, "hashtest"));
const hash = new Sha1().update(data).hex(); const hash = new Sha1().update(data).hex();

View file

@ -3,8 +3,6 @@ import { Sha256, HmacSha256, Message } from "./sha256.ts";
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { join, resolve } from "../path/mod.ts"; import { join, resolve } from "../path/mod.ts";
const { test } = Deno;
const testdataDir = resolve("hash", "testdata"); const testdataDir = resolve("hash", "testdata");
/** Handy function to convert an array/array buffer to a string of hex values. */ /** Handy function to convert an array/array buffer to a string of hex values. */
@ -222,7 +220,7 @@ for (const method of methods) {
for (const [name, tests] of Object.entries(fixtures.sha256)) { for (const [name, tests] of Object.entries(fixtures.sha256)) {
let i = 1; let i = 1;
for (const [expected, message] of Object.entries(tests)) { for (const [expected, message] of Object.entries(tests)) {
test({ Deno.test({
name: `sha256.${method}() - ${name} - #${i++}`, name: `sha256.${method}() - ${name} - #${i++}`,
fn() { fn() {
const algorithm = new Sha256(); const algorithm = new Sha256();
@ -242,7 +240,7 @@ for (const method of methods) {
for (const [name, tests] of Object.entries(fixtures.sha224)) { for (const [name, tests] of Object.entries(fixtures.sha224)) {
let i = 1; let i = 1;
for (const [expected, message] of Object.entries(tests)) { for (const [expected, message] of Object.entries(tests)) {
test({ Deno.test({
name: `sha224.${method}() - ${name} - #${i++}`, name: `sha224.${method}() - ${name} - #${i++}`,
fn() { fn() {
const algorithm = new Sha256(true); const algorithm = new Sha256(true);
@ -262,7 +260,7 @@ for (const method of methods) {
for (const [name, tests] of Object.entries(fixtures.sha256Hmac)) { for (const [name, tests] of Object.entries(fixtures.sha256Hmac)) {
let i = 1; let i = 1;
for (const [expected, [key, message]] of Object.entries(tests)) { for (const [expected, [key, message]] of Object.entries(tests)) {
test({ Deno.test({
name: `hmacSha256.${method}() - ${name} - #${i++}`, name: `hmacSha256.${method}() - ${name} - #${i++}`,
fn() { fn() {
const algorithm = new HmacSha256(key); const algorithm = new HmacSha256(key);
@ -282,7 +280,7 @@ for (const method of methods) {
for (const [name, tests] of Object.entries(fixtures.sha224Hmac)) { for (const [name, tests] of Object.entries(fixtures.sha224Hmac)) {
let i = 1; let i = 1;
for (const [expected, [key, message]] of Object.entries(tests)) { for (const [expected, [key, message]] of Object.entries(tests)) {
test({ Deno.test({
name: `hmacSha224.${method}() - ${name} - #${i++}`, name: `hmacSha224.${method}() - ${name} - #${i++}`,
fn() { fn() {
const algorithm = new HmacSha256(key, true); 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 data = await Deno.readFile(join(testdataDir, "hashtest"));
const hash = new Sha256().update(data).hex(); const hash = new Sha256().update(data).hex();

View file

@ -1,8 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
/* eslint-disable @typescript-eslint/camelcase */ /* eslint-disable @typescript-eslint/camelcase */
const { test } = Deno;
import { assertEquals, assertThrows } from "../testing/asserts.ts"; import { assertEquals, assertThrows } from "../testing/asserts.ts";
import { import {
Keccak224, Keccak224,
@ -262,7 +259,7 @@ function s2b(data: string): Uint8Array {
return new TextEncoder().encode(data); return new TextEncoder().encode(data);
} }
test("[hash/sha3] testSha3-224Raw", () => { Deno.test("[hash/sha3] testSha3-224Raw", () => {
const sha3sum = (data: ArrayBuffer): ArrayBuffer => { const sha3sum = (data: ArrayBuffer): ArrayBuffer => {
const sha3 = new Sha3_224(); const sha3 = new Sha3_224();
return sha3.update(data).digest(); 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 sha3sum = (data: string): string => {
const sha3 = new Sha3_224(); const sha3 = new Sha3_224();
return sha3.update(data).toString(); 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 sha3sum = (data: ArrayBuffer): ArrayBuffer => {
const sha3 = new Sha3_256(); const sha3 = new Sha3_256();
return sha3.update(data).digest(); 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 sha3sum = (data: string): string => {
const sha3 = new Sha3_256(); const sha3 = new Sha3_256();
return sha3.update(data).toString(); 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 sha3sum = (data: ArrayBuffer): ArrayBuffer => {
const sha3 = new Sha3_384(); const sha3 = new Sha3_384();
return sha3.update(data).digest(); 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 sha3sum = (data: string): string => {
const sha3 = new Sha3_384(); const sha3 = new Sha3_384();
return sha3.update(data).toString(); 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 sha3sum = (data: ArrayBuffer): ArrayBuffer => {
const sha3 = new Sha3_512(); const sha3 = new Sha3_512();
return sha3.update(data).digest(); 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 sha3sum = (data: string): string => {
const sha3 = new Sha3_512(); const sha3 = new Sha3_512();
return sha3.update(data).toString(); 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 keccakSum = (data: ArrayBuffer): ArrayBuffer => {
const keccak = new Keccak224(); const keccak = new Keccak224();
return keccak.update(data).digest(); 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 keccakSum = (data: string): string => {
const keccak = new Keccak224(); const keccak = new Keccak224();
return keccak.update(data).toString(); 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 keccakSum = (data: ArrayBuffer): ArrayBuffer => {
const keccak = new Keccak256(); const keccak = new Keccak256();
return keccak.update(data).digest(); 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 keccakSum = (data: string): string => {
const keccak = new Keccak256(); const keccak = new Keccak256();
return keccak.update(data).toString(); 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 keccakSum = (data: ArrayBuffer): ArrayBuffer => {
const keccak = new Keccak384(); const keccak = new Keccak384();
return keccak.update(data).digest(); 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 keccakSum = (data: string): string => {
const keccak = new Keccak384(); const keccak = new Keccak384();
return keccak.update(data).toString(); 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 keccakSum = (data: ArrayBuffer): ArrayBuffer => {
const keccak = new Keccak512(); const keccak = new Keccak512();
return keccak.update(data).digest(); 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 keccakSum = (data: string): string => {
const keccak = new Keccak512(); const keccak = new Keccak512();
return keccak.update(data).toString(); 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 shakeSum = (data: ArrayBuffer): ArrayBuffer => {
const shake = new Shake128(128); const shake = new Shake128(128);
return shake.update(data).digest(); 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 shakeSum = (data: string): string => {
const shake = new Shake128(128); const shake = new Shake128(128);
return shake.update(data).toString(); 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 shakeSum = (data: ArrayBuffer): ArrayBuffer => {
const shake = new Shake128(224); const shake = new Shake128(224);
return shake.update(data).digest(); 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 shakeSum = (data: string): string => {
const shake = new Shake128(224); const shake = new Shake128(224);
return shake.update(data).toString(); 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 shakeSum = (data: string): string => {
const shake = new Shake128(2048); const shake = new Shake128(2048);
return shake.update(data).toString(); 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 shakeSum = (data: string): string => {
const shake = new Shake256(256); const shake = new Shake256(256);
return shake.update(data).toString(); 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 shakeSum = (data: string): string => {
const shake = new Shake256(128); const shake = new Shake256(128);
return shake.update(data).toString(); 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 shakeSum = (data: string): string => {
const shake = new Shake256(384); const shake = new Shake256(384);
return shake.update(data).toString(); 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 shakeSum = (data: string): string => {
const shake = new Shake256(512); const shake = new Shake256(512);
return shake.update(data).toString(); 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 sha3 = new Sha3_256();
const output = sha3 const output = sha3
.update(s2b("a")) .update(s2b("a"))
@ -561,7 +558,7 @@ test("[hash/sha3] testSha3-256Chain", () => {
); );
}); });
test("[hash/sha3] testSha3UpdateFinalized", () => { Deno.test("[hash/sha3] testSha3UpdateFinalized", () => {
assertThrows( assertThrows(
() => { () => {
const sha3 = new Sha3_256(); const sha3 = new Sha3_256();

View file

@ -3,8 +3,6 @@ import { Sha512, HmacSha512, Message } from "./sha512.ts";
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { join, resolve } from "../path/mod.ts"; import { join, resolve } from "../path/mod.ts";
const { test } = Deno;
const testdataDir = resolve("hash", "testdata"); const testdataDir = resolve("hash", "testdata");
/** Handy function to convert an array/array buffer to a string of hex values. */ /** 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)) { for (const [name, tests] of Object.entries(fixtures.sha512bits224)) {
let i = 1; let i = 1;
for (const [expected, message] of Object.entries(tests)) { for (const [expected, message] of Object.entries(tests)) {
test({ Deno.test({
name: `sha512/224.${method}() - ${name} - #${i++}`, name: `sha512/224.${method}() - ${name} - #${i++}`,
fn() { fn() {
const algorithm = new Sha512(224); const algorithm = new Sha512(224);
@ -302,7 +300,7 @@ for (const method of methods) {
for (const [name, tests] of Object.entries(fixtures.sha512bits256)) { for (const [name, tests] of Object.entries(fixtures.sha512bits256)) {
let i = 1; let i = 1;
for (const [expected, message] of Object.entries(tests)) { for (const [expected, message] of Object.entries(tests)) {
test({ Deno.test({
name: `sha512/256.${method}() - ${name} - #${i++}`, name: `sha512/256.${method}() - ${name} - #${i++}`,
fn() { fn() {
const algorithm = new Sha512(256); const algorithm = new Sha512(256);
@ -322,7 +320,7 @@ for (const method of methods) {
for (const [name, tests] of Object.entries(fixtures.sha512)) { for (const [name, tests] of Object.entries(fixtures.sha512)) {
let i = 1; let i = 1;
for (const [expected, message] of Object.entries(tests)) { for (const [expected, message] of Object.entries(tests)) {
test({ Deno.test({
name: `sha512.${method}() - ${name} - #${i++}`, name: `sha512.${method}() - ${name} - #${i++}`,
fn() { fn() {
const algorithm = new Sha512(); const algorithm = new Sha512();
@ -342,7 +340,7 @@ for (const method of methods) {
for (const [name, tests] of Object.entries(fixtures.hmacSha512bits224)) { for (const [name, tests] of Object.entries(fixtures.hmacSha512bits224)) {
let i = 1; let i = 1;
for (const [expected, [key, message]] of Object.entries(tests)) { for (const [expected, [key, message]] of Object.entries(tests)) {
test({ Deno.test({
name: `hmacSha512/224.${method}() - ${name} - #${i++}`, name: `hmacSha512/224.${method}() - ${name} - #${i++}`,
fn() { fn() {
const algorithm = new HmacSha512(key, 224); const algorithm = new HmacSha512(key, 224);
@ -362,7 +360,7 @@ for (const method of methods) {
for (const [name, tests] of Object.entries(fixtures.hmacSha512bits256)) { for (const [name, tests] of Object.entries(fixtures.hmacSha512bits256)) {
let i = 1; let i = 1;
for (const [expected, [key, message]] of Object.entries(tests)) { for (const [expected, [key, message]] of Object.entries(tests)) {
test({ Deno.test({
name: `hmacSha512/256.${method}() - ${name} - #${i++}`, name: `hmacSha512/256.${method}() - ${name} - #${i++}`,
fn() { fn() {
const algorithm = new HmacSha512(key, 256); const algorithm = new HmacSha512(key, 256);
@ -382,7 +380,7 @@ for (const method of methods) {
for (const [name, tests] of Object.entries(fixtures.hmacSha512)) { for (const [name, tests] of Object.entries(fixtures.hmacSha512)) {
let i = 1; let i = 1;
for (const [expected, [key, message]] of Object.entries(tests)) { for (const [expected, [key, message]] of Object.entries(tests)) {
test({ Deno.test({
name: `hmacSha512.${method}() - ${name} - #${i++}`, name: `hmacSha512.${method}() - ${name} - #${i++}`,
fn() { fn() {
const algorithm = new HmacSha512(key); 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 data = await Deno.readFile(join(testdataDir, "hashtest"));
const hash = new Sha512().update(data).hex(); const hash = new Sha512().update(data).hex();
assertEquals( assertEquals(

View file

@ -18,11 +18,13 @@ import { BufReader, ReadLineResult } from "../io/bufio.ts";
import { ServerRequest, Response } from "./server.ts"; import { ServerRequest, Response } from "./server.ts";
import { StringReader } from "../io/readers.ts"; import { StringReader } from "../io/readers.ts";
import { mockConn } from "./_mock_conn.ts"; import { mockConn } from "./_mock_conn.ts";
const { Buffer, test, readAll } = Deno;
test("bodyReader", async () => { Deno.test("bodyReader", async () => {
const text = "Hello, Deno"; 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); assertEquals(decode(await Deno.readAll(r)), text);
}); });
function chunkify(n: number, char: string): string { function chunkify(n: number, char: string): string {
@ -31,7 +33,7 @@ function chunkify(n: number, char: string): string {
.join(""); .join("");
return `${n.toString(16)}\r\n${v}\r\n`; return `${n.toString(16)}\r\n${v}\r\n`;
} }
test("chunkedBodyReader", async () => { Deno.test("chunkedBodyReader", async () => {
const body = [ const body = [
chunkify(3, "a"), chunkify(3, "a"),
chunkify(5, "b"), chunkify(5, "b"),
@ -40,11 +42,11 @@ test("chunkedBodyReader", async () => {
chunkify(0, ""), chunkify(0, ""),
].join(""); ].join("");
const h = new Headers(); 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; let result: number | null;
// Use small buffer as some chunks exceed buffer size // Use small buffer as some chunks exceed buffer size
const buf = new Uint8Array(5); const buf = new Uint8Array(5);
const dest = new Buffer(); const dest = new Deno.Buffer();
while ((result = await r.read(buf)) !== null) { while ((result = await r.read(buf)) !== null) {
const len = Math.min(buf.byteLength, result); const len = Math.min(buf.byteLength, result);
await dest.write(buf.subarray(0, len)); await dest.write(buf.subarray(0, len));
@ -53,7 +55,7 @@ test("chunkedBodyReader", async () => {
assertEquals(new TextDecoder().decode(dest.bytes()), exp); assertEquals(new TextDecoder().decode(dest.bytes()), exp);
}); });
test("chunkedBodyReader with trailers", async () => { Deno.test("chunkedBodyReader with trailers", async () => {
const body = [ const body = [
chunkify(3, "a"), chunkify(3, "a"),
chunkify(5, "b"), chunkify(5, "b"),
@ -67,7 +69,7 @@ test("chunkedBodyReader with trailers", async () => {
const h = new Headers({ const h = new Headers({
trailer: "deno,node", 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("trailer"), true);
assertEquals(h.has("deno"), false); assertEquals(h.has("deno"), false);
assertEquals(h.has("node"), false); assertEquals(h.has("node"), false);
@ -79,18 +81,20 @@ test("chunkedBodyReader with trailers", async () => {
assertEquals(h.get("node"), "js"); assertEquals(h.get("node"), "js");
}); });
test("readTrailers", async () => { Deno.test("readTrailers", async () => {
const h = new Headers({ const h = new Headers({
trailer: "Deno, Node", trailer: "Deno, Node",
}); });
const trailer = ["deno: land", "node: js", "", ""].join("\r\n"); 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.has("trailer"), false);
assertEquals(h.get("deno"), "land"); assertEquals(h.get("deno"), "land");
assertEquals(h.get("node"), "js"); assertEquals(h.get("node"), "js");
}); });
test("readTrailer should throw if undeclared headers found in trailer", async () => { Deno.test(
"readTrailer should throw if undeclared headers found in trailer",
async () => {
const patterns = [ const patterns = [
["deno,node", "deno: land\r\nnode: js\r\ngo: lang\r\n\r\n"], ["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\n\r\n"],
@ -102,31 +106,38 @@ test("readTrailer should throw if undeclared headers found in trailer", async ()
}); });
await assertThrowsAsync( await assertThrowsAsync(
async () => { async () => {
await readTrailers(h, new BufReader(new Buffer(encode(trailer)))); await readTrailers(
h,
new BufReader(new Deno.Buffer(encode(trailer)))
);
}, },
Deno.errors.InvalidData, Deno.errors.InvalidData,
`Undeclared trailers: [ "` `Undeclared trailers: [ "`
); );
} }
}); }
);
test("readTrailer should throw if trailer contains prohibited fields", async () => { Deno.test(
"readTrailer should throw if trailer contains prohibited fields",
async () => {
for (const f of ["Content-Length", "Trailer", "Transfer-Encoding"]) { for (const f of ["Content-Length", "Trailer", "Transfer-Encoding"]) {
const h = new Headers({ const h = new Headers({
trailer: f, trailer: f,
}); });
await assertThrowsAsync( await assertThrowsAsync(
async () => { async () => {
await readTrailers(h, new BufReader(new Buffer())); await readTrailers(h, new BufReader(new Deno.Buffer()));
}, },
Deno.errors.InvalidData, Deno.errors.InvalidData,
`Prohibited trailer names: [ "` `Prohibited trailer names: [ "`
); );
} }
}); }
);
test("writeTrailer", async () => { Deno.test("writeTrailer", async () => {
const w = new Buffer(); const w = new Deno.Buffer();
await writeTrailers( await writeTrailers(
w, w,
new Headers({ "transfer-encoding": "chunked", trailer: "deno,node" }), new Headers({ "transfer-encoding": "chunked", trailer: "deno,node" }),
@ -138,8 +149,8 @@ test("writeTrailer", async () => {
); );
}); });
test("writeTrailer should throw", async () => { Deno.test("writeTrailer should throw", async () => {
const w = new Buffer(); const w = new Deno.Buffer();
await assertThrowsAsync( await assertThrowsAsync(
() => { () => {
return writeTrailers(w, new Headers(), new Headers()); 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 // 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 = [ const testCases = [
{ in: "HTTP/0.9", want: [0, 9] }, { in: "HTTP/0.9", want: [0, 9] },
{ in: "HTTP/1.0", want: [1, 0] }, { 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 shortText = "Hello";
const body = new TextEncoder().encode(shortText); const body = new TextEncoder().encode(shortText);
@ -248,7 +259,7 @@ test("writeUint8ArrayResponse", async function (): Promise<void> {
assertEquals(eof, null); assertEquals(eof, null);
}); });
test("writeStringResponse", async function (): Promise<void> { Deno.test("writeStringResponse", async function (): Promise<void> {
const body = "Hello"; const body = "Hello";
const res: Response = { body }; const res: Response = { body };
@ -283,7 +294,7 @@ test("writeStringResponse", async function (): Promise<void> {
assertEquals(eof, null); assertEquals(eof, null);
}); });
test("writeStringReaderResponse", async function (): Promise<void> { Deno.test("writeStringReaderResponse", async function (): Promise<void> {
const shortText = "Hello"; const shortText = "Hello";
const body = new StringReader(shortText); const body = new StringReader(shortText);
@ -326,8 +337,8 @@ test("writeStringReaderResponse", async function (): Promise<void> {
assertEquals(r.more, false); assertEquals(r.more, false);
}); });
test("writeResponse with trailer", async () => { Deno.test("writeResponse with trailer", async () => {
const w = new Buffer(); const w = new Deno.Buffer();
const body = new StringReader("Hello"); const body = new StringReader("Hello");
await writeResponse(w, { await writeResponse(w, {
status: 200, status: 200,
@ -356,18 +367,18 @@ test("writeResponse with trailer", async () => {
assertEquals(ret, exp); assertEquals(ret, exp);
}); });
test("writeResponseShouldNotModifyOriginHeaders", async () => { Deno.test("writeResponseShouldNotModifyOriginHeaders", async () => {
const headers = new Headers(); const headers = new Headers();
const buf = new Deno.Buffer(); const buf = new Deno.Buffer();
await writeResponse(buf, { body: "foo", headers }); 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 }); 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 const input = `GET / HTTP/1.1
malformedHeader malformedHeader
`; `;
@ -385,7 +396,7 @@ malformedHeader
// Ported from Go // Ported from Go
// https://github.com/golang/go/blob/go1.12.5/src/net/http/request_test.go#L377-L443 // https://github.com/golang/go/blob/go1.12.5/src/net/http/request_test.go#L377-L443
// TODO(zekth) fix tests // TODO(zekth) fix tests
test("testReadRequestError", async function (): Promise<void> { Deno.test("testReadRequestError", async function (): Promise<void> {
const testCases = [ const testCases = [
{ {
in: "GET / HTTP/1.1\r\nheader: foo\r\n\r\n", in: "GET / HTTP/1.1\r\nheader: foo\r\n\r\n",

View file

@ -2,9 +2,8 @@
import { ServerRequest, Response } from "./server.ts"; import { ServerRequest, Response } from "./server.ts";
import { getCookies, deleteCookie, setCookie } from "./cookie.ts"; import { getCookies, deleteCookie, setCookie } from "./cookie.ts";
import { assert, assertEquals } from "../testing/asserts.ts"; import { assert, assertEquals } from "../testing/asserts.ts";
const { test } = Deno;
test({ Deno.test({
name: "Cookie parser", name: "Cookie parser",
fn(): void { fn(): void {
const req = new ServerRequest(); const req = new ServerRequest();
@ -32,7 +31,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Cookie Delete", name: "Cookie Delete",
fn(): void { fn(): void {
const res: Response = {}; const res: Response = {};
@ -44,7 +43,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Cookie Set", name: "Cookie Set",
fn(): void { fn(): void {
const res: Response = {}; const res: Response = {};

View file

@ -6,7 +6,6 @@
// TODO Add tests like these: // TODO Add tests like these:
// https://github.com/indexzero/http-server/blob/master/test/http-server-test.js // 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 { posix, extname } from "../path/mod.ts";
import { listenAndServe, ServerRequest, Response } from "./server.ts"; import { listenAndServe, ServerRequest, Response } from "./server.ts";
import { parse } from "../flags/mod.ts"; import { parse } from "../flags/mod.ts";
@ -33,7 +32,7 @@ interface FileServerArgs {
const encoder = new TextEncoder(); const encoder = new TextEncoder();
const serverArgs = parse(args) as FileServerArgs; const serverArgs = parse(Deno.args) as FileServerArgs;
const target = posix.resolve(serverArgs._[0] ?? ""); const target = posix.resolve(serverArgs._[0] ?? "");
const MEDIA_TYPES: Record<string, string> = { const MEDIA_TYPES: Record<string, string> = {
@ -100,7 +99,10 @@ export async function serveFile(
req: ServerRequest, req: ServerRequest,
filePath: string filePath: string
): Promise<Response> { ): 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(); const headers = new Headers();
headers.set("content-length", fileInfo.size.toString()); headers.set("content-length", fileInfo.size.toString());
const contentTypeValue = contentType(filePath); const contentTypeValue = contentType(filePath);
@ -124,7 +126,7 @@ async function serveDir(
): Promise<Response> { ): Promise<Response> {
const dirUrl = `/${posix.relative(target, dirPath)}`; const dirUrl = `/${posix.relative(target, dirPath)}`;
const listEntry: EntryInfo[] = []; 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 filePath = posix.join(dirPath, entry.name);
const fileUrl = posix.join(dirUrl, entry.name); const fileUrl = posix.join(dirUrl, entry.name);
if (entry.name === "index.html" && entry.isFile) { if (entry.name === "index.html" && entry.isFile) {
@ -134,7 +136,7 @@ async function serveDir(
// Yuck! // Yuck!
let fileInfo = null; let fileInfo = null;
try { try {
fileInfo = await stat(filePath); fileInfo = await Deno.stat(filePath);
} catch (e) { } catch (e) {
// Pass // Pass
} }
@ -318,7 +320,7 @@ function main(): void {
-h, --help Prints help information -h, --help Prints help information
-p, --port <PORT> Set port -p, --port <PORT> Set port
--cors Enable CORS via the "Access-Control-Allow-Origin" header`); --cors Enable CORS via the "Access-Control-Allow-Origin" header`);
exit(); Deno.exit();
} }
listenAndServe( listenAndServe(
@ -336,7 +338,7 @@ function main(): void {
let response: Response | undefined; let response: Response | undefined;
try { try {
const fileInfo = await stat(fsPath); const fileInfo = await Deno.stat(fsPath);
if (fileInfo.isDirectory) { if (fileInfo.isDirectory) {
response = await serveDir(req, fsPath); response = await serveDir(req, fsPath);
} else { } else {

View file

@ -4,7 +4,6 @@ import { BufReader } from "../io/bufio.ts";
import { TextProtoReader } from "../textproto/mod.ts"; import { TextProtoReader } from "../textproto/mod.ts";
import { ServerRequest } from "./server.ts"; import { ServerRequest } from "./server.ts";
import { serveFile } from "./file_server.ts"; import { serveFile } from "./file_server.ts";
const { test } = Deno;
let fileServer: Deno.Process<Deno.RunOptions & { stdout: "piped" }>; let fileServer: Deno.Process<Deno.RunOptions & { stdout: "piped" }>;
type FileServerCfg = { type FileServerCfg = {
@ -68,7 +67,9 @@ async function killFileServer(): Promise<void> {
fileServer.stdout!.close(); fileServer.stdout!.close();
} }
test("file_server serveFile in ./", async (): Promise<void> => { Deno.test(
"file_server serveFile in ./",
async (): Promise<void> => {
await startFileServer(); await startFileServer();
try { try {
const res = await fetch("http://localhost:4507/README.md"); const res = await fetch("http://localhost:4507/README.md");
@ -83,9 +84,12 @@ test("file_server serveFile in ./", async (): Promise<void> => {
} finally { } finally {
await killFileServer(); await killFileServer();
} }
}); }
);
test("file_server serveFile in ./http", async (): Promise<void> => { Deno.test(
"file_server serveFile in ./http",
async (): Promise<void> => {
await startFileServer({ target: "./http" }); await startFileServer({ target: "./http" });
try { try {
const res = await fetch("http://localhost:4507/README.md"); const res = await fetch("http://localhost:4507/README.md");
@ -101,9 +105,10 @@ test("file_server serveFile in ./http", async (): Promise<void> => {
} finally { } finally {
await killFileServer(); await killFileServer();
} }
}); }
);
test("serveDirectory", async function (): Promise<void> { Deno.test("serveDirectory", async function (): Promise<void> {
await startFileServer(); await startFileServer();
try { try {
const res = await fetch("http://localhost:4507/"); 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(); await startFileServer();
try { try {
const res = await fetch("http://localhost:4507/badfile.txt"); 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(); await startFileServer();
try { try {
let res = await fetch("http://localhost:4507/http/testdata/%"); 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({ const helpProcess = Deno.run({
cmd: [ cmd: [
Deno.execPath(), Deno.execPath(),
@ -177,7 +182,7 @@ test("printHelp", async function (): Promise<void> {
helpProcess.stdout.close(); helpProcess.stdout.close();
}); });
test("contentType", async () => { Deno.test("contentType", async () => {
const request = new ServerRequest(); const request = new ServerRequest();
const response = await serveFile(request, "http/testdata/hello.html"); const response = await serveFile(request, "http/testdata/hello.html");
const contentType = response.headers!.get("content-type"); const contentType = response.headers!.get("content-type");
@ -185,7 +190,7 @@ test("contentType", async () => {
(response.body as Deno.File).close(); (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(); await startFileServerAsLibrary();
try { try {
const res = await fetch("http://localhost:8000"); const res = await fetch("http://localhost:8000");

View file

@ -1,11 +1,10 @@
import { assert, assertEquals } from "../testing/asserts.ts"; import { assert, assertEquals } from "../testing/asserts.ts";
import { BufReader, BufWriter } from "../io/bufio.ts"; import { BufReader, BufWriter } from "../io/bufio.ts";
import { TextProtoReader } from "../textproto/mod.ts"; import { TextProtoReader } from "../textproto/mod.ts";
const { connect, run, test } = Deno;
let server: Deno.Process<Deno.RunOptions & { stdout: "piped" }>; let server: Deno.Process<Deno.RunOptions & { stdout: "piped" }>;
async function startServer(): Promise<void> { async function startServer(): Promise<void> {
server = run({ server = Deno.run({
// TODO(lucacasonato): remove unstable when stabilized // TODO(lucacasonato): remove unstable when stabilized
cmd: [Deno.execPath(), "run", "--unstable", "-A", "http/racing_server.ts"], cmd: [Deno.execPath(), "run", "--unstable", "-A", "http/racing_server.ts"],
stdout: "piped", stdout: "piped",
@ -59,10 +58,10 @@ content-length: 6
Step7 Step7
`; `;
test("serverPipelineRace", async function (): Promise<void> { Deno.test("serverPipelineRace", async function (): Promise<void> {
await startServer(); await startServer();
const conn = await connect({ port: 4501 }); const conn = await Deno.connect({ port: 4501 });
const r = new TextProtoReader(new BufReader(conn)); const r = new TextProtoReader(new BufReader(conn));
const w = new BufWriter(conn); const w = new BufWriter(conn);
await w.write(new TextEncoder().encode(input)); await w.write(new TextEncoder().encode(input));

View file

@ -10,10 +10,6 @@ import {
writeResponse, writeResponse,
readRequest, readRequest,
} from "./_io.ts"; } from "./_io.ts";
import Listener = Deno.Listener;
import Conn = Deno.Conn;
import Reader = Deno.Reader;
const { listen, listenTls } = Deno;
export class ServerRequest { export class ServerRequest {
url!: string; url!: string;
@ -22,7 +18,7 @@ export class ServerRequest {
protoMinor!: number; protoMinor!: number;
protoMajor!: number; protoMajor!: number;
headers!: Headers; headers!: Headers;
conn!: Conn; conn!: Deno.Conn;
r!: BufReader; r!: BufReader;
w!: BufWriter; w!: BufWriter;
done: Deferred<Error | undefined> = deferred(); done: Deferred<Error | undefined> = deferred();
@ -119,9 +115,9 @@ export class ServerRequest {
export class Server implements AsyncIterable<ServerRequest> { export class Server implements AsyncIterable<ServerRequest> {
private closing = false; private closing = false;
private connections: Conn[] = []; private connections: Deno.Conn[] = [];
constructor(public listener: Listener) {} constructor(public listener: Deno.Listener) {}
close(): void { close(): void {
this.closing = true; this.closing = true;
@ -140,7 +136,7 @@ export class Server implements AsyncIterable<ServerRequest> {
// Yields all HTTP requests on a single TCP connection. // Yields all HTTP requests on a single TCP connection.
private async *iterateHttpRequests( private async *iterateHttpRequests(
conn: Conn conn: Deno.Conn
): AsyncIterableIterator<ServerRequest> { ): AsyncIterableIterator<ServerRequest> {
const reader = new BufReader(conn); const reader = new BufReader(conn);
const writer = new BufWriter(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); this.connections.push(conn);
} }
private untrackConnection(conn: Conn): void { private untrackConnection(conn: Deno.Conn): void {
const index = this.connections.indexOf(conn); const index = this.connections.indexOf(conn);
if (index !== -1) { if (index !== -1) {
this.connections.splice(index, 1); this.connections.splice(index, 1);
@ -211,7 +207,7 @@ export class Server implements AsyncIterable<ServerRequest> {
): AsyncIterableIterator<ServerRequest> { ): AsyncIterableIterator<ServerRequest> {
if (this.closing) return; if (this.closing) return;
// Wait for a new connection. // Wait for a new connection.
let conn: Conn; let conn: Deno.Conn;
try { try {
conn = await this.listener.accept(); conn = await this.listener.accept();
} catch (error) { } catch (error) {
@ -257,7 +253,7 @@ export function serve(addr: string | HTTPOptions): Server {
addr = { hostname, port: Number(port) }; addr = { hostname, port: Number(port) };
} }
const listener = listen(addr); const listener = Deno.listen(addr);
return new Server(listener); return new Server(listener);
} }
@ -309,7 +305,7 @@ export function serveTLS(options: HTTPSOptions): Server {
...options, ...options,
transport: "tcp", transport: "tcp",
}; };
const listener = listenTls(tlsOptions); const listener = Deno.listenTls(tlsOptions);
return new Server(listener); return new Server(listener);
} }
@ -349,6 +345,6 @@ export async function listenAndServeTLS(
export interface Response { export interface Response {
status?: number; status?: number;
headers?: Headers; headers?: Headers;
body?: Uint8Array | Reader | string; body?: Uint8Array | Deno.Reader | string;
trailers?: () => Promise<Headers> | Headers; trailers?: () => Promise<Headers> | Headers;
} }

View file

@ -19,8 +19,6 @@ import { delay } from "../async/delay.ts";
import { encode, decode } from "../encoding/utf8.ts"; import { encode, decode } from "../encoding/utf8.ts";
import { mockConn } from "./_mock_conn.ts"; import { mockConn } from "./_mock_conn.ts";
const { Buffer, test } = Deno;
interface ResponseTest { interface ResponseTest {
response: Response; response: Response;
raw: string; raw: string;
@ -43,7 +41,7 @@ const responseTests: ResponseTest[] = [
{ {
response: { response: {
status: 200, status: 200,
body: new Buffer(new TextEncoder().encode("abcdef")), body: new Deno.Buffer(new TextEncoder().encode("abcdef")),
}, },
raw: 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) { for (const testCase of responseTests) {
const buf = new Buffer(); const buf = new Deno.Buffer();
const bufw = new BufWriter(buf); const bufw = new BufWriter(buf);
const request = new ServerRequest(); const request = new ServerRequest();
request.w = bufw; 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 // Has content length
{ {
const req = new ServerRequest(); const req = new ServerRequest();
req.headers = new Headers(); req.headers = new Headers();
req.headers.set("content-length", "5"); req.headers.set("content-length", "5");
const buf = new Buffer(encode("Hello")); const buf = new Deno.Buffer(encode("Hello"));
req.r = new BufReader(buf); req.r = new BufReader(buf);
assertEquals(req.contentLength, 5); assertEquals(req.contentLength, 5);
} }
@ -96,7 +94,7 @@ test("requestContentLength", function (): void {
chunkOffset += chunkSize; chunkOffset += chunkSize;
} }
chunksData += "0\r\n\r\n"; chunksData += "0\r\n\r\n";
const buf = new Buffer(encode(chunksData)); const buf = new Deno.Buffer(encode(chunksData));
req.r = new BufReader(buf); req.r = new BufReader(buf);
assertEquals(req.contentLength, null); 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(); const req = new ServerRequest();
req.headers = new Headers(); req.headers = new Headers();
req.headers.set("content-length", "5"); req.headers.set("content-length", "5");
const buf = new Buffer(encode("Hello")); const buf = new Deno.Buffer(encode("Hello"));
req.r = new BufReader(buf); req.r = new BufReader(buf);
const body = decode(await Deno.readAll(req.body)); const body = decode(await Deno.readAll(req.body));
assertEquals(body, "Hello"); assertEquals(body, "Hello");
@ -138,27 +136,32 @@ test("requestBodyWithContentLength", async function (): Promise<void> {
const req = new ServerRequest(); const req = new ServerRequest();
req.headers = new Headers(); req.headers = new Headers();
req.headers.set("Content-Length", "5000"); req.headers.set("Content-Length", "5000");
const buf = new Buffer(encode(longText)); const buf = new Deno.Buffer(encode(longText));
req.r = new BufReader(buf); req.r = new BufReader(buf);
const body = decode(await Deno.readAll(req.body)); const body = decode(await Deno.readAll(req.body));
assertEquals(body, longText); assertEquals(body, longText);
} }
// Handler ignored to consume body // Handler ignored to consume body
}); });
test("ServerRequest.finalize() should consume unread body / content-length", async () => { Deno.test(
"ServerRequest.finalize() should consume unread body / content-length",
async () => {
const text = "deno.land"; const text = "deno.land";
const req = new ServerRequest(); const req = new ServerRequest();
req.headers = new Headers(); req.headers = new Headers();
req.headers.set("content-length", "" + text.length); req.headers.set("content-length", "" + text.length);
const tr = totalReader(new Buffer(encode(text))); const tr = totalReader(new Deno.Buffer(encode(text)));
req.r = new BufReader(tr); req.r = new BufReader(tr);
req.w = new BufWriter(new Buffer()); req.w = new BufWriter(new Deno.Buffer());
await req.respond({ status: 200, body: "ok" }); await req.respond({ status: 200, body: "ok" });
assertEquals(tr.total, 0); assertEquals(tr.total, 0);
await req.finalize(); await req.finalize();
assertEquals(tr.total, text.length); assertEquals(tr.total, text.length);
}); }
test("ServerRequest.finalize() should consume unread body / chunked, trailers", async () => { );
Deno.test(
"ServerRequest.finalize() should consume unread body / chunked, trailers",
async () => {
const text = [ const text = [
"5", "5",
"Hello", "Hello",
@ -176,9 +179,9 @@ test("ServerRequest.finalize() should consume unread body / chunked, trailers",
req.headers.set("transfer-encoding", "chunked"); req.headers.set("transfer-encoding", "chunked");
req.headers.set("trailer", "deno,node"); req.headers.set("trailer", "deno,node");
const body = encode(text); const body = encode(text);
const tr = totalReader(new Buffer(body)); const tr = totalReader(new Deno.Buffer(body));
req.r = new BufReader(tr); req.r = new BufReader(tr);
req.w = new BufWriter(new Buffer()); req.w = new BufWriter(new Deno.Buffer());
await req.respond({ status: 200, body: "ok" }); await req.respond({ status: 200, body: "ok" });
assertEquals(tr.total, 0); assertEquals(tr.total, 0);
assertEquals(req.headers.has("trailer"), true); assertEquals(req.headers.has("trailer"), true);
@ -189,8 +192,9 @@ test("ServerRequest.finalize() should consume unread body / chunked, trailers",
assertEquals(req.headers.has("trailer"), false); assertEquals(req.headers.has("trailer"), false);
assertEquals(req.headers.get("deno"), "land"); assertEquals(req.headers.get("deno"), "land");
assertEquals(req.headers.get("node"), "js"); assertEquals(req.headers.get("node"), "js");
}); }
test("requestBodyWithTransferEncoding", async function (): Promise<void> { );
Deno.test("requestBodyWithTransferEncoding", async function (): Promise<void> {
{ {
const shortText = "Hello"; const shortText = "Hello";
const req = new ServerRequest(); const req = new ServerRequest();
@ -208,7 +212,7 @@ test("requestBodyWithTransferEncoding", async function (): Promise<void> {
chunkOffset += chunkSize; chunkOffset += chunkSize;
} }
chunksData += "0\r\n\r\n"; chunksData += "0\r\n\r\n";
const buf = new Buffer(encode(chunksData)); const buf = new Deno.Buffer(encode(chunksData));
req.r = new BufReader(buf); req.r = new BufReader(buf);
const body = decode(await Deno.readAll(req.body)); const body = decode(await Deno.readAll(req.body));
assertEquals(body, shortText); assertEquals(body, shortText);
@ -232,20 +236,22 @@ test("requestBodyWithTransferEncoding", async function (): Promise<void> {
chunkOffset += chunkSize; chunkOffset += chunkSize;
} }
chunksData += "0\r\n\r\n"; chunksData += "0\r\n\r\n";
const buf = new Buffer(encode(chunksData)); const buf = new Deno.Buffer(encode(chunksData));
req.r = new BufReader(buf); req.r = new BufReader(buf);
const body = decode(await Deno.readAll(req.body)); const body = decode(await Deno.readAll(req.body));
assertEquals(body, longText); assertEquals(body, longText);
} }
}); });
test("requestBodyReaderWithContentLength", async function (): Promise<void> { Deno.test("requestBodyReaderWithContentLength", async function (): Promise<
void
> {
{ {
const shortText = "Hello"; const shortText = "Hello";
const req = new ServerRequest(); const req = new ServerRequest();
req.headers = new Headers(); req.headers = new Headers();
req.headers.set("content-length", "" + shortText.length); 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); req.r = new BufReader(buf);
const readBuf = new Uint8Array(6); const readBuf = new Uint8Array(6);
let offset = 0; let offset = 0;
@ -266,7 +272,7 @@ test("requestBodyReaderWithContentLength", async function (): Promise<void> {
const req = new ServerRequest(); const req = new ServerRequest();
req.headers = new Headers(); req.headers = new Headers();
req.headers.set("Content-Length", "5000"); req.headers.set("Content-Length", "5000");
const buf = new Buffer(encode(longText)); const buf = new Deno.Buffer(encode(longText));
req.r = new BufReader(buf); req.r = new BufReader(buf);
const readBuf = new Uint8Array(1000); const readBuf = new Uint8Array(1000);
let offset = 0; 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 shortText = "Hello";
const req = new ServerRequest(); const req = new ServerRequest();
@ -300,7 +308,7 @@ test("requestBodyReaderWithTransferEncoding", async function (): Promise<void> {
chunkOffset += chunkSize; chunkOffset += chunkSize;
} }
chunksData += "0\r\n\r\n"; chunksData += "0\r\n\r\n";
const buf = new Buffer(encode(chunksData)); const buf = new Deno.Buffer(encode(chunksData));
req.r = new BufReader(buf); req.r = new BufReader(buf);
const readBuf = new Uint8Array(6); const readBuf = new Uint8Array(6);
let offset = 0; let offset = 0;
@ -333,7 +341,7 @@ test("requestBodyReaderWithTransferEncoding", async function (): Promise<void> {
chunkOffset += chunkSize; chunkOffset += chunkSize;
} }
chunksData += "0\r\n\r\n"; chunksData += "0\r\n\r\n";
const buf = new Buffer(encode(chunksData)); const buf = new Deno.Buffer(encode(chunksData));
req.r = new BufReader(buf); req.r = new BufReader(buf);
const readBuf = new Uint8Array(1000); const readBuf = new Uint8Array(1000);
let offset = 0; let offset = 0;
@ -349,7 +357,7 @@ test("requestBodyReaderWithTransferEncoding", async function (): Promise<void> {
} }
}); });
test({ Deno.test({
name: "destroyed connection", name: "destroyed connection",
fn: async (): Promise<void> => { fn: async (): Promise<void> => {
// Runs a simple server as another process // Runs a simple server as another process
@ -393,7 +401,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "serveTLS", name: "serveTLS",
fn: async (): Promise<void> => { fn: async (): Promise<void> => {
// Runs a simple server as another process // Runs a simple server as another process
@ -450,7 +458,9 @@ test({
}, },
}); });
test("close server while iterating", async (): Promise<void> => { Deno.test(
"close server while iterating",
async (): Promise<void> => {
const server = serve(":8123"); const server = serve(":8123");
const nextWhileClosing = server[Symbol.asyncIterator]().next(); const nextWhileClosing = server[Symbol.asyncIterator]().next();
server.close(); server.close();
@ -458,9 +468,10 @@ test("close server while iterating", async (): Promise<void> => {
const nextAfterClosing = server[Symbol.asyncIterator]().next(); const nextAfterClosing = server[Symbol.asyncIterator]().next();
assertEquals(await nextAfterClosing, { value: undefined, done: true }); assertEquals(await nextAfterClosing, { value: undefined, done: true });
}); }
);
test({ Deno.test({
name: "[http] close server while connection is open", name: "[http] close server while connection is open",
async fn(): Promise<void> { async fn(): Promise<void> {
async function iteratorReq(server: Server): Promise<void> { async function iteratorReq(server: Server): Promise<void> {
@ -491,7 +502,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "respond error closes connection", name: "respond error closes connection",
async fn(): Promise<void> { async fn(): Promise<void> {
const serverRoutine = async (): Promise<void> => { const serverRoutine = async (): Promise<void> => {
@ -522,7 +533,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "[http] request error gets 400 response", name: "[http] request error gets 400 response",
async fn(): Promise<void> { async fn(): Promise<void> {
const server = serve(":8124"); const server = serve(":8124");
@ -546,7 +557,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "serveTLS Invalid Cert", name: "serveTLS Invalid Cert",
fn: async (): Promise<void> => { fn: async (): Promise<void> => {
async function iteratorReq(server: Server): Promise<void> { async function iteratorReq(server: Server): Promise<void> {

View file

@ -2,9 +2,6 @@
// Copyright 2009 The Go Authors. All rights reserved. // Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style // Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file. // 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 { assert, assertEquals, fail } from "../testing/asserts.ts";
import { import {
BufReader, BufReader,
@ -47,11 +44,11 @@ Deno.test("bufioReaderSimple", async function (): Promise<void> {
interface ReadMaker { interface ReadMaker {
name: string; name: string;
fn: (r: Reader) => Reader; fn: (r: Deno.Reader) => Deno.Reader;
} }
const readMakers: ReadMaker[] = [ const readMakers: ReadMaker[] = [
{ name: "full", fn: (r): Reader => r }, { name: "full", fn: (r): Deno.Reader => r },
{ {
name: "byte", name: "byte",
fn: (r): iotest.OneByteReader => new iotest.OneByteReader(r), fn: (r): iotest.OneByteReader => new iotest.OneByteReader(r),
@ -190,7 +187,7 @@ const testInputrn = encoder.encode(
const testOutput = encoder.encode("0123456789abcdefghijklmnopqrstuvwxy"); const testOutput = encoder.encode("0123456789abcdefghijklmnopqrstuvwxy");
// TestReader wraps a Uint8Array and returns reads of a specific length. // 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) {} constructor(private data: Uint8Array, private stride: number) {}
read(buf: Uint8Array): Promise<number | null> { read(buf: Uint8Array): Promise<number | null> {
@ -337,7 +334,7 @@ Deno.test("bufioWriter", async function (): Promise<void> {
data[i] = charCode(" ") + (i % (charCode("~") - charCode(" "))); data[i] = charCode(" ") + (i % (charCode("~") - charCode(" ")));
} }
const w = new Buffer(); const w = new Deno.Buffer();
for (const nwrite of bufsizes) { for (const nwrite of bufsizes) {
for (const bs of bufsizes) { for (const bs of bufsizes) {
// Write nwrite bytes using buffer size bs. // Write nwrite bytes using buffer size bs.
@ -371,7 +368,7 @@ Deno.test("bufioWriterSync", function (): void {
data[i] = charCode(" ") + (i % (charCode("~") - charCode(" "))); data[i] = charCode(" ") + (i % (charCode("~") - charCode(" ")));
} }
const w = new Buffer(); const w = new Deno.Buffer();
for (const nwrite of bufsizes) { for (const nwrite of bufsizes) {
for (const bs of bufsizes) { for (const bs of bufsizes) {
// Write nwrite bytes using buffer size bs. // Write nwrite bytes using buffer size bs.
@ -401,7 +398,7 @@ Deno.test("bufReaderReadFull", async function (): Promise<void> {
const enc = new TextEncoder(); const enc = new TextEncoder();
const dec = new TextDecoder(); const dec = new TextDecoder();
const text = "Hello World"; 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 bufr = new BufReader(data, 3);
{ {
const buf = new Uint8Array(6); const buf = new Uint8Array(6);
@ -426,7 +423,7 @@ Deno.test("bufReaderReadFull", async function (): Promise<void> {
Deno.test("readStringDelimAndLines", async function (): Promise<void> { Deno.test("readStringDelimAndLines", async function (): Promise<void> {
const enc = new TextEncoder(); const enc = new TextEncoder();
const data = new Buffer( const data = new Deno.Buffer(
enc.encode("Hello World\tHello World 2\tHello World 3") enc.encode("Hello World\tHello World 2\tHello World 3")
); );
const chunks_ = []; const chunks_ = [];
@ -438,7 +435,7 @@ Deno.test("readStringDelimAndLines", async function (): Promise<void> {
assertEquals(chunks_.length, 3); assertEquals(chunks_.length, 3);
assertEquals(chunks_, ["Hello World", "Hello World 2", "Hello World 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_ = []; const lines_ = [];
for await (const l of readLines(linesData)) { for await (const l of readLines(linesData)) {

View file

@ -1,6 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // 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 { assertEquals } from "../testing/asserts.ts";
import { import {
copyN, copyN,
@ -14,7 +12,7 @@ import { BufReader } from "./bufio.ts";
import { tempFile } from "./util.ts"; import { tempFile } from "./util.ts";
import * as path from "../path/mod.ts"; import * as path from "../path/mod.ts";
class BinaryReader implements Reader { class BinaryReader implements Deno.Reader {
index = 0; index = 0;
constructor(private bytes: Uint8Array = new Uint8Array(0)) {} constructor(private bytes: Uint8Array = new Uint8Array(0)) {}
@ -73,7 +71,7 @@ Deno.test("testSliceLongToBytes2", function (): void {
}); });
Deno.test("testCopyN1", async function (): Promise<void> { Deno.test("testCopyN1", async function (): Promise<void> {
const w = new Buffer(); const w = new Deno.Buffer();
const r = new StringReader("abcdefghij"); const r = new StringReader("abcdefghij");
const n = await copyN(r, w, 3); const n = await copyN(r, w, 3);
assertEquals(n, 3); assertEquals(n, 3);
@ -81,7 +79,7 @@ Deno.test("testCopyN1", async function (): Promise<void> {
}); });
Deno.test("testCopyN2", 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 r = new StringReader("abcdefghij");
const n = await copyN(r, w, 11); const n = await copyN(r, w, 11);
assertEquals(n, 10); assertEquals(n, 10);

View file

@ -1,27 +1,23 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
// Based on https://github.com/golang/go/blob/0452f9460f50f0f0aba18df43dc2b31906fb66cc/src/io/io.go // Based on https://github.com/golang/go/blob/0452f9460f50f0f0aba18df43dc2b31906fb66cc/src/io/io.go
// Copyright 2009 The Go Authors. All rights reserved. // Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style // Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
type Reader = Deno.Reader;
import { encode } from "../encoding/utf8.ts"; import { encode } from "../encoding/utf8.ts";
const { Buffer } = Deno;
/** Reader utility for strings */ /** Reader utility for strings */
export class StringReader extends Buffer { export class StringReader extends Deno.Buffer {
constructor(private readonly s: string) { constructor(private readonly s: string) {
super(encode(s).buffer); super(encode(s).buffer);
} }
} }
/** Reader utility for combining multiple readers */ /** Reader utility for combining multiple readers */
export class MultiReader implements Reader { export class MultiReader implements Deno.Reader {
private readonly readers: Reader[]; private readonly readers: Deno.Reader[];
private currentIndex = 0; private currentIndex = 0;
constructor(...readers: Reader[]) { constructor(...readers: Deno.Reader[]) {
this.readers = readers; this.readers = readers;
} }

View file

@ -1,11 +1,10 @@
const { copy, test } = Deno;
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { LimitedReader, MultiReader, StringReader } from "./readers.ts"; import { LimitedReader, MultiReader, StringReader } from "./readers.ts";
import { StringWriter } from "./writers.ts"; import { StringWriter } from "./writers.ts";
import { copyN } from "./ioutil.ts"; import { copyN } from "./ioutil.ts";
import { decode } from "../encoding/utf8.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 r = new StringReader("abcdef");
const res0 = await r.read(new Uint8Array(6)); const res0 = await r.read(new Uint8Array(6));
assertEquals(res0, 6); assertEquals(res0, 6);
@ -13,7 +12,7 @@ test("ioStringReader", async function (): Promise<void> {
assertEquals(res1, null); assertEquals(res1, null);
}); });
test("ioStringReader", async function (): Promise<void> { Deno.test("ioStringReader", async function (): Promise<void> {
const r = new StringReader("abcdef"); const r = new StringReader("abcdef");
const buf = new Uint8Array(3); const buf = new Uint8Array(3);
const res1 = await r.read(buf); const res1 = await r.read(buf);
@ -27,17 +26,17 @@ test("ioStringReader", async function (): Promise<void> {
assertEquals(decode(buf), "def"); 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 r = new MultiReader(new StringReader("abc"), new StringReader("def"));
const w = new StringWriter(); const w = new StringWriter();
const n = await copyN(r, w, 4); const n = await copyN(r, w, 4);
assertEquals(n, 4); assertEquals(n, 4);
assertEquals(w.toString(), "abcd"); assertEquals(w.toString(), "abcd");
await copy(r, w); await Deno.copy(r, w);
assertEquals(w.toString(), "abcdef"); assertEquals(w.toString(), "abcdef");
}); });
test("ioLimitedReader", async function (): Promise<void> { Deno.test("ioLimitedReader", async function (): Promise<void> {
let sr = new StringReader("abc"); let sr = new StringReader("abc");
let r = new LimitedReader(sr, 2); let r = new LimitedReader(sr, 2);
let buffer = await Deno.readAll(r); let buffer = await Deno.readAll(r);
@ -55,7 +54,7 @@ test("ioLimitedReader", async function (): Promise<void> {
assertEquals((await Deno.readAll(r)).length, 0); 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 rb = new StringReader("abc");
const wb = new StringWriter(); const wb = new StringWriter();
await Deno.copy(new LimitedReader(rb, -1), wb); await Deno.copy(new LimitedReader(rb, -1), wb);

View file

@ -1,7 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // 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"; import * as path from "../path/mod.ts";
/** /**
@ -36,13 +33,13 @@ export async function tempFile(
prefix?: string; prefix?: string;
postfix?: string; postfix?: string;
} = { prefix: "", postfix: "" } } = { prefix: "", postfix: "" }
): Promise<{ file: File; filepath: string }> { ): Promise<{ file: Deno.File; filepath: string }> {
const r = Math.floor(Math.random() * 1000000); const r = Math.floor(Math.random() * 1000000);
const filepath = path.resolve( const filepath = path.resolve(
`${dir}/${opts.prefix || ""}${r}${opts.postfix || ""}` `${dir}/${opts.prefix || ""}${r}${opts.postfix || ""}`
); );
await mkdir(path.dirname(filepath), { recursive: true }); await Deno.mkdir(path.dirname(filepath), { recursive: true });
const file = await open(filepath, { const file = await Deno.open(filepath, {
create: true, create: true,
read: true, read: true,
write: true, write: true,

View file

@ -1,10 +1,9 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { remove, test } = Deno;
import { assert, assertEquals } from "../testing/asserts.ts"; import { assert, assertEquals } from "../testing/asserts.ts";
import * as path from "../path/mod.ts"; import * as path from "../path/mod.ts";
import { copyBytes, tempFile } from "./util.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); const dst = new Uint8Array(4);
dst.fill(0); dst.fill(0);
@ -38,7 +37,7 @@ test("[io/tuil] copyBytes", function (): void {
assertEquals(dst, Uint8Array.of(3, 4, 0, 0)); assertEquals(dst, Uint8Array.of(3, 4, 0, 0));
}); });
test({ Deno.test({
name: "[io/util] tempfile", name: "[io/util] tempfile",
fn: async function (): Promise<void> { fn: async function (): Promise<void> {
const f = await tempFile(".", { const f = await tempFile(".", {
@ -48,6 +47,6 @@ test({
const base = path.basename(f.filepath); const base = path.basename(f.filepath);
assert(!!base.match(/^prefix-.+?-postfix$/)); assert(!!base.match(/^prefix-.+?-postfix$/));
f.file.close(); f.file.close();
await remove(f.filepath); await Deno.remove(f.filepath);
}, },
}); });

View file

@ -1,15 +1,14 @@
const { copy, test } = Deno;
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { StringWriter } from "./writers.ts"; import { StringWriter } from "./writers.ts";
import { StringReader } from "./readers.ts"; import { StringReader } from "./readers.ts";
import { copyN } from "./ioutil.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 w = new StringWriter("base");
const r = new StringReader("0123456789"); const r = new StringReader("0123456789");
await copyN(r, w, 4); await copyN(r, w, 4);
assertEquals(w.toString(), "base0123"); assertEquals(w.toString(), "base0123");
await copy(r, w); await Deno.copy(r, w);
assertEquals(w.toString(), "base0123456789"); assertEquals(w.toString(), "base0123456789");
}); });

View file

@ -1,8 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // 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 { getLevelByName, LevelName, LogLevels } from "./levels.ts";
import { LogRecord } from "./logger.ts"; import { LogRecord } from "./logger.ts";
import { red, yellow, blue, bold } from "../fmt/colors.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 { export abstract class WriterHandler extends BaseHandler {
protected _writer!: Writer; protected _writer!: Deno.Writer;
#encoder = new TextEncoder(); #encoder = new TextEncoder();
abstract log(msg: string): void; abstract log(msg: string): void;
@ -100,11 +96,11 @@ interface FileHandlerOptions extends HandlerOptions {
} }
export class FileHandler extends WriterHandler { export class FileHandler extends WriterHandler {
protected _file: File | undefined; protected _file: Deno.File | undefined;
protected _buf!: BufWriterSync; protected _buf!: BufWriterSync;
protected _filename: string; protected _filename: string;
protected _mode: LogMode; protected _mode: LogMode;
protected _openOptions: OpenOptions; protected _openOptions: Deno.OpenOptions;
protected _encoder = new TextEncoder(); protected _encoder = new TextEncoder();
#unloadCallback = (): Promise<void> => this.destroy(); #unloadCallback = (): Promise<void> => this.destroy();
@ -123,7 +119,7 @@ export class FileHandler extends WriterHandler {
} }
async setup(): Promise<void> { 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._writer = this._file;
this._buf = new BufWriterSync(this._file); this._buf = new BufWriterSync(this._file);
@ -204,7 +200,7 @@ export class RotatingFileHandler extends FileHandler {
} }
} }
} else { } 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 { rotateLogFiles(): void {
this._buf.flush(); this._buf.flush();
close(this._file!.rid); Deno.close(this._file!.rid);
for (let i = this.#maxBackupCount - 1; i >= 0; i--) { for (let i = this.#maxBackupCount - 1; i >= 0; i--) {
const source = this._filename + (i === 0 ? "" : "." + i); const source = this._filename + (i === 0 ? "" : "." + i);
const dest = this._filename + "." + (i + 1); const dest = this._filename + "." + (i + 1);
if (existsSync(source)) { 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._writer = this._file;
this._buf = new BufWriterSync(this._file); this._buf = new BufWriterSync(this._file);
} }

View file

@ -1,5 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { test } = Deno;
import { import {
assert, assert,
assertEquals, assertEquals,
@ -27,7 +26,7 @@ class TestHandler extends BaseHandler {
} }
} }
test("simpleHandler", function (): void { Deno.test("simpleHandler", function (): void {
const cases = new Map<number, string[]>([ const cases = new Map<number, string[]>([
[ [
LogLevels.DEBUG, LogLevels.DEBUG,
@ -73,7 +72,7 @@ test("simpleHandler", function (): void {
} }
}); });
test("testFormatterAsString", function (): void { Deno.test("testFormatterAsString", function (): void {
const handler = new TestHandler("DEBUG", { const handler = new TestHandler("DEBUG", {
formatter: "test {levelName} {msg}", formatter: "test {levelName} {msg}",
}); });
@ -83,7 +82,7 @@ test("testFormatterAsString", function (): void {
assertEquals(handler.messages, ["test DEBUG Hello, world!"]); assertEquals(handler.messages, ["test DEBUG Hello, world!"]);
}); });
test("testFormatterAsFunction", function (): void { Deno.test("testFormatterAsFunction", function (): void {
const handler = new TestHandler("DEBUG", { const handler = new TestHandler("DEBUG", {
formatter: (logRecord): string => formatter: (logRecord): string =>
`fn formatter ${logRecord.levelName} ${logRecord.msg}`, `fn formatter ${logRecord.levelName} ${logRecord.msg}`,
@ -94,7 +93,7 @@ test("testFormatterAsFunction", function (): void {
assertEquals(handler.messages, ["fn formatter ERROR Hello, world!"]); assertEquals(handler.messages, ["fn formatter ERROR Hello, world!"]);
}); });
test({ Deno.test({
name: "FileHandler with mode 'w' will wipe clean existing log file", name: "FileHandler with mode 'w' will wipe clean existing log file",
async fn() { async fn() {
const fileHandler = new FileHandler("WARNING", { 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", name: "FileHandler with mode 'x' will throw if log file already exists",
async fn() { async fn() {
const fileHandler = new FileHandler("WARNING", { const fileHandler = new FileHandler("WARNING", {
@ -136,7 +135,7 @@ test({
}, },
}); });
test({ Deno.test({
name: name:
"RotatingFileHandler with mode 'w' will wipe clean existing log file and remove others", "RotatingFileHandler with mode 'w' will wipe clean existing log file and remove others",
async fn() { async fn() {
@ -172,7 +171,7 @@ test({
}, },
}); });
test({ Deno.test({
name: name:
"RotatingFileHandler with mode 'x' will throw if any log file already exists", "RotatingFileHandler with mode 'x' will throw if any log file already exists",
async fn() { async fn() {
@ -200,7 +199,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "RotatingFileHandler with first rollover, monitor step by step", name: "RotatingFileHandler with first rollover, monitor step by step",
async fn() { async fn() {
const fileHandler = new RotatingFileHandler("WARNING", { const fileHandler = new RotatingFileHandler("WARNING", {
@ -229,7 +228,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "RotatingFileHandler with first rollover, check all at once", name: "RotatingFileHandler with first rollover, check all at once",
async fn() { async fn() {
const fileHandler = new RotatingFileHandler("WARNING", { const fileHandler = new RotatingFileHandler("WARNING", {
@ -254,7 +253,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "RotatingFileHandler with all backups rollover", name: "RotatingFileHandler with all backups rollover",
async fn() { async fn() {
Deno.writeFileSync(LOG_FILE, new TextEncoder().encode("original log file")); 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", name: "RotatingFileHandler maxBytes cannot be less than 1",
async fn() { async fn() {
await assertThrowsAsync( await assertThrowsAsync(
@ -323,7 +322,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "RotatingFileHandler maxBackupCount cannot be less than 1", name: "RotatingFileHandler maxBackupCount cannot be less than 1",
async fn() { async fn() {
await assertThrowsAsync( await assertThrowsAsync(
@ -342,7 +341,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Window unload flushes buffer", name: "Window unload flushes buffer",
async fn() { async fn() {
const fileHandler = new FileHandler("WARNING", { const fileHandler = new FileHandler("WARNING", {
@ -360,7 +359,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "RotatingFileHandler: rotate on byte length, not msg length", name: "RotatingFileHandler: rotate on byte length, not msg length",
async fn() { async fn() {
const fileHandler = new RotatingFileHandler("WARNING", { const fileHandler = new RotatingFileHandler("WARNING", {
@ -394,7 +393,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "FileHandler: Critical logs trigger immediate flush", name: "FileHandler: Critical logs trigger immediate flush",
async fn() { async fn() {
const fileHandler = new FileHandler("WARNING", { const fileHandler = new FileHandler("WARNING", {

View file

@ -1,5 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { test } = Deno;
import { assertEquals, assert } from "../testing/asserts.ts"; import { assertEquals, assert } from "../testing/asserts.ts";
import { LogRecord, Logger } from "./logger.ts"; import { LogRecord, Logger } from "./logger.ts";
import { LogLevels, LevelName } from "./levels.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"); const handler = new TestHandler("DEBUG");
let logger = new Logger("DEBUG"); let logger = new Logger("DEBUG");
@ -32,7 +31,7 @@ test("simpleLogger", function (): void {
assertEquals(logger.handlers, [handler]); assertEquals(logger.handlers, [handler]);
}); });
test("customHandler", function (): void { Deno.test("customHandler", function (): void {
const handler = new TestHandler("DEBUG"); const handler = new TestHandler("DEBUG");
const logger = new Logger("DEBUG", [handler]); const logger = new Logger("DEBUG", [handler]);
@ -48,7 +47,7 @@ test("customHandler", function (): void {
assertEquals(inlineData!, "foo"); assertEquals(inlineData!, "foo");
}); });
test("logFunctions", function (): void { Deno.test("logFunctions", function (): void {
const doLog = (level: LevelName): TestHandler => { const doLog = (level: LevelName): TestHandler => {
const handler = new TestHandler(level); const handler = new TestHandler(level);
const logger = new Logger(level, [handler]); const logger = new Logger(level, [handler]);
@ -98,7 +97,9 @@ test("logFunctions", function (): void {
assertEquals(handler.messages, ["CRITICAL doo"]); assertEquals(handler.messages, ["CRITICAL doo"]);
}); });
test("String resolver fn will not execute if msg will not be logged", function (): void { Deno.test(
"String resolver fn will not execute if msg will not be logged",
function (): void {
const handler = new TestHandler("ERROR"); const handler = new TestHandler("ERROR");
const logger = new Logger("ERROR", [handler]); const logger = new Logger("ERROR", [handler]);
let called = false; let called = false;
@ -108,12 +109,17 @@ test("String resolver fn will not execute if msg will not be logged", function (
return "expensive function result"; return "expensive function result";
}; };
const inlineData: string | undefined = logger.debug(expensiveFunction, 1, 2); const inlineData: string | undefined = logger.debug(
expensiveFunction,
1,
2
);
assert(!called); assert(!called);
assertEquals(inlineData, undefined); 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 handler = new TestHandler("ERROR");
const logger = new Logger("ERROR", [handler]); const logger = new Logger("ERROR", [handler]);
const expensiveFunction = (x: number): string => { const expensiveFunction = (x: number): string => {
@ -126,7 +132,9 @@ test("String resolver fn resolves as expected", function (): void {
assertEquals(secondInlineData, "expensive function result 12"); assertEquals(secondInlineData, "expensive function result 12");
}); });
test("All types map correctly to log strings and are returned as is", function (): void { Deno.test(
"All types map correctly to log strings and are returned as is",
function (): void {
const handler = new TestHandler("DEBUG"); const handler = new TestHandler("DEBUG");
const logger = new Logger("DEBUG", [handler]); const logger = new Logger("DEBUG", [handler]);
const sym = Symbol(); const sym = Symbol();
@ -218,4 +226,5 @@ test("All types map correctly to log strings and are returned as is", function (
}); });
assertEquals(handler.messages[16], 'ERROR {"payload":"data","other":123}'); assertEquals(handler.messages[16], 'ERROR {"payload":"data","other":123}');
assertEquals(handler.messages[17], 'ERROR {"payload":"data","other":123}'); assertEquals(handler.messages[17], 'ERROR {"payload":"data","other":123}');
}); }
);

View file

@ -1,5 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { test } = Deno;
import { assert, assertEquals } from "../testing/asserts.ts"; import { assert, assertEquals } from "../testing/asserts.ts";
import { getLogger, debug, info, warning, error, critical } from "./mod.ts"; import { getLogger, debug, info, warning, error, critical } from "./mod.ts";
import { Logger } from "./logger.ts"; import { Logger } from "./logger.ts";
@ -13,11 +12,11 @@ try {
// Pass // Pass
} }
test("logger is initialized", function (): void { Deno.test("logger is initialized", function (): void {
assert(logger instanceof Logger); 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 sym = Symbol("a");
const debugData: string = debug("foo"); const debugData: string = debug("foo");
const debugResolver: string | undefined = debug(() => "foo"); const debugResolver: string | undefined = debug(() => "foo");

View file

@ -1,5 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { test } = Deno;
import { assertEquals, assertThrows } from "../testing/asserts.ts"; import { assertEquals, assertThrows } from "../testing/asserts.ts";
import * as log from "./mod.ts"; import * as log from "./mod.ts";
import { 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: { const loggers: {
[key: string]: (msg: string, ...args: unknown[]) => void; [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"); const handler = new TestHandler("DEBUG");
await log.setup({ await log.setup({
@ -76,7 +75,7 @@ test("getLogger", async function (): Promise<void> {
assertEquals(logger.handlers, [handler]); assertEquals(logger.handlers, [handler]);
}); });
test("getLoggerWithName", async function (): Promise<void> { Deno.test("getLoggerWithName", async function (): Promise<void> {
const fooHandler = new TestHandler("DEBUG"); const fooHandler = new TestHandler("DEBUG");
await log.setup({ await log.setup({
@ -97,7 +96,7 @@ test("getLoggerWithName", async function (): Promise<void> {
assertEquals(logger.handlers, [fooHandler]); assertEquals(logger.handlers, [fooHandler]);
}); });
test("getLoggerUnknown", async function (): Promise<void> { Deno.test("getLoggerUnknown", async function (): Promise<void> {
await log.setup({ await log.setup({
handlers: {}, handlers: {},
loggers: {}, loggers: {},
@ -109,7 +108,7 @@ test("getLoggerUnknown", async function (): Promise<void> {
assertEquals(logger.handlers, []); assertEquals(logger.handlers, []);
}); });
test("getInvalidLoggerLevels", function (): void { Deno.test("getInvalidLoggerLevels", function (): void {
assertThrows(() => getLevelByName("FAKE_LOG_LEVEL" as LevelName)); assertThrows(() => getLevelByName("FAKE_LOG_LEVEL" as LevelName));
assertThrows(() => getLevelName(5000)); assertThrows(() => getLevelName(5000));
}); });

View file

@ -1,10 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // 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 { equal, findIndex, findLastIndex, hasPrefix } from "../bytes/mod.ts";
import { copyN } from "../io/ioutil.ts"; import { copyN } from "../io/ioutil.ts";
import { MultiReader } from "../io/readers.ts"; import { MultiReader } from "../io/readers.ts";
@ -150,7 +144,7 @@ export function scanUntilBoundary(
return buf.length; return buf.length;
} }
class PartReader implements Reader, Closer { class PartReader implements Deno.Reader, Deno.Closer {
n: number | null = 0; n: number | null = 0;
total = 0; total = 0;
@ -163,7 +157,7 @@ class PartReader implements Reader, Closer {
// or we find a reason to stop (boundary or EOF). // or we find a reason to stop (boundary or EOF).
let peekLength = 1; let peekLength = 1;
while (this.n === 0) { while (this.n === 0) {
peekLength = max(peekLength, br.buffered()); peekLength = Math.max(peekLength, br.buffered());
const peekBuf = await br.peek(peekLength); const peekBuf = await br.peek(peekLength);
if (peekBuf === null) { if (peekBuf === null) {
throw new Deno.errors.UnexpectedEof(); throw new Deno.errors.UnexpectedEof();
@ -187,7 +181,7 @@ class PartReader implements Reader, Closer {
return null; return null;
} }
const nread = min(p.length, this.n); const nread = Math.min(p.length, this.n);
const buf = p.subarray(0, nread); const buf = p.subarray(0, nread);
const r = await br.readFull(buf); const r = await br.readFull(buf);
assert(r === buf); assert(r === buf);
@ -272,7 +266,7 @@ export class MultipartReader {
readonly dashBoundary = encoder.encode(`--${this.boundary}`); readonly dashBoundary = encoder.encode(`--${this.boundary}`);
readonly bufReader: BufReader; readonly bufReader: BufReader;
constructor(reader: Reader, private boundary: string) { constructor(reader: Deno.Reader, private boundary: string) {
this.bufReader = new BufReader(reader); this.bufReader = new BufReader(reader);
} }
@ -287,7 +281,7 @@ export class MultipartReader {
const fileMap = new Map<string, FormFile | FormFile[]>(); const fileMap = new Map<string, FormFile | FormFile[]>();
const valueMap = new Map<string, string>(); const valueMap = new Map<string, string>();
let maxValueBytes = maxMemory + (10 << 20); let maxValueBytes = maxMemory + (10 << 20);
const buf = new Buffer(new Uint8Array(maxValueBytes)); const buf = new Deno.Buffer(new Uint8Array(maxValueBytes));
for (;;) { for (;;) {
const p = await this.nextPart(); const p = await this.nextPart();
if (p === null) { if (p === null) {
@ -321,7 +315,7 @@ export class MultipartReader {
postfix: ext, postfix: ext,
}); });
try { try {
const size = await copy(new MultiReader(buf, p), file); const size = await Deno.copy(new MultiReader(buf, p), file);
file.close(); file.close();
formFile = { formFile = {
@ -331,7 +325,7 @@ export class MultipartReader {
size, size,
}; };
} catch (e) { } catch (e) {
await remove(filepath); await Deno.remove(filepath);
throw e; throw e;
} }
} else { } else {
@ -465,13 +459,13 @@ function multipatFormData(
}; };
} }
class PartWriter implements Writer { class PartWriter implements Deno.Writer {
closed = false; closed = false;
private readonly partHeader: string; private readonly partHeader: string;
private headersWritten = false; private headersWritten = false;
constructor( constructor(
private writer: Writer, private writer: Deno.Writer,
readonly boundary: string, readonly boundary: string,
public headers: Headers, public headers: Headers,
isFirstBoundary: boolean isFirstBoundary: boolean
@ -531,7 +525,7 @@ export class MultipartWriter {
private bufWriter: BufWriter; private bufWriter: BufWriter;
private isClosed = false; private isClosed = false;
constructor(private readonly writer: Writer, boundary?: string) { constructor(private readonly writer: Deno.Writer, boundary?: string) {
if (boundary !== void 0) { if (boundary !== void 0) {
this._boundary = checkBoundary(boundary); this._boundary = checkBoundary(boundary);
} else { } else {
@ -544,7 +538,7 @@ export class MultipartWriter {
return `multipart/form-data; boundary=${this.boundary}`; return `multipart/form-data; boundary=${this.boundary}`;
} }
private createPart(headers: Headers): Writer { private createPart(headers: Headers): Deno.Writer {
if (this.isClosed) { if (this.isClosed) {
throw new Error("multipart: writer is closed"); throw new Error("multipart: writer is closed");
} }
@ -561,7 +555,7 @@ export class MultipartWriter {
return part; return part;
} }
createFormFile(field: string, filename: string): Writer { createFormFile(field: string, filename: string): Deno.Writer {
const h = new Headers(); const h = new Headers();
h.set( h.set(
"Content-Disposition", "Content-Disposition",
@ -571,7 +565,7 @@ export class MultipartWriter {
return this.createPart(h); return this.createPart(h);
} }
createFormField(field: string): Writer { createFormField(field: string): Deno.Writer {
const h = new Headers(); const h = new Headers();
h.set("Content-Disposition", `form-data; name="${field}"`); h.set("Content-Disposition", `form-data; name="${field}"`);
h.set("Content-Type", "application/octet-stream"); h.set("Content-Type", "application/octet-stream");
@ -586,10 +580,10 @@ export class MultipartWriter {
async writeFile( async writeFile(
field: string, field: string,
filename: string, filename: string,
file: Reader file: Deno.Reader
): Promise<void> { ): Promise<void> {
const f = await this.createFormFile(field, filename); const f = await this.createFormFile(field, filename);
await copy(file, f); await Deno.copy(file, f);
} }
private flush(): Promise<void> { private flush(): Promise<void> {

View file

@ -1,6 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { Buffer, open, test } = Deno;
import { import {
assert, assert,
assertEquals, assertEquals,
@ -23,7 +21,7 @@ const dashBoundary = e.encode("--" + boundary);
const nlDashBoundary = e.encode("\r\n--" + boundary); const nlDashBoundary = e.encode("\r\n--" + boundary);
const testdataDir = path.resolve("mime", "testdata"); const testdataDir = path.resolve("mime", "testdata");
test("multipartScanUntilBoundary1", function (): void { Deno.test("multipartScanUntilBoundary1", function (): void {
const data = `--${boundary}`; const data = `--${boundary}`;
const n = scanUntilBoundary( const n = scanUntilBoundary(
e.encode(data), e.encode(data),
@ -35,7 +33,7 @@ test("multipartScanUntilBoundary1", function (): void {
assertEquals(n, null); assertEquals(n, null);
}); });
test("multipartScanUntilBoundary2", function (): void { Deno.test("multipartScanUntilBoundary2", function (): void {
const data = `foo\r\n--${boundary}`; const data = `foo\r\n--${boundary}`;
const n = scanUntilBoundary( const n = scanUntilBoundary(
e.encode(data), e.encode(data),
@ -47,7 +45,7 @@ test("multipartScanUntilBoundary2", function (): void {
assertEquals(n, 3); assertEquals(n, 3);
}); });
test("multipartScanUntilBoundary3", function (): void { Deno.test("multipartScanUntilBoundary3", function (): void {
const data = `foobar`; const data = `foobar`;
const n = scanUntilBoundary( const n = scanUntilBoundary(
e.encode(data), e.encode(data),
@ -59,7 +57,7 @@ test("multipartScanUntilBoundary3", function (): void {
assertEquals(n, data.length); assertEquals(n, data.length);
}); });
test("multipartScanUntilBoundary4", function (): void { Deno.test("multipartScanUntilBoundary4", function (): void {
const data = `foo\r\n--`; const data = `foo\r\n--`;
const n = scanUntilBoundary( const n = scanUntilBoundary(
e.encode(data), e.encode(data),
@ -71,30 +69,30 @@ test("multipartScanUntilBoundary4", function (): void {
assertEquals(n, 3); assertEquals(n, 3);
}); });
test("multipartMatchAfterPrefix1", function (): void { Deno.test("multipartMatchAfterPrefix1", function (): void {
const data = `${boundary}\r`; const data = `${boundary}\r`;
const v = matchAfterPrefix(e.encode(data), e.encode(boundary), false); const v = matchAfterPrefix(e.encode(data), e.encode(boundary), false);
assertEquals(v, 1); assertEquals(v, 1);
}); });
test("multipartMatchAfterPrefix2", function (): void { Deno.test("multipartMatchAfterPrefix2", function (): void {
const data = `${boundary}hoge`; const data = `${boundary}hoge`;
const v = matchAfterPrefix(e.encode(data), e.encode(boundary), false); const v = matchAfterPrefix(e.encode(data), e.encode(boundary), false);
assertEquals(v, -1); assertEquals(v, -1);
}); });
test("multipartMatchAfterPrefix3", function (): void { Deno.test("multipartMatchAfterPrefix3", function (): void {
const data = `${boundary}`; const data = `${boundary}`;
const v = matchAfterPrefix(e.encode(data), e.encode(boundary), false); const v = matchAfterPrefix(e.encode(data), e.encode(boundary), false);
assertEquals(v, 0); assertEquals(v, 0);
}); });
test("multipartMultipartWriter", async function (): Promise<void> { Deno.test("multipartMultipartWriter", async function (): Promise<void> {
const buf = new Buffer(); const buf = new Deno.Buffer();
const mw = new MultipartWriter(buf); const mw = new MultipartWriter(buf);
await mw.writeField("foo", "foo"); await mw.writeField("foo", "foo");
await mw.writeField("bar", "bar"); 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, read: true,
}); });
await mw.writeFile("file", "sample.txt", f); await mw.writeFile("file", "sample.txt", f);
@ -102,7 +100,7 @@ test("multipartMultipartWriter", async function (): Promise<void> {
f.close(); f.close();
}); });
test("multipartMultipartWriter2", function (): void { Deno.test("multipartMultipartWriter2", function (): void {
const w = new StringWriter(); const w = new StringWriter();
assertThrows( assertThrows(
(): MultipartWriter => new MultipartWriter(w, ""), (): 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 w = new StringWriter();
const mw = new MultipartWriter(w); const mw = new MultipartWriter(w);
await mw.writeField("foo", "foo"); await mw.writeField("foo", "foo");
@ -174,10 +172,10 @@ test("multipartMultipartWriter3", async function (): Promise<void> {
); );
}); });
test({ Deno.test({
name: "[mime/multipart] readForm() basic", name: "[mime/multipart] readForm() basic",
async fn() { 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( const mr = new MultipartReader(
o, o,
"--------------------------434049563556637648550474" "--------------------------434049563556637648550474"
@ -196,18 +194,21 @@ test({
}, },
}); });
test({ Deno.test({
name: name:
"[mime/multipart] readForm() should store big file completely in temp file", "[mime/multipart] readForm() should store big file completely in temp file",
async fn() { async fn() {
const multipartFile = path.join(testdataDir, "form-data.dat"); const multipartFile = path.join(testdataDir, "form-data.dat");
const sampleFile = await Deno.makeTempFile(); 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 const size = 1 << 24; // 16mb
await Deno.truncate(sampleFile, size); 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); const mw = new MultipartWriter(writer);
await mw.writeField("deno", "land"); await mw.writeField("deno", "land");
@ -243,10 +244,10 @@ test({
}, },
}); });
test({ Deno.test({
name: "[mime/multipart] removeAll() should remove all tempfiles", name: "[mime/multipart] removeAll() should remove all tempfiles",
async fn() { 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( const mr = new MultipartReader(
o, o,
"--------------------------434049563556637648550474" "--------------------------434049563556637648550474"
@ -270,10 +271,10 @@ test({
}, },
}); });
test({ Deno.test({
name: "[mime/multipart] entries()", name: "[mime/multipart] entries()",
async fn() { 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( const mr = new MultipartReader(
o, o,
"--------------------------434049563556637648550474" "--------------------------434049563556637648550474"

View file

@ -1,12 +1,11 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { test } = Deno;
import { assertEquals, assertThrows, fail } from "../../testing/asserts.ts"; import { assertEquals, assertThrows, fail } from "../../testing/asserts.ts";
import { appendFile, appendFileSync } from "./_fs_appendFile.ts"; import { appendFile, appendFileSync } from "./_fs_appendFile.ts";
import { fromFileUrl } from "../path.ts"; import { fromFileUrl } from "../path.ts";
const decoder = new TextDecoder("utf-8"); const decoder = new TextDecoder("utf-8");
test({ Deno.test({
name: "No callback Fn results in Error", name: "No callback Fn results in Error",
fn() { fn() {
assertThrows( assertThrows(
@ -19,7 +18,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Unsupported encoding results in error()", name: "Unsupported encoding results in error()",
fn() { fn() {
assertThrows( assertThrows(
@ -57,7 +56,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Async: Data is written to passed in rid", name: "Async: Data is written to passed in rid",
async fn() { async fn() {
const tempFile: string = await Deno.makeTempFile(); const tempFile: string = await Deno.makeTempFile();
@ -86,7 +85,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Async: Data is written to passed in file path", name: "Async: Data is written to passed in file path",
async fn() { async fn() {
const openResourcesBeforeAppend: Deno.ResourceMap = Deno.resources(); const openResourcesBeforeAppend: Deno.ResourceMap = Deno.resources();
@ -110,7 +109,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Async: Data is written to passed in URL", name: "Async: Data is written to passed in URL",
async fn() { async fn() {
const openResourcesBeforeAppend: Deno.ResourceMap = Deno.resources(); const openResourcesBeforeAppend: Deno.ResourceMap = Deno.resources();
@ -135,7 +134,7 @@ test({
}, },
}); });
test({ Deno.test({
name: name:
"Async: Callback is made with error if attempting to append data to an existing file with 'ax' flag", "Async: Callback is made with error if attempting to append data to an existing file with 'ax' flag",
async fn() { async fn() {
@ -159,7 +158,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Sync: Data is written to passed in rid", name: "Sync: Data is written to passed in rid",
fn() { fn() {
const tempFile: string = Deno.makeTempFileSync(); const tempFile: string = Deno.makeTempFileSync();
@ -176,7 +175,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Sync: Data is written to passed in file path", name: "Sync: Data is written to passed in file path",
fn() { fn() {
const openResourcesBeforeAppend: Deno.ResourceMap = Deno.resources(); const openResourcesBeforeAppend: Deno.ResourceMap = Deno.resources();
@ -188,7 +187,7 @@ test({
}, },
}); });
test({ Deno.test({
name: name:
"Sync: error thrown if attempting to append data to an existing file with 'ax' flag", "Sync: error thrown if attempting to append data to an existing file with 'ax' flag",
fn() { fn() {

View file

@ -1,9 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { test } = Deno;
import { fail, assert } from "../../testing/asserts.ts"; import { fail, assert } from "../../testing/asserts.ts";
import { chmod, chmodSync } from "./_fs_chmod.ts"; import { chmod, chmodSync } from "./_fs_chmod.ts";
test({ Deno.test({
name: "ASYNC: Permissions are changed (non-Windows)", name: "ASYNC: Permissions are changed (non-Windows)",
ignore: Deno.build.os === "windows", ignore: Deno.build.os === "windows",
async fn() { async fn() {
@ -29,7 +28,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "SYNC: Permissions are changed (non-Windows)", name: "SYNC: Permissions are changed (non-Windows)",
ignore: Deno.build.os === "windows", ignore: Deno.build.os === "windows",
fn() { fn() {

View file

@ -1,5 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { test } = Deno;
import { fail, assertEquals } from "../../testing/asserts.ts"; import { fail, assertEquals } from "../../testing/asserts.ts";
import { chown, chownSync } from "./_fs_chown.ts"; import { chown, chownSync } from "./_fs_chown.ts";
@ -7,7 +6,7 @@ import { chown, chownSync } from "./_fs_chown.ts";
// id again // id again
const ignore = Deno.build.os == "windows"; const ignore = Deno.build.os == "windows";
test({ Deno.test({
ignore, ignore,
name: "ASYNC: setting existing uid/gid works as expected (non-Windows)", name: "ASYNC: setting existing uid/gid works as expected (non-Windows)",
async fn() { async fn() {
@ -35,7 +34,7 @@ test({
}, },
}); });
test({ Deno.test({
ignore, ignore,
name: "SYNC: setting existing uid/gid works as expected (non-Windows)", name: "SYNC: setting existing uid/gid works as expected (non-Windows)",
fn() { fn() {

View file

@ -1,9 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { test } = Deno;
import { fail, assert, assertThrows } from "../../testing/asserts.ts"; import { fail, assert, assertThrows } from "../../testing/asserts.ts";
import { close, closeSync } from "./_fs_close.ts"; import { close, closeSync } from "./_fs_close.ts";
test({ Deno.test({
name: "ASYNC: File is closed", name: "ASYNC: File is closed",
async fn() { async fn() {
const tempFile: string = await Deno.makeTempFile(); const tempFile: string = await Deno.makeTempFile();
@ -28,7 +27,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "ASYNC: Invalid fd", name: "ASYNC: Invalid fd",
async fn() { async fn() {
await new Promise((resolve, reject) => { await new Promise((resolve, reject) => {
@ -40,7 +39,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "close callback should be asynchronous", name: "close callback should be asynchronous",
async fn() { async fn() {
const tempFile: string = Deno.makeTempFileSync(); const tempFile: string = Deno.makeTempFileSync();
@ -60,7 +59,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "SYNC: File is closed", name: "SYNC: File is closed",
fn() { fn() {
const tempFile: string = Deno.makeTempFileSync(); const tempFile: string = Deno.makeTempFileSync();
@ -73,7 +72,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "SYNC: Invalid fd", name: "SYNC: Invalid fd",
fn() { fn() {
assertThrows(() => closeSync(-1)); assertThrows(() => closeSync(-1));

View file

@ -1,13 +1,11 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // 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 { copyFile, copyFileSync } from "./_fs_copy.ts";
import { existsSync } from "./_fs_exists.ts"; import { existsSync } from "./_fs_exists.ts";
import { assert } from "../../testing/asserts.ts";
const { test } = Deno;
const destFile = "./destination.txt"; const destFile = "./destination.txt";
test({ Deno.test({
name: "[std/node/fs] copy file", name: "[std/node/fs] copy file",
fn: async () => { fn: async () => {
const sourceFile = Deno.makeTempFileSync(); const sourceFile = Deno.makeTempFileSync();
@ -21,7 +19,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "[std/node/fs] copy file sync", name: "[std/node/fs] copy file sync",
fn: () => { fn: () => {
const sourceFile = Deno.makeTempFileSync(); const sourceFile = Deno.makeTempFileSync();

View file

@ -1,9 +1,8 @@
const { test } = Deno;
import { assert, assertEquals, fail } from "../../testing/asserts.ts"; import { assert, assertEquals, fail } from "../../testing/asserts.ts";
import Dir from "./_fs_dir.ts"; import Dir from "./_fs_dir.ts";
import Dirent from "./_fs_dirent.ts"; import Dirent from "./_fs_dirent.ts";
test({ Deno.test({
name: "Closing current directory with callback is successful", name: "Closing current directory with callback is successful",
fn() { fn() {
let calledBack = false; let calledBack = false;
@ -16,21 +15,21 @@ test({
}, },
}); });
test({ Deno.test({
name: "Closing current directory without callback returns void Promise", name: "Closing current directory without callback returns void Promise",
async fn() { async fn() {
await new Dir(".").close(); await new Dir(".").close();
}, },
}); });
test({ Deno.test({
name: "Closing current directory synchronously works", name: "Closing current directory synchronously works",
fn() { fn() {
new Dir(".").closeSync(); new Dir(".").closeSync();
}, },
}); });
test({ Deno.test({
name: "Path is correctly returned", name: "Path is correctly returned",
fn() { fn() {
assertEquals(new Dir("std/node").path, "std/node"); assertEquals(new Dir("std/node").path, "std/node");
@ -40,7 +39,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "read returns null for empty directory", name: "read returns null for empty directory",
async fn() { async fn() {
const testDir: string = Deno.makeTempDirSync(); const testDir: string = Deno.makeTempDirSync();
@ -67,7 +66,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Async read returns one file at a time", name: "Async read returns one file at a time",
async fn() { async fn() {
const testDir: string = Deno.makeTempDirSync(); const testDir: string = Deno.makeTempDirSync();
@ -108,7 +107,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Sync read returns one file at a time", name: "Sync read returns one file at a time",
fn() { fn() {
const testDir: string = Deno.makeTempDirSync(); const testDir: string = Deno.makeTempDirSync();
@ -139,7 +138,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Async iteration over existing directory", name: "Async iteration over existing directory",
async fn() { async fn() {
const testDir: string = Deno.makeTempDirSync(); const testDir: string = Deno.makeTempDirSync();

View file

@ -1,4 +1,3 @@
const { test } = Deno;
import { assert, assertEquals, assertThrows } from "../../testing/asserts.ts"; import { assert, assertEquals, assertThrows } from "../../testing/asserts.ts";
import Dirent from "./_fs_dirent.ts"; import Dirent from "./_fs_dirent.ts";
@ -9,7 +8,7 @@ class DirEntryMock implements Deno.DirEntry {
isSymlink = false; isSymlink = false;
} }
test({ Deno.test({
name: "Directories are correctly identified", name: "Directories are correctly identified",
fn() { fn() {
const entry: DirEntryMock = new DirEntryMock(); const entry: DirEntryMock = new DirEntryMock();
@ -22,7 +21,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Files are correctly identified", name: "Files are correctly identified",
fn() { fn() {
const entry: DirEntryMock = new DirEntryMock(); const entry: DirEntryMock = new DirEntryMock();
@ -35,7 +34,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Symlinks are correctly identified", name: "Symlinks are correctly identified",
fn() { fn() {
const entry: DirEntryMock = new DirEntryMock(); const entry: DirEntryMock = new DirEntryMock();
@ -48,7 +47,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "File name is correct", name: "File name is correct",
fn() { fn() {
const entry: DirEntryMock = new DirEntryMock(); const entry: DirEntryMock = new DirEntryMock();
@ -57,7 +56,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Socket and FIFO pipes aren't yet available", name: "Socket and FIFO pipes aren't yet available",
fn() { fn() {
const entry: DirEntryMock = new DirEntryMock(); const entry: DirEntryMock = new DirEntryMock();

View file

@ -1,11 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { assertEquals } from "../../testing/asserts.ts"; import { assertEquals } from "../../testing/asserts.ts";
import { exists, existsSync } from "./_fs_exists.ts"; import { exists, existsSync } from "./_fs_exists.ts";
const { test } = Deno; Deno.test("existsFile", async function () {
test("existsFile", async function () {
const availableFile = await new Promise((resolve) => { const availableFile = await new Promise((resolve) => {
const tmpFilePath = Deno.makeTempFileSync(); const tmpFilePath = Deno.makeTempFileSync();
exists(tmpFilePath, (exists: boolean) => { exists(tmpFilePath, (exists: boolean) => {
@ -20,7 +17,7 @@ test("existsFile", async function () {
assertEquals(notAvailableFile, false); assertEquals(notAvailableFile, false);
}); });
test("existsSyncFile", function () { Deno.test("existsSyncFile", function () {
const tmpFilePath = Deno.makeTempFileSync(); const tmpFilePath = Deno.makeTempFileSync();
assertEquals(existsSync(tmpFilePath), true); assertEquals(existsSync(tmpFilePath), true);
Deno.removeSync(tmpFilePath); Deno.removeSync(tmpFilePath);

View file

@ -1,11 +1,11 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { test } = Deno;
import { fail, assertEquals } from "../../testing/asserts.ts"; import { fail, assertEquals } from "../../testing/asserts.ts";
import { link, linkSync } from "./_fs_link.ts"; import { link, linkSync } from "./_fs_link.ts";
import { assert } from "https://deno.land/std@v0.50.0/testing/asserts.ts"; import { assert } from "https://deno.land/std@v0.50.0/testing/asserts.ts";
const isWindows = Deno.build.os === "windows"; const isWindows = Deno.build.os === "windows";
test({ Deno.test({
ignore: isWindows, ignore: isWindows,
name: "ASYNC: hard linking files works as expected", name: "ASYNC: hard linking files works as expected",
async fn() { async fn() {
@ -30,7 +30,7 @@ test({
}, },
}); });
test({ Deno.test({
ignore: isWindows, ignore: isWindows,
name: "ASYNC: hard linking files passes error to callback", name: "ASYNC: hard linking files passes error to callback",
async fn() { async fn() {
@ -52,7 +52,7 @@ test({
}, },
}); });
test({ Deno.test({
ignore: isWindows, ignore: isWindows,
name: "SYNC: hard linking files works as expected", name: "SYNC: hard linking files works as expected",
fn() { fn() {

View file

@ -1,14 +1,11 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { assert } from "../../testing/asserts.ts"; import { assert } from "../../testing/asserts.ts";
import { mkdir, mkdirSync } from "./_fs_mkdir.ts"; import { mkdir, mkdirSync } from "./_fs_mkdir.ts";
import { existsSync } from "./_fs_exists.ts"; import { existsSync } from "./_fs_exists.ts";
const { test } = Deno;
const tmpDir = "./tmpdir"; const tmpDir = "./tmpdir";
test({ Deno.test({
name: "[node/fs] mkdir", name: "[node/fs] mkdir",
fn: async () => { fn: async () => {
const result = await new Promise((resolve) => { const result = await new Promise((resolve) => {
@ -22,7 +19,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "[node/fs] mkdirSync", name: "[node/fs] mkdirSync",
fn: () => { fn: () => {
mkdirSync(tmpDir); mkdirSync(tmpDir);

View file

@ -1,13 +1,9 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { intoCallbackAPIWithIntercept, MaybeEmpty } from "../_utils.ts"; import { intoCallbackAPIWithIntercept, MaybeEmpty } from "../_utils.ts";
import { getEncoding, FileOptions } from "./_fs_common.ts"; import { getEncoding, FileOptions } from "./_fs_common.ts";
import { Buffer } from "../buffer.ts"; import { Buffer } from "../buffer.ts";
import { fromFileUrl } from "../path.ts"; import { fromFileUrl } from "../path.ts";
const { readFile: denoReadFile, readFileSync: denoReadFileSync } = Deno;
type ReadFileCallback = ( type ReadFileCallback = (
err: MaybeEmpty<Error>, err: MaybeEmpty<Error>,
data: MaybeEmpty<string | Buffer> data: MaybeEmpty<string | Buffer>
@ -38,7 +34,7 @@ export function readFile(
const encoding = getEncoding(optOrCallback); const encoding = getEncoding(optOrCallback);
intoCallbackAPIWithIntercept<Uint8Array, string | Buffer>( intoCallbackAPIWithIntercept<Uint8Array, string | Buffer>(
denoReadFile, Deno.readFile,
(data: Uint8Array): string | Buffer => maybeDecode(data, encoding), (data: Uint8Array): string | Buffer => maybeDecode(data, encoding),
cb, cb,
path path
@ -50,5 +46,5 @@ export function readFileSync(
opt?: FileOptions | string opt?: FileOptions | string
): string | Buffer { ): string | Buffer {
path = path instanceof URL ? fromFileUrl(path) : path; path = path instanceof URL ? fromFileUrl(path) : path;
return maybeDecode(denoReadFileSync(path), getEncoding(opt)); return maybeDecode(Deno.readFileSync(path), getEncoding(opt));
} }

View file

@ -1,4 +1,3 @@
const { test } = Deno;
import { readFile, readFileSync } from "./_fs_readFile.ts"; import { readFile, readFileSync } from "./_fs_readFile.ts";
import * as path from "../../path/mod.ts"; import * as path from "../../path/mod.ts";
import { assertEquals, assert } from "../../testing/asserts.ts"; import { assertEquals, assert } from "../../testing/asserts.ts";
@ -7,7 +6,7 @@ const testData = path.resolve(
path.join("node", "_fs", "testdata", "hello.txt") path.join("node", "_fs", "testdata", "hello.txt")
); );
test("readFileSuccess", async function () { Deno.test("readFileSuccess", async function () {
const data = await new Promise((res, rej) => { const data = await new Promise((res, rej) => {
readFile(testData, (err, data) => { readFile(testData, (err, data) => {
if (err) { if (err) {
@ -21,7 +20,7 @@ test("readFileSuccess", async function () {
assertEquals(new TextDecoder().decode(data as Uint8Array), "hello world"); 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) => { const data = await new Promise((res, rej) => {
readFile(testData, { encoding: "utf8" }, (err, data) => { readFile(testData, { encoding: "utf8" }, (err, data) => {
if (err) { if (err) {
@ -35,7 +34,7 @@ test("readFileEncodeUtf8Success", async function () {
assertEquals(data as string, "hello world"); assertEquals(data as string, "hello world");
}); });
test("readFileEncodingAsString", async function () { Deno.test("readFileEncodingAsString", async function () {
const data = await new Promise((res, rej) => { const data = await new Promise((res, rej) => {
readFile(testData, "utf8", (err, data) => { readFile(testData, "utf8", (err, data) => {
if (err) { if (err) {
@ -49,19 +48,19 @@ test("readFileEncodingAsString", async function () {
assertEquals(data as string, "hello world"); assertEquals(data as string, "hello world");
}); });
test("readFileSyncSuccess", function () { Deno.test("readFileSyncSuccess", function () {
const data = readFileSync(testData); const data = readFileSync(testData);
assert(data instanceof Uint8Array); assert(data instanceof Uint8Array);
assertEquals(new TextDecoder().decode(data as Uint8Array), "hello world"); assertEquals(new TextDecoder().decode(data as Uint8Array), "hello world");
}); });
test("readFileEncodeUtf8Success", function () { Deno.test("readFileEncodeUtf8Success", function () {
const data = readFileSync(testData, { encoding: "utf8" }); const data = readFileSync(testData, { encoding: "utf8" });
assertEquals(typeof data, "string"); assertEquals(typeof data, "string");
assertEquals(data as string, "hello world"); assertEquals(data as string, "hello world");
}); });
test("readFileEncodeAsString", function () { Deno.test("readFileEncodeAsString", function () {
const data = readFileSync(testData, "utf8"); const data = readFileSync(testData, "utf8");
assertEquals(typeof data, "string"); assertEquals(typeof data, "string");
assertEquals(data as string, "hello world"); assertEquals(data as string, "hello world");

View file

@ -6,8 +6,6 @@ import {
} from "../_utils.ts"; } from "../_utils.ts";
import { fromFileUrl } from "../path.ts"; import { fromFileUrl } from "../path.ts";
const { readLink: denoReadlink, readLinkSync: denoReadlinkSync } = Deno;
type ReadlinkCallback = ( type ReadlinkCallback = (
err: MaybeEmpty<Error>, err: MaybeEmpty<Error>,
linkString: MaybeEmpty<string | Uint8Array> linkString: MaybeEmpty<string | Uint8Array>
@ -66,7 +64,7 @@ export function readlink(
const encoding = getEncoding(optOrCallback); const encoding = getEncoding(optOrCallback);
intoCallbackAPIWithIntercept<string, Uint8Array | string>( intoCallbackAPIWithIntercept<string, Uint8Array | string>(
denoReadlink, Deno.readLink,
(data: string): string | Uint8Array => maybeEncode(data, encoding), (data: string): string | Uint8Array => maybeEncode(data, encoding),
cb, cb,
path path
@ -79,5 +77,5 @@ export function readlinkSync(
): string | Uint8Array { ): string | Uint8Array {
path = path instanceof URL ? fromFileUrl(path) : path; path = path instanceof URL ? fromFileUrl(path) : path;
return maybeEncode(denoReadlinkSync(path), getEncoding(opt)); return maybeEncode(Deno.readLinkSync(path), getEncoding(opt));
} }

View file

@ -1,4 +1,3 @@
const { test } = Deno;
import { readlink, readlinkSync } from "./_fs_readlink.ts"; import { readlink, readlinkSync } from "./_fs_readlink.ts";
import { assertEquals, assert } from "../../testing/asserts.ts"; import { assertEquals, assert } from "../../testing/asserts.ts";
import * as path from "../path.ts"; import * as path from "../path.ts";
@ -13,7 +12,7 @@ if (Deno.build.os === "windows") {
Deno.symlinkSync(oldname, newname); Deno.symlinkSync(oldname, newname);
} }
test({ Deno.test({
name: "readlinkSuccess", name: "readlinkSuccess",
async fn() { async fn() {
const data = await new Promise((res, rej) => { const data = await new Promise((res, rej) => {
@ -30,7 +29,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "readlinkEncodeBufferSuccess", name: "readlinkEncodeBufferSuccess",
async fn() { async fn() {
const data = await new Promise((res, rej) => { const data = await new Promise((res, rej) => {
@ -47,7 +46,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "readlinkSyncSuccess", name: "readlinkSyncSuccess",
fn() { fn() {
const data = readlinkSync(newname); const data = readlinkSync(newname);
@ -56,7 +55,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "readlinkEncodeBufferSuccess", name: "readlinkEncodeBufferSuccess",
fn() { fn() {
const data = readlinkSync(newname, { encoding: "buffer" }); const data = readlinkSync(newname, { encoding: "buffer" });

View file

@ -1,6 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { test } = Deno;
import { import {
assert, assert,
assertEquals, assertEquals,
@ -13,7 +11,7 @@ import * as path from "../../path/mod.ts";
const testDataDir = path.resolve(path.join("node", "_fs", "testdata")); const testDataDir = path.resolve(path.join("node", "_fs", "testdata"));
const decoder = new TextDecoder("utf-8"); 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( assertThrows(
() => { () => {
writeFile("some/path", "some data", "utf8"); 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( assertThrows(
() => { () => {
writeFile("some/path", "some data", "made-up-encoding", () => {}); writeFile("some/path", "some data", "made-up-encoding", () => {});
@ -66,7 +64,9 @@ test("Invalid encoding results in error()", function testEncodingErrors() {
); );
}); });
test("Unsupported encoding results in error()", function testUnsupportedEncoding() { Deno.test(
"Unsupported encoding results in error()",
function testUnsupportedEncoding() {
assertThrows( assertThrows(
() => { () => {
writeFile("some/path", "some data", "hex", () => {}); writeFile("some/path", "some data", "hex", () => {});
@ -107,9 +107,12 @@ test("Unsupported encoding results in error()", function testUnsupportedEncoding
Error, Error,
`Not implemented: "base64" encoding` `Not implemented: "base64" encoding`
); );
}); }
);
test("Data is written to correct rid", async function testCorrectWriteUsingRid() { Deno.test(
"Data is written to correct rid",
async function testCorrectWriteUsingRid() {
const tempFile: string = await Deno.makeTempFile(); const tempFile: string = await Deno.makeTempFile();
const file: Deno.File = await Deno.open(tempFile, { const file: Deno.File = await Deno.open(tempFile, {
create: true, create: true,
@ -128,9 +131,12 @@ test("Data is written to correct rid", async function testCorrectWriteUsingRid()
const data = await Deno.readFile(tempFile); const data = await Deno.readFile(tempFile);
await Deno.remove(tempFile); await Deno.remove(tempFile);
assertEquals(decoder.decode(data), "hello world"); assertEquals(decoder.decode(data), "hello world");
}); }
);
test("Data is written to correct file", async function testCorrectWriteUsingPath() { Deno.test(
"Data is written to correct file",
async function testCorrectWriteUsingPath() {
const res = await new Promise((resolve) => { const res = await new Promise((resolve) => {
writeFile("_fs_writeFile_test_file.txt", "hello world", resolve); writeFile("_fs_writeFile_test_file.txt", "hello world", resolve);
}); });
@ -139,9 +145,10 @@ test("Data is written to correct file", async function testCorrectWriteUsingPath
await Deno.remove("_fs_writeFile_test_file.txt"); await Deno.remove("_fs_writeFile_test_file.txt");
assertEquals(res, null); assertEquals(res, null);
assertEquals(decoder.decode(data), "hello world"); 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( const url = new URL(
Deno.build.os === "windows" Deno.build.os === "windows"
? "file:///" + ? "file:///" +
@ -162,7 +169,7 @@ test("Path can be an URL", async function testCorrectWriteUsingURL() {
assertEquals(decoder.decode(data), "hello world"); 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; if (Deno.build.os === "windows") return;
const filename = "_fs_writeFile_test_file.txt"; const filename = "_fs_writeFile_test_file.txt";
@ -177,7 +184,9 @@ test("Mode is correctly set", async function testCorrectFileMode() {
assertEquals(fileInfo.mode & 0o777, 0o777); assertEquals(fileInfo.mode & 0o777, 0o777);
}); });
test("Mode is not set when rid is passed", async function testCorrectFileModeRid() { Deno.test(
"Mode is not set when rid is passed",
async function testCorrectFileModeRid() {
if (Deno.build.os === "windows") return; if (Deno.build.os === "windows") return;
const filename: string = await Deno.makeTempFile(); const filename: string = await Deno.makeTempFile();
@ -199,9 +208,12 @@ test("Mode is not set when rid is passed", async function testCorrectFileModeRid
await Deno.remove(filename); await Deno.remove(filename);
assert(fileInfo.mode); assert(fileInfo.mode);
assertNotEquals(fileInfo.mode & 0o777, 0o777); assertNotEquals(fileInfo.mode & 0o777, 0o777);
}); }
);
test("Data is written synchronously to correct rid", function testCorrectWriteSyncUsingRid() { Deno.test(
"Data is written synchronously to correct rid",
function testCorrectWriteSyncUsingRid() {
const tempFile: string = Deno.makeTempFileSync(); const tempFile: string = Deno.makeTempFileSync();
const file: Deno.File = Deno.openSync(tempFile, { const file: Deno.File = Deno.openSync(tempFile, {
create: true, create: true,
@ -215,9 +227,12 @@ test("Data is written synchronously to correct rid", function testCorrectWriteSy
const data = Deno.readFileSync(tempFile); const data = Deno.readFileSync(tempFile);
Deno.removeSync(tempFile); Deno.removeSync(tempFile);
assertEquals(decoder.decode(data), "hello world"); assertEquals(decoder.decode(data), "hello world");
}); }
);
test("Data is written synchronously to correct file", function testCorrectWriteSyncUsingPath() { Deno.test(
"Data is written synchronously to correct file",
function testCorrectWriteSyncUsingPath() {
const file = "_fs_writeFileSync_test_file"; const file = "_fs_writeFileSync_test_file";
writeFileSync(file, "hello world"); writeFileSync(file, "hello world");
@ -225,9 +240,10 @@ test("Data is written synchronously to correct file", function testCorrectWriteS
const data = Deno.readFileSync(file); const data = Deno.readFileSync(file);
Deno.removeSync(file); Deno.removeSync(file);
assertEquals(decoder.decode(data), "hello world"); 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( const filePath = path.join(
testDataDir, testDataDir,
"_fs_writeFileSync_test_file_url.txt" "_fs_writeFileSync_test_file_url.txt"
@ -244,7 +260,9 @@ test("sync: Path can be an URL", function testCorrectWriteSyncUsingURL() {
assertEquals(decoder.decode(data), "hello world"); assertEquals(decoder.decode(data), "hello world");
}); });
test("Mode is correctly set when writing synchronously", function testCorrectFileModeSync() { Deno.test(
"Mode is correctly set when writing synchronously",
function testCorrectFileModeSync() {
if (Deno.build.os === "windows") return; if (Deno.build.os === "windows") return;
const filename = "_fs_writeFileSync_test_file.txt"; const filename = "_fs_writeFileSync_test_file.txt";
@ -254,4 +272,5 @@ test("Mode is correctly set when writing synchronously", function testCorrectFil
Deno.removeSync(filename); Deno.removeSync(filename);
assert(fileInfo && fileInfo.mode); assert(fileInfo && fileInfo.mode);
assertEquals(fileInfo.mode & 0o777, 0o777); assertEquals(fileInfo.mode & 0o777, 0o777);
}); }
);

View file

@ -1,4 +1,3 @@
const { test } = Deno;
import { readFile } from "./_fs_readFile.ts"; import { readFile } from "./_fs_readFile.ts";
import * as path from "../../../path/mod.ts"; import * as path from "../../../path/mod.ts";
import { assertEquals, assert } from "../../../testing/asserts.ts"; import { assertEquals, assert } from "../../../testing/asserts.ts";
@ -7,28 +6,28 @@ const testData = path.resolve(
path.join("node", "_fs", "testdata", "hello.txt") path.join("node", "_fs", "testdata", "hello.txt")
); );
test("readFileSuccess", async function () { Deno.test("readFileSuccess", async function () {
const data = await readFile(testData); const data = await readFile(testData);
assert(data instanceof Uint8Array); assert(data instanceof Uint8Array);
assertEquals(new TextDecoder().decode(data as Uint8Array), "hello world"); 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" }); const data = await readFile(testData, { encoding: "utf8" });
assertEquals(typeof data, "string"); assertEquals(typeof data, "string");
assertEquals(data as string, "hello world"); assertEquals(data as string, "hello world");
}); });
test("readFileEncodingAsString", async function () { Deno.test("readFileEncodingAsString", async function () {
const data = await readFile(testData, "utf8"); const data = await readFile(testData, "utf8");
assertEquals(typeof data, "string"); assertEquals(typeof data, "string");
assertEquals(data as string, "hello world"); assertEquals(data as string, "hello world");
}); });
test("readFileError", async function () { Deno.test("readFileError", async function () {
try { try {
await readFile("invalid-file", "utf8"); await readFile("invalid-file", "utf8");
} catch (e) { } catch (e) {

View file

@ -1,6 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { test } = Deno;
import { import {
assert, assert,
assertEquals, assertEquals,
@ -11,7 +9,7 @@ import { writeFile } from "./_fs_writeFile.ts";
const decoder = new TextDecoder("utf-8"); const decoder = new TextDecoder("utf-8");
test("Invalid encoding results in error()", function testEncodingErrors() { Deno.test("Invalid encoding results in error()", function testEncodingErrors() {
assertThrowsAsync( assertThrowsAsync(
async () => { async () => {
await writeFile("some/path", "some data", "made-up-encoding"); await writeFile("some/path", "some data", "made-up-encoding");
@ -30,7 +28,9 @@ test("Invalid encoding results in error()", function testEncodingErrors() {
); );
}); });
test("Unsupported encoding results in error()", function testUnsupportedEncoding() { Deno.test(
"Unsupported encoding results in error()",
function testUnsupportedEncoding() {
assertThrowsAsync( assertThrowsAsync(
async () => { async () => {
await writeFile("some/path", "some data", "hex"); await writeFile("some/path", "some data", "hex");
@ -47,9 +47,12 @@ test("Unsupported encoding results in error()", function testUnsupportedEncoding
Error, Error,
`Not implemented: "base64" encoding` `Not implemented: "base64" encoding`
); );
}); }
);
test("Data is written to correct rid", async function testCorrectWriteUsingRid() { Deno.test(
"Data is written to correct rid",
async function testCorrectWriteUsingRid() {
const tempFile: string = await Deno.makeTempFile(); const tempFile: string = await Deno.makeTempFile();
const file: Deno.File = await Deno.open(tempFile, { const file: Deno.File = await Deno.open(tempFile, {
create: true, create: true,
@ -63,9 +66,12 @@ test("Data is written to correct rid", async function testCorrectWriteUsingRid()
const data = await Deno.readFile(tempFile); const data = await Deno.readFile(tempFile);
await Deno.remove(tempFile); await Deno.remove(tempFile);
assertEquals(decoder.decode(data), "hello world"); assertEquals(decoder.decode(data), "hello world");
}); }
);
test("Data is written to correct file", async function testCorrectWriteUsingPath() { Deno.test(
"Data is written to correct file",
async function testCorrectWriteUsingPath() {
const openResourcesBeforeWrite: Deno.ResourceMap = Deno.resources(); const openResourcesBeforeWrite: Deno.ResourceMap = Deno.resources();
await writeFile("_fs_writeFile_test_file.txt", "hello world"); await writeFile("_fs_writeFile_test_file.txt", "hello world");
@ -74,9 +80,10 @@ test("Data is written to correct file", async function testCorrectWriteUsingPath
const data = await Deno.readFile("_fs_writeFile_test_file.txt"); const data = await Deno.readFile("_fs_writeFile_test_file.txt");
await Deno.remove("_fs_writeFile_test_file.txt"); await Deno.remove("_fs_writeFile_test_file.txt");
assertEquals(decoder.decode(data), "hello world"); 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; if (Deno.build.os === "windows") return;
const filename = "_fs_writeFile_test_file.txt"; const filename = "_fs_writeFile_test_file.txt";
await writeFile(filename, "hello world", { mode: 0o777 }); await writeFile(filename, "hello world", { mode: 0o777 });
@ -87,7 +94,9 @@ test("Mode is correctly set", async function testCorrectFileMode() {
assertEquals(fileInfo.mode & 0o777, 0o777); assertEquals(fileInfo.mode & 0o777, 0o777);
}); });
test("Mode is not set when rid is passed", async function testCorrectFileModeRid() { Deno.test(
"Mode is not set when rid is passed",
async function testCorrectFileModeRid() {
if (Deno.build.os === "windows") return; if (Deno.build.os === "windows") return;
const filename: string = await Deno.makeTempFile(); const filename: string = await Deno.makeTempFile();
@ -104,4 +113,5 @@ test("Mode is not set when rid is passed", async function testCorrectFileModeRid
await Deno.remove(filename); await Deno.remove(filename);
assert(fileInfo.mode); assert(fileInfo.mode);
assertNotEquals(fileInfo.mode & 0o777, 0o777); assertNotEquals(fileInfo.mode & 0o777, 0o777);
}); }
);

View file

@ -20,8 +20,6 @@
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // 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 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE. // USE OR OTHER DEALINGS IN THE SOFTWARE.
const { test } = Deno;
import { assert, assertStrictEquals } from "../../testing/asserts.ts"; import { assert, assertStrictEquals } from "../../testing/asserts.ts";
import { callbackify } from "./_util_callbackify.ts"; import { callbackify } from "./_util_callbackify.ts";
@ -76,7 +74,9 @@ class TestQueue {
} }
} }
test("callbackify passes the resolution value as the second argument to the callback", async () => { Deno.test(
"callbackify passes the resolution value as the second argument to the callback",
async () => {
const testQueue = new TestQueue(); const testQueue = new TestQueue();
for (const value of values) { for (const value of values) {
@ -127,9 +127,12 @@ test("callbackify passes the resolution value as the second argument to the call
} }
await testQueue.waitForCompletion(); await testQueue.waitForCompletion();
}); }
);
test("callbackify passes the rejection value as the first argument to the callback", async () => { Deno.test(
"callbackify passes the rejection value as the first argument to the callback",
async () => {
const testQueue = new TestQueue(); const testQueue = new TestQueue();
for (const value of values) { for (const value of values) {
@ -146,8 +149,11 @@ test("callbackify passes the rejection value as the first argument to the callba
if (err instanceof Error) { if (err instanceof Error) {
if ("reason" in err) { if ("reason" in err) {
assert(!value); assert(!value);
assertStrictEquals(
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
assertStrictEquals((err as any).code, "ERR_FALSY_VALUE_REJECTION"); (err as any).code,
"ERR_FALSY_VALUE_REJECTION"
);
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
assertStrictEquals((err as any).reason, value); assertStrictEquals((err as any).reason, value);
} else { } else {
@ -179,8 +185,11 @@ test("callbackify passes the rejection value as the first argument to the callba
if (err instanceof Error) { if (err instanceof Error) {
if ("reason" in err) { if ("reason" in err) {
assert(!value); assert(!value);
assertStrictEquals(
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
assertStrictEquals((err as any).code, "ERR_FALSY_VALUE_REJECTION"); (err as any).code,
"ERR_FALSY_VALUE_REJECTION"
);
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
assertStrictEquals((err as any).reason, value); assertStrictEquals((err as any).reason, value);
} else { } else {
@ -210,8 +219,11 @@ test("callbackify passes the rejection value as the first argument to the callba
if (err instanceof Error) { if (err instanceof Error) {
if ("reason" in err) { if ("reason" in err) {
assert(!value); assert(!value);
assertStrictEquals(
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
assertStrictEquals((err as any).code, "ERR_FALSY_VALUE_REJECTION"); (err as any).code,
"ERR_FALSY_VALUE_REJECTION"
);
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
assertStrictEquals((err as any).reason, value); assertStrictEquals((err as any).reason, value);
} else { } else {
@ -226,9 +238,10 @@ test("callbackify passes the rejection value as the first argument to the callba
} }
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(); const testQueue = new TestQueue();
for (const value of values) { for (const value of values) {
@ -276,7 +289,7 @@ test("callbackify passes arguments to the original", async () => {
await testQueue.waitForCompletion(); await testQueue.waitForCompletion();
}); });
test("callbackify preserves the `this` binding", async () => { Deno.test("callbackify preserves the `this` binding", async () => {
const testQueue = new TestQueue(); const testQueue = new TestQueue();
for (const value of values) { for (const value of values) {
@ -325,7 +338,7 @@ test("callbackify preserves the `this` binding", async () => {
await testQueue.waitForCompletion(); 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) => { ["foo", null, undefined, false, 0, {}, Symbol(), []].forEach((value) => {
try { try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
@ -344,7 +357,9 @@ test("callbackify throws with non-function inputs", () => {
}); });
}); });
test("callbackify returns a function that throws if the last argument is not a function", () => { Deno.test(
"callbackify returns a function that throws if the last argument is not a function",
() => {
// eslint-disable-next-line require-await // eslint-disable-next-line require-await
async function asyncFn(): Promise<number> { async function asyncFn(): Promise<number> {
return 42; return 42;
@ -371,4 +386,5 @@ test("callbackify returns a function that throws if the last argument is not a f
); );
} }
}); });
}); }
);

View file

@ -20,27 +20,26 @@
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // 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 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE. // USE OR OTHER DEALINGS IN THE SOFTWARE.
import { import {
assert, assert,
assertEquals, assertEquals,
assertStrictEquals, assertStrictEquals,
assertThrowsAsync, assertThrowsAsync,
} from "../../testing/asserts.ts"; } from "../../testing/asserts.ts";
import { promisify } from "./_util_promisify.ts"; import { promisify } from "./_util_promisify.ts";
import * as fs from "../fs.ts"; import * as fs from "../fs.ts";
const { test } = Deno;
const readFile = promisify(fs.readFile); const readFile = promisify(fs.readFile);
const customPromisifyArgs = Symbol.for("deno.nodejs.util.promisify.customArgs"); const customPromisifyArgs = Symbol.for("deno.nodejs.util.promisify.customArgs");
test("Errors should reject the promise", async function testPromiseRejection() { Deno.test(
"Errors should reject the promise",
async function testPromiseRejection() {
await assertThrowsAsync(() => readFile("/dontexist"), Deno.errors.NotFound); await assertThrowsAsync(() => readFile("/dontexist"), Deno.errors.NotFound);
}); }
);
test("Promisify.custom", async function testPromisifyCustom() { Deno.test("Promisify.custom", async function testPromisifyCustom() {
function fn(): void {} function fn(): void {}
function promisifedFn(): void {} function promisifedFn(): void {}
@ -56,7 +55,7 @@ test("Promisify.custom", async function testPromisifyCustom() {
await promisifiedFnB; await promisifiedFnB;
}); });
test("promiisfy.custom symbol", function testPromisifyCustomSymbol() { Deno.test("promiisfy.custom symbol", function testPromisifyCustomSymbol() {
function fn(): void {} function fn(): void {}
function promisifiedFn(): void {} function promisifiedFn(): void {}
@ -72,7 +71,7 @@ test("promiisfy.custom symbol", function testPromisifyCustomSymbol() {
assertStrictEquals(promisify(promisify(fn)), promisifiedFn); assertStrictEquals(promisify(promisify(fn)), promisifiedFn);
}); });
test("Invalid argument should throw", function testThrowInvalidArgument() { Deno.test("Invalid argument should throw", function testThrowInvalidArgument() {
function fn(): void {} function fn(): void {}
// @ts-ignore TypeScript (as of 3.7) does not support indexing namespaces by symbol // @ts-ignore TypeScript (as of 3.7) does not support indexing namespaces by symbol
fn[promisify.custom] = 42; 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 firstValue = 5;
const secondValue = 17; const secondValue = 17;
@ -99,39 +98,53 @@ test("Custom promisify args", async function testPromisifyCustomArgs() {
assertEquals(obj, { first: firstValue, second: secondValue }); assertEquals(obj, { first: firstValue, second: secondValue });
}); });
test("Multiple callback args without custom promisify args", async function testPromisifyWithoutCustomArgs() { Deno.test(
"Multiple callback args without custom promisify args",
async function testPromisifyWithoutCustomArgs() {
function fn(callback: Function): void { function fn(callback: Function): void {
callback(null, "foo", "bar"); callback(null, "foo", "bar");
} }
const value = await promisify(fn)(); const value = await promisify(fn)();
assertStrictEquals(value, "foo"); assertStrictEquals(value, "foo");
}); }
);
test("Undefined resolved value", async function testPromisifyWithUndefinedResolvedValue() { Deno.test(
"Undefined resolved value",
async function testPromisifyWithUndefinedResolvedValue() {
function fn(callback: Function): void { function fn(callback: Function): void {
callback(null); callback(null);
} }
const value = await promisify(fn)(); const value = await promisify(fn)();
assertStrictEquals(value, undefined); assertStrictEquals(value, undefined);
}); }
);
test("Undefined resolved value II", async function testPromisifyWithUndefinedResolvedValueII() { Deno.test(
"Undefined resolved value II",
async function testPromisifyWithUndefinedResolvedValueII() {
function fn(callback: Function): void { function fn(callback: Function): void {
callback(); callback();
} }
const value = await promisify(fn)(); const value = await promisify(fn)();
assertStrictEquals(value, undefined); assertStrictEquals(value, undefined);
}); }
);
test("Resolved value: number", async function testPromisifyWithNumberResolvedValue() { Deno.test(
"Resolved value: number",
async function testPromisifyWithNumberResolvedValue() {
function fn(err: Error | null, val: number, callback: Function): void { function fn(err: Error | null, val: number, callback: Function): void {
callback(err, val); callback(err, val);
} }
const value = await promisify(fn)(null, 42); const value = await promisify(fn)(null, 42);
assertStrictEquals(value, 42); assertStrictEquals(value, 42);
}); }
);
test("Rejected value", async function testPromisifyWithNumberRejectedValue() { Deno.test(
"Rejected value",
async function testPromisifyWithNumberRejectedValue() {
function fn(err: Error | null, val: null, callback: Function): void { function fn(err: Error | null, val: null, callback: Function): void {
callback(err, val); callback(err, val);
} }
@ -140,9 +153,10 @@ test("Rejected value", async function testPromisifyWithNumberRejectedValue() {
Error, Error,
"oops" "oops"
); );
}); }
);
test("Rejected value", async function testPromisifyWithAsObjectMethod() { Deno.test("Rejected value", async function testPromisifyWithAsObjectMethod() {
const o: { fn?: Function } = {}; const o: { fn?: Function } = {};
const fn = promisify(function (cb: Function): void { const fn = promisify(function (cb: Function): void {
// @ts-ignore TypeScript // @ts-ignore TypeScript
@ -155,8 +169,12 @@ test("Rejected value", async function testPromisifyWithAsObjectMethod() {
assert(val); assert(val);
}); });
test("Multiple callback", async function testPromisifyWithMultipleCallback() { Deno.test(
const err = new Error("Should not have called the callback with the error."); "Multiple callback",
async function testPromisifyWithMultipleCallback() {
const err = new Error(
"Should not have called the callback with the error."
);
const stack = err.stack; const stack = err.stack;
const fn = promisify(function (cb: Function): void { const fn = promisify(function (cb: Function): void {
@ -167,9 +185,10 @@ test("Multiple callback", async function testPromisifyWithMultipleCallback() {
await fn(); await fn();
await Promise.resolve(); await Promise.resolve();
return assertStrictEquals(stack, err.stack); return assertStrictEquals(stack, err.stack);
}); }
);
test("Promisify a promise", function testPromisifyPromise() { Deno.test("Promisify a promise", function testPromisifyPromise() {
function c(): void {} function c(): void {}
const a = promisify(function (): void {}); const a = promisify(function (): void {});
const b = promisify(a); const b = promisify(a);
@ -177,7 +196,7 @@ test("Promisify a promise", function testPromisifyPromise() {
assertStrictEquals(a, b); assertStrictEquals(a, b);
}); });
test("Test error", async function testInvalidArguments() { Deno.test("Test error", async function testInvalidArguments() {
let errToThrow; let errToThrow;
const thrower = promisify(function ( 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) => { [undefined, null, true, 0, "str", {}, [], Symbol()].forEach((input) => {
try { try {
// @ts-ignore TypeScript // @ts-ignore TypeScript

View file

@ -20,8 +20,6 @@
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // 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 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE. // USE OR OTHER DEALINGS IN THE SOFTWARE.
const { test } = Deno;
import { assertStrictEquals } from "../../testing/asserts.ts"; import { assertStrictEquals } from "../../testing/asserts.ts";
import { import {
isDate, isDate,
@ -68,19 +66,19 @@ import {
import * as testModuleNamespaceOpbject from "./_util_types.ts"; import * as testModuleNamespaceOpbject from "./_util_types.ts";
// isAnyArrayBuffer // 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 ArrayBuffer(0)), true);
assertStrictEquals(isAnyArrayBuffer(new SharedArrayBuffer(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([]), false); assertStrictEquals(isAnyArrayBuffer([]), false);
assertStrictEquals(isAnyArrayBuffer(new Error()), false); assertStrictEquals(isAnyArrayBuffer(new Error()), false);
}); });
// isArrayBufferView // 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 Int8Array(0)), true);
assertStrictEquals(isArrayBufferView(new Uint8Array(0)), true); assertStrictEquals(isArrayBufferView(new Uint8Array(0)), true);
assertStrictEquals(isArrayBufferView(new Uint8ClampedArray(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); 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([]), false); assertStrictEquals(isArrayBufferView([]), false);
assertStrictEquals(isArrayBufferView(new Error()), false); assertStrictEquals(isArrayBufferView(new Error()), false);
@ -103,18 +101,18 @@ test("Should return false for invalid ArrayBufferView types", () => {
// isArgumentsObject // isArgumentsObject
// Note: not testable in TS // 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([]), false); assertStrictEquals(isArgumentsObject([]), false);
assertStrictEquals(isArgumentsObject(new Error()), false); assertStrictEquals(isArgumentsObject(new Error()), false);
}); });
// isArrayBuffer // isArrayBuffer
test("Should return true for valid ArrayBuffer types", () => { Deno.test("Should return true for valid ArrayBuffer types", () => {
assertStrictEquals(isArrayBuffer(new ArrayBuffer(0)), true); 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(new SharedArrayBuffer(0)), false);
assertStrictEquals(isArrayBuffer({}), false); assertStrictEquals(isArrayBuffer({}), false);
assertStrictEquals(isArrayBuffer([]), false); assertStrictEquals(isArrayBuffer([]), false);
@ -122,12 +120,12 @@ test("Should return false for invalid ArrayBuffer types", () => {
}); });
// isAsyncFunction // 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> => {}; const asyncFunction = async (): Promise<void> => {};
assertStrictEquals(isAsyncFunction(asyncFunction), true); 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 => {}; const syncFunction = (): void => {};
assertStrictEquals(isAsyncFunction(syncFunction), false); assertStrictEquals(isAsyncFunction(syncFunction), false);
assertStrictEquals(isAsyncFunction({}), false); assertStrictEquals(isAsyncFunction({}), false);
@ -136,34 +134,34 @@ test("Should return false for invalid async function types", () => {
}); });
// isBigInt64Array // isBigInt64Array
test("Should return true for valid BigInt64Array types", () => { Deno.test("Should return true for valid BigInt64Array types", () => {
assertStrictEquals(isBigInt64Array(new BigInt64Array()), true); 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 BigUint64Array()), false);
assertStrictEquals(isBigInt64Array(new Float32Array()), false); assertStrictEquals(isBigInt64Array(new Float32Array()), false);
assertStrictEquals(isBigInt64Array(new Int32Array()), false); assertStrictEquals(isBigInt64Array(new Int32Array()), false);
}); });
// isBigUint64Array // isBigUint64Array
test("Should return true for valid isBigUint64Array types", () => { Deno.test("Should return true for valid isBigUint64Array types", () => {
assertStrictEquals(isBigUint64Array(new BigUint64Array()), true); 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 BigInt64Array()), false);
assertStrictEquals(isBigUint64Array(new Float32Array()), false); assertStrictEquals(isBigUint64Array(new Float32Array()), false);
assertStrictEquals(isBigUint64Array(new Int32Array()), false); assertStrictEquals(isBigUint64Array(new Int32Array()), false);
}); });
// isBooleanObject // 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(false)), true);
assertStrictEquals(isBooleanObject(new Boolean(true)), 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(false), false);
assertStrictEquals(isBooleanObject(true), false); assertStrictEquals(isBooleanObject(true), false);
assertStrictEquals(isBooleanObject(Boolean(false)), false); assertStrictEquals(isBooleanObject(Boolean(false)), false);
@ -171,35 +169,35 @@ test("Should return false for invalid isBigUint64Array types", () => {
}); });
// isBoxedPrimitive // 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(new Boolean(false)), true);
assertStrictEquals(isBoxedPrimitive(Object(Symbol("foo"))), true); assertStrictEquals(isBoxedPrimitive(Object(Symbol("foo"))), true);
assertStrictEquals(isBoxedPrimitive(Object(BigInt(5))), true); assertStrictEquals(isBoxedPrimitive(Object(BigInt(5))), true);
assertStrictEquals(isBoxedPrimitive(new String("foo")), 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(false), false);
assertStrictEquals(isBoxedPrimitive(Symbol("foo")), false); assertStrictEquals(isBoxedPrimitive(Symbol("foo")), false);
}); });
// isDateView // 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); 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); assertStrictEquals(isDataView(new Float64Array(0)), false);
}); });
// isDate // 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()), true);
assertStrictEquals(isDate(new Date(0)), true); assertStrictEquals(isDate(new Date(0)), true);
assertStrictEquals(isDate(new (eval("Date"))()), 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(Date()), false);
assertStrictEquals(isDate({}), false); assertStrictEquals(isDate({}), false);
assertStrictEquals(isDate([]), false); assertStrictEquals(isDate([]), false);
@ -208,34 +206,34 @@ test("Should return false for invalid date types", () => {
}); });
// isFloat32Array // isFloat32Array
test("Should return true for valid Float32Array types", () => { Deno.test("Should return true for valid Float32Array types", () => {
assertStrictEquals(isFloat32Array(new Float32Array(0)), true); 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 ArrayBuffer(0)), false);
assertStrictEquals(isFloat32Array(new Float64Array(0)), false); assertStrictEquals(isFloat32Array(new Float64Array(0)), false);
}); });
// isFloat64Array // isFloat64Array
test("Should return true for valid Float64Array types", () => { Deno.test("Should return true for valid Float64Array types", () => {
assertStrictEquals(isFloat64Array(new Float64Array(0)), true); 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 ArrayBuffer(0)), false);
assertStrictEquals(isFloat64Array(new Uint8Array(0)), false); assertStrictEquals(isFloat64Array(new Uint8Array(0)), false);
}); });
// isGeneratorFunction // isGeneratorFunction
test("Should return true for valid generator functions", () => { Deno.test("Should return true for valid generator functions", () => {
assertStrictEquals( assertStrictEquals(
isGeneratorFunction(function* foo() {}), isGeneratorFunction(function* foo() {}),
true true
); );
}); });
test("Should return false for invalid generator functions", () => { Deno.test("Should return false for invalid generator functions", () => {
assertStrictEquals( assertStrictEquals(
isGeneratorFunction(function foo() {}), isGeneratorFunction(function foo() {}),
false false
@ -243,12 +241,12 @@ test("Should return false for invalid generator functions", () => {
}); });
// isGeneratorObject // isGeneratorObject
test("Should return true for valid generator object types", () => { Deno.test("Should return true for valid generator object types", () => {
function* foo(): Iterator<void> {} function* foo(): Iterator<void> {}
assertStrictEquals(isGeneratorObject(foo()), true); assertStrictEquals(isGeneratorObject(foo()), true);
}); });
test("Should return false for invalid generation object types", () => { Deno.test("Should return false for invalid generation object types", () => {
assertStrictEquals( assertStrictEquals(
isGeneratorObject(function* foo() {}), isGeneratorObject(function* foo() {}),
false false
@ -256,52 +254,52 @@ test("Should return false for invalid generation object types", () => {
}); });
// isInt8Array // isInt8Array
test("Should return true for valid Int8Array types", () => { Deno.test("Should return true for valid Int8Array types", () => {
assertStrictEquals(isInt8Array(new Int8Array(0)), true); 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 ArrayBuffer(0)), false);
assertStrictEquals(isInt8Array(new Float64Array(0)), false); assertStrictEquals(isInt8Array(new Float64Array(0)), false);
}); });
// isInt16Array // isInt16Array
test("Should return true for valid Int16Array types", () => { Deno.test("Should return true for valid Int16Array types", () => {
assertStrictEquals(isInt16Array(new Int16Array(0)), true); 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 ArrayBuffer(0)), false);
assertStrictEquals(isInt16Array(new Float64Array(0)), false); assertStrictEquals(isInt16Array(new Float64Array(0)), false);
}); });
// isInt32Array // isInt32Array
test("Should return true for valid isInt32Array types", () => { Deno.test("Should return true for valid isInt32Array types", () => {
assertStrictEquals(isInt32Array(new Int32Array(0)), true); 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 ArrayBuffer(0)), false);
assertStrictEquals(isInt32Array(new Float64Array(0)), false); assertStrictEquals(isInt32Array(new Float64Array(0)), false);
}); });
// isStringObject // 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("")), true);
assertStrictEquals(isStringObject(new String("Foo")), 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(""), false);
assertStrictEquals(isStringObject("Foo"), false); assertStrictEquals(isStringObject("Foo"), false);
}); });
// isMap // isMap
test("Should return true for valid Map types", () => { Deno.test("Should return true for valid Map types", () => {
assertStrictEquals(isMap(new Map()), true); 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([]), false); assertStrictEquals(isMap([]), false);
assertStrictEquals(isMap(new Date()), false); assertStrictEquals(isMap(new Date()), false);
@ -309,7 +307,7 @@ test("Should return false for invalid Map types", () => {
}); });
// isMapIterator // isMapIterator
test("Should return true for valid Map Iterator types", () => { Deno.test("Should return true for valid Map Iterator types", () => {
const map = new Map(); const map = new Map();
assertStrictEquals(isMapIterator(map.keys()), true); assertStrictEquals(isMapIterator(map.keys()), true);
assertStrictEquals(isMapIterator(map.values()), 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); 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(new Map()), false);
assertStrictEquals(isMapIterator([]), false); assertStrictEquals(isMapIterator([]), false);
assertStrictEquals(isMapIterator(new Date()), false); assertStrictEquals(isMapIterator(new Date()), false);
@ -325,70 +323,70 @@ test("Should return false for invalid Map iterator types", () => {
}); });
// isModuleNamespaceObject // isModuleNamespaceObject
test("Should return true for valid module namespace objects", () => { Deno.test("Should return true for valid module namespace objects", () => {
assertStrictEquals(isModuleNamespaceObject(testModuleNamespaceOpbject), true); 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); assertStrictEquals(isModuleNamespaceObject(assertStrictEquals), false);
}); });
// isNativeError // 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 Error()), true);
assertStrictEquals(isNativeError(new TypeError()), true); assertStrictEquals(isNativeError(new TypeError()), true);
assertStrictEquals(isNativeError(new RangeError()), 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(null), false);
assertStrictEquals(isNativeError(NaN), false); assertStrictEquals(isNativeError(NaN), false);
}); });
// isNumberObject // isNumberObject
test("Should return true for valid number objects", () => { Deno.test("Should return true for valid number objects", () => {
assertStrictEquals(isNumberObject(new Number(0)), true); 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); assertStrictEquals(isNumberObject(0), false);
}); });
// isBigIntObject // 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); 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); assertStrictEquals(isBigIntObject(BigInt(42)), false);
}); });
// isPromise // isPromise
test("Should return true for valid Promise types", () => { Deno.test("Should return true for valid Promise types", () => {
assertStrictEquals(isPromise(Promise.resolve(42)), true); 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); assertStrictEquals(isPromise(new Object()), false);
}); });
// isRegExp // isRegExp
test("Should return true for valid RegExp", () => { Deno.test("Should return true for valid RegExp", () => {
assertStrictEquals(isRegExp(/abc/), true); assertStrictEquals(isRegExp(/abc/), true);
assertStrictEquals(isRegExp(new RegExp("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({}), false);
assertStrictEquals(isRegExp("/abc/"), false); assertStrictEquals(isRegExp("/abc/"), false);
}); });
// isSet // isSet
test("Should return true for valid Set types", () => { Deno.test("Should return true for valid Set types", () => {
assertStrictEquals(isSet(new Set()), true); 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([]), false); assertStrictEquals(isSet([]), false);
assertStrictEquals(isSet(new Map()), false); assertStrictEquals(isSet(new Map()), false);
@ -396,7 +394,7 @@ test("Should return false for invalid Set types", () => {
}); });
// isSetIterator // isSetIterator
test("Should return true for valid Set Iterator types", () => { Deno.test("Should return true for valid Set Iterator types", () => {
const set = new Set(); const set = new Set();
assertStrictEquals(isSetIterator(set.keys()), true); assertStrictEquals(isSetIterator(set.keys()), true);
assertStrictEquals(isSetIterator(set.values()), 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); 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(new Set()), false);
assertStrictEquals(isSetIterator([]), false); assertStrictEquals(isSetIterator([]), false);
assertStrictEquals(isSetIterator(new Map()), false); assertStrictEquals(isSetIterator(new Map()), false);
@ -412,100 +410,100 @@ test("Should return false for invalid Set Iterator types", () => {
}); });
// isSharedArrayBuffer // isSharedArrayBuffer
test("Should return true for valid SharedArrayBuffer types", () => { Deno.test("Should return true for valid SharedArrayBuffer types", () => {
assertStrictEquals(isSharedArrayBuffer(new SharedArrayBuffer(0)), true); 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); assertStrictEquals(isSharedArrayBuffer(new ArrayBuffer(0)), false);
}); });
// isStringObject // 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("")), true);
assertStrictEquals(isStringObject(new String("Foo")), 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(""), false);
assertStrictEquals(isStringObject("Foo"), false); assertStrictEquals(isStringObject("Foo"), false);
}); });
// isSymbolObject // isSymbolObject
test("Should return true for valid Symbol types", () => { Deno.test("Should return true for valid Symbol types", () => {
assertStrictEquals(isSymbolObject(Object(Symbol("foo"))), true); 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); assertStrictEquals(isSymbolObject(Symbol("foo")), false);
}); });
// isTypedArray // 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 Uint8Array(0)), true);
assertStrictEquals(isTypedArray(new Float64Array(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); assertStrictEquals(isTypedArray(new ArrayBuffer(0)), false);
}); });
// isUint8Array // isUint8Array
test("Should return true for valid Uint8Array types", () => { Deno.test("Should return true for valid Uint8Array types", () => {
assertStrictEquals(isUint8Array(new Uint8Array(0)), true); 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 ArrayBuffer(0)), false);
assertStrictEquals(isUint8Array(new Float64Array(0)), false); assertStrictEquals(isUint8Array(new Float64Array(0)), false);
}); });
// isUint8ClampedArray // isUint8ClampedArray
test("Should return true for valid Uint8ClampedArray types", () => { Deno.test("Should return true for valid Uint8ClampedArray types", () => {
assertStrictEquals(isUint8ClampedArray(new Uint8ClampedArray(0)), true); 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 ArrayBuffer(0)), false);
assertStrictEquals(isUint8ClampedArray(new Float64Array(0)), false); assertStrictEquals(isUint8ClampedArray(new Float64Array(0)), false);
}); });
// isUint16Array // isUint16Array
test("Should return true for valid isUint16Array types", () => { Deno.test("Should return true for valid isUint16Array types", () => {
assertStrictEquals(isUint16Array(new Uint16Array(0)), true); 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 ArrayBuffer(0)), false);
assertStrictEquals(isUint16Array(new Float64Array(0)), false); assertStrictEquals(isUint16Array(new Float64Array(0)), false);
}); });
// isUint32Array // isUint32Array
test("Should return true for valid Uint32Array types", () => { Deno.test("Should return true for valid Uint32Array types", () => {
assertStrictEquals(isUint32Array(new Uint32Array(0)), true); 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 ArrayBuffer(0)), false);
assertStrictEquals(isUint32Array(new Float64Array(0)), false); assertStrictEquals(isUint32Array(new Float64Array(0)), false);
}); });
// isWeakMap // isWeakMap
test("Should return true for valid WeakMap types", () => { Deno.test("Should return true for valid WeakMap types", () => {
assertStrictEquals(isWeakMap(new WeakMap()), true); 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 Set()), false);
assertStrictEquals(isWeakMap(new Map()), false); assertStrictEquals(isWeakMap(new Map()), false);
}); });
// isWeakSet // isWeakSet
test("Should return true for valid WeakSet types", () => { Deno.test("Should return true for valid WeakSet types", () => {
assertStrictEquals(isWeakSet(new WeakSet()), true); 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 Set()), false);
assertStrictEquals(isWeakSet(new Map()), false); assertStrictEquals(isWeakSet(new Map()), false);
}); });

View file

@ -1,4 +1,3 @@
const { test } = Deno;
import { import {
assert, assert,
assertEquals, assertEquals,
@ -11,7 +10,7 @@ const shouldNeverBeEmitted: Function = () => {
fail("Should never be called"); fail("Should never be called");
}; };
test({ Deno.test({
name: name:
'When adding a new event, "eventListener" event is fired before adding the listener', 'When adding a new event, "eventListener" event is fired before adding the listener',
fn() { fn() {
@ -32,7 +31,7 @@ test({
}, },
}); });
test({ Deno.test({
name: name:
'When removing a listenert, "removeListener" event is fired after removal', 'When removing a listenert, "removeListener" event is fired after removal',
fn() { fn() {
@ -52,7 +51,7 @@ test({
}, },
}); });
test({ Deno.test({
name: name:
"Default max listeners is 10, but can be changed by direct assignment only", "Default max listeners is 10, but can be changed by direct assignment only",
fn() { fn() {
@ -65,7 +64,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "addListener adds a listener, and listener count is correct", name: "addListener adds a listener, and listener count is correct",
fn() { fn() {
const testEmitter = new EventEmitter(); const testEmitter = new EventEmitter();
@ -76,7 +75,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Emitted events are called synchronously in the order they were added", name: "Emitted events are called synchronously in the order they were added",
fn() { fn() {
const testEmitter = new EventEmitter(); const testEmitter = new EventEmitter();
@ -103,7 +102,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Registered event names are returned as strings or Sybols", name: "Registered event names are returned as strings or Sybols",
fn() { fn() {
const testEmitter = new EventEmitter(); const testEmitter = new EventEmitter();
@ -115,7 +114,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "You can set and get max listeners", name: "You can set and get max listeners",
fn() { fn() {
const testEmitter = new EventEmitter(); const testEmitter = new EventEmitter();
@ -125,7 +124,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "You can retrieve registered functions for an event", name: "You can retrieve registered functions for an event",
fn() { fn() {
const testEmitter = new EventEmitter(); const testEmitter = new EventEmitter();
@ -140,7 +139,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Off is alias for removeListener", name: "Off is alias for removeListener",
fn() { fn() {
const testEmitter = new EventEmitter(); const testEmitter = new EventEmitter();
@ -151,7 +150,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Event registration can be chained", name: "Event registration can be chained",
fn() { fn() {
const testEmitter = new EventEmitter(); const testEmitter = new EventEmitter();
@ -162,7 +161,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Events can be registered to only fire once", name: "Events can be registered to only fire once",
fn() { fn() {
let eventsFired: string[] = []; let eventsFired: string[] = [];
@ -186,7 +185,7 @@ test({
}, },
}); });
test({ Deno.test({
name: name:
"You can inject a listener into the start of the stack, rather than at the end", "You can inject a listener into the start of the stack, rather than at the end",
fn() { fn() {
@ -206,7 +205,7 @@ test({
}, },
}); });
test({ Deno.test({
name: 'You can prepend a "once" listener', name: 'You can prepend a "once" listener',
fn() { fn() {
const eventsFired: string[] = []; const eventsFired: string[] = [];
@ -226,7 +225,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Remove all listeners, which can also be chained", name: "Remove all listeners, which can also be chained",
fn() { fn() {
const testEmitter = new EventEmitter(); const testEmitter = new EventEmitter();
@ -245,7 +244,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Provide a non-existent event to removeAllListeners will do nothing", name: "Provide a non-existent event to removeAllListeners will do nothing",
fn() { fn() {
const testEmitter = new EventEmitter(); const testEmitter = new EventEmitter();
@ -264,7 +263,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Remove individual listeners, which can also be chained", name: "Remove individual listeners, which can also be chained",
fn() { fn() {
const testEmitter = new EventEmitter(); const testEmitter = new EventEmitter();
@ -287,7 +286,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "It is OK to try to remove non-existent listener", name: "It is OK to try to remove non-existent listener",
fn() { fn() {
const testEmitter = new EventEmitter(); const testEmitter = new EventEmitter();
@ -306,7 +305,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "all listeners complete execution even if removed before execution", name: "all listeners complete execution even if removed before execution",
fn() { fn() {
const testEmitter = new EventEmitter(); const testEmitter = new EventEmitter();
@ -329,7 +328,7 @@ test({
}, },
}); });
test({ Deno.test({
name: 'Raw listener will return event listener or wrapped "once" function', name: 'Raw listener will return event listener or wrapped "once" function',
fn() { fn() {
const testEmitter = new EventEmitter(); const testEmitter = new EventEmitter();
@ -352,7 +351,7 @@ test({
}, },
}); });
test({ Deno.test({
name: name:
"Once wrapped raw listeners may be executed multiple times, until the wrapper is executed", "Once wrapped raw listeners may be executed multiple times, until the wrapper is executed",
fn() { fn() {
@ -375,7 +374,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Can add once event listener to EventEmitter via standalone function", name: "Can add once event listener to EventEmitter via standalone function",
async fn() { async fn() {
const ee = new EventEmitter(); const ee = new EventEmitter();
@ -388,7 +387,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Can add once event listener to EventTarget via standalone function", name: "Can add once event listener to EventTarget via standalone function",
async fn() { async fn() {
const et: EventTarget = new EventTarget(); const et: EventTarget = new EventTarget();
@ -402,7 +401,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Only valid integers are allowed for max listeners", name: "Only valid integers are allowed for max listeners",
fn() { fn() {
const ee = new EventEmitter(); const ee = new EventEmitter();
@ -424,7 +423,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "ErrorMonitor can spy on error events without consuming them", name: "ErrorMonitor can spy on error events without consuming them",
fn() { fn() {
const ee = new EventEmitter(); const ee = new EventEmitter();
@ -462,7 +461,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "asynchronous iteration of events are handled as expected", name: "asynchronous iteration of events are handled as expected",
async fn() { async fn() {
const ee = new EventEmitter(); const ee = new EventEmitter();
@ -490,7 +489,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "asynchronous error handling of emitted events works as expected", name: "asynchronous error handling of emitted events works as expected",
async fn() { async fn() {
const ee = new EventEmitter(); const ee = new EventEmitter();
@ -515,7 +514,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "error thrown during asynchronous processing of events is handled", name: "error thrown during asynchronous processing of events is handled",
async fn() { async fn() {
const ee = new EventEmitter(); const ee = new EventEmitter();
@ -544,7 +543,7 @@ test({
}, },
}); });
test({ Deno.test({
name: name:
"error thrown in processing loop of asynchronous event prevents processing of additional events", "error thrown in processing loop of asynchronous event prevents processing of additional events",
async fn() { async fn() {
@ -570,7 +569,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "asynchronous iterator next() works as expected", name: "asynchronous iterator next() works as expected",
async fn() { async fn() {
const ee = new EventEmitter(); const ee = new EventEmitter();
@ -610,7 +609,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "async iterable throw handles various scenarios", name: "async iterable throw handles various scenarios",
async fn() { async fn() {
const ee = new EventEmitter(); const ee = new EventEmitter();

View file

@ -1,6 +1,4 @@
/* eslint-disable @typescript-eslint/no-var-requires */ /* eslint-disable @typescript-eslint/no-var-requires */
const { test } = Deno;
import { import {
assertEquals, assertEquals,
assert, assert,
@ -10,7 +8,7 @@ import { createRequire } from "./module.ts";
const require = createRequire(import.meta.url); const require = createRequire(import.meta.url);
test("requireSuccess", function () { Deno.test("requireSuccess", function () {
// Relative to import.meta.url // Relative to import.meta.url
const result = require("./tests/cjs/cjs_a.js"); const result = require("./tests/cjs/cjs_a.js");
assert("helloA" in result); assert("helloA" in result);
@ -23,14 +21,14 @@ test("requireSuccess", function () {
assertEquals(result.leftPad("pad", 4), " pad"); assertEquals(result.leftPad("pad", 4), " pad");
}); });
test("requireCycle", function () { Deno.test("requireCycle", function () {
const resultA = require("./tests/cjs/cjs_cycle_a"); const resultA = require("./tests/cjs/cjs_cycle_a");
const resultB = require("./tests/cjs/cjs_cycle_b"); const resultB = require("./tests/cjs/cjs_cycle_b");
assert(resultA); assert(resultA);
assert(resultB); assert(resultB);
}); });
test("requireBuiltin", function () { Deno.test("requireBuiltin", function () {
const fs = require("fs"); const fs = require("fs");
assert("readFileSync" in fs); assert("readFileSync" in fs);
const { readFileSync, isNull, extname } = require("./tests/cjs/cjs_builtin"); const { readFileSync, isNull, extname } = require("./tests/cjs/cjs_builtin");
@ -42,18 +40,18 @@ test("requireBuiltin", function () {
assertEquals(extname("index.html"), ".html"); assertEquals(extname("index.html"), ".html");
}); });
test("requireIndexJS", function () { Deno.test("requireIndexJS", function () {
const { isIndex } = require("./tests/cjs"); const { isIndex } = require("./tests/cjs");
assert(isIndex); assert(isIndex);
}); });
test("requireNodeOs", function () { Deno.test("requireNodeOs", function () {
const os = require("os"); const os = require("os");
assert(os.arch); assert(os.arch);
assert(typeof os.arch() == "string"); assert(typeof os.arch() == "string");
}); });
test("requireStack", function () { Deno.test("requireStack", function () {
const { hello } = require("./tests/cjs/cjs_throw"); const { hello } = require("./tests/cjs/cjs_throw");
try { try {
hello(); hello();

View file

@ -1,50 +1,49 @@
const { test } = Deno;
import { assert, assertThrows, assertEquals } from "../testing/asserts.ts"; import { assert, assertThrows, assertEquals } from "../testing/asserts.ts";
import * as os from "./os.ts"; import * as os from "./os.ts";
test({ Deno.test({
name: "build architecture is a string", name: "build architecture is a string",
fn() { fn() {
assertEquals(typeof os.arch(), "string"); assertEquals(typeof os.arch(), "string");
}, },
}); });
test({ Deno.test({
name: "home directory is a string", name: "home directory is a string",
fn() { fn() {
assertEquals(typeof os.homedir(), "string"); assertEquals(typeof os.homedir(), "string");
}, },
}); });
test({ Deno.test({
name: "tmp directory is a string", name: "tmp directory is a string",
fn() { fn() {
assertEquals(typeof os.tmpdir(), "string"); assertEquals(typeof os.tmpdir(), "string");
}, },
}); });
test({ Deno.test({
name: "hostname is a string", name: "hostname is a string",
fn() { fn() {
assertEquals(typeof os.hostname(), "string"); assertEquals(typeof os.hostname(), "string");
}, },
}); });
test({ Deno.test({
name: "platform is a string", name: "platform is a string",
fn() { fn() {
assertEquals(typeof os.platform(), "string"); assertEquals(typeof os.platform(), "string");
}, },
}); });
test({ Deno.test({
name: "release is a string", name: "release is a string",
fn() { fn() {
assertEquals(typeof os.release(), "string"); assertEquals(typeof os.release(), "string");
}, },
}); });
test({ Deno.test({
name: "getPriority(): PID must be a 32 bit integer", name: "getPriority(): PID must be a 32 bit integer",
fn() { fn() {
assertThrows( assertThrows(
@ -64,7 +63,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "setPriority(): PID must be a 32 bit integer", name: "setPriority(): PID must be a 32 bit integer",
fn() { fn() {
assertThrows( assertThrows(
@ -84,7 +83,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "setPriority(): priority must be an integer between -20 and 19", name: "setPriority(): priority must be an integer between -20 and 19",
fn() { fn() {
assertThrows( assertThrows(
@ -118,7 +117,7 @@ test({
}, },
}); });
test({ Deno.test({
name: name:
"setPriority(): if only one argument specified, then this is the priority, NOT the pid", "setPriority(): if only one argument specified, then this is the priority, NOT the pid",
fn() { fn() {
@ -153,7 +152,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Signals are as expected", name: "Signals are as expected",
fn() { fn() {
// Test a few random signals for equality // Test a few random signals for equality
@ -163,21 +162,21 @@ test({
}, },
}); });
test({ Deno.test({
name: "EOL is as expected", name: "EOL is as expected",
fn() { fn() {
assert(os.EOL == "\r\n" || os.EOL == "\n"); assert(os.EOL == "\r\n" || os.EOL == "\n");
}, },
}); });
test({ Deno.test({
name: "Endianness is determined", name: "Endianness is determined",
fn() { fn() {
assert(["LE", "BE"].includes(os.endianness())); assert(["LE", "BE"].includes(os.endianness()));
}, },
}); });
test({ Deno.test({
name: "Load average is an array of 3 numbers", name: "Load average is an array of 3 numbers",
fn() { fn() {
const result = os.loadavg(); const result = os.loadavg();
@ -188,7 +187,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "Primitive coercion works as expected", name: "Primitive coercion works as expected",
fn() { fn() {
assertEquals(`${os.arch}`, os.arch()); assertEquals(`${os.arch}`, os.arch());
@ -199,7 +198,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "APIs not yet implemented", name: "APIs not yet implemented",
fn() { fn() {
assertThrows( assertThrows(

View file

@ -1,32 +1,22 @@
import { notImplemented } from "./_utils.ts"; 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 { function on(_event: string, _callback: Function): void {
// TODO(rsp): to be implemented // TODO(rsp): to be implemented
notImplemented(); notImplemented();
} }
export const process = { export const process = {
version, version: `v${Deno.version.deno}`,
versions, versions: {
platform, node: Deno.version.deno,
arch, ...Deno.version,
pid, },
cwd, platform: Deno.build.os === "windows" ? "win32" : Deno.build.os,
chdir, arch: Deno.build.arch,
exit, pid: Deno.pid,
cwd: Deno.cwd,
chdir: Deno.chdir,
exit: Deno.exit,
on, on,
get env(): { [index: string]: string } { get env(): { [index: string]: string } {
// using getter to avoid --allow-env unless it's used // using getter to avoid --allow-env unless it's used

View file

@ -1,11 +1,10 @@
const { test } = Deno;
import { assert, assertThrows, assertEquals } from "../testing/asserts.ts"; import { assert, assertThrows, assertEquals } from "../testing/asserts.ts";
import { process } from "./process.ts"; import { process } from "./process.ts";
// NOTE: Deno.execPath() (and thus process.argv) currently requires --allow-env // 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) // (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", name: "process.cwd and process.chdir success",
fn() { fn() {
// this should be run like other tests from directory up // this should be run like other tests from directory up
@ -17,7 +16,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "process.chdir failure", name: "process.chdir failure",
fn() { fn() {
assertThrows( assertThrows(
@ -33,7 +32,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "process.version", name: "process.version",
fn() { fn() {
assertEquals(typeof process, "object"); assertEquals(typeof process, "object");
@ -43,14 +42,14 @@ test({
}, },
}); });
test({ Deno.test({
name: "process.platform", name: "process.platform",
fn() { fn() {
assertEquals(typeof process.platform, "string"); assertEquals(typeof process.platform, "string");
}, },
}); });
test({ Deno.test({
name: "process.arch", name: "process.arch",
fn() { fn() {
assertEquals(typeof process.arch, "string"); assertEquals(typeof process.arch, "string");
@ -59,7 +58,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "process.pid", name: "process.pid",
fn() { fn() {
assertEquals(typeof process.pid, "number"); assertEquals(typeof process.pid, "number");
@ -67,7 +66,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "process.on", name: "process.on",
fn() { fn() {
assertEquals(typeof process.on, "function"); assertEquals(typeof process.on, "function");
@ -81,7 +80,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "process.argv", name: "process.argv",
fn() { fn() {
assert(Array.isArray(process.argv)); assert(Array.isArray(process.argv));
@ -93,7 +92,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "process.env", name: "process.env",
fn() { fn() {
assertEquals(typeof process.env.PATH, "string"); assertEquals(typeof process.env.PATH, "string");

View file

@ -1,8 +1,7 @@
const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { stringify, parse } from "./querystring.ts"; import { stringify, parse } from "./querystring.ts";
test({ Deno.test({
name: "stringify", name: "stringify",
fn() { fn() {
assertEquals( assertEquals(
@ -17,7 +16,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "parse", name: "parse",
fn() { fn() {
assertEquals(parse("a=hello&b=5&c=true&d=foo&d=bar"), { assertEquals(parse("a=hello&b=5&c=true&d=foo&d=bar"), {

View file

@ -1,8 +1,7 @@
const { test } = Deno;
import { assert } from "../testing/asserts.ts"; import { assert } from "../testing/asserts.ts";
import * as util from "./util.ts"; import * as util from "./util.ts";
test({ Deno.test({
name: "[util] isBoolean", name: "[util] isBoolean",
fn() { fn() {
assert(util.isBoolean(true)); assert(util.isBoolean(true));
@ -14,7 +13,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "[util] isNull", name: "[util] isNull",
fn() { fn() {
let n; let n;
@ -25,7 +24,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "[util] isNullOrUndefined", name: "[util] isNullOrUndefined",
fn() { fn() {
let n; let n;
@ -36,7 +35,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "[util] isNumber", name: "[util] isNumber",
fn() { fn() {
assert(util.isNumber(666)); assert(util.isNumber(666));
@ -46,7 +45,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "[util] isString", name: "[util] isString",
fn() { fn() {
assert(util.isString("deno")); assert(util.isString("deno"));
@ -55,7 +54,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "[util] isSymbol", name: "[util] isSymbol",
fn() { fn() {
assert(util.isSymbol(Symbol())); assert(util.isSymbol(Symbol()));
@ -64,7 +63,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "[util] isUndefined", name: "[util] isUndefined",
fn() { fn() {
let t; let t;
@ -74,7 +73,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "[util] isObject", name: "[util] isObject",
fn() { fn() {
const dio = { stand: "Za Warudo" }; const dio = { stand: "Za Warudo" };
@ -84,7 +83,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "[util] isError", name: "[util] isError",
fn() { fn() {
const java = new Error(); const java = new Error();
@ -96,7 +95,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "[util] isFunction", name: "[util] isFunction",
fn() { fn() {
const f = function (): void {}; const f = function (): void {};
@ -106,7 +105,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "[util] isRegExp", name: "[util] isRegExp",
fn() { fn() {
assert(util.isRegExp(new RegExp(/f/))); assert(util.isRegExp(new RegExp(/f/)));
@ -116,7 +115,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "[util] isArray", name: "[util] isArray",
fn() { fn() {
assert(util.isArray([])); assert(util.isArray([]));
@ -125,7 +124,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "[util] isPrimitive", name: "[util] isPrimitive",
fn() { fn() {
const stringType = "hasti"; const stringType = "hasti";
@ -149,7 +148,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "[util] TextDecoder", name: "[util] TextDecoder",
fn() { fn() {
assert(util.TextDecoder === TextDecoder); assert(util.TextDecoder === TextDecoder);
@ -158,7 +157,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "[util] TextEncoder", name: "[util] TextEncoder",
fn() { fn() {
assert(util.TextEncoder === TextEncoder); assert(util.TextEncoder === TextEncoder);
@ -167,7 +166,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "[util] isDate", name: "[util] isDate",
fn() { fn() {
// Test verifies the method is exposed. See _util/_util_types_test for details // Test verifies the method is exposed. See _util/_util_types_test for details

View file

@ -1,8 +1,6 @@
// This file is ported from globrex@0.1.2 // This file is ported from globrex@0.1.2
// MIT License // MIT License
// Copyright (c) 2018 Terkel Gjervig Nielsen // Copyright (c) 2018 Terkel Gjervig Nielsen
const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { GlobrexOptions, globrex } from "./_globrex.ts"; import { GlobrexOptions, globrex } from "./_globrex.ts";
@ -27,7 +25,7 @@ function match(
return !!match; return !!match;
} }
test({ Deno.test({
name: "globrex: standard", name: "globrex: standard",
fn(): void { fn(): void {
const res = globrex("*.js"); const res = globrex("*.js");
@ -37,7 +35,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "globrex: Standard * matching", name: "globrex: Standard * matching",
fn(): void { fn(): void {
t.equal(match("*", "foo"), true, "match everything"); t.equal(match("*", "foo"), true, "match everything");
@ -67,7 +65,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "globrex: advance * matching", name: "globrex: advance * matching",
fn(): void { fn(): void {
t.equal( t.equal(
@ -178,7 +176,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "globrex: ? match one character, no more and no less", name: "globrex: ? match one character, no more and no less",
fn(): void { fn(): void {
t.equal(match("f?o", "foo", { extended: true }), true); t.equal(match("f?o", "foo", { extended: true }), true);
@ -218,7 +216,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "globrex: [] match a character range", name: "globrex: [] match a character range",
fn(): void { fn(): void {
t.equal(match("fo[oz]", "foo", { extended: true }), true); t.equal(match("fo[oz]", "foo", { extended: true }), true);
@ -249,7 +247,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "globrex: [] extended character ranges", name: "globrex: [] extended character ranges",
fn(): void { fn(): void {
t.equal( t.equal(
@ -307,7 +305,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "globrex: {} match a choice of different substrings", name: "globrex: {} match a choice of different substrings",
fn(): void { fn(): void {
t.equal(match("foo{bar,baaz}", "foobaaz", { extended: true }), true); t.equal(match("foo{bar,baaz}", "foobaaz", { extended: true }), true);
@ -355,7 +353,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "globrex: complex extended matches", name: "globrex: complex extended matches",
fn(): void { fn(): void {
t.equal( t.equal(
@ -447,7 +445,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "globrex: standard globstar", name: "globrex: standard globstar",
fn(): void { fn(): void {
const tester = (globstar: boolean): void => { const tester = (globstar: boolean): void => {
@ -482,7 +480,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "globrex: remaining chars should match themself", name: "globrex: remaining chars should match themself",
fn(): void { fn(): void {
const tester = (globstar: boolean): void => { const tester = (globstar: boolean): void => {
@ -499,7 +497,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "globrex: globstar advance testing", name: "globrex: globstar advance testing",
fn(): void { fn(): void {
t.equal(match("/foo/*", "/foo/bar.txt", { globstar: true }), true); t.equal(match("/foo/*", "/foo/bar.txt", { globstar: true }), true);
@ -639,7 +637,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "globrex: extended extglob ?", name: "globrex: extended extglob ?",
fn(): void { fn(): void {
t.equal(match("(foo).txt", "(foo).txt", { extended: true }), true); t.equal(match("(foo).txt", "(foo).txt", { extended: true }), true);
@ -692,7 +690,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "globrex: extended extglob *", name: "globrex: extended extglob *",
fn(): void { fn(): void {
t.equal(match("*(foo).txt", "foo.txt", { extended: true }), true); t.equal(match("*(foo).txt", "foo.txt", { extended: true }), true);
@ -729,7 +727,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "globrex: extended extglob +", name: "globrex: extended extglob +",
fn(): void { fn(): void {
t.equal(match("+(foo).txt", "foo.txt", { extended: true }), true); t.equal(match("+(foo).txt", "foo.txt", { extended: true }), true);
@ -739,7 +737,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "globrex: extended extglob @", name: "globrex: extended extglob @",
fn(): void { fn(): void {
t.equal(match("@(foo).txt", "foo.txt", { extended: true }), true); t.equal(match("@(foo).txt", "foo.txt", { extended: true }), true);
@ -760,7 +758,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "globrex: extended extglob !", name: "globrex: extended extglob !",
fn(): void { fn(): void {
t.equal(match("!(boo).txt", "foo.txt", { extended: true }), true); t.equal(match("!(boo).txt", "foo.txt", { extended: true }), true);
@ -777,7 +775,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "globrex: strict", name: "globrex: strict",
fn(): void { fn(): void {
t.equal(match("foo//bar.txt", "foo/bar.txt"), true); t.equal(match("foo//bar.txt", "foo/bar.txt"), true);
@ -786,7 +784,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "globrex: stress testing", name: "globrex: stress testing",
fn(): void { fn(): void {
t.equal( t.equal(

View file

@ -1,11 +1,9 @@
// Copyright the Browserify authors. MIT License. // Copyright the Browserify authors. MIT License.
// Ported from https://github.com/browserify/path-browserify/ // Ported from https://github.com/browserify/path-browserify/
const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import * as path from "./mod.ts"; import * as path from "./mod.ts";
test("basename", function () { Deno.test("basename", function () {
assertEquals(path.basename(".js", ".js"), ""); assertEquals(path.basename(".js", ".js"), "");
assertEquals(path.basename(""), ""); assertEquals(path.basename(""), "");
assertEquals(path.basename("/dir/basename.ext"), "basename.ext"); 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("\\dir\\basename.ext"), "basename.ext");
assertEquals(path.win32.basename("\\basename.ext"), "basename.ext"); assertEquals(path.win32.basename("\\basename.ext"), "basename.ext");
assertEquals(path.win32.basename("basename.ext"), "basename.ext"); assertEquals(path.win32.basename("basename.ext"), "basename.ext");

View file

@ -1,11 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { common } from "./mod.ts"; import { common } from "./mod.ts";
test({ Deno.test({
name: "path - common - basic usage", name: "path - common - basic usage",
fn() { fn() {
const actual = common( const actual = common(
@ -20,7 +17,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "path - common - no shared", name: "path - common - no shared",
fn() { fn() {
const actual = common( const actual = common(
@ -31,7 +28,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "path - common - windows sep", name: "path - common - windows sep",
fn() { fn() {
const actual = common( const actual = common(

View file

@ -1,11 +1,9 @@
// Copyright the Browserify authors. MIT License. // Copyright the Browserify authors. MIT License.
// Ported from https://github.com/browserify/path-browserify/ // Ported from https://github.com/browserify/path-browserify/
const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import * as path from "./mod.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/b"), "/a"); assertEquals(path.posix.dirname("/a/b"), "/a");
assertEquals(path.posix.dirname("/a"), "/"); assertEquals(path.posix.dirname("/a"), "/");
@ -16,7 +14,7 @@ test("dirname", function () {
assertEquals(path.posix.dirname("foo"), "."); assertEquals(path.posix.dirname("foo"), ".");
}); });
test("dirnameWin32", function () { Deno.test("dirnameWin32", function () {
assertEquals(path.win32.dirname("c:\\"), "c:\\"); assertEquals(path.win32.dirname("c:\\"), "c:\\");
assertEquals(path.win32.dirname("c:\\foo"), "c:\\"); assertEquals(path.win32.dirname("c:\\foo"), "c:\\");
assertEquals(path.win32.dirname("c:\\foo\\"), "c:\\"); assertEquals(path.win32.dirname("c:\\foo\\"), "c:\\");

View file

@ -1,7 +1,5 @@
// Copyright the Browserify authors. MIT License. // Copyright the Browserify authors. MIT License.
// Ported from https://github.com/browserify/path-browserify/ // Ported from https://github.com/browserify/path-browserify/
const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import * as path from "./mod.ts"; import * as path from "./mod.ts";
@ -52,7 +50,7 @@ const pairs = [
["file.//", "."], ["file.//", "."],
]; ];
test("extname", function () { Deno.test("extname", function () {
pairs.forEach(function (p) { pairs.forEach(function (p) {
const input = p[0]; const input = p[0];
const expected = p[1]; const expected = p[1];
@ -70,7 +68,7 @@ test("extname", function () {
assertEquals(path.posix.extname("file.\\\\"), ".\\\\"); assertEquals(path.posix.extname("file.\\\\"), ".\\\\");
}); });
test("extnameWin32", function () { Deno.test("extnameWin32", function () {
pairs.forEach(function (p) { pairs.forEach(function (p) {
const input = p[0].replace(slashRE, "\\"); const input = p[0].replace(slashRE, "\\");
const expected = p[1]; const expected = p[1];

View file

@ -1,10 +1,9 @@
const { mkdir, test } = Deno;
import { assert, assertEquals } from "../testing/asserts.ts"; import { assert, assertEquals } from "../testing/asserts.ts";
import { testWalk, touch, walkArray } from "../fs/walk_test.ts"; import { testWalk, touch, walkArray } from "../fs/walk_test.ts";
import { globToRegExp, isGlob, joinGlobs, normalizeGlob } from "./glob.ts"; import { globToRegExp, isGlob, joinGlobs, normalizeGlob } from "./glob.ts";
import { SEP, join } from "./mod.ts"; import { SEP, join } from "./mod.ts";
test({ Deno.test({
name: "glob: glob to regex", name: "glob: glob to regex",
fn(): void { fn(): void {
assertEquals(globToRegExp("unicorn.*") instanceof RegExp, true); assertEquals(globToRegExp("unicorn.*") instanceof RegExp, true);
@ -47,8 +46,8 @@ test({
testWalk( testWalk(
async (d: string): Promise<void> => { async (d: string): Promise<void> => {
await mkdir(d + "/a"); await Deno.mkdir(d + "/a");
await mkdir(d + "/b"); await Deno.mkdir(d + "/b");
await touch(d + "/a/x.ts"); await touch(d + "/a/x.ts");
await touch(d + "/b/z.ts"); await touch(d + "/b/z.ts");
await touch(d + "/b/z.js"); await touch(d + "/b/z.js");
@ -65,8 +64,8 @@ testWalk(
testWalk( testWalk(
async (d: string): Promise<void> => { async (d: string): Promise<void> => {
await mkdir(d + "/a"); await Deno.mkdir(d + "/a");
await mkdir(d + "/a/yo"); await Deno.mkdir(d + "/a/yo");
await touch(d + "/a/yo/x.ts"); await touch(d + "/a/yo/x.ts");
}, },
async function globInWalkFolderWildcard(): Promise<void> { async function globInWalkFolderWildcard(): Promise<void> {
@ -85,10 +84,10 @@ testWalk(
testWalk( testWalk(
async (d: string): Promise<void> => { async (d: string): Promise<void> => {
await mkdir(d + "/a"); await Deno.mkdir(d + "/a");
await mkdir(d + "/a/unicorn"); await Deno.mkdir(d + "/a/unicorn");
await mkdir(d + "/a/deno"); await Deno.mkdir(d + "/a/deno");
await mkdir(d + "/a/raptor"); await Deno.mkdir(d + "/a/raptor");
await touch(d + "/a/raptor/x.ts"); await touch(d + "/a/raptor/x.ts");
await touch(d + "/a/deno/x.ts"); await touch(d + "/a/deno/x.ts");
await touch(d + "/a/unicorn/x.ts"); await touch(d + "/a/unicorn/x.ts");
@ -124,7 +123,7 @@ testWalk(
} }
); );
test({ Deno.test({
name: "isGlob: pattern to test", name: "isGlob: pattern to test",
fn(): void { fn(): void {
// should be true if valid glob pattern // 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}..`); assertEquals(normalizeGlob(`**${SEP}..`, { globstar: true }), `**${SEP}..`);
}); });
test("joinGlobsGlobstar", function (): void { Deno.test("joinGlobsGlobstar", function (): void {
assertEquals(joinGlobs(["**", ".."], { globstar: true }), `**${SEP}..`); assertEquals(joinGlobs(["**", ".."], { globstar: true }), `**${SEP}..`);
}); });

View file

@ -1,18 +1,16 @@
// Copyright the Browserify authors. MIT License. // Copyright the Browserify authors. MIT License.
// Ported from https://github.com/browserify/path-browserify/ // Ported from https://github.com/browserify/path-browserify/
const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import * as path from "./mod.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("/home/foo/.."), true); assertEquals(path.posix.isAbsolute("/home/foo/.."), true);
assertEquals(path.posix.isAbsolute("bar/"), false); assertEquals(path.posix.isAbsolute("bar/"), false);
assertEquals(path.posix.isAbsolute("./baz"), 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("//"), true); assertEquals(path.win32.isAbsolute("//"), true);
assertEquals(path.win32.isAbsolute("//server"), true); assertEquals(path.win32.isAbsolute("//server"), true);

View file

@ -1,4 +1,3 @@
const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import * as path from "./mod.ts"; import * as path from "./mod.ts";
@ -106,7 +105,7 @@ const windowsJoinTests = [
[["c:", "file"], "c:\\file"], [["c:", "file"], "c:\\file"],
]; ];
test("join", function () { Deno.test("join", function () {
joinTests.forEach(function (p) { joinTests.forEach(function (p) {
const _p = p[0] as string[]; const _p = p[0] as string[];
const actual = path.posix.join.apply(null, _p); 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) { joinTests.forEach(function (p) {
const _p = p[0] as string[]; const _p = p[0] as string[];
const actual = path.win32.join.apply(null, _p).replace(backslashRE, "/"); const actual = path.win32.join.apply(null, _p).replace(backslashRE, "/");

View file

@ -1,12 +1,10 @@
// Copyright the Browserify authors. MIT License. // Copyright the Browserify authors. MIT License.
// Ported from https://github.com/browserify/path-browserify/ // 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 { assertEquals } from "../testing/asserts.ts";
import * as path from "./mod.ts"; import * as path from "./mod.ts";
// TODO(kt3k): fix any types in this file
const winPaths = [ const winPaths = [
// [path, root] // [path, root]
["C:\\path\\dir\\index.html", "C:\\"], ["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); checkParseFormat(path.win32, winPaths);
checkSpecialCaseParseFormat(path.win32, winSpecialCaseParseTests); checkSpecialCaseParseFormat(path.win32, winSpecialCaseParseTests);
}); });
test("parse", function () { Deno.test("parse", function () {
checkParseFormat(path.posix, unixPaths); checkParseFormat(path.posix, unixPaths);
}); });
test("formatWin32", function () { Deno.test("formatWin32", function () {
checkFormat(path.win32, winSpecialCaseFormatTests); checkFormat(path.win32, winSpecialCaseFormatTests);
}); });
test("format", function () { Deno.test("format", function () {
checkFormat(path.posix, unixSpecialCaseFormatTests); checkFormat(path.posix, unixSpecialCaseFormatTests);
}); });
@ -165,7 +163,7 @@ const posixTrailingTests = [
], ],
]; ];
test("parseTrailingWin32", function () { Deno.test("parseTrailingWin32", function () {
windowsTrailingTests.forEach(function (p) { windowsTrailingTests.forEach(function (p) {
const actual = path.win32.parse(p[0] as string); const actual = path.win32.parse(p[0] as string);
const expected = p[1]; const expected = p[1];
@ -173,7 +171,7 @@ test("parseTrailingWin32", function () {
}); });
}); });
test("parseTrailing", function () { Deno.test("parseTrailing", function () {
posixTrailingTests.forEach(function (p) { posixTrailingTests.forEach(function (p) {
const actual = path.posix.parse(p[0] as string); const actual = path.posix.parse(p[0] as string);
const expected = p[1]; const expected = p[1];

View file

@ -1,7 +1,5 @@
// Copyright the Browserify authors. MIT License. // Copyright the Browserify authors. MIT License.
// Ported from https://github.com/browserify/path-browserify/ // Ported from https://github.com/browserify/path-browserify/
const { test } = Deno;
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import * as path from "./mod.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) { relativeTests.posix.forEach(function (p) {
const expected = p[2]; const expected = p[2];
const actual = path.posix.relative(p[0], p[1]); 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) { relativeTests.win32.forEach(function (p) {
const expected = p[2]; const expected = p[2];
const actual = path.win32.relative(p[0], p[1]); const actual = path.win32.relative(p[0], p[1]);

View file

@ -1,7 +1,5 @@
// Copyright the Browserify authors. MIT License. // Copyright the Browserify authors. MIT License.
// Ported from https://github.com/browserify/path-browserify/ // Ported from https://github.com/browserify/path-browserify/
const { cwd, test } = Deno;
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import * as path from "./mod.ts"; import * as path from "./mod.ts";
@ -28,13 +26,13 @@ const posixTests =
[ [
[["/var/lib", "../", "file/"], "/var/file"], [["/var/lib", "../", "file/"], "/var/file"],
[["/var/lib", "/../", "file/"], "/file"], [["/var/lib", "/../", "file/"], "/file"],
[["a/b/c/", "../../.."], cwd()], [["a/b/c/", "../../.."], Deno.cwd()],
[["."], cwd()], [["."], Deno.cwd()],
[["/some/dir", ".", "/absolute/"], "/absolute"], [["/some/dir", ".", "/absolute/"], "/absolute"],
[["/foo/tmp.3/", "../tmp.3/cycles/root.js"], "/foo/tmp.3/cycles/root.js"], [["/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) { posixTests.forEach(function (p) {
const _p = p[0] as string[]; const _p = p[0] as string[];
const actual = path.posix.resolve.apply(null, _p); 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) { windowsTests.forEach(function (p) {
const _p = p[0] as string[]; const _p = p[0] as string[];
const actual = path.win32.resolve.apply(null, _p); const actual = path.win32.resolve.apply(null, _p);

View file

@ -1,13 +1,11 @@
// Copyright the Browserify authors. MIT License. // Copyright the Browserify authors. MIT License.
// Ported from https://github.com/browserify/path-browserify/ // Ported from https://github.com/browserify/path-browserify/
const { cwd, test } = Deno;
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import * as path from "./mod.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 // join will internally ignore all the zero-length strings and it will return
// '.' if the joined string is a zero-length string. // '.' if the joined string is a zero-length string.
assertEquals(path.posix.join(""), "."); assertEquals(path.posix.join(""), ".");
@ -18,28 +16,28 @@ test("joinZeroLength", function () {
assertEquals(path.join(pwd, ""), pwd); assertEquals(path.join(pwd, ""), pwd);
}); });
test("normalizeZeroLength", function () { Deno.test("normalizeZeroLength", function () {
// normalize will return '.' if the input is a zero-length string // normalize will return '.' if the input is a zero-length string
assertEquals(path.posix.normalize(""), "."); assertEquals(path.posix.normalize(""), ".");
if (path.win32) assertEquals(path.win32.normalize(""), "."); if (path.win32) assertEquals(path.win32.normalize(""), ".");
assertEquals(path.normalize(pwd), pwd); assertEquals(path.normalize(pwd), pwd);
}); });
test("isAbsoluteZeroLength", function () { Deno.test("isAbsoluteZeroLength", function () {
// Since '' is not a valid path in any of the common environments, // Since '' is not a valid path in any of the common environments,
// return false // return false
assertEquals(path.posix.isAbsolute(""), false); assertEquals(path.posix.isAbsolute(""), false);
if (path.win32) assertEquals(path.win32.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 // resolve, internally ignores all the zero-length strings and returns the
// current working directory // current working directory
assertEquals(path.resolve(""), pwd); assertEquals(path.resolve(""), pwd);
assertEquals(path.resolve("", ""), pwd); assertEquals(path.resolve("", ""), pwd);
}); });
test("relativeZeroLength", function () { Deno.test("relativeZeroLength", function () {
// relative, internally calls resolve. So, '' is actually the current // relative, internally calls resolve. So, '' is actually the current
// directory // directory
assertEquals(path.relative("", pwd), ""); assertEquals(path.relative("", pwd), "");

View file

@ -1,11 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { grant, grantOrThrow } from "./mod.ts"; import { grant, grantOrThrow } from "./mod.ts";
import { assert, assertEquals } from "../testing/asserts.ts"; import { assert, assertEquals } from "../testing/asserts.ts";
const { test } = Deno; Deno.test({
test({
name: "grant basic", name: "grant basic",
async fn() { async fn() {
assertEquals(await grant({ name: "net" }, { name: "env" }), [ assertEquals(await grant({ name: "net" }, { name: "env" }), [
@ -15,7 +12,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "grant array", name: "grant array",
async fn() { async fn() {
assertEquals(await grant([{ name: "net" }, { name: "env" }]), [ assertEquals(await grant([{ name: "net" }, { name: "env" }]), [
@ -25,21 +22,21 @@ test({
}, },
}); });
test({ Deno.test({
name: "grant logic", name: "grant logic",
async fn() { async fn() {
assert(await grant({ name: "net" })); assert(await grant({ name: "net" }));
}, },
}); });
test({ Deno.test({
name: "grantOrThrow basic", name: "grantOrThrow basic",
async fn() { async fn() {
await grantOrThrow({ name: "net" }, { name: "env" }); await grantOrThrow({ name: "net" }, { name: "env" });
}, },
}); });
test({ Deno.test({
name: "grantOrThrow array", name: "grantOrThrow array",
async fn() { async fn() {
await grantOrThrow([{ name: "net" }, { name: "env" }]); await grantOrThrow([{ name: "net" }, { name: "env" }]);

View file

@ -1,9 +1,8 @@
const { test } = Deno;
import { assertEquals, assertThrows } from "../testing/asserts.ts"; import { assertEquals, assertThrows } from "../testing/asserts.ts";
import { delay } from "../async/delay.ts"; import { delay } from "../async/delay.ts";
import { signal, onSignal } from "./mod.ts"; import { signal, onSignal } from "./mod.ts";
test({ Deno.test({
name: "signal() throws when called with empty signals", name: "signal() throws when called with empty signals",
ignore: Deno.build.os === "windows", ignore: Deno.build.os === "windows",
fn() { fn() {
@ -18,7 +17,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "signal() iterates for multiple signals", name: "signal() iterates for multiple signals",
ignore: Deno.build.os === "windows", ignore: Deno.build.os === "windows",
fn: async (): Promise<void> => { fn: async (): Promise<void> => {
@ -59,7 +58,7 @@ test({
}, },
}); });
test({ Deno.test({
name: "onSignal() registers and disposes of event handler", name: "onSignal() registers and disposes of event handler",
ignore: Deno.build.os === "windows", ignore: Deno.build.os === "windows",
async fn() { async fn() {

Some files were not shown because too many files have changed in this diff Show more