UNPKG

2.67 kBPlain TextView Raw
1import * as fs from "fs";
2
3const areBuffersEqual = (bufA: Buffer, bufB: Buffer) => {
4 const len = bufA.length;
5 if (len !== bufB.length) {
6 return false;
7 }
8 for (let i = 0; i < len; i += 1) {
9 if (bufA.readUInt8(i) !== bufB.readUInt8(i)) {
10 return false;
11 }
12 }
13 return true;
14};
15
16export default (path: string) => {
17 return {
18 shouldNotExist: () => {
19 let message;
20 try {
21 fs.statSync(path);
22 message = `Path ${path} should NOT exist`;
23 } catch (err) {
24 if (err.code !== "ENOENT") {
25 throw err;
26 }
27 }
28 if (message) {
29 throw new Error(message);
30 }
31 },
32
33 shouldBeDirectory: () => {
34 let message;
35 let stat;
36 try {
37 stat = fs.statSync(path);
38 if (!stat.isDirectory()) {
39 message = `Path ${path} should be a directory`;
40 }
41 } catch (err) {
42 if (err.code === "ENOENT") {
43 message = `Path ${path} should exist`;
44 } else {
45 throw err;
46 }
47 }
48 if (message) {
49 throw new Error(message);
50 }
51 },
52
53 shouldBeFileWithContent: (expectedContent: any) => {
54 let message;
55 let content;
56
57 const generateMessage = (expected: string, found: string) => {
58 message = `File ${path} should have content "${expected}" but found "${found}"`;
59 };
60
61 try {
62 if (Buffer.isBuffer(expectedContent)) {
63 content = fs.readFileSync(path);
64 if (!areBuffersEqual(expectedContent, content)) {
65 generateMessage(
66 expectedContent.toString("hex"),
67 content.toString("hex")
68 );
69 }
70 } else {
71 content = fs.readFileSync(path, "utf8");
72 if (content !== expectedContent) {
73 generateMessage(expectedContent, content);
74 }
75 }
76 } catch (err) {
77 if (err.code === "ENOENT") {
78 message = `File ${path} should exist`;
79 } else {
80 throw err;
81 }
82 }
83 if (message) {
84 throw new Error(message);
85 }
86 },
87
88 shouldHaveMode: (expectedMode: any) => {
89 let mode;
90 let message;
91
92 try {
93 mode = fs.statSync(path).mode.toString(8);
94 mode = mode.substring(mode.length - 3);
95 if (mode !== expectedMode) {
96 message = `Path ${path} should have mode "${expectedMode}" but have instead "${mode}"`;
97 }
98 } catch (err) {
99 if (err.code === "ENOENT") {
100 message = `Path ${path} should exist`;
101 } else {
102 throw err;
103 }
104 }
105 if (message) {
106 throw new Error(message);
107 }
108 }
109 };
110};