0
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-10-30 09:08:00 -04:00
Original: e1d5c00279
This commit is contained in:
Vincent LE GOFF 2019-03-06 22:39:50 +01:00 committed by Ryan Dahl
parent d29957ad17
commit e36edfdb3f
59 changed files with 893 additions and 891 deletions

View file

@ -4,14 +4,15 @@ import {
bytesEqual, bytesEqual,
bytesHasPrefix bytesHasPrefix
} from "./bytes.ts"; } from "./bytes.ts";
import { assertEqual, test } from "./deps.ts"; import { test } from "../testing/mod.ts";
import { assertEq } from "../testing/asserts.ts";
test(function bytesBytesFindIndex() { test(function bytesBytesFindIndex() {
const i = bytesFindIndex( const i = bytesFindIndex(
new Uint8Array([1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 3]), new Uint8Array([1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 3]),
new Uint8Array([0, 1, 2]) new Uint8Array([0, 1, 2])
); );
assertEqual(i, 2); assertEq(i, 2);
}); });
test(function bytesBytesFindLastIndex1() { test(function bytesBytesFindLastIndex1() {
@ -19,7 +20,7 @@ test(function bytesBytesFindLastIndex1() {
new Uint8Array([0, 1, 2, 0, 1, 2, 0, 1, 3]), new Uint8Array([0, 1, 2, 0, 1, 2, 0, 1, 3]),
new Uint8Array([0, 1, 2]) new Uint8Array([0, 1, 2])
); );
assertEqual(i, 3); assertEq(i, 3);
}); });
test(function bytesBytesBytesEqual() { test(function bytesBytesBytesEqual() {
@ -27,10 +28,10 @@ test(function bytesBytesBytesEqual() {
new Uint8Array([0, 1, 2, 3]), new Uint8Array([0, 1, 2, 3]),
new Uint8Array([0, 1, 2, 3]) new Uint8Array([0, 1, 2, 3])
); );
assertEqual(v, true); assertEq(v, true);
}); });
test(function bytesBytesHasPrefix() { test(function bytesBytesHasPrefix() {
const v = bytesHasPrefix(new Uint8Array([0, 1, 2]), new Uint8Array([0, 1])); const v = bytesHasPrefix(new Uint8Array([0, 1, 2]), new Uint8Array([0, 1]));
assertEqual(v, true); assertEq(v, true);
}); });

View file

@ -1,24 +1,25 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { assert, test } from "../testing/mod.ts"; import { test } from "../testing/mod.ts";
import { assertEq } from "../testing/asserts.ts";
import { red, bgBlue, setEnabled, getEnabled } from "./mod.ts"; import { red, bgBlue, setEnabled, getEnabled } from "./mod.ts";
import "./example.ts"; import "./example.ts";
test(function singleColor() { test(function singleColor() {
assert.equal(red("Hello world"), "Hello world"); assertEq(red("Hello world"), "Hello world");
}); });
test(function doubleColor() { test(function doubleColor() {
assert.equal(bgBlue(red("Hello world")), "Hello world"); assertEq(bgBlue(red("Hello world")), "Hello world");
}); });
test(function replacesCloseCharacters() { test(function replacesCloseCharacters() {
assert.equal(red("Hello"), "Hello"); assertEq(red("Hello"), "Hello");
}); });
test(function enablingColors() { test(function enablingColors() {
assert.equal(getEnabled(), true); assertEq(getEnabled(), true);
setEnabled(false); setEnabled(false);
assert.equal(bgBlue(red("Hello world")), "Hello world"); assertEq(bgBlue(red("Hello world")), "Hello world");
setEnabled(true); setEnabled(true);
assert.equal(red("Hello world"), "Hello world"); assertEq(red("Hello world"), "Hello world");
}); });

View file

@ -1,29 +1,30 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { test, assertEqual, assert } from "../testing/mod.ts"; import { test } from "../testing/mod.ts";
import { assert, assertEq } from "../testing/asserts.ts";
import * as datetime from "./mod.ts"; import * as datetime from "./mod.ts";
test(function parseDateTime() { test(function parseDateTime() {
assertEqual( assertEq(
datetime.parseDateTime("01-03-2019 16:34", "mm-dd-yyyy hh:mm"), datetime.parseDateTime("01-03-2019 16:34", "mm-dd-yyyy hh:mm"),
new Date(2019, 1, 3, 16, 34) new Date(2019, 1, 3, 16, 34)
); );
assertEqual( assertEq(
datetime.parseDateTime("03-01-2019 16:34", "dd-mm-yyyy hh:mm"), datetime.parseDateTime("03-01-2019 16:34", "dd-mm-yyyy hh:mm"),
new Date(2019, 1, 3, 16, 34) new Date(2019, 1, 3, 16, 34)
); );
assertEqual( assertEq(
datetime.parseDateTime("2019-01-03 16:34", "yyyy-mm-dd hh:mm"), datetime.parseDateTime("2019-01-03 16:34", "yyyy-mm-dd hh:mm"),
new Date(2019, 1, 3, 16, 34) new Date(2019, 1, 3, 16, 34)
); );
assertEqual( assertEq(
datetime.parseDateTime("16:34 01-03-2019", "hh:mm mm-dd-yyyy"), datetime.parseDateTime("16:34 01-03-2019", "hh:mm mm-dd-yyyy"),
new Date(2019, 1, 3, 16, 34) new Date(2019, 1, 3, 16, 34)
); );
assertEqual( assertEq(
datetime.parseDateTime("16:34 03-01-2019", "hh:mm dd-mm-yyyy"), datetime.parseDateTime("16:34 03-01-2019", "hh:mm dd-mm-yyyy"),
new Date(2019, 1, 3, 16, 34) new Date(2019, 1, 3, 16, 34)
); );
assertEqual( assertEq(
datetime.parseDateTime("16:34 2019-01-03", "hh:mm yyyy-mm-dd"), datetime.parseDateTime("16:34 2019-01-03", "hh:mm yyyy-mm-dd"),
new Date(2019, 1, 3, 16, 34) new Date(2019, 1, 3, 16, 34)
); );
@ -35,20 +36,20 @@ test(function invalidParseDateTimeFormatThrows() {
(datetime as any).parseDateTime("2019-01-01 00:00", "x-y-z"); (datetime as any).parseDateTime("2019-01-01 00:00", "x-y-z");
assert(false, "no exception was thrown"); assert(false, "no exception was thrown");
} catch (e) { } catch (e) {
assertEqual(e.message, "Invalid datetime format!"); assertEq(e.message, "Invalid datetime format!");
} }
}); });
test(function parseDate() { test(function parseDate() {
assertEqual( assertEq(
datetime.parseDate("01-03-2019", "mm-dd-yyyy"), datetime.parseDate("01-03-2019", "mm-dd-yyyy"),
new Date(2019, 1, 3) new Date(2019, 1, 3)
); );
assertEqual( assertEq(
datetime.parseDate("03-01-2019", "dd-mm-yyyy"), datetime.parseDate("03-01-2019", "dd-mm-yyyy"),
new Date(2019, 1, 3) new Date(2019, 1, 3)
); );
assertEqual( assertEq(
datetime.parseDate("2019-01-03", "yyyy-mm-dd"), datetime.parseDate("2019-01-03", "yyyy-mm-dd"),
new Date(2019, 1, 3) new Date(2019, 1, 3)
); );
@ -60,12 +61,12 @@ test(function invalidParseDateFormatThrows() {
(datetime as any).parseDate("2019-01-01", "x-y-z"); (datetime as any).parseDate("2019-01-01", "x-y-z");
assert(false, "no exception was thrown"); assert(false, "no exception was thrown");
} catch (e) { } catch (e) {
assertEqual(e.message, "Invalid date format!"); assertEq(e.message, "Invalid date format!");
} }
}); });
test(function currentDayOfYear() { test(function currentDayOfYear() {
assertEqual( assertEq(
datetime.currentDayOfYear(), datetime.currentDayOfYear(),
Math.ceil(new Date().getTime() / 86400000) - Math.ceil(new Date().getTime() / 86400000) -
Math.floor( Math.floor(

View file

@ -1,14 +1,15 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
const { run } = Deno; const { run } = Deno;
import { test, assertEqual } from "../testing/mod.ts"; import { test } from "../testing/mod.ts";
import { assertEq } from "../testing/asserts.ts";
/** Example of how to do basic tests */ /** Example of how to do basic tests */
test(function t1() { test(function t1() {
assertEqual("hello", "hello"); assertEq("hello", "hello");
}); });
test(function t2() { test(function t2() {
assertEqual("world", "world"); assertEq("world", "world");
}); });
/** A more complicated test that runs a subprocess. */ /** A more complicated test that runs a subprocess. */
@ -18,5 +19,5 @@ test(async function catSmoke() {
stdout: "piped" stdout: "piped"
}); });
const s = await p.status(); const s = await p.status();
assertEqual(s.code, 0); assertEq(s.code, 0);
}); });

View file

@ -1,5 +1,6 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { test, assertEqual } from "../../testing/mod.ts"; import { test } from "../../testing/mod.ts";
import { assertEq } from "../../testing/asserts.ts";
import { parse } from "../mod.ts"; import { parse } from "../mod.ts";
// flag boolean true (default all --args to boolean) // flag boolean true (default all --args to boolean)
@ -8,12 +9,12 @@ test(function flagBooleanTrue() {
boolean: true boolean: true
}); });
assertEqual(argv, { assertEq(argv, {
honk: true, honk: true,
_: ["moo", "cow"] _: ["moo", "cow"]
}); });
assertEqual(typeof argv.honk, "boolean"); assertEq(typeof argv.honk, "boolean");
}); });
// flag boolean true only affects double hyphen arguments without equals signs // flag boolean true only affects double hyphen arguments without equals signs
@ -22,12 +23,12 @@ test(function flagBooleanTrueOnlyAffectsDoubleDash() {
boolean: true boolean: true
}); });
assertEqual(argv, { assertEq(argv, {
honk: true, honk: true,
tacos: "good", tacos: "good",
p: 55, p: 55,
_: ["moo", "cow"] _: ["moo", "cow"]
}); });
assertEqual(typeof argv.honk, "boolean"); assertEq(typeof argv.honk, "boolean");
}); });

View file

@ -1,5 +1,6 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { test, assertEqual } from "../../testing/mod.ts"; import { test } from "../../testing/mod.ts";
import { assertEq } from "../../testing/asserts.ts";
import { parse } from "../mod.ts"; import { parse } from "../mod.ts";
test(function flagBooleanDefaultFalse() { test(function flagBooleanDefaultFalse() {
@ -8,14 +9,14 @@ test(function flagBooleanDefaultFalse() {
default: { verbose: false, t: false } default: { verbose: false, t: false }
}); });
assertEqual(argv, { assertEq(argv, {
verbose: false, verbose: false,
t: false, t: false,
_: ["moo"] _: ["moo"]
}); });
assertEqual(typeof argv.verbose, "boolean"); assertEq(typeof argv.verbose, "boolean");
assertEqual(typeof argv.t, "boolean"); assertEq(typeof argv.t, "boolean");
}); });
test(function booleanGroups() { test(function booleanGroups() {
@ -23,16 +24,16 @@ test(function booleanGroups() {
boolean: ["x", "y", "z"] boolean: ["x", "y", "z"]
}); });
assertEqual(argv, { assertEq(argv, {
x: true, x: true,
y: false, y: false,
z: true, z: true,
_: ["one", "two", "three"] _: ["one", "two", "three"]
}); });
assertEqual(typeof argv.x, "boolean"); assertEq(typeof argv.x, "boolean");
assertEqual(typeof argv.y, "boolean"); assertEq(typeof argv.y, "boolean");
assertEqual(typeof argv.z, "boolean"); assertEq(typeof argv.z, "boolean");
}); });
test(function booleanAndAliasWithChainableApi() { test(function booleanAndAliasWithChainableApi() {
@ -55,8 +56,8 @@ test(function booleanAndAliasWithChainableApi() {
_: ["derp"] _: ["derp"]
}; };
assertEqual(aliasedArgv, expected); assertEq(aliasedArgv, expected);
assertEqual(propertyArgv, expected); assertEq(propertyArgv, expected);
}); });
test(function booleanAndAliasWithOptionsHash() { test(function booleanAndAliasWithOptionsHash() {
@ -73,8 +74,8 @@ test(function booleanAndAliasWithOptionsHash() {
h: true, h: true,
_: ["derp"] _: ["derp"]
}; };
assertEqual(aliasedArgv, expected); assertEq(aliasedArgv, expected);
assertEqual(propertyArgv, expected); assertEq(propertyArgv, expected);
}); });
test(function booleanAndAliasArrayWithOptionsHash() { test(function booleanAndAliasArrayWithOptionsHash() {
@ -94,9 +95,9 @@ test(function booleanAndAliasArrayWithOptionsHash() {
h: true, h: true,
_: ["derp"] _: ["derp"]
}; };
assertEqual(aliasedArgv, expected); assertEq(aliasedArgv, expected);
assertEqual(propertyArgv, expected); assertEq(propertyArgv, expected);
assertEqual(altPropertyArgv, expected); assertEq(altPropertyArgv, expected);
}); });
test(function booleanAndAliasUsingExplicitTrue() { test(function booleanAndAliasUsingExplicitTrue() {
@ -114,8 +115,8 @@ test(function booleanAndAliasUsingExplicitTrue() {
_: [] _: []
}; };
assertEqual(aliasedArgv, expected); assertEq(aliasedArgv, expected);
assertEqual(propertyArgv, expected); assertEq(propertyArgv, expected);
}); });
// regression, see https://github.com/substack/node-optimist/issues/71 // regression, see https://github.com/substack/node-optimist/issues/71
@ -125,15 +126,15 @@ test(function booleanAndNonBoolean() {
boolean: "boool" boolean: "boool"
}); });
assertEqual(parsed.boool, true); assertEq(parsed.boool, true);
assertEqual(parsed.other, "true"); assertEq(parsed.other, "true");
const parsed2 = parse(["--boool", "--other=false"], { const parsed2 = parse(["--boool", "--other=false"], {
boolean: "boool" boolean: "boool"
}); });
assertEqual(parsed2.boool, true); assertEq(parsed2.boool, true);
assertEqual(parsed2.other, "false"); assertEq(parsed2.other, "false");
}); });
test(function booleanParsingTrue() { test(function booleanParsingTrue() {
@ -144,7 +145,7 @@ test(function booleanParsingTrue() {
boolean: ["boool"] boolean: ["boool"]
}); });
assertEqual(parsed.boool, true); assertEq(parsed.boool, true);
}); });
test(function booleanParsingFalse() { test(function booleanParsingFalse() {
@ -155,5 +156,5 @@ test(function booleanParsingFalse() {
boolean: ["boool"] boolean: ["boool"]
}); });
assertEqual(parsed.boool, false); assertEq(parsed.boool, false);
}); });

View file

@ -1,24 +1,26 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { test, assertEqual } from "../../testing/mod.ts"; import { test } from "../../testing/mod.ts";
import { assertEq } from "../../testing/asserts.ts";
import { parse } from "../mod.ts"; import { parse } from "../mod.ts";
test(function hyphen() { test(function hyphen() {
assertEqual(parse(["-n", "-"]), { n: "-", _: [] }); assertEq(parse(["-n", "-"]), { n: "-", _: [] });
assertEqual(parse(["-"]), { _: ["-"] }); assertEq(parse(["-"]), { _: ["-"] });
assertEqual(parse(["-f-"]), { f: "-", _: [] }); assertEq(parse(["-f-"]), { f: "-", _: [] });
assertEqual(parse(["-b", "-"], { boolean: "b" }), { b: true, _: ["-"] }); assertEq(parse(["-b", "-"], { boolean: "b" }), { b: true, _: ["-"] });
assertEqual(parse(["-s", "-"], { string: "s" }), { s: "-", _: [] }); assertEq(parse(["-s", "-"], { string: "s" }), { s: "-", _: [] });
}); });
test(function doubleDash() { test(function doubleDash() {
assertEqual(parse(["-a", "--", "b"]), { a: true, _: ["b"] }); assertEq(parse(["-a", "--", "b"]), { a: true, _: ["b"] });
assertEqual(parse(["--a", "--", "b"]), { a: true, _: ["b"] }); assertEq(parse(["--a", "--", "b"]), { a: true, _: ["b"] });
assertEqual(parse(["--a", "--", "b"]), { a: true, _: ["b"] }); assertEq(parse(["--a", "--", "b"]), { a: true, _: ["b"] });
}); });
test(function moveArgsAfterDoubleDashIntoOwnArray() { test(function moveArgsAfterDoubleDashIntoOwnArray() {
assertEqual( assertEq(parse(["--name", "John", "before", "--", "after"], { "--": true }), {
parse(["--name", "John", "before", "--", "after"], { "--": true }), name: "John",
{ name: "John", _: ["before"], "--": ["after"] } _: ["before"],
); "--": ["after"]
});
}); });

View file

@ -1,5 +1,6 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { test, assertEqual } from "../../testing/mod.ts"; import { test } from "../../testing/mod.ts";
import { assertEq } from "../../testing/asserts.ts";
import { parse } from "../mod.ts"; import { parse } from "../mod.ts";
test(function booleanDefaultTrue() { test(function booleanDefaultTrue() {
@ -7,7 +8,7 @@ test(function booleanDefaultTrue() {
boolean: "sometrue", boolean: "sometrue",
default: { sometrue: true } default: { sometrue: true }
}); });
assertEqual(argv.sometrue, true); assertEq(argv.sometrue, true);
}); });
test(function booleanDefaultFalse() { test(function booleanDefaultFalse() {
@ -15,7 +16,7 @@ test(function booleanDefaultFalse() {
boolean: "somefalse", boolean: "somefalse",
default: { somefalse: false } default: { somefalse: false }
}); });
assertEqual(argv.somefalse, false); assertEq(argv.somefalse, false);
}); });
test(function booleanDefaultNull() { test(function booleanDefaultNull() {
@ -23,10 +24,10 @@ test(function booleanDefaultNull() {
boolean: "maybe", boolean: "maybe",
default: { maybe: null } default: { maybe: null }
}); });
assertEqual(argv.maybe, null); assertEq(argv.maybe, null);
const argv2 = parse(["--maybe"], { const argv2 = parse(["--maybe"], {
boolean: "maybe", boolean: "maybe",
default: { maybe: null } default: { maybe: null }
}); });
assertEqual(argv2.maybe, true); assertEq(argv2.maybe, true);
}); });

View file

@ -1,5 +1,6 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { test, assertEqual } from "../../testing/mod.ts"; import { test } from "../../testing/mod.ts";
import { assertEq } from "../../testing/asserts.ts";
import { parse } from "../mod.ts"; import { parse } from "../mod.ts";
test(function dottedAlias() { test(function dottedAlias() {
@ -7,17 +8,17 @@ test(function dottedAlias() {
default: { "a.b": 11 }, default: { "a.b": 11 },
alias: { "a.b": "aa.bb" } alias: { "a.b": "aa.bb" }
}); });
assertEqual(argv.a.b, 22); assertEq(argv.a.b, 22);
assertEqual(argv.aa.bb, 22); assertEq(argv.aa.bb, 22);
}); });
test(function dottedDefault() { test(function dottedDefault() {
const argv = parse("", { default: { "a.b": 11 }, alias: { "a.b": "aa.bb" } }); const argv = parse("", { default: { "a.b": 11 }, alias: { "a.b": "aa.bb" } });
assertEqual(argv.a.b, 11); assertEq(argv.a.b, 11);
assertEqual(argv.aa.bb, 11); assertEq(argv.aa.bb, 11);
}); });
test(function dottedDefaultWithNoAlias() { test(function dottedDefaultWithNoAlias() {
const argv = parse("", { default: { "a.b": 11 } }); const argv = parse("", { default: { "a.b": 11 } });
assertEqual(argv.a.b, 11); assertEq(argv.a.b, 11);
}); });

View file

@ -1,13 +1,14 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { test, assertEqual } from "../../testing/mod.ts"; import { test } from "../../testing/mod.ts";
import { assertEq } from "../../testing/asserts.ts";
import { parse } from "../mod.ts"; import { parse } from "../mod.ts";
test(function short() { test(function short() {
const argv = parse(["-b=123"]); const argv = parse(["-b=123"]);
assertEqual(argv, { b: 123, _: [] }); assertEq(argv, { b: 123, _: [] });
}); });
test(function multiShort() { test(function multiShort() {
const argv = parse(["-a=whatever", "-b=robots"]); const argv = parse(["-a=whatever", "-b=robots"]);
assertEqual(argv, { a: "whatever", b: "robots", _: [] }); assertEq(argv, { a: "whatever", b: "robots", _: [] });
}); });

View file

