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

refactor: rewrite testPerm into unitTest (#4231)

Rewrite "testPerm" helper function used for testing of internal 
runtime code. It's been renamed to "unitTest" and provides API that
is extensible in the future by accepting optional "UnitTestOptions" 
argument. "test" helper was also removed and replaced by
overloaded version of "unitTest" that takes only function argument.

"UnitTestOptions" currently supports "perms" and "skip"
options, where former works exactly as first argument to "testPerm"
did, while the latter allows to conditionally skip tests.
This commit is contained in:
Bartek Iwańczuk 2020-03-04 17:31:14 +01:00 committed by GitHub
parent 30682cf74f
commit 8d96dffa41
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
60 changed files with 2389 additions and 2047 deletions

View file

@ -1,14 +1,14 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, assert, assertEquals } from "./test_util.ts";
import { unitTest, assert, assertEquals } from "./test_util.ts";
test(function blobString(): void {
unitTest(function blobString(): void {
const b1 = new Blob(["Hello World"]);
const str = "Test";
const b2 = new Blob([b1, str]);
assertEquals(b2.size, b1.size + str.length);
});
test(function blobBuffer(): void {
unitTest(function blobBuffer(): void {
const buffer = new ArrayBuffer(12);
const u8 = new Uint8Array(buffer);
const f1 = new Float32Array(buffer);
@ -18,7 +18,7 @@ test(function blobBuffer(): void {
assertEquals(b2.size, 3 * u8.length);
});
test(function blobSlice(): void {
unitTest(function blobSlice(): void {
const blob = new Blob(["Deno", "Foo"]);
const b1 = blob.slice(0, 3, "Text/HTML");
assert(b1 instanceof Blob);
@ -32,7 +32,7 @@ test(function blobSlice(): void {
assertEquals(b4.size, blob.size);
});
test(function blobShouldNotThrowError(): void {
unitTest(function blobShouldNotThrowError(): void {
let hasThrown = false;
try {
@ -50,7 +50,7 @@ test(function blobShouldNotThrowError(): void {
assertEquals(hasThrown, false);
});
test(function nativeEndLine(): void {
unitTest(function nativeEndLine(): void {
const options: object = {
ending: "native"
};

View file

@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, testPerm, assertEquals, assert } from "./test_util.ts";
import { unitTest, assertEquals, assert } from "./test_util.ts";
// just a hack to get a body object
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@ -21,7 +21,7 @@ const intArrays = [
Float32Array,
Float64Array
];
test(async function arrayBufferFromByteArrays(): Promise<void> {
unitTest(async function arrayBufferFromByteArrays(): Promise<void> {
const buffer = new TextEncoder().encode("ahoyhoy8").buffer;
for (const type of intArrays) {
@ -32,37 +32,43 @@ test(async function arrayBufferFromByteArrays(): Promise<void> {
});
//FormData
testPerm({ net: true }, async function bodyMultipartFormData(): Promise<void> {
const response = await fetch(
"http://localhost:4545/cli/tests/subdir/multipart_form_data.txt"
);
const text = await response.text();
unitTest(
{ perms: { net: true } },
async function bodyMultipartFormData(): Promise<void> {
const response = await fetch(
"http://localhost:4545/cli/tests/subdir/multipart_form_data.txt"
);
const text = await response.text();
const body = buildBody(text);
const body = buildBody(text);
// @ts-ignore
body.contentType = "multipart/form-data;boundary=boundary";
// @ts-ignore
body.contentType = "multipart/form-data;boundary=boundary";
const formData = await body.formData();
assert(formData.has("field_1"));
assertEquals(formData.get("field_1")!.toString(), "value_1 \r\n");
assert(formData.has("field_2"));
});
const formData = await body.formData();
assert(formData.has("field_1"));
assertEquals(formData.get("field_1")!.toString(), "value_1 \r\n");
assert(formData.has("field_2"));
}
);
testPerm({ net: true }, async function bodyURLEncodedFormData(): Promise<void> {
const response = await fetch(
"http://localhost:4545/cli/tests/subdir/form_urlencoded.txt"
);
const text = await response.text();
unitTest(
{ perms: { net: true } },
async function bodyURLEncodedFormData(): Promise<void> {
const response = await fetch(
"http://localhost:4545/cli/tests/subdir/form_urlencoded.txt"
);
const text = await response.text();
const body = buildBody(text);
const body = buildBody(text);
// @ts-ignore
body.contentType = "application/x-www-form-urlencoded";
// @ts-ignore
body.contentType = "application/x-www-form-urlencoded";
const formData = await body.formData();
assert(formData.has("field_1"));
assertEquals(formData.get("field_1")!.toString(), "Hi");
assert(formData.has("field_2"));
assertEquals(formData.get("field_2")!.toString(), "<Deno>");
});
const formData = await body.formData();
assert(formData.has("field_1"));
assertEquals(formData.get("field_1")!.toString(), "Hi");
assert(formData.has("field_2"));
assertEquals(formData.get("field_2")!.toString(), "<Deno>");
}
);

View file

@ -3,7 +3,12 @@
// This code has been ported almost directly from Go's src/bytes/buffer_test.go
// Copyright 2009 The Go Authors. All rights reserved. BSD license.
// https://github.com/golang/go/blob/master/LICENSE
import { assertEquals, assert, assertStrContains, test } from "./test_util.ts";
import {
assertEquals,
assert,
assertStrContains,
unitTest
} from "./test_util.ts";
const { Buffer, readAll, readAllSync, writeAll, writeAllSync } = Deno;
type Buffer = Deno.Buffer;
@ -76,7 +81,7 @@ function repeat(c: string, bytes: number): Uint8Array {
return ui8;
}
test(function bufferNewBuffer(): void {
unitTest(function bufferNewBuffer(): void {
init();
assert(testBytes);
assert(testString);
@ -84,7 +89,7 @@ test(function bufferNewBuffer(): void {
check(buf, testString);
});
test(async function bufferBasicOperations(): Promise<void> {
unitTest(async function bufferBasicOperations(): Promise<void> {
init();
assert(testBytes);
assert(testString);
@ -124,7 +129,7 @@ test(async function bufferBasicOperations(): Promise<void> {
}
});
test(async function bufferReadEmptyAtEOF(): Promise<void> {
unitTest(async function bufferReadEmptyAtEOF(): Promise<void> {
// check that EOF of 'buf' is not reached (even though it's empty) if
// results are written to buffer that has 0 length (ie. it can't store any data)
const buf = new Buffer();
@ -133,7 +138,7 @@ test(async function bufferReadEmptyAtEOF(): Promise<void> {
assertEquals(result, 0);
});
test(async function bufferLargeByteWrites(): Promise<void> {
unitTest(async function bufferLargeByteWrites(): Promise<void> {
init();
const buf = new Buffer();
const limit = 9;
@ -144,7 +149,7 @@ test(async function bufferLargeByteWrites(): Promise<void> {
check(buf, "");
});
test(async function bufferTooLargeByteWrites(): Promise<void> {
unitTest(async function bufferTooLargeByteWrites(): Promise<void> {
init();
const tmp = new Uint8Array(72);
const growLen = Number.MAX_VALUE;
@ -163,7 +168,7 @@ test(async function bufferTooLargeByteWrites(): Promise<void> {
assertStrContains(err.message, "grown beyond the maximum size");
});
test(async function bufferLargeByteReads(): Promise<void> {
unitTest(async function bufferLargeByteReads(): Promise<void> {
init();
assert(testBytes);
assert(testString);
@ -176,12 +181,12 @@ test(async function bufferLargeByteReads(): Promise<void> {
check(buf, "");
});
test(function bufferCapWithPreallocatedSlice(): void {
unitTest(function bufferCapWithPreallocatedSlice(): void {
const buf = new Buffer(new ArrayBuffer(10));
assertEquals(buf.capacity, 10);
});
test(async function bufferReadFrom(): Promise<void> {
unitTest(async function bufferReadFrom(): Promise<void> {
init();
assert(testBytes);
assert(testString);
@ -200,7 +205,7 @@ test(async function bufferReadFrom(): Promise<void> {
}
});
test(async function bufferReadFromSync(): Promise<void> {
unitTest(async function bufferReadFromSync(): Promise<void> {
init();
assert(testBytes);
assert(testString);
@ -219,7 +224,7 @@ test(async function bufferReadFromSync(): Promise<void> {
}
});
test(async function bufferTestGrow(): Promise<void> {
unitTest(async function bufferTestGrow(): Promise<void> {
const tmp = new Uint8Array(72);
for (const startLen of [0, 100, 1000, 10000, 100000]) {
const xBytes = repeat("x", startLen);
@ -244,7 +249,7 @@ test(async function bufferTestGrow(): Promise<void> {
}
});
test(async function testReadAll(): Promise<void> {
unitTest(async function testReadAll(): Promise<void> {
init();
assert(testBytes);
const reader = new Buffer(testBytes.buffer as ArrayBuffer);
@ -255,7 +260,7 @@ test(async function testReadAll(): Promise<void> {
}
});
test(function testReadAllSync(): void {
unitTest(function testReadAllSync(): void {
init();
assert(testBytes);
const reader = new Buffer(testBytes.buffer as ArrayBuffer);
@ -266,7 +271,7 @@ test(function testReadAllSync(): void {
}
});
test(async function testWriteAll(): Promise<void> {
unitTest(async function testWriteAll(): Promise<void> {
init();
assert(testBytes);
const writer = new Buffer();
@ -278,7 +283,7 @@ test(async function testWriteAll(): Promise<void> {
}
});
test(function testWriteAllSync(): void {
unitTest(function testWriteAllSync(): void {
init();
assert(testBytes);
const writer = new Buffer();

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, assert } from "./test_util.ts";
import { unitTest, assert } from "./test_util.ts";
test(function buildInfo(): void {
unitTest(function buildInfo(): void {
// Deno.build is injected by rollup at compile time. Here
// we check it has been properly transformed.
const { arch, os } = Deno.build;

View file

@ -1,58 +1,62 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { testPerm, assert, assertEquals } from "./test_util.ts";
import { unitTest, assert, assertEquals } from "./test_util.ts";
const isNotWindows = Deno.build.os !== "win";
testPerm({ read: true, write: true }, function chmodSyncSuccess(): void {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const tempDir = Deno.makeTempDirSync();
const filename = tempDir + "/test.txt";
Deno.writeFileSync(filename, data, { perm: 0o666 });
unitTest(
{ perms: { read: true, write: true } },
function chmodSyncSuccess(): void {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const tempDir = Deno.makeTempDirSync();
const filename = tempDir + "/test.txt";
Deno.writeFileSync(filename, data, { perm: 0o666 });
// On windows no effect, but should not crash
Deno.chmodSync(filename, 0o777);
// On windows no effect, but should not crash
Deno.chmodSync(filename, 0o777);
// Check success when not on windows
if (isNotWindows) {
const fileInfo = Deno.statSync(filename);
assert(fileInfo.mode);
assertEquals(fileInfo.mode & 0o777, 0o777);
}
});
// Check symlink when not on windows
if (isNotWindows) {
testPerm(
{ read: true, write: true },
function chmodSyncSymlinkSuccess(): void {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const tempDir = Deno.makeTempDirSync();
const filename = tempDir + "/test.txt";
Deno.writeFileSync(filename, data, { perm: 0o666 });
const symlinkName = tempDir + "/test_symlink.txt";
Deno.symlinkSync(filename, symlinkName);
let symlinkInfo = Deno.lstatSync(symlinkName);
assert(symlinkInfo.mode);
const symlinkMode = symlinkInfo.mode & 0o777; // platform dependent
Deno.chmodSync(symlinkName, 0o777);
// Change actual file mode, not symlink
// Check success when not on windows
if (isNotWindows) {
const fileInfo = Deno.statSync(filename);
assert(fileInfo.mode);
assertEquals(fileInfo.mode & 0o777, 0o777);
symlinkInfo = Deno.lstatSync(symlinkName);
assert(symlinkInfo.mode);
assertEquals(symlinkInfo.mode & 0o777, symlinkMode);
}
);
}
}
);
testPerm({ write: true }, function chmodSyncFailure(): void {
// Check symlink when not on windows
unitTest(
{
skip: Deno.build.os === "win",
perms: { read: true, write: true }
},
function chmodSyncSymlinkSuccess(): void {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const tempDir = Deno.makeTempDirSync();
const filename = tempDir + "/test.txt";
Deno.writeFileSync(filename, data, { perm: 0o666 });
const symlinkName = tempDir + "/test_symlink.txt";
Deno.symlinkSync(filename, symlinkName);
let symlinkInfo = Deno.lstatSync(symlinkName);
assert(symlinkInfo.mode);
const symlinkMode = symlinkInfo.mode & 0o777; // platform dependent
Deno.chmodSync(symlinkName, 0o777);
// Change actual file mode, not symlink
const fileInfo = Deno.statSync(filename);
assert(fileInfo.mode);
assertEquals(fileInfo.mode & 0o777, 0o777);
symlinkInfo = Deno.lstatSync(symlinkName);
assert(symlinkInfo.mode);
assertEquals(symlinkInfo.mode & 0o777, symlinkMode);
}
);
unitTest({ perms: { write: true } }, function chmodSyncFailure(): void {
let err;
try {
const filename = "/badfile.txt";
@ -63,7 +67,7 @@ testPerm({ write: true }, function chmodSyncFailure(): void {
assert(err instanceof Deno.errors.NotFound);
});
testPerm({ write: false }, function chmodSyncPerm(): void {
unitTest({ perms: { write: false } }, function chmodSyncPerm(): void {
let err;
try {
Deno.chmodSync("/somefile.txt", 0o777);
@ -74,58 +78,63 @@ testPerm({ write: false }, function chmodSyncPerm(): void {
assertEquals(err.name, "PermissionDenied");
});
testPerm({ read: true, write: true }, async function chmodSuccess(): Promise<
void
> {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const tempDir = Deno.makeTempDirSync();
const filename = tempDir + "/test.txt";
Deno.writeFileSync(filename, data, { perm: 0o666 });
unitTest(
{ perms: { read: true, write: true } },
async function chmodSuccess(): Promise<void> {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const tempDir = Deno.makeTempDirSync();
const filename = tempDir + "/test.txt";
Deno.writeFileSync(filename, data, { perm: 0o666 });
// On windows no effect, but should not crash
await Deno.chmod(filename, 0o777);
// On windows no effect, but should not crash
await Deno.chmod(filename, 0o777);
// Check success when not on windows
if (isNotWindows) {
const fileInfo = Deno.statSync(filename);
assert(fileInfo.mode);
assertEquals(fileInfo.mode & 0o777, 0o777);
}
});
// Check symlink when not on windows
if (isNotWindows) {
testPerm(
{ read: true, write: true },
async function chmodSymlinkSuccess(): Promise<void> {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const tempDir = Deno.makeTempDirSync();
const filename = tempDir + "/test.txt";
Deno.writeFileSync(filename, data, { perm: 0o666 });
const symlinkName = tempDir + "/test_symlink.txt";
Deno.symlinkSync(filename, symlinkName);
let symlinkInfo = Deno.lstatSync(symlinkName);
assert(symlinkInfo.mode);
const symlinkMode = symlinkInfo.mode & 0o777; // platform dependent
await Deno.chmod(symlinkName, 0o777);
// Just change actual file mode, not symlink
// Check success when not on windows
if (isNotWindows) {
const fileInfo = Deno.statSync(filename);
assert(fileInfo.mode);
assertEquals(fileInfo.mode & 0o777, 0o777);
symlinkInfo = Deno.lstatSync(symlinkName);
assert(symlinkInfo.mode);
assertEquals(symlinkInfo.mode & 0o777, symlinkMode);
}
);
}
}
);
testPerm({ write: true }, async function chmodFailure(): Promise<void> {
// Check symlink when not on windows
unitTest(
{
skip: Deno.build.os === "win",
perms: { read: true, write: true }
},
async function chmodSymlinkSuccess(): Promise<void> {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const tempDir = Deno.makeTempDirSync();
const filename = tempDir + "/test.txt";
Deno.writeFileSync(filename, data, { perm: 0o666 });
const symlinkName = tempDir + "/test_symlink.txt";
Deno.symlinkSync(filename, symlinkName);
let symlinkInfo = Deno.lstatSync(symlinkName);
assert(symlinkInfo.mode);
const symlinkMode = symlinkInfo.mode & 0o777; // platform dependent
await Deno.chmod(symlinkName, 0o777);
// Just change actual file mode, not symlink
const fileInfo = Deno.statSync(filename);
assert(fileInfo.mode);
assertEquals(fileInfo.mode & 0o777, 0o777);
symlinkInfo = Deno.lstatSync(symlinkName);
assert(symlinkInfo.mode);
assertEquals(symlinkInfo.mode & 0o777, symlinkMode);
}
);
unitTest({ perms: { write: true } }, async function chmodFailure(): Promise<
void
> {
let err;
try {
const filename = "/badfile.txt";
@ -136,7 +145,9 @@ testPerm({ write: true }, async function chmodFailure(): Promise<void> {
assert(err instanceof Deno.errors.NotFound);
});
testPerm({ write: false }, async function chmodPerm(): Promise<void> {
unitTest({ perms: { write: false } }, async function chmodPerm(): Promise<
void
> {
let err;
try {
await Deno.chmod("/somefile.txt", 0o777);

View file

@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { testPerm, assertEquals, assert } from "./test_util.ts";
import { unitTest, assertEquals, assert } from "./test_util.ts";
// chown on Windows is noop for now, so ignore its testing on Windows
if (Deno.build.os !== "win") {
@ -28,7 +28,7 @@ if (Deno.build.os !== "win") {
return { uid, gid };
}
testPerm({}, async function chownNoWritePermission(): Promise<void> {
unitTest(async function chownNoWritePermission(): Promise<void> {
const filePath = "chown_test_file.txt";
try {
await Deno.chown(filePath, 1000, 1000);
@ -37,8 +37,8 @@ if (Deno.build.os !== "win") {
}
});
testPerm(
{ run: true, write: true },
unitTest(
{ perms: { run: true, write: true } },
async function chownSyncFileNotExist(): Promise<void> {
const { uid, gid } = await getUidAndGid();
const filePath = Deno.makeTempDirSync() + "/chown_test_file.txt";
@ -51,8 +51,8 @@ if (Deno.build.os !== "win") {
}
);
testPerm(
{ run: true, write: true },
unitTest(
{ perms: { run: true, write: true } },
async function chownFileNotExist(): Promise<void> {
const { uid, gid } = await getUidAndGid();
const filePath = (await Deno.makeTempDir()) + "/chown_test_file.txt";
@ -65,42 +65,46 @@ if (Deno.build.os !== "win") {
}
);
testPerm({ write: true }, function chownSyncPermissionDenied(): void {
const enc = new TextEncoder();
const dirPath = Deno.makeTempDirSync();
const filePath = dirPath + "/chown_test_file.txt";
const fileData = enc.encode("Hello");
Deno.writeFileSync(filePath, fileData);
unitTest(
{ perms: { write: true } },
function chownSyncPermissionDenied(): void {
const enc = new TextEncoder();
const dirPath = Deno.makeTempDirSync();
const filePath = dirPath + "/chown_test_file.txt";
const fileData = enc.encode("Hello");
Deno.writeFileSync(filePath, fileData);
try {
// try changing the file's owner to root
Deno.chownSync(filePath, 0, 0);
} catch (e) {
assert(e instanceof Deno.errors.PermissionDenied);
try {
// try changing the file's owner to root
Deno.chownSync(filePath, 0, 0);
} catch (e) {
assert(e instanceof Deno.errors.PermissionDenied);
}
Deno.removeSync(dirPath, { recursive: true });
}
Deno.removeSync(dirPath, { recursive: true });
});
);
testPerm({ write: true }, async function chownPermissionDenied(): Promise<
void
> {
const enc = new TextEncoder();
const dirPath = await Deno.makeTempDir();
const filePath = dirPath + "/chown_test_file.txt";
const fileData = enc.encode("Hello");
await Deno.writeFile(filePath, fileData);
unitTest(
{ perms: { write: true } },
async function chownPermissionDenied(): Promise<void> {
const enc = new TextEncoder();
const dirPath = await Deno.makeTempDir();
const filePath = dirPath + "/chown_test_file.txt";
const fileData = enc.encode("Hello");
await Deno.writeFile(filePath, fileData);
try {
// try changing the file's owner to root
await Deno.chown(filePath, 0, 0);
} catch (e) {
assert(e instanceof Deno.errors.PermissionDenied);
try {
// try changing the file's owner to root
await Deno.chown(filePath, 0, 0);
} catch (e) {
assert(e instanceof Deno.errors.PermissionDenied);
}
await Deno.remove(dirPath, { recursive: true });
}
await Deno.remove(dirPath, { recursive: true });
});
);
testPerm(
{ run: true, write: true },
unitTest(
{ perms: { run: true, write: true } },
async function chownSyncSucceed(): Promise<void> {
// TODO: when a file's owner is actually being changed,
// chown only succeeds if run under priviledged user (root)
@ -121,22 +125,23 @@ if (Deno.build.os !== "win") {
}
);
testPerm({ run: true, write: true }, async function chownSucceed(): Promise<
void
> {
// TODO: same as chownSyncSucceed
const { uid, gid } = await getUidAndGid();
unitTest(
{ perms: { run: true, write: true } },
async function chownSucceed(): Promise<void> {
// TODO: same as chownSyncSucceed
const { uid, gid } = await getUidAndGid();
const enc = new TextEncoder();
const dirPath = await Deno.makeTempDir();
const filePath = dirPath + "/chown_test_file.txt";
const fileData = enc.encode("Hello");
await Deno.writeFile(filePath, fileData);
const enc = new TextEncoder();
const dirPath = await Deno.makeTempDir();
const filePath = dirPath + "/chown_test_file.txt";
const fileData = enc.encode("Hello");
await Deno.writeFile(filePath, fileData);
// the test script creates this file with the same uid and gid,
// here chown is a noop so it succeeds under non-priviledged user
await Deno.chown(filePath, uid, gid);
// the test script creates this file with the same uid and gid,
// here chown is a noop so it succeeds under non-priviledged user
await Deno.chown(filePath, uid, gid);
Deno.removeSync(dirPath, { recursive: true });
});
Deno.removeSync(dirPath, { recursive: true });
}
);
}

View file

@ -1,10 +1,10 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { assert, assertEquals, test } from "./test_util.ts";
import { assert, assertEquals, unitTest } from "./test_util.ts";
const { compile, transpileOnly, bundle } = Deno;
test(async function compilerApiCompileSources() {
unitTest(async function compilerApiCompileSources() {
const [diagnostics, actual] = await compile("/foo.ts", {
"/foo.ts": `import * as bar from "./bar.ts";\n\nconsole.log(bar);\n`,
"/bar.ts": `export const bar = "bar";\n`
@ -19,7 +19,7 @@ test(async function compilerApiCompileSources() {
]);
});
test(async function compilerApiCompileNoSources() {
unitTest(async function compilerApiCompileNoSources() {
const [diagnostics, actual] = await compile("./cli/tests/subdir/mod1.ts");
assert(diagnostics == null);
assert(actual);
@ -29,7 +29,7 @@ test(async function compilerApiCompileNoSources() {
assert(keys[1].endsWith("print_hello.js"));
});
test(async function compilerApiCompileOptions() {
unitTest(async function compilerApiCompileOptions() {
const [diagnostics, actual] = await compile(
"/foo.ts",
{
@ -46,7 +46,7 @@ test(async function compilerApiCompileOptions() {
assert(actual["/foo.js"].startsWith("define("));
});
test(async function compilerApiCompileLib() {
unitTest(async function compilerApiCompileLib() {
const [diagnostics, actual] = await compile(
"/foo.ts",
{
@ -62,7 +62,7 @@ test(async function compilerApiCompileLib() {
assertEquals(Object.keys(actual), ["/foo.js.map", "/foo.js"]);
});
test(async function compilerApiCompileTypes() {
unitTest(async function compilerApiCompileTypes() {
const [diagnostics, actual] = await compile(
"/foo.ts",
{
@ -77,7 +77,7 @@ test(async function compilerApiCompileTypes() {
assertEquals(Object.keys(actual), ["/foo.js.map", "/foo.js"]);
});
test(async function transpileOnlyApi() {
unitTest(async function transpileOnlyApi() {
const actual = await transpileOnly({
"foo.ts": `export enum Foo { Foo, Bar, Baz };\n`
});
@ -87,7 +87,7 @@ test(async function transpileOnlyApi() {
assert(actual["foo.ts"].map);
});
test(async function transpileOnlyApiConfig() {
unitTest(async function transpileOnlyApiConfig() {
const actual = await transpileOnly(
{
"foo.ts": `export enum Foo { Foo, Bar, Baz };\n`
@ -103,7 +103,7 @@ test(async function transpileOnlyApiConfig() {
assert(actual["foo.ts"].map == null);
});
test(async function bundleApiSources() {
unitTest(async function bundleApiSources() {
const [diagnostics, actual] = await bundle("/foo.ts", {
"/foo.ts": `export * from "./bar.ts";\n`,
"/bar.ts": `export const bar = "bar";\n`
@ -113,14 +113,14 @@ test(async function bundleApiSources() {
assert(actual.includes(`__exp["bar"]`));
});
test(async function bundleApiNoSources() {
unitTest(async function bundleApiNoSources() {
const [diagnostics, actual] = await bundle("./cli/tests/subdir/mod1.ts");
assert(diagnostics == null);
assert(actual.includes(`__instantiate("mod1")`));
assert(actual.includes(`__exp["printHello3"]`));
});
test(async function bundleApiConfig() {
unitTest(async function bundleApiConfig() {
const [diagnostics, actual] = await bundle(
"/foo.ts",
{
@ -135,7 +135,7 @@ test(async function bundleApiConfig() {
assert(!actual.includes(`random`));
});
test(async function bundleApiJsModules() {
unitTest(async function bundleApiJsModules() {
const [diagnostics, actual] = await bundle("/foo.js", {
"/foo.js": `export * from "./bar.js";\n`,
"/bar.js": `export const bar = "bar";\n`
@ -144,7 +144,7 @@ test(async function bundleApiJsModules() {
assert(actual.includes(`System.register("bar",`));
});
test(async function diagnosticsTest() {
unitTest(async function diagnosticsTest() {
const [diagnostics] = await compile("/foo.ts", {
"/foo.ts": `document.getElementById("foo");`
});

View file

@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { assert, assertEquals, test } from "./test_util.ts";
import { assert, assertEquals, unitTest } from "./test_util.ts";
// Some of these APIs aren't exposed in the types and so we have to cast to any
// in order to "trick" TypeScript.
@ -23,7 +23,7 @@ function stringify(...args: unknown[]): string {
// test cases from web-platform-tests
// via https://github.com/web-platform-tests/wpt/blob/master/console/console-is-a-namespace.any.js
test(function consoleShouldBeANamespace(): void {
unitTest(function consoleShouldBeANamespace(): void {
const prototype1 = Object.getPrototypeOf(console);
const prototype2 = Object.getPrototypeOf(prototype1);
@ -31,12 +31,12 @@ test(function consoleShouldBeANamespace(): void {
assertEquals(prototype2, Object.prototype);
});
test(function consoleHasRightInstance(): void {
unitTest(function consoleHasRightInstance(): void {
assert(console instanceof Console);
assertEquals({} instanceof Console, false);
});
test(function consoleTestAssertShouldNotThrowError(): void {
unitTest(function consoleTestAssertShouldNotThrowError(): void {
mockConsole(console => {
console.assert(true);
let hasThrown = undefined;
@ -50,13 +50,13 @@ test(function consoleTestAssertShouldNotThrowError(): void {
});
});
test(function consoleTestStringifyComplexObjects(): void {
unitTest(function consoleTestStringifyComplexObjects(): void {
assertEquals(stringify("foo"), "foo");
assertEquals(stringify(["foo", "bar"]), `[ "foo", "bar" ]`);
assertEquals(stringify({ foo: "bar" }), `{ foo: "bar" }`);
});
test(function consoleTestStringifyLongStrings(): void {
unitTest(function consoleTestStringifyLongStrings(): void {
const veryLongString = "a".repeat(200);
// If we stringify an object containing the long string, it gets abbreviated.
let actual = stringify({ veryLongString });
@ -68,7 +68,7 @@ test(function consoleTestStringifyLongStrings(): void {
});
/* eslint-disable @typescript-eslint/explicit-function-return-type */
test(function consoleTestStringifyCircular(): void {
unitTest(function consoleTestStringifyCircular(): void {
class Base {
a = 1;
m1() {}
@ -173,7 +173,7 @@ test(function consoleTestStringifyCircular(): void {
});
/* eslint-enable @typescript-eslint/explicit-function-return-type */
test(function consoleTestStringifyWithDepth(): void {
unitTest(function consoleTestStringifyWithDepth(): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const nestedObj: any = { a: { b: { c: { d: { e: { f: 42 } } } } } };
assertEquals(
@ -196,7 +196,7 @@ test(function consoleTestStringifyWithDepth(): void {
);
});
test(function consoleTestWithCustomInspector(): void {
unitTest(function consoleTestWithCustomInspector(): void {
class A {
[customInspect](): string {
return "b";
@ -206,7 +206,7 @@ test(function consoleTestWithCustomInspector(): void {
assertEquals(stringify(new A()), "b");
});
test(function consoleTestWithCustomInspectorError(): void {
unitTest(function consoleTestWithCustomInspectorError(): void {
class A {
[customInspect](): string {
throw new Error("BOOM");
@ -227,7 +227,7 @@ test(function consoleTestWithCustomInspectorError(): void {
assertEquals(stringify(B.prototype), "{}");
});
test(function consoleTestWithIntegerFormatSpecifier(): void {
unitTest(function consoleTestWithIntegerFormatSpecifier(): void {
assertEquals(stringify("%i"), "%i");
assertEquals(stringify("%i", 42.0), "42");
assertEquals(stringify("%i", 42), "42");
@ -246,7 +246,7 @@ test(function consoleTestWithIntegerFormatSpecifier(): void {
);
});
test(function consoleTestWithFloatFormatSpecifier(): void {
unitTest(function consoleTestWithFloatFormatSpecifier(): void {
assertEquals(stringify("%f"), "%f");
assertEquals(stringify("%f", 42.0), "42");
assertEquals(stringify("%f", 42), "42");
@ -262,7 +262,7 @@ test(function consoleTestWithFloatFormatSpecifier(): void {
assertEquals(stringify("%f %f", 42), "42 %f");
});
test(function consoleTestWithStringFormatSpecifier(): void {
unitTest(function consoleTestWithStringFormatSpecifier(): void {
assertEquals(stringify("%s"), "%s");
assertEquals(stringify("%s", undefined), "undefined");
assertEquals(stringify("%s", "foo"), "foo");
@ -273,7 +273,7 @@ test(function consoleTestWithStringFormatSpecifier(): void {
assertEquals(stringify("%s", Symbol("foo")), "Symbol(foo)");
});
test(function consoleTestWithObjectFormatSpecifier(): void {
unitTest(function consoleTestWithObjectFormatSpecifier(): void {
assertEquals(stringify("%o"), "%o");
assertEquals(stringify("%o", 42), "42");
assertEquals(stringify("%o", "foo"), "foo");
@ -285,7 +285,7 @@ test(function consoleTestWithObjectFormatSpecifier(): void {
);
});
test(function consoleTestWithVariousOrInvalidFormatSpecifier(): void {
unitTest(function consoleTestWithVariousOrInvalidFormatSpecifier(): void {
assertEquals(stringify("%s:%s"), "%s:%s");
assertEquals(stringify("%i:%i"), "%i:%i");
assertEquals(stringify("%d:%d"), "%d:%d");
@ -301,7 +301,7 @@ test(function consoleTestWithVariousOrInvalidFormatSpecifier(): void {
assertEquals(stringify("abc%", 1), "abc% 1");
});
test(function consoleTestCallToStringOnLabel(): void {
unitTest(function consoleTestCallToStringOnLabel(): void {
const methods = ["count", "countReset", "time", "timeLog", "timeEnd"];
mockConsole(console => {
for (const method of methods) {
@ -317,7 +317,7 @@ test(function consoleTestCallToStringOnLabel(): void {
});
});
test(function consoleTestError(): void {
unitTest(function consoleTestError(): void {
class MyError extends Error {
constructor(errStr: string) {
super(errStr);
@ -335,7 +335,7 @@ test(function consoleTestError(): void {
}
});
test(function consoleTestClear(): void {
unitTest(function consoleTestClear(): void {
const stdoutWriteSync = stdout.writeSync;
const uint8 = new TextEncoder().encode("\x1b[1;1H" + "\x1b[0J");
let buffer = new Uint8Array(0);
@ -354,7 +354,7 @@ test(function consoleTestClear(): void {
});
// Test bound this issue
test(function consoleDetachedLog(): void {
unitTest(function consoleDetachedLog(): void {
mockConsole(console => {
const log = console.log;
const dir = console.dir;
@ -427,7 +427,7 @@ function mockConsole(f: ConsoleExamineFunc): void {
}
// console.group test
test(function consoleGroup(): void {
unitTest(function consoleGroup(): void {
mockConsole((console, out): void => {
console.group("1");
console.log("2");
@ -452,7 +452,7 @@ test(function consoleGroup(): void {
});
// console.group with console.warn test
test(function consoleGroupWarn(): void {
unitTest(function consoleGroupWarn(): void {
mockConsole((console, _out, _err, both): void => {
assert(both);
console.warn("1");
@ -482,7 +482,7 @@ test(function consoleGroupWarn(): void {
});
// console.table test
test(function consoleTable(): void {
unitTest(function consoleTable(): void {
mockConsole((console, out): void => {
console.table({ a: "test", b: 1 });
assertEquals(
@ -653,7 +653,7 @@ test(function consoleTable(): void {
});
// console.log(Error) test
test(function consoleLogShouldNotThrowError(): void {
unitTest(function consoleLogShouldNotThrowError(): void {
mockConsole(console => {
let result = 0;
try {
@ -673,7 +673,7 @@ test(function consoleLogShouldNotThrowError(): void {
});
// console.dir test
test(function consoleDir(): void {
unitTest(function consoleDir(): void {
mockConsole((console, out): void => {
console.dir("DIR");
assertEquals(out.toString(), "DIR\n");
@ -685,7 +685,7 @@ test(function consoleDir(): void {
});
// console.dir test
test(function consoleDirXml(): void {
unitTest(function consoleDirXml(): void {
mockConsole((console, out): void => {
console.dirxml("DIRXML");
assertEquals(out.toString(), "DIRXML\n");
@ -697,7 +697,7 @@ test(function consoleDirXml(): void {
});
// console.trace test
test(function consoleTrace(): void {
unitTest(function consoleTrace(): void {
mockConsole((console, _out, err): void => {
console.trace("%s", "custom message");
assert(err);

View file

@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { testPerm, assert, assertEquals } from "./test_util.ts";
import { unitTest, assert, assertEquals } from "./test_util.ts";
function readFileString(filename: string): string {
const dataRead = Deno.readFileSync(filename);
@ -19,102 +19,119 @@ function assertSameContent(filename1: string, filename2: string): void {
assertEquals(data1, data2);
}
testPerm({ read: true, write: true }, function copyFileSyncSuccess(): void {
const tempDir = Deno.makeTempDirSync();
const fromFilename = tempDir + "/from.txt";
const toFilename = tempDir + "/to.txt";
writeFileString(fromFilename, "Hello world!");
Deno.copyFileSync(fromFilename, toFilename);
// No change to original file
assertEquals(readFileString(fromFilename), "Hello world!");
// Original == Dest
assertSameContent(fromFilename, toFilename);
});
testPerm({ write: true, read: true }, function copyFileSyncFailure(): void {
const tempDir = Deno.makeTempDirSync();
const fromFilename = tempDir + "/from.txt";
const toFilename = tempDir + "/to.txt";
// We skip initial writing here, from.txt does not exist
let err;
try {
unitTest(
{ perms: { read: true, write: true } },
function copyFileSyncSuccess(): void {
const tempDir = Deno.makeTempDirSync();
const fromFilename = tempDir + "/from.txt";
const toFilename = tempDir + "/to.txt";
writeFileString(fromFilename, "Hello world!");
Deno.copyFileSync(fromFilename, toFilename);
} catch (e) {
err = e;
// No change to original file
assertEquals(readFileString(fromFilename), "Hello world!");
// Original == Dest
assertSameContent(fromFilename, toFilename);
}
assert(!!err);
assert(err instanceof Deno.errors.NotFound);
});
);
testPerm({ write: true, read: false }, function copyFileSyncPerm1(): void {
let caughtError = false;
try {
Deno.copyFileSync("/from.txt", "/to.txt");
} catch (e) {
caughtError = true;
assert(e instanceof Deno.errors.PermissionDenied);
unitTest(
{ perms: { write: true, read: true } },
function copyFileSyncFailure(): void {
const tempDir = Deno.makeTempDirSync();
const fromFilename = tempDir + "/from.txt";
const toFilename = tempDir + "/to.txt";
// We skip initial writing here, from.txt does not exist
let err;
try {
Deno.copyFileSync(fromFilename, toFilename);
} catch (e) {
err = e;
}
assert(!!err);
assert(err instanceof Deno.errors.NotFound);
}
assert(caughtError);
});
);
testPerm({ write: false, read: true }, function copyFileSyncPerm2(): void {
let caughtError = false;
try {
Deno.copyFileSync("/from.txt", "/to.txt");
} catch (e) {
caughtError = true;
assert(e instanceof Deno.errors.PermissionDenied);
unitTest(
{ perms: { write: true, read: false } },
function copyFileSyncPerm1(): void {
let caughtError = false;
try {
Deno.copyFileSync("/from.txt", "/to.txt");
} catch (e) {
caughtError = true;
assert(e instanceof Deno.errors.PermissionDenied);
}
assert(caughtError);
}
assert(caughtError);
});
);
testPerm({ read: true, write: true }, function copyFileSyncOverwrite(): void {
const tempDir = Deno.makeTempDirSync();
const fromFilename = tempDir + "/from.txt";
const toFilename = tempDir + "/to.txt";
writeFileString(fromFilename, "Hello world!");
// Make Dest exist and have different content
writeFileString(toFilename, "Goodbye!");
Deno.copyFileSync(fromFilename, toFilename);
// No change to original file
assertEquals(readFileString(fromFilename), "Hello world!");
// Original == Dest
assertSameContent(fromFilename, toFilename);
});
unitTest(
{ perms: { write: false, read: true } },
function copyFileSyncPerm2(): void {
let caughtError = false;
try {
Deno.copyFileSync("/from.txt", "/to.txt");
} catch (e) {
caughtError = true;
assert(e instanceof Deno.errors.PermissionDenied);
}
assert(caughtError);
}
);
testPerm({ read: true, write: true }, async function copyFileSuccess(): Promise<
void
> {
const tempDir = Deno.makeTempDirSync();
const fromFilename = tempDir + "/from.txt";
const toFilename = tempDir + "/to.txt";
writeFileString(fromFilename, "Hello world!");
await Deno.copyFile(fromFilename, toFilename);
// No change to original file
assertEquals(readFileString(fromFilename), "Hello world!");
// Original == Dest
assertSameContent(fromFilename, toFilename);
});
unitTest(
{ perms: { read: true, write: true } },
function copyFileSyncOverwrite(): void {
const tempDir = Deno.makeTempDirSync();
const fromFilename = tempDir + "/from.txt";
const toFilename = tempDir + "/to.txt";
writeFileString(fromFilename, "Hello world!");
// Make Dest exist and have different content
writeFileString(toFilename, "Goodbye!");
Deno.copyFileSync(fromFilename, toFilename);
// No change to original file
assertEquals(readFileString(fromFilename), "Hello world!");
// Original == Dest
assertSameContent(fromFilename, toFilename);
}
);
testPerm({ read: true, write: true }, async function copyFileFailure(): Promise<
void
> {
const tempDir = Deno.makeTempDirSync();
const fromFilename = tempDir + "/from.txt";
const toFilename = tempDir + "/to.txt";
// We skip initial writing here, from.txt does not exist
let err;
try {
unitTest(
{ perms: { read: true, write: true } },
async function copyFileSuccess(): Promise<void> {
const tempDir = Deno.makeTempDirSync();
const fromFilename = tempDir + "/from.txt";
const toFilename = tempDir + "/to.txt";
writeFileString(fromFilename, "Hello world!");
await Deno.copyFile(fromFilename, toFilename);
} catch (e) {
err = e;
// No change to original file
assertEquals(readFileString(fromFilename), "Hello world!");
// Original == Dest
assertSameContent(fromFilename, toFilename);
}
assert(!!err);
assert(err instanceof Deno.errors.NotFound);
});
);
testPerm(
{ read: true, write: true },
unitTest(
{ perms: { read: true, write: true } },
async function copyFileFailure(): Promise<void> {
const tempDir = Deno.makeTempDirSync();
const fromFilename = tempDir + "/from.txt";
const toFilename = tempDir + "/to.txt";
// We skip initial writing here, from.txt does not exist
let err;
try {
await Deno.copyFile(fromFilename, toFilename);
} catch (e) {
err = e;
}
assert(!!err);
assert(err instanceof Deno.errors.NotFound);
}
);
unitTest(
{ perms: { read: true, write: true } },
async function copyFileOverwrite(): Promise<void> {
const tempDir = Deno.makeTempDirSync();
const fromFilename = tempDir + "/from.txt";
@ -130,28 +147,30 @@ testPerm(
}
);
testPerm({ read: false, write: true }, async function copyFilePerm1(): Promise<
void
> {
let caughtError = false;
try {
await Deno.copyFile("/from.txt", "/to.txt");
} catch (e) {
caughtError = true;
assert(e instanceof Deno.errors.PermissionDenied);
unitTest(
{ perms: { read: false, write: true } },
async function copyFilePerm1(): Promise<void> {
let caughtError = false;
try {
await Deno.copyFile("/from.txt", "/to.txt");
} catch (e) {
caughtError = true;
assert(e instanceof Deno.errors.PermissionDenied);
}
assert(caughtError);
}
assert(caughtError);
});
);
testPerm({ read: true, write: false }, async function copyFilePerm2(): Promise<
void
> {
let caughtError = false;
try {
await Deno.copyFile("/from.txt", "/to.txt");
} catch (e) {
caughtError = true;
assert(e instanceof Deno.errors.PermissionDenied);
unitTest(
{ perms: { read: true, write: false } },
async function copyFilePerm2(): Promise<void> {
let caughtError = false;
try {
await Deno.copyFile("/from.txt", "/to.txt");
} catch (e) {
caughtError = true;
assert(e instanceof Deno.errors.PermissionDenied);
}
assert(caughtError);
}
assert(caughtError);
});
);

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, assertEquals } from "./test_util.ts";
import { unitTest, assertEquals } from "./test_util.ts";
test(function customEventInitializedWithDetail(): void {
unitTest(function customEventInitializedWithDetail(): void {
const type = "touchstart";
const detail = { message: "hello" };
const customEventInit = {
@ -20,7 +20,7 @@ test(function customEventInitializedWithDetail(): void {
assertEquals(event.type, type);
});
test(function toStringShouldBeWebCompatibility(): void {
unitTest(function toStringShouldBeWebCompatibility(): void {
const type = "touchstart";
const event = new CustomEvent(type, {});
assertEquals(event.toString(), "[object CustomEvent]");

View file

@ -1,11 +1,11 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, testPerm, assert, assertEquals } from "./test_util.ts";
import { unitTest, assert, assertEquals } from "./test_util.ts";
test(function dirCwdNotNull(): void {
unitTest(function dirCwdNotNull(): void {
assert(Deno.cwd() != null);
});
testPerm({ write: true }, function dirCwdChdirSuccess(): void {
unitTest({ perms: { write: true } }, function dirCwdChdirSuccess(): void {
const initialdir = Deno.cwd();
const path = Deno.makeTempDirSync();
Deno.chdir(path);
@ -18,7 +18,7 @@ testPerm({ write: true }, function dirCwdChdirSuccess(): void {
Deno.chdir(initialdir);
});
testPerm({ write: true }, function dirCwdError(): void {
unitTest({ perms: { write: true } }, function dirCwdError(): void {
// excluding windows since it throws resource busy, while removeSync
if (["linux", "mac"].includes(Deno.build.os)) {
const initialdir = Deno.cwd();
@ -39,7 +39,7 @@ testPerm({ write: true }, function dirCwdError(): void {
}
});
testPerm({ write: true }, function dirChdirError(): void {
unitTest({ perms: { write: true } }, function dirChdirError(): void {
const path = Deno.makeTempDirSync() + "test";
try {
Deno.chdir(path);

View file

@ -1,10 +1,4 @@
import {
assert,
test,
testPerm,
assertMatch,
unreachable
} from "./test_util.ts";
import { assert, unitTest, assertMatch, unreachable } from "./test_util.ts";
const openErrorStackPattern = new RegExp(
`^.*
@ -14,15 +8,18 @@ const openErrorStackPattern = new RegExp(
"ms"
);
testPerm({ read: true }, async function sendAsyncStackTrace(): Promise<void> {
await Deno.open("nonexistent.txt")
.then(unreachable)
.catch((error): void => {
assertMatch(error.stack, openErrorStackPattern);
});
});
unitTest(
{ perms: { read: true } },
async function sendAsyncStackTrace(): Promise<void> {
await Deno.open("nonexistent.txt")
.then(unreachable)
.catch((error): void => {
assertMatch(error.stack, openErrorStackPattern);
});
}
);
test(async function malformedJsonControlBuffer(): Promise<void> {
unitTest(async function malformedJsonControlBuffer(): Promise<void> {
// @ts-ignore
const opId = Deno.core.ops()["op_open"];
// @ts-ignore

View file

@ -2,7 +2,7 @@ import {
assert,
assertEquals,
assertMatch,
test,
unitTest,
unreachable
} from "./test_util.ts";
@ -14,7 +14,7 @@ const readErrorStackPattern = new RegExp(
"ms"
);
test(async function sendAsyncStackTrace(): Promise<void> {
unitTest(async function sendAsyncStackTrace(): Promise<void> {
const buf = new Uint8Array(10);
const rid = 10;
try {
@ -25,7 +25,7 @@ test(async function sendAsyncStackTrace(): Promise<void> {
}
});
test(async function malformedMinimalControlBuffer(): Promise<void> {
unitTest(async function malformedMinimalControlBuffer(): Promise<void> {
// @ts-ignore
const readOpId = Deno.core.ops()["op_read"];
// @ts-ignore

View file

@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, assert } from "./test_util.ts";
import { unitTest, assert } from "./test_util.ts";
// @ts-ignore TypeScript (as of 3.7) does not support indexing namespaces by symbol
const { setPrepareStackTrace } = Deno[Deno.symbols.internal];
@ -80,7 +80,7 @@ function getMockCallSite(
};
}
test(function prepareStackTrace(): void {
unitTest(function prepareStackTrace(): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const MockError = {} as any;
setPrepareStackTrace(MockError);
@ -96,7 +96,7 @@ test(function prepareStackTrace(): void {
assert(result.includes(".ts:"), "should remap to something in 'js/'");
});
test(function applySourceMap(): void {
unitTest(function applySourceMap(): void {
const result = Deno.applySourceMap({
filename: "CLI_SNAPSHOT.js",
line: 23,

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, assertEquals } from "./test_util.ts";
import { unitTest, assertEquals } from "./test_util.ts";
test(function addEventListenerTest(): void {
unitTest(function addEventListenerTest(): void {
const document = new EventTarget();
// @ts-ignore tests ignoring the type system for resilience
@ -12,7 +12,7 @@ test(function addEventListenerTest(): void {
assertEquals(document.addEventListener("x", null), undefined);
});
test(function constructedEventTargetCanBeUsedAsExpected(): void {
unitTest(function constructedEventTargetCanBeUsedAsExpected(): void {
const target = new EventTarget();
const event = new Event("foo", { bubbles: true, cancelable: false });
let callCount = 0;
@ -35,7 +35,7 @@ test(function constructedEventTargetCanBeUsedAsExpected(): void {
assertEquals(callCount, 2);
});
test(function anEventTargetCanBeSubclassed(): void {
unitTest(function anEventTargetCanBeSubclassed(): void {
class NicerEventTarget extends EventTarget {
on(
type: string,
@ -69,7 +69,7 @@ test(function anEventTargetCanBeSubclassed(): void {
assertEquals(callCount, 0);
});
test(function removingNullEventListenerShouldSucceed(): void {
unitTest(function removingNullEventListenerShouldSucceed(): void {
const document = new EventTarget();
// @ts-ignore
assertEquals(document.removeEventListener("x", null, false), undefined);
@ -79,7 +79,7 @@ test(function removingNullEventListenerShouldSucceed(): void {
assertEquals(document.removeEventListener("x", null), undefined);
});
test(function constructedEventTargetUseObjectPrototype(): void {
unitTest(function constructedEventTargetUseObjectPrototype(): void {
const target = new EventTarget();
const event = new Event("toString", { bubbles: true, cancelable: false });
let callCount = 0;
@ -102,12 +102,12 @@ test(function constructedEventTargetUseObjectPrototype(): void {
assertEquals(callCount, 2);
});
test(function toStringShouldBeWebCompatible(): void {
unitTest(function toStringShouldBeWebCompatible(): void {
const target = new EventTarget();
assertEquals(target.toString(), "[object EventTarget]");
});
test(function dispatchEventShouldNotThrowError(): void {
unitTest(function dispatchEventShouldNotThrowError(): void {
let hasThrown = false;
try {
@ -126,7 +126,7 @@ test(function dispatchEventShouldNotThrowError(): void {
assertEquals(hasThrown, false);
});
test(function eventTargetThisShouldDefaultToWindow(): void {
unitTest(function eventTargetThisShouldDefaultToWindow(): void {
const {
addEventListener,
dispatchEvent,

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, assertEquals, assert } from "./test_util.ts";
import { unitTest, assertEquals, assert } from "./test_util.ts";
test(function eventInitializedWithType(): void {
unitTest(function eventInitializedWithType(): void {
const type = "click";
const event = new Event(type);
@ -13,7 +13,7 @@ test(function eventInitializedWithType(): void {
assertEquals(event.cancelable, false);
});
test(function eventInitializedWithTypeAndDict(): void {
unitTest(function eventInitializedWithTypeAndDict(): void {
const init = "submit";
const eventInit = { bubbles: true, cancelable: true } as EventInit;
const event = new Event(init, eventInit);
@ -26,7 +26,7 @@ test(function eventInitializedWithTypeAndDict(): void {
assertEquals(event.cancelable, true);
});
test(function eventComposedPathSuccess(): void {
unitTest(function eventComposedPathSuccess(): void {
const type = "click";
const event = new Event(type);
const composedPath = event.composedPath();
@ -34,7 +34,7 @@ test(function eventComposedPathSuccess(): void {
assertEquals(composedPath, []);
});
test(function eventStopPropagationSuccess(): void {
unitTest(function eventStopPropagationSuccess(): void {
const type = "click";
const event = new Event(type);
@ -43,7 +43,7 @@ test(function eventStopPropagationSuccess(): void {
assertEquals(event.cancelBubble, true);
});
test(function eventStopImmediatePropagationSuccess(): void {
unitTest(function eventStopImmediatePropagationSuccess(): void {
const type = "click";
const event = new Event(type);
@ -54,7 +54,7 @@ test(function eventStopImmediatePropagationSuccess(): void {
assertEquals(event.cancelBubbleImmediately, true);
});
test(function eventPreventDefaultSuccess(): void {
unitTest(function eventPreventDefaultSuccess(): void {
const type = "click";
const event = new Event(type);
@ -69,7 +69,7 @@ test(function eventPreventDefaultSuccess(): void {
assertEquals(cancelableEvent.defaultPrevented, true);
});
test(function eventInitializedWithNonStringType(): void {
unitTest(function eventInitializedWithNonStringType(): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const type: any = undefined;
const event = new Event(type);
@ -83,7 +83,7 @@ test(function eventInitializedWithNonStringType(): void {
});
// ref https://github.com/web-platform-tests/wpt/blob/master/dom/events/Event-isTrusted.any.js
test(function eventIsTrusted(): void {
unitTest(function eventIsTrusted(): void {
const desc1 = Object.getOwnPropertyDescriptor(new Event("x"), "isTrusted");
assert(desc1);
assertEquals(typeof desc1.get, "function");

View file

@ -1,15 +1,16 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import {
test,
testPerm,
unitTest,
assert,
assertEquals,
assertStrContains,
assertThrows
// fail
assertThrows,
fail
} from "./test_util.ts";
testPerm({ net: true }, async function fetchProtocolError(): Promise<void> {
unitTest({ perms: { net: true } }, async function fetchProtocolError(): Promise<
void
> {
let err;
try {
await fetch("file:///");
@ -20,24 +21,29 @@ testPerm({ net: true }, async function fetchProtocolError(): Promise<void> {
assertStrContains(err.message, "not supported");
});
testPerm({ net: true }, async function fetchConnectionError(): Promise<void> {
let err;
try {
await fetch("http://localhost:4000");
} catch (err_) {
err = err_;
unitTest(
{ perms: { net: true } },
async function fetchConnectionError(): Promise<void> {
let err;
try {
await fetch("http://localhost:4000");
} catch (err_) {
err = err_;
}
assert(err instanceof Deno.errors.Http);
assertStrContains(err.message, "error trying to connect");
}
assert(err instanceof Deno.errors.Http);
assertStrContains(err.message, "error trying to connect");
});
);
testPerm({ net: true }, async function fetchJsonSuccess(): Promise<void> {
unitTest({ perms: { net: true } }, async function fetchJsonSuccess(): Promise<
void
> {
const response = await fetch("http://localhost:4545/cli/tests/fixture.json");
const json = await response.json();
assertEquals(json.name, "deno");
});
test(async function fetchPerm(): Promise<void> {
unitTest(async function fetchPerm(): Promise<void> {
let err;
try {
await fetch("http://localhost:4545/cli/tests/fixture.json");
@ -48,13 +54,13 @@ test(async function fetchPerm(): Promise<void> {
assertEquals(err.name, "PermissionDenied");
});
testPerm({ net: true }, async function fetchUrl(): Promise<void> {
unitTest({ perms: { net: true } }, async function fetchUrl(): Promise<void> {
const response = await fetch("http://localhost:4545/cli/tests/fixture.json");
assertEquals(response.url, "http://localhost:4545/cli/tests/fixture.json");
response.body.close();
});
testPerm({ net: true }, async function fetchURL(): Promise<void> {
unitTest({ perms: { net: true } }, async function fetchURL(): Promise<void> {
const response = await fetch(
new URL("http://localhost:4545/cli/tests/fixture.json")
);
@ -62,7 +68,9 @@ testPerm({ net: true }, async function fetchURL(): Promise<void> {
response.body.close();
});
testPerm({ net: true }, async function fetchHeaders(): Promise<void> {
unitTest({ perms: { net: true } }, async function fetchHeaders(): Promise<
void
> {
const response = await fetch("http://localhost:4545/cli/tests/fixture.json");
const headers = response.headers;
assertEquals(headers.get("Content-Type"), "application/json");
@ -70,7 +78,7 @@ testPerm({ net: true }, async function fetchHeaders(): Promise<void> {
response.body.close();
});
testPerm({ net: true }, async function fetchBlob(): Promise<void> {
unitTest({ perms: { net: true } }, async function fetchBlob(): Promise<void> {
const response = await fetch("http://localhost:4545/cli/tests/fixture.json");
const headers = response.headers;
const blob = await response.blob();
@ -78,7 +86,9 @@ testPerm({ net: true }, async function fetchBlob(): Promise<void> {
assertEquals(blob.size, Number(headers.get("Content-Length")));
});
testPerm({ net: true }, async function fetchBodyUsed(): Promise<void> {
unitTest({ perms: { net: true } }, async function fetchBodyUsed(): Promise<
void
> {
const response = await fetch("http://localhost:4545/cli/tests/fixture.json");
assertEquals(response.bodyUsed, false);
assertThrows((): void => {
@ -89,7 +99,9 @@ testPerm({ net: true }, async function fetchBodyUsed(): Promise<void> {
assertEquals(response.bodyUsed, true);
});
testPerm({ net: true }, async function fetchAsyncIterator(): Promise<void> {
unitTest({ perms: { net: true } }, async function fetchAsyncIterator(): Promise<
void
> {
const response = await fetch("http://localhost:4545/cli/tests/fixture.json");
const headers = response.headers;
let total = 0;
@ -101,7 +113,9 @@ testPerm({ net: true }, async function fetchAsyncIterator(): Promise<void> {
response.body.close();
});
testPerm({ net: true }, async function responseClone(): Promise<void> {
unitTest({ perms: { net: true } }, async function responseClone(): Promise<
void
> {
const response = await fetch("http://localhost:4545/cli/tests/fixture.json");
const response1 = response.clone();
assert(response !== response1);
@ -114,7 +128,9 @@ testPerm({ net: true }, async function responseClone(): Promise<void> {
}
});
testPerm({ net: true }, async function fetchEmptyInvalid(): Promise<void> {
unitTest({ perms: { net: true } }, async function fetchEmptyInvalid(): Promise<
void
> {
let err;
try {
await fetch("");
@ -124,25 +140,26 @@ testPerm({ net: true }, async function fetchEmptyInvalid(): Promise<void> {
assert(err instanceof URIError);
});
testPerm({ net: true }, async function fetchMultipartFormDataSuccess(): Promise<
void
> {
const response = await fetch(
"http://localhost:4545/cli/tests/subdir/multipart_form_data.txt"
);
const formData = await response.formData();
assert(formData.has("field_1"));
assertEquals(formData.get("field_1")!.toString(), "value_1 \r\n");
assert(formData.has("field_2"));
/* TODO(ry) Re-enable this test once we bring back the global File type.
unitTest(
{ perms: { net: true } },
async function fetchMultipartFormDataSuccess(): Promise<void> {
const response = await fetch(
"http://localhost:4545/cli/tests/subdir/multipart_form_data.txt"
);
const formData = await response.formData();
assert(formData.has("field_1"));
assertEquals(formData.get("field_1")!.toString(), "value_1 \r\n");
assert(formData.has("field_2"));
/* TODO(ry) Re-enable this test once we bring back the global File type.
const file = formData.get("field_2") as File;
assertEquals(file.name, "file.js");
*/
// Currently we cannot read from file...
});
// Currently we cannot read from file...
}
);
testPerm(
{ net: true },
unitTest(
{ perms: { net: true } },
async function fetchURLEncodedFormDataSuccess(): Promise<void> {
const response = await fetch(
"http://localhost:4545/cli/tests/subdir/form_urlencoded.txt"
@ -155,32 +172,40 @@ testPerm(
}
);
/*
// TODO: leaking resources
testPerm({ net: true }, async function fetchWithRedirection(): Promise<void> {
const response = await fetch("http://localhost:4546/"); // will redirect to http://localhost:4545/
assertEquals(response.status, 200);
assertEquals(response.statusText, "OK");
assertEquals(response.url, "http://localhost:4545/");
const body = await response.text();
assert(body.includes("<title>Directory listing for /</title>"));
});
unitTest(
{
// TODO(bartlomieju): leaking resources
skip: true,
perms: { net: true }
},
async function fetchWithRedirection(): Promise<void> {
const response = await fetch("http://localhost:4546/"); // will redirect to http://localhost:4545/
assertEquals(response.status, 200);
assertEquals(response.statusText, "OK");
assertEquals(response.url, "http://localhost:4545/");
const body = await response.text();
assert(body.includes("<title>Directory listing for /</title>"));
}
);
// TODO: leaking resources
testPerm({ net: true }, async function fetchWithRelativeRedirection(): Promise<
void
> {
const response = await fetch("http://localhost:4545/cli/tests"); // will redirect to /cli/tests/
assertEquals(response.status, 200);
assertEquals(response.statusText, "OK");
const body = await response.text();
assert(body.includes("<title>Directory listing for /cli/tests/</title>"));
});
*/
unitTest(
{
// TODO: leaking resources
skip: true,
perms: { net: true }
},
async function fetchWithRelativeRedirection(): Promise<void> {
const response = await fetch("http://localhost:4545/cli/tests"); // will redirect to /cli/tests/
assertEquals(response.status, 200);
assertEquals(response.statusText, "OK");
const body = await response.text();
assert(body.includes("<title>Directory listing for /cli/tests/</title>"));
}
);
// The feature below is not implemented, but the test should work after implementation
/*
testPerm({ net: true }, async function fetchWithInfRedirection(): Promise<
unitTest({ perms: { net: true} }, async function fetchWithInfRedirection(): Promise<
void
> {
const response = await fetch("http://localhost:4549/cli/tests"); // will redirect to the same place
@ -188,61 +213,69 @@ testPerm({ net: true }, async function fetchWithInfRedirection(): Promise<
});
*/
testPerm({ net: true }, async function fetchInitStringBody(): Promise<void> {
const data = "Hello World";
const response = await fetch("http://localhost:4545/echo_server", {
method: "POST",
body: data
});
const text = await response.text();
assertEquals(text, data);
assert(response.headers.get("content-type")!.startsWith("text/plain"));
});
unitTest(
{ perms: { net: true } },
async function fetchInitStringBody(): Promise<void> {
const data = "Hello World";
const response = await fetch("http://localhost:4545/echo_server", {
method: "POST",
body: data
});
const text = await response.text();
assertEquals(text, data);
assert(response.headers.get("content-type")!.startsWith("text/plain"));
}
);
testPerm({ net: true }, async function fetchRequestInitStringBody(): Promise<
unitTest(
{ perms: { net: true } },
async function fetchRequestInitStringBody(): Promise<void> {
const data = "Hello World";
const req = new Request("http://localhost:4545/echo_server", {
method: "POST",
body: data
});
const response = await fetch(req);
const text = await response.text();
assertEquals(text, data);
}
);
unitTest(
{ perms: { net: true } },
async function fetchInitTypedArrayBody(): Promise<void> {
const data = "Hello World";
const response = await fetch("http://localhost:4545/echo_server", {
method: "POST",
body: new TextEncoder().encode(data)
});
const text = await response.text();
assertEquals(text, data);
}
);
unitTest(
{ perms: { net: true } },
async function fetchInitURLSearchParamsBody(): Promise<void> {
const data = "param1=value1&param2=value2";
const params = new URLSearchParams(data);
const response = await fetch("http://localhost:4545/echo_server", {
method: "POST",
body: params
});
const text = await response.text();
assertEquals(text, data);
assert(
response.headers
.get("content-type")!
.startsWith("application/x-www-form-urlencoded")
);
}
);
unitTest({ perms: { net: true } }, async function fetchInitBlobBody(): Promise<
void
> {
const data = "Hello World";
const req = new Request("http://localhost:4545/echo_server", {
method: "POST",
body: data
});
const response = await fetch(req);
const text = await response.text();
assertEquals(text, data);
});
testPerm({ net: true }, async function fetchInitTypedArrayBody(): Promise<
void
> {
const data = "Hello World";
const response = await fetch("http://localhost:4545/echo_server", {
method: "POST",
body: new TextEncoder().encode(data)
});
const text = await response.text();
assertEquals(text, data);
});
testPerm({ net: true }, async function fetchInitURLSearchParamsBody(): Promise<
void
> {
const data = "param1=value1&param2=value2";
const params = new URLSearchParams(data);
const response = await fetch("http://localhost:4545/echo_server", {
method: "POST",
body: params
});
const text = await response.text();
assertEquals(text, data);
assert(
response.headers
.get("content-type")!
.startsWith("application/x-www-form-urlencoded")
);
});
testPerm({ net: true }, async function fetchInitBlobBody(): Promise<void> {
const data = "const a = 1";
const blob = new Blob([data], {
type: "text/javascript"
@ -256,7 +289,9 @@ testPerm({ net: true }, async function fetchInitBlobBody(): Promise<void> {
assert(response.headers.get("content-type")!.startsWith("text/javascript"));
});
testPerm({ net: true }, async function fetchUserAgent(): Promise<void> {
unitTest({ perms: { net: true } }, async function fetchUserAgent(): Promise<
void
> {
const data = "Hello World";
const response = await fetch("http://localhost:4545/echo_server", {
method: "POST",
@ -269,7 +304,7 @@ testPerm({ net: true }, async function fetchUserAgent(): Promise<void> {
// TODO(ry) The following tests work but are flaky. There's a race condition
// somewhere. Here is what one of these flaky failures looks like:
//
// test fetchPostBodyString_permW0N1E0R0
// unitTest fetchPostBodyString_permW0N1E0R0
// assertEquals failed. actual = expected = POST /blah HTTP/1.1
// hello: World
// foo: Bar
@ -309,7 +344,7 @@ function bufferServer(addr: string): Deno.Buffer {
return buf;
}
testPerm({ net: true }, async function fetchRequest():Promise<void> {
unitTest({ perms: { net: true} }, async function fetchRequest():Promise<void> {
const addr = "127.0.0.1:4501";
const buf = bufferServer(addr);
const response = await fetch(`http://${addr}/blah`, {
@ -329,7 +364,7 @@ testPerm({ net: true }, async function fetchRequest():Promise<void> {
assertEquals(actual, expected);
});
testPerm({ net: true }, async function fetchPostBodyString():Promise<void> {
unitTest({ perms: { net: true} }, async function fetchPostBodyString():Promise<void> {
const addr = "127.0.0.1:4502";
const buf = bufferServer(addr);
const body = "hello world";
@ -353,7 +388,7 @@ testPerm({ net: true }, async function fetchPostBodyString():Promise<void> {
assertEquals(actual, expected);
});
testPerm({ net: true }, async function fetchPostBodyTypedArray():Promise<void> {
unitTest({ perms: { net: true} }, async function fetchPostBodyTypedArray():Promise<void> {
const addr = "127.0.0.1:4503";
const buf = bufferServer(addr);
const bodyStr = "hello world";
@ -379,51 +414,57 @@ testPerm({ net: true }, async function fetchPostBodyTypedArray():Promise<void> {
});
*/
/*
// TODO: leaking resources
testPerm({ net: true }, async function fetchWithManualRedirection(): Promise<
void
> {
const response = await fetch("http://localhost:4546/", {
redirect: "manual"
}); // will redirect to http://localhost:4545/
assertEquals(response.status, 0);
assertEquals(response.statusText, "");
assertEquals(response.url, "");
assertEquals(response.type, "opaqueredirect");
try {
await response.text();
fail(
"Reponse.text() didn't throw on a filtered response without a body (type opaqueredirect)"
);
} catch (e) {
return;
unitTest(
{
// TODO: leaking resources
skip: true,
perms: { net: true }
},
async function fetchWithManualRedirection(): Promise<void> {
const response = await fetch("http://localhost:4546/", {
redirect: "manual"
}); // will redirect to http://localhost:4545/
assertEquals(response.status, 0);
assertEquals(response.statusText, "");
assertEquals(response.url, "");
assertEquals(response.type, "opaqueredirect");
try {
await response.text();
fail(
"Reponse.text() didn't throw on a filtered response without a body (type opaqueredirect)"
);
} catch (e) {
return;
}
}
});
);
// TODO: leaking resources
testPerm({ net: true }, async function fetchWithErrorRedirection(): Promise<
void
> {
const response = await fetch("http://localhost:4546/", {
redirect: "error"
}); // will redirect to http://localhost:4545/
assertEquals(response.status, 0);
assertEquals(response.statusText, "");
assertEquals(response.url, "");
assertEquals(response.type, "error");
try {
await response.text();
fail(
"Reponse.text() didn't throw on a filtered response without a body (type error)"
);
} catch (e) {
return;
unitTest(
{
// TODO: leaking resources
skip: true,
perms: { net: true }
},
async function fetchWithErrorRedirection(): Promise<void> {
const response = await fetch("http://localhost:4546/", {
redirect: "error"
}); // will redirect to http://localhost:4545/
assertEquals(response.status, 0);
assertEquals(response.statusText, "");
assertEquals(response.url, "");
assertEquals(response.type, "error");
try {
await response.text();
fail(
"Reponse.text() didn't throw on a filtered response without a body (type error)"
);
} catch (e) {
return;
}
}
});
*/
);
test(function responseRedirect(): void {
unitTest(function responseRedirect(): void {
const response = new Response(
"example.com/beforeredirect",
200,
@ -441,7 +482,7 @@ test(function responseRedirect(): void {
assertEquals(redir.type, "default");
});
test(function responseConstructionHeaderRemoval(): void {
unitTest(function responseConstructionHeaderRemoval(): void {
const res = new Response(
"example.com",
200,

View file

@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, assert, assertEquals } from "./test_util.ts";
import { unitTest, assert, assertEquals } from "./test_util.ts";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function testFirstArgument(arg1: any[], expectedSize: number): void {
@ -10,47 +10,47 @@ function testFirstArgument(arg1: any[], expectedSize: number): void {
assertEquals(file.type, "");
}
test(function fileEmptyFileBits(): void {
unitTest(function fileEmptyFileBits(): void {
testFirstArgument([], 0);
});
test(function fileStringFileBits(): void {
unitTest(function fileStringFileBits(): void {
testFirstArgument(["bits"], 4);
});
test(function fileUnicodeStringFileBits(): void {
unitTest(function fileUnicodeStringFileBits(): void {
testFirstArgument(["𝓽𝓮𝔁𝓽"], 16);
});
test(function fileStringObjectFileBits(): void {
unitTest(function fileStringObjectFileBits(): void {
testFirstArgument([new String("string object")], 13);
});
test(function fileEmptyBlobFileBits(): void {
unitTest(function fileEmptyBlobFileBits(): void {
testFirstArgument([new Blob()], 0);
});
test(function fileBlobFileBits(): void {
unitTest(function fileBlobFileBits(): void {
testFirstArgument([new Blob(["bits"])], 4);
});
test(function fileEmptyFileFileBits(): void {
unitTest(function fileEmptyFileFileBits(): void {
testFirstArgument([new File([], "world.txt")], 0);
});
test(function fileFileFileBits(): void {
unitTest(function fileFileFileBits(): void {
testFirstArgument([new File(["bits"], "world.txt")], 4);
});
test(function fileArrayBufferFileBits(): void {
unitTest(function fileArrayBufferFileBits(): void {
testFirstArgument([new ArrayBuffer(8)], 8);
});
test(function fileTypedArrayFileBits(): void {
unitTest(function fileTypedArrayFileBits(): void {
testFirstArgument([new Uint8Array([0x50, 0x41, 0x53, 0x53])], 4);
});
test(function fileVariousFileBits(): void {
unitTest(function fileVariousFileBits(): void {
testFirstArgument(
[
"bits",
@ -64,15 +64,15 @@ test(function fileVariousFileBits(): void {
);
});
test(function fileNumberInFileBits(): void {
unitTest(function fileNumberInFileBits(): void {
testFirstArgument([12], 2);
});
test(function fileArrayInFileBits(): void {
unitTest(function fileArrayInFileBits(): void {
testFirstArgument([[1, 2, 3]], 5);
});
test(function fileObjectInFileBits(): void {
unitTest(function fileObjectInFileBits(): void {
// "[object Object]"
testFirstArgument([{}], 15);
});
@ -84,22 +84,22 @@ function testSecondArgument(arg2: any, expectedFileName: string): void {
assertEquals(file.name, expectedFileName);
}
test(function fileUsingFileName(): void {
unitTest(function fileUsingFileName(): void {
testSecondArgument("dummy", "dummy");
});
test(function fileUsingSpecialCharacterInFileName(): void {
unitTest(function fileUsingSpecialCharacterInFileName(): void {
testSecondArgument("dummy/foo", "dummy:foo");
});
test(function fileUsingNullFileName(): void {
unitTest(function fileUsingNullFileName(): void {
testSecondArgument(null, "null");
});
test(function fileUsingNumberFileName(): void {
unitTest(function fileUsingNumberFileName(): void {
testSecondArgument(1, "1");
});
test(function fileUsingEmptyStringFileName(): void {
unitTest(function fileUsingEmptyStringFileName(): void {
testSecondArgument("", "");
});

View file

@ -1,19 +1,20 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import {
test,
testPerm,
unitTest,
assert,
assertEquals,
assertStrContains
} from "./test_util.ts";
test(function filesStdioFileDescriptors(): void {
unitTest(function filesStdioFileDescriptors(): void {
assertEquals(Deno.stdin.rid, 0);
assertEquals(Deno.stdout.rid, 1);
assertEquals(Deno.stderr.rid, 2);
});
testPerm({ read: true }, async function filesCopyToStdout(): Promise<void> {
unitTest({ perms: { read: true } }, async function filesCopyToStdout(): Promise<
void
> {
const filename = "cli/tests/fixture.json";
const file = await Deno.open(filename);
assert(file.rid > 2);
@ -24,20 +25,23 @@ testPerm({ read: true }, async function filesCopyToStdout(): Promise<void> {
file.close();
});
testPerm({ read: true }, async function filesToAsyncIterator(): Promise<void> {
const filename = "cli/tests/hello.txt";
const file = await Deno.open(filename);
unitTest(
{ perms: { read: true } },
async function filesToAsyncIterator(): Promise<void> {
const filename = "cli/tests/hello.txt";
const file = await Deno.open(filename);
let totalSize = 0;
for await (const buf of Deno.toAsyncIterator(file)) {
totalSize += buf.byteLength;
let totalSize = 0;
for await (const buf of Deno.toAsyncIterator(file)) {
totalSize += buf.byteLength;
}
assertEquals(totalSize, 12);
file.close();
}
);
assertEquals(totalSize, 12);
file.close();
});
test(async function readerToAsyncIterator(): Promise<void> {
unitTest(async function readerToAsyncIterator(): Promise<void> {
// ref: https://github.com/denoland/deno/issues/2330
const encoder = new TextEncoder();
@ -70,23 +74,26 @@ test(async function readerToAsyncIterator(): Promise<void> {
assertEquals(totalSize, 12);
});
testPerm({ write: false }, async function writePermFailure(): Promise<void> {
const filename = "tests/hello.txt";
const writeModes: Deno.OpenMode[] = ["w", "a", "x"];
for (const mode of writeModes) {
let err;
try {
await Deno.open(filename, mode);
} catch (e) {
err = e;
unitTest(
{ perms: { write: false } },
async function writePermFailure(): Promise<void> {
const filename = "tests/hello.txt";
const writeModes: Deno.OpenMode[] = ["w", "a", "x"];
for (const mode of writeModes) {
let err;
try {
await Deno.open(filename, mode);
} catch (e) {
err = e;
}
assert(!!err);
assert(err instanceof Deno.errors.PermissionDenied);
assertEquals(err.name, "PermissionDenied");
}
assert(!!err);
assert(err instanceof Deno.errors.PermissionDenied);
assertEquals(err.name, "PermissionDenied");
}
});
);
test(async function openOptions(): Promise<void> {
unitTest(async function openOptions(): Promise<void> {
const filename = "cli/tests/fixture.json";
let err;
try {
@ -131,7 +138,9 @@ test(async function openOptions(): Promise<void> {
);
});
testPerm({ read: false }, async function readPermFailure(): Promise<void> {
unitTest({ perms: { read: false } }, async function readPermFailure(): Promise<
void
> {
let caughtError = false;
try {
await Deno.open("package.json", "r");
@ -143,35 +152,36 @@ testPerm({ read: false }, async function readPermFailure(): Promise<void> {
assert(caughtError);
});
testPerm({ write: true }, async function writeNullBufferFailure(): Promise<
void
> {
const tempDir = Deno.makeTempDirSync();
const filename = tempDir + "hello.txt";
const w = {
write: true,
truncate: true,
create: true
};
const file = await Deno.open(filename, w);
unitTest(
{ perms: { write: true } },
async function writeNullBufferFailure(): Promise<void> {
const tempDir = Deno.makeTempDirSync();
const filename = tempDir + "hello.txt";
const w = {
write: true,
truncate: true,
create: true
};
const file = await Deno.open(filename, w);
// writing null should throw an error
let err;
try {
// @ts-ignore
await file.write(null);
} catch (e) {
err = e;
// writing null should throw an error
let err;
try {
// @ts-ignore
await file.write(null);
} catch (e) {
err = e;
}
// TODO: Check error kind when dispatch_minimal pipes errors properly
assert(!!err);
file.close();
await Deno.remove(tempDir, { recursive: true });
}
// TODO: Check error kind when dispatch_minimal pipes errors properly
assert(!!err);
);
file.close();
await Deno.remove(tempDir, { recursive: true });
});
testPerm(
{ write: true, read: true },
unitTest(
{ perms: { write: true, read: true } },
async function readNullBufferFailure(): Promise<void> {
const tempDir = Deno.makeTempDirSync();
const filename = tempDir + "hello.txt";
@ -197,8 +207,8 @@ testPerm(
}
);
testPerm(
{ write: false, read: false },
unitTest(
{ perms: { write: false, read: false } },
async function readWritePermFailure(): Promise<void> {
const filename = "tests/hello.txt";
const writeModes: Deno.OpenMode[] = ["r+", "w+", "a+", "x+"];
@ -216,63 +226,65 @@ testPerm(
}
);
testPerm({ read: true, write: true }, async function createFile(): Promise<
void
> {
const tempDir = await Deno.makeTempDir();
const filename = tempDir + "/test.txt";
const f = await Deno.create(filename);
let fileInfo = Deno.statSync(filename);
assert(fileInfo.isFile());
assert(fileInfo.len === 0);
const enc = new TextEncoder();
const data = enc.encode("Hello");
await f.write(data);
fileInfo = Deno.statSync(filename);
assert(fileInfo.len === 5);
f.close();
unitTest(
{ perms: { read: true, write: true } },
async function createFile(): Promise<void> {
const tempDir = await Deno.makeTempDir();
const filename = tempDir + "/test.txt";
const f = await Deno.create(filename);
let fileInfo = Deno.statSync(filename);
assert(fileInfo.isFile());
assert(fileInfo.len === 0);
const enc = new TextEncoder();
const data = enc.encode("Hello");
await f.write(data);
fileInfo = Deno.statSync(filename);
assert(fileInfo.len === 5);
f.close();
// TODO: test different modes
await Deno.remove(tempDir, { recursive: true });
});
testPerm({ read: true, write: true }, async function openModeWrite(): Promise<
void
> {
const tempDir = Deno.makeTempDirSync();
const encoder = new TextEncoder();
const filename = tempDir + "hello.txt";
const data = encoder.encode("Hello world!\n");
let file = await Deno.open(filename, "w");
// assert file was created
let fileInfo = Deno.statSync(filename);
assert(fileInfo.isFile());
assertEquals(fileInfo.len, 0);
// write some data
await file.write(data);
fileInfo = Deno.statSync(filename);
assertEquals(fileInfo.len, 13);
// assert we can't read from file
let thrown = false;
try {
const buf = new Uint8Array(20);
await file.read(buf);
} catch (e) {
thrown = true;
} finally {
assert(thrown, "'w' mode shouldn't allow to read file");
// TODO: test different modes
await Deno.remove(tempDir, { recursive: true });
}
file.close();
// assert that existing file is truncated on open
file = await Deno.open(filename, "w");
file.close();
const fileSize = Deno.statSync(filename).len;
assertEquals(fileSize, 0);
await Deno.remove(tempDir, { recursive: true });
});
);
testPerm(
{ read: true, write: true },
unitTest(
{ perms: { read: true, write: true } },
async function openModeWrite(): Promise<void> {
const tempDir = Deno.makeTempDirSync();
const encoder = new TextEncoder();
const filename = tempDir + "hello.txt";
const data = encoder.encode("Hello world!\n");
let file = await Deno.open(filename, "w");
// assert file was created
let fileInfo = Deno.statSync(filename);
assert(fileInfo.isFile());
assertEquals(fileInfo.len, 0);
// write some data
await file.write(data);
fileInfo = Deno.statSync(filename);
assertEquals(fileInfo.len, 13);
// assert we can't read from file
let thrown = false;
try {
const buf = new Uint8Array(20);
await file.read(buf);
} catch (e) {
thrown = true;
} finally {
assert(thrown, "'w' mode shouldn't allow to read file");
}
file.close();
// assert that existing file is truncated on open
file = await Deno.open(filename, "w");
file.close();
const fileSize = Deno.statSync(filename).len;
assertEquals(fileSize, 0);
await Deno.remove(tempDir, { recursive: true });
}
);
unitTest(
{ perms: { read: true, write: true } },
async function openModeWriteRead(): Promise<void> {
const tempDir = Deno.makeTempDirSync();
const encoder = new TextEncoder();
@ -305,7 +317,7 @@ testPerm(
}
);
testPerm({ read: true }, async function seekStart(): Promise<void> {
unitTest({ perms: { read: true } }, async function seekStart(): Promise<void> {
const filename = "cli/tests/hello.txt";
const file = await Deno.open(filename);
const seekPosition = 6;
@ -325,7 +337,7 @@ testPerm({ read: true }, async function seekStart(): Promise<void> {
file.close();
});
testPerm({ read: true }, function seekSyncStart(): void {
unitTest({ perms: { read: true } }, function seekSyncStart(): void {
const filename = "cli/tests/hello.txt";
const file = Deno.openSync(filename);
const seekPosition = 6;
@ -342,7 +354,9 @@ testPerm({ read: true }, function seekSyncStart(): void {
file.close();
});
testPerm({ read: true }, async function seekCurrent(): Promise<void> {
unitTest({ perms: { read: true } }, async function seekCurrent(): Promise<
void
> {
const filename = "cli/tests/hello.txt";
const file = await Deno.open(filename);
// Deliberately move 1 step forward
@ -362,7 +376,7 @@ testPerm({ read: true }, async function seekCurrent(): Promise<void> {
file.close();
});
testPerm({ read: true }, function seekSyncCurrent(): void {
unitTest({ perms: { read: true } }, function seekSyncCurrent(): void {
const filename = "cli/tests/hello.txt";
const file = Deno.openSync(filename);
// Deliberately move 1 step forward
@ -382,7 +396,7 @@ testPerm({ read: true }, function seekSyncCurrent(): void {
file.close();
});
testPerm({ read: true }, async function seekEnd(): Promise<void> {
unitTest({ perms: { read: true } }, async function seekEnd(): Promise<void> {
const filename = "cli/tests/hello.txt";
const file = await Deno.open(filename);
const seekPosition = -6;
@ -396,7 +410,7 @@ testPerm({ read: true }, async function seekEnd(): Promise<void> {
file.close();
});
testPerm({ read: true }, function seekSyncEnd(): void {
unitTest({ perms: { read: true } }, function seekSyncEnd(): void {
const filename = "cli/tests/hello.txt";
const file = Deno.openSync(filename);
const seekPosition = -6;
@ -410,7 +424,7 @@ testPerm({ read: true }, function seekSyncEnd(): void {
file.close();
});
testPerm({ read: true }, async function seekMode(): Promise<void> {
unitTest({ perms: { read: true } }, async function seekMode(): Promise<void> {
const filename = "cli/tests/hello.txt";
const file = await Deno.open(filename);
let err;

View file

@ -1,17 +1,17 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, assert, assertEquals } from "./test_util.ts";
import { unitTest, assert, assertEquals } from "./test_util.ts";
test(function formDataHasCorrectNameProp(): void {
unitTest(function formDataHasCorrectNameProp(): void {
assertEquals(FormData.name, "FormData");
});
test(function formDataParamsAppendSuccess(): void {
unitTest(function formDataParamsAppendSuccess(): void {
const formData = new FormData();
formData.append("a", "true");
assertEquals(formData.get("a"), "true");
});
test(function formDataParamsDeleteSuccess(): void {
unitTest(function formDataParamsDeleteSuccess(): void {
const formData = new FormData();
formData.append("a", "true");
formData.append("b", "false");
@ -21,7 +21,7 @@ test(function formDataParamsDeleteSuccess(): void {
assertEquals(formData.get("b"), null);
});
test(function formDataParamsGetAllSuccess(): void {
unitTest(function formDataParamsGetAllSuccess(): void {
const formData = new FormData();
formData.append("a", "true");
formData.append("b", "false");
@ -31,7 +31,7 @@ test(function formDataParamsGetAllSuccess(): void {
assertEquals(formData.getAll("c"), []);
});
test(function formDataParamsGetSuccess(): void {
unitTest(function formDataParamsGetSuccess(): void {
const formData = new FormData();
formData.append("a", "true");
formData.append("b", "false");
@ -47,7 +47,7 @@ test(function formDataParamsGetSuccess(): void {
assertEquals(formData.get("e"), "null");
});
test(function formDataParamsHasSuccess(): void {
unitTest(function formDataParamsHasSuccess(): void {
const formData = new FormData();
formData.append("a", "true");
formData.append("b", "false");
@ -56,7 +56,7 @@ test(function formDataParamsHasSuccess(): void {
assert(!formData.has("c"));
});
test(function formDataParamsSetSuccess(): void {
unitTest(function formDataParamsSetSuccess(): void {
const formData = new FormData();
formData.append("a", "true");
formData.append("b", "false");
@ -73,7 +73,7 @@ test(function formDataParamsSetSuccess(): void {
assertEquals(formData.get("e"), "null");
});
test(function formDataSetEmptyBlobSuccess(): void {
unitTest(function formDataSetEmptyBlobSuccess(): void {
const formData = new FormData();
formData.set("a", new Blob([]), "blank.txt");
formData.get("a");
@ -85,7 +85,7 @@ test(function formDataSetEmptyBlobSuccess(): void {
*/
});
test(function formDataParamsForEachSuccess(): void {
unitTest(function formDataParamsForEachSuccess(): void {
const init = [
["a", "54"],
["b", "true"]
@ -104,7 +104,7 @@ test(function formDataParamsForEachSuccess(): void {
assertEquals(callNum, init.length);
});
test(function formDataParamsArgumentsCheck(): void {
unitTest(function formDataParamsArgumentsCheck(): void {
const methodRequireOneParam = [
"delete",
"getAll",
@ -183,7 +183,7 @@ test(function formDataParamsArgumentsCheck(): void {
});
});
test(function toStringShouldBeWebCompatibility(): void {
unitTest(function toStringShouldBeWebCompatibility(): void {
const formData = new FormData();
assertEquals(formData.toString(), "[object FormData]");
});

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { assert, test } from "./test_util.ts";
import { assert, unitTest } from "./test_util.ts";
test(function formatDiagnosticBasic() {
unitTest(function formatDiagnosticBasic() {
const fixture: Deno.DiagnosticItem[] = [
{
message: "Example error",
@ -19,7 +19,7 @@ test(function formatDiagnosticBasic() {
assert(out.includes("foo.ts"));
});
test(function formatDiagnosticError() {
unitTest(function formatDiagnosticError() {
let thrown = false;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const bad = ([{ hello: 123 }] as any) as Deno.DiagnosticItem[];

View file

@ -1,9 +1,9 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { testPerm, assert } from "./test_util.ts";
import { unitTest, assert } from "./test_util.ts";
// TODO(ry) Add more tests to specify format.
testPerm({ read: false }, function fsEventsPermissions() {
unitTest({ perms: { read: false } }, function fsEventsPermissions() {
let thrown = false;
try {
Deno.fsEvents(".");
@ -25,26 +25,27 @@ async function getTwoEvents(
return events;
}
testPerm({ read: true, write: true }, async function fsEventsBasic(): Promise<
void
> {
const testDir = await Deno.makeTempDir();
const iter = Deno.fsEvents(testDir);
unitTest(
{ perms: { read: true, write: true } },
async function fsEventsBasic(): Promise<void> {
const testDir = await Deno.makeTempDir();
const iter = Deno.fsEvents(testDir);
// Asynchornously capture two fs events.
const eventsPromise = getTwoEvents(iter);
// Asynchornously capture two fs events.
const eventsPromise = getTwoEvents(iter);
// Make some random file system activity.
const file1 = testDir + "/file1.txt";
const file2 = testDir + "/file2.txt";
Deno.writeFileSync(file1, new Uint8Array([0, 1, 2]));
Deno.writeFileSync(file2, new Uint8Array([0, 1, 2]));
// Make some random file system activity.
const file1 = testDir + "/file1.txt";
const file2 = testDir + "/file2.txt";
Deno.writeFileSync(file1, new Uint8Array([0, 1, 2]));
Deno.writeFileSync(file2, new Uint8Array([0, 1, 2]));
// We should have gotten two fs events.
const events = await eventsPromise;
assert(events.length >= 2);
assert(events[0].kind == "create");
assert(events[0].paths[0].includes(testDir));
assert(events[1].kind == "create" || events[1].kind == "modify");
assert(events[1].paths[0].includes(testDir));
});
// We should have gotten two fs events.
const events = await eventsPromise;
assert(events.length >= 2);
assert(events[0].kind == "create");
assert(events[0].paths[0].includes(testDir));
assert(events[1].kind == "create" || events[1].kind == "modify");
assert(events[1].paths[0].includes(testDir));
}
);

View file

@ -1,49 +1,49 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, assertNotEquals, assertStrictEq } from "./test_util.ts";
import { unitTest, assertNotEquals, assertStrictEq } from "./test_util.ts";
test(function getRandomValuesInt8Array(): void {
unitTest(function getRandomValuesInt8Array(): void {
const arr = new Int8Array(32);
crypto.getRandomValues(arr);
assertNotEquals(arr, new Int8Array(32));
});
test(function getRandomValuesUint8Array(): void {
unitTest(function getRandomValuesUint8Array(): void {
const arr = new Uint8Array(32);
crypto.getRandomValues(arr);
assertNotEquals(arr, new Uint8Array(32));
});
test(function getRandomValuesUint8ClampedArray(): void {
unitTest(function getRandomValuesUint8ClampedArray(): void {
const arr = new Uint8ClampedArray(32);
crypto.getRandomValues(arr);
assertNotEquals(arr, new Uint8ClampedArray(32));
});
test(function getRandomValuesInt16Array(): void {
unitTest(function getRandomValuesInt16Array(): void {
const arr = new Int16Array(4);
crypto.getRandomValues(arr);
assertNotEquals(arr, new Int16Array(4));
});
test(function getRandomValuesUint16Array(): void {
unitTest(function getRandomValuesUint16Array(): void {
const arr = new Uint16Array(4);
crypto.getRandomValues(arr);
assertNotEquals(arr, new Uint16Array(4));
});
test(function getRandomValuesInt32Array(): void {
unitTest(function getRandomValuesInt32Array(): void {
const arr = new Int32Array(8);
crypto.getRandomValues(arr);
assertNotEquals(arr, new Int32Array(8));
});
test(function getRandomValuesUint32Array(): void {
unitTest(function getRandomValuesUint32Array(): void {
const arr = new Uint32Array(8);
crypto.getRandomValues(arr);
assertNotEquals(arr, new Uint32Array(8));
});
test(function getRandomValuesReturnValue(): void {
unitTest(function getRandomValuesReturnValue(): void {
const arr = new Uint32Array(8);
const rtn = crypto.getRandomValues(arr);
assertNotEquals(arr, new Uint32Array(8));

View file

@ -1,51 +1,51 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, assert } from "./test_util.ts";
import { unitTest, assert } from "./test_util.ts";
test(function globalThisExists(): void {
unitTest(function globalThisExists(): void {
assert(globalThis != null);
});
test(function windowExists(): void {
unitTest(function windowExists(): void {
assert(window != null);
});
test(function selfExists(): void {
unitTest(function selfExists(): void {
assert(self != null);
});
test(function windowWindowExists(): void {
unitTest(function windowWindowExists(): void {
assert(window.window === window);
});
test(function windowSelfExists(): void {
unitTest(function windowSelfExists(): void {
assert(window.self === window);
});
test(function globalThisEqualsWindow(): void {
unitTest(function globalThisEqualsWindow(): void {
assert(globalThis === window);
});
test(function globalThisEqualsSelf(): void {
unitTest(function globalThisEqualsSelf(): void {
assert(globalThis === self);
});
test(function DenoNamespaceExists(): void {
unitTest(function DenoNamespaceExists(): void {
assert(Deno != null);
});
test(function DenoNamespaceEqualsWindowDeno(): void {
unitTest(function DenoNamespaceEqualsWindowDeno(): void {
assert(Deno === window.Deno);
});
test(function DenoNamespaceIsFrozen(): void {
unitTest(function DenoNamespaceIsFrozen(): void {
assert(Object.isFrozen(Deno));
});
test(function webAssemblyExists(): void {
unitTest(function webAssemblyExists(): void {
assert(typeof WebAssembly.compile === "function");
});
test(function DenoNamespaceImmutable(): void {
unitTest(function DenoNamespaceImmutable(): void {
const denoCopy = window.Deno;
try {
// @ts-ignore
@ -89,7 +89,7 @@ test(function DenoNamespaceImmutable(): void {
assert(print === Deno.core.print);
});
test(async function windowQueueMicrotask(): Promise<void> {
unitTest(async function windowQueueMicrotask(): Promise<void> {
let resolve1: () => void | undefined;
let resolve2: () => void | undefined;
let microtaskDone = false;

View file

@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, assert, assertEquals } from "./test_util.ts";
import { unitTest, assert, assertEquals } from "./test_util.ts";
const {
stringifyArgs
// @ts-ignore TypeScript (as of 3.7) does not support indexing namespaces by symbol
@ -8,7 +8,7 @@ const {
// Logic heavily copied from web-platform-tests, make
// sure pass mostly header basic test
// ref: https://github.com/web-platform-tests/wpt/blob/7c50c216081d6ea3c9afe553ee7b64534020a1b2/fetch/api/headers/headers-basic.html
test(function newHeaderTest(): void {
unitTest(function newHeaderTest(): void {
new Headers();
new Headers(undefined);
new Headers({});
@ -37,7 +37,7 @@ for (const name in headerDict) {
headerSeq.push([name, headerDict[name]]);
}
test(function newHeaderWithSequence(): void {
unitTest(function newHeaderWithSequence(): void {
const headers = new Headers(headerSeq);
for (const name in headerDict) {
assertEquals(headers.get(name), String(headerDict[name]));
@ -45,14 +45,14 @@ test(function newHeaderWithSequence(): void {
assertEquals(headers.get("length"), null);
});
test(function newHeaderWithRecord(): void {
unitTest(function newHeaderWithRecord(): void {
const headers = new Headers(headerDict);
for (const name in headerDict) {
assertEquals(headers.get(name), String(headerDict[name]));
}
});
test(function newHeaderWithHeadersInstance(): void {
unitTest(function newHeaderWithHeadersInstance(): void {
const headers = new Headers(headerDict);
const headers2 = new Headers(headers);
for (const name in headerDict) {
@ -60,7 +60,7 @@ test(function newHeaderWithHeadersInstance(): void {
}
});
test(function headerAppendSuccess(): void {
unitTest(function headerAppendSuccess(): void {
const headers = new Headers();
for (const name in headerDict) {
headers.append(name, headerDict[name]);
@ -68,7 +68,7 @@ test(function headerAppendSuccess(): void {
}
});
test(function headerSetSuccess(): void {
unitTest(function headerSetSuccess(): void {
const headers = new Headers();
for (const name in headerDict) {
headers.set(name, headerDict[name]);
@ -76,7 +76,7 @@ test(function headerSetSuccess(): void {
}
});
test(function headerHasSuccess(): void {
unitTest(function headerHasSuccess(): void {
const headers = new Headers(headerDict);
for (const name in headerDict) {
assert(headers.has(name), "headers has name " + name);
@ -87,7 +87,7 @@ test(function headerHasSuccess(): void {
}
});
test(function headerDeleteSuccess(): void {
unitTest(function headerDeleteSuccess(): void {
const headers = new Headers(headerDict);
for (const name in headerDict) {
assert(headers.has(name), "headers have a header: " + name);
@ -96,7 +96,7 @@ test(function headerDeleteSuccess(): void {
}
});
test(function headerGetSuccess(): void {
unitTest(function headerGetSuccess(): void {
const headers = new Headers(headerDict);
for (const name in headerDict) {
assertEquals(headers.get(name), String(headerDict[name]));
@ -104,7 +104,7 @@ test(function headerGetSuccess(): void {
}
});
test(function headerEntriesSuccess(): void {
unitTest(function headerEntriesSuccess(): void {
const headers = new Headers(headerDict);
const iterators = headers.entries();
for (const it of iterators) {
@ -115,7 +115,7 @@ test(function headerEntriesSuccess(): void {
}
});
test(function headerKeysSuccess(): void {
unitTest(function headerKeysSuccess(): void {
const headers = new Headers(headerDict);
const iterators = headers.keys();
for (const it of iterators) {
@ -123,7 +123,7 @@ test(function headerKeysSuccess(): void {
}
});
test(function headerValuesSuccess(): void {
unitTest(function headerValuesSuccess(): void {
const headers = new Headers(headerDict);
const iterators = headers.values();
const entries = headers.entries();
@ -145,7 +145,7 @@ const headerEntriesDict: Record<string, string> = {
"Content-Types": "value6"
};
test(function headerForEachSuccess(): void {
unitTest(function headerForEachSuccess(): void {
const headers = new Headers(headerEntriesDict);
const keys = Object.keys(headerEntriesDict);
keys.forEach((key): void => {
@ -162,7 +162,7 @@ test(function headerForEachSuccess(): void {
assertEquals(callNum, keys.length);
});
test(function headerSymbolIteratorSuccess(): void {
unitTest(function headerSymbolIteratorSuccess(): void {
assert(Symbol.iterator in Headers.prototype);
const headers = new Headers(headerEntriesDict);
for (const header of headers) {
@ -173,7 +173,7 @@ test(function headerSymbolIteratorSuccess(): void {
}
});
test(function headerTypesAvailable(): void {
unitTest(function headerTypesAvailable(): void {
function newHeaders(): Headers {
return new Headers();
}
@ -183,7 +183,7 @@ test(function headerTypesAvailable(): void {
// Modified from https://github.com/bitinn/node-fetch/blob/7d3293200a91ad52b5ca7962f9d6fd1c04983edb/test/test.js#L2001-L2014
// Copyright (c) 2016 David Frank. MIT License.
test(function headerIllegalReject(): void {
unitTest(function headerIllegalReject(): void {
let errorCount = 0;
try {
new Headers({ "He y": "ok" });
@ -237,7 +237,7 @@ test(function headerIllegalReject(): void {
});
// If pair does not contain exactly two items,then throw a TypeError.
test(function headerParamsShouldThrowTypeError(): void {
unitTest(function headerParamsShouldThrowTypeError(): void {
let hasThrown = 0;
try {
@ -254,7 +254,7 @@ test(function headerParamsShouldThrowTypeError(): void {
assertEquals(hasThrown, 2);
});
test(function headerParamsArgumentsCheck(): void {
unitTest(function headerParamsArgumentsCheck(): void {
const methodRequireOneParam = ["delete", "get", "has", "forEach"];
const methodRequireTwoParams = ["append", "set"];
@ -327,7 +327,7 @@ test(function headerParamsArgumentsCheck(): void {
});
});
test(function toStringShouldBeWebCompatibility(): void {
unitTest(function toStringShouldBeWebCompatibility(): void {
const headers = new Headers();
assertEquals(headers.toString(), "[object Headers]");
});
@ -336,7 +336,7 @@ function stringify(...args: unknown[]): string {
return stringifyArgs(args).replace(/\n$/, "");
}
test(function customInspectReturnsCorrectHeadersFormat(): void {
unitTest(function customInspectReturnsCorrectHeadersFormat(): void {
const blankHeaders = new Headers();
assertEquals(stringify(blankHeaders), "Headers {}");
const singleHeader = new Headers([["Content-Type", "application/json"]]);

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, assert } from "./test_util.ts";
import { unitTest, assert } from "./test_util.ts";
test(function internalsExists(): void {
unitTest(function internalsExists(): void {
const {
stringifyArgs
// @ts-ignore TypeScript (as of 3.7) does not support indexing namespaces by symbol

View file

@ -1,113 +1,147 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { testPerm, assert, assertEquals } from "./test_util.ts";
import { unitTest, assert, assertEquals } from "./test_util.ts";
testPerm({ read: true, write: true }, function linkSyncSuccess(): void {
const testDir = Deno.makeTempDirSync();
const oldData = "Hardlink";
const oldName = testDir + "/oldname";
const newName = testDir + "/newname";
Deno.writeFileSync(oldName, new TextEncoder().encode(oldData));
// Create the hard link.
Deno.linkSync(oldName, newName);
// We should expect reading the same content.
const newData = new TextDecoder().decode(Deno.readFileSync(newName));
assertEquals(oldData, newData);
// Writing to newname also affects oldname.
const newData2 = "Modified";
Deno.writeFileSync(newName, new TextEncoder().encode(newData2));
assertEquals(newData2, new TextDecoder().decode(Deno.readFileSync(oldName)));
// Writing to oldname also affects newname.
const newData3 = "ModifiedAgain";
Deno.writeFileSync(oldName, new TextEncoder().encode(newData3));
assertEquals(newData3, new TextDecoder().decode(Deno.readFileSync(newName)));
// Remove oldname. File still accessible through newname.
Deno.removeSync(oldName);
const newNameStat = Deno.statSync(newName);
assert(newNameStat.isFile());
assert(!newNameStat.isSymlink()); // Not a symlink.
assertEquals(newData3, new TextDecoder().decode(Deno.readFileSync(newName)));
});
testPerm({ read: true, write: true }, function linkSyncExists(): void {
const testDir = Deno.makeTempDirSync();
const oldName = testDir + "/oldname";
const newName = testDir + "/newname";
Deno.writeFileSync(oldName, new TextEncoder().encode("oldName"));
// newname is already created.
Deno.writeFileSync(newName, new TextEncoder().encode("newName"));
let err;
try {
unitTest(
{ perms: { read: true, write: true } },
function linkSyncSuccess(): void {
const testDir = Deno.makeTempDirSync();
const oldData = "Hardlink";
const oldName = testDir + "/oldname";
const newName = testDir + "/newname";
Deno.writeFileSync(oldName, new TextEncoder().encode(oldData));
// Create the hard link.
Deno.linkSync(oldName, newName);
} catch (e) {
err = e;
// We should expect reading the same content.
const newData = new TextDecoder().decode(Deno.readFileSync(newName));
assertEquals(oldData, newData);
// Writing to newname also affects oldname.
const newData2 = "Modified";
Deno.writeFileSync(newName, new TextEncoder().encode(newData2));
assertEquals(
newData2,
new TextDecoder().decode(Deno.readFileSync(oldName))
);
// Writing to oldname also affects newname.
const newData3 = "ModifiedAgain";
Deno.writeFileSync(oldName, new TextEncoder().encode(newData3));
assertEquals(
newData3,
new TextDecoder().decode(Deno.readFileSync(newName))
);
// Remove oldname. File still accessible through newname.
Deno.removeSync(oldName);
const newNameStat = Deno.statSync(newName);
assert(newNameStat.isFile());
assert(!newNameStat.isSymlink()); // Not a symlink.
assertEquals(
newData3,
new TextDecoder().decode(Deno.readFileSync(newName))
);
}
assert(!!err);
assert(err instanceof Deno.errors.AlreadyExists);
});
);
testPerm({ read: true, write: true }, function linkSyncNotFound(): void {
const testDir = Deno.makeTempDirSync();
const oldName = testDir + "/oldname";
const newName = testDir + "/newname";
unitTest(
{ perms: { read: true, write: true } },
function linkSyncExists(): void {
const testDir = Deno.makeTempDirSync();
const oldName = testDir + "/oldname";
const newName = testDir + "/newname";
Deno.writeFileSync(oldName, new TextEncoder().encode("oldName"));
// newname is already created.
Deno.writeFileSync(newName, new TextEncoder().encode("newName"));
let err;
try {
Deno.linkSync(oldName, newName);
} catch (e) {
err = e;
let err;
try {
Deno.linkSync(oldName, newName);
} catch (e) {
err = e;
}
assert(!!err);
assert(err instanceof Deno.errors.AlreadyExists);
}
assert(!!err);
assert(err instanceof Deno.errors.NotFound);
});
);
testPerm({ read: false, write: true }, function linkSyncReadPerm(): void {
let err;
try {
Deno.linkSync("oldbaddir", "newbaddir");
} catch (e) {
err = e;
unitTest(
{ perms: { read: true, write: true } },
function linkSyncNotFound(): void {
const testDir = Deno.makeTempDirSync();
const oldName = testDir + "/oldname";
const newName = testDir + "/newname";
let err;
try {
Deno.linkSync(oldName, newName);
} catch (e) {
err = e;
}
assert(!!err);
assert(err instanceof Deno.errors.NotFound);
}
assert(err instanceof Deno.errors.PermissionDenied);
assertEquals(err.name, "PermissionDenied");
});
);
testPerm({ read: true, write: false }, function linkSyncWritePerm(): void {
let err;
try {
Deno.linkSync("oldbaddir", "newbaddir");
} catch (e) {
err = e;
unitTest(
{ perms: { read: false, write: true } },
function linkSyncReadPerm(): void {
let err;
try {
Deno.linkSync("oldbaddir", "newbaddir");
} catch (e) {
err = e;
}
assert(err instanceof Deno.errors.PermissionDenied);
assertEquals(err.name, "PermissionDenied");
}
assert(err instanceof Deno.errors.PermissionDenied);
assertEquals(err.name, "PermissionDenied");
});
);
testPerm({ read: true, write: true }, async function linkSuccess(): Promise<
void
> {
const testDir = Deno.makeTempDirSync();
const oldData = "Hardlink";
const oldName = testDir + "/oldname";
const newName = testDir + "/newname";
Deno.writeFileSync(oldName, new TextEncoder().encode(oldData));
// Create the hard link.
await Deno.link(oldName, newName);
// We should expect reading the same content.
const newData = new TextDecoder().decode(Deno.readFileSync(newName));
assertEquals(oldData, newData);
// Writing to newname also affects oldname.
const newData2 = "Modified";
Deno.writeFileSync(newName, new TextEncoder().encode(newData2));
assertEquals(newData2, new TextDecoder().decode(Deno.readFileSync(oldName)));
// Writing to oldname also affects newname.
const newData3 = "ModifiedAgain";
Deno.writeFileSync(oldName, new TextEncoder().encode(newData3));
assertEquals(newData3, new TextDecoder().decode(Deno.readFileSync(newName)));
// Remove oldname. File still accessible through newname.
Deno.removeSync(oldName);
const newNameStat = Deno.statSync(newName);
assert(newNameStat.isFile());
assert(!newNameStat.isSymlink()); // Not a symlink.
assertEquals(newData3, new TextDecoder().decode(Deno.readFileSync(newName)));
});
unitTest(
{ perms: { read: true, write: false } },
function linkSyncWritePerm(): void {
let err;
try {
Deno.linkSync("oldbaddir", "newbaddir");
} catch (e) {
err = e;
}
assert(err instanceof Deno.errors.PermissionDenied);
assertEquals(err.name, "PermissionDenied");
}
);
unitTest(
{ perms: { read: true, write: true } },
async function linkSuccess(): Promise<void> {
const testDir = Deno.makeTempDirSync();
const oldData = "Hardlink";
const oldName = testDir + "/oldname";
const newName = testDir + "/newname";
Deno.writeFileSync(oldName, new TextEncoder().encode(oldData));
// Create the hard link.
await Deno.link(oldName, newName);
// We should expect reading the same content.
const newData = new TextDecoder().decode(Deno.readFileSync(newName));
assertEquals(oldData, newData);
// Writing to newname also affects oldname.
const newData2 = "Modified";
Deno.writeFileSync(newName, new TextEncoder().encode(newData2));
assertEquals(
newData2,
new TextDecoder().decode(Deno.readFileSync(oldName))
);
// Writing to oldname also affects newname.
const newData3 = "ModifiedAgain";
Deno.writeFileSync(oldName, new TextEncoder().encode(newData3));
assertEquals(
newData3,
new TextDecoder().decode(Deno.readFileSync(newName))
);
// Remove oldname. File still accessible through newname.
Deno.removeSync(oldName);
const newNameStat = Deno.statSync(newName);
assert(newNameStat.isFile());
assert(!newNameStat.isSymlink()); // Not a symlink.
assertEquals(
newData3,
new TextDecoder().decode(Deno.readFileSync(newName))
);
}
);

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, assert } from "./test_util.ts";
import { unitTest, assert } from "./test_util.ts";
test(function locationBasic(): void {
unitTest(function locationBasic(): void {
// location example: file:///Users/rld/src/deno/js/unit_tests.ts
assert(window.location.toString().endsWith("unit_tests.ts"));
});

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, testPerm, assert, assertEquals } from "./test_util.ts";
import { unitTest, assert, assertEquals } from "./test_util.ts";
testPerm({ write: true }, function makeTempDirSyncSuccess(): void {
unitTest({ perms: { write: true } }, function makeTempDirSyncSuccess(): void {
const dir1 = Deno.makeTempDirSync({ prefix: "hello", suffix: "world" });
const dir2 = Deno.makeTempDirSync({ prefix: "hello", suffix: "world" });
// Check that both dirs are different.
@ -26,7 +26,7 @@ testPerm({ write: true }, function makeTempDirSyncSuccess(): void {
assert(err instanceof Deno.errors.NotFound);
});
test(function makeTempDirSyncPerm(): void {
unitTest(function makeTempDirSyncPerm(): void {
// makeTempDirSync should require write permissions (for now).
let err;
try {
@ -38,32 +38,35 @@ test(function makeTempDirSyncPerm(): void {
assertEquals(err.name, "PermissionDenied");
});
testPerm({ write: true }, async function makeTempDirSuccess(): Promise<void> {
const dir1 = await Deno.makeTempDir({ prefix: "hello", suffix: "world" });
const dir2 = await Deno.makeTempDir({ prefix: "hello", suffix: "world" });
// Check that both dirs are different.
assert(dir1 !== dir2);
for (const dir of [dir1, dir2]) {
// Check that the prefix and suffix are applied.
const lastPart = dir.replace(/^.*[\\\/]/, "");
assert(lastPart.startsWith("hello"));
assert(lastPart.endsWith("world"));
unitTest(
{ perms: { write: true } },
async function makeTempDirSuccess(): Promise<void> {
const dir1 = await Deno.makeTempDir({ prefix: "hello", suffix: "world" });
const dir2 = await Deno.makeTempDir({ prefix: "hello", suffix: "world" });
// Check that both dirs are different.
assert(dir1 !== dir2);
for (const dir of [dir1, dir2]) {
// Check that the prefix and suffix are applied.
const lastPart = dir.replace(/^.*[\\\/]/, "");
assert(lastPart.startsWith("hello"));
assert(lastPart.endsWith("world"));
}
// Check that the `dir` option works.
const dir3 = await Deno.makeTempDir({ dir: dir1 });
assert(dir3.startsWith(dir1));
assert(/^[\\\/]/.test(dir3.slice(dir1.length)));
// Check that creating a temp dir inside a nonexisting directory fails.
let err;
try {
await Deno.makeTempDir({ dir: "/baddir" });
} catch (err_) {
err = err_;
}
assert(err instanceof Deno.errors.NotFound);
}
// Check that the `dir` option works.
const dir3 = await Deno.makeTempDir({ dir: dir1 });
assert(dir3.startsWith(dir1));
assert(/^[\\\/]/.test(dir3.slice(dir1.length)));
// Check that creating a temp dir inside a nonexisting directory fails.
let err;
try {
await Deno.makeTempDir({ dir: "/baddir" });
} catch (err_) {
err = err_;
}
assert(err instanceof Deno.errors.NotFound);
});
);
testPerm({ write: true }, function makeTempFileSyncSuccess(): void {
unitTest({ perms: { write: true } }, function makeTempFileSyncSuccess(): void {
const file1 = Deno.makeTempFileSync({ prefix: "hello", suffix: "world" });
const file2 = Deno.makeTempFileSync({ prefix: "hello", suffix: "world" });
// Check that both dirs are different.
@ -89,7 +92,7 @@ testPerm({ write: true }, function makeTempFileSyncSuccess(): void {
assert(err instanceof Deno.errors.NotFound);
});
test(function makeTempFileSyncPerm(): void {
unitTest(function makeTempFileSyncPerm(): void {
// makeTempFileSync should require write permissions (for now).
let err;
try {
@ -101,28 +104,31 @@ test(function makeTempFileSyncPerm(): void {
assertEquals(err.name, "PermissionDenied");
});
testPerm({ write: true }, async function makeTempFileSuccess(): Promise<void> {
const file1 = await Deno.makeTempFile({ prefix: "hello", suffix: "world" });
const file2 = await Deno.makeTempFile({ prefix: "hello", suffix: "world" });
// Check that both dirs are different.
assert(file1 !== file2);
for (const dir of [file1, file2]) {
// Check that the prefix and suffix are applied.
const lastPart = dir.replace(/^.*[\\\/]/, "");
assert(lastPart.startsWith("hello"));
assert(lastPart.endsWith("world"));
unitTest(
{ perms: { write: true } },
async function makeTempFileSuccess(): Promise<void> {
const file1 = await Deno.makeTempFile({ prefix: "hello", suffix: "world" });
const file2 = await Deno.makeTempFile({ prefix: "hello", suffix: "world" });
// Check that both dirs are different.
assert(file1 !== file2);
for (const dir of [file1, file2]) {
// Check that the prefix and suffix are applied.
const lastPart = dir.replace(/^.*[\\\/]/, "");
assert(lastPart.startsWith("hello"));
assert(lastPart.endsWith("world"));
}
// Check that the `dir` option works.
const dir = Deno.makeTempDirSync({ prefix: "tempdir" });
const file3 = await Deno.makeTempFile({ dir });
assert(file3.startsWith(dir));
assert(/^[\\\/]/.test(file3.slice(dir.length)));
// Check that creating a temp file inside a nonexisting directory fails.
let err;
try {
await Deno.makeTempFile({ dir: "/baddir" });
} catch (err_) {
err = err_;
}
assert(err instanceof Deno.errors.NotFound);
}
// Check that the `dir` option works.
const dir = Deno.makeTempDirSync({ prefix: "tempdir" });
const file3 = await Deno.makeTempFile({ dir });
assert(file3.startsWith(dir));
assert(/^[\\\/]/.test(file3.slice(dir.length)));
// Check that creating a temp file inside a nonexisting directory fails.
let err;
try {
await Deno.makeTempFile({ dir: "/baddir" });
} catch (err_) {
err = err_;
}
assert(err instanceof Deno.errors.NotFound);
});
);

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, testPerm, assert } from "./test_util.ts";
import { unitTest, assert } from "./test_util.ts";
test(async function metrics(): Promise<void> {
unitTest(async function metrics(): Promise<void> {
const m1 = Deno.metrics();
assert(m1.opsDispatched > 0);
assert(m1.opsDispatchedSync > 0);
@ -28,19 +28,22 @@ test(async function metrics(): Promise<void> {
assert(m2.bytesReceived > m1.bytesReceived);
});
testPerm({ write: true }, function metricsUpdatedIfNoResponseSync(): void {
const filename = Deno.makeTempDirSync() + "/test.txt";
unitTest(
{ perms: { write: true } },
function metricsUpdatedIfNoResponseSync(): void {
const filename = Deno.makeTempDirSync() + "/test.txt";
const data = new Uint8Array([41, 42, 43]);
Deno.writeFileSync(filename, data, { perm: 0o666 });
const data = new Uint8Array([41, 42, 43]);
Deno.writeFileSync(filename, data, { perm: 0o666 });
const metrics = Deno.metrics();
assert(metrics.opsDispatched === metrics.opsCompleted);
assert(metrics.opsDispatchedSync === metrics.opsCompletedSync);
});
const metrics = Deno.metrics();
assert(metrics.opsDispatched === metrics.opsCompleted);
assert(metrics.opsDispatchedSync === metrics.opsCompletedSync);
}
);
testPerm(
{ write: true },
unitTest(
{ perms: { write: true } },
async function metricsUpdatedIfNoResponseAsync(): Promise<void> {
const filename = Deno.makeTempDirSync() + "/test.txt";

View file

@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, assert, assertEquals } from "../test_util.ts";
import { unitTest, assert, assertEquals } from "../test_util.ts";
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
function setup() {
@ -25,7 +25,7 @@ function setup() {
};
}
test(function testDomIterable(): void {
unitTest(function testDomIterable(): void {
const { DomIterable, Base } = setup();
const fixture: Array<[string, number]> = [
@ -67,7 +67,7 @@ test(function testDomIterable(): void {
assertEquals(DomIterable.name, Base.name);
});
test(function testDomIterableScope(): void {
unitTest(function testDomIterableScope(): void {
const { DomIterable } = setup();
const domIterable = new DomIterable([["foo", 1]]);

View file

@ -1,24 +1,30 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { testPerm, assert, assertEquals } from "./test_util.ts";
import { unitTest, assert, assertEquals } from "./test_util.ts";
testPerm({ read: true, write: true }, function mkdirSyncSuccess(): void {
const path = Deno.makeTempDirSync() + "/dir";
Deno.mkdirSync(path);
const pathInfo = Deno.statSync(path);
assert(pathInfo.isDirectory());
});
testPerm({ read: true, write: true }, function mkdirSyncMode(): void {
const path = Deno.makeTempDirSync() + "/dir";
Deno.mkdirSync(path, { mode: 0o755 }); // no perm for x
const pathInfo = Deno.statSync(path);
if (pathInfo.mode !== null) {
// Skip windows
assertEquals(pathInfo.mode & 0o777, 0o755);
unitTest(
{ perms: { read: true, write: true } },
function mkdirSyncSuccess(): void {
const path = Deno.makeTempDirSync() + "/dir";
Deno.mkdirSync(path);
const pathInfo = Deno.statSync(path);
assert(pathInfo.isDirectory());
}
});
);
testPerm({ write: false }, function mkdirSyncPerm(): void {
unitTest(
{ perms: { read: true, write: true } },
function mkdirSyncMode(): void {
const path = Deno.makeTempDirSync() + "/dir";
Deno.mkdirSync(path, { mode: 0o755 }); // no perm for x
const pathInfo = Deno.statSync(path);
if (pathInfo.mode !== null) {
// Skip windows
assertEquals(pathInfo.mode & 0o777, 0o755);
}
}
);
unitTest({ perms: { write: false } }, function mkdirSyncPerm(): void {
let err;
try {
Deno.mkdirSync("/baddir");
@ -29,16 +35,17 @@ testPerm({ write: false }, function mkdirSyncPerm(): void {
assertEquals(err.name, "PermissionDenied");
});
testPerm({ read: true, write: true }, async function mkdirSuccess(): Promise<
void
> {
const path = Deno.makeTempDirSync() + "/dir";
await Deno.mkdir(path);
const pathInfo = Deno.statSync(path);
assert(pathInfo.isDirectory());
});
unitTest(
{ perms: { read: true, write: true } },
async function mkdirSuccess(): Promise<void> {
const path = Deno.makeTempDirSync() + "/dir";
await Deno.mkdir(path);
const pathInfo = Deno.statSync(path);
assert(pathInfo.isDirectory());
}
);
testPerm({ write: true }, function mkdirErrIfExists(): void {
unitTest({ perms: { write: true } }, function mkdirErrIfExists(): void {
let err;
try {
Deno.mkdirSync(".");
@ -48,18 +55,22 @@ testPerm({ write: true }, function mkdirErrIfExists(): void {
assert(err instanceof Deno.errors.AlreadyExists);
});
testPerm({ read: true, write: true }, function mkdirSyncRecursive(): void {
const path = Deno.makeTempDirSync() + "/nested/directory";
Deno.mkdirSync(path, { recursive: true });
const pathInfo = Deno.statSync(path);
assert(pathInfo.isDirectory());
});
unitTest(
{ perms: { read: true, write: true } },
function mkdirSyncRecursive(): void {
const path = Deno.makeTempDirSync() + "/nested/directory";
Deno.mkdirSync(path, { recursive: true });
const pathInfo = Deno.statSync(path);
assert(pathInfo.isDirectory());
}
);
testPerm({ read: true, write: true }, async function mkdirRecursive(): Promise<
void
> {
const path = Deno.makeTempDirSync() + "/nested/directory";
await Deno.mkdir(path, { recursive: true });
const pathInfo = Deno.statSync(path);
assert(pathInfo.isDirectory());
});
unitTest(
{ perms: { read: true, write: true } },
async function mkdirRecursive(): Promise<void> {
const path = Deno.makeTempDirSync() + "/nested/directory";
await Deno.mkdir(path, { recursive: true });
const pathInfo = Deno.statSync(path);
assert(pathInfo.isDirectory());
}
);

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { testPerm, assert, assertEquals } from "./test_util.ts";
import { unitTest, assert, assertEquals } from "./test_util.ts";
testPerm({ net: true }, function netTcpListenClose(): void {
unitTest({ perms: { net: true } }, function netTcpListenClose(): void {
const listener = Deno.listen({ hostname: "127.0.0.1", port: 4500 });
assertEquals(listener.addr.transport, "tcp");
assertEquals(listener.addr.hostname, "127.0.0.1");
@ -9,56 +9,71 @@ testPerm({ net: true }, function netTcpListenClose(): void {
listener.close();
});
testPerm({ net: true }, function netUdpListenClose(): void {
if (Deno.build.os === "win") return; // TODO
const socket = Deno.listen({
hostname: "127.0.0.1",
port: 4500,
transport: "udp"
});
assertEquals(socket.addr.transport, "udp");
assertEquals(socket.addr.hostname, "127.0.0.1");
assertEquals(socket.addr.port, 4500);
socket.close();
});
testPerm({ net: true }, async function netTcpCloseWhileAccept(): Promise<void> {
const listener = Deno.listen({ port: 4501 });
const p = listener.accept();
listener.close();
let err;
try {
await p;
} catch (e) {
err = e;
unitTest(
{
perms: { net: true },
// TODO:
skip: Deno.build.os === "win"
},
function netUdpListenClose(): void {
const socket = Deno.listen({
hostname: "127.0.0.1",
port: 4500,
transport: "udp"
});
assertEquals(socket.addr.transport, "udp");
assertEquals(socket.addr.hostname, "127.0.0.1");
assertEquals(socket.addr.port, 4500);
socket.close();
}
assert(!!err);
assert(err instanceof Error);
assertEquals(err.message, "Listener has been closed");
});
);
testPerm({ net: true }, async function netTcpConcurrentAccept(): Promise<void> {
const listener = Deno.listen({ port: 4502 });
let acceptErrCount = 0;
const checkErr = (e: Error): void => {
if (e.message === "Listener has been closed") {
assertEquals(acceptErrCount, 1);
} else if (e.message === "Another accept task is ongoing") {
acceptErrCount++;
} else {
throw new Error("Unexpected error message");
unitTest(
{
perms: { net: true }
},
async function netTcpCloseWhileAccept(): Promise<void> {
const listener = Deno.listen({ port: 4501 });
const p = listener.accept();
listener.close();
let err;
try {
await p;
} catch (e) {
err = e;
}
};
const p = listener.accept().catch(checkErr);
const p1 = listener.accept().catch(checkErr);
await Promise.race([p, p1]);
listener.close();
await Promise.all([p, p1]);
assertEquals(acceptErrCount, 1);
});
assert(!!err);
assert(err instanceof Error);
assertEquals(err.message, "Listener has been closed");
}
);
testPerm({ net: true }, async function netTcpDialListen(): Promise<void> {
unitTest(
{ perms: { net: true } },
async function netTcpConcurrentAccept(): Promise<void> {
const listener = Deno.listen({ port: 4502 });
let acceptErrCount = 0;
const checkErr = (e: Error): void => {
if (e.message === "Listener has been closed") {
assertEquals(acceptErrCount, 1);
} else if (e.message === "Another accept task is ongoing") {
acceptErrCount++;
} else {
throw new Error("Unexpected error message");
}
};
const p = listener.accept().catch(checkErr);
const p1 = listener.accept().catch(checkErr);
await Promise.race([p, p1]);
listener.close();
await Promise.all([p, p1]);
assertEquals(acceptErrCount, 1);
}
);
unitTest({ perms: { net: true } }, async function netTcpDialListen(): Promise<
void
> {
const listener = Deno.listen({ port: 4500 });
listener.accept().then(
async (conn): Promise<void> => {
@ -90,34 +105,35 @@ testPerm({ net: true }, async function netTcpDialListen(): Promise<void> {
conn.close();
});
testPerm({ net: true }, async function netUdpSendReceive(): Promise<void> {
if (Deno.build.os === "win") return; // TODO
unitTest(
{ skip: Deno.build.os === "win", perms: { net: true } },
async function netUdpSendReceive(): Promise<void> {
const alice = Deno.listen({ port: 4500, transport: "udp" });
assertEquals(alice.addr.port, 4500);
assertEquals(alice.addr.hostname, "0.0.0.0");
assertEquals(alice.addr.transport, "udp");
const alice = Deno.listen({ port: 4500, transport: "udp" });
assertEquals(alice.addr.port, 4500);
assertEquals(alice.addr.hostname, "0.0.0.0");
assertEquals(alice.addr.transport, "udp");
const bob = Deno.listen({ port: 4501, transport: "udp" });
assertEquals(bob.addr.port, 4501);
assertEquals(bob.addr.hostname, "0.0.0.0");
assertEquals(bob.addr.transport, "udp");
const bob = Deno.listen({ port: 4501, transport: "udp" });
assertEquals(bob.addr.port, 4501);
assertEquals(bob.addr.hostname, "0.0.0.0");
assertEquals(bob.addr.transport, "udp");
const sent = new Uint8Array([1, 2, 3]);
await alice.send(sent, bob.addr);
const sent = new Uint8Array([1, 2, 3]);
await alice.send(sent, bob.addr);
const [recvd, remote] = await bob.receive();
assertEquals(remote.port, 4500);
assertEquals(recvd.length, 3);
assertEquals(1, recvd[0]);
assertEquals(2, recvd[1]);
assertEquals(3, recvd[2]);
alice.close();
bob.close();
}
);
const [recvd, remote] = await bob.receive();
assertEquals(remote.port, 4500);
assertEquals(recvd.length, 3);
assertEquals(1, recvd[0]);
assertEquals(2, recvd[1]);
assertEquals(3, recvd[2]);
alice.close();
bob.close();
});
testPerm(
{ net: true },
unitTest(
{ perms: { net: true } },
async function netTcpListenCloseWhileIterating(): Promise<void> {
const listener = Deno.listen({ port: 8000 });
const nextWhileClosing = listener[Symbol.asyncIterator]().next();
@ -129,11 +145,9 @@ testPerm(
}
);
testPerm(
{ net: true },
unitTest(
{ skip: Deno.build.os === "win", perms: { net: true } },
async function netUdpListenCloseWhileIterating(): Promise<void> {
if (Deno.build.os === "win") return; // TODO
const socket = Deno.listen({ port: 8000, transport: "udp" });
const nextWhileClosing = socket[Symbol.asyncIterator]().next();
socket.close();
@ -145,7 +159,7 @@ testPerm(
);
/* TODO(ry) Re-enable this test.
testPerm({ net: true }, async function netListenAsyncIterator(): Promise<void> {
unitTest({ perms: { net: true } }, async function netListenAsyncIterator(): Promise<void> {
const listener = Deno.listen(":4500");
const runAsyncIterator = async (): Promise<void> => {
for await (let conn of listener) {
@ -174,7 +188,7 @@ testPerm({ net: true }, async function netListenAsyncIterator(): Promise<void> {
*/
/* TODO Fix broken test.
testPerm({ net: true }, async function netCloseReadSuccess() {
unitTest({ perms: { net: true } }, async function netCloseReadSuccess() {
const addr = "127.0.0.1:4500";
const listener = Deno.listen(addr);
const closeDeferred = deferred();
@ -206,7 +220,7 @@ testPerm({ net: true }, async function netCloseReadSuccess() {
*/
/* TODO Fix broken test.
testPerm({ net: true }, async function netDoubleCloseRead() {
unitTest({ perms: { net: true } }, async function netDoubleCloseRead() {
const addr = "127.0.0.1:4500";
const listener = Deno.listen(addr);
const closeDeferred = deferred();
@ -233,7 +247,7 @@ testPerm({ net: true }, async function netDoubleCloseRead() {
*/
/* TODO Fix broken test.
testPerm({ net: true }, async function netCloseWriteSuccess() {
unitTest({ perms: { net: true } }, async function netCloseWriteSuccess() {
const addr = "127.0.0.1:4500";
const listener = Deno.listen(addr);
const closeDeferred = deferred();
@ -267,7 +281,7 @@ testPerm({ net: true }, async function netCloseWriteSuccess() {
*/
/* TODO Fix broken test.
testPerm({ net: true }, async function netDoubleCloseWrite() {
unitTest({ perms: { net: true } }, async function netDoubleCloseWrite() {
const addr = "127.0.0.1:4500";
const listener = Deno.listen(addr);
const closeDeferred = deferred();

View file

@ -1,14 +1,13 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import {
test,
testPerm,
assert,
assertEquals,
assertNotEquals,
assertThrows
assertThrows,
unitTest
} from "./test_util.ts";
testPerm({ env: true }, function envSuccess(): void {
unitTest({ perms: { env: true } }, function envSuccess(): void {
const env = Deno.env();
assert(env !== null);
// eslint-disable-next-line @typescript-eslint/camelcase
@ -18,12 +17,12 @@ testPerm({ env: true }, function envSuccess(): void {
assertEquals(Deno.env("test_var"), env.test_var);
});
testPerm({ env: true }, function envNotFound(): void {
unitTest({ perms: { env: true } }, function envNotFound(): void {
const r = Deno.env("env_var_does_not_exist!");
assertEquals(r, undefined);
});
test(function envPermissionDenied1(): void {
unitTest(function envPermissionDenied1(): void {
let err;
try {
Deno.env();
@ -35,7 +34,7 @@ test(function envPermissionDenied1(): void {
assertEquals(err.name, "PermissionDenied");
});
test(function envPermissionDenied2(): void {
unitTest(function envPermissionDenied2(): void {
let err;
try {
Deno.env("PATH");
@ -47,11 +46,12 @@ test(function envPermissionDenied2(): void {
assertEquals(err.name, "PermissionDenied");
});
if (Deno.build.os === "win") {
// This test verifies that on Windows, environment variables are
// case-insensitive. Case normalization needs be done using the collation
// that Windows uses, rather than naively using String.toLowerCase().
testPerm({ env: true, run: true }, async function envCaseInsensitive() {
// This test verifies that on Windows, environment variables are
// case-insensitive. Case normalization needs be done using the collation
// that Windows uses, rather than naively using String.toLowerCase().
unitTest(
{ skip: Deno.build.os !== "win", perms: { env: true, run: true } },
async function envCaseInsensitive() {
// Utility function that runs a Deno subprocess with the environment
// specified in `inputEnv`. The subprocess reads the environment variables
// which are in the keys of `expectedEnv` and writes them to stdout as JSON.
@ -61,9 +61,9 @@ if (Deno.build.os === "win") {
expectedEnv: Record<string, string>
): Promise<void> => {
const src = `
console.log(
${JSON.stringify(Object.keys(expectedEnv))}.map(k => Deno.env(k))
)`;
console.log(
${JSON.stringify(Object.keys(expectedEnv))}.map(k => Deno.env(k))
)`;
const proc = Deno.run({
args: [Deno.execPath(), "eval", src],
env: inputEnv,
@ -108,14 +108,14 @@ if (Deno.build.os === "win") {
{ [c2]: "Dz", [uc2]: "DZ" },
{ [c2]: "Dz", [uc2]: "DZ", [lc2]: "DZ" }
);
});
}
}
);
test(function osPid(): void {
unitTest(function osPid(): void {
assert(Deno.pid > 0);
});
testPerm({ env: true }, function getDir(): void {
unitTest({ perms: { env: true } }, function getDir(): void {
type supportOS = "mac" | "win" | "linux";
interface Runtime {
@ -263,7 +263,7 @@ testPerm({ env: true }, function getDir(): void {
}
});
testPerm({}, function getDirWithoutPermission(): void {
unitTest(function getDirWithoutPermission(): void {
assertThrows(
() => Deno.dir("home"),
Deno.errors.PermissionDenied,
@ -271,11 +271,11 @@ testPerm({}, function getDirWithoutPermission(): void {
);
});
testPerm({ env: true }, function execPath(): void {
unitTest({ perms: { env: true } }, function execPath(): void {
assertNotEquals(Deno.execPath(), "");
});
testPerm({ env: false }, function execPathPerm(): void {
unitTest({ perms: { env: false } }, function execPathPerm(): void {
let caughtError = false;
try {
Deno.execPath();
@ -287,12 +287,12 @@ testPerm({ env: false }, function execPathPerm(): void {
assert(caughtError);
});
testPerm({ env: true }, function loadavgSuccess(): void {
unitTest({ perms: { env: true } }, function loadavgSuccess(): void {
const load = Deno.loadavg();
assertEquals(load.length, 3);
});
testPerm({ env: false }, function loadavgPerm(): void {
unitTest({ perms: { env: false } }, function loadavgPerm(): void {
let caughtError = false;
try {
Deno.loadavg();
@ -304,11 +304,11 @@ testPerm({ env: false }, function loadavgPerm(): void {
assert(caughtError);
});
testPerm({ env: true }, function hostnameDir(): void {
unitTest({ perms: { env: true } }, function hostnameDir(): void {
assertNotEquals(Deno.hostname(), "");
});
testPerm({ env: false }, function hostnamePerm(): void {
unitTest({ perms: { env: false } }, function hostnamePerm(): void {
let caughtError = false;
try {
Deno.hostname();
@ -320,11 +320,11 @@ testPerm({ env: false }, function hostnamePerm(): void {
assert(caughtError);
});
testPerm({ env: true }, function releaseDir(): void {
unitTest({ perms: { env: true } }, function releaseDir(): void {
assertNotEquals(Deno.osRelease(), "");
});
testPerm({ env: false }, function releasePerm(): void {
unitTest({ perms: { env: false } }, function releasePerm(): void {
let caughtError = false;
try {
Deno.osRelease();

View file

@ -1,7 +1,9 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { testPerm, assert, createResolvable } from "./test_util.ts";
import { unitTest, assert, createResolvable } from "./test_util.ts";
testPerm({ hrtime: false }, async function performanceNow(): Promise<void> {
unitTest({ perms: { hrtime: false } }, async function performanceNow(): Promise<
void
> {
const resolvable = createResolvable();
const start = performance.now();
setTimeout((): void => {

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, assert } from "./test_util.ts";
import { unitTest, assert } from "./test_util.ts";
test(async function permissionInvalidName(): Promise<void> {
unitTest(async function permissionInvalidName(): Promise<void> {
let thrown = false;
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@ -14,7 +14,7 @@ test(async function permissionInvalidName(): Promise<void> {
}
});
test(async function permissionNetInvalidUrl(): Promise<void> {
unitTest(async function permissionNetInvalidUrl(): Promise<void> {
let thrown = false;
try {
await Deno.permissions.query({ name: "net", url: ":" });

View file

@ -1,14 +1,13 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import {
test,
testPerm,
assert,
assertEquals,
assertStrContains
assertStrContains,
unitTest
} from "./test_util.ts";
const { kill, run, readFile, open, makeTempDir, writeFile } = Deno;
test(function runPermissions(): void {
unitTest(function runPermissions(): void {
let caughtError = false;
try {
Deno.run({ args: ["python", "-c", "print('hello world')"] });
@ -19,7 +18,7 @@ test(function runPermissions(): void {
assert(caughtError);
});
testPerm({ run: true }, async function runSuccess(): Promise<void> {
unitTest({ perms: { run: true } }, async function runSuccess(): Promise<void> {
const p = run({
args: ["python", "-c", "print('hello world')"],
stdout: "piped",
@ -33,36 +32,39 @@ testPerm({ run: true }, async function runSuccess(): Promise<void> {
p.close();
});
testPerm({ run: true }, async function runCommandFailedWithCode(): Promise<
void
> {
const p = run({
args: ["python", "-c", "import sys;sys.exit(41 + 1)"]
});
const status = await p.status();
assertEquals(status.success, false);
assertEquals(status.code, 42);
assertEquals(status.signal, undefined);
p.close();
});
testPerm({ run: true }, async function runCommandFailedWithSignal(): Promise<
void
> {
if (Deno.build.os === "win") {
return; // No signals on windows.
unitTest(
{ perms: { run: true } },
async function runCommandFailedWithCode(): Promise<void> {
const p = run({
args: ["python", "-c", "import sys;sys.exit(41 + 1)"]
});
const status = await p.status();
assertEquals(status.success, false);
assertEquals(status.code, 42);
assertEquals(status.signal, undefined);
p.close();
}
const p = run({
args: ["python", "-c", "import os;os.kill(os.getpid(), 9)"]
});
const status = await p.status();
assertEquals(status.success, false);
assertEquals(status.code, undefined);
assertEquals(status.signal, 9);
p.close();
});
);
testPerm({ run: true }, function runNotFound(): void {
unitTest(
{
// No signals on windows.
skip: Deno.build.os === "win",
perms: { run: true }
},
async function runCommandFailedWithSignal(): Promise<void> {
const p = run({
args: ["python", "-c", "import os;os.kill(os.getpid(), 9)"]
});
const status = await p.status();
assertEquals(status.success, false);
assertEquals(status.code, undefined);
assertEquals(status.signal, 9);
p.close();
}
);
unitTest({ perms: { run: true } }, function runNotFound(): void {
let error;
try {
run({ args: ["this file hopefully doesn't exist"] });
@ -73,8 +75,8 @@ testPerm({ run: true }, function runNotFound(): void {
assert(error instanceof Deno.errors.NotFound);
});
testPerm(
{ write: true, run: true },
unitTest(
{ perms: { write: true, run: true } },
async function runWithCwdIsAsync(): Promise<void> {
const enc = new TextEncoder();
const cwd = await makeTempDir({ prefix: "deno_command_test" });
@ -116,7 +118,9 @@ while True:
}
);
testPerm({ run: true }, async function runStdinPiped(): Promise<void> {
unitTest({ perms: { run: true } }, async function runStdinPiped(): Promise<
void
> {
const p = run({
args: ["python", "-c", "import sys; assert 'hello' == sys.stdin.read();"],
stdin: "piped"
@ -138,7 +142,9 @@ testPerm({ run: true }, async function runStdinPiped(): Promise<void> {
p.close();
});
testPerm({ run: true }, async function runStdoutPiped(): Promise<void> {
unitTest({ perms: { run: true } }, async function runStdoutPiped(): Promise<
void
> {
const p = run({
args: ["python", "-c", "import sys; sys.stdout.write('hello')"],
stdout: "piped"
@ -165,7 +171,9 @@ testPerm({ run: true }, async function runStdoutPiped(): Promise<void> {
p.close();
});
testPerm({ run: true }, async function runStderrPiped(): Promise<void> {
unitTest({ perms: { run: true } }, async function runStderrPiped(): Promise<
void
> {
const p = run({
args: ["python", "-c", "import sys; sys.stderr.write('hello')"],
stderr: "piped"
@ -192,7 +200,7 @@ testPerm({ run: true }, async function runStderrPiped(): Promise<void> {
p.close();
});
testPerm({ run: true }, async function runOutput(): Promise<void> {
unitTest({ perms: { run: true } }, async function runOutput(): Promise<void> {
const p = run({
args: ["python", "-c", "import sys; sys.stdout.write('hello')"],
stdout: "piped"
@ -203,7 +211,9 @@ testPerm({ run: true }, async function runOutput(): Promise<void> {
p.close();
});
testPerm({ run: true }, async function runStderrOutput(): Promise<void> {
unitTest({ perms: { run: true } }, async function runStderrOutput(): Promise<
void
> {
const p = run({
args: ["python", "-c", "import sys; sys.stderr.write('error')"],
stderr: "piped"
@ -214,8 +224,8 @@ testPerm({ run: true }, async function runStderrOutput(): Promise<void> {
p.close();
});
testPerm(
{ run: true, write: true, read: true },
unitTest(
{ perms: { run: true, write: true, read: true } },
async function runRedirectStdoutStderr(): Promise<void> {
const tempDir = await makeTempDir();
const fileName = tempDir + "/redirected_stdio.txt";
@ -244,8 +254,8 @@ testPerm(
}
);
testPerm(
{ run: true, write: true, read: true },
unitTest(
{ perms: { run: true, write: true, read: true } },
async function runRedirectStdin(): Promise<void> {
const tempDir = await makeTempDir();
const fileName = tempDir + "/redirected_stdio.txt";
@ -265,7 +275,7 @@ testPerm(
}
);
testPerm({ run: true }, async function runEnv(): Promise<void> {
unitTest({ perms: { run: true } }, async function runEnv(): Promise<void> {
const p = run({
args: [
"python",
@ -284,7 +294,7 @@ testPerm({ run: true }, async function runEnv(): Promise<void> {
p.close();
});
testPerm({ run: true }, async function runClose(): Promise<void> {
unitTest({ perms: { run: true } }, async function runClose(): Promise<void> {
const p = run({
args: [
"python",
@ -304,7 +314,7 @@ testPerm({ run: true }, async function runClose(): Promise<void> {
p.stderr!.close();
});
test(function signalNumbers(): void {
unitTest(function signalNumbers(): void {
if (Deno.build.os === "mac") {
assertEquals(Deno.Signal.SIGSTOP, 17);
} else if (Deno.build.os === "linux") {
@ -314,7 +324,7 @@ test(function signalNumbers(): void {
// Ignore signal tests on windows for now...
if (Deno.build.os !== "win") {
test(function killPermissions(): void {
unitTest(function killPermissions(): void {
let caughtError = false;
try {
// Unlike the other test cases, we don't have permission to spawn a
@ -329,7 +339,9 @@ if (Deno.build.os !== "win") {
assert(caughtError);
});
testPerm({ run: true }, async function killSuccess(): Promise<void> {
unitTest({ perms: { run: true } }, async function killSuccess(): Promise<
void
> {
const p = run({
args: ["python", "-c", "from time import sleep; sleep(10000)"]
});
@ -347,7 +359,9 @@ if (Deno.build.os !== "win") {
p.close();
});
testPerm({ run: true }, async function killFailed(): Promise<void> {
unitTest({ perms: { run: true } }, async function killFailed(): Promise<
void
> {
const p = run({
args: ["python", "-c", "from time import sleep; sleep(10000)"]
});

View file

@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { testPerm, assert, assertEquals } from "./test_util.ts";
import { unitTest, assert, assertEquals } from "./test_util.ts";
type FileInfo = Deno.FileInfo;
@ -21,12 +21,12 @@ function assertSameContent(files: FileInfo[]): void {
assertEquals(counter, 2);
}
testPerm({ read: true }, function readDirSyncSuccess(): void {
unitTest({ perms: { read: true } }, function readDirSyncSuccess(): void {
const files = Deno.readDirSync("cli/tests/");
assertSameContent(files);
});
testPerm({ read: false }, function readDirSyncPerm(): void {
unitTest({ perms: { read: false } }, function readDirSyncPerm(): void {
let caughtError = false;
try {
Deno.readDirSync("tests/");
@ -37,7 +37,7 @@ testPerm({ read: false }, function readDirSyncPerm(): void {
assert(caughtError);
});
testPerm({ read: true }, function readDirSyncNotDir(): void {
unitTest({ perms: { read: true } }, function readDirSyncNotDir(): void {
let caughtError = false;
let src;
@ -51,7 +51,7 @@ testPerm({ read: true }, function readDirSyncNotDir(): void {
assertEquals(src, undefined);
});
testPerm({ read: true }, function readDirSyncNotFound(): void {
unitTest({ perms: { read: true } }, function readDirSyncNotFound(): void {
let caughtError = false;
let src;
@ -65,12 +65,16 @@ testPerm({ read: true }, function readDirSyncNotFound(): void {
assertEquals(src, undefined);
});
testPerm({ read: true }, async function readDirSuccess(): Promise<void> {
unitTest({ perms: { read: true } }, async function readDirSuccess(): Promise<
void
> {
const files = await Deno.readDir("cli/tests/");
assertSameContent(files);
});
testPerm({ read: false }, async function readDirPerm(): Promise<void> {
unitTest({ perms: { read: false } }, async function readDirPerm(): Promise<
void
> {
let caughtError = false;
try {
await Deno.readDir("tests/");

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { testPerm, assert, assertEquals } from "./test_util.ts";
import { unitTest, assert, assertEquals } from "./test_util.ts";
testPerm({ read: true }, function readFileSyncSuccess(): void {
unitTest({ perms: { read: true } }, function readFileSyncSuccess(): void {
const data = Deno.readFileSync("cli/tests/fixture.json");
assert(data.byteLength > 0);
const decoder = new TextDecoder("utf-8");
@ -10,7 +10,7 @@ testPerm({ read: true }, function readFileSyncSuccess(): void {
assertEquals(pkg.name, "deno");
});
testPerm({ read: false }, function readFileSyncPerm(): void {
unitTest({ perms: { read: false } }, function readFileSyncPerm(): void {
let caughtError = false;
try {
Deno.readFileSync("cli/tests/fixture.json");
@ -21,7 +21,7 @@ testPerm({ read: false }, function readFileSyncPerm(): void {
assert(caughtError);
});
testPerm({ read: true }, function readFileSyncNotFound(): void {
unitTest({ perms: { read: true } }, function readFileSyncNotFound(): void {
let caughtError = false;
let data;
try {
@ -34,7 +34,9 @@ testPerm({ read: true }, function readFileSyncNotFound(): void {
assert(data === undefined);
});
testPerm({ read: true }, async function readFileSuccess(): Promise<void> {
unitTest({ perms: { read: true } }, async function readFileSuccess(): Promise<
void
> {
const data = await Deno.readFile("cli/tests/fixture.json");
assert(data.byteLength > 0);
const decoder = new TextDecoder("utf-8");
@ -43,7 +45,9 @@ testPerm({ read: true }, async function readFileSuccess(): Promise<void> {
assertEquals(pkg.name, "deno");
});
testPerm({ read: false }, async function readFilePerm(): Promise<void> {
unitTest({ perms: { read: false } }, async function readFilePerm(): Promise<
void
> {
let caughtError = false;
try {
await Deno.readFile("cli/tests/fixture.json");

View file

@ -1,21 +1,26 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { testPerm, assert, assertEquals } from "./test_util.ts";
import { unitTest, assert, assertEquals } from "./test_util.ts";
testPerm({ write: true, read: true }, function readlinkSyncSuccess(): void {
const testDir = Deno.makeTempDirSync();
const target = testDir + "/target";
const symlink = testDir + "/symln";
Deno.mkdirSync(target);
// TODO Add test for Windows once symlink is implemented for Windows.
// See https://github.com/denoland/deno/issues/815.
if (Deno.build.os !== "win") {
Deno.symlinkSync(target, symlink);
const targetPath = Deno.readlinkSync(symlink);
assertEquals(targetPath, target);
unitTest(
{ perms: { write: true, read: true } },
function readlinkSyncSuccess(): void {
const testDir = Deno.makeTempDirSync();
const target = testDir + "/target";
const symlink = testDir + "/symln";
Deno.mkdirSync(target);
// TODO Add test for Windows once symlink is implemented for Windows.
// See https://github.com/denoland/deno/issues/815.
if (Deno.build.os !== "win") {
Deno.symlinkSync(target, symlink);
const targetPath = Deno.readlinkSync(symlink);
assertEquals(targetPath, target);
}
}
});
);
testPerm({ read: false }, async function readlinkSyncPerm(): Promise<void> {
unitTest({ perms: { read: false } }, async function readlinkSyncPerm(): Promise<
void
> {
let caughtError = false;
try {
Deno.readlinkSync("/symlink");
@ -26,7 +31,7 @@ testPerm({ read: false }, async function readlinkSyncPerm(): Promise<void> {
assert(caughtError);
});
testPerm({ read: true }, function readlinkSyncNotFound(): void {
unitTest({ perms: { read: true } }, function readlinkSyncNotFound(): void {
let caughtError = false;
let data;
try {
@ -39,23 +44,26 @@ testPerm({ read: true }, function readlinkSyncNotFound(): void {
assertEquals(data, undefined);
});
testPerm({ write: true, read: true }, async function readlinkSuccess(): Promise<
unitTest(
{ perms: { write: true, read: true } },
async function readlinkSuccess(): Promise<void> {
const testDir = Deno.makeTempDirSync();
const target = testDir + "/target";
const symlink = testDir + "/symln";
Deno.mkdirSync(target);
// TODO Add test for Windows once symlink is implemented for Windows.
// See https://github.com/denoland/deno/issues/815.
if (Deno.build.os !== "win") {
Deno.symlinkSync(target, symlink);
const targetPath = await Deno.readlink(symlink);
assertEquals(targetPath, target);
}
}
);
unitTest({ perms: { read: false } }, async function readlinkPerm(): Promise<
void
> {
const testDir = Deno.makeTempDirSync();
const target = testDir + "/target";
const symlink = testDir + "/symln";
Deno.mkdirSync(target);
// TODO Add test for Windows once symlink is implemented for Windows.
// See https://github.com/denoland/deno/issues/815.
if (Deno.build.os !== "win") {
Deno.symlinkSync(target, symlink);
const targetPath = await Deno.readlink(symlink);
assertEquals(targetPath, target);
}
});
testPerm({ read: false }, async function readlinkPerm(): Promise<void> {
let caughtError = false;
try {
await Deno.readlink("/symlink");

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { testPerm, assert } from "./test_util.ts";
import { unitTest, assert } from "./test_util.ts";
testPerm({ read: true }, function realpathSyncSuccess(): void {
unitTest({ perms: { read: true } }, function realpathSyncSuccess(): void {
const incompletePath = "cli/tests/fixture.json";
const realPath = Deno.realpathSync(incompletePath);
if (Deno.build.os !== "win") {
@ -12,8 +12,12 @@ testPerm({ read: true }, function realpathSyncSuccess(): void {
assert(realPath.endsWith(incompletePath));
});
if (Deno.build.os !== "win") {
testPerm({ read: true, write: true }, function realpathSyncSymlink(): void {
unitTest(
{
skip: Deno.build.os === "win",
perms: { read: true, write: true }
},
function realpathSyncSymlink(): void {
const testDir = Deno.makeTempDirSync();
const target = testDir + "/target";
const symlink = testDir + "/symln";
@ -22,10 +26,10 @@ if (Deno.build.os !== "win") {
const targetPath = Deno.realpathSync(symlink);
assert(targetPath.startsWith("/"));
assert(targetPath.endsWith("/target"));
});
}
}
);
testPerm({ read: false }, function realpathSyncPerm(): void {
unitTest({ perms: { read: false } }, function realpathSyncPerm(): void {
let caughtError = false;
try {
Deno.realpathSync("some_file");
@ -36,7 +40,7 @@ testPerm({ read: false }, function realpathSyncPerm(): void {
assert(caughtError);
});
testPerm({ read: true }, function realpathSyncNotFound(): void {
unitTest({ perms: { read: true } }, function realpathSyncNotFound(): void {
let caughtError = false;
try {
Deno.realpathSync("bad_filename");
@ -47,7 +51,9 @@ testPerm({ read: true }, function realpathSyncNotFound(): void {
assert(caughtError);
});
testPerm({ read: true }, async function realpathSuccess(): Promise<void> {
unitTest({ perms: { read: true } }, async function realpathSuccess(): Promise<
void
> {
const incompletePath = "cli/tests/fixture.json";
const realPath = await Deno.realpath(incompletePath);
if (Deno.build.os !== "win") {
@ -58,23 +64,26 @@ testPerm({ read: true }, async function realpathSuccess(): Promise<void> {
assert(realPath.endsWith(incompletePath));
});
if (Deno.build.os !== "win") {
testPerm(
{ read: true, write: true },
async function realpathSymlink(): Promise<void> {
const testDir = Deno.makeTempDirSync();
const target = testDir + "/target";
const symlink = testDir + "/symln";
Deno.mkdirSync(target);
Deno.symlinkSync(target, symlink);
const targetPath = await Deno.realpath(symlink);
assert(targetPath.startsWith("/"));
assert(targetPath.endsWith("/target"));
}
);
}
unitTest(
{
skip: Deno.build.os === "win",
perms: { read: true, write: true }
},
async function realpathSymlink(): Promise<void> {
const testDir = Deno.makeTempDirSync();
const target = testDir + "/target";
const symlink = testDir + "/symln";
Deno.mkdirSync(target);
Deno.symlinkSync(target, symlink);
const targetPath = await Deno.realpath(symlink);
assert(targetPath.startsWith("/"));
assert(targetPath.endsWith("/target"));
}
);
testPerm({ read: false }, async function realpathPerm(): Promise<void> {
unitTest({ perms: { read: false } }, async function realpathPerm(): Promise<
void
> {
let caughtError = false;
try {
await Deno.realpath("some_file");
@ -85,7 +94,9 @@ testPerm({ read: false }, async function realpathPerm(): Promise<void> {
assert(caughtError);
});
testPerm({ read: true }, async function realpathNotFound(): Promise<void> {
unitTest({ perms: { read: true } }, async function realpathNotFound(): Promise<
void
> {
let caughtError = false;
try {
await Deno.realpath("bad_filename");

View file

@ -1,77 +1,86 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { testPerm, assert, assertEquals } from "./test_util.ts";
import { unitTest, assert, assertEquals } from "./test_util.ts";
// SYNC
testPerm({ write: true, read: true }, function removeSyncDirSuccess(): void {
// REMOVE EMPTY DIRECTORY
const path = Deno.makeTempDirSync() + "/subdir";
Deno.mkdirSync(path);
const pathInfo = Deno.statSync(path);
assert(pathInfo.isDirectory()); // check exist first
Deno.removeSync(path); // remove
// We then check again after remove
let err;
try {
Deno.statSync(path);
} catch (e) {
err = e;
unitTest(
{ perms: { write: true, read: true } },
function removeSyncDirSuccess(): void {
// REMOVE EMPTY DIRECTORY
const path = Deno.makeTempDirSync() + "/subdir";
Deno.mkdirSync(path);
const pathInfo = Deno.statSync(path);
assert(pathInfo.isDirectory()); // check exist first
Deno.removeSync(path); // remove
// We then check again after remove
let err;
try {
Deno.statSync(path);
} catch (e) {
err = e;
}
// Directory is gone
assert(err instanceof Deno.errors.NotFound);
}
// Directory is gone
assert(err instanceof Deno.errors.NotFound);
});
);
testPerm({ write: true, read: true }, function removeSyncFileSuccess(): void {
// REMOVE FILE
const enc = new TextEncoder();
const data = enc.encode("Hello");
const filename = Deno.makeTempDirSync() + "/test.txt";
Deno.writeFileSync(filename, data, { perm: 0o666 });
const fileInfo = Deno.statSync(filename);
assert(fileInfo.isFile()); // check exist first
Deno.removeSync(filename); // remove
// We then check again after remove
let err;
try {
Deno.statSync(filename);
} catch (e) {
err = e;
unitTest(
{ perms: { write: true, read: true } },
function removeSyncFileSuccess(): void {
// REMOVE FILE
const enc = new TextEncoder();
const data = enc.encode("Hello");
const filename = Deno.makeTempDirSync() + "/test.txt";
Deno.writeFileSync(filename, data, { perm: 0o666 });
const fileInfo = Deno.statSync(filename);
assert(fileInfo.isFile()); // check exist first
Deno.removeSync(filename); // remove
// We then check again after remove
let err;
try {
Deno.statSync(filename);
} catch (e) {
err = e;
}
// File is gone
assert(err instanceof Deno.errors.NotFound);
}
// File is gone
assert(err instanceof Deno.errors.NotFound);
});
);
testPerm({ write: true, read: true }, function removeSyncFail(): void {
// NON-EMPTY DIRECTORY
const path = Deno.makeTempDirSync() + "/dir/subdir";
const subPath = path + "/subsubdir";
Deno.mkdirSync(path, { recursive: true });
Deno.mkdirSync(subPath);
const pathInfo = Deno.statSync(path);
assert(pathInfo.isDirectory()); // check exist first
const subPathInfo = Deno.statSync(subPath);
assert(subPathInfo.isDirectory()); // check exist first
let err;
try {
// Should not be able to recursively remove
Deno.removeSync(path);
} catch (e) {
err = e;
unitTest(
{ perms: { write: true, read: true } },
function removeSyncFail(): void {
// NON-EMPTY DIRECTORY
const path = Deno.makeTempDirSync() + "/dir/subdir";
const subPath = path + "/subsubdir";
Deno.mkdirSync(path, { recursive: true });
Deno.mkdirSync(subPath);
const pathInfo = Deno.statSync(path);
assert(pathInfo.isDirectory()); // check exist first
const subPathInfo = Deno.statSync(subPath);
assert(subPathInfo.isDirectory()); // check exist first
let err;
try {
// Should not be able to recursively remove
Deno.removeSync(path);
} catch (e) {
err = e;
}
// TODO(ry) Is Other really the error we should get here? What would Go do?
assert(err instanceof Error);
// NON-EXISTENT DIRECTORY/FILE
try {
// Non-existent
Deno.removeSync("/baddir");
} catch (e) {
err = e;
}
assert(err instanceof Deno.errors.NotFound);
}
// TODO(ry) Is Other really the error we should get here? What would Go do?
assert(err instanceof Error);
// NON-EXISTENT DIRECTORY/FILE
try {
// Non-existent
Deno.removeSync("/baddir");
} catch (e) {
err = e;
}
assert(err instanceof Deno.errors.NotFound);
});
);
testPerm(
{ write: true, read: true },
unitTest(
{ perms: { write: true, read: true } },
function removeSyncDanglingSymlinkSuccess(): void {
const danglingSymlinkPath = Deno.makeTempDirSync() + "/dangling_symlink";
// TODO(#3832): Remove "Not Implemented" error checking when symlink creation is implemented for Windows
@ -98,8 +107,8 @@ testPerm(
}
);
testPerm(
{ write: true, read: true },
unitTest(
{ perms: { write: true, read: true } },
function removeSyncValidSymlinkSuccess(): void {
const encoder = new TextEncoder();
const data = encoder.encode("Test");
@ -132,7 +141,7 @@ testPerm(
}
);
testPerm({ write: false }, function removeSyncPerm(): void {
unitTest({ perms: { write: false } }, function removeSyncPerm(): void {
let err;
try {
Deno.removeSync("/baddir");
@ -143,45 +152,48 @@ testPerm({ write: false }, function removeSyncPerm(): void {
assertEquals(err.name, "PermissionDenied");
});
testPerm({ write: true, read: true }, function removeAllSyncDirSuccess(): void {
// REMOVE EMPTY DIRECTORY
let path = Deno.makeTempDirSync() + "/dir/subdir";
Deno.mkdirSync(path, { recursive: true });
let pathInfo = Deno.statSync(path);
assert(pathInfo.isDirectory()); // check exist first
Deno.removeSync(path, { recursive: true }); // remove
// We then check again after remove
let err;
try {
Deno.statSync(path);
} catch (e) {
err = e;
}
// Directory is gone
assert(err instanceof Deno.errors.NotFound);
unitTest(
{ perms: { write: true, read: true } },
function removeAllSyncDirSuccess(): void {
// REMOVE EMPTY DIRECTORY
let path = Deno.makeTempDirSync() + "/dir/subdir";
Deno.mkdirSync(path, { recursive: true });
let pathInfo = Deno.statSync(path);
assert(pathInfo.isDirectory()); // check exist first
Deno.removeSync(path, { recursive: true }); // remove
// We then check again after remove
let err;
try {
Deno.statSync(path);
} catch (e) {
err = e;
}
// Directory is gone
assert(err instanceof Deno.errors.NotFound);
// REMOVE NON-EMPTY DIRECTORY
path = Deno.makeTempDirSync() + "/dir/subdir";
const subPath = path + "/subsubdir";
Deno.mkdirSync(path, { recursive: true });
Deno.mkdirSync(subPath);
pathInfo = Deno.statSync(path);
assert(pathInfo.isDirectory()); // check exist first
const subPathInfo = Deno.statSync(subPath);
assert(subPathInfo.isDirectory()); // check exist first
Deno.removeSync(path, { recursive: true }); // remove
// We then check parent directory again after remove
try {
Deno.statSync(path);
} catch (e) {
err = e;
// REMOVE NON-EMPTY DIRECTORY
path = Deno.makeTempDirSync() + "/dir/subdir";
const subPath = path + "/subsubdir";
Deno.mkdirSync(path, { recursive: true });
Deno.mkdirSync(subPath);
pathInfo = Deno.statSync(path);
assert(pathInfo.isDirectory()); // check exist first
const subPathInfo = Deno.statSync(subPath);
assert(subPathInfo.isDirectory()); // check exist first
Deno.removeSync(path, { recursive: true }); // remove
// We then check parent directory again after remove
try {
Deno.statSync(path);
} catch (e) {
err = e;
}
// Directory is gone
assert(err instanceof Deno.errors.NotFound);
}
// Directory is gone
assert(err instanceof Deno.errors.NotFound);
});
);
testPerm(
{ write: true, read: true },
unitTest(
{ perms: { write: true, read: true } },
function removeAllSyncFileSuccess(): void {
// REMOVE FILE
const enc = new TextEncoder();
@ -203,7 +215,7 @@ testPerm(
}
);
testPerm({ write: true }, function removeAllSyncFail(): void {
unitTest({ perms: { write: true } }, function removeAllSyncFail(): void {
// NON-EXISTENT DIRECTORY/FILE
let err;
try {
@ -215,7 +227,7 @@ testPerm({ write: true }, function removeAllSyncFail(): void {
assert(err instanceof Deno.errors.NotFound);
});
testPerm({ write: false }, function removeAllSyncPerm(): void {
unitTest({ perms: { write: false } }, function removeAllSyncPerm(): void {
let err;
try {
Deno.removeSync("/baddir", { recursive: true });
@ -228,8 +240,8 @@ testPerm({ write: false }, function removeAllSyncPerm(): void {
// ASYNC
testPerm(
{ write: true, read: true },
unitTest(
{ perms: { write: true, read: true } },
async function removeDirSuccess(): Promise<void> {
// REMOVE EMPTY DIRECTORY
const path = Deno.makeTempDirSync() + "/dir/subdir";
@ -249,8 +261,8 @@ testPerm(
}
);
testPerm(
{ write: true, read: true },
unitTest(
{ perms: { write: true, read: true } },
async function removeFileSuccess(): Promise<void> {
// REMOVE FILE
const enc = new TextEncoder();
@ -272,38 +284,39 @@ testPerm(
}
);
testPerm({ write: true, read: true }, async function removeFail(): Promise<
void
> {
// NON-EMPTY DIRECTORY
const path = Deno.makeTempDirSync() + "/dir/subdir";
const subPath = path + "/subsubdir";
Deno.mkdirSync(path, { recursive: true });
Deno.mkdirSync(subPath);
const pathInfo = Deno.statSync(path);
assert(pathInfo.isDirectory()); // check exist first
const subPathInfo = Deno.statSync(subPath);
assert(subPathInfo.isDirectory()); // check exist first
let err;
try {
// Should not be able to recursively remove
await Deno.remove(path);
} catch (e) {
err = e;
unitTest(
{ perms: { write: true, read: true } },
async function removeFail(): Promise<void> {
// NON-EMPTY DIRECTORY
const path = Deno.makeTempDirSync() + "/dir/subdir";
const subPath = path + "/subsubdir";
Deno.mkdirSync(path, { recursive: true });
Deno.mkdirSync(subPath);
const pathInfo = Deno.statSync(path);
assert(pathInfo.isDirectory()); // check exist first
const subPathInfo = Deno.statSync(subPath);
assert(subPathInfo.isDirectory()); // check exist first
let err;
try {
// Should not be able to recursively remove
await Deno.remove(path);
} catch (e) {
err = e;
}
assert(err instanceof Error);
// NON-EXISTENT DIRECTORY/FILE
try {
// Non-existent
await Deno.remove("/baddir");
} catch (e) {
err = e;
}
assert(err instanceof Deno.errors.NotFound);
}
assert(err instanceof Error);
// NON-EXISTENT DIRECTORY/FILE
try {
// Non-existent
await Deno.remove("/baddir");
} catch (e) {
err = e;
}
assert(err instanceof Deno.errors.NotFound);
});
);
testPerm(
{ write: true, read: true },
unitTest(
{ perms: { write: true, read: true } },
async function removeDanglingSymlinkSuccess(): Promise<void> {
const danglingSymlinkPath = Deno.makeTempDirSync() + "/dangling_symlink";
// TODO(#3832): Remove "Not Implemented" error checking when symlink creation is implemented for Windows
@ -330,8 +343,8 @@ testPerm(
}
);
testPerm(
{ write: true, read: true },
unitTest(
{ perms: { write: true, read: true } },
async function removeValidSymlinkSuccess(): Promise<void> {
const encoder = new TextEncoder();
const data = encoder.encode("Test");
@ -364,7 +377,9 @@ testPerm(
}
);
testPerm({ write: false }, async function removePerm(): Promise<void> {
unitTest({ perms: { write: false } }, async function removePerm(): Promise<
void
> {
let err;
try {
await Deno.remove("/baddir");
@ -375,8 +390,8 @@ testPerm({ write: false }, async function removePerm(): Promise<void> {
assertEquals(err.name, "PermissionDenied");
});
testPerm(
{ write: true, read: true },
unitTest(
{ perms: { write: true, read: true } },
async function removeAllDirSuccess(): Promise<void> {
// REMOVE EMPTY DIRECTORY
let path = Deno.makeTempDirSync() + "/dir/subdir";
@ -415,8 +430,8 @@ testPerm(
}
);
testPerm(
{ write: true, read: true },
unitTest(
{ perms: { write: true, read: true } },
async function removeAllFileSuccess(): Promise<void> {
// REMOVE FILE
const enc = new TextEncoder();
@ -438,7 +453,9 @@ testPerm(
}
);
testPerm({ write: true }, async function removeAllFail(): Promise<void> {
unitTest({ perms: { write: true } }, async function removeAllFail(): Promise<
void
> {
// NON-EXISTENT DIRECTORY/FILE
let err;
try {
@ -450,7 +467,9 @@ testPerm({ write: true }, async function removeAllFail(): Promise<void> {
assert(err instanceof Deno.errors.NotFound);
});
testPerm({ write: false }, async function removeAllPerm(): Promise<void> {
unitTest({ perms: { write: false } }, async function removeAllPerm(): Promise<
void
> {
let err;
try {
await Deno.remove("/baddir", { recursive: true });

View file

@ -1,74 +1,84 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { testPerm, assert, assertEquals } from "./test_util.ts";
import { unitTest, assert, assertEquals } from "./test_util.ts";
testPerm({ read: true, write: true }, function renameSyncSuccess(): void {
const testDir = Deno.makeTempDirSync();
const oldpath = testDir + "/oldpath";
const newpath = testDir + "/newpath";
Deno.mkdirSync(oldpath);
Deno.renameSync(oldpath, newpath);
const newPathInfo = Deno.statSync(newpath);
assert(newPathInfo.isDirectory());
let caughtErr = false;
let oldPathInfo;
try {
oldPathInfo = Deno.statSync(oldpath);
} catch (e) {
caughtErr = true;
assert(e instanceof Deno.errors.NotFound);
}
assert(caughtErr);
assertEquals(oldPathInfo, undefined);
});
testPerm({ read: false, write: true }, function renameSyncReadPerm(): void {
let err;
try {
const oldpath = "/oldbaddir";
const newpath = "/newbaddir";
unitTest(
{ perms: { read: true, write: true } },
function renameSyncSuccess(): void {
const testDir = Deno.makeTempDirSync();
const oldpath = testDir + "/oldpath";
const newpath = testDir + "/newpath";
Deno.mkdirSync(oldpath);
Deno.renameSync(oldpath, newpath);
} catch (e) {
err = e;
const newPathInfo = Deno.statSync(newpath);
assert(newPathInfo.isDirectory());
let caughtErr = false;
let oldPathInfo;
try {
oldPathInfo = Deno.statSync(oldpath);
} catch (e) {
caughtErr = true;
assert(e instanceof Deno.errors.NotFound);
}
assert(caughtErr);
assertEquals(oldPathInfo, undefined);
}
assert(err instanceof Deno.errors.PermissionDenied);
assertEquals(err.name, "PermissionDenied");
});
);
testPerm({ read: true, write: false }, function renameSyncWritePerm(): void {
let err;
try {
const oldpath = "/oldbaddir";
const newpath = "/newbaddir";
Deno.renameSync(oldpath, newpath);
} catch (e) {
err = e;
unitTest(
{ perms: { read: false, write: true } },
function renameSyncReadPerm(): void {
let err;
try {
const oldpath = "/oldbaddir";
const newpath = "/newbaddir";
Deno.renameSync(oldpath, newpath);
} catch (e) {
err = e;
}
assert(err instanceof Deno.errors.PermissionDenied);
assertEquals(err.name, "PermissionDenied");
}
assert(err instanceof Deno.errors.PermissionDenied);
assertEquals(err.name, "PermissionDenied");
});
);
testPerm({ read: true, write: true }, async function renameSuccess(): Promise<
void
> {
const testDir = Deno.makeTempDirSync();
const oldpath = testDir + "/oldpath";
const newpath = testDir + "/newpath";
Deno.mkdirSync(oldpath);
await Deno.rename(oldpath, newpath);
const newPathInfo = Deno.statSync(newpath);
assert(newPathInfo.isDirectory());
let caughtErr = false;
let oldPathInfo;
try {
oldPathInfo = Deno.statSync(oldpath);
} catch (e) {
caughtErr = true;
assert(e instanceof Deno.errors.NotFound);
unitTest(
{ perms: { read: true, write: false } },
function renameSyncWritePerm(): void {
let err;
try {
const oldpath = "/oldbaddir";
const newpath = "/newbaddir";
Deno.renameSync(oldpath, newpath);
} catch (e) {
err = e;
}
assert(err instanceof Deno.errors.PermissionDenied);
assertEquals(err.name, "PermissionDenied");
}
assert(caughtErr);
assertEquals(oldPathInfo, undefined);
});
);
unitTest(
{ perms: { read: true, write: true } },
async function renameSuccess(): Promise<void> {
const testDir = Deno.makeTempDirSync();
const oldpath = testDir + "/oldpath";
const newpath = testDir + "/newpath";
Deno.mkdirSync(oldpath);
await Deno.rename(oldpath, newpath);
const newPathInfo = Deno.statSync(newpath);
assert(newPathInfo.isDirectory());
let caughtErr = false;
let oldPathInfo;
try {
oldPathInfo = Deno.statSync(oldpath);
} catch (e) {
caughtErr = true;
assert(e instanceof Deno.errors.NotFound);
}
assert(caughtErr);
assertEquals(oldPathInfo, undefined);
}
);

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, assert, assertEquals } from "./test_util.ts";
import { unitTest, assert, assertEquals } from "./test_util.ts";
test(function fromInit(): void {
unitTest(function fromInit(): void {
const req = new Request("https://example.com", {
body: "ahoyhoy",
method: "POST",
@ -16,7 +16,7 @@ test(function fromInit(): void {
assertEquals(req.headers.get("test-header"), "value");
});
test(function fromRequest(): void {
unitTest(function fromRequest(): void {
const r = new Request("https://example.com");
// @ts-ignore
r._bodySource = "ahoyhoy";
@ -30,7 +30,7 @@ test(function fromRequest(): void {
assertEquals(req.headers.get("test-header"), r.headers.get("test-header"));
});
test(async function cloneRequestBodyStream(): Promise<void> {
unitTest(async function cloneRequestBodyStream(): Promise<void> {
// hack to get a stream
const stream = new Request("", { body: "a test body" }).body;
const r1 = new Request("https://example.com", {

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, testPerm, assertEquals } from "./test_util.ts";
import { unitTest, assertEquals } from "./test_util.ts";
test(function resourcesStdio(): void {
unitTest(function resourcesStdio(): void {
const res = Deno.resources();
assertEquals(res[0], "stdin");
@ -9,7 +9,9 @@ test(function resourcesStdio(): void {
assertEquals(res[2], "stderr");
});
testPerm({ net: true }, async function resourcesNet(): Promise<void> {
unitTest({ perms: { net: true } }, async function resourcesNet(): Promise<
void
> {
const listener = Deno.listen({ port: 4501 });
const dialerConn = await Deno.connect({ port: 4501 });
const listenerConn = await listener.accept();
@ -29,7 +31,9 @@ testPerm({ net: true }, async function resourcesNet(): Promise<void> {
listener.close();
});
testPerm({ read: true }, async function resourcesFile(): Promise<void> {
unitTest({ perms: { read: true } }, async function resourcesFile(): Promise<
void
> {
const resourcesBefore = Deno.resources();
const f = await Deno.open("cli/tests/hello.txt");
const resourcesAfter = Deno.resources();

View file

@ -1,7 +1,6 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import {
test,
testPerm,
unitTest,
assert,
assertEquals,
assertThrows,
@ -14,8 +13,9 @@ function defer(n: number): Promise<void> {
});
}
if (Deno.build.os === "win") {
test(async function signalsNotImplemented(): Promise<void> {
unitTest(
{ skip: Deno.build.os !== "win" },
async function signalsNotImplemented(): Promise<void> {
assertThrows(
() => {
Deno.signal(1);
@ -100,9 +100,12 @@ if (Deno.build.os === "win") {
Error,
"not implemented"
);
});
} else {
testPerm({ run: true }, async function signalStreamTest(): Promise<void> {
}
);
unitTest(
{ skip: Deno.build.os === "win", perms: { run: true, net: true } },
async function signalStreamTest(): Promise<void> {
const resolvable = createResolvable();
// This prevents the program from exiting.
const t = setInterval(() => {}, 1000);
@ -131,9 +134,12 @@ if (Deno.build.os === "win") {
// for more explanation see `FIXME` in `cli/js/timers.ts::setGlobalTimeout`
await defer(20);
await resolvable;
});
}
);
testPerm({ run: true }, async function signalPromiseTest(): Promise<void> {
unitTest(
{ skip: Deno.build.os === "win", perms: { run: true } },
async function signalPromiseTest(): Promise<void> {
const resolvable = createResolvable();
// This prevents the program from exiting.
const t = setInterval(() => {}, 1000);
@ -151,9 +157,12 @@ if (Deno.build.os === "win") {
// for more explanation see `FIXME` in `cli/js/timers.ts::setGlobalTimeout`
await defer(20);
await resolvable;
});
}
);
testPerm({ run: true }, async function signalShorthandsTest(): Promise<void> {
unitTest(
{ skip: Deno.build.os === "win", perms: { run: true } },
async function signalShorthandsTest(): Promise<void> {
let s: Deno.SignalStream;
s = Deno.signals.alarm(); // for SIGALRM
assert(s instanceof Deno.SignalStream);
@ -188,5 +197,5 @@ if (Deno.build.os === "win") {
s = Deno.signals.windowChange(); // for SIGWINCH
assert(s instanceof Deno.SignalStream);
s.dispose();
});
}
}
);

View file

@ -1,9 +1,11 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { testPerm, assert, assertEquals } from "./test_util.ts";
import { unitTest, assert, assertEquals } from "./test_util.ts";
// TODO Add tests for modified, accessed, and created fields once there is a way
// to create temp files.
testPerm({ read: true }, async function statSyncSuccess(): Promise<void> {
unitTest({ perms: { read: true } }, async function statSyncSuccess(): Promise<
void
> {
const packageInfo = Deno.statSync("README.md");
assert(packageInfo.isFile());
assert(!packageInfo.isSymlink());
@ -17,7 +19,9 @@ testPerm({ read: true }, async function statSyncSuccess(): Promise<void> {
assert(!testsInfo.isSymlink());
});
testPerm({ read: false }, async function statSyncPerm(): Promise<void> {
unitTest({ perms: { read: false } }, async function statSyncPerm(): Promise<
void
> {
let caughtError = false;
try {
Deno.statSync("README.md");
@ -28,7 +32,9 @@ testPerm({ read: false }, async function statSyncPerm(): Promise<void> {
assert(caughtError);
});
testPerm({ read: true }, async function statSyncNotFound(): Promise<void> {
unitTest({ perms: { read: true } }, async function statSyncNotFound(): Promise<
void
> {
let caughtError = false;
let badInfo;
@ -43,7 +49,9 @@ testPerm({ read: true }, async function statSyncNotFound(): Promise<void> {
assertEquals(badInfo, undefined);
});
testPerm({ read: true }, async function lstatSyncSuccess(): Promise<void> {
unitTest({ perms: { read: true } }, async function lstatSyncSuccess(): Promise<
void
> {
const packageInfo = Deno.lstatSync("README.md");
assert(packageInfo.isFile());
assert(!packageInfo.isSymlink());
@ -57,7 +65,9 @@ testPerm({ read: true }, async function lstatSyncSuccess(): Promise<void> {
assert(!coreInfo.isSymlink());
});
testPerm({ read: false }, async function lstatSyncPerm(): Promise<void> {
unitTest({ perms: { read: false } }, async function lstatSyncPerm(): Promise<
void
> {
let caughtError = false;
try {
Deno.lstatSync("README.md");
@ -68,7 +78,9 @@ testPerm({ read: false }, async function lstatSyncPerm(): Promise<void> {
assert(caughtError);
});
testPerm({ read: true }, async function lstatSyncNotFound(): Promise<void> {
unitTest({ perms: { read: true } }, async function lstatSyncNotFound(): Promise<
void
> {
let caughtError = false;
let badInfo;
@ -83,7 +95,9 @@ testPerm({ read: true }, async function lstatSyncNotFound(): Promise<void> {
assertEquals(badInfo, undefined);
});
testPerm({ read: true }, async function statSuccess(): Promise<void> {
unitTest({ perms: { read: true } }, async function statSuccess(): Promise<
void
> {
const packageInfo = await Deno.stat("README.md");
assert(packageInfo.isFile());
assert(!packageInfo.isSymlink());
@ -97,7 +111,7 @@ testPerm({ read: true }, async function statSuccess(): Promise<void> {
assert(!testsInfo.isSymlink());
});
testPerm({ read: false }, async function statPerm(): Promise<void> {
unitTest({ perms: { read: false } }, async function statPerm(): Promise<void> {
let caughtError = false;
try {
await Deno.stat("README.md");
@ -108,7 +122,9 @@ testPerm({ read: false }, async function statPerm(): Promise<void> {
assert(caughtError);
});
testPerm({ read: true }, async function statNotFound(): Promise<void> {
unitTest({ perms: { read: true } }, async function statNotFound(): Promise<
void
> {
let caughtError = false;
let badInfo;
@ -123,7 +139,9 @@ testPerm({ read: true }, async function statNotFound(): Promise<void> {
assertEquals(badInfo, undefined);
});
testPerm({ read: true }, async function lstatSuccess(): Promise<void> {
unitTest({ perms: { read: true } }, async function lstatSuccess(): Promise<
void
> {
const packageInfo = await Deno.lstat("README.md");
assert(packageInfo.isFile());
assert(!packageInfo.isSymlink());
@ -137,7 +155,7 @@ testPerm({ read: true }, async function lstatSuccess(): Promise<void> {
assert(!coreInfo.isSymlink());
});
testPerm({ read: false }, async function lstatPerm(): Promise<void> {
unitTest({ perms: { read: false } }, async function lstatPerm(): Promise<void> {
let caughtError = false;
try {
await Deno.lstat("README.md");
@ -148,7 +166,9 @@ testPerm({ read: false }, async function lstatPerm(): Promise<void> {
assert(caughtError);
});
testPerm({ read: true }, async function lstatNotFound(): Promise<void> {
unitTest({ perms: { read: true } }, async function lstatNotFound(): Promise<
void
> {
let caughtError = false;
let badInfo;
@ -163,52 +183,47 @@ testPerm({ read: true }, async function lstatNotFound(): Promise<void> {
assertEquals(badInfo, undefined);
});
const isWindows = Deno.build.os === "win";
unitTest(
{ skip: Deno.build.os !== "win", perms: { read: true, write: true } },
async function statNoUnixFields(): Promise<void> {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const tempDir = Deno.makeTempDirSync();
const filename = tempDir + "/test.txt";
Deno.writeFileSync(filename, data, { perm: 0o666 });
const s = Deno.statSync(filename);
assert(s.dev === null);
assert(s.ino === null);
assert(s.mode === null);
assert(s.nlink === null);
assert(s.uid === null);
assert(s.gid === null);
assert(s.rdev === null);
assert(s.blksize === null);
assert(s.blocks === null);
}
);
// OS dependent tests
if (isWindows) {
testPerm(
{ read: true, write: true },
async function statNoUnixFields(): Promise<void> {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const tempDir = Deno.makeTempDirSync();
const filename = tempDir + "/test.txt";
Deno.writeFileSync(filename, data, { perm: 0o666 });
const s = Deno.statSync(filename);
assert(s.dev === null);
assert(s.ino === null);
assert(s.mode === null);
assert(s.nlink === null);
assert(s.uid === null);
assert(s.gid === null);
assert(s.rdev === null);
assert(s.blksize === null);
assert(s.blocks === null);
}
);
} else {
testPerm(
{ read: true, write: true },
async function statUnixFields(): Promise<void> {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const tempDir = Deno.makeTempDirSync();
const filename = tempDir + "/test.txt";
const filename2 = tempDir + "/test2.txt";
Deno.writeFileSync(filename, data, { perm: 0o666 });
// Create a link
Deno.linkSync(filename, filename2);
const s = Deno.statSync(filename);
assert(s.dev !== null);
assert(s.ino !== null);
assertEquals(s.mode! & 0o666, 0o666);
assertEquals(s.nlink, 2);
assert(s.uid !== null);
assert(s.gid !== null);
assert(s.rdev !== null);
assert(s.blksize !== null);
assert(s.blocks !== null);
}
);
}
unitTest(
{ skip: Deno.build.os === "win", perms: { read: true, write: true } },
async function statUnixFields(): Promise<void> {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const tempDir = Deno.makeTempDirSync();
const filename = tempDir + "/test.txt";
const filename2 = tempDir + "/test2.txt";
Deno.writeFileSync(filename, data, { perm: 0o666 });
// Create a link
Deno.linkSync(filename, filename2);
const s = Deno.statSync(filename);
assert(s.dev !== null);
assert(s.ino !== null);
assertEquals(s.mode! & 0o666, 0o666);
assertEquals(s.nlink, 2);
assert(s.uid !== null);
assert(s.gid !== null);
assert(s.rdev !== null);
assert(s.blksize !== null);
assert(s.blocks !== null);
}
);

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, assert } from "./test_util.ts";
import { unitTest, assert } from "./test_util.ts";
test(function symbolsExists(): void {
unitTest(function symbolsExists(): void {
assert("internal" in Deno.symbols);
assert("customInspect" in Deno.symbols);
});

View file

@ -1,30 +1,33 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, testPerm, assert, assertEquals } from "./test_util.ts";
import { unitTest, assert, assertEquals } from "./test_util.ts";
testPerm({ read: true, write: true }, function symlinkSyncSuccess(): void {
const testDir = Deno.makeTempDirSync();
const oldname = testDir + "/oldname";
const newname = testDir + "/newname";
Deno.mkdirSync(oldname);
let errOnWindows;
// Just for now, until we implement symlink for Windows.
try {
Deno.symlinkSync(oldname, newname);
} catch (e) {
errOnWindows = e;
unitTest(
{ perms: { read: true, write: true } },
function symlinkSyncSuccess(): void {
const testDir = Deno.makeTempDirSync();
const oldname = testDir + "/oldname";
const newname = testDir + "/newname";
Deno.mkdirSync(oldname);
let errOnWindows;
// Just for now, until we implement symlink for Windows.
try {
Deno.symlinkSync(oldname, newname);
} catch (e) {
errOnWindows = e;
}
if (errOnWindows) {
assertEquals(Deno.build.os, "win");
assertEquals(errOnWindows.message, "Not implemented");
} else {
const newNameInfoLStat = Deno.lstatSync(newname);
const newNameInfoStat = Deno.statSync(newname);
assert(newNameInfoLStat.isSymlink());
assert(newNameInfoStat.isDirectory());
}
}
if (errOnWindows) {
assertEquals(Deno.build.os, "win");
assertEquals(errOnWindows.message, "Not implemented");
} else {
const newNameInfoLStat = Deno.lstatSync(newname);
const newNameInfoStat = Deno.statSync(newname);
assert(newNameInfoLStat.isSymlink());
assert(newNameInfoStat.isDirectory());
}
});
);
test(function symlinkSyncPerm(): void {
unitTest(function symlinkSyncPerm(): void {
let err;
try {
Deno.symlinkSync("oldbaddir", "newbaddir");
@ -37,42 +40,46 @@ test(function symlinkSyncPerm(): void {
// Just for now, until we implement symlink for Windows.
// Symlink with type should succeed on other platforms with type ignored
testPerm({ write: true }, function symlinkSyncNotImplemented(): void {
const testDir = Deno.makeTempDirSync();
const oldname = testDir + "/oldname";
const newname = testDir + "/newname";
let err;
try {
Deno.symlinkSync(oldname, newname, "dir");
} catch (e) {
err = e;
unitTest(
{ perms: { write: true } },
function symlinkSyncNotImplemented(): void {
const testDir = Deno.makeTempDirSync();
const oldname = testDir + "/oldname";
const newname = testDir + "/newname";
let err;
try {
Deno.symlinkSync(oldname, newname, "dir");
} catch (e) {
err = e;
}
if (err) {
assertEquals(Deno.build.os, "win");
assertEquals(err.message, "Not implemented");
}
}
if (err) {
assertEquals(Deno.build.os, "win");
assertEquals(err.message, "Not implemented");
}
});
);
testPerm({ read: true, write: true }, async function symlinkSuccess(): Promise<
void
> {
const testDir = Deno.makeTempDirSync();
const oldname = testDir + "/oldname";
const newname = testDir + "/newname";
Deno.mkdirSync(oldname);
let errOnWindows;
// Just for now, until we implement symlink for Windows.
try {
await Deno.symlink(oldname, newname);
} catch (e) {
errOnWindows = e;
unitTest(
{ perms: { read: true, write: true } },
async function symlinkSuccess(): Promise<void> {
const testDir = Deno.makeTempDirSync();
const oldname = testDir + "/oldname";
const newname = testDir + "/newname";
Deno.mkdirSync(oldname);
let errOnWindows;
// Just for now, until we implement symlink for Windows.
try {
await Deno.symlink(oldname, newname);
} catch (e) {
errOnWindows = e;
}
if (errOnWindows) {
assertEquals(errOnWindows.message, "Not implemented");
} else {
const newNameInfoLStat = Deno.lstatSync(newname);
const newNameInfoStat = Deno.statSync(newname);
assert(newNameInfoLStat.isSymlink());
assert(newNameInfoStat.isDirectory());
}
}
if (errOnWindows) {
assertEquals(errOnWindows.message, "Not implemented");
} else {
const newNameInfoLStat = Deno.lstatSync(newname);
const newNameInfoStat = Deno.statSync(newname);
assert(newNameInfoLStat.isSymlink());
assert(newNameInfoStat.isDirectory());
}
});
);

View file

@ -137,42 +137,65 @@ function assertOps(fn: Deno.TestFunction): Deno.TestFunction {
// the test has exactly the same contents as before the test.
function assertResources(fn: Deno.TestFunction): Deno.TestFunction {
return async function resourceSanitizer(): Promise<void> {
const preResources = Deno.resources();
const pre = Deno.resources();
await fn();
const postResources = Deno.resources();
const post = Deno.resources();
const msg = `Test case is leaking resources.
Before: ${JSON.stringify(preResources, null, 2)}
After: ${JSON.stringify(postResources, null, 2)}`;
assertEquals(preResources, postResources, msg);
Before: ${JSON.stringify(pre, null, 2)}
After: ${JSON.stringify(post, null, 2)}`;
assertEquals(pre, post, msg);
};
}
export function testPerm(perms: TestPermissions, fn: Deno.TestFunction): void {
const normalizedPerms = normalizeTestPermissions(perms);
interface UnitTestOptions {
skip?: boolean;
perms?: TestPermissions;
}
export function unitTest(fn: Deno.TestFunction): void;
export function unitTest(options: UnitTestOptions, fn: Deno.TestFunction): void;
export function unitTest(
optionsOrFn: UnitTestOptions | Deno.TestFunction,
maybeFn?: Deno.TestFunction
): void {
assert(optionsOrFn, "At least one argument is required");
let options: UnitTestOptions;
let name: string;
let fn: Deno.TestFunction;
if (typeof optionsOrFn === "function") {
options = {};
fn = optionsOrFn;
name = fn.name;
assert(name, "Missing test function name");
} else {
options = optionsOrFn;
assert(maybeFn, "Missing test function definition");
assert(
typeof maybeFn === "function",
"Second argument should be test function definition"
);
fn = maybeFn;
name = fn.name;
assert(name, "Missing test function name");
}
if (options.skip) {
return;
}
const normalizedPerms = normalizeTestPermissions(options.perms || {});
registerPermCombination(normalizedPerms);
if (!permissionsMatch(processPerms, normalizedPerms)) {
return;
}
Deno.test(fn.name, assertResources(assertOps(fn)));
}
export function test(fn: Deno.TestFunction): void {
testPerm(
{
read: false,
write: false,
net: false,
env: false,
run: false,
plugin: false,
hrtime: false
},
fn
);
const testDefinition: Deno.TestDefinition = {
name,
fn: assertResources(assertOps(fn))
};
Deno.test(testDefinition);
}
function extractNumber(re: RegExp, str: string): number | undefined {
@ -231,7 +254,7 @@ export function createResolvable<T>(): Resolvable<T> {
return Object.assign(promise, methods!) as Resolvable<T>;
}
test(function permissionsMatches(): void {
unitTest(function permissionsMatches(): void {
assert(
permissionsMatch(
{
@ -318,46 +341,49 @@ test(function permissionsMatches(): void {
);
});
testPerm({ read: true }, async function parsingUnitTestOutput(): Promise<void> {
const cwd = Deno.cwd();
const testDataPath = `${cwd}/tools/testdata/`;
unitTest(
{ perms: { read: true } },
async function parsingUnitTestOutput(): Promise<void> {
const cwd = Deno.cwd();
const testDataPath = `${cwd}/tools/testdata/`;
let result;
let result;
// This is an example of a successful unit test output.
const f1 = await Deno.open(`${testDataPath}/unit_test_output1.txt`);
result = await parseUnitTestOutput(f1, false);
assertEquals(result.actual, 96);
assertEquals(result.expected, 96);
f1.close();
// This is an example of a successful unit test output.
const f1 = await Deno.open(`${testDataPath}/unit_test_output1.txt`);
result = await parseUnitTestOutput(f1, false);
assertEquals(result.actual, 96);
assertEquals(result.expected, 96);
f1.close();
// This is an example of a silently dying unit test.
const f2 = await Deno.open(`${testDataPath}/unit_test_output2.txt`);
result = await parseUnitTestOutput(f2, false);
assertEquals(result.actual, undefined);
assertEquals(result.expected, 96);
f2.close();
// This is an example of a silently dying unit test.
const f2 = await Deno.open(`${testDataPath}/unit_test_output2.txt`);
result = await parseUnitTestOutput(f2, false);
assertEquals(result.actual, undefined);
assertEquals(result.expected, 96);
f2.close();
// This is an example of compiling before successful unit tests.
const f3 = await Deno.open(`${testDataPath}/unit_test_output3.txt`);
result = await parseUnitTestOutput(f3, false);
assertEquals(result.actual, 96);
assertEquals(result.expected, 96);
f3.close();
// This is an example of compiling before successful unit tests.
const f3 = await Deno.open(`${testDataPath}/unit_test_output3.txt`);
result = await parseUnitTestOutput(f3, false);
assertEquals(result.actual, 96);
assertEquals(result.expected, 96);
f3.close();
// Check what happens on empty output.
const f = new Deno.Buffer(new TextEncoder().encode("\n\n\n"));
result = await parseUnitTestOutput(f, false);
assertEquals(result.actual, undefined);
assertEquals(result.expected, undefined);
});
// Check what happens on empty output.
const f = new Deno.Buffer(new TextEncoder().encode("\n\n\n"));
result = await parseUnitTestOutput(f, false);
assertEquals(result.actual, undefined);
assertEquals(result.expected, undefined);
}
);
/*
* Ensure all unit test files (e.g. xxx_test.ts) are present as imports in
* cli/js/unit_tests.ts as it is easy to miss this out
*/
testPerm(
{ read: true },
unitTest(
{ perms: { read: true } },
async function assertAllUnitTestFilesImported(): Promise<void> {
const directoryTestFiles = Deno.readDirSync("./cli/js")
.map(k => k.name)

View file

@ -1,19 +1,19 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, assert, assertEquals } from "./test_util.ts";
import { unitTest, assert, assertEquals } from "./test_util.ts";
test(function btoaSuccess(): void {
unitTest(function btoaSuccess(): void {
const text = "hello world";
const encoded = btoa(text);
assertEquals(encoded, "aGVsbG8gd29ybGQ=");
});
test(function atobSuccess(): void {
unitTest(function atobSuccess(): void {
const encoded = "aGVsbG8gd29ybGQ=";
const decoded = atob(encoded);
assertEquals(decoded, "hello world");
});
test(function atobWithAsciiWhitespace(): void {
unitTest(function atobWithAsciiWhitespace(): void {
const encodedList = [
" aGVsbG8gd29ybGQ=",
" aGVsbG8gd29ybGQ=",
@ -30,7 +30,7 @@ test(function atobWithAsciiWhitespace(): void {
}
});
test(function atobThrows(): void {
unitTest(function atobThrows(): void {
let threw = false;
try {
atob("aGVsbG8gd29ybGQ==");
@ -40,7 +40,7 @@ test(function atobThrows(): void {
assert(threw);
});
test(function atobThrows2(): void {
unitTest(function atobThrows2(): void {
let threw = false;
try {
atob("aGVsbG8gd29ybGQ===");
@ -50,7 +50,7 @@ test(function atobThrows2(): void {
assert(threw);
});
test(function btoaFailed(): void {
unitTest(function btoaFailed(): void {
const text = "你好";
let err;
try {
@ -62,7 +62,7 @@ test(function btoaFailed(): void {
assert(err instanceof TypeError);
});
test(function textDecoder2(): void {
unitTest(function textDecoder2(): void {
// prettier-ignore
const fixture = new Uint8Array([
0xf0, 0x9d, 0x93, 0xbd,
@ -74,7 +74,7 @@ test(function textDecoder2(): void {
assertEquals(decoder.decode(fixture), "𝓽𝓮𝔁𝓽");
});
test(function textDecoderIgnoreBOM(): void {
unitTest(function textDecoderIgnoreBOM(): void {
// prettier-ignore
const fixture = new Uint8Array([
0xef, 0xbb, 0xbf,
@ -87,7 +87,7 @@ test(function textDecoderIgnoreBOM(): void {
assertEquals(decoder.decode(fixture), "𝓽𝓮𝔁𝓽");
});
test(function textDecoderNotBOM(): void {
unitTest(function textDecoderNotBOM(): void {
// prettier-ignore
const fixture = new Uint8Array([
0xef, 0xbb, 0x89,
@ -100,13 +100,13 @@ test(function textDecoderNotBOM(): void {
assertEquals(decoder.decode(fixture), "ﻉ𝓽𝓮𝔁𝓽");
});
test(function textDecoderASCII(): void {
unitTest(function textDecoderASCII(): void {
const fixture = new Uint8Array([0x89, 0x95, 0x9f, 0xbf]);
const decoder = new TextDecoder("ascii");
assertEquals(decoder.decode(fixture), "‰•Ÿ¿");
});
test(function textDecoderErrorEncoding(): void {
unitTest(function textDecoderErrorEncoding(): void {
let didThrow = false;
try {
new TextDecoder("foo");
@ -117,7 +117,7 @@ test(function textDecoderErrorEncoding(): void {
assert(didThrow);
});
test(function textEncoder(): void {
unitTest(function textEncoder(): void {
const fixture = "𝓽𝓮𝔁𝓽";
const encoder = new TextEncoder();
// prettier-ignore
@ -129,7 +129,7 @@ test(function textEncoder(): void {
]);
});
test(function textEncodeInto(): void {
unitTest(function textEncodeInto(): void {
const fixture = "text";
const encoder = new TextEncoder();
const bytes = new Uint8Array(5);
@ -142,7 +142,7 @@ test(function textEncodeInto(): void {
]);
});
test(function textEncodeInto2(): void {
unitTest(function textEncodeInto2(): void {
const fixture = "𝓽𝓮𝔁𝓽";
const encoder = new TextEncoder();
const bytes = new Uint8Array(17);
@ -158,7 +158,7 @@ test(function textEncodeInto2(): void {
]);
});
test(function textDecoderSharedUint8Array(): void {
unitTest(function textDecoderSharedUint8Array(): void {
const ab = new SharedArrayBuffer(6);
const dataView = new DataView(ab);
const charCodeA = "A".charCodeAt(0);
@ -171,7 +171,7 @@ test(function textDecoderSharedUint8Array(): void {
assertEquals(actual, "ABCDEF");
});
test(function textDecoderSharedInt32Array(): void {
unitTest(function textDecoderSharedInt32Array(): void {
const ab = new SharedArrayBuffer(8);
const dataView = new DataView(ab);
const charCodeA = "A".charCodeAt(0);
@ -184,7 +184,7 @@ test(function textDecoderSharedInt32Array(): void {
assertEquals(actual, "ABCDEFGH");
});
test(function toStringShouldBeWebCompatibility(): void {
unitTest(function toStringShouldBeWebCompatibility(): void {
const encoder = new TextEncoder();
assertEquals(encoder.toString(), "[object TextEncoder]");

View file

@ -1,6 +1,6 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import {
test,
unitTest,
createResolvable,
assert,
assertEquals,
@ -31,7 +31,7 @@ async function waitForMs(ms: number): Promise<number> {
return new Promise((resolve: () => void): number => setTimeout(resolve, ms));
}
test(async function timeoutSuccess(): Promise<void> {
unitTest(async function timeoutSuccess(): Promise<void> {
const { promise, resolve } = deferred();
let count = 0;
setTimeout((): void => {
@ -43,7 +43,7 @@ test(async function timeoutSuccess(): Promise<void> {
assertEquals(count, 1);
});
test(async function timeoutArgs(): Promise<void> {
unitTest(async function timeoutArgs(): Promise<void> {
const { promise, resolve } = deferred();
const arg = 1;
setTimeout(
@ -61,7 +61,7 @@ test(async function timeoutArgs(): Promise<void> {
await promise;
});
test(async function timeoutCancelSuccess(): Promise<void> {
unitTest(async function timeoutCancelSuccess(): Promise<void> {
let count = 0;
const id = setTimeout((): void => {
count++;
@ -72,7 +72,7 @@ test(async function timeoutCancelSuccess(): Promise<void> {
assertEquals(count, 0);
});
test(async function timeoutCancelMultiple(): Promise<void> {
unitTest(async function timeoutCancelMultiple(): Promise<void> {
function uncalled(): never {
throw new Error("This function should not be called.");
}
@ -97,7 +97,7 @@ test(async function timeoutCancelMultiple(): Promise<void> {
await waitForMs(50);
});
test(async function timeoutCancelInvalidSilentFail(): Promise<void> {
unitTest(async function timeoutCancelInvalidSilentFail(): Promise<void> {
// Expect no panic
const { promise, resolve } = deferred();
let count = 0;
@ -114,7 +114,7 @@ test(async function timeoutCancelInvalidSilentFail(): Promise<void> {
clearTimeout(2147483647);
});
test(async function intervalSuccess(): Promise<void> {
unitTest(async function intervalSuccess(): Promise<void> {
const { promise, resolve } = deferred();
let count = 0;
const id = setInterval((): void => {
@ -129,7 +129,7 @@ test(async function intervalSuccess(): Promise<void> {
assertEquals(count, 1);
});
test(async function intervalCancelSuccess(): Promise<void> {
unitTest(async function intervalCancelSuccess(): Promise<void> {
let count = 0;
const id = setInterval((): void => {
count++;
@ -139,7 +139,7 @@ test(async function intervalCancelSuccess(): Promise<void> {
assertEquals(count, 0);
});
test(async function intervalOrdering(): Promise<void> {
unitTest(async function intervalOrdering(): Promise<void> {
const timers: number[] = [];
let timeouts = 0;
function onTimeout(): void {
@ -155,12 +155,12 @@ test(async function intervalOrdering(): Promise<void> {
assertEquals(timeouts, 1);
});
test(async function intervalCancelInvalidSilentFail(): Promise<void> {
unitTest(async function intervalCancelInvalidSilentFail(): Promise<void> {
// Should silently fail (no panic)
clearInterval(2147483647);
});
test(async function fireCallbackImmediatelyWhenDelayOverMaxValue(): Promise<
unitTest(async function fireCallbackImmediatelyWhenDelayOverMaxValue(): Promise<
void
> {
let count = 0;
@ -171,7 +171,7 @@ test(async function fireCallbackImmediatelyWhenDelayOverMaxValue(): Promise<
assertEquals(count, 1);
});
test(async function timeoutCallbackThis(): Promise<void> {
unitTest(async function timeoutCallbackThis(): Promise<void> {
const { promise, resolve } = deferred();
const obj = {
foo(): void {
@ -183,7 +183,7 @@ test(async function timeoutCallbackThis(): Promise<void> {
await promise;
});
test(async function timeoutBindThis(): Promise<void> {
unitTest(async function timeoutBindThis(): Promise<void> {
const thisCheckPassed = [null, undefined, window, globalThis];
const thisCheckFailed = [
@ -231,7 +231,7 @@ test(async function timeoutBindThis(): Promise<void> {
}
});
test(async function clearTimeoutShouldConvertToNumber(): Promise<void> {
unitTest(async function clearTimeoutShouldConvertToNumber(): Promise<void> {
let called = false;
const obj = {
valueOf(): number {
@ -243,7 +243,7 @@ test(async function clearTimeoutShouldConvertToNumber(): Promise<void> {
assert(called);
});
test(function setTimeoutShouldThrowWithBigint(): void {
unitTest(function setTimeoutShouldThrowWithBigint(): void {
let hasThrown = 0;
try {
setTimeout((): void => {}, (1n as unknown) as number);
@ -258,7 +258,7 @@ test(function setTimeoutShouldThrowWithBigint(): void {
assertEquals(hasThrown, 2);
});
test(function clearTimeoutShouldThrowWithBigint(): void {
unitTest(function clearTimeoutShouldThrowWithBigint(): void {
let hasThrown = 0;
try {
clearTimeout((1n as unknown) as number);
@ -273,23 +273,23 @@ test(function clearTimeoutShouldThrowWithBigint(): void {
assertEquals(hasThrown, 2);
});
test(function testFunctionName(): void {
unitTest(function testFunctionName(): void {
assertEquals(clearTimeout.name, "clearTimeout");
assertEquals(clearInterval.name, "clearInterval");
});
test(function testFunctionParamsLength(): void {
unitTest(function testFunctionParamsLength(): void {
assertEquals(setTimeout.length, 1);
assertEquals(setInterval.length, 1);
assertEquals(clearTimeout.length, 0);
assertEquals(clearInterval.length, 0);
});
test(function clearTimeoutAndClearIntervalNotBeEquals(): void {
unitTest(function clearTimeoutAndClearIntervalNotBeEquals(): void {
assertNotEquals(clearTimeout, clearInterval);
});
test(async function timerMaxCpuBug(): Promise<void> {
unitTest(async function timerMaxCpuBug(): Promise<void> {
// There was a bug where clearing a timeout would cause Deno to use 100% CPU.
clearTimeout(setTimeout(() => {}, 1000));
// We can check this by counting how many ops have triggered in the interim.
@ -300,7 +300,7 @@ test(async function timerMaxCpuBug(): Promise<void> {
assert(opsDispatched_ - opsDispatched < 10);
});
test(async function timerBasicMicrotaskOrdering(): Promise<void> {
unitTest(async function timerBasicMicrotaskOrdering(): Promise<void> {
let s = "";
let count = 0;
const { promise, resolve } = deferred();
@ -324,7 +324,7 @@ test(async function timerBasicMicrotaskOrdering(): Promise<void> {
assertEquals(s, "deno");
});
test(async function timerNestedMicrotaskOrdering(): Promise<void> {
unitTest(async function timerNestedMicrotaskOrdering(): Promise<void> {
let s = "";
const { promise, resolve } = deferred();
s += "0";

View file

@ -1,10 +1,9 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import {
test,
testPerm,
assert,
assertEquals,
createResolvable
createResolvable,
unitTest
} from "./test_util.ts";
import { BufWriter, BufReader } from "../../std/io/bufio.ts";
import { TextProtoReader } from "../../std/textproto/mod.ts";
@ -12,7 +11,7 @@ import { TextProtoReader } from "../../std/textproto/mod.ts";
const encoder = new TextEncoder();
const decoder = new TextDecoder();
test(async function connectTLSNoPerm(): Promise<void> {
unitTest(async function connectTLSNoPerm(): Promise<void> {
let err;
try {
await Deno.connectTLS({ hostname: "github.com", port: 443 });
@ -23,7 +22,7 @@ test(async function connectTLSNoPerm(): Promise<void> {
assertEquals(err.name, "PermissionDenied");
});
test(async function connectTLSCertFileNoReadPerm(): Promise<void> {
unitTest(async function connectTLSCertFileNoReadPerm(): Promise<void> {
let err;
try {
await Deno.connectTLS({
@ -38,8 +37,8 @@ test(async function connectTLSCertFileNoReadPerm(): Promise<void> {
assertEquals(err.name, "PermissionDenied");
});
testPerm(
{ read: true, net: true },
unitTest(
{ perms: { read: true, net: true } },
async function listenTLSNonExistentCertKeyFiles(): Promise<void> {
let err;
const options = {
@ -71,24 +70,29 @@ testPerm(
}
);
testPerm({ net: true }, async function listenTLSNoReadPerm(): Promise<void> {
let err;
try {
Deno.listenTLS({
hostname: "localhost",
port: 4500,
certFile: "cli/tests/tls/localhost.crt",
keyFile: "cli/tests/tls/localhost.key"
});
} catch (e) {
err = e;
unitTest(
{ perms: { net: true } },
async function listenTLSNoReadPerm(): Promise<void> {
let err;
try {
Deno.listenTLS({
hostname: "localhost",
port: 4500,
certFile: "cli/tests/tls/localhost.crt",
keyFile: "cli/tests/tls/localhost.key"
});
} catch (e) {
err = e;
}
assert(err instanceof Deno.errors.PermissionDenied);
assertEquals(err.name, "PermissionDenied");
}
assert(err instanceof Deno.errors.PermissionDenied);
assertEquals(err.name, "PermissionDenied");
});
);
testPerm(
{ read: true, write: true, net: true },
unitTest(
{
perms: { read: true, write: true, net: true }
},
async function listenTLSEmptyKeyFile(): Promise<void> {
let err;
const options = {
@ -116,8 +120,8 @@ testPerm(
}
);
testPerm(
{ read: true, write: true, net: true },
unitTest(
{ perms: { read: true, write: true, net: true } },
async function listenTLSEmptyCertFile(): Promise<void> {
let err;
const options = {
@ -145,65 +149,66 @@ testPerm(
}
);
testPerm({ read: true, net: true }, async function dialAndListenTLS(): Promise<
void
> {
const resolvable = createResolvable();
const hostname = "localhost";
const port = 4500;
unitTest(
{ perms: { read: true, net: true } },
async function dialAndListenTLS(): Promise<void> {
const resolvable = createResolvable();
const hostname = "localhost";
const port = 4500;
const listener = Deno.listenTLS({
hostname,
port,
certFile: "cli/tests/tls/localhost.crt",
keyFile: "cli/tests/tls/localhost.key"
});
const listener = Deno.listenTLS({
hostname,
port,
certFile: "cli/tests/tls/localhost.crt",
keyFile: "cli/tests/tls/localhost.key"
});
const response = encoder.encode(
"HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n"
);
const response = encoder.encode(
"HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n"
);
listener.accept().then(
async (conn): Promise<void> => {
assert(conn.remoteAddr != null);
assert(conn.localAddr != null);
await conn.write(response);
// TODO(bartlomieju): this might be a bug
setTimeout(() => {
conn.close();
resolvable.resolve();
}, 0);
}
);
listener.accept().then(
async (conn): Promise<void> => {
assert(conn.remoteAddr != null);
assert(conn.localAddr != null);
await conn.write(response);
// TODO(bartlomieju): this might be a bug
setTimeout(() => {
conn.close();
resolvable.resolve();
}, 0);
}
);
const conn = await Deno.connectTLS({
hostname,
port,
certFile: "cli/tests/tls/RootCA.pem"
});
assert(conn.rid > 0);
const w = new BufWriter(conn);
const r = new BufReader(conn);
const body = `GET / HTTP/1.1\r\nHost: ${hostname}:${port}\r\n\r\n`;
const writeResult = await w.write(encoder.encode(body));
assertEquals(body.length, writeResult);
await w.flush();
const tpr = new TextProtoReader(r);
const statusLine = await tpr.readLine();
assert(statusLine !== Deno.EOF, `line must be read: ${String(statusLine)}`);
const m = statusLine.match(/^(.+?) (.+?) (.+?)$/);
assert(m !== null, "must be matched");
const [_, proto, status, ok] = m;
assertEquals(proto, "HTTP/1.1");
assertEquals(status, "200");
assertEquals(ok, "OK");
const headers = await tpr.readMIMEHeader();
assert(headers !== Deno.EOF);
const contentLength = parseInt(headers.get("content-length")!);
const bodyBuf = new Uint8Array(contentLength);
await r.readFull(bodyBuf);
assertEquals(decoder.decode(bodyBuf), "Hello World\n");
conn.close();
listener.close();
await resolvable;
});
const conn = await Deno.connectTLS({
hostname,
port,
certFile: "cli/tests/tls/RootCA.pem"
});
assert(conn.rid > 0);
const w = new BufWriter(conn);
const r = new BufReader(conn);
const body = `GET / HTTP/1.1\r\nHost: ${hostname}:${port}\r\n\r\n`;
const writeResult = await w.write(encoder.encode(body));
assertEquals(body.length, writeResult);
await w.flush();
const tpr = new TextProtoReader(r);
const statusLine = await tpr.readLine();
assert(statusLine !== Deno.EOF, `line must be read: ${String(statusLine)}`);
const m = statusLine.match(/^(.+?) (.+?) (.+?)$/);
assert(m !== null, "must be matched");
const [_, proto, status, ok] = m;
assertEquals(proto, "HTTP/1.1");
assertEquals(status, "200");
assertEquals(ok, "OK");
const headers = await tpr.readMIMEHeader();
assert(headers !== Deno.EOF);
const contentLength = parseInt(headers.get("content-length")!);
const bodyBuf = new Uint8Array(contentLength);
await r.readFull(bodyBuf);
assertEquals(decoder.decode(bodyBuf), "Hello World\n");
conn.close();
listener.close();
await resolvable;
}
);

View file

@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { testPerm, assertEquals, assert } from "./test_util.ts";
import { unitTest, assertEquals, assert } from "./test_util.ts";
function readDataSync(name: string): string {
const data = Deno.readFileSync(name);
@ -15,43 +15,47 @@ async function readData(name: string): Promise<string> {
return text;
}
testPerm({ read: true, write: true }, function truncateSyncSuccess(): void {
const enc = new TextEncoder();
const d = enc.encode("Hello");
const filename = Deno.makeTempDirSync() + "/test_truncateSync.txt";
Deno.writeFileSync(filename, d);
Deno.truncateSync(filename, 20);
let data = readDataSync(filename);
assertEquals(data.length, 20);
Deno.truncateSync(filename, 5);
data = readDataSync(filename);
assertEquals(data.length, 5);
Deno.truncateSync(filename, -5);
data = readDataSync(filename);
assertEquals(data.length, 0);
Deno.removeSync(filename);
});
unitTest(
{ perms: { read: true, write: true } },
function truncateSyncSuccess(): void {
const enc = new TextEncoder();
const d = enc.encode("Hello");
const filename = Deno.makeTempDirSync() + "/test_truncateSync.txt";
Deno.writeFileSync(filename, d);
Deno.truncateSync(filename, 20);
let data = readDataSync(filename);
assertEquals(data.length, 20);
Deno.truncateSync(filename, 5);
data = readDataSync(filename);
assertEquals(data.length, 5);
Deno.truncateSync(filename, -5);
data = readDataSync(filename);
assertEquals(data.length, 0);
Deno.removeSync(filename);
}
);
testPerm({ read: true, write: true }, async function truncateSuccess(): Promise<
void
> {
const enc = new TextEncoder();
const d = enc.encode("Hello");
const filename = Deno.makeTempDirSync() + "/test_truncate.txt";
await Deno.writeFile(filename, d);
await Deno.truncate(filename, 20);
let data = await readData(filename);
assertEquals(data.length, 20);
await Deno.truncate(filename, 5);
data = await readData(filename);
assertEquals(data.length, 5);
await Deno.truncate(filename, -5);
data = await readData(filename);
assertEquals(data.length, 0);
await Deno.remove(filename);
});
unitTest(
{ perms: { read: true, write: true } },
async function truncateSuccess(): Promise<void> {
const enc = new TextEncoder();
const d = enc.encode("Hello");
const filename = Deno.makeTempDirSync() + "/test_truncate.txt";
await Deno.writeFile(filename, d);
await Deno.truncate(filename, 20);
let data = await readData(filename);
assertEquals(data.length, 20);
await Deno.truncate(filename, 5);
data = await readData(filename);
assertEquals(data.length, 5);
await Deno.truncate(filename, -5);
data = await readData(filename);
assertEquals(data.length, 0);
await Deno.remove(filename);
}
);
testPerm({ write: false }, function truncateSyncPerm(): void {
unitTest({ perms: { write: false } }, function truncateSyncPerm(): void {
let err;
try {
Deno.mkdirSync("/test_truncateSyncPermission.txt");
@ -62,7 +66,9 @@ testPerm({ write: false }, function truncateSyncPerm(): void {
assertEquals(err.name, "PermissionDenied");
});
testPerm({ write: false }, async function truncatePerm(): Promise<void> {
unitTest({ perms: { write: false } }, async function truncatePerm(): Promise<
void
> {
let err;
try {
await Deno.mkdir("/test_truncatePermission.txt");

View file

@ -1,16 +1,16 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, testPerm, assert } from "./test_util.ts";
import { unitTest, assert } from "./test_util.ts";
// Note tests for Deno.setRaw is in integration tests.
testPerm({ read: true }, function isatty(): void {
unitTest({ perms: { read: true } }, function isatty(): void {
// CI not under TTY, so cannot test stdin/stdout/stderr.
const f = Deno.openSync("cli/tests/hello.txt");
assert(!Deno.isatty(f.rid));
f.close();
});
test(function isattyError(): void {
unitTest(function isattyError(): void {
let caught = false;
try {
// Absurdly large rid.

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, assert, assertEquals } from "./test_util.ts";
import { unitTest, assert, assertEquals } from "./test_util.ts";
test(function urlSearchParamsInitString(): void {
unitTest(function urlSearchParamsInitString(): void {
const init = "c=4&a=2&b=3&%C3%A1=1";
const searchParams = new URLSearchParams(init);
assert(
@ -10,7 +10,7 @@ test(function urlSearchParamsInitString(): void {
);
});
test(function urlSearchParamsInitIterable(): void {
unitTest(function urlSearchParamsInitIterable(): void {
const init = [
["a", "54"],
["b", "true"]
@ -19,13 +19,13 @@ test(function urlSearchParamsInitIterable(): void {
assertEquals(searchParams.toString(), "a=54&b=true");
});
test(function urlSearchParamsInitRecord(): void {
unitTest(function urlSearchParamsInitRecord(): void {
const init = { a: "54", b: "true" };
const searchParams = new URLSearchParams(init);
assertEquals(searchParams.toString(), "a=54&b=true");
});
test(function urlSearchParamsInit(): void {
unitTest(function urlSearchParamsInit(): void {
const params1 = new URLSearchParams("a=b");
assertEquals(params1.toString(), "a=b");
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@ -33,20 +33,20 @@ test(function urlSearchParamsInit(): void {
assertEquals(params2.toString(), "a=b");
});
test(function urlSearchParamsAppendSuccess(): void {
unitTest(function urlSearchParamsAppendSuccess(): void {
const searchParams = new URLSearchParams();
searchParams.append("a", "true");
assertEquals(searchParams.toString(), "a=true");
});
test(function urlSearchParamsDeleteSuccess(): void {
unitTest(function urlSearchParamsDeleteSuccess(): void {
const init = "a=54&b=true";
const searchParams = new URLSearchParams(init);
searchParams.delete("b");
assertEquals(searchParams.toString(), "a=54");
});
test(function urlSearchParamsGetAllSuccess(): void {
unitTest(function urlSearchParamsGetAllSuccess(): void {
const init = "a=54&b=true&a=true";
const searchParams = new URLSearchParams(init);
assertEquals(searchParams.getAll("a"), ["54", "true"]);
@ -54,7 +54,7 @@ test(function urlSearchParamsGetAllSuccess(): void {
assertEquals(searchParams.getAll("c"), []);
});
test(function urlSearchParamsGetSuccess(): void {
unitTest(function urlSearchParamsGetSuccess(): void {
const init = "a=54&b=true&a=true";
const searchParams = new URLSearchParams(init);
assertEquals(searchParams.get("a"), "54");
@ -62,7 +62,7 @@ test(function urlSearchParamsGetSuccess(): void {
assertEquals(searchParams.get("c"), null);
});
test(function urlSearchParamsHasSuccess(): void {
unitTest(function urlSearchParamsHasSuccess(): void {
const init = "a=54&b=true&a=true";
const searchParams = new URLSearchParams(init);
assert(searchParams.has("a"));
@ -70,28 +70,28 @@ test(function urlSearchParamsHasSuccess(): void {
assert(!searchParams.has("c"));
});
test(function urlSearchParamsSetReplaceFirstAndRemoveOthers(): void {
unitTest(function urlSearchParamsSetReplaceFirstAndRemoveOthers(): void {
const init = "a=54&b=true&a=true";
const searchParams = new URLSearchParams(init);
searchParams.set("a", "false");
assertEquals(searchParams.toString(), "a=false&b=true");
});
test(function urlSearchParamsSetAppendNew(): void {
unitTest(function urlSearchParamsSetAppendNew(): void {
const init = "a=54&b=true&a=true";
const searchParams = new URLSearchParams(init);
searchParams.set("c", "foo");
assertEquals(searchParams.toString(), "a=54&b=true&a=true&c=foo");
});
test(function urlSearchParamsSortSuccess(): void {
unitTest(function urlSearchParamsSortSuccess(): void {
const init = "c=4&a=2&b=3&a=1";
const searchParams = new URLSearchParams(init);
searchParams.sort();
assertEquals(searchParams.toString(), "a=2&a=1&b=3&c=4");
});
test(function urlSearchParamsForEachSuccess(): void {
unitTest(function urlSearchParamsForEachSuccess(): void {
const init = [
["a", "54"],
["b", "true"]
@ -107,28 +107,28 @@ test(function urlSearchParamsForEachSuccess(): void {
assertEquals(callNum, init.length);
});
test(function urlSearchParamsMissingName(): void {
unitTest(function urlSearchParamsMissingName(): void {
const init = "=4";
const searchParams = new URLSearchParams(init);
assertEquals(searchParams.get(""), "4");
assertEquals(searchParams.toString(), "=4");
});
test(function urlSearchParamsMissingValue(): void {
unitTest(function urlSearchParamsMissingValue(): void {
const init = "4=";
const searchParams = new URLSearchParams(init);
assertEquals(searchParams.get("4"), "");
assertEquals(searchParams.toString(), "4=");
});
test(function urlSearchParamsMissingEqualSign(): void {
unitTest(function urlSearchParamsMissingEqualSign(): void {
const init = "4";
const searchParams = new URLSearchParams(init);
assertEquals(searchParams.get("4"), "");
assertEquals(searchParams.toString(), "4=");
});
test(function urlSearchParamsMissingPair(): void {
unitTest(function urlSearchParamsMissingPair(): void {
const init = "c=4&&a=54&";
const searchParams = new URLSearchParams(init);
assertEquals(searchParams.toString(), "c=4&a=54");
@ -136,7 +136,7 @@ test(function urlSearchParamsMissingPair(): void {
// If pair does not contain exactly two items, then throw a TypeError.
// ref https://url.spec.whatwg.org/#interface-urlsearchparams
test(function urlSearchParamsShouldThrowTypeError(): void {
unitTest(function urlSearchParamsShouldThrowTypeError(): void {
let hasThrown = 0;
try {
@ -166,7 +166,7 @@ test(function urlSearchParamsShouldThrowTypeError(): void {
assertEquals(hasThrown, 2);
});
test(function urlSearchParamsAppendArgumentsCheck(): void {
unitTest(function urlSearchParamsAppendArgumentsCheck(): void {
const methodRequireOneParam = ["delete", "getAll", "get", "has", "forEach"];
const methodRequireTwoParams = ["append", "set"];
@ -209,7 +209,7 @@ test(function urlSearchParamsAppendArgumentsCheck(): void {
});
// ref: https://github.com/web-platform-tests/wpt/blob/master/url/urlsearchparams-delete.any.js
test(function urlSearchParamsDeletingAppendedMultiple(): void {
unitTest(function urlSearchParamsDeletingAppendedMultiple(): void {
const params = new URLSearchParams();
params.append("first", (1 as unknown) as string);
assert(params.has("first"));
@ -223,7 +223,7 @@ test(function urlSearchParamsDeletingAppendedMultiple(): void {
});
// ref: https://github.com/web-platform-tests/wpt/blob/master/url/urlsearchparams-constructor.any.js#L176-L182
test(function urlSearchParamsCustomSymbolIterator(): void {
unitTest(function urlSearchParamsCustomSymbolIterator(): void {
const params = new URLSearchParams();
params[Symbol.iterator] = function*(): IterableIterator<[string, string]> {
yield ["a", "b"];
@ -232,12 +232,14 @@ test(function urlSearchParamsCustomSymbolIterator(): void {
assertEquals(params1.get("a"), "b");
});
test(function urlSearchParamsCustomSymbolIteratorWithNonStringParams(): void {
const params = {};
// @ts-ignore
params[Symbol.iterator] = function*(): IterableIterator<[number, number]> {
yield [1, 2];
};
const params1 = new URLSearchParams((params as unknown) as string[][]);
assertEquals(params1.get("1"), "2");
});
unitTest(
function urlSearchParamsCustomSymbolIteratorWithNonStringParams(): void {
const params = {};
// @ts-ignore
params[Symbol.iterator] = function*(): IterableIterator<[number, number]> {
yield [1, 2];
};
const params1 = new URLSearchParams((params as unknown) as string[][]);
assertEquals(params1.get("1"), "2");
}
);

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { test, assert, assertEquals, assertThrows } from "./test_util.ts";
import { unitTest, assert, assertEquals, assertThrows } from "./test_util.ts";
test(function urlParsing(): void {
unitTest(function urlParsing(): void {
const url = new URL(
"https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat"
);
@ -31,7 +31,7 @@ test(function urlParsing(): void {
);
});
test(function urlModifications(): void {
unitTest(function urlModifications(): void {
const url = new URL(
"https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat"
);
@ -86,7 +86,7 @@ test(function urlModifications(): void {
);
});
test(function urlModifyHref(): void {
unitTest(function urlModifyHref(): void {
const url = new URL("http://example.com/");
url.href = "https://foo:bar@example.com:8080/baz/qat#qux";
assertEquals(url.protocol, "https:");
@ -98,7 +98,7 @@ test(function urlModifyHref(): void {
assertEquals(url.hash, "#qux");
});
test(function urlModifyPathname(): void {
unitTest(function urlModifyPathname(): void {
const url = new URL("http://foo.bar/baz%qat/qux%quux");
assertEquals(url.pathname, "/baz%qat/qux%quux");
url.pathname = url.pathname;
@ -109,7 +109,7 @@ test(function urlModifyPathname(): void {
assertEquals(url.pathname, "/baz%23qat%20qux");
});
test(function urlModifyHash(): void {
unitTest(function urlModifyHash(): void {
const url = new URL("http://foo.bar");
url.hash = "%foo bar/qat%qux#bar";
assertEquals(url.hash, "#%foo%20bar/qat%qux#bar");
@ -117,7 +117,7 @@ test(function urlModifyHash(): void {
assertEquals(url.hash, "#%foo%20bar/qat%qux#bar");
});
test(function urlSearchParamsReuse(): void {
unitTest(function urlSearchParamsReuse(): void {
const url = new URL(
"https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat"
);
@ -126,7 +126,7 @@ test(function urlSearchParamsReuse(): void {
assert(sp === url.searchParams, "Search params should be reused.");
});
test(function urlBaseURL(): void {
unitTest(function urlBaseURL(): void {
const base = new URL(
"https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat"
);
@ -134,7 +134,7 @@ test(function urlBaseURL(): void {
assertEquals(url.href, "https://foo:bar@baz.qat:8000/foo/bar?baz=foo#qux");
});
test(function urlBaseString(): void {
unitTest(function urlBaseString(): void {
const url = new URL(
"/foo/bar?baz=foo#qux",
"https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat"
@ -142,7 +142,7 @@ test(function urlBaseString(): void {
assertEquals(url.href, "https://foo:bar@baz.qat:8000/foo/bar?baz=foo#qux");
});
test(function urlRelativeWithBase(): void {
unitTest(function urlRelativeWithBase(): void {
assertEquals(new URL("", "file:///a/a/a").href, "file:///a/a/a");
assertEquals(new URL(".", "file:///a/a/a").href, "file:///a/a/");
assertEquals(new URL("..", "file:///a/a/a").href, "file:///a/");
@ -152,11 +152,11 @@ test(function urlRelativeWithBase(): void {
assertEquals(new URL("../b", "file:///a/a/a").href, "file:///a/b");
});
test(function emptyBasePath(): void {
unitTest(function emptyBasePath(): void {
assertEquals(new URL("", "http://example.com").href, "http://example.com/");
});
test(function deletingAllParamsRemovesQuestionMarkFromURL(): void {
unitTest(function deletingAllParamsRemovesQuestionMarkFromURL(): void {
const url = new URL("http://example.com/?param1&param2");
url.searchParams.delete("param1");
url.searchParams.delete("param2");
@ -164,7 +164,7 @@ test(function deletingAllParamsRemovesQuestionMarkFromURL(): void {
assertEquals(url.search, "");
});
test(function removingNonExistentParamRemovesQuestionMarkFromURL(): void {
unitTest(function removingNonExistentParamRemovesQuestionMarkFromURL(): void {
const url = new URL("http://example.com/?");
assertEquals(url.href, "http://example.com/?");
url.searchParams.delete("param1");
@ -172,7 +172,7 @@ test(function removingNonExistentParamRemovesQuestionMarkFromURL(): void {
assertEquals(url.search, "");
});
test(function sortingNonExistentParamRemovesQuestionMarkFromURL(): void {
unitTest(function sortingNonExistentParamRemovesQuestionMarkFromURL(): void {
const url = new URL("http://example.com/?");
assertEquals(url.href, "http://example.com/?");
url.searchParams.sort();
@ -181,7 +181,7 @@ test(function sortingNonExistentParamRemovesQuestionMarkFromURL(): void {
});
/*
test(function customInspectFunction(): void {
unitTest(function customInspectFunction(): void {
const url = new URL("http://example.com/?");
assertEquals(
Deno.inspect(url),
@ -190,14 +190,14 @@ test(function customInspectFunction(): void {
});
*/
test(function protocolNotHttpOrFile() {
unitTest(function protocolNotHttpOrFile() {
const url = new URL("about:blank");
assertEquals(url.href, "about:blank");
assertEquals(url.protocol, "about:");
assertEquals(url.origin, "null");
});
test(function createBadUrl(): void {
unitTest(function createBadUrl(): void {
assertThrows(() => {
new URL("0.0.0.0:8080");
});

View file

@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { testPerm, assert } from "./test_util.ts";
import { unitTest, assert } from "./test_util.ts";
// Allow 10 second difference.
// Note this might not be enough for FAT (but we are not testing on such fs).
@ -9,24 +9,27 @@ function assertFuzzyTimestampEquals(t1: any, t2: number): void {
assert(Math.abs(t1 - t2) < 10);
}
testPerm({ read: true, write: true }, function utimeSyncFileSuccess(): void {
const testDir = Deno.makeTempDirSync();
const filename = testDir + "/file.txt";
Deno.writeFileSync(filename, new TextEncoder().encode("hello"), {
perm: 0o666
});
unitTest(
{ perms: { read: true, write: true } },
function utimeSyncFileSuccess(): void {
const testDir = Deno.makeTempDirSync();
const filename = testDir + "/file.txt";
Deno.writeFileSync(filename, new TextEncoder().encode("hello"), {
perm: 0o666
});
const atime = 1000;
const mtime = 50000;
Deno.utimeSync(filename, atime, mtime);
const atime = 1000;
const mtime = 50000;
Deno.utimeSync(filename, atime, mtime);
const fileInfo = Deno.statSync(filename);
assertFuzzyTimestampEquals(fileInfo.accessed, atime);
assertFuzzyTimestampEquals(fileInfo.modified, mtime);
});
const fileInfo = Deno.statSync(filename);
assertFuzzyTimestampEquals(fileInfo.accessed, atime);
assertFuzzyTimestampEquals(fileInfo.modified, mtime);
}
);
testPerm(
{ read: true, write: true },
unitTest(
{ perms: { read: true, write: true } },
function utimeSyncDirectorySuccess(): void {
const testDir = Deno.makeTempDirSync();
@ -40,20 +43,23 @@ testPerm(
}
);
testPerm({ read: true, write: true }, function utimeSyncDateSuccess(): void {
const testDir = Deno.makeTempDirSync();
unitTest(
{ perms: { read: true, write: true } },
function utimeSyncDateSuccess(): void {
const testDir = Deno.makeTempDirSync();
const atime = 1000;
const mtime = 50000;
Deno.utimeSync(testDir, new Date(atime * 1000), new Date(mtime * 1000));
const atime = 1000;
const mtime = 50000;
Deno.utimeSync(testDir, new Date(atime * 1000), new Date(mtime * 1000));
const dirInfo = Deno.statSync(testDir);
assertFuzzyTimestampEquals(dirInfo.accessed, atime);
assertFuzzyTimestampEquals(dirInfo.modified, mtime);
});
const dirInfo = Deno.statSync(testDir);
assertFuzzyTimestampEquals(dirInfo.accessed, atime);
assertFuzzyTimestampEquals(dirInfo.modified, mtime);
}
);
testPerm(
{ read: true, write: true },
unitTest(
{ perms: { read: true, write: true } },
function utimeSyncLargeNumberSuccess(): void {
const testDir = Deno.makeTempDirSync();
@ -69,36 +75,42 @@ testPerm(
}
);
testPerm({ read: true, write: true }, function utimeSyncNotFound(): void {
const atime = 1000;
const mtime = 50000;
unitTest(
{ perms: { read: true, write: true } },
function utimeSyncNotFound(): void {
const atime = 1000;
const mtime = 50000;
let caughtError = false;
try {
Deno.utimeSync("/baddir", atime, mtime);
} catch (e) {
caughtError = true;
assert(e instanceof Deno.errors.NotFound);
let caughtError = false;
try {
Deno.utimeSync("/baddir", atime, mtime);
} catch (e) {
caughtError = true;
assert(e instanceof Deno.errors.NotFound);
}
assert(caughtError);
}
assert(caughtError);
});
);
testPerm({ read: true, write: false }, function utimeSyncPerm(): void {
const atime = 1000;
const mtime = 50000;
unitTest(
{ perms: { read: true, write: false } },
function utimeSyncPerm(): void {
const atime = 1000;
const mtime = 50000;
let caughtError = false;
try {
Deno.utimeSync("/some_dir", atime, mtime);
} catch (e) {
caughtError = true;
assert(e instanceof Deno.errors.PermissionDenied);
let caughtError = false;
try {
Deno.utimeSync("/some_dir", atime, mtime);
} catch (e) {
caughtError = true;
assert(e instanceof Deno.errors.PermissionDenied);
}
assert(caughtError);
}
assert(caughtError);
});
);
testPerm(
{ read: true, write: true },
unitTest(
{ perms: { read: true, write: true } },
async function utimeFileSuccess(): Promise<void> {
const testDir = Deno.makeTempDirSync();
const filename = testDir + "/file.txt";
@ -116,8 +128,8 @@ testPerm(
}
);
testPerm(
{ read: true, write: true },
unitTest(
{ perms: { read: true, write: true } },
async function utimeDirectorySuccess(): Promise<void> {
const testDir = Deno.makeTempDirSync();
@ -131,8 +143,8 @@ testPerm(
}
);
testPerm(
{ read: true, write: true },
unitTest(
{ perms: { read: true, write: true } },
async function utimeDateSuccess(): Promise<void> {
const testDir = Deno.makeTempDirSync();
@ -146,34 +158,36 @@ testPerm(
}
);
testPerm({ read: true, write: true }, async function utimeNotFound(): Promise<
void
> {
const atime = 1000;
const mtime = 50000;
unitTest(
{ perms: { read: true, write: true } },
async function utimeNotFound(): Promise<void> {
const atime = 1000;
const mtime = 50000;
let caughtError = false;
try {
await Deno.utime("/baddir", atime, mtime);
} catch (e) {
caughtError = true;
assert(e instanceof Deno.errors.NotFound);
let caughtError = false;
try {
await Deno.utime("/baddir", atime, mtime);
} catch (e) {
caughtError = true;
assert(e instanceof Deno.errors.NotFound);
}
assert(caughtError);
}
assert(caughtError);
});
);
testPerm({ read: true, write: false }, async function utimeSyncPerm(): Promise<
void
> {
const atime = 1000;
const mtime = 50000;
unitTest(
{ perms: { read: true, write: false } },
async function utimeSyncPerm(): Promise<void> {
const atime = 1000;
const mtime = 50000;
let caughtError = false;
try {
await Deno.utime("/some_dir", atime, mtime);
} catch (e) {
caughtError = true;
assert(e instanceof Deno.errors.PermissionDenied);
let caughtError = false;
try {
await Deno.utime("/some_dir", atime, mtime);
} catch (e) {
caughtError = true;
assert(e instanceof Deno.errors.PermissionDenied);
}
assert(caughtError);
}
assert(caughtError);
});
);

View file

@ -1,6 +1,6 @@
import { test, assert } from "./test_util.ts";
import { unitTest, assert } from "./test_util.ts";
test(function version(): void {
unitTest(function version(): void {
const pattern = /^\d+\.\d+\.\d+/;
assert(pattern.test(Deno.version.deno));
assert(pattern.test(Deno.version.v8));

View file

@ -1,18 +1,21 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { testPerm, assert, assertEquals } from "./test_util.ts";
import { unitTest, assert, assertEquals } from "./test_util.ts";
testPerm({ read: true, write: true }, function writeFileSyncSuccess(): void {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const filename = Deno.makeTempDirSync() + "/test.txt";
Deno.writeFileSync(filename, data);
const dataRead = Deno.readFileSync(filename);
const dec = new TextDecoder("utf-8");
const actual = dec.decode(dataRead);
assertEquals("Hello", actual);
});
unitTest(
{ perms: { read: true, write: true } },
function writeFileSyncSuccess(): void {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const filename = Deno.makeTempDirSync() + "/test.txt";
Deno.writeFileSync(filename, data);
const dataRead = Deno.readFileSync(filename);
const dec = new TextDecoder("utf-8");
const actual = dec.decode(dataRead);
assertEquals("Hello", actual);
}
);
testPerm({ write: true }, function writeFileSyncFail(): void {
unitTest({ perms: { write: true } }, function writeFileSyncFail(): void {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const filename = "/baddir/test.txt";
@ -27,7 +30,7 @@ testPerm({ write: true }, function writeFileSyncFail(): void {
assert(caughtError);
});
testPerm({ write: false }, function writeFileSyncPerm(): void {
unitTest({ perms: { write: false } }, function writeFileSyncPerm(): void {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const filename = "/baddir/test.txt";
@ -42,65 +45,74 @@ testPerm({ write: false }, function writeFileSyncPerm(): void {
assert(caughtError);
});
testPerm({ read: true, write: true }, function writeFileSyncUpdatePerm(): void {
if (Deno.build.os !== "win") {
unitTest(
{ perms: { read: true, write: true } },
function writeFileSyncUpdatePerm(): void {
if (Deno.build.os !== "win") {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const filename = Deno.makeTempDirSync() + "/test.txt";
Deno.writeFileSync(filename, data, { perm: 0o755 });
assertEquals(Deno.statSync(filename).mode! & 0o777, 0o755);
Deno.writeFileSync(filename, data, { perm: 0o666 });
assertEquals(Deno.statSync(filename).mode! & 0o777, 0o666);
}
}
);
unitTest(
{ perms: { read: true, write: true } },
function writeFileSyncCreate(): void {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const filename = Deno.makeTempDirSync() + "/test.txt";
Deno.writeFileSync(filename, data, { perm: 0o755 });
assertEquals(Deno.statSync(filename).mode! & 0o777, 0o755);
Deno.writeFileSync(filename, data, { perm: 0o666 });
assertEquals(Deno.statSync(filename).mode! & 0o777, 0o666);
}
});
let caughtError = false;
// if create turned off, the file won't be created
try {
Deno.writeFileSync(filename, data, { create: false });
} catch (e) {
caughtError = true;
assert(e instanceof Deno.errors.NotFound);
}
assert(caughtError);
testPerm({ read: true, write: true }, function writeFileSyncCreate(): void {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const filename = Deno.makeTempDirSync() + "/test.txt";
let caughtError = false;
// if create turned off, the file won't be created
try {
// Turn on create, should have no error
Deno.writeFileSync(filename, data, { create: true });
Deno.writeFileSync(filename, data, { create: false });
} catch (e) {
caughtError = true;
assert(e instanceof Deno.errors.NotFound);
const dataRead = Deno.readFileSync(filename);
const dec = new TextDecoder("utf-8");
const actual = dec.decode(dataRead);
assertEquals("Hello", actual);
}
assert(caughtError);
);
// Turn on create, should have no error
Deno.writeFileSync(filename, data, { create: true });
Deno.writeFileSync(filename, data, { create: false });
const dataRead = Deno.readFileSync(filename);
const dec = new TextDecoder("utf-8");
const actual = dec.decode(dataRead);
assertEquals("Hello", actual);
});
unitTest(
{ perms: { read: true, write: true } },
function writeFileSyncAppend(): void {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const filename = Deno.makeTempDirSync() + "/test.txt";
Deno.writeFileSync(filename, data);
Deno.writeFileSync(filename, data, { append: true });
let dataRead = Deno.readFileSync(filename);
const dec = new TextDecoder("utf-8");
let actual = dec.decode(dataRead);
assertEquals("HelloHello", actual);
// Now attempt overwrite
Deno.writeFileSync(filename, data, { append: false });
dataRead = Deno.readFileSync(filename);
actual = dec.decode(dataRead);
assertEquals("Hello", actual);
// append not set should also overwrite
Deno.writeFileSync(filename, data);
dataRead = Deno.readFileSync(filename);
actual = dec.decode(dataRead);
assertEquals("Hello", actual);
}
);
testPerm({ read: true, write: true }, function writeFileSyncAppend(): void {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const filename = Deno.makeTempDirSync() + "/test.txt";
Deno.writeFileSync(filename, data);
Deno.writeFileSync(filename, data, { append: true });
let dataRead = Deno.readFileSync(filename);
const dec = new TextDecoder("utf-8");
let actual = dec.decode(dataRead);
assertEquals("HelloHello", actual);
// Now attempt overwrite
Deno.writeFileSync(filename, data, { append: false });
dataRead = Deno.readFileSync(filename);
actual = dec.decode(dataRead);
assertEquals("Hello", actual);
// append not set should also overwrite
Deno.writeFileSync(filename, data);
dataRead = Deno.readFileSync(filename);
actual = dec.decode(dataRead);
assertEquals("Hello", actual);
});
testPerm(
{ read: true, write: true },
unitTest(
{ perms: { read: true, write: true } },
async function writeFileSuccess(): Promise<void> {
const enc = new TextEncoder();
const data = enc.encode("Hello");
@ -113,8 +125,8 @@ testPerm(
}
);
testPerm(
{ read: true, write: true },
unitTest(
{ perms: { read: true, write: true } },
async function writeFileNotFound(): Promise<void> {
const enc = new TextEncoder();
const data = enc.encode("Hello");
@ -131,25 +143,26 @@ testPerm(
}
);
testPerm({ read: true, write: false }, async function writeFilePerm(): Promise<
void
> {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const filename = "/baddir/test.txt";
// The following should fail due to no write permission
let caughtError = false;
try {
await Deno.writeFile(filename, data);
} catch (e) {
caughtError = true;
assert(e instanceof Deno.errors.PermissionDenied);
unitTest(
{ perms: { read: true, write: false } },
async function writeFilePerm(): Promise<void> {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const filename = "/baddir/test.txt";
// The following should fail due to no write permission
let caughtError = false;
try {
await Deno.writeFile(filename, data);
} catch (e) {
caughtError = true;
assert(e instanceof Deno.errors.PermissionDenied);
}
assert(caughtError);
}
assert(caughtError);
});
);
testPerm(
{ read: true, write: true },
unitTest(
{ perms: { read: true, write: true } },
async function writeFileUpdatePerm(): Promise<void> {
if (Deno.build.os !== "win") {
const enc = new TextEncoder();
@ -163,51 +176,53 @@ testPerm(
}
);
testPerm({ read: true, write: true }, async function writeFileCreate(): Promise<
void
> {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const filename = Deno.makeTempDirSync() + "/test.txt";
let caughtError = false;
// if create turned off, the file won't be created
try {
unitTest(
{ perms: { read: true, write: true } },
async function writeFileCreate(): Promise<void> {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const filename = Deno.makeTempDirSync() + "/test.txt";
let caughtError = false;
// if create turned off, the file won't be created
try {
await Deno.writeFile(filename, data, { create: false });
} catch (e) {
caughtError = true;
assert(e instanceof Deno.errors.NotFound);
}
assert(caughtError);
// Turn on create, should have no error
await Deno.writeFile(filename, data, { create: true });
await Deno.writeFile(filename, data, { create: false });
} catch (e) {
caughtError = true;
assert(e instanceof Deno.errors.NotFound);
const dataRead = Deno.readFileSync(filename);
const dec = new TextDecoder("utf-8");
const actual = dec.decode(dataRead);
assertEquals("Hello", actual);
}
assert(caughtError);
);
// Turn on create, should have no error
await Deno.writeFile(filename, data, { create: true });
await Deno.writeFile(filename, data, { create: false });
const dataRead = Deno.readFileSync(filename);
const dec = new TextDecoder("utf-8");
const actual = dec.decode(dataRead);
assertEquals("Hello", actual);
});
testPerm({ read: true, write: true }, async function writeFileAppend(): Promise<
void
> {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const filename = Deno.makeTempDirSync() + "/test.txt";
await Deno.writeFile(filename, data);
await Deno.writeFile(filename, data, { append: true });
let dataRead = Deno.readFileSync(filename);
const dec = new TextDecoder("utf-8");
let actual = dec.decode(dataRead);
assertEquals("HelloHello", actual);
// Now attempt overwrite
await Deno.writeFile(filename, data, { append: false });
dataRead = Deno.readFileSync(filename);
actual = dec.decode(dataRead);
assertEquals("Hello", actual);
// append not set should also overwrite
await Deno.writeFile(filename, data);
dataRead = Deno.readFileSync(filename);
actual = dec.decode(dataRead);
assertEquals("Hello", actual);
});
unitTest(
{ perms: { read: true, write: true } },
async function writeFileAppend(): Promise<void> {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const filename = Deno.makeTempDirSync() + "/test.txt";
await Deno.writeFile(filename, data);
await Deno.writeFile(filename, data, { append: true });
let dataRead = Deno.readFileSync(filename);
const dec = new TextDecoder("utf-8");
let actual = dec.decode(dataRead);
assertEquals("HelloHello", actual);
// Now attempt overwrite
await Deno.writeFile(filename, data, { append: false });
dataRead = Deno.readFileSync(filename);
actual = dec.decode(dataRead);
assertEquals("Hello", actual);
// append not set should also overwrite
await Deno.writeFile(filename, data);
dataRead = Deno.readFileSync(filename);
actual = dec.decode(dataRead);
assertEquals("Hello", actual);
}
);