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> {
for (let i = 1; i < args.length; i++) {
const filename = args[i];
const file = await open(filename);
await copy(file, stdout);
for (let i = 1; i < Deno.args.length; i++) {
const filename = Deno.args[i];
const file = await Deno.open(filename);
await Deno.copy(file, Deno.stdout);
}
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -3,10 +3,8 @@
import { parse } from "../../yaml.ts";
const { readFileSync, cwd } = Deno;
(() => {
const yml = readFileSync(`${cwd()}/example/sample_document.yml`);
const yml = Deno.readFileSync(`${Deno.cwd()}/example/sample_document.yml`);
const document = new TextDecoder().decode(yml);
const obj = parse(document) as object;

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

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

View file

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

View file

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

View file

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

View file

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

View file

@ -3,8 +3,6 @@ import { Sha256, HmacSha256, Message } from "./sha256.ts";
import { assertEquals } from "../testing/asserts.ts";
import { join, resolve } from "../path/mod.ts";
const { test } = Deno;
const testdataDir = resolve("hash", "testdata");
/** Handy function to convert an array/array buffer to a string of hex values. */
@ -178,7 +176,7 @@ fixtures.sha256.ArrayBuffer = {
// deno-fmt-ignore
fixtures.sha224.Uint8Array = {
'e17541396a3ecd1cd5a2b968b84e597e8eae3b0ea3127963bf48dd3b': new Uint8Array([211, 212]),
'730e109bd7a8a32b1cb9d9a09aa2325d2430587ddbc0c38bad911525': new Uint8Array([84, 104, 101, 32, 113, 117, 105, 99, 107, 32, 98, 114, 111, 119, 110, 32, 102, 111, 120, 32, 106, 117, 109, 112, 115, 32, 111, 118, 101, 114, 32, 116, 104, 101, 32, 108, 97, 122, 121, 32, 100, 111, 103])
'730e109bd7a8a32b1cb9d9a09aa2325d2430587ddbc0c38bad911525': new Uint8Array([84, 104, 101, 32, 113, 117, 105, 99, 107, 32, 98, 114, 111, 119, 110, 32, 102, 111, 120, 32, 106, 117, 109, 112, 115, 32, 111, 118, 101, 114, 32, 116, 104, 101, 32, 108, 97, 122, 121, 32, 100, 111, 103])
};
// prettier-ignore
// deno-fmt-ignore
@ -222,7 +220,7 @@ for (const method of methods) {
for (const [name, tests] of Object.entries(fixtures.sha256)) {
let i = 1;
for (const [expected, message] of Object.entries(tests)) {
test({
Deno.test({
name: `sha256.${method}() - ${name} - #${i++}`,
fn() {
const algorithm = new Sha256();
@ -242,7 +240,7 @@ for (const method of methods) {
for (const [name, tests] of Object.entries(fixtures.sha224)) {
let i = 1;
for (const [expected, message] of Object.entries(tests)) {
test({
Deno.test({
name: `sha224.${method}() - ${name} - #${i++}`,
fn() {
const algorithm = new Sha256(true);
@ -262,7 +260,7 @@ for (const method of methods) {
for (const [name, tests] of Object.entries(fixtures.sha256Hmac)) {
let i = 1;
for (const [expected, [key, message]] of Object.entries(tests)) {
test({
Deno.test({
name: `hmacSha256.${method}() - ${name} - #${i++}`,
fn() {
const algorithm = new HmacSha256(key);
@ -282,7 +280,7 @@ for (const method of methods) {
for (const [name, tests] of Object.entries(fixtures.sha224Hmac)) {
let i = 1;
for (const [expected, [key, message]] of Object.entries(tests)) {
test({
Deno.test({
name: `hmacSha224.${method}() - ${name} - #${i++}`,
fn() {
const algorithm = new HmacSha256(key, true);
@ -298,7 +296,7 @@ for (const method of methods) {
}
}
test("[hash/sha256] test Uint8Array from Reader", async () => {
Deno.test("[hash/sha256] test Uint8Array from Reader", async () => {
const data = await Deno.readFile(join(testdataDir, "hashtest"));
const hash = new Sha256().update(data).hex();

View file

@ -1,8 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
/* eslint-disable @typescript-eslint/camelcase */
const { test } = Deno;
import { assertEquals, assertThrows } from "../testing/asserts.ts";
import {
Keccak224,
@ -262,7 +259,7 @@ function s2b(data: string): Uint8Array {
return new TextEncoder().encode(data);
}
test("[hash/sha3] testSha3-224Raw", () => {
Deno.test("[hash/sha3] testSha3-224Raw", () => {
const sha3sum = (data: ArrayBuffer): ArrayBuffer => {
const sha3 = new Sha3_224();
return sha3.update(data).digest();
@ -274,7 +271,7 @@ test("[hash/sha3] testSha3-224Raw", () => {
}
});
test("[hash/sha3] testSha3-224String", () => {
Deno.test("[hash/sha3] testSha3-224String", () => {
const sha3sum = (data: string): string => {
const sha3 = new Sha3_224();
return sha3.update(data).toString();
@ -285,7 +282,7 @@ test("[hash/sha3] testSha3-224String", () => {
}
});
test("[hash/sha3] testSha3-256Raw", () => {
Deno.test("[hash/sha3] testSha3-256Raw", () => {
const sha3sum = (data: ArrayBuffer): ArrayBuffer => {
const sha3 = new Sha3_256();
return sha3.update(data).digest();
@ -297,7 +294,7 @@ test("[hash/sha3] testSha3-256Raw", () => {
}
});
test("[hash/sha3] testSha3-256String", () => {
Deno.test("[hash/sha3] testSha3-256String", () => {
const sha3sum = (data: string): string => {
const sha3 = new Sha3_256();
return sha3.update(data).toString();
@ -308,7 +305,7 @@ test("[hash/sha3] testSha3-256String", () => {
}
});
test("[hash/sha3] testSha3-384Raw", () => {
Deno.test("[hash/sha3] testSha3-384Raw", () => {
const sha3sum = (data: ArrayBuffer): ArrayBuffer => {
const sha3 = new Sha3_384();
return sha3.update(data).digest();
@ -320,7 +317,7 @@ test("[hash/sha3] testSha3-384Raw", () => {
}
});
test("[hash/sha3] testSha3-384String", () => {
Deno.test("[hash/sha3] testSha3-384String", () => {
const sha3sum = (data: string): string => {
const sha3 = new Sha3_384();
return sha3.update(data).toString();
@ -331,7 +328,7 @@ test("[hash/sha3] testSha3-384String", () => {
}
});
test("[hash/sha3] testSha3-512Raw", () => {
Deno.test("[hash/sha3] testSha3-512Raw", () => {
const sha3sum = (data: ArrayBuffer): ArrayBuffer => {
const sha3 = new Sha3_512();
return sha3.update(data).digest();
@ -343,7 +340,7 @@ test("[hash/sha3] testSha3-512Raw", () => {
}
});
test("[hash/sha3] testSha3-512String", () => {
Deno.test("[hash/sha3] testSha3-512String", () => {
const sha3sum = (data: string): string => {
const sha3 = new Sha3_512();
return sha3.update(data).toString();
@ -354,7 +351,7 @@ test("[hash/sha3] testSha3-512String", () => {
}
});
test("[hash/sha3] testKeccak-224Raw", () => {
Deno.test("[hash/sha3] testKeccak-224Raw", () => {
const keccakSum = (data: ArrayBuffer): ArrayBuffer => {
const keccak = new Keccak224();
return keccak.update(data).digest();
@ -366,7 +363,7 @@ test("[hash/sha3] testKeccak-224Raw", () => {
}
});
test("[hash/sha3] testKeccak-224String", () => {
Deno.test("[hash/sha3] testKeccak-224String", () => {
const keccakSum = (data: string): string => {
const keccak = new Keccak224();
return keccak.update(data).toString();
@ -377,7 +374,7 @@ test("[hash/sha3] testKeccak-224String", () => {
}
});
test("[hash/sha3] testKeccak-256Raw", () => {
Deno.test("[hash/sha3] testKeccak-256Raw", () => {
const keccakSum = (data: ArrayBuffer): ArrayBuffer => {
const keccak = new Keccak256();
return keccak.update(data).digest();
@ -389,7 +386,7 @@ test("[hash/sha3] testKeccak-256Raw", () => {
}
});
test("[hash/sha3] testKeccak-256String", () => {
Deno.test("[hash/sha3] testKeccak-256String", () => {
const keccakSum = (data: string): string => {
const keccak = new Keccak256();
return keccak.update(data).toString();
@ -400,7 +397,7 @@ test("[hash/sha3] testKeccak-256String", () => {
}
});
test("[hash/sha3] testKeccak-384Raw", () => {
Deno.test("[hash/sha3] testKeccak-384Raw", () => {
const keccakSum = (data: ArrayBuffer): ArrayBuffer => {
const keccak = new Keccak384();
return keccak.update(data).digest();
@ -412,7 +409,7 @@ test("[hash/sha3] testKeccak-384Raw", () => {
}
});
test("[hash/sha3] testKeccak-384String", () => {
Deno.test("[hash/sha3] testKeccak-384String", () => {
const keccakSum = (data: string): string => {
const keccak = new Keccak384();
return keccak.update(data).toString();
@ -423,7 +420,7 @@ test("[hash/sha3] testKeccak-384String", () => {
}
});
test("[hash/sha3] testKeccak-512Raw", () => {
Deno.test("[hash/sha3] testKeccak-512Raw", () => {
const keccakSum = (data: ArrayBuffer): ArrayBuffer => {
const keccak = new Keccak512();
return keccak.update(data).digest();
@ -435,7 +432,7 @@ test("[hash/sha3] testKeccak-512Raw", () => {
}
});
test("[hash/sha3] testKeccak-512String", () => {
Deno.test("[hash/sha3] testKeccak-512String", () => {
const keccakSum = (data: string): string => {
const keccak = new Keccak512();
return keccak.update(data).toString();
@ -446,7 +443,7 @@ test("[hash/sha3] testKeccak-512String", () => {
}
});
test("[hash/sha3] testSHAKE-128Raw", () => {
Deno.test("[hash/sha3] testSHAKE-128Raw", () => {
const shakeSum = (data: ArrayBuffer): ArrayBuffer => {
const shake = new Shake128(128);
return shake.update(data).digest();
@ -458,7 +455,7 @@ test("[hash/sha3] testSHAKE-128Raw", () => {
}
});
test("[hash/sha3] testSHAKE-128String", () => {
Deno.test("[hash/sha3] testSHAKE-128String", () => {
const shakeSum = (data: string): string => {
const shake = new Shake128(128);
return shake.update(data).toString();
@ -469,7 +466,7 @@ test("[hash/sha3] testSHAKE-128String", () => {
}
});
test("[hash/sha3] testSHAKE-128-224Raw", () => {
Deno.test("[hash/sha3] testSHAKE-128-224Raw", () => {
const shakeSum = (data: ArrayBuffer): ArrayBuffer => {
const shake = new Shake128(224);
return shake.update(data).digest();
@ -481,7 +478,7 @@ test("[hash/sha3] testSHAKE-128-224Raw", () => {
}
});
test("[hash/sha3] testSHAKE-128-224String", () => {
Deno.test("[hash/sha3] testSHAKE-128-224String", () => {
const shakeSum = (data: string): string => {
const shake = new Shake128(224);
return shake.update(data).toString();
@ -492,7 +489,7 @@ test("[hash/sha3] testSHAKE-128-224String", () => {
}
});
test("[hash/sha3] testSHAKE-128-2048", () => {
Deno.test("[hash/sha3] testSHAKE-128-2048", () => {
const shakeSum = (data: string): string => {
const shake = new Shake128(2048);
return shake.update(data).toString();
@ -503,7 +500,7 @@ test("[hash/sha3] testSHAKE-128-2048", () => {
}
});
test("[hash/sha3] testSHAKE-256", () => {
Deno.test("[hash/sha3] testSHAKE-256", () => {
const shakeSum = (data: string): string => {
const shake = new Shake256(256);
return shake.update(data).toString();
@ -514,7 +511,7 @@ test("[hash/sha3] testSHAKE-256", () => {
}
});
test("[hash/sha3] testSHAKE-256-128", () => {
Deno.test("[hash/sha3] testSHAKE-256-128", () => {
const shakeSum = (data: string): string => {
const shake = new Shake256(128);
return shake.update(data).toString();
@ -525,7 +522,7 @@ test("[hash/sha3] testSHAKE-256-128", () => {
}
});
test("[hash/sha3] testSHAKE-256-384", () => {
Deno.test("[hash/sha3] testSHAKE-256-384", () => {
const shakeSum = (data: string): string => {
const shake = new Shake256(384);
return shake.update(data).toString();
@ -536,7 +533,7 @@ test("[hash/sha3] testSHAKE-256-384", () => {
}
});
test("[hash/sha3] testSHAKE-256-512", () => {
Deno.test("[hash/sha3] testSHAKE-256-512", () => {
const shakeSum = (data: string): string => {
const shake = new Shake256(512);
return shake.update(data).toString();
@ -547,7 +544,7 @@ test("[hash/sha3] testSHAKE-256-512", () => {
}
});
test("[hash/sha3] testSha3-256Chain", () => {
Deno.test("[hash/sha3] testSha3-256Chain", () => {
const sha3 = new Sha3_256();
const output = sha3
.update(s2b("a"))
@ -561,7 +558,7 @@ test("[hash/sha3] testSha3-256Chain", () => {
);
});
test("[hash/sha3] testSha3UpdateFinalized", () => {
Deno.test("[hash/sha3] testSha3UpdateFinalized", () => {
assertThrows(
() => {
const sha3 = new Sha3_256();

View file

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

View file

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

View file

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

View file

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

View file

@ -4,7 +4,6 @@ import { BufReader } from "../io/bufio.ts";
import { TextProtoReader } from "../textproto/mod.ts";
import { ServerRequest } from "./server.ts";
import { serveFile } from "./file_server.ts";
const { test } = Deno;
let fileServer: Deno.Process<Deno.RunOptions & { stdout: "piped" }>;
type FileServerCfg = {
@ -68,42 +67,48 @@ async function killFileServer(): Promise<void> {
fileServer.stdout!.close();
}
test("file_server serveFile in ./", async (): Promise<void> => {
await startFileServer();
try {
const res = await fetch("http://localhost:4507/README.md");
assert(res.headers.has("access-control-allow-origin"));
assert(res.headers.has("access-control-allow-headers"));
assertEquals(res.headers.get("content-type"), "text/markdown");
const downloadedFile = await res.text();
const localFile = new TextDecoder().decode(
await Deno.readFile("README.md")
);
assertEquals(downloadedFile, localFile);
} finally {
await killFileServer();
Deno.test(
"file_server serveFile in ./",
async (): Promise<void> => {
await startFileServer();
try {
const res = await fetch("http://localhost:4507/README.md");
assert(res.headers.has("access-control-allow-origin"));
assert(res.headers.has("access-control-allow-headers"));
assertEquals(res.headers.get("content-type"), "text/markdown");
const downloadedFile = await res.text();
const localFile = new TextDecoder().decode(
await Deno.readFile("README.md")
);
assertEquals(downloadedFile, localFile);
} finally {
await killFileServer();
}
}
});
);
test("file_server serveFile in ./http", async (): Promise<void> => {
await startFileServer({ target: "./http" });
try {
const res = await fetch("http://localhost:4507/README.md");
assert(res.headers.has("access-control-allow-origin"));
assert(res.headers.has("access-control-allow-headers"));
assertEquals(res.headers.get("content-type"), "text/markdown");
const downloadedFile = await res.text();
const localFile = new TextDecoder().decode(
await Deno.readFile("./http/README.md")
);
console.log(downloadedFile, localFile);
assertEquals(downloadedFile, localFile);
} finally {
await killFileServer();
Deno.test(
"file_server serveFile in ./http",
async (): Promise<void> => {
await startFileServer({ target: "./http" });
try {
const res = await fetch("http://localhost:4507/README.md");
assert(res.headers.has("access-control-allow-origin"));
assert(res.headers.has("access-control-allow-headers"));
assertEquals(res.headers.get("content-type"), "text/markdown");
const downloadedFile = await res.text();
const localFile = new TextDecoder().decode(
await Deno.readFile("./http/README.md")
);
console.log(downloadedFile, localFile);
assertEquals(downloadedFile, localFile);
} finally {
await killFileServer();
}
}
});
);
test("serveDirectory", async function (): Promise<void> {
Deno.test("serveDirectory", async function (): Promise<void> {
await startFileServer();
try {
const res = await fetch("http://localhost:4507/");
@ -125,7 +130,7 @@ test("serveDirectory", async function (): Promise<void> {
}
});
test("serveFallback", async function (): Promise<void> {
Deno.test("serveFallback", async function (): Promise<void> {
await startFileServer();
try {
const res = await fetch("http://localhost:4507/badfile.txt");
@ -138,7 +143,7 @@ test("serveFallback", async function (): Promise<void> {
}
});
test("serveWithUnorthodoxFilename", async function (): Promise<void> {
Deno.test("serveWithUnorthodoxFilename", async function (): Promise<void> {
await startFileServer();
try {
let res = await fetch("http://localhost:4507/http/testdata/%");
@ -156,7 +161,7 @@ test("serveWithUnorthodoxFilename", async function (): Promise<void> {
}
});
test("printHelp", async function (): Promise<void> {
Deno.test("printHelp", async function (): Promise<void> {
const helpProcess = Deno.run({
cmd: [
Deno.execPath(),
@ -177,7 +182,7 @@ test("printHelp", async function (): Promise<void> {
helpProcess.stdout.close();
});
test("contentType", async () => {
Deno.test("contentType", async () => {
const request = new ServerRequest();
const response = await serveFile(request, "http/testdata/hello.html");
const contentType = response.headers!.get("content-type");
@ -185,7 +190,7 @@ test("contentType", async () => {
(response.body as Deno.File).close();
});
test("file_server running as library", async function (): Promise<void> {
Deno.test("file_server running as library", async function (): Promise<void> {
await startFileServerAsLibrary();
try {
const res = await fetch("http://localhost:8000");

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,5 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { test } = Deno;
import { assertEquals, assert } from "../testing/asserts.ts";
import { LogRecord, Logger } from "./logger.ts";
import { LogLevels, LevelName } from "./levels.ts";
@ -19,7 +18,7 @@ class TestHandler extends BaseHandler {
}
}
test("simpleLogger", function (): void {
Deno.test("simpleLogger", function (): void {
const handler = new TestHandler("DEBUG");
let logger = new Logger("DEBUG");
@ -32,7 +31,7 @@ test("simpleLogger", function (): void {
assertEquals(logger.handlers, [handler]);
});
test("customHandler", function (): void {
Deno.test("customHandler", function (): void {
const handler = new TestHandler("DEBUG");
const logger = new Logger("DEBUG", [handler]);
@ -48,7 +47,7 @@ test("customHandler", function (): void {
assertEquals(inlineData!, "foo");
});
test("logFunctions", function (): void {
Deno.test("logFunctions", function (): void {
const doLog = (level: LevelName): TestHandler => {
const handler = new TestHandler(level);
const logger = new Logger(level, [handler]);
@ -98,22 +97,29 @@ test("logFunctions", function (): void {
assertEquals(handler.messages, ["CRITICAL doo"]);
});
test("String resolver fn will not execute if msg will not be logged", function (): void {
const handler = new TestHandler("ERROR");
const logger = new Logger("ERROR", [handler]);
let called = false;
Deno.test(
"String resolver fn will not execute if msg will not be logged",
function (): void {
const handler = new TestHandler("ERROR");
const logger = new Logger("ERROR", [handler]);
let called = false;
const expensiveFunction = (): string => {
called = true;
return "expensive function result";
};
const expensiveFunction = (): string => {
called = true;
return "expensive function result";
};
const inlineData: string | undefined = logger.debug(expensiveFunction, 1, 2);
assert(!called);
assertEquals(inlineData, undefined);
});
const inlineData: string | undefined = logger.debug(
expensiveFunction,
1,
2
);
assert(!called);
assertEquals(inlineData, undefined);
}
);
test("String resolver fn resolves as expected", function (): void {
Deno.test("String resolver fn resolves as expected", function (): void {
const handler = new TestHandler("ERROR");
const logger = new Logger("ERROR", [handler]);
const expensiveFunction = (x: number): string => {
@ -126,96 +132,99 @@ test("String resolver fn resolves as expected", function (): void {
assertEquals(secondInlineData, "expensive function result 12");
});
test("All types map correctly to log strings and are returned as is", function (): void {
const handler = new TestHandler("DEBUG");
const logger = new Logger("DEBUG", [handler]);
const sym = Symbol();
const syma = Symbol("a");
const fn = (): string => {
return "abc";
};
Deno.test(
"All types map correctly to log strings and are returned as is",
function (): void {
const handler = new TestHandler("DEBUG");
const logger = new Logger("DEBUG", [handler]);
const sym = Symbol();
const syma = Symbol("a");
const fn = (): string => {
return "abc";
};
// string
const data1: string = logger.debug("abc");
assertEquals(data1, "abc");
const data2: string = logger.debug("def", 1);
assertEquals(data2, "def");
assertEquals(handler.messages[0], "DEBUG abc");
assertEquals(handler.messages[1], "DEBUG def");
// string
const data1: string = logger.debug("abc");
assertEquals(data1, "abc");
const data2: string = logger.debug("def", 1);
assertEquals(data2, "def");
assertEquals(handler.messages[0], "DEBUG abc");
assertEquals(handler.messages[1], "DEBUG def");
// null
const data3: null = logger.info(null);
assertEquals(data3, null);
const data4: null = logger.info(null, 1);
assertEquals(data4, null);
assertEquals(handler.messages[2], "INFO null");
assertEquals(handler.messages[3], "INFO null");
// null
const data3: null = logger.info(null);
assertEquals(data3, null);
const data4: null = logger.info(null, 1);
assertEquals(data4, null);
assertEquals(handler.messages[2], "INFO null");
assertEquals(handler.messages[3], "INFO null");
// number
const data5: number = logger.warning(3);
assertEquals(data5, 3);
const data6: number = logger.warning(3, 1);
assertEquals(data6, 3);
assertEquals(handler.messages[4], "WARNING 3");
assertEquals(handler.messages[5], "WARNING 3");
// number
const data5: number = logger.warning(3);
assertEquals(data5, 3);
const data6: number = logger.warning(3, 1);
assertEquals(data6, 3);
assertEquals(handler.messages[4], "WARNING 3");
assertEquals(handler.messages[5], "WARNING 3");
// bigint
const data7: bigint = logger.error(5n);
assertEquals(data7, 5n);
const data8: bigint = logger.error(5n, 1);
assertEquals(data8, 5n);
assertEquals(handler.messages[6], "ERROR 5");
assertEquals(handler.messages[7], "ERROR 5");
// bigint
const data7: bigint = logger.error(5n);
assertEquals(data7, 5n);
const data8: bigint = logger.error(5n, 1);
assertEquals(data8, 5n);
assertEquals(handler.messages[6], "ERROR 5");
assertEquals(handler.messages[7], "ERROR 5");
// boolean
const data9: boolean = logger.critical(true);
assertEquals(data9, true);
const data10: boolean = logger.critical(false, 1);
assertEquals(data10, false);
assertEquals(handler.messages[8], "CRITICAL true");
assertEquals(handler.messages[9], "CRITICAL false");
// boolean
const data9: boolean = logger.critical(true);
assertEquals(data9, true);
const data10: boolean = logger.critical(false, 1);
assertEquals(data10, false);
assertEquals(handler.messages[8], "CRITICAL true");
assertEquals(handler.messages[9], "CRITICAL false");
// undefined
const data11: undefined = logger.debug(undefined);
assertEquals(data11, undefined);
const data12: undefined = logger.debug(undefined, 1);
assertEquals(data12, undefined);
assertEquals(handler.messages[10], "DEBUG undefined");
assertEquals(handler.messages[11], "DEBUG undefined");
// undefined
const data11: undefined = logger.debug(undefined);
assertEquals(data11, undefined);
const data12: undefined = logger.debug(undefined, 1);
assertEquals(data12, undefined);
assertEquals(handler.messages[10], "DEBUG undefined");
assertEquals(handler.messages[11], "DEBUG undefined");
// symbol
const data13: symbol = logger.info(sym);
assertEquals(data13, sym);
const data14: symbol = logger.info(syma, 1);
assertEquals(data14, syma);
assertEquals(handler.messages[12], "INFO Symbol()");
assertEquals(handler.messages[13], "INFO Symbol(a)");
// symbol
const data13: symbol = logger.info(sym);
assertEquals(data13, sym);
const data14: symbol = logger.info(syma, 1);
assertEquals(data14, syma);
assertEquals(handler.messages[12], "INFO Symbol()");
assertEquals(handler.messages[13], "INFO Symbol(a)");
// function
const data15: string | undefined = logger.warning(fn);
assertEquals(data15, "abc");
const data16: string | undefined = logger.warning(fn, 1);
assertEquals(data16, "abc");
assertEquals(handler.messages[14], "WARNING abc");
assertEquals(handler.messages[15], "WARNING abc");
// function
const data15: string | undefined = logger.warning(fn);
assertEquals(data15, "abc");
const data16: string | undefined = logger.warning(fn, 1);
assertEquals(data16, "abc");
assertEquals(handler.messages[14], "WARNING abc");
assertEquals(handler.messages[15], "WARNING abc");
// object
const data17: { payload: string; other: number } = logger.error({
payload: "data",
other: 123,
});
assertEquals(data17, {
payload: "data",
other: 123,
});
const data18: { payload: string; other: number } = logger.error(
{ payload: "data", other: 123 },
1
);
assertEquals(data18, {
payload: "data",
other: 123,
});
assertEquals(handler.messages[16], 'ERROR {"payload":"data","other":123}');
assertEquals(handler.messages[17], 'ERROR {"payload":"data","other":123}');
});
// object
const data17: { payload: string; other: number } = logger.error({
payload: "data",
other: 123,
});
assertEquals(data17, {
payload: "data",
other: 123,
});
const data18: { payload: string; other: number } = logger.error(
{ payload: "data", other: 123 },
1
);
assertEquals(data18, {
payload: "data",
other: 123,
});
assertEquals(handler.messages[16], 'ERROR {"payload":"data","other":123}');
assertEquals(handler.messages[17], 'ERROR {"payload":"data","other":123}');
}
);

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,6 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
const { test } = Deno;
import {
assert,
assertEquals,
@ -13,7 +11,7 @@ import * as path from "../../path/mod.ts";
const testDataDir = path.resolve(path.join("node", "_fs", "testdata"));
const decoder = new TextDecoder("utf-8");
test("Callback must be a function error", function fn() {
Deno.test("Callback must be a function error", function fn() {
assertThrows(
() => {
writeFile("some/path", "some data", "utf8");
@ -23,7 +21,7 @@ test("Callback must be a function error", function fn() {
);
});
test("Invalid encoding results in error()", function testEncodingErrors() {
Deno.test("Invalid encoding results in error()", function testEncodingErrors() {
assertThrows(
() => {
writeFile("some/path", "some data", "made-up-encoding", () => {});
@ -66,82 +64,91 @@ test("Invalid encoding results in error()", function testEncodingErrors() {
);
});
test("Unsupported encoding results in error()", function testUnsupportedEncoding() {
assertThrows(
() => {
writeFile("some/path", "some data", "hex", () => {});
},
Error,
`Not implemented: "hex" encoding`
);
Deno.test(
"Unsupported encoding results in error()",
function testUnsupportedEncoding() {
assertThrows(
() => {
writeFile("some/path", "some data", "hex", () => {});
},
Error,
`Not implemented: "hex" encoding`
);
assertThrows(
() => {
writeFileSync("some/path", "some data", "hex");
},
Error,
`Not implemented: "hex" encoding`
);
assertThrows(
() => {
writeFileSync("some/path", "some data", "hex");
},
Error,
`Not implemented: "hex" encoding`
);
assertThrows(
() => {
writeFile(
"some/path",
"some data",
{
assertThrows(
() => {
writeFile(
"some/path",
"some data",
{
encoding: "base64",
},
() => {}
);
},
Error,
`Not implemented: "base64" encoding`
);
assertThrows(
() => {
writeFileSync("some/path", "some data", {
encoding: "base64",
},
() => {}
);
},
Error,
`Not implemented: "base64" encoding`
);
});
},
Error,
`Not implemented: "base64" encoding`
);
}
);
assertThrows(
() => {
writeFileSync("some/path", "some data", {
encoding: "base64",
});
},
Error,
`Not implemented: "base64" encoding`
);
});
test("Data is written to correct rid", async function testCorrectWriteUsingRid() {
const tempFile: string = await Deno.makeTempFile();
const file: Deno.File = await Deno.open(tempFile, {
create: true,
write: true,
read: true,
});
await new Promise((resolve, reject) => {
writeFile(file.rid, "hello world", (err) => {
if (err) return reject(err);
resolve();
Deno.test(
"Data is written to correct rid",
async function testCorrectWriteUsingRid() {
const tempFile: string = await Deno.makeTempFile();
const file: Deno.File = await Deno.open(tempFile, {
create: true,
write: true,
read: true,
});
});
Deno.close(file.rid);
const data = await Deno.readFile(tempFile);
await Deno.remove(tempFile);
assertEquals(decoder.decode(data), "hello world");
});
await new Promise((resolve, reject) => {
writeFile(file.rid, "hello world", (err) => {
if (err) return reject(err);
resolve();
});
});
Deno.close(file.rid);
test("Data is written to correct file", async function testCorrectWriteUsingPath() {
const res = await new Promise((resolve) => {
writeFile("_fs_writeFile_test_file.txt", "hello world", resolve);
});
const data = await Deno.readFile(tempFile);
await Deno.remove(tempFile);
assertEquals(decoder.decode(data), "hello world");
}
);
const data = await Deno.readFile("_fs_writeFile_test_file.txt");
await Deno.remove("_fs_writeFile_test_file.txt");
assertEquals(res, null);
assertEquals(decoder.decode(data), "hello world");
});
Deno.test(
"Data is written to correct file",
async function testCorrectWriteUsingPath() {
const res = await new Promise((resolve) => {
writeFile("_fs_writeFile_test_file.txt", "hello world", resolve);
});
test("Path can be an URL", async function testCorrectWriteUsingURL() {
const data = await Deno.readFile("_fs_writeFile_test_file.txt");
await Deno.remove("_fs_writeFile_test_file.txt");
assertEquals(res, null);
assertEquals(decoder.decode(data), "hello world");
}
);
Deno.test("Path can be an URL", async function testCorrectWriteUsingURL() {
const url = new URL(
Deno.build.os === "windows"
? "file:///" +
@ -162,7 +169,7 @@ test("Path can be an URL", async function testCorrectWriteUsingURL() {
assertEquals(decoder.decode(data), "hello world");
});
test("Mode is correctly set", async function testCorrectFileMode() {
Deno.test("Mode is correctly set", async function testCorrectFileMode() {
if (Deno.build.os === "windows") return;
const filename = "_fs_writeFile_test_file.txt";
@ -177,57 +184,66 @@ test("Mode is correctly set", async function testCorrectFileMode() {
assertEquals(fileInfo.mode & 0o777, 0o777);
});
test("Mode is not set when rid is passed", async function testCorrectFileModeRid() {
if (Deno.build.os === "windows") return;
Deno.test(
"Mode is not set when rid is passed",
async function testCorrectFileModeRid() {
if (Deno.build.os === "windows") return;
const filename: string = await Deno.makeTempFile();
const file: Deno.File = await Deno.open(filename, {
create: true,
write: true,
read: true,
});
await new Promise((resolve, reject) => {
writeFile(file.rid, "hello world", { mode: 0o777 }, (err) => {
if (err) return reject(err);
resolve();
const filename: string = await Deno.makeTempFile();
const file: Deno.File = await Deno.open(filename, {
create: true,
write: true,
read: true,
});
});
Deno.close(file.rid);
const fileInfo = await Deno.stat(filename);
await Deno.remove(filename);
assert(fileInfo.mode);
assertNotEquals(fileInfo.mode & 0o777, 0o777);
});
await new Promise((resolve, reject) => {
writeFile(file.rid, "hello world", { mode: 0o777 }, (err) => {
if (err) return reject(err);
resolve();
});
});
Deno.close(file.rid);
test("Data is written synchronously to correct rid", function testCorrectWriteSyncUsingRid() {
const tempFile: string = Deno.makeTempFileSync();
const file: Deno.File = Deno.openSync(tempFile, {
create: true,
write: true,
read: true,
});
const fileInfo = await Deno.stat(filename);
await Deno.remove(filename);
assert(fileInfo.mode);
assertNotEquals(fileInfo.mode & 0o777, 0o777);
}
);
writeFileSync(file.rid, "hello world");
Deno.close(file.rid);
Deno.test(
"Data is written synchronously to correct rid",
function testCorrectWriteSyncUsingRid() {
const tempFile: string = Deno.makeTempFileSync();
const file: Deno.File = Deno.openSync(tempFile, {
create: true,
write: true,
read: true,
});
const data = Deno.readFileSync(tempFile);
Deno.removeSync(tempFile);
assertEquals(decoder.decode(data), "hello world");
});
writeFileSync(file.rid, "hello world");
Deno.close(file.rid);
test("Data is written synchronously to correct file", function testCorrectWriteSyncUsingPath() {
const file = "_fs_writeFileSync_test_file";
const data = Deno.readFileSync(tempFile);
Deno.removeSync(tempFile);
assertEquals(decoder.decode(data), "hello world");
}
);
writeFileSync(file, "hello world");
Deno.test(
"Data is written synchronously to correct file",
function testCorrectWriteSyncUsingPath() {
const file = "_fs_writeFileSync_test_file";
const data = Deno.readFileSync(file);
Deno.removeSync(file);
assertEquals(decoder.decode(data), "hello world");
});
writeFileSync(file, "hello world");
test("sync: Path can be an URL", function testCorrectWriteSyncUsingURL() {
const data = Deno.readFileSync(file);
Deno.removeSync(file);
assertEquals(decoder.decode(data), "hello world");
}
);
Deno.test("sync: Path can be an URL", function testCorrectWriteSyncUsingURL() {
const filePath = path.join(
testDataDir,
"_fs_writeFileSync_test_file_url.txt"
@ -244,14 +260,17 @@ test("sync: Path can be an URL", function testCorrectWriteSyncUsingURL() {
assertEquals(decoder.decode(data), "hello world");
});
test("Mode is correctly set when writing synchronously", function testCorrectFileModeSync() {
if (Deno.build.os === "windows") return;
const filename = "_fs_writeFileSync_test_file.txt";
Deno.test(
"Mode is correctly set when writing synchronously",
function testCorrectFileModeSync() {
if (Deno.build.os === "windows") return;
const filename = "_fs_writeFileSync_test_file.txt";
writeFileSync(filename, "hello world", { mode: 0o777 });
writeFileSync(filename, "hello world", { mode: 0o777 });
const fileInfo = Deno.statSync(filename);
Deno.removeSync(filename);
assert(fileInfo && fileInfo.mode);
assertEquals(fileInfo.mode & 0o777, 0o777);
});
const fileInfo = Deno.statSync(filename);
Deno.removeSync(filename);
assert(fileInfo && fileInfo.mode);
assertEquals(fileInfo.mode & 0o777, 0o777);
}
);

View file

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

View file

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

View file

@ -20,8 +20,6 @@
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
const { test } = Deno;
import { assert, assertStrictEquals } from "../../testing/asserts.ts";
import { callbackify } from "./_util_callbackify.ts";
@ -76,159 +74,174 @@ class TestQueue {
}
}
test("callbackify passes the resolution value as the second argument to the callback", async () => {
const testQueue = new TestQueue();
Deno.test(
"callbackify passes the resolution value as the second argument to the callback",
async () => {
const testQueue = new TestQueue();
for (const value of values) {
// eslint-disable-next-line require-await
async function asyncFn(): Promise<typeof value> {
return value;
}
const cbAsyncFn = callbackify(asyncFn);
testQueue.enqueue((done) => {
cbAsyncFn((err: unknown, ret: unknown) => {
assertStrictEquals(err, null);
assertStrictEquals(ret, value);
done();
for (const value of values) {
// eslint-disable-next-line require-await
async function asyncFn(): Promise<typeof value> {
return value;
}
const cbAsyncFn = callbackify(asyncFn);
testQueue.enqueue((done) => {
cbAsyncFn((err: unknown, ret: unknown) => {
assertStrictEquals(err, null);
assertStrictEquals(ret, value);
done();
});
});
});
function promiseFn(): Promise<typeof value> {
return Promise.resolve(value);
}
const cbPromiseFn = callbackify(promiseFn);
testQueue.enqueue((done) => {
cbPromiseFn((err: unknown, ret: unknown) => {
assertStrictEquals(err, null);
assertStrictEquals(ret, value);
done();
function promiseFn(): Promise<typeof value> {
return Promise.resolve(value);
}
const cbPromiseFn = callbackify(promiseFn);
testQueue.enqueue((done) => {
cbPromiseFn((err: unknown, ret: unknown) => {
assertStrictEquals(err, null);
assertStrictEquals(ret, value);
done();
});
});
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function thenableFn(): PromiseLike<any> {
return {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
then(onfulfilled): PromiseLike<any> {
assert(onfulfilled);
onfulfilled(value);
return this;
},
};
}
const cbThenableFn = callbackify(thenableFn);
testQueue.enqueue((done) => {
cbThenableFn((err: unknown, ret: unknown) => {
assertStrictEquals(err, null);
assertStrictEquals(ret, value);
done();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function thenableFn(): PromiseLike<any> {
return {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
then(onfulfilled): PromiseLike<any> {
assert(onfulfilled);
onfulfilled(value);
return this;
},
};
}
const cbThenableFn = callbackify(thenableFn);
testQueue.enqueue((done) => {
cbThenableFn((err: unknown, ret: unknown) => {
assertStrictEquals(err, null);
assertStrictEquals(ret, value);
done();
});
});
});
}
await testQueue.waitForCompletion();
}
);
await testQueue.waitForCompletion();
});
Deno.test(
"callbackify passes the rejection value as the first argument to the callback",
async () => {
const testQueue = new TestQueue();
test("callbackify passes the rejection value as the first argument to the callback", async () => {
const testQueue = new TestQueue();
for (const value of values) {
// eslint-disable-next-line require-await
async function asyncFn(): Promise<never> {
return Promise.reject(value);
}
const cbAsyncFn = callbackify(asyncFn);
assertStrictEquals(cbAsyncFn.length, 1);
assertStrictEquals(cbAsyncFn.name, "asyncFnCallbackified");
testQueue.enqueue((done) => {
cbAsyncFn((err: unknown, ret: unknown) => {
assertStrictEquals(ret, undefined);
if (err instanceof Error) {
if ("reason" in err) {
assert(!value);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
assertStrictEquals((err as any).code, "ERR_FALSY_VALUE_REJECTION");
// eslint-disable-next-line @typescript-eslint/no-explicit-any
assertStrictEquals((err as any).reason, value);
for (const value of values) {
// eslint-disable-next-line require-await
async function asyncFn(): Promise<never> {
return Promise.reject(value);
}
const cbAsyncFn = callbackify(asyncFn);
assertStrictEquals(cbAsyncFn.length, 1);
assertStrictEquals(cbAsyncFn.name, "asyncFnCallbackified");
testQueue.enqueue((done) => {
cbAsyncFn((err: unknown, ret: unknown) => {
assertStrictEquals(ret, undefined);
if (err instanceof Error) {
if ("reason" in err) {
assert(!value);
assertStrictEquals(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(err as any).code,
"ERR_FALSY_VALUE_REJECTION"
);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
assertStrictEquals((err as any).reason, value);
} else {
assertStrictEquals(String(value).endsWith(err.message), true);
}
} else {
assertStrictEquals(String(value).endsWith(err.message), true);
assertStrictEquals(err, value);
}
} else {
assertStrictEquals(err, value);
}
done();
done();
});
});
});
function promiseFn(): Promise<never> {
return Promise.reject(value);
}
const obj = {};
Object.defineProperty(promiseFn, "name", {
value: obj,
writable: false,
enumerable: false,
configurable: true,
});
function promiseFn(): Promise<never> {
return Promise.reject(value);
}
const obj = {};
Object.defineProperty(promiseFn, "name", {
value: obj,
writable: false,
enumerable: false,
configurable: true,
});
const cbPromiseFn = callbackify(promiseFn);
assertStrictEquals(promiseFn.name, obj);
testQueue.enqueue((done) => {
cbPromiseFn((err: unknown, ret: unknown) => {
assertStrictEquals(ret, undefined);
if (err instanceof Error) {
if ("reason" in err) {
assert(!value);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
assertStrictEquals((err as any).code, "ERR_FALSY_VALUE_REJECTION");
// eslint-disable-next-line @typescript-eslint/no-explicit-any
assertStrictEquals((err as any).reason, value);
const cbPromiseFn = callbackify(promiseFn);
assertStrictEquals(promiseFn.name, obj);
testQueue.enqueue((done) => {
cbPromiseFn((err: unknown, ret: unknown) => {
assertStrictEquals(ret, undefined);
if (err instanceof Error) {
if ("reason" in err) {
assert(!value);
assertStrictEquals(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(err as any).code,
"ERR_FALSY_VALUE_REJECTION"
);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
assertStrictEquals((err as any).reason, value);
} else {
assertStrictEquals(String(value).endsWith(err.message), true);
}
} else {
assertStrictEquals(String(value).endsWith(err.message), true);
assertStrictEquals(err, value);
}
} else {
assertStrictEquals(err, value);
}
done();
done();
});
});
});
function thenableFn(): PromiseLike<never> {
return {
then(onfulfilled, onrejected): PromiseLike<never> {
assert(onrejected);
onrejected(value);
return this;
},
};
function thenableFn(): PromiseLike<never> {
return {
then(onfulfilled, onrejected): PromiseLike<never> {
assert(onrejected);
onrejected(value);
return this;
},
};
}
const cbThenableFn = callbackify(thenableFn);
testQueue.enqueue((done) => {
cbThenableFn((err: unknown, ret: unknown) => {
assertStrictEquals(ret, undefined);
if (err instanceof Error) {
if ("reason" in err) {
assert(!value);
assertStrictEquals(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(err as any).code,
"ERR_FALSY_VALUE_REJECTION"
);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
assertStrictEquals((err as any).reason, value);
} else {
assertStrictEquals(String(value).endsWith(err.message), true);
}
} else {
assertStrictEquals(err, value);
}
done();
});
});
}
const cbThenableFn = callbackify(thenableFn);
testQueue.enqueue((done) => {
cbThenableFn((err: unknown, ret: unknown) => {
assertStrictEquals(ret, undefined);
if (err instanceof Error) {
if ("reason" in err) {
assert(!value);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
assertStrictEquals((err as any).code, "ERR_FALSY_VALUE_REJECTION");
// eslint-disable-next-line @typescript-eslint/no-explicit-any
assertStrictEquals((err as any).reason, value);
} else {
assertStrictEquals(String(value).endsWith(err.message), true);
}
} else {
assertStrictEquals(err, value);
}
done();
});
});
await testQueue.waitForCompletion();
}
);
await testQueue.waitForCompletion();
});
test("callbackify passes arguments to the original", async () => {
Deno.test("callbackify passes arguments to the original", async () => {
const testQueue = new TestQueue();
for (const value of values) {
@ -276,7 +289,7 @@ test("callbackify passes arguments to the original", async () => {
await testQueue.waitForCompletion();
});
test("callbackify preserves the `this` binding", async () => {
Deno.test("callbackify preserves the `this` binding", async () => {
const testQueue = new TestQueue();
for (const value of values) {
@ -325,7 +338,7 @@ test("callbackify preserves the `this` binding", async () => {
await testQueue.waitForCompletion();
});
test("callbackify throws with non-function inputs", () => {
Deno.test("callbackify throws with non-function inputs", () => {
["foo", null, undefined, false, 0, {}, Symbol(), []].forEach((value) => {
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@ -344,31 +357,34 @@ test("callbackify throws with non-function inputs", () => {
});
});
test("callbackify returns a function that throws if the last argument is not a function", () => {
// eslint-disable-next-line require-await
async function asyncFn(): Promise<number> {
return 42;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const cb = callbackify(asyncFn) as any;
const args: unknown[] = [];
["foo", null, undefined, false, 0, {}, Symbol(), []].forEach((value) => {
args.push(value);
try {
cb(...args);
throw Error("We should never reach this error");
} catch (err) {
assert(err instanceof TypeError);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
assertStrictEquals((err as any).code, "ERR_INVALID_ARG_TYPE");
assertStrictEquals(err.name, "TypeError");
assertStrictEquals(
err.message,
"The last argument must be of type function."
);
Deno.test(
"callbackify returns a function that throws if the last argument is not a function",
() => {
// eslint-disable-next-line require-await
async function asyncFn(): Promise<number> {
return 42;
}
});
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const cb = callbackify(asyncFn) as any;
const args: unknown[] = [];
["foo", null, undefined, false, 0, {}, Symbol(), []].forEach((value) => {
args.push(value);
try {
cb(...args);
throw Error("We should never reach this error");
} catch (err) {
assert(err instanceof TypeError);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
assertStrictEquals((err as any).code, "ERR_INVALID_ARG_TYPE");
assertStrictEquals(err.name, "TypeError");
assertStrictEquals(
err.message,
"The last argument must be of type function."
);
}
});
}
);

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

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