1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-22 15:06:54 -05:00
denoland-deno/js/write_file_test.ts

90 lines
2.8 KiB
TypeScript
Raw Normal View History

// Copyright 2018 the Deno authors. All rights reserved. MIT license.
import { testPerm, assert, assertEqual } from "./test_util.ts";
import * as deno from "deno";
testPerm({ write: true }, function writeFileSyncSuccess() {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const filename = deno.makeTempDirSync() + "/test.txt";
deno.writeFileSync(filename, data, 0o666);
const dataRead = deno.readFileSync(filename);
const dec = new TextDecoder("utf-8");
const actual = dec.decode(dataRead);
assertEqual("Hello", actual);
});
testPerm({ write: true }, function writeFileSyncFail() {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const filename = "/baddir/test.txt";
// The following should fail because /baddir doesn't exist (hopefully).
let caughtError = false;
try {
deno.writeFileSync(filename, data);
} catch (e) {
caughtError = true;
assertEqual(e.kind, deno.ErrorKind.NotFound);
assertEqual(e.name, "NotFound");
}
assert(caughtError);
});
testPerm({ write: false }, function writeFileSyncPerm() {
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 {
deno.writeFileSync(filename, data);
} catch (e) {
caughtError = true;
assertEqual(e.kind, deno.ErrorKind.PermissionDenied);
assertEqual(e.name, "PermissionDenied");
}
assert(caughtError);
});
testPerm({ write: true }, async function writeFileSuccess() {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const filename = deno.makeTempDirSync() + "/test.txt";
await deno.writeFile(filename, data, 0o666);
const dataRead = deno.readFileSync(filename);
const dec = new TextDecoder("utf-8");
const actual = dec.decode(dataRead);
assertEqual("Hello", actual);
});
testPerm({ write: true }, async function writeFileNotFound() {
const enc = new TextEncoder();
const data = enc.encode("Hello");
const filename = "/baddir/test.txt";
// The following should fail because /baddir doesn't exist (hopefully).
let caughtError = false;
try {
await deno.writeFile(filename, data);
} catch (e) {
caughtError = true;
assertEqual(e.kind, deno.ErrorKind.NotFound);
assertEqual(e.name, "NotFound");
}
assert(caughtError);
});
testPerm({ write: false }, async function writeFilePerm() {
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;
assertEqual(e.kind, deno.ErrorKind.PermissionDenied);
assertEqual(e.name, "PermissionDenied");
}
assert(caughtError);
});