@ -1,17 +1,18 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { test, assertEqual } from "../../testing/mod.ts"; import { test } from "../../testing/mod.ts";
import { assertEq } from "../../testing/asserts.ts";
import { parse } from "../mod.ts"; import { parse } from "../mod.ts";
test(function longOpts() { test(function longOpts() {
assertEqual(parse(["--bool"]), { bool: true, _: [] }); assertEq(parse(["--bool"]), { bool: true, _: [] });
assertEqual(parse(["--pow", "xixxle"]), { pow: "xixxle", _: [] }); assertEq(parse(["--pow", "xixxle"]), { pow: "xixxle", _: [] });
assertEqual(parse(["--pow=xixxle"]), { pow: "xixxle", _: [] }); assertEq(parse(["--pow=xixxle"]), { pow: "xixxle", _: [] });
assertEqual(parse(["--host", "localhost", "--port", "555"]), { assertEq(parse(["--host", "localhost", "--port", "555"]), {
host: "localhost", host: "localhost",
port: 555, port: 555,
_: [] _: []
}); });
assertEqual(parse(["--host=localhost", "--port=555"]), { assertEq(parse(["--host=localhost", "--port=555"]), {
host: "localhost", host: "localhost",
port: 555, port: 555,
_: [] _: []

View file

@ -1,5 +1,6 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { test, assertEqual } from "../../testing/mod.ts"; import { test } from "../../testing/mod.ts";
import { assertEq } from "../../testing/asserts.ts";
import { parse } from "../mod.ts"; import { parse } from "../mod.ts";
test(function nums() { test(function nums() {
@ -16,7 +17,7 @@ test(function nums() {
"0xdeadbeef", "0xdeadbeef",
"789" "789"
]); ]);
assertEqual(argv, { assertEq(argv, {
x: 1234, x: 1234,
y: 5.67, y: 5.67,
z: 1e7, z: 1e7,
@ -24,17 +25,17 @@ test(function nums() {
hex: 0xdeadbeef, hex: 0xdeadbeef,
_: [789] _: [789]
}); });
assertEqual(typeof argv.x, "number"); assertEq(typeof argv.x, "number");
assertEqual(typeof argv.y, "number"); assertEq(typeof argv.y, "number");
assertEqual(typeof argv.z, "number"); assertEq(typeof argv.z, "number");
assertEqual(typeof argv.w, "string"); assertEq(typeof argv.w, "string");
assertEqual(typeof argv.hex, "number"); assertEq(typeof argv.hex, "number");
assertEqual(typeof argv._[0], "number"); assertEq(typeof argv._[0], "number");
}); });
test(function alreadyNumber() { test(function alreadyNumber() {
const argv = parse(["-x", 1234, 789]); const argv = parse(["-x", 1234, 789]);
assertEqual(argv, { x: 1234, _: [789] }); assertEq(argv, { x: 1234, _: [789] });
assertEqual(typeof argv.x, "number"); assertEq(typeof argv.x, "number");
assertEqual(typeof argv._[0], "number"); assertEq(typeof argv._[0], "number");
}); });

View file

@ -1,17 +1,18 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { test, assertEqual } from "../../testing/mod.ts"; import { test } from "../../testing/mod.ts";
import { assertEq } from "../../testing/asserts.ts";
import { parse } from "../mod.ts"; import { parse } from "../mod.ts";
test(function _arseArgs() { test(function _arseArgs() {
assertEqual(parse(["--no-moo"]), { moo: false, _: [] }); assertEq(parse(["--no-moo"]), { moo: false, _: [] });
assertEqual(parse(["-v", "a", "-v", "b", "-v", "c"]), { assertEq(parse(["-v", "a", "-v", "b", "-v", "c"]), {
v: ["a", "b", "c"], v: ["a", "b", "c"],
_: [] _: []
}); });
}); });
test(function comprehensive() { test(function comprehensive() {
assertEqual( assertEq(
parse([ parse([
"--name=meowmers", "--name=meowmers",
"bare", "bare",
@ -49,8 +50,8 @@ test(function comprehensive() {
test(function flagBoolean() { test(function flagBoolean() {
const argv = parse(["-t", "moo"], { boolean: "t" }); const argv = parse(["-t", "moo"], { boolean: "t" });
assertEqual(argv, { t: true, _: ["moo"] }); assertEq(argv, { t: true, _: ["moo"] });
assertEqual(typeof argv.t, "boolean"); assertEq(typeof argv.t, "boolean");
}); });
test(function flagBooleanValue() { test(function flagBooleanValue() {
@ -59,63 +60,63 @@ test(function flagBooleanValue() {
default: { verbose: true } default: { verbose: true }
}); });
assertEqual(argv, { assertEq(argv, {
verbose: false, verbose: false,
t: true, t: true,
_: ["moo"] _: ["moo"]
}); });
assertEqual(typeof argv.verbose, "boolean"); assertEq(typeof argv.verbose, "boolean");
assertEqual(typeof argv.t, "boolean"); assertEq(typeof argv.t, "boolean");
}); });
test(function newlinesInParams() { test(function newlinesInParams() {
const args = parse(["-s", "X\nX"]); const args = parse(["-s", "X\nX"]);
assertEqual(args, { _: [], s: "X\nX" }); assertEq(args, { _: [], s: "X\nX" });
// reproduce in bash: // reproduce in bash:
// VALUE="new // VALUE="new
// line" // line"
// deno program.js --s="$VALUE" // deno program.js --s="$VALUE"
const args2 = parse(["--s=X\nX"]); const args2 = parse(["--s=X\nX"]);
assertEqual(args2, { _: [], s: "X\nX" }); assertEq(args2, { _: [], s: "X\nX" });
}); });
test(function strings() { test(function strings() {
const s = parse(["-s", "0001234"], { string: "s" }).s; const s = parse(["-s", "0001234"], { string: "s" }).s;
assertEqual(s, "0001234"); assertEq(s, "0001234");
assertEqual(typeof s, "string"); assertEq(typeof s, "string");
const x = parse(["-x", "56"], { string: "x" }).x; const x = parse(["-x", "56"], { string: "x" }).x;
assertEqual(x, "56"); assertEq(x, "56");
assertEqual(typeof x, "string"); assertEq(typeof x, "string");
}); });
test(function stringArgs() { test(function stringArgs() {
const s = parse([" ", " "], { string: "_" })._; const s = parse([" ", " "], { string: "_" })._;
assertEqual(s.length, 2); assertEq(s.length, 2);
assertEqual(typeof s[0], "string"); assertEq(typeof s[0], "string");
assertEqual(s[0], " "); assertEq(s[0], " ");
assertEqual(typeof s[1], "string"); assertEq(typeof s[1], "string");
assertEqual(s[1], " "); assertEq(s[1], " ");
}); });
test(function emptyStrings() { test(function emptyStrings() {
const s = parse(["-s"], { string: "s" }).s; const s = parse(["-s"], { string: "s" }).s;
assertEqual(s, ""); assertEq(s, "");
assertEqual(typeof s, "string"); assertEq(typeof s, "string");
const str = parse(["--str"], { string: "str" }).str; const str = parse(["--str"], { string: "str" }).str;
assertEqual(str, ""); assertEq(str, "");
assertEqual(typeof str, "string"); assertEq(typeof str, "string");
const letters = parse(["-art"], { const letters = parse(["-art"], {
string: ["a", "t"] string: ["a", "t"]
}); });
assertEqual(letters.a, ""); assertEq(letters.a, "");
assertEqual(letters.r, true); assertEq(letters.r, true);
assertEqual(letters.t, ""); assertEq(letters.t, "");
}); });
test(function stringAndAlias() { test(function stringAndAlias() {
@ -124,25 +125,25 @@ test(function stringAndAlias() {
alias: { s: "str" } alias: { s: "str" }
}); });
assertEqual(x.str, "000123"); assertEq(x.str, "000123");
assertEqual(typeof x.str, "string"); assertEq(typeof x.str, "string");
assertEqual(x.s, "000123"); assertEq(x.s, "000123");
assertEqual(typeof x.s, "string"); assertEq(typeof x.s, "string");
const y = parse(["-s", "000123"], { const y = parse(["-s", "000123"], {
string: "str", string: "str",
alias: { str: "s" } alias: { str: "s" }
}); });
assertEqual(y.str, "000123"); assertEq(y.str, "000123");
assertEqual(typeof y.str, "string"); assertEq(typeof y.str, "string");
assertEqual(y.s, "000123"); assertEq(y.s, "000123");
assertEqual(typeof y.s, "string"); assertEq(typeof y.s, "string");
}); });
test(function slashBreak() { test(function slashBreak() {
assertEqual(parse(["-I/foo/bar/baz"]), { I: "/foo/bar/baz", _: [] }); assertEq(parse(["-I/foo/bar/baz"]), { I: "/foo/bar/baz", _: [] });
assertEqual(parse(["-xyz/foo/bar/baz"]), { assertEq(parse(["-xyz/foo/bar/baz"]), {
x: true, x: true,
y: true, y: true,
z: "/foo/bar/baz", z: "/foo/bar/baz",
@ -154,19 +155,19 @@ test(function alias() {
const argv = parse(["-f", "11", "--zoom", "55"], { const argv = parse(["-f", "11", "--zoom", "55"], {
alias: { z: "zoom" } alias: { z: "zoom" }
}); });
assertEqual(argv.zoom, 55); assertEq(argv.zoom, 55);
assertEqual(argv.z, argv.zoom); assertEq(argv.z, argv.zoom);
assertEqual(argv.f, 11); assertEq(argv.f, 11);
}); });
test(function multiAlias() { test(function multiAlias() {
const argv = parse(["-f", "11", "--zoom", "55"], { const argv = parse(["-f", "11", "--zoom", "55"], {
alias: { z: ["zm", "zoom"] } alias: { z: ["zm", "zoom"] }
}); });
assertEqual(argv.zoom, 55); assertEq(argv.zoom, 55);
assertEqual(argv.z, argv.zoom); assertEq(argv.z, argv.zoom);
assertEqual(argv.z, argv.zm); assertEq(argv.z, argv.zm);
assertEqual(argv.f, 11); assertEq(argv.f, 11);
}); });
test(function nestedDottedObjects() { test(function nestedDottedObjects() {
@ -181,7 +182,7 @@ test(function nestedDottedObjects() {
"--beep.boop" "--beep.boop"
]); ]);
assertEqual(argv.foo, { assertEq(argv.foo, {
bar: 3, bar: 3,
baz: 4, baz: 4,
quux: { quux: {
@ -189,5 +190,5 @@ test(function nestedDottedObjects() {
o_O: true o_O: true
} }
}); });
assertEqual(argv.beep, { boop: true }); assertEq(argv.beep, { boop: true });
}); });

View file

@ -1,25 +1,26 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { test, assertEqual } from "../../testing/mod.ts"; import { test } from "../../testing/mod.ts";
import { assertEq } from "../../testing/asserts.ts";
import { parse } from "../mod.ts"; import { parse } from "../mod.ts";
test(function numbericShortArgs() { test(function numbericShortArgs() {
assertEqual(parse(["-n123"]), { n: 123, _: [] }); assertEq(parse(["-n123"]), { n: 123, _: [] });
assertEqual(parse(["-123", "456"]), { 1: true, 2: true, 3: 456, _: [] }); assertEq(parse(["-123", "456"]), { 1: true, 2: true, 3: 456, _: [] });
}); });
test(function short() { test(function short() {
assertEqual(parse(["-b"]), { b: true, _: [] }); assertEq(parse(["-b"]), { b: true, _: [] });
assertEqual(parse(["foo", "bar", "baz"]), { _: ["foo", "bar", "baz"] }); assertEq(parse(["foo", "bar", "baz"]), { _: ["foo", "bar", "baz"] });
assertEqual(parse(["-cats"]), { c: true, a: true, t: true, s: true, _: [] }); assertEq(parse(["-cats"]), { c: true, a: true, t: true, s: true, _: [] });
assertEqual(parse(["-cats", "meow"]), { assertEq(parse(["-cats", "meow"]), {
c: true, c: true,
a: true, a: true,
t: true, t: true,
s: "meow", s: "meow",
_: [] _: []
}); });
assertEqual(parse(["-h", "localhost"]), { h: "localhost", _: [] }); assertEq(parse(["-h", "localhost"]), { h: "localhost", _: [] });
assertEqual(parse(["-h", "localhost", "-p", "555"]), { assertEq(parse(["-h", "localhost", "-p", "555"]), {
h: "localhost", h: "localhost",
p: 555, p: 555,
_: [] _: []
@ -27,7 +28,7 @@ test(function short() {
}); });
test(function mixedShortBoolAndCapture() { test(function mixedShortBoolAndCapture() {
assertEqual(parse(["-h", "localhost", "-fp", "555", "script.js"]), { assertEq(parse(["-h", "localhost", "-fp", "555", "script.js"]), {
f: true, f: true,
p: 555, p: 555,
h: "localhost", h: "localhost",
@ -36,7 +37,7 @@ test(function mixedShortBoolAndCapture() {
}); });
test(function shortAndLong() { test(function shortAndLong() {
assertEqual(parse(["-h", "localhost", "-fp", "555", "script.js"]), { assertEq(parse(["-h", "localhost", "-fp", "555", "script.js"]), {
f: true, f: true,
p: 555, p: 555,
h: "localhost", h: "localhost",

View file

@ -1,5 +1,6 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { test, assertEqual } from "../../testing/mod.ts"; import { test } from "../../testing/mod.ts";
import { assertEq } from "../../testing/asserts.ts";
import { parse } from "../mod.ts"; import { parse } from "../mod.ts";
// stops parsing on the first non-option when stopEarly is set // stops parsing on the first non-option when stopEarly is set
@ -8,7 +9,7 @@ test(function stopParsing() {
stopEarly: true stopEarly: true
}); });
assertEqual(argv, { assertEq(argv, {
aaa: "bbb", aaa: "bbb",
_: ["ccc", "--ddd"] _: ["ccc", "--ddd"]
}); });

View file

@ -1,5 +1,6 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { test, assertEqual } from "../../testing/mod.ts"; import { test } from "../../testing/mod.ts";
import { assertEq } from "../../testing/asserts.ts";
import { parse } from "../mod.ts"; import { parse } from "../mod.ts";
test(function booleanAndAliasIsNotUnknown() { test(function booleanAndAliasIsNotUnknown() {
@ -18,7 +19,7 @@ test(function booleanAndAliasIsNotUnknown() {
const aliasedArgv = parse(aliased, opts); const aliasedArgv = parse(aliased, opts);
const propertyArgv = parse(regular, opts); const propertyArgv = parse(regular, opts);
assertEqual(unknown, ["--derp", "-d"]); assertEq(unknown, ["--derp", "-d"]);
}); });
test(function flagBooleanTrueAnyDoubleHyphenArgumentIsNotUnknown() { test(function flagBooleanTrueAnyDoubleHyphenArgumentIsNotUnknown() {
@ -31,8 +32,8 @@ test(function flagBooleanTrueAnyDoubleHyphenArgumentIsNotUnknown() {
boolean: true, boolean: true,
unknown: unknownFn unknown: unknownFn
}); });
assertEqual(unknown, ["--tacos=good", "cow", "-p"]); assertEq(unknown, ["--tacos=good", "cow", "-p"]);
assertEqual(argv, { assertEq(argv, {
honk: true, honk: true,
_: [] _: []
}); });
@ -54,7 +55,7 @@ test(function stringAndAliasIsNotUnkown() {
const aliasedArgv = parse(aliased, opts); const aliasedArgv = parse(aliased, opts);
const propertyArgv = parse(regular, opts); const propertyArgv = parse(regular, opts);
assertEqual(unknown, ["--derp", "-d"]); assertEq(unknown, ["--derp", "-d"]);
}); });
test(function defaultAndAliasIsNotUnknown() { test(function defaultAndAliasIsNotUnknown() {
@ -73,7 +74,7 @@ test(function defaultAndAliasIsNotUnknown() {
const aliasedArgv = parse(aliased, opts); const aliasedArgv = parse(aliased, opts);
const propertyArgv = parse(regular, opts); const propertyArgv = parse(regular, opts);
assertEqual(unknown, []); assertEq(unknown, []);
}); });
test(function valueFollowingDoubleHyphenIsNotUnknown() { test(function valueFollowingDoubleHyphenIsNotUnknown() {
@ -89,8 +90,8 @@ test(function valueFollowingDoubleHyphenIsNotUnknown() {
}; };
const argv = parse(aliased, opts); const argv = parse(aliased, opts);
assertEqual(unknown, ["--bad"]); assertEq(unknown, ["--bad"]);
assertEqual(argv, { assertEq(argv, {
"--": ["good", "arg"], "--": ["good", "arg"],
_: [] _: []
}); });

View file

@ -1,7 +1,8 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { test, assertEqual } from "../../testing/mod.ts"; import { test } from "../../testing/mod.ts";
import { assertEq } from "../../testing/asserts.ts";
import { parse } from "../mod.ts"; import { parse } from "../mod.ts";
test(function whitespaceShouldBeWhitespace() { test(function whitespaceShouldBeWhitespace() {
assertEqual(parse(["-x", "\t"]).x, "\t"); assertEq(parse(["-x", "\t"]).x, "\t");
}); });

View file

@ -1,6 +1,7 @@
const { mkdir, open } = Deno; const { mkdir, open } = Deno;
import { FileInfo } from "deno"; import { FileInfo } from "deno";
import { test, assert } from "../testing/mod.ts"; import { test } from "../testing/mod.ts";
import { assertEq } from "../testing/asserts.ts";
import { glob } from "./glob.ts"; import { glob } from "./glob.ts";
import { join } from "./path.ts"; import { join } from "./path.ts";
import { testWalk } from "./walk_test.ts"; import { testWalk } from "./walk_test.ts";
@ -22,43 +23,43 @@ async function walkArray(
const arr_sync = Array.from(walkSync(dirname, options), (f: FileInfo) => const arr_sync = Array.from(walkSync(dirname, options), (f: FileInfo) =>
f.path.replace(/\\/g, "/") f.path.replace(/\\/g, "/")
).sort(); ).sort();
assert.equal(arr, arr_sync); assertEq(arr, arr_sync);
return arr; return arr;
} }
test({ test({
name: "glob: glob to regex", name: "glob: glob to regex",
fn() { fn() {
assert.equal(glob("unicorn.*") instanceof RegExp, true); assertEq(glob("unicorn.*") instanceof RegExp, true);
assert.equal(glob("unicorn.*").test("poney.ts"), false); assertEq(glob("unicorn.*").test("poney.ts"), false);
assert.equal(glob("unicorn.*").test("unicorn.py"), true); assertEq(glob("unicorn.*").test("unicorn.py"), true);
assert.equal(glob("*.ts").test("poney.ts"), true); assertEq(glob("*.ts").test("poney.ts"), true);
assert.equal(glob("*.ts").test("unicorn.js"), false); assertEq(glob("*.ts").test("unicorn.js"), false);
assert.equal( assertEq(
glob(join("unicorn", "**", "cathedral.ts")).test( glob(join("unicorn", "**", "cathedral.ts")).test(
join("unicorn", "in", "the", "cathedral.ts") join("unicorn", "in", "the", "cathedral.ts")
), ),
true true
); );
assert.equal( assertEq(
glob(join("unicorn", "**", "cathedral.ts")).test( glob(join("unicorn", "**", "cathedral.ts")).test(
join("unicorn", "in", "the", "kitchen.ts") join("unicorn", "in", "the", "kitchen.ts")
), ),
false false
); );
assert.equal( assertEq(
glob(join("unicorn", "**", "bathroom.*")).test( glob(join("unicorn", "**", "bathroom.*")).test(
join("unicorn", "sleeping", "in", "bathroom.py") join("unicorn", "sleeping", "in", "bathroom.py")
), ),
true true
); );
assert.equal( assertEq(
glob(join("unicorn", "!(sleeping)", "bathroom.ts"), { glob(join("unicorn", "!(sleeping)", "bathroom.ts"), {
extended: true extended: true
}).test(join("unicorn", "flying", "bathroom.ts")), }).test(join("unicorn", "flying", "bathroom.ts")),
true true
); );
assert.equal( assertEq(
glob(join("unicorn", "(!sleeping)", "bathroom.ts"), { glob(join("unicorn", "(!sleeping)", "bathroom.ts"), {
extended: true extended: true
}).test(join("unicorn", "sleeping", "bathroom.ts")), }).test(join("unicorn", "sleeping", "bathroom.ts")),
@ -74,8 +75,8 @@ testWalk(
}, },
async function globInWalk() { async function globInWalk() {
const arr = await walkArray(".", { match: [glob("*.ts")] }); const arr = await walkArray(".", { match: [glob("*.ts")] });
assert.equal(arr.length, 1); assertEq(arr.length, 1);
assert.equal(arr[0], "./a/x.ts"); assertEq(arr[0], "./a/x.ts");
} }
); );
@ -89,9 +90,9 @@ testWalk(
}, },
async function globInWalkWildcardFiles() { async function globInWalkWildcardFiles() {
const arr = await walkArray(".", { match: [glob("*.ts")] }); const arr = await walkArray(".", { match: [glob("*.ts")] });
assert.equal(arr.length, 2); assertEq(arr.length, 2);
assert.equal(arr[0], "./a/x.ts"); assertEq(arr[0], "./a/x.ts");
assert.equal(arr[1], "./b/z.ts"); assertEq(arr[1], "./b/z.ts");
} }
); );
@ -110,8 +111,8 @@ testWalk(
}) })
] ]
}); });
assert.equal(arr.length, 1); assertEq(arr.length, 1);
assert.equal(arr[0], "./a/yo/x.ts"); assertEq(arr[0], "./a/yo/x.ts");
} }
); );
@ -134,9 +135,9 @@ testWalk(
}) })
] ]
}); });
assert.equal(arr.length, 2); assertEq(arr.length, 2);
assert.equal(arr[0], "./a/deno/x.ts"); assertEq(arr[0], "./a/deno/x.ts");
assert.equal(arr[1], "./a/raptor/x.ts"); assertEq(arr[1], "./a/raptor/x.ts");
} }
); );
@ -151,8 +152,8 @@ testWalk(
match: [glob("x.*", { flags: "g", globstar: true })] match: [glob("x.*", { flags: "g", globstar: true })]
}); });
console.log(arr); console.log(arr);
assert.equal(arr.length, 2); assertEq(arr.length, 2);
assert.equal(arr[0], "./x.js"); assertEq(arr[0], "./x.js");
assert.equal(arr[1], "./x.ts"); assertEq(arr[1], "./x.ts");
} }
); );

View file

@ -3,11 +3,12 @@
// Copyright (c) 2018 Terkel Gjervig Nielsen // Copyright (c) 2018 Terkel Gjervig Nielsen
import * as deno from "deno"; import * as deno from "deno";
import { test, assert } from "../testing/mod.ts"; import { test } from "../testing/mod.ts";
import { assertEq } from "../testing/asserts.ts";
import { globrex } from "./globrex.ts"; import { globrex } from "./globrex.ts";
const isWin = deno.platform.os === "win"; const isWin = deno.platform.os === "win";
const t = { equal: assert.equal, is: assert.equal }; const t = { equal: assertEq, is: assertEq };
function match(glob, strUnix, strWin?, opts = {}) { function match(glob, strUnix, strWin?, opts = {}) {
if (typeof strWin === "object") { if (typeof strWin === "object") {

View file

@ -1,75 +1,73 @@
// Copyright the Browserify authors. MIT License. // Copyright the Browserify authors. MIT License.
// Ported from https://github.com/browserify/path-browserify/ // Ported from https://github.com/browserify/path-browserify/
import { test, assertEqual } from "../../testing/mod.ts"; import { test } from "../../testing/mod.ts";
import { assertEq } from "../../testing/asserts.ts";
import * as path from "./mod.ts"; import * as path from "./mod.ts";
test(function basename() { test(function basename() {
assertEqual(path.basename(".js", ".js"), ""); assertEq(path.basename(".js", ".js"), "");
assertEqual(path.basename(""), ""); assertEq(path.basename(""), "");
assertEqual(path.basename("/dir/basename.ext"), "basename.ext"); assertEq(path.basename("/dir/basename.ext"), "basename.ext");
assertEqual(path.basename("/basename.ext"), "basename.ext"); assertEq(path.basename("/basename.ext"), "basename.ext");
assertEqual(path.basename("basename.ext"), "basename.ext"); assertEq(path.basename("basename.ext"), "basename.ext");
assertEqual(path.basename("basename.ext/"), "basename.ext"); assertEq(path.basename("basename.ext/"), "basename.ext");
assertEqual(path.basename("basename.ext//"), "basename.ext"); assertEq(path.basename("basename.ext//"), "basename.ext");
assertEqual(path.basename("aaa/bbb", "/bbb"), "bbb"); assertEq(path.basename("aaa/bbb", "/bbb"), "bbb");
assertEqual(path.basename("aaa/bbb", "a/bbb"), "bbb"); assertEq(path.basename("aaa/bbb", "a/bbb"), "bbb");
assertEqual(path.basename("aaa/bbb", "bbb"), "bbb"); assertEq(path.basename("aaa/bbb", "bbb"), "bbb");
assertEqual(path.basename("aaa/bbb//", "bbb"), "bbb"); assertEq(path.basename("aaa/bbb//", "bbb"), "bbb");
assertEqual(path.basename("aaa/bbb", "bb"), "b"); assertEq(path.basename("aaa/bbb", "bb"), "b");
assertEqual(path.basename("aaa/bbb", "b"), "bb"); assertEq(path.basename("aaa/bbb", "b"), "bb");
assertEqual(path.basename("/aaa/bbb", "/bbb"), "bbb"); assertEq(path.basename("/aaa/bbb", "/bbb"), "bbb");
assertEqual(path.basename("/aaa/bbb", "a/bbb"), "bbb"); assertEq(path.basename("/aaa/bbb", "a/bbb"), "bbb");
assertEqual(path.basename("/aaa/bbb", "bbb"), "bbb"); assertEq(path.basename("/aaa/bbb", "bbb"), "bbb");
assertEqual(path.basename("/aaa/bbb//", "bbb"), "bbb"); assertEq(path.basename("/aaa/bbb//", "bbb"), "bbb");
assertEqual(path.basename("/aaa/bbb", "bb"), "b"); assertEq(path.basename("/aaa/bbb", "bb"), "b");
assertEqual(path.basename("/aaa/bbb", "b"), "bb"); assertEq(path.basename("/aaa/bbb", "b"), "bb");
assertEqual(path.basename("/aaa/bbb"), "bbb"); assertEq(path.basename("/aaa/bbb"), "bbb");
assertEqual(path.basename("/aaa/"), "aaa"); assertEq(path.basename("/aaa/"), "aaa");
assertEqual(path.basename("/aaa/b"), "b"); assertEq(path.basename("/aaa/b"), "b");
assertEqual(path.basename("/a/b"), "b"); assertEq(path.basename("/a/b"), "b");
assertEqual(path.basename("//a"), "a"); assertEq(path.basename("//a"), "a");
// On unix a backslash is just treated as any other character. // On unix a backslash is just treated as any other character.
assertEqual( assertEq(path.posix.basename("\\dir\\basename.ext"), "\\dir\\basename.ext");
path.posix.basename("\\dir\\basename.ext"), assertEq(path.posix.basename("\\basename.ext"), "\\basename.ext");
"\\dir\\basename.ext" assertEq(path.posix.basename("basename.ext"), "basename.ext");
); assertEq(path.posix.basename("basename.ext\\"), "basename.ext\\");
assertEqual(path.posix.basename("\\basename.ext"), "\\basename.ext"); assertEq(path.posix.basename("basename.ext\\\\"), "basename.ext\\\\");
assertEqual(path.posix.basename("basename.ext"), "basename.ext"); assertEq(path.posix.basename("foo"), "foo");
assertEqual(path.posix.basename("basename.ext\\"), "basename.ext\\");
assertEqual(path.posix.basename("basename.ext\\\\"), "basename.ext\\\\");
assertEqual(path.posix.basename("foo"), "foo");
// POSIX filenames may include control characters // POSIX filenames may include control characters
const controlCharFilename = "Icon" + String.fromCharCode(13); const controlCharFilename = "Icon" + String.fromCharCode(13);
assertEqual( assertEq(
path.posix.basename("/a/b/" + controlCharFilename), path.posix.basename("/a/b/" + controlCharFilename),
controlCharFilename controlCharFilename
); );
}); });
test(function basenameWin32() { test(function basenameWin32() {
assertEqual(path.win32.basename("\\dir\\basename.ext"), "basename.ext"); assertEq(path.win32.basename("\\dir\\basename.ext"), "basename.ext");
assertEqual(path.win32.basename("\\basename.ext"), "basename.ext"); assertEq(path.win32.basename("\\basename.ext"), "basename.ext");
assertEqual(path.win32.basename("basename.ext"), "basename.ext"); assertEq(path.win32.basename("basename.ext"), "basename.ext");
assertEqual(path.win32.basename("basename.ext\\"), "basename.ext"); assertEq(path.win32.basename("basename.ext\\"), "basename.ext");
assertEqual(path.win32.basename("basename.ext\\\\"), "basename.ext"); assertEq(path.win32.basename("basename.ext\\\\"), "basename.ext");
assertEqual(path.win32.basename("foo"), "foo"); assertEq(path.win32.basename("foo"), "foo");
assertEqual(path.win32.basename("aaa\\bbb", "\\bbb"), "bbb"); assertEq(path.win32.basename("aaa\\bbb", "\\bbb"), "bbb");
assertEqual(path.win32.basename("aaa\\bbb", "a\\bbb"), "bbb"); assertEq(path.win32.basename("aaa\\bbb", "a\\bbb"), "bbb");
assertEqual(path.win32.basename("aaa\\bbb", "bbb"), "bbb"); assertEq(path.win32.basename("aaa\\bbb", "bbb"), "bbb");
assertEqual(path.win32.basename("aaa\\bbb\\\\\\\\", "bbb"), "bbb"); assertEq(path.win32.basename("aaa\\bbb\\\\\\\\", "bbb"), "bbb");
assertEqual(path.win32.basename("aaa\\bbb", "bb"), "b"); assertEq(path.win32.basename("aaa\\bbb", "bb"), "b");
assertEqual(path.win32.basename("aaa\\bbb", "b"), "bb"); assertEq(path.win32.basename("aaa\\bbb", "b"), "bb");
assertEqual(path.win32.basename("C:"), ""); assertEq(path.win32.basename("C:"), "");
assertEqual(path.win32.basename("C:."), "."); assertEq(path.win32.basename("C:."), ".");
assertEqual(path.win32.basename("C:\\"), ""); assertEq(path.win32.basename("C:\\"), "");
assertEqual(path.win32.basename("C:\\dir\\base.ext"), "base.ext"); assertEq(path.win32.basename("C:\\dir\\base.ext"), "base.ext");
assertEqual(path.win32.basename("C:\\basename.ext"), "basename.ext"); assertEq(path.win32.basename("C:\\basename.ext"), "basename.ext");
assertEqual(path.win32.basename("C:basename.ext"), "basename.ext"); assertEq(path.win32.basename("C:basename.ext"), "basename.ext");
assertEqual(path.win32.basename("C:basename.ext\\"), "basename.ext"); assertEq(path.win32.basename("C:basename.ext\\"), "basename.ext");
assertEqual(path.win32.basename("C:basename.ext\\\\"), "basename.ext"); assertEq(path.win32.basename("C:basename.ext\\\\"), "basename.ext");
assertEqual(path.win32.basename("C:foo"), "foo"); assertEq(path.win32.basename("C:foo"), "foo");
assertEqual(path.win32.basename("file:stream"), "file:stream"); assertEq(path.win32.basename("file:stream"), "file:stream");
}); });

View file

@ -1,61 +1,62 @@
// Copyright the Browserify authors. MIT License. // Copyright the Browserify authors. MIT License.
// Ported from https://github.com/browserify/path-browserify/ // Ported from https://github.com/browserify/path-browserify/
import { test, assertEqual } from "../../testing/mod.ts"; import { test } from "../../testing/mod.ts";
import { assertEq } from "../../testing/asserts.ts";
import * as path from "./mod.ts"; import * as path from "./mod.ts";
test(function dirname() { test(function dirname() {
assertEqual(path.posix.dirname("/a/b/"), "/a"); assertEq(path.posix.dirname("/a/b/"), "/a");
assertEqual(path.posix.dirname("/a/b"), "/a"); assertEq(path.posix.dirname("/a/b"), "/a");
assertEqual(path.posix.dirname("/a"), "/"); assertEq(path.posix.dirname("/a"), "/");
assertEqual(path.posix.dirname(""), "."); assertEq(path.posix.dirname(""), ".");
assertEqual(path.posix.dirname("/"), "/"); assertEq(path.posix.dirname("/"), "/");
assertEqual(path.posix.dirname("////"), "/"); assertEq(path.posix.dirname("////"), "/");
assertEqual(path.posix.dirname("//a"), "//"); assertEq(path.posix.dirname("//a"), "//");
assertEqual(path.posix.dirname("foo"), "."); assertEq(path.posix.dirname("foo"), ".");
}); });
test(function dirnameWin32() { test(function dirnameWin32() {
assertEqual(path.win32.dirname("c:\\"), "c:\\"); assertEq(path.win32.dirname("c:\\"), "c:\\");
assertEqual(path.win32.dirname("c:\\foo"), "c:\\"); assertEq(path.win32.dirname("c:\\foo"), "c:\\");
assertEqual(path.win32.dirname("c:\\foo\\"), "c:\\"); assertEq(path.win32.dirname("c:\\foo\\"), "c:\\");
assertEqual(path.win32.dirname("c:\\foo\\bar"), "c:\\foo"); assertEq(path.win32.dirname("c:\\foo\\bar"), "c:\\foo");
assertEqual(path.win32.dirname("c:\\foo\\bar\\"), "c:\\foo"); assertEq(path.win32.dirname("c:\\foo\\bar\\"), "c:\\foo");
assertEqual(path.win32.dirname("c:\\foo\\bar\\baz"), "c:\\foo\\bar"); assertEq(path.win32.dirname("c:\\foo\\bar\\baz"), "c:\\foo\\bar");
assertEqual(path.win32.dirname("\\"), "\\"); assertEq(path.win32.dirname("\\"), "\\");
assertEqual(path.win32.dirname("\\foo"), "\\"); assertEq(path.win32.dirname("\\foo"), "\\");
assertEqual(path.win32.dirname("\\foo\\"), "\\"); assertEq(path.win32.dirname("\\foo\\"), "\\");
assertEqual(path.win32.dirname("\\foo\\bar"), "\\foo"); assertEq(path.win32.dirname("\\foo\\bar"), "\\foo");
assertEqual(path.win32.dirname("\\foo\\bar\\"), "\\foo"); assertEq(path.win32.dirname("\\foo\\bar\\"), "\\foo");
assertEqual(path.win32.dirname("\\foo\\bar\\baz"), "\\foo\\bar"); assertEq(path.win32.dirname("\\foo\\bar\\baz"), "\\foo\\bar");
assertEqual(path.win32.dirname("c:"), "c:"); assertEq(path.win32.dirname("c:"), "c:");
assertEqual(path.win32.dirname("c:foo"), "c:"); assertEq(path.win32.dirname("c:foo"), "c:");
assertEqual(path.win32.dirname("c:foo\\"), "c:"); assertEq(path.win32.dirname("c:foo\\"), "c:");
assertEqual(path.win32.dirname("c:foo\\bar"), "c:foo"); assertEq(path.win32.dirname("c:foo\\bar"), "c:foo");
assertEqual(path.win32.dirname("c:foo\\bar\\"), "c:foo"); assertEq(path.win32.dirname("c:foo\\bar\\"), "c:foo");
assertEqual(path.win32.dirname("c:foo\\bar\\baz"), "c:foo\\bar"); assertEq(path.win32.dirname("c:foo\\bar\\baz"), "c:foo\\bar");
assertEqual(path.win32.dirname("file:stream"), "."); assertEq(path.win32.dirname("file:stream"), ".");
assertEqual(path.win32.dirname("dir\\file:stream"), "dir"); assertEq(path.win32.dirname("dir\\file:stream"), "dir");
assertEqual(path.win32.dirname("\\\\unc\\share"), "\\\\unc\\share"); assertEq(path.win32.dirname("\\\\unc\\share"), "\\\\unc\\share");
assertEqual(path.win32.dirname("\\\\unc\\share\\foo"), "\\\\unc\\share\\"); assertEq(path.win32.dirname("\\\\unc\\share\\foo"), "\\\\unc\\share\\");
assertEqual(path.win32.dirname("\\\\unc\\share\\foo\\"), "\\\\unc\\share\\"); assertEq(path.win32.dirname("\\\\unc\\share\\foo\\"), "\\\\unc\\share\\");
assertEqual( assertEq(
path.win32.dirname("\\\\unc\\share\\foo\\bar"), path.win32.dirname("\\\\unc\\share\\foo\\bar"),
"\\\\unc\\share\\foo" "\\\\unc\\share\\foo"
); );
assertEqual( assertEq(
path.win32.dirname("\\\\unc\\share\\foo\\bar\\"), path.win32.dirname("\\\\unc\\share\\foo\\bar\\"),
"\\\\unc\\share\\foo" "\\\\unc\\share\\foo"
); );
assertEqual( assertEq(
path.win32.dirname("\\\\unc\\share\\foo\\bar\\baz"), path.win32.dirname("\\\\unc\\share\\foo\\bar\\baz"),
"\\\\unc\\share\\foo\\bar" "\\\\unc\\share\\foo\\bar"
); );
assertEqual(path.win32.dirname("/a/b/"), "/a"); assertEq(path.win32.dirname("/a/b/"), "/a");
assertEqual(path.win32.dirname("/a/b"), "/a"); assertEq(path.win32.dirname("/a/b"), "/a");
assertEqual(path.win32.dirname("/a"), "/"); assertEq(path.win32.dirname("/a"), "/");
assertEqual(path.win32.dirname(""), "."); assertEq(path.win32.dirname(""), ".");
assertEqual(path.win32.dirname("/"), "/"); assertEq(path.win32.dirname("/"), "/");
assertEqual(path.win32.dirname("////"), "/"); assertEq(path.win32.dirname("////"), "/");
assertEqual(path.win32.dirname("foo"), "."); assertEq(path.win32.dirname("foo"), ".");
}); });

View file

@ -1,7 +1,8 @@
// Copyright the Browserify authors. MIT License. // Copyright the Browserify authors. MIT License.
// Ported from https://github.com/browserify/path-browserify/ // Ported from https://github.com/browserify/path-browserify/
import { test, assertEqual } from "../../testing/mod.ts"; import { test } from "../../testing/mod.ts";
import { assertEq } from "../../testing/asserts.ts";
import * as path from "./mod.ts"; import * as path from "./mod.ts";
const slashRE = /\//g; const slashRE = /\//g;
@ -55,35 +56,35 @@ test(function extname() {
pairs.forEach(function(p) { pairs.forEach(function(p) {
const input = p[0]; const input = p[0];
const expected = p[1]; const expected = p[1];
assertEqual(expected, path.posix.extname(input)); assertEq(expected, path.posix.extname(input));
}); });
// On *nix, backslash is a valid name component like any other character. // On *nix, backslash is a valid name component like any other character.
assertEqual(path.posix.extname(".\\"), ""); assertEq(path.posix.extname(".\\"), "");
assertEqual(path.posix.extname("..\\"), ".\\"); assertEq(path.posix.extname("..\\"), ".\\");
assertEqual(path.posix.extname("file.ext\\"), ".ext\\"); assertEq(path.posix.extname("file.ext\\"), ".ext\\");
assertEqual(path.posix.extname("file.ext\\\\"), ".ext\\\\"); assertEq(path.posix.extname("file.ext\\\\"), ".ext\\\\");
assertEqual(path.posix.extname("file\\"), ""); assertEq(path.posix.extname("file\\"), "");
assertEqual(path.posix.extname("file\\\\"), ""); assertEq(path.posix.extname("file\\\\"), "");
assertEqual(path.posix.extname("file.\\"), ".\\"); assertEq(path.posix.extname("file.\\"), ".\\");
assertEqual(path.posix.extname("file.\\\\"), ".\\\\"); assertEq(path.posix.extname("file.\\\\"), ".\\\\");
}); });
test(function extnameWin32() { test(function extnameWin32() {
pairs.forEach(function(p) { pairs.forEach(function(p) {
const input = p[0].replace(slashRE, "\\"); const input = p[0].replace(slashRE, "\\");
const expected = p[1]; const expected = p[1];
assertEqual(expected, path.win32.extname(input)); assertEq(expected, path.win32.extname(input));
assertEqual(expected, path.win32.extname("C:" + input)); assertEq(expected, path.win32.extname("C:" + input));
}); });
// On Windows, backslash is a path separator. // On Windows, backslash is a path separator.
assertEqual(path.win32.extname(".\\"), ""); assertEq(path.win32.extname(".\\"), "");
assertEqual(path.win32.extname("..\\"), ""); assertEq(path.win32.extname("..\\"), "");
assertEqual(path.win32.extname("file.ext\\"), ".ext"); assertEq(path.win32.extname("file.ext\\"), ".ext");
assertEqual(path.win32.extname("file.ext\\\\"), ".ext"); assertEq(path.win32.extname("file.ext\\\\"), ".ext");
assertEqual(path.win32.extname("file\\"), ""); assertEq(path.win32.extname("file\\"), "");
assertEqual(path.win32.extname("file\\\\"), ""); assertEq(path.win32.extname("file\\\\"), "");
assertEqual(path.win32.extname("file.\\"), "."); assertEq(path.win32.extname("file.\\"), ".");
assertEqual(path.win32.extname("file.\\\\"), "."); assertEq(path.win32.extname("file.\\\\"), ".");
}); });

View file

@ -1,33 +1,34 @@
// Copyright the Browserify authors. MIT License. // Copyright the Browserify authors. MIT License.
// Ported from https://github.com/browserify/path-browserify/ // Ported from https://github.com/browserify/path-browserify/
import { test, assertEqual } from "../../testing/mod.ts"; import { test } from "../../testing/mod.ts";
import { assertEq } from "../../testing/asserts.ts";
import * as path from "./mod.ts"; import * as path from "./mod.ts";
test(function isAbsolute() { test(function isAbsolute() {
assertEqual(path.posix.isAbsolute("/home/foo"), true); assertEq(path.posix.isAbsolute("/home/foo"), true);
assertEqual(path.posix.isAbsolute("/home/foo/.."), true); assertEq(path.posix.isAbsolute("/home/foo/.."), true);
assertEqual(path.posix.isAbsolute("bar/"), false); assertEq(path.posix.isAbsolute("bar/"), false);
assertEqual(path.posix.isAbsolute("./baz"), false); assertEq(path.posix.isAbsolute("./baz"), false);
}); });
test(function isAbsoluteWin32() { test(function isAbsoluteWin32() {
assertEqual(path.win32.isAbsolute("/"), true); assertEq(path.win32.isAbsolute("/"), true);
assertEqual(path.win32.isAbsolute("//"), true); assertEq(path.win32.isAbsolute("//"), true);
assertEqual(path.win32.isAbsolute("//server"), true); assertEq(path.win32.isAbsolute("//server"), true);
assertEqual(path.win32.isAbsolute("//server/file"), true); assertEq(path.win32.isAbsolute("//server/file"), true);
assertEqual(path.win32.isAbsolute("\\\\server\\file"), true); assertEq(path.win32.isAbsolute("\\\\server\\file"), true);
assertEqual(path.win32.isAbsolute("\\\\server"), true); assertEq(path.win32.isAbsolute("\\\\server"), true);
assertEqual(path.win32.isAbsolute("\\\\"), true); assertEq(path.win32.isAbsolute("\\\\"), true);
assertEqual(path.win32.isAbsolute("c"), false); assertEq(path.win32.isAbsolute("c"), false);
assertEqual(path.win32.isAbsolute("c:"), false); assertEq(path.win32.isAbsolute("c:"), false);
assertEqual(path.win32.isAbsolute("c:\\"), true); assertEq(path.win32.isAbsolute("c:\\"), true);
assertEqual(path.win32.isAbsolute("c:/"), true); assertEq(path.win32.isAbsolute("c:/"), true);
assertEqual(path.win32.isAbsolute("c://"), true); assertEq(path.win32.isAbsolute("c://"), true);
assertEqual(path.win32.isAbsolute("C:/Users/"), true); assertEq(path.win32.isAbsolute("C:/Users/"), true);
assertEqual(path.win32.isAbsolute("C:\\Users\\"), true); assertEq(path.win32.isAbsolute("C:\\Users\\"), true);
assertEqual(path.win32.isAbsolute("C:cwd/another"), false); assertEq(path.win32.isAbsolute("C:cwd/another"), false);
assertEqual(path.win32.isAbsolute("C:cwd\\another"), false); assertEq(path.win32.isAbsolute("C:cwd\\another"), false);
assertEqual(path.win32.isAbsolute("directory/directory"), false); assertEq(path.win32.isAbsolute("directory/directory"), false);
assertEqual(path.win32.isAbsolute("directory\\directory"), false); assertEq(path.win32.isAbsolute("directory\\directory"), false);
}); });

View file

@ -1,4 +1,5 @@
import { test, assertEqual } from "../../testing/mod.ts"; import { test } from "../../testing/mod.ts";
import { assertEq } from "../../testing/asserts.ts";
import * as path from "./mod.ts"; import * as path from "./mod.ts";
const backslashRE = /\\/g; const backslashRE = /\\/g;
@ -108,17 +109,17 @@ const windowsJoinTests = [
test(function join() { test(function join() {
joinTests.forEach(function(p) { joinTests.forEach(function(p) {
const actual = path.posix.join.apply(null, p[0]); const actual = path.posix.join.apply(null, p[0]);
assertEqual(actual, p[1]); assertEq(actual, p[1]);
}); });
}); });
test(function joinWin32() { test(function joinWin32() {
joinTests.forEach(function(p) { joinTests.forEach(function(p) {
const actual = path.win32.join.apply(null, p[0]).replace(backslashRE, "/"); const actual = path.win32.join.apply(null, p[0]).replace(backslashRE, "/");
assertEqual(actual, p[1]); assertEq(actual, p[1]);
}); });
windowsJoinTests.forEach(function(p) { windowsJoinTests.forEach(function(p) {
const actual = path.win32.join.apply(null, p[0]); const actual = path.win32.join.apply(null, p[0]);
assertEqual(actual, p[1]); assertEq(actual, p[1]);
}); });
}); });

View file

@ -1,7 +1,8 @@
// Copyright the Browserify authors. MIT License. // Copyright the Browserify authors. MIT License.
// Ported from https://github.com/browserify/path-browserify/ // Ported from https://github.com/browserify/path-browserify/
import { test, assertEqual } from "../../testing/mod.ts"; import { test } from "../../testing/mod.ts";
import { assertEq } from "../../testing/asserts.ts";
import * as path from "./mod.ts"; import * as path from "./mod.ts";
const winPaths = [ const winPaths = [
@ -130,15 +131,15 @@ function checkParseFormat(path, paths) {
paths.forEach(function(p) { paths.forEach(function(p) {
const element = p[0]; const element = p[0];
const output = path.parse(element); const output = path.parse(element);
assertEqual(typeof output.root, "string"); assertEq(typeof output.root, "string");
assertEqual(typeof output.dir, "string"); assertEq(typeof output.dir, "string");
assertEqual(typeof output.base, "string"); assertEq(typeof output.base, "string");
assertEqual(typeof output.ext, "string"); assertEq(typeof output.ext, "string");
assertEqual(typeof output.name, "string"); assertEq(typeof output.name, "string");
assertEqual(path.format(output), element); assertEq(path.format(output), element);
assertEqual(output.rooroot, undefined); assertEq(output.rooroot, undefined);
assertEqual(output.dir, output.dir ? path.dirname(element) : ""); assertEq(output.dir, output.dir ? path.dirname(element) : "");
assertEqual(output.base, path.basename(element)); assertEq(output.base, path.basename(element));
}); });
} }
@ -148,14 +149,14 @@ function checkSpecialCaseParseFormat(path, testCases) {
const expect = testCase[1]; const expect = testCase[1];
const output = path.parse(element); const output = path.parse(element);
Object.keys(expect).forEach(function(key) { Object.keys(expect).forEach(function(key) {
assertEqual(output[key], expect[key]); assertEq(output[key], expect[key]);
}); });
}); });
} }
function checkFormat(path, testCases) { function checkFormat(path, testCases) {
testCases.forEach(function(testCase) { testCases.forEach(function(testCase) {
assertEqual(path.format(testCase[0]), testCase[1]); assertEq(path.format(testCase[0]), testCase[1]);
}); });
} }
@ -163,7 +164,7 @@ test(function parseTrailingWin32() {
windowsTrailingTests.forEach(function(p) { windowsTrailingTests.forEach(function(p) {
const actual = path.win32.parse(p[0] as string); const actual = path.win32.parse(p[0] as string);
const expected = p[1]; const expected = p[1];
assertEqual(actual, expected); assertEq(actual, expected);
}); });
}); });
@ -171,6 +172,6 @@ test(function parseTrailing() {
posixTrailingTests.forEach(function(p) { posixTrailingTests.forEach(function(p) {
const actual = path.posix.parse(p[0] as string); const actual = path.posix.parse(p[0] as string);
const expected = p[1]; const expected = p[1];
assertEqual(actual, expected); assertEq(actual, expected);
}); });
}); });

View file

@ -1,7 +1,8 @@
// Copyright the Browserify authors. MIT License. // Copyright the Browserify authors. MIT License.
// Ported from https://github.com/browserify/path-browserify/ // Ported from https://github.com/browserify/path-browserify/
import { test, assertEqual } from "../../testing/mod.ts"; import { test } from "../../testing/mod.ts";
import { assertEq } from "../../testing/asserts.ts";
import * as path from "./mod.ts"; import * as path from "./mod.ts";
const relativeTests = { const relativeTests = {
@ -59,7 +60,7 @@ test(function relative() {
relativeTests.posix.forEach(function(p) { relativeTests.posix.forEach(function(p) {
const expected = p[2]; const expected = p[2];
const actual = path.posix.relative(p[0], p[1]); const actual = path.posix.relative(p[0], p[1]);
assertEqual(actual, expected); assertEq(actual, expected);
}); });
}); });
@ -67,6 +68,6 @@ test(function relativeWin32() {
relativeTests.win32.forEach(function(p) { relativeTests.win32.forEach(function(p) {
const expected = p[2]; const expected = p[2];
const actual = path.win32.relative(p[0], p[1]); const actual = path.win32.relative(p[0], p[1]);
assertEqual(actual, expected); assertEq(actual, expected);
}); });
}); });

View file

@ -2,7 +2,8 @@
// Ported from https://github.com/browserify/path-browserify/ // Ported from https://github.com/browserify/path-browserify/
const { cwd } = Deno; const { cwd } = Deno;
import { test, assertEqual } from "../../testing/mod.ts"; import { test } from "../../testing/mod.ts";
import { assertEq } from "../../testing/asserts.ts";
import * as path from "./mod.ts"; import * as path from "./mod.ts";
const windowsTests = const windowsTests =
@ -37,13 +38,13 @@ const posixTests =
test(function resolve() { test(function resolve() {
posixTests.forEach(function(p) { posixTests.forEach(function(p) {
const actual = path.posix.resolve.apply(null, p[0]); const actual = path.posix.resolve.apply(null, p[0]);
assertEqual(actual, p[1]); assertEq(actual, p[1]);
}); });
}); });
test(function resolveWin32() { test(function resolveWin32() {
windowsTests.forEach(function(p) { windowsTests.forEach(function(p) {
const actual = path.win32.resolve.apply(null, p[0]); const actual = path.win32.resolve.apply(null, p[0]);
assertEqual(actual, p[1]); assertEq(actual, p[1]);
}); });
}); });

View file

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

View file

@ -10,7 +10,8 @@ const {
} = Deno; } = Deno;
import { FileInfo } from "deno"; import { FileInfo } from "deno";
import { walk, walkSync, WalkOptions } from "./walk.ts"; import { walk, walkSync, WalkOptions } from "./walk.ts";
import { test, assert, TestFunction } from "../testing/mod.ts"; import { test, TestFunction } from "../testing/mod.ts";
import { assert, assertEq } from "../testing/asserts.ts";
const isWindows = platform.os === "win"; const isWindows = platform.os === "win";
@ -46,7 +47,7 @@ async function walkArray(
const arr_sync = Array.from(walkSync(dirname, options), (f: FileInfo) => const arr_sync = Array.from(walkSync(dirname, options), (f: FileInfo) =>
f.path.replace(/\\/g, "/") f.path.replace(/\\/g, "/")
).sort(); ).sort();
assert.equal(arr, arr_sync); assertEq(arr, arr_sync);
return arr; return arr;
} }
@ -55,7 +56,7 @@ async function touch(path: string): Promise<void> {
} }
function assertReady(expectedLength: number) { function assertReady(expectedLength: number) {
const arr = Array.from(walkSync(), (f: FileInfo) => f.path); const arr = Array.from(walkSync(), (f: FileInfo) => f.path);
assert.equal(arr.length, expectedLength); assertEq(arr.length, expectedLength);
} }
testWalk( testWalk(
@ -64,7 +65,7 @@ testWalk(
}, },
async function emptyDir() { async function emptyDir() {
const arr = await walkArray(); const arr = await walkArray();
assert.equal(arr.length, 0); assertEq(arr.length, 0);
} }
); );
@ -74,8 +75,8 @@ testWalk(
}, },
async function singleFile() { async function singleFile() {
const arr = await walkArray(); const arr = await walkArray();
assert.equal(arr.length, 1); assertEq(arr.length, 1);
assert.equal(arr[0], "./x"); assertEq(arr[0], "./x");
} }
); );
@ -88,11 +89,11 @@ testWalk(
for (const f of walkSync()) { for (const f of walkSync()) {
count += 1; count += 1;
} }
assert.equal(count, 1); assertEq(count, 1);
for await (const f of walk()) { for await (const f of walk()) {
count += 1; count += 1;
} }
assert.equal(count, 2); assertEq(count, 2);
} }
); );
@ -103,8 +104,8 @@ testWalk(
}, },
async function nestedSingleFile() { async function nestedSingleFile() {
const arr = await walkArray(); const arr = await walkArray();
assert.equal(arr.length, 1); assertEq(arr.length, 1);
assert.equal(arr[0], "./a/x"); assertEq(arr[0], "./a/x");
} }
); );
@ -116,10 +117,10 @@ testWalk(
async function depth() { async function depth() {
assertReady(1); assertReady(1);
const arr_3 = await walkArray(".", { maxDepth: 3 }); const arr_3 = await walkArray(".", { maxDepth: 3 });
assert.equal(arr_3.length, 0); assertEq(arr_3.length, 0);
const arr_5 = await walkArray(".", { maxDepth: 5 }); const arr_5 = await walkArray(".", { maxDepth: 5 });
assert.equal(arr_5.length, 1); assertEq(arr_5.length, 1);
assert.equal(arr_5[0], "./a/b/c/d/x"); assertEq(arr_5[0], "./a/b/c/d/x");
} }
); );
@ -131,8 +132,8 @@ testWalk(
async function ext() { async function ext() {
assertReady(2); assertReady(2);
const arr = await walkArray(".", { exts: [".ts"] }); const arr = await walkArray(".", { exts: [".ts"] });
assert.equal(arr.length, 1); assertEq(arr.length, 1);
assert.equal(arr[0], "./x.ts"); assertEq(arr[0], "./x.ts");
} }
); );
@ -145,9 +146,9 @@ testWalk(
async function extAny() { async function extAny() {
assertReady(3); assertReady(3);
const arr = await walkArray(".", { exts: [".rs", ".ts"] }); const arr = await walkArray(".", { exts: [".rs", ".ts"] });
assert.equal(arr.length, 2); assertEq(arr.length, 2);
assert.equal(arr[0], "./x.ts"); assertEq(arr[0], "./x.ts");
assert.equal(arr[1], "./y.rs"); assertEq(arr[1], "./y.rs");
} }
); );
@ -159,8 +160,8 @@ testWalk(
async function match() { async function match() {
assertReady(2); assertReady(2);
const arr = await walkArray(".", { match: [/x/] }); const arr = await walkArray(".", { match: [/x/] });
assert.equal(arr.length, 1); assertEq(arr.length, 1);
assert.equal(arr[0], "./x"); assertEq(arr[0], "./x");
} }
); );
@ -173,9 +174,9 @@ testWalk(
async function matchAny() { async function matchAny() {
assertReady(3); assertReady(3);
const arr = await walkArray(".", { match: [/x/, /y/] }); const arr = await walkArray(".", { match: [/x/, /y/] });
assert.equal(arr.length, 2); assertEq(arr.length, 2);
assert.equal(arr[0], "./x"); assertEq(arr[0], "./x");
assert.equal(arr[1], "./y"); assertEq(arr[1], "./y");
} }
); );
@ -187,8 +188,8 @@ testWalk(
async function skip() { async function skip() {
assertReady(2); assertReady(2);
const arr = await walkArray(".", { skip: [/x/] }); const arr = await walkArray(".", { skip: [/x/] });
assert.equal(arr.length, 1); assertEq(arr.length, 1);
assert.equal(arr[0], "./y"); assertEq(arr[0], "./y");
} }
); );
@ -201,8 +202,8 @@ testWalk(
async function skipAny() { async function skipAny() {
assertReady(3); assertReady(3);
const arr = await walkArray(".", { skip: [/x/, /y/] }); const arr = await walkArray(".", { skip: [/x/, /y/] });
assert.equal(arr.length, 1); assertEq(arr.length, 1);
assert.equal(arr[0], "./z"); assertEq(arr[0], "./z");
} }
); );
@ -217,19 +218,19 @@ testWalk(
async function subDir() { async function subDir() {
assertReady(3); assertReady(3);
const arr = await walkArray("b"); const arr = await walkArray("b");
assert.equal(arr.length, 1); assertEq(arr.length, 1);
assert.equal(arr[0], "b/z"); assertEq(arr[0], "b/z");
} }
); );
testWalk(async (d: string) => {}, async function onError() { testWalk(async (d: string) => {}, async function onError() {
assertReady(0); assertReady(0);
const ignored = await walkArray("missing"); const ignored = await walkArray("missing");
assert.equal(ignored.length, 0); assertEq(ignored.length, 0);
let errors = 0; let errors = 0;
const arr = await walkArray("missing", { onError: e => (errors += 1) }); const arr = await walkArray("missing", { onError: e => (errors += 1) });
// It's 2 since walkArray iterates over both sync and async. // It's 2 since walkArray iterates over both sync and async.
assert.equal(errors, 2); assertEq(errors, 2);
}); });
testWalk( testWalk(
@ -254,11 +255,11 @@ testWalk(
assertReady(3); assertReady(3);
const files = await walkArray("a"); const files = await walkArray("a");
assert.equal(files.length, 2); assertEq(files.length, 2);
assert(!files.includes("a/bb/z")); assert(!files.includes("a/bb/z"));
const arr = await walkArray("a", { followSymlinks: true }); const arr = await walkArray("a", { followSymlinks: true });
assert.equal(arr.length, 3); assertEq(arr.length, 3);
assert(arr.some(f => f.endsWith("/b/z"))); assert(arr.some(f => f.endsWith("/b/z")));
} }
); );

