@eggjs/mock 7.0.0-beta.20 → 7.0.0-beta.22

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.
Files changed (96) hide show
  1. package/dist/app/extend/agent.d.ts +33 -38
  2. package/dist/app/extend/agent.js +46 -5
  3. package/dist/app/extend/application.d.ts +171 -5
  4. package/dist/app/extend/application.js +445 -9
  5. package/dist/app/middleware/cluster_app_mock.d.ts +2 -5
  6. package/dist/app/middleware/cluster_app_mock.js +99 -96
  7. package/dist/app.d.ts +5 -9
  8. package/dist/app.js +18 -17
  9. package/dist/bootstrap.d.ts +5 -15
  10. package/dist/bootstrap.js +13 -29
  11. package/dist/index.d.ts +77 -10
  12. package/dist/index.js +90 -22
  13. package/dist/inject_mocha.d.ts +1 -1
  14. package/dist/inject_mocha.js +35 -23
  15. package/dist/lib/agent_handler.d.ts +3 -10
  16. package/dist/lib/agent_handler.js +24 -9
  17. package/dist/lib/app.d.ts +3 -6
  18. package/dist/lib/app.js +291 -14
  19. package/dist/lib/app_handler.d.ts +5 -6
  20. package/dist/lib/app_handler.js +69 -21
  21. package/dist/lib/cluster.d.ts +121 -6
  22. package/dist/lib/cluster.js +340 -7
  23. package/dist/lib/context.d.ts +1 -4
  24. package/dist/lib/context.js +11 -3
  25. package/dist/lib/format_options.d.ts +2 -7
  26. package/dist/lib/format_options.js +93 -4
  27. package/dist/lib/inject_context.d.ts +1 -4
  28. package/dist/lib/inject_context.js +126 -22
  29. package/dist/lib/mock_agent.d.ts +4 -8
  30. package/dist/lib/mock_agent.js +45 -3
  31. package/dist/lib/mock_custom_loader.d.ts +1 -4
  32. package/dist/lib/mock_custom_loader.js +34 -3
  33. package/dist/lib/mock_http_server.d.ts +2 -6
  34. package/dist/lib/mock_http_server.js +18 -3
  35. package/dist/lib/mock_httpclient.d.ts +36 -2
  36. package/dist/lib/mock_httpclient.js +146 -4
  37. package/dist/lib/parallel/agent.d.ts +20 -5
  38. package/dist/lib/parallel/agent.js +117 -8
  39. package/dist/lib/parallel/app.d.ts +19 -24
  40. package/dist/lib/parallel/app.js +111 -9
  41. package/dist/lib/parallel/util.d.ts +3 -2
  42. package/dist/lib/parallel/util.js +66 -4
  43. package/dist/lib/prerequire.d.ts +1 -1
  44. package/dist/lib/prerequire.js +25 -1
  45. package/dist/lib/request_call_function.d.ts +1 -1
  46. package/dist/lib/request_call_function.js +47 -34
  47. package/dist/lib/restore.d.ts +1 -2
  48. package/dist/lib/restore.js +13 -9
  49. package/dist/lib/start-cluster.d.ts +2 -1
  50. package/dist/lib/start-cluster.js +14 -15
  51. package/dist/lib/supertest.d.ts +11 -2
  52. package/dist/lib/supertest.js +40 -5
  53. package/dist/lib/tmp/empty.d.ts +1 -1
  54. package/dist/lib/tmp/empty.js +2 -1
  55. package/dist/lib/types.d.ts +72 -3
  56. package/dist/lib/types.js +2 -3
  57. package/dist/lib/utils.d.ts +8 -11
  58. package/dist/lib/utils.js +69 -3
  59. package/dist/register.d.ts +7 -11
  60. package/dist/register.js +41 -55
  61. package/package.json +7 -7
  62. package/dist/agent-BKYkjoCx.js +0 -111
  63. package/dist/agent-CHCe8tnW.d.ts +0 -24
  64. package/dist/agent-DZ_fHoxJ.js +0 -48
  65. package/dist/agent_handler-DeUtoRVT.js +0 -26
  66. package/dist/app-6Bn3F5Uw.js +0 -252
  67. package/dist/app-CoypamK1.js +0 -99
  68. package/dist/app-l47a-gqT.d.ts +0 -7
  69. package/dist/app_handler-CkiK6fyC.js +0 -55
  70. package/dist/app_handler-Gp5J9X-v.d.ts +0 -9
  71. package/dist/application-BPpvw5dg.d.ts +0 -175
  72. package/dist/application-LrKwuOKn.js +0 -385
  73. package/dist/cluster-CA_hr9eV.js +0 -283
  74. package/dist/cluster-RTfUwmUd.d.ts +0 -126
  75. package/dist/context-BIduDy1M.js +0 -10
  76. package/dist/format_options-LRnReKde.js +0 -65
  77. package/dist/index-BtBMDZg8.d.ts +0 -78
  78. package/dist/inject_context-BxpcF-ds.js +0 -106
  79. package/dist/inject_mocha-BVf8v6El.js +0 -38
  80. package/dist/inject_mocha-Daf1Aj8M.d.ts +0 -1
  81. package/dist/mock_agent-CxT7Q0_N.js +0 -45
  82. package/dist/mock_custom_loader-f_tHRojG.js +0 -35
  83. package/dist/mock_http_server-De0r07gr.js +0 -17
  84. package/dist/mock_httpclient-1EgQkMxi.d.ts +0 -40
  85. package/dist/mock_httpclient-B6UVI7GS.js +0 -110
  86. package/dist/restore-BL0cE0KG.d.ts +0 -4
  87. package/dist/restore-CVQYXquh.js +0 -16
  88. package/dist/src-D22EjdGo.js +0 -47
  89. package/dist/supertest-BIds28yL.d.ts +0 -16
  90. package/dist/supertest-Cg412Los.js +0 -39
  91. package/dist/types-CPNMyF89.js +0 -1
  92. package/dist/types-CjZ-JeCo.d.ts +0 -75
  93. package/dist/typings/index.d.ts +0 -1
  94. package/dist/util-1xYBaaoh.d.ts +0 -6
  95. package/dist/util-BpppqTXv.js +0 -59
  96. package/dist/utils-MhP_Krx1.js +0 -40
