2021-04-02 23:11:27 +00:00
|
|
|
/**
|
|
|
|
* Functions useful for testing.
|
|
|
|
*
|
|
|
|
* It re-exports chai.assert, so that you can import it from here with confidence
|
|
|
|
* that it has been instrumented to support things like assert.isRejected
|
|
|
|
* (via chai.use(chaiAsPromised).
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
|
|
/* global before, after */
|
|
|
|
|
2021-07-14 11:17:12 +00:00
|
|
|
import * as _ from 'underscore';
|
|
|
|
import * as chai from 'chai';
|
|
|
|
import { assert } from 'chai';
|
|
|
|
import * as chaiAsPromised from 'chai-as-promised';
|
|
|
|
import * as path from 'path';
|
|
|
|
import * as fse from 'fs-extra';
|
2021-09-20 18:42:53 +00:00
|
|
|
import clone = require('lodash/clone');
|
2021-07-14 11:17:12 +00:00
|
|
|
import * as tmp from 'tmp-promise';
|
|
|
|
import * as winston from 'winston';
|
|
|
|
import { serialize } from 'winston/lib/winston/common';
|
|
|
|
|
|
|
|
import * as docUtils from 'app/server/lib/docUtils';
|
|
|
|
import * as log from 'app/server/lib/log';
|
|
|
|
import { getAppRoot } from 'app/server/lib/places';
|
2021-04-02 23:11:27 +00:00
|
|
|
|
|
|
|
chai.use(chaiAsPromised);
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Creates a temporary file with the given contents.
|
|
|
|
* @param {String} content. Data to store in the file.
|
|
|
|
* @param {[Boolean]} optKeep. Optionally pass in true to keep the file from being deleted, which
|
|
|
|
* is useful to see the content while debugging a test.
|
|
|
|
* @returns {Promise} A promise for the path of the new file.
|
|
|
|
*/
|
2021-07-14 11:17:12 +00:00
|
|
|
export async function writeTmpFile(content: any, optKeep?: boolean) {
|
2021-04-02 23:11:27 +00:00
|
|
|
// discardDescriptor ensures tmp module closes it. It can lead to horrible bugs to close this
|
|
|
|
// descriptor yourself, since tmp also closes it on exit, and if it's a different descriptor by
|
|
|
|
// that time, it can lead to a crash. See https://github.com/raszi/node-tmp/issues/168
|
2021-07-14 11:17:12 +00:00
|
|
|
const obj = await tmp.file({keep: optKeep, discardDescriptor: true});
|
|
|
|
await fse.writeFile(obj.path, content);
|
|
|
|
return obj.path;
|
2021-04-02 23:11:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Creates a temporary file with `numLines` of generated data, each line about 30 bytes long.
|
|
|
|
* This is useful for testing operations with large files.
|
|
|
|
* @param {Number} numLines. How many lines to store in the file.
|
|
|
|
* @param {[Boolean]} optKeep. Optionally pass in true to keep the file from being deleted, which
|
|
|
|
* is useful to see the content while debugging a test.
|
|
|
|
* @returns {Promise} A promise for the path of the new file.
|
|
|
|
*/
|
2021-07-14 11:17:12 +00:00
|
|
|
export async function generateTmpFile(numLines: number, optKeep?: boolean) {
|
2021-04-02 23:11:27 +00:00
|
|
|
// Generate a bigger data file.
|
2021-07-14 11:17:12 +00:00
|
|
|
const data = [];
|
|
|
|
for (let i = 0; i < numLines; i++) {
|
2021-04-02 23:11:27 +00:00
|
|
|
data.push(i + " abcdefghijklmnopqrstuvwxyz\n");
|
|
|
|
}
|
|
|
|
return writeTmpFile(data.join(""), optKeep);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Helper class to capture log output when we want to test it.
|
|
|
|
*/
|
2021-07-14 11:17:12 +00:00
|
|
|
class CaptureTransport extends winston.Transport {
|
|
|
|
private _captureFunc: (level: string, msg: string, meta: any) => void;
|
|
|
|
|
|
|
|
public constructor(options: any) {
|
|
|
|
super();
|
|
|
|
this._captureFunc = options.captureFunc;
|
|
|
|
if (options.name) {
|
|
|
|
this.name = options.name;
|
|
|
|
}
|
2021-04-02 23:11:27 +00:00
|
|
|
}
|
2021-07-14 11:17:12 +00:00
|
|
|
|
|
|
|
public log(level: string, msg: string, meta: any, callback: () => void) {
|
|
|
|
this._captureFunc(level, msg, meta);
|
|
|
|
}
|
|
|
|
}
|
2021-04-02 23:11:27 +00:00
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* When used inside a test suite (inside describe()), changes the log level to the given one
|
|
|
|
* before tests, restoring it back afterwards. In addition, if optCaptureFunc is given, it will be
|
|
|
|
* called as optCaptureFunc(level, msg) with every message logged (including those suppressed).
|
|
|
|
*
|
|
|
|
* This should be called at the suite level (i.e. inside describe()).
|
|
|
|
*/
|
2021-07-14 11:17:12 +00:00
|
|
|
export function setTmpLogLevel(level: string, optCaptureFunc?: (level: string, msg: string, meta: any) => void) {
|
2021-04-02 23:11:27 +00:00
|
|
|
// If verbose is set in the environment, sabotage all reductions in logging level.
|
|
|
|
// Handier than modifying the setTmpLogLevel line and then remembering to set it back
|
|
|
|
// before committing.
|
|
|
|
if (process.env.VERBOSE === '1') {
|
|
|
|
level = 'debug';
|
|
|
|
}
|
|
|
|
|
2021-07-14 11:17:12 +00:00
|
|
|
let prevLogLevel: string|undefined = undefined;
|
|
|
|
const name = _.uniqueId('CaptureLog');
|
2021-04-02 23:11:27 +00:00
|
|
|
|
|
|
|
before(function() {
|
2021-07-14 11:17:12 +00:00
|
|
|
if (this.runnable().parent?.root) {
|
2021-04-02 23:11:27 +00:00
|
|
|
throw new Error("setTmpLogLevel should be called at suite level, not at root level");
|
|
|
|
}
|
|
|
|
|
|
|
|
prevLogLevel = log.transports.file.level;
|
|
|
|
log.transports.file.level = level;
|
|
|
|
if (optCaptureFunc) {
|
2021-07-14 11:17:12 +00:00
|
|
|
log.add(CaptureTransport as any, { captureFunc: optCaptureFunc, name }); // typing is off.
|
2021-04-02 23:11:27 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
after(function() {
|
|
|
|
if (optCaptureFunc) {
|
2021-07-14 11:17:12 +00:00
|
|
|
log.remove(name);
|
2021-04-02 23:11:27 +00:00
|
|
|
}
|
|
|
|
log.transports.file.level = prevLogLevel;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Captures debug log messages produced by callback. Suppresses ALL messages from console, and
|
|
|
|
* captures those at minLevel and higher. Returns a promise for the array of "level: message"
|
|
|
|
* strings. These may be tested using testUtils.assertMatchArray(). Callback may return a promise.
|
|
|
|
*/
|
2021-07-14 11:17:12 +00:00
|
|
|
export async function captureLog(minLevel: string, callback: any) {
|
|
|
|
const messages: string[] = [];
|
2021-04-02 23:11:27 +00:00
|
|
|
const prevLogLevel = log.transports.file.level;
|
|
|
|
const name = _.uniqueId('CaptureLog');
|
|
|
|
|
2021-07-14 11:17:12 +00:00
|
|
|
function capture(level: string, msg: string, meta: any) {
|
|
|
|
if ((log as any).levels[level] <= (log as any).levels[minLevel]) { // winston types are off?
|
2021-04-02 23:11:27 +00:00
|
|
|
messages.push(level + ': ' + msg + (meta ? ' ' + serialize(meta) : ''));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-14 11:17:12 +00:00
|
|
|
log.transports.file.level = -1 as any; // Suppress all log output.
|
|
|
|
log.add(CaptureTransport as any, { captureFunc: capture, name }); // types are off.
|
|
|
|
try {
|
|
|
|
await callback();
|
|
|
|
} finally {
|
2021-04-02 23:11:27 +00:00
|
|
|
log.remove(name);
|
|
|
|
log.transports.file.level = prevLogLevel;
|
2021-07-14 11:17:12 +00:00
|
|
|
}
|
|
|
|
return messages;
|
2021-04-02 23:11:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Asserts that each string of stringArray matches the corresponding regex in regexArray.
|
|
|
|
*/
|
2021-07-14 11:17:12 +00:00
|
|
|
export function assertMatchArray(stringArray: string[], regexArray: RegExp[]) {
|
2021-04-02 23:11:27 +00:00
|
|
|
for (let i = 0; i < Math.min(stringArray.length, regexArray.length); i++) {
|
|
|
|
assert.match(stringArray[i], regexArray[i]);
|
|
|
|
}
|
|
|
|
assert.isAtMost(stringArray.length, regexArray.length,
|
|
|
|
`Unexpected strings seen: ${stringArray.slice(regexArray.length).join('\n')}`);
|
|
|
|
assert.isAtLeast(stringArray.length, regexArray.length,
|
|
|
|
'Not all expected strings were seen');
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Helper method for handling expected Promise rejections.
|
|
|
|
*
|
|
|
|
* @param {Promise} promise = the promise we are checking for errors
|
|
|
|
* @param {String} errCode - Error code to check against `err.code` from the caller.
|
|
|
|
* @param {RegExp} errRegexp - Regular expression to check against `err.message` from the caller.
|
|
|
|
*/
|
2022-03-24 17:11:26 +00:00
|
|
|
export function expectRejection(promise: Promise<any>, errCode: number|string, errRegexp: RegExp) {
|
2021-04-02 23:11:27 +00:00
|
|
|
return promise
|
|
|
|
.then(function() {
|
|
|
|
assert(false, "Expected promise to return an error: " + errCode);
|
|
|
|
})
|
|
|
|
.catch(function(err) {
|
|
|
|
if (err.cause) {
|
|
|
|
err = err.cause;
|
|
|
|
}
|
|
|
|
assert.strictEqual(err.code, errCode);
|
|
|
|
|
|
|
|
if (errRegexp !== undefined) {
|
|
|
|
assert(errRegexp.test(err.message), "Description doesn't match regexp: " +
|
|
|
|
errRegexp + ' !~ ' + err.message);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Reads in doc actions from a test script. Used in DocStorage_Script.js and DocData.js.
|
|
|
|
* This parser inserts line numbers into the step names of the test case bodies. Users of the test
|
|
|
|
* script should iterate through the steps using processTestScriptSteps, which will strip out the
|
|
|
|
* line numbers, and include them into any failure messages.
|
|
|
|
*
|
|
|
|
* @param {String} file - Input test script
|
|
|
|
* @returns {Promise:Object} - Parsed test script object
|
|
|
|
*/
|
2021-07-14 11:17:12 +00:00
|
|
|
export async function readTestScript(file: string) {
|
|
|
|
const fullText = await fse.readFile(file, {encoding: 'utf8'});
|
|
|
|
const allLines: string[] = [];
|
|
|
|
fullText.split("\n").forEach(function(line, i) {
|
|
|
|
if (line.match(/^\s*\/\//)) {
|
|
|
|
allLines.push('');
|
|
|
|
} else {
|
|
|
|
line = line.replace(/"(APPLY|CHECK_OUTPUT|LOAD_SAMPLE)"\s*,/, '"$1@' + (i + 1) + '",');
|
|
|
|
allLines.push(line);
|
|
|
|
}
|
2021-04-02 23:11:27 +00:00
|
|
|
});
|
2021-07-14 11:17:12 +00:00
|
|
|
return JSON.parse(allLines.join("\n"));
|
|
|
|
}
|
2021-04-02 23:11:27 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* For a test case step, such as ["APPLY", {actions}], checks if the step name has an encoded line
|
|
|
|
* number, strips it, runs the callback with the step data, and inserts the line number into any
|
|
|
|
* errors thrown by the callback.
|
|
|
|
*/
|
2021-07-14 11:17:12 +00:00
|
|
|
export async function processTestScriptSteps<T>(body: Promise<[string, T]>[],
|
|
|
|
stepCallback: (step: [string, T]) => Promise<void>) {
|
|
|
|
for (const promise of body) {
|
|
|
|
const step = await promise;
|
|
|
|
const stepName = step[0];
|
|
|
|
const lineNoPos = stepName.indexOf('@');
|
|
|
|
const lineNum = (lineNoPos === -1) ? null : stepName.slice(lineNoPos + 1);
|
2021-04-02 23:11:27 +00:00
|
|
|
step[0] = (lineNoPos === -1) ? stepName : stepName.slice(0, lineNoPos);
|
2021-07-14 11:17:12 +00:00
|
|
|
try {
|
|
|
|
await stepCallback(step);
|
|
|
|
} catch (e) {
|
2021-04-02 23:11:27 +00:00
|
|
|
e.message = "LINE " + lineNum + ": " + e.message;
|
|
|
|
throw e;
|
2021-07-14 11:17:12 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-04-02 23:11:27 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Helper that substitutes every instance of `from` value to `to` value. Iterates down the object.
|
|
|
|
*/
|
2021-07-14 11:17:12 +00:00
|
|
|
export function deepSubstitute(obj: any, from: any, to: any): any {
|
2021-04-02 23:11:27 +00:00
|
|
|
from = _.isArray(from) ? from : [from];
|
|
|
|
if (_.isArray(obj)) {
|
|
|
|
return obj.map(el => deepSubstitute(el, from, to));
|
|
|
|
} else if (obj && typeof obj === 'object' && !_.isFunction(obj)) {
|
|
|
|
return _.mapObject(obj, el => deepSubstitute(el, from, to));
|
|
|
|
} else {
|
|
|
|
return from.indexOf(obj) !== -1 ? to : obj;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-14 11:17:12 +00:00
|
|
|
export const fixturesRoot = path.resolve(getAppRoot(), 'test', 'fixtures');
|
2021-04-02 23:11:27 +00:00
|
|
|
|
2021-07-14 11:17:12 +00:00
|
|
|
export const appRoot = getAppRoot();
|
2021-04-02 23:11:27 +00:00
|
|
|
|
|
|
|
/**
|
2021-06-15 16:52:03 +00:00
|
|
|
* Copy the given filename from the fixtures directory (test/fixtures)
|
|
|
|
* to the storage manager root.
|
2021-04-02 23:11:27 +00:00
|
|
|
* @param {string} alias - Optional alias that lets you rename the document on disk.
|
|
|
|
*/
|
2021-07-14 11:17:12 +00:00
|
|
|
export async function useFixtureDoc(fileName: string, storageManager: any, alias: string = fileName) {
|
|
|
|
const srcPath = path.resolve(fixturesRoot, "docs", fileName);
|
|
|
|
const docName = await useLocalDoc(srcPath, storageManager, alias);
|
|
|
|
log.info("Using fixture %s as %s", fileName, docName + ".grist");
|
|
|
|
return docName;
|
2021-06-15 16:52:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Copy the given filename from srcPath to the storage manager root.
|
|
|
|
* @param {string} alias - Optional alias that lets you rename the document on disk.
|
|
|
|
*/
|
2021-07-14 11:17:12 +00:00
|
|
|
export async function useLocalDoc(srcPath: string, storageManager: any, alias: string = srcPath) {
|
|
|
|
let docName = path.basename(alias || srcPath, ".grist");
|
|
|
|
docName = await docUtils.createNumbered(
|
|
|
|
docName, "-",
|
|
|
|
(name: string) => docUtils.createExclusive(storageManager.getPath(name)));
|
|
|
|
await docUtils.copyFile(srcPath, storageManager.getPath(docName));
|
|
|
|
await storageManager.markAsChanged(docName);
|
|
|
|
return docName;
|
|
|
|
}
|
|
|
|
|
|
|
|
// an helper to copy a fixtures document to destPath
|
|
|
|
export async function copyFixtureDoc(docName: string, destPath: string) {
|
|
|
|
const srcPath = path.resolve(fixturesRoot, 'docs', docName);
|
|
|
|
await docUtils.copyFile(srcPath, destPath);
|
|
|
|
}
|
|
|
|
|
|
|
|
// a helper to read a fixtures document into memory
|
|
|
|
export async function readFixtureDoc(docName: string) {
|
|
|
|
const srcPath = path.resolve(fixturesRoot, 'docs', docName);
|
|
|
|
return fse.readFile(srcPath);
|
2021-04-02 23:11:27 +00:00
|
|
|
}
|
|
|
|
|
2021-09-20 18:42:53 +00:00
|
|
|
// a class to store a snapshot of environment variables, can be reverted to by
|
|
|
|
// calling .restore()
|
|
|
|
export class EnvironmentSnapshot {
|
|
|
|
private _oldEnv: NodeJS.ProcessEnv;
|
|
|
|
public constructor() {
|
|
|
|
this._oldEnv = clone(process.env);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Reset environment variables.
|
|
|
|
public restore() {
|
|
|
|
Object.assign(process.env, this._oldEnv);
|
|
|
|
for (const key of Object.keys(process.env)) {
|
|
|
|
if (this._oldEnv[key] === undefined) {
|
|
|
|
delete process.env[key];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-24 17:11:26 +00:00
|
|
|
export async function getBuildFile(relativePath: string): Promise<string> {
|
|
|
|
if (await fse.pathExists(path.join('_build', relativePath))) {
|
|
|
|
return path.join('_build', relativePath);
|
|
|
|
}
|
|
|
|
return path.join('_build', 'core', relativePath);
|
|
|
|
}
|
|
|
|
|
2021-07-14 11:17:12 +00:00
|
|
|
export { assert };
|