View file

@ -1,7 +1,8 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
const { readFile, run } = Deno; const { readFile, run } = Deno;
import { test, assert, assertEqual } from "../testing/mod.ts"; import { test } from "../testing/mod.ts";
import { assert, assertEq } from "../testing/asserts.ts";
import { BufReader } from "../io/bufio.ts"; import { BufReader } from "../io/bufio.ts";
import { TextProtoReader } from "../textproto/mod.ts"; import { TextProtoReader } from "../textproto/mod.ts";
@ -35,12 +36,12 @@ test(async function serveFile() {
const res = await fetch("http://localhost:4500/azure-pipelines.yml"); const res = await fetch("http://localhost:4500/azure-pipelines.yml");
assert(res.headers.has("access-control-allow-origin")); assert(res.headers.has("access-control-allow-origin"));
assert(res.headers.has("access-control-allow-headers")); assert(res.headers.has("access-control-allow-headers"));
assertEqual(res.headers.get("content-type"), "text/yaml; charset=utf-8"); assertEq(res.headers.get("content-type"), "text/yaml; charset=utf-8");
const downloadedFile = await res.text(); const downloadedFile = await res.text();
const localFile = new TextDecoder().decode( const localFile = new TextDecoder().decode(
await readFile("./azure-pipelines.yml") await readFile("./azure-pipelines.yml")
); );
assertEqual(downloadedFile, localFile); assertEq(downloadedFile, localFile);
} finally { } finally {
killFileServer(); killFileServer();
} }
@ -65,7 +66,7 @@ test(async function serveFallback() {
const res = await fetch("http://localhost:4500/badfile.txt"); const res = await fetch("http://localhost:4500/badfile.txt");
assert(res.headers.has("access-control-allow-origin")); assert(res.headers.has("access-control-allow-origin"));
assert(res.headers.has("access-control-allow-headers")); assert(res.headers.has("access-control-allow-headers"));
assertEqual(res.status, 404); assertEq(res.status, 404);
} finally { } finally {
killFileServer(); killFileServer();
} }

