diff --git a/.gitignore b/.gitignore index bb7de9d001..af7c9e4793 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ deno.d.ts node_modules package.json package-lock.json +.vscode diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 262061005b..507d580f7a 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -12,7 +12,7 @@ jobs: - 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: 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-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: curl -L https://deno.land/x/install/install.sh | sh -s $(DENO_VERSION) - 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-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 - 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: 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-net --allow-write --allow-read test.ts diff --git a/bytes/bytes_test.ts b/bytes/bytes_test.ts index b91991eb3e..c0aa1519dd 100644 --- a/bytes/bytes_test.ts +++ b/bytes/bytes_test.ts @@ -7,7 +7,7 @@ import { import { test } from "../testing/mod.ts"; import { assertEquals } from "../testing/asserts.ts"; -test(function bytesBytesFindIndex() { +test(function bytesBytesFindIndex(): void { const i = bytesFindIndex( new Uint8Array([1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 3]), new Uint8Array([0, 1, 2]) @@ -15,7 +15,7 @@ test(function bytesBytesFindIndex() { assertEquals(i, 2); }); -test(function bytesBytesFindLastIndex1() { +test(function bytesBytesFindLastIndex1(): void { const i = bytesFindLastIndex( new Uint8Array([0, 1, 2, 0, 1, 2, 0, 1, 3]), new Uint8Array([0, 1, 2]) @@ -23,7 +23,7 @@ test(function bytesBytesFindLastIndex1() { assertEquals(i, 3); }); -test(function bytesBytesBytesEqual() { +test(function bytesBytesBytesEqual(): void { const v = bytesEqual( new Uint8Array([0, 1, 2, 3]), new Uint8Array([0, 1, 2, 3]) @@ -31,7 +31,7 @@ test(function bytesBytesBytesEqual() { assertEquals(v, true); }); -test(function bytesBytesHasPrefix() { +test(function bytesBytesHasPrefix(): void { const v = bytesHasPrefix(new Uint8Array([0, 1, 2]), new Uint8Array([0, 1])); assertEquals(v, true); }); diff --git a/colors/test.ts b/colors/test.ts index 6f3f7e5a8b..26e34c742c 100644 --- a/colors/test.ts +++ b/colors/test.ts @@ -4,19 +4,19 @@ import { assertEquals } from "../testing/asserts.ts"; import { red, bgBlue, setEnabled, getEnabled } from "./mod.ts"; import "../examples/colors.ts"; -test(function singleColor() { +test(function singleColor(): void { assertEquals(red("Hello world"), "Hello world"); }); -test(function doubleColor() { +test(function doubleColor(): void { assertEquals(bgBlue(red("Hello world")), "Hello world"); }); -test(function replacesCloseCharacters() { +test(function replacesCloseCharacters(): void { assertEquals(red("Hello"), "Hello"); }); -test(function enablingColors() { +test(function enablingColors(): void { assertEquals(getEnabled(), true); setEnabled(false); assertEquals(bgBlue(red("Hello world")), "Hello world"); diff --git a/datetime/test.ts b/datetime/test.ts index dcbc166a5b..95bcd36533 100644 --- a/datetime/test.ts +++ b/datetime/test.ts @@ -3,7 +3,7 @@ import { test } from "../testing/mod.ts"; import { assert, assertEquals } from "../testing/asserts.ts"; import * as datetime from "./mod.ts"; -test(function parseDateTime() { +test(function parseDateTime(): void { assertEquals( datetime.parseDateTime("01-03-2019 16:30", "mm-dd-yyyy hh:mm"), new Date(2019, 0, 3, 16, 30) @@ -30,7 +30,7 @@ test(function parseDateTime() { ); }); -test(function invalidParseDateTimeFormatThrows() { +test(function invalidParseDateTimeFormatThrows(): void { try { // eslint-disable-next-line @typescript-eslint/no-explicit-any (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( datetime.parseDate("01-03-2019", "mm-dd-yyyy"), new Date(2019, 0, 3) @@ -55,7 +55,7 @@ test(function parseDate() { ); }); -test(function invalidParseDateFormatThrows() { +test(function invalidParseDateFormatThrows(): void { try { // eslint-disable-next-line @typescript-eslint/no-explicit-any (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(70, datetime.dayOfYear(new Date("2019-03-11T03: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())); }); diff --git a/examples/echo_server.ts b/examples/echo_server.ts index 95b9f74131..970df4f8d7 100644 --- a/examples/echo_server.ts +++ b/examples/echo_server.ts @@ -1,7 +1,7 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. const { listen, copy } = Deno; -(async () => { +(async (): Promise => { const addr = "0.0.0.0:8080"; const listener = listen("tcp", addr); console.log("listening on", addr); diff --git a/examples/test.ts b/examples/test.ts index a8f4e3548a..17d19a312b 100644 --- a/examples/test.ts +++ b/examples/test.ts @@ -4,16 +4,16 @@ import { test } from "../testing/mod.ts"; import { assertEquals } from "../testing/asserts.ts"; /** Example of how to do basic tests */ -test(function t1() { +test(function t1(): void { assertEquals("hello", "hello"); }); -test(function t2() { +test(function t2(): void { assertEquals("world", "world"); }); /** A more complicated test that runs a subprocess. */ -test(async function catSmoke() { +test(async function catSmoke(): Promise { const p = run({ args: ["deno", "--allow-read", "examples/cat.ts", "README.md"], stdout: "piped" diff --git a/examples/ws.ts b/examples/ws.ts index 83e890bc03..f5965b7eb4 100644 --- a/examples/ws.ts +++ b/examples/ws.ts @@ -10,7 +10,7 @@ async function main(): Promise { console.log("websocket server is running on 0.0.0.0:8080"); for await (const req of serve("0.0.0.0:8080")) { if (req.url === "/ws") { - (async () => { + (async (): Promise => { const sock = await acceptWebSocket(req); console.log("socket connected!"); for await (const ev of sock.receive()) { diff --git a/flags/all_bool_test.ts b/flags/all_bool_test.ts index 59779c7792..22b6bcd2d2 100755 --- a/flags/all_bool_test.ts +++ b/flags/all_bool_test.ts @@ -4,7 +4,7 @@ import { assertEquals } from "../testing/asserts.ts"; import { parse } from "./mod.ts"; // flag boolean true (default all --args to boolean) -test(function flagBooleanTrue() { +test(function flagBooleanTrue(): void { const argv = parse(["moo", "--honk", "cow"], { boolean: true }); @@ -18,7 +18,7 @@ test(function flagBooleanTrue() { }); // 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"], { boolean: true }); diff --git a/flags/bool_test.ts b/flags/bool_test.ts index 820393543f..a33e9be0b1 100755 --- a/flags/bool_test.ts +++ b/flags/bool_test.ts @@ -3,7 +3,7 @@ import { test } from "../testing/mod.ts"; import { assertEquals } from "../testing/asserts.ts"; import { parse } from "./mod.ts"; -test(function flagBooleanDefaultFalse() { +test(function flagBooleanDefaultFalse(): void { const argv = parse(["moo"], { boolean: ["t", "verbose"], default: { verbose: false, t: false } @@ -19,7 +19,7 @@ test(function flagBooleanDefaultFalse() { assertEquals(typeof argv.t, "boolean"); }); -test(function booleanGroups() { +test(function booleanGroups(): void { const argv = parse(["-x", "-z", "one", "two", "three"], { boolean: ["x", "y", "z"] }); @@ -36,7 +36,7 @@ test(function booleanGroups() { assertEquals(typeof argv.z, "boolean"); }); -test(function booleanAndAliasWithChainableApi() { +test(function booleanAndAliasWithChainableApi(): void { const aliased = ["-h", "derp"]; const regular = ["--herp", "derp"]; const aliasedArgv = parse(aliased, { @@ -57,7 +57,7 @@ test(function booleanAndAliasWithChainableApi() { assertEquals(propertyArgv, expected); }); -test(function booleanAndAliasWithOptionsHash() { +test(function booleanAndAliasWithOptionsHash(): void { const aliased = ["-h", "derp"]; const regular = ["--herp", "derp"]; const opts = { @@ -75,7 +75,7 @@ test(function booleanAndAliasWithOptionsHash() { assertEquals(propertyArgv, expected); }); -test(function booleanAndAliasArrayWithOptionsHash() { +test(function booleanAndAliasArrayWithOptionsHash(): void { const aliased = ["-h", "derp"]; const regular = ["--herp", "derp"]; const alt = ["--harp", "derp"]; @@ -97,7 +97,7 @@ test(function booleanAndAliasArrayWithOptionsHash() { assertEquals(altPropertyArgv, expected); }); -test(function booleanAndAliasUsingExplicitTrue() { +test(function booleanAndAliasUsingExplicitTrue(): void { const aliased = ["-h", "true"]; const regular = ["--herp", "true"]; const opts = { @@ -118,7 +118,7 @@ test(function booleanAndAliasUsingExplicitTrue() { // regression, see https://github.com/substack/node-optimist/issues/71 // boolean and --x=true -test(function booleanAndNonBoolean() { +test(function booleanAndNonBoolean(): void { const parsed = parse(["--boool", "--other=true"], { boolean: "boool" }); @@ -134,7 +134,7 @@ test(function booleanAndNonBoolean() { assertEquals(parsed2.other, "false"); }); -test(function booleanParsingTrue() { +test(function booleanParsingTrue(): void { const parsed = parse(["--boool=true"], { default: { boool: false @@ -145,7 +145,7 @@ test(function booleanParsingTrue() { assertEquals(parsed.boool, true); }); -test(function booleanParsingFalse() { +test(function booleanParsingFalse(): void { const parsed = parse(["--boool=false"], { default: { boool: true diff --git a/flags/dash_test.ts b/flags/dash_test.ts index 7d52e4905e..f4901b3523 100755 --- a/flags/dash_test.ts +++ b/flags/dash_test.ts @@ -3,7 +3,7 @@ import { test } from "../testing/mod.ts"; import { assertEquals } from "../testing/asserts.ts"; import { parse } from "./mod.ts"; -test(function hyphen() { +test(function hyphen(): void { assertEquals(parse(["-n", "-"]), { n: "-", _: [] }); assertEquals(parse(["-"]), { _: ["-"] }); assertEquals(parse(["-f-"]), { f: "-", _: [] }); @@ -11,13 +11,13 @@ test(function hyphen() { 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"] }); }); -test(function moveArgsAfterDoubleDashIntoOwnArray() { +test(function moveArgsAfterDoubleDashIntoOwnArray(): void { assertEquals( parse(["--name", "John", "before", "--", "after"], { "--": true }), { diff --git a/flags/default_bool_test.ts b/flags/default_bool_test.ts index a1a329074b..dc953cdc89 100755 --- a/flags/default_bool_test.ts +++ b/flags/default_bool_test.ts @@ -3,7 +3,7 @@ import { test } from "../testing/mod.ts"; import { assertEquals } from "../testing/asserts.ts"; import { parse } from "./mod.ts"; -test(function booleanDefaultTrue() { +test(function booleanDefaultTrue(): void { const argv = parse([], { boolean: "sometrue", default: { sometrue: true } @@ -11,7 +11,7 @@ test(function booleanDefaultTrue() { assertEquals(argv.sometrue, true); }); -test(function booleanDefaultFalse() { +test(function booleanDefaultFalse(): void { const argv = parse([], { boolean: "somefalse", default: { somefalse: false } @@ -19,7 +19,7 @@ test(function booleanDefaultFalse() { assertEquals(argv.somefalse, false); }); -test(function booleanDefaultNull() { +test(function booleanDefaultNull(): void { const argv = parse([], { boolean: "maybe", default: { maybe: null } diff --git a/flags/dotted_test.ts b/flags/dotted_test.ts index d5a4918152..6a27eb6f77 100755 --- a/flags/dotted_test.ts +++ b/flags/dotted_test.ts @@ -3,7 +3,7 @@ import { test } from "../testing/mod.ts"; import { assertEquals } from "../testing/asserts.ts"; import { parse } from "./mod.ts"; -test(function dottedAlias() { +test(function dottedAlias(): void { const argv = parse(["--a.b", "22"], { default: { "a.b": 11 }, alias: { "a.b": "aa.bb" } @@ -12,13 +12,13 @@ test(function dottedAlias() { assertEquals(argv.aa.bb, 22); }); -test(function dottedDefault() { +test(function dottedDefault(): void { const argv = parse("", { default: { "a.b": 11 }, alias: { "a.b": "aa.bb" } }); assertEquals(argv.a.b, 11); assertEquals(argv.aa.bb, 11); }); -test(function dottedDefaultWithNoAlias() { +test(function dottedDefaultWithNoAlias(): void { const argv = parse("", { default: { "a.b": 11 } }); assertEquals(argv.a.b, 11); }); diff --git a/flags/kv_short_test.ts b/flags/kv_short_test.ts index 0cd93df02a..271e5c67d9 100755 --- a/flags/kv_short_test.ts +++ b/flags/kv_short_test.ts @@ -3,12 +3,12 @@ import { test } from "../testing/mod.ts"; import { assertEquals } from "../testing/asserts.ts"; import { parse } from "./mod.ts"; -test(function short() { +test(function short(): void { const argv = parse(["-b=123"]); assertEquals(argv, { b: 123, _: [] }); }); -test(function multiShort() { +test(function multiShort(): void { const argv = parse(["-a=whatever", "-b=robots"]); assertEquals(argv, { a: "whatever", b: "robots", _: [] }); }); diff --git a/flags/long_test.ts b/flags/long_test.ts index fb26a4c07f..5b14fc630e 100755 --- a/flags/long_test.ts +++ b/flags/long_test.ts @@ -3,7 +3,7 @@ import { test } from "../testing/mod.ts"; import { assertEquals } from "../testing/asserts.ts"; import { parse } from "./mod.ts"; -test(function longOpts() { +test(function longOpts(): void { assertEquals(parse(["--bool"]), { bool: true, _: [] }); assertEquals(parse(["--pow", "xixxle"]), { pow: "xixxle", _: [] }); assertEquals(parse(["--pow=xixxle"]), { pow: "xixxle", _: [] }); diff --git a/flags/mod.ts b/flags/mod.ts index 0c0702e8bc..433f4eb154 100644 --- a/flags/mod.ts +++ b/flags/mod.ts @@ -10,7 +10,7 @@ export interface ArgParsingOptions { } const DEFAULT_OPTIONS = { - unknown: i => i, + unknown: (i): unknown => i, boolean: false, alias: {}, string: [], @@ -27,7 +27,7 @@ function isNumber(x: unknown): boolean { function hasKey(obj, keys): boolean { let o = obj; - keys.slice(0, -1).forEach(function(key) { + keys.slice(0, -1).forEach(function(key): void { o = o[key] || {}; }); @@ -38,8 +38,8 @@ function hasKey(obj, keys): boolean { export function parse( args, initialOptions?: ArgParsingOptions + // eslint-disable-next-line @typescript-eslint/no-explicit-any ): { [key: string]: any } { - // eslint-disable-line @typescript-eslint/no-explicit-any const options: ArgParsingOptions = { ...DEFAULT_OPTIONS, ...(initialOptions || {}) @@ -59,17 +59,17 @@ export function parse( [] .concat(options["boolean"]) .filter(Boolean) - .forEach(function(key) { + .forEach(function(key): void { flags.bools[key] = true; }); } 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].forEach(function(x) { + aliases[key].forEach(function(x): void { aliases[x] = [key].concat( - aliases[key].filter(function(y) { + aliases[key].filter(function(y): boolean { return x !== y; }) ); @@ -79,7 +79,7 @@ export function parse( [] .concat(options.string) .filter(Boolean) - .forEach(function(key) { + .forEach(function(key): void { flags.strings[key] = true; if (aliases[key]) { flags.strings[aliases[key]] = true; @@ -101,7 +101,7 @@ export function parse( function setKey(obj, keys, value): void { let o = obj; - keys.slice(0, -1).forEach(function(key) { + keys.slice(0, -1).forEach(function(key): void { if (o[key] === undefined) o[key] = {}; o = o[key]; }); @@ -128,18 +128,18 @@ export function parse( const value = !flags.strings[key] && isNumber(val) ? Number(val) : val; setKey(argv, key.split("."), value); - (aliases[key] || []).forEach(function(x) { + (aliases[key] || []).forEach(function(x): void { setKey(argv, x.split("."), value); }); } function aliasIsBoolean(key): boolean { - return aliases[key].some(function(x) { + return aliases[key].some(function(x): boolean { 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]); }); @@ -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("."))) { setKey(argv, key.split("."), defaults[key]); - (aliases[key] || []).forEach(function(x) { + (aliases[key] || []).forEach(function(x): void { setKey(argv, x.split("."), defaults[key]); }); } @@ -261,11 +261,11 @@ export function parse( if (options["--"]) { argv["--"] = []; - notFlags.forEach(function(key) { + notFlags.forEach(function(key): void { argv["--"].push(key); }); } else { - notFlags.forEach(function(key) { + notFlags.forEach(function(key): void { argv._.push(key); }); } diff --git a/flags/num_test.ts b/flags/num_test.ts index 752e1752fa..1123f7ecc1 100755 --- a/flags/num_test.ts +++ b/flags/num_test.ts @@ -3,7 +3,7 @@ import { test } from "../testing/mod.ts"; import { assertEquals } from "../testing/asserts.ts"; import { parse } from "./mod.ts"; -test(function nums() { +test(function nums(): void { const argv = parse([ "-x", "1234", @@ -33,7 +33,7 @@ test(function nums() { assertEquals(typeof argv._[0], "number"); }); -test(function alreadyNumber() { +test(function alreadyNumber(): void { const argv = parse(["-x", 1234, 789]); assertEquals(argv, { x: 1234, _: [789] }); assertEquals(typeof argv.x, "number"); diff --git a/flags/parse_test.ts b/flags/parse_test.ts index dbcdb4a863..2e154f78c9 100755 --- a/flags/parse_test.ts +++ b/flags/parse_test.ts @@ -3,7 +3,7 @@ import { test } from "../testing/mod.ts"; import { assertEquals } from "../testing/asserts.ts"; import { parse } from "./mod.ts"; -test(function _arseArgs() { +test(function _arseArgs(): void { assertEquals(parse(["--no-moo"]), { moo: false, _: [] }); assertEquals(parse(["-v", "a", "-v", "b", "-v", "c"]), { v: ["a", "b", "c"], @@ -11,7 +11,7 @@ test(function _arseArgs() { }); }); -test(function comprehensive() { +test(function comprehensive(): void { assertEquals( parse([ "--name=meowmers", @@ -48,13 +48,13 @@ test(function comprehensive() { ); }); -test(function flagBoolean() { +test(function flagBoolean(): void { const argv = parse(["-t", "moo"], { boolean: "t" }); assertEquals(argv, { t: true, _: ["moo"] }); assertEquals(typeof argv.t, "boolean"); }); -test(function flagBooleanValue() { +test(function flagBooleanValue(): void { const argv = parse(["--verbose", "false", "moo", "-t", "true"], { boolean: ["t", "verbose"], default: { verbose: true } @@ -70,7 +70,7 @@ test(function flagBooleanValue() { assertEquals(typeof argv.t, "boolean"); }); -test(function newlinesInParams() { +test(function newlinesInParams(): void { const args = parse(["-s", "X\nX"]); assertEquals(args, { _: [], s: "X\nX" }); @@ -82,7 +82,7 @@ test(function newlinesInParams() { assertEquals(args2, { _: [], s: "X\nX" }); }); -test(function strings() { +test(function strings(): void { const s = parse(["-s", "0001234"], { string: "s" }).s; assertEquals(s, "0001234"); assertEquals(typeof s, "string"); @@ -92,7 +92,7 @@ test(function strings() { assertEquals(typeof x, "string"); }); -test(function stringArgs() { +test(function stringArgs(): void { const s = parse([" ", " "], { string: "_" })._; assertEquals(s.length, 2); assertEquals(typeof s[0], "string"); @@ -101,7 +101,7 @@ test(function stringArgs() { assertEquals(s[1], " "); }); -test(function emptyStrings() { +test(function emptyStrings(): void { const s = parse(["-s"], { string: "s" }).s; assertEquals(s, ""); assertEquals(typeof s, "string"); @@ -119,7 +119,7 @@ test(function emptyStrings() { assertEquals(letters.t, ""); }); -test(function stringAndAlias() { +test(function stringAndAlias(): void { const x = parse(["--str", "000123"], { string: "s", alias: { s: "str" } @@ -141,7 +141,7 @@ test(function stringAndAlias() { assertEquals(typeof y.s, "string"); }); -test(function slashBreak() { +test(function slashBreak(): void { assertEquals(parse(["-I/foo/bar/baz"]), { I: "/foo/bar/baz", _: [] }); assertEquals(parse(["-xyz/foo/bar/baz"]), { x: true, @@ -151,7 +151,7 @@ test(function slashBreak() { }); }); -test(function alias() { +test(function alias(): void { const argv = parse(["-f", "11", "--zoom", "55"], { alias: { z: "zoom" } }); @@ -160,7 +160,7 @@ test(function alias() { assertEquals(argv.f, 11); }); -test(function multiAlias() { +test(function multiAlias(): void { const argv = parse(["-f", "11", "--zoom", "55"], { alias: { z: ["zm", "zoom"] } }); @@ -170,7 +170,7 @@ test(function multiAlias() { assertEquals(argv.f, 11); }); -test(function nestedDottedObjects() { +test(function nestedDottedObjects(): void { const argv = parse([ "--foo.bar", "3", diff --git a/flags/short_test.ts b/flags/short_test.ts index 700902dd74..f624381b16 100755 --- a/flags/short_test.ts +++ b/flags/short_test.ts @@ -3,12 +3,12 @@ import { test } from "../testing/mod.ts"; import { assertEquals } from "../testing/asserts.ts"; import { parse } from "./mod.ts"; -test(function numbericShortArgs() { +test(function numbericShortArgs(): void { assertEquals(parse(["-n123"]), { n: 123, _: [] }); assertEquals(parse(["-123", "456"]), { 1: true, 2: true, 3: 456, _: [] }); }); -test(function short() { +test(function short(): void { assertEquals(parse(["-b"]), { b: true, _: [] }); assertEquals(parse(["foo", "bar", "baz"]), { _: ["foo", "bar", "baz"] }); 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"]), { f: true, p: 555, @@ -36,7 +36,7 @@ test(function mixedShortBoolAndCapture() { }); }); -test(function shortAndLong() { +test(function shortAndLong(): void { assertEquals(parse(["-h", "localhost", "-fp", "555", "script.js"]), { f: true, p: 555, diff --git a/flags/stop_early_test.ts b/flags/stop_early_test.ts index 70194adfe4..144a2921f8 100755 --- a/flags/stop_early_test.ts +++ b/flags/stop_early_test.ts @@ -4,7 +4,7 @@ import { assertEquals } from "../testing/asserts.ts"; import { parse } from "./mod.ts"; // 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"], { stopEarly: true }); diff --git a/flags/unknown_test.ts b/flags/unknown_test.ts index fcb47e36b4..84d4db8995 100755 --- a/flags/unknown_test.ts +++ b/flags/unknown_test.ts @@ -3,7 +3,7 @@ import { test } from "../testing/mod.ts"; import { assertEquals } from "../testing/asserts.ts"; import { parse } from "./mod.ts"; -test(function booleanAndAliasIsNotUnknown() { +test(function booleanAndAliasIsNotUnknown(): void { const unknown = []; function unknownFn(arg): boolean { unknown.push(arg); @@ -22,7 +22,7 @@ test(function booleanAndAliasIsNotUnknown() { assertEquals(unknown, ["--derp", "-d"]); }); -test(function flagBooleanTrueAnyDoubleHyphenArgumentIsNotUnknown() { +test(function flagBooleanTrueAnyDoubleHyphenArgumentIsNotUnknown(): void { const unknown = []; function unknownFn(arg): boolean { unknown.push(arg); @@ -39,7 +39,7 @@ test(function flagBooleanTrueAnyDoubleHyphenArgumentIsNotUnknown() { }); }); -test(function stringAndAliasIsNotUnkown() { +test(function stringAndAliasIsNotUnkown(): void { const unknown = []; function unknownFn(arg): boolean { unknown.push(arg); @@ -58,7 +58,7 @@ test(function stringAndAliasIsNotUnkown() { assertEquals(unknown, ["--derp", "-d"]); }); -test(function defaultAndAliasIsNotUnknown() { +test(function defaultAndAliasIsNotUnknown(): void { const unknown = []; function unknownFn(arg): boolean { unknown.push(arg); @@ -77,7 +77,7 @@ test(function defaultAndAliasIsNotUnknown() { assertEquals(unknown, []); }); -test(function valueFollowingDoubleHyphenIsNotUnknown() { +test(function valueFollowingDoubleHyphenIsNotUnknown(): void { const unknown = []; function unknownFn(arg): boolean { unknown.push(arg); diff --git a/flags/whitespace_test.ts b/flags/whitespace_test.ts index f0f24703c6..9e6ba71156 100755 --- a/flags/whitespace_test.ts +++ b/flags/whitespace_test.ts @@ -3,6 +3,6 @@ import { test } from "../testing/mod.ts"; import { assertEquals } from "../testing/asserts.ts"; import { parse } from "./mod.ts"; -test(function whitespaceShouldBeWhitespace() { +test(function whitespaceShouldBeWhitespace(): void { assertEquals(parse(["-x", "\t"]).x, "\t"); }); diff --git a/fs/empty_dir_test.ts b/fs/empty_dir_test.ts index d91c497a74..b44e600d74 100644 --- a/fs/empty_dir_test.ts +++ b/fs/empty_dir_test.ts @@ -10,7 +10,7 @@ import * as path from "./path/mod.ts"; const testdataDir = path.resolve("fs", "testdata"); -test(async function emptyDirIfItNotExist() { +test(async function emptyDirIfItNotExist(): Promise { const testDir = path.join(testdataDir, "empty_dir_test_1"); const testNestDir = path.join(testDir, "nest"); // 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 testNestDir = path.join(testDir, "nest"); // 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 { const testDir = path.join(testdataDir, "empty_dir_test_3"); const testNestDir = path.join(testDir, "nest"); // create test dir @@ -67,21 +67,25 @@ test(async function emptyDirIfItExist() { assertEquals(stat.isDirectory(), true); // nest directory have been remove - await assertThrowsAsync(async () => { - await Deno.stat(testNestDir); - }); + await assertThrowsAsync( + async (): Promise => { + await Deno.stat(testNestDir); + } + ); // test file have been remove - await assertThrowsAsync(async () => { - await Deno.stat(testDirFile); - }); + await assertThrowsAsync( + async (): Promise => { + await Deno.stat(testDirFile); + } + ); } finally { // remote test dir await Deno.remove(testDir, { recursive: true }); } }); -test(function emptyDirSyncIfItExist() { +test(function emptyDirSyncIfItExist(): void { const testDir = path.join(testdataDir, "empty_dir_test_4"); const testNestDir = path.join(testDir, "nest"); // create test dir @@ -106,14 +110,18 @@ test(function emptyDirSyncIfItExist() { assertEquals(stat.isDirectory(), true); // nest directory have been remove - assertThrows(() => { - Deno.statSync(testNestDir); - }); + assertThrows( + (): void => { + Deno.statSync(testNestDir); + } + ); // test file have been remove - assertThrows(() => { - Deno.statSync(testDirFile); - }); + assertThrows( + (): void => { + Deno.statSync(testDirFile); + } + ); } finally { // remote test dir Deno.removeSync(testDir, { recursive: true }); diff --git a/fs/ensure_dir_test.ts b/fs/ensure_dir_test.ts index 3426588b7d..ad34336dca 100644 --- a/fs/ensure_dir_test.ts +++ b/fs/ensure_dir_test.ts @@ -7,22 +7,26 @@ import { ensureFile, ensureFileSync } from "./ensure_file.ts"; const testdataDir = path.resolve("fs", "testdata"); -test(async function ensureDirIfItNotExist() { +test(async function ensureDirIfItNotExist(): Promise { const baseDir = path.join(testdataDir, "ensure_dir_not_exist"); const testDir = path.join(baseDir, "test"); await ensureDir(testDir); - await assertThrowsAsync(async () => { - await Deno.stat(testDir).then(() => { - throw new Error("test dir should exists."); - }); - }); + await assertThrowsAsync( + async (): Promise => { + await Deno.stat(testDir).then( + (): void => { + throw new Error("test dir should exists."); + } + ); + } + ); await Deno.remove(baseDir, { recursive: true }); }); -test(function ensureDirSyncIfItNotExist() { +test(function ensureDirSyncIfItNotExist(): void { const baseDir = path.join(testdataDir, "ensure_dir_sync_not_exist"); const testDir = path.join(baseDir, "test"); @@ -33,7 +37,7 @@ test(function ensureDirSyncIfItNotExist() { Deno.removeSync(baseDir, { recursive: true }); }); -test(async function ensureDirIfItExist() { +test(async function ensureDirIfItExist(): Promise { const baseDir = path.join(testdataDir, "ensure_dir_exist"); const testDir = path.join(baseDir, "test"); @@ -42,16 +46,20 @@ test(async function ensureDirIfItExist() { await ensureDir(testDir); - await assertThrowsAsync(async () => { - await Deno.stat(testDir).then(() => { - throw new Error("test dir should still exists."); - }); - }); + await assertThrowsAsync( + async (): Promise => { + await Deno.stat(testDir).then( + (): void => { + throw new Error("test dir should still exists."); + } + ); + } + ); await Deno.remove(baseDir, { recursive: true }); }); -test(function ensureDirSyncIfItExist() { +test(function ensureDirSyncIfItExist(): void { const baseDir = path.join(testdataDir, "ensure_dir_sync_exist"); const testDir = path.join(baseDir, "test"); @@ -60,22 +68,24 @@ test(function ensureDirSyncIfItExist() { ensureDirSync(testDir); - assertThrows(() => { - Deno.statSync(testDir); - throw new Error("test dir should still exists."); - }); + assertThrows( + (): void => { + Deno.statSync(testDir); + throw new Error("test dir should still exists."); + } + ); Deno.removeSync(baseDir, { recursive: true }); }); -test(async function ensureDirIfItAsFile() { +test(async function ensureDirIfItAsFile(): Promise { const baseDir = path.join(testdataDir, "ensure_dir_exist_file"); const testFile = path.join(baseDir, "test"); await ensureFile(testFile); await assertThrowsAsync( - async () => { + async (): Promise => { await ensureDir(testFile); }, Error, @@ -85,14 +95,14 @@ test(async function ensureDirIfItAsFile() { await Deno.remove(baseDir, { recursive: true }); }); -test(function ensureDirSyncIfItAsFile() { +test(function ensureDirSyncIfItAsFile(): void { const baseDir = path.join(testdataDir, "ensure_dir_exist_file_async"); const testFile = path.join(baseDir, "test"); ensureFileSync(testFile); assertThrows( - () => { + (): void => { ensureDirSync(testFile); }, Error, diff --git a/fs/ensure_file_test.ts b/fs/ensure_file_test.ts index fd3f4718ad..fa27133ab4 100644 --- a/fs/ensure_file_test.ts +++ b/fs/ensure_file_test.ts @@ -6,36 +6,42 @@ import * as path from "./path/mod.ts"; const testdataDir = path.resolve("fs", "testdata"); -test(async function ensureFileIfItNotExist() { +test(async function ensureFileIfItNotExist(): Promise { const testDir = path.join(testdataDir, "ensure_file_1"); const testFile = path.join(testDir, "test.txt"); await ensureFile(testFile); - await assertThrowsAsync(async () => { - await Deno.stat(testFile).then(() => { - throw new Error("test file should exists."); - }); - }); + await assertThrowsAsync( + async (): Promise => { + await Deno.stat(testFile).then( + (): void => { + throw new Error("test file should exists."); + } + ); + } + ); await Deno.remove(testDir, { recursive: true }); }); -test(function ensureFileSyncIfItNotExist() { +test(function ensureFileSyncIfItNotExist(): void { const testDir = path.join(testdataDir, "ensure_file_2"); const testFile = path.join(testDir, "test.txt"); ensureFileSync(testFile); - assertThrows(() => { - Deno.statSync(testFile); - throw new Error("test file should exists."); - }); + assertThrows( + (): void => { + Deno.statSync(testFile); + throw new Error("test file should exists."); + } + ); Deno.removeSync(testDir, { recursive: true }); }); -test(async function ensureFileIfItExist() { +test(async function ensureFileIfItExist(): Promise { const testDir = path.join(testdataDir, "ensure_file_3"); const testFile = path.join(testDir, "test.txt"); @@ -44,16 +50,20 @@ test(async function ensureFileIfItExist() { await ensureFile(testFile); - await assertThrowsAsync(async () => { - await Deno.stat(testFile).then(() => { - throw new Error("test file should exists."); - }); - }); + await assertThrowsAsync( + async (): Promise => { + await Deno.stat(testFile).then( + (): void => { + throw new Error("test file should exists."); + } + ); + } + ); await Deno.remove(testDir, { recursive: true }); }); -test(function ensureFileSyncIfItExist() { +test(function ensureFileSyncIfItExist(): void { const testDir = path.join(testdataDir, "ensure_file_4"); const testFile = path.join(testDir, "test.txt"); @@ -62,21 +72,23 @@ test(function ensureFileSyncIfItExist() { ensureFileSync(testFile); - assertThrows(() => { - Deno.statSync(testFile); - throw new Error("test file should exists."); - }); + assertThrows( + (): void => { + Deno.statSync(testFile); + throw new Error("test file should exists."); + } + ); Deno.removeSync(testDir, { recursive: true }); }); -test(async function ensureFileIfItExistAsDir() { +test(async function ensureFileIfItExistAsDir(): Promise { const testDir = path.join(testdataDir, "ensure_file_5"); await Deno.mkdir(testDir, true); await assertThrowsAsync( - async () => { + async (): Promise => { await ensureFile(testDir); }, Error, @@ -86,13 +98,13 @@ test(async function ensureFileIfItExistAsDir() { await Deno.remove(testDir, { recursive: true }); }); -test(function ensureFileSyncIfItExistAsDir() { +test(function ensureFileSyncIfItExistAsDir(): void { const testDir = path.join(testdataDir, "ensure_file_6"); Deno.mkdirSync(testDir, true); assertThrows( - () => { + (): void => { ensureFileSync(testDir); }, Error, diff --git a/fs/ensure_link_test.ts b/fs/ensure_link_test.ts index 02beaa87dc..8d14f34ec0 100644 --- a/fs/ensure_link_test.ts +++ b/fs/ensure_link_test.ts @@ -11,32 +11,36 @@ import * as path from "./path/mod.ts"; const testdataDir = path.resolve("fs", "testdata"); -test(async function ensureLinkIfItNotExist() { +test(async function ensureLinkIfItNotExist(): Promise { const srcDir = path.join(testdataDir, "ensure_link_1"); const destDir = path.join(testdataDir, "ensure_link_1_2"); const testFile = path.join(srcDir, "test.txt"); const linkFile = path.join(destDir, "link.txt"); - await assertThrowsAsync(async () => { - await ensureLink(testFile, linkFile); - }); + await assertThrowsAsync( + (): Promise => { + await ensureLink(testFile, linkFile); + } + ); await Deno.remove(destDir, { recursive: true }); }); -test(function ensureLinkSyncIfItNotExist() { +test(function ensureLinkSyncIfItNotExist(): void { const testDir = path.join(testdataDir, "ensure_link_2"); const testFile = path.join(testDir, "test.txt"); const linkFile = path.join(testDir, "link.txt"); - assertThrows(() => { - ensureLinkSync(testFile, linkFile); - }); + assertThrows( + (): void => { + ensureLinkSync(testFile, linkFile); + } + ); Deno.removeSync(testDir, { recursive: true }); }); -test(async function ensureLinkIfItExist() { +test(async function ensureLinkIfItExist(): Promise { const testDir = path.join(testdataDir, "ensure_link_3"); const testFile = path.join(testDir, "test.txt"); const linkFile = path.join(testDir, "link.txt"); @@ -83,7 +87,7 @@ test(async function ensureLinkIfItExist() { await Deno.remove(testDir, { recursive: true }); }); -test(function ensureLinkSyncIfItExist() { +test(function ensureLinkSyncIfItExist(): void { const testDir = path.join(testdataDir, "ensure_link_4"); const testFile = path.join(testDir, "test.txt"); const linkFile = path.join(testDir, "link.txt"); @@ -131,7 +135,7 @@ test(function ensureLinkSyncIfItExist() { Deno.removeSync(testDir, { recursive: true }); }); -test(async function ensureLinkDirectoryIfItExist() { +test(async function ensureLinkDirectoryIfItExist(): Promise { const testDir = path.join(testdataDir, "ensure_link_origin_3"); const linkDir = path.join(testdataDir, "ensure_link_link_3"); const testFile = path.join(testDir, "test.txt"); @@ -140,7 +144,7 @@ test(async function ensureLinkDirectoryIfItExist() { await Deno.writeFile(testFile, new Uint8Array()); await assertThrowsAsync( - async () => { + async (): Promise => { await ensureLink(testDir, linkDir); }, Deno.DenoError, @@ -150,7 +154,7 @@ test(async function ensureLinkDirectoryIfItExist() { Deno.removeSync(testDir, { recursive: true }); }); -test(function ensureLinkSyncDirectoryIfItExist() { +test(function ensureLinkSyncDirectoryIfItExist(): void { const testDir = path.join(testdataDir, "ensure_link_origin_3"); const linkDir = path.join(testdataDir, "ensure_link_link_3"); const testFile = path.join(testDir, "test.txt"); @@ -159,7 +163,7 @@ test(function ensureLinkSyncDirectoryIfItExist() { Deno.writeFileSync(testFile, new Uint8Array()); assertThrows( - () => { + (): void => { ensureLinkSync(testDir, linkDir); }, Deno.DenoError, diff --git a/fs/ensure_symlink_test.ts b/fs/ensure_symlink_test.ts index 22be30b889..d769615fb6 100644 --- a/fs/ensure_symlink_test.ts +++ b/fs/ensure_symlink_test.ts @@ -12,36 +12,46 @@ import * as path from "./path/mod.ts"; const testdataDir = path.resolve("fs", "testdata"); const isWindows = Deno.platform.os === "win"; -test(async function ensureSymlinkIfItNotExist() { +test(async function ensureSymlinkIfItNotExist(): Promise { const testDir = path.join(testdataDir, "link_file_1"); const testFile = path.join(testDir, "test.txt"); - assertThrowsAsync(async () => { - await ensureSymlink(testFile, path.join(testDir, "test1.txt")); - }); + assertThrowsAsync( + async (): Promise => { + await ensureSymlink(testFile, path.join(testDir, "test1.txt")); + } + ); - assertThrowsAsync(async () => { - await Deno.stat(testFile).then(() => { - throw new Error("test file should exists."); - }); - }); + assertThrowsAsync( + async (): Promise => { + await Deno.stat(testFile).then( + (): void => { + throw new Error("test file should exists."); + } + ); + } + ); }); -test(function ensureSymlinkSyncIfItNotExist() { +test(function ensureSymlinkSyncIfItNotExist(): void { const testDir = path.join(testdataDir, "link_file_2"); const testFile = path.join(testDir, "test.txt"); - assertThrows(() => { - ensureSymlinkSync(testFile, path.join(testDir, "test1.txt")); - }); + assertThrows( + (): void => { + ensureSymlinkSync(testFile, path.join(testDir, "test1.txt")); + } + ); - assertThrows(() => { - Deno.statSync(testFile); - throw new Error("test file should exists."); - }); + assertThrows( + (): void => { + Deno.statSync(testFile); + throw new Error("test file should exists."); + } + ); }); -test(async function ensureSymlinkIfItExist() { +test(async function ensureSymlinkIfItExist(): Promise { const testDir = path.join(testdataDir, "link_file_3"); const testFile = path.join(testDir, "test.txt"); const linkFile = path.join(testDir, "link.txt"); @@ -51,7 +61,7 @@ test(async function ensureSymlinkIfItExist() { if (isWindows) { await assertThrowsAsync( - () => ensureSymlink(testFile, linkFile), + (): Promise => ensureSymlink(testFile, linkFile), Error, "Not implemented" ); @@ -70,7 +80,7 @@ test(async function ensureSymlinkIfItExist() { await Deno.remove(testDir, { recursive: true }); }); -test(function ensureSymlinkSyncIfItExist() { +test(function ensureSymlinkSyncIfItExist(): void { const testDir = path.join(testdataDir, "link_file_4"); const testFile = path.join(testDir, "test.txt"); const linkFile = path.join(testDir, "link.txt"); @@ -80,7 +90,7 @@ test(function ensureSymlinkSyncIfItExist() { if (isWindows) { assertThrows( - () => ensureSymlinkSync(testFile, linkFile), + (): void => ensureSymlinkSync(testFile, linkFile), Error, "Not implemented" ); @@ -100,7 +110,7 @@ test(function ensureSymlinkSyncIfItExist() { Deno.removeSync(testDir, { recursive: true }); }); -test(async function ensureSymlinkDirectoryIfItExist() { +test(async function ensureSymlinkDirectoryIfItExist(): Promise { const testDir = path.join(testdataDir, "link_file_origin_3"); const linkDir = path.join(testdataDir, "link_file_link_3"); const testFile = path.join(testDir, "test.txt"); @@ -110,7 +120,7 @@ test(async function ensureSymlinkDirectoryIfItExist() { if (isWindows) { await assertThrowsAsync( - () => ensureSymlink(testDir, linkDir), + (): Promise => ensureSymlink(testDir, linkDir), Error, "Not implemented" ); @@ -132,7 +142,7 @@ test(async function ensureSymlinkDirectoryIfItExist() { await Deno.remove(testDir, { recursive: true }); }); -test(function ensureSymlinkSyncDirectoryIfItExist() { +test(function ensureSymlinkSyncDirectoryIfItExist(): void { const testDir = path.join(testdataDir, "link_file_origin_3"); const linkDir = path.join(testdataDir, "link_file_link_3"); const testFile = path.join(testDir, "test.txt"); @@ -142,7 +152,7 @@ test(function ensureSymlinkSyncDirectoryIfItExist() { if (isWindows) { assertThrows( - () => ensureSymlinkSync(testDir, linkDir), + (): void => ensureSymlinkSync(testDir, linkDir), Error, "Not implemented" ); diff --git a/fs/eol.ts b/fs/eol.ts index 46babe406f..55d03fa836 100644 --- a/fs/eol.ts +++ b/fs/eol.ts @@ -17,7 +17,7 @@ export function detect(content: string): EOL | null { if (!d || d.length === 0) { 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) { return EOL.CRLF; } else { diff --git a/fs/eol_test.ts b/fs/eol_test.ts index 94ca486275..4669c795ac 100644 --- a/fs/eol_test.ts +++ b/fs/eol_test.ts @@ -11,28 +11,28 @@ const NoNLinput = "deno is not node"; test({ name: "[EOL] Detect CR LF", - fn() { + fn(): void { assertEquals(detect(CRLFinput), EOL.CRLF); } }); test({ name: "[EOL] Detect LF", - fn() { + fn(): void { assertEquals(detect(LFinput), EOL.LF); } }); test({ name: "[EOL] Detect No New Line", - fn() { + fn(): void { assertEquals(detect(NoNLinput), null); } }); test({ name: "[EOL] Detect Mixed", - fn() { + fn(): void { assertEquals(detect(Mixedinput), EOL.CRLF); assertEquals(detect(Mixedinput2), EOL.CRLF); } @@ -40,7 +40,7 @@ test({ test({ name: "[EOL] Format", - fn() { + fn(): void { assertEquals(format(CRLFinput, EOL.LF), LFinput); assertEquals(format(LFinput, EOL.LF), LFinput); assertEquals(format(LFinput, EOL.CRLF), CRLFinput); diff --git a/fs/exists.ts b/fs/exists.ts index ce4b83a4cf..4638630fd1 100644 --- a/fs/exists.ts +++ b/fs/exists.ts @@ -3,8 +3,8 @@ /** Test whether or not the given path exists by checking with the file system */ export async function exists(filePath: string): Promise { return Deno.lstat(filePath) - .then(() => true) - .catch(() => false); + .then((): boolean => true) + .catch((): boolean => false); } /** Test whether or not the given path exists by checking with the file system */ diff --git a/fs/exists_test.ts b/fs/exists_test.ts index 1e94c7f691..a75cdb9f4e 100644 --- a/fs/exists_test.ts +++ b/fs/exists_test.ts @@ -6,7 +6,7 @@ import * as path from "./path/mod.ts"; const testdataDir = path.resolve("fs", "testdata"); -test(async function existsFile() { +test(async function existsFile(): Promise { assertEquals( await exists(path.join(testdataDir, "not_exist_file.ts")), false @@ -14,12 +14,12 @@ test(async function existsFile() { 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, "0.ts")), true); }); -test(async function existsDirectory() { +test(async function existsDirectory(): Promise { assertEquals( await exists(path.join(testdataDir, "not_exist_directory")), false @@ -27,7 +27,7 @@ test(async function existsDirectory() { assertEquals(existsSync(testdataDir), true); }); -test(function existsDirectorySync() { +test(function existsDirectorySync(): void { assertEquals( existsSync(path.join(testdataDir, "not_exist_directory")), false @@ -35,12 +35,12 @@ test(function existsDirectorySync() { 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 assertEquals(existsSync(path.join(testdataDir, "0-link.ts")), true); }); -test(async function existsLink() { +test(async function existsLink(): Promise { // 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); }); diff --git a/fs/glob_test.ts b/fs/glob_test.ts index fc3704ae3d..5772373dd4 100644 --- a/fs/glob_test.ts +++ b/fs/glob_test.ts @@ -20,8 +20,9 @@ async function walkArray( arr.push(f.path.replace(/\\/g, "/")); } arr.sort(); - const arrSync = Array.from(walkSync(dirname, options), (f: FileInfo) => - f.path.replace(/\\/g, "/") + const arrSync = Array.from( + walkSync(dirname, options), + (f: FileInfo): string => f.path.replace(/\\/g, "/") ).sort(); assertEquals(arr, arrSync); return arr; @@ -29,7 +30,7 @@ async function walkArray( test({ name: "glob: glob to regex", - fn() { + fn(): void { assertEquals(glob("unicorn.*") instanceof RegExp, true); assertEquals(glob("unicorn.*").test("poney.ts"), false); assertEquals(glob("unicorn.*").test("unicorn.py"), true); @@ -69,11 +70,11 @@ test({ }); testWalk( - async (d: string) => { + async (d: string): Promise => { await mkdir(d + "/a"); await touch(d + "/a/x.ts"); }, - async function globInWalk() { + async function globInWalk(): Promise { const arr = await walkArray(".", { match: [glob("*.ts")] }); assertEquals(arr.length, 1); assertEquals(arr[0], "./a/x.ts"); @@ -81,14 +82,14 @@ testWalk( ); testWalk( - async (d: string) => { + async (d: string): Promise => { await mkdir(d + "/a"); await mkdir(d + "/b"); await touch(d + "/a/x.ts"); await touch(d + "/b/z.ts"); await touch(d + "/b/z.js"); }, - async function globInWalkWildcardFiles() { + async function globInWalkWildcardFiles(): Promise { const arr = await walkArray(".", { match: [glob("*.ts")] }); assertEquals(arr.length, 2); assertEquals(arr[0], "./a/x.ts"); @@ -97,12 +98,12 @@ testWalk( ); testWalk( - async (d: string) => { + async (d: string): Promise => { await mkdir(d + "/a"); await mkdir(d + "/a/yo"); await touch(d + "/a/yo/x.ts"); }, - async function globInWalkFolderWildcard() { + async function globInWalkFolderWildcard(): Promise { const arr = await walkArray(".", { match: [ glob(join("a", "**", "*.ts"), { @@ -117,7 +118,7 @@ testWalk( ); testWalk( - async (d: string) => { + async (d: string): Promise => { await mkdir(d + "/a"); await mkdir(d + "/a/unicorn"); await mkdir(d + "/a/deno"); @@ -126,7 +127,7 @@ testWalk( await touch(d + "/a/deno/x.ts"); await touch(d + "/a/unicorn/x.ts"); }, - async function globInWalkFolderExtended() { + async function globInWalkFolderExtended(): Promise { const arr = await walkArray(".", { match: [ glob(join("a", "+(raptor|deno)", "*.ts"), { @@ -142,12 +143,12 @@ testWalk( ); testWalk( - async (d: string) => { + async (d: string): Promise => { await touch(d + "/x.ts"); await touch(d + "/x.js"); await touch(d + "/b.js"); }, - async function globInWalkWildcardExtension() { + async function globInWalkWildcardExtension(): Promise { const arr = await walkArray(".", { match: [glob("x.*", { flags: "g", globstar: true })] }); diff --git a/fs/globrex_test.ts b/fs/globrex_test.ts index 8d43b53521..34821b6203 100644 --- a/fs/globrex_test.ts +++ b/fs/globrex_test.ts @@ -35,7 +35,7 @@ function matchSegments(t, pattern, ifUnix, ifWin, opts): GlobrexResult { test({ name: "globrex: standard", - fn() { + fn(): void { let res = globrex("*.js"); t.equal(typeof globrex, "function", "constructor is a typeof function"); t.equal(res instanceof Object, true, "returns object"); @@ -45,7 +45,7 @@ test({ test({ name: "globrex: Standard * matching", - fn() { + fn(): void { t.equal(match("*", "foo"), true, "match everything"); t.equal(match("*", "foo", { flags: "g" }), true, "match everything"); t.equal(match("f*", "foo"), true, "match the end"); @@ -75,7 +75,7 @@ test({ test({ name: "globrex: advance * matching", - fn() { + fn(): void { t.equal( match("*.min.js", "http://example.com/jquery.min.js", { globstar: false @@ -186,7 +186,7 @@ test({ test({ 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", "fooo", { extended: true }), false); t.equal(match("f?oo", "foo", { extended: true }), false); @@ -226,7 +226,7 @@ test({ test({ name: "globrex: [] match a character range", - fn() { + fn(): void { t.equal(match("fo[oz]", "foo", { extended: true }), true); t.equal(match("fo[oz]", "foz", { extended: true }), true); t.equal(match("fo[oz]", "fog", { extended: true }), false); @@ -257,7 +257,7 @@ test({ test({ name: "globrex: [] extended character ranges", - fn() { + fn(): void { t.equal( match("[[:alnum:]]/bar.txt", "a/bar.txt", { extended: true }), true @@ -315,7 +315,7 @@ test({ test({ 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}", "foobar", { extended: true }), true); t.equal(match("foo{bar,baaz}", "foobuzz", { extended: true }), false); @@ -363,7 +363,7 @@ test({ test({ name: "globrex: complex extended matches", - fn() { + fn(): void { t.equal( match( "http://?o[oz].b*z.com/{*.js,*.html}", @@ -455,7 +455,7 @@ test({ test({ name: "globrex: standard globstar", - fn() { + fn(): void { const tester = (globstar): void => { t.equal( match( @@ -490,7 +490,7 @@ test({ test({ name: "globrex: remaining chars should match themself", - fn() { + fn(): void { const tester = (globstar): void => { const testExtStr = "\\/$^+.()=!|,.*"; t.equal(match(testExtStr, testExtStr, { extended: true }), true); @@ -507,7 +507,7 @@ test({ test({ 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/baz.txt", { globstar: true }), true); @@ -647,7 +647,7 @@ test({ test({ 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", ".txt", { extended: true }), true); @@ -700,7 +700,7 @@ test({ test({ name: "globrex: extended extglob *", - fn() { + fn(): void { 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", "foofoo.txt", { extended: true }), true); @@ -737,7 +737,7 @@ test({ test({ 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", ".txt", { extended: true }), false); @@ -747,7 +747,7 @@ test({ test({ 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|baz)bar.txt", "foobar.txt", { extended: true }), true); @@ -768,7 +768,7 @@ test({ test({ name: "globrex: extended extglob !", - fn() { + fn(): void { 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("!bar.txt", "!bar.txt", { extended: true }), true); @@ -785,7 +785,7 @@ test({ test({ 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", { strict: true }), false); @@ -794,7 +794,7 @@ test({ test({ name: "globrex: filepath path-regex", - fn() { + fn(): void { let opts = { extended: true, filepath: true, globstar: false }, res, pattern; @@ -847,7 +847,7 @@ test({ test({ name: "globrex: filepath path segments", - fn() { + fn(): void { let opts = { extended: true }, win, unix; @@ -895,7 +895,7 @@ test({ test({ name: "globrex: stress testing", - fn() { + fn(): void { t.equal( match("**/*/?yfile.{md,js,txt}", "foo/bar/baz/myfile.md", { extended: true diff --git a/fs/move_test.ts b/fs/move_test.ts index aa49b4cca8..fae951e1fa 100644 --- a/fs/move_test.ts +++ b/fs/move_test.ts @@ -13,16 +13,18 @@ import * as path from "./path/mod.ts"; const testdataDir = path.resolve("fs", "testdata"); -test(async function moveDirectoryIfSrcNotExists() { +test(async function moveDirectoryIfSrcNotExists(): Promise { const srcDir = path.join(testdataDir, "move_test_src_1"); const destDir = path.join(testdataDir, "move_test_dest_1"); // if src directory not exist - await assertThrowsAsync(async () => { - await move(srcDir, destDir); - }); + await assertThrowsAsync( + async (): Promise => { + await move(srcDir, destDir); + } + ); }); -test(async function moveDirectoryIfDestNotExists() { +test(async function moveDirectoryIfDestNotExists(): Promise { const srcDir = path.join(testdataDir, "move_test_src_2"); const destDir = path.join(testdataDir, "move_test_dest_2"); @@ -30,7 +32,7 @@ test(async function moveDirectoryIfDestNotExists() { // if dest directory not exist await assertThrowsAsync( - async () => { + async (): Promise => { await move(srcDir, destDir); throw new Error("should not throw error"); }, @@ -41,17 +43,19 @@ test(async function moveDirectoryIfDestNotExists() { await Deno.remove(destDir); }); -test(async function moveFileIfSrcNotExists() { +test(async function moveFileIfSrcNotExists(): Promise { const srcFile = path.join(testdataDir, "move_test_src_3", "test.txt"); const destFile = path.join(testdataDir, "move_test_dest_3", "test.txt"); // if src directory not exist - await assertThrowsAsync(async () => { - await move(srcFile, destFile); - }); + await assertThrowsAsync( + async (): Promise => { + await move(srcFile, destFile); + } + ); }); -test(async function moveFileIfDestExists() { +test(async function moveFileIfDestExists(): Promise { const srcDir = path.join(testdataDir, "move_test_src_4"); const destDir = path.join(testdataDir, "move_test_dest_4"); const srcFile = path.join(srcDir, "test.txt"); @@ -74,7 +78,7 @@ test(async function moveFileIfDestExists() { // move it without override await assertThrowsAsync( - async () => { + async (): Promise => { await move(srcFile, destFile); }, Error, @@ -83,7 +87,7 @@ test(async function moveFileIfDestExists() { // move again with overwrite await assertThrowsAsync( - async () => { + async (): Promise => { await move(srcFile, destFile, { overwrite: true }); throw new Error("should not throw error"); }, @@ -101,7 +105,7 @@ test(async function moveFileIfDestExists() { ]); }); -test(async function moveDirectory() { +test(async function moveDirectory(): Promise { const srcDir = path.join(testdataDir, "move_test_src_5"); const destDir = path.join(testdataDir, "move_test_dest_5"); const srcFile = path.join(srcDir, "test.txt"); @@ -126,7 +130,9 @@ test(async function moveDirectory() { 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 destDir = path.join(testdataDir, "move_test_dest_6"); const srcFile = path.join(srcDir, "test.txt"); @@ -156,14 +162,14 @@ test(async function moveIfSrcAndDestDirectoryExistsAndOverwrite() { await Deno.remove(destDir, { recursive: true }); }); -test(async function moveIntoSubDir() { +test(async function moveIntoSubDir(): Promise { const srcDir = path.join(testdataDir, "move_test_src_7"); const destDir = path.join(srcDir, "nest"); await ensureDir(destDir); await assertThrowsAsync( - async () => { + async (): Promise => { await move(srcDir, destDir); }, Error, @@ -172,16 +178,18 @@ test(async function moveIntoSubDir() { await Deno.remove(srcDir, { recursive: true }); }); -test(function moveSyncDirectoryIfSrcNotExists() { +test(function moveSyncDirectoryIfSrcNotExists(): void { const srcDir = path.join(testdataDir, "move_sync_test_src_1"); const destDir = path.join(testdataDir, "move_sync_test_dest_1"); // if src directory not exist - assertThrows(() => { - moveSync(srcDir, destDir); - }); + assertThrows( + (): void => { + moveSync(srcDir, destDir); + } + ); }); -test(function moveSyncDirectoryIfDestNotExists() { +test(function moveSyncDirectoryIfDestNotExists(): void { const srcDir = path.join(testdataDir, "move_sync_test_src_2"); const destDir = path.join(testdataDir, "move_sync_test_dest_2"); @@ -189,7 +197,7 @@ test(function moveSyncDirectoryIfDestNotExists() { // if dest directory not exist assertThrows( - () => { + (): void => { moveSync(srcDir, destDir); throw new Error("should not throw error"); }, @@ -200,17 +208,19 @@ test(function moveSyncDirectoryIfDestNotExists() { Deno.removeSync(destDir); }); -test(function moveSyncFileIfSrcNotExists() { +test(function moveSyncFileIfSrcNotExists(): void { const srcFile = path.join(testdataDir, "move_sync_test_src_3", "test.txt"); const destFile = path.join(testdataDir, "move_sync_test_dest_3", "test.txt"); // if src directory not exist - assertThrows(() => { - moveSync(srcFile, destFile); - }); + assertThrows( + (): void => { + moveSync(srcFile, destFile); + } + ); }); -test(function moveSyncFileIfDestExists() { +test(function moveSyncFileIfDestExists(): void { const srcDir = path.join(testdataDir, "move_sync_test_src_4"); const destDir = path.join(testdataDir, "move_sync_test_dest_4"); const srcFile = path.join(srcDir, "test.txt"); @@ -232,7 +242,7 @@ test(function moveSyncFileIfDestExists() { // move it without override assertThrows( - () => { + (): void => { moveSync(srcFile, destFile); }, Error, @@ -241,7 +251,7 @@ test(function moveSyncFileIfDestExists() { // move again with overwrite assertThrows( - () => { + (): void => { moveSync(srcFile, destFile, { overwrite: true }); throw new Error("should not throw error"); }, @@ -257,7 +267,7 @@ test(function moveSyncFileIfDestExists() { Deno.removeSync(destDir, { recursive: true }); }); -test(function moveSyncDirectory() { +test(function moveSyncDirectory(): void { const srcDir = path.join(testdataDir, "move_sync_test_src_5"); const destDir = path.join(testdataDir, "move_sync_test_dest_5"); const srcFile = path.join(srcDir, "test.txt"); @@ -280,7 +290,7 @@ test(function moveSyncDirectory() { Deno.removeSync(destDir, { recursive: true }); }); -test(function moveSyncIfSrcAndDestDirectoryExistsAndOverwrite() { +test(function moveSyncIfSrcAndDestDirectoryExistsAndOverwrite(): void { const srcDir = path.join(testdataDir, "move_sync_test_src_6"); const destDir = path.join(testdataDir, "move_sync_test_dest_6"); const srcFile = path.join(srcDir, "test.txt"); @@ -307,14 +317,14 @@ test(function moveSyncIfSrcAndDestDirectoryExistsAndOverwrite() { Deno.removeSync(destDir, { recursive: true }); }); -test(function moveSyncIntoSubDir() { +test(function moveSyncIntoSubDir(): void { const srcDir = path.join(testdataDir, "move_sync_test_src_7"); const destDir = path.join(srcDir, "nest"); ensureDirSync(destDir); assertThrows( - () => { + (): void => { moveSync(srcDir, destDir); }, Error, diff --git a/fs/read_file_str_test.ts b/fs/read_file_str_test.ts index eb529022c5..d7d67d8d46 100644 --- a/fs/read_file_str_test.ts +++ b/fs/read_file_str_test.ts @@ -5,14 +5,14 @@ import * as path from "./path/mod.ts"; const testdataDir = path.resolve("fs", "testdata"); -test(function testReadFileSync() { +test(function testReadFileSync(): void { const jsonFile = path.join(testdataDir, "json_valid_obj.json"); const strFile = readFileStrSync(jsonFile); assert(typeof strFile === "string"); assert(strFile.length > 0); }); -test(async function testReadFile() { +test(async function testReadFile(): Promise { const jsonFile = path.join(testdataDir, "json_valid_obj.json"); const strFile = await readFileStr(jsonFile); assert(typeof strFile === "string"); diff --git a/fs/read_json.ts b/fs/read_json.ts index 8979c24e8c..ca5928afea 100644 --- a/fs/read_json.ts +++ b/fs/read_json.ts @@ -1,7 +1,7 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. /** Reads a JSON file and then parses it into an object */ -export async function readJson(filePath: string): Promise { +export async function readJson(filePath: string): Promise { const decoder = new TextDecoder("utf-8"); const content = decoder.decode(await Deno.readFile(filePath)); @@ -15,7 +15,7 @@ export async function readJson(filePath: string): Promise { } /** 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 content = decoder.decode(Deno.readFileSync(filePath)); diff --git a/fs/read_json_test.ts b/fs/read_json_test.ts index ca32ee0539..c8aa6dcf1d 100644 --- a/fs/read_json_test.ts +++ b/fs/read_json_test.ts @@ -10,31 +10,37 @@ import * as path from "./path/mod.ts"; const testdataDir = path.resolve("fs", "testdata"); -test(async function readJsonFileNotExists() { +test(async function readJsonFileNotExists(): Promise { const emptyJsonFile = path.join(testdataDir, "json_not_exists.json"); - await assertThrowsAsync(async () => { - await readJson(emptyJsonFile); - }); + await assertThrowsAsync( + async (): Promise => { + await readJson(emptyJsonFile); + } + ); }); -test(async function readEmptyJsonFile() { +test(async function readEmptyJsonFile(): Promise { const emptyJsonFile = path.join(testdataDir, "json_empty.json"); - await assertThrowsAsync(async () => { - await readJson(emptyJsonFile); - }); + await assertThrowsAsync( + async (): Promise => { + await readJson(emptyJsonFile); + } + ); }); -test(async function readInvalidJsonFile() { +test(async function readInvalidJsonFile(): Promise { const invalidJsonFile = path.join(testdataDir, "json_invalid.json"); - await assertThrowsAsync(async () => { - await readJson(invalidJsonFile); - }); + await assertThrowsAsync( + async (): Promise => { + await readJson(invalidJsonFile); + } + ); }); -test(async function readValidArrayJsonFile() { +test(async function readValidArrayJsonFile(): Promise { const invalidJsonFile = path.join(testdataDir, "json_valid_array.json"); const json = await readJson(invalidJsonFile); @@ -42,7 +48,7 @@ test(async function readValidArrayJsonFile() { assertEquals(json, ["1", "2", "3"]); }); -test(async function readValidObjJsonFile() { +test(async function readValidObjJsonFile(): Promise { const invalidJsonFile = path.join(testdataDir, "json_valid_obj.json"); const json = await readJson(invalidJsonFile); @@ -50,37 +56,43 @@ test(async function readValidObjJsonFile() { assertEquals(json, { key1: "value1", key2: "value2" }); }); -test(async function readValidObjJsonFileWithRelativePath() { +test(async function readValidObjJsonFileWithRelativePath(): Promise { const json = await readJson("./fs/testdata/json_valid_obj.json"); assertEquals(json, { key1: "value1", key2: "value2" }); }); -test(function readJsonFileNotExistsSync() { +test(function readJsonFileNotExistsSync(): void { const emptyJsonFile = path.join(testdataDir, "json_not_exists.json"); - assertThrows(() => { - readJsonSync(emptyJsonFile); - }); + assertThrows( + (): void => { + readJsonSync(emptyJsonFile); + } + ); }); -test(function readEmptyJsonFileSync() { +test(function readEmptyJsonFileSync(): void { const emptyJsonFile = path.join(testdataDir, "json_empty.json"); - assertThrows(() => { - readJsonSync(emptyJsonFile); - }); + assertThrows( + (): void => { + readJsonSync(emptyJsonFile); + } + ); }); -test(function readInvalidJsonFile() { +test(function readInvalidJsonFile(): void { const invalidJsonFile = path.join(testdataDir, "json_invalid.json"); - assertThrows(() => { - readJsonSync(invalidJsonFile); - }); + assertThrows( + (): void => { + readJsonSync(invalidJsonFile); + } + ); }); -test(function readValidArrayJsonFileSync() { +test(function readValidArrayJsonFileSync(): void { const invalidJsonFile = path.join(testdataDir, "json_valid_array.json"); const json = readJsonSync(invalidJsonFile); @@ -88,7 +100,7 @@ test(function readValidArrayJsonFileSync() { assertEquals(json, ["1", "2", "3"]); }); -test(function readValidObjJsonFileSync() { +test(function readValidObjJsonFileSync(): void { const invalidJsonFile = path.join(testdataDir, "json_valid_obj.json"); const json = readJsonSync(invalidJsonFile); @@ -96,7 +108,7 @@ test(function readValidObjJsonFileSync() { assertEquals(json, { key1: "value1", key2: "value2" }); }); -test(function readValidObjJsonFileSyncWithRelativePath() { +test(function readValidObjJsonFileSyncWithRelativePath(): void { const json = readJsonSync("./fs/testdata/json_valid_obj.json"); assertEquals(json, { key1: "value1", key2: "value2" }); diff --git a/fs/utils.ts b/fs/utils.ts index 06b4c295c2..83390ad706 100644 --- a/fs/utils.ts +++ b/fs/utils.ts @@ -17,7 +17,7 @@ export function isSubdir( const srcArray = src.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; }, true); } diff --git a/fs/utils_test.ts b/fs/utils_test.ts index d833aa559d..5b33842ad8 100644 --- a/fs/utils_test.ts +++ b/fs/utils_test.ts @@ -9,7 +9,7 @@ import { ensureDirSync } from "./ensure_dir.ts"; const testdataDir = path.resolve("fs", "testdata"); -test(function _isSubdir() { +test(function _isSubdir(): void { const pairs = [ ["", "", 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] ]; - pairs.forEach(function(p) { + pairs.forEach(function(p): void { const src = p[0] as string; const dest = p[1] as string; const expected = p[2] as boolean; @@ -34,13 +34,13 @@ test(function _isSubdir() { }); }); -test(function _getFileInfoType() { +test(function _getFileInfoType(): void { const pairs = [ [path.join(testdataDir, "file_type_1"), "file"], [path.join(testdataDir, "file_type_dir_1"), "dir"] ]; - pairs.forEach(function(p) { + pairs.forEach(function(p): void { const filePath = p[0] as string; const type = p[1] as PathType; switch (type) { diff --git a/fs/walk.ts b/fs/walk.ts index 1e433e18b1..b21044e72d 100644 --- a/fs/walk.ts +++ b/fs/walk.ts @@ -14,15 +14,20 @@ function patternTest(patterns: RegExp[], path: string): boolean { // Forced to reset last index on regex while iterating for have // consistent results. // See: https://stackoverflow.com/a/1520853 - return patterns.some(pattern => { - let r = pattern.test(path); - pattern.lastIndex = 0; - return r; - }); + return patterns.some( + (pattern): boolean => { + let r = pattern.test(path); + pattern.lastIndex = 0; + return r; + } + ); } 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; } if (options.match && !patternTest(options.match, f.path)) { diff --git a/fs/walk_test.ts b/fs/walk_test.ts index 4c72de2c7d..e94a653c6b 100644 --- a/fs/walk_test.ts +++ b/fs/walk_test.ts @@ -35,8 +35,9 @@ async function walkArray( arr.push(f.path.replace(/\\/g, "/")); } arr.sort(); - const arrSync = Array.from(walkSync(dirname, options), (f: FileInfo) => - f.path.replace(/\\/g, "/") + const arrSync = Array.from( + walkSync(dirname, options), + (f: FileInfo): string => f.path.replace(/\\/g, "/") ).sort(); assertEquals(arr, arrSync); return arr; @@ -46,25 +47,25 @@ async function touch(path: string): Promise { await open(path, "w"); } 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); } testWalk( - async (d: string) => { + async (d: string): Promise => { await mkdir(d + "/empty"); }, - async function emptyDir() { + async function emptyDir(): Promise { const arr = await walkArray(); assertEquals(arr.length, 0); } ); testWalk( - async (d: string) => { + async (d: string): Promise => { await touch(d + "/x"); }, - async function singleFile() { + async function singleFile(): Promise { const arr = await walkArray(); assertEquals(arr.length, 1); assertEquals(arr[0], "./x"); @@ -72,10 +73,10 @@ testWalk( ); testWalk( - async (d: string) => { + async (d: string): Promise => { await touch(d + "/x"); }, - async function iteratable() { + async function iteratable(): Promise { let count = 0; for (const _ of walkSync()) { count += 1; @@ -89,11 +90,11 @@ testWalk( ); testWalk( - async (d: string) => { + async (d: string): Promise => { await mkdir(d + "/a"); await touch(d + "/a/x"); }, - async function nestedSingleFile() { + async function nestedSingleFile(): Promise { const arr = await walkArray(); assertEquals(arr.length, 1); assertEquals(arr[0], "./a/x"); @@ -101,11 +102,11 @@ testWalk( ); testWalk( - async (d: string) => { + async (d: string): Promise => { await mkdir(d + "/a/b/c/d", true); await touch(d + "/a/b/c/d/x"); }, - async function depth() { + async function depth(): Promise { assertReady(1); const arr3 = await walkArray(".", { maxDepth: 3 }); assertEquals(arr3.length, 0); @@ -116,11 +117,11 @@ testWalk( ); testWalk( - async (d: string) => { + async (d: string): Promise => { await touch(d + "/x.ts"); await touch(d + "/y.rs"); }, - async function ext() { + async function ext(): Promise { assertReady(2); const arr = await walkArray(".", { exts: [".ts"] }); assertEquals(arr.length, 1); @@ -129,12 +130,12 @@ testWalk( ); testWalk( - async (d: string) => { + async (d: string): Promise => { await touch(d + "/x.ts"); await touch(d + "/y.rs"); await touch(d + "/z.py"); }, - async function extAny() { + async function extAny(): Promise { assertReady(3); const arr = await walkArray(".", { exts: [".rs", ".ts"] }); assertEquals(arr.length, 2); @@ -144,11 +145,11 @@ testWalk( ); testWalk( - async (d: string) => { + async (d: string): Promise => { await touch(d + "/x"); await touch(d + "/y"); }, - async function match() { + async function match(): Promise { assertReady(2); const arr = await walkArray(".", { match: [/x/] }); assertEquals(arr.length, 1); @@ -157,12 +158,12 @@ testWalk( ); testWalk( - async (d: string) => { + async (d: string): Promise => { await touch(d + "/x"); await touch(d + "/y"); await touch(d + "/z"); }, - async function matchAny() { + async function matchAny(): Promise { assertReady(3); const arr = await walkArray(".", { match: [/x/, /y/] }); assertEquals(arr.length, 2); @@ -172,11 +173,11 @@ testWalk( ); testWalk( - async (d: string) => { + async (d: string): Promise => { await touch(d + "/x"); await touch(d + "/y"); }, - async function skip() { + async function skip(): Promise { assertReady(2); const arr = await walkArray(".", { skip: [/x/] }); assertEquals(arr.length, 1); @@ -185,12 +186,12 @@ testWalk( ); testWalk( - async (d: string) => { + async (d: string): Promise => { await touch(d + "/x"); await touch(d + "/y"); await touch(d + "/z"); }, - async function skipAny() { + async function skipAny(): Promise { assertReady(3); const arr = await walkArray(".", { skip: [/x/, /y/] }); assertEquals(arr.length, 1); @@ -199,14 +200,14 @@ testWalk( ); testWalk( - async (d: string) => { + async (d: string): Promise => { await mkdir(d + "/a"); await mkdir(d + "/b"); await touch(d + "/a/x"); await touch(d + "/a/y"); await touch(d + "/b/z"); }, - async function subDir() { + async function subDir(): Promise { assertReady(3); const arr = await walkArray("b"); assertEquals(arr.length, 1); @@ -214,18 +215,21 @@ testWalk( } ); -testWalk(async (_d: string) => {}, async function onError() { - assertReady(0); - const ignored = await walkArray("missing"); - assertEquals(ignored.length, 0); - let errors = 0; - await walkArray("missing", { onError: _e => (errors += 1) }); - // It's 2 since walkArray iterates over both sync and async. - assertEquals(errors, 2); -}); +testWalk( + async (_d: string): Promise => {}, + async function onError(): Promise { + assertReady(0); + const ignored = await walkArray("missing"); + assertEquals(ignored.length, 0); + let errors = 0; + await walkArray("missing", { onError: (_e): number => (errors += 1) }); + // It's 2 since walkArray iterates over both sync and async. + assertEquals(errors, 2); + } +); testWalk( - async (d: string) => { + async (d: string): Promise => { await mkdir(d + "/a"); await mkdir(d + "/b"); await touch(d + "/a/x"); @@ -238,7 +242,7 @@ testWalk( assert(err.message, "Not implemented"); } }, - async function symlink() { + async function symlink(): Promise { // symlink is not yet implemented on Windows. if (isWindows) { return; @@ -251,6 +255,6 @@ testWalk( const arr = await walkArray("a", { followSymlinks: true }); assertEquals(arr.length, 3); - assert(arr.some(f => f.endsWith("/b/z"))); + assert(arr.some((f): boolean => f.endsWith("/b/z"))); } ); diff --git a/fs/write_file_str_test.ts b/fs/write_file_str_test.ts index 4039b26f6c..77b1e734e4 100644 --- a/fs/write_file_str_test.ts +++ b/fs/write_file_str_test.ts @@ -5,7 +5,7 @@ import * as path from "./path/mod.ts"; const testdataDir = path.resolve("fs", "testdata"); -test(function testReadFileSync() { +test(function testReadFileSync(): void { const jsonFile = path.join(testdataDir, "write_file_1.json"); const content = "write_file_str_test"; writeFileStrSync(jsonFile, content); @@ -21,7 +21,7 @@ test(function testReadFileSync() { assertEquals(content, result); }); -test(async function testReadFile() { +test(async function testReadFile(): Promise { const jsonFile = path.join(testdataDir, "write_file_2.json"); const content = "write_file_str_test"; await writeFileStr(jsonFile, content); diff --git a/fs/write_json_test.ts b/fs/write_json_test.ts index acc3660010..a282d399f4 100644 --- a/fs/write_json_test.ts +++ b/fs/write_json_test.ts @@ -10,11 +10,11 @@ import * as path from "./path/mod.ts"; const testdataDir = path.resolve("fs", "testdata"); -test(async function writeJsonIfNotExists() { +test(async function writeJsonIfNotExists(): Promise { const notExistsJsonFile = path.join(testdataDir, "file_not_exists.json"); await assertThrowsAsync( - async () => { + async (): Promise => { await writeJson(notExistsJsonFile, { a: "1" }); throw new Error("should write success"); }, @@ -29,13 +29,13 @@ test(async function writeJsonIfNotExists() { assertEquals(new TextDecoder().decode(content), `{"a":"1"}`); }); -test(async function writeJsonIfExists() { +test(async function writeJsonIfExists(): Promise { const existsJsonFile = path.join(testdataDir, "file_write_exists.json"); await Deno.writeFile(existsJsonFile, new Uint8Array()); await assertThrowsAsync( - async () => { + async (): Promise => { await writeJson(existsJsonFile, { a: "1" }); throw new Error("should write success"); }, @@ -50,7 +50,7 @@ test(async function writeJsonIfExists() { assertEquals(new TextDecoder().decode(content), `{"a":"1"}`); }); -test(async function writeJsonIfExistsAnInvalidJson() { +test(async function writeJsonIfExistsAnInvalidJson(): Promise { const existsInvalidJsonFile = path.join( testdataDir, "file_write_invalid.json" @@ -60,7 +60,7 @@ test(async function writeJsonIfExistsAnInvalidJson() { await Deno.writeFile(existsInvalidJsonFile, invalidJsonContent); await assertThrowsAsync( - async () => { + async (): Promise => { await writeJson(existsInvalidJsonFile, { a: "1" }); throw new Error("should write success"); }, @@ -75,14 +75,14 @@ test(async function writeJsonIfExistsAnInvalidJson() { assertEquals(new TextDecoder().decode(content), `{"a":"1"}`); }); -test(async function writeJsonWithSpaces() { +test(async function writeJsonWithSpaces(): Promise { const existsJsonFile = path.join(testdataDir, "file_write_spaces.json"); const invalidJsonContent = new TextEncoder().encode(); await Deno.writeFile(existsJsonFile, invalidJsonContent); await assertThrowsAsync( - async () => { + async (): Promise => { await writeJson(existsJsonFile, { a: "1" }, { spaces: 2 }); throw new Error("should write success"); }, @@ -97,14 +97,14 @@ test(async function writeJsonWithSpaces() { assertEquals(new TextDecoder().decode(content), `{\n "a": "1"\n}`); }); -test(async function writeJsonWithReplacer() { +test(async function writeJsonWithReplacer(): Promise { const existsJsonFile = path.join(testdataDir, "file_write_replacer.json"); const invalidJsonContent = new TextEncoder().encode(); await Deno.writeFile(existsJsonFile, invalidJsonContent); await assertThrowsAsync( - async () => { + async (): Promise => { await writeJson( existsJsonFile, { a: "1", b: "2", c: "3" }, @@ -125,11 +125,11 @@ test(async function writeJsonWithReplacer() { assertEquals(new TextDecoder().decode(content), `{"a":"1"}`); }); -test(function writeJsonSyncIfNotExists() { +test(function writeJsonSyncIfNotExists(): void { const notExistsJsonFile = path.join(testdataDir, "file_not_exists_sync.json"); assertThrows( - () => { + (): void => { writeJsonSync(notExistsJsonFile, { a: "1" }); throw new Error("should write success"); }, @@ -144,13 +144,13 @@ test(function writeJsonSyncIfNotExists() { assertEquals(new TextDecoder().decode(content), `{"a":"1"}`); }); -test(function writeJsonSyncIfExists() { +test(function writeJsonSyncIfExists(): void { const existsJsonFile = path.join(testdataDir, "file_write_exists_sync.json"); Deno.writeFileSync(existsJsonFile, new Uint8Array()); assertThrows( - () => { + (): void => { writeJsonSync(existsJsonFile, { a: "1" }); throw new Error("should write success"); }, @@ -165,7 +165,7 @@ test(function writeJsonSyncIfExists() { assertEquals(new TextDecoder().decode(content), `{"a":"1"}`); }); -test(function writeJsonSyncIfExistsAnInvalidJson() { +test(function writeJsonSyncIfExistsAnInvalidJson(): void { const existsInvalidJsonFile = path.join( testdataDir, "file_write_invalid_sync.json" @@ -175,7 +175,7 @@ test(function writeJsonSyncIfExistsAnInvalidJson() { Deno.writeFileSync(existsInvalidJsonFile, invalidJsonContent); assertThrows( - () => { + (): void => { writeJsonSync(existsInvalidJsonFile, { a: "1" }); throw new Error("should write success"); }, @@ -190,14 +190,14 @@ test(function writeJsonSyncIfExistsAnInvalidJson() { 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 invalidJsonContent = new TextEncoder().encode(); Deno.writeFileSync(existsJsonFile, invalidJsonContent); assertThrows( - () => { + (): void => { writeJsonSync(existsJsonFile, { a: "1" }, { spaces: 2 }); throw new Error("should write success"); }, @@ -212,7 +212,7 @@ test(function writeJsonWithSpaces() { assertEquals(new TextDecoder().decode(content), `{\n "a": "1"\n}`); }); -test(function writeJsonWithReplacer() { +test(function writeJsonWithReplacer(): void { const existsJsonFile = path.join( testdataDir, "file_write_replacer_sync.json" @@ -222,7 +222,7 @@ test(function writeJsonWithReplacer() { Deno.writeFileSync(existsJsonFile, invalidJsonContent); assertThrows( - () => { + (): void => { writeJsonSync( existsJsonFile, { a: "1", b: "2", c: "3" }, diff --git a/http/file_server.ts b/http/file_server.ts index 83de373648..6a3fb9e459 100755 --- a/http/file_server.ts +++ b/http/file_server.ts @@ -76,9 +76,11 @@ function modeToString(isDir: boolean, maybeMode: number | null): string { .split("") .reverse() .slice(0, 3) - .forEach(v => { - output = modeMap[+v] + output; - }); + .forEach( + (v): void => { + output = modeMap[+v] + output; + } + ); output = `(${isDir ? "d" : "-"}${output})`; return output; } @@ -220,30 +222,33 @@ function setCORS(res: Response): void { ); } -listenAndServe(addr, async req => { - const fileName = req.url.replace(/\/$/, ""); - const filePath = currentDir + fileName; +listenAndServe( + addr, + async (req): Promise => { + const fileName = req.url.replace(/\/$/, ""); + const filePath = currentDir + fileName; - let response: Response; + let response: Response; - try { - const fileInfo = await stat(filePath); - if (fileInfo.isDirectory()) { - // Bug with deno.stat: name and path not populated - // Yuck! - response = await serveDir(req, filePath, fileName); - } else { - response = await serveFile(req, filePath); + try { + const fileInfo = await stat(filePath); + if (fileInfo.isDirectory()) { + // Bug with deno.stat: name and path not populated + // Yuck! + response = await serveDir(req, filePath, fileName); + } else { + response = await serveFile(req, filePath); + } + } catch (e) { + response = await serveFallback(req, e); + } finally { + if (CORSEnabled) { + setCORS(response); + } + serverLog(req, response); + req.respond(response); } - } catch (e) { - response = await serveFallback(req, e); - } finally { - if (CORSEnabled) { - setCORS(response); - } - serverLog(req, response); - req.respond(response); } -}); +); console.log(`HTTP server listening on http://${addr}/`); diff --git a/http/file_server_test.ts b/http/file_server_test.ts index 31ddca08eb..b976c0dc0e 100644 --- a/http/file_server_test.ts +++ b/http/file_server_test.ts @@ -30,7 +30,7 @@ function killFileServer(): void { fileServer.stdout.close(); } -test(async function serveFile() { +test(async function serveFile(): Promise { await startFileServer(); try { 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 { await startFileServer(); try { const res = await fetch("http://localhost:4500/"); @@ -60,7 +60,7 @@ test(async function serveDirectory() { } }); -test(async function serveFallback() { +test(async function serveFallback(): Promise { await startFileServer(); try { const res = await fetch("http://localhost:4500/badfile.txt"); diff --git a/http/racing_server.ts b/http/racing_server.ts index c44fc12161..0053fa4282 100644 --- a/http/racing_server.ts +++ b/http/racing_server.ts @@ -8,7 +8,7 @@ const body = new TextEncoder().encode("Hello 1\n"); const body4 = new TextEncoder().encode("World 4\n"); function sleep(ms: number): Promise { - return new Promise(res => setTimeout(res, ms)); + return new Promise((res): number => setTimeout(res, ms)); } async function delayedRespond(request: ServerRequest): Promise { diff --git a/http/server.ts b/http/server.ts index f1ef015ba4..0892b26f7d 100644 --- a/http/server.ts +++ b/http/server.ts @@ -16,10 +16,12 @@ interface Deferred { function deferred(isResolved = false): Deferred { let resolve, reject; - const promise = new Promise((res, rej) => { - resolve = res; - reject = rej; - }); + const promise = new Promise( + (res, rej): void => { + resolve = res; + reject = rej; + } + ); if (isResolved) { resolve(); } @@ -181,7 +183,7 @@ export class ServerRequest { const transferEncodings = this.headers .get("transfer-encoding") .split(",") - .map(e => e.trim().toLowerCase()); + .map((e): string => e.trim().toLowerCase()); if (transferEncodings.includes("chunked")) { // Based on https://tools.ietf.org/html/rfc2616#section-19.4.6 const tp = new TextProtoReader(this.r); @@ -341,10 +343,10 @@ export async function* serve( let handleConn = (_conn: Conn): void => {}; let scheduleAccept = (): void => {}; const acceptRoutine = (): void => { - scheduleAccept = () => { + scheduleAccept = (): void => { listener.accept().then(handleConn); }; - handleConn = (conn: Conn) => { + handleConn = (conn: Conn): void => { const httpConn = createHttpConn(conn); serveConn(env, httpConn); // don't block scheduleAccept(); // schedule next accept diff --git a/http/server_test.ts b/http/server_test.ts index ed28025cde..36d704a4d6 100644 --- a/http/server_test.ts +++ b/http/server_test.ts @@ -28,12 +28,14 @@ interface Deferred { } function deferred(isResolved = false): Deferred { - let resolve: Handler = () => void 0; - let reject: Handler = () => void 0; - const promise = new Promise((res, rej) => { - resolve = res; - reject = rej; - }); + let resolve: Handler = (): void => void 0; + let reject: Handler = (): void => void 0; + const promise = new Promise( + (res, rej): void => { + resolve = res; + reject = rej; + } + ); if (isResolved) { resolve(); } @@ -64,7 +66,7 @@ const responseTests: ResponseTest[] = [ } ]; -test(async function responseWrite() { +test(async function responseWrite(): Promise { for (const testCase of responseTests) { const buf = new Buffer(); const bufw = new BufWriter(buf); @@ -75,15 +77,15 @@ test(async function responseWrite() { localAddr: "", remoteAddr: "", rid: -1, - closeRead: () => {}, - closeWrite: () => {}, - read: async () => { + closeRead: (): void => {}, + closeWrite: (): void => {}, + read: async (): Promise => { return { eof: true, nread: 0 }; }, - write: async () => { + write: async (): Promise => { return -1; }, - close: () => {}, + close: (): void => {}, lastPipelineId: 0, 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 { { const req = new ServerRequest(); req.headers = new Headers(); @@ -117,7 +119,7 @@ test(async function requestBodyWithContentLength() { } }); -test(async function requestBodyWithTransferEncoding() { +test(async function requestBodyWithTransferEncoding(): Promise { { const shortText = "Hello"; const req = new ServerRequest(); @@ -166,7 +168,7 @@ test(async function requestBodyWithTransferEncoding() { } }); -test(async function requestBodyStreamWithContentLength() { +test(async function requestBodyStreamWithContentLength(): Promise { { const shortText = "Hello"; const req = new ServerRequest(); @@ -201,7 +203,7 @@ test(async function requestBodyStreamWithContentLength() { } }); -test(async function requestBodyStreamWithTransferEncoding() { +test(async function requestBodyStreamWithTransferEncoding(): Promise { { const shortText = "Hello"; const req = new ServerRequest(); diff --git a/io/bufio_test.ts b/io/bufio_test.ts index 1351b7e370..d1db119d8a 100644 --- a/io/bufio_test.ts +++ b/io/bufio_test.ts @@ -29,7 +29,7 @@ async function readBytes(buf: BufReader): Promise { return decoder.decode(b.subarray(0, nb)); } -test(async function bufioReaderSimple() { +test(async function bufioReaderSimple(): Promise { const data = "hello world"; const b = new BufReader(stringsReader(data)); const s = await readBytes(b); @@ -42,9 +42,12 @@ interface ReadMaker { } const readMakers: ReadMaker[] = [ - { name: "full", fn: r => r }, - { name: "byte", fn: r => new iotest.OneByteReader(r) }, - { name: "half", fn: r => new iotest.HalfReader(r) } + { name: "full", fn: (r): Reader => 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) }, // { name: "timeout", fn: r => new iotest.TimeoutReader(r) }, ]; @@ -70,12 +73,12 @@ interface NamedBufReader { } const bufreaders: NamedBufReader[] = [ - { name: "1", fn: (b: BufReader) => reads(b, 1) }, - { name: "2", fn: (b: BufReader) => reads(b, 2) }, - { name: "3", fn: (b: BufReader) => reads(b, 3) }, - { name: "4", fn: (b: BufReader) => reads(b, 4) }, - { name: "5", fn: (b: BufReader) => reads(b, 5) }, - { name: "7", fn: (b: BufReader) => reads(b, 7) }, + { name: "1", fn: (b: BufReader): Promise => reads(b, 1) }, + { name: "2", fn: (b: BufReader): Promise => reads(b, 2) }, + { name: "3", fn: (b: BufReader): Promise => reads(b, 3) }, + { name: "4", fn: (b: BufReader): Promise => reads(b, 4) }, + { name: "5", fn: (b: BufReader): Promise => reads(b, 5) }, + { name: "7", fn: (b: BufReader): Promise => reads(b, 7) }, { name: "bytes", fn: readBytes } // { name: "lines", fn: readLines }, ]; @@ -94,7 +97,7 @@ const bufsizes: number[] = [ 4096 ]; -test(async function bufioBufReader() { +test(async function bufioBufReader(): Promise { const texts = new Array(31); let str = ""; let all = ""; @@ -122,7 +125,7 @@ test(async function bufioBufReader() { } }); -test(async function bufioBufferFull() { +test(async function bufioBufferFull(): Promise { const longString = "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); @@ -201,12 +204,12 @@ async function testReadLine(input: Uint8Array): Promise { } } -test(async function bufioReadLine() { +test(async function bufioReadLine(): Promise { await testReadLine(testInput); await testReadLine(testInputrn); }); -test(async function bufioPeek() { +test(async function bufioPeek(): Promise { const decoder = new TextDecoder(); let p = new Uint8Array(10); // string is 16 (minReadBufferSize) long. @@ -283,7 +286,7 @@ test(async function bufioPeek() { */ }); -test(async function bufioWriter() { +test(async function bufioWriter(): Promise { const data = new Uint8Array(8192); 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 { const enc = new TextEncoder(); const dec = new TextDecoder(); const text = "Hello World"; diff --git a/io/ioutil_test.ts b/io/ioutil_test.ts index c6980ebb93..c1c1ded72a 100644 --- a/io/ioutil_test.ts +++ b/io/ioutil_test.ts @@ -26,19 +26,19 @@ class BinaryReader implements Reader { } } -test(async function testReadShort() { +test(async function testReadShort(): Promise { const r = new BinaryReader(new Uint8Array([0x12, 0x34])); const short = await readShort(new BufReader(r)); assertEquals(short, 0x1234); }); -test(async function testReadInt() { +test(async function testReadInt(): Promise { const r = new BinaryReader(new Uint8Array([0x12, 0x34, 0x56, 0x78])); const int = await readInt(new BufReader(r)); assertEquals(int, 0x12345678); }); -test(async function testReadLong() { +test(async function testReadLong(): Promise { const r = new BinaryReader( new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78]) ); @@ -46,7 +46,7 @@ test(async function testReadLong() { assertEquals(long, 0x1234567812345678); }); -test(async function testReadLong2() { +test(async function testReadLong2(): Promise { const r = new BinaryReader( new Uint8Array([0, 0, 0, 0, 0x12, 0x34, 0x56, 0x78]) ); @@ -54,7 +54,7 @@ test(async function testReadLong2() { assertEquals(long, 0x12345678); }); -test(async function testSliceLongToBytes() { +test(async function testSliceLongToBytes(): Promise { const arr = sliceLongToBytes(0x1234567890abcdef); const actual = readLong(new BufReader(new BinaryReader(new Uint8Array(arr)))); const expected = readLong( @@ -67,12 +67,12 @@ test(async function testSliceLongToBytes() { assertEquals(actual, expected); }); -test(async function testSliceLongToBytes2() { +test(async function testSliceLongToBytes2(): Promise { const arr = sliceLongToBytes(0x12345678); assertEquals(arr, [0, 0, 0, 0, 0x12, 0x34, 0x56, 0x78]); }); -test(async function testCopyN1() { +test(async function testCopyN1(): Promise { const w = new Buffer(); const r = stringsReader("abcdefghij"); const n = await copyN(w, r, 3); @@ -80,7 +80,7 @@ test(async function testCopyN1() { assertEquals(w.toString(), "abc"); }); -test(async function testCopyN2() { +test(async function testCopyN2(): Promise { const w = new Buffer(); const r = stringsReader("abcdefghij"); const n = await copyN(w, r, 11); diff --git a/io/readers_test.ts b/io/readers_test.ts index 35616ace24..a3806fbe21 100644 --- a/io/readers_test.ts +++ b/io/readers_test.ts @@ -6,14 +6,14 @@ import { StringWriter } from "./writers.ts"; import { copyN } from "./ioutil.ts"; import { decode } from "../strings/strings.ts"; -test(async function ioStringReader() { +test(async function ioStringReader(): Promise { const r = new StringReader("abcdef"); const { nread, eof } = await r.read(new Uint8Array(6)); assertEquals(nread, 6); assertEquals(eof, true); }); -test(async function ioStringReader() { +test(async function ioStringReader(): Promise { const r = new StringReader("abcdef"); const buf = new Uint8Array(3); let res1 = await r.read(buf); @@ -26,7 +26,7 @@ test(async function ioStringReader() { assertEquals(decode(buf), "def"); }); -test(async function ioMultiReader() { +test(async function ioMultiReader(): Promise { const r = new MultiReader(new StringReader("abc"), new StringReader("def")); const w = new StringWriter(); const n = await copyN(w, r, 4); diff --git a/io/util_test.ts b/io/util_test.ts index 6dde3a4fc5..3302fe9e32 100644 --- a/io/util_test.ts +++ b/io/util_test.ts @@ -5,7 +5,7 @@ import { assert, assertEquals } from "../testing/asserts.ts"; import { copyBytes, tempFile } from "./util.ts"; import * as path from "../fs/path.ts"; -test(function testCopyBytes() { +test(function testCopyBytes(): void { let dst = new Uint8Array(4); dst.fill(0); @@ -39,7 +39,7 @@ test(function testCopyBytes() { assertEquals(dst, Uint8Array.of(3, 4, 0, 0)); }); -test(async function ioTempfile() { +test(async function ioTempfile(): Promise { const f = await tempFile(".", { prefix: "prefix-", postfix: "-postfix" diff --git a/io/writers_test.ts b/io/writers_test.ts index 5d6ed33efc..decf611f1b 100644 --- a/io/writers_test.ts +++ b/io/writers_test.ts @@ -5,7 +5,7 @@ import { StringWriter } from "./writers.ts"; import { StringReader } from "./readers.ts"; import { copyN } from "./ioutil.ts"; -test(async function ioStringWriter() { +test(async function ioStringWriter(): Promise { const w = new StringWriter("base"); const r = new StringReader("0123456789"); await copyN(w, r, 4); diff --git a/log/handlers.ts b/log/handlers.ts index 666a8aa48f..f13a858e95 100644 --- a/log/handlers.ts +++ b/log/handlers.ts @@ -37,16 +37,19 @@ export class BaseHandler { return this.formatter(logRecord); } - return this.formatter.replace(/{(\S+)}/g, (match, p1) => { - const value = logRecord[p1]; + return this.formatter.replace( + /{(\S+)}/g, + (match, p1): string => { + const value = logRecord[p1]; - // do not interpolate missing values - if (!value) { - return match; + // do not interpolate missing values + if (!value) { + return match; + } + + return value; } - - return value; - }); + ); } log(_msg: string): void {} diff --git a/log/handlers_test.ts b/log/handlers_test.ts index 9cbf70be6c..329541fa1b 100644 --- a/log/handlers_test.ts +++ b/log/handlers_test.ts @@ -12,7 +12,7 @@ class TestHandler extends BaseHandler { } } -test(function simpleHandler() { +test(function simpleHandler(): void { const cases = new Map([ [ LogLevel.DEBUG, @@ -62,7 +62,7 @@ test(function simpleHandler() { } }); -test(function testFormatterAsString() { +test(function testFormatterAsString(): void { const handler = new TestHandler("DEBUG", { formatter: "test {levelName} {msg}" }); @@ -78,9 +78,9 @@ test(function testFormatterAsString() { assertEquals(handler.messages, ["test DEBUG Hello, world!"]); }); -test(function testFormatterAsFunction() { +test(function testFormatterAsFunction(): void { const handler = new TestHandler("DEBUG", { - formatter: logRecord => + formatter: (logRecord): string => `fn formmatter ${logRecord.levelName} ${logRecord.msg}` }); diff --git a/log/logger.ts b/log/logger.ts index d92c34a582..4150fb524b 100644 --- a/log/logger.ts +++ b/log/logger.ts @@ -39,9 +39,11 @@ export class Logger { levelName: getLevelName(level) }; - this.handlers.forEach(handler => { - handler.handle(record); - }); + this.handlers.forEach( + (handler): void => { + handler.handle(record); + } + ); } // eslint-disable-next-line @typescript-eslint/no-explicit-any diff --git a/log/logger_test.ts b/log/logger_test.ts index 7027201604..eb4e7673df 100644 --- a/log/logger_test.ts +++ b/log/logger_test.ts @@ -19,7 +19,7 @@ class TestHandler extends BaseHandler { } } -test(function simpleLogger() { +test(function simpleLogger(): void { const handler = new TestHandler("DEBUG"); let logger = new Logger("DEBUG"); @@ -32,7 +32,7 @@ test(function simpleLogger() { assertEquals(logger.handlers, [handler]); }); -test(function customHandler() { +test(function customHandler(): void { const handler = new TestHandler("DEBUG"); const logger = new Logger("DEBUG", [handler]); @@ -51,7 +51,7 @@ test(function customHandler() { assertEquals(handler.messages, ["DEBUG foo"]); }); -test(function logFunctions() { +test(function logFunctions(): void { let handler: TestHandler; const doLog = (level: string): void => { diff --git a/log/mod.ts b/log/mod.ts index ef5ca5a89b..9149e86044 100644 --- a/log/mod.ts +++ b/log/mod.ts @@ -89,9 +89,11 @@ export async function setup(config: LogConfig): Promise { }; // tear down existing handlers - state.handlers.forEach(handler => { - handler.destroy(); - }); + state.handlers.forEach( + (handler): void => { + handler.destroy(); + } + ); state.handlers.clear(); // setup handlers @@ -113,11 +115,13 @@ export async function setup(config: LogConfig): Promise { const handlerNames = loggerConfig.handlers || []; const handlers: BaseHandler[] = []; - handlerNames.forEach(handlerName => { - if (state.handlers.has(handlerName)) { - handlers.push(state.handlers.get(handlerName)); + handlerNames.forEach( + (handlerName): void => { + if (state.handlers.has(handlerName)) { + handlers.push(state.handlers.get(handlerName)); + } } - }); + ); const levelName = loggerConfig.level || DEFAULT_LEVEL; const logger = new Logger(levelName, handlers); diff --git a/log/test.ts b/log/test.ts index 44d86fa65e..f21fb5b3d7 100644 --- a/log/test.ts +++ b/log/test.ts @@ -22,7 +22,7 @@ class TestHandler extends log.handlers.BaseHandler { } } -test(async function defaultHandlers() { +test(async function defaultHandlers(): Promise { const loggers = { DEBUG: log.debug, INFO: log.info, @@ -59,7 +59,7 @@ test(async function defaultHandlers() { } }); -test(async function getLogger() { +test(async function getLogger(): Promise { const handler = new TestHandler("DEBUG"); await log.setup({ @@ -80,7 +80,7 @@ test(async function getLogger() { assertEquals(logger.handlers, [handler]); }); -test(async function getLoggerWithName() { +test(async function getLoggerWithName(): Promise { const fooHandler = new TestHandler("DEBUG"); await log.setup({ @@ -101,7 +101,7 @@ test(async function getLoggerWithName() { assertEquals(logger.handlers, [fooHandler]); }); -test(async function getLoggerUnknown() { +test(async function getLoggerUnknown(): Promise { await log.setup({ handlers: {}, loggers: {} diff --git a/media_types/test.ts b/media_types/test.ts index d028448f91..9d630ad103 100644 --- a/media_types/test.ts +++ b/media_types/test.ts @@ -11,14 +11,14 @@ import { types } from "./mod.ts"; -test(function testLookup() { +test(function testLookup(): void { assertEquals(lookup("json"), "application/json"); assertEquals(lookup(".md"), "text/markdown"); assertEquals(lookup("folder/file.js"), "application/javascript"); assertEquals(lookup("folder/.htaccess"), undefined); }); -test(function testContentType() { +test(function testContentType(): void { assertEquals(contentType("markdown"), "text/markdown; charset=utf-8"); assertEquals(contentType("file.json"), "application/json; charset=utf-8"); assertEquals(contentType("text/html"), "text/html; charset=utf-8"); @@ -29,23 +29,23 @@ test(function testContentType() { assertEquals(contentType(".htaccess"), undefined); }); -test(function testExtension() { +test(function testExtension(): void { assertEquals(extension("application/octet-stream"), "bin"); assertEquals(extension("application/javascript"), "js"); assertEquals(extension("text/html"), "html"); }); -test(function testCharset() { +test(function testCharset(): void { assertEquals(charset("text/markdown"), "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("foo"), undefined); }); -test(function testTypes() { +test(function testTypes(): void { assertEquals(types.get("js"), "application/javascript"); assertEquals(types.get("foo"), undefined); }); diff --git a/multipart/formfile_test.ts b/multipart/formfile_test.ts index 7f45c24dbe..63509fc9d2 100644 --- a/multipart/formfile_test.ts +++ b/multipart/formfile_test.ts @@ -3,7 +3,7 @@ import { test } from "../testing/mod.ts"; import { assertEquals } from "../testing/asserts.ts"; import { isFormFile } from "./formfile.ts"; -test(function multipartIsFormFile() { +test(function multipartIsFormFile(): void { assertEquals( isFormFile({ filename: "foo", diff --git a/multipart/multipart.ts b/multipart/multipart.ts index 9b3f1ceb01..0032e1cf54 100644 --- a/multipart/multipart.ts +++ b/multipart/multipart.ts @@ -166,19 +166,21 @@ class PartReader implements Reader, Closer { this.contentDisposition = comps[0]; comps .slice(1) - .map(v => v.trim()) - .map(kv => { - const [k, v] = kv.split("="); - if (v) { - const s = v.charAt(0); - const e = v.charAt(v.length - 1); - if ((s === e && s === '"') || s === "'") { - params[k] = v.substr(1, v.length - 2); - } else { - params[k] = v; + .map((v): string => v.trim()) + .map( + (kv): void => { + const [k, v] = kv.split("="); + if (v) { + const s = v.charAt(0); + const e = v.charAt(v.length - 1); + if ((s === e && s === '"') || s === "'") { + params[k] = v.substr(1, v.length - 2); + } else { + params[k] = v; + } } } - }); + ); return (this.contentDispositionParams = params); } diff --git a/multipart/multipart_test.ts b/multipart/multipart_test.ts index 0c80b8841c..ba4f05116d 100644 --- a/multipart/multipart_test.ts +++ b/multipart/multipart_test.ts @@ -23,7 +23,7 @@ const boundary = "--abcde"; const dashBoundary = e.encode("--" + boundary); const nlDashBoundary = e.encode("\r\n--" + boundary); -test(function multipartScanUntilBoundary1() { +test(function multipartScanUntilBoundary1(): void { const data = `--${boundary}`; const [n, err] = scanUntilBoundary( e.encode(data), @@ -36,7 +36,7 @@ test(function multipartScanUntilBoundary1() { assertEquals(err, "EOF"); }); -test(function multipartScanUntilBoundary2() { +test(function multipartScanUntilBoundary2(): void { const data = `foo\r\n--${boundary}`; const [n, err] = scanUntilBoundary( e.encode(data), @@ -49,7 +49,7 @@ test(function multipartScanUntilBoundary2() { assertEquals(err, "EOF"); }); -test(function multipartScanUntilBoundary4() { +test(function multipartScanUntilBoundary4(): void { const data = `foo\r\n--`; const [n, err] = scanUntilBoundary( e.encode(data), @@ -62,7 +62,7 @@ test(function multipartScanUntilBoundary4() { assertEquals(err, null); }); -test(function multipartScanUntilBoundary3() { +test(function multipartScanUntilBoundary3(): void { const data = `foobar`; const [n, err] = scanUntilBoundary( e.encode(data), @@ -75,25 +75,25 @@ test(function multipartScanUntilBoundary3() { assertEquals(err, null); }); -test(function multipartMatchAfterPrefix1() { +test(function multipartMatchAfterPrefix1(): void { const data = `${boundary}\r`; const v = matchAfterPrefix(e.encode(data), e.encode(boundary), null); assertEquals(v, 1); }); -test(function multipartMatchAfterPrefix2() { +test(function multipartMatchAfterPrefix2(): void { const data = `${boundary}hoge`; const v = matchAfterPrefix(e.encode(data), e.encode(boundary), null); assertEquals(v, -1); }); -test(function multipartMatchAfterPrefix3() { +test(function multipartMatchAfterPrefix3(): void { const data = `${boundary}`; const v = matchAfterPrefix(e.encode(data), e.encode(boundary), null); assertEquals(v, 0); }); -test(async function multipartMultipartWriter() { +test(async function multipartMultipartWriter(): Promise { const buf = new Buffer(); const mw = new MultipartWriter(buf); await mw.writeField("foo", "foo"); @@ -103,15 +103,15 @@ test(async function multipartMultipartWriter() { await mw.close(); }); -test(function multipartMultipartWriter2() { +test(function multipartMultipartWriter2(): void { const w = new StringWriter(); assertThrows( - () => new MultipartWriter(w, ""), + (): MultipartWriter => new MultipartWriter(w, ""), Error, "invalid boundary length" ); assertThrows( - () => + (): MultipartWriter => new MultipartWriter( w, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" @@ -120,52 +120,52 @@ test(function multipartMultipartWriter2() { "invalid boundary length" ); assertThrows( - () => new MultipartWriter(w, "aaa aaa"), + (): MultipartWriter => new MultipartWriter(w, "aaa aaa"), Error, "invalid boundary character" ); assertThrows( - () => new MultipartWriter(w, "boundary¥¥"), + (): MultipartWriter => new MultipartWriter(w, "boundary¥¥"), Error, "invalid boundary character" ); }); -test(async function multipartMultipartWriter3() { +test(async function multipartMultipartWriter3(): Promise { const w = new StringWriter(); const mw = new MultipartWriter(w); await mw.writeField("foo", "foo"); await mw.close(); await assertThrowsAsync( - async () => { + async (): Promise => { await mw.close(); }, Error, "closed" ); await assertThrowsAsync( - async () => { + async (): Promise => { await mw.writeFile("bar", "file", null); }, Error, "closed" ); await assertThrowsAsync( - async () => { + async (): Promise => { await mw.writeField("bar", "bar"); }, Error, "closed" ); assertThrows( - () => { + (): void => { mw.createFormField("bar"); }, Error, "closed" ); assertThrows( - () => { + (): void => { mw.createFormFile("bar", "file"); }, Error, @@ -173,7 +173,7 @@ test(async function multipartMultipartWriter3() { ); }); -test(async function multipartMultipartReader() { +test(async function multipartMultipartReader(): Promise { // FIXME: path resolution const o = await open(path.resolve("./multipart/fixtures/sample.txt")); const mr = new MultipartReader( @@ -188,7 +188,7 @@ test(async function multipartMultipartReader() { assert(file.content !== void 0); }); -test(async function multipartMultipartReader2() { +test(async function multipartMultipartReader2(): Promise { const o = await open(path.resolve("./multipart/fixtures/sample.txt")); const mr = new MultipartReader( o, diff --git a/prettier/main.ts b/prettier/main.ts index f4a2232ccb..a11501de13 100755 --- a/prettier/main.ts +++ b/prettier/main.ts @@ -188,7 +188,7 @@ async function checkSourceFiles( const results = await Promise.all(checks); - if (results.every(result => result)) { + if (results.every((result): boolean => result)) { console.log("Every file is formatted"); exit(0); } else { @@ -240,10 +240,12 @@ async function main(opts): Promise { } const options = { flags: "g" }; const skip = Array.isArray(ignore) - ? ignore.map((i: string) => glob(i, options)) + ? ignore.map((i: string): RegExp => glob(i, options)) : [glob(ignore, options)]; 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 }); try { if (check) { diff --git a/prettier/main_test.ts b/prettier/main_test.ts index 3d5d54d662..0c8cca7129 100644 --- a/prettier/main_test.ts +++ b/prettier/main_test.ts @@ -45,7 +45,7 @@ async function clearTestdataChanges(): Promise { await xrun({ args: ["git", "checkout", testdata] }).status(); } -test(async function testPrettierCheckAndFormatFiles() { +test(async function testPrettierCheckAndFormatFiles(): Promise { await clearTestdataChanges(); const files = [ @@ -73,7 +73,7 @@ Formatting ./prettier/testdata/1.js` await clearTestdataChanges(); }); -test(async function testPrettierCheckAndFormatDirs() { +test(async function testPrettierCheckAndFormatDirs(): Promise { await clearTestdataChanges(); const dirs = [join(testdata, "foo"), join(testdata, "bar")]; @@ -99,7 +99,7 @@ Formatting ./prettier/testdata/foo/1.js` await clearTestdataChanges(); }); -test(async function testPrettierOptions() { +test(async function testPrettierOptions(): Promise { await clearTestdataChanges(); const file0 = join(testdata, "opts", "0.ts"); diff --git a/strings/pad_test.ts b/strings/pad_test.ts index 43c80b36fa..e0364cf38a 100644 --- a/strings/pad_test.ts +++ b/strings/pad_test.ts @@ -2,7 +2,7 @@ import { test } from "../testing/mod.ts"; import { assertEquals } from "../testing/asserts.ts"; import { pad } from "./pad.ts"; -test(function padTest() { +test(function padTest(): void { const expected1 = "**deno"; const expected2 = "deno"; const expected3 = "deno**"; diff --git a/testing/README.md b/testing/README.md index 271ff75e60..0445e344fc 100644 --- a/testing/README.md +++ b/testing/README.md @@ -50,7 +50,7 @@ import { assertEquals } from "https://deno.land/std/testing/asserts.ts"; test({ name: "testing example", - fn() { + fn(): void { assertEquals("world", "world"); assertEquals({ hello: "world" }, { hello: "world" }); } @@ -62,7 +62,7 @@ runTests(); Short syntax (named function instead of object): ```ts -test(function example() { +test(function example(): void { assertEquals("world", "world"); assertEquals({ hello: "world" }, { hello: "world" }); }); @@ -71,14 +71,14 @@ test(function example() { Using `assertStrictEq()`: ```ts -test(function isStrictlyEqual() { +test(function isStrictlyEqual(): void { const a = {}; const b = a; assertStrictEq(a, b); }); // This test fails -test(function isNotStrictlyEqual() { +test(function isNotStrictlyEqual(): void { const a = {}; const b = {}; assertStrictEq(a, b); @@ -88,15 +88,17 @@ test(function isNotStrictlyEqual() { Using `assertThrows()`: ```ts -test(function doesThrow() { - assertThrows(() => { - throw new TypeError("hello world!"); - }); - assertThrows(() => { +test(function doesThrow(): void { + assertThrows( + (): void => { + throw new TypeError("hello world!"); + } + ); + assertThrows((): void => { throw new TypeError("hello world!"); }, TypeError); assertThrows( - () => { + (): void => { throw new TypeError("hello world!"); }, TypeError, @@ -105,40 +107,48 @@ test(function doesThrow() { }); // This test will not pass -test(function fails() { - assertThrows(() => { - console.log("Hello world"); - }); +test(function fails(): void { + assertThrows( + (): void => { + console.log("Hello world"); + } + ); }); ``` Using `assertThrowsAsync()`: ```ts -test(async function doesThrow() { - await assertThrowsAsync(async () => { - throw new TypeError("hello world!"); - }); - await assertThrowsAsync(async () => { +test(async function doesThrow(): Promise { + await assertThrowsAsync( + async (): Promise => { + throw new TypeError("hello world!"); + } + ); + await assertThrowsAsync(async (): Promise => { throw new TypeError("hello world!"); }, TypeError); await assertThrowsAsync( - async () => { + async (): Promise => { throw new TypeError("hello world!"); }, TypeError, "hello" ); - await assertThrowsAsync(async () => { - return Promise.reject(new Error()); - }); + await assertThrowsAsync( + async (): Promise => { + return Promise.reject(new Error()); + } + ); }); // This test will not pass -test(async function fails() { - await assertThrowsAsync(async () => { - console.log("Hello world"); - }); +test(async function fails(): Promise { + await assertThrowsAsync( + async (): Promise => { + console.log("Hello world"); + } + ); }); ``` @@ -149,7 +159,7 @@ Basic usage: ```ts import { runBenchmarks, bench } from "https://deno.land/std/testing/bench.ts"; -bench(function forIncrementX1e9(b) { +bench(function forIncrementX1e9(b): void { b.start(); for (let i = 0; i < 1e9; i++); b.stop(); @@ -164,7 +174,7 @@ Averaging execution time over multiple runs: bench({ name: "runs100ForIncrementX1e6", runs: 100, - func(b) { + func(b): void { b.start(); for (let i = 0; i < 1e6; i++); b.stop(); diff --git a/testing/asserts.ts b/testing/asserts.ts index 83fa7c8e50..a2583c22a9 100644 --- a/testing/asserts.ts +++ b/testing/asserts.ts @@ -15,7 +15,7 @@ export class AssertionError extends Error { export function equal(c: unknown, d: unknown): boolean { 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.size !== b.size) { return false; diff --git a/testing/asserts_test.ts b/testing/asserts_test.ts index ed58d74df8..e4f05f166e 100644 --- a/testing/asserts_test.ts +++ b/testing/asserts_test.ts @@ -16,7 +16,7 @@ import { } from "./asserts.ts"; import { test } from "./mod.ts"; -test(function testingEqual() { +test(function testingEqual(): void { assert(equal("world", "world")); assert(!equal("hello", "world")); assert(equal(5, 5)); @@ -48,7 +48,7 @@ test(function testingEqual() { assert(equal(new Set("denosaurus"), new Set("denosaurussss"))); }); -test(function testingNotEquals() { +test(function testingNotEquals(): void { const a = { foo: "bar" }; const b = { bar: "foo" }; assertNotEquals(a, b); @@ -64,7 +64,7 @@ test(function testingNotEquals() { assertEquals(didThrow, true); }); -test(function testingAssertStringContains() { +test(function testingAssertStringContains(): void { assertStrContains("Denosaurus", "saur"); assertStrContains("Denosaurus", "Deno"); assertStrContains("Denosaurus", "rus"); @@ -79,7 +79,7 @@ test(function testingAssertStringContains() { assertEquals(didThrow, true); }); -test(function testingArrayContains() { +test(function testingArrayContains(): void { const fixture = ["deno", "iz", "luv"]; const fixtureObject = [{ deno: "luv" }, { deno: "Js" }]; assertArrayContains(fixture, ["deno"]); @@ -95,7 +95,7 @@ test(function testingArrayContains() { assertEquals(didThrow, true); }); -test(function testingAssertStringContainsThrow() { +test(function testingAssertStringContainsThrow(): void { let didThrow = false; try { assertStrContains("Denosaurus from Jurassic", "Raptor"); @@ -110,11 +110,11 @@ test(function testingAssertStringContainsThrow() { assert(didThrow); }); -test(function testingAssertStringMatching() { +test(function testingAssertStringMatching(): void { assertMatch("foobar@deno.com", RegExp(/[a-zA-Z]+@[a-zA-Z]+.com/)); }); -test(function testingAssertStringMatchingThrows() { +test(function testingAssertStringMatchingThrows(): void { let didThrow = false; try { assertMatch("Denosaurus from Jurassic", RegExp(/Raptor/)); @@ -129,7 +129,7 @@ test(function testingAssertStringMatchingThrows() { assert(didThrow); }); -test(function testingAssertsUnimplemented() { +test(function testingAssertsUnimplemented(): void { let didThrow = false; try { unimplemented(); @@ -141,7 +141,7 @@ test(function testingAssertsUnimplemented() { assert(didThrow); }); -test(function testingAssertsUnreachable() { +test(function testingAssertsUnreachable(): void { let didThrow = false; try { unreachable(); @@ -153,10 +153,10 @@ test(function testingAssertsUnreachable() { assert(didThrow); }); -test(function testingAssertFail() { +test(function testingAssertFail(): void { assertThrows(fail, AssertionError, "Failed assertion."); assertThrows( - () => { + (): void => { fail("foo"); }, AssertionError, diff --git a/testing/bench.ts b/testing/bench.ts index 0094f62924..5b396df0e5 100644 --- a/testing/bench.ts +++ b/testing/bench.ts @@ -96,7 +96,7 @@ export async function runBenchmarks({ }: BenchmarkRunOptions = {}): Promise { // Filtering candidates by the "only" and "skip" constraint 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 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 if (failed) { - setTimeout(() => exit(1), 0); + setTimeout((): void => exit(1), 0); } } diff --git a/testing/bench_example.ts b/testing/bench_example.ts index 86e25b9a6c..d27fb97e8c 100644 --- a/testing/bench_example.ts +++ b/testing/bench_example.ts @@ -2,7 +2,7 @@ import { BenchmarkTimer, bench, runIfMain } from "./bench.ts"; // Basic -bench(function forIncrementX1e9(b: BenchmarkTimer) { +bench(function forIncrementX1e9(b: BenchmarkTimer): void { b.start(); for (let i = 0; i < 1e9; i++); b.stop(); @@ -12,7 +12,7 @@ bench(function forIncrementX1e9(b: BenchmarkTimer) { bench({ name: "runs100ForIncrementX1e6", runs: 100, - func(b) { + func(b): void { b.start(); for (let i = 0; i < 1e6; i++); b.stop(); @@ -20,7 +20,7 @@ bench({ }); // Itsabug -bench(function throwing(b) { +bench(function throwing(b): void { b.start(); // Throws bc the timer's stop method is never called }); diff --git a/testing/bench_test.ts b/testing/bench_test.ts index 8042db480f..1c6459bbb0 100644 --- a/testing/bench_test.ts +++ b/testing/bench_test.ts @@ -3,20 +3,20 @@ import { bench, runBenchmarks } from "./bench.ts"; import "./bench_example.ts"; -test(async function benching() { - bench(function forIncrementX1e9(b) { +test(async function benching(): Promise { + bench(function forIncrementX1e9(b): void { b.start(); for (let i = 0; i < 1e9; i++); b.stop(); }); - bench(function forDecrementX1e9(b) { + bench(function forDecrementX1e9(b): void { b.start(); for (let i = 1e9; i > 0; i--); b.stop(); }); - bench(async function forAwaitFetchDenolandX10(b) { + bench(async function forAwaitFetchDenolandX10(b): Promise { b.start(); for (let i = 0; i < 10; i++) { let r = await fetch("https://deno.land/"); @@ -25,14 +25,16 @@ test(async function benching() { b.stop(); }); - bench(async function promiseAllFetchDenolandX10(b) { + bench(async function promiseAllFetchDenolandX10(b): Promise { const urls = new Array(10).fill("https://deno.land/"); b.start(); await Promise.all( - urls.map(async (denoland: string) => { - let r = await fetch(denoland); - await r.text(); - }) + urls.map( + async (denoland: string): Promise => { + let r = await fetch(denoland); + await r.text(); + } + ) ); b.stop(); }); @@ -40,14 +42,14 @@ test(async function benching() { bench({ name: "runs100ForIncrementX1e6", runs: 100, - func(b) { + func(b): void { b.start(); for (let i = 0; i < 1e6; i++); b.stop(); } }); - bench(function throwing(b) { + bench(function throwing(b): void { b.start(); // Throws bc the timer's stop method is never called }); diff --git a/testing/diff.ts b/testing/diff.ts index e951032f56..4c96b3b282 100644 --- a/testing/diff.ts +++ b/testing/diff.ts @@ -54,12 +54,18 @@ export default function diff(A: T[], B: T[]): Array> { if (!M && !N && !suffixCommon.length && !prefixCommon.length) return []; if (!N) { return [ - ...prefixCommon.map(c => ({ type: DiffType.common, value: c })), - ...A.map(a => ({ - type: swapped ? DiffType.added : DiffType.removed, - value: a - })), - ...suffixCommon.map(c => ({ type: DiffType.common, value: c })) + ...prefixCommon.map( + (c): DiffResult => ({ type: DiffType.common, value: c }) + ), + ...A.map( + (a): DiffResult => ({ + type: swapped ? DiffType.added : DiffType.removed, + value: a + }) + ), + ...suffixCommon.map( + (c): DiffResult => ({ type: DiffType.common, value: c }) + ) ]; } const offset = N; @@ -198,8 +204,12 @@ export default function diff(A: T[], B: T[]): Array> { ); } return [ - ...prefixCommon.map(c => ({ type: DiffType.common, value: c })), + ...prefixCommon.map( + (c): DiffResult => ({ type: DiffType.common, value: c }) + ), ...backTrace(A, B, fp[delta + offset], swapped), - ...suffixCommon.map(c => ({ type: DiffType.common, value: c })) + ...suffixCommon.map( + (c): DiffResult => ({ type: DiffType.common, value: c }) + ) ]; } diff --git a/testing/diff_test.ts b/testing/diff_test.ts index e62f452488..d9fbdb9564 100644 --- a/testing/diff_test.ts +++ b/testing/diff_test.ts @@ -4,14 +4,14 @@ import { test } from "./mod.ts"; test({ name: "empty", - fn() { + fn(): void { assertEquals(diff([], []), []); } }); test({ name: '"a" vs "b"', - fn() { + fn(): void { assertEquals(diff(["a"], ["b"]), [ { type: "removed", value: "a" }, { type: "added", value: "b" } @@ -21,28 +21,28 @@ test({ test({ name: '"a" vs "a"', - fn() { + fn(): void { assertEquals(diff(["a"], ["a"]), [{ type: "common", value: "a" }]); } }); test({ name: '"a" vs ""', - fn() { + fn(): void { assertEquals(diff(["a"], []), [{ type: "removed", value: "a" }]); } }); test({ name: '"" vs "a"', - fn() { + fn(): void { assertEquals(diff([], ["a"]), [{ type: "added", value: "a" }]); } }); test({ name: '"a" vs "a, b"', - fn() { + fn(): void { assertEquals(diff(["a"], ["a", "b"]), [ { type: "common", value: "a" }, { type: "added", value: "b" } @@ -52,7 +52,7 @@ test({ test({ name: '"strength" vs "string"', - fn() { + fn(): void { assertEquals(diff(Array.from("strength"), Array.from("string")), [ { type: "common", value: "s" }, { type: "common", value: "t" }, @@ -69,7 +69,7 @@ test({ test({ name: '"strength" vs ""', - fn() { + fn(): void { assertEquals(diff(Array.from("strength"), Array.from("")), [ { type: "removed", value: "s" }, { type: "removed", value: "t" }, @@ -85,7 +85,7 @@ test({ test({ name: '"" vs "strength"', - fn() { + fn(): void { assertEquals(diff(Array.from(""), Array.from("strength")), [ { type: "added", value: "s" }, { type: "added", value: "t" }, @@ -101,7 +101,7 @@ test({ test({ name: '"abc", "c" vs "abc", "bcd", "c"', - fn() { + fn(): void { assertEquals(diff(["abc", "c"], ["abc", "bcd", "c"]), [ { type: "common", value: "abc" }, { type: "added", value: "bcd" }, diff --git a/testing/format.ts b/testing/format.ts index 9a8b02ac6a..8ed066eb05 100644 --- a/testing/format.ts +++ b/testing/format.ts @@ -358,11 +358,13 @@ const getKeysOfEnumerableProperties = (object: {}): Array => { const keys: Array = Object.keys(object).sort(); if (Object.getOwnPropertySymbols) { - Object.getOwnPropertySymbols(object).forEach(symbol => { - if (Object.getOwnPropertyDescriptor(object, symbol)!.enumerable) { - keys.push(symbol); + Object.getOwnPropertySymbols(object).forEach( + (symbol): void => { + if (Object.getOwnPropertyDescriptor(object, symbol)!.enumerable) { + keys.push(symbol); + } } - }); + ); } return keys; @@ -524,7 +526,7 @@ const getConfig = (options: Options): Config => ({ // eslint-disable-next-line @typescript-eslint/no-explicit-any export function format(val: any, options: Optional = {}): string { const opts = Object.keys(DEFAULT_OPTIONS).reduce( - (acc: Options, k: keyof Options) => { + (acc: Options, k: keyof Options): unknown => { const opt = options[k]; if (typeof opt === "undefined") { return { ...acc, [k]: DEFAULT_OPTIONS[k] }; diff --git a/testing/format_test.ts b/testing/format_test.ts index fe6d946efe..0601a5db29 100644 --- a/testing/format_test.ts +++ b/testing/format_test.ts @@ -53,7 +53,7 @@ const createExpected = () => test({ name: "prints empty arguments", - fn() { + fn(): void { const val = returnArguments(); assertEquals(format(val), "Arguments []"); } @@ -61,7 +61,7 @@ test({ test({ name: "prints an empty array", - fn() { + fn(): void { const val: unknown[] = []; assertEquals(format(val), "Array []"); } @@ -69,7 +69,7 @@ test({ test({ name: "prints an array with items", - fn() { + fn(): void { const val = [1, 2, 3]; assertEquals(format(val), "Array [\n 1,\n 2,\n 3,\n]"); } @@ -77,7 +77,7 @@ test({ test({ name: "prints a empty typed array", - fn() { + fn(): void { const val = new Uint32Array(0); assertEquals(format(val), "Uint32Array []"); } @@ -85,7 +85,7 @@ test({ test({ name: "prints a typed array with items", - fn() { + fn(): void { const val = new Uint32Array(3); assertEquals(format(val), "Uint32Array [\n 0,\n 0,\n 0,\n]"); } @@ -93,7 +93,7 @@ test({ test({ name: "prints an array buffer", - fn() { + fn(): void { const val = new ArrayBuffer(3); assertEquals(format(val), "ArrayBuffer []"); } @@ -101,7 +101,7 @@ test({ test({ name: "prints a nested array", - fn() { + fn(): void { const val = [[1, 2, 3]]; assertEquals( format(val), @@ -112,7 +112,7 @@ test({ test({ name: "prints true", - fn() { + fn(): void { const val = true; assertEquals(format(val), "true"); } @@ -120,7 +120,7 @@ test({ test({ name: "prints false", - fn() { + fn(): void { const val = false; assertEquals(format(val), "false"); } @@ -128,7 +128,7 @@ test({ test({ name: "prints an error", - fn() { + fn(): void { const val = new Error(); assertEquals(format(val), "[Error]"); } @@ -136,7 +136,7 @@ test({ test({ name: "prints a typed error with a message", - fn() { + fn(): void { const val = new TypeError("message"); assertEquals(format(val), "[TypeError: message]"); } @@ -144,7 +144,7 @@ test({ test({ name: "prints a function constructor", - fn() { + fn(): void { // tslint:disable-next-line:function-constructor const val = new Function(); assertEquals(format(val), "[Function anonymous]"); @@ -153,20 +153,20 @@ test({ test({ name: "prints an anonymous callback function", - fn() { + fn(): void { let val; function f(cb: () => void): void { val = cb; } // tslint:disable-next-line:no-empty - f(() => {}); + f((): void => {}); assertEquals(format(val), "[Function anonymous]"); } }); test({ name: "prints an anonymous assigned function", - fn() { + fn(): void { // tslint:disable-next-line:no-empty const val = (): void => {}; const formatted = format(val); @@ -179,7 +179,7 @@ test({ test({ name: "prints a named function", - fn() { + fn(): void { // tslint:disable-next-line:no-empty const val = function named(): void {}; assertEquals(format(val), "[Function named]"); @@ -188,7 +188,7 @@ test({ test({ name: "prints a named generator function", - fn() { + fn(): void { const val = function* generate(): IterableIterator { yield 1; yield 2; @@ -200,7 +200,7 @@ test({ test({ name: "can customize function names", - fn() { + fn(): void { // tslint:disable-next-line:no-empty const val = function named(): void {}; assertEquals( @@ -214,7 +214,7 @@ test({ test({ name: "prints Infinity", - fn() { + fn(): void { const val = Infinity; assertEquals(format(val), "Infinity"); } @@ -222,7 +222,7 @@ test({ test({ name: "prints -Infinity", - fn() { + fn(): void { const val = -Infinity; assertEquals(format(val), "-Infinity"); } @@ -230,7 +230,7 @@ test({ test({ name: "prints an empty map", - fn() { + fn(): void { const val = new Map(); assertEquals(format(val), "Map {}"); } @@ -238,7 +238,7 @@ test({ test({ name: "prints a map with values", - fn() { + fn(): void { const val = new Map(); val.set("prop1", "value1"); val.set("prop2", "value2"); @@ -251,7 +251,7 @@ test({ test({ name: "prints a map with non-string keys", - fn() { + fn(): void { // eslint-disable-next-line @typescript-eslint/no-explicit-any const val = new Map([ [false, "boolean"], @@ -294,7 +294,7 @@ test({ test({ name: "prints NaN", - fn() { + fn(): void { const val = NaN; assertEquals(format(val), "NaN"); } @@ -302,7 +302,7 @@ test({ test({ name: "prints null", - fn() { + fn(): void { const val = null; assertEquals(format(val), "null"); } @@ -310,7 +310,7 @@ test({ test({ name: "prints a positive number", - fn() { + fn(): void { const val = 123; assertEquals(format(val), "123"); } @@ -318,7 +318,7 @@ test({ test({ name: "prints a negative number", - fn() { + fn(): void { const val = -123; assertEquals(format(val), "-123"); } @@ -326,7 +326,7 @@ test({ test({ name: "prints zero", - fn() { + fn(): void { const val = 0; assertEquals(format(val), "0"); } @@ -334,7 +334,7 @@ test({ test({ name: "prints negative zero", - fn() { + fn(): void { const val = -0; assertEquals(format(val), "-0"); } @@ -342,7 +342,7 @@ test({ test({ name: "prints a date", - fn() { + fn(): void { const val = new Date(10e11); assertEquals(format(val), "2001-09-09T01:46:40.000Z"); } @@ -350,7 +350,7 @@ test({ test({ name: "prints an invalid date", - fn() { + fn(): void { const val = new Date(Infinity); assertEquals(format(val), "Date { NaN }"); } @@ -358,7 +358,7 @@ test({ test({ name: "prints an empty object", - fn() { + fn(): void { const val = {}; assertEquals(format(val), "Object {}"); } @@ -366,7 +366,7 @@ test({ test({ name: "prints an object with properties", - fn() { + fn(): void { const val = { prop1: "value1", prop2: "value2" }; assertEquals( format(val), @@ -377,7 +377,7 @@ test({ test({ name: "prints an object with properties and symbols", - fn() { + fn(): void { // eslint-disable-next-line @typescript-eslint/no-explicit-any const val: any = {}; val[Symbol("symbol1")] = "value2"; @@ -393,7 +393,7 @@ test({ test({ name: "prints an object without non-enumerable properties which have string key", - fn() { + fn(): void { const val = { enumerable: true }; @@ -409,7 +409,7 @@ test({ test({ name: "prints an object without non-enumerable properties which have symbol key", - fn() { + fn(): void { const val = { enumerable: true }; @@ -424,7 +424,7 @@ test({ test({ name: "prints an object with sorted properties", - fn() { + fn(): void { const val = { b: 1, a: 2 }; assertEquals(format(val), 'Object {\n "a": 2,\n "b": 1,\n}'); } @@ -432,7 +432,7 @@ test({ test({ name: "prints regular expressions from constructors", - fn() { + fn(): void { const val = new RegExp("regexp"); assertEquals(format(val), "/regexp/"); } @@ -440,7 +440,7 @@ test({ test({ name: "prints regular expressions from literals", - fn() { + fn(): void { const val = /regexp/gi; assertEquals(format(val), "/regexp/gi"); } @@ -448,7 +448,7 @@ test({ test({ name: "prints regular expressions {escapeRegex: false}", - fn() { + fn(): void { const val = /regexp\d/gi; assertEquals(format(val), "/regexp\\d/gi"); } @@ -456,7 +456,7 @@ test({ test({ name: "prints regular expressions {escapeRegex: true}", - fn() { + fn(): void { const val = /regexp\d/gi; assertEquals(format(val, { escapeRegex: true }), "/regexp\\\\d/gi"); } @@ -464,7 +464,7 @@ test({ test({ name: "escapes regular expressions nested inside object", - fn() { + fn(): void { const obj = { test: /regexp\d/gi }; assertEquals( format(obj, { escapeRegex: true }), @@ -475,7 +475,7 @@ test({ test({ name: "prints an empty set", - fn() { + fn(): void { const val = new Set(); assertEquals(format(val), "Set {}"); } @@ -483,7 +483,7 @@ test({ test({ name: "prints a set with values", - fn() { + fn(): void { const val = new Set(); val.add("value1"); val.add("value2"); @@ -493,7 +493,7 @@ test({ test({ name: "prints a string", - fn() { + fn(): void { const val = "string"; assertEquals(format(val), '"string"'); } @@ -501,7 +501,7 @@ test({ test({ name: "prints and escape a string", - fn() { + fn(): void { const val = "\"'\\"; assertEquals(format(val), '"\\"\'\\\\"'); } @@ -509,7 +509,7 @@ test({ test({ name: "doesn't escape string with {excapeString: false}", - fn() { + fn(): void { const val = "\"'\\n"; assertEquals(format(val, { escapeString: false }), '""\'\\n"'); } @@ -517,7 +517,7 @@ test({ test({ name: "prints a string with escapes", - fn() { + fn(): void { assertEquals(format('"-"'), '"\\"-\\""'); assertEquals(format("\\ \\\\"), '"\\\\ \\\\\\\\"'); } @@ -525,7 +525,7 @@ test({ test({ name: "prints a multiline string", - fn() { + fn(): void { const val = ["line 1", "line 2", "line 3"].join("\n"); assertEquals(format(val), '"' + val + '"'); } @@ -533,7 +533,7 @@ test({ test({ name: "prints a multiline string as value of object property", - fn() { + fn(): void { const polyline = { props: { id: "J", @@ -571,7 +571,7 @@ test({ test({ name: "prints a symbol", - fn() { + fn(): void { const val = Symbol("symbol"); assertEquals(format(val), "Symbol(symbol)"); } @@ -579,7 +579,7 @@ test({ test({ name: "prints undefined", - fn() { + fn(): void { const val = undefined; assertEquals(format(val), "undefined"); } @@ -587,7 +587,7 @@ test({ test({ name: "prints a WeakMap", - fn() { + fn(): void { const val = new WeakMap(); assertEquals(format(val), "WeakMap {}"); } @@ -595,7 +595,7 @@ test({ test({ name: "prints a WeakSet", - fn() { + fn(): void { const val = new WeakSet(); assertEquals(format(val), "WeakSet {}"); } @@ -603,7 +603,7 @@ test({ test({ name: "prints deeply nested objects", - fn() { + fn(): void { const val = { prop: { prop: { prop: "value" } } }; assertEquals( format(val), @@ -614,7 +614,7 @@ test({ test({ name: "prints circular references", - fn() { + fn(): void { // eslint-disable-next-line @typescript-eslint/no-explicit-any const val: any = {}; val.prop = val; @@ -624,7 +624,7 @@ test({ test({ name: "prints parallel references", - fn() { + fn(): void { const inner = {}; const val = { prop1: inner, prop2: inner }; assertEquals( @@ -636,14 +636,14 @@ test({ test({ name: "default implicit: 2 spaces", - fn() { + fn(): void { assertEquals(format(createVal()), createExpected()); } }); test({ name: "default explicit: 2 spaces", - fn() { + fn(): void { assertEquals(format(createVal(), { indent: 2 }), createExpected()); } }); @@ -651,7 +651,7 @@ test({ // Tests assume that no strings in val contain multiple adjacent spaces! test({ name: "non-default: 0 spaces", - fn() { + fn(): void { const indent = 0; assertEquals( format(createVal(), { indent }), @@ -662,7 +662,7 @@ test({ test({ name: "non-default: 4 spaces", - fn() { + fn(): void { const indent = 4; assertEquals( format(createVal(), { indent }), @@ -673,7 +673,7 @@ test({ test({ name: "can customize the max depth", - fn() { + fn(): void { const v = [ { "arguments empty": returnArguments(), @@ -719,14 +719,14 @@ test({ test({ name: "prints objects with no constructor", - fn() { + fn(): void { assertEquals(format(Object.create(null)), "Object {}"); } }); test({ name: "prints identity-obj-proxy with string constructor", - fn() { + fn(): void { const obj = Object.create(null); obj.constructor = "constructor"; const expected = [ @@ -740,10 +740,10 @@ test({ test({ name: "calls toJSON and prints its return value", - fn() { + fn(): void { assertEquals( format({ - toJSON: () => ({ value: false }), + toJSON: (): unknown => ({ value: false }), value: true }), 'Object {\n "value": false,\n}' @@ -753,10 +753,10 @@ test({ test({ name: "calls toJSON and prints an internal representation.", - fn() { + fn(): void { assertEquals( format({ - toJSON: () => "[Internal Object]", + toJSON: (): string => "[Internal Object]", value: true }), '"[Internal Object]"' @@ -766,7 +766,7 @@ test({ test({ name: "calls toJSON only on functions", - fn() { + fn(): void { assertEquals( format({ toJSON: false, @@ -779,10 +779,10 @@ test({ test({ name: "does not call toJSON recursively", - fn() { + fn(): void { assertEquals( format({ - toJSON: () => ({ toJSON: () => ({ value: true }) }), + toJSON: (): unknown => ({ toJSON: (): unknown => ({ value: true }) }), value: false }), 'Object {\n "toJSON": [Function toJSON],\n}' @@ -792,10 +792,10 @@ test({ test({ name: "calls toJSON on Sets", - fn() { + fn(): void { const set = new Set([1]); // eslint-disable-next-line @typescript-eslint/no-explicit-any - (set as any).toJSON = () => "map"; + (set as any).toJSON = (): string => "map"; assertEquals(format(set), '"map"'); } }); diff --git a/testing/mod.ts b/testing/mod.ts index 71f27db20c..fab8145e82 100644 --- a/testing/mod.ts +++ b/testing/mod.ts @@ -212,7 +212,7 @@ export async function runTests({ skip = /^\s*$/ }: RunOptions = {}): Promise { const tests: TestDefinition[] = candidates.filter( - ({ name }) => only.test(name) && !skip.test(name) + ({ name }): boolean => only.test(name) && !skip.test(name) ); const stats: TestStats = { measured: 0, @@ -232,7 +232,7 @@ export async function runTests({ if (stats.failed) { // Use setTimeout to avoid the error being ignored due to unhandled // promise rejections being swallowed. - setTimeout(() => { + setTimeout((): void => { console.error(`There were ${stats.failed} test failures.`); Deno.exit(1); }, 0); diff --git a/testing/pretty.ts b/testing/pretty.ts index f4794f889e..b2ab79d702 100644 --- a/testing/pretty.ts +++ b/testing/pretty.ts @@ -18,9 +18,9 @@ function createStr(v: unknown): string { function createColor(diffType: DiffType): (s: string) => string { switch (diffType) { case DiffType.added: - return (s: string) => green(bold(s)); + return (s: string): string => green(bold(s)); case DiffType.removed: - return (s: string) => red(bold(s)); + return (s: string): string => red(bold(s)); default: return white; } @@ -46,10 +46,12 @@ function buildMessage(diffResult: ReadonlyArray>): string[] { ); messages.push(""); messages.push(""); - diffResult.forEach((result: DiffResult) => { - const c = createColor(result.type); - messages.push(c(`${createSign(result.type)}${result.value}`)); - }); + diffResult.forEach( + (result: DiffResult): void => { + const c = createColor(result.type); + messages.push(c(`${createSign(result.type)}${result.value}`)); + } + ); messages.push(""); return messages; diff --git a/testing/pretty_test.ts b/testing/pretty_test.ts index d0e90f6568..07ab83d5ee 100644 --- a/testing/pretty_test.ts +++ b/testing/pretty_test.ts @@ -18,7 +18,7 @@ const removed: (s: string) => string = (s: string): string => red(bold(s)); test({ name: "pass case", - fn() { + fn(): void { assertEquals({ a: 10 }, { a: 10 }); assertEquals(true, true); assertEquals(10, 10); @@ -29,9 +29,9 @@ test({ test({ name: "failed with number", - fn() { + fn(): void { assertThrows( - () => assertEquals(1, 2), + (): void => assertEquals(1, 2), Error, [...createHeader(), removed(`- 1`), added(`+ 2`), ""].join("\n") ); @@ -40,9 +40,9 @@ test({ test({ name: "failed with number vs string", - fn() { + fn(): void { assertThrows( - () => assertEquals(1, "1"), + (): void => assertEquals(1, "1"), Error, [...createHeader(), removed(`- 1`), added(`+ "1"`)].join("\n") ); @@ -51,9 +51,9 @@ test({ test({ name: "failed with array", - fn() { + fn(): void { assertThrows( - () => assertEquals([1, "2", 3], ["1", "2", 3]), + (): void => assertEquals([1, "2", 3], ["1", "2", 3]), Error, [ ...createHeader(), @@ -71,9 +71,9 @@ test({ test({ name: "failed with object", - fn() { + fn(): void { 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, [ ...createHeader(), diff --git a/testing/test.ts b/testing/test.ts index 2359cba2ea..8c06442725 100644 --- a/testing/test.ts +++ b/testing/test.ts @@ -13,7 +13,7 @@ import "./pretty_test.ts"; import "./asserts_test.ts"; import "./bench_test.ts"; -test(function testingAssertEqualActualUncoercable() { +test(function testingAssertEqualActualUncoercable(): void { let didThrow = false; const a = Object.create(null); try { @@ -24,7 +24,7 @@ test(function testingAssertEqualActualUncoercable() { assert(didThrow); }); -test(function testingAssertEqualExpectedUncoercable() { +test(function testingAssertEqualExpectedUncoercable(): void { let didThrow = false; const a = Object.create(null); try { @@ -35,13 +35,13 @@ test(function testingAssertEqualExpectedUncoercable() { assert(didThrow); }); -test(function testingAssertStrictEqual() { +test(function testingAssertStrictEqual(): void { const a = {}; const b = a; assertStrictEq(a, b); }); -test(function testingAssertNotStrictEqual() { +test(function testingAssertNotStrictEqual(): void { let didThrow = false; const a = {}; const b = {}; @@ -54,23 +54,27 @@ test(function testingAssertNotStrictEqual() { assert(didThrow); }); -test(function testingDoesThrow() { +test(function testingDoesThrow(): void { let count = 0; - assertThrows(() => { - count++; - throw new Error(); - }); + assertThrows( + (): void => { + count++; + throw new Error(); + } + ); assert(count === 1); }); -test(function testingDoesNotThrow() { +test(function testingDoesNotThrow(): void { let count = 0; let didThrow = false; try { - assertThrows(() => { - count++; - console.log("Hello world"); - }); + assertThrows( + (): void => { + count++; + console.log("Hello world"); + } + ); } catch (e) { assert(e.message === "Expected function to throw."); didThrow = true; @@ -79,20 +83,20 @@ test(function testingDoesNotThrow() { assert(didThrow); }); -test(function testingThrowsErrorType() { +test(function testingThrowsErrorType(): void { let count = 0; - assertThrows(() => { + assertThrows((): void => { count++; throw new TypeError(); }, TypeError); assert(count === 1); }); -test(function testingThrowsNotErrorType() { +test(function testingThrowsNotErrorType(): void { let count = 0; let didThrow = false; try { - assertThrows(() => { + assertThrows((): void => { count++; throw new TypeError(); }, RangeError); @@ -104,10 +108,10 @@ test(function testingThrowsNotErrorType() { assert(didThrow); }); -test(function testingThrowsMsgIncludes() { +test(function testingThrowsMsgIncludes(): void { let count = 0; assertThrows( - () => { + (): void => { count++; throw new TypeError("Hello world!"); }, @@ -117,12 +121,12 @@ test(function testingThrowsMsgIncludes() { assert(count === 1); }); -test(function testingThrowsMsgNotIncludes() { +test(function testingThrowsMsgNotIncludes(): void { let count = 0; let didThrow = false; try { assertThrows( - () => { + (): void => { count++; throw new TypeError("Hello world!"); }, @@ -140,32 +144,38 @@ test(function testingThrowsMsgNotIncludes() { assert(didThrow); }); -test(async function testingDoesThrowAsync() { +test(async function testingDoesThrowAsync(): Promise { let count = 0; - await assertThrowsAsync(async () => { - count++; - throw new Error(); - }); + await assertThrowsAsync( + async (): Promise => { + count++; + throw new Error(); + } + ); assert(count === 1); }); -test(async function testingDoesReject() { +test(async function testingDoesReject(): Promise { let count = 0; - await assertThrowsAsync(() => { - count++; - return Promise.reject(new Error()); - }); + await assertThrowsAsync( + (): Promise => { + count++; + return Promise.reject(new Error()); + } + ); assert(count === 1); }); -test(async function testingDoesNotThrowAsync() { +test(async function testingDoesNotThrowAsync(): Promise { let count = 0; let didThrow = false; try { - await assertThrowsAsync(async () => { - count++; - console.log("Hello world"); - }); + await assertThrowsAsync( + async (): Promise => { + count++; + console.log("Hello world"); + } + ); } catch (e) { assert(e.message === "Expected function to throw."); didThrow = true; @@ -174,15 +184,17 @@ test(async function testingDoesNotThrowAsync() { assert(didThrow); }); -test(async function testingDoesNotRejectAsync() { +test(async function testingDoesNotRejectAsync(): Promise { let count = 0; let didThrow = false; try { - await assertThrowsAsync(() => { - count++; - console.log("Hello world"); - return Promise.resolve(); - }); + await assertThrowsAsync( + (): Promise => { + count++; + console.log("Hello world"); + return Promise.resolve(); + } + ); } catch (e) { assert(e.message === "Expected function to throw."); didThrow = true; @@ -191,20 +203,20 @@ test(async function testingDoesNotRejectAsync() { assert(didThrow); }); -test(async function testingThrowsAsyncErrorType() { +test(async function testingThrowsAsyncErrorType(): Promise { let count = 0; - await assertThrowsAsync(async () => { + await assertThrowsAsync((): Promise => { count++; throw new TypeError(); }, TypeError); assert(count === 1); }); -test(async function testingThrowsAsyncNotErrorType() { +test(async function testingThrowsAsyncNotErrorType(): Promise { let count = 0; let didThrow = false; try { - await assertThrowsAsync(async () => { + await assertThrowsAsync(async (): Promise => { count++; throw new TypeError(); }, RangeError); @@ -216,10 +228,10 @@ test(async function testingThrowsAsyncNotErrorType() { assert(didThrow); }); -test(async function testingThrowsAsyncMsgIncludes() { +test(async function testingThrowsAsyncMsgIncludes(): Promise { let count = 0; await assertThrowsAsync( - async () => { + async (): Promise => { count++; throw new TypeError("Hello world!"); }, @@ -229,12 +241,12 @@ test(async function testingThrowsAsyncMsgIncludes() { assert(count === 1); }); -test(async function testingThrowsAsyncMsgNotIncludes() { +test(async function testingThrowsAsyncMsgNotIncludes(): Promise { let count = 0; let didThrow = false; try { await assertThrowsAsync( - async () => { + async (): Promise => { count++; throw new TypeError("Hello world!"); }, diff --git a/testing/testing_bench.ts b/testing/testing_bench.ts index 0cc2f233b0..9033e3a72f 100644 --- a/testing/testing_bench.ts +++ b/testing/testing_bench.ts @@ -3,13 +3,13 @@ import { runTests } from "./mod.ts"; import "./asserts_test.ts"; -bench(async function testingSerial(b) { +bench(async function testingSerial(b): Promise { b.start(); await runTests(); b.stop(); }); -bench(async function testingParallel(b) { +bench(async function testingParallel(b): Promise { b.start(); await runTests({ parallel: true }); b.stop(); diff --git a/textproto/test.ts b/textproto/test.ts index 5d1b64b11e..5218d20f46 100644 --- a/textproto/test.ts +++ b/textproto/test.ts @@ -13,7 +13,7 @@ function reader(s: string): TextProtoReader { return new TextProtoReader(new BufReader(stringsReader(s))); } -test(async function textprotoReader() { +test(async function textprotoReader(): Promise { let r = reader("line1\nline2\n"); let [s, err] = await r.readLine(); assertEquals(s, "line1"); @@ -44,7 +44,7 @@ test(async function textprotoReadMIMEHeader() { }); */ -test(async function textprotoReadMIMEHeaderSingle() { +test(async function textprotoReadMIMEHeaderSingle(): Promise { let r = reader("Foo: bar\n\n"); let [m, err] = await r.readMIMEHeader(); 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, // with spaces before colons, and spaces in keys. -test(async function textprotoReadMIMEHeaderNonCompliant() { +test(async function textprotoReadMIMEHeaderNonCompliant(): Promise { // Invalid HTTP response header as sent by an Axis security // camera: (this is handled by IE, Firefox, Chrome, curl, etc.) let r = reader( @@ -82,7 +82,7 @@ test(async function textprotoReadMIMEHeaderNonCompliant() { */ }); -test(async function textprotoAppend() { +test(async function textprotoAppend(): Promise { const enc = new TextEncoder(); const dec = new TextDecoder(); const u1 = enc.encode("Hello "); @@ -91,7 +91,7 @@ test(async function textprotoAppend() { assertEquals(dec.decode(joined), "Hello World"); }); -test(async function textprotoReadEmpty() { +test(async function textprotoReadEmpty(): Promise { let r = reader(""); let [, err] = await r.readMIMEHeader(); // Should not crash! diff --git a/toml/parser.ts b/toml/parser.ts index c29f5a761c..c615c3c1e8 100644 --- a/toml/parser.ts +++ b/toml/parser.ts @@ -399,12 +399,12 @@ class Dumper { const out = []; const props = Object.keys(obj); const propObj = props.filter( - e => + (e): boolean => (obj[e] instanceof Array && !this._isSimplySerializable(obj[e][0])) || !this._isSimplySerializable(obj[e]) ); const propPrim = props.filter( - e => + (e): boolean => !(obj[e] instanceof Array && !this._isSimplySerializable(obj[e][0])) && this._isSimplySerializable(obj[e]) ); diff --git a/toml/parser_test.ts b/toml/parser_test.ts index 6cafb4b0d2..03c7337141 100644 --- a/toml/parser_test.ts +++ b/toml/parser_test.ts @@ -7,7 +7,7 @@ const testFilesDir = path.resolve("toml", "testdata"); test({ name: "[TOML] Strings", - fn() { + fn(): void { const expected = { strings: { str0: "deno", @@ -28,7 +28,7 @@ test({ test({ name: "[TOML] CRLF", - fn() { + fn(): void { const expected = { boolean: { bool1: true, bool2: false } }; const actual = parseFile(path.join(testFilesDir, "CRLF.toml")); assertEquals(actual, expected); @@ -37,7 +37,7 @@ test({ test({ name: "[TOML] Boolean", - fn() { + fn(): void { const expected = { boolean: { bool1: true, bool2: false } }; const actual = parseFile(path.join(testFilesDir, "boolean.toml")); assertEquals(actual, expected); @@ -46,7 +46,7 @@ test({ test({ name: "[TOML] Integer", - fn() { + fn(): void { const expected = { integer: { int1: 99, @@ -71,7 +71,7 @@ test({ test({ name: "[TOML] Float", - fn() { + fn(): void { const expected = { float: { flt1: 1.0, @@ -97,7 +97,7 @@ test({ test({ name: "[TOML] Arrays", - fn() { + fn(): void { const expected = { arrays: { data: [["gamma", "delta"], [1, 2]], @@ -111,7 +111,7 @@ test({ test({ name: "[TOML] Table", - fn() { + fn(): void { const expected = { deeply: { nested: { @@ -144,7 +144,7 @@ test({ test({ name: "[TOML] Simple", - fn() { + fn(): void { const expected = { deno: "is", not: "[node]", @@ -159,7 +159,7 @@ test({ test({ name: "[TOML] Datetime", - fn() { + fn(): void { const expected = { datetime: { odt1: new Date("1979-05-27T07:32:00Z"), @@ -178,7 +178,7 @@ test({ test({ name: "[TOML] Inline Table", - fn() { + fn(): void { const expected = { inlinetable: { nile: { @@ -223,7 +223,7 @@ test({ test({ name: "[TOML] Array of Tables", - fn() { + fn(): void { const expected = { bin: [ { name: "deno", path: "cli/main.rs" }, @@ -238,7 +238,7 @@ test({ test({ name: "[TOML] Cargo", - fn() { + fn(): void { /* eslint-disable @typescript-eslint/camelcase */ const expected = { workspace: { members: ["./", "core"] }, @@ -285,7 +285,7 @@ test({ test({ name: "[TOML] Stringify", - fn() { + fn(): void { const src = { foo: { bar: "deno" }, this: { is: { nested: "denonono" } }, diff --git a/util/deep_assign.ts b/util/deep_assign.ts index 4857e18b53..77bf5e9b36 100644 --- a/util/deep_assign.ts +++ b/util/deep_assign.ts @@ -5,24 +5,26 @@ export function deepAssign(target: object, ...sources: object[]): object { if (!source || typeof source !== `object`) { return; } - Object.entries(source).forEach(([key, value]) => { - if (value instanceof Date) { - target[key] = new Date(value); - return; + Object.entries(source).forEach( + ([key, value]): void => { + if (value instanceof Date) { + target[key] = new Date(value); + return; + } + if (!value || typeof value !== `object`) { + target[key] = value; + return; + } + if (Array.isArray(value)) { + target[key] = []; + } + // value is an Object + if (typeof target[key] !== `object` || !target[key]) { + target[key] = {}; + } + deepAssign(target[key], value); } - if (!value || typeof value !== `object`) { - target[key] = value; - return; - } - if (Array.isArray(value)) { - target[key] = []; - } - // value is an Object - if (typeof target[key] !== `object` || !target[key]) { - target[key] = {}; - } - deepAssign(target[key], value); - }); + ); } return target; } diff --git a/util/deep_assign_test.ts b/util/deep_assign_test.ts index 36be979d8d..c197344f7a 100644 --- a/util/deep_assign_test.ts +++ b/util/deep_assign_test.ts @@ -3,7 +3,7 @@ import { test } from "../testing/mod.ts"; import { assertEquals, assert } from "../testing/asserts.ts"; import { deepAssign } from "./deep_assign.ts"; -test(function deepAssignTest() { +test(function deepAssignTest(): void { const date = new Date("1979-05-27T07:32:00Z"); const reg = RegExp(/DENOWOWO/); const obj1 = { deno: { bar: { deno: ["is", "not", "node"] } } }; diff --git a/ws/sha1_test.ts b/ws/sha1_test.ts index b9f5aba0e9..8ece1a7e80 100644 --- a/ws/sha1_test.ts +++ b/ws/sha1_test.ts @@ -3,20 +3,20 @@ import { test } from "../testing/mod.ts"; import { assertEquals } from "../testing/asserts.ts"; import { Sha1 } from "./sha1.ts"; -test(function testSha1() { +test(function testSha1(): void { const sha1 = new Sha1(); sha1.update("abcde"); assertEquals(sha1.toString(), "03de6c570bfe24bfc328ccd7ca46b76eadaf4334"); }); -test(function testSha1WithArray() { +test(function testSha1WithArray(): void { const data = Uint8Array.of(0x61, 0x62, 0x63, 0x64, 0x65); const sha1 = new Sha1(); sha1.update(data); assertEquals(sha1.toString(), "03de6c570bfe24bfc328ccd7ca46b76eadaf4334"); }); -test(function testSha1WithBuffer() { +test(function testSha1WithBuffer(): void { const data = Uint8Array.of(0x61, 0x62, 0x63, 0x64, 0x65); const sha1 = new Sha1(); sha1.update(data.buffer); diff --git a/ws/test.ts b/ws/test.ts index bb7549a4d7..5d0cc90934 100644 --- a/ws/test.ts +++ b/ws/test.ts @@ -13,7 +13,7 @@ import { unmask } from "./mod.ts"; -test(async function testReadUnmaskedTextFrame() { +test(async function testReadUnmaskedTextFrame(): Promise { // unmasked single text frame with payload "Hello" const buf = new BufReader( new Buffer(new Uint8Array([0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f])) @@ -25,7 +25,7 @@ test(async function testReadUnmaskedTextFrame() { assertEquals(frame.isLastFrame, true); }); -test(async function testReadMakedTextFrame() { +test(async function testReadMakedTextFrame(): Promise { //a masked single text frame with payload "Hello" const buf = new BufReader( new Buffer( @@ -52,7 +52,7 @@ test(async function testReadMakedTextFrame() { assertEquals(frame.isLastFrame, true); }); -test(async function testReadUnmaskedSplittedTextFrames() { +test(async function testReadUnmaskedSplittedTextFrames(): Promise { const buf1 = new BufReader( new Buffer(new Uint8Array([0x01, 0x03, 0x48, 0x65, 0x6c])) ); @@ -71,7 +71,7 @@ test(async function testReadUnmaskedSplittedTextFrames() { assertEquals(new Buffer(f2.payload).toString(), "lo"); }); -test(async function testReadUnmaksedPingPongFrame() { +test(async function testReadUnmaksedPingPongFrame(): Promise { // unmasked ping with payload "Hello" const buf = new BufReader( 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"); }); -test(async function testReadUnmaksedBigBinaryFrame() { +test(async function testReadUnmaksedBigBinaryFrame(): Promise { const a = [0x82, 0x7e, 0x01, 0x00]; for (let i = 0; i < 256; i++) { a.push(i); @@ -117,7 +117,7 @@ test(async function testReadUnmaksedBigBinaryFrame() { assertEquals(bin.payload.length, 256); }); -test(async function testReadUnmaskedBigBigBinaryFrame() { +test(async function testReadUnmaskedBigBigBinaryFrame(): Promise { const a = [0x82, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00]; for (let i = 0; i < 0xffff; i++) { a.push(i); @@ -130,13 +130,13 @@ test(async function testReadUnmaskedBigBigBinaryFrame() { assertEquals(bin.payload.length, 0xffff + 1); }); -test(async function testCreateSecAccept() { +test(async function testCreateSecAccept(): Promise { const nonce = "dGhlIHNhbXBsZSBub25jZQ=="; const d = createSecAccept(nonce); assertEquals(d, "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="); }); -test(function testAcceptable() { +test(function testAcceptable(): void { const ret = acceptable({ headers: new Headers({ upgrade: "websocket", @@ -153,7 +153,7 @@ const invalidHeaders = [ { upgrade: "websocket", "sec-websocket-ky": "" } ]; -test(function testAcceptableInvalid() { +test(function testAcceptableInvalid(): void { for (const pat of invalidHeaders) { const ret = acceptable({ headers: new Headers(pat)