@friggframework/devtools 1.1.1-canary.282.4de1ac1.0 → 1.2.0-canary.293.50b9cd8.0

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/index.js CHANGED
@@ -1,5 +1,5 @@
1
- const eslintConfig = require('./eslint-config')
2
- const prettierConfig = require('./prettier-config')
1
+ const eslintConfig = require('../../../utils/eslint-config')
2
+ const prettierConfig = require('../../../utils/prettier-config')
3
3
  const testEnvironment = require('./test-environment/index');
4
4
 
5
5
  module.exports = {
package/package.json CHANGED
@@ -1,10 +1,9 @@
1
1
  {
2
2
  "name": "@friggframework/devtools",
3
3
  "prettier": "@friggframework/prettier-config",
4
- "version": "1.1.1-canary.282.4de1ac1.0",
4
+ "version": "1.2.0-canary.293.50b9cd8.0",
5
5
  "dependencies": {
6
6
  "@babel/eslint-parser": "^7.18.9",
7
- "@friggframework/core": "1.1.1-canary.282.4de1ac1.0",
8
7
  "eslint": "^8.22.0",
9
8
  "eslint-config-prettier": "^8.5.0",
10
9
  "eslint-plugin-json": "^3.1.0",
@@ -15,6 +14,7 @@
15
14
  "mongodb-memory-server": "^8.9.0"
16
15
  },
17
16
  "devDependencies": {
17
+ "@friggframework/core": "1.2.0-canary.293.50b9cd8.0",
18
18
  "jest": "^28.1.3",
19
19
  "prettier": "^2.7.1"
20
20
  },
@@ -37,5 +37,5 @@
37
37
  "publishConfig": {
38
38
  "access": "public"
39
39
  },
40
- "gitHead": "4de1ac138121295b795e1e9e0bb9e37bea2e8492"
40
+ "gitHead": "50b9cd8324cb94af601837fcd4661276613ecd47"
41
41
  }
@@ -1,11 +1,7 @@
1
- const {
2
- Auther,
3
- ModuleConstants,
4
- createObjectId,
5
- connectToDatabase,
6
- disconnectFromDatabase,
7
- } = require('@friggframework/core');
8
- const { createMockApiObject } = require("./mock-integration");
1
+ const { Auther } = require('@friggframework/core/module-plugin/auther');
2
+ const { ModuleConstants } = require('@friggframework/core/module-plugin/ModuleConstants');
3
+ const { createObjectId,connectToDatabase, disconnectFromDatabase } = require('@friggframework/core/database');
4
+ const { createMockApiObject } = require("@friggframework/devtools/test-environment/mock-integration");
9
5
 
10
6
 
11
7
  function testAutherDefinition(definition, mocks) {
@@ -1,24 +1,25 @@
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');
1
+ const Authenticator = require('@friggframework/devtools/test/Authenticator')
2
+ const { createMockIntegration, createMockApiObject } = require('mock-integration');
10
3
  const { testAutherDefinition } = require('./auther-definition-tester');
11
- const Authenticator = require('./Authenticator')
12
-
13
- module.exports = {
4
+ const { testDefinitionRequiredAuthMethods } = require('./auther-definition-method-tester');
5
+ const { } = require('./../../utils/test-environment');
6
+ const {
14
7
  TestMongo,
15
8
  overrideEnvironment,
16
9
  restoreEnvironment,
17
10
  globalTeardown,
18
11
  globalSetup,
12
+ } = require('./../../../utils/test-environment');
13
+
14
+ module.exports = {
19
15
  createMockIntegration,
20
16
  createMockApiObject,
21
17
  testDefinitionRequiredAuthMethods,
22
18
  testAutherDefinition,
23
- Authenticator
19
+ Authenticator,
20
+ TestMongo,
21
+ overrideEnvironment,
22
+ restoreEnvironment,
23
+ globalTeardown,
24
+ globalSetup,
24
25
  };
@@ -1,9 +1,8 @@
1
- const { Auther, Credential, Entity, IntegrationModel, mongoose } = require('@friggframework/core');
2
-
1
+ const { Auther, Credential, Entity, IntegrationModel, createObjectId } = require('@friggframework/core')
3
2
 
4
3
  async function createMockIntegration(IntegrationClassDef, userId = null, config = {},) {
5
4
  const integration = new IntegrationClassDef();
6
- userId = userId || new mongoose.Types.ObjectId();
5
+ userId = userId || createObjectId();
7
6
  integration.delegateTypes.push(...IntegrationClassDef.Config.events)
8
7
 
9
8
  const insertOptions = {
@@ -51,8 +50,9 @@ async function createMockIntegration(IntegrationClassDef, userId = null, config
51
50
  integration.id = integration.record._id
52
51
 
53
52
  for (const i in entities){
53
+ if (Object.entries(IntegrationClassDef.modules).length <= i) break
54
54
  const [moduleName, ModuleDef] = Object.entries(IntegrationClassDef.modules)[i];
55
- const module = Auther.getInstance({definition: ModuleDef, userId: userId})
55
+ const module = await Auther.getInstance({definition: ModuleDef, userId: userId})
56
56
  module.entity = entities[i];
57
57
  integration[moduleName] = module;
58
58
  }
@@ -1,3 +0,0 @@
1
- {
2
- "extends": "@friggframework/eslint-config"
3
- }
@@ -1,17 +0,0 @@
1
- # v1.0.8 (Mon Jan 09 2023)
2
-
3
- #### 🐛 Bug Fix
4
-
5
- - Merge remote-tracking branch 'origin/main' into gitbook-updates [#48](https://github.com/friggframework/frigg/pull/48) ([@seanspeaks](https://github.com/seanspeaks))
6
- - Bump independent versions \[skip ci\] ([@seanspeaks](https://github.com/seanspeaks))
7
- - Merge remote-tracking branch 'origin/main' into simplify-mongoose-models ([@seanspeaks](https://github.com/seanspeaks))
8
- - Add READMEs for all packages and api-modules [#20](https://github.com/friggframework/frigg/pull/20) ([@seanspeaks](https://github.com/seanspeaks))
9
- - Add READMEs for all packages and api-modules ([@seanspeaks](https://github.com/seanspeaks))
10
-
11
- #### ⚠️ Pushed to `main`
12
-
13
- - Refactored for more conventional naming (at least for packages) ([@seanspeaks](https://github.com/seanspeaks))
14
-
15
- #### Authors: 1
16
-
17
- - Sean Matthews ([@seanspeaks](https://github.com/seanspeaks))
@@ -1,9 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2022 Left Hook Inc.
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
-
7
- The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.
8
-
9
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -1,3 +0,0 @@
1
- # eslint-config
2
-
3
- This package exports the default `eslint-config` settings used in [Frigg](https://friggframework.org). You can find its documentation [on Frigg's website](https://docs.friggframework.org/packages/eslint-config).
File without changes
@@ -1,38 +0,0 @@
1
- module.exports = {
2
- env: {
3
- commonjs: true,
4
- es2020: true,
5
- jest: true,
6
- },
7
- extends: ['prettier', 'plugin:markdown/recommended'],
8
- parser: '@babel/eslint-parser',
9
- parserOptions: {
10
- ecmaVersion: 11,
11
- requireConfigFile: false,
12
- },
13
- plugins: ['no-only-tests'],
14
- ignorePatterns: ['coverage/', '.nyc_output/'],
15
- overrides: [
16
- {
17
- files: ['*.json'],
18
- plugins: ['json'],
19
- extends: ['plugin:json/recommended'],
20
- },
21
- {
22
- files: ['*.yaml', '*.yml'],
23
- plugins: ['yaml'],
24
- extends: ['plugin:yaml/recommended'],
25
- },
26
- ],
27
- rules: {
28
- 'no-only-tests/no-only-tests': ['error', { fix: false }],
29
- 'no-unused-vars': [
30
- 'warn',
31
- { vars: 'all', args: 'after-used', ignoreRestSiblings: false },
32
- ],
33
- 'no-console': ['warn'],
34
- camelcase: ['warn'],
35
- 'no-mixed-requires': ['warn'],
36
- 'no-warning-comments': ['warn'],
37
- },
38
- };
@@ -1,3 +0,0 @@
1
- {
2
- "extends": "@friggframework/eslint-config"
3
- }
@@ -1,17 +0,0 @@
1
- # v1.0.6 (Mon Jan 09 2023)
2
-
3
- #### 🐛 Bug Fix
4
-
5
- - Merge remote-tracking branch 'origin/main' into gitbook-updates [#48](https://github.com/friggframework/frigg/pull/48) ([@seanspeaks](https://github.com/seanspeaks))
6
- - Bump independent versions \[skip ci\] ([@seanspeaks](https://github.com/seanspeaks))
7
- - Merge remote-tracking branch 'origin/main' into simplify-mongoose-models ([@seanspeaks](https://github.com/seanspeaks))
8
- - Add READMEs for all packages and api-modules [#20](https://github.com/friggframework/frigg/pull/20) ([@seanspeaks](https://github.com/seanspeaks))
9
- - Add READMEs for all packages and api-modules ([@seanspeaks](https://github.com/seanspeaks))
10
-
11
- #### ⚠️ Pushed to `main`
12
-
13
- - Refactored for more conventional naming (at least for packages) ([@seanspeaks](https://github.com/seanspeaks))
14
-
15
- #### Authors: 1
16
-
17
- - Sean Matthews ([@seanspeaks](https://github.com/seanspeaks))
@@ -1,9 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2022 Left Hook Inc.
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
-
7
- The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.
8
-
9
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -1,3 +0,0 @@
1
- # prettier-config
2
-
3
- This package exports the `prettier-config` default used in [Frigg](https://friggframework.org). You can find its documentation [on Frigg's website](https://docs.friggframework.org/packages/prettier-config).
File without changes
@@ -1,6 +0,0 @@
1
- module.exports = {
2
- semi: true,
3
- tabWidth: 4,
4
- singleQuote: true,
5
- useTabs: false,
6
- };
@@ -1,3 +0,0 @@
1
- {
2
- "extends": "@friggframework/eslint-config"
3
- }
@@ -1,46 +0,0 @@
1
- # v1.1.6 (Tue Jan 31 2023)
2
-
3
- #### 🐛 Bug Fix
4
-
5
- - Updates/api module yotpo [#108](https://github.com/friggframework/frigg/pull/108) ([@seanspeaks](https://github.com/seanspeaks))
6
- - # mock-api.js Work in Progress ([@seanspeaks](https://github.com/seanspeaks))
7
- - Bump independent versions \[skip ci\] ([@seanspeaks](https://github.com/seanspeaks))
8
-
9
- #### Authors: 1
10
-
11
- - Sean Matthews ([@seanspeaks](https://github.com/seanspeaks))
12
-
13
- ---
14
-
15
- # v1.1.5 (Mon Jan 09 2023)
16
-
17
- #### 🐛 Bug Fix
18
-
19
- - Merge remote-tracking branch 'origin/main' into gitbook-updates [#48](https://github.com/friggframework/frigg/pull/48) ([@seanspeaks](https://github.com/seanspeaks))
20
- - Bump independent versions \[skip ci\] ([@seanspeaks](https://github.com/seanspeaks))
21
- - Merge remote-tracking branch 'origin/main' into simplify-mongoose-models ([@seanspeaks](https://github.com/seanspeaks))
22
- - Add READMEs for all packages and api-modules [#20](https://github.com/friggframework/frigg/pull/20) ([@seanspeaks](https://github.com/seanspeaks))
23
- - Add READMEs for all packages and api-modules ([@seanspeaks](https://github.com/seanspeaks))
24
-
25
- #### ⚠️ Pushed to `main`
26
-
27
- - Merge branch 'main' into gitbook-updates ([@seanspeaks](https://github.com/seanspeaks))
28
- - Refactored for more conventional naming (at least for packages) ([@seanspeaks](https://github.com/seanspeaks))
29
-
30
- #### Authors: 1
31
-
32
- - Sean Matthews ([@seanspeaks](https://github.com/seanspeaks))
33
-
34
- ---
35
-
36
- # v1.1.4 (Mon Sep 19 2022)
37
-
38
- #### 🐛 Bug Fix
39
-
40
- - Test environment setup for all modules [#49](https://github.com/friggframework/frigg/pull/49) ([@seanspeaks](https://github.com/seanspeaks))
41
- - Test environment setup for all modules ([@seanspeaks](https://github.com/seanspeaks))
42
- - Merge remote-tracking branch 'origin/main' into gitbook-updates [#48](https://github.com/friggframework/frigg/pull/48) ([@seanspeaks](https://github.com/seanspeaks))
43
-
44
- #### Authors: 1
45
-
46
- - Sean Matthews ([@seanspeaks](https://github.com/seanspeaks))
@@ -1,9 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2022 Left Hook Inc.
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
-
7
- The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.
8
-
9
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -1,3 +0,0 @@
1
- # test-environment
2
-
3
- This package exports the `test-environment` defaults used in [Frigg](https://friggframework.org). You can find its documentation [on Frigg's website](https://docs.friggframework.org/packages/test-environment).
File without changes
@@ -1,8 +0,0 @@
1
- const { TestMongo } = require('./mongodb');
2
- const { overrideEnvironment} = require('./override-environment');
3
-
4
- module.exports = async function () {
5
- overrideEnvironment({ STAGE: 'dev'})
6
- global.testMongo = new TestMongo();
7
- await global.testMongo.start();
8
- };
@@ -1,5 +0,0 @@
1
- const { restoreEnvironment } = require('./override-environment');
2
- module.exports = async function () {
3
- restoreEnvironment();
4
- await global.testMongo.stop();
5
- };
@@ -1,14 +0,0 @@
1
- module.exports = {
2
- collectCoverage: true,
3
- testTimeout: 20_000,
4
- runner: 'groups',
5
- coverageReporters: ['text'],
6
- coverageThreshold: {
7
- global: {
8
- statements: 80,
9
- branches: 80,
10
- functions: 80,
11
- lines: 80,
12
- },
13
- },
14
- };
@@ -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,22 +0,0 @@
1
- const { MongoMemoryServer } = require('mongodb-memory-server');
2
-
3
- class TestMongo {
4
- #mongoServer;
5
-
6
- // Start the in-memory mongo instance and set env variable for the app to use in its connection.
7
- async start() {
8
- this.#mongoServer = await MongoMemoryServer.create();
9
- process.env.MONGO_URI = this.#mongoServer.getUri();
10
- console.log('Started in memory mongo server', process.env.MONGO_URI);
11
- }
12
-
13
- async stop() {
14
- await this.#mongoServer.stop();
15
- process.env.MONGO_URI = undefined;
16
- this.#mongoServer = undefined;
17
- }
18
- }
19
-
20
- module.exports = {
21
- TestMongo,
22
- };
@@ -1,11 +0,0 @@
1
- const originalEnv = process.env;
2
-
3
- function overrideEnvironment(overrideByKey) {
4
- process.env = { ...process.env, ...overrideByKey };
5
- }
6
-
7
- function restoreEnvironment() {
8
- process.env = originalEnv;
9
- }
10
-
11
- module.exports = { overrideEnvironment, restoreEnvironment };