View file

@ -4,7 +4,7 @@ import { Conn, Reader, Writer } from "deno";
import { BufReader, BufState, BufWriter } from "../io/bufio.ts"; import { BufReader, BufState, BufWriter } from "../io/bufio.ts";
import { TextProtoReader } from "../textproto/mod.ts"; import { TextProtoReader } from "../textproto/mod.ts";
import { STATUS_TEXT } from "./http_status.ts"; import { STATUS_TEXT } from "./http_status.ts";
import { assert } from "../testing/mod.ts"; import { assert } from "../testing/asserts.ts";
interface Deferred { interface Deferred {
promise: Promise<{}>; promise: Promise<{}>;

View file

@ -6,7 +6,8 @@
// https://github.com/golang/go/blob/master/src/net/http/responsewrite_test.go // https://github.com/golang/go/blob/master/src/net/http/responsewrite_test.go
const { Buffer } = Deno; const { Buffer } = Deno;
import { assertEqual, test } from "../testing/mod.ts"; import { test } from "../testing/mod.ts";
import { assertEq } from "../testing/asserts.ts";
import { Response, ServerRequest } from "./server.ts"; import { Response, ServerRequest } from "./server.ts";
import { BufReader, BufWriter } from "../io/bufio.ts"; import { BufReader, BufWriter } from "../io/bufio.ts";
@ -46,7 +47,7 @@ test(async function responseWrite() {
request.w = bufw; request.w = bufw;
await request.respond(testCase.response); await request.respond(testCase.response);
assertEqual(buf.toString(), testCase.raw); assertEq(buf.toString(), testCase.raw);
} }
}); });
@ -58,7 +59,7 @@ test(async function requestBodyWithContentLength() {
const buf = new Buffer(enc.encode("Hello")); const buf = new Buffer(enc.encode("Hello"));
req.r = new BufReader(buf); req.r = new BufReader(buf);
const body = dec.decode(await req.body()); const body = dec.decode(await req.body());
assertEqual(body, "Hello"); assertEq(body, "Hello");
} }
// Larger than internal buf // Larger than internal buf
@ -70,7 +71,7 @@ test(async function requestBodyWithContentLength() {
const buf = new Buffer(enc.encode(longText)); const buf = new Buffer(enc.encode(longText));
req.r = new BufReader(buf); req.r = new BufReader(buf);
const body = dec.decode(await req.body()); const body = dec.decode(await req.body());
assertEqual(body, longText); assertEq(body, longText);
} }
}); });
@ -95,7 +96,7 @@ test(async function requestBodyWithTransferEncoding() {
const buf = new Buffer(enc.encode(chunksData)); const buf = new Buffer(enc.encode(chunksData));
req.r = new BufReader(buf); req.r = new BufReader(buf);
const body = dec.decode(await req.body()); const body = dec.decode(await req.body());
assertEqual(body, shortText); assertEq(body, shortText);
} }
// Larger than internal buf // Larger than internal buf
@ -119,7 +120,7 @@ test(async function requestBodyWithTransferEncoding() {
const buf = new Buffer(enc.encode(chunksData)); const buf = new Buffer(enc.encode(chunksData));
req.r = new BufReader(buf); req.r = new BufReader(buf);
const body = dec.decode(await req.body()); const body = dec.decode(await req.body());
assertEqual(body, longText); assertEq(body, longText);
} }
}); });
@ -135,7 +136,7 @@ test(async function requestBodyStreamWithContentLength() {
let offset = 0; let offset = 0;
for await (const chunk of it) { for await (const chunk of it) {
const s = dec.decode(chunk); const s = dec.decode(chunk);
assertEqual(shortText.substr(offset, s.length), s); assertEq(shortText.substr(offset, s.length), s);
offset += s.length; offset += s.length;
} }
} }
@ -152,7 +153,7 @@ test(async function requestBodyStreamWithContentLength() {
let offset = 0; let offset = 0;
for await (const chunk of it) { for await (const chunk of it) {
const s = dec.decode(chunk); const s = dec.decode(chunk);
assertEqual(longText.substr(offset, s.length), s); assertEq(longText.substr(offset, s.length), s);
offset += s.length; offset += s.length;
} }
} }
@ -182,7 +183,7 @@ test(async function requestBodyStreamWithTransferEncoding() {
let offset = 0; let offset = 0;
for await (const chunk of it) { for await (const chunk of it) {
const s = dec.decode(chunk); const s = dec.decode(chunk);
assertEqual(shortText.substr(offset, s.length), s); assertEq(shortText.substr(offset, s.length), s);
offset += s.length; offset += s.length;
} }
} }
@ -211,7 +212,7 @@ test(async function requestBodyStreamWithTransferEncoding() {
let offset = 0; let offset = 0;
for await (const chunk of it) { for await (const chunk of it) {
const s = dec.decode(chunk); const s = dec.decode(chunk);
assertEqual(longText.substr(offset, s.length), s); assertEq(longText.substr(offset, s.length), s);
offset += s.length; offset += s.length;
} }
} }

View file

@ -5,7 +5,7 @@
import { Reader, ReadResult, Writer } from "deno"; import { Reader, ReadResult, Writer } from "deno";
import { charCode, copyBytes } from "./util.ts"; import { charCode, copyBytes } from "./util.ts";
import { assert } from "../testing/mod.ts"; import { assert } from "../testing/asserts.ts";
const DEFAULT_BUF_SIZE = 4096; const DEFAULT_BUF_SIZE = 4096;
const MIN_BUF_SIZE = 16; const MIN_BUF_SIZE = 16;

View file

