Skip to content

Commit

Permalink
test: translate tests into ts, extract mocha (#3565)
Browse files Browse the repository at this point in the history
  • Loading branch information
pavelfeldman authored Aug 22, 2020
1 parent 57e8617 commit 398bd47
Show file tree
Hide file tree
Showing 11 changed files with 460 additions and 249 deletions.
126 changes: 1 addition & 125 deletions test-runner/src/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,128 +14,4 @@
* limitations under the License.
*/

const fs = require('fs');
const path = require('path');
const program = require('commander');
const { installTransform } = require('./transform');
const { Runner } = require('./runner');
const { TestCollector } = require('./testCollector');

let beforeFunction;
let afterFunction;
let matrix = {};

global['before'] = (fn => beforeFunction = fn);
global['after'] = (fn => afterFunction = fn);
global['matrix'] = (m => matrix = m);

program
.version('Version ' + /** @type {any} */ (require)('../package.json').version)
.option('--forbid-only', 'Fail if exclusive test(s) encountered', false)
.option('-g, --grep <grep>', 'Only run tests matching this string or regexp', '.*')
.option('-j, --jobs <jobs>', 'Number of concurrent jobs for --parallel; use 1 to run in serial, default: (number of CPU cores / 2)', Math.ceil(require('os').cpus().length / 2).toString())
.option('--reporter <reporter>', 'Specify reporter to use', '')
.option('--trial-run', 'Only collect the matching tests and report them as passing')
.option('--quiet', 'Suppress stdio', false)
.option('--debug', 'Run tests in-process for debugging', false)
.option('--output <outputDir>', 'Folder for output artifacts, default: test-results', path.join(process.cwd(), 'test-results'))
.option('--timeout <timeout>', 'Specify test timeout threshold (in milliseconds), default: 10000', '10000')
.option('-u, --update-snapshots', 'Use this flag to re-record every snapshot that fails during this test run')
.action(async (command) => {
// Collect files]
const testDir = path.resolve(process.cwd(), command.args[0]);
const files = collectFiles(testDir, '', command.args.slice(1));

const revertBabelRequire = installTransform();
let hasSetup = false;
try {
hasSetup = fs.statSync(path.join(testDir, 'setup.js')).isFile();
} catch (e) {
}
try {
hasSetup = hasSetup || fs.statSync(path.join(testDir, 'setup.ts')).isFile();
} catch (e) {
}

if (hasSetup)
require(path.join(testDir, 'setup'));
revertBabelRequire();

const testCollector = new TestCollector(files, matrix, {
forbidOnly: command.forbidOnly || undefined,
grep: command.grep,
timeout: command.timeout,
});
const rootSuite = testCollector.suite;
if (command.forbidOnly && testCollector.hasOnly()) {
console.error('=====================================');
console.error(' --forbid-only found a focused test.');
console.error('=====================================');
process.exit(1);
}

const total = rootSuite.total();
if (!total) {
console.error('=================');
console.error(' no tests found.');
console.error('=================');
process.exit(1);
}

// Trial run does not need many workers, use one.
const jobs = (command.trialRun || command.debug) ? 1 : command.jobs;
const runner = new Runner(rootSuite, total, {
debug: command.debug,
quiet: command.quiet,
grep: command.grep,
jobs,
outputDir: command.output,
reporter: command.reporter,
retries: command.retries,
snapshotDir: path.join(testDir, '__snapshots__'),
testDir,
timeout: command.timeout,
trialRun: command.trialRun,
updateSnapshots: command.updateSnapshots
});
try {
if (beforeFunction)
await beforeFunction();
await runner.run();
await runner.stop();
} finally {
if (afterFunction)
await afterFunction();
}
process.exit(runner.stats.failures ? 1 : 0);
});

program.parse(process.argv);

function collectFiles(testDir, dir, filters) {
const fullDir = path.join(testDir, dir);
if (fs.statSync(fullDir).isFile())
return [fullDir];
const files = [];
for (const name of fs.readdirSync(fullDir)) {
if (fs.lstatSync(path.join(fullDir, name)).isDirectory()) {
files.push(...collectFiles(testDir, path.join(dir, name), filters));
continue;
}
if (!name.endsWith('spec.ts'))
continue;
const relativeName = path.join(dir, name);
const fullName = path.join(testDir, relativeName);
if (!filters.length) {
files.push(fullName);
continue;
}
for (const filter of filters) {
if (relativeName.includes(filter)) {
files.push(fullName);
break;
}
}
}
return files;
}
require('./lib/cli');
141 changes: 141 additions & 0 deletions test-runner/src/cli.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import * as fs from 'fs';
import * as path from 'path';
import program from 'commander';
import { installTransform } from './transform';
import { Runner } from './runner';
import { TestCollector } from './testCollector';

let beforeFunction;
let afterFunction;
let matrix = {};

global['before'] = (fn => beforeFunction = fn);
global['after'] = (fn => afterFunction = fn);
global['matrix'] = (m => matrix = m);

program
.version('Version ' + /** @type {any} */ (require)('../package.json').version)
.option('--forbid-only', 'Fail if exclusive test(s) encountered', false)
.option('-g, --grep <grep>', 'Only run tests matching this string or regexp', '.*')
.option('-j, --jobs <jobs>', 'Number of concurrent jobs for --parallel; use 1 to run in serial, default: (number of CPU cores / 2)', Math.ceil(require('os').cpus().length / 2).toString())
.option('--reporter <reporter>', 'Specify reporter to use', '')
.option('--trial-run', 'Only collect the matching tests and report them as passing')
.option('--quiet', 'Suppress stdio', false)
.option('--debug', 'Run tests in-process for debugging', false)
.option('--output <outputDir>', 'Folder for output artifacts, default: test-results', path.join(process.cwd(), 'test-results'))
.option('--timeout <timeout>', 'Specify test timeout threshold (in milliseconds), default: 10000', '10000')
.option('-u, --update-snapshots', 'Use this flag to re-record every snapshot that fails during this test run')
.action(async (command) => {
// Collect files]
const testDir = path.resolve(process.cwd(), command.args[0]);
const files = collectFiles(testDir, '', command.args.slice(1));

const revertBabelRequire = installTransform();
let hasSetup = false;
try {
hasSetup = fs.statSync(path.join(testDir, 'setup.js')).isFile();
} catch (e) {
}
try {
hasSetup = hasSetup || fs.statSync(path.join(testDir, 'setup.ts')).isFile();
} catch (e) {
}

if (hasSetup)
require(path.join(testDir, 'setup'));
revertBabelRequire();

const testCollector = new TestCollector(files, matrix, {
forbidOnly: command.forbidOnly || undefined,
grep: command.grep,
timeout: command.timeout,
});
const rootSuite = testCollector.suite;
if (command.forbidOnly && testCollector.hasOnly()) {
console.error('=====================================');
console.error(' --forbid-only found a focused test.');
console.error('=====================================');
process.exit(1);
}

const total = rootSuite.total();
if (!total) {
console.error('=================');
console.error(' no tests found.');
console.error('=================');
process.exit(1);
}

// Trial run does not need many workers, use one.
const jobs = (command.trialRun || command.debug) ? 1 : command.jobs;
const runner = new Runner(rootSuite, total, {
debug: command.debug,
quiet: command.quiet,
grep: command.grep,
jobs,
outputDir: command.output,
reporter: command.reporter,
retries: command.retries,
snapshotDir: path.join(testDir, '__snapshots__'),
testDir,
timeout: command.timeout,
trialRun: command.trialRun,
updateSnapshots: command.updateSnapshots
});
try {
if (beforeFunction)
await beforeFunction();
await runner.run();
await runner.stop();
} finally {
if (afterFunction)
await afterFunction();
}
process.exit(runner.stats.failures ? 1 : 0);
});

program.parse(process.argv);

function collectFiles(testDir, dir, filters) {
const fullDir = path.join(testDir, dir);
if (fs.statSync(fullDir).isFile())
return [fullDir];
const files = [];
for (const name of fs.readdirSync(fullDir)) {
if (fs.lstatSync(path.join(fullDir, name)).isDirectory()) {
files.push(...collectFiles(testDir, path.join(dir, name), filters));
continue;
}
if (!name.endsWith('spec.ts'))
continue;
const relativeName = path.join(dir, name);
const fullName = path.join(testDir, relativeName);
if (!filters.length) {
files.push(fullName);
continue;
}
for (const filter of filters) {
if (relativeName.includes(filter)) {
files.push(fullName);
break;
}
}
}
return files;
}
2 changes: 1 addition & 1 deletion test-runner/src/dotReporter.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ class DotReporter extends Base {
});

runner.on(constants.EVENT_TEST_FAIL, test => {
if (test.duration >= test.timeout())
if (test.duration >= test.timeout)
process.stdout.write(colors.red('T'));
else
process.stdout.write(colors.red('F'));
Expand Down
13 changes: 6 additions & 7 deletions test-runner/src/fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/

import debug from 'debug';
import { Test } from './test';

declare global {
interface WorkerState {
Expand All @@ -38,17 +39,15 @@ export function setParameters(params: any) {
registerWorkerFixture(name as keyof WorkerState, async ({}, test) => await test(parameters[name] as never));
}

type TestInfo = {
file: string;
title: string;
timeout: number;
type TestConfig = {
outputDir: string;
testDir: string;
};

type TestResult = {
success: boolean;
info: TestInfo;
test: Test;
config: TestConfig;
error?: Error;
};

Expand Down Expand Up @@ -168,10 +167,10 @@ export class FixturePool {
]);
}

wrapTestCallback(callback: any, timeout: number, info: TestInfo) {
wrapTestCallback(callback: any, timeout: number, test: Test, config: TestConfig) {
if (!callback)
return callback;
const testResult: TestResult = { success: true, info };
const testResult: TestResult = { success: true, test, config };
return async() => {
try {
await this.resolveParametersAndRun(callback, timeout);
Expand Down
Loading

0 comments on commit 398bd47

Please sign in to comment.