summaryrefslogtreecommitdiffstats
path: root/dom/system/tests/ioutils/file_ioutils_test_fixtures.js
blob: 5d2e5011c9540f7802427de4432fc0fcb70f1de6 (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
71
72
73
74
75
76
77
78
// Utility functions.

Uint8Array.prototype.equals = function equals(other) {
  if (this.byteLength !== other.byteLength) {
    return false;
  }
  return this.every((val, i) => val === other[i]);
};

async function createFile(location, contents = "") {
  if (typeof contents === "string") {
    contents = new TextEncoder().encode(contents);
  }
  await IOUtils.write(location, contents);
  const exists = await fileExists(location);
  ok(exists, `Created temporary file at: ${location}`);
}

async function createDir(location) {
  await IOUtils.makeDirectory(location, {
    ignoreExisting: true,
    createAncestors: true,
  });
  const exists = await dirExists(location);
  ok(exists, `Created temporary directory at: ${location}`);
}

async function fileHasBinaryContents(location, expectedContents) {
  if (!(expectedContents instanceof Uint8Array)) {
    throw new TypeError("expectedContents must be a byte array");
  }
  info(`Opening ${location} for reading`);
  const bytes = await IOUtils.read(location);
  return bytes.equals(expectedContents);
}

async function fileHasTextContents(location, expectedContents) {
  if (typeof expectedContents !== "string") {
    throw new TypeError("expectedContents must be a string");
  }
  info(`Opening ${location} for reading`);
  const bytes = await IOUtils.read(location);
  const contents = new TextDecoder().decode(bytes);
  return contents === expectedContents;
}

async function fileExists(file) {
  try {
    let { type } = await IOUtils.stat(file);
    return type === "regular";
  } catch (ex) {
    return false;
  }
}

async function dirExists(dir) {
  try {
    let { type } = await IOUtils.stat(dir);
    return type === "directory";
  } catch (ex) {
    return false;
  }
}

async function cleanup(...files) {
  for (const file of files) {
    await IOUtils.remove(file, {
      ignoreAbsent: true,
      recursive: true,
    });
    const exists = await IOUtils.exists(file);
    ok(!exists, `Removed temporary file: ${file}`);
  }
}

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}