Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor and improve testing and un-skip skipped test re JSON file output #1752

Merged
merged 2 commits into from
Mar 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 5 additions & 10 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,7 @@ import stripAnsi from 'strip-ansi';
import { ExcludeFlagInvalidInputError } from '../lib/errors/exclude-flag-invalid-input';
import { modeValidation } from './modes';
import { JsonFileOutputBadInputError } from '../lib/errors/json-file-output-bad-input-error';
import {
createDirectory,
writeContentsToFileSwallowingErrors,
} from '../lib/json-file-output';
import { saveJsonToFileCreatingDirectoryIfRequired } from '../lib/json-file-output';
import {
Options,
TestOptions,
Expand Down Expand Up @@ -188,12 +185,10 @@ async function saveJsonResultsToFile(
return;
}

// create the directory if it doesn't exist
const dirPath = pathLib.dirname(jsonOutputFile);
const createDirSuccess = createDirectory(dirPath);
if (createDirSuccess) {
await writeContentsToFileSwallowingErrors(jsonOutputFile, stringifiedJson);
}
await saveJsonToFileCreatingDirectoryIfRequired(
jsonOutputFile,
stringifiedJson,
);
}

function checkRuntime() {
Expand Down
12 changes: 12 additions & 0 deletions src/lib/json-file-output.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { gte } from 'semver';
import { existsSync, mkdirSync, createWriteStream } from 'fs';
import * as path from 'path';

export const MIN_VERSION_FOR_MKDIR_RECURSIVE = '10.12.0';

Expand Down Expand Up @@ -66,3 +67,14 @@ export async function writeContentsToFileSwallowingErrors(
}
});
}

export async function saveJsonToFileCreatingDirectoryIfRequired(
jsonOutputFile: string,
contents: string,
): Promise<void> {
const dirPath = path.dirname(jsonOutputFile);
const createDirSuccess = createDirectory(dirPath);
if (createDirSuccess) {
await writeContentsToFileSwallowingErrors(jsonOutputFile, contents);
}
}
84 changes: 2 additions & 82 deletions test/jest/acceptance/cli-json-file-output.spec.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,13 @@
import { exec } from 'child_process';
import { sep, join } from 'path';
import { readFileSync, unlinkSync, rmdirSync, mkdirSync, existsSync } from 'fs';
import { readFileSync, unlinkSync } from 'fs';
import { v4 as uuidv4 } from 'uuid';
import { fakeServer } from '../../acceptance/fake-server';
import cli = require('../../../src/cli/commands');

const osName = require('os-name');

