forked from twilio-labs/function-templates
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest-helper.js
103 lines (89 loc) · 2.06 KB
/
test-helper.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
const fs = require('fs');
const path = require('path');
const Twilio = require('twilio');
class MockRuntime {
constructor(context) {
this.context = context;
this._assets = {};
this._functions = {};
}
_addAsset(key, filePath) {
const resolved = path.resolve(
path.dirname(module.parent.filename),
filePath
);
this._assets[key] = {
path: resolved,
open: () => fs.readFileSync(resolved),
};
}
_addFunction(key, filePath) {
this._functions[key] = {
path: path.resolve(filePath),
};
}
getAssets() {
if (Object.keys(this._assets).length === 0) {
throw new Error('You must explicitly add assets using MockRuntime');
}
return this._assets;
}
getFunctions() {
if (Object.keys(this._functions).length === 0) {
throw new Error('You must explicitly add functions using MockRuntime');
}
return this._functions;
}
}
class Response {
constructor() {
this._body = {};
this._headers = {};
this._statusCode = 200;
}
setBody(body) {
this._body = body;
}
setStatusCode(code) {
this._statusCode = code;
}
appendHeader(key, value) {
this._headers[key] = value;
}
}
const setup = (context = {}, runtime = new MockRuntime()) => {
global.Twilio = Twilio;
global.Twilio.Response = Response;
if (context.ACCOUNT_SID && context.AUTH_TOKEN) {
global.twilioClient = new Twilio(context.ACCOUNT_SID, context.AUTH_TOKEN);
}
global.Runtime = runtime;
};
const teardown = () => {
delete global.Twilio;
if (global.twilioClient) delete global.twilioClient;
if (global.Runtime) delete global.Runtime;
};
const backupEnv = () => {
return { ...process.env };
};
const restoreEnv = (backupEnv) => {
if (backupEnv === undefined) {
return;
}
for (const key of Object.keys(process.env)) {
if (backupEnv[key] === undefined) {
delete process.env[key];
}
}
for (const key of Object.keys(backupEnv)) {
process.env[key] = backupEnv[key];
}
};
module.exports = {
setup,
teardown,
MockRuntime,
backupEnv,
restoreEnv,
};