CyberChef/tests/lib/TestRegister.mjs

126 lines
3.6 KiB
JavaScript
Raw Normal View History

2017-02-25 00:50:17 +01:00
/**
* TestRegister.js
*
* This is so individual files can register their tests in one place, and
* ensure that they will get run by the frontend.
*
* @author tlwr [toby@toby.codes]
* @author d98762625 [d98762625@gmail.com]
* @copyright Crown Copyright 2018
2017-02-25 00:50:17 +01:00
* @license Apache-2.0
*/
2018-12-28 22:49:40 +01:00
import Chef from "../../src/core/Chef";
/**
* Object to store and run the list of tests.
*
* @class
* @constructor
*/
class TestRegister {
2017-02-25 00:50:17 +01:00
/**
* initialise with no tests
2017-02-25 00:50:17 +01:00
*/
constructor() {
2017-02-25 00:50:17 +01:00
this.tests = [];
this.apiTests = [];
2017-02-25 00:50:17 +01:00
}
/**
* Add a list of tests to the register.
*
* @param {Object[]} tests
*/
addTests(tests) {
2017-02-25 00:50:17 +01:00
this.tests = this.tests.concat(tests);
}
2017-02-25 00:50:17 +01:00
/**
* Add a list of api tests to the register
* @param {Object[]} tests
*/
addApiTests(tests) {
this.apiTests = this.apiTests.concat(tests);
}
2017-02-25 00:50:17 +01:00
/**
* Runs all the tests in the register.
*/
runTests () {
2017-02-25 00:50:17 +01:00
return Promise.all(
this.tests.map(function(test, i) {
2017-05-03 00:06:28 +02:00
const chef = new Chef();
2017-02-25 00:50:17 +01:00
return chef.bake(
2017-02-25 00:50:17 +01:00
test.input,
test.recipeConfig,
{},
0,
false
2017-07-24 15:49:16 +02:00
).then(function(result) {
2017-05-03 00:06:28 +02:00
const ret = {
2017-02-25 00:50:17 +01:00
test: test,
status: null,
output: null,
};
if (result.error) {
if (test.expectedError) {
ret.status = "passing";
} else {
ret.status = "erroring";
ret.output = result.error.displayStr;
}
} else {
if (test.expectedError) {
ret.status = "failing";
ret.output = "Expected an error but did not receive one.";
} else if (result.result === test.expectedOutput) {
ret.status = "passing";
2019-07-05 13:22:52 +02:00
} else if ("expectedMatch" in test && test.expectedMatch.test(result.result)) {
ret.status = "passing";
2017-02-25 00:50:17 +01:00
} else {
ret.status = "failing";
const expected = test.expectedOutput ? test.expectedOutput :
test.expectedMatch ? test.expectedMatch.toString() : "unknown";
2017-02-25 00:50:17 +01:00
ret.output = [
"Expected",
"\t" + expected.replace(/\n/g, "\n\t"),
2017-02-25 00:50:17 +01:00
"Received",
"\t" + result.result.replace(/\n/g, "\n\t"),
].join("\n");
}
}
return ret;
});
})
);
}
/**
* Run all api related tests and wrap results in report format
*/
runApiTests() {
return Promise.all(this.apiTests.map(async function(test, i) {
const result = {
test: test,
status: null,
output: null,
};
try {
await test.run();
result.status = "passing";
} catch (e) {
result.status = "erroring";
result.output = e.message;
}
return result;
}));
}
}
// Export an instance to make a singleton
export default new TestRegister();