Skip to content

Commit

Permalink
adding tests
Browse files Browse the repository at this point in the history
Signed-off-by: Marc Dumais <[email protected]>
  • Loading branch information
marcdumais-work committed Nov 2, 2023
1 parent 206f00b commit 2a62b57
Show file tree
Hide file tree
Showing 6 changed files with 757 additions and 32 deletions.
4 changes: 3 additions & 1 deletion nodejs-wrapper/.gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
node_modules
download
dependency-check-summary.txt
dependency-check-summary.txt
license-check-summary*
2 changes: 1 addition & 1 deletion nodejs-wrapper/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ This npm package makes it easy to integrate [dash-licenses](https://github.com/e

- called using `bash`
- `node.js` is installed and `node` executable is in the path
- on Linux, mac or Windows using Windows Subsystem for Linux (WSL)
- on Linux (tested), probably works on mac and Windows using the Windows Subsystem for Linux (WSL)
- to run `dash-licenses`: JDK or JRE 11 or later is installed and the `java` executable is in the path
- to run `dash-licenses` in [automatic review mode](https://github.com/eclipse/dash-licenses#automatic-ip-team-review-requests):
- a PAT (Personal Access Token) generated on the Eclipse Foundation Gitlab by an Eclipse project committer
Expand Down
3 changes: 3 additions & 0 deletions nodejs-wrapper/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
"chai": "^4.3.10",
"mocha": "^10.2.0"
},
"mocha": {
"timeout": 60000
},
"repository": {
"type": "git",
"url": "git+https://github.com/eclipse/dash-licenses.git"
Expand Down
60 changes: 30 additions & 30 deletions nodejs-wrapper/src/dash-licenses-wrapper.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,18 +90,18 @@ const dashLicensesConfig = {};
const dashLicensesConfigDefaults = {
/** batch size. Passed as-is to dash-licenses */
"batch": 100,
/** default config file, to fine-tune dash-licenses options */
"configFile": "dashLicensesConfig.json",
/** optional config file, to fine-tune dash-licenses options */
"configFile": "",
/** run this script in debug mode, printing-out more information */
"debug": false,
/** run in dry run mode - do not create IP review tickets */
"dryRun": false,
/**
* file where exclusions are defined. Excluded 3PPs will be ignored, if
* reported by dash-licenses, and so will not cause this script to exit with
* an error status
* optional file where exclusions are defined. Excluded 3PPs will be ignored,
* if reported by dash-licenses, and so will not cause this script to exit
* with an error status
*/
"exclusions": "license-check-exclusions.json",
"exclusions": "",
/** display help and exit */
"help": false,
/** file where dependencies are defined. Passed as-is to dash-licenses */
Expand Down Expand Up @@ -155,7 +155,7 @@ async function main() {
process.exit(1);
}
info(`Using input file: ${depsInputFile} - found`);
if (!fs.existsSync(exclusionsFile)) {
if (exclusionsFile && !fs.existsSync(exclusionsFile)) {
warn(`Exclusions file not found: ${exclusionsFile}. Ignoring it`);
} else {
info(`Using exclusions file: ${exclusionsFile} - found`);
Expand Down Expand Up @@ -183,11 +183,11 @@ async function main() {
process.exit(1);
}
}
// sanity check on downloaded dash-licenses .jar file - it can occasionally happen that the
// download is not a valid jar file, without curl reporting a problem. e.g. the content might
// be an error message in plain text, rather than the expected content. ATM the legit .jar is
// expected to be ~12MB in size - if we download something much smaller, it's likely not what
// we want.
// sanity check on downloaded dash-licenses .jar file - it can occasionally happen
// that the download is not a valid jar file, without curl reporting a problem. e.g.
// the content might be an error message in plain text, rather than the expected
// content. ATM the legit .jar is expected to be ~12MB in size - if we download
// something much smaller, it's likely not what we want.
if (fs.statSync(dashLicensesJar).size < 1000000) {
const invalidJar = dashLicensesJar + '.invalid';
error(`Downloaded dash-licenses jar file appears to be invalid or corrupted: ${dashLicensesJar}`);
Expand Down Expand Up @@ -235,7 +235,7 @@ async function main() {
const restricted = await getRestrictedDependenciesFromSummary(summaryFile);
// filter-out restricted dependencies that are in the exclusion file
if (restricted.length > 0) {
if (fs.existsSync(exclusionsFile)) {
if (exclusionsFile && fs.existsSync(exclusionsFile)) {
info('Checking dash-licenses "restricted" results against configured exclusions...');
const exclusions = readExclusions(exclusionsFile);
const unmatched = new Set(exclusions.keys());
Expand Down Expand Up @@ -326,7 +326,10 @@ function resolveConfig() {
}

// optional configuration provided from a config file
const configFromFile = parseConfigFile(configFile);
let configFromFile = [];
if (configFile) {
configFromFile = parseConfigFile(configFile);
}

// Resolve configuration: In order of priority (highest to lowest):
// CLI, config file, defaults
Expand All @@ -349,19 +352,16 @@ function resolveConfig() {
process.exit(0);
}

debug("Parsed config file: ");
debug(`(From file: ${configFile})`);
debug("-------------------------------------");
debug(getPrintableConfig(configFromFile));
debug("-------------------------------------\n");
debug("Parsed CLI:");
debug("-------------------------------------");
debug(getPrintableConfig(configFromCLI));
debug("-------------------------------------\n");
info("Effective configuration: ");
info("-------------------------------------");
info(getPrintableConfig(dashLicensesConfig));
info("-------------------------------------\n");
if (configFile) {
// debug("Parsed config file: ");
debug(`(From file: ${configFile})`);
debug("Parsed config file: " + getPrintableConfig(configFromFile) + "\n");
}
// debug("Parsed CLI:");
debug("Parsed CLI: " + getPrintableConfig(configFromCLI) + "\n");

// info("Effective configuration:");
info("Effective configuration: " + getPrintableConfig(dashLicensesConfig) + "\n");
}

/**
Expand Down Expand Up @@ -559,11 +559,11 @@ function prettyCommand(status, indent = 2) {
return JSON.stringify([status.bin, ...status.args], undefined, indent);
}

function info(text) { console.warn(cyan(`INFO: ${text}`)); }
function info(text) { console.info(cyan(`INFO: ${text}`)); }
function warn(text) { console.warn(yellow(`WARN: ${text}`)); }
function error(text) { console.error(red(`ERROR: ${text}`)); }
function debug(text) { if (dashLicensesConfig.debug) { console.warn(gray(`DEBUG: ${text}`)); } }
function help(text) { console.warn(green(`${text}`)); }
function debug(text) { if (dashLicensesConfig.debug) { console.info(gray(`DEBUG: ${text}`)); } }
function help(text) { console.info(green(`${text}`)); }

function style(code, text) { return noColor ? text : `\x1b[${code}m${text}\x1b[0m`; }
function cyan(text) { return style(96, text); }
Expand Down
140 changes: 140 additions & 0 deletions nodejs-wrapper/test/dash-licenses-wrapper.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
// Mocha tests for dash-licenses-wrapper
const chai = require('chai');
const should = chai.should();
const expect = chai.expect;
// const fs = require('fs');
const path = require('path');
const cp = require('child_process');

const wrapper = path.resolve("src", "dash-licenses-wrapper.js");

function runWrapper(args) {
const command = `${wrapper}`;
// const opts = { stdio: ['ignore', 'inherit', 'inherit']};
const opts = { stdio: 'pipe'};
let status = cp.spawnSync(command, args, opts);
// console.log("***" + status.stdout);

// "Debugger attached.\nWaiting for the debugger to disconnect...\n"
// const error
return [status.status, status.stdout.toString(), status.stderr.toString()];

}

describe("dash-licenses-wrapper tests", function() {
describe("test CLI parameters", function() {
it("test CLI param --help", function() {
const [status, output, error] = runWrapper(["--help"]);
expect(status).to.equal(0);
expect(error).to.be.empty;
expect(output).to.match(/^.*Usage: dash-licenses-wrapper.js \[options\]/);
});
it("test output is in color by default", function() {
const [status, output, error] = runWrapper(["--help"]);
expect(status).to.equal(0);
expect(error).to.be.empty;
expect(output).to.match(/^\x1b\[/);
});
it("test CLI param --noColor results in no color in output", function() {
const [status, output, error] = runWrapper(["--noColor", "--help"]);
expect(status).to.equal(0);
expect(error).to.be.empty;
expect(output).to.not.match(/^\x1b\[/);
});
it("test CLI param --dryRun results in exit before calling dash-licenses", function() {
const [status, output, error] = runWrapper(["--noColor", "--dryRun"]);
expect(status).to.equal(0);
// dash-licenses outputs on stderr
expect(error).to.be.empty;
expect(output).to.match(/Dry-run mode enabled/);
});
it("test that dry run mode is disabled by default", function() {
const [status, output, error] = runWrapper(["--noColor", "--help"]);
expect(status).to.equal(0);
expect(error).to.be.empty;
expect(output).to.not.match(/Dry-run mode enabled/);
});
it.only("test \"--debug\" CLI param enables extra traces", function() {
const [status, output, error] = runWrapper(["--debug", "--noColor", "--dryRun"]);
// console.log("***" + output);
// console.log("^^^" + error);
expect(status).to.equal(0);
// expect(error).to.equal("");

expect(extractCLIConfiguration(output, "debug")).to.equal(true);
const expectedCLIArgsDebugTrace =
`DEBUG: Parsed CLI: {
"debug": true,
"noColor": true,
"dryRun": true
}`;
expect(output).to.match(new RegExp(`^${expectedCLIArgsDebugTrace}`,'gm'));
});
it("test CLI param --inputFile ", function() {
const [status, output, error] = runWrapper(["--noColor", "--dryRun"]);
// console.log("***" + output);
// console.log("^^^" + error);
const entry = extractEffectiveConfiguration(output, "inputFile");
// console.log(`****** ${entry}`);
// expect(entry).to.equal("");
// expect(error).to.be.empty;
// expect(output).to.not.match(/Dry-run mode enabled/);
});
});
describe("Run dash-licenses with example yarn lock file", function() {
// it("", function() {
// const yarnLockExample = path.resolve("..", "core", "src", "test", "java", "test_data_yarn.lock");
// const [status, output, error] = runWrapper(["--inputfile", "yarnlockExample"]);
// console.log(output);
// expect(status).to.equal(0);
// });
});
});

/**
* Returns the effective value of a given dash-licenses-wrapper parameter. i.e. the value that will
* end-up being used once defaults, config file and CLI have been resolved.
* @param {string} output of dash-licenses-wrapper. The effective configuration is always printed except when using "--help"
* @param {string} configParamName optional name of a parameter to extract from the effective configuration.
*/
function extractEffectiveConfiguration(output, configParamName) {
// console.log(`********* ${output} `)
// const effectiveConfigTrace = output.match(/INFO: Effective configuration\:({.*})/gm);
const match = output.match(/^INFO: Effective configuration:(.*{.*})$/ms);
const config = match[1];
// console.log(`^^^^^^^^^:${config}`);
if (config && configParamName) {
const match = config.match(new RegExp(`^\\s+(\\"${configParamName}.*?),?$`,'m'));
const param = match[1];
// console.log(`$$$$$ extracted: ${param}`);
return param;
} else {
return config;
}
}

/**
*
* @param {string} output of dash-licenses-wrapper. Debug mode has to be enabled to see CLI configuration
* @param {string} configParamName optional name of a parameter to extract from the CLI configuration. If omitted, the entire CLI configuration is returned as a JSON object.
* @returns {string | any}
*/
function extractCLIConfiguration(output, configParamName) {
// console.log(`*********${output} `)
const match = output.match(/^DEBUG: Parsed CLI:(.*?{.*?})$/ms);
const config = match[1];
// console.log(`^^^^^^^^^:${config}`);

let obj;
try {
obj = JSON.parse(config);
} catch (e) {
console.error(e);
}

if (config && configParamName) {
return obj[`${configParamName}`];
} else {
return obj;
}
}
Loading

0 comments on commit 2a62b57

Please sign in to comment.