@ -5,7 +5,8 @@
const { Buffer } = Deno; const { Buffer } = Deno;
import { Reader, ReadResult } from "deno"; import { Reader, ReadResult } from "deno";
import { test, assert, assertEqual } from "../testing/mod.ts"; import { test } from "../testing/mod.ts";
import { assert, assertEq } from "../testing/asserts.ts";
import { BufReader, BufWriter } from "./bufio.ts"; import { BufReader, BufWriter } from "./bufio.ts";
import * as iotest from "./iotest.ts"; import * as iotest from "./iotest.ts";
import { charCode, copyBytes, stringsReader } from "./util.ts"; import { charCode, copyBytes, stringsReader } from "./util.ts";
@ -31,7 +32,7 @@ test(async function bufioReaderSimple() {
const data = "hello world"; const data = "hello world";
const b = new BufReader(stringsReader(data)); const b = new BufReader(stringsReader(data));
const s = await readBytes(b); const s = await readBytes(b);
assert.equal(s, data); assertEq(s, data);
}); });
interface ReadMaker { interface ReadMaker {
@ -113,7 +114,7 @@ test(async function bufioBufReader() {
const debugStr = const debugStr =
`reader=${readmaker.name} ` + `reader=${readmaker.name} ` +
`fn=${bufreader.name} bufsize=${bufsize} want=${text} got=${s}`; `fn=${bufreader.name} bufsize=${bufsize} want=${text} got=${s}`;
assertEqual(s, text, debugStr); assertEq(s, text, debugStr);
} }
} }
} }
@ -128,12 +129,12 @@ test(async function bufioBufferFull() {
const decoder = new TextDecoder(); const decoder = new TextDecoder();
let actual = decoder.decode(line); let actual = decoder.decode(line);
assertEqual(err, "BufferFull"); assertEq(err, "BufferFull");
assertEqual(actual, "And now, hello, "); assertEq(actual, "And now, hello, ");
[line, err] = await buf.readSlice(charCode("!")); [line, err] = await buf.readSlice(charCode("!"));
actual = decoder.decode(line); actual = decoder.decode(line);
assertEqual(actual, "world!"); assertEq(actual, "world!");
assert(err == null); assert(err == null);
}); });
@ -177,20 +178,20 @@ async function testReadLine(input: Uint8Array): Promise<void> {
if (line.byteLength > 0 && err != null) { if (line.byteLength > 0 && err != null) {
throw Error("readLine returned both data and error"); throw Error("readLine returned both data and error");
} }
assertEqual(isPrefix, false); assertEq(isPrefix, false);
if (err == "EOF") { if (err == "EOF") {
break; break;
} }
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
let want = testOutput.subarray(done, done + line.byteLength); let want = testOutput.subarray(done, done + line.byteLength);
assertEqual( assertEq(
line, line,
want, want,
`Bad line at stride ${stride}: want: ${want} got: ${line}` `Bad line at stride ${stride}: want: ${want} got: ${line}`
); );
done += line.byteLength; done += line.byteLength;
} }
assertEqual( assertEq(
done, done,
testOutput.byteLength, testOutput.byteLength,
`readLine didn't return everything: got: ${done}, ` + `readLine didn't return everything: got: ${done}, ` +
@ -214,54 +215,54 @@ test(async function bufioPeek() {
); );
let [actual, err] = await buf.peek(1); let [actual, err] = await buf.peek(1);
assertEqual(decoder.decode(actual), "a"); assertEq(decoder.decode(actual), "a");
assert(err == null); assert(err == null);
[actual, err] = await buf.peek(4); [actual, err] = await buf.peek(4);
assertEqual(decoder.decode(actual), "abcd"); assertEq(decoder.decode(actual), "abcd");
assert(err == null); assert(err == null);
[actual, err] = await buf.peek(32); [actual, err] = await buf.peek(32);
assertEqual(decoder.decode(actual), "abcdefghijklmnop"); assertEq(decoder.decode(actual), "abcdefghijklmnop");
assertEqual(err, "BufferFull"); assertEq(err, "BufferFull");
await buf.read(p.subarray(0, 3)); await buf.read(p.subarray(0, 3));
assertEqual(decoder.decode(p.subarray(0, 3)), "abc"); assertEq(decoder.decode(p.subarray(0, 3)), "abc");
[actual, err] = await buf.peek(1); [actual, err] = await buf.peek(1);
assertEqual(decoder.decode(actual), "d"); assertEq(decoder.decode(actual), "d");
assert(err == null); assert(err == null);
[actual, err] = await buf.peek(1); [actual, err] = await buf.peek(1);
assertEqual(decoder.decode(actual), "d"); assertEq(decoder.decode(actual), "d");
assert(err == null); assert(err == null);
[actual, err] = await buf.peek(1); [actual, err] = await buf.peek(1);
assertEqual(decoder.decode(actual), "d"); assertEq(decoder.decode(actual), "d");
assert(err == null); assert(err == null);
[actual, err] = await buf.peek(2); [actual, err] = await buf.peek(2);
assertEqual(decoder.decode(actual), "de"); assertEq(decoder.decode(actual), "de");
assert(err == null); assert(err == null);
let { eof } = await buf.read(p.subarray(0, 3)); let { eof } = await buf.read(p.subarray(0, 3));
assertEqual(decoder.decode(p.subarray(0, 3)), "def"); assertEq(decoder.decode(p.subarray(0, 3)), "def");
assert(!eof); assert(!eof);
assert(err == null); assert(err == null);
[actual, err] = await buf.peek(4); [actual, err] = await buf.peek(4);
assertEqual(decoder.decode(actual), "ghij"); assertEq(decoder.decode(actual), "ghij");
assert(err == null); assert(err == null);
await buf.read(p); await buf.read(p);
assertEqual(decoder.decode(p), "ghijklmnop"); assertEq(decoder.decode(p), "ghijklmnop");
[actual, err] = await buf.peek(0); [actual, err] = await buf.peek(0);
assertEqual(decoder.decode(actual), ""); assertEq(decoder.decode(actual), "");
assert(err == null); assert(err == null);
[actual, err] = await buf.peek(1); [actual, err] = await buf.peek(1);
assertEqual(decoder.decode(actual), ""); assertEq(decoder.decode(actual), "");
assert(err == "EOF"); assert(err == "EOF");
/* TODO /* TODO
// Test for issue 3022, not exposing a reader's error on a successful Peek. // Test for issue 3022, not exposing a reader's error on a successful Peek.
@ -301,15 +302,15 @@ test(async function bufioWriter() {
const context = `nwrite=${nwrite} bufsize=${bs}`; const context = `nwrite=${nwrite} bufsize=${bs}`;
const n = await buf.write(data.subarray(0, nwrite)); const n = await buf.write(data.subarray(0, nwrite));
assertEqual(n, nwrite, context); assertEq(n, nwrite, context);
await buf.flush(); await buf.flush();
const written = w.bytes(); const written = w.bytes();
assertEqual(written.byteLength, nwrite); assertEq(written.byteLength, nwrite);
for (let l = 0; l < written.byteLength; l++) { for (let l = 0; l < written.byteLength; l++) {
assertEqual(written[l], data[l]); assertEq(written[l], data[l]);
} }
} }
} }
@ -324,15 +325,15 @@ test(async function bufReaderReadFull() {
{ {
const buf = new Uint8Array(6); const buf = new Uint8Array(6);
const [nread, err] = await bufr.readFull(buf); const [nread, err] = await bufr.readFull(buf);
assertEqual(nread, 6); assertEq(nread, 6);
assert(!err); assert(!err);
assertEqual(dec.decode(buf), "Hello "); assertEq(dec.decode(buf), "Hello ");
} }
{ {
const buf = new Uint8Array(6); const buf = new Uint8Array(6);
const [nread, err] = await bufr.readFull(buf); const [nread, err] = await bufr.readFull(buf);
assertEqual(nread, 5); assertEq(nread, 5);
assertEqual(err, "EOF"); assertEq(err, "EOF");
assertEqual(dec.decode(buf.subarray(0, 5)), "World"); assertEq(dec.decode(buf.subarray(0, 5)), "World");
} }
}); });

View file

@ -1,7 +1,7 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { BufReader } from "./bufio.ts"; import { BufReader } from "./bufio.ts";
import { Reader, Writer } from "deno"; import { Reader, Writer } from "deno";
import { assert } from "../testing/mod.ts"; import { assert } from "../testing/asserts.ts";
/** copy N size at the most. If read size is lesser than N, then returns nread */ /** copy N size at the most. If read size is lesser than N, then returns nread */
export async function copyN( export async function copyN(
@ -19,7 +19,7 @@ export async function copyN(
bytesRead += nread; bytesRead += nread;
if (nread > 0) { if (nread > 0) {
const n = await dest.write(buf.slice(0, nread)); const n = await dest.write(buf.slice(0, nread));
assert.assert(n === nread, "could not write"); assert(n === nread, "could not write");
} }
if (eof) { if (eof) {
break; break;

View file

@ -1,7 +1,8 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
const { Buffer } = Deno; const { Buffer } = Deno;
import { Reader, ReadResult } from "deno"; import { Reader, ReadResult } from "deno";
import { assert, assertEqual, test } from "../testing/mod.ts"; import { test } from "../testing/mod.ts";
import { assertEq } from "../testing/asserts.ts";
import { import {
copyN, copyN,
readInt, readInt,
@ -27,13 +28,13 @@ class BinaryReader implements Reader {
test(async function testReadShort() { test(async function testReadShort() {
const r = new BinaryReader(new Uint8Array([0x12, 0x34])); const r = new BinaryReader(new Uint8Array([0x12, 0x34]));
const short = await readShort(new BufReader(r)); const short = await readShort(new BufReader(r));
assertEqual(short, 0x1234); assertEq(short, 0x1234);
}); });
test(async function testReadInt() { test(async function testReadInt() {
const r = new BinaryReader(new Uint8Array([0x12, 0x34, 0x56, 0x78])); const r = new BinaryReader(new Uint8Array([0x12, 0x34, 0x56, 0x78]));
const int = await readInt(new BufReader(r)); const int = await readInt(new BufReader(r));
assertEqual(int, 0x12345678); assertEq(int, 0x12345678);
}); });
test(async function testReadLong() { test(async function testReadLong() {
@ -41,7 +42,7 @@ test(async function testReadLong() {
new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78]) new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78])
); );
const long = await readLong(new BufReader(r)); const long = await readLong(new BufReader(r));
assertEqual(long, 0x1234567812345678); assertEq(long, 0x1234567812345678);
}); });
test(async function testReadLong2() { test(async function testReadLong2() {
@ -49,7 +50,7 @@ test(async function testReadLong2() {
new Uint8Array([0, 0, 0, 0, 0x12, 0x34, 0x56, 0x78]) new Uint8Array([0, 0, 0, 0, 0x12, 0x34, 0x56, 0x78])
); );
const long = await readLong(new BufReader(r)); const long = await readLong(new BufReader(r));
assertEqual(long, 0x12345678); assertEq(long, 0x12345678);
}); });
test(async function testSliceLongToBytes() { test(async function testSliceLongToBytes() {
@ -62,26 +63,26 @@ test(async function testSliceLongToBytes() {
) )
) )
); );
assertEqual(actual, expected); assertEq(actual, expected);
}); });
test(async function testSliceLongToBytes2() { test(async function testSliceLongToBytes2() {
const arr = sliceLongToBytes(0x12345678); const arr = sliceLongToBytes(0x12345678);
assertEqual(arr, [0, 0, 0, 0, 0x12, 0x34, 0x56, 0x78]); assertEq(arr, [0, 0, 0, 0, 0x12, 0x34, 0x56, 0x78]);
}); });
test(async function testCopyN1() { test(async function testCopyN1() {
const w = new Buffer(); const w = new Buffer();
const r = stringsReader("abcdefghij"); const r = stringsReader("abcdefghij");
const n = await copyN(w, r, 3); const n = await copyN(w, r, 3);
assert.equal(n, 3); assertEq(n, 3);
assert.equal(w.toString(), "abc"); assertEq(w.toString(), "abc");
}); });
test(async function testCopyN2() { test(async function testCopyN2() {
const w = new Buffer(); const w = new Buffer();
const r = stringsReader("abcdefghij"); const r = stringsReader("abcdefghij");
const n = await copyN(w, r, 11); const n = await copyN(w, r, 11);
assert.equal(n, 10); assertEq(n, 10);
assert.equal(w.toString(), "abcdefghij"); assertEq(w.toString(), "abcdefghij");
}); });

View file

@ -1,5 +1,6 @@
const { copy } = Deno; const { copy } = Deno;
import { assert, test } from "../testing/mod.ts"; import { test } from "../testing/mod.ts";
import { assertEq } from "../testing/asserts.ts";
import { MultiReader, StringReader } from "./readers.ts"; import { MultiReader, StringReader } from "./readers.ts";
import { StringWriter } from "./writers.ts"; import { StringWriter } from "./writers.ts";
import { copyN } from "./ioutil.ts"; import { copyN } from "./ioutil.ts";
@ -8,29 +9,29 @@ import { decode } from "../strings/strings.ts";
test(async function ioStringReader() { test(async function ioStringReader() {
const r = new StringReader("abcdef"); const r = new StringReader("abcdef");
const { nread, eof } = await r.read(new Uint8Array(6)); const { nread, eof } = await r.read(new Uint8Array(6));
assert.equal(nread, 6); assertEq(nread, 6);
assert.equal(eof, true); assertEq(eof, true);
}); });
test(async function ioStringReader() { test(async function ioStringReader() {
const r = new StringReader("abcdef"); const r = new StringReader("abcdef");
const buf = new Uint8Array(3); const buf = new Uint8Array(3);
let res1 = await r.read(buf); let res1 = await r.read(buf);
assert.equal(res1.nread, 3); assertEq(res1.nread, 3);
assert.equal(res1.eof, false); assertEq(res1.eof, false);
assert.equal(decode(buf), "abc"); assertEq(decode(buf), "abc");
let res2 = await r.read(buf); let res2 = await r.read(buf);
assert.equal(res2.nread, 3); assertEq(res2.nread, 3);
assert.equal(res2.eof, true); assertEq(res2.eof, true);
assert.equal(decode(buf), "def"); assertEq(decode(buf), "def");
}); });
test(async function ioMultiReader() { test(async function ioMultiReader() {
const r = new MultiReader(new StringReader("abc"), new StringReader("def")); const r = new MultiReader(new StringReader("abc"), new StringReader("def"));
const w = new StringWriter(); const w = new StringWriter();
const n = await copyN(w, r, 4); const n = await copyN(w, r, 4);
assert.equal(n, 4); assertEq(n, 4);
assert.equal(w.toString(), "abcd"); assertEq(w.toString(), "abcd");
await copy(w, r); await copy(w, r);
assert.equal(w.toString(), "abcdef"); assertEq(w.toString(), "abcdef");
}); });

View file

@ -1,6 +1,7 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
const { remove } = Deno; const { remove } = Deno;
import { test, assert } from "../testing/mod.ts"; import { test } from "../testing/mod.ts";
import { assert, assertEq } from "../testing/asserts.ts";
import { copyBytes, tempFile } from "./util.ts"; import { copyBytes, tempFile } from "./util.ts";
import * as path from "../fs/path.ts"; import * as path from "../fs/path.ts";
@ -11,31 +12,31 @@ test(function testCopyBytes() {
let src = Uint8Array.of(1, 2); let src = Uint8Array.of(1, 2);
let len = copyBytes(dst, src, 0); let len = copyBytes(dst, src, 0);
assert(len === 2); assert(len === 2);
assert.equal(dst, Uint8Array.of(1, 2, 0, 0)); assertEq(dst, Uint8Array.of(1, 2, 0, 0));
dst.fill(0); dst.fill(0);
src = Uint8Array.of(1, 2); src = Uint8Array.of(1, 2);
len = copyBytes(dst, src, 1); len = copyBytes(dst, src, 1);
assert(len === 2); assert(len === 2);
assert.equal(dst, Uint8Array.of(0, 1, 2, 0)); assertEq(dst, Uint8Array.of(0, 1, 2, 0));
dst.fill(0); dst.fill(0);
src = Uint8Array.of(1, 2, 3, 4, 5); src = Uint8Array.of(1, 2, 3, 4, 5);
len = copyBytes(dst, src); len = copyBytes(dst, src);
assert(len === 4); assert(len === 4);
assert.equal(dst, Uint8Array.of(1, 2, 3, 4)); assertEq(dst, Uint8Array.of(1, 2, 3, 4));
dst.fill(0); dst.fill(0);
src = Uint8Array.of(1, 2); src = Uint8Array.of(1, 2);
len = copyBytes(dst, src, 100); len = copyBytes(dst, src, 100);
assert(len === 0); assert(len === 0);
assert.equal(dst, Uint8Array.of(0, 0, 0, 0)); assertEq(dst, Uint8Array.of(0, 0, 0, 0));
dst.fill(0); dst.fill(0);
src = Uint8Array.of(3, 4); src = Uint8Array.of(3, 4);
len = copyBytes(dst, src, -2); len = copyBytes(dst, src, -2);
assert(len === 2); assert(len === 2);
assert.equal(dst, Uint8Array.of(3, 4, 0, 0)); assertEq(dst, Uint8Array.of(3, 4, 0, 0));
}); });
test(async function ioTempfile() { test(async function ioTempfile() {
@ -45,6 +46,6 @@ test(async function ioTempfile() {
}); });
console.log(f.file, f.filepath); console.log(f.file, f.filepath);
const base = path.basename(f.filepath); const base = path.basename(f.filepath);
assert.assert(!!base.match(/^prefix-.+?-postfix$/)); assert(!!base.match(/^prefix-.+?-postfix$/));
await remove(f.filepath); await remove(f.filepath);
}); });

View file

@ -1,5 +1,6 @@
const { copy } = Deno; const { copy } = Deno;
import { assert, test } from "../testing/mod.ts"; import { test } from "../testing/mod.ts";
import { assertEq } from "../testing/asserts.ts";
import { StringWriter } from "./writers.ts"; import { StringWriter } from "./writers.ts";
import { StringReader } from "./readers.ts"; import { StringReader } from "./readers.ts";
import { copyN } from "./ioutil.ts"; import { copyN } from "./ioutil.ts";
@ -8,7 +9,7 @@ test(async function ioStringWriter() {
const w = new StringWriter("base"); const w = new StringWriter("base");
const r = new StringReader("0123456789"); const r = new StringReader("0123456789");
await copyN(w, r, 4); await copyN(w, r, 4);
assert.equal(w.toString(), "base0123"); assertEq(w.toString(), "base0123");
await copy(w, r); await copy(w, r);
assert.equal(w.toString(), "base0123456789"); assertEq(w.toString(), "base0123456789");
}); });

View file

@ -1,5 +1,6 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { assertEqual, test } from "../testing/mod.ts"; import { test } from "../testing/mod.ts";
import { assertEq } from "../testing/asserts.ts";
import { LogLevel, getLevelName, getLevelByName } from "./levels.ts"; import { LogLevel, getLevelName, getLevelByName } from "./levels.ts";
import { BaseHandler } from "./handlers.ts"; import { BaseHandler } from "./handlers.ts";
@ -55,9 +56,9 @@ test(function simpleHandler() {
}); });
} }
assertEqual(handler.level, testCase); assertEq(handler.level, testCase);
assertEqual(handler.levelName, testLevel); assertEq(handler.levelName, testLevel);
assertEqual(handler.messages, messages); assertEq(handler.messages, messages);
} }
}); });
@ -74,7 +75,7 @@ test(function testFormatterAsString() {
levelName: "DEBUG" levelName: "DEBUG"
}); });
assertEqual(handler.messages, ["test DEBUG Hello, world!"]); assertEq(handler.messages, ["test DEBUG Hello, world!"]);
}); });
test(function testFormatterAsFunction() { test(function testFormatterAsFunction() {
@ -91,5 +92,5 @@ test(function testFormatterAsFunction() {
levelName: "ERROR" levelName: "ERROR"
}); });
assertEqual(handler.messages, ["fn formmatter ERROR Hello, world!"]); assertEq(handler.messages, ["fn formmatter ERROR Hello, world!"]);
}); });

View file