@@ -1,126 +0,0 @@
1
- import { EggTestRequest } from "./supertest-BIds28yL.js";
2
- import { MockClusterApplicationOptions, MockClusterOptions } from "./types-CjZ-JeCo.js";
3
- import { ApplicationUnittest } from "./application-BPpvw5dg.js";
4
- import { Coffee } from "coffee";
5
-
6
- //#region src/lib/cluster.d.ts
7
- declare global {
8
- var eggMockMasterPort: number;
9
- }
10
- /**
11
- * A cluster version of egg.Application, you can test with supertest
12
- * @example
13
- * ```js
14
- * const mm = require('mm');
15
- * const request = require('supertest');
16
- *
17
- * describe('ClusterApplication', () => {
18
- * let app;
19
- * before(function (done) {
20
- * app = mm.cluster({ baseDir });
21
- * app.ready(done);
22
- * });
23
- *
24
- * after(function () {
25
- * app.close();
26
- * });
27
- *
28
- * it('should 200', function (done) {
29
- * request(app.callback())
30
- * .get('/')
31
- * .expect(200, done);
32
- * });
33
- * });
34
- */
35
- declare class ClusterApplication extends Coffee {
36
- [key: string | symbol]: any;
37
- options: MockClusterApplicationOptions;
38
- port: number;
39
- baseDir: string;
40
- closed: boolean;
41
- private _address;
42
- /**
43
- * @class
44
- * @param {Object} options
45
- * - {String} baseDir - The directory of the application
46
- * - {Object} plugins - Custom you plugins
47
- * - {String} framework - The directory of the egg framework
48
- * - {Boolean} [cache=true] - Cache application based on baseDir
49
- * - {Boolean} [coverage=true] - Switch on process coverage, but it'll be slower
50
- * - {Boolean} [clean=true] - Remove $baseDir/logs
51
- * - {Object} [opt] - opt pass to coffee, such as { execArgv: ['--debug'] }
52
- * ```
53
- */
54
- constructor(options: MockClusterApplicationOptions);
55
- /**
56
- * the process that forked
57
- * @member {ChildProcess}
58
- */
59
- get process(): any;
60
- /**
61
- * Compatible API for supertest
62
- */
63
- callback(): this;
64
- /**
65
- * Compatible API for supertest
66
- * @member {String} url
67
- * @private
68
- */
69
- get url(): string;
70
- /**
71
- * Compatible API for supertest
72
- */
73
- address(): {
74
- port: number;
75
- address: string | undefined;
76
- };
77
- /**
78
- * Compatible API for supertest
79
- */
80
- listen(): this;
81
- /**
82
- * kill the process
83
- */
84
- close(): Promise<void>;
85
- get isClosed(): boolean;
86
- get router(): {
87
- pathFor(url: string): any;
88
- };
89
- /**
90
- * get app[property] value in app worker
91
- */
92
- getAppInstanceProperty(property: string): any;
93
- /**
94
- * collection logger message, then can be use on `expectLog()`
95
- * it's different from `app.expectLog()`, only support string params.
96
- *
97
- * @param {String} [logger] - logger instance name, default is `logger`
98
- * @function ClusterApplication#expectLog
99
- */
100
- mockLog(logger?: string): void;
101
- /**
102
- * expect str in the logger
103
- * it's different from `app.expectLog()`, only support string params.
104
- *
105
- * @param {String} str - test str
106
- * @param {String} [logger] - logger instance name, default is `logger`
107
- * @function ClusterApplication#expectLog
108
- */
109
- expectLog(str: string, logger?: string): void;
110
- /**
111
- * not expect str in the logger
112
- * it's different from `app.notExpectLog()`, only support string params.
113
- *
114
- * @param {String} str - test str
115
- * @param {String} [logger] - logger instance name, default is `logger`
116
- * @function ClusterApplication#notExpectLog
117
- */
118
- notExpectLog(str: string, logger?: string): void;
119
- httpRequest(): EggTestRequest;
120
- _callFunctionOnAppWorker(method: string, args?: any[], property?: any, needResult?: boolean): any;
121
- }
122
- type MockClusterApplication = ClusterApplication & ApplicationUnittest;
123
- declare function createCluster(initOptions?: MockClusterOptions): MockClusterApplication;
124
- declare function restore(): Promise<void>;
125
- //#endregion
126
- export { ClusterApplication, MockClusterApplication, createCluster, restore };
@@ -1,10 +0,0 @@
1
- //#region src/lib/context.ts
2
- const context = { runInBackground(scope) {
3
- const taskName = scope._name || scope.name;
4
- if (taskName) scope._name = taskName;
5
- const promise = this._runInBackground(scope);
6
- this.app._backgroundTasks.push(promise);
7
- } };
8
-
9
- //#endregion
10
- export { context };
@@ -1,65 +0,0 @@
1
- import { getSourceDirname } from "./utils-MhP_Krx1.js";
2
- import path from "node:path";
3
- import { readJSONSync } from "utility";
4
- import { isMocked, mm } from "mm";
5
- import { debuglog } from "node:util";
6
- import { getFrameworkPath } from "@eggjs/utils";
7
-
8
- //#region src/lib/format_options.ts
9
- const debug = debuglog("egg/mock/lib/format_options");
10
- /**
11
- * format the options
12
- */
13
- function formatOptions(initOptions) {
14
- const options = {
15
- baseDir: process.cwd(),
16
- cache: true,
17
- coverage: true,
18
- clean: true,
19
- ...initOptions
20
- };
21
- if (!path.isAbsolute(options.baseDir)) options.baseDir = path.join(process.cwd(), "test/fixtures", options.baseDir);
22
- let framework = initOptions?.framework ?? initOptions?.customEgg;
23
- if (framework === true) {
24
- framework = process.cwd();
25
- options.plugin = false;
26
- } else {
27
- if (!framework) framework = "";
28
- framework = getFrameworkPath({
29
- framework,
30
- baseDir: options.baseDir
31
- });
32
- }
33
- options.framework = options.customEgg = framework;
34
- const plugins = options.plugins = options.plugins || {};
35
- let pluginPath = path.join(getSourceDirname(), "..");
36
- if (pluginPath.endsWith("/dist") || pluginPath.endsWith("\\dist")) pluginPath = path.join(pluginPath, "..");
37
- plugins["egg-mock"] = {
38
- enable: true,
39
- path: pluginPath
40
- };
41
- if (options.plugin !== false) {
42
- const pluginPath$1 = process.cwd();
43
- const pkgPath = path.join(pluginPath$1, "package.json");
44
- const pluginName = getPluginName(pkgPath);
45
- if (options.plugin && !pluginName) throw new Error(`should set "eggPlugin" property in ${pkgPath}`);
46
- if (pluginName) plugins[pluginName] = {
47
- enable: true,
48
- path: pluginPath$1
49
- };
50
- }
51
- const env = process.env.EGG_SERVER_ENV;
52
- if (!isMocked(process.env, "HOME") && (env === "default" || env === "test" || env === "prod")) mm(process.env, "HOME", options.baseDir);
53
- if (process.env.EGG_MOCK_SERVER_ENV) options.cache = false;
54
- debug("[formatOptions] options: %j", options);
55
- return options;
56
- }
57
- function getPluginName(pkgPath) {
58
- try {
59
- const pkg = readJSONSync(pkgPath);
60
- if (pkg.eggPlugin?.name) return pkg.eggPlugin.name;
61
- } catch {}
62
- }
63
-
64
- //#endregion
65
- export { formatOptions };
@@ -1,78 +0,0 @@
1
- import { createCluster } from "./cluster-RTfUwmUd.js";
2
- import { createApp } from "./app-l47a-gqT.js";
3
- import { restore as restore$1 } from "./restore-BL0cE0KG.js";
4
- import { setGetAppCallback } from "./app_handler-Gp5J9X-v.js";
5
- import * as mm0 from "mm";
6
- import { mock } from "mm";
7
-
8
- //#region src/index.d.ts
9
- declare const mock$1: {
10
- restore: typeof restore$1;
11
- /**
12
- * Create a egg mocked application
13
- * @function mm#app
14
- * @param {Object} [options]
15
- * - {String} baseDir - The directory of the application
16
- * - {Object} plugins - Custom you plugins
17
- * - {String} framework - The directory of the egg framework
18
- * - {Boolean} [true] cache - Cache application based on baseDir
19
- * - {Boolean} [true] coverage - Switch on process coverage, but it'll be slower
20
- * - {Boolean} [true] clean - Remove $baseDir/logs
21
- * @return {App} return {@link Application}
22
- * @example
23
- * ```js
24
- * const app = mm.app();
25
- * ```
26
- */
27
- app: typeof createApp;
28
- /**
29
- * Create a egg mocked cluster application
30
- * @function mm#cluster
31
- * @see ClusterApplication
32
- */
33
- cluster: typeof createCluster;
34
- /**
35
- * mock the serverEnv of Egg
36
- * @member {Function} mm#env
37
- * @param {String} env - contain default, test, prod, local, unittest
38
- * @see https://github.com/eggjs/egg-core/blob/master/lib/loader/egg_loader.js#L78
39
- */
40
- env(env: string): void;
41
- /**
42
- * mock console level
43
- * @param {String} level - logger level
44
- */
45
- consoleLevel(level: string): void;
46
- home(homePath?: string): void;
47
- setGetAppCallback: typeof setGetAppCallback;
48
- isMocked: typeof mm0.isMocked;
49
- mock: typeof mock;
50
- mm: typeof mock;
51
- datas: typeof mm0.datas;
52
- mockDatas: typeof mm0.datas;
53
- data: typeof mm0.data;
54
- mockData: typeof mm0.data;
55
- dataWithAsyncDispose: typeof mm0.dataWithAsyncDispose;
56
- empty: typeof mm0.empty;
57
- mockEmpty: typeof mm0.empty;
58
- error: typeof mm0.error;
59
- mockError: typeof mm0.error;
60
- spy: typeof mm0.spy;
61
- errorOnce: typeof mm0.errorOnce;
62
- syncError: typeof mm0.syncError;
63
- syncEmpty: typeof mm0.syncEmpty;
64
- syncData: typeof mm0.syncData;
65
- http: {
66
- request: (url: mm0.RequestURL, data: mm0.ResponseData, headers?: Record<string, any>, delay?: number) => void;
67
- requestError: (url: mm0.RequestURL, reqError?: mm0.MockError, resError?: mm0.MockError, delay?: number) => void;
68
- };
69
- https: {
70
- request: (url: mm0.RequestURL, data: mm0.ResponseData, headers?: Record<string, any>, delay?: number) => void;
71
- requestError: (url: mm0.RequestURL, reqError?: mm0.MockError, resError?: mm0.MockError, delay?: number) => void;
72
- };
73
- spawn: typeof mm0.spawn;
74
- classMethod: typeof mm0.classMethod;
75
- };
76
- declare const proxyMock: ((target: any, property: PropertyKey, value?: any) => void) & typeof mock$1;
77
- //#endregion
78
- export { proxyMock };
@@ -1,106 +0,0 @@
1
- import { getApp } from "./app_handler-CkiK6fyC.js";
2
- import assert from "node:assert";
3
- import { debuglog } from "node:util";
4
-
5
- //#region src/lib/inject_context.ts
6
- const debug = debuglog("egg/mock/lib/inject_context");
7
- const MOCHA_SUITE_APP = Symbol.for("mocha#suite#app");
8
- /**
9
- * Monkey patch the mocha instance with egg context.
10
- *
11
- * @param {Function} mocha - the module of mocha
12
- */
13
- function injectContext(mocha) {
14
- if (mocha._injectContextLoaded) {
15
- debug("mocha already injected context, skip it");
16
- return;
17
- }
18
- const { Runner } = mocha;
19
- const runSuite = Runner.prototype.runSuite;
20
- const runTests = Runner.prototype.runTests;
21
- function getTestTitle(suite, test) {
22
- const suiteTitle = suite.root ? "root suite" : suite.title;
23
- if (!test) return `"${suiteTitle}"`;
24
- return `"${suiteTitle} - ${test.title}"`;
25
- }
26
- Runner.prototype.runSuite = async function(suite, fn) {
27
- debug("run suite: %s", suite.title);
28
- let app;
29
- const self = this;
30
- try {
31
- app = await getApp(suite);
32
- debug("get app: %s", !!app);
33
- await app.ready();
34
- } catch {
35
- app = null;
36
- }
37
- if (!app) return runSuite.call(self, suite, fn);
38
- let errSuite;
39
- try {
40
- suite.ctx[MOCHA_SUITE_APP] = app;
41
- await (app.mockModuleContextScope || app.mockContextScope).call(app, async function() {
42
- await new Promise((resolve) => {
43
- runSuite.call(self, suite, (aErrSuite) => {
44
- errSuite = aErrSuite;
45
- resolve();
46
- });
47
- });
48
- });
49
- } catch (err) {
50
- suite.beforeAll("egg-mock-mock-ctx-failed", async () => {
51
- throw err;
52
- });
53
- return runSuite.call(self, suite, (aErrSuite) => {
54
- return fn(aErrSuite);
55
- });
56
- }
57
- return fn(errSuite);
58
- };
59
- Runner.prototype.runTests = async function(suite, fn) {
60
- const tests = suite.tests.slice();
61
- if (!tests.length) return runTests.call(this, suite, fn);
62
- const app = suite.ctx[MOCHA_SUITE_APP];
63
- const self = this;
64
- if (!app) return runTests.call(self, suite, fn);
65
- function done(errSuite) {
66
- suite.tests = tests;
67
- return fn(errSuite);
68
- }
69
- async function next(i) {
70
- const test = tests[i];
71
- if (!test) return done();
72
- suite.tests = [test];
73
- let app$1;
74
- try {
75
- app$1 = await getApp(suite, test);
76
- assert(app$1, `not found app for test ${getTestTitle(suite, test)}`);
77
- await app$1.ready();
78
- } catch (err) {
79
- self.fail(test, err);
80
- return next(i + 1);
81
- }
82
- try {
83
- await (app$1.mockModuleContextScope || app$1.mockContextScope).call(app$1, async function() {
84
- return await new Promise((resolve) => {
85
- runTests.call(self, suite, () => {
86
- return resolve();
87
- });
88
- });
89
- });
90
- } catch (err) {
91
- self.fail(test, err);
92
- return next(i + 1);
93
- }
94
- return next(i + 1);
95
- }
96
- next(0).catch((err) => {
97
- self.fail(suite, err);
98
- done(suite);
99
- });
100
- };
101
- mocha._injectContextLoaded = true;
102
- debug("inject context success");
103
- }
104
-
105
- //#endregion
106
- export { injectContext };
@@ -1,38 +0,0 @@
1
- import { injectContext } from "./inject_context-BxpcF-ds.js";
2
- import { createRequire } from "node:module";
3
- import { debuglog } from "node:util";
4
- import { getRequire } from "@eggjs/utils";
5
- import "mocha";
6
-
7
- //#region rolldown:runtime
8
- var __require = /* @__PURE__ */ createRequire(import.meta.url);
9
-
10
- //#endregion
11
- //#region src/inject_mocha.ts
12
- const debug = debuglog("egg/mock/inject_mocha");
13
- /**
14
- * Find active node mocha instances.
15
- */
16
- function findNodeJSMocha() {
17
- let children;
18
- if (typeof __require === "function") children = __require.cache || {};
19
- else {
20
- children = getRequire().cache || {};
21
- debug("createRequire on esm");
22
- }
23
- return Object.keys(children).filter(function(child) {
24
- const val = children[child].exports;
25
- return typeof val === "function" && val.name === "Mocha";
26
- }).map(function(child) {
27
- return children[child].exports;
28
- });
29
- }
30
- const modules = findNodeJSMocha();
31
- debug("modules length: %s", modules.length);
32
- for (const module of modules) {
33
- if (!module) continue;
34
- injectContext(module);
35
- }
36
-
37
- //#endregion
38
- export { };
@@ -1 +0,0 @@
1
- import "mocha";
@@ -1,45 +0,0 @@
1
- import { debuglog } from "node:util";
2
- import { Dispatcher, HttpClient, MockAgent, getGlobalDispatcher, setGlobalDispatcher } from "urllib";
3
-
4
- //#region src/lib/mock_agent.ts
5
- const debug = debuglog("egg/mock/lib/mock_agent");
6
- globalThis.__mockAgent = null;
7
- globalThis.__httpClientDispatchers = /* @__PURE__ */ new Map();
8
- function getMockAgent(app) {
9
- debug("getMockAgent");
10
- if (!globalThis.__globalDispatcher) {
11
- globalThis.__globalDispatcher = getGlobalDispatcher();
12
- debug("create global dispatcher");
13
- }
14
- if (app?.httpClient && !globalThis.__httpClientDispatchers.has(app.httpClient)) {
15
- globalThis.__httpClientDispatchers.set(app.httpClient, app.httpClient.getDispatcher());
16
- debug("add new httpClient, size: %d", globalThis.__httpClientDispatchers.size);
17
- }
18
- if (!globalThis.__mockAgent) {
19
- globalThis.__mockAgent = new MockAgent();
20
- setGlobalDispatcher(globalThis.__mockAgent);
21
- if (typeof app?.httpClient?.setDispatcher === "function") app.httpClient.setDispatcher(globalThis.__mockAgent);
22
- debug("create new mockAgent");
23
- }
24
- return globalThis.__mockAgent;
25
- }
26
- async function restoreMockAgent() {
27
- debug("restoreMockAgent start");
28
- if (globalThis.__globalDispatcher) {
29
- setGlobalDispatcher(globalThis.__globalDispatcher);
30
- debug("restore global dispatcher");
31
- }
32
- debug("restore httpClient, size: %d", globalThis.__httpClientDispatchers.size);
33
- for (const [httpClient$1, dispatcher] of globalThis.__httpClientDispatchers) httpClient$1.setDispatcher(dispatcher);
34
- globalThis.__httpClientDispatchers.clear();
35
- if (globalThis.__mockAgent) {
36
- const agent = globalThis.__mockAgent;
37
- globalThis.__mockAgent = null;
38
- await agent.close();
39
- debug("close mockAgent");
40
- }
41
- debug("restoreMockAgent end");
42
- }
43
-
44
- //#endregion
45
- export { getMockAgent, restoreMockAgent };
@@ -1,35 +0,0 @@
1
- import { debuglog } from "node:util";
2
-
3
- //#region src/lib/mock_custom_loader.ts
4
- const debug = debuglog("egg/mock/lib/mock_custom_loader");
5
- function setCustomLoader(app) {
6
- const customLoader = app.config.customLoader;
7
- if (!customLoader) return;
8
- for (const field of Object.keys(customLoader)) {
9
- const loaderConfig = Object.assign({}, customLoader[field]);
10
- loaderConfig.field = field;
11
- addMethod(loaderConfig);
12
- }
13
- function addMethod(loaderConfig) {
14
- const field = loaderConfig.field;
15
- const appMethodName = "mock" + field.replace(/^[a-z]/i, (s) => s.toUpperCase());
16
- if (app[appMethodName]) {
17
- app.coreLogger.warn("Can't override app.%s", appMethodName);
18
- return;
19
- }
20
- debug("[addMethod] %s => %j", appMethodName, loaderConfig);
21
- app[appMethodName] = function(service, methodName, fn) {
22
- if (typeof service === "string") {
23
- const arr = service.split(".");
24
- service = loaderConfig.inject === "ctx" ? this[field + "Classes"] : this[field];
25
- for (const key of arr) service = service[key];
26
- service = service.prototype || service;
27
- }
28
- this._mockFn(service, methodName, fn);
29
- return this;
30
- };
31
- }
32
- }
33
-
34
- //#endregion
35
- export { setCustomLoader };
@@ -1,17 +0,0 @@
1
- import http, { Server } from "node:http";
2
-
3
- //#region src/lib/mock_http_server.ts
4
- const SERVER = Symbol("http_server");
5
- function createServer(app) {
6
- let server = app[SERVER] || app.callback();
7
- if (typeof server === "function") {
8
- server = http.createServer(server);
9
- app[SERVER] = server;
10
- if (!app.server) app.server = server;
11
- app.emit("server", server);
12
- }
13
- return server;
14
- }
15
-
16
- //#endregion
17
- export { createServer };
@@ -1,40 +0,0 @@
1
- import { BodyInit, Dispatcher, Headers } from "urllib";
2
-
3
- //#region src/lib/mock_httpclient.d.ts
4
- interface MockResultOptions {
5
- data: string | Buffer | Record<string, any>;
6
- /**
7
- * http status
8
- */
9
- status?: number;
10
- /**
11
- * response header
12
- */
13
- headers?: Record<string, string>;
14
- /**
15
- * delay the associated reply by a set amount in ms
16
- */
17
- delay?: number;
18
- /**
19
- * any matching request will always reply with the defined response indefinitely
20
- */
21
- persist?: boolean;
22
- /**
23
- * any matching request will reply with the defined response a fixed amount of times
24
- */
25
- repeats?: number;
26
- }
27
- type ResultObject = MockResultOptions;
28
- interface MockResponseCallbackOptions {
29
- path: string;
30
- method: string;
31
- headers?: Headers | Record<string, string>;
32
- origin?: string;
33
- body?: BodyInit | Dispatcher.DispatchOptions['body'] | null;
34
- maxRedirections?: number;
35
- }
36
- type MockResultFunction = (url: string, options: MockResponseCallbackOptions) => MockResultOptions | string;
37
- declare function createMockHttpClient(app: any): (mockUrl: string | RegExp, mockMethod: string | string[] | MockResultOptions | MockResultFunction, mockResult?: MockResultOptions | MockResultFunction | string) => void;
38
- type MockHttpClientMethod = ReturnType<typeof createMockHttpClient>;
39
- //#endregion
40
- export { MockHttpClientMethod, MockResponseCallbackOptions, MockResultFunction, MockResultOptions, ResultObject, createMockHttpClient };
@@ -1,110 +0,0 @@
1
- import { getMockAgent } from "./mock_agent-CxT7Q0_N.js";
2
- import { mm } from "mm";
3
- import { extend } from "@eggjs/extend2";
4
-
5
- //#region src/lib/mock_httpclient.ts
6
- function normalizeResult(result) {
7
- if (typeof result === "string") result = { data: result };
8
- if (!result.status) result.status = 200;
9
- result.data = result.data || "";
10
- if (Buffer.isBuffer(result.data)) {} else if (typeof result.data === "object") result.data = Buffer.from(JSON.stringify(result.data));
11
- else if (typeof result.data === "string") result.data = Buffer.from(result.data);
12
- else throw new Error("`mockResult.data` must be buffer, string or json");
13
- result.headers = result.headers ?? {};
14
- return result;
15
- }
16
- const MOCK_CONFIGS = Symbol("MOCK_CONFIGS");
17
- const MOCK_CONFIG_INDEX = Symbol("MOCK_CONFIG_INDEX");
18
- function createMockHttpClient(app) {
19
- /**
20
- * mock httpclient
21
- * @function mockHttpclient
22
- * @param {String} mockUrl - url
23
- * @param {String|Array} mockMethod - http method, default is '*'
24
- * @param {Object|Function} mockResult - you data
25
- * - data - buffer / string / json
26
- * - status - http status
27
- * - headers - response header
28
- * - delay - delay the associated reply by a set amount in ms.
29
- * - persist - any matching request will always reply with the defined response indefinitely, default is true
30
- * - repeats - number, any matching request will reply with the defined response a fixed amount of times
31
- */
32
- return function mockHttpClient(mockUrl, mockMethod, mockResult) {
33
- let mockMethods = mockMethod;
34
- if (!mockResult) {
35
- mockResult = mockMethod;
36
- mockMethods = ["*"];
37
- }
38
- if (!Array.isArray(mockMethods)) mockMethods = [mockMethods];
39
- mockMethods = mockMethods.map((method) => (method || "GET").toUpperCase());
40
- let mockConfigs = app[MOCK_CONFIGS];
41
- if (!mockConfigs) {
42
- mockConfigs = [];
43
- mm(app, MOCK_CONFIGS, mockConfigs);
44
- }
45
- let mockConfigIndex = -1;
46
- let origin = mockUrl;
47
- let originMethod;
48
- const pathname = mockUrl;
49
- let pathMethod;
50
- if (typeof mockUrl === "string") {
51
- const urlObject = new URL(mockUrl);
52
- origin = urlObject.origin;
53
- const originalPathname = urlObject.pathname;
54
- pathMethod = (path) => {
55
- if (path === originalPathname) return true;
56
- if (path.includes("?")) return path.startsWith(originalPathname);
57
- return false;
58
- };
59
- } else if (mockUrl instanceof RegExp) {
60
- let requestOrigin = "";
61
- originMethod = (value) => {
62
- requestOrigin = value;
63
- return true;
64
- };
65
- pathMethod = (path) => {
66
- for (const config of mockConfigs) if (config.mockUrl.test(`${requestOrigin}${path}`)) {
67
- mm(app, MOCK_CONFIG_INDEX, config.mockConfigIndex);
68
- return true;
69
- }
70
- return false;
71
- };
72
- mockConfigIndex = mockConfigs.length;
73
- mockConfigs.push({
74
- mockUrl,
75
- mockResult,
76
- mockConfigIndex
77
- });
78
- }
79
- const mockPool = originMethod ? getMockAgent(app).get(originMethod) : getMockAgent(app).get(originMethod ?? origin);
80
- let persist = true;
81
- if (typeof mockResult === "object" && typeof mockResult.persist === "boolean") persist = mockResult.persist;
82
- mockMethods.forEach(function(method) {
83
- const mockScope = mockPool.intercept({
84
- path: pathMethod ?? pathname,
85
- method: method === "*" ? () => true : method
86
- }).reply((options) => {
87
- const requestUrl = `${options.origin}${options.path}`;
88
- let mockRequestResult;
89
- if (mockConfigIndex >= 0) {
90
- mockResult = mockConfigs[app[MOCK_CONFIG_INDEX]].mockResult;
91
- mockRequestResult = typeof mockResult === "function" ? mockResult(requestUrl, options) : mockResult;
92
- } else mockRequestResult = typeof mockResult === "function" ? mockResult(requestUrl, options) : mockResult;
93
- const result = extend(true, {}, normalizeResult(mockRequestResult));
94
- return {
95
- statusCode: result.status,
96
- data: result.data,
97
- responseOptions: { headers: result.headers }
98
- };
99
- });
100
- if (typeof mockResult === "object") {
101
- if (mockResult.delay && mockResult.delay > 0) mockScope.delay(mockResult.delay);
102
- }
103
- if (persist) mockScope.persist();
104
- else if (typeof mockResult === "object" && mockResult.repeats && mockResult.repeats > 0) mockScope.times(mockResult.repeats);
105
- });
106
- };
107
- }
108
-
109
- //#endregion
110
- export { createMockHttpClient };
@@ -1,4 +0,0 @@
1
- //#region src/lib/restore.d.ts
2
- declare function restore(): Promise<void>;
3
- //#endregion
4
- export { restore };