summaryrefslogtreecommitdiff
path: root/js/test_util.ts
blob: 7124222a7915ea4e8f8c3515ce441aa6e24ea2b0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Copyright 2018 the Deno authors. All rights reserved. MIT license.
//
// We want to test many ops in deno which have different behavior depending on
// the permissions set. These tests can specify which permissions they expect,
// which appends a special string like "permW1N0" to the end of the test name.
// Here we run several copies of deno with different permissions, filtering the
// tests by the special string. permW0N0 means allow-write but not allow-net.
// See tools/unit_tests.py for more details.

import * as deno from "deno";
import * as testing from "./testing/testing.ts";
export { assert, assertEqual } from "./testing/testing.ts";

// testing.setFilter must be run before any tests are defined.
const permFilter = deno.argv[1];
permFromString(permFilter);
testing.setFilter(permFilter);

interface DenoPermissions {
  write?: boolean;
  net?: boolean;
}

function permToString(perms: DenoPermissions): string {
  const w = perms.write ? 1 : 0;
  const n = perms.net ? 1 : 0;
  return `permW${w}N${n}`;
}

function permFromString(s: string): DenoPermissions {
  const re = /^permW([01])N([01])$/;
  const found = s.match(re);
  if (!found) {
    throw Error("Not a permission string");
  }
  return {
    write: Boolean(Number(found[1])),
    net: Boolean(Number(found[2]))
  };
}

export function testPerm(perms: DenoPermissions, fn: testing.TestFunction) {
  const name = `${fn.name}_${permToString(perms)}`;
  testing.test({ fn, name });
}

export function test(fn: testing.TestFunction) {
  testPerm({ write: false, net: false }, fn);
}

test(function permSerialization() {
  for (let write of [true, false]) {
    for (let net of [true, false]) {
      let perms: DenoPermissions = { write, net };
      testing.assertEqual(perms, permFromString(permToString(perms)));
    }
  }
});

// To better catch internal errors, permFromString should throw if it gets an
// invalid permission string.
test(function permFromStringThrows() {
  let threw = false;
  try {
    permFromString("bad");
  } catch (e) {
    threw = true;
  }
  testing.assert(threw);
});