@ -1,5 +1,6 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { assertEqual, test } from "../testing/mod.ts"; import { test } from "../testing/mod.ts";
import { assertEq } from "../testing/asserts.ts";
import { LogRecord, Logger } from "./logger.ts"; import { LogRecord, Logger } from "./logger.ts";
import { LogLevel } from "./levels.ts"; import { LogLevel } from "./levels.ts";
import { BaseHandler } from "./handlers.ts"; import { BaseHandler } from "./handlers.ts";
@ -22,13 +23,13 @@ test(function simpleLogger() {
const handler = new TestHandler("DEBUG"); const handler = new TestHandler("DEBUG");
let logger = new Logger("DEBUG"); let logger = new Logger("DEBUG");
assertEqual(logger.level, LogLevel.DEBUG); assertEq(logger.level, LogLevel.DEBUG);
assertEqual(logger.levelName, "DEBUG"); assertEq(logger.levelName, "DEBUG");
assertEqual(logger.handlers, []); assertEq(logger.handlers, []);
logger = new Logger("DEBUG", [handler]); logger = new Logger("DEBUG", [handler]);
assertEqual(logger.handlers, [handler]); assertEq(logger.handlers, [handler]);
}); });
test(function customHandler() { test(function customHandler() {
@ -37,7 +38,7 @@ test(function customHandler() {
logger.debug("foo", 1, 2); logger.debug("foo", 1, 2);
assertEqual(handler.records, [ assertEq(handler.records, [
{ {
msg: "foo", msg: "foo",
args: [1, 2], args: [1, 2],
@ -47,7 +48,7 @@ test(function customHandler() {
} }
]); ]);
assertEqual(handler.messages, ["DEBUG foo"]); assertEq(handler.messages, ["DEBUG foo"]);
}); });
test(function logFunctions() { test(function logFunctions() {
@ -65,7 +66,7 @@ test(function logFunctions() {
doLog("DEBUG"); doLog("DEBUG");
assertEqual(handler.messages, [ assertEq(handler.messages, [
"DEBUG foo", "DEBUG foo",
"INFO bar", "INFO bar",
"WARNING baz", "WARNING baz",
@ -75,7 +76,7 @@ test(function logFunctions() {
doLog("INFO"); doLog("INFO");
assertEqual(handler.messages, [ assertEq(handler.messages, [
"INFO bar", "INFO bar",
"WARNING baz", "WARNING baz",
"ERROR boo", "ERROR boo",
@ -84,13 +85,13 @@ test(function logFunctions() {
doLog("WARNING"); doLog("WARNING");
assertEqual(handler.messages, ["WARNING baz", "ERROR boo", "CRITICAL doo"]); assertEq(handler.messages, ["WARNING baz", "ERROR boo", "CRITICAL doo"]);
doLog("ERROR"); doLog("ERROR");
assertEqual(handler.messages, ["ERROR boo", "CRITICAL doo"]); assertEq(handler.messages, ["ERROR boo", "CRITICAL doo"]);
doLog("CRITICAL"); doLog("CRITICAL");
assertEqual(handler.messages, ["CRITICAL doo"]); assertEq(handler.messages, ["CRITICAL doo"]);
}); });

View file

@ -1,5 +1,6 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { assertEqual, test } from "../testing/mod.ts"; import { test } from "../testing/mod.ts";
import { assertEq } from "../testing/asserts.ts";
import * as log from "./mod.ts"; import * as log from "./mod.ts";
import { LogLevel } from "./levels.ts"; import { LogLevel } from "./levels.ts";
@ -54,7 +55,7 @@ test(async function defaultHandlers() {
logger("foo"); logger("foo");
logger("bar", 1, 2); logger("bar", 1, 2);
assertEqual(handler.messages, [`${levelName} foo`, `${levelName} bar`]); assertEq(handler.messages, [`${levelName} foo`, `${levelName} bar`]);
} }
}); });
@ -75,8 +76,8 @@ test(async function getLogger() {
const logger = log.getLogger(); const logger = log.getLogger();
assertEqual(logger.levelName, "DEBUG"); assertEq(logger.levelName, "DEBUG");
assertEqual(logger.handlers, [handler]); assertEq(logger.handlers, [handler]);
}); });
test(async function getLoggerWithName() { test(async function getLoggerWithName() {
@ -96,8 +97,8 @@ test(async function getLoggerWithName() {
const logger = log.getLogger("bar"); const logger = log.getLogger("bar");
assertEqual(logger.levelName, "INFO"); assertEq(logger.levelName, "INFO");
assertEqual(logger.handlers, [fooHandler]); assertEq(logger.handlers, [fooHandler]);
}); });
test(async function getLoggerUnknown() { test(async function getLoggerUnknown() {
@ -108,6 +109,6 @@ test(async function getLoggerUnknown() {
const logger = log.getLogger("nonexistent"); const logger = log.getLogger("nonexistent");
assertEqual(logger.levelName, "NOTSET"); assertEq(logger.levelName, "NOTSET");
assertEqual(logger.handlers, []); assertEq(logger.handlers, []);
}); });

View file

@ -1,6 +1,7 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { assertEqual, test } from "../testing/mod.ts"; import { test } from "../testing/mod.ts";
import { assertEq } from "../testing/asserts.ts";
import { import {
lookup, lookup,
contentType, contentType,
@ -11,40 +12,40 @@ import {
} from "./mod.ts"; } from "./mod.ts";
test(function testLookup() { test(function testLookup() {
assertEqual(lookup("json"), "application/json"); assertEq(lookup("json"), "application/json");
assertEqual(lookup(".md"), "text/markdown"); assertEq(lookup(".md"), "text/markdown");
assertEqual(lookup("folder/file.js"), "application/javascript"); assertEq(lookup("folder/file.js"), "application/javascript");
assertEqual(lookup("folder/.htaccess"), undefined); assertEq(lookup("folder/.htaccess"), undefined);
}); });
test(function testContentType() { test(function testContentType() {
assertEqual(contentType("markdown"), "text/markdown; charset=utf-8"); assertEq(contentType("markdown"), "text/markdown; charset=utf-8");
assertEqual(contentType("file.json"), "application/json; charset=utf-8"); assertEq(contentType("file.json"), "application/json; charset=utf-8");
assertEqual(contentType("text/html"), "text/html; charset=utf-8"); assertEq(contentType("text/html"), "text/html; charset=utf-8");
assertEqual( assertEq(
contentType("text/html; charset=iso-8859-1"), contentType("text/html; charset=iso-8859-1"),
"text/html; charset=iso-8859-1" "text/html; charset=iso-8859-1"
); );
assertEqual(contentType(".htaccess"), undefined); assertEq(contentType(".htaccess"), undefined);
}); });
test(function testExtension() { test(function testExtension() {
assertEqual(extension("application/octet-stream"), "bin"); assertEq(extension("application/octet-stream"), "bin");
assertEqual(extension("application/javascript"), "js"); assertEq(extension("application/javascript"), "js");
assertEqual(extension("text/html"), "html"); assertEq(extension("text/html"), "html");
}); });
test(function testCharset() { test(function testCharset() {
assertEqual(charset("text/markdown"), "UTF-8"); assertEq(charset("text/markdown"), "UTF-8");
assertEqual(charset("text/css"), "UTF-8"); assertEq(charset("text/css"), "UTF-8");
}); });
test(function testExtensions() { test(function testExtensions() {
assertEqual(extensions.get("application/javascript"), ["js", "mjs"]); assertEq(extensions.get("application/javascript"), ["js", "mjs"]);
assertEqual(extensions.get("foo"), undefined); assertEq(extensions.get("foo"), undefined);
}); });
test(function testTypes() { test(function testTypes() {
assertEqual(types.get("js"), "application/javascript"); assertEq(types.get("js"), "application/javascript");
assertEqual(types.get("foo"), undefined); assertEq(types.get("foo"), undefined);
}); });

View file

@ -1,16 +1,17 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { assert, test } from "../testing/mod.ts"; import { test } from "../testing/mod.ts";
import { assertEq } from "../testing/asserts.ts";
import { isFormFile } from "./formfile.ts"; import { isFormFile } from "./formfile.ts";
test(function multipartIsFormFile() { test(function multipartIsFormFile() {
assert.equal( assertEq(
isFormFile({ isFormFile({
filename: "foo", filename: "foo",
type: "application/json" type: "application/json"
}), }),
true true
); );
assert.equal( assertEq(
isFormFile({ isFormFile({
filename: "foo" filename: "foo"
}), }),

View file

@ -1,7 +1,13 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
const { Buffer, copy, open, remove } = Deno; const { Buffer, copy, open, remove } = Deno;
import { assert, test } from "../testing/mod.ts"; import {
assert,
assertEq,
assertThrows,
assertThrowsAsync
} from "../testing/asserts.ts";
import { test } from "../testing/mod.ts";
import { import {
matchAfterPrefix, matchAfterPrefix,
MultipartReader, MultipartReader,
@ -26,8 +32,8 @@ test(function multipartScanUntilBoundary1() {
0, 0,
"EOF" "EOF"
); );
assert.equal(n, 0); assertEq(n, 0);
assert.equal(err, "EOF"); assertEq(err, "EOF");
}); });
test(function multipartScanUntilBoundary2() { test(function multipartScanUntilBoundary2() {
@ -39,8 +45,8 @@ test(function multipartScanUntilBoundary2() {
0, 0,
"EOF" "EOF"
); );
assert.equal(n, 3); assertEq(n, 3);
assert.equal(err, "EOF"); assertEq(err, "EOF");
}); });
test(function multipartScanUntilBoundary4() { test(function multipartScanUntilBoundary4() {
@ -52,8 +58,8 @@ test(function multipartScanUntilBoundary4() {
0, 0,
null null
); );
assert.equal(n, 3); assertEq(n, 3);
assert.equal(err, null); assertEq(err, null);
}); });
test(function multipartScanUntilBoundary3() { test(function multipartScanUntilBoundary3() {
@ -65,26 +71,26 @@ test(function multipartScanUntilBoundary3() {
0, 0,
null null
); );
assert.equal(n, data.length); assertEq(n, data.length);
assert.equal(err, null); assertEq(err, null);
}); });
test(function multipartMatchAfterPrefix1() { test(function multipartMatchAfterPrefix1() {
const data = `${boundary}\r`; const data = `${boundary}\r`;
const v = matchAfterPrefix(e.encode(data), e.encode(boundary), null); const v = matchAfterPrefix(e.encode(data), e.encode(boundary), null);
assert.equal(v, 1); assertEq(v, 1);
}); });
test(function multipartMatchAfterPrefix2() { test(function multipartMatchAfterPrefix2() {
const data = `${boundary}hoge`; const data = `${boundary}hoge`;
const v = matchAfterPrefix(e.encode(data), e.encode(boundary), null); const v = matchAfterPrefix(e.encode(data), e.encode(boundary), null);
assert.equal(v, -1); assertEq(v, -1);
}); });
test(function multipartMatchAfterPrefix3() { test(function multipartMatchAfterPrefix3() {
const data = `${boundary}`; const data = `${boundary}`;
const v = matchAfterPrefix(e.encode(data), e.encode(boundary), null); const v = matchAfterPrefix(e.encode(data), e.encode(boundary), null);
assert.equal(v, 0); assertEq(v, 0);
}); });
test(async function multipartMultipartWriter() { test(async function multipartMultipartWriter() {
@ -99,12 +105,12 @@ test(async function multipartMultipartWriter() {
test(function multipartMultipartWriter2() { test(function multipartMultipartWriter2() {
const w = new StringWriter(); const w = new StringWriter();
assert.throws( assertThrows(
() => new MultipartWriter(w, ""), () => new MultipartWriter(w, ""),
Error, Error,
"invalid boundary length" "invalid boundary length"
); );
assert.throws( assertThrows(
() => () =>
new MultipartWriter( new MultipartWriter(
w, w,
@ -113,12 +119,12 @@ test(function multipartMultipartWriter2() {
Error, Error,
"invalid boundary length" "invalid boundary length"
); );
assert.throws( assertThrows(
() => new MultipartWriter(w, "aaa aaa"), () => new MultipartWriter(w, "aaa aaa"),
Error, Error,
"invalid boundary character" "invalid boundary character"
); );
assert.throws( assertThrows(
() => new MultipartWriter(w, "boundary¥¥"), () => new MultipartWriter(w, "boundary¥¥"),
Error, Error,
"invalid boundary character" "invalid boundary character"
@ -130,35 +136,35 @@ test(async function multipartMultipartWriter3() {
const mw = new MultipartWriter(w); const mw = new MultipartWriter(w);
await mw.writeField("foo", "foo"); await mw.writeField("foo", "foo");
await mw.close(); await mw.close();
await assert.throwsAsync( await assertThrowsAsync(
async () => { async () => {
await mw.close(); await mw.close();
}, },
Error, Error,
"closed" "closed"
); );
await assert.throwsAsync( await assertThrowsAsync(
async () => { async () => {
await mw.writeFile("bar", "file", null); await mw.writeFile("bar", "file", null);
}, },
Error, Error,
"closed" "closed"
); );
await assert.throwsAsync( await assertThrowsAsync(
async () => { async () => {
await mw.writeField("bar", "bar"); await mw.writeField("bar", "bar");
}, },
Error, Error,
"closed" "closed"
); );
assert.throws( assertThrows(
() => { () => {
mw.createFormField("bar"); mw.createFormField("bar");
}, },
Error, Error,
"closed" "closed"
); );
assert.throws( assertThrows(
() => { () => {
mw.createFormFile("bar", "file"); mw.createFormFile("bar", "file");
}, },
@ -175,11 +181,11 @@ test(async function multipartMultipartReader() {
"--------------------------434049563556637648550474" "--------------------------434049563556637648550474"
); );
const form = await mr.readForm(10 << 20); const form = await mr.readForm(10 << 20);
assert.equal(form["foo"], "foo"); assertEq(form["foo"], "foo");
assert.equal(form["bar"], "bar"); assertEq(form["bar"], "bar");
const file = form["file"] as FormFile; const file = form["file"] as FormFile;
assert.equal(isFormFile(file), true); assertEq(isFormFile(file), true);
assert.assert(file.content !== void 0); assert(file.content !== void 0);
}); });
test(async function multipartMultipartReader2() { test(async function multipartMultipartReader2() {
@ -190,15 +196,15 @@ test(async function multipartMultipartReader2() {
); );
const form = await mr.readForm(20); // const form = await mr.readForm(20); //
try { try {
assert.equal(form["foo"], "foo"); assertEq(form["foo"], "foo");
assert.equal(form["bar"], "bar"); assertEq(form["bar"], "bar");
const file = form["file"] as FormFile; const file = form["file"] as FormFile;
assert.equal(file.type, "application/octet-stream"); assertEq(file.type, "application/octet-stream");
const f = await open(file.tempfile); const f = await open(file.tempfile);
const w = new StringWriter(); const w = new StringWriter();
await copy(w, f); await copy(w, f);
const json = JSON.parse(w.toString()); const json = JSON.parse(w.toString());
assert.equal(json["compilerOptions"]["target"], "es2018"); assertEq(json["compilerOptions"]["target"], "es2018");
f.close(); f.close();
} finally { } finally {
const file = form["file"] as FormFile; const file = form["file"] as FormFile;

View file

@ -1,6 +1,7 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { test, assertEqual } from "../testing/mod.ts"; import { test } from "../testing/mod.ts";
import { xrun, executableSuffix } from "./util.ts"; import { xrun, executableSuffix } from "./util.ts";
import { assertEq } from "../testing/asserts.ts";
const { readAll } = Deno; const { readAll } = Deno;
const decoder = new TextDecoder(); const decoder = new TextDecoder();
@ -45,20 +46,20 @@ test(async function testPrettierCheckAndFormatFiles() {
const files = [`${testdata}/0.ts`, `${testdata}/1.js`]; const files = [`${testdata}/0.ts`, `${testdata}/1.js`];
var { code, stdout } = await run([...cmd, "--check", ...files]); var { code, stdout } = await run([...cmd, "--check", ...files]);
assertEqual(code, 1); assertEq(code, 1);
assertEqual(normalizeOutput(stdout), "Some files are not formatted"); assertEq(normalizeOutput(stdout), "Some files are not formatted");
var { code, stdout } = await run([...cmd, ...files]); var { code, stdout } = await run([...cmd, ...files]);
assertEqual(code, 0); assertEq(code, 0);
assertEqual( assertEq(
normalizeOutput(stdout), normalizeOutput(stdout),
`Formatting prettier/testdata/0.ts `Formatting prettier/testdata/0.ts
Formatting prettier/testdata/1.js` Formatting prettier/testdata/1.js`
); );
var { code, stdout } = await run([...cmd, "--check", ...files]); var { code, stdout } = await run([...cmd, "--check", ...files]);
assertEqual(code, 0); assertEq(code, 0);
assertEqual(normalizeOutput(stdout), "Every file is formatted"); assertEq(normalizeOutput(stdout), "Every file is formatted");
await clearTestdataChanges(); await clearTestdataChanges();
}); });
@ -69,12 +70,12 @@ test(async function testPrettierCheckAndFormatDirs() {
const dirs = [`${testdata}/foo`, `${testdata}/bar`]; const dirs = [`${testdata}/foo`, `${testdata}/bar`];
var { code, stdout } = await run([...cmd, "--check", ...dirs]); var { code, stdout } = await run([...cmd, "--check", ...dirs]);
assertEqual(code, 1); assertEq(code, 1);
assertEqual(normalizeOutput(stdout), "Some files are not formatted"); assertEq(normalizeOutput(stdout), "Some files are not formatted");
var { code, stdout } = await run([...cmd, ...dirs]); var { code, stdout } = await run([...cmd, ...dirs]);
assertEqual(code, 0); assertEq(code, 0);
assertEqual( assertEq(
normalizeOutput(stdout), normalizeOutput(stdout),
`Formatting prettier/testdata/bar/0.ts `Formatting prettier/testdata/bar/0.ts
Formatting prettier/testdata/bar/1.js Formatting prettier/testdata/bar/1.js
@ -83,8 +84,8 @@ Formatting prettier/testdata/foo/1.js`
); );
var { code, stdout } = await run([...cmd, "--check", ...dirs]); var { code, stdout } = await run([...cmd, "--check", ...dirs]);
assertEqual(code, 0); assertEq(code, 0);
assertEqual(normalizeOutput(stdout), "Every file is formatted"); assertEq(normalizeOutput(stdout), "Every file is formatted");
await clearTestdataChanges(); await clearTestdataChanges();
}); });

File diff suppressed because one or more lines are too long

View file

@ -11,53 +11,38 @@ contains a `name` property and a `fn` property. When running tests and
outputting the results, the name of the past function is used, or if the outputting the results, the name of the past function is used, or if the
object is passed, the `name` property is used to identify the test. object is passed, the `name` property is used to identify the test.
The module also exports `assert`, `assertEqual`, and `equal`. Asserts are exposed in `testing/asserts.ts` module.
`equal` is a deep comparision function, where `actual` and `expected` are
compared deeply, and if they vary, `equal` returns `false`.
The export `assert` is a function, but it is also decorated with other useful
functions:
- `equal` - Deep comparision function, where `actual` and `expected` are
compared deeply, and if they vary, `equal` returns `false`.
- `assert()` - Expects a boolean value, throws if the value is `false`. - `assert()` - Expects a boolean value, throws if the value is `false`.
- `assert.equal()` - Uses the `equal` comparison and throws if the `actual` and - `assertEq()` - Uses the `equal` comparison and throws if the `actual` and
`expected` are not equal. `expected` are not equal.
- `assert.strictEqual()` - Compares `actual` and `expected` strictly, therefore - `assertStrictEq()` - Compares `actual` and `expected` strictly, therefore
for non-primitives the values must reference the same instance. for non-primitives the values must reference the same instance.
- `assert.throws()` - Expects the passed `fn` to throw. If `fn` does not throw, - `assertThrows()` - Expects the passed `fn` to throw. If `fn` does not throw,
this function does. Also compares any errors thrown to an optional expected this function does. Also compares any errors thrown to an optional expected
`Error` class and checks that the error `.message` includes an optional `Error` class and checks that the error `.message` includes an optional
string. string.
- `assert.throwsAsync()` - Expects the passed `fn` to be async and throw (or - `assertThrowsAsync()` - Expects the passed `fn` to be async and throw (or
return a `Promise` that rejects). If the `fn` does not throw or reject, this return a `Promise` that rejects). If the `fn` does not throw or reject, this
function will throw asynchronously. Also compares any errors thrown to an function will throw asynchronously. Also compares any errors thrown to an
optional expected `Error` class and checks that the error `.message` includes optional expected `Error` class and checks that the error `.message` includes
an optional string. an optional string.
`assertEqual()` is the same as `assert.equal()` but maintained for backwards
compatibility.
`runTests()` executes the declared tests. `runTests()` executes the declared tests.
Basic usage: Basic usage:
```ts ```ts
import { import { runTests, test } from "https://deno.land/std/testing/mod.ts";
runTests, import { assertEq } from "https://deno.land/std/testing/asserts.ts";
test,
assert,
equal
} from "https://deno.land/std/testing/mod.ts";
test({ test({
name: "testing example", name: "testing example",
fn() { fn() {
assert(equal("world", "world")); assertEq("world", "world"));
assert(!equal("hello", "world")); assertEq({ hello: "world" }, { hello: "world" }));
assert(equal({ hello: "world" }, { hello: "world" }));
assert(!equal({ world: "hello" }, { hello: "world" }));
assert.equal("world", "world");
assert.equal({ hello: "world" }, { hello: "world" });
} }
}); });
@ -68,43 +53,39 @@ Short syntax (named function instead of object):
```ts ```ts
test(function example() { test(function example() {
assert(equal("world", "world")); assertEq("world", "world"));
assert(!equal("hello", "world")); assertEq({ hello: "world" }, { hello: "world" }));
assert(equal({ hello: "world" }, { hello: "world" }));
assert(!equal({ world: "hello" }, { hello: "world" }));
assert.equal("world", "world");
assert.equal({ hello: "world" }, { hello: "world" });
}); });
``` ```
Using `assert.strictEqual()`: Using `assertStrictEq()`:
```ts ```ts
test(function isStrictlyEqual() { test(function isStrictlyEqual() {
const a = {}; const a = {};
const b = a; const b = a;
assert.strictEqual(a, b); assertStrictEq(a, b);
}); });
// This test fails // This test fails
test(function isNotStrictlyEqual() { test(function isNotStrictlyEqual() {
const a = {}; const a = {};
const b = {}; const b = {};
assert.strictEqual(a, b); assertStrictEq(a, b);
}); });
``` ```
Using `assert.throws()`: Using `assertThrows()`:
```ts ```ts
test(function doesThrow() { test(function doesThrow() {
assert.throws(() => { assertThrows(() => {
throw new TypeError("hello world!"); throw new TypeError("hello world!");
}); });
assert.throws(() => { assertThrows(() => {
throw new TypeError("hello world!"); throw new TypeError("hello world!");
}, TypeError); }, TypeError);
assert.throws( assertThrows(
() => { () => {
throw new TypeError("hello world!"); throw new TypeError("hello world!");
}, },
@ -115,37 +96,37 @@ test(function doesThrow() {
// This test will not pass // This test will not pass
test(function fails() { test(function fails() {
assert.throws(() => { assertThrows(() => {
console.log("Hello world"); console.log("Hello world");
}); });
}); });
``` ```
Using `assert.throwsAsync()`: Using `assertThrowsAsync()`:
```ts ```ts
test(async function doesThrow() { test(async function doesThrow() {
assert.throwsAsync(async () => { assertThrowsAsync(async () => {
throw new TypeError("hello world!"); throw new TypeError("hello world!");
}); });
assert.throwsAsync(async () => { assertThrowsAsync(async () => {
throw new TypeError("hello world!"); throw new TypeError("hello world!");
}, TypeError); }, TypeError);
assert.throwsAsync( assertThrowsAsync(
async () => { async () => {
throw new TypeError("hello world!"); throw new TypeError("hello world!");
}, },
TypeError, TypeError,
"hello" "hello"
); );
assert.throwsAsync(async () => { assertThrowsAsync(async () => {
return Promise.reject(new Error()); return Promise.reject(new Error());
}); });
}); });
// This test will not pass // This test will not pass
test(async function fails() { test(async function fails() {
assert.throwsAsync(async () => { assertThrowsAsync(async () => {
console.log("Hello world"); console.log("Hello world");
}); });
}); });

View file

@ -1,11 +1,38 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { assertEqual as prettyAssertEqual } from "./pretty.ts"; import { assertEq as prettyAssertEqual } from "./pretty.ts";
interface Constructor { interface Constructor {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
new (...args: any[]): any; new (...args: any[]): any;
} }
export function equal(c: unknown, d: unknown): boolean {
const seen = new Map();
return (function compare(a: unknown, b: unknown) {
if (Object.is(a, b)) {
return true;
}
if (a && typeof a === "object" && b && typeof b === "object") {
if (seen.get(a) === b) {
return true;
}
if (Object.keys(a || {}).length !== Object.keys(b || {}).length) {
return false;
}
const merged = { ...a, ...b };
for (const key in merged) {
type Key = keyof typeof merged;
if (!compare(a && a[key as Key], b && b[key as Key])) {
return false;
}
}
seen.set(a, b);
return true;
}
return false;
})(c, d);
}
/** Make an assertion, if not `true`, then throw. */ /** Make an assertion, if not `true`, then throw. */
export function assert(expr: boolean, msg = ""): void { export function assert(expr: boolean, msg = ""): void {
if (!expr) { if (!expr) {
@ -17,7 +44,11 @@ export function assert(expr: boolean, msg = ""): void {
* Make an assertion that `actual` and `expected` are equal, deeply. If not * Make an assertion that `actual` and `expected` are equal, deeply. If not
* deeply equal, then throw. * deeply equal, then throw.
*/ */
export function equal(actual: unknown, expected: unknown, msg?: string): void { export function assertEq(
actual: unknown,
expected: unknown,
msg?: string
): void {
prettyAssertEqual(actual, expected, msg); prettyAssertEqual(actual, expected, msg);
} }

View file

@ -1,12 +1,34 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { assertStrContains, assertMatch } from "./asserts.ts"; import { assert, equal, assertStrContains, assertMatch } from "./asserts.ts";
import { test, assert } from "./mod.ts"; import { test } from "./mod.ts";
// import { assertEqual as prettyAssertEqual } from "./pretty.ts"; // import { assertEq as prettyAssertEqual } from "./pretty.ts";
// import "./format_test.ts"; // import "./format_test.ts";
// import "./diff_test.ts"; // import "./diff_test.ts";
// import "./pretty_test.ts"; // import "./pretty_test.ts";
test(function testingEqual() {
assert(equal("world", "world"));
assert(!equal("hello", "world"));
assert(equal(5, 5));
assert(!equal(5, 6));
assert(equal(NaN, NaN));
assert(equal({ hello: "world" }, { hello: "world" }));
assert(!equal({ world: "hello" }, { hello: "world" }));
assert(
equal(
{ hello: "world", hi: { there: "everyone" } },
{ hello: "world", hi: { there: "everyone" } }
)
);
assert(
!equal(
{ hello: "world", hi: { there: "everyone" } },
{ hello: "world", hi: { there: "everyone else" } }
)
);
});
test(function testingAssertStringContains() { test(function testingAssertStringContains() {
assertStrContains("Denosaurus", "saur"); assertStrContains("Denosaurus", "saur");
assertStrContains("Denosaurus", "Deno"); assertStrContains("Denosaurus", "Deno");

View file

@ -1,17 +1,18 @@
import diff from "./diff.ts"; import diff from "./diff.ts";
import { test, assertEqual } from "./mod.ts"; import { assertEq } from "../testing/asserts.ts";
import { test } from "./mod.ts";
test({ test({
name: "empty", name: "empty",
fn() { fn() {
assertEqual(diff([], []), []); assertEq(diff([], []), []);
} }
}); });
test({ test({
name: '"a" vs "b"', name: '"a" vs "b"',
fn() { fn() {
assertEqual(diff(["a"], ["b"]), [ assertEq(diff(["a"], ["b"]), [
{ type: "removed", value: "a" }, { type: "removed", value: "a" },
{ type: "added", value: "b" } { type: "added", value: "b" }
]); ]);
@ -21,28 +22,28 @@ test({
test({ test({
name: '"a" vs "a"', name: '"a" vs "a"',
fn() { fn() {
assertEqual(diff(["a"], ["a"]), [{ type: "common", value: "a" }]); assertEq(diff(["a"], ["a"]), [{ type: "common", value: "a" }]);
} }
}); });
test({ test({
name: '"a" vs ""', name: '"a" vs ""',
fn() { fn() {
assertEqual(diff(["a"], []), [{ type: "removed", value: "a" }]); assertEq(diff(["a"], []), [{ type: "removed", value: "a" }]);
} }
}); });
test({ test({
name: '"" vs "a"', name: '"" vs "a"',
fn() { fn() {
assertEqual(diff([], ["a"]), [{ type: "added", value: "a" }]); assertEq(diff([], ["a"]), [{ type: "added", value: "a" }]);
} }
}); });
test({ test({
name: '"a" vs "a, b"', name: '"a" vs "a, b"',
fn() { fn() {
assertEqual(diff(["a"], ["a", "b"]), [ assertEq(diff(["a"], ["a", "b"]), [
{ type: "common", value: "a" }, { type: "common", value: "a" },
{ type: "added", value: "b" } { type: "added", value: "b" }
]); ]);
@ -52,7 +53,7 @@ test({
test({ test({
name: '"strength" vs "string"', name: '"strength" vs "string"',
fn() { fn() {
assertEqual(diff(Array.from("strength"), Array.from("string")), [ assertEq(diff(Array.from("strength"), Array.from("string")), [
{ type: "common", value: "s" }, { type: "common", value: "s" },
{ type: "common", value: "t" }, { type: "common", value: "t" },
{ type: "common", value: "r" }, { type: "common", value: "r" },
@ -69,7 +70,7 @@ test({
test({ test({
name: '"strength" vs ""', name: '"strength" vs ""',
fn() { fn() {
assertEqual(diff(Array.from("strength"), Array.from("")), [ assertEq(diff(Array.from("strength"), Array.from("")), [
{ type: "removed", value: "s" }, { type: "removed", value: "s" },
{ type: "removed", value: "t" }, { type: "removed", value: "t" },
{ type: "removed", value: "r" }, { type: "removed", value: "r" },
@ -85,7 +86,7 @@ test({
test({ test({
name: '"" vs "strength"', name: '"" vs "strength"',
fn() { fn() {
assertEqual(diff(Array.from(""), Array.from("strength")), [ assertEq(diff(Array.from(""), Array.from("strength")), [
{ type: "added", value: "s" }, { type: "added", value: "s" },
{ type: "added", value: "t" }, { type: "added", value: "t" },
{ type: "added", value: "r" }, { type: "added", value: "r" },
@ -101,7 +102,7 @@ test({
test({ test({
name: '"abc", "c" vs "abc", "bcd", "c"', name: '"abc", "c" vs "abc", "bcd", "c"',
fn() { fn() {
assertEqual(diff(["abc", "c"], ["abc", "bcd", "c"]), [ assertEq(diff(["abc", "c"], ["abc", "bcd", "c"]), [
{ type: "common", value: "abc" }, { type: "common", value: "abc" },
{ type: "added", value: "bcd" }, { type: "added", value: "bcd" },
{ type: "common", value: "c" } { type: "common", value: "c" }

View file

@ -6,7 +6,8 @@
* LICENSE file in the root directory of this source tree. * LICENSE file in the root directory of this source tree.
* *
*/ */
import { test, assertEqual } from "./mod.ts"; import { test } from "./mod.ts";
import { assertEq } from "../testing/asserts.ts";
import { format } from "./format.ts"; import { format } from "./format.ts";
// eslint-disable-next-line @typescript-eslint/no-unused-vars,@typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-unused-vars,@typescript-eslint/no-explicit-any
@ -54,7 +55,7 @@ test({
name: "prints empty arguments", name: "prints empty arguments",
fn() { fn() {
const val = returnArguments(); const val = returnArguments();
assertEqual(format(val), "Arguments []"); assertEq(format(val), "Arguments []");
} }
}); });
@ -62,7 +63,7 @@ test({
name: "prints an empty array", name: "prints an empty array",
fn() { fn() {
const val: unknown[] = []; const val: unknown[] = [];
assertEqual(format(val), "Array []"); assertEq(format(val), "Array []");
} }
}); });
@ -70,7 +71,7 @@ test({
name: "prints an array with items", name: "prints an array with items",
fn() { fn() {
const val = [1, 2, 3]; const val = [1, 2, 3];
assertEqual(format(val), "Array [\n 1,\n 2,\n 3,\n]"); assertEq(format(val), "Array [\n 1,\n 2,\n 3,\n]");
} }
}); });
@ -78,7 +79,7 @@ test({
name: "prints a empty typed array", name: "prints a empty typed array",
fn() { fn() {
const val = new Uint32Array(0); const val = new Uint32Array(0);
assertEqual(format(val), "Uint32Array []"); assertEq(format(val), "Uint32Array []");
} }
}); });
@ -86,7 +87,7 @@ test({
name: "prints a typed array with items", name: "prints a typed array with items",
fn() { fn() {
const val = new Uint32Array(3); const val = new Uint32Array(3);
assertEqual(format(val), "Uint32Array [\n 0,\n 0,\n 0,\n]"); assertEq(format(val), "Uint32Array [\n 0,\n 0,\n 0,\n]");
} }
}); });
@ -94,7 +95,7 @@ test({
name: "prints an array buffer", name: "prints an array buffer",
fn() { fn() {
const val = new ArrayBuffer(3); const val = new ArrayBuffer(3);
assertEqual(format(val), "ArrayBuffer []"); assertEq(format(val), "ArrayBuffer []");
} }
}); });
@ -102,7 +103,7 @@ test({
name: "prints a nested array", name: "prints a nested array",
fn() { fn() {
const val = [[1, 2, 3]]; const val = [[1, 2, 3]];
assertEqual( assertEq(
format(val), format(val),
"Array [\n Array [\n 1,\n 2,\n 3,\n ],\n]" "Array [\n Array [\n 1,\n 2,\n 3,\n ],\n]"
); );
@ -113,7 +114,7 @@ test({
name: "prints true", name: "prints true",
fn() { fn() {
const val = true; const val = true;
assertEqual(format(val), "true"); assertEq(format(val), "true");
} }
}); });
@ -121,7 +122,7 @@ test({
name: "prints false", name: "prints false",
fn() { fn() {
const val = false; const val = false;
assertEqual(format(val), "false"); assertEq(format(val), "false");
} }
}); });
@ -129,7 +130,7 @@ test({
name: "prints an error", name: "prints an error",
fn() { fn() {
const val = new Error(); const val = new Error();
assertEqual(format(val), "[Error]"); assertEq(format(val), "[Error]");
} }
}); });
@ -137,7 +138,7 @@ test({
name: "prints a typed error with a message", name: "prints a typed error with a message",
fn() { fn() {
const val = new TypeError("message"); const val = new TypeError("message");
assertEqual(format(val), "[TypeError: message]"); assertEq(format(val), "[TypeError: message]");
} }
}); });
@ -146,7 +147,7 @@ test({
fn() { fn() {
// tslint:disable-next-line:function-constructor // tslint:disable-next-line:function-constructor
const val = new Function(); const val = new Function();
assertEqual(format(val), "[Function anonymous]"); assertEq(format(val), "[Function anonymous]");
} }
}); });
@ -159,7 +160,7 @@ test({
} }
// tslint:disable-next-line:no-empty // tslint:disable-next-line:no-empty
f(() => {}); f(() => {});
assertEqual(format(val), "[Function anonymous]"); assertEq(format(val), "[Function anonymous]");
} }
}); });
@ -169,7 +170,7 @@ test({
// tslint:disable-next-line:no-empty // tslint:disable-next-line:no-empty
const val = (): void => {}; const val = (): void => {};
const formatted = format(val); const formatted = format(val);
assertEqual( assertEq(
formatted === "[Function anonymous]" || formatted === "[Function val]", formatted === "[Function anonymous]" || formatted === "[Function val]",
true true
); );
@ -181,7 +182,7 @@ test({
fn() { fn() {
// tslint:disable-next-line:no-empty // tslint:disable-next-line:no-empty
const val = function named(): void {}; const val = function named(): void {};
assertEqual(format(val), "[Function named]"); assertEq(format(val), "[Function named]");
} }
}); });
@ -193,7 +194,7 @@ test({
yield 2; yield 2;
yield 3; yield 3;
}; };
assertEqual(format(val), "[Function generate]"); assertEq(format(val), "[Function generate]");
} }
}); });
@ -202,7 +203,7 @@ test({
fn() { fn() {
// tslint:disable-next-line:no-empty // tslint:disable-next-line:no-empty
const val = function named(): void {}; const val = function named(): void {};
assertEqual( assertEq(
format(val, { format(val, {
printFunctionName: false printFunctionName: false
}), }),
@ -215,7 +216,7 @@ test({
name: "prints Infinity", name: "prints Infinity",
fn() { fn() {
const val = Infinity; const val = Infinity;
assertEqual(format(val), "Infinity"); assertEq(format(val), "Infinity");
} }
}); });
@ -223,7 +224,7 @@ test({
name: "prints -Infinity", name: "prints -Infinity",
fn() { fn() {
const val = -Infinity; const val = -Infinity;
assertEqual(format(val), "-Infinity"); assertEq(format(val), "-Infinity");
} }
}); });
@ -231,7 +232,7 @@ test({
name: "prints an empty map", name: "prints an empty map",
fn() { fn() {
const val = new Map(); const val = new Map();
assertEqual(format(val), "Map {}"); assertEq(format(val), "Map {}");
} }
}); });
@ -241,7 +242,7 @@ test({
const val = new Map(); const val = new Map();
val.set("prop1", "value1"); val.set("prop1", "value1");
val.set("prop2", "value2"); val.set("prop2", "value2");
assertEqual( assertEq(
format(val), format(val),
'Map {\n "prop1" => "value1",\n "prop2" => "value2",\n}' 'Map {\n "prop1" => "value1",\n "prop2" => "value2",\n}'
); );
@ -287,7 +288,7 @@ test({
' } => "object",', ' } => "object",',
"}" "}"
].join("\n"); ].join("\n");
assertEqual(format(val), expected); assertEq(format(val), expected);
} }
}); });
@ -295,7 +296,7 @@ test({
name: "prints NaN", name: "prints NaN",
fn() { fn() {
const val = NaN; const val = NaN;
assertEqual(format(val), "NaN"); assertEq(format(val), "NaN");
} }
}); });
@ -303,7 +304,7 @@ test({
name: "prints null", name: "prints null",
fn() { fn() {
const val = null; const val = null;
assertEqual(format(val), "null"); assertEq(format(val), "null");
} }
}); });
@ -311,7 +312,7 @@ test({
name: "prints a positive number", name: "prints a positive number",
fn() { fn() {
const val = 123; const val = 123;
assertEqual(format(val), "123"); assertEq(format(val), "123");
} }
}); });
@ -319,7 +320,7 @@ test({
name: "prints a negative number", name: "prints a negative number",
fn() { fn() {
const val = -123; const val = -123;
assertEqual(format(val), "-123"); assertEq(format(val), "-123");
} }
}); });
@ -327,7 +328,7 @@ test({
name: "prints zero", name: "prints zero",
fn() { fn() {
const val = 0; const val = 0;
assertEqual(format(val), "0"); assertEq(format(val), "0");
} }
}); });
@ -335,7 +336,7 @@ test({
name: "prints negative zero", name: "prints negative zero",
fn() { fn() {
const val = -0; const val = -0;
assertEqual(format(val), "-0"); assertEq(format(val), "-0");
} }
}); });
@ -343,7 +344,7 @@ test({
name: "prints a date", name: "prints a date",
fn() { fn() {
const val = new Date(10e11); const val = new Date(10e11);
assertEqual(format(val), "2001-09-09T01:46:40.000Z"); assertEq(format(val), "2001-09-09T01:46:40.000Z");
} }
}); });
@ -351,7 +352,7 @@ test({
name: "prints an invalid date", name: "prints an invalid date",
fn() { fn() {
const val = new Date(Infinity); const val = new Date(Infinity);
assertEqual(format(val), "Date { NaN }"); assertEq(format(val), "Date { NaN }");
} }
}); });
@ -359,7 +360,7 @@ test({
name: "prints an empty object", name: "prints an empty object",
fn() { fn() {
const val = {}; const val = {};
assertEqual(format(val), "Object {}"); assertEq(format(val), "Object {}");
} }
}); });
@ -367,7 +368,7 @@ test({
name: "prints an object with properties", name: "prints an object with properties",
fn() { fn() {
const val = { prop1: "value1", prop2: "value2" }; const val = { prop1: "value1", prop2: "value2" };
assertEqual( assertEq(
format(val), format(val),
'Object {\n "prop1": "value1",\n "prop2": "value2",\n}' 'Object {\n "prop1": "value1",\n "prop2": "value2",\n}'
); );
@ -382,7 +383,7 @@ test({
val[Symbol("symbol1")] = "value2"; val[Symbol("symbol1")] = "value2";
val[Symbol("symbol2")] = "value3"; val[Symbol("symbol2")] = "value3";
val.prop = "value1"; val.prop = "value1";
assertEqual( assertEq(
format(val), format(val),
'Object {\n "prop": "value1",\n Symbol(symbol1): "value2",\n Symbol(symbol2): "value3",\n}' 'Object {\n "prop": "value1",\n Symbol(symbol1): "value2",\n Symbol(symbol2): "value3",\n}'
); );
@ -401,7 +402,7 @@ test({
enumerable: false, enumerable: false,
value: false value: false
}); });
assertEqual(format(val), 'Object {\n "enumerable": true,\n}'); assertEq(format(val), 'Object {\n "enumerable": true,\n}');
} }
}); });
@ -417,7 +418,7 @@ test({
enumerable: false, enumerable: false,
value: false value: false
}); });
assertEqual(format(val), 'Object {\n "enumerable": true,\n}'); assertEq(format(val), 'Object {\n "enumerable": true,\n}');
} }
}); });
@ -425,7 +426,7 @@ test({
name: "prints an object with sorted properties", name: "prints an object with sorted properties",
fn() { fn() {
const val = { b: 1, a: 2 }; const val = { b: 1, a: 2 };
assertEqual(format(val), 'Object {\n "a": 2,\n "b": 1,\n}'); assertEq(format(val), 'Object {\n "a": 2,\n "b": 1,\n}');
} }
}); });
@ -433,7 +434,7 @@ test({
name: "prints regular expressions from constructors", name: "prints regular expressions from constructors",
fn() { fn() {
const val = new RegExp("regexp"); const val = new RegExp("regexp");
assertEqual(format(val), "/regexp/"); assertEq(format(val), "/regexp/");
} }
}); });
@ -441,7 +442,7 @@ test({
name: "prints regular expressions from literals", name: "prints regular expressions from literals",
fn() { fn() {
const val = /regexp/gi; const val = /regexp/gi;
assertEqual(format(val), "/regexp/gi"); assertEq(format(val), "/regexp/gi");
} }
}); });
@ -449,7 +450,7 @@ test({
name: "prints regular expressions {escapeRegex: false}", name: "prints regular expressions {escapeRegex: false}",
fn() { fn() {
const val = /regexp\d/gi; const val = /regexp\d/gi;
assertEqual(format(val), "/regexp\\d/gi"); assertEq(format(val), "/regexp\\d/gi");
} }
}); });
@ -457,7 +458,7 @@ test({
name: "prints regular expressions {escapeRegex: true}", name: "prints regular expressions {escapeRegex: true}",
fn() { fn() {
const val = /regexp\d/gi; const val = /regexp\d/gi;
assertEqual(format(val, { escapeRegex: true }), "/regexp\\\\d/gi"); assertEq(format(val, { escapeRegex: true }), "/regexp\\\\d/gi");
} }
}); });
@ -465,7 +466,7 @@ test({
name: "escapes regular expressions nested inside object", name: "escapes regular expressions nested inside object",
fn() { fn() {
const obj = { test: /regexp\d/gi }; const obj = { test: /regexp\d/gi };
assertEqual( assertEq(
format(obj, { escapeRegex: true }), format(obj, { escapeRegex: true }),
'Object {\n "test": /regexp\\\\d/gi,\n}' 'Object {\n "test": /regexp\\\\d/gi,\n}'
); );
@ -476,7 +477,7 @@ test({
name: "prints an empty set", name: "prints an empty set",
fn() { fn() {
const val = new Set(); const val = new Set();
assertEqual(format(val), "Set {}"); assertEq(format(val), "Set {}");
} }
}); });
@ -486,7 +487,7 @@ test({
const val = new Set(); const val = new Set();
val.add("value1"); val.add("value1");
val.add("value2"); val.add("value2");
assertEqual(format(val), 'Set {\n "value1",\n "value2",\n}'); assertEq(format(val), 'Set {\n "value1",\n "value2",\n}');
} }
}); });
@ -494,7 +495,7 @@ test({
name: "prints a string", name: "prints a string",
fn() { fn() {
const val = "string"; const val = "string";
assertEqual(format(val), '"string"'); assertEq(format(val), '"string"');
} }
}); });
@ -502,7 +503,7 @@ test({
name: "prints and escape a string", name: "prints and escape a string",
fn() { fn() {
const val = "\"'\\"; const val = "\"'\\";
assertEqual(format(val), '"\\"\'\\\\"'); assertEq(format(val), '"\\"\'\\\\"');
} }
}); });
@ -510,15 +511,15 @@ test({
name: "doesn't escape string with {excapeString: false}", name: "doesn't escape string with {excapeString: false}",
fn() { fn() {
const val = "\"'\\n"; const val = "\"'\\n";
assertEqual(format(val, { escapeString: false }), '""\'\\n"'); assertEq(format(val, { escapeString: false }), '""\'\\n"');
} }
}); });
test({ test({
name: "prints a string with escapes", name: "prints a string with escapes",
fn() { fn() {
assertEqual(format('"-"'), '"\\"-\\""'); assertEq(format('"-"'), '"\\"-\\""');
assertEqual(format("\\ \\\\"), '"\\\\ \\\\\\\\"'); assertEq(format("\\ \\\\"), '"\\\\ \\\\\\\\"');
} }
}); });
@ -526,7 +527,7 @@ test({
name: "prints a multiline string", name: "prints a multiline string",
fn() { fn() {
const val = ["line 1", "line 2", "line 3"].join("\n"); const val = ["line 1", "line 2", "line 3"].join("\n");
assertEqual(format(val), '"' + val + '"'); assertEq(format(val), '"' + val + '"');
} }
}); });
@ -546,7 +547,7 @@ test({
}, },
type: "svg" type: "svg"
}; };
assertEqual( assertEq(
format(val), format(val),
[ [
"Object {", "Object {",
@ -572,7 +573,7 @@ test({
name: "prints a symbol", name: "prints a symbol",
fn() { fn() {
const val = Symbol("symbol"); const val = Symbol("symbol");
assertEqual(format(val), "Symbol(symbol)"); assertEq(format(val), "Symbol(symbol)");
} }
}); });
@ -580,7 +581,7 @@ test({
name: "prints undefined", name: "prints undefined",
fn() { fn() {
const val = undefined; const val = undefined;
assertEqual(format(val), "undefined"); assertEq(format(val), "undefined");
} }
}); });
@ -588,7 +589,7 @@ test({
name: "prints a WeakMap", name: "prints a WeakMap",
fn() { fn() {
const val = new WeakMap(); const val = new WeakMap();
assertEqual(format(val), "WeakMap {}"); assertEq(format(val), "WeakMap {}");
} }
}); });
@ -596,7 +597,7 @@ test({
name: "prints a WeakSet", name: "prints a WeakSet",
fn() { fn() {
const val = new WeakSet(); const val = new WeakSet();
assertEqual(format(val), "WeakSet {}"); assertEq(format(val), "WeakSet {}");
} }
}); });
@ -604,7 +605,7 @@ test({
name: "prints deeply nested objects", name: "prints deeply nested objects",
fn() { fn() {
const val = { prop: { prop: { prop: "value" } } }; const val = { prop: { prop: { prop: "value" } } };
assertEqual( assertEq(
format(val), format(val),
'Object {\n "prop": Object {\n "prop": Object {\n "prop": "value",\n },\n },\n}' 'Object {\n "prop": Object {\n "prop": Object {\n "prop": "value",\n },\n },\n}'
); );
@ -617,7 +618,7 @@ test({
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
const val: any = {}; const val: any = {};
val.prop = val; val.prop = val;
assertEqual(format(val), 'Object {\n "prop": [Circular],\n}'); assertEq(format(val), 'Object {\n "prop": [Circular],\n}');
} }
}); });
@ -626,7 +627,7 @@ test({
fn() { fn() {
const inner = {}; const inner = {};
const val = { prop1: inner, prop2: inner }; const val = { prop1: inner, prop2: inner };
assertEqual( assertEq(
format(val), format(val),
'Object {\n "prop1": Object {},\n "prop2": Object {},\n}' 'Object {\n "prop1": Object {},\n "prop2": Object {},\n}'
); );
@ -636,14 +637,14 @@ test({
test({ test({
name: "default implicit: 2 spaces", name: "default implicit: 2 spaces",
fn() { fn() {
assertEqual(format(createVal()), createExpected()); assertEq(format(createVal()), createExpected());
} }
}); });
test({ test({
name: "default explicit: 2 spaces", name: "default explicit: 2 spaces",
fn() { fn() {
assertEqual(format(createVal(), { indent: 2 }), createExpected()); assertEq(format(createVal(), { indent: 2 }), createExpected());
} }
}); });
@ -652,7 +653,7 @@ test({
name: "non-default: 0 spaces", name: "non-default: 0 spaces",
fn() { fn() {
const indent = 0; const indent = 0;
assertEqual( assertEq(
format(createVal(), { indent }), format(createVal(), { indent }),
createExpected().replace(/ {2}/g, " ".repeat(indent)) createExpected().replace(/ {2}/g, " ".repeat(indent))
); );
@ -663,7 +664,7 @@ test({
name: "non-default: 4 spaces", name: "non-default: 4 spaces",
fn() { fn() {
const indent = 4; const indent = 4;
assertEqual( assertEq(
format(createVal(), { indent }), format(createVal(), { indent }),
createExpected().replace(/ {2}/g, " ".repeat(indent)) createExpected().replace(/ {2}/g, " ".repeat(indent))
); );
@ -691,7 +692,7 @@ test({
"set non-empty": new Set(["value"]) "set non-empty": new Set(["value"])
} }
]; ];
assertEqual( assertEq(
format(v, { maxDepth: 2 }), format(v, { maxDepth: 2 }),
[ [
"Array [", "Array [",
@ -719,7 +720,7 @@ test({
test({ test({
name: "prints objects with no constructor", name: "prints objects with no constructor",
fn() { fn() {
assertEqual(format(Object.create(null)), "Object {}"); assertEq(format(Object.create(null)), "Object {}");
} }
}); });
@ -733,14 +734,14 @@ test({
' "constructor": "constructor",', ' "constructor": "constructor",',
"}" "}"
].join("\n"); ].join("\n");
assertEqual(format(obj), expected); assertEq(format(obj), expected);
} }
}); });
test({ test({
name: "calls toJSON and prints its return value", name: "calls toJSON and prints its return value",
fn() { fn() {
assertEqual( assertEq(
format({ format({
toJSON: () => ({ value: false }), toJSON: () => ({ value: false }),
value: true value: true
@ -753,7 +754,7 @@ test({
test({ test({
name: "calls toJSON and prints an internal representation.", name: "calls toJSON and prints an internal representation.",
fn() { fn() {
assertEqual( assertEq(
format({ format({
toJSON: () => "[Internal Object]", toJSON: () => "[Internal Object]",
value: true value: true
@ -766,7 +767,7 @@ test({
test({ test({
name: "calls toJSON only on functions", name: "calls toJSON only on functions",
fn() { fn() {
assertEqual( assertEq(
format({ format({
toJSON: false, toJSON: false,
value: true value: true
@ -779,7 +780,7 @@ test({
test({ test({
name: "does not call toJSON recursively", name: "does not call toJSON recursively",
fn() { fn() {
assertEqual( assertEq(
format({ format({
toJSON: () => ({ toJSON: () => ({ value: true }) }), toJSON: () => ({ toJSON: () => ({ value: true }) }),
value: false value: false
@ -795,6 +796,6 @@ test({
const set = new Set([1]); const set = new Set([1]);
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
(set as any).toJSON = () => "map"; (set as any).toJSON = () => "map";
assertEqual(format(set), '"map"'); assertEq(format(set), '"map"');
} }
}); });

View file

@ -1,68 +1,6 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { green, red } from "../colors/mod.ts"; import { green, red } from "../colors/mod.ts";
import { assertEqual as prettyAssertEqual } from "./pretty.ts";
import {
assert as assertImport,
equal as AssertEqual,
assertStrictEq,
assertStrContains,
assertMatch,
fail,
assertThrows,
assertThrowsAsync
} from "./asserts.ts";
export function equal(c: unknown, d: unknown): boolean {
const seen = new Map();
return (function compare(a: unknown, b: unknown) {
if (Object.is(a, b)) {
return true;
}
if (a && typeof a === "object" && b && typeof b === "object") {
if (seen.get(a) === b) {
return true;
}
if (Object.keys(a || {}).length !== Object.keys(b || {}).length) {
return false;
}
const merged = { ...a, ...b };
for (const key in merged) {
type Key = keyof typeof merged;
if (!compare(a && a[key as Key], b && b[key as Key])) {
return false;
}
}
seen.set(a, b);
return true;
}
return false;
})(c, d);
}
const assertions = {
assert: assertImport,
equal: AssertEqual,
strictEqual: assertStrictEq,
assertStrContains: assertStrContains,
assertMatch: assertMatch,
fail: fail,
throws: assertThrows,
throwsAsync: assertThrowsAsync
};
type Assert = typeof assertions.assert & typeof assertions;
// Decorate assertions.assert with all the assertions
Object.assign(assertions.assert, assertions);
export const assert = assertions.assert as Assert;
/**
* Alias to pretty.assertEqual
* @deprecated
*/
export const assertEqual = prettyAssertEqual;
export type TestFunction = () => void | Promise<void>; export type TestFunction = () => void | Promise<void>;

View file

@ -1,6 +1,6 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { equal } from "./mod.ts"; import { equal } from "./asserts.ts";
import { red, green, white, gray, bold } from "../colors/mod.ts"; import { red, green, white, gray, bold } from "../colors/mod.ts";
import diff, { DiffType, DiffResult } from "./diff.ts"; import diff, { DiffType, DiffResult } from "./diff.ts";
import { format } from "./format.ts"; import { format } from "./format.ts";
@ -55,7 +55,7 @@ function buildMessage(diffResult: ReadonlyArray<DiffResult<string>>): string[] {
return messages; return messages;
} }
export function assertEqual( export function assertEq(
actual: unknown, actual: unknown,
expected: unknown, expected: unknown,
msg?: string msg?: string

View file

@ -1,8 +1,9 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { test, assert } from "./mod.ts"; import { test } from "./mod.ts";
import { red, green, white, gray, bold } from "../colors/mod.ts"; import { red, green, white, gray, bold } from "../colors/mod.ts";
import { assertEqual } from "./pretty.ts"; import { assertEq } from "./pretty.ts";
import { assertThrows } from "./asserts.ts";
const createHeader = (): string[] => [ const createHeader = (): string[] => [
"", "",
@ -18,19 +19,19 @@ const removed: (s: string) => string = (s: string): string => red(bold(s));
test({ test({
name: "pass case", name: "pass case",
fn() { fn() {
assertEqual({ a: 10 }, { a: 10 }); assertEq({ a: 10 }, { a: 10 });
assertEqual(true, true); assertEq(true, true);
assertEqual(10, 10); assertEq(10, 10);
assertEqual("abc", "abc"); assertEq("abc", "abc");
assertEqual({ a: 10, b: { c: "1" } }, { a: 10, b: { c: "1" } }); assertEq({ a: 10, b: { c: "1" } }, { a: 10, b: { c: "1" } });
} }
}); });
test({ test({
name: "failed with number", name: "failed with number",
fn() { fn() {
assert.throws( assertThrows(
() => assertEqual(1, 2), () => assertEq(1, 2),
Error, Error,
[...createHeader(), removed(`- 1`), added(`+ 2`), ""].join("\n") [...createHeader(), removed(`- 1`), added(`+ 2`), ""].join("\n")
); );
@ -40,8 +41,8 @@ test({
test({ test({
name: "failed with number vs string", name: "failed with number vs string",
fn() { fn() {
assert.throws( assertThrows(
() => assertEqual(1, "1"), () => assertEq(1, "1"),
Error, Error,
[...createHeader(), removed(`- 1`), added(`+ "1"`)].join("\n") [...createHeader(), removed(`- 1`), added(`+ "1"`)].join("\n")
); );
@ -51,8 +52,8 @@ test({
test({ test({
name: "failed with array", name: "failed with array",
fn() { fn() {
assert.throws( assertThrows(
() => assertEqual([1, "2", 3], ["1", "2", 3]), () => assertEq([1, "2", 3], ["1", "2", 3]),
Error, Error,
[ [
...createHeader(), ...createHeader(),
@ -71,8 +72,8 @@ test({
test({ test({
name: "failed with object", name: "failed with object",
fn() { fn() {
assert.throws( assertThrows(
() => assertEqual({ a: 1, b: "2", c: 3 }, { a: 1, b: 2, c: [3] }), () => assertEq({ a: 1, b: "2", c: 3 }, { a: 1, b: 2, c: [3] }),
Error, Error,
[ [
...createHeader(), ...createHeader(),

View file

@ -1,45 +1,23 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { test, assert, assertEqual, equal, runIfMain } from "./mod.ts"; import { test, runIfMain } from "./mod.ts";
import { assertEqual as prettyAssertEqual } from "./pretty.ts"; import {
assert,
assertEq,
assertStrictEq,
assertThrows,
assertThrowsAsync,
fail
} from "../testing/asserts.ts";
import "./format_test.ts"; import "./format_test.ts";
import "./diff_test.ts"; import "./diff_test.ts";
import "./pretty_test.ts"; import "./pretty_test.ts";
import "./asserts_test.ts"; import "./asserts_test.ts";
test(function testingEqual() {
assert(equal("world", "world"));
assert(!equal("hello", "world"));
assert(equal(5, 5));
assert(!equal(5, 6));
assert(equal(NaN, NaN));
assert(equal({ hello: "world" }, { hello: "world" }));
assert(!equal({ world: "hello" }, { hello: "world" }));
assert(
equal(
{ hello: "world", hi: { there: "everyone" } },
{ hello: "world", hi: { there: "everyone" } }
)
);
assert(
!equal(
{ hello: "world", hi: { there: "everyone" } },
{ hello: "world", hi: { there: "everyone else" } }
)
);
});
test(function testingAssertEqual() {
const a = Object.create(null);
a.b = "foo";
assert.equal(a, a);
assert(assertEqual === prettyAssertEqual);
});
test(function testingAssertFail() { test(function testingAssertFail() {
assert.throws(assert.fail, Error, "Failed assertion."); assertThrows(fail, Error, "Failed assertion.");
assert.throws( assertThrows(
() => { () => {
assert.fail("foo"); fail("foo");
}, },
Error, Error,
"Failed assertion: foo" "Failed assertion: foo"
@ -50,7 +28,7 @@ test(function testingAssertEqualActualUncoercable() {
let didThrow = false; let didThrow = false;
const a = Object.create(null); const a = Object.create(null);
try { try {
assert.equal(a, "bar"); assertEq(a, "bar");
} catch (e) { } catch (e) {
didThrow = true; didThrow = true;
} }
@ -61,7 +39,7 @@ test(function testingAssertEqualExpectedUncoercable() {
let didThrow = false; let didThrow = false;
const a = Object.create(null); const a = Object.create(null);
try { try {
assert.equal("bar", a); assertStrictEq("bar", a);
} catch (e) { } catch (e) {
didThrow = true; didThrow = true;
} }
@ -71,7 +49,7 @@ test(function testingAssertEqualExpectedUncoercable() {
test(function testingAssertStrictEqual() { test(function testingAssertStrictEqual() {
const a = {}; const a = {};
const b = a; const b = a;
assert.strictEqual(a, b); assertStrictEq(a, b);
}); });
test(function testingAssertNotStrictEqual() { test(function testingAssertNotStrictEqual() {
@ -79,7 +57,7 @@ test(function testingAssertNotStrictEqual() {
const a = {}; const a = {};
const b = {}; const b = {};
try { try {
assert.strictEqual(a, b); assertStrictEq(a, b);
} catch (e) { } catch (e) {
assert(e.message === "actual: [object Object] expected: [object Object]"); assert(e.message === "actual: [object Object] expected: [object Object]");
didThrow = true; didThrow = true;
@ -89,7 +67,7 @@ test(function testingAssertNotStrictEqual() {
test(function testingDoesThrow() { test(function testingDoesThrow() {
let count = 0; let count = 0;
assert.throws(() => { assertThrows(() => {
count++; count++;
throw new Error(); throw new Error();
}); });
@ -100,7 +78,7 @@ test(function testingDoesNotThrow() {
let count = 0; let count = 0;
let didThrow = false; let didThrow = false;
try { try {
assert.throws(() => { assertThrows(() => {
count++; count++;
console.log("Hello world"); console.log("Hello world");
}); });
@ -114,7 +92,7 @@ test(function testingDoesNotThrow() {
test(function testingThrowsErrorType() { test(function testingThrowsErrorType() {
let count = 0; let count = 0;
assert.throws(() => { assertThrows(() => {
count++; count++;
throw new TypeError(); throw new TypeError();
}, TypeError); }, TypeError);
@ -125,7 +103,7 @@ test(function testingThrowsNotErrorType() {
let count = 0; let count = 0;
let didThrow = false; let didThrow = false;
try { try {
assert.throws(() => { assertThrows(() => {
count++; count++;
throw new TypeError(); throw new TypeError();
}, RangeError); }, RangeError);
@ -139,7 +117,7 @@ test(function testingThrowsNotErrorType() {
test(function testingThrowsMsgIncludes() { test(function testingThrowsMsgIncludes() {
let count = 0; let count = 0;
assert.throws( assertThrows(
() => { () => {
count++; count++;
throw new TypeError("Hello world!"); throw new TypeError("Hello world!");
@ -154,7 +132,7 @@ test(function testingThrowsMsgNotIncludes() {
let count = 0; let count = 0;
let didThrow = false; let didThrow = false;
try { try {
assert.throws( assertThrows(
() => { () => {
count++; count++;
throw new TypeError("Hello world!"); throw new TypeError("Hello world!");
@ -175,7 +153,7 @@ test(function testingThrowsMsgNotIncludes() {
test(async function testingDoesThrowAsync() { test(async function testingDoesThrowAsync() {
let count = 0; let count = 0;
await assert.throwsAsync(async () => { await assertThrowsAsync(async () => {
count++; count++;
throw new Error(); throw new Error();
}); });
@ -184,7 +162,7 @@ test(async function testingDoesThrowAsync() {
test(async function testingDoesReject() { test(async function testingDoesReject() {
let count = 0; let count = 0;
await assert.throwsAsync(() => { await assertThrowsAsync(() => {
count++; count++;
return Promise.reject(new Error()); return Promise.reject(new Error());
}); });
@ -195,7 +173,7 @@ test(async function testingDoesNotThrowAsync() {
let count = 0; let count = 0;
let didThrow = false; let didThrow = false;
try { try {
await assert.throwsAsync(async () => { await assertThrowsAsync(async () => {
count++; count++;
console.log("Hello world"); console.log("Hello world");
}); });
@ -211,7 +189,7 @@ test(async function testingDoesNotRejectAsync() {
let count = 0; let count = 0;
let didThrow = false; let didThrow = false;
try { try {
await assert.throwsAsync(() => { await assertThrowsAsync(() => {
count++; count++;
console.log("Hello world"); console.log("Hello world");
return Promise.resolve(); return Promise.resolve();
@ -226,7 +204,7 @@ test(async function testingDoesNotRejectAsync() {
test(async function testingThrowsAsyncErrorType() { test(async function testingThrowsAsyncErrorType() {
let count = 0; let count = 0;
await assert.throwsAsync(async () => { await assertThrowsAsync(async () => {
count++; count++;
throw new TypeError(); throw new TypeError();
}, TypeError); }, TypeError);
@ -237,7 +215,7 @@ test(async function testingThrowsAsyncNotErrorType() {
let count = 0; let count = 0;
let didThrow = false; let didThrow = false;
try { try {
await assert.throwsAsync(async () => { await assertThrowsAsync(async () => {
count++; count++;
throw new TypeError(); throw new TypeError();
}, RangeError); }, RangeError);
@ -251,7 +229,7 @@ test(async function testingThrowsAsyncNotErrorType() {
test(async function testingThrowsAsyncMsgIncludes() { test(async function testingThrowsAsyncMsgIncludes() {
let count = 0; let count = 0;
await assert.throwsAsync( await assertThrowsAsync(
async () => { async () => {
count++; count++;
throw new TypeError("Hello world!"); throw new TypeError("Hello world!");
@ -266,7 +244,7 @@ test(async function testingThrowsAsyncMsgNotIncludes() {
let count = 0; let count = 0;
let didThrow = false; let didThrow = false;
try { try {
await assert.throwsAsync( await assertThrowsAsync(
async () => { async () => {
count++; count++;
throw new TypeError("Hello world!"); throw new TypeError("Hello world!");

View file

@ -6,7 +6,8 @@
import { BufReader } from "../io/bufio.ts"; import { BufReader } from "../io/bufio.ts";
import { TextProtoReader, append } from "./mod.ts"; import { TextProtoReader, append } from "./mod.ts";
import { stringsReader } from "../io/util.ts"; import { stringsReader } from "../io/util.ts";
import { test, assert, assertEqual } from "../testing/mod.ts"; import { assert, assertEq } from "../testing/asserts.ts";
import { test } from "../testing/mod.ts";
function reader(s: string): TextProtoReader { function reader(s: string): TextProtoReader {
return new TextProtoReader(new BufReader(stringsReader(s))); return new TextProtoReader(new BufReader(stringsReader(s)));
@ -15,15 +16,15 @@ function reader(s: string): TextProtoReader {
test(async function textprotoReader() { test(async function textprotoReader() {
let r = reader("line1\nline2\n"); let r = reader("line1\nline2\n");
let [s, err] = await r.readLine(); let [s, err] = await r.readLine();
assertEqual(s, "line1"); assertEq(s, "line1");
assert(err == null); assert(err == null);
[s, err] = await r.readLine(); [s, err] = await r.readLine();
assertEqual(s, "line2"); assertEq(s, "line2");
assert(err == null); assert(err == null);
[s, err] = await r.readLine(); [s, err] = await r.readLine();
assertEqual(s, ""); assertEq(s, "");
assert(err == "EOF"); assert(err == "EOF");
}); });
@ -46,7 +47,7 @@ test(async function textprotoReadMIMEHeader() {
test(async function textprotoReadMIMEHeaderSingle() { test(async function textprotoReadMIMEHeaderSingle() {
let r = reader("Foo: bar\n\n"); let r = reader("Foo: bar\n\n");
let [m, err] = await r.readMIMEHeader(); let [m, err] = await r.readMIMEHeader();
assertEqual(m.get("Foo"), "bar"); assertEq(m.get("Foo"), "bar");
assert(!err); assert(!err);
}); });
@ -87,12 +88,12 @@ test(async function textprotoAppend() {
const u1 = enc.encode("Hello "); const u1 = enc.encode("Hello ");
const u2 = enc.encode("World"); const u2 = enc.encode("World");
const joined = append(u1, u2); const joined = append(u1, u2);
assertEqual(dec.decode(joined), "Hello World"); assertEq(dec.decode(joined), "Hello World");
}); });
test(async function textprotoReadEmpty() { test(async function textprotoReadEmpty() {
let r = reader(""); let r = reader("");
let [, err] = await r.readMIMEHeader(); let [, err] = await r.readMIMEHeader();
// Should not crash! // Should not crash!
assertEqual(err, "EOF"); assertEq(err, "EOF");
}); });

View file

@ -1,23 +1,24 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { assert, test } from "../testing/mod.ts"; import { test } from "../testing/mod.ts";
import { assertEq } from "../testing/asserts.ts";
import { Sha1 } from "./sha1.ts"; import { Sha1 } from "./sha1.ts";
test(function testSha1() { test(function testSha1() {
const sha1 = new Sha1(); const sha1 = new Sha1();
sha1.update("abcde"); sha1.update("abcde");
assert.equal(sha1.toString(), "03de6c570bfe24bfc328ccd7ca46b76eadaf4334"); assertEq(sha1.toString(), "03de6c570bfe24bfc328ccd7ca46b76eadaf4334");
}); });
test(function testSha1WithArray() { test(function testSha1WithArray() {
const data = Uint8Array.of(0x61, 0x62, 0x63, 0x64, 0x65); const data = Uint8Array.of(0x61, 0x62, 0x63, 0x64, 0x65);
const sha1 = new Sha1(); const sha1 = new Sha1();
sha1.update(data); sha1.update(data);
assert.equal(sha1.toString(), "03de6c570bfe24bfc328ccd7ca46b76eadaf4334"); assertEq(sha1.toString(), "03de6c570bfe24bfc328ccd7ca46b76eadaf4334");
}); });
test(function testSha1WithBuffer() { test(function testSha1WithBuffer() {
const data = Uint8Array.of(0x61, 0x62, 0x63, 0x64, 0x65); const data = Uint8Array.of(0x61, 0x62, 0x63, 0x64, 0x65);
const sha1 = new Sha1(); const sha1 = new Sha1();
sha1.update(data.buffer); sha1.update(data.buffer);
assert.equal(sha1.toString(), "03de6c570bfe24bfc328ccd7ca46b76eadaf4334"); assertEq(sha1.toString(), "03de6c570bfe24bfc328ccd7ca46b76eadaf4334");
}); });

View file

@ -3,7 +3,8 @@ import "./sha1_test.ts";
const { Buffer } = Deno; const { Buffer } = Deno;
import { BufReader } from "../io/bufio.ts"; import { BufReader } from "../io/bufio.ts";
import { test, assert } from "../testing/mod.ts"; import { assert, assertEq } from "../testing/asserts.ts";
import { test } from "../testing/mod.ts";
import { import {
acceptable, acceptable,
createSecAccept, createSecAccept,
@ -18,10 +19,10 @@ test(async function testReadUnmaskedTextFrame() {
new Buffer(new Uint8Array([0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f])) new Buffer(new Uint8Array([0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f]))
); );
const frame = await readFrame(buf); const frame = await readFrame(buf);
assert.equal(frame.opcode, OpCode.TextFrame); assertEq(frame.opcode, OpCode.TextFrame);
assert.equal(frame.mask, undefined); assertEq(frame.mask, undefined);
assert.equal(new Buffer(frame.payload).toString(), "Hello"); assertEq(new Buffer(frame.payload).toString(), "Hello");
assert.equal(frame.isLastFrame, true); assertEq(frame.isLastFrame, true);
}); });
test(async function testReadMakedTextFrame() { test(async function testReadMakedTextFrame() {
@ -45,10 +46,10 @@ test(async function testReadMakedTextFrame() {
); );
const frame = await readFrame(buf); const frame = await readFrame(buf);
console.dir(frame); console.dir(frame);
assert.equal(frame.opcode, OpCode.TextFrame); assertEq(frame.opcode, OpCode.TextFrame);
unmask(frame.payload, frame.mask); unmask(frame.payload, frame.mask);
assert.equal(new Buffer(frame.payload).toString(), "Hello"); assertEq(new Buffer(frame.payload).toString(), "Hello");
assert.equal(frame.isLastFrame, true); assertEq(frame.isLastFrame, true);
}); });
test(async function testReadUnmaskedSplittedTextFrames() { test(async function testReadUnmaskedSplittedTextFrames() {
@ -59,15 +60,15 @@ test(async function testReadUnmaskedSplittedTextFrames() {
new Buffer(new Uint8Array([0x80, 0x02, 0x6c, 0x6f])) new Buffer(new Uint8Array([0x80, 0x02, 0x6c, 0x6f]))
); );
const [f1, f2] = await Promise.all([readFrame(buf1), readFrame(buf2)]); const [f1, f2] = await Promise.all([readFrame(buf1), readFrame(buf2)]);
assert.equal(f1.isLastFrame, false); assertEq(f1.isLastFrame, false);
assert.equal(f1.mask, undefined); assertEq(f1.mask, undefined);
assert.equal(f1.opcode, OpCode.TextFrame); assertEq(f1.opcode, OpCode.TextFrame);
assert.equal(new Buffer(f1.payload).toString(), "Hel"); assertEq(new Buffer(f1.payload).toString(), "Hel");
assert.equal(f2.isLastFrame, true); assertEq(f2.isLastFrame, true);
assert.equal(f2.mask, undefined); assertEq(f2.mask, undefined);
assert.equal(f2.opcode, OpCode.Continue); assertEq(f2.opcode, OpCode.Continue);
assert.equal(new Buffer(f2.payload).toString(), "lo"); assertEq(new Buffer(f2.payload).toString(), "lo");
}); });
test(async function testReadUnmaksedPingPongFrame() { test(async function testReadUnmaksedPingPongFrame() {
@ -76,8 +77,8 @@ test(async function testReadUnmaksedPingPongFrame() {
new Buffer(new Uint8Array([0x89, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f])) new Buffer(new Uint8Array([0x89, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f]))
); );
const ping = await readFrame(buf); const ping = await readFrame(buf);
assert.equal(ping.opcode, OpCode.Ping); assertEq(ping.opcode, OpCode.Ping);
assert.equal(new Buffer(ping.payload).toString(), "Hello"); assertEq(new Buffer(ping.payload).toString(), "Hello");
const buf2 = new BufReader( const buf2 = new BufReader(
new Buffer( new Buffer(
@ -97,10 +98,10 @@ test(async function testReadUnmaksedPingPongFrame() {
) )
); );
const pong = await readFrame(buf2); const pong = await readFrame(buf2);
assert.equal(pong.opcode, OpCode.Pong); assertEq(pong.opcode, OpCode.Pong);
assert(pong.mask !== undefined); assert(pong.mask !== undefined);
unmask(pong.payload, pong.mask); unmask(pong.payload, pong.mask);
assert.equal(new Buffer(pong.payload).toString(), "Hello"); assertEq(new Buffer(pong.payload).toString(), "Hello");
}); });
test(async function testReadUnmaksedBigBinaryFrame() { test(async function testReadUnmaksedBigBinaryFrame() {
@ -110,10 +111,10 @@ test(async function testReadUnmaksedBigBinaryFrame() {
} }
const buf = new BufReader(new Buffer(new Uint8Array(a))); const buf = new BufReader(new Buffer(new Uint8Array(a)));
const bin = await readFrame(buf); const bin = await readFrame(buf);
assert.equal(bin.opcode, OpCode.BinaryFrame); assertEq(bin.opcode, OpCode.BinaryFrame);
assert.equal(bin.isLastFrame, true); assertEq(bin.isLastFrame, true);
assert.equal(bin.mask, undefined); assertEq(bin.mask, undefined);
assert.equal(bin.payload.length, 256); assertEq(bin.payload.length, 256);
}); });
test(async function testReadUnmaskedBigBigBinaryFrame() { test(async function testReadUnmaskedBigBigBinaryFrame() {
@ -123,16 +124,16 @@ test(async function testReadUnmaskedBigBigBinaryFrame() {
} }
const buf = new BufReader(new Buffer(new Uint8Array(a))); const buf = new BufReader(new Buffer(new Uint8Array(a)));
const bin = await readFrame(buf); const bin = await readFrame(buf);
assert.equal(bin.opcode, OpCode.BinaryFrame); assertEq(bin.opcode, OpCode.BinaryFrame);
assert.equal(bin.isLastFrame, true); assertEq(bin.isLastFrame, true);
assert.equal(bin.mask, undefined); assertEq(bin.mask, undefined);
assert.equal(bin.payload.length, 0xffff + 1); assertEq(bin.payload.length, 0xffff + 1);
}); });
test(async function testCreateSecAccept() { test(async function testCreateSecAccept() {
const nonce = "dGhlIHNhbXBsZSBub25jZQ=="; const nonce = "dGhlIHNhbXBsZSBub25jZQ==";
const d = createSecAccept(nonce); const d = createSecAccept(nonce);
assert.equal(d, "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="); assertEq(d, "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=");
}); });
test(function testAcceptable() { test(function testAcceptable() {
@ -142,7 +143,7 @@ test(function testAcceptable() {
"sec-websocket-key": "aaa" "sec-websocket-key": "aaa"
}) })
}); });
assert.equal(ret, true); assertEq(ret, true);
}); });
const invalidHeaders = [ const invalidHeaders = [
@ -157,6 +158,6 @@ test(function testAcceptableInvalid() {
const ret = acceptable({ const ret = acceptable({
headers: new Headers(pat) headers: new Headers(pat)
}); });
assert.equal(ret, false); assertEq(ret, false);
} }
}); });