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

feat: expose fetch to custom functions #1079

Merged
merged 4 commits into from
Apr 14, 2020
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
231 changes: 133 additions & 98 deletions src/__tests__/linter.jest.test.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { normalize } from '@stoplight/path';
import { DiagnosticSeverity } from '@stoplight/types';
import * as nock from 'nock';
import * as path from 'path';
import { isOpenApiv3 } from '../formats';
import { httpAndFileResolver } from '../resolvers/http-and-file';
import { Spectral } from '../spectral';

import { isOpenApiv3 } from '../formats';
import { functions } from '../functions';
import { httpAndFileResolver } from '../resolvers/http-and-file';
import { readRuleset } from '../rulesets';
import { setFunctionContext } from '../rulesets/evaluators';
import oasDocumentSchema from '../rulesets/oas/functions/oasDocumentSchema';
import { Spectral } from '../spectral';
import { IRuleset, RulesetExceptionCollection } from '../types/ruleset';

const customFunctionOASRuleset = path.join(__dirname, './__fixtures__/custom-functions-oas-ruleset.json');
Expand All @@ -24,6 +25,7 @@ describe('Linter', () => {

afterEach(() => {
jest.restoreAllMocks();
nock.cleanAll();
});

it('should make use of custom functions', async () => {
Expand Down Expand Up @@ -73,116 +75,161 @@ describe('Linter', () => {
);
});

it('should expose function-live lifespan cache to custom functions', async () => {
const logSpy = jest.spyOn(global.console, 'log').mockImplementation(Function);
describe('custom functions', () => {
it('should have access to function-live lifespan cache', async () => {
const logSpy = jest.spyOn(global.console, 'log').mockImplementation(Function);

await spectral.setRuleset({
exceptions: {},
rules: {
foo: {
given: '$',
then: {
function: 'fn',
await spectral.setRuleset({
exceptions: {},
rules: {
foo: {
given: '$',
then: {
function: 'fn',
},
},
},
bar: {
given: '$',
then: {
function: 'fn',
bar: {
given: '$',
then: {
function: 'fn',
},
},
},
},
functions: {
fn: {
source: null,
name: 'fn',
schema: null,
code: `module.exports = function() {
functions: {
fn: {
source: null,
name: 'fn',
schema: null,
code: `module.exports = function() {
console.log(this.cache.get('test') || this.cache.set('test', []).get('test'));
}`,
},
},
},
});
});

await spectral.run({});
await spectral.run({});

// verifies whether the 2 subsequent calls passed the same cache instance as the first argument
expect(logSpy.mock.calls[0][0]).toBe(logSpy.mock.calls[1][0]);
// verifies whether the 2 subsequent calls passed the same cache instance as the first argument
expect(logSpy.mock.calls[0][0]).toBe(logSpy.mock.calls[1][0]);

await spectral.run({});
await spectral.run({});

expect(logSpy.mock.calls[2][0]).toBe(logSpy.mock.calls[3][0]);
expect(logSpy.mock.calls[0][0]).toBe(logSpy.mock.calls[2][0]);
});
expect(logSpy.mock.calls[2][0]).toBe(logSpy.mock.calls[3][0]);
expect(logSpy.mock.calls[0][0]).toBe(logSpy.mock.calls[2][0]);
});

it('should expose cache to custom functions that is not shared among them', async () => {
const logSpy = jest.spyOn(global.console, 'log').mockImplementation(Function);
it('should have access to cache that is not shared among them', async () => {
const logSpy = jest.spyOn(global.console, 'log').mockImplementation(Function);

await spectral.setRuleset({
exceptions: {},
rules: {
foo: {
given: '$',
then: {
function: 'fn',
await spectral.setRuleset({
exceptions: {},
rules: {
foo: {
given: '$',
then: {
function: 'fn',
},
},
},
bar: {
given: '$',
then: {
function: 'fn-2',
bar: {
given: '$',
then: {
function: 'fn-2',
},
},
},
},
functions: {
fn: {
source: null,
name: 'fn',
schema: null,
code: `module.exports = function() {
functions: {
fn: {
source: null,
name: 'fn',
schema: null,
code: `module.exports = function() {
console.log(this.cache.get('test') || this.cache.set('test', []).get('test'));
}`,
},
'fn-2': {
source: null,
name: 'fn-2',
schema: null,
code: `module.exports = function() {
},
'fn-2': {
source: null,
name: 'fn-2',
schema: null,
code: `module.exports = function() {
console.log(this.cache.get('test') || this.cache.set('test', []).get('test'));
}`,
},
},
},
});
});

await spectral.run({});
await spectral.run({});

// verifies whether the 2 subsequent calls **DID NOT** pass the same cache instance as the first argument
expect(logSpy.mock.calls[0][0]).not.toBe(logSpy.mock.calls[1][0]);
// verifies whether the 2 subsequent calls **DID NOT** pass the same cache instance as the first argument
expect(logSpy.mock.calls[0][0]).not.toBe(logSpy.mock.calls[1][0]);

await spectral.run({});
await spectral.run({});

// verifies whether the 2 subsequent calls **DID NOT** pass the same cache instance as the first argument
expect(logSpy.mock.calls[2][0]).not.toBe(logSpy.mock.calls[3][0]);
// verifies whether the 2 subsequent calls **DID NOT** pass the same cache instance as the first argument
expect(logSpy.mock.calls[2][0]).not.toBe(logSpy.mock.calls[3][0]);

// verifies whether the 2 subsequent calls to the same function passe the same cache instance as the first argument
expect(logSpy.mock.calls[0][0]).toBe(logSpy.mock.calls[2][0]);
expect(logSpy.mock.calls[1][0]).toBe(logSpy.mock.calls[3][0]);
});
// verifies whether the 2 subsequent calls to the same function passe the same cache instance as the first argument
expect(logSpy.mock.calls[0][0]).toBe(logSpy.mock.calls[2][0]);
expect(logSpy.mock.calls[1][0]).toBe(logSpy.mock.calls[3][0]);
});

it('should support require calls', async () => {
await spectral.loadRuleset(customFunctionOASRuleset);
expect(
await spectral.run({
info: {},
paths: {},
}),
).toEqual([
expect.objectContaining({
code: 'has-bar-get-operation',
message: 'Object does not have undefined property',
path: ['paths'],
}),
]);
it('should support require calls', async () => {
await spectral.loadRuleset(customFunctionOASRuleset);
expect(
await spectral.run({
info: {},
paths: {},
}),
).toEqual([
expect.objectContaining({
code: 'has-bar-get-operation',
message: 'Object does not have undefined property',
path: ['paths'],
}),
]);
});

it('should be able to call any available function', async () => {
await spectral.loadRuleset(customDirectoryFunctionsRuleset);
expect(await spectral.run({ bar: 2 })).toEqual(
expect.arrayContaining([
expect.objectContaining({
code: 'validate-bar',
message: '`bar` property should be a string',
}),
]),
);
});

it('should be able to make a request using fetch', async () => {
const scope = nock('https://stoplight.io')
.get('/')
.once()
.reply(200);

spectral.setRuleset({
exceptions: {},
functions: {
fn: {
source: null,
schema: null,
name: 'fn',
code: `module.exports = () => void fetch('https://stoplight.io')`,
},
},
rules: {
empty: {
given: '$',
then: {
function: 'fn',
},
},
},
});

await spectral.run({});

expect(scope.isDone()).toBe(true);
});
});

it('should respect the scope of defined functions (ruleset-based)', async () => {
Expand All @@ -199,18 +246,6 @@ console.log(this.cache.get('test') || this.cache.set('test', []).get('test'));
]);
});

it('should expose all available functions to custom functions', async () => {
await spectral.loadRuleset(customDirectoryFunctionsRuleset);
expect(await spectral.run({ bar: 2 })).toEqual(
expect.arrayContaining([
expect.objectContaining({
code: 'validate-bar',
message: '`bar` property should be a string',
}),
]),
);
});

it('should report resolving errors for correct files', async () => {
spectral = new Spectral({ resolver: httpAndFileResolver });

Expand Down
49 changes: 49 additions & 0 deletions src/__tests__/linter.karma.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { FetchMockSandbox } from 'fetch-mock';
import { Spectral } from '../spectral';

describe('Linter', () => {
let fetchMock: FetchMockSandbox;
let spectral: Spectral;

beforeEach(() => {
fetchMock = require('fetch-mock').sandbox();
window.fetch = fetchMock;
spectral = new Spectral();
});

afterEach(() => {
window.fetch = fetch;
});

describe('custom functions', () => {
it('should be able to make a request using fetch', async () => {
fetchMock.mock('https://stoplight.io', {
nulltoken marked this conversation as resolved.
Show resolved Hide resolved
status: 200,
});

spectral.setRuleset({
exceptions: {},
functions: {
fn: {
source: null,
schema: null,
name: 'fn',
code: `module.exports = () => void fetch('https://stoplight.io')`,
},
},
rules: {
empty: {
given: '$',
then: {
function: 'fn',
},
},
},
});

await spectral.run({});

expect(fetchMock.calls('https://stoplight.io')).toHaveLength(1);
});
});
});
22 changes: 22 additions & 0 deletions src/rulesets/__tests__/evaluators.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,28 @@ describe('Code evaluators', () => {
expect(() => evaluateExport(`module.exports = 2`, null)).toThrow();
expect(() => evaluateExport(`this.returnExports = {}`, null)).toThrow();
});

describe('inject', () => {
it('can expose any arbitrary value', () => {
const fetch = jest.fn();
const url = 'https://foo.bar';
const fn = evaluateExport(`module.exports = () => fetch(url, { headers })`, null, {
fetch,
url,
headers: {
auth: 'Basic bar',
},
});

fn();

expect(fetch).toBeCalledWith(url, {
headers: {
auth: 'Basic bar',
},
});
});
});
});

describe('setFunctionContext', () => {
Expand Down
Loading