const main = './dist/cli/index.js'.replace(/\//g, sep);
const testTimeout = 50000;
const isWindows =
osName()
.toLowerCase()
.indexOf('windows') === 0;

describe('test --json-file-output ', () => {
let oldkey;
let oldendpoint;
Expand Down Expand Up @@ -122,79 +117,4 @@ describe('test --json-file-output ', () => {
},
testTimeout,
);

it(
'`test --json-file-output can handle a relative path`',

(done) => {
// if 'test-output' doesn't exist, created it
if (!existsSync('test-output')) {
mkdirSync('test-output');
}

const tempFolder = uuidv4();
const outputPath = `test-output/${tempFolder}/snyk-direct-json-test-output.json`;

exec(
`node ${main} test ${noVulnsProjectPath} --json --json-file-output=${outputPath}`,
{
env: {
PATH: process.env.PATH,
SNYK_TOKEN: apiKey,
SNYK_API,
SNYK_HOST,
},
},
async (err, stdout) => {
if (err) {
throw err;
}
// give file a little time to be finished to be written
await new Promise((r) => setTimeout(r, 5000));
const stdoutJson = stdout;
const outputFileContents = readFileSync(outputPath, 'utf-8');
unlinkSync(outputPath);
rmdirSync(`test-output/${tempFolder}`);
expect(stdoutJson).toEqual(outputFileContents);
done();
},
);
},
testTimeout,
);

if (isWindows) {
test.skip(
'`test --json-file-output can handle an absolute path`',
() => {
// if 'test-output' doesn't exist, created it
if (!existsSync('test-output')) {
mkdirSync('test-output');
}

const tempFolder = uuidv4();
const outputPath = join(
process.cwd(),
`test-output/${tempFolder}/snyk-direct-json-test-output.json`,
);

exec(
`node ${main} test ${noVulnsProjectPath} --json --json-file-output=${outputPath}`,
async (err, stdout) => {
if (err) {
throw err;
}
// give file a little time to be finished to be written
await new Promise((r) => setTimeout(r, 5000));
const stdoutJson = stdout;
const outputFileContents = readFileSync(outputPath, 'utf-8');
unlinkSync(outputPath);
rmdirSync(`test-output/${tempFolder}`);
expect(stdoutJson).toEqual(outputFileContents);
},
);
},
testTimeout,
);
}
});
181 changes: 181 additions & 0 deletions test/jest/system/json-file-output.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
import * as jsonFileOutputModule from '../../../src/lib/json-file-output';

import { v4 as uuidv4 } from 'uuid';
import { readFileSync, unlinkSync, rmdirSync, mkdirSync, existsSync } from 'fs';
import * as path from 'path';
import * as fsModule from 'fs';

describe('saveJsonToFileCreatingDirectoryIfRequired', () => {
beforeEach(() => {
jest.restoreAllMocks();
});

describe('supports absolute paths', () => {
it('with directory that does not exists', async () => {
const tempFolder = uuidv4();
const outputPath = path.join(
process.cwd(),
'test-output',
tempFolder,
'test-output.json',
);

const fullDirPath = path.dirname(outputPath);
expect(fullDirPath).toBe(
path.join(process.cwd(), 'test-output', tempFolder),
);
const jsonString = JSON.stringify({
ok: true,
somekey: 'someval',
});

const mkdirSyncDirSpy = jest.spyOn(fsModule, 'mkdirSync');

try {
// this should create the tempFolder inside of test-output (and test-ouptut if it doesn't exist yet) as well as write the file
await jsonFileOutputModule.saveJsonToFileCreatingDirectoryIfRequired(
outputPath,
jsonString,
);

// ensure that mkDirSync was called once
expect(mkdirSyncDirSpy).toHaveBeenCalledTimes(1);

const outputFileContents = readFileSync(outputPath, 'utf-8');
expect(outputFileContents.trim()).toEqual(jsonString);
} finally {
unlinkSync(outputPath);
rmdirSync(fullDirPath);
}
});

it('with directory that already exists', async () => {
const tempFolder = uuidv4();
const outputPath = path.join(
process.cwd(),
'test-output',
tempFolder,
'test-output.json',
);

// if 'test-output' doesn't exist, created it
if (!existsSync('test-output')) {
mkdirSync('test-output');
}

const fullDirPath = path.dirname(outputPath);

// create the temp folder before calling saveJsonToFileCreatingDirectoryIfRequired
mkdirSync(fullDirPath);
expect(fullDirPath).toBe(
path.join(process.cwd(), 'test-output', tempFolder),
);
const jsonString = JSON.stringify({
ok: true,
somekey: 'someval',
});

const mkdirSyncDirSpy = jest.spyOn(fsModule, 'mkdirSync');
expect(mkdirSyncDirSpy).toHaveBeenCalledTimes(0); // zero because we already created the temp folder, so should have to create it again

try {
// this should create the tempFolder inside of test-output (and test-ouptut if it doesn't exist yet) as well as write the file
await jsonFileOutputModule.saveJsonToFileCreatingDirectoryIfRequired(
outputPath,
jsonString,
);

// ensure that mkDirSync was called once
expect(mkdirSyncDirSpy).toHaveBeenCalledTimes(0); // zero because we already created the temp folder, so should have to create it again

const outputFileContents = readFileSync(outputPath, 'utf-8');
expect(outputFileContents.trim()).toEqual(jsonString);
} finally {
unlinkSync(outputPath);
rmdirSync(fullDirPath);
}
});
});

// relative paths
describe('supports relative paths', () => {
it('with directory that does not exists', async () => {
const tempFolder = uuidv4();
const outputPath = path.join(
'test-output',
tempFolder,
'test-output.json',
);

const fullDirPath = path.dirname(outputPath);
expect(fullDirPath).toBe(path.join('test-output', tempFolder));
const jsonString = JSON.stringify({
ok: true,
somekey: 'someval',
});

const mkdirSyncDirSpy = jest.spyOn(fsModule, 'mkdirSync');

try {
// this should create the tempFolder inside of test-output (and test-ouptut if it doesn't exist yet) as well as write the file
await jsonFileOutputModule.saveJsonToFileCreatingDirectoryIfRequired(
outputPath,
jsonString,
);

// ensure that mkDirSync was called once
expect(mkdirSyncDirSpy).toHaveBeenCalledTimes(1);

const outputFileContents = readFileSync(outputPath, 'utf-8');
expect(outputFileContents.trim()).toEqual(jsonString);
} finally {
unlinkSync(outputPath);
rmdirSync(fullDirPath);
}
});

it('with directory that already exists', async () => {
const tempFolder = uuidv4();
const outputPath = path.join(
'test-output',
tempFolder,
'test-output.json',
);

// if 'test-output' doesn't exist, created it
if (!existsSync('test-output')) {
mkdirSync('test-output');
}

const fullDirPath = path.dirname(outputPath);

// create the temp folder before calling saveJsonToFileCreatingDirectoryIfRequired
mkdirSync(fullDirPath);
expect(fullDirPath).toBe(path.join('test-output', tempFolder));
const jsonString = JSON.stringify({
ok: true,
somekey: 'someval',
});

const mkdirSyncDirSpy = jest.spyOn(fsModule, 'mkdirSync');
expect(mkdirSyncDirSpy).toHaveBeenCalledTimes(0); // zero because we already created the temp folder, so should have to create it again

try {
// this should create the tempFolder inside of test-output (and test-ouptut if it doesn't exist yet) as well as write the file
await jsonFileOutputModule.saveJsonToFileCreatingDirectoryIfRequired(
outputPath,
jsonString,
);

// ensure that mkDirSync was called once
expect(mkdirSyncDirSpy).toHaveBeenCalledTimes(0); // zero because we already created the temp folder, so should have to create it again

const outputFileContents = readFileSync(outputPath, 'utf-8');
expect(outputFileContents.trim()).toEqual(jsonString);
} finally {
unlinkSync(outputPath);
rmdirSync(fullDirPath);
}
});
});
});