Make warnings fail
Original: 4543b563a9
This commit is contained in:
Vincent LE GOFF 2019-04-24 13:41:23 +02:00 committed by Ryan Dahl
parent e1f7a60bb3
commit dcd01dd025
88 changed files with 948 additions and 806 deletions

1
.gitignore vendored
View file

@ -4,3 +4,4 @@ deno.d.ts
node_modules node_modules
package.json package.json
package-lock.json package-lock.json
.vscode

View file

@ -12,7 +12,7 @@ jobs:
- script: npm install eslint typescript@$(TS_VERSION) @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-config-prettier - script: npm install eslint typescript@$(TS_VERSION) @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-config-prettier
- script: curl -L https://deno.land/x/install/install.sh | sh -s $(DENO_VERSION) - script: curl -L https://deno.land/x/install/install.sh | sh -s $(DENO_VERSION)
- script: echo '##vso[task.prependpath]$(HOME)/.deno/bin/' - script: echo '##vso[task.prependpath]$(HOME)/.deno/bin/'
- script: npx eslint **/*.ts - script: npx eslint **/*.ts --max-warnings=0
- script: deno --allow-run --allow-write --allow-read format.ts --check - script: deno --allow-run --allow-write --allow-read format.ts --check
- script: deno --allow-run --allow-net --allow-write --allow-read test.ts - script: deno --allow-run --allow-net --allow-write --allow-read test.ts
@ -23,7 +23,7 @@ jobs:
- script: npm -g install eslint typescript@$(TS_VERSION) @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-config-prettier - script: npm -g install eslint typescript@$(TS_VERSION) @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-config-prettier
- script: curl -L https://deno.land/x/install/install.sh | sh -s $(DENO_VERSION) - script: curl -L https://deno.land/x/install/install.sh | sh -s $(DENO_VERSION)
- script: echo '##vso[task.prependpath]$(HOME)/.deno/bin/' - script: echo '##vso[task.prependpath]$(HOME)/.deno/bin/'
- script: eslint **/*.ts - script: eslint **/*.ts --max-warnings=0
- script: deno --allow-run --allow-write --allow-read format.ts --check - script: deno --allow-run --allow-write --allow-read format.ts --check
- script: deno --allow-run --allow-net --allow-write --allow-read test.ts - script: deno --allow-run --allow-net --allow-write --allow-read test.ts
@ -34,6 +34,6 @@ jobs:
- bash: npm install eslint typescript@$(TS_VERSION) @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-config-prettier - bash: npm install eslint typescript@$(TS_VERSION) @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-config-prettier
- powershell: iwr https://deno.land/x/install/install.ps1 -out install.ps1; .\install.ps1 $(DENO_VERSION) - powershell: iwr https://deno.land/x/install/install.ps1 -out install.ps1; .\install.ps1 $(DENO_VERSION)
- bash: echo "##vso[task.prependpath]C:\Users\VssAdministrator\.deno\\bin" - bash: echo "##vso[task.prependpath]C:\Users\VssAdministrator\.deno\\bin"
- bash: npx eslint **/*.ts - bash: npx eslint **/*.ts --max-warnings=0
- bash: deno.exe --allow-run --allow-write --allow-read format.ts --check - bash: deno.exe --allow-run --allow-write --allow-read format.ts --check
- bash: deno.exe --allow-run --allow-net --allow-write --allow-read test.ts - bash: deno.exe --allow-run --allow-net --allow-write --allow-read test.ts

View file

@ -7,7 +7,7 @@ import {
import { test } from "../testing/mod.ts"; import { test } from "../testing/mod.ts";
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
test(function bytesBytesFindIndex() { test(function bytesBytesFindIndex(): void {
const i = bytesFindIndex( const i = bytesFindIndex(
new Uint8Array([1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 3]), new Uint8Array([1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 3]),
new Uint8Array([0, 1, 2]) new Uint8Array([0, 1, 2])
@ -15,7 +15,7 @@ test(function bytesBytesFindIndex() {
assertEquals(i, 2); assertEquals(i, 2);
}); });
test(function bytesBytesFindLastIndex1() { test(function bytesBytesFindLastIndex1(): void {
const i = bytesFindLastIndex( const i = bytesFindLastIndex(
new Uint8Array([0, 1, 2, 0, 1, 2, 0, 1, 3]), new Uint8Array([0, 1, 2, 0, 1, 2, 0, 1, 3]),
new Uint8Array([0, 1, 2]) new Uint8Array([0, 1, 2])
@ -23,7 +23,7 @@ test(function bytesBytesFindLastIndex1() {
assertEquals(i, 3); assertEquals(i, 3);
}); });
test(function bytesBytesBytesEqual() { test(function bytesBytesBytesEqual(): void {
const v = bytesEqual( const v = bytesEqual(
new Uint8Array([0, 1, 2, 3]), new Uint8Array([0, 1, 2, 3]),
new Uint8Array([0, 1, 2, 3]) new Uint8Array([0, 1, 2, 3])
@ -31,7 +31,7 @@ test(function bytesBytesBytesEqual() {
assertEquals(v, true); assertEquals(v, true);
}); });
test(function bytesBytesHasPrefix() { test(function bytesBytesHasPrefix(): void {
const v = bytesHasPrefix(new Uint8Array([0, 1, 2]), new Uint8Array([0, 1])); const v = bytesHasPrefix(new Uint8Array([0, 1, 2]), new Uint8Array([0, 1]));
assertEquals(v, true); assertEquals(v, true);
}); });

View file

@ -4,19 +4,19 @@ import { assertEquals } from "../testing/asserts.ts";
import { red, bgBlue, setEnabled, getEnabled } from "./mod.ts"; import { red, bgBlue, setEnabled, getEnabled } from "./mod.ts";
import "../examples/colors.ts"; import "../examples/colors.ts";
test(function singleColor() { test(function singleColor(): void {
assertEquals(red("Hello world"), "Hello world"); assertEquals(red("Hello world"), "Hello world");
}); });
test(function doubleColor() { test(function doubleColor(): void {
assertEquals(bgBlue(red("Hello world")), "Hello world"); assertEquals(bgBlue(red("Hello world")), "Hello world");
}); });
test(function replacesCloseCharacters() { test(function replacesCloseCharacters(): void {
assertEquals(red("Hello"), "Hello"); assertEquals(red("Hello"), "Hello");
}); });
test(function enablingColors() { test(function enablingColors(): void {
assertEquals(getEnabled(), true); assertEquals(getEnabled(), true);
setEnabled(false); setEnabled(false);
assertEquals(bgBlue(red("Hello world")), "Hello world"); assertEquals(bgBlue(red("Hello world")), "Hello world");

View file

@ -3,7 +3,7 @@ import { test } from "../testing/mod.ts";
import { assert, assertEquals } from "../testing/asserts.ts"; import { assert, assertEquals } from "../testing/asserts.ts";
import * as datetime from "./mod.ts"; import * as datetime from "./mod.ts";
test(function parseDateTime() { test(function parseDateTime(): void {
assertEquals( assertEquals(
datetime.parseDateTime("01-03-2019 16:30", "mm-dd-yyyy hh:mm"), datetime.parseDateTime("01-03-2019 16:30", "mm-dd-yyyy hh:mm"),
new Date(2019, 0, 3, 16, 30) new Date(2019, 0, 3, 16, 30)
@ -30,7 +30,7 @@ test(function parseDateTime() {
); );
}); });
test(function invalidParseDateTimeFormatThrows() { test(function invalidParseDateTimeFormatThrows(): void {
try { try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
(datetime as any).parseDateTime("2019-01-01 00:00", "x-y-z"); (datetime as any).parseDateTime("2019-01-01 00:00", "x-y-z");
@ -40,7 +40,7 @@ test(function invalidParseDateTimeFormatThrows() {
} }
}); });
test(function parseDate() { test(function parseDate(): void {
assertEquals( assertEquals(
datetime.parseDate("01-03-2019", "mm-dd-yyyy"), datetime.parseDate("01-03-2019", "mm-dd-yyyy"),
new Date(2019, 0, 3) new Date(2019, 0, 3)
@ -55,7 +55,7 @@ test(function parseDate() {
); );
}); });
test(function invalidParseDateFormatThrows() { test(function invalidParseDateFormatThrows(): void {
try { try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
(datetime as any).parseDate("2019-01-01", "x-y-z"); (datetime as any).parseDate("2019-01-01", "x-y-z");
@ -65,12 +65,12 @@ test(function invalidParseDateFormatThrows() {
} }
}); });
test(function DayOfYear() { test(function DayOfYear(): void {
assertEquals(1, datetime.dayOfYear(new Date("2019-01-01T03:24:00"))); assertEquals(1, datetime.dayOfYear(new Date("2019-01-01T03:24:00")));
assertEquals(70, datetime.dayOfYear(new Date("2019-03-11T03:24:00"))); assertEquals(70, datetime.dayOfYear(new Date("2019-03-11T03:24:00")));
assertEquals(365, datetime.dayOfYear(new Date("2019-12-31T03:24:00"))); assertEquals(365, datetime.dayOfYear(new Date("2019-12-31T03:24:00")));
}); });
test(function currentDayOfYear() { test(function currentDayOfYear(): void {
assertEquals(datetime.currentDayOfYear(), datetime.dayOfYear(new Date())); assertEquals(datetime.currentDayOfYear(), datetime.dayOfYear(new Date()));
}); });

View file

@ -1,7 +1,7 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
const { listen, copy } = Deno; const { listen, copy } = Deno;
(async () => { (async (): Promise<void> => {
const addr = "0.0.0.0:8080"; const addr = "0.0.0.0:8080";
const listener = listen("tcp", addr); const listener = listen("tcp", addr);
console.log("listening on", addr); console.log("listening on", addr);

View file

@ -4,16 +4,16 @@ import { test } from "../testing/mod.ts";
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
/** Example of how to do basic tests */ /** Example of how to do basic tests */
test(function t1() { test(function t1(): void {
assertEquals("hello", "hello"); assertEquals("hello", "hello");
}); });
test(function t2() { test(function t2(): void {
assertEquals("world", "world"); assertEquals("world", "world");
}); });
/** A more complicated test that runs a subprocess. */ /** A more complicated test that runs a subprocess. */
test(async function catSmoke() { test(async function catSmoke(): Promise<void> {
const p = run({ const p = run({
args: ["deno", "--allow-read", "examples/cat.ts", "README.md"], args: ["deno", "--allow-read", "examples/cat.ts", "README.md"],
stdout: "piped" stdout: "piped"

View file

@ -10,7 +10,7 @@ async function main(): Promise<void> {
console.log("websocket server is running on 0.0.0.0:8080"); console.log("websocket server is running on 0.0.0.0:8080");
for await (const req of serve("0.0.0.0:8080")) { for await (const req of serve("0.0.0.0:8080")) {
if (req.url === "/ws") { if (req.url === "/ws") {
(async () => { (async (): Promise<void> => {
const sock = await acceptWebSocket(req); const sock = await acceptWebSocket(req);
console.log("socket connected!"); console.log("socket connected!");
for await (const ev of sock.receive()) { for await (const ev of sock.receive()) {

View file

@ -4,7 +4,7 @@ import { assertEquals } from "../testing/asserts.ts";
import { parse } from "./mod.ts"; import { parse } from "./mod.ts";
// flag boolean true (default all --args to boolean) // flag boolean true (default all --args to boolean)
test(function flagBooleanTrue() { test(function flagBooleanTrue(): void {
const argv = parse(["moo", "--honk", "cow"], { const argv = parse(["moo", "--honk", "cow"], {
boolean: true boolean: true
}); });
@ -18,7 +18,7 @@ test(function flagBooleanTrue() {
}); });
// flag boolean true only affects double hyphen arguments without equals signs // flag boolean true only affects double hyphen arguments without equals signs
test(function flagBooleanTrueOnlyAffectsDoubleDash() { test(function flagBooleanTrueOnlyAffectsDoubleDash(): void {
var argv = parse(["moo", "--honk", "cow", "-p", "55", "--tacos=good"], { var argv = parse(["moo", "--honk", "cow", "-p", "55", "--tacos=good"], {
boolean: true boolean: true
}); });

View file

@ -3,7 +3,7 @@ import { test } from "../testing/mod.ts";
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { parse } from "./mod.ts"; import { parse } from "./mod.ts";
test(function flagBooleanDefaultFalse() { test(function flagBooleanDefaultFalse(): void {
const argv = parse(["moo"], { const argv = parse(["moo"], {
boolean: ["t", "verbose"], boolean: ["t", "verbose"],
default: { verbose: false, t: false } default: { verbose: false, t: false }
@ -19,7 +19,7 @@ test(function flagBooleanDefaultFalse() {
assertEquals(typeof argv.t, "boolean"); assertEquals(typeof argv.t, "boolean");
}); });
test(function booleanGroups() { test(function booleanGroups(): void {
const argv = parse(["-x", "-z", "one", "two", "three"], { const argv = parse(["-x", "-z", "one", "two", "three"], {
boolean: ["x", "y", "z"] boolean: ["x", "y", "z"]
}); });
@ -36,7 +36,7 @@ test(function booleanGroups() {
assertEquals(typeof argv.z, "boolean"); assertEquals(typeof argv.z, "boolean");
}); });
test(function booleanAndAliasWithChainableApi() { test(function booleanAndAliasWithChainableApi(): void {
const aliased = ["-h", "derp"]; const aliased = ["-h", "derp"];
const regular = ["--herp", "derp"]; const regular = ["--herp", "derp"];
const aliasedArgv = parse(aliased, { const aliasedArgv = parse(aliased, {
@ -57,7 +57,7 @@ test(function booleanAndAliasWithChainableApi() {
assertEquals(propertyArgv, expected); assertEquals(propertyArgv, expected);
}); });
test(function booleanAndAliasWithOptionsHash() { test(function booleanAndAliasWithOptionsHash(): void {
const aliased = ["-h", "derp"]; const aliased = ["-h", "derp"];
const regular = ["--herp", "derp"]; const regular = ["--herp", "derp"];
const opts = { const opts = {
@ -75,7 +75,7 @@ test(function booleanAndAliasWithOptionsHash() {
assertEquals(propertyArgv, expected); assertEquals(propertyArgv, expected);
}); });
test(function booleanAndAliasArrayWithOptionsHash() { test(function booleanAndAliasArrayWithOptionsHash(): void {
const aliased = ["-h", "derp"]; const aliased = ["-h", "derp"];
const regular = ["--herp", "derp"]; const regular = ["--herp", "derp"];
const alt = ["--harp", "derp"]; const alt = ["--harp", "derp"];
@ -97,7 +97,7 @@ test(function booleanAndAliasArrayWithOptionsHash() {
assertEquals(altPropertyArgv, expected); assertEquals(altPropertyArgv, expected);
}); });
test(function booleanAndAliasUsingExplicitTrue() { test(function booleanAndAliasUsingExplicitTrue(): void {
const aliased = ["-h", "true"]; const aliased = ["-h", "true"];
const regular = ["--herp", "true"]; const regular = ["--herp", "true"];
const opts = { const opts = {
@ -118,7 +118,7 @@ test(function booleanAndAliasUsingExplicitTrue() {
// regression, see https://github.com/substack/node-optimist/issues/71 // regression, see https://github.com/substack/node-optimist/issues/71
// boolean and --x=true // boolean and --x=true
test(function booleanAndNonBoolean() { test(function booleanAndNonBoolean(): void {
const parsed = parse(["--boool", "--other=true"], { const parsed = parse(["--boool", "--other=true"], {
boolean: "boool" boolean: "boool"
}); });
@ -134,7 +134,7 @@ test(function booleanAndNonBoolean() {
assertEquals(parsed2.other, "false"); assertEquals(parsed2.other, "false");
}); });
test(function booleanParsingTrue() { test(function booleanParsingTrue(): void {
const parsed = parse(["--boool=true"], { const parsed = parse(["--boool=true"], {
default: { default: {
boool: false boool: false
@ -145,7 +145,7 @@ test(function booleanParsingTrue() {
assertEquals(parsed.boool, true); assertEquals(parsed.boool, true);
}); });
test(function booleanParsingFalse() { test(function booleanParsingFalse(): void {
const parsed = parse(["--boool=false"], { const parsed = parse(["--boool=false"], {
default: { default: {
boool: true boool: true

View file

@ -3,7 +3,7 @@ import { test } from "../testing/mod.ts";
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { parse } from "./mod.ts"; import { parse } from "./mod.ts";
test(function hyphen() { test(function hyphen(): void {
assertEquals(parse(["-n", "-"]), { n: "-", _: [] }); assertEquals(parse(["-n", "-"]), { n: "-", _: [] });
assertEquals(parse(["-"]), { _: ["-"] }); assertEquals(parse(["-"]), { _: ["-"] });
assertEquals(parse(["-f-"]), { f: "-", _: [] }); assertEquals(parse(["-f-"]), { f: "-", _: [] });
@ -11,13 +11,13 @@ test(function hyphen() {
assertEquals(parse(["-s", "-"], { string: "s" }), { s: "-", _: [] }); assertEquals(parse(["-s", "-"], { string: "s" }), { s: "-", _: [] });
}); });
test(function doubleDash() { test(function doubleDash(): void {
assertEquals(parse(["-a", "--", "b"]), { a: true, _: ["b"] }); assertEquals(parse(["-a", "--", "b"]), { a: true, _: ["b"] });
assertEquals(parse(["--a", "--", "b"]), { a: true, _: ["b"] }); assertEquals(parse(["--a", "--", "b"]), { a: true, _: ["b"] });
assertEquals(parse(["--a", "--", "b"]), { a: true, _: ["b"] }); assertEquals(parse(["--a", "--", "b"]), { a: true, _: ["b"] });
}); });
test(function moveArgsAfterDoubleDashIntoOwnArray() { test(function moveArgsAfterDoubleDashIntoOwnArray(): void {
assertEquals( assertEquals(
parse(["--name", "John", "before", "--", "after"], { "--": true }), parse(["--name", "John", "before", "--", "after"], { "--": true }),
{ {

View file

@ -3,7 +3,7 @@ import { test } from "../testing/mod.ts";
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { parse } from "./mod.ts"; import { parse } from "./mod.ts";
test(function booleanDefaultTrue() { test(function booleanDefaultTrue(): void {
const argv = parse([], { const argv = parse([], {
boolean: "sometrue", boolean: "sometrue",
default: { sometrue: true } default: { sometrue: true }
@ -11,7 +11,7 @@ test(function booleanDefaultTrue() {
assertEquals(argv.sometrue, true); assertEquals(argv.sometrue, true);
}); });
test(function booleanDefaultFalse() { test(function booleanDefaultFalse(): void {
const argv = parse([], { const argv = parse([], {
boolean: "somefalse", boolean: "somefalse",
default: { somefalse: false } default: { somefalse: false }
@ -19,7 +19,7 @@ test(function booleanDefaultFalse() {
assertEquals(argv.somefalse, false); assertEquals(argv.somefalse, false);
}); });
test(function booleanDefaultNull() { test(function booleanDefaultNull(): void {
const argv = parse([], { const argv = parse([], {
boolean: "maybe", boolean: "maybe",
default: { maybe: null } default: { maybe: null }

View file

@ -3,7 +3,7 @@ import { test } from "../testing/mod.ts";
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { parse } from "./mod.ts"; import { parse } from "./mod.ts";
test(function dottedAlias() { test(function dottedAlias(): void {
const argv = parse(["--a.b", "22"], { const argv = parse(["--a.b", "22"], {
default: { "a.b": 11 }, default: { "a.b": 11 },
alias: { "a.b": "aa.bb" } alias: { "a.b": "aa.bb" }
@ -12,13 +12,13 @@ test(function dottedAlias() {
assertEquals(argv.aa.bb, 22); assertEquals(argv.aa.bb, 22);
}); });
test(function dottedDefault() { test(function dottedDefault(): void {
const argv = parse("", { default: { "a.b": 11 }, alias: { "a.b": "aa.bb" } }); const argv = parse("", { default: { "a.b": 11 }, alias: { "a.b": "aa.bb" } });
assertEquals(argv.a.b, 11); assertEquals(argv.a.b, 11);
assertEquals(argv.aa.bb, 11); assertEquals(argv.aa.bb, 11);
}); });
test(function dottedDefaultWithNoAlias() { test(function dottedDefaultWithNoAlias(): void {
const argv = parse("", { default: { "a.b": 11 } }); const argv = parse("", { default: { "a.b": 11 } });
assertEquals(argv.a.b, 11); assertEquals(argv.a.b, 11);
}); });

View file

@ -3,12 +3,12 @@ import { test } from "../testing/mod.ts";
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { parse } from "./mod.ts"; import { parse } from "./mod.ts";
test(function short() { test(function short(): void {
const argv = parse(["-b=123"]); const argv = parse(["-b=123"]);
assertEquals(argv, { b: 123, _: [] }); assertEquals(argv, { b: 123, _: [] });
}); });
test(function multiShort() { test(function multiShort(): void {
const argv = parse(["-a=whatever", "-b=robots"]); const argv = parse(["-a=whatever", "-b=robots"]);
assertEquals(argv, { a: "whatever", b: "robots", _: [] }); assertEquals(argv, { a: "whatever", b: "robots", _: [] });
}); });

View file

@ -3,7 +3,7 @@ import { test } from "../testing/mod.ts";
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { parse } from "./mod.ts"; import { parse } from "./mod.ts";
test(function longOpts() { test(function longOpts(): void {
assertEquals(parse(["--bool"]), { bool: true, _: [] }); assertEquals(parse(["--bool"]), { bool: true, _: [] });
assertEquals(parse(["--pow", "xixxle"]), { pow: "xixxle", _: [] }); assertEquals(parse(["--pow", "xixxle"]), { pow: "xixxle", _: [] });
assertEquals(parse(["--pow=xixxle"]), { pow: "xixxle", _: [] }); assertEquals(parse(["--pow=xixxle"]), { pow: "xixxle", _: [] });

View file

@ -10,7 +10,7 @@ export interface ArgParsingOptions {
} }
const DEFAULT_OPTIONS = { const DEFAULT_OPTIONS = {
unknown: i => i, unknown: (i): unknown => i,
boolean: false, boolean: false,
alias: {}, alias: {},
string: [], string: [],
@ -27,7 +27,7 @@ function isNumber(x: unknown): boolean {
function hasKey(obj, keys): boolean { function hasKey(obj, keys): boolean {
let o = obj; let o = obj;
keys.slice(0, -1).forEach(function(key) { keys.slice(0, -1).forEach(function(key): void {
o = o[key] || {}; o = o[key] || {};
}); });
@ -38,8 +38,8 @@ function hasKey(obj, keys): boolean {
export function parse( export function parse(
args, args,
initialOptions?: ArgParsingOptions initialOptions?: ArgParsingOptions
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): { [key: string]: any } { ): { [key: string]: any } {
// eslint-disable-line @typescript-eslint/no-explicit-any
const options: ArgParsingOptions = { const options: ArgParsingOptions = {
...DEFAULT_OPTIONS, ...DEFAULT_OPTIONS,
...(initialOptions || {}) ...(initialOptions || {})
@ -59,17 +59,17 @@ export function parse(
[] []
.concat(options["boolean"]) .concat(options["boolean"])
.filter(Boolean) .filter(Boolean)
.forEach(function(key) { .forEach(function(key): void {
flags.bools[key] = true; flags.bools[key] = true;
}); });
} }
const aliases = {}; const aliases = {};
Object.keys(options.alias).forEach(function(key) { Object.keys(options.alias).forEach(function(key): void {
aliases[key] = [].concat(options.alias[key]); aliases[key] = [].concat(options.alias[key]);
aliases[key].forEach(function(x) { aliases[key].forEach(function(x): void {
aliases[x] = [key].concat( aliases[x] = [key].concat(
aliases[key].filter(function(y) { aliases[key].filter(function(y): boolean {
return x !== y; return x !== y;
}) })
); );
@ -79,7 +79,7 @@ export function parse(
[] []
.concat(options.string) .concat(options.string)
.filter(Boolean) .filter(Boolean)
.forEach(function(key) { .forEach(function(key): void {
flags.strings[key] = true; flags.strings[key] = true;
if (aliases[key]) { if (aliases[key]) {
flags.strings[aliases[key]] = true; flags.strings[aliases[key]] = true;
@ -101,7 +101,7 @@ export function parse(
function setKey(obj, keys, value): void { function setKey(obj, keys, value): void {
let o = obj; let o = obj;
keys.slice(0, -1).forEach(function(key) { keys.slice(0, -1).forEach(function(key): void {
if (o[key] === undefined) o[key] = {}; if (o[key] === undefined) o[key] = {};
o = o[key]; o = o[key];
}); });
@ -128,18 +128,18 @@ export function parse(
const value = !flags.strings[key] && isNumber(val) ? Number(val) : val; const value = !flags.strings[key] && isNumber(val) ? Number(val) : val;
setKey(argv, key.split("."), value); setKey(argv, key.split("."), value);
(aliases[key] || []).forEach(function(x) { (aliases[key] || []).forEach(function(x): void {
setKey(argv, x.split("."), value); setKey(argv, x.split("."), value);
}); });
} }
function aliasIsBoolean(key): boolean { function aliasIsBoolean(key): boolean {
return aliases[key].some(function(x) { return aliases[key].some(function(x): boolean {
return flags.bools[x]; return flags.bools[x];
}); });
} }
Object.keys(flags.bools).forEach(function(key) { Object.keys(flags.bools).forEach(function(key): void {
setArg(key, defaults[key] === undefined ? false : defaults[key]); setArg(key, defaults[key] === undefined ? false : defaults[key]);
}); });
@ -249,11 +249,11 @@ export function parse(
} }
} }
Object.keys(defaults).forEach(function(key) { Object.keys(defaults).forEach(function(key): void {
if (!hasKey(argv, key.split("."))) { if (!hasKey(argv, key.split("."))) {
setKey(argv, key.split("."), defaults[key]); setKey(argv, key.split("."), defaults[key]);
(aliases[key] || []).forEach(function(x) { (aliases[key] || []).forEach(function(x): void {
setKey(argv, x.split("."), defaults[key]); setKey(argv, x.split("."), defaults[key]);
}); });
} }
@ -261,11 +261,11 @@ export function parse(
if (options["--"]) { if (options["--"]) {
argv["--"] = []; argv["--"] = [];
notFlags.forEach(function(key) { notFlags.forEach(function(key): void {
argv["--"].push(key); argv["--"].push(key);
}); });
} else { } else {
notFlags.forEach(function(key) { notFlags.forEach(function(key): void {
argv._.push(key); argv._.push(key);
}); });
} }

View file

@ -3,7 +3,7 @@ import { test } from "../testing/mod.ts";
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { parse } from "./mod.ts"; import { parse } from "./mod.ts";
test(function nums() { test(function nums(): void {
const argv = parse([ const argv = parse([
"-x", "-x",
"1234", "1234",
@ -33,7 +33,7 @@ test(function nums() {
assertEquals(typeof argv._[0], "number"); assertEquals(typeof argv._[0], "number");
}); });
test(function alreadyNumber() { test(function alreadyNumber(): void {
const argv = parse(["-x", 1234, 789]); const argv = parse(["-x", 1234, 789]);
assertEquals(argv, { x: 1234, _: [789] }); assertEquals(argv, { x: 1234, _: [789] });
assertEquals(typeof argv.x, "number"); assertEquals(typeof argv.x, "number");

View file

@ -3,7 +3,7 @@ import { test } from "../testing/mod.ts";
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { parse } from "./mod.ts"; import { parse } from "./mod.ts";
test(function _arseArgs() { test(function _arseArgs(): void {
assertEquals(parse(["--no-moo"]), { moo: false, _: [] }); assertEquals(parse(["--no-moo"]), { moo: false, _: [] });
assertEquals(parse(["-v", "a", "-v", "b", "-v", "c"]), { assertEquals(parse(["-v", "a", "-v", "b", "-v", "c"]), {
v: ["a", "b", "c"], v: ["a", "b", "c"],
@ -11,7 +11,7 @@ test(function _arseArgs() {
}); });
}); });
test(function comprehensive() { test(function comprehensive(): void {
assertEquals( assertEquals(
parse([ parse([
"--name=meowmers", "--name=meowmers",
@ -48,13 +48,13 @@ test(function comprehensive() {
); );
}); });
test(function flagBoolean() { test(function flagBoolean(): void {
const argv = parse(["-t", "moo"], { boolean: "t" }); const argv = parse(["-t", "moo"], { boolean: "t" });
assertEquals(argv, { t: true, _: ["moo"] }); assertEquals(argv, { t: true, _: ["moo"] });
assertEquals(typeof argv.t, "boolean"); assertEquals(typeof argv.t, "boolean");
}); });
test(function flagBooleanValue() { test(function flagBooleanValue(): void {
const argv = parse(["--verbose", "false", "moo", "-t", "true"], { const argv = parse(["--verbose", "false", "moo", "-t", "true"], {
boolean: ["t", "verbose"], boolean: ["t", "verbose"],
default: { verbose: true } default: { verbose: true }
@ -70,7 +70,7 @@ test(function flagBooleanValue() {
assertEquals(typeof argv.t, "boolean"); assertEquals(typeof argv.t, "boolean");
}); });
test(function newlinesInParams() { test(function newlinesInParams(): void {
const args = parse(["-s", "X\nX"]); const args = parse(["-s", "X\nX"]);
assertEquals(args, { _: [], s: "X\nX" }); assertEquals(args, { _: [], s: "X\nX" });
@ -82,7 +82,7 @@ test(function newlinesInParams() {
assertEquals(args2, { _: [], s: "X\nX" }); assertEquals(args2, { _: [], s: "X\nX" });
}); });
test(function strings() { test(function strings(): void {
const s = parse(["-s", "0001234"], { string: "s" }).s; const s = parse(["-s", "0001234"], { string: "s" }).s;
assertEquals(s, "0001234"); assertEquals(s, "0001234");
assertEquals(typeof s, "string"); assertEquals(typeof s, "string");
@ -92,7 +92,7 @@ test(function strings() {
assertEquals(typeof x, "string"); assertEquals(typeof x, "string");
}); });
test(function stringArgs() { test(function stringArgs(): void {
const s = parse([" ", " "], { string: "_" })._; const s = parse([" ", " "], { string: "_" })._;
assertEquals(s.length, 2); assertEquals(s.length, 2);
assertEquals(typeof s[0], "string"); assertEquals(typeof s[0], "string");
@ -101,7 +101,7 @@ test(function stringArgs() {
assertEquals(s[1], " "); assertEquals(s[1], " ");
}); });
test(function emptyStrings() { test(function emptyStrings(): void {
const s = parse(["-s"], { string: "s" }).s; const s = parse(["-s"], { string: "s" }).s;
assertEquals(s, ""); assertEquals(s, "");
assertEquals(typeof s, "string"); assertEquals(typeof s, "string");
@ -119,7 +119,7 @@ test(function emptyStrings() {
assertEquals(letters.t, ""); assertEquals(letters.t, "");
}); });
test(function stringAndAlias() { test(function stringAndAlias(): void {
const x = parse(["--str", "000123"], { const x = parse(["--str", "000123"], {
string: "s", string: "s",
alias: { s: "str" } alias: { s: "str" }
@ -141,7 +141,7 @@ test(function stringAndAlias() {
assertEquals(typeof y.s, "string"); assertEquals(typeof y.s, "string");
}); });
test(function slashBreak() { test(function slashBreak(): void {
assertEquals(parse(["-I/foo/bar/baz"]), { I: "/foo/bar/baz", _: [] }); assertEquals(parse(["-I/foo/bar/baz"]), { I: "/foo/bar/baz", _: [] });
assertEquals(parse(["-xyz/foo/bar/baz"]), { assertEquals(parse(["-xyz/foo/bar/baz"]), {
x: true, x: true,
@ -151,7 +151,7 @@ test(function slashBreak() {
}); });
}); });
test(function alias() { test(function alias(): void {
const argv = parse(["-f", "11", "--zoom", "55"], { const argv = parse(["-f", "11", "--zoom", "55"], {
alias: { z: "zoom" } alias: { z: "zoom" }
}); });
@ -160,7 +160,7 @@ test(function alias() {
assertEquals(argv.f, 11); assertEquals(argv.f, 11);
}); });
test(function multiAlias() { test(function multiAlias(): void {
const argv = parse(["-f", "11", "--zoom", "55"], { const argv = parse(["-f", "11", "--zoom", "55"], {
alias: { z: ["zm", "zoom"] } alias: { z: ["zm", "zoom"] }
}); });
@ -170,7 +170,7 @@ test(function multiAlias() {
assertEquals(argv.f, 11); assertEquals(argv.f, 11);
}); });
test(function nestedDottedObjects() { test(function nestedDottedObjects(): void {
const argv = parse([ const argv = parse([
"--foo.bar", "--foo.bar",
"3", "3",

View file

@ -3,12 +3,12 @@ import { test } from "../testing/mod.ts";
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { parse } from "./mod.ts"; import { parse } from "./mod.ts";
test(function numbericShortArgs() { test(function numbericShortArgs(): void {
assertEquals(parse(["-n123"]), { n: 123, _: [] }); assertEquals(parse(["-n123"]), { n: 123, _: [] });
assertEquals(parse(["-123", "456"]), { 1: true, 2: true, 3: 456, _: [] }); assertEquals(parse(["-123", "456"]), { 1: true, 2: true, 3: 456, _: [] });
}); });
test(function short() { test(function short(): void {
assertEquals(parse(["-b"]), { b: true, _: [] }); assertEquals(parse(["-b"]), { b: true, _: [] });
assertEquals(parse(["foo", "bar", "baz"]), { _: ["foo", "bar", "baz"] }); assertEquals(parse(["foo", "bar", "baz"]), { _: ["foo", "bar", "baz"] });
assertEquals(parse(["-cats"]), { c: true, a: true, t: true, s: true, _: [] }); assertEquals(parse(["-cats"]), { c: true, a: true, t: true, s: true, _: [] });
@ -27,7 +27,7 @@ test(function short() {
}); });
}); });
test(function mixedShortBoolAndCapture() { test(function mixedShortBoolAndCapture(): void {
assertEquals(parse(["-h", "localhost", "-fp", "555", "script.js"]), { assertEquals(parse(["-h", "localhost", "-fp", "555", "script.js"]), {
f: true, f: true,
p: 555, p: 555,
@ -36,7 +36,7 @@ test(function mixedShortBoolAndCapture() {
}); });
}); });
test(function shortAndLong() { test(function shortAndLong(): void {
assertEquals(parse(["-h", "localhost", "-fp", "555", "script.js"]), { assertEquals(parse(["-h", "localhost", "-fp", "555", "script.js"]), {
f: true, f: true,
p: 555, p: 555,

View file

@ -4,7 +4,7 @@ import { assertEquals } from "../testing/asserts.ts";
import { parse } from "./mod.ts"; import { parse } from "./mod.ts";
// stops parsing on the first non-option when stopEarly is set // stops parsing on the first non-option when stopEarly is set
test(function stopParsing() { test(function stopParsing(): void {
const argv = parse(["--aaa", "bbb", "ccc", "--ddd"], { const argv = parse(["--aaa", "bbb", "ccc", "--ddd"], {
stopEarly: true stopEarly: true
}); });

View file

@ -3,7 +3,7 @@ import { test } from "../testing/mod.ts";
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { parse } from "./mod.ts"; import { parse } from "./mod.ts";
test(function booleanAndAliasIsNotUnknown() { test(function booleanAndAliasIsNotUnknown(): void {
const unknown = []; const unknown = [];
function unknownFn(arg): boolean { function unknownFn(arg): boolean {
unknown.push(arg); unknown.push(arg);
@ -22,7 +22,7 @@ test(function booleanAndAliasIsNotUnknown() {
assertEquals(unknown, ["--derp", "-d"]); assertEquals(unknown, ["--derp", "-d"]);
}); });
test(function flagBooleanTrueAnyDoubleHyphenArgumentIsNotUnknown() { test(function flagBooleanTrueAnyDoubleHyphenArgumentIsNotUnknown(): void {
const unknown = []; const unknown = [];
function unknownFn(arg): boolean { function unknownFn(arg): boolean {
unknown.push(arg); unknown.push(arg);
@ -39,7 +39,7 @@ test(function flagBooleanTrueAnyDoubleHyphenArgumentIsNotUnknown() {
}); });
}); });
test(function stringAndAliasIsNotUnkown() { test(function stringAndAliasIsNotUnkown(): void {
const unknown = []; const unknown = [];
function unknownFn(arg): boolean { function unknownFn(arg): boolean {
unknown.push(arg); unknown.push(arg);
@ -58,7 +58,7 @@ test(function stringAndAliasIsNotUnkown() {
assertEquals(unknown, ["--derp", "-d"]); assertEquals(unknown, ["--derp", "-d"]);
}); });
test(function defaultAndAliasIsNotUnknown() { test(function defaultAndAliasIsNotUnknown(): void {
const unknown = []; const unknown = [];
function unknownFn(arg): boolean { function unknownFn(arg): boolean {
unknown.push(arg); unknown.push(arg);
@ -77,7 +77,7 @@ test(function defaultAndAliasIsNotUnknown() {
assertEquals(unknown, []); assertEquals(unknown, []);
}); });
test(function valueFollowingDoubleHyphenIsNotUnknown() { test(function valueFollowingDoubleHyphenIsNotUnknown(): void {
const unknown = []; const unknown = [];
function unknownFn(arg): boolean { function unknownFn(arg): boolean {
unknown.push(arg); unknown.push(arg);

View file

@ -3,6 +3,6 @@ import { test } from "../testing/mod.ts";
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { parse } from "./mod.ts"; import { parse } from "./mod.ts";
test(function whitespaceShouldBeWhitespace() { test(function whitespaceShouldBeWhitespace(): void {
assertEquals(parse(["-x", "\t"]).x, "\t"); assertEquals(parse(["-x", "\t"]).x, "\t");
}); });

View file

@ -10,7 +10,7 @@ import * as path from "./path/mod.ts";
const testdataDir = path.resolve("fs", "testdata"); const testdataDir = path.resolve("fs", "testdata");
test(async function emptyDirIfItNotExist() { test(async function emptyDirIfItNotExist(): Promise<void> {
const testDir = path.join(testdataDir, "empty_dir_test_1"); const testDir = path.join(testdataDir, "empty_dir_test_1");
const testNestDir = path.join(testDir, "nest"); const testNestDir = path.join(testDir, "nest");
// empty a dir which not exist. then it will create new one // empty a dir which not exist. then it will create new one
@ -26,7 +26,7 @@ test(async function emptyDirIfItNotExist() {
} }
}); });
test(function emptyDirSyncIfItNotExist() { test(function emptyDirSyncIfItNotExist(): void {
const testDir = path.join(testdataDir, "empty_dir_test_2"); const testDir = path.join(testdataDir, "empty_dir_test_2");
const testNestDir = path.join(testDir, "nest"); const testNestDir = path.join(testDir, "nest");
// empty a dir which not exist. then it will create new one // empty a dir which not exist. then it will create new one
@ -42,7 +42,7 @@ test(function emptyDirSyncIfItNotExist() {
} }
}); });
test(async function emptyDirIfItExist() { test(async function emptyDirIfItExist(): Promise<void> {
const testDir = path.join(testdataDir, "empty_dir_test_3"); const testDir = path.join(testdataDir, "empty_dir_test_3");
const testNestDir = path.join(testDir, "nest"); const testNestDir = path.join(testDir, "nest");
// create test dir // create test dir
@ -67,21 +67,25 @@ test(async function emptyDirIfItExist() {
assertEquals(stat.isDirectory(), true); assertEquals(stat.isDirectory(), true);
// nest directory have been remove // nest directory have been remove
await assertThrowsAsync(async () => { await assertThrowsAsync(
async (): Promise<void> => {
await Deno.stat(testNestDir); await Deno.stat(testNestDir);
}); }
);
// test file have been remove // test file have been remove
await assertThrowsAsync(async () => { await assertThrowsAsync(
async (): Promise<void> => {
await Deno.stat(testDirFile); await Deno.stat(testDirFile);
}); }
);
} finally { } finally {
// remote test dir // remote test dir
await Deno.remove(testDir, { recursive: true }); await Deno.remove(testDir, { recursive: true });
} }
}); });
test(function emptyDirSyncIfItExist() { test(function emptyDirSyncIfItExist(): void {
const testDir = path.join(testdataDir, "empty_dir_test_4"); const testDir = path.join(testdataDir, "empty_dir_test_4");
const testNestDir = path.join(testDir, "nest"); const testNestDir = path.join(testDir, "nest");
// create test dir // create test dir
@ -106,14 +110,18 @@ test(function emptyDirSyncIfItExist() {
assertEquals(stat.isDirectory(), true); assertEquals(stat.isDirectory(), true);
// nest directory have been remove // nest directory have been remove
assertThrows(() => { assertThrows(
(): void => {
Deno.statSync(testNestDir); Deno.statSync(testNestDir);
}); }
);
// test file have been remove // test file have been remove
assertThrows(() => { assertThrows(
(): void => {
Deno.statSync(testDirFile); Deno.statSync(testDirFile);
}); }
);
} finally { } finally {
// remote test dir // remote test dir
Deno.removeSync(testDir, { recursive: true }); Deno.removeSync(testDir, { recursive: true });

View file

@ -7,22 +7,26 @@ import { ensureFile, ensureFileSync } from "./ensure_file.ts";
const testdataDir = path.resolve("fs", "testdata"); const testdataDir = path.resolve("fs", "testdata");
test(async function ensureDirIfItNotExist() { test(async function ensureDirIfItNotExist(): Promise<void> {
const baseDir = path.join(testdataDir, "ensure_dir_not_exist"); const baseDir = path.join(testdataDir, "ensure_dir_not_exist");
const testDir = path.join(baseDir, "test"); const testDir = path.join(baseDir, "test");
await ensureDir(testDir); await ensureDir(testDir);
await assertThrowsAsync(async () => { await assertThrowsAsync(
await Deno.stat(testDir).then(() => { async (): Promise<void> => {
await Deno.stat(testDir).then(
(): void => {
throw new Error("test dir should exists."); throw new Error("test dir should exists.");
}); }
}); );
}
);
await Deno.remove(baseDir, { recursive: true }); await Deno.remove(baseDir, { recursive: true });
}); });
test(function ensureDirSyncIfItNotExist() { test(function ensureDirSyncIfItNotExist(): void {
const baseDir = path.join(testdataDir, "ensure_dir_sync_not_exist"); const baseDir = path.join(testdataDir, "ensure_dir_sync_not_exist");
const testDir = path.join(baseDir, "test"); const testDir = path.join(baseDir, "test");
@ -33,7 +37,7 @@ test(function ensureDirSyncIfItNotExist() {
Deno.removeSync(baseDir, { recursive: true }); Deno.removeSync(baseDir, { recursive: true });
}); });
test(async function ensureDirIfItExist() { test(async function ensureDirIfItExist(): Promise<void> {
const baseDir = path.join(testdataDir, "ensure_dir_exist"); const baseDir = path.join(testdataDir, "ensure_dir_exist");
const testDir = path.join(baseDir, "test"); const testDir = path.join(baseDir, "test");
@ -42,16 +46,20 @@ test(async function ensureDirIfItExist() {
await ensureDir(testDir); await ensureDir(testDir);
await assertThrowsAsync(async () => { await assertThrowsAsync(
await Deno.stat(testDir).then(() => { async (): Promise<void> => {
await Deno.stat(testDir).then(
(): void => {
throw new Error("test dir should still exists."); throw new Error("test dir should still exists.");
}); }
}); );
}
);
await Deno.remove(baseDir, { recursive: true }); await Deno.remove(baseDir, { recursive: true });
}); });
test(function ensureDirSyncIfItExist() { test(function ensureDirSyncIfItExist(): void {
const baseDir = path.join(testdataDir, "ensure_dir_sync_exist"); const baseDir = path.join(testdataDir, "ensure_dir_sync_exist");
const testDir = path.join(baseDir, "test"); const testDir = path.join(baseDir, "test");
@ -60,22 +68,24 @@ test(function ensureDirSyncIfItExist() {
ensureDirSync(testDir); ensureDirSync(testDir);
assertThrows(() => { assertThrows(
(): void => {
Deno.statSync(testDir); Deno.statSync(testDir);
throw new Error("test dir should still exists."); throw new Error("test dir should still exists.");
}); }
);
Deno.removeSync(baseDir, { recursive: true }); Deno.removeSync(baseDir, { recursive: true });
}); });
test(async function ensureDirIfItAsFile() { test(async function ensureDirIfItAsFile(): Promise<void> {
const baseDir = path.join(testdataDir, "ensure_dir_exist_file"); const baseDir = path.join(testdataDir, "ensure_dir_exist_file");
const testFile = path.join(baseDir, "test"); const testFile = path.join(baseDir, "test");
await ensureFile(testFile); await ensureFile(testFile);
await assertThrowsAsync( await assertThrowsAsync(
async () => { async (): Promise<void> => {
await ensureDir(testFile); await ensureDir(testFile);
}, },
Error, Error,
@ -85,14 +95,14 @@ test(async function ensureDirIfItAsFile() {
await Deno.remove(baseDir, { recursive: true }); await Deno.remove(baseDir, { recursive: true });
}); });
test(function ensureDirSyncIfItAsFile() { test(function ensureDirSyncIfItAsFile(): void {
const baseDir = path.join(testdataDir, "ensure_dir_exist_file_async"); const baseDir = path.join(testdataDir, "ensure_dir_exist_file_async");
const testFile = path.join(baseDir, "test"); const testFile = path.join(baseDir, "test");
ensureFileSync(testFile); ensureFileSync(testFile);
assertThrows( assertThrows(
() => { (): void => {
ensureDirSync(testFile); ensureDirSync(testFile);
}, },
Error, Error,

View file

@ -6,36 +6,42 @@ import * as path from "./path/mod.ts";
const testdataDir = path.resolve("fs", "testdata"); const testdataDir = path.resolve("fs", "testdata");
test(async function ensureFileIfItNotExist() { test(async function ensureFileIfItNotExist(): Promise<void> {
const testDir = path.join(testdataDir, "ensure_file_1"); const testDir = path.join(testdataDir, "ensure_file_1");
const testFile = path.join(testDir, "test.txt"); const testFile = path.join(testDir, "test.txt");
await ensureFile(testFile); await ensureFile(testFile);
await assertThrowsAsync(async () => { await assertThrowsAsync(
await Deno.stat(testFile).then(() => { async (): Promise<void> => {
await Deno.stat(testFile).then(
(): void => {
throw new Error("test file should exists."); throw new Error("test file should exists.");
}); }
}); );
}
);
await Deno.remove(testDir, { recursive: true }); await Deno.remove(testDir, { recursive: true });
}); });
test(function ensureFileSyncIfItNotExist() { test(function ensureFileSyncIfItNotExist(): void {
const testDir = path.join(testdataDir, "ensure_file_2"); const testDir = path.join(testdataDir, "ensure_file_2");
const testFile = path.join(testDir, "test.txt"); const testFile = path.join(testDir, "test.txt");
ensureFileSync(testFile); ensureFileSync(testFile);
assertThrows(() => { assertThrows(
(): void => {
Deno.statSync(testFile); Deno.statSync(testFile);
throw new Error("test file should exists."); throw new Error("test file should exists.");
}); }
);
Deno.removeSync(testDir, { recursive: true }); Deno.removeSync(testDir, { recursive: true });
}); });
test(async function ensureFileIfItExist() { test(async function ensureFileIfItExist(): Promise<void> {
const testDir = path.join(testdataDir, "ensure_file_3"); const testDir = path.join(testdataDir, "ensure_file_3");
const testFile = path.join(testDir, "test.txt"); const testFile = path.join(testDir, "test.txt");
@ -44,16 +50,20 @@ test(async function ensureFileIfItExist() {
await ensureFile(testFile); await ensureFile(testFile);
await assertThrowsAsync(async () => { await assertThrowsAsync(
await Deno.stat(testFile).then(() => { async (): Promise<void> => {
await Deno.stat(testFile).then(
(): void => {
throw new Error("test file should exists."); throw new Error("test file should exists.");
}); }
}); );
}
);
await Deno.remove(testDir, { recursive: true }); await Deno.remove(testDir, { recursive: true });
}); });
test(function ensureFileSyncIfItExist() { test(function ensureFileSyncIfItExist(): void {
const testDir = path.join(testdataDir, "ensure_file_4"); const testDir = path.join(testdataDir, "ensure_file_4");
const testFile = path.join(testDir, "test.txt"); const testFile = path.join(testDir, "test.txt");
@ -62,21 +72,23 @@ test(function ensureFileSyncIfItExist() {
ensureFileSync(testFile); ensureFileSync(testFile);
assertThrows(() => { assertThrows(
(): void => {
Deno.statSync(testFile); Deno.statSync(testFile);
throw new Error("test file should exists."); throw new Error("test file should exists.");
}); }
);
Deno.removeSync(testDir, { recursive: true }); Deno.removeSync(testDir, { recursive: true });
}); });
test(async function ensureFileIfItExistAsDir() { test(async function ensureFileIfItExistAsDir(): Promise<void> {
const testDir = path.join(testdataDir, "ensure_file_5"); const testDir = path.join(testdataDir, "ensure_file_5");
await Deno.mkdir(testDir, true); await Deno.mkdir(testDir, true);
await assertThrowsAsync( await assertThrowsAsync(
async () => { async (): Promise<void> => {
await ensureFile(testDir); await ensureFile(testDir);
}, },
Error, Error,
@ -86,13 +98,13 @@ test(async function ensureFileIfItExistAsDir() {
await Deno.remove(testDir, { recursive: true }); await Deno.remove(testDir, { recursive: true });
}); });
test(function ensureFileSyncIfItExistAsDir() { test(function ensureFileSyncIfItExistAsDir(): void {
const testDir = path.join(testdataDir, "ensure_file_6"); const testDir = path.join(testdataDir, "ensure_file_6");
Deno.mkdirSync(testDir, true); Deno.mkdirSync(testDir, true);
assertThrows( assertThrows(
() => { (): void => {
ensureFileSync(testDir); ensureFileSync(testDir);
}, },
Error, Error,

View file

@ -11,32 +11,36 @@ import * as path from "./path/mod.ts";
const testdataDir = path.resolve("fs", "testdata"); const testdataDir = path.resolve("fs", "testdata");
test(async function ensureLinkIfItNotExist() { test(async function ensureLinkIfItNotExist(): Promise<void> {
const srcDir = path.join(testdataDir, "ensure_link_1"); const srcDir = path.join(testdataDir, "ensure_link_1");
const destDir = path.join(testdataDir, "ensure_link_1_2"); const destDir = path.join(testdataDir, "ensure_link_1_2");
const testFile = path.join(srcDir, "test.txt"); const testFile = path.join(srcDir, "test.txt");
const linkFile = path.join(destDir, "link.txt"); const linkFile = path.join(destDir, "link.txt");
await assertThrowsAsync(async () => { await assertThrowsAsync(
(): Promise<void> => {
await ensureLink(testFile, linkFile); await ensureLink(testFile, linkFile);
}); }
);
await Deno.remove(destDir, { recursive: true }); await Deno.remove(destDir, { recursive: true });
}); });
test(function ensureLinkSyncIfItNotExist() { test(function ensureLinkSyncIfItNotExist(): void {
const testDir = path.join(testdataDir, "ensure_link_2"); const testDir = path.join(testdataDir, "ensure_link_2");
const testFile = path.join(testDir, "test.txt"); const testFile = path.join(testDir, "test.txt");
const linkFile = path.join(testDir, "link.txt"); const linkFile = path.join(testDir, "link.txt");
assertThrows(() => { assertThrows(
(): void => {
ensureLinkSync(testFile, linkFile); ensureLinkSync(testFile, linkFile);
}); }
);
Deno.removeSync(testDir, { recursive: true }); Deno.removeSync(testDir, { recursive: true });
}); });
test(async function ensureLinkIfItExist() { test(async function ensureLinkIfItExist(): Promise<void> {
const testDir = path.join(testdataDir, "ensure_link_3"); const testDir = path.join(testdataDir, "ensure_link_3");
const testFile = path.join(testDir, "test.txt"); const testFile = path.join(testDir, "test.txt");
const linkFile = path.join(testDir, "link.txt"); const linkFile = path.join(testDir, "link.txt");
@ -83,7 +87,7 @@ test(async function ensureLinkIfItExist() {
await Deno.remove(testDir, { recursive: true }); await Deno.remove(testDir, { recursive: true });
}); });
test(function ensureLinkSyncIfItExist() { test(function ensureLinkSyncIfItExist(): void {
const testDir = path.join(testdataDir, "ensure_link_4"); const testDir = path.join(testdataDir, "ensure_link_4");
const testFile = path.join(testDir, "test.txt"); const testFile = path.join(testDir, "test.txt");
const linkFile = path.join(testDir, "link.txt"); const linkFile = path.join(testDir, "link.txt");
@ -131,7 +135,7 @@ test(function ensureLinkSyncIfItExist() {
Deno.removeSync(testDir, { recursive: true }); Deno.removeSync(testDir, { recursive: true });
}); });
test(async function ensureLinkDirectoryIfItExist() { test(async function ensureLinkDirectoryIfItExist(): Promise<void> {
const testDir = path.join(testdataDir, "ensure_link_origin_3"); const testDir = path.join(testdataDir, "ensure_link_origin_3");
const linkDir = path.join(testdataDir, "ensure_link_link_3"); const linkDir = path.join(testdataDir, "ensure_link_link_3");
const testFile = path.join(testDir, "test.txt"); const testFile = path.join(testDir, "test.txt");
@ -140,7 +144,7 @@ test(async function ensureLinkDirectoryIfItExist() {
await Deno.writeFile(testFile, new Uint8Array()); await Deno.writeFile(testFile, new Uint8Array());
await assertThrowsAsync( await assertThrowsAsync(
async () => { async (): Promise<void> => {
await ensureLink(testDir, linkDir); await ensureLink(testDir, linkDir);
}, },
Deno.DenoError, Deno.DenoError,
@ -150,7 +154,7 @@ test(async function ensureLinkDirectoryIfItExist() {
Deno.removeSync(testDir, { recursive: true }); Deno.removeSync(testDir, { recursive: true });
}); });
test(function ensureLinkSyncDirectoryIfItExist() { test(function ensureLinkSyncDirectoryIfItExist(): void {
const testDir = path.join(testdataDir, "ensure_link_origin_3"); const testDir = path.join(testdataDir, "ensure_link_origin_3");
const linkDir = path.join(testdataDir, "ensure_link_link_3"); const linkDir = path.join(testdataDir, "ensure_link_link_3");
const testFile = path.join(testDir, "test.txt"); const testFile = path.join(testDir, "test.txt");
@ -159,7 +163,7 @@ test(function ensureLinkSyncDirectoryIfItExist() {
Deno.writeFileSync(testFile, new Uint8Array()); Deno.writeFileSync(testFile, new Uint8Array());
assertThrows( assertThrows(
() => { (): void => {
ensureLinkSync(testDir, linkDir); ensureLinkSync(testDir, linkDir);
}, },
Deno.DenoError, Deno.DenoError,

View file

@ -12,36 +12,46 @@ import * as path from "./path/mod.ts";
const testdataDir = path.resolve("fs", "testdata"); const testdataDir = path.resolve("fs", "testdata");
const isWindows = Deno.platform.os === "win"; const isWindows = Deno.platform.os === "win";
test(async function ensureSymlinkIfItNotExist() { test(async function ensureSymlinkIfItNotExist(): Promise<void> {
const testDir = path.join(testdataDir, "link_file_1"); const testDir = path.join(testdataDir, "link_file_1");
const testFile = path.join(testDir, "test.txt"); const testFile = path.join(testDir, "test.txt");
assertThrowsAsync(async () => { assertThrowsAsync(
async (): Promise<void> => {
await ensureSymlink(testFile, path.join(testDir, "test1.txt")); await ensureSymlink(testFile, path.join(testDir, "test1.txt"));
}); }
);
assertThrowsAsync(async () => { assertThrowsAsync(
await Deno.stat(testFile).then(() => { async (): Promise<void> => {
await Deno.stat(testFile).then(
(): void => {
throw new Error("test file should exists."); throw new Error("test file should exists.");
}); }
}); );
}
);
}); });
test(function ensureSymlinkSyncIfItNotExist() { test(function ensureSymlinkSyncIfItNotExist(): void {
const testDir = path.join(testdataDir, "link_file_2"); const testDir = path.join(testdataDir, "link_file_2");
const testFile = path.join(testDir, "test.txt"); const testFile = path.join(testDir, "test.txt");
assertThrows(() => { assertThrows(
(): void => {
ensureSymlinkSync(testFile, path.join(testDir, "test1.txt")); ensureSymlinkSync(testFile, path.join(testDir, "test1.txt"));
}); }
);
assertThrows(() => { assertThrows(
(): void => {
Deno.statSync(testFile); Deno.statSync(testFile);
throw new Error("test file should exists."); throw new Error("test file should exists.");
}); }
);
}); });
test(async function ensureSymlinkIfItExist() { test(async function ensureSymlinkIfItExist(): Promise<void> {
const testDir = path.join(testdataDir, "link_file_3"); const testDir = path.join(testdataDir, "link_file_3");
const testFile = path.join(testDir, "test.txt"); const testFile = path.join(testDir, "test.txt");
const linkFile = path.join(testDir, "link.txt"); const linkFile = path.join(testDir, "link.txt");
@ -51,7 +61,7 @@ test(async function ensureSymlinkIfItExist() {
if (isWindows) { if (isWindows) {
await assertThrowsAsync( await assertThrowsAsync(
() => ensureSymlink(testFile, linkFile), (): Promise<void> => ensureSymlink(testFile, linkFile),
Error, Error,
"Not implemented" "Not implemented"
); );
@ -70,7 +80,7 @@ test(async function ensureSymlinkIfItExist() {
await Deno.remove(testDir, { recursive: true }); await Deno.remove(testDir, { recursive: true });
}); });
test(function ensureSymlinkSyncIfItExist() { test(function ensureSymlinkSyncIfItExist(): void {
const testDir = path.join(testdataDir, "link_file_4"); const testDir = path.join(testdataDir, "link_file_4");
const testFile = path.join(testDir, "test.txt"); const testFile = path.join(testDir, "test.txt");
const linkFile = path.join(testDir, "link.txt"); const linkFile = path.join(testDir, "link.txt");
@ -80,7 +90,7 @@ test(function ensureSymlinkSyncIfItExist() {
if (isWindows) { if (isWindows) {
assertThrows( assertThrows(
() => ensureSymlinkSync(testFile, linkFile), (): void => ensureSymlinkSync(testFile, linkFile),
Error, Error,
"Not implemented" "Not implemented"
); );
@ -100,7 +110,7 @@ test(function ensureSymlinkSyncIfItExist() {
Deno.removeSync(testDir, { recursive: true }); Deno.removeSync(testDir, { recursive: true });
}); });
test(async function ensureSymlinkDirectoryIfItExist() { test(async function ensureSymlinkDirectoryIfItExist(): Promise<void> {
const testDir = path.join(testdataDir, "link_file_origin_3"); const testDir = path.join(testdataDir, "link_file_origin_3");
const linkDir = path.join(testdataDir, "link_file_link_3"); const linkDir = path.join(testdataDir, "link_file_link_3");
const testFile = path.join(testDir, "test.txt"); const testFile = path.join(testDir, "test.txt");
@ -110,7 +120,7 @@ test(async function ensureSymlinkDirectoryIfItExist() {
if (isWindows) { if (isWindows) {
await assertThrowsAsync( await assertThrowsAsync(
() => ensureSymlink(testDir, linkDir), (): Promise<void> => ensureSymlink(testDir, linkDir),
Error, Error,
"Not implemented" "Not implemented"
); );
@ -132,7 +142,7 @@ test(async function ensureSymlinkDirectoryIfItExist() {
await Deno.remove(testDir, { recursive: true }); await Deno.remove(testDir, { recursive: true });
}); });
test(function ensureSymlinkSyncDirectoryIfItExist() { test(function ensureSymlinkSyncDirectoryIfItExist(): void {
const testDir = path.join(testdataDir, "link_file_origin_3"); const testDir = path.join(testdataDir, "link_file_origin_3");
const linkDir = path.join(testdataDir, "link_file_link_3"); const linkDir = path.join(testdataDir, "link_file_link_3");
const testFile = path.join(testDir, "test.txt"); const testFile = path.join(testDir, "test.txt");
@ -142,7 +152,7 @@ test(function ensureSymlinkSyncDirectoryIfItExist() {
if (isWindows) { if (isWindows) {
assertThrows( assertThrows(
() => ensureSymlinkSync(testDir, linkDir), (): void => ensureSymlinkSync(testDir, linkDir),
Error, Error,
"Not implemented" "Not implemented"
); );

View file

@ -17,7 +17,7 @@ export function detect(content: string): EOL | null {
if (!d || d.length === 0) { if (!d || d.length === 0) {
return null; return null;
} }
const crlf = d.filter((x: string) => x === EOL.CRLF); const crlf = d.filter((x: string): boolean => x === EOL.CRLF);
if (crlf.length > 0) { if (crlf.length > 0) {
return EOL.CRLF; return EOL.CRLF;
} else { } else {

View file

@ -11,28 +11,28 @@ const NoNLinput = "deno is not node";
test({ test({
name: "[EOL] Detect CR LF", name: "[EOL] Detect CR LF",
fn() { fn(): void {
assertEquals(detect(CRLFinput), EOL.CRLF); assertEquals(detect(CRLFinput), EOL.CRLF);
} }
}); });
test({ test({
name: "[EOL] Detect LF", name: "[EOL] Detect LF",
fn() { fn(): void {
assertEquals(detect(LFinput), EOL.LF); assertEquals(detect(LFinput), EOL.LF);
} }
}); });
test({ test({
name: "[EOL] Detect No New Line", name: "[EOL] Detect No New Line",
fn() { fn(): void {
assertEquals(detect(NoNLinput), null); assertEquals(detect(NoNLinput), null);
} }
}); });
test({ test({
name: "[EOL] Detect Mixed", name: "[EOL] Detect Mixed",
fn() { fn(): void {
assertEquals(detect(Mixedinput), EOL.CRLF); assertEquals(detect(Mixedinput), EOL.CRLF);
assertEquals(detect(Mixedinput2), EOL.CRLF); assertEquals(detect(Mixedinput2), EOL.CRLF);
} }
@ -40,7 +40,7 @@ test({
test({ test({
name: "[EOL] Format", name: "[EOL] Format",
fn() { fn(): void {
assertEquals(format(CRLFinput, EOL.LF), LFinput); assertEquals(format(CRLFinput, EOL.LF), LFinput);
assertEquals(format(LFinput, EOL.LF), LFinput); assertEquals(format(LFinput, EOL.LF), LFinput);
assertEquals(format(LFinput, EOL.CRLF), CRLFinput); assertEquals(format(LFinput, EOL.CRLF), CRLFinput);

View file

@ -3,8 +3,8 @@
/** Test whether or not the given path exists by checking with the file system */ /** Test whether or not the given path exists by checking with the file system */
export async function exists(filePath: string): Promise<boolean> { export async function exists(filePath: string): Promise<boolean> {
return Deno.lstat(filePath) return Deno.lstat(filePath)
.then(() => true) .then((): boolean => true)
.catch(() => false); .catch((): boolean => false);
} }
/** Test whether or not the given path exists by checking with the file system */ /** Test whether or not the given path exists by checking with the file system */

View file

@ -6,7 +6,7 @@ import * as path from "./path/mod.ts";
const testdataDir = path.resolve("fs", "testdata"); const testdataDir = path.resolve("fs", "testdata");
test(async function existsFile() { test(async function existsFile(): Promise<void> {
assertEquals( assertEquals(
await exists(path.join(testdataDir, "not_exist_file.ts")), await exists(path.join(testdataDir, "not_exist_file.ts")),
false false
@ -14,12 +14,12 @@ test(async function existsFile() {
assertEquals(await existsSync(path.join(testdataDir, "0.ts")), true); assertEquals(await existsSync(path.join(testdataDir, "0.ts")), true);
}); });
test(function existsFileSync() { test(function existsFileSync(): void {
assertEquals(existsSync(path.join(testdataDir, "not_exist_file.ts")), false); assertEquals(existsSync(path.join(testdataDir, "not_exist_file.ts")), false);
assertEquals(existsSync(path.join(testdataDir, "0.ts")), true); assertEquals(existsSync(path.join(testdataDir, "0.ts")), true);
}); });
test(async function existsDirectory() { test(async function existsDirectory(): Promise<void> {
assertEquals( assertEquals(
await exists(path.join(testdataDir, "not_exist_directory")), await exists(path.join(testdataDir, "not_exist_directory")),
false false
@ -27,7 +27,7 @@ test(async function existsDirectory() {
assertEquals(existsSync(testdataDir), true); assertEquals(existsSync(testdataDir), true);
}); });
test(function existsDirectorySync() { test(function existsDirectorySync(): void {
assertEquals( assertEquals(
existsSync(path.join(testdataDir, "not_exist_directory")), existsSync(path.join(testdataDir, "not_exist_directory")),
false false
@ -35,12 +35,12 @@ test(function existsDirectorySync() {
assertEquals(existsSync(testdataDir), true); assertEquals(existsSync(testdataDir), true);
}); });
test(function existsLinkSync() { test(function existsLinkSync(): void {
// TODO(axetroy): generate link file use Deno api instead of set a link file in repository // TODO(axetroy): generate link file use Deno api instead of set a link file in repository
assertEquals(existsSync(path.join(testdataDir, "0-link.ts")), true); assertEquals(existsSync(path.join(testdataDir, "0-link.ts")), true);
}); });
test(async function existsLink() { test(async function existsLink(): Promise<void> {
// TODO(axetroy): generate link file use Deno api instead of set a link file in repository // TODO(axetroy): generate link file use Deno api instead of set a link file in repository
assertEquals(await exists(path.join(testdataDir, "0-link.ts")), true); assertEquals(await exists(path.join(testdataDir, "0-link.ts")), true);
}); });

View file

@ -20,8 +20,9 @@ async function walkArray(
arr.push(f.path.replace(/\\/g, "/")); arr.push(f.path.replace(/\\/g, "/"));
} }
arr.sort(); arr.sort();
const arrSync = Array.from(walkSync(dirname, options), (f: FileInfo) => const arrSync = Array.from(
f.path.replace(/\\/g, "/") walkSync(dirname, options),
(f: FileInfo): string => f.path.replace(/\\/g, "/")
).sort(); ).sort();
assertEquals(arr, arrSync); assertEquals(arr, arrSync);
return arr; return arr;
@ -29,7 +30,7 @@ async function walkArray(
test({ test({
name: "glob: glob to regex", name: "glob: glob to regex",
fn() { fn(): void {
assertEquals(glob("unicorn.*") instanceof RegExp, true); assertEquals(glob("unicorn.*") instanceof RegExp, true);
assertEquals(glob("unicorn.*").test("poney.ts"), false); assertEquals(glob("unicorn.*").test("poney.ts"), false);
assertEquals(glob("unicorn.*").test("unicorn.py"), true); assertEquals(glob("unicorn.*").test("unicorn.py"), true);
@ -69,11 +70,11 @@ test({
}); });
testWalk( testWalk(
async (d: string) => { async (d: string): Promise<void> => {
await mkdir(d + "/a"); await mkdir(d + "/a");
await touch(d + "/a/x.ts"); await touch(d + "/a/x.ts");
}, },
async function globInWalk() { async function globInWalk(): Promise<void> {
const arr = await walkArray(".", { match: [glob("*.ts")] }); const arr = await walkArray(".", { match: [glob("*.ts")] });
assertEquals(arr.length, 1); assertEquals(arr.length, 1);
assertEquals(arr[0], "./a/x.ts"); assertEquals(arr[0], "./a/x.ts");
@ -81,14 +82,14 @@ testWalk(
); );
testWalk( testWalk(
async (d: string) => { async (d: string): Promise<void> => {
await mkdir(d + "/a"); await mkdir(d + "/a");
await mkdir(d + "/b"); await mkdir(d + "/b");
await touch(d + "/a/x.ts"); await touch(d + "/a/x.ts");
await touch(d + "/b/z.ts"); await touch(d + "/b/z.ts");
await touch(d + "/b/z.js"); await touch(d + "/b/z.js");
}, },
async function globInWalkWildcardFiles() { async function globInWalkWildcardFiles(): Promise<void> {
const arr = await walkArray(".", { match: [glob("*.ts")] }); const arr = await walkArray(".", { match: [glob("*.ts")] });
assertEquals(arr.length, 2); assertEquals(arr.length, 2);
assertEquals(arr[0], "./a/x.ts"); assertEquals(arr[0], "./a/x.ts");
@ -97,12 +98,12 @@ testWalk(
); );
testWalk( testWalk(
async (d: string) => { async (d: string): Promise<void> => {
await mkdir(d + "/a"); await mkdir(d + "/a");
await mkdir(d + "/a/yo"); await mkdir(d + "/a/yo");
await touch(d + "/a/yo/x.ts"); await touch(d + "/a/yo/x.ts");
}, },
async function globInWalkFolderWildcard() { async function globInWalkFolderWildcard(): Promise<void> {
const arr = await walkArray(".", { const arr = await walkArray(".", {
match: [ match: [
glob(join("a", "**", "*.ts"), { glob(join("a", "**", "*.ts"), {
@ -117,7 +118,7 @@ testWalk(
); );
testWalk( testWalk(
async (d: string) => { async (d: string): Promise<void> => {
await mkdir(d + "/a"); await mkdir(d + "/a");
await mkdir(d + "/a/unicorn"); await mkdir(d + "/a/unicorn");
await mkdir(d + "/a/deno"); await mkdir(d + "/a/deno");
@ -126,7 +127,7 @@ testWalk(
await touch(d + "/a/deno/x.ts"); await touch(d + "/a/deno/x.ts");
await touch(d + "/a/unicorn/x.ts"); await touch(d + "/a/unicorn/x.ts");
}, },
async function globInWalkFolderExtended() { async function globInWalkFolderExtended(): Promise<void> {
const arr = await walkArray(".", { const arr = await walkArray(".", {
match: [ match: [
glob(join("a", "+(raptor|deno)", "*.ts"), { glob(join("a", "+(raptor|deno)", "*.ts"), {
@ -142,12 +143,12 @@ testWalk(
); );
testWalk( testWalk(
async (d: string) => { async (d: string): Promise<void> => {
await touch(d + "/x.ts"); await touch(d + "/x.ts");
await touch(d + "/x.js"); await touch(d + "/x.js");
await touch(d + "/b.js"); await touch(d + "/b.js");
}, },
async function globInWalkWildcardExtension() { async function globInWalkWildcardExtension(): Promise<void> {
const arr = await walkArray(".", { const arr = await walkArray(".", {
match: [glob("x.*", { flags: "g", globstar: true })] match: [glob("x.*", { flags: "g", globstar: true })]
}); });

View file

@ -35,7 +35,7 @@ function matchSegments(t, pattern, ifUnix, ifWin, opts): GlobrexResult {
test({ test({
name: "globrex: standard", name: "globrex: standard",
fn() { fn(): void {
let res = globrex("*.js"); let res = globrex("*.js");
t.equal(typeof globrex, "function", "constructor is a typeof function"); t.equal(typeof globrex, "function", "constructor is a typeof function");
t.equal(res instanceof Object, true, "returns object"); t.equal(res instanceof Object, true, "returns object");
@ -45,7 +45,7 @@ test({
test({ test({
name: "globrex: Standard * matching", name: "globrex: Standard * matching",
fn() { fn(): void {
t.equal(match("*", "foo"), true, "match everything"); t.equal(match("*", "foo"), true, "match everything");
t.equal(match("*", "foo", { flags: "g" }), true, "match everything"); t.equal(match("*", "foo", { flags: "g" }), true, "match everything");
t.equal(match("f*", "foo"), true, "match the end"); t.equal(match("f*", "foo"), true, "match the end");
@ -75,7 +75,7 @@ test({
test({ test({
name: "globrex: advance * matching", name: "globrex: advance * matching",
fn() { fn(): void {
t.equal( t.equal(
match("*.min.js", "http://example.com/jquery.min.js", { match("*.min.js", "http://example.com/jquery.min.js", {
globstar: false globstar: false
@ -186,7 +186,7 @@ test({
test({ test({
name: "globrex: ? match one character, no more and no less", name: "globrex: ? match one character, no more and no less",
fn() { fn(): void {
t.equal(match("f?o", "foo", { extended: true }), true); t.equal(match("f?o", "foo", { extended: true }), true);
t.equal(match("f?o", "fooo", { extended: true }), false); t.equal(match("f?o", "fooo", { extended: true }), false);
t.equal(match("f?oo", "foo", { extended: true }), false); t.equal(match("f?oo", "foo", { extended: true }), false);
@ -226,7 +226,7 @@ test({
test({ test({
name: "globrex: [] match a character range", name: "globrex: [] match a character range",
fn() { fn(): void {
t.equal(match("fo[oz]", "foo", { extended: true }), true); t.equal(match("fo[oz]", "foo", { extended: true }), true);
t.equal(match("fo[oz]", "foz", { extended: true }), true); t.equal(match("fo[oz]", "foz", { extended: true }), true);
t.equal(match("fo[oz]", "fog", { extended: true }), false); t.equal(match("fo[oz]", "fog", { extended: true }), false);
@ -257,7 +257,7 @@ test({
test({ test({
name: "globrex: [] extended character ranges", name: "globrex: [] extended character ranges",
fn() { fn(): void {
t.equal( t.equal(
match("[[:alnum:]]/bar.txt", "a/bar.txt", { extended: true }), match("[[:alnum:]]/bar.txt", "a/bar.txt", { extended: true }),
true true
@ -315,7 +315,7 @@ test({
test({ test({
name: "globrex: {} match a choice of different substrings", name: "globrex: {} match a choice of different substrings",
fn() { fn(): void {
t.equal(match("foo{bar,baaz}", "foobaaz", { extended: true }), true); t.equal(match("foo{bar,baaz}", "foobaaz", { extended: true }), true);
t.equal(match("foo{bar,baaz}", "foobar", { extended: true }), true); t.equal(match("foo{bar,baaz}", "foobar", { extended: true }), true);
t.equal(match("foo{bar,baaz}", "foobuzz", { extended: true }), false); t.equal(match("foo{bar,baaz}", "foobuzz", { extended: true }), false);
@ -363,7 +363,7 @@ test({
test({ test({
name: "globrex: complex extended matches", name: "globrex: complex extended matches",
fn() { fn(): void {
t.equal( t.equal(
match( match(
"http://?o[oz].b*z.com/{*.js,*.html}", "http://?o[oz].b*z.com/{*.js,*.html}",
@ -455,7 +455,7 @@ test({
test({ test({
name: "globrex: standard globstar", name: "globrex: standard globstar",
fn() { fn(): void {
const tester = (globstar): void => { const tester = (globstar): void => {
t.equal( t.equal(
match( match(
@ -490,7 +490,7 @@ test({
test({ test({
name: "globrex: remaining chars should match themself", name: "globrex: remaining chars should match themself",
fn() { fn(): void {
const tester = (globstar): void => { const tester = (globstar): void => {
const testExtStr = "\\/$^+.()=!|,.*"; const testExtStr = "\\/$^+.()=!|,.*";
t.equal(match(testExtStr, testExtStr, { extended: true }), true); t.equal(match(testExtStr, testExtStr, { extended: true }), true);
@ -507,7 +507,7 @@ test({
test({ test({
name: "globrex: globstar advance testing", name: "globrex: globstar advance testing",
fn() { fn(): void {
t.equal(match("/foo/*", "/foo/bar.txt", { globstar: true }), true); t.equal(match("/foo/*", "/foo/bar.txt", { globstar: true }), true);
t.equal(match("/foo/**", "/foo/bar.txt", { globstar: true }), true); t.equal(match("/foo/**", "/foo/bar.txt", { globstar: true }), true);
t.equal(match("/foo/**", "/foo/bar/baz.txt", { globstar: true }), true); t.equal(match("/foo/**", "/foo/bar/baz.txt", { globstar: true }), true);
@ -647,7 +647,7 @@ test({
test({ test({
name: "globrex: extended extglob ?", name: "globrex: extended extglob ?",
fn() { fn(): void {
t.equal(match("(foo).txt", "(foo).txt", { extended: true }), true); t.equal(match("(foo).txt", "(foo).txt", { extended: true }), true);
t.equal(match("?(foo).txt", "foo.txt", { extended: true }), true); t.equal(match("?(foo).txt", "foo.txt", { extended: true }), true);
t.equal(match("?(foo).txt", ".txt", { extended: true }), true); t.equal(match("?(foo).txt", ".txt", { extended: true }), true);
@ -700,7 +700,7 @@ test({
test({ test({
name: "globrex: extended extglob *", name: "globrex: extended extglob *",
fn() { fn(): void {
t.equal(match("*(foo).txt", "foo.txt", { extended: true }), true); t.equal(match("*(foo).txt", "foo.txt", { extended: true }), true);
t.equal(match("*foo.txt", "bofoo.txt", { extended: true }), true); t.equal(match("*foo.txt", "bofoo.txt", { extended: true }), true);
t.equal(match("*(foo).txt", "foofoo.txt", { extended: true }), true); t.equal(match("*(foo).txt", "foofoo.txt", { extended: true }), true);
@ -737,7 +737,7 @@ test({
test({ test({
name: "globrex: extended extglob +", name: "globrex: extended extglob +",
fn() { fn(): void {
t.equal(match("+(foo).txt", "foo.txt", { extended: true }), true); t.equal(match("+(foo).txt", "foo.txt", { extended: true }), true);
t.equal(match("+foo.txt", "+foo.txt", { extended: true }), true); t.equal(match("+foo.txt", "+foo.txt", { extended: true }), true);
t.equal(match("+(foo).txt", ".txt", { extended: true }), false); t.equal(match("+(foo).txt", ".txt", { extended: true }), false);
@ -747,7 +747,7 @@ test({
test({ test({
name: "globrex: extended extglob @", name: "globrex: extended extglob @",
fn() { fn(): void {
t.equal(match("@(foo).txt", "foo.txt", { extended: true }), true); t.equal(match("@(foo).txt", "foo.txt", { extended: true }), true);
t.equal(match("@foo.txt", "@foo.txt", { extended: true }), true); t.equal(match("@foo.txt", "@foo.txt", { extended: true }), true);
t.equal(match("@(foo|baz)bar.txt", "foobar.txt", { extended: true }), true); t.equal(match("@(foo|baz)bar.txt", "foobar.txt", { extended: true }), true);
@ -768,7 +768,7 @@ test({
test({ test({
name: "globrex: extended extglob !", name: "globrex: extended extglob !",
fn() { fn(): void {
t.equal(match("!(boo).txt", "foo.txt", { extended: true }), true); t.equal(match("!(boo).txt", "foo.txt", { extended: true }), true);
t.equal(match("!(foo|baz)bar.txt", "buzbar.txt", { extended: true }), true); t.equal(match("!(foo|baz)bar.txt", "buzbar.txt", { extended: true }), true);
t.equal(match("!bar.txt", "!bar.txt", { extended: true }), true); t.equal(match("!bar.txt", "!bar.txt", { extended: true }), true);
@ -785,7 +785,7 @@ test({
test({ test({
name: "globrex: strict", name: "globrex: strict",
fn() { fn(): void {
t.equal(match("foo//bar.txt", "foo/bar.txt"), true); t.equal(match("foo//bar.txt", "foo/bar.txt"), true);
t.equal(match("foo///bar.txt", "foo/bar.txt"), true); t.equal(match("foo///bar.txt", "foo/bar.txt"), true);
t.equal(match("foo///bar.txt", "foo/bar.txt", { strict: true }), false); t.equal(match("foo///bar.txt", "foo/bar.txt", { strict: true }), false);
@ -794,7 +794,7 @@ test({
test({ test({
name: "globrex: filepath path-regex", name: "globrex: filepath path-regex",
fn() { fn(): void {
let opts = { extended: true, filepath: true, globstar: false }, let opts = { extended: true, filepath: true, globstar: false },
res, res,
pattern; pattern;
@ -847,7 +847,7 @@ test({
test({ test({
name: "globrex: filepath path segments", name: "globrex: filepath path segments",
fn() { fn(): void {
let opts = { extended: true }, let opts = { extended: true },
win, win,
unix; unix;
@ -895,7 +895,7 @@ test({
test({ test({
name: "globrex: stress testing", name: "globrex: stress testing",
fn() { fn(): void {
t.equal( t.equal(
match("**/*/?yfile.{md,js,txt}", "foo/bar/baz/myfile.md", { match("**/*/?yfile.{md,js,txt}", "foo/bar/baz/myfile.md", {
extended: true extended: true

View file

@ -13,16 +13,18 @@ import * as path from "./path/mod.ts";
const testdataDir = path.resolve("fs", "testdata"); const testdataDir = path.resolve("fs", "testdata");
test(async function moveDirectoryIfSrcNotExists() { test(async function moveDirectoryIfSrcNotExists(): Promise<void> {
const srcDir = path.join(testdataDir, "move_test_src_1"); const srcDir = path.join(testdataDir, "move_test_src_1");
const destDir = path.join(testdataDir, "move_test_dest_1"); const destDir = path.join(testdataDir, "move_test_dest_1");
// if src directory not exist // if src directory not exist
await assertThrowsAsync(async () => { await assertThrowsAsync(
async (): Promise<void> => {
await move(srcDir, destDir); await move(srcDir, destDir);
}); }
);
}); });
test(async function moveDirectoryIfDestNotExists() { test(async function moveDirectoryIfDestNotExists(): Promise<void> {
const srcDir = path.join(testdataDir, "move_test_src_2"); const srcDir = path.join(testdataDir, "move_test_src_2");
const destDir = path.join(testdataDir, "move_test_dest_2"); const destDir = path.join(testdataDir, "move_test_dest_2");
@ -30,7 +32,7 @@ test(async function moveDirectoryIfDestNotExists() {
// if dest directory not exist // if dest directory not exist
await assertThrowsAsync( await assertThrowsAsync(
async () => { async (): Promise<void> => {
await move(srcDir, destDir); await move(srcDir, destDir);
throw new Error("should not throw error"); throw new Error("should not throw error");
}, },
@ -41,17 +43,19 @@ test(async function moveDirectoryIfDestNotExists() {
await Deno.remove(destDir); await Deno.remove(destDir);
}); });
test(async function moveFileIfSrcNotExists() { test(async function moveFileIfSrcNotExists(): Promise<void> {
const srcFile = path.join(testdataDir, "move_test_src_3", "test.txt"); const srcFile = path.join(testdataDir, "move_test_src_3", "test.txt");
const destFile = path.join(testdataDir, "move_test_dest_3", "test.txt"); const destFile = path.join(testdataDir, "move_test_dest_3", "test.txt");
// if src directory not exist // if src directory not exist
await assertThrowsAsync(async () => { await assertThrowsAsync(
async (): Promise<void> => {
await move(srcFile, destFile); await move(srcFile, destFile);
}); }
);
}); });
test(async function moveFileIfDestExists() { test(async function moveFileIfDestExists(): Promise<void> {
const srcDir = path.join(testdataDir, "move_test_src_4"); const srcDir = path.join(testdataDir, "move_test_src_4");
const destDir = path.join(testdataDir, "move_test_dest_4"); const destDir = path.join(testdataDir, "move_test_dest_4");
const srcFile = path.join(srcDir, "test.txt"); const srcFile = path.join(srcDir, "test.txt");
@ -74,7 +78,7 @@ test(async function moveFileIfDestExists() {
// move it without override // move it without override
await assertThrowsAsync( await assertThrowsAsync(
async () => { async (): Promise<void> => {
await move(srcFile, destFile); await move(srcFile, destFile);
}, },
Error, Error,
@ -83,7 +87,7 @@ test(async function moveFileIfDestExists() {
// move again with overwrite // move again with overwrite
await assertThrowsAsync( await assertThrowsAsync(
async () => { async (): Promise<void> => {
await move(srcFile, destFile, { overwrite: true }); await move(srcFile, destFile, { overwrite: true });
throw new Error("should not throw error"); throw new Error("should not throw error");
}, },
@ -101,7 +105,7 @@ test(async function moveFileIfDestExists() {
]); ]);
}); });
test(async function moveDirectory() { test(async function moveDirectory(): Promise<void> {
const srcDir = path.join(testdataDir, "move_test_src_5"); const srcDir = path.join(testdataDir, "move_test_src_5");
const destDir = path.join(testdataDir, "move_test_dest_5"); const destDir = path.join(testdataDir, "move_test_dest_5");
const srcFile = path.join(srcDir, "test.txt"); const srcFile = path.join(srcDir, "test.txt");
@ -126,7 +130,9 @@ test(async function moveDirectory() {
await Deno.remove(destDir, { recursive: true }); await Deno.remove(destDir, { recursive: true });
}); });
test(async function moveIfSrcAndDestDirectoryExistsAndOverwrite() { test(async function moveIfSrcAndDestDirectoryExistsAndOverwrite(): Promise<
void
> {
const srcDir = path.join(testdataDir, "move_test_src_6"); const srcDir = path.join(testdataDir, "move_test_src_6");
const destDir = path.join(testdataDir, "move_test_dest_6"); const destDir = path.join(testdataDir, "move_test_dest_6");
const srcFile = path.join(srcDir, "test.txt"); const srcFile = path.join(srcDir, "test.txt");
@ -156,14 +162,14 @@ test(async function moveIfSrcAndDestDirectoryExistsAndOverwrite() {
await Deno.remove(destDir, { recursive: true }); await Deno.remove(destDir, { recursive: true });
}); });
test(async function moveIntoSubDir() { test(async function moveIntoSubDir(): Promise<void> {
const srcDir = path.join(testdataDir, "move_test_src_7"); const srcDir = path.join(testdataDir, "move_test_src_7");
const destDir = path.join(srcDir, "nest"); const destDir = path.join(srcDir, "nest");
await ensureDir(destDir); await ensureDir(destDir);
await assertThrowsAsync( await assertThrowsAsync(
async () => { async (): Promise<void> => {
await move(srcDir, destDir); await move(srcDir, destDir);
}, },
Error, Error,
@ -172,16 +178,18 @@ test(async function moveIntoSubDir() {
await Deno.remove(srcDir, { recursive: true }); await Deno.remove(srcDir, { recursive: true });
}); });
test(function moveSyncDirectoryIfSrcNotExists() { test(function moveSyncDirectoryIfSrcNotExists(): void {
const srcDir = path.join(testdataDir, "move_sync_test_src_1"); const srcDir = path.join(testdataDir, "move_sync_test_src_1");
const destDir = path.join(testdataDir, "move_sync_test_dest_1"); const destDir = path.join(testdataDir, "move_sync_test_dest_1");
// if src directory not exist // if src directory not exist
assertThrows(() => { assertThrows(
(): void => {
moveSync(srcDir, destDir); moveSync(srcDir, destDir);
}); }
);
}); });
test(function moveSyncDirectoryIfDestNotExists() { test(function moveSyncDirectoryIfDestNotExists(): void {
const srcDir = path.join(testdataDir, "move_sync_test_src_2"); const srcDir = path.join(testdataDir, "move_sync_test_src_2");
const destDir = path.join(testdataDir, "move_sync_test_dest_2"); const destDir = path.join(testdataDir, "move_sync_test_dest_2");
@ -189,7 +197,7 @@ test(function moveSyncDirectoryIfDestNotExists() {
// if dest directory not exist // if dest directory not exist
assertThrows( assertThrows(
() => { (): void => {
moveSync(srcDir, destDir); moveSync(srcDir, destDir);
throw new Error("should not throw error"); throw new Error("should not throw error");
}, },
@ -200,17 +208,19 @@ test(function moveSyncDirectoryIfDestNotExists() {
Deno.removeSync(destDir); Deno.removeSync(destDir);
}); });
test(function moveSyncFileIfSrcNotExists() { test(function moveSyncFileIfSrcNotExists(): void {
const srcFile = path.join(testdataDir, "move_sync_test_src_3", "test.txt"); const srcFile = path.join(testdataDir, "move_sync_test_src_3", "test.txt");
const destFile = path.join(testdataDir, "move_sync_test_dest_3", "test.txt"); const destFile = path.join(testdataDir, "move_sync_test_dest_3", "test.txt");
// if src directory not exist // if src directory not exist
assertThrows(() => { assertThrows(
(): void => {
moveSync(srcFile, destFile); moveSync(srcFile, destFile);
}); }
);
}); });
test(function moveSyncFileIfDestExists() { test(function moveSyncFileIfDestExists(): void {
const srcDir = path.join(testdataDir, "move_sync_test_src_4"); const srcDir = path.join(testdataDir, "move_sync_test_src_4");
const destDir = path.join(testdataDir, "move_sync_test_dest_4"); const destDir = path.join(testdataDir, "move_sync_test_dest_4");
const srcFile = path.join(srcDir, "test.txt"); const srcFile = path.join(srcDir, "test.txt");
@ -232,7 +242,7 @@ test(function moveSyncFileIfDestExists() {
// move it without override // move it without override
assertThrows( assertThrows(
() => { (): void => {
moveSync(srcFile, destFile); moveSync(srcFile, destFile);
}, },
Error, Error,
@ -241,7 +251,7 @@ test(function moveSyncFileIfDestExists() {
// move again with overwrite // move again with overwrite
assertThrows( assertThrows(
() => { (): void => {
moveSync(srcFile, destFile, { overwrite: true }); moveSync(srcFile, destFile, { overwrite: true });
throw new Error("should not throw error"); throw new Error("should not throw error");
}, },
@ -257,7 +267,7 @@ test(function moveSyncFileIfDestExists() {
Deno.removeSync(destDir, { recursive: true }); Deno.removeSync(destDir, { recursive: true });
}); });
test(function moveSyncDirectory() { test(function moveSyncDirectory(): void {
const srcDir = path.join(testdataDir, "move_sync_test_src_5"); const srcDir = path.join(testdataDir, "move_sync_test_src_5");
const destDir = path.join(testdataDir, "move_sync_test_dest_5"); const destDir = path.join(testdataDir, "move_sync_test_dest_5");
const srcFile = path.join(srcDir, "test.txt"); const srcFile = path.join(srcDir, "test.txt");
@ -280,7 +290,7 @@ test(function moveSyncDirectory() {
Deno.removeSync(destDir, { recursive: true }); Deno.removeSync(destDir, { recursive: true });
}); });
test(function moveSyncIfSrcAndDestDirectoryExistsAndOverwrite() { test(function moveSyncIfSrcAndDestDirectoryExistsAndOverwrite(): void {
const srcDir = path.join(testdataDir, "move_sync_test_src_6"); const srcDir = path.join(testdataDir, "move_sync_test_src_6");
const destDir = path.join(testdataDir, "move_sync_test_dest_6"); const destDir = path.join(testdataDir, "move_sync_test_dest_6");
const srcFile = path.join(srcDir, "test.txt"); const srcFile = path.join(srcDir, "test.txt");
@ -307,14 +317,14 @@ test(function moveSyncIfSrcAndDestDirectoryExistsAndOverwrite() {
Deno.removeSync(destDir, { recursive: true }); Deno.removeSync(destDir, { recursive: true });
}); });
test(function moveSyncIntoSubDir() { test(function moveSyncIntoSubDir(): void {
const srcDir = path.join(testdataDir, "move_sync_test_src_7"); const srcDir = path.join(testdataDir, "move_sync_test_src_7");
const destDir = path.join(srcDir, "nest"); const destDir = path.join(srcDir, "nest");
ensureDirSync(destDir); ensureDirSync(destDir);
assertThrows( assertThrows(
() => { (): void => {
moveSync(srcDir, destDir); moveSync(srcDir, destDir);
}, },
Error, Error,

View file

@ -5,14 +5,14 @@ import * as path from "./path/mod.ts";
const testdataDir = path.resolve("fs", "testdata"); const testdataDir = path.resolve("fs", "testdata");
test(function testReadFileSync() { test(function testReadFileSync(): void {
const jsonFile = path.join(testdataDir, "json_valid_obj.json"); const jsonFile = path.join(testdataDir, "json_valid_obj.json");
const strFile = readFileStrSync(jsonFile); const strFile = readFileStrSync(jsonFile);
assert(typeof strFile === "string"); assert(typeof strFile === "string");
assert(strFile.length > 0); assert(strFile.length > 0);
}); });
test(async function testReadFile() { test(async function testReadFile(): Promise<void> {
const jsonFile = path.join(testdataDir, "json_valid_obj.json"); const jsonFile = path.join(testdataDir, "json_valid_obj.json");
const strFile = await readFileStr(jsonFile); const strFile = await readFileStr(jsonFile);
assert(typeof strFile === "string"); assert(typeof strFile === "string");

View file

@ -1,7 +1,7 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
/** Reads a JSON file and then parses it into an object */ /** Reads a JSON file and then parses it into an object */
export async function readJson(filePath: string): Promise<any> { export async function readJson(filePath: string): Promise<unknown> {
const decoder = new TextDecoder("utf-8"); const decoder = new TextDecoder("utf-8");
const content = decoder.decode(await Deno.readFile(filePath)); const content = decoder.decode(await Deno.readFile(filePath));
@ -15,7 +15,7 @@ export async function readJson(filePath: string): Promise<any> {
} }
/** Reads a JSON file and then parses it into an object */ /** Reads a JSON file and then parses it into an object */
export function readJsonSync(filePath: string): any { export function readJsonSync(filePath: string): unknown {
const decoder = new TextDecoder("utf-8"); const decoder = new TextDecoder("utf-8");
const content = decoder.decode(Deno.readFileSync(filePath)); const content = decoder.decode(Deno.readFileSync(filePath));

View file

@ -10,31 +10,37 @@ import * as path from "./path/mod.ts";
const testdataDir = path.resolve("fs", "testdata"); const testdataDir = path.resolve("fs", "testdata");
test(async function readJsonFileNotExists() { test(async function readJsonFileNotExists(): Promise<void> {
const emptyJsonFile = path.join(testdataDir, "json_not_exists.json"); const emptyJsonFile = path.join(testdataDir, "json_not_exists.json");
await assertThrowsAsync(async () => { await assertThrowsAsync(
async (): Promise<void> => {
await readJson(emptyJsonFile); await readJson(emptyJsonFile);
}); }
);
}); });
test(async function readEmptyJsonFile() { test(async function readEmptyJsonFile(): Promise<void> {
const emptyJsonFile = path.join(testdataDir, "json_empty.json"); const emptyJsonFile = path.join(testdataDir, "json_empty.json");
await assertThrowsAsync(async () => { await assertThrowsAsync(
async (): Promise<void> => {
await readJson(emptyJsonFile); await readJson(emptyJsonFile);
}); }
);
}); });
test(async function readInvalidJsonFile() { test(async function readInvalidJsonFile(): Promise<void> {
const invalidJsonFile = path.join(testdataDir, "json_invalid.json"); const invalidJsonFile = path.join(testdataDir, "json_invalid.json");
await assertThrowsAsync(async () => { await assertThrowsAsync(
async (): Promise<void> => {
await readJson(invalidJsonFile); await readJson(invalidJsonFile);
}); }
);
}); });
test(async function readValidArrayJsonFile() { test(async function readValidArrayJsonFile(): Promise<void> {
const invalidJsonFile = path.join(testdataDir, "json_valid_array.json"); const invalidJsonFile = path.join(testdataDir, "json_valid_array.json");
const json = await readJson(invalidJsonFile); const json = await readJson(invalidJsonFile);
@ -42,7 +48,7 @@ test(async function readValidArrayJsonFile() {
assertEquals(json, ["1", "2", "3"]); assertEquals(json, ["1", "2", "3"]);
}); });
test(async function readValidObjJsonFile() { test(async function readValidObjJsonFile(): Promise<void> {
const invalidJsonFile = path.join(testdataDir, "json_valid_obj.json"); const invalidJsonFile = path.join(testdataDir, "json_valid_obj.json");
const json = await readJson(invalidJsonFile); const json = await readJson(invalidJsonFile);
@ -50,37 +56,43 @@ test(async function readValidObjJsonFile() {
assertEquals(json, { key1: "value1", key2: "value2" }); assertEquals(json, { key1: "value1", key2: "value2" });
}); });
test(async function readValidObjJsonFileWithRelativePath() { test(async function readValidObjJsonFileWithRelativePath(): Promise<void> {
const json = await readJson("./fs/testdata/json_valid_obj.json"); const json = await readJson("./fs/testdata/json_valid_obj.json");
assertEquals(json, { key1: "value1", key2: "value2" }); assertEquals(json, { key1: "value1", key2: "value2" });
}); });
test(function readJsonFileNotExistsSync() { test(function readJsonFileNotExistsSync(): void {
const emptyJsonFile = path.join(testdataDir, "json_not_exists.json"); const emptyJsonFile = path.join(testdataDir, "json_not_exists.json");
assertThrows(() => { assertThrows(
(): void => {
readJsonSync(emptyJsonFile); readJsonSync(emptyJsonFile);
}); }
);
}); });
test(function readEmptyJsonFileSync() { test(function readEmptyJsonFileSync(): void {
const emptyJsonFile = path.join(testdataDir, "json_empty.json"); const emptyJsonFile = path.join(testdataDir, "json_empty.json");
assertThrows(() => { assertThrows(
(): void => {
readJsonSync(emptyJsonFile); readJsonSync(emptyJsonFile);
}); }
);
}); });
test(function readInvalidJsonFile() { test(function readInvalidJsonFile(): void {
const invalidJsonFile = path.join(testdataDir, "json_invalid.json"); const invalidJsonFile = path.join(testdataDir, "json_invalid.json");
assertThrows(() => { assertThrows(
(): void => {
readJsonSync(invalidJsonFile); readJsonSync(invalidJsonFile);
}); }
);
}); });
test(function readValidArrayJsonFileSync() { test(function readValidArrayJsonFileSync(): void {
const invalidJsonFile = path.join(testdataDir, "json_valid_array.json"); const invalidJsonFile = path.join(testdataDir, "json_valid_array.json");
const json = readJsonSync(invalidJsonFile); const json = readJsonSync(invalidJsonFile);
@ -88,7 +100,7 @@ test(function readValidArrayJsonFileSync() {
assertEquals(json, ["1", "2", "3"]); assertEquals(json, ["1", "2", "3"]);
}); });
test(function readValidObjJsonFileSync() { test(function readValidObjJsonFileSync(): void {
const invalidJsonFile = path.join(testdataDir, "json_valid_obj.json"); const invalidJsonFile = path.join(testdataDir, "json_valid_obj.json");
const json = readJsonSync(invalidJsonFile); const json = readJsonSync(invalidJsonFile);
@ -96,7 +108,7 @@ test(function readValidObjJsonFileSync() {
assertEquals(json, { key1: "value1", key2: "value2" }); assertEquals(json, { key1: "value1", key2: "value2" });
}); });
test(function readValidObjJsonFileSyncWithRelativePath() { test(function readValidObjJsonFileSyncWithRelativePath(): void {
const json = readJsonSync("./fs/testdata/json_valid_obj.json"); const json = readJsonSync("./fs/testdata/json_valid_obj.json");
assertEquals(json, { key1: "value1", key2: "value2" }); assertEquals(json, { key1: "value1", key2: "value2" });

View file

@ -17,7 +17,7 @@ export function isSubdir(
const srcArray = src.split(sep); const srcArray = src.split(sep);
const destArray = dest.split(sep); const destArray = dest.split(sep);
return srcArray.reduce((acc: boolean, current, i) => { return srcArray.reduce((acc, current, i): boolean => {
return acc && destArray[i] === current; return acc && destArray[i] === current;
}, true); }, true);
} }

View file

@ -9,7 +9,7 @@ import { ensureDirSync } from "./ensure_dir.ts";
const testdataDir = path.resolve("fs", "testdata"); const testdataDir = path.resolve("fs", "testdata");
test(function _isSubdir() { test(function _isSubdir(): void {
const pairs = [ const pairs = [
["", "", false, path.posix.sep], ["", "", false, path.posix.sep],
["/first/second", "/first", false, path.posix.sep], ["/first/second", "/first", false, path.posix.sep],
@ -21,7 +21,7 @@ test(function _isSubdir() {
["c:\\first", "c:\\first\\second", true, path.win32.sep] ["c:\\first", "c:\\first\\second", true, path.win32.sep]
]; ];
pairs.forEach(function(p) { pairs.forEach(function(p): void {
const src = p[0] as string; const src = p[0] as string;
const dest = p[1] as string; const dest = p[1] as string;
const expected = p[2] as boolean; const expected = p[2] as boolean;
@ -34,13 +34,13 @@ test(function _isSubdir() {
}); });
}); });
test(function _getFileInfoType() { test(function _getFileInfoType(): void {
const pairs = [ const pairs = [
[path.join(testdataDir, "file_type_1"), "file"], [path.join(testdataDir, "file_type_1"), "file"],
[path.join(testdataDir, "file_type_dir_1"), "dir"] [path.join(testdataDir, "file_type_dir_1"), "dir"]
]; ];
pairs.forEach(function(p) { pairs.forEach(function(p): void {
const filePath = p[0] as string; const filePath = p[0] as string;
const type = p[1] as PathType; const type = p[1] as PathType;
switch (type) { switch (type) {

View file

@ -14,15 +14,20 @@ function patternTest(patterns: RegExp[], path: string): boolean {
// Forced to reset last index on regex while iterating for have // Forced to reset last index on regex while iterating for have
// consistent results. // consistent results.
// See: https://stackoverflow.com/a/1520853 // See: https://stackoverflow.com/a/1520853
return patterns.some(pattern => { return patterns.some(
(pattern): boolean => {
let r = pattern.test(path); let r = pattern.test(path);
pattern.lastIndex = 0; pattern.lastIndex = 0;
return r; return r;
}); }
);
} }
function include(f: FileInfo, options: WalkOptions): boolean { function include(f: FileInfo, options: WalkOptions): boolean {
if (options.exts && !options.exts.some(ext => f.path.endsWith(ext))) { if (
options.exts &&
!options.exts.some((ext): boolean => f.path.endsWith(ext))
) {
return false; return false;
} }
if (options.match && !patternTest(options.match, f.path)) { if (options.match && !patternTest(options.match, f.path)) {

View file

@ -35,8 +35,9 @@ async function walkArray(
arr.push(f.path.replace(/\\/g, "/")); arr.push(f.path.replace(/\\/g, "/"));
} }
arr.sort(); arr.sort();
const arrSync = Array.from(walkSync(dirname, options), (f: FileInfo) => const arrSync = Array.from(
f.path.replace(/\\/g, "/") walkSync(dirname, options),
(f: FileInfo): string => f.path.replace(/\\/g, "/")
).sort(); ).sort();
assertEquals(arr, arrSync); assertEquals(arr, arrSync);
return arr; return arr;
@ -46,25 +47,25 @@ async function touch(path: string): Promise<void> {
await open(path, "w"); await open(path, "w");
} }
function assertReady(expectedLength: number): void { function assertReady(expectedLength: number): void {
const arr = Array.from(walkSync(), (f: FileInfo) => f.path); const arr = Array.from(walkSync(), (f: FileInfo): string => f.path);
assertEquals(arr.length, expectedLength); assertEquals(arr.length, expectedLength);
} }
testWalk( testWalk(
async (d: string) => { async (d: string): Promise<void> => {
await mkdir(d + "/empty"); await mkdir(d + "/empty");
}, },
async function emptyDir() { async function emptyDir(): Promise<void> {
const arr = await walkArray(); const arr = await walkArray();
assertEquals(arr.length, 0); assertEquals(arr.length, 0);
} }
); );
testWalk( testWalk(
async (d: string) => { async (d: string): Promise<void> => {
await touch(d + "/x"); await touch(d + "/x");
}, },
async function singleFile() { async function singleFile(): Promise<void> {
const arr = await walkArray(); const arr = await walkArray();
assertEquals(arr.length, 1); assertEquals(arr.length, 1);
assertEquals(arr[0], "./x"); assertEquals(arr[0], "./x");
@ -72,10 +73,10 @@ testWalk(
); );
testWalk( testWalk(
async (d: string) => { async (d: string): Promise<void> => {
await touch(d + "/x"); await touch(d + "/x");
}, },
async function iteratable() { async function iteratable(): Promise<void> {
let count = 0; let count = 0;
for (const _ of walkSync()) { for (const _ of walkSync()) {
count += 1; count += 1;
@ -89,11 +90,11 @@ testWalk(
); );
testWalk( testWalk(
async (d: string) => { async (d: string): Promise<void> => {
await mkdir(d + "/a"); await mkdir(d + "/a");
await touch(d + "/a/x"); await touch(d + "/a/x");
}, },
async function nestedSingleFile() { async function nestedSingleFile(): Promise<void> {
const arr = await walkArray(); const arr = await walkArray();
assertEquals(arr.length, 1); assertEquals(arr.length, 1);
assertEquals(arr[0], "./a/x"); assertEquals(arr[0], "./a/x");
@ -101,11 +102,11 @@ testWalk(
); );
testWalk( testWalk(
async (d: string) => { async (d: string): Promise<void> => {
await mkdir(d + "/a/b/c/d", true); await mkdir(d + "/a/b/c/d", true);
await touch(d + "/a/b/c/d/x"); await touch(d + "/a/b/c/d/x");
}, },
async function depth() { async function depth(): Promise<void> {
assertReady(1); assertReady(1);
const arr3 = await walkArray(".", { maxDepth: 3 }); const arr3 = await walkArray(".", { maxDepth: 3 });
assertEquals(arr3.length, 0); assertEquals(arr3.length, 0);
@ -116,11 +117,11 @@ testWalk(
); );
testWalk( testWalk(
async (d: string) => { async (d: string): Promise<void> => {
await touch(d + "/x.ts"); await touch(d + "/x.ts");
await touch(d + "/y.rs"); await touch(d + "/y.rs");
}, },
async function ext() { async function ext(): Promise<void> {
assertReady(2); assertReady(2);
const arr = await walkArray(".", { exts: [".ts"] }); const arr = await walkArray(".", { exts: [".ts"] });
assertEquals(arr.length, 1); assertEquals(arr.length, 1);
@ -129,12 +130,12 @@ testWalk(
); );
testWalk( testWalk(
async (d: string) => { async (d: string): Promise<void> => {
await touch(d + "/x.ts"); await touch(d + "/x.ts");
await touch(d + "/y.rs"); await touch(d + "/y.rs");
await touch(d + "/z.py"); await touch(d + "/z.py");
}, },
async function extAny() { async function extAny(): Promise<void> {
assertReady(3); assertReady(3);
const arr = await walkArray(".", { exts: [".rs", ".ts"] }); const arr = await walkArray(".", { exts: [".rs", ".ts"] });
assertEquals(arr.length, 2); assertEquals(arr.length, 2);
@ -144,11 +145,11 @@ testWalk(
); );
testWalk( testWalk(
async (d: string) => { async (d: string): Promise<void> => {
await touch(d + "/x"); await touch(d + "/x");
await touch(d + "/y"); await touch(d + "/y");
}, },
async function match() { async function match(): Promise<void> {
assertReady(2); assertReady(2);
const arr = await walkArray(".", { match: [/x/] }); const arr = await walkArray(".", { match: [/x/] });
assertEquals(arr.length, 1); assertEquals(arr.length, 1);
@ -157,12 +158,12 @@ testWalk(
); );
testWalk( testWalk(
async (d: string) => { async (d: string): Promise<void> => {
await touch(d + "/x"); await touch(d + "/x");
await touch(d + "/y"); await touch(d + "/y");
await touch(d + "/z"); await touch(d + "/z");
}, },
async function matchAny() { async function matchAny(): Promise<void> {
assertReady(3); assertReady(3);
const arr = await walkArray(".", { match: [/x/, /y/] }); const arr = await walkArray(".", { match: [/x/, /y/] });
assertEquals(arr.length, 2); assertEquals(arr.length, 2);
@ -172,11 +173,11 @@ testWalk(
); );
testWalk( testWalk(
async (d: string) => { async (d: string): Promise<void> => {
await touch(d + "/x"); await touch(d + "/x");
await touch(d + "/y"); await touch(d + "/y");
}, },
async function skip() { async function skip(): Promise<void> {
assertReady(2); assertReady(2);
const arr = await walkArray(".", { skip: [/x/] }); const arr = await walkArray(".", { skip: [/x/] });
assertEquals(arr.length, 1); assertEquals(arr.length, 1);
@ -185,12 +186,12 @@ testWalk(
); );
testWalk( testWalk(
async (d: string) => { async (d: string): Promise<void> => {
await touch(d + "/x"); await touch(d + "/x");
await touch(d + "/y"); await touch(d + "/y");
await touch(d + "/z"); await touch(d + "/z");
}, },
async function skipAny() { async function skipAny(): Promise<void> {
assertReady(3); assertReady(3);
const arr = await walkArray(".", { skip: [/x/, /y/] }); const arr = await walkArray(".", { skip: [/x/, /y/] });
assertEquals(arr.length, 1); assertEquals(arr.length, 1);
@ -199,14 +200,14 @@ testWalk(
); );
testWalk( testWalk(
async (d: string) => { async (d: string): Promise<void> => {
await mkdir(d + "/a"); await mkdir(d + "/a");
await mkdir(d + "/b"); await mkdir(d + "/b");
await touch(d + "/a/x"); await touch(d + "/a/x");
await touch(d + "/a/y"); await touch(d + "/a/y");
await touch(d + "/b/z"); await touch(d + "/b/z");
}, },
async function subDir() { async function subDir(): Promise<void> {
assertReady(3); assertReady(3);
const arr = await walkArray("b"); const arr = await walkArray("b");
assertEquals(arr.length, 1); assertEquals(arr.length, 1);
@ -214,18 +215,21 @@ testWalk(
} }
); );
testWalk(async (_d: string) => {}, async function onError() { testWalk(
async (_d: string): Promise<void> => {},
async function onError(): Promise<void> {
assertReady(0); assertReady(0);
const ignored = await walkArray("missing"); const ignored = await walkArray("missing");
assertEquals(ignored.length, 0); assertEquals(ignored.length, 0);
let errors = 0; let errors = 0;
await walkArray("missing", { onError: _e => (errors += 1) }); await walkArray("missing", { onError: (_e): number => (errors += 1) });
// It's 2 since walkArray iterates over both sync and async. // It's 2 since walkArray iterates over both sync and async.
assertEquals(errors, 2); assertEquals(errors, 2);
}); }
);
testWalk( testWalk(
async (d: string) => { async (d: string): Promise<void> => {
await mkdir(d + "/a"); await mkdir(d + "/a");
await mkdir(d + "/b"); await mkdir(d + "/b");
await touch(d + "/a/x"); await touch(d + "/a/x");
@ -238,7 +242,7 @@ testWalk(
assert(err.message, "Not implemented"); assert(err.message, "Not implemented");
} }
}, },
async function symlink() { async function symlink(): Promise<void> {
// symlink is not yet implemented on Windows. // symlink is not yet implemented on Windows.
if (isWindows) { if (isWindows) {
return; return;
@ -251,6 +255,6 @@ testWalk(
const arr = await walkArray("a", { followSymlinks: true }); const arr = await walkArray("a", { followSymlinks: true });
assertEquals(arr.length, 3); assertEquals(arr.length, 3);
assert(arr.some(f => f.endsWith("/b/z"))); assert(arr.some((f): boolean => f.endsWith("/b/z")));
} }
); );

View file

@ -5,7 +5,7 @@ import * as path from "./path/mod.ts";
const testdataDir = path.resolve("fs", "testdata"); const testdataDir = path.resolve("fs", "testdata");
test(function testReadFileSync() { test(function testReadFileSync(): void {
const jsonFile = path.join(testdataDir, "write_file_1.json"); const jsonFile = path.join(testdataDir, "write_file_1.json");
const content = "write_file_str_test"; const content = "write_file_str_test";
writeFileStrSync(jsonFile, content); writeFileStrSync(jsonFile, content);
@ -21,7 +21,7 @@ test(function testReadFileSync() {
assertEquals(content, result); assertEquals(content, result);
}); });
test(async function testReadFile() { test(async function testReadFile(): Promise<void> {
const jsonFile = path.join(testdataDir, "write_file_2.json"); const jsonFile = path.join(testdataDir, "write_file_2.json");
const content = "write_file_str_test"; const content = "write_file_str_test";
await writeFileStr(jsonFile, content); await writeFileStr(jsonFile, content);

View file

@ -10,11 +10,11 @@ import * as path from "./path/mod.ts";
const testdataDir = path.resolve("fs", "testdata"); const testdataDir = path.resolve("fs", "testdata");
test(async function writeJsonIfNotExists() { test(async function writeJsonIfNotExists(): Promise<void> {
const notExistsJsonFile = path.join(testdataDir, "file_not_exists.json"); const notExistsJsonFile = path.join(testdataDir, "file_not_exists.json");
await assertThrowsAsync( await assertThrowsAsync(
async () => { async (): Promise<void> => {
await writeJson(notExistsJsonFile, { a: "1" }); await writeJson(notExistsJsonFile, { a: "1" });
throw new Error("should write success"); throw new Error("should write success");
}, },
@ -29,13 +29,13 @@ test(async function writeJsonIfNotExists() {
assertEquals(new TextDecoder().decode(content), `{"a":"1"}`); assertEquals(new TextDecoder().decode(content), `{"a":"1"}`);
}); });
test(async function writeJsonIfExists() { test(async function writeJsonIfExists(): Promise<void> {
const existsJsonFile = path.join(testdataDir, "file_write_exists.json"); const existsJsonFile = path.join(testdataDir, "file_write_exists.json");
await Deno.writeFile(existsJsonFile, new Uint8Array()); await Deno.writeFile(existsJsonFile, new Uint8Array());
await assertThrowsAsync( await assertThrowsAsync(
async () => { async (): Promise<void> => {
await writeJson(existsJsonFile, { a: "1" }); await writeJson(existsJsonFile, { a: "1" });
throw new Error("should write success"); throw new Error("should write success");
}, },
@ -50,7 +50,7 @@ test(async function writeJsonIfExists() {
assertEquals(new TextDecoder().decode(content), `{"a":"1"}`); assertEquals(new TextDecoder().decode(content), `{"a":"1"}`);
}); });
test(async function writeJsonIfExistsAnInvalidJson() { test(async function writeJsonIfExistsAnInvalidJson(): Promise<void> {
const existsInvalidJsonFile = path.join( const existsInvalidJsonFile = path.join(
testdataDir, testdataDir,
"file_write_invalid.json" "file_write_invalid.json"
@ -60,7 +60,7 @@ test(async function writeJsonIfExistsAnInvalidJson() {
await Deno.writeFile(existsInvalidJsonFile, invalidJsonContent); await Deno.writeFile(existsInvalidJsonFile, invalidJsonContent);
await assertThrowsAsync( await assertThrowsAsync(
async () => { async (): Promise<void> => {
await writeJson(existsInvalidJsonFile, { a: "1" }); await writeJson(existsInvalidJsonFile, { a: "1" });
throw new Error("should write success"); throw new Error("should write success");
}, },
@ -75,14 +75,14 @@ test(async function writeJsonIfExistsAnInvalidJson() {
assertEquals(new TextDecoder().decode(content), `{"a":"1"}`); assertEquals(new TextDecoder().decode(content), `{"a":"1"}`);
}); });
test(async function writeJsonWithSpaces() { test(async function writeJsonWithSpaces(): Promise<void> {
const existsJsonFile = path.join(testdataDir, "file_write_spaces.json"); const existsJsonFile = path.join(testdataDir, "file_write_spaces.json");
const invalidJsonContent = new TextEncoder().encode(); const invalidJsonContent = new TextEncoder().encode();
await Deno.writeFile(existsJsonFile, invalidJsonContent); await Deno.writeFile(existsJsonFile, invalidJsonContent);
await assertThrowsAsync( await assertThrowsAsync(
async () => { async (): Promise<void> => {
await writeJson(existsJsonFile, { a: "1" }, { spaces: 2 }); await writeJson(existsJsonFile, { a: "1" }, { spaces: 2 });
throw new Error("should write success"); throw new Error("should write success");
}, },
@ -97,14 +97,14 @@ test(async function writeJsonWithSpaces() {
assertEquals(new TextDecoder().decode(content), `{\n "a": "1"\n}`); assertEquals(new TextDecoder().decode(content), `{\n "a": "1"\n}`);
}); });
test(async function writeJsonWithReplacer() { test(async function writeJsonWithReplacer(): Promise<void> {
const existsJsonFile = path.join(testdataDir, "file_write_replacer.json"); const existsJsonFile = path.join(testdataDir, "file_write_replacer.json");
const invalidJsonContent = new TextEncoder().encode(); const invalidJsonContent = new TextEncoder().encode();
await Deno.writeFile(existsJsonFile, invalidJsonContent); await Deno.writeFile(existsJsonFile, invalidJsonContent);
await assertThrowsAsync( await assertThrowsAsync(
async () => { async (): Promise<void> => {
await writeJson( await writeJson(
existsJsonFile, existsJsonFile,
{ a: "1", b: "2", c: "3" }, { a: "1", b: "2", c: "3" },
@ -125,11 +125,11 @@ test(async function writeJsonWithReplacer() {
assertEquals(new TextDecoder().decode(content), `{"a":"1"}`); assertEquals(new TextDecoder().decode(content), `{"a":"1"}`);
}); });
test(function writeJsonSyncIfNotExists() { test(function writeJsonSyncIfNotExists(): void {
const notExistsJsonFile = path.join(testdataDir, "file_not_exists_sync.json"); const notExistsJsonFile = path.join(testdataDir, "file_not_exists_sync.json");
assertThrows( assertThrows(
() => { (): void => {
writeJsonSync(notExistsJsonFile, { a: "1" }); writeJsonSync(notExistsJsonFile, { a: "1" });
throw new Error("should write success"); throw new Error("should write success");
}, },
@ -144,13 +144,13 @@ test(function writeJsonSyncIfNotExists() {
assertEquals(new TextDecoder().decode(content), `{"a":"1"}`); assertEquals(new TextDecoder().decode(content), `{"a":"1"}`);
}); });
test(function writeJsonSyncIfExists() { test(function writeJsonSyncIfExists(): void {
const existsJsonFile = path.join(testdataDir, "file_write_exists_sync.json"); const existsJsonFile = path.join(testdataDir, "file_write_exists_sync.json");
Deno.writeFileSync(existsJsonFile, new Uint8Array()); Deno.writeFileSync(existsJsonFile, new Uint8Array());
assertThrows( assertThrows(
() => { (): void => {
writeJsonSync(existsJsonFile, { a: "1" }); writeJsonSync(existsJsonFile, { a: "1" });
throw new Error("should write success"); throw new Error("should write success");
}, },
@ -165,7 +165,7 @@ test(function writeJsonSyncIfExists() {
assertEquals(new TextDecoder().decode(content), `{"a":"1"}`); assertEquals(new TextDecoder().decode(content), `{"a":"1"}`);
}); });
test(function writeJsonSyncIfExistsAnInvalidJson() { test(function writeJsonSyncIfExistsAnInvalidJson(): void {
const existsInvalidJsonFile = path.join( const existsInvalidJsonFile = path.join(
testdataDir, testdataDir,
"file_write_invalid_sync.json" "file_write_invalid_sync.json"
@ -175,7 +175,7 @@ test(function writeJsonSyncIfExistsAnInvalidJson() {
Deno.writeFileSync(existsInvalidJsonFile, invalidJsonContent); Deno.writeFileSync(existsInvalidJsonFile, invalidJsonContent);
assertThrows( assertThrows(
() => { (): void => {
writeJsonSync(existsInvalidJsonFile, { a: "1" }); writeJsonSync(existsInvalidJsonFile, { a: "1" });
throw new Error("should write success"); throw new Error("should write success");
}, },
@ -190,14 +190,14 @@ test(function writeJsonSyncIfExistsAnInvalidJson() {
assertEquals(new TextDecoder().decode(content), `{"a":"1"}`); assertEquals(new TextDecoder().decode(content), `{"a":"1"}`);
}); });
test(function writeJsonWithSpaces() { test(function writeJsonWithSpaces(): void {
const existsJsonFile = path.join(testdataDir, "file_write_spaces_sync.json"); const existsJsonFile = path.join(testdataDir, "file_write_spaces_sync.json");
const invalidJsonContent = new TextEncoder().encode(); const invalidJsonContent = new TextEncoder().encode();
Deno.writeFileSync(existsJsonFile, invalidJsonContent); Deno.writeFileSync(existsJsonFile, invalidJsonContent);
assertThrows( assertThrows(
() => { (): void => {
writeJsonSync(existsJsonFile, { a: "1" }, { spaces: 2 }); writeJsonSync(existsJsonFile, { a: "1" }, { spaces: 2 });
throw new Error("should write success"); throw new Error("should write success");
}, },
@ -212,7 +212,7 @@ test(function writeJsonWithSpaces() {
assertEquals(new TextDecoder().decode(content), `{\n "a": "1"\n}`); assertEquals(new TextDecoder().decode(content), `{\n "a": "1"\n}`);
}); });
test(function writeJsonWithReplacer() { test(function writeJsonWithReplacer(): void {
const existsJsonFile = path.join( const existsJsonFile = path.join(
testdataDir, testdataDir,
"file_write_replacer_sync.json" "file_write_replacer_sync.json"
@ -222,7 +222,7 @@ test(function writeJsonWithReplacer() {
Deno.writeFileSync(existsJsonFile, invalidJsonContent); Deno.writeFileSync(existsJsonFile, invalidJsonContent);
assertThrows( assertThrows(
() => { (): void => {
writeJsonSync( writeJsonSync(
existsJsonFile, existsJsonFile,
{ a: "1", b: "2", c: "3" }, { a: "1", b: "2", c: "3" },

View file

@ -76,9 +76,11 @@ function modeToString(isDir: boolean, maybeMode: number | null): string {
.split("") .split("")
.reverse() .reverse()
.slice(0, 3) .slice(0, 3)
.forEach(v => { .forEach(
(v): void => {
output = modeMap[+v] + output; output = modeMap[+v] + output;
}); }
);
output = `(${isDir ? "d" : "-"}${output})`; output = `(${isDir ? "d" : "-"}${output})`;
return output; return output;
} }
@ -220,7 +222,9 @@ function setCORS(res: Response): void {
); );
} }
listenAndServe(addr, async req => { listenAndServe(
addr,
async (req): Promise<void> => {
const fileName = req.url.replace(/\/$/, ""); const fileName = req.url.replace(/\/$/, "");
const filePath = currentDir + fileName; const filePath = currentDir + fileName;
@ -244,6 +248,7 @@ listenAndServe(addr, async req => {
serverLog(req, response); serverLog(req, response);
req.respond(response); req.respond(response);
} }
}); }
);
console.log(`HTTP server listening on http://${addr}/`); console.log(`HTTP server listening on http://${addr}/`);

View file

@ -30,7 +30,7 @@ function killFileServer(): void {
fileServer.stdout.close(); fileServer.stdout.close();
} }
test(async function serveFile() { test(async function serveFile(): Promise<void> {
await startFileServer(); await startFileServer();
try { try {
const res = await fetch("http://localhost:4500/azure-pipelines.yml"); const res = await fetch("http://localhost:4500/azure-pipelines.yml");
@ -47,7 +47,7 @@ test(async function serveFile() {
} }
}); });
test(async function serveDirectory() { test(async function serveDirectory(): Promise<void> {
await startFileServer(); await startFileServer();
try { try {
const res = await fetch("http://localhost:4500/"); const res = await fetch("http://localhost:4500/");
@ -60,7 +60,7 @@ test(async function serveDirectory() {
} }
}); });
test(async function serveFallback() { test(async function serveFallback(): Promise<void> {
await startFileServer(); await startFileServer();
try { try {
const res = await fetch("http://localhost:4500/badfile.txt"); const res = await fetch("http://localhost:4500/badfile.txt");

View file

@ -8,7 +8,7 @@ const body = new TextEncoder().encode("Hello 1\n");
const body4 = new TextEncoder().encode("World 4\n"); const body4 = new TextEncoder().encode("World 4\n");
function sleep(ms: number): Promise<void> { function sleep(ms: number): Promise<void> {
return new Promise(res => setTimeout(res, ms)); return new Promise((res): number => setTimeout(res, ms));
} }
async function delayedRespond(request: ServerRequest): Promise<void> { async function delayedRespond(request: ServerRequest): Promise<void> {

View file

@ -16,10 +16,12 @@ interface Deferred {
function deferred(isResolved = false): Deferred { function deferred(isResolved = false): Deferred {
let resolve, reject; let resolve, reject;
const promise = new Promise((res, rej) => { const promise = new Promise(
(res, rej): void => {
resolve = res; resolve = res;
reject = rej; reject = rej;
}); }
);
if (isResolved) { if (isResolved) {
resolve(); resolve();
} }
@ -181,7 +183,7 @@ export class ServerRequest {
const transferEncodings = this.headers const transferEncodings = this.headers
.get("transfer-encoding") .get("transfer-encoding")
.split(",") .split(",")
.map(e => e.trim().toLowerCase()); .map((e): string => e.trim().toLowerCase());
if (transferEncodings.includes("chunked")) { if (transferEncodings.includes("chunked")) {
// Based on https://tools.ietf.org/html/rfc2616#section-19.4.6 // Based on https://tools.ietf.org/html/rfc2616#section-19.4.6
const tp = new TextProtoReader(this.r); const tp = new TextProtoReader(this.r);
@ -341,10 +343,10 @@ export async function* serve(
let handleConn = (_conn: Conn): void => {}; let handleConn = (_conn: Conn): void => {};
let scheduleAccept = (): void => {}; let scheduleAccept = (): void => {};
const acceptRoutine = (): void => { const acceptRoutine = (): void => {
scheduleAccept = () => { scheduleAccept = (): void => {
listener.accept().then(handleConn); listener.accept().then(handleConn);
}; };
handleConn = (conn: Conn) => { handleConn = (conn: Conn): void => {
const httpConn = createHttpConn(conn); const httpConn = createHttpConn(conn);
serveConn(env, httpConn); // don't block serveConn(env, httpConn); // don't block
scheduleAccept(); // schedule next accept scheduleAccept(); // schedule next accept

View file

@ -28,12 +28,14 @@ interface Deferred {
} }
function deferred(isResolved = false): Deferred { function deferred(isResolved = false): Deferred {
let resolve: Handler = () => void 0; let resolve: Handler = (): void => void 0;
let reject: Handler = () => void 0; let reject: Handler = (): void => void 0;
const promise = new Promise((res, rej) => { const promise = new Promise(
(res, rej): void => {
resolve = res; resolve = res;
reject = rej; reject = rej;
}); }
);
if (isResolved) { if (isResolved) {
resolve(); resolve();
} }
@ -64,7 +66,7 @@ const responseTests: ResponseTest[] = [
} }
]; ];
test(async function responseWrite() { test(async function responseWrite(): Promise<void> {
for (const testCase of responseTests) { for (const testCase of responseTests) {
const buf = new Buffer(); const buf = new Buffer();
const bufw = new BufWriter(buf); const bufw = new BufWriter(buf);
@ -75,15 +77,15 @@ test(async function responseWrite() {
localAddr: "", localAddr: "",
remoteAddr: "", remoteAddr: "",
rid: -1, rid: -1,
closeRead: () => {}, closeRead: (): void => {},
closeWrite: () => {}, closeWrite: (): void => {},
read: async () => { read: async (): Promise<Deno.ReadResult> => {
return { eof: true, nread: 0 }; return { eof: true, nread: 0 };
}, },
write: async () => { write: async (): Promise<number> => {
return -1; return -1;
}, },
close: () => {}, close: (): void => {},
lastPipelineId: 0, lastPipelineId: 0,
pendingDeferredMap: new Map([[0, deferred(true)], [1, deferred()]]) pendingDeferredMap: new Map([[0, deferred(true)], [1, deferred()]])
}; };
@ -93,7 +95,7 @@ test(async function responseWrite() {
} }
}); });
test(async function requestBodyWithContentLength() { test(async function requestBodyWithContentLength(): Promise<void> {
{ {
const req = new ServerRequest(); const req = new ServerRequest();
req.headers = new Headers(); req.headers = new Headers();
@ -117,7 +119,7 @@ test(async function requestBodyWithContentLength() {
} }
}); });
test(async function requestBodyWithTransferEncoding() { test(async function requestBodyWithTransferEncoding(): Promise<void> {
{ {
const shortText = "Hello"; const shortText = "Hello";
const req = new ServerRequest(); const req = new ServerRequest();
@ -166,7 +168,7 @@ test(async function requestBodyWithTransferEncoding() {
} }
}); });
test(async function requestBodyStreamWithContentLength() { test(async function requestBodyStreamWithContentLength(): Promise<void> {
{ {
const shortText = "Hello"; const shortText = "Hello";
const req = new ServerRequest(); const req = new ServerRequest();
@ -201,7 +203,7 @@ test(async function requestBodyStreamWithContentLength() {
} }
}); });
test(async function requestBodyStreamWithTransferEncoding() { test(async function requestBodyStreamWithTransferEncoding(): Promise<void> {
{ {
const shortText = "Hello"; const shortText = "Hello";
const req = new ServerRequest(); const req = new ServerRequest();

View file

@ -29,7 +29,7 @@ async function readBytes(buf: BufReader): Promise<string> {
return decoder.decode(b.subarray(0, nb)); return decoder.decode(b.subarray(0, nb));
} }
test(async function bufioReaderSimple() { test(async function bufioReaderSimple(): Promise<void> {
const data = "hello world"; const data = "hello world";
const b = new BufReader(stringsReader(data)); const b = new BufReader(stringsReader(data));
const s = await readBytes(b); const s = await readBytes(b);
@ -42,9 +42,12 @@ interface ReadMaker {
} }
const readMakers: ReadMaker[] = [ const readMakers: ReadMaker[] = [
{ name: "full", fn: r => r }, { name: "full", fn: (r): Reader => r },
{ name: "byte", fn: r => new iotest.OneByteReader(r) }, {
{ name: "half", fn: r => new iotest.HalfReader(r) } name: "byte",
fn: (r): iotest.OneByteReader => new iotest.OneByteReader(r)
},
{ name: "half", fn: (r): iotest.HalfReader => new iotest.HalfReader(r) }
// TODO { name: "data+err", r => new iotest.DataErrReader(r) }, // TODO { name: "data+err", r => new iotest.DataErrReader(r) },
// { name: "timeout", fn: r => new iotest.TimeoutReader(r) }, // { name: "timeout", fn: r => new iotest.TimeoutReader(r) },
]; ];
@ -70,12 +73,12 @@ interface NamedBufReader {
} }
const bufreaders: NamedBufReader[] = [ const bufreaders: NamedBufReader[] = [
{ name: "1", fn: (b: BufReader) => reads(b, 1) }, { name: "1", fn: (b: BufReader): Promise<string> => reads(b, 1) },
{ name: "2", fn: (b: BufReader) => reads(b, 2) }, { name: "2", fn: (b: BufReader): Promise<string> => reads(b, 2) },
{ name: "3", fn: (b: BufReader) => reads(b, 3) }, { name: "3", fn: (b: BufReader): Promise<string> => reads(b, 3) },
{ name: "4", fn: (b: BufReader) => reads(b, 4) }, { name: "4", fn: (b: BufReader): Promise<string> => reads(b, 4) },
{ name: "5", fn: (b: BufReader) => reads(b, 5) }, { name: "5", fn: (b: BufReader): Promise<string> => reads(b, 5) },
{ name: "7", fn: (b: BufReader) => reads(b, 7) }, { name: "7", fn: (b: BufReader): Promise<string> => reads(b, 7) },
{ name: "bytes", fn: readBytes } { name: "bytes", fn: readBytes }
// { name: "lines", fn: readLines }, // { name: "lines", fn: readLines },
]; ];
@ -94,7 +97,7 @@ const bufsizes: number[] = [
4096 4096
]; ];
test(async function bufioBufReader() { test(async function bufioBufReader(): Promise<void> {
const texts = new Array<string>(31); const texts = new Array<string>(31);
let str = ""; let str = "";
let all = ""; let all = "";
@ -122,7 +125,7 @@ test(async function bufioBufReader() {
} }
}); });
test(async function bufioBufferFull() { test(async function bufioBufferFull(): Promise<void> {
const longString = const longString =
"And now, hello, world! It is the time for all good men to come to the aid of their party"; "And now, hello, world! It is the time for all good men to come to the aid of their party";
const buf = new BufReader(stringsReader(longString), MIN_READ_BUFFER_SIZE); const buf = new BufReader(stringsReader(longString), MIN_READ_BUFFER_SIZE);
@ -201,12 +204,12 @@ async function testReadLine(input: Uint8Array): Promise<void> {
} }
} }
test(async function bufioReadLine() { test(async function bufioReadLine(): Promise<void> {
await testReadLine(testInput); await testReadLine(testInput);
await testReadLine(testInputrn); await testReadLine(testInputrn);
}); });
test(async function bufioPeek() { test(async function bufioPeek(): Promise<void> {
const decoder = new TextDecoder(); const decoder = new TextDecoder();
let p = new Uint8Array(10); let p = new Uint8Array(10);
// string is 16 (minReadBufferSize) long. // string is 16 (minReadBufferSize) long.
@ -283,7 +286,7 @@ test(async function bufioPeek() {
*/ */
}); });
test(async function bufioWriter() { test(async function bufioWriter(): Promise<void> {
const data = new Uint8Array(8192); const data = new Uint8Array(8192);
for (let i = 0; i < data.byteLength; i++) { for (let i = 0; i < data.byteLength; i++) {
@ -317,7 +320,7 @@ test(async function bufioWriter() {
} }
}); });
test(async function bufReaderReadFull() { test(async function bufReaderReadFull(): Promise<void> {
const enc = new TextEncoder(); const enc = new TextEncoder();
const dec = new TextDecoder(); const dec = new TextDecoder();
const text = "Hello World"; const text = "Hello World";

View file

@ -26,19 +26,19 @@ class BinaryReader implements Reader {
} }
} }
test(async function testReadShort() { test(async function testReadShort(): Promise<void> {
const r = new BinaryReader(new Uint8Array([0x12, 0x34])); const r = new BinaryReader(new Uint8Array([0x12, 0x34]));
const short = await readShort(new BufReader(r)); const short = await readShort(new BufReader(r));
assertEquals(short, 0x1234); assertEquals(short, 0x1234);
}); });
test(async function testReadInt() { test(async function testReadInt(): Promise<void> {
const r = new BinaryReader(new Uint8Array([0x12, 0x34, 0x56, 0x78])); const r = new BinaryReader(new Uint8Array([0x12, 0x34, 0x56, 0x78]));
const int = await readInt(new BufReader(r)); const int = await readInt(new BufReader(r));
assertEquals(int, 0x12345678); assertEquals(int, 0x12345678);
}); });
test(async function testReadLong() { test(async function testReadLong(): Promise<void> {
const r = new BinaryReader( const r = new BinaryReader(
new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78]) new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78])
); );
@ -46,7 +46,7 @@ test(async function testReadLong() {
assertEquals(long, 0x1234567812345678); assertEquals(long, 0x1234567812345678);
}); });
test(async function testReadLong2() { test(async function testReadLong2(): Promise<void> {
const r = new BinaryReader( const r = new BinaryReader(
new Uint8Array([0, 0, 0, 0, 0x12, 0x34, 0x56, 0x78]) new Uint8Array([0, 0, 0, 0, 0x12, 0x34, 0x56, 0x78])
); );
@ -54,7 +54,7 @@ test(async function testReadLong2() {
assertEquals(long, 0x12345678); assertEquals(long, 0x12345678);
}); });
test(async function testSliceLongToBytes() { test(async function testSliceLongToBytes(): Promise<void> {
const arr = sliceLongToBytes(0x1234567890abcdef); const arr = sliceLongToBytes(0x1234567890abcdef);
const actual = readLong(new BufReader(new BinaryReader(new Uint8Array(arr)))); const actual = readLong(new BufReader(new BinaryReader(new Uint8Array(arr))));
const expected = readLong( const expected = readLong(
@ -67,12 +67,12 @@ test(async function testSliceLongToBytes() {
assertEquals(actual, expected); assertEquals(actual, expected);
}); });
test(async function testSliceLongToBytes2() { test(async function testSliceLongToBytes2(): Promise<void> {
const arr = sliceLongToBytes(0x12345678); const arr = sliceLongToBytes(0x12345678);
assertEquals(arr, [0, 0, 0, 0, 0x12, 0x34, 0x56, 0x78]); assertEquals(arr, [0, 0, 0, 0, 0x12, 0x34, 0x56, 0x78]);
}); });
test(async function testCopyN1() { test(async function testCopyN1(): Promise<void> {
const w = new Buffer(); const w = new Buffer();
const r = stringsReader("abcdefghij"); const r = stringsReader("abcdefghij");
const n = await copyN(w, r, 3); const n = await copyN(w, r, 3);
@ -80,7 +80,7 @@ test(async function testCopyN1() {
assertEquals(w.toString(), "abc"); assertEquals(w.toString(), "abc");
}); });
test(async function testCopyN2() { test(async function testCopyN2(): Promise<void> {
const w = new Buffer(); const w = new Buffer();
const r = stringsReader("abcdefghij"); const r = stringsReader("abcdefghij");
const n = await copyN(w, r, 11); const n = await copyN(w, r, 11);

View file

@ -6,14 +6,14 @@ import { StringWriter } from "./writers.ts";
import { copyN } from "./ioutil.ts"; import { copyN } from "./ioutil.ts";
import { decode } from "../strings/strings.ts"; import { decode } from "../strings/strings.ts";
test(async function ioStringReader() { test(async function ioStringReader(): Promise<void> {
const r = new StringReader("abcdef"); const r = new StringReader("abcdef");
const { nread, eof } = await r.read(new Uint8Array(6)); const { nread, eof } = await r.read(new Uint8Array(6));
assertEquals(nread, 6); assertEquals(nread, 6);
assertEquals(eof, true); assertEquals(eof, true);
}); });
test(async function ioStringReader() { test(async function ioStringReader(): Promise<void> {
const r = new StringReader("abcdef"); const r = new StringReader("abcdef");
const buf = new Uint8Array(3); const buf = new Uint8Array(3);
let res1 = await r.read(buf); let res1 = await r.read(buf);
@ -26,7 +26,7 @@ test(async function ioStringReader() {
assertEquals(decode(buf), "def"); assertEquals(decode(buf), "def");
}); });
test(async function ioMultiReader() { test(async function ioMultiReader(): Promise<void> {
const r = new MultiReader(new StringReader("abc"), new StringReader("def")); const r = new MultiReader(new StringReader("abc"), new StringReader("def"));
const w = new StringWriter(); const w = new StringWriter();
const n = await copyN(w, r, 4); const n = await copyN(w, r, 4);

View file

@ -5,7 +5,7 @@ import { assert, assertEquals } from "../testing/asserts.ts";
import { copyBytes, tempFile } from "./util.ts"; import { copyBytes, tempFile } from "./util.ts";
import * as path from "../fs/path.ts"; import * as path from "../fs/path.ts";
test(function testCopyBytes() { test(function testCopyBytes(): void {
let dst = new Uint8Array(4); let dst = new Uint8Array(4);
dst.fill(0); dst.fill(0);
@ -39,7 +39,7 @@ test(function testCopyBytes() {
assertEquals(dst, Uint8Array.of(3, 4, 0, 0)); assertEquals(dst, Uint8Array.of(3, 4, 0, 0));
}); });
test(async function ioTempfile() { test(async function ioTempfile(): Promise<void> {
const f = await tempFile(".", { const f = await tempFile(".", {
prefix: "prefix-", prefix: "prefix-",
postfix: "-postfix" postfix: "-postfix"

View file

@ -5,7 +5,7 @@ import { StringWriter } from "./writers.ts";
import { StringReader } from "./readers.ts"; import { StringReader } from "./readers.ts";
import { copyN } from "./ioutil.ts"; import { copyN } from "./ioutil.ts";
test(async function ioStringWriter() { test(async function ioStringWriter(): Promise<void> {
const w = new StringWriter("base"); const w = new StringWriter("base");
const r = new StringReader("0123456789"); const r = new StringReader("0123456789");
await copyN(w, r, 4); await copyN(w, r, 4);

View file

@ -37,7 +37,9 @@ export class BaseHandler {
return this.formatter(logRecord); return this.formatter(logRecord);
} }
return this.formatter.replace(/{(\S+)}/g, (match, p1) => { return this.formatter.replace(
/{(\S+)}/g,
(match, p1): string => {
const value = logRecord[p1]; const value = logRecord[p1];
// do not interpolate missing values // do not interpolate missing values
@ -46,7 +48,8 @@ export class BaseHandler {
} }
return value; return value;
}); }
);
} }
log(_msg: string): void {} log(_msg: string): void {}

View file

@ -12,7 +12,7 @@ class TestHandler extends BaseHandler {
} }
} }
test(function simpleHandler() { test(function simpleHandler(): void {
const cases = new Map<number, string[]>([ const cases = new Map<number, string[]>([
[ [
LogLevel.DEBUG, LogLevel.DEBUG,
@ -62,7 +62,7 @@ test(function simpleHandler() {
} }
}); });
test(function testFormatterAsString() { test(function testFormatterAsString(): void {
const handler = new TestHandler("DEBUG", { const handler = new TestHandler("DEBUG", {
formatter: "test {levelName} {msg}" formatter: "test {levelName} {msg}"
}); });
@ -78,9 +78,9 @@ test(function testFormatterAsString() {
assertEquals(handler.messages, ["test DEBUG Hello, world!"]); assertEquals(handler.messages, ["test DEBUG Hello, world!"]);
}); });
test(function testFormatterAsFunction() { test(function testFormatterAsFunction(): void {
const handler = new TestHandler("DEBUG", { const handler = new TestHandler("DEBUG", {
formatter: logRecord => formatter: (logRecord): string =>
`fn formmatter ${logRecord.levelName} ${logRecord.msg}` `fn formmatter ${logRecord.levelName} ${logRecord.msg}`
}); });

View file

@ -39,9 +39,11 @@ export class Logger {
levelName: getLevelName(level) levelName: getLevelName(level)
}; };
this.handlers.forEach(handler => { this.handlers.forEach(
(handler): void => {
handler.handle(record); handler.handle(record);
}); }
);
} }
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any

View file

@ -19,7 +19,7 @@ class TestHandler extends BaseHandler {
} }
} }
test(function simpleLogger() { test(function simpleLogger(): void {
const handler = new TestHandler("DEBUG"); const handler = new TestHandler("DEBUG");
let logger = new Logger("DEBUG"); let logger = new Logger("DEBUG");
@ -32,7 +32,7 @@ test(function simpleLogger() {
assertEquals(logger.handlers, [handler]); assertEquals(logger.handlers, [handler]);
}); });
test(function customHandler() { test(function customHandler(): void {
const handler = new TestHandler("DEBUG"); const handler = new TestHandler("DEBUG");
const logger = new Logger("DEBUG", [handler]); const logger = new Logger("DEBUG", [handler]);
@ -51,7 +51,7 @@ test(function customHandler() {
assertEquals(handler.messages, ["DEBUG foo"]); assertEquals(handler.messages, ["DEBUG foo"]);
}); });
test(function logFunctions() { test(function logFunctions(): void {
let handler: TestHandler; let handler: TestHandler;
const doLog = (level: string): void => { const doLog = (level: string): void => {

View file

@ -89,9 +89,11 @@ export async function setup(config: LogConfig): Promise<void> {
}; };
// tear down existing handlers // tear down existing handlers
state.handlers.forEach(handler => { state.handlers.forEach(
(handler): void => {
handler.destroy(); handler.destroy();
}); }
);
state.handlers.clear(); state.handlers.clear();
// setup handlers // setup handlers
@ -113,11 +115,13 @@ export async function setup(config: LogConfig): Promise<void> {
const handlerNames = loggerConfig.handlers || []; const handlerNames = loggerConfig.handlers || [];
const handlers: BaseHandler[] = []; const handlers: BaseHandler[] = [];
handlerNames.forEach(handlerName => { handlerNames.forEach(
(handlerName): void => {
if (state.handlers.has(handlerName)) { if (state.handlers.has(handlerName)) {
handlers.push(state.handlers.get(handlerName)); handlers.push(state.handlers.get(handlerName));
} }
}); }
);
const levelName = loggerConfig.level || DEFAULT_LEVEL; const levelName = loggerConfig.level || DEFAULT_LEVEL;
const logger = new Logger(levelName, handlers); const logger = new Logger(levelName, handlers);

View file

@ -22,7 +22,7 @@ class TestHandler extends log.handlers.BaseHandler {
} }
} }
test(async function defaultHandlers() { test(async function defaultHandlers(): Promise<void> {
const loggers = { const loggers = {
DEBUG: log.debug, DEBUG: log.debug,
INFO: log.info, INFO: log.info,
@ -59,7 +59,7 @@ test(async function defaultHandlers() {
} }
}); });
test(async function getLogger() { test(async function getLogger(): Promise<void> {
const handler = new TestHandler("DEBUG"); const handler = new TestHandler("DEBUG");
await log.setup({ await log.setup({
@ -80,7 +80,7 @@ test(async function getLogger() {
assertEquals(logger.handlers, [handler]); assertEquals(logger.handlers, [handler]);
}); });
test(async function getLoggerWithName() { test(async function getLoggerWithName(): Promise<void> {
const fooHandler = new TestHandler("DEBUG"); const fooHandler = new TestHandler("DEBUG");
await log.setup({ await log.setup({
@ -101,7 +101,7 @@ test(async function getLoggerWithName() {
assertEquals(logger.handlers, [fooHandler]); assertEquals(logger.handlers, [fooHandler]);
}); });
test(async function getLoggerUnknown() { test(async function getLoggerUnknown(): Promise<void> {
await log.setup({ await log.setup({
handlers: {}, handlers: {},
loggers: {} loggers: {}

View file

@ -11,14 +11,14 @@ import {
types types
} from "./mod.ts"; } from "./mod.ts";
test(function testLookup() { test(function testLookup(): void {
assertEquals(lookup("json"), "application/json"); assertEquals(lookup("json"), "application/json");
assertEquals(lookup(".md"), "text/markdown"); assertEquals(lookup(".md"), "text/markdown");
assertEquals(lookup("folder/file.js"), "application/javascript"); assertEquals(lookup("folder/file.js"), "application/javascript");
assertEquals(lookup("folder/.htaccess"), undefined); assertEquals(lookup("folder/.htaccess"), undefined);
}); });
test(function testContentType() { test(function testContentType(): void {
assertEquals(contentType("markdown"), "text/markdown; charset=utf-8"); assertEquals(contentType("markdown"), "text/markdown; charset=utf-8");
assertEquals(contentType("file.json"), "application/json; charset=utf-8"); assertEquals(contentType("file.json"), "application/json; charset=utf-8");
assertEquals(contentType("text/html"), "text/html; charset=utf-8"); assertEquals(contentType("text/html"), "text/html; charset=utf-8");
@ -29,23 +29,23 @@ test(function testContentType() {
assertEquals(contentType(".htaccess"), undefined); assertEquals(contentType(".htaccess"), undefined);
}); });
test(function testExtension() { test(function testExtension(): void {
assertEquals(extension("application/octet-stream"), "bin"); assertEquals(extension("application/octet-stream"), "bin");
assertEquals(extension("application/javascript"), "js"); assertEquals(extension("application/javascript"), "js");
assertEquals(extension("text/html"), "html"); assertEquals(extension("text/html"), "html");
}); });
test(function testCharset() { test(function testCharset(): void {
assertEquals(charset("text/markdown"), "UTF-8"); assertEquals(charset("text/markdown"), "UTF-8");
assertEquals(charset("text/css"), "UTF-8"); assertEquals(charset("text/css"), "UTF-8");
}); });
test(function testExtensions() { test(function testExtensions(): void {
assertEquals(extensions.get("application/javascript"), ["js", "mjs"]); assertEquals(extensions.get("application/javascript"), ["js", "mjs"]);
assertEquals(extensions.get("foo"), undefined); assertEquals(extensions.get("foo"), undefined);
}); });
test(function testTypes() { test(function testTypes(): void {
assertEquals(types.get("js"), "application/javascript"); assertEquals(types.get("js"), "application/javascript");
assertEquals(types.get("foo"), undefined); assertEquals(types.get("foo"), undefined);
}); });

View file

@ -3,7 +3,7 @@ import { test } from "../testing/mod.ts";
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { isFormFile } from "./formfile.ts"; import { isFormFile } from "./formfile.ts";
test(function multipartIsFormFile() { test(function multipartIsFormFile(): void {
assertEquals( assertEquals(
isFormFile({ isFormFile({
filename: "foo", filename: "foo",

View file

@ -166,8 +166,9 @@ class PartReader implements Reader, Closer {
this.contentDisposition = comps[0]; this.contentDisposition = comps[0];
comps comps
.slice(1) .slice(1)
.map(v => v.trim()) .map((v): string => v.trim())
.map(kv => { .map(
(kv): void => {
const [k, v] = kv.split("="); const [k, v] = kv.split("=");
if (v) { if (v) {
const s = v.charAt(0); const s = v.charAt(0);
@ -178,7 +179,8 @@ class PartReader implements Reader, Closer {
params[k] = v; params[k] = v;
} }
} }
}); }
);
return (this.contentDispositionParams = params); return (this.contentDispositionParams = params);
} }

View file

@ -23,7 +23,7 @@ const boundary = "--abcde";
const dashBoundary = e.encode("--" + boundary); const dashBoundary = e.encode("--" + boundary);
const nlDashBoundary = e.encode("\r\n--" + boundary); const nlDashBoundary = e.encode("\r\n--" + boundary);
test(function multipartScanUntilBoundary1() { test(function multipartScanUntilBoundary1(): void {
const data = `--${boundary}`; const data = `--${boundary}`;
const [n, err] = scanUntilBoundary( const [n, err] = scanUntilBoundary(
e.encode(data), e.encode(data),
@ -36,7 +36,7 @@ test(function multipartScanUntilBoundary1() {
assertEquals(err, "EOF"); assertEquals(err, "EOF");
}); });
test(function multipartScanUntilBoundary2() { test(function multipartScanUntilBoundary2(): void {
const data = `foo\r\n--${boundary}`; const data = `foo\r\n--${boundary}`;
const [n, err] = scanUntilBoundary( const [n, err] = scanUntilBoundary(
e.encode(data), e.encode(data),
@ -49,7 +49,7 @@ test(function multipartScanUntilBoundary2() {
assertEquals(err, "EOF"); assertEquals(err, "EOF");
}); });
test(function multipartScanUntilBoundary4() { test(function multipartScanUntilBoundary4(): void {
const data = `foo\r\n--`; const data = `foo\r\n--`;
const [n, err] = scanUntilBoundary( const [n, err] = scanUntilBoundary(
e.encode(data), e.encode(data),
@ -62,7 +62,7 @@ test(function multipartScanUntilBoundary4() {
assertEquals(err, null); assertEquals(err, null);
}); });
test(function multipartScanUntilBoundary3() { test(function multipartScanUntilBoundary3(): void {
const data = `foobar`; const data = `foobar`;
const [n, err] = scanUntilBoundary( const [n, err] = scanUntilBoundary(
e.encode(data), e.encode(data),
@ -75,25 +75,25 @@ test(function multipartScanUntilBoundary3() {
assertEquals(err, null); assertEquals(err, null);
}); });
test(function multipartMatchAfterPrefix1() { test(function multipartMatchAfterPrefix1(): void {
const data = `${boundary}\r`; const data = `${boundary}\r`;
const v = matchAfterPrefix(e.encode(data), e.encode(boundary), null); const v = matchAfterPrefix(e.encode(data), e.encode(boundary), null);
assertEquals(v, 1); assertEquals(v, 1);
}); });
test(function multipartMatchAfterPrefix2() { test(function multipartMatchAfterPrefix2(): void {
const data = `${boundary}hoge`; const data = `${boundary}hoge`;
const v = matchAfterPrefix(e.encode(data), e.encode(boundary), null); const v = matchAfterPrefix(e.encode(data), e.encode(boundary), null);
assertEquals(v, -1); assertEquals(v, -1);
}); });
test(function multipartMatchAfterPrefix3() { test(function multipartMatchAfterPrefix3(): void {
const data = `${boundary}`; const data = `${boundary}`;
const v = matchAfterPrefix(e.encode(data), e.encode(boundary), null); const v = matchAfterPrefix(e.encode(data), e.encode(boundary), null);
assertEquals(v, 0); assertEquals(v, 0);
}); });
test(async function multipartMultipartWriter() { test(async function multipartMultipartWriter(): Promise<void> {
const buf = new Buffer(); const buf = new Buffer();
const mw = new MultipartWriter(buf); const mw = new MultipartWriter(buf);
await mw.writeField("foo", "foo"); await mw.writeField("foo", "foo");
@ -103,15 +103,15 @@ test(async function multipartMultipartWriter() {
await mw.close(); await mw.close();
}); });
test(function multipartMultipartWriter2() { test(function multipartMultipartWriter2(): void {
const w = new StringWriter(); const w = new StringWriter();
assertThrows( assertThrows(
() => new MultipartWriter(w, ""), (): MultipartWriter => new MultipartWriter(w, ""),
Error, Error,
"invalid boundary length" "invalid boundary length"
); );
assertThrows( assertThrows(
() => (): MultipartWriter =>
new MultipartWriter( new MultipartWriter(
w, w,
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
@ -120,52 +120,52 @@ test(function multipartMultipartWriter2() {
"invalid boundary length" "invalid boundary length"
); );
assertThrows( assertThrows(
() => new MultipartWriter(w, "aaa aaa"), (): MultipartWriter => new MultipartWriter(w, "aaa aaa"),
Error, Error,
"invalid boundary character" "invalid boundary character"
); );
assertThrows( assertThrows(
() => new MultipartWriter(w, "boundary¥¥"), (): MultipartWriter => new MultipartWriter(w, "boundary¥¥"),
Error, Error,
"invalid boundary character" "invalid boundary character"
); );
}); });
test(async function multipartMultipartWriter3() { test(async function multipartMultipartWriter3(): Promise<void> {
const w = new StringWriter(); const w = new StringWriter();
const mw = new MultipartWriter(w); const mw = new MultipartWriter(w);
await mw.writeField("foo", "foo"); await mw.writeField("foo", "foo");
await mw.close(); await mw.close();
await assertThrowsAsync( await assertThrowsAsync(
async () => { async (): Promise<void> => {
await mw.close(); await mw.close();
}, },
Error, Error,
"closed" "closed"
); );
await assertThrowsAsync( await assertThrowsAsync(
async () => { async (): Promise<void> => {
await mw.writeFile("bar", "file", null); await mw.writeFile("bar", "file", null);
}, },
Error, Error,
"closed" "closed"
); );
await assertThrowsAsync( await assertThrowsAsync(
async () => { async (): Promise<void> => {
await mw.writeField("bar", "bar"); await mw.writeField("bar", "bar");
}, },
Error, Error,
"closed" "closed"
); );
assertThrows( assertThrows(
() => { (): void => {
mw.createFormField("bar"); mw.createFormField("bar");
}, },
Error, Error,
"closed" "closed"
); );
assertThrows( assertThrows(
() => { (): void => {
mw.createFormFile("bar", "file"); mw.createFormFile("bar", "file");
}, },
Error, Error,
@ -173,7 +173,7 @@ test(async function multipartMultipartWriter3() {
); );
}); });
test(async function multipartMultipartReader() { test(async function multipartMultipartReader(): Promise<void> {
// FIXME: path resolution // FIXME: path resolution
const o = await open(path.resolve("./multipart/fixtures/sample.txt")); const o = await open(path.resolve("./multipart/fixtures/sample.txt"));
const mr = new MultipartReader( const mr = new MultipartReader(
@ -188,7 +188,7 @@ test(async function multipartMultipartReader() {
assert(file.content !== void 0); assert(file.content !== void 0);
}); });
test(async function multipartMultipartReader2() { test(async function multipartMultipartReader2(): Promise<void> {
const o = await open(path.resolve("./multipart/fixtures/sample.txt")); const o = await open(path.resolve("./multipart/fixtures/sample.txt"));
const mr = new MultipartReader( const mr = new MultipartReader(
o, o,

View file

@ -188,7 +188,7 @@ async function checkSourceFiles(
const results = await Promise.all(checks); const results = await Promise.all(checks);
if (results.every(result => result)) { if (results.every((result): boolean => result)) {
console.log("Every file is formatted"); console.log("Every file is formatted");
exit(0); exit(0);
} else { } else {
@ -240,10 +240,12 @@ async function main(opts): Promise<void> {
} }
const options = { flags: "g" }; const options = { flags: "g" };
const skip = Array.isArray(ignore) const skip = Array.isArray(ignore)
? ignore.map((i: string) => glob(i, options)) ? ignore.map((i: string): RegExp => glob(i, options))
: [glob(ignore, options)]; : [glob(ignore, options)];
const match = const match =
args.length > 0 ? args.map((a: string) => glob(a, options)) : undefined; args.length > 0
? args.map((a: string): RegExp => glob(a, options))
: undefined;
const files = walk(".", { match, skip }); const files = walk(".", { match, skip });
try { try {
if (check) { if (check) {

View file

@ -45,7 +45,7 @@ async function clearTestdataChanges(): Promise<void> {
await xrun({ args: ["git", "checkout", testdata] }).status(); await xrun({ args: ["git", "checkout", testdata] }).status();
} }
test(async function testPrettierCheckAndFormatFiles() { test(async function testPrettierCheckAndFormatFiles(): Promise<void> {
await clearTestdataChanges(); await clearTestdataChanges();
const files = [ const files = [
@ -73,7 +73,7 @@ Formatting ./prettier/testdata/1.js`
await clearTestdataChanges(); await clearTestdataChanges();
}); });
test(async function testPrettierCheckAndFormatDirs() { test(async function testPrettierCheckAndFormatDirs(): Promise<void> {
await clearTestdataChanges(); await clearTestdataChanges();
const dirs = [join(testdata, "foo"), join(testdata, "bar")]; const dirs = [join(testdata, "foo"), join(testdata, "bar")];
@ -99,7 +99,7 @@ Formatting ./prettier/testdata/foo/1.js`
await clearTestdataChanges(); await clearTestdataChanges();
}); });
test(async function testPrettierOptions() { test(async function testPrettierOptions(): Promise<void> {
await clearTestdataChanges(); await clearTestdataChanges();
const file0 = join(testdata, "opts", "0.ts"); const file0 = join(testdata, "opts", "0.ts");

View file

@ -2,7 +2,7 @@ import { test } from "../testing/mod.ts";
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { pad } from "./pad.ts"; import { pad } from "./pad.ts";
test(function padTest() { test(function padTest(): void {
const expected1 = "**deno"; const expected1 = "**deno";
const expected2 = "deno"; const expected2 = "deno";
const expected3 = "deno**"; const expected3 = "deno**";

View file

@ -50,7 +50,7 @@ import { assertEquals } from "https://deno.land/std/testing/asserts.ts";
test({ test({
name: "testing example", name: "testing example",
fn() { fn(): void {
assertEquals("world", "world"); assertEquals("world", "world");
assertEquals({ hello: "world" }, { hello: "world" }); assertEquals({ hello: "world" }, { hello: "world" });
} }
@ -62,7 +62,7 @@ runTests();
Short syntax (named function instead of object): Short syntax (named function instead of object):
```ts ```ts
test(function example() { test(function example(): void {
assertEquals("world", "world"); assertEquals("world", "world");
assertEquals({ hello: "world" }, { hello: "world" }); assertEquals({ hello: "world" }, { hello: "world" });
}); });
@ -71,14 +71,14 @@ test(function example() {
Using `assertStrictEq()`: Using `assertStrictEq()`:
```ts ```ts
test(function isStrictlyEqual() { test(function isStrictlyEqual(): void {
const a = {}; const a = {};
const b = a; const b = a;
assertStrictEq(a, b); assertStrictEq(a, b);
}); });
// This test fails // This test fails
test(function isNotStrictlyEqual() { test(function isNotStrictlyEqual(): void {
const a = {}; const a = {};
const b = {}; const b = {};
assertStrictEq(a, b); assertStrictEq(a, b);
@ -88,15 +88,17 @@ test(function isNotStrictlyEqual() {
Using `assertThrows()`: Using `assertThrows()`:
```ts ```ts
test(function doesThrow() { test(function doesThrow(): void {
assertThrows(() => { assertThrows(
(): void => {
throw new TypeError("hello world!"); throw new TypeError("hello world!");
}); }
assertThrows(() => { );
assertThrows((): void => {
throw new TypeError("hello world!"); throw new TypeError("hello world!");
}, TypeError); }, TypeError);
assertThrows( assertThrows(
() => { (): void => {
throw new TypeError("hello world!"); throw new TypeError("hello world!");
}, },
TypeError, TypeError,
@ -105,40 +107,48 @@ test(function doesThrow() {
}); });
// This test will not pass // This test will not pass
test(function fails() { test(function fails(): void {
assertThrows(() => { assertThrows(
(): void => {
console.log("Hello world"); console.log("Hello world");
}); }
);
}); });
``` ```
Using `assertThrowsAsync()`: Using `assertThrowsAsync()`:
```ts ```ts
test(async function doesThrow() { test(async function doesThrow(): Promise<void> {
await assertThrowsAsync(async () => { await assertThrowsAsync(
async (): Promise<void> => {
throw new TypeError("hello world!"); throw new TypeError("hello world!");
}); }
await assertThrowsAsync(async () => { );
await assertThrowsAsync(async (): Promise<void> => {
throw new TypeError("hello world!"); throw new TypeError("hello world!");
}, TypeError); }, TypeError);
await assertThrowsAsync( await assertThrowsAsync(
async () => { async (): Promise<void> => {
throw new TypeError("hello world!"); throw new TypeError("hello world!");
}, },
TypeError, TypeError,
"hello" "hello"
); );
await assertThrowsAsync(async () => { await assertThrowsAsync(
async (): Promise<void> => {
return Promise.reject(new Error()); return Promise.reject(new Error());
}); }
);
}); });
// This test will not pass // This test will not pass
test(async function fails() { test(async function fails(): Promise<void> {
await assertThrowsAsync(async () => { await assertThrowsAsync(
async (): Promise<void> => {
console.log("Hello world"); console.log("Hello world");
}); }
);
}); });
``` ```
@ -149,7 +159,7 @@ Basic usage:
```ts ```ts
import { runBenchmarks, bench } from "https://deno.land/std/testing/bench.ts"; import { runBenchmarks, bench } from "https://deno.land/std/testing/bench.ts";
bench(function forIncrementX1e9(b) { bench(function forIncrementX1e9(b): void {
b.start(); b.start();
for (let i = 0; i < 1e9; i++); for (let i = 0; i < 1e9; i++);
b.stop(); b.stop();
@ -164,7 +174,7 @@ Averaging execution time over multiple runs:
bench({ bench({
name: "runs100ForIncrementX1e6", name: "runs100ForIncrementX1e6",
runs: 100, runs: 100,
func(b) { func(b): void {
b.start(); b.start();
for (let i = 0; i < 1e6; i++); for (let i = 0; i < 1e6; i++);
b.stop(); b.stop();

View file

@ -15,7 +15,7 @@ export class AssertionError extends Error {
export function equal(c: unknown, d: unknown): boolean { export function equal(c: unknown, d: unknown): boolean {
const seen = new Map(); const seen = new Map();
return (function compare(a: unknown, b: unknown) { return (function compare(a: unknown, b: unknown): boolean {
if (a && a instanceof Set && b && b instanceof Set) { if (a && a instanceof Set && b && b instanceof Set) {
if (a.size !== b.size) { if (a.size !== b.size) {
return false; return false;

View file

@ -16,7 +16,7 @@ import {
} from "./asserts.ts"; } from "./asserts.ts";
import { test } from "./mod.ts"; import { test } from "./mod.ts";
test(function testingEqual() { test(function testingEqual(): void {
assert(equal("world", "world")); assert(equal("world", "world"));
assert(!equal("hello", "world")); assert(!equal("hello", "world"));
assert(equal(5, 5)); assert(equal(5, 5));
@ -48,7 +48,7 @@ test(function testingEqual() {
assert(equal(new Set("denosaurus"), new Set("denosaurussss"))); assert(equal(new Set("denosaurus"), new Set("denosaurussss")));
}); });
test(function testingNotEquals() { test(function testingNotEquals(): void {
const a = { foo: "bar" }; const a = { foo: "bar" };
const b = { bar: "foo" }; const b = { bar: "foo" };
assertNotEquals(a, b); assertNotEquals(a, b);
@ -64,7 +64,7 @@ test(function testingNotEquals() {
assertEquals(didThrow, true); assertEquals(didThrow, true);
}); });
test(function testingAssertStringContains() { test(function testingAssertStringContains(): void {
assertStrContains("Denosaurus", "saur"); assertStrContains("Denosaurus", "saur");
assertStrContains("Denosaurus", "Deno"); assertStrContains("Denosaurus", "Deno");
assertStrContains("Denosaurus", "rus"); assertStrContains("Denosaurus", "rus");
@ -79,7 +79,7 @@ test(function testingAssertStringContains() {
assertEquals(didThrow, true); assertEquals(didThrow, true);
}); });
test(function testingArrayContains() { test(function testingArrayContains(): void {
const fixture = ["deno", "iz", "luv"]; const fixture = ["deno", "iz", "luv"];
const fixtureObject = [{ deno: "luv" }, { deno: "Js" }]; const fixtureObject = [{ deno: "luv" }, { deno: "Js" }];
assertArrayContains(fixture, ["deno"]); assertArrayContains(fixture, ["deno"]);
@ -95,7 +95,7 @@ test(function testingArrayContains() {
assertEquals(didThrow, true); assertEquals(didThrow, true);
}); });
test(function testingAssertStringContainsThrow() { test(function testingAssertStringContainsThrow(): void {
let didThrow = false; let didThrow = false;
try { try {
assertStrContains("Denosaurus from Jurassic", "Raptor"); assertStrContains("Denosaurus from Jurassic", "Raptor");
@ -110,11 +110,11 @@ test(function testingAssertStringContainsThrow() {
assert(didThrow); assert(didThrow);
}); });
test(function testingAssertStringMatching() { test(function testingAssertStringMatching(): void {
assertMatch("foobar@deno.com", RegExp(/[a-zA-Z]+@[a-zA-Z]+.com/)); assertMatch("foobar@deno.com", RegExp(/[a-zA-Z]+@[a-zA-Z]+.com/));
}); });
test(function testingAssertStringMatchingThrows() { test(function testingAssertStringMatchingThrows(): void {
let didThrow = false; let didThrow = false;
try { try {
assertMatch("Denosaurus from Jurassic", RegExp(/Raptor/)); assertMatch("Denosaurus from Jurassic", RegExp(/Raptor/));
@ -129,7 +129,7 @@ test(function testingAssertStringMatchingThrows() {
assert(didThrow); assert(didThrow);
}); });
test(function testingAssertsUnimplemented() { test(function testingAssertsUnimplemented(): void {
let didThrow = false; let didThrow = false;
try { try {
unimplemented(); unimplemented();
@ -141,7 +141,7 @@ test(function testingAssertsUnimplemented() {
assert(didThrow); assert(didThrow);
}); });
test(function testingAssertsUnreachable() { test(function testingAssertsUnreachable(): void {
let didThrow = false; let didThrow = false;
try { try {
unreachable(); unreachable();
@ -153,10 +153,10 @@ test(function testingAssertsUnreachable() {
assert(didThrow); assert(didThrow);
}); });
test(function testingAssertFail() { test(function testingAssertFail(): void {
assertThrows(fail, AssertionError, "Failed assertion."); assertThrows(fail, AssertionError, "Failed assertion.");
assertThrows( assertThrows(
() => { (): void => {
fail("foo"); fail("foo");
}, },
AssertionError, AssertionError,

View file

@ -96,7 +96,7 @@ export async function runBenchmarks({
}: BenchmarkRunOptions = {}): Promise<void> { }: BenchmarkRunOptions = {}): Promise<void> {
// Filtering candidates by the "only" and "skip" constraint // Filtering candidates by the "only" and "skip" constraint
const benchmarks: BenchmarkDefinition[] = candidates.filter( const benchmarks: BenchmarkDefinition[] = candidates.filter(
({ name }) => only.test(name) && !skip.test(name) ({ name }): boolean => only.test(name) && !skip.test(name)
); );
// Init main counters and error flag // Init main counters and error flag
const filtered = candidates.length - benchmarks.length; const filtered = candidates.length - benchmarks.length;
@ -164,7 +164,7 @@ export async function runBenchmarks({
); );
// Making sure the program exit code is not zero in case of failure // Making sure the program exit code is not zero in case of failure
if (failed) { if (failed) {
setTimeout(() => exit(1), 0); setTimeout((): void => exit(1), 0);
} }
} }

View file

@ -2,7 +2,7 @@
import { BenchmarkTimer, bench, runIfMain } from "./bench.ts"; import { BenchmarkTimer, bench, runIfMain } from "./bench.ts";
// Basic // Basic
bench(function forIncrementX1e9(b: BenchmarkTimer) { bench(function forIncrementX1e9(b: BenchmarkTimer): void {
b.start(); b.start();
for (let i = 0; i < 1e9; i++); for (let i = 0; i < 1e9; i++);
b.stop(); b.stop();
@ -12,7 +12,7 @@ bench(function forIncrementX1e9(b: BenchmarkTimer) {
bench({ bench({
name: "runs100ForIncrementX1e6", name: "runs100ForIncrementX1e6",
runs: 100, runs: 100,
func(b) { func(b): void {
b.start(); b.start();
for (let i = 0; i < 1e6; i++); for (let i = 0; i < 1e6; i++);
b.stop(); b.stop();
@ -20,7 +20,7 @@ bench({
}); });
// Itsabug // Itsabug
bench(function throwing(b) { bench(function throwing(b): void {
b.start(); b.start();
// Throws bc the timer's stop method is never called // Throws bc the timer's stop method is never called
}); });

View file

@ -3,20 +3,20 @@ import { bench, runBenchmarks } from "./bench.ts";
import "./bench_example.ts"; import "./bench_example.ts";
test(async function benching() { test(async function benching(): Promise<void> {
bench(function forIncrementX1e9(b) { bench(function forIncrementX1e9(b): void {
b.start(); b.start();
for (let i = 0; i < 1e9; i++); for (let i = 0; i < 1e9; i++);
b.stop(); b.stop();
}); });
bench(function forDecrementX1e9(b) { bench(function forDecrementX1e9(b): void {
b.start(); b.start();
for (let i = 1e9; i > 0; i--); for (let i = 1e9; i > 0; i--);
b.stop(); b.stop();
}); });
bench(async function forAwaitFetchDenolandX10(b) { bench(async function forAwaitFetchDenolandX10(b): Promise<void> {
b.start(); b.start();
for (let i = 0; i < 10; i++) { for (let i = 0; i < 10; i++) {
let r = await fetch("https://deno.land/"); let r = await fetch("https://deno.land/");
@ -25,14 +25,16 @@ test(async function benching() {
b.stop(); b.stop();
}); });
bench(async function promiseAllFetchDenolandX10(b) { bench(async function promiseAllFetchDenolandX10(b): Promise<void> {
const urls = new Array(10).fill("https://deno.land/"); const urls = new Array(10).fill("https://deno.land/");
b.start(); b.start();
await Promise.all( await Promise.all(
urls.map(async (denoland: string) => { urls.map(
async (denoland: string): Promise<void> => {
let r = await fetch(denoland); let r = await fetch(denoland);
await r.text(); await r.text();
}) }
)
); );
b.stop(); b.stop();
}); });
@ -40,14 +42,14 @@ test(async function benching() {
bench({ bench({
name: "runs100ForIncrementX1e6", name: "runs100ForIncrementX1e6",
runs: 100, runs: 100,
func(b) { func(b): void {
b.start(); b.start();
for (let i = 0; i < 1e6; i++); for (let i = 0; i < 1e6; i++);
b.stop(); b.stop();
} }
}); });
bench(function throwing(b) { bench(function throwing(b): void {
b.start(); b.start();
// Throws bc the timer's stop method is never called // Throws bc the timer's stop method is never called
}); });

View file

@ -54,12 +54,18 @@ export default function diff<T>(A: T[], B: T[]): Array<DiffResult<T>> {
if (!M && !N && !suffixCommon.length && !prefixCommon.length) return []; if (!M && !N && !suffixCommon.length && !prefixCommon.length) return [];
if (!N) { if (!N) {
return [ return [
...prefixCommon.map(c => ({ type: DiffType.common, value: c })), ...prefixCommon.map(
...A.map(a => ({ (c): DiffResult<typeof c> => ({ type: DiffType.common, value: c })
),
...A.map(
(a): DiffResult<typeof a> => ({
type: swapped ? DiffType.added : DiffType.removed, type: swapped ? DiffType.added : DiffType.removed,
value: a value: a
})), })
...suffixCommon.map(c => ({ type: DiffType.common, value: c })) ),
...suffixCommon.map(
(c): DiffResult<typeof c> => ({ type: DiffType.common, value: c })
)
]; ];
} }
const offset = N; const offset = N;
@ -198,8 +204,12 @@ export default function diff<T>(A: T[], B: T[]): Array<DiffResult<T>> {
); );
} }
return [ return [
...prefixCommon.map(c => ({ type: DiffType.common, value: c })), ...prefixCommon.map(
(c): DiffResult<typeof c> => ({ type: DiffType.common, value: c })
),
...backTrace(A, B, fp[delta + offset], swapped), ...backTrace(A, B, fp[delta + offset], swapped),
...suffixCommon.map(c => ({ type: DiffType.common, value: c })) ...suffixCommon.map(
(c): DiffResult<typeof c> => ({ type: DiffType.common, value: c })
)
]; ];
} }

View file

@ -4,14 +4,14 @@ import { test } from "./mod.ts";
test({ test({
name: "empty", name: "empty",
fn() { fn(): void {
assertEquals(diff([], []), []); assertEquals(diff([], []), []);
} }
}); });
test({ test({
name: '"a" vs "b"', name: '"a" vs "b"',
fn() { fn(): void {
assertEquals(diff(["a"], ["b"]), [ assertEquals(diff(["a"], ["b"]), [
{ type: "removed", value: "a" }, { type: "removed", value: "a" },
{ type: "added", value: "b" } { type: "added", value: "b" }
@ -21,28 +21,28 @@ test({
test({ test({
name: '"a" vs "a"', name: '"a" vs "a"',
fn() { fn(): void {
assertEquals(diff(["a"], ["a"]), [{ type: "common", value: "a" }]); assertEquals(diff(["a"], ["a"]), [{ type: "common", value: "a" }]);
} }
}); });
test({ test({
name: '"a" vs ""', name: '"a" vs ""',
fn() { fn(): void {
assertEquals(diff(["a"], []), [{ type: "removed", value: "a" }]); assertEquals(diff(["a"], []), [{ type: "removed", value: "a" }]);
} }
}); });
test({ test({
name: '"" vs "a"', name: '"" vs "a"',
fn() { fn(): void {
assertEquals(diff([], ["a"]), [{ type: "added", value: "a" }]); assertEquals(diff([], ["a"]), [{ type: "added", value: "a" }]);
} }
}); });
test({ test({
name: '"a" vs "a, b"', name: '"a" vs "a, b"',
fn() { fn(): void {
assertEquals(diff(["a"], ["a", "b"]), [ assertEquals(diff(["a"], ["a", "b"]), [
{ type: "common", value: "a" }, { type: "common", value: "a" },
{ type: "added", value: "b" } { type: "added", value: "b" }
@ -52,7 +52,7 @@ test({
test({ test({
name: '"strength" vs "string"', name: '"strength" vs "string"',
fn() { fn(): void {
assertEquals(diff(Array.from("strength"), Array.from("string")), [ assertEquals(diff(Array.from("strength"), Array.from("string")), [
{ type: "common", value: "s" }, { type: "common", value: "s" },
{ type: "common", value: "t" }, { type: "common", value: "t" },
@ -69,7 +69,7 @@ test({
test({ test({
name: '"strength" vs ""', name: '"strength" vs ""',
fn() { fn(): void {
assertEquals(diff(Array.from("strength"), Array.from("")), [ assertEquals(diff(Array.from("strength"), Array.from("")), [
{ type: "removed", value: "s" }, { type: "removed", value: "s" },
{ type: "removed", value: "t" }, { type: "removed", value: "t" },
@ -85,7 +85,7 @@ test({
test({ test({
name: '"" vs "strength"', name: '"" vs "strength"',
fn() { fn(): void {
assertEquals(diff(Array.from(""), Array.from("strength")), [ assertEquals(diff(Array.from(""), Array.from("strength")), [
{ type: "added", value: "s" }, { type: "added", value: "s" },
{ type: "added", value: "t" }, { type: "added", value: "t" },
@ -101,7 +101,7 @@ test({
test({ test({
name: '"abc", "c" vs "abc", "bcd", "c"', name: '"abc", "c" vs "abc", "bcd", "c"',
fn() { fn(): void {
assertEquals(diff(["abc", "c"], ["abc", "bcd", "c"]), [ assertEquals(diff(["abc", "c"], ["abc", "bcd", "c"]), [
{ type: "common", value: "abc" }, { type: "common", value: "abc" },
{ type: "added", value: "bcd" }, { type: "added", value: "bcd" },

View file

@ -358,11 +358,13 @@ const getKeysOfEnumerableProperties = (object: {}): Array<string | symbol> => {
const keys: Array<string | symbol> = Object.keys(object).sort(); const keys: Array<string | symbol> = Object.keys(object).sort();
if (Object.getOwnPropertySymbols) { if (Object.getOwnPropertySymbols) {
Object.getOwnPropertySymbols(object).forEach(symbol => { Object.getOwnPropertySymbols(object).forEach(
(symbol): void => {
if (Object.getOwnPropertyDescriptor(object, symbol)!.enumerable) { if (Object.getOwnPropertyDescriptor(object, symbol)!.enumerable) {
keys.push(symbol); keys.push(symbol);
} }
}); }
);
} }
return keys; return keys;
@ -524,7 +526,7 @@ const getConfig = (options: Options): Config => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
export function format(val: any, options: Optional<Options> = {}): string { export function format(val: any, options: Optional<Options> = {}): string {
const opts = Object.keys(DEFAULT_OPTIONS).reduce( const opts = Object.keys(DEFAULT_OPTIONS).reduce(
(acc: Options, k: keyof Options) => { (acc: Options, k: keyof Options): unknown => {
const opt = options[k]; const opt = options[k];
if (typeof opt === "undefined") { if (typeof opt === "undefined") {
return { ...acc, [k]: DEFAULT_OPTIONS[k] }; return { ...acc, [k]: DEFAULT_OPTIONS[k] };

View file

@ -53,7 +53,7 @@ const createExpected = () =>
test({ test({
name: "prints empty arguments", name: "prints empty arguments",
fn() { fn(): void {
const val = returnArguments(); const val = returnArguments();
assertEquals(format(val), "Arguments []"); assertEquals(format(val), "Arguments []");
} }
@ -61,7 +61,7 @@ test({
test({ test({
name: "prints an empty array", name: "prints an empty array",
fn() { fn(): void {
const val: unknown[] = []; const val: unknown[] = [];
assertEquals(format(val), "Array []"); assertEquals(format(val), "Array []");
} }
@ -69,7 +69,7 @@ test({
test({ test({
name: "prints an array with items", name: "prints an array with items",
fn() { fn(): void {
const val = [1, 2, 3]; const val = [1, 2, 3];
assertEquals(format(val), "Array [\n 1,\n 2,\n 3,\n]"); assertEquals(format(val), "Array [\n 1,\n 2,\n 3,\n]");
} }
@ -77,7 +77,7 @@ test({
test({ test({
name: "prints a empty typed array", name: "prints a empty typed array",
fn() { fn(): void {
const val = new Uint32Array(0); const val = new Uint32Array(0);
assertEquals(format(val), "Uint32Array []"); assertEquals(format(val), "Uint32Array []");
} }
@ -85,7 +85,7 @@ test({
test({ test({
name: "prints a typed array with items", name: "prints a typed array with items",
fn() { fn(): void {
const val = new Uint32Array(3); const val = new Uint32Array(3);
assertEquals(format(val), "Uint32Array [\n 0,\n 0,\n 0,\n]"); assertEquals(format(val), "Uint32Array [\n 0,\n 0,\n 0,\n]");
} }
@ -93,7 +93,7 @@ test({
test({ test({
name: "prints an array buffer", name: "prints an array buffer",
fn() { fn(): void {
const val = new ArrayBuffer(3); const val = new ArrayBuffer(3);
assertEquals(format(val), "ArrayBuffer []"); assertEquals(format(val), "ArrayBuffer []");
} }
@ -101,7 +101,7 @@ test({
test({ test({
name: "prints a nested array", name: "prints a nested array",
fn() { fn(): void {
const val = [[1, 2, 3]]; const val = [[1, 2, 3]];
assertEquals( assertEquals(
format(val), format(val),
@ -112,7 +112,7 @@ test({
test({ test({
name: "prints true", name: "prints true",
fn() { fn(): void {
const val = true; const val = true;
assertEquals(format(val), "true"); assertEquals(format(val), "true");
} }
@ -120,7 +120,7 @@ test({
test({ test({
name: "prints false", name: "prints false",
fn() { fn(): void {
const val = false; const val = false;
assertEquals(format(val), "false"); assertEquals(format(val), "false");
} }
@ -128,7 +128,7 @@ test({
test({ test({
name: "prints an error", name: "prints an error",
fn() { fn(): void {
const val = new Error(); const val = new Error();
assertEquals(format(val), "[Error]"); assertEquals(format(val), "[Error]");
} }
@ -136,7 +136,7 @@ test({
test({ test({
name: "prints a typed error with a message", name: "prints a typed error with a message",
fn() { fn(): void {
const val = new TypeError("message"); const val = new TypeError("message");
assertEquals(format(val), "[TypeError: message]"); assertEquals(format(val), "[TypeError: message]");
} }
@ -144,7 +144,7 @@ test({
test({ test({
name: "prints a function constructor", name: "prints a function constructor",
fn() { fn(): void {
// tslint:disable-next-line:function-constructor // tslint:disable-next-line:function-constructor
const val = new Function(); const val = new Function();
assertEquals(format(val), "[Function anonymous]"); assertEquals(format(val), "[Function anonymous]");
@ -153,20 +153,20 @@ test({
test({ test({
name: "prints an anonymous callback function", name: "prints an anonymous callback function",
fn() { fn(): void {
let val; let val;
function f(cb: () => void): void { function f(cb: () => void): void {
val = cb; val = cb;
} }
// tslint:disable-next-line:no-empty // tslint:disable-next-line:no-empty
f(() => {}); f((): void => {});
assertEquals(format(val), "[Function anonymous]"); assertEquals(format(val), "[Function anonymous]");
} }
}); });
test({ test({
name: "prints an anonymous assigned function", name: "prints an anonymous assigned function",
fn() { fn(): void {
// tslint:disable-next-line:no-empty // tslint:disable-next-line:no-empty
const val = (): void => {}; const val = (): void => {};
const formatted = format(val); const formatted = format(val);
@ -179,7 +179,7 @@ test({
test({ test({
name: "prints a named function", name: "prints a named function",
fn() { fn(): void {
// tslint:disable-next-line:no-empty // tslint:disable-next-line:no-empty
const val = function named(): void {}; const val = function named(): void {};
assertEquals(format(val), "[Function named]"); assertEquals(format(val), "[Function named]");
@ -188,7 +188,7 @@ test({
test({ test({
name: "prints a named generator function", name: "prints a named generator function",
fn() { fn(): void {
const val = function* generate(): IterableIterator<number> { const val = function* generate(): IterableIterator<number> {
yield 1; yield 1;
yield 2; yield 2;
@ -200,7 +200,7 @@ test({
test({ test({
name: "can customize function names", name: "can customize function names",
fn() { fn(): void {
// tslint:disable-next-line:no-empty // tslint:disable-next-line:no-empty
const val = function named(): void {}; const val = function named(): void {};
assertEquals( assertEquals(
@ -214,7 +214,7 @@ test({
test({ test({
name: "prints Infinity", name: "prints Infinity",
fn() { fn(): void {
const val = Infinity; const val = Infinity;
assertEquals(format(val), "Infinity"); assertEquals(format(val), "Infinity");
} }
@ -222,7 +222,7 @@ test({
test({ test({
name: "prints -Infinity", name: "prints -Infinity",
fn() { fn(): void {
const val = -Infinity; const val = -Infinity;
assertEquals(format(val), "-Infinity"); assertEquals(format(val), "-Infinity");
} }
@ -230,7 +230,7 @@ test({
test({ test({
name: "prints an empty map", name: "prints an empty map",
fn() { fn(): void {
const val = new Map(); const val = new Map();
assertEquals(format(val), "Map {}"); assertEquals(format(val), "Map {}");
} }
@ -238,7 +238,7 @@ test({
test({ test({
name: "prints a map with values", name: "prints a map with values",
fn() { fn(): void {
const val = new Map(); const val = new Map();
val.set("prop1", "value1"); val.set("prop1", "value1");
val.set("prop2", "value2"); val.set("prop2", "value2");
@ -251,7 +251,7 @@ test({
test({ test({
name: "prints a map with non-string keys", name: "prints a map with non-string keys",
fn() { fn(): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
const val = new Map<any, any>([ const val = new Map<any, any>([
[false, "boolean"], [false, "boolean"],
@ -294,7 +294,7 @@ test({
test({ test({
name: "prints NaN", name: "prints NaN",
fn() { fn(): void {
const val = NaN; const val = NaN;
assertEquals(format(val), "NaN"); assertEquals(format(val), "NaN");
} }
@ -302,7 +302,7 @@ test({
test({ test({
name: "prints null", name: "prints null",
fn() { fn(): void {
const val = null; const val = null;
assertEquals(format(val), "null"); assertEquals(format(val), "null");
} }
@ -310,7 +310,7 @@ test({
test({ test({
name: "prints a positive number", name: "prints a positive number",
fn() { fn(): void {
const val = 123; const val = 123;
assertEquals(format(val), "123"); assertEquals(format(val), "123");
} }
@ -318,7 +318,7 @@ test({
test({ test({
name: "prints a negative number", name: "prints a negative number",
fn() { fn(): void {
const val = -123; const val = -123;
assertEquals(format(val), "-123"); assertEquals(format(val), "-123");
} }
@ -326,7 +326,7 @@ test({
test({ test({
name: "prints zero", name: "prints zero",
fn() { fn(): void {
const val = 0; const val = 0;
assertEquals(format(val), "0"); assertEquals(format(val), "0");
} }
@ -334,7 +334,7 @@ test({
test({ test({
name: "prints negative zero", name: "prints negative zero",
fn() { fn(): void {
const val = -0; const val = -0;
assertEquals(format(val), "-0"); assertEquals(format(val), "-0");
} }
@ -342,7 +342,7 @@ test({
test({ test({
name: "prints a date", name: "prints a date",
fn() { fn(): void {
const val = new Date(10e11); const val = new Date(10e11);
assertEquals(format(val), "2001-09-09T01:46:40.000Z"); assertEquals(format(val), "2001-09-09T01:46:40.000Z");
} }
@ -350,7 +350,7 @@ test({
test({ test({
name: "prints an invalid date", name: "prints an invalid date",
fn() { fn(): void {
const val = new Date(Infinity); const val = new Date(Infinity);
assertEquals(format(val), "Date { NaN }"); assertEquals(format(val), "Date { NaN }");
} }
@ -358,7 +358,7 @@ test({
test({ test({
name: "prints an empty object", name: "prints an empty object",
fn() { fn(): void {
const val = {}; const val = {};
assertEquals(format(val), "Object {}"); assertEquals(format(val), "Object {}");
} }
@ -366,7 +366,7 @@ test({
test({ test({
name: "prints an object with properties", name: "prints an object with properties",
fn() { fn(): void {
const val = { prop1: "value1", prop2: "value2" }; const val = { prop1: "value1", prop2: "value2" };
assertEquals( assertEquals(
format(val), format(val),
@ -377,7 +377,7 @@ test({
test({ test({
name: "prints an object with properties and symbols", name: "prints an object with properties and symbols",
fn() { fn(): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
const val: any = {}; const val: any = {};
val[Symbol("symbol1")] = "value2"; val[Symbol("symbol1")] = "value2";
@ -393,7 +393,7 @@ test({
test({ test({
name: name:
"prints an object without non-enumerable properties which have string key", "prints an object without non-enumerable properties which have string key",
fn() { fn(): void {
const val = { const val = {
enumerable: true enumerable: true
}; };
@ -409,7 +409,7 @@ test({
test({ test({
name: name:
"prints an object without non-enumerable properties which have symbol key", "prints an object without non-enumerable properties which have symbol key",
fn() { fn(): void {
const val = { const val = {
enumerable: true enumerable: true
}; };
@ -424,7 +424,7 @@ test({
test({ test({
name: "prints an object with sorted properties", name: "prints an object with sorted properties",
fn() { fn(): void {
const val = { b: 1, a: 2 }; const val = { b: 1, a: 2 };
assertEquals(format(val), 'Object {\n "a": 2,\n "b": 1,\n}'); assertEquals(format(val), 'Object {\n "a": 2,\n "b": 1,\n}');
} }
@ -432,7 +432,7 @@ test({
test({ test({
name: "prints regular expressions from constructors", name: "prints regular expressions from constructors",
fn() { fn(): void {
const val = new RegExp("regexp"); const val = new RegExp("regexp");
assertEquals(format(val), "/regexp/"); assertEquals(format(val), "/regexp/");
} }
@ -440,7 +440,7 @@ test({
test({ test({
name: "prints regular expressions from literals", name: "prints regular expressions from literals",
fn() { fn(): void {
const val = /regexp/gi; const val = /regexp/gi;
assertEquals(format(val), "/regexp/gi"); assertEquals(format(val), "/regexp/gi");
} }
@ -448,7 +448,7 @@ test({
test({ test({
name: "prints regular expressions {escapeRegex: false}", name: "prints regular expressions {escapeRegex: false}",
fn() { fn(): void {
const val = /regexp\d/gi; const val = /regexp\d/gi;
assertEquals(format(val), "/regexp\\d/gi"); assertEquals(format(val), "/regexp\\d/gi");
} }
@ -456,7 +456,7 @@ test({
test({ test({
name: "prints regular expressions {escapeRegex: true}", name: "prints regular expressions {escapeRegex: true}",
fn() { fn(): void {
const val = /regexp\d/gi; const val = /regexp\d/gi;
assertEquals(format(val, { escapeRegex: true }), "/regexp\\\\d/gi"); assertEquals(format(val, { escapeRegex: true }), "/regexp\\\\d/gi");
} }
@ -464,7 +464,7 @@ test({
test({ test({
name: "escapes regular expressions nested inside object", name: "escapes regular expressions nested inside object",
fn() { fn(): void {
const obj = { test: /regexp\d/gi }; const obj = { test: /regexp\d/gi };
assertEquals( assertEquals(
format(obj, { escapeRegex: true }), format(obj, { escapeRegex: true }),
@ -475,7 +475,7 @@ test({
test({ test({
name: "prints an empty set", name: "prints an empty set",
fn() { fn(): void {
const val = new Set(); const val = new Set();
assertEquals(format(val), "Set {}"); assertEquals(format(val), "Set {}");
} }
@ -483,7 +483,7 @@ test({
test({ test({
name: "prints a set with values", name: "prints a set with values",
fn() { fn(): void {
const val = new Set(); const val = new Set();
val.add("value1"); val.add("value1");
val.add("value2"); val.add("value2");
@ -493,7 +493,7 @@ test({
test({ test({
name: "prints a string", name: "prints a string",
fn() { fn(): void {
const val = "string"; const val = "string";
assertEquals(format(val), '"string"'); assertEquals(format(val), '"string"');
} }
@ -501,7 +501,7 @@ test({
test({ test({
name: "prints and escape a string", name: "prints and escape a string",
fn() { fn(): void {
const val = "\"'\\"; const val = "\"'\\";
assertEquals(format(val), '"\\"\'\\\\"'); assertEquals(format(val), '"\\"\'\\\\"');
} }
@ -509,7 +509,7 @@ test({
test({ test({
name: "doesn't escape string with {excapeString: false}", name: "doesn't escape string with {excapeString: false}",
fn() { fn(): void {
const val = "\"'\\n"; const val = "\"'\\n";
assertEquals(format(val, { escapeString: false }), '""\'\\n"'); assertEquals(format(val, { escapeString: false }), '""\'\\n"');
} }
@ -517,7 +517,7 @@ test({
test({ test({
name: "prints a string with escapes", name: "prints a string with escapes",
fn() { fn(): void {
assertEquals(format('"-"'), '"\\"-\\""'); assertEquals(format('"-"'), '"\\"-\\""');
assertEquals(format("\\ \\\\"), '"\\\\ \\\\\\\\"'); assertEquals(format("\\ \\\\"), '"\\\\ \\\\\\\\"');
} }
@ -525,7 +525,7 @@ test({
test({ test({
name: "prints a multiline string", name: "prints a multiline string",
fn() { fn(): void {
const val = ["line 1", "line 2", "line 3"].join("\n"); const val = ["line 1", "line 2", "line 3"].join("\n");
assertEquals(format(val), '"' + val + '"'); assertEquals(format(val), '"' + val + '"');
} }
@ -533,7 +533,7 @@ test({
test({ test({
name: "prints a multiline string as value of object property", name: "prints a multiline string as value of object property",
fn() { fn(): void {
const polyline = { const polyline = {
props: { props: {
id: "J", id: "J",
@ -571,7 +571,7 @@ test({
test({ test({
name: "prints a symbol", name: "prints a symbol",
fn() { fn(): void {
const val = Symbol("symbol"); const val = Symbol("symbol");
assertEquals(format(val), "Symbol(symbol)"); assertEquals(format(val), "Symbol(symbol)");
} }
@ -579,7 +579,7 @@ test({
test({ test({
name: "prints undefined", name: "prints undefined",
fn() { fn(): void {
const val = undefined; const val = undefined;
assertEquals(format(val), "undefined"); assertEquals(format(val), "undefined");
} }
@ -587,7 +587,7 @@ test({
test({ test({
name: "prints a WeakMap", name: "prints a WeakMap",
fn() { fn(): void {
const val = new WeakMap(); const val = new WeakMap();
assertEquals(format(val), "WeakMap {}"); assertEquals(format(val), "WeakMap {}");
} }
@ -595,7 +595,7 @@ test({
test({ test({
name: "prints a WeakSet", name: "prints a WeakSet",
fn() { fn(): void {
const val = new WeakSet(); const val = new WeakSet();
assertEquals(format(val), "WeakSet {}"); assertEquals(format(val), "WeakSet {}");
} }
@ -603,7 +603,7 @@ test({
test({ test({
name: "prints deeply nested objects", name: "prints deeply nested objects",
fn() { fn(): void {
const val = { prop: { prop: { prop: "value" } } }; const val = { prop: { prop: { prop: "value" } } };
assertEquals( assertEquals(
format(val), format(val),
@ -614,7 +614,7 @@ test({
test({ test({
name: "prints circular references", name: "prints circular references",
fn() { fn(): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
const val: any = {}; const val: any = {};
val.prop = val; val.prop = val;
@ -624,7 +624,7 @@ test({
test({ test({
name: "prints parallel references", name: "prints parallel references",
fn() { fn(): void {
const inner = {}; const inner = {};
const val = { prop1: inner, prop2: inner }; const val = { prop1: inner, prop2: inner };
assertEquals( assertEquals(
@ -636,14 +636,14 @@ test({
test({ test({
name: "default implicit: 2 spaces", name: "default implicit: 2 spaces",
fn() { fn(): void {
assertEquals(format(createVal()), createExpected()); assertEquals(format(createVal()), createExpected());
} }
}); });
test({ test({
name: "default explicit: 2 spaces", name: "default explicit: 2 spaces",
fn() { fn(): void {
assertEquals(format(createVal(), { indent: 2 }), createExpected()); assertEquals(format(createVal(), { indent: 2 }), createExpected());
} }
}); });
@ -651,7 +651,7 @@ test({
// Tests assume that no strings in val contain multiple adjacent spaces! // Tests assume that no strings in val contain multiple adjacent spaces!
test({ test({
name: "non-default: 0 spaces", name: "non-default: 0 spaces",
fn() { fn(): void {
const indent = 0; const indent = 0;
assertEquals( assertEquals(
format(createVal(), { indent }), format(createVal(), { indent }),
@ -662,7 +662,7 @@ test({
test({ test({
name: "non-default: 4 spaces", name: "non-default: 4 spaces",
fn() { fn(): void {
const indent = 4; const indent = 4;
assertEquals( assertEquals(
format(createVal(), { indent }), format(createVal(), { indent }),
@ -673,7 +673,7 @@ test({
test({ test({
name: "can customize the max depth", name: "can customize the max depth",
fn() { fn(): void {
const v = [ const v = [
{ {
"arguments empty": returnArguments(), "arguments empty": returnArguments(),
@ -719,14 +719,14 @@ test({
test({ test({
name: "prints objects with no constructor", name: "prints objects with no constructor",
fn() { fn(): void {
assertEquals(format(Object.create(null)), "Object {}"); assertEquals(format(Object.create(null)), "Object {}");
} }
}); });
test({ test({
name: "prints identity-obj-proxy with string constructor", name: "prints identity-obj-proxy with string constructor",
fn() { fn(): void {
const obj = Object.create(null); const obj = Object.create(null);
obj.constructor = "constructor"; obj.constructor = "constructor";
const expected = [ const expected = [
@ -740,10 +740,10 @@ test({
test({ test({
name: "calls toJSON and prints its return value", name: "calls toJSON and prints its return value",
fn() { fn(): void {
assertEquals( assertEquals(
format({ format({
toJSON: () => ({ value: false }), toJSON: (): unknown => ({ value: false }),
value: true value: true
}), }),
'Object {\n "value": false,\n}' 'Object {\n "value": false,\n}'
@ -753,10 +753,10 @@ test({
test({ test({
name: "calls toJSON and prints an internal representation.", name: "calls toJSON and prints an internal representation.",
fn() { fn(): void {
assertEquals( assertEquals(
format({ format({
toJSON: () => "[Internal Object]", toJSON: (): string => "[Internal Object]",
value: true value: true
}), }),
'"[Internal Object]"' '"[Internal Object]"'
@ -766,7 +766,7 @@ test({
test({ test({
name: "calls toJSON only on functions", name: "calls toJSON only on functions",
fn() { fn(): void {
assertEquals( assertEquals(
format({ format({
toJSON: false, toJSON: false,
@ -779,10 +779,10 @@ test({
test({ test({
name: "does not call toJSON recursively", name: "does not call toJSON recursively",
fn() { fn(): void {
assertEquals( assertEquals(
format({ format({
toJSON: () => ({ toJSON: () => ({ value: true }) }), toJSON: (): unknown => ({ toJSON: (): unknown => ({ value: true }) }),
value: false value: false
}), }),
'Object {\n "toJSON": [Function toJSON],\n}' 'Object {\n "toJSON": [Function toJSON],\n}'
@ -792,10 +792,10 @@ test({
test({ test({
name: "calls toJSON on Sets", name: "calls toJSON on Sets",
fn() { fn(): void {
const set = new Set([1]); const set = new Set([1]);
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
(set as any).toJSON = () => "map"; (set as any).toJSON = (): string => "map";
assertEquals(format(set), '"map"'); assertEquals(format(set), '"map"');
} }
}); });

View file

@ -212,7 +212,7 @@ export async function runTests({
skip = /^\s*$/ skip = /^\s*$/
}: RunOptions = {}): Promise<void> { }: RunOptions = {}): Promise<void> {
const tests: TestDefinition[] = candidates.filter( const tests: TestDefinition[] = candidates.filter(
({ name }) => only.test(name) && !skip.test(name) ({ name }): boolean => only.test(name) && !skip.test(name)
); );
const stats: TestStats = { const stats: TestStats = {
measured: 0, measured: 0,
@ -232,7 +232,7 @@ export async function runTests({
if (stats.failed) { if (stats.failed) {
// Use setTimeout to avoid the error being ignored due to unhandled // Use setTimeout to avoid the error being ignored due to unhandled
// promise rejections being swallowed. // promise rejections being swallowed.
setTimeout(() => { setTimeout((): void => {
console.error(`There were ${stats.failed} test failures.`); console.error(`There were ${stats.failed} test failures.`);
Deno.exit(1); Deno.exit(1);
}, 0); }, 0);

View file

@ -18,9 +18,9 @@ function createStr(v: unknown): string {
function createColor(diffType: DiffType): (s: string) => string { function createColor(diffType: DiffType): (s: string) => string {
switch (diffType) { switch (diffType) {
case DiffType.added: case DiffType.added:
return (s: string) => green(bold(s)); return (s: string): string => green(bold(s));
case DiffType.removed: case DiffType.removed:
return (s: string) => red(bold(s)); return (s: string): string => red(bold(s));
default: default:
return white; return white;
} }
@ -46,10 +46,12 @@ function buildMessage(diffResult: ReadonlyArray<DiffResult<string>>): string[] {
); );
messages.push(""); messages.push("");
messages.push(""); messages.push("");
diffResult.forEach((result: DiffResult<string>) => { diffResult.forEach(
(result: DiffResult<string>): void => {
const c = createColor(result.type); const c = createColor(result.type);
messages.push(c(`${createSign(result.type)}${result.value}`)); messages.push(c(`${createSign(result.type)}${result.value}`));
}); }
);
messages.push(""); messages.push("");
return messages; return messages;

View file

@ -18,7 +18,7 @@ const removed: (s: string) => string = (s: string): string => red(bold(s));
test({ test({
name: "pass case", name: "pass case",
fn() { fn(): void {
assertEquals({ a: 10 }, { a: 10 }); assertEquals({ a: 10 }, { a: 10 });
assertEquals(true, true); assertEquals(true, true);
assertEquals(10, 10); assertEquals(10, 10);
@ -29,9 +29,9 @@ test({
test({ test({
name: "failed with number", name: "failed with number",
fn() { fn(): void {
assertThrows( assertThrows(
() => assertEquals(1, 2), (): void => assertEquals(1, 2),
Error, Error,
[...createHeader(), removed(`- 1`), added(`+ 2`), ""].join("\n") [...createHeader(), removed(`- 1`), added(`+ 2`), ""].join("\n")
); );
@ -40,9 +40,9 @@ test({
test({ test({
name: "failed with number vs string", name: "failed with number vs string",
fn() { fn(): void {
assertThrows( assertThrows(
() => assertEquals(1, "1"), (): void => assertEquals(1, "1"),
Error, Error,
[...createHeader(), removed(`- 1`), added(`+ "1"`)].join("\n") [...createHeader(), removed(`- 1`), added(`+ "1"`)].join("\n")
); );
@ -51,9 +51,9 @@ test({
test({ test({
name: "failed with array", name: "failed with array",
fn() { fn(): void {
assertThrows( assertThrows(
() => assertEquals([1, "2", 3], ["1", "2", 3]), (): void => assertEquals([1, "2", 3], ["1", "2", 3]),
Error, Error,
[ [
...createHeader(), ...createHeader(),
@ -71,9 +71,9 @@ test({
test({ test({
name: "failed with object", name: "failed with object",
fn() { fn(): void {
assertThrows( assertThrows(
() => assertEquals({ a: 1, b: "2", c: 3 }, { a: 1, b: 2, c: [3] }), (): void => assertEquals({ a: 1, b: "2", c: 3 }, { a: 1, b: 2, c: [3] }),
Error, Error,
[ [
...createHeader(), ...createHeader(),

View file

@ -13,7 +13,7 @@ import "./pretty_test.ts";
import "./asserts_test.ts"; import "./asserts_test.ts";
import "./bench_test.ts"; import "./bench_test.ts";
test(function testingAssertEqualActualUncoercable() { test(function testingAssertEqualActualUncoercable(): void {
let didThrow = false; let didThrow = false;
const a = Object.create(null); const a = Object.create(null);
try { try {
@ -24,7 +24,7 @@ test(function testingAssertEqualActualUncoercable() {
assert(didThrow); assert(didThrow);
}); });
test(function testingAssertEqualExpectedUncoercable() { test(function testingAssertEqualExpectedUncoercable(): void {
let didThrow = false; let didThrow = false;
const a = Object.create(null); const a = Object.create(null);
try { try {
@ -35,13 +35,13 @@ test(function testingAssertEqualExpectedUncoercable() {
assert(didThrow); assert(didThrow);
}); });
test(function testingAssertStrictEqual() { test(function testingAssertStrictEqual(): void {
const a = {}; const a = {};
const b = a; const b = a;
assertStrictEq(a, b); assertStrictEq(a, b);
}); });
test(function testingAssertNotStrictEqual() { test(function testingAssertNotStrictEqual(): void {
let didThrow = false; let didThrow = false;
const a = {}; const a = {};
const b = {}; const b = {};
@ -54,23 +54,27 @@ test(function testingAssertNotStrictEqual() {
assert(didThrow); assert(didThrow);
}); });
test(function testingDoesThrow() { test(function testingDoesThrow(): void {
let count = 0; let count = 0;
assertThrows(() => { assertThrows(
(): void => {
count++; count++;
throw new Error(); throw new Error();
}); }
);
assert(count === 1); assert(count === 1);
}); });
test(function testingDoesNotThrow() { test(function testingDoesNotThrow(): void {
let count = 0; let count = 0;
let didThrow = false; let didThrow = false;
try { try {
assertThrows(() => { assertThrows(
(): void => {
count++; count++;
console.log("Hello world"); console.log("Hello world");
}); }
);
} catch (e) { } catch (e) {
assert(e.message === "Expected function to throw."); assert(e.message === "Expected function to throw.");
didThrow = true; didThrow = true;
@ -79,20 +83,20 @@ test(function testingDoesNotThrow() {
assert(didThrow); assert(didThrow);
}); });
test(function testingThrowsErrorType() { test(function testingThrowsErrorType(): void {
let count = 0; let count = 0;
assertThrows(() => { assertThrows((): void => {
count++; count++;
throw new TypeError(); throw new TypeError();
}, TypeError); }, TypeError);
assert(count === 1); assert(count === 1);
}); });
test(function testingThrowsNotErrorType() { test(function testingThrowsNotErrorType(): void {
let count = 0; let count = 0;
let didThrow = false; let didThrow = false;
try { try {
assertThrows(() => { assertThrows((): void => {
count++; count++;
throw new TypeError(); throw new TypeError();
}, RangeError); }, RangeError);
@ -104,10 +108,10 @@ test(function testingThrowsNotErrorType() {
assert(didThrow); assert(didThrow);
}); });
test(function testingThrowsMsgIncludes() { test(function testingThrowsMsgIncludes(): void {
let count = 0; let count = 0;
assertThrows( assertThrows(
() => { (): void => {
count++; count++;
throw new TypeError("Hello world!"); throw new TypeError("Hello world!");
}, },
@ -117,12 +121,12 @@ test(function testingThrowsMsgIncludes() {
assert(count === 1); assert(count === 1);
}); });
test(function testingThrowsMsgNotIncludes() { test(function testingThrowsMsgNotIncludes(): void {
let count = 0; let count = 0;
let didThrow = false; let didThrow = false;
try { try {
assertThrows( assertThrows(
() => { (): void => {
count++; count++;
throw new TypeError("Hello world!"); throw new TypeError("Hello world!");
}, },
@ -140,32 +144,38 @@ test(function testingThrowsMsgNotIncludes() {
assert(didThrow); assert(didThrow);
}); });
test(async function testingDoesThrowAsync() { test(async function testingDoesThrowAsync(): Promise<void> {
let count = 0; let count = 0;
await assertThrowsAsync(async () => { await assertThrowsAsync(
async (): Promise<void> => {
count++; count++;
throw new Error(); throw new Error();
}); }
);
assert(count === 1); assert(count === 1);
}); });
test(async function testingDoesReject() { test(async function testingDoesReject(): Promise<void> {
let count = 0; let count = 0;
await assertThrowsAsync(() => { await assertThrowsAsync(
(): Promise<never> => {
count++; count++;
return Promise.reject(new Error()); return Promise.reject(new Error());
}); }
);
assert(count === 1); assert(count === 1);
}); });
test(async function testingDoesNotThrowAsync() { test(async function testingDoesNotThrowAsync(): Promise<void> {
let count = 0; let count = 0;
let didThrow = false; let didThrow = false;
try { try {
await assertThrowsAsync(async () => { await assertThrowsAsync(
async (): Promise<void> => {
count++; count++;
console.log("Hello world"); console.log("Hello world");
}); }
);
} catch (e) { } catch (e) {
assert(e.message === "Expected function to throw."); assert(e.message === "Expected function to throw.");
didThrow = true; didThrow = true;
@ -174,15 +184,17 @@ test(async function testingDoesNotThrowAsync() {
assert(didThrow); assert(didThrow);
}); });
test(async function testingDoesNotRejectAsync() { test(async function testingDoesNotRejectAsync(): Promise<void> {
let count = 0; let count = 0;
let didThrow = false; let didThrow = false;
try { try {
await assertThrowsAsync(() => { await assertThrowsAsync(
(): Promise<void> => {
count++; count++;
console.log("Hello world"); console.log("Hello world");
return Promise.resolve(); return Promise.resolve();
}); }
);
} catch (e) { } catch (e) {
assert(e.message === "Expected function to throw."); assert(e.message === "Expected function to throw.");
didThrow = true; didThrow = true;
@ -191,20 +203,20 @@ test(async function testingDoesNotRejectAsync() {
assert(didThrow); assert(didThrow);
}); });
test(async function testingThrowsAsyncErrorType() { test(async function testingThrowsAsyncErrorType(): Promise<void> {
let count = 0; let count = 0;
await assertThrowsAsync(async () => { await assertThrowsAsync((): Promise<void> => {
count++; count++;
throw new TypeError(); throw new TypeError();
}, TypeError); }, TypeError);
assert(count === 1); assert(count === 1);
}); });
test(async function testingThrowsAsyncNotErrorType() { test(async function testingThrowsAsyncNotErrorType(): Promise<void> {
let count = 0; let count = 0;
let didThrow = false; let didThrow = false;
try { try {
await assertThrowsAsync(async () => { await assertThrowsAsync(async (): Promise<void> => {
count++; count++;
throw new TypeError(); throw new TypeError();
}, RangeError); }, RangeError);
@ -216,10 +228,10 @@ test(async function testingThrowsAsyncNotErrorType() {
assert(didThrow); assert(didThrow);
}); });
test(async function testingThrowsAsyncMsgIncludes() { test(async function testingThrowsAsyncMsgIncludes(): Promise<void> {
let count = 0; let count = 0;
await assertThrowsAsync( await assertThrowsAsync(
async () => { async (): Promise<void> => {
count++; count++;
throw new TypeError("Hello world!"); throw new TypeError("Hello world!");
}, },
@ -229,12 +241,12 @@ test(async function testingThrowsAsyncMsgIncludes() {
assert(count === 1); assert(count === 1);
}); });
test(async function testingThrowsAsyncMsgNotIncludes() { test(async function testingThrowsAsyncMsgNotIncludes(): Promise<void> {
let count = 0; let count = 0;
let didThrow = false; let didThrow = false;
try { try {
await assertThrowsAsync( await assertThrowsAsync(
async () => { async (): Promise<void> => {
count++; count++;
throw new TypeError("Hello world!"); throw new TypeError("Hello world!");
}, },

View file

@ -3,13 +3,13 @@ import { runTests } from "./mod.ts";
import "./asserts_test.ts"; import "./asserts_test.ts";
bench(async function testingSerial(b) { bench(async function testingSerial(b): Promise<void> {
b.start(); b.start();
await runTests(); await runTests();
b.stop(); b.stop();
}); });
bench(async function testingParallel(b) { bench(async function testingParallel(b): Promise<void> {
b.start(); b.start();
await runTests({ parallel: true }); await runTests({ parallel: true });
b.stop(); b.stop();

View file

@ -13,7 +13,7 @@ function reader(s: string): TextProtoReader {
return new TextProtoReader(new BufReader(stringsReader(s))); return new TextProtoReader(new BufReader(stringsReader(s)));
} }
test(async function textprotoReader() { test(async function textprotoReader(): Promise<void> {
let r = reader("line1\nline2\n"); let r = reader("line1\nline2\n");
let [s, err] = await r.readLine(); let [s, err] = await r.readLine();
assertEquals(s, "line1"); assertEquals(s, "line1");
@ -44,7 +44,7 @@ test(async function textprotoReadMIMEHeader() {
}); });
*/ */
test(async function textprotoReadMIMEHeaderSingle() { test(async function textprotoReadMIMEHeaderSingle(): Promise<void> {
let r = reader("Foo: bar\n\n"); let r = reader("Foo: bar\n\n");
let [m, err] = await r.readMIMEHeader(); let [m, err] = await r.readMIMEHeader();
assertEquals(m.get("Foo"), "bar"); assertEquals(m.get("Foo"), "bar");
@ -53,7 +53,7 @@ test(async function textprotoReadMIMEHeaderSingle() {
// Test that we read slightly-bogus MIME headers seen in the wild, // Test that we read slightly-bogus MIME headers seen in the wild,
// with spaces before colons, and spaces in keys. // with spaces before colons, and spaces in keys.
test(async function textprotoReadMIMEHeaderNonCompliant() { test(async function textprotoReadMIMEHeaderNonCompliant(): Promise<void> {
// Invalid HTTP response header as sent by an Axis security // Invalid HTTP response header as sent by an Axis security
// camera: (this is handled by IE, Firefox, Chrome, curl, etc.) // camera: (this is handled by IE, Firefox, Chrome, curl, etc.)
let r = reader( let r = reader(
@ -82,7 +82,7 @@ test(async function textprotoReadMIMEHeaderNonCompliant() {
*/ */
}); });
test(async function textprotoAppend() { test(async function textprotoAppend(): Promise<void> {
const enc = new TextEncoder(); const enc = new TextEncoder();
const dec = new TextDecoder(); const dec = new TextDecoder();
const u1 = enc.encode("Hello "); const u1 = enc.encode("Hello ");
@ -91,7 +91,7 @@ test(async function textprotoAppend() {
assertEquals(dec.decode(joined), "Hello World"); assertEquals(dec.decode(joined), "Hello World");
}); });
test(async function textprotoReadEmpty() { test(async function textprotoReadEmpty(): Promise<void> {
let r = reader(""); let r = reader("");
let [, err] = await r.readMIMEHeader(); let [, err] = await r.readMIMEHeader();
// Should not crash! // Should not crash!

View file

@ -399,12 +399,12 @@ class Dumper {
const out = []; const out = [];
const props = Object.keys(obj); const props = Object.keys(obj);
const propObj = props.filter( const propObj = props.filter(
e => (e): boolean =>
(obj[e] instanceof Array && !this._isSimplySerializable(obj[e][0])) || (obj[e] instanceof Array && !this._isSimplySerializable(obj[e][0])) ||
!this._isSimplySerializable(obj[e]) !this._isSimplySerializable(obj[e])
); );
const propPrim = props.filter( const propPrim = props.filter(
e => (e): boolean =>
!(obj[e] instanceof Array && !this._isSimplySerializable(obj[e][0])) && !(obj[e] instanceof Array && !this._isSimplySerializable(obj[e][0])) &&
this._isSimplySerializable(obj[e]) this._isSimplySerializable(obj[e])
); );

View file

@ -7,7 +7,7 @@ const testFilesDir = path.resolve("toml", "testdata");
test({ test({
name: "[TOML] Strings", name: "[TOML] Strings",
fn() { fn(): void {
const expected = { const expected = {
strings: { strings: {
str0: "deno", str0: "deno",
@ -28,7 +28,7 @@ test({
test({ test({
name: "[TOML] CRLF", name: "[TOML] CRLF",
fn() { fn(): void {
const expected = { boolean: { bool1: true, bool2: false } }; const expected = { boolean: { bool1: true, bool2: false } };
const actual = parseFile(path.join(testFilesDir, "CRLF.toml")); const actual = parseFile(path.join(testFilesDir, "CRLF.toml"));
assertEquals(actual, expected); assertEquals(actual, expected);
@ -37,7 +37,7 @@ test({
test({ test({
name: "[TOML] Boolean", name: "[TOML] Boolean",
fn() { fn(): void {
const expected = { boolean: { bool1: true, bool2: false } }; const expected = { boolean: { bool1: true, bool2: false } };
const actual = parseFile(path.join(testFilesDir, "boolean.toml")); const actual = parseFile(path.join(testFilesDir, "boolean.toml"));
assertEquals(actual, expected); assertEquals(actual, expected);
@ -46,7 +46,7 @@ test({
test({ test({
name: "[TOML] Integer", name: "[TOML] Integer",
fn() { fn(): void {
const expected = { const expected = {
integer: { integer: {
int1: 99, int1: 99,
@ -71,7 +71,7 @@ test({
test({ test({
name: "[TOML] Float", name: "[TOML] Float",
fn() { fn(): void {
const expected = { const expected = {
float: { float: {
flt1: 1.0, flt1: 1.0,
@ -97,7 +97,7 @@ test({
test({ test({
name: "[TOML] Arrays", name: "[TOML] Arrays",
fn() { fn(): void {
const expected = { const expected = {
arrays: { arrays: {
data: [["gamma", "delta"], [1, 2]], data: [["gamma", "delta"], [1, 2]],
@ -111,7 +111,7 @@ test({
test({ test({
name: "[TOML] Table", name: "[TOML] Table",
fn() { fn(): void {
const expected = { const expected = {
deeply: { deeply: {
nested: { nested: {
@ -144,7 +144,7 @@ test({
test({ test({
name: "[TOML] Simple", name: "[TOML] Simple",
fn() { fn(): void {
const expected = { const expected = {
deno: "is", deno: "is",
not: "[node]", not: "[node]",
@ -159,7 +159,7 @@ test({
test({ test({
name: "[TOML] Datetime", name: "[TOML] Datetime",
fn() { fn(): void {
const expected = { const expected = {
datetime: { datetime: {
odt1: new Date("1979-05-27T07:32:00Z"), odt1: new Date("1979-05-27T07:32:00Z"),
@ -178,7 +178,7 @@ test({
test({ test({
name: "[TOML] Inline Table", name: "[TOML] Inline Table",
fn() { fn(): void {
const expected = { const expected = {
inlinetable: { inlinetable: {
nile: { nile: {
@ -223,7 +223,7 @@ test({
test({ test({
name: "[TOML] Array of Tables", name: "[TOML] Array of Tables",
fn() { fn(): void {
const expected = { const expected = {
bin: [ bin: [
{ name: "deno", path: "cli/main.rs" }, { name: "deno", path: "cli/main.rs" },
@ -238,7 +238,7 @@ test({
test({ test({
name: "[TOML] Cargo", name: "[TOML] Cargo",
fn() { fn(): void {
/* eslint-disable @typescript-eslint/camelcase */ /* eslint-disable @typescript-eslint/camelcase */
const expected = { const expected = {
workspace: { members: ["./", "core"] }, workspace: { members: ["./", "core"] },
@ -285,7 +285,7 @@ test({
test({ test({
name: "[TOML] Stringify", name: "[TOML] Stringify",
fn() { fn(): void {
const src = { const src = {
foo: { bar: "deno" }, foo: { bar: "deno" },
this: { is: { nested: "denonono" } }, this: { is: { nested: "denonono" } },

View file

@ -5,7 +5,8 @@ export function deepAssign(target: object, ...sources: object[]): object {
if (!source || typeof source !== `object`) { if (!source || typeof source !== `object`) {
return; return;
} }
Object.entries(source).forEach(([key, value]) => { Object.entries(source).forEach(
([key, value]): void => {
if (value instanceof Date) { if (value instanceof Date) {
target[key] = new Date(value); target[key] = new Date(value);
return; return;
@ -22,7 +23,8 @@ export function deepAssign(target: object, ...sources: object[]): object {
target[key] = {}; target[key] = {};
} }
deepAssign(target[key], value); deepAssign(target[key], value);
}); }
);
} }
return target; return target;
} }

View file

@ -3,7 +3,7 @@ import { test } from "../testing/mod.ts";
import { assertEquals, assert } from "../testing/asserts.ts"; import { assertEquals, assert } from "../testing/asserts.ts";
import { deepAssign } from "./deep_assign.ts"; import { deepAssign } from "./deep_assign.ts";
test(function deepAssignTest() { test(function deepAssignTest(): void {
const date = new Date("1979-05-27T07:32:00Z"); const date = new Date("1979-05-27T07:32:00Z");
const reg = RegExp(/DENOWOWO/); const reg = RegExp(/DENOWOWO/);
const obj1 = { deno: { bar: { deno: ["is", "not", "node"] } } }; const obj1 = { deno: { bar: { deno: ["is", "not", "node"] } } };

View file

@ -3,20 +3,20 @@ import { test } from "../testing/mod.ts";
import { assertEquals } from "../testing/asserts.ts"; import { assertEquals } from "../testing/asserts.ts";
import { Sha1 } from "./sha1.ts"; import { Sha1 } from "./sha1.ts";
test(function testSha1() { test(function testSha1(): void {
const sha1 = new Sha1(); const sha1 = new Sha1();
sha1.update("abcde"); sha1.update("abcde");
assertEquals(sha1.toString(), "03de6c570bfe24bfc328ccd7ca46b76eadaf4334"); assertEquals(sha1.toString(), "03de6c570bfe24bfc328ccd7ca46b76eadaf4334");
}); });
test(function testSha1WithArray() { test(function testSha1WithArray(): void {
const data = Uint8Array.of(0x61, 0x62, 0x63, 0x64, 0x65); const data = Uint8Array.of(0x61, 0x62, 0x63, 0x64, 0x65);
const sha1 = new Sha1(); const sha1 = new Sha1();
sha1.update(data); sha1.update(data);
assertEquals(sha1.toString(), "03de6c570bfe24bfc328ccd7ca46b76eadaf4334"); assertEquals(sha1.toString(), "03de6c570bfe24bfc328ccd7ca46b76eadaf4334");
}); });
test(function testSha1WithBuffer() { test(function testSha1WithBuffer(): void {
const data = Uint8Array.of(0x61, 0x62, 0x63, 0x64, 0x65); const data = Uint8Array.of(0x61, 0x62, 0x63, 0x64, 0x65);
const sha1 = new Sha1(); const sha1 = new Sha1();
sha1.update(data.buffer); sha1.update(data.buffer);

View file

@ -13,7 +13,7 @@ import {
unmask unmask
} from "./mod.ts"; } from "./mod.ts";
test(async function testReadUnmaskedTextFrame() { test(async function testReadUnmaskedTextFrame(): Promise<void> {
// unmasked single text frame with payload "Hello" // unmasked single text frame with payload "Hello"
const buf = new BufReader( const buf = new BufReader(
new Buffer(new Uint8Array([0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f])) new Buffer(new Uint8Array([0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f]))
@ -25,7 +25,7 @@ test(async function testReadUnmaskedTextFrame() {
assertEquals(frame.isLastFrame, true); assertEquals(frame.isLastFrame, true);
}); });
test(async function testReadMakedTextFrame() { test(async function testReadMakedTextFrame(): Promise<void> {
//a masked single text frame with payload "Hello" //a masked single text frame with payload "Hello"
const buf = new BufReader( const buf = new BufReader(
new Buffer( new Buffer(
@ -52,7 +52,7 @@ test(async function testReadMakedTextFrame() {
assertEquals(frame.isLastFrame, true); assertEquals(frame.isLastFrame, true);
}); });
test(async function testReadUnmaskedSplittedTextFrames() { test(async function testReadUnmaskedSplittedTextFrames(): Promise<void> {
const buf1 = new BufReader( const buf1 = new BufReader(
new Buffer(new Uint8Array([0x01, 0x03, 0x48, 0x65, 0x6c])) new Buffer(new Uint8Array([0x01, 0x03, 0x48, 0x65, 0x6c]))
); );
@ -71,7 +71,7 @@ test(async function testReadUnmaskedSplittedTextFrames() {
assertEquals(new Buffer(f2.payload).toString(), "lo"); assertEquals(new Buffer(f2.payload).toString(), "lo");
}); });
test(async function testReadUnmaksedPingPongFrame() { test(async function testReadUnmaksedPingPongFrame(): Promise<void> {
// unmasked ping with payload "Hello" // unmasked ping with payload "Hello"
const buf = new BufReader( const buf = new BufReader(
new Buffer(new Uint8Array([0x89, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f])) new Buffer(new Uint8Array([0x89, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f]))
@ -104,7 +104,7 @@ test(async function testReadUnmaksedPingPongFrame() {
assertEquals(new Buffer(pong.payload).toString(), "Hello"); assertEquals(new Buffer(pong.payload).toString(), "Hello");
}); });
test(async function testReadUnmaksedBigBinaryFrame() { test(async function testReadUnmaksedBigBinaryFrame(): Promise<void> {
const a = [0x82, 0x7e, 0x01, 0x00]; const a = [0x82, 0x7e, 0x01, 0x00];
for (let i = 0; i < 256; i++) { for (let i = 0; i < 256; i++) {
a.push(i); a.push(i);
@ -117,7 +117,7 @@ test(async function testReadUnmaksedBigBinaryFrame() {
assertEquals(bin.payload.length, 256); assertEquals(bin.payload.length, 256);
}); });
test(async function testReadUnmaskedBigBigBinaryFrame() { test(async function testReadUnmaskedBigBigBinaryFrame(): Promise<void> {
const a = [0x82, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00]; const a = [0x82, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00];
for (let i = 0; i < 0xffff; i++) { for (let i = 0; i < 0xffff; i++) {
a.push(i); a.push(i);
@ -130,13 +130,13 @@ test(async function testReadUnmaskedBigBigBinaryFrame() {
assertEquals(bin.payload.length, 0xffff + 1); assertEquals(bin.payload.length, 0xffff + 1);
}); });
test(async function testCreateSecAccept() { test(async function testCreateSecAccept(): Promise<void> {
const nonce = "dGhlIHNhbXBsZSBub25jZQ=="; const nonce = "dGhlIHNhbXBsZSBub25jZQ==";
const d = createSecAccept(nonce); const d = createSecAccept(nonce);
assertEquals(d, "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="); assertEquals(d, "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=");
}); });
test(function testAcceptable() { test(function testAcceptable(): void {
const ret = acceptable({ const ret = acceptable({
headers: new Headers({ headers: new Headers({
upgrade: "websocket", upgrade: "websocket",
@ -153,7 +153,7 @@ const invalidHeaders = [
{ upgrade: "websocket", "sec-websocket-ky": "" } { upgrade: "websocket", "sec-websocket-ky": "" }
]; ];
test(function testAcceptableInvalid() { test(function testAcceptableInvalid(): void {
for (const pat of invalidHeaders) { for (const pat of invalidHeaders) {
const ret = acceptable({ const ret = acceptable({
headers: new Headers(pat) headers: new Headers(pat)