forked from adaptlearning/adapt_framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.js
250 lines (211 loc) · 6.96 KB
/
test.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
const os = require('os');
const { spawn, exec } = require('child_process');
const jest = require('jest');
const config = require('./jest.config');
const globs = require('globs');
const path = require('path');
async function doFilesExist(patterns) {
return await new Promise(resolve => globs(patterns, (err, matches) => resolve(Boolean(!err && matches?.length))));
}
async function asyncSpawn(command, ...args) {
return await new Promise((resolve, reject) => {
spawn(command, args, { stdio: [0, 1, 2] })
.on('error', reject)
.on('close', code => {
if (!code) return resolve();
reject(new Error(`Command failed: "${command} ${args.join(' ')}"`));
});
});
}
async function backgroundSpawn(command, ...args) {
return await new Promise((resolve, reject) => {
let hasErrored = false;
const process = spawn(command, args, { stdio: [0, 1, 2] })
.on('error', err => {
hasErrored = true;
reject(err);
})
.on('close', code => {
if (!code) return;
hasErrored = true;
reject(new Error(`Command failed: "${command} ${args.join(' ')}"`));
});
setTimeout(() => {
if (hasErrored) return;
resolve(process);
}, 1000);
});
}
async function waitForExec(command, ...args) {
return await new Promise(resolve => exec([command, ...args].join(' '), { stdio: [0, 1, 2] }, resolve));
}
async function hasInstalled() {
return await doFilesExist([
'src/components/*',
'src/extensions/*',
'src/menu/*',
'src/theme/*'
]);
};
async function hasBuilt() {
return await doFilesExist([
path.join(argumentValues.outputdir, 'index.html')
]);
};
async function adaptInstall() {
return asyncSpawn(`adapt${os.platform() === 'win32' ? '.cmd' : ''}`, 'install');
};
async function gruntDiff() {
return asyncSpawn(...[
'node',
'./node_modules/grunt/bin/grunt',
'diff',
Boolean(process.env.npm_config_outputdir) && `--outputdir=${argumentValues.outputdir}`
].filter(Boolean));
};
async function gruntServer() {
return backgroundSpawn('node', './node_modules/grunt/bin/grunt', 'server-silent', 'run', `--outputdir=${argumentValues.outputdir}`);
};
async function waitForGruntServer() {
return waitForExec('node', './node_modules/wait-on/bin/wait-on', 'http://127.0.0.1:9001');
};
async function cypressRun() {
if (argumentValues.testfiles) {
return asyncSpawn('node', './node_modules/cypress/bin/cypress', 'run', '--spec', `${argumentValues.testfiles}`, '--config', `{"fixturesFolder": "${argumentValues.outputdir}"}`);
}
return asyncSpawn('node', './node_modules/cypress/bin/cypress', 'run', '--config', `{"fixturesFolder": "${argumentValues.outputdir}"}`);
};
async function jestRun() {
config.testEnvironmentOptions.outputDir = argumentValues.outputdir;
// Limit the tests if a certain set are passed in
if (argumentValues.testfiles) {
config.testMatch = argumentValues.testfiles.split(',');
}
return jest.runCLI(config, [process.cwd().replace(/\\/g, '/')]);
};
async function jestClear() {
return asyncSpawn('node', './node_modules/jest/bin/jest', '--clearCache');
};
const acceptedArgs = [
'outputdir',
'skipinstall',
'testfiles'
];
const argumentValues = {
outputdir: (process.env.npm_config_outputdir || './build/'),
skipinstall: false,
testfiles: null
};
const commands = {
help: {
name: 'help',
description: 'Display this help screen',
async start() {
const helpText = `
Usage:
To run prepare with the unit and then e2e tests:
$ npm test
To run prepare with the unit and then e2e tests without overwriting the ./src/ plugins:
$ npm test --skipinstall
To run prepare with specif unit and/or e2e tests:
$ npm test --testfiles=**/globForTestsToRun/**
To run any of the available commands:
$ npm test <command>
To run prepare, e2e or unit with a defined output directory:
$ npm test <command> --outputdir=./build/
where <command> is one of:
${Object.values(commands).map(({ name, description }) => ` ${name.padEnd(21, ' ')}${description}`).join('\n')}
`;
console.log(helpText);
}
},
prepare: {
name: 'prepare',
description: 'Install and build Adapt ready for testing (runs automatically when requied)',
async start() {
if ((argumentValues.skipinstall !== 'true') && !await hasInstalled()) {
console.log('Installing latest adapt plugins');
await adaptInstall();
}
if (!await hasBuilt()) {
console.log(`Performing course build to '${argumentValues.outputdir}'`);
await gruntDiff();
}
}
},
e2e: {
name: 'e2e',
description: 'Run prepare and e2e testing',
async start() {
const gruntServerRun = await gruntServer();
await waitForGruntServer();
try {
const cypressCode = await cypressRun();
if (cypressCode > 0) {
console.log(`Cypress failed with code '${cypressCode}'`);
process.exit(1);
}
} catch (cypressErr) {
console.log('Cypress tests failure');
console.log(cypressErr);
}
gruntServerRun.kill();
}
},
unit: {
name: 'unit',
description: 'Run prepare and unit testing',
async start() {
return await jestRun();
}
},
clear: {
name: 'clear',
description: 'Clear testing cache',
async start() {
return await jestClear();
}
}
};
const runTest = async () => {
const parameters = process.argv.slice(2);
const hasParameters = Boolean(parameters.length);
let [ passedArgs = '' ] = parameters;
const [ commandName ] = passedArgs.split(' ');
const command = commands[commandName];
const isCommandNotFound = !command;
// Read the input for passed arguments that arent command names
passedArgs = passedArgs.trim().replaceAll('--', '').toLowerCase().split(' ').filter(name => isCommandNotFound || name !== commandName);
// Update argumentValues array for later use while checking if the command is valid
const paramsRecognised = passedArgs.every(passedArg => {
const passedArgParts = passedArg.trim().split('=');
argumentValues[passedArgParts[0]] = passedArgParts[1];
return acceptedArgs.includes(passedArgParts[0]);
});
try {
if (isCommandNotFound && hasParameters && !paramsRecognised) {
const e = new Error(`Unknown command/argument "${parameters[0]}", please check the documentation. $ npm test help`);
console.error(e);
return;
}
const isCommandHelp = (commandName === 'help');
const isCommandPrepare = (commandName === 'prepare');
const shouldPrepare = (isCommandPrepare || !isCommandHelp);
if (shouldPrepare) {
await commands.prepare.start();
if (isCommandPrepare) return;
}
// No specific command called - run tests by default
if (isCommandNotFound) {
await commands.unit.start();
await commands.e2e.start();
process.exit(0);
}
await command.start();
process.exit(0);
} catch (err) {
console.error(err);
process.exit(1);
}
};
runTest();