-
Notifications
You must be signed in to change notification settings - Fork 50
/
utils.js
100 lines (86 loc) · 2.6 KB
/
utils.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
'use strict';
const path = require('path');
const fs = require('fs');
const defaultTestsRootFolder = 'test'; // default test folder used for tests
function getTestsFolder(testsRootFolder) {
return testsRootFolder || defaultTestsRootFolder;
}
function getTestFilePath(funcName, testsRootFolder) {
return path.join(getTestsFolder(testsRootFolder), `${funcName.replace(/.*\//g, '')}.js`);
}
function traverseTestFolder(testFolder, prefix) {
const funcFiles = [];
const dirContents = fs.readdirSync(testFolder);
dirContents.forEach((val) => {
const stats = fs.statSync(path.join(testFolder, val));
if (stats.isFile()) {
funcFiles.push(prefix ? path.join(prefix, val) : val);
} else {
const subContents = traverseTestFolder(
path.join(testFolder, val), prefix ? path.join(prefix, val) : val,
);
subContents.forEach((subval) => {
funcFiles.push(subval);
});
}
});
return funcFiles;
}
// getTestFiles. Returns all test files, attaches to functions
function getTestFiles(funcs, testFolder, funcList) {
const funcFiles = traverseTestFolder(testFolder);
const resFuncs = {};
if (funcFiles.length > 0) {
funcFiles.forEach((val) => {
if (['.js', '.ts'].includes(path.extname(val))) {
const base = path.basename(val).replace(/(\.test)?.[tj]s$/, '');
// Create test for non-functions only if no funcList
if (funcs[base] || funcList.length === 0) {
resFuncs[base] = funcs[base] || {};
resFuncs[base].mochaPlugin = {
testPath: path.join(getTestsFolder(testFolder), val),
};
}
}
});
}
return resFuncs;
}
// Create the test folder
function createTestFolder(testsRootFolder) {
const testsFolder = getTestsFolder(testsRootFolder);
const exists = fs.existsSync(testsFolder);
if (exists) {
return testsFolder;
}
fs.mkdirSync(testsFolder);
return testsFolder;
}
function getTemplateFromFile(templateFilenamePath) {
return fs.readFileSync(templateFilenamePath, 'utf-8');
}
function funcNameFromPath(filePath) {
const data = path.parse(filePath);
return data.name;
}
function setEnv(serverless, funcName) {
const serviceVars = serverless.service.provider.environment || {};
let functionVars = {};
if (funcName && serverless.service.functions[funcName]) {
functionVars = serverless.service.functions[funcName].environment || {};
}
return Object.assign(
process.env,
serviceVars,
functionVars,
);
}
module.exports = {
getTestsFolder,
getTestFilePath,
getTestFiles,
createTestFolder,
getTemplateFromFile,
funcNameFromPath,
setEnv,
};