@friggframework/core 1.0.3-v1-alpha-package-update.5 → 1.0.3-v1-alpha-package-update.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/encrypt/encrypt.test.js +1 -1
- package/index.js +1 -7
- package/integrations/jest-setup.js +1 -1
- package/integrations/jest-teardown.js +1 -1
- package/logs/logger.test.js +1 -1
- package/module-plugin/jest-setup.js +1 -1
- package/module-plugin/jest-teardown.js +1 -1
- package/package.json +2 -12
- package/eslint-config/.eslintrc.json +0 -3
- package/eslint-config/CHANGELOG.md +0 -17
- package/eslint-config/LICENSE.md +0 -9
- package/eslint-config/README.md +0 -3
- package/eslint-config/bump3.txt +0 -0
- package/eslint-config/index.js +0 -38
- package/migrations/README.md +0 -3
- package/migrations/bump3.txt +0 -0
- package/migrations/index.js +0 -9
- package/migrations/jest.config.js +0 -3
- package/migrations/manager.js +0 -33
- package/migrations/migrator.js +0 -170
- package/migrations/options.js +0 -28
- package/prettier-config/.eslintrc.json +0 -3
- package/prettier-config/CHANGELOG.md +0 -17
- package/prettier-config/LICENSE.md +0 -9
- package/prettier-config/README.md +0 -3
- package/prettier-config/bump3.txt +0 -0
- package/prettier-config/index.js +0 -6
- package/test-environment/.eslintrc.json +0 -3
- package/test-environment/Authenticator.js +0 -73
- package/test-environment/CHANGELOG.md +0 -46
- package/test-environment/LICENSE.md +0 -9
- package/test-environment/README.md +0 -3
- package/test-environment/auther-definition-method-tester.js +0 -45
- package/test-environment/auther-definition-tester.js +0 -104
- package/test-environment/bump3.txt +0 -0
- package/test-environment/index.js +0 -24
- package/test-environment/integration-validator.js +0 -2
- package/test-environment/jest-global-setup.js +0 -6
- package/test-environment/jest-global-teardown.js +0 -3
- package/test-environment/jest-preset.js +0 -14
- package/test-environment/mock-api-readme.md +0 -102
- package/test-environment/mock-api.js +0 -284
- package/test-environment/mock-integration.js +0 -82
- package/test-environment/mongodb.js +0 -22
- package/test-environment/override-environment.js +0 -11
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
const {flushDebugLog} = require('../logs');
|
|
2
|
-
|
|
3
|
-
async function testDefinitionRequiredAuthMethods(api, definition, authCallbackParams, tokenResponse, userId) {
|
|
4
|
-
|
|
5
|
-
// const response = await definition.getToken(api, authCallbackParams);
|
|
6
|
-
// expect(api.setTokens).toHaveBeenCalled();
|
|
7
|
-
// if (tokenResponse) {
|
|
8
|
-
// expect(response).toMatchObject(tokenResponse);
|
|
9
|
-
// }
|
|
10
|
-
|
|
11
|
-
const entityDetails = await definition.requiredAuthMethods.getEntityDetails(api, authCallbackParams, tokenResponse, userId);
|
|
12
|
-
expect(entityDetails).toHaveProperty('identifiers');
|
|
13
|
-
expect(Object.values(entityDetails.identifiers).length).toBeGreaterThan(0);
|
|
14
|
-
for (const key of Object.keys(entityDetails.identifiers)){
|
|
15
|
-
expect(key).toBeDefined();
|
|
16
|
-
expect(entityDetails.identifiers[key]).toBeDefined();
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
const credentialDetails = await definition.requiredAuthMethods.getCredentialDetails(api);
|
|
21
|
-
expect(credentialDetails).toHaveProperty('identifiers');
|
|
22
|
-
expect(Object.values(entityDetails.identifiers).length).toBeGreaterThan(0);
|
|
23
|
-
for (const key of Object.keys(entityDetails.identifiers)){
|
|
24
|
-
expect(key).toBeDefined();
|
|
25
|
-
expect(entityDetails.identifiers[key]).toBeDefined();
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
const successResponse = await definition.requiredAuthMethods.testAuthRequest(api);
|
|
29
|
-
expect(successResponse).toBeTruthy();
|
|
30
|
-
const savedKeys = {};
|
|
31
|
-
for (const key of definition.requiredAuthMethods.apiPropertiesToPersist.credential){
|
|
32
|
-
savedKeys[key] = api[key];
|
|
33
|
-
delete api[key];
|
|
34
|
-
}
|
|
35
|
-
let validAuth = false;
|
|
36
|
-
try {
|
|
37
|
-
if (await definition.requiredAuthMethods.testAuthRequest(api)) validAuth = true;
|
|
38
|
-
} catch (e) {
|
|
39
|
-
flushDebugLog(e);
|
|
40
|
-
}
|
|
41
|
-
expect(validAuth).not.toBeTruthy();
|
|
42
|
-
Object.assign(api, savedKeys);
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
module.exports = { testDefinitionRequiredAuthMethods }
|
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
const {Auther, ModuleConstants} = require('../module-plugin');
|
|
2
|
-
const { createObjectId, connectToDatabase, disconnectFromDatabase } = require('../database/mongo');
|
|
3
|
-
const { createMockApiObject } = require("./mock-integration");
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
function testAutherDefinition(definition, mocks) {
|
|
7
|
-
const getModule = async (params) => {
|
|
8
|
-
const module = await Auther.getInstance({
|
|
9
|
-
definition,
|
|
10
|
-
userId: createObjectId(),
|
|
11
|
-
...params,
|
|
12
|
-
});
|
|
13
|
-
module.api = createMockApiObject(jest, module.api, mocks);
|
|
14
|
-
return module
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
describe(`${definition.moduleName} Module Tests`, () => {
|
|
19
|
-
let module, authUrl;
|
|
20
|
-
beforeAll(async () => {
|
|
21
|
-
await connectToDatabase();
|
|
22
|
-
module = await getModule();
|
|
23
|
-
});
|
|
24
|
-
|
|
25
|
-
afterAll(async () => {
|
|
26
|
-
await disconnectFromDatabase();
|
|
27
|
-
});
|
|
28
|
-
|
|
29
|
-
let requirements, authorizeParams;
|
|
30
|
-
if (definition.API.requesterType === ModuleConstants.authType.oauth2) {
|
|
31
|
-
authorizeParams = mocks.authorizeResponse;
|
|
32
|
-
describe('getAuthorizationRequirements() test', () => {
|
|
33
|
-
it('should return auth requirements', async () => {
|
|
34
|
-
requirements = module.getAuthorizationRequirements();
|
|
35
|
-
expect(requirements).toBeDefined();
|
|
36
|
-
expect(requirements.type).toEqual(ModuleConstants.authType.oauth2);
|
|
37
|
-
expect(requirements.url).toBeDefined();
|
|
38
|
-
authUrl = requirements.url;
|
|
39
|
-
});
|
|
40
|
-
});
|
|
41
|
-
} else if (definition.API.requesterType === ModuleConstants.authType.basic) {
|
|
42
|
-
// could also confirm authorizeParams against the auth requirements
|
|
43
|
-
authorizeParams = mocks.authorizeParams
|
|
44
|
-
describe('getAuthorizationRequirements() test', () => {
|
|
45
|
-
it('should return auth requirements', async () => {
|
|
46
|
-
requirements = module.getAuthorizationRequirements();
|
|
47
|
-
expect(requirements).toBeDefined();
|
|
48
|
-
expect(requirements.type).toEqual(ModuleConstants.authType.basic);
|
|
49
|
-
});
|
|
50
|
-
});
|
|
51
|
-
} else if (definition.API.requesterType === ModuleConstants.authType.apiKey) {
|
|
52
|
-
// could also confirm authorizeParams against the auth requirements
|
|
53
|
-
authorizeParams = mocks.authorizeParams
|
|
54
|
-
describe('getAuthorizationRequirements() test', () => {
|
|
55
|
-
it('should return auth requirements', async () => {
|
|
56
|
-
requirements = module.getAuthorizationRequirements();
|
|
57
|
-
expect(requirements).toBeDefined();
|
|
58
|
-
expect(requirements.type).toEqual(ModuleConstants.authType.apiKey);
|
|
59
|
-
});
|
|
60
|
-
});
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
describe('Authorization requests', () => {
|
|
64
|
-
let firstRes;
|
|
65
|
-
it('processAuthorizationCallback()', async () => {
|
|
66
|
-
firstRes = await module.processAuthorizationCallback(authorizeParams);
|
|
67
|
-
expect(firstRes).toBeDefined();
|
|
68
|
-
expect(firstRes.entity_id).toBeDefined();
|
|
69
|
-
expect(firstRes.credential_id).toBeDefined();
|
|
70
|
-
});
|
|
71
|
-
it('retrieves existing entity on subsequent calls', async () => {
|
|
72
|
-
const res = await module.processAuthorizationCallback(authorizeParams);
|
|
73
|
-
expect(res).toEqual(firstRes);
|
|
74
|
-
});
|
|
75
|
-
});
|
|
76
|
-
|
|
77
|
-
describe('Test credential retrieval and module instantiation', () => {
|
|
78
|
-
it('retrieve by entity id', async () => {
|
|
79
|
-
const newModule = await getModule({
|
|
80
|
-
userId: module.userId,
|
|
81
|
-
entityId: module.entity.id
|
|
82
|
-
});
|
|
83
|
-
expect(newModule).toBeDefined();
|
|
84
|
-
expect(newModule.entity).toBeDefined();
|
|
85
|
-
expect(newModule.credential).toBeDefined();
|
|
86
|
-
expect(await newModule.testAuth()).toBeTruthy();
|
|
87
|
-
|
|
88
|
-
});
|
|
89
|
-
|
|
90
|
-
it('retrieve by credential id', async () => {
|
|
91
|
-
const newModule = await getModule({
|
|
92
|
-
userId: module.userId,
|
|
93
|
-
credentialId: module.credential.id
|
|
94
|
-
});
|
|
95
|
-
expect(newModule).toBeDefined();
|
|
96
|
-
expect(newModule.credential).toBeDefined();
|
|
97
|
-
expect(await newModule.testAuth()).toBeTruthy();
|
|
98
|
-
});
|
|
99
|
-
});
|
|
100
|
-
});
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
module.exports = { testAutherDefinition }
|
|
104
|
-
|
|
File without changes
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
const { TestMongo } = require('./mongodb');
|
|
2
|
-
const {
|
|
3
|
-
overrideEnvironment,
|
|
4
|
-
restoreEnvironment,
|
|
5
|
-
} = require('./override-environment');
|
|
6
|
-
const globalTeardown = require('./jest-global-teardown');
|
|
7
|
-
const globalSetup = require('./jest-global-setup');
|
|
8
|
-
const {testDefinitionRequiredAuthMethods} = require('./auther-definition-method-tester');
|
|
9
|
-
const {createMockIntegration, createMockApiObject} = require('./mock-integration');
|
|
10
|
-
const { testAutherDefinition } = require('./auther-definition-tester');
|
|
11
|
-
const Authenticator = require('./Authenticator')
|
|
12
|
-
|
|
13
|
-
module.exports = {
|
|
14
|
-
TestMongo,
|
|
15
|
-
overrideEnvironment,
|
|
16
|
-
restoreEnvironment,
|
|
17
|
-
globalTeardown,
|
|
18
|
-
globalSetup,
|
|
19
|
-
createMockIntegration,
|
|
20
|
-
createMockApiObject,
|
|
21
|
-
testDefinitionRequiredAuthMethods,
|
|
22
|
-
testAutherDefinition,
|
|
23
|
-
Authenticator
|
|
24
|
-
};
|
|
@@ -1,102 +0,0 @@
|
|
|
1
|
-
# Mocked Requests Set Up for Your API Module
|
|
2
|
-
|
|
3
|
-
## Add Tooling to the Test File
|
|
4
|
-
|
|
5
|
-
Example code:
|
|
6
|
-
|
|
7
|
-
```js
|
|
8
|
-
const Api = require('./Api');
|
|
9
|
-
const { mockApi } = require('../../../../test/utils/mockApi');
|
|
10
|
-
|
|
11
|
-
const MockedApi = mockApi(Api, {
|
|
12
|
-
authenticationMode: 'browser',
|
|
13
|
-
});
|
|
14
|
-
|
|
15
|
-
describe('DemoNock API', async () => {
|
|
16
|
-
before(async function () {
|
|
17
|
-
await MockedApi.initialize({ test: this.test });
|
|
18
|
-
});
|
|
19
|
-
|
|
20
|
-
after(async function () {
|
|
21
|
-
await MockedApi.clean({ test: this.test });
|
|
22
|
-
});
|
|
23
|
-
|
|
24
|
-
it('tests a nice thing', async () => {
|
|
25
|
-
const api = await MockedApi.mock();
|
|
26
|
-
const users = await api.getUsers();
|
|
27
|
-
expect(users).to.have.length(2);
|
|
28
|
-
});
|
|
29
|
-
});
|
|
30
|
-
```
|
|
31
|
-
|
|
32
|
-
Api - the LH API class that is being tested/mocked
|
|
33
|
-
|
|
34
|
-
mockApi - tool to record/playback requests and automate login to API
|
|
35
|
-
|
|
36
|
-
MockedApi - Api class with wrapper around it to record/playback requests and automate login to API. `authenticationMode` sets how to handle authentication when recording requests. Browser means it will require a manual step in the browser (uses Authenticator). Client credentials mode gets a token automcaitcally with machine-to-machine token. Manual means the developer will handle authentication manually, like setting an API key. By default mockApi will use the class name of the mocked API to name the output file. This can be overidden by passing in `displayName`.
|
|
37
|
-
test/recorded-requests - the directory where recorded API requests are saved
|
|
38
|
-
|
|
39
|
-
before - make sure to use the `async function` form here, so we can access mocha's `this` object. The call to `initialize` sets up the tooling for recording/playback
|
|
40
|
-
|
|
41
|
-
after - same here need to use the `async function` form and pass in `this.test` to `clean`. This stops recording/playback and removes all hooks and other tooling from Node's HTTP code.
|
|
42
|
-
|
|
43
|
-
test - instead of using `new Api` in your tests, use `await MockedApi.mock`. Any parameters you would normally pass into `new Api` will be passed through with the call to `mock`. The instance of the Api class that is returned will already be authenticated (unless using manual mode).
|
|
44
|
-
|
|
45
|
-
## Creating new API tests
|
|
46
|
-
|
|
47
|
-
When running your tests while creating them, use `npm --record-apis=demonock test`.
|
|
48
|
-
|
|
49
|
-
This tells the tooling to record the requests made while running the tests for the DemoNockApi class.
|
|
50
|
-
|
|
51
|
-
## Finalizing API tests
|
|
52
|
-
|
|
53
|
-
When satisified with your tests, run `npm test` without adding the `--record-apis` flag to make sure the recorded requests worked. The tests should pass without needing you to perform a login step in the browser.
|
|
54
|
-
|
|
55
|
-
## Tests that fail...
|
|
56
|
-
|
|
57
|
-
Sometimes a "finished" test that was previously working starts to fail. Or, a test passes when it should fail (false negative). There are a few reasons this might happen.
|
|
58
|
-
|
|
59
|
-
### Test fails after code updates
|
|
60
|
-
|
|
61
|
-
If you made updates to the code, this may cause a test to fail. In this case the developer doesn't need to update mocks. To make the test pass, the updated code should be fixed, or the test should be updated to reflect the new data shape.
|
|
62
|
-
|
|
63
|
-
One way to test for this scenario is running `npm test` in the main branch, seeing that all tests pass, and then confirming tests fail in your feature branch. This would show that the test is almost certainly failing due to a change in your branch.
|
|
64
|
-
|
|
65
|
-
### Test should fail but passes
|
|
66
|
-
|
|
67
|
-
If a test is passing, but in the "real world" the code is failing, the API response may have changed. Re-record mocks by running tests with `--record-apis=nockdemo`. Hopefully, one or more tests will now fail. These tests and related code should be updated to work with the new API response data shape.
|
|
68
|
-
|
|
69
|
-
When creating the PR for this update, flag that the mocks were re-recorded so the updated mocks will be sure to be reviewed by another team member as part of code review.
|
|
70
|
-
|
|
71
|
-
### Mocks in error state
|
|
72
|
-
|
|
73
|
-
If the recorded files get messed up when updating (sometimes unavoidable under certain error conditions) just `git restore test/recorded-requests` or delete the file(s) in that directory and re-record.
|
|
74
|
-
|
|
75
|
-
## Miscellaneous Notes
|
|
76
|
-
|
|
77
|
-
More than one API can be set to record mode at a time: `npm --record-apis=activecampaign,hubspot test`
|
|
78
|
-
|
|
79
|
-
You can use .only when --record-apis is passed, but only for the root level test suite. Otherwise an error will be thrown to prevent partial recording of the mocks. .skip is fine to use to skip tests that should not be recorded.
|
|
80
|
-
|
|
81
|
-
CAN UPDATE RECORDED REQUESTS:
|
|
82
|
-
|
|
83
|
-
```js
|
|
84
|
-
describe('Nock Demo API', () => {
|
|
85
|
-
it('does x');
|
|
86
|
-
it.skip('does y');
|
|
87
|
-
});
|
|
88
|
-
```
|
|
89
|
-
|
|
90
|
-
CANNOT UPDATE RECORDED REQUESTS:
|
|
91
|
-
|
|
92
|
-
```js
|
|
93
|
-
describe('Nock Demo API', () => {
|
|
94
|
-
it('does x');
|
|
95
|
-
it('does y');
|
|
96
|
-
});
|
|
97
|
-
```
|
|
98
|
-
|
|
99
|
-
## Caveats
|
|
100
|
-
|
|
101
|
-
- Client credential mode may only work with Crossbeam currently
|
|
102
|
-
- Puppet mode (browser automation) for login is not yet implemented
|
|
@@ -1,284 +0,0 @@
|
|
|
1
|
-
const nock = require('nock');
|
|
2
|
-
const Authenticator = require('./Authenticator');
|
|
3
|
-
const { join: joinPath } = require('path');
|
|
4
|
-
const { parse: parseUrl } = require('url');
|
|
5
|
-
const { mkdir, readFile, rename, rm, writeFile } = require('fs/promises');
|
|
6
|
-
|
|
7
|
-
// TODO store in DB?
|
|
8
|
-
const tokenDirectory = joinPath(process.cwd(), 'test', '.token-cache');
|
|
9
|
-
const fixtureDirectory = joinPath(process.cwd(), 'test', 'recorded-requests');
|
|
10
|
-
nock.back.fixtures = fixtureDirectory;
|
|
11
|
-
|
|
12
|
-
// Try to rename but fail silently if the file does not exist.
|
|
13
|
-
const tryRename = async (a, b) => {
|
|
14
|
-
try {
|
|
15
|
-
await rename(a, b);
|
|
16
|
-
} catch (error) {
|
|
17
|
-
if (error.code === 'ENOENT') {
|
|
18
|
-
return;
|
|
19
|
-
}
|
|
20
|
-
throw error;
|
|
21
|
-
}
|
|
22
|
-
};
|
|
23
|
-
const getJestGlobalState = () => {
|
|
24
|
-
const globalSymbols = Object.getOwnPropertySymbols(global);
|
|
25
|
-
let jestState;
|
|
26
|
-
globalSymbols.forEach((sym) => {
|
|
27
|
-
if (sym.toString() === 'Symbol(JEST_STATE_SYMBOL)') {
|
|
28
|
-
jestState = global[sym];
|
|
29
|
-
}
|
|
30
|
-
});
|
|
31
|
-
|
|
32
|
-
return jestState;
|
|
33
|
-
};
|
|
34
|
-
|
|
35
|
-
const checkForOnlies = () => {
|
|
36
|
-
let didFindOnly = false;
|
|
37
|
-
const findOnly = (child) => {
|
|
38
|
-
if (child.mode === 'only') {
|
|
39
|
-
didFindOnly = true;
|
|
40
|
-
}
|
|
41
|
-
if (child.children) {
|
|
42
|
-
child.children.forEach((nestedChild) => {
|
|
43
|
-
findOnly(nestedChild);
|
|
44
|
-
});
|
|
45
|
-
}
|
|
46
|
-
};
|
|
47
|
-
const jestState = getJestGlobalState();
|
|
48
|
-
const rootDescribe = jestState.rootDescribeBlock;
|
|
49
|
-
|
|
50
|
-
for (const child of rootDescribe.children) {
|
|
51
|
-
findOnly(child);
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
return didFindOnly;
|
|
55
|
-
};
|
|
56
|
-
|
|
57
|
-
const mockApi = (Api, classOptionByName = {}) => {
|
|
58
|
-
const {
|
|
59
|
-
authenticationMode,
|
|
60
|
-
displayName = Api.name,
|
|
61
|
-
filteringScope,
|
|
62
|
-
} = classOptionByName;
|
|
63
|
-
// The tag is the lower case display name, with any trailing 'Api' in the string removed.
|
|
64
|
-
const tag = displayName.replace(/Api$/i, '').toLowerCase();
|
|
65
|
-
const tokenFile = `${displayName}.json`;
|
|
66
|
-
const tokenFileFullPath = joinPath(tokenDirectory, tokenFile);
|
|
67
|
-
|
|
68
|
-
return class MockedApi extends Api {
|
|
69
|
-
static name = `Mocked${displayName}`;
|
|
70
|
-
static tokenResponse = null;
|
|
71
|
-
static excludedRecordingPaths = [];
|
|
72
|
-
static #context = {};
|
|
73
|
-
|
|
74
|
-
static async initialize() {
|
|
75
|
-
this.#context = {};
|
|
76
|
-
|
|
77
|
-
const didFindOnlies = checkForOnlies();
|
|
78
|
-
|
|
79
|
-
if (didFindOnlies) {
|
|
80
|
-
throw new Error(
|
|
81
|
-
'Cancelled recording API mocks because some tests were marked `.only`. Please remove any `.only`s from any `describe` blocks deeper than the root level, and all `it` blocks.'
|
|
82
|
-
);
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
this.#context.originalNockMode = nock.back.currentMode;
|
|
86
|
-
|
|
87
|
-
const { npm_config_record_apis: apisToRecordText = '' } =
|
|
88
|
-
process.env;
|
|
89
|
-
const apisToRecord = apisToRecordText
|
|
90
|
-
.split(',')
|
|
91
|
-
.map((name) => name.trim().toLowerCase());
|
|
92
|
-
|
|
93
|
-
if (apisToRecord.includes(tag)) {
|
|
94
|
-
this.#context.nockMode = 'update';
|
|
95
|
-
} else {
|
|
96
|
-
this.#context.nockMode = 'lockdown';
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
nock.back.setMode(this.#context.nockMode);
|
|
100
|
-
|
|
101
|
-
const fixtureFile = `${displayName}.json`;
|
|
102
|
-
|
|
103
|
-
if (this.#context.nockMode === 'update') {
|
|
104
|
-
const fixtureFileFullPath = joinPath(
|
|
105
|
-
fixtureDirectory,
|
|
106
|
-
fixtureFile
|
|
107
|
-
);
|
|
108
|
-
const fixtureFileBackupFullPath = joinPath(
|
|
109
|
-
fixtureDirectory,
|
|
110
|
-
`.${displayName}.json.backup`
|
|
111
|
-
);
|
|
112
|
-
|
|
113
|
-
await tryRename(fixtureFileFullPath, fixtureFileBackupFullPath);
|
|
114
|
-
|
|
115
|
-
this.#context.restoreFixture = async () =>
|
|
116
|
-
await tryRename(
|
|
117
|
-
fixtureFileBackupFullPath,
|
|
118
|
-
fixtureFileFullPath
|
|
119
|
-
);
|
|
120
|
-
this.#context.deleteFixtureBackup = async () =>
|
|
121
|
-
await rm(fixtureFileBackupFullPath, { force: true });
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
const nockBack = await nock.back(fixtureFile, {
|
|
125
|
-
before: (scope) => {
|
|
126
|
-
if (filteringScope) {
|
|
127
|
-
scope.options.filteringScope = filteringScope;
|
|
128
|
-
}
|
|
129
|
-
},
|
|
130
|
-
// Filter out token URLs
|
|
131
|
-
afterRecord: (recordings) =>
|
|
132
|
-
recordings.filter(
|
|
133
|
-
({ path }) =>
|
|
134
|
-
!this.excludedRecordingPaths.includes(path)
|
|
135
|
-
),
|
|
136
|
-
recorder: {
|
|
137
|
-
output_objects: true,
|
|
138
|
-
enable_reqheaders_recording: false,
|
|
139
|
-
},
|
|
140
|
-
});
|
|
141
|
-
|
|
142
|
-
this.#context.assertAllRequests = () =>
|
|
143
|
-
nockBack.context.assertScopesFinished();
|
|
144
|
-
this.#context.done = () => nockBack.nockDone();
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
static async clean() {
|
|
148
|
-
const {
|
|
149
|
-
assertAllRequests,
|
|
150
|
-
done,
|
|
151
|
-
nockMode,
|
|
152
|
-
originalNockMode,
|
|
153
|
-
restoreFixture,
|
|
154
|
-
deleteFixtureBackup,
|
|
155
|
-
} = this.#context;
|
|
156
|
-
|
|
157
|
-
const { didAllTestsPass } = global.mockApiResults;
|
|
158
|
-
|
|
159
|
-
if (done) {
|
|
160
|
-
done();
|
|
161
|
-
}
|
|
162
|
-
if (originalNockMode) {
|
|
163
|
-
nock.back.setMode(originalNockMode);
|
|
164
|
-
}
|
|
165
|
-
if (assertAllRequests && nockMode !== 'update') {
|
|
166
|
-
assertAllRequests();
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
nock.cleanAll();
|
|
170
|
-
nock.restore();
|
|
171
|
-
|
|
172
|
-
if (nockMode === 'update') {
|
|
173
|
-
if (!didAllTestsPass) {
|
|
174
|
-
try {
|
|
175
|
-
await restoreFixture();
|
|
176
|
-
} finally {
|
|
177
|
-
throw new Error(
|
|
178
|
-
'Cancelled recording API mocks because some tests failed. Please fix the failing tests and try to record again.'
|
|
179
|
-
);
|
|
180
|
-
}
|
|
181
|
-
} else {
|
|
182
|
-
await deleteFixtureBackup();
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
static async saveCachedTokenResponse() {
|
|
188
|
-
if (!this.tokenResponse) {
|
|
189
|
-
return;
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
await mkdir(tokenDirectory, { recursive: true });
|
|
193
|
-
await writeFile(
|
|
194
|
-
tokenFileFullPath,
|
|
195
|
-
JSON.stringify(this.tokenResponse)
|
|
196
|
-
);
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
static async loadCachedTokenResponse() {
|
|
200
|
-
try {
|
|
201
|
-
const tokenResponseText = await readFile(tokenFileFullPath);
|
|
202
|
-
this.tokenResponse = JSON.parse(tokenResponseText);
|
|
203
|
-
} catch (error) {
|
|
204
|
-
if (error.code === 'ENOENT') {
|
|
205
|
-
this.tokenResponse = null;
|
|
206
|
-
return;
|
|
207
|
-
}
|
|
208
|
-
throw error;
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
static async mock(...constructorParameters) {
|
|
213
|
-
const api = new this(...constructorParameters);
|
|
214
|
-
|
|
215
|
-
if (nock.back.currentMode !== 'lockdown') {
|
|
216
|
-
await this.loadCachedTokenResponse();
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
// TODO read authentication mode from module package
|
|
220
|
-
if (authenticationMode === 'client_credentials') {
|
|
221
|
-
// TODO make generic (tied to crossbeam api)
|
|
222
|
-
api.grantType = 'client_credentials';
|
|
223
|
-
api.refreshAccessToken = api.getTokenFromClientCredentials;
|
|
224
|
-
|
|
225
|
-
if (process.env.CROSSBEAM_API_BASE_URL)
|
|
226
|
-
api.baseUrl = process.env.CROSSBEAM_API_BASE_URL;
|
|
227
|
-
if (process.env.CROSSBEAM_API_AUTH_URL)
|
|
228
|
-
api.tokenUri = `${process.env.CROSSBEAM_API_AUTH_URL}/oauth/token`;
|
|
229
|
-
if (process.env.CROSSBEAM_API_AUDIENCE)
|
|
230
|
-
api.audience = process.env.CROSSBEAM_API_AUDIENCE;
|
|
231
|
-
|
|
232
|
-
api.client_secret = process.env.CROSSBEAM_TEST_CLIENT_SECRET;
|
|
233
|
-
api.client_id = process.env.CROSSBEAM_TEST_CLIENT_ID;
|
|
234
|
-
api.refreshAccessToken = api.getTokenFromClientCredentials;
|
|
235
|
-
|
|
236
|
-
this.tokenResponse = await api.getTokenFromClientCredentials();
|
|
237
|
-
} else if (authenticationMode === 'puppet') {
|
|
238
|
-
throw new Error('Not yet implemented');
|
|
239
|
-
} else if (authenticationMode === 'browser') {
|
|
240
|
-
if (nock.back.currentMode !== 'lockdown') {
|
|
241
|
-
const { path: tokenPath } = parseUrl(api.tokenUri);
|
|
242
|
-
this.excludedRecordingPaths.push(tokenPath);
|
|
243
|
-
|
|
244
|
-
if (this.tokenResponse) {
|
|
245
|
-
await api.setTokens(this.tokenResponse);
|
|
246
|
-
|
|
247
|
-
try {
|
|
248
|
-
await api.testAuth();
|
|
249
|
-
} catch {
|
|
250
|
-
this.tokenResponse = null;
|
|
251
|
-
nock.cleanAll();
|
|
252
|
-
await rm(tokenFileFullPath, {
|
|
253
|
-
force: true,
|
|
254
|
-
});
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
if (!this.tokenResponse) {
|
|
259
|
-
const url = api.authorizationUri;
|
|
260
|
-
const { data } = await Authenticator.oauth2(url);
|
|
261
|
-
const { code } = data;
|
|
262
|
-
this.tokenResponse = await api.getTokenFromCode(code);
|
|
263
|
-
await api.setTokens(this.tokenResponse);
|
|
264
|
-
nock.cleanAll();
|
|
265
|
-
}
|
|
266
|
-
}
|
|
267
|
-
} else if (authenticationMode === 'manual') {
|
|
268
|
-
// NOOP. This space intentionally left blank. No action should be performed in this mode, and the developer writing the test will handle authentication externally to this module.
|
|
269
|
-
} else {
|
|
270
|
-
throw new Error(
|
|
271
|
-
'Unrecognized authentication mode for mocked API.'
|
|
272
|
-
);
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
if (nock.back.currentMode !== 'lockdown') {
|
|
276
|
-
await this.saveCachedTokenResponse();
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
return api;
|
|
280
|
-
}
|
|
281
|
-
};
|
|
282
|
-
};
|
|
283
|
-
|
|
284
|
-
module.exports = { mockApi };
|
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
const { Auther, Credential, Entity } = require('../module-plugin');
|
|
2
|
-
const { IntegrationModel } = require('../integrations');
|
|
3
|
-
const { mongoose } = require('../database/mongoose');
|
|
4
|
-
|
|
5
|
-
async function createMockIntegration(IntegrationClassDef, userId = null, config = {},) {
|
|
6
|
-
const integration = new IntegrationClassDef();
|
|
7
|
-
userId = userId || new mongoose.Types.ObjectId();
|
|
8
|
-
integration.delegateTypes.push(...IntegrationClassDef.Config.events)
|
|
9
|
-
|
|
10
|
-
const insertOptions = {
|
|
11
|
-
new: true,
|
|
12
|
-
upsert: true,
|
|
13
|
-
setDefaultsOnInsert: true,
|
|
14
|
-
}
|
|
15
|
-
const user = {user: userId}
|
|
16
|
-
|
|
17
|
-
const credential = await Credential.findOneAndUpdate(
|
|
18
|
-
user,
|
|
19
|
-
{ $set: user },
|
|
20
|
-
insertOptions
|
|
21
|
-
);
|
|
22
|
-
const entity1 = await Entity.findOneAndUpdate(
|
|
23
|
-
user,
|
|
24
|
-
{
|
|
25
|
-
$set: {
|
|
26
|
-
credential: credential.id,
|
|
27
|
-
user: userId,
|
|
28
|
-
name: 'Test user',
|
|
29
|
-
externalId: '1234567890123456',
|
|
30
|
-
},
|
|
31
|
-
},
|
|
32
|
-
insertOptions
|
|
33
|
-
);
|
|
34
|
-
const entity2 = await Entity.findOneAndUpdate(
|
|
35
|
-
user,
|
|
36
|
-
{
|
|
37
|
-
$set: {
|
|
38
|
-
credential: credential.id,
|
|
39
|
-
user: userId,
|
|
40
|
-
},
|
|
41
|
-
},
|
|
42
|
-
insertOptions
|
|
43
|
-
);
|
|
44
|
-
|
|
45
|
-
const entities = [entity1, entity2]
|
|
46
|
-
integration.record = await IntegrationModel.create({
|
|
47
|
-
entities,
|
|
48
|
-
user: userId,
|
|
49
|
-
config: {type: IntegrationClassDef.Config.name, ...config}
|
|
50
|
-
})
|
|
51
|
-
|
|
52
|
-
integration.id = integration.record._id
|
|
53
|
-
|
|
54
|
-
for (const i in entities){
|
|
55
|
-
const [moduleName, ModuleDef] = Object.entries(IntegrationClassDef.modules)[i];
|
|
56
|
-
const module = Auther.getInstance({definition: ModuleDef, userId: userId})
|
|
57
|
-
module.entity = entities[i];
|
|
58
|
-
integration[moduleName] = module;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
return integration
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
function createMockApiObject(jest, api = {}, mockMethodMap) {
|
|
65
|
-
// take in an api class and object with keys that are method names
|
|
66
|
-
// and values which are the mock response (or implementation)
|
|
67
|
-
const clone = (data) => JSON.parse(JSON.stringify(data));
|
|
68
|
-
|
|
69
|
-
for (const [methodName, mockDataOrImplementation] of Object.entries(mockMethodMap)) {
|
|
70
|
-
if (mockDataOrImplementation instanceof Function) {
|
|
71
|
-
api[methodName] = jest.fn(mockDataOrImplementation);
|
|
72
|
-
}
|
|
73
|
-
else if (api[methodName]?.constructor?.name === "AsyncFunction") {
|
|
74
|
-
api[methodName] = jest.fn().mockResolvedValue(clone(mockDataOrImplementation));
|
|
75
|
-
} else {
|
|
76
|
-
api[methodName] = jest.fn().mockReturnValue(clone(mockDataOrImplementation));
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
return api;
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
module.exports = {createMockIntegration, createMockApiObject};
|