Skip to content

Commit

Permalink
test: migrate cli tap tests to jest
Browse files Browse the repository at this point in the history
  • Loading branch information
Jahed Ahmed committed Nov 30, 2021
1 parent 85b681b commit bebac90
Show file tree
Hide file tree
Showing 11 changed files with 436 additions and 240 deletions.
27 changes: 24 additions & 3 deletions test/acceptance/fake-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ type FakeServer = {
setNextResponse: (r: any) => void;
setNextStatusCode: (c: number) => void;
setFeatureFlag: (featureFlag: string, enabled: boolean) => void;
unauthorizeAction: (action: string, reason?: string) => void;
getSnykToken: () => string;
listen: (port: string | number, callback: () => void) => void;
restore: () => void;
close: (callback: () => void) => void;
Expand All @@ -23,6 +25,7 @@ type FakeServer = {
export const fakeServer = (basePath: string, snykToken: string): FakeServer => {
let requests: express.Request[] = [];
let featureFlags: Map<string, boolean> = featureFlagDefaults();
let unauthorizedActions = new Map();
let nextStatusCode: number | undefined = undefined;
let nextResponse: any = undefined;
let depGraphResponse: Record<string, unknown> | undefined = undefined;
Expand All @@ -32,6 +35,7 @@ export const fakeServer = (basePath: string, snykToken: string): FakeServer => {
requests = [];
depGraphResponse = undefined;
featureFlags = featureFlagDefaults();
unauthorizedActions = new Map();
};

const getRequests = () => {
Expand Down Expand Up @@ -66,6 +70,18 @@ export const fakeServer = (basePath: string, snykToken: string): FakeServer => {
featureFlags.set(featureFlag, enabled);
};

const getSnykToken = (): string => snykToken;

const unauthorizeAction = (
action: string,
reason = 'unauthorized by test',
) => {
unauthorizedActions.set(action, {
allowed: false,
reason,
});
};

const app = express();
app.use(bodyParser.json({ limit: '50mb' }));
app.use((req, res, next) => {
Expand Down Expand Up @@ -383,9 +399,12 @@ export const fakeServer = (basePath: string, snykToken: string): FakeServer => {
res.status(200).send(baseResponse);
});

app.get(basePath + '/authorization/:action', (req, res, next) => {
res.send({ result: { allowed: true } });
return next();
app.get(basePath + '/authorization/:action', (req, res) => {
const result = unauthorizedActions.get(req.params.action) || {
allowed: true,
reason: 'Default fake server response.',
};
res.send({ result });
});

app.put(basePath + '/monitor/:registry/graph', (req, res, next) => {
Expand Down Expand Up @@ -442,6 +461,8 @@ export const fakeServer = (basePath: string, snykToken: string): FakeServer => {
setNextResponse,
setNextStatusCode,
setFeatureFlag,
unauthorizeAction,
getSnykToken,
listen,
restore,
close,
Expand Down
9 changes: 9 additions & 0 deletions test/acceptance/workspaces/policy/.snyk
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Snyk (https://snyk.io) policy file, patches or ignores known vulnerabilities.
version: v1.22.1
# ignores vulnerabilities until expiry date; change duration by modifying expiry date
ignore:
'npm:marked:20170907':
- '*':
reason: Default policy location test
expires: 2027-11-19T14:12:53.987Z
patch: {}
59 changes: 59 additions & 0 deletions test/jest/acceptance/snyk-auth/snyk-auth.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { fakeServer } from '../../../acceptance/fake-server';
import { createProjectFromWorkspace } from '../../util/createProject';
import { runSnykCLI } from '../../util/runSnykCLI';
import { removeAuth } from '../../util/removeAuth';

jest.setTimeout(1000 * 60);

describe('snyk auth', () => {
let server: ReturnType<typeof fakeServer>;
let env: Record<string, string>;

beforeAll((done) => {
const apiPath = '/api/v1';
const apiPort = process.env.PORT || process.env.SNYK_PORT || '12345';
env = {
...process.env,
SNYK_API: 'http://localhost:' + apiPort + apiPath,
SNYK_TOKEN: '123456789', // replace token from process.env
SNYK_DISABLE_ANALYTICS: '1',
};

server = fakeServer(apiPath, env.SNYK_TOKEN);
server.listen(apiPort, () => done());
});

afterEach(() => {
server.restore();
});

afterAll((done) => {
server.close(() => done());
});

it('accepts valid token', async () => {
const project = await createProjectFromWorkspace('fail-on/no-vulns');
server.setDepGraphResponse(await project.readJSON('vulns-result.json'));

const { code, stdout } = await runSnykCLI(`auth ${server.getSnykToken()}`, {
cwd: project.path(),
env: removeAuth(project, env),
});

expect(code).toEqual(0);
expect(stdout).toMatch('Your account has been authenticated.');
});

it('rejects invalid token', async () => {
const project = await createProjectFromWorkspace('fail-on/no-vulns');
server.setDepGraphResponse(await project.readJSON('vulns-result.json'));

const { code, stdout } = await runSnykCLI(`auth invalid-token`, {
cwd: project.path(),
env: removeAuth(project, env),
});

expect(code).toEqual(2);
expect(stdout).toMatch('Authentication failed.');
});
});
109 changes: 109 additions & 0 deletions test/jest/acceptance/snyk-ignore/snyk-ignore.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import { load as loadPolicy } from 'snyk-policy';
import { fakeServer } from '../../../acceptance/fake-server';
import { createProjectFromWorkspace } from '../../util/createProject';
import { runSnykCLI } from '../../util/runSnykCLI';

jest.setTimeout(1000 * 60);

describe('snyk ignore', () => {
let server: ReturnType<typeof fakeServer>;
let env: Record<string, string>;

beforeAll((done) => {
const apiPath = '/api/v1';
const apiPort = process.env.PORT || process.env.SNYK_PORT || '12345';
env = {
...process.env,
SNYK_API: 'http://localhost:' + apiPort + apiPath,
SNYK_TOKEN: '123456789', // replace token from process.env
SNYK_DISABLE_ANALYTICS: '1',
};

server = fakeServer(apiPath, env.SNYK_TOKEN);
server.listen(apiPort, () => done());
});

afterEach(() => {
server.restore();
});

afterAll((done) => {
server.close(() => done());
});

it('creates a policy file using minimal options', async () => {
const project = await createProjectFromWorkspace('empty');
const { code } = await runSnykCLI(`ignore --id=ID`, {
cwd: project.path(),
env: env,
});

expect(code).toEqual(0);

const policy = await loadPolicy(project.path());
expect(policy).toMatchObject({
ignore: {
ID: [
{
'*': {
reason: 'None Given',
expires: expect.any(Date),
created: expect.any(Date),
},
},
],
},
});
});

it('creates a policy file using provided options', async () => {
const project = await createProjectFromWorkspace('empty');
const { code } = await runSnykCLI(
`ignore --id=ID --reason=REASON --expiry=2017-10-07 --policy-path=${project.path()}`,
{
cwd: project.path(),
env: env,
},
);

expect(code).toEqual(0);
const policy = await loadPolicy(project.path());
expect(policy).toMatchObject({
ignore: {
ID: [
{
'*': {
reason: 'REASON',
expires: new Date('2017-10-07'),
created: expect.any(Date),
},
},
],
},
});
});

it('fails on missing ID', async () => {
const project = await createProjectFromWorkspace('empty');
const { code, stdout } = await runSnykCLI(`ignore --reason=REASON`, {
cwd: project.path(),
env: env,
});

expect(code).toEqual(2);
expect(stdout).toMatch('id is a required field');
});

it('errors when user is not authorized to ignore', async () => {
const project = await createProjectFromWorkspace('empty');
server.unauthorizeAction('cliIgnore', 'not allowed');

const { code, stdout } = await runSnykCLI(`ignore --id=ID`, {
cwd: project.path(),
env,
});

expect(code).toEqual(0);
expect(stdout).toMatch('not allowed');
});
});
64 changes: 64 additions & 0 deletions test/jest/acceptance/snyk-monitor/json-output.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { fakeServer } from '../../../acceptance/fake-server';
import { createProjectFromWorkspace } from '../../util/createProject';
import { runSnykCLI } from '../../util/runSnykCLI';

jest.setTimeout(1000 * 60);

describe('snyk monitor --json', () => {
let server: ReturnType<typeof fakeServer>;
let env: Record<string, string>;

beforeAll((done) => {
const apiPath = '/api/v1';
const apiPort = process.env.PORT || process.env.SNYK_PORT || '12345';
env = {
...process.env,
SNYK_API: 'http://localhost:' + apiPort + apiPath,
SNYK_TOKEN: '123456789', // replace token from process.env
SNYK_DISABLE_ANALYTICS: '1',
};

server = fakeServer(apiPath, env.SNYK_TOKEN);
server.listen(apiPort, () => done());
});

afterEach(() => {
server.restore();
});

afterAll((done) => {
server.close(() => done());
});

it('includes result details', async () => {
const project = await createProjectFromWorkspace('no-vulns');
const { code, stdout } = await runSnykCLI(`monitor --json`, {
cwd: project.path(),
env: env,
});

expect(code).toEqual(0);
expect(JSON.parse(stdout)).toMatchObject({
packageManager: 'npm',
manageUrl: 'http://localhost:12345/manage',
});
});

it('includes path errors', async () => {
const project = await createProjectFromWorkspace(
'no-supported-target-files',
);
const { code, stdout } = await runSnykCLI(`monitor --json`, {
cwd: project.path(),
env: env,
});

expect(code).toEqual(3);
expect(JSON.parse(stdout)).toMatchObject({
path: project.path(),
error: expect.stringMatching(
`Could not detect supported target files in ${project.path()}.`,
),
});
});
});
54 changes: 54 additions & 0 deletions test/jest/acceptance/snyk-policy/snyk-policy.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { fakeServer } from '../../../acceptance/fake-server';
import { createProjectFromWorkspace } from '../../util/createProject';
import { runSnykCLI } from '../../util/runSnykCLI';

jest.setTimeout(1000 * 60);

describe('snyk policy', () => {
let server: ReturnType<typeof fakeServer>;
let env: Record<string, string>;

beforeAll((done) => {
const apiPath = '/api/v1';
const apiPort = process.env.PORT || process.env.SNYK_PORT || '12345';
env = {
...process.env,
SNYK_API: 'http://localhost:' + apiPort + apiPath,
SNYK_TOKEN: '123456789', // replace token from process.env
SNYK_DISABLE_ANALYTICS: '1',
};

server = fakeServer(apiPath, env.SNYK_TOKEN);
server.listen(apiPort, () => done());
});

afterEach(() => {
server.restore();
});

afterAll((done) => {
server.close(() => done());
});

it('loads policy file', async () => {
const project = await createProjectFromWorkspace('policy');
const { code, stdout } = await runSnykCLI('policy', {
cwd: project.path(),
env: env,
});

expect(code).toEqual(0);
expect(stdout).toMatch('Current Snyk policy, read from .snyk file');
});

it('fails when policy not found', async () => {
const project = await createProjectFromWorkspace('empty');
const { code, stdout } = await runSnykCLI('policy', {
cwd: project.path(),
env: env,
});

expect(code).toEqual(2);
expect(stdout).toMatch('Could not load policy.');
});
});
Loading

0 comments on commit bebac90

Please sign in to comment.