Skip to content

Commit

Permalink
refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
Mate Pek committed Aug 28, 2021
1 parent 917b123 commit 1a742c0
Show file tree
Hide file tree
Showing 6 changed files with 47 additions and 157 deletions.
5 changes: 2 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"icon": "resources/icon.png",
"author": "Mate Pek",
"publisher": "matepek",
"version": "3.7.0",
"version": "3.6.28",
"license": "MIT",
"homepage": "https://github.com/matepek/vscode-catch2-test-adapter",
"repository": {
Expand Down Expand Up @@ -61,8 +61,7 @@
"tslib": "^2.3.1",
"vscode-test-adapter-api": "^1.9.0",
"vscode-test-adapter-util": "^0.7.1",
"xml2js": "^0.4.23",
"junit-report-merger": "^2.2.3"
"xml2js": "^0.4.23"
},
"devDependencies": {
"@sentry/node": "^6.11.0",
Expand Down
3 changes: 1 addition & 2 deletions src/ExecutableConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import { RootSuite } from './RootSuite';
import { readJSONSync } from 'fs-extra';
import { Spawner, DefaultSpawner, SpawnWithExecutor } from './Spawner';
import { RunTask, ExecutionWrapper, FrameworkSpecific } from './AdvancedExecutableInterface';
import { isWin } from '../test/Common';
import { LoggerWrapper } from './LoggerWrapper';

///
Expand Down Expand Up @@ -577,7 +576,7 @@ export class ExecutableConfig implements vscode.Disposable {
}

function checkEnvForPath(env: Record<string, string>, log: LoggerWrapper): void {
if (isWin) {
if (process.platform == 'win32') {
checkPathVariance('PATH', env, log);
checkPathVariance('Path', env, log);
checkPathVariance('path', env, log);
Expand Down
2 changes: 1 addition & 1 deletion src/RunnableFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ export class RunnableFactory {
const cpputest = runWithHelpRes.stdout.match(
this._cpputest.helpRegex
? new RegExp(this._cpputest.helpRegex, regexFlags)
: /[-g|sg|xg|xsg groupName]... [-n|sn|xn|xsn testName].../,
: /\[-g\|sg\|xg\|xsg groupName\]\.\.\. \[-n\|sn\|xn\|xsn testName\]\.\.\. \[-t groupName\.testName\]\.\.\./,
);
if (cpputest) {
return new CppUTestRunnable(
Expand Down
118 changes: 18 additions & 100 deletions src/framework/CppUTestRunnable.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import * as fs from 'fs-extra';
import { inspect } from 'util';
import { mergeFiles } from 'junit-report-merger';
import * as fs from 'fs';
import { inspect, promisify } from 'util';
import { Suite } from '../Suite';
import { AbstractRunnable, RunnableReloadResult } from '../AbstractRunnable';
import { CppUTestTest } from './CppUTestTest';
import { Parser } from 'xml2js';
import { RunnableProperties } from '../RunnableProperties';
import { SharedVariables } from '../SharedVariables';
import { RunningRunnable, ProcessResult } from '../RunningRunnable';
Expand All @@ -28,67 +26,11 @@ export class CppUTestRunnable extends AbstractRunnable {
return this.properties.testGrouping;
} else {
const grouping = { groupByExecutable: this._getGroupByExecutable() };
grouping.groupByExecutable.groupByTags = { tags: [], tagFormat: '${tag}' };
return grouping;
}
}

private async _reloadFromXml(xmlStr: string, cancellationFlag: CancellationFlag): Promise<RunnableReloadResult> {
const testGrouping = this.getTestGrouping();

interface XmlObject {
[prop: string]: any; //eslint-disable-line
}

let xml: XmlObject = {};

new Parser({ explicitArray: true }).parseString(xmlStr, (err: Error, result: Record<string, unknown>) => {
if (err) {
throw err;
} else {
xml = result;
}
});

const reloadResult = new RunnableReloadResult();

const processTestcases = async (testsuite: any, reloadResult: RunnableReloadResult) => {
const suiteName = testsuite.$.name;
for (let i = 0; i < testsuite.testcase.length; i++) {
if (cancellationFlag.isCancellationRequested) return;

const testCase = testsuite.testcase[i];
const testName = testCase.$.name.startsWith('DISABLED_') ? testCase.$.name.substr(9) : testCase.$.name;
const testNameAsId = suiteName + '.' + testCase.$.name;

const file = testCase.$.file ? await this._resolveSourceFilePath(testCase.$.file) : undefined;
const line = testCase.$.line ? testCase.$.line - 1 : undefined;

reloadResult.add(
...(await this._createSubtreeAndAddTest(
testGrouping,
testNameAsId,
testName,
file,
[suiteName],
(parent: Suite) => new CppUTestTest(this._shared, this, parent, testNameAsId, testName, file, line),
(old: AbstractTest) => (old as CppUTestTest).update(testNameAsId, file, line),
)),
);
}
};

if (xml.testsuites !== undefined) {
for (let i = 0; i < xml.testsuites.testsuite.length; ++i) {
await processTestcases(xml.testsuites.testsuite[i], reloadResult)
.catch((err) => this._shared.log.info('Error', err));
}
} else {
await processTestcases(xml.testsuite, reloadResult);
}

return reloadResult;
}

private async _reloadFromString(
stdOutStr: string,
cancellationFlag: CancellationFlag,
Expand Down Expand Up @@ -120,18 +62,18 @@ export class CppUTestRunnable extends AbstractRunnable {
}

protected async _reloadChildren(cancellationFlag: CancellationFlag): Promise<RunnableReloadResult> {
const cacheFile = this.properties.path + '.TestMate.testListCache.xml';
const cacheFile = this.properties.path + '.TestMate.testListCache.txt';

if (this._shared.enabledTestListCaching) {
try {
const cacheStat = await fs.stat(cacheFile);
const execStat = await fs.stat(this.properties.path);
const cacheStat = await promisify(fs.stat)(cacheFile);
const execStat = await promisify(fs.stat)(this.properties.path);

if (cacheStat.size > 0 && cacheStat.mtime > execStat.mtime) {
this._shared.log.info('loading from cache: ', cacheFile);
const xmlStr = await fs.readFile(cacheFile, 'utf8');
const str = await promisify(fs.readFile)(cacheFile, 'utf8');

return await this._reloadFromXml(xmlStr, cancellationFlag);
return await this._reloadFromString(str, cancellationFlag);
}
} catch (e) {
this._shared.log.info('coudnt use cache', e);
Expand All @@ -149,47 +91,23 @@ export class CppUTestRunnable extends AbstractRunnable {
);

if (cppUTestListOutput.stderr && !this.properties.ignoreTestEnumerationStdErr) {
this._shared.log.warn('reloadChildren -> cppUTestListOutput.stderr: ', cppUTestListOutput);
this._shared.log.warn('reloadChildren -> googleTestListOutput.stderr: ', cppUTestListOutput);
return await this._createAndAddUnexpectedStdError(cppUTestListOutput.stdout, cppUTestListOutput.stderr);
}

if (cppUTestListOutput.stdout.length === 0) {
this._shared.log.debug(cppUTestListOutput);
throw Error('stoud is empty');
}

const result = this._reloadFromString(cppUTestListOutput.stdout, cancellationFlag);
const result = await this._reloadFromString(cppUTestListOutput.stdout, cancellationFlag);

if (this._shared.enabledTestListCaching) {
//Generate xmls folder
const junitXmlsFolderPath = this.properties.path + '_junit_xmls';
fs.mkdir(junitXmlsFolderPath)
.then(() => this._shared.log.info('junit-xmls folder created', junitXmlsFolderPath))
.catch(err => this._shared.log.error('error creating xmls folder: ', junitXmlsFolderPath, err));
//Generate xml files
const args = this.properties.prependTestListingArgs.concat(['-ojunit']);
const options = { cwd: junitXmlsFolderPath };
await this.properties.spawner
.spawnAsync(this.properties.path, args, options, 30000)
.then(() => this._shared.log.info('create cpputest xmls', this.properties.path, args, options.cwd));
//Merge xmls into single xml
fs.readdir(junitXmlsFolderPath, (err, files) => {
if (files.length > 1) {
mergeFiles(cacheFile, [junitXmlsFolderPath + '/*.xml'])
.then(() => this._shared.log.info('cache xml written', cacheFile))
.catch(err => this._shared.log.warn('combine xml cache file could not create: ', cacheFile, err));
} else {
fs.copyFile(junitXmlsFolderPath + '/' + files[0], cacheFile);
}
});
//Delete xmls folder
fs.remove(junitXmlsFolderPath)
.then(() => this._shared.log.info('junit-xmls folder deleted', junitXmlsFolderPath))
.catch(err => this._shared.log.error('error deleting xmls folder: ', junitXmlsFolderPath, err));
promisify(fs.writeFile)(cacheFile, cppUTestListOutput.stdout).catch(err =>
this._shared.log.warn('couldnt write cache file:', err),
);
}

return result;
}

//TODO:matepek: reviewed until this

protected _getRunParamsInner(childrenToRun: readonly Readonly<AbstractTest>[]): string[] {
// TODO: Add multiple options
const execParams: string[] = [];
Expand All @@ -201,7 +119,7 @@ export class CppUTestRunnable extends AbstractRunnable {
return execParams;
}

protected _getDebugParamsInner(childrenToRun: readonly Readonly<AbstractTest>[], breakOnFailure: boolean): string[] {
protected _getDebugParamsInner(childrenToRun: readonly Readonly<AbstractTest>[], _breakOnFailure: boolean): string[] {
// TODO: Proper debug options
// TODO: colouring 'debug.enableOutputColouring'
// TODO: Add multiple options
Expand Down Expand Up @@ -333,7 +251,7 @@ export class CppUTestRunnable extends AbstractRunnable {
} else {
if (code !== null && code !== undefined) resolve(ProcessResult.createFromErrorCode(code));
else if (signal !== null && signal !== undefined) resolve(ProcessResult.createFromSignal(signal));
else resolve(ProcessResult.error('unknown sfngvdlfkxdvgn'));
else resolve(ProcessResult.error('unknown sgrstbdfg'));
}
});
})
Expand Down
28 changes: 25 additions & 3 deletions test/cpp/cpputest/cpputest1.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,40 @@ TEST_GROUP(FirstTestGroup)

TEST(FirstTestGroup, FirstTest)
{
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
//std::this_thread::sleep_for(std::chrono::milliseconds(2000));
}

TEST(FirstTestGroup, SecondTest)
{
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
//std::this_thread::sleep_for(std::chrono::milliseconds(2000));
CHECK(false);
}

TEST(FirstTestGroup, ThirdTest)
{
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
//std::this_thread::sleep_for(std::chrono::milliseconds(2000));
//FAIL("Fail me!");
}


TEST_GROUP(SecondTestGroupt)
{
};

TEST(SecondTestGroupt, FirstTest)
{
//std::this_thread::sleep_for(std::chrono::milliseconds(2000));
}

TEST(SecondTestGroupt, SecondTest)
{
//std::this_thread::sleep_for(std::chrono::milliseconds(2000));
CHECK(false);
}

TEST(SecondTestGroupt, ThirdTest)
{
//std::this_thread::sleep_for(std::chrono::milliseconds(2000));
//FAIL("Fail me!");
}

Expand Down
48 changes: 0 additions & 48 deletions test/framework/CppUTestRunnable.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { CppUTestRunnable } from '../../src/framework/CppUTestRunnable';
import { RootSuite } from '../../src/RootSuite';
import { RunnableProperties } from '../../src/RunnableProperties';
import { DefaultSpawner } from '../../src/Spawner';
import { EOL } from 'os';

///

Expand Down Expand Up @@ -166,51 +165,4 @@ describe(pathlib.basename(__filename), function () {
}
});
});

context('Testing _reloadFromXml', function () {
it('should reload ex.1', async function () {
const { root, runnable } = createCppUTestRunnable();

const testOutput: string[] = [
'<?xml version="1.0" encoding="UTF-8" ?>',
'<testsuite errors="0" failures="0" hostname="localhost" name="FirstTestGroup" tests="2" time="4.002" timestamp="2021-08-26T16:19:26">',
'<properties>',
'</properties>',
'<testcase classname="FirstTestGroup" name="SecondTest" assertions="0" time="2.001" file="/mnt/c/Users/testcppcpputestcpputest1.cpp" line="20">',
'</testcase>',
'<testcase classname="FirstTestGroup" name="FirstTest" assertions="0" time="2.001" file="/mnt/c/Users/testcppcpputestcpputest1.cpp" line="15">',
'</testcase>',
'<system-out></system-out>',
'<system-err></system-err>',
'</testsuite>,',
];
const res = await runnable['_reloadFromXml'](testOutput.join(EOL), { isCancellationRequested: false });

const tests = [...res.tests].sort((a, b) => a.testNameAsId.localeCompare(b.testNameAsId));

assert.strictEqual(tests.length, 2);

assert.strictEqual(tests[0].testNameAsId, 'FirstTestGroup.FirstTest');
assert.strictEqual(tests[0].label, 'FirstTest');
assert.strictEqual(tests[0].file, pathlib.normalize('/mnt/c/Users/testcppcpputestcpputest1.cpp'));
assert.strictEqual(tests[0].line, 14);
assert.strictEqual(tests[0].skipped, false);
assert.strictEqual(tests[0].getStaticEvent('1'), undefined);
assert.strictEqual(tests[1].testNameAsId, 'FirstTestGroup.SecondTest');
assert.strictEqual(tests[1].label, 'SecondTest');
assert.strictEqual(tests[1].file, pathlib.normalize('/mnt/c/Users/testcppcpputestcpputest1.cpp'));
assert.strictEqual(tests[1].line, 19);
assert.strictEqual(tests[1].skipped, false);
assert.strictEqual(tests[1].getStaticEvent('1'), undefined);

assert.strictEqual(root.children.length, 1);
const suite1 = root.children[0];
assert.strictEqual(suite1.label, 'name');
if (suite1.type === 'suite') {
assert.strictEqual(suite1.children.length, 2);
} else {
assert.strictEqual(suite1.type, 'suite');
}
});
});
});

0 comments on commit 1a742c0

Please sign in to comment.