forked from babel/babel
/
cache.js
125 lines (97 loc) 路 2.9 KB
/
cache.js
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
import fs from "fs";
import path from "path";
const testCacheFilename = path.join(__dirname, ".babel");
const oldBabelDisableCacheValue = process.env.BABEL_DISABLE_CACHE;
process.env.BABEL_CACHE_PATH = testCacheFilename;
delete process.env.BABEL_DISABLE_CACHE;
function writeCache(data, mode = 0o666) {
if (typeof data === "object") {
data = JSON.stringify(data);
}
fs.writeFileSync(testCacheFilename, data, { mode });
}
function cleanCache() {
try {
fs.unlinkSync(testCacheFilename);
} catch (e) {
// It is convenient to always try to clear
}
}
function resetCache() {
process.env.BABEL_CACHE_PATH = null;
process.env.BABEL_DISABLE_CACHE = oldBabelDisableCacheValue;
}
describe("@babel/register - caching", () => {
describe("cache", () => {
let load, get, save;
let stderr = "";
let consoleWarnSpy;
beforeEach(() => {
// Since lib/cache is a singleton we need to fully reload it
jest.resetModules();
const cache = require("../lib/cache");
load = cache.load;
get = cache.get;
save = cache.save;
consoleWarnSpy = jest
.spyOn(console, "warn")
.mockImplementation(err => (stderr += err));
});
afterEach(() => {
cleanCache();
consoleWarnSpy.mockRestore();
});
afterAll(resetCache);
it("should load and get cached data", () => {
writeCache({ foo: "bar" });
load();
expect(get()).toEqual({ foo: "bar" });
});
it("should load and get an object with no cached data", () => {
load();
expect(get()).toEqual({});
});
it("should load and get an object with invalid cached data", () => {
writeCache("foobar");
load();
expect(get()).toEqual({});
});
it("should create the cache on save", () => {
save();
expect(fs.existsSync(testCacheFilename)).toBe(true);
expect(get()).toEqual({});
});
it("should create the cache after load", cb => {
load();
process.nextTick(() => {
expect(fs.existsSync(testCacheFilename)).toBe(true);
expect(get()).toEqual({});
cb();
});
});
// Only write mode is effective on Windows
if (process.platform !== "win32") {
it("should be disabled when CACHE_PATH is not allowed to read", () => {
writeCache({ foo: "bar" }, 0o266);
load();
expect(get()).toEqual({});
expect(consoleWarnSpy.mock.calls[0][0]).toContain(
"Babel could not read cache file",
);
});
}
it("should be disabled when CACHE_PATH is not allowed to write", cb => {
writeCache({ foo: "bar" }, 0o466);
load();
expect(get()).toEqual({ foo: "bar" });
process.nextTick(() => {
load();
expect(get()).toEqual({});
expect(consoleWarnSpy.mock.calls[0][0]).toContain(
"Babel could not write cache to file",
);
cb();
});
});
});
});