Run unit tests against node.js too (#137790)

* tests - run unit tests also against node.js

* fixes

* fail if major node.js version mismatch

* -tfs is unsupported

* Add `@ts-check` and remove `jsdom`

* tests - process.env layer breaker

* Improve loader config

* skip one test

* address todos

* try to force color output

* Use a file: URI as baseUrl

Co-authored-by: Alex Dima <alexdima@microsoft.com>
This commit is contained in:
Benjamin Pasero
2021-11-24 13:45:17 +01:00
committed by GitHub
parent bb7a76bf2b
commit 754190f326
15 changed files with 114 additions and 208 deletions

View File

@@ -1,49 +0,0 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const yaserver = require('yaserver');
const http = require('http');
const glob = require('glob');
const path = require('path');
const fs = require('fs');
const REPO_ROOT = path.join(__dirname, '../../../');
const PORT = 8887;
function template(str, env) {
return str.replace(/{{\s*([\w_\-]+)\s*}}/g, function (all, part) {
return env[part];
});
}
yaserver.createServer({ rootDir: REPO_ROOT }).then((staticServer) => {
const server = http.createServer((req, res) => {
if (req.url === '' || req.url === '/') {
glob('**/vs/{base,platform,editor}/**/test/{common,browser}/**/*.test.js', {
cwd: path.join(REPO_ROOT, 'out'),
// ignore: ['**/test/{node,electron*}/**/*.js']
}, function (err, files) {
if (err) { console.log(err); process.exit(0); }
var modules = files
.map(function (file) { return file.replace(/\.js$/, ''); });
fs.readFile(path.join(__dirname, 'index.html'), 'utf8', function (err, templateString) {
if (err) { console.log(err); process.exit(0); }
res.end(template(templateString, {
modules: JSON.stringify(modules)
}));
});
});
} else {
return staticServer.handle(req, res);
}
});
server.listen(PORT, () => {
console.log(`http://localhost:${PORT}/`);
});
});

View File

@@ -1,12 +0,0 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define([], function() {
return {
load: function(name, req, load) {
load({});
}
};
});

View File

@@ -1,30 +0,0 @@
<html>
<head>
<meta charset="utf-8">
<title>VSCode Tests</title>
<link href="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.css" rel="stylesheet" />
</head>
<body>
<div id="mocha"></div>
<script src="/out/vs/loader.js"></script>
<script src="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.js"></script>
<script>
mocha.setup('tdd');
require.config({
baseUrl: '/out',
paths: {
assert: '/test/unit/assert.js',
sinon: '/node_modules/sinon/pkg/sinon.js',
'sinon-test': '/node_modules/sinon-test/dist/sinon-test.js'
}
});
require({{ modules }}, function () {
mocha.run();
});
</script>
</body>
</html>

View File

@@ -3,13 +3,15 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*eslint-env mocha*/
/*global define,run*/
//@ts-check
process.env.MOCHA_COLORS = '1'; // Force colors (note that this must come before any mocha imports)
const assert = require('assert');
const mocha = require('mocha');
const path = require('path');
const fs = require('fs');
const glob = require('glob');
const jsdom = require('jsdom-no-contextify');
const minimatch = require('minimatch');
const coverage = require('../coverage');
const optimist = require('optimist')
@@ -17,13 +19,21 @@ const optimist = require('optimist')
.describe('build', 'Run from out-build').boolean('build')
.describe('run', 'Run a single file').string('run')
.describe('coverage', 'Generate a coverage report').boolean('coverage')
.describe('browser', 'Run tests in a browser').boolean('browser')
.alias('h', 'help').boolean('h')
.describe('h', 'Show help');
const TEST_GLOB = '**/test/**/*.test.js';
const excludeGlob = '**/{browser,electron-sandbox,electron-browser,electron-main,editor/contrib}/**/*.test.js';
const excludeModules = [
'vs/platform/environment/test/node/nativeModules.test.js',
'vs/base/parts/storage/test/node/storage.test.js',
'vs/platform/files/test/common/files.test.js' // TODO@bpasero enable once we ship Electron 16
]
/**
* @type {{ build: boolean; run: string; runGlob: string; coverage: boolean; help: boolean; }}
*/
const argv = optimist.argv;
if (argv.help) {
@@ -36,21 +46,54 @@ const out = argv.build ? 'out-build' : 'out';
const loader = require(`../../../${out}/vs/loader`);
const src = path.join(REPO_ROOT, out);
const majorRequiredNodeVersion = `v${/^target\s+"([^"]+)"$/m.exec(fs.readFileSync(path.join(REPO_ROOT, 'remote', '.yarnrc'), 'utf8'))[1]}`.substring(0, 3);
const currentMajorNodeVersion = process.version.substring(0, 3);
if (majorRequiredNodeVersion !== currentMajorNodeVersion) {
console.error(`node.js unit tests require a major node.js version of ${majorRequiredNodeVersion} (your version is: ${currentMajorNodeVersion})`);
process.exit(1);
}
function main() {
process.on('uncaughtException', function (e) {
console.error(e.stack || e);
});
/**
* @param {string} path
* @param {{ isWindows?: boolean, scheme?: string, fallbackAuthority?: string }} config
* @returns {string}
*/
function fileUriFromPath(path, config) {
// Since we are building a URI, we normalize any backslash
// to slashes and we ensure that the path begins with a '/'.
let pathName = path.replace(/\\/g, '/');
if (pathName.length > 0 && pathName.charAt(0) !== '/') {
pathName = `/${pathName}`;
}
/** @type {string} */
let uri;
// Windows: in order to support UNC paths (which start with '//')
// that have their own authority, we do not use the provided authority
// but rather preserve it.
if (config.isWindows && pathName.startsWith('//')) {
uri = encodeURI(`${config.scheme || 'file'}:${pathName}`);
}
// Otherwise we optionally add the provided authority if specified
else {
uri = encodeURI(`${config.scheme || 'file'}://${config.fallbackAuthority || ''}${pathName}`);
}
return uri.replace(/#/g, '%23');
}
const loaderConfig = {
nodeRequire: require,
nodeMain: __filename,
baseUrl: path.join(REPO_ROOT, 'src'),
paths: {
'vs/css': '../test/unit/node/css.mock',
'vs': `../${out}/vs`,
'lib': `../${out}/lib`,
'bootstrap-fork': `../${out}/bootstrap-fork`
},
baseUrl: fileUriFromPath(src, { isWindows: process.platform === 'win32' }),
catchError: true
};
@@ -67,28 +110,19 @@ function main() {
loader.config(loaderConfig);
global.define = loader;
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.self = global.window = global.document.parentWindow;
global.Element = global.window.Element;
global.HTMLElement = global.window.HTMLElement;
global.Node = global.window.Node;
global.navigator = global.window.navigator;
global.XMLHttpRequest = global.window.XMLHttpRequest;
let didErr = false;
const write = process.stderr.write;
process.stderr.write = function (data) {
didErr = didErr || !!data;
write.apply(process.stderr, arguments);
process.stderr.write = function (...args) {
didErr = didErr || !!args[0];
return write.apply(process.stderr, args);
};
/** @type { (callback:(err:any)=>void)=>void } */
let loadFunc = null;
if (argv.runGlob) {
loadFunc = (cb) => {
const doRun = tests => {
const doRun = /** @param {string[]} tests */(tests) => {
const modulesToLoad = tests.map(test => {
if (path.isAbsolute(test)) {
test = path.relative(src, path.resolve(test));
@@ -96,7 +130,7 @@ function main() {
return test.replace(/(\.js)|(\.d\.ts)|(\.js\.map)$/, '');
});
define(modulesToLoad, () => cb(null), cb);
loader(modulesToLoad, () => cb(null), cb);
};
glob(argv.runGlob, { cwd: src }, function (err, files) { doRun(files); });
@@ -109,18 +143,19 @@ function main() {
return path.relative(src, path.resolve(test)).replace(/(\.js)|(\.js\.map)$/, '').replace(/\\/g, '/');
});
loadFunc = (cb) => {
define(modulesToLoad, () => cb(null), cb);
loader(modulesToLoad, () => cb(null), cb);
};
} else {
loadFunc = (cb) => {
glob(TEST_GLOB, { cwd: src }, function (err, files) {
/** @type {string[]} */
const modules = [];
for (let file of files) {
if (!minimatch(file, excludeGlob)) {
if (!minimatch(file, excludeGlob) && excludeModules.indexOf(file) === -1) {
modules.push(file.replace(/\.js$/, ''));
}
}
define(modules, function () { cb(null); }, cb);
loader(modules, function () { cb(null); }, cb);
});
};
}
@@ -135,7 +170,7 @@ function main() {
if (!argv.run && !argv.runGlob) {
// set up last test
suite('Loader', function () {
mocha.suite('Loader', function () {
test('should not explode while loading', function () {
assert.ok(!didErr, 'should not explode while loading');
});
@@ -144,7 +179,7 @@ function main() {
// report failing test for every unexpected error during any of the tests
let unexpectedErrors = [];
suite('Errors', function () {
mocha.suite('Errors', function () {
test('should not have unexpected errors in tests', function () {
if (unexpectedErrors.length) {
unexpectedErrors.forEach(function (stack) {
@@ -165,13 +200,9 @@ function main() {
});
// fire up mocha
run();
mocha.run();
});
});
}
if (process.argv.some(function (a) { return /^--browser/.test(a); })) {
require('./browser');
} else {
main();
}
main();