@eggjs/mock 6.0.7 → 6.1.0-beta.2

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 (211) hide show
  1. package/README.md +35 -56
  2. package/README.zh_CN.md +30 -50
  3. package/dist/_virtual/rolldown_runtime.js +7 -0
  4. package/dist/app/extend/agent.d.ts +39 -0
  5. package/dist/app/extend/agent.js +48 -0
  6. package/dist/app/extend/application.d.ts +176 -0
  7. package/dist/app/extend/application.js +385 -0
  8. package/dist/app/middleware/cluster_app_mock.d.ts +6 -0
  9. package/dist/app/middleware/cluster_app_mock.js +97 -0
  10. package/dist/app.d.ts +10 -0
  11. package/dist/app.js +17 -0
  12. package/dist/bootstrap.d.ts +9 -0
  13. package/dist/bootstrap.js +14 -0
  14. package/dist/index.d.ts +81 -0
  15. package/dist/index.js +48 -0
  16. package/dist/lib/agent_handler.d.ts +7 -0
  17. package/dist/lib/agent_handler.js +26 -0
  18. package/dist/lib/app.d.ts +7 -0
  19. package/dist/lib/app.js +251 -0
  20. package/dist/lib/app_handler.d.ts +9 -0
  21. package/dist/lib/app_handler.js +56 -0
  22. package/dist/lib/cluster.d.ts +126 -0
  23. package/dist/lib/cluster.js +283 -0
  24. package/dist/lib/context.d.ts +4 -0
  25. package/dist/lib/context.js +13 -0
  26. package/dist/lib/format_options.d.ts +10 -0
  27. package/dist/lib/format_options.js +65 -0
  28. package/dist/lib/inject_context.d.ts +9 -0
  29. package/dist/lib/inject_context.js +106 -0
  30. package/dist/lib/mock_agent.d.ts +9 -0
  31. package/dist/lib/mock_agent.js +45 -0
  32. package/dist/lib/mock_custom_loader.d.ts +4 -0
  33. package/dist/lib/mock_custom_loader.js +35 -0
  34. package/dist/lib/mock_http_server.d.ts +6 -0
  35. package/dist/lib/mock_http_server.js +17 -0
  36. package/dist/lib/mock_httpclient.d.ts +40 -0
  37. package/dist/lib/mock_httpclient.js +110 -0
  38. package/dist/lib/parallel/agent.d.ts +24 -0
  39. package/dist/lib/parallel/agent.js +111 -0
  40. package/dist/lib/parallel/app.d.ts +24 -0
  41. package/dist/lib/parallel/app.js +98 -0
  42. package/dist/lib/parallel/util.d.ts +6 -0
  43. package/dist/lib/parallel/util.js +59 -0
  44. package/dist/lib/prerequire.d.ts +1 -0
  45. package/dist/lib/prerequire.js +1 -0
  46. package/dist/lib/request_call_function.d.ts +1 -0
  47. package/dist/lib/request_call_function.js +37 -0
  48. package/dist/lib/restore.d.ts +4 -0
  49. package/dist/lib/restore.js +16 -0
  50. package/dist/{commonjs/lib → lib}/start-cluster.d.ts +1 -1
  51. package/dist/lib/start-cluster.js +19 -0
  52. package/dist/lib/supertest.d.ts +16 -0
  53. package/dist/lib/supertest.js +39 -0
  54. package/dist/lib/tmp/empty.d.ts +1 -0
  55. package/dist/lib/tmp/empty.js +1 -0
  56. package/{src/lib/types.ts → dist/lib/types.d.ts} +12 -29
  57. package/dist/lib/types.js +1 -0
  58. package/dist/lib/utils.d.ts +12 -0
  59. package/dist/lib/utils.js +40 -0
  60. package/dist/register.d.ts +12 -0
  61. package/dist/register.js +65 -0
  62. package/dist/typings/index.d.ts +1 -0
  63. package/package.json +68 -100
  64. package/dist/commonjs/app/extend/agent.d.ts +0 -34
  65. package/dist/commonjs/app/extend/agent.js +0 -49
  66. package/dist/commonjs/app/extend/application.d.ts +0 -172
  67. package/dist/commonjs/app/extend/application.js +0 -450
  68. package/dist/commonjs/app/middleware/cluster_app_mock.d.ts +0 -3
  69. package/dist/commonjs/app/middleware/cluster_app_mock.js +0 -101
  70. package/dist/commonjs/app.d.ts +0 -6
  71. package/dist/commonjs/app.js +0 -20
  72. package/dist/commonjs/bootstrap.d.ts +0 -5
  73. package/dist/commonjs/bootstrap.js +0 -59
  74. package/dist/commonjs/index.d.ts +0 -77
  75. package/dist/commonjs/index.js +0 -114
  76. package/dist/commonjs/lib/agent_handler.d.ts +0 -3
  77. package/dist/commonjs/lib/agent_handler.js +0 -28
  78. package/dist/commonjs/lib/app.d.ts +0 -3
  79. package/dist/commonjs/lib/app.js +0 -301
  80. package/dist/commonjs/lib/app_handler.d.ts +0 -5
  81. package/dist/commonjs/lib/app_handler.js +0 -71
  82. package/dist/commonjs/lib/cluster.d.ts +0 -114
  83. package/dist/commonjs/lib/cluster.js +0 -337
  84. package/dist/commonjs/lib/context.d.ts +0 -1
  85. package/dist/commonjs/lib/context.js +0 -16
  86. package/dist/commonjs/lib/format_options.d.ts +0 -5
  87. package/dist/commonjs/lib/format_options.js +0 -100
  88. package/dist/commonjs/lib/inject_context.d.ts +0 -6
  89. package/dist/commonjs/lib/inject_context.js +0 -132
  90. package/dist/commonjs/lib/mock_agent.d.ts +0 -5
  91. package/dist/commonjs/lib/mock_agent.js +0 -49
  92. package/dist/commonjs/lib/mock_custom_loader.d.ts +0 -1
  93. package/dist/commonjs/lib/mock_custom_loader.js +0 -37
  94. package/dist/commonjs/lib/mock_http_server.d.ts +0 -2
  95. package/dist/commonjs/lib/mock_http_server.js +0 -24
  96. package/dist/commonjs/lib/mock_httpclient.d.ts +0 -36
  97. package/dist/commonjs/lib/mock_httpclient.js +0 -147
  98. package/dist/commonjs/lib/parallel/agent.d.ts +0 -20
  99. package/dist/commonjs/lib/parallel/agent.js +0 -125
  100. package/dist/commonjs/lib/parallel/app.d.ts +0 -20
  101. package/dist/commonjs/lib/parallel/app.js +0 -115
  102. package/dist/commonjs/lib/parallel/util.d.ts +0 -3
  103. package/dist/commonjs/lib/parallel/util.js +0 -77
  104. package/dist/commonjs/lib/prerequire.d.ts +0 -1
  105. package/dist/commonjs/lib/prerequire.js +0 -26
  106. package/dist/commonjs/lib/request_call_function.d.ts +0 -1
  107. package/dist/commonjs/lib/request_call_function.js +0 -52
  108. package/dist/commonjs/lib/restore.d.ts +0 -1
  109. package/dist/commonjs/lib/restore.js +0 -16
  110. package/dist/commonjs/lib/start-cluster.js +0 -23
  111. package/dist/commonjs/lib/supertest.d.ts +0 -11
  112. package/dist/commonjs/lib/supertest.js +0 -48
  113. package/dist/commonjs/lib/tmp/empty.d.ts +0 -1
  114. package/dist/commonjs/lib/tmp/empty.js +0 -3
  115. package/dist/commonjs/lib/types.d.ts +0 -68
  116. package/dist/commonjs/lib/types.js +0 -3
  117. package/dist/commonjs/lib/utils.d.ts +0 -9
  118. package/dist/commonjs/lib/utils.js +0 -80
  119. package/dist/commonjs/package.json +0 -3
  120. package/dist/commonjs/register.d.ts +0 -8
  121. package/dist/commonjs/register.js +0 -80
  122. package/dist/esm/app/extend/agent.d.ts +0 -34
  123. package/dist/esm/app/extend/agent.js +0 -46
  124. package/dist/esm/app/extend/application.d.ts +0 -172
  125. package/dist/esm/app/extend/application.js +0 -444
  126. package/dist/esm/app/middleware/cluster_app_mock.d.ts +0 -3
  127. package/dist/esm/app/middleware/cluster_app_mock.js +0 -99
  128. package/dist/esm/app.d.ts +0 -6
  129. package/dist/esm/app.js +0 -17
  130. package/dist/esm/bootstrap.d.ts +0 -5
  131. package/dist/esm/bootstrap.js +0 -15
  132. package/dist/esm/index.d.ts +0 -77
  133. package/dist/esm/index.js +0 -91
  134. package/dist/esm/lib/agent_handler.d.ts +0 -3
  135. package/dist/esm/lib/agent_handler.js +0 -24
  136. package/dist/esm/lib/app.d.ts +0 -3
  137. package/dist/esm/lib/app.js +0 -295
  138. package/dist/esm/lib/app_handler.d.ts +0 -5
  139. package/dist/esm/lib/app_handler.js +0 -65
  140. package/dist/esm/lib/cluster.d.ts +0 -114
  141. package/dist/esm/lib/cluster.js +0 -328
  142. package/dist/esm/lib/context.d.ts +0 -1
  143. package/dist/esm/lib/context.js +0 -13
  144. package/dist/esm/lib/format_options.d.ts +0 -5
  145. package/dist/esm/lib/format_options.js +0 -94
  146. package/dist/esm/lib/inject_context.d.ts +0 -6
  147. package/dist/esm/lib/inject_context.js +0 -126
  148. package/dist/esm/lib/mock_agent.d.ts +0 -5
  149. package/dist/esm/lib/mock_agent.js +0 -45
  150. package/dist/esm/lib/mock_custom_loader.d.ts +0 -1
  151. package/dist/esm/lib/mock_custom_loader.js +0 -34
  152. package/dist/esm/lib/mock_http_server.d.ts +0 -2
  153. package/dist/esm/lib/mock_http_server.js +0 -18
  154. package/dist/esm/lib/mock_httpclient.d.ts +0 -36
  155. package/dist/esm/lib/mock_httpclient.js +0 -144
  156. package/dist/esm/lib/parallel/agent.d.ts +0 -20
  157. package/dist/esm/lib/parallel/agent.js +0 -117
  158. package/dist/esm/lib/parallel/app.d.ts +0 -20
  159. package/dist/esm/lib/parallel/app.js +0 -110
  160. package/dist/esm/lib/parallel/util.d.ts +0 -3
  161. package/dist/esm/lib/parallel/util.js +0 -73
  162. package/dist/esm/lib/prerequire.d.ts +0 -1
  163. package/dist/esm/lib/prerequire.js +0 -25
  164. package/dist/esm/lib/request_call_function.d.ts +0 -1
  165. package/dist/esm/lib/request_call_function.js +0 -47
  166. package/dist/esm/lib/restore.d.ts +0 -1
  167. package/dist/esm/lib/restore.js +0 -13
  168. package/dist/esm/lib/start-cluster.d.ts +0 -2
  169. package/dist/esm/lib/start-cluster.js +0 -18
  170. package/dist/esm/lib/supertest.d.ts +0 -11
  171. package/dist/esm/lib/supertest.js +0 -40
  172. package/dist/esm/lib/tmp/empty.d.ts +0 -1
  173. package/dist/esm/lib/tmp/empty.js +0 -2
  174. package/dist/esm/lib/types.d.ts +0 -68
  175. package/dist/esm/lib/types.js +0 -2
  176. package/dist/esm/lib/utils.d.ts +0 -9
  177. package/dist/esm/lib/utils.js +0 -69
  178. package/dist/esm/package.json +0 -3
  179. package/dist/esm/register.d.ts +0 -8
  180. package/dist/esm/register.js +0 -75
  181. package/dist/package.json +0 -4
  182. package/src/app/extend/agent.ts +0 -57
  183. package/src/app/extend/application.ts +0 -512
  184. package/src/app/middleware/cluster_app_mock.ts +0 -102
  185. package/src/app.ts +0 -18
  186. package/src/bootstrap.ts +0 -25
  187. package/src/index.ts +0 -112
  188. package/src/lib/agent_handler.ts +0 -28
  189. package/src/lib/app.ts +0 -314
  190. package/src/lib/app_handler.ts +0 -77
  191. package/src/lib/cluster.ts +0 -363
  192. package/src/lib/context.ts +0 -14
  193. package/src/lib/format_options.ts +0 -103
  194. package/src/lib/inject_context.ts +0 -134
  195. package/src/lib/mock_agent.ts +0 -57
  196. package/src/lib/mock_custom_loader.ts +0 -36
  197. package/src/lib/mock_http_server.ts +0 -19
  198. package/src/lib/mock_httpclient.ts +0 -183
  199. package/src/lib/parallel/agent.ts +0 -128
  200. package/src/lib/parallel/app.ts +0 -123
  201. package/src/lib/parallel/util.ts +0 -66
  202. package/src/lib/prerequire.ts +0 -25
  203. package/src/lib/request_call_function.ts +0 -49
  204. package/src/lib/restore.ts +0 -14
  205. package/src/lib/start-cluster.ts +0 -23
  206. package/src/lib/supertest.ts +0 -45
  207. package/src/lib/tmp/.gitkeep +0 -0
  208. package/src/lib/tmp/empty.ts +0 -0
  209. package/src/lib/utils.ts +0 -82
  210. package/src/register.ts +0 -80
  211. package/src/typings/index.d.ts +0 -4
@@ -0,0 +1,176 @@
1
+ import { MockHttpClientMethod, MockResultFunction, MockResultOptions } from "../../lib/mock_httpclient.js";
2
+ import { EggTestRequest } from "../../lib/supertest.js";
3
+ import { MockOptions } from "../../lib/types.js";
4
+ import { Context, EggCore, EggCoreOptions } from "@eggjs/core";
5
+ import { mock } from "mm";
6
+ import { IncomingMessage } from "node:http";
7
+ import { Logger } from "egg-logger";
8
+ import * as urllib1 from "urllib";
9
+ import { HttpClient } from "urllib";
10
+
11
+ //#region src/app/extend/application.d.ts
12
+ interface MockContextOptions {
13
+ /**
14
+ * mock ctxStorage or not, default is `true`
15
+ */
16
+ mockCtxStorage?: boolean;
17
+ /**
18
+ * reuse ctxStorage or not, default is `true`
19
+ */
20
+ reuseCtxStorage?: boolean;
21
+ }
22
+ interface MockContextData {
23
+ headers?: Record<string, string | string[]>;
24
+ [key: string]: any;
25
+ }
26
+ interface MockContext extends EggContext, Context {
27
+ service: any;
28
+ }
29
+ declare abstract class ApplicationUnittest extends EggCore {
30
+ [key: string]: any;
31
+ options: MockOptions & EggCoreOptions;
32
+ _mockHttpClient?: MockHttpClientMethod;
33
+ httpclient: HttpClient;
34
+ /**
35
+ * mock Context
36
+ * @function App#mockContext
37
+ * @param {Object} data - ctx data
38
+ * @param {Object} [options] - mock ctx options
39
+ * @example
40
+ * ```js
41
+ * const ctx = app.mockContext({
42
+ * user: {
43
+ * name: 'Jason'
44
+ * }
45
+ * });
46
+ * console.log(ctx.user.name); // Jason
47
+ *
48
+ * // controller
49
+ * module.exports = function*() {
50
+ * this.body = this.user.name;
51
+ * };
52
+ * ```
53
+ */
54
+ mockContext(data?: MockContextData, options?: MockContextOptions): MockContext;
55
+ mockContextScope(fn: (ctx?: MockContext) => Promise<any>, data?: MockContextData): Promise<any>;
56
+ /**
57
+ * mock cookie session
58
+ * @function App#mockSession
59
+ * @param {Object} data - session object
60
+ */
61
+ mockSession(data: any): this;
62
+ /**
63
+ * Mock service
64
+ * @function App#mockService
65
+ * @param {String} service - name
66
+ * @param {String} methodName - method
67
+ * @param {Object|Function|Error} fn - mock you data
68
+ */
69
+ mockService(service: string | any, methodName: string, fn: any): this;
70
+ /**
71
+ * mock service that return error
72
+ * @function App#mockServiceError
73
+ * @param {String} service - name
74
+ * @param {String} methodName - method
75
+ * @param {Error} [err] - error information
76
+ */
77
+ mockServiceError(service: string | any, methodName: string, err?: string | Error): this;
78
+ _mockFn(obj: any, name: string, data: any): void;
79
+ /**
80
+ * mock request
81
+ * @function App#mockRequest
82
+ * @param {Request} req - mock request
83
+ */
84
+ mockRequest(req: MockContextData): IncomingMessage;
85
+ /**
86
+ * mock cookies
87
+ * @function App#mockCookies
88
+ */
89
+ mockCookies(cookies: Record<string, string | string[]>): this;
90
+ /**
91
+ * mock header
92
+ * @function App#mockHeaders
93
+ */
94
+ mockHeaders(headers: Record<string, string | string[]>): this;
95
+ /**
96
+ * mock csrf
97
+ * @function App#mockCsrf
98
+ * @since 1.11
99
+ */
100
+ mockCsrf(): this;
101
+ /**
102
+ * mock httpclient
103
+ * @alias mockHttpClient
104
+ * @function App#mockHttpclient
105
+ */
106
+ mockHttpclient(mockUrl: string | RegExp, mockMethod: string | string[] | MockResultOptions | MockResultFunction, mockResult?: MockResultOptions | MockResultFunction | string): this;
107
+ /**
108
+ * mock httpclient
109
+ * @function App#mockHttpClient
110
+ */
111
+ mockHttpClient(mockUrl: string | RegExp, mockMethod: string | string[] | MockResultOptions | MockResultFunction, mockResult?: MockResultOptions | MockResultFunction | string): this;
112
+ /**
113
+ * @deprecated Please use app.mockHttpClient instead of app.mockUrllib
114
+ */
115
+ mockUrllib(mockUrl: string | RegExp, mockMethod: string | string[] | MockResultOptions | MockResultFunction, mockResult?: MockResultOptions | MockResultFunction | string): this;
116
+ /**
117
+ * get mock httpclient agent
118
+ * @function App#mockHttpclientAgent
119
+ */
120
+ mockAgent(): urllib1.MockAgent<urllib1.MockAgent.Options>;
121
+ mockAgentRestore(): Promise<void>;
122
+ /**
123
+ * @see mm#restore
124
+ * @function App#mockRestore
125
+ */
126
+ mockRestore(): Promise<void>;
127
+ /**
128
+ * @see mm
129
+ * @function App#mm
130
+ */
131
+ get mm(): typeof mock;
132
+ /**
133
+ * override loadAgent
134
+ * @function App#loadAgent
135
+ */
136
+ loadAgent(): void;
137
+ /**
138
+ * mock serverEnv
139
+ * @function App#mockEnv
140
+ * @param {String} env - serverEnv
141
+ */
142
+ mockEnv(env: string): this;
143
+ /**
144
+ * http request helper
145
+ * @function App#httpRequest
146
+ * @return {SupertestRequest} req - supertest request
147
+ * @see https://github.com/visionmedia/supertest
148
+ */
149
+ httpRequest(): EggTestRequest;
150
+ /**
151
+ * collection logger message, then can be use on `expectLog()`
152
+ * @param {String|Logger} [logger] - logger instance, default is `app.logger`
153
+ * @function App#mockLog
154
+ */
155
+ mockLog(logger?: string | Logger): void;
156
+ __checkExpectLog(expectOrNot: boolean, str: string | RegExp, logger?: string | Logger): void;
157
+ /**
158
+ * expect str/regexp in the logger, if your server disk is slow, please call `mockLog()` first.
159
+ * @param {String|RegExp} str - test str or regexp
160
+ * @param {String|Logger} [logger] - logger instance, default is `ctx.logger`
161
+ * @function App#expectLog
162
+ */
163
+ expectLog(str: string | RegExp, logger?: string | Logger): void;
164
+ /**
165
+ * not expect str/regexp in the logger, if your server disk is slow, please call `mockLog()` first.
166
+ * @param {String|RegExp} str - test str or regexp
167
+ * @param {String|Logger} [logger] - logger instance, default is `ctx.logger`
168
+ * @function App#notExpectLog
169
+ */
170
+ notExpectLog(str: string | RegExp, logger?: string | Logger): void;
171
+ backgroundTasksFinished(): Promise<void>;
172
+ get _backgroundTasks(): Promise<any>[];
173
+ set _backgroundTasks(tasks: Promise<any>[]);
174
+ }
175
+ //#endregion
176
+ export { MockContext, MockContextData, MockContextOptions, ApplicationUnittest as default };
@@ -0,0 +1,385 @@
1
+ import { request } from "../../lib/supertest.js";
2
+ import { getMockAgent, restoreMockAgent } from "../../lib/mock_agent.js";
3
+ import { createMockHttpClient } from "../../lib/mock_httpclient.js";
4
+ import { EggCore } from "@eggjs/core";
5
+ import assert from "node:assert";
6
+ import { mock, restore } from "mm";
7
+ import { debuglog } from "node:util";
8
+ import fs from "node:fs";
9
+ import http, { IncomingMessage } from "node:http";
10
+ import mergeDescriptors from "merge-descriptors";
11
+ import { isAsyncFunction, isObject } from "is-type-of";
12
+ import { Logger, Transport } from "egg-logger";
13
+
14
+ //#region src/app/extend/application.ts
15
+ const debug = debuglog("egg/mock/app/extend/application");
16
+ const ORIGIN_TYPES = Symbol("@eggjs/mock originTypes");
17
+ const BACKGROUND_TASKS = Symbol("Application#backgroundTasks");
18
+ const REUSED_CTX = Symbol("Context#reusedInSuite");
19
+ var ApplicationUnittest = class extends EggCore {
20
+ _mockHttpClient;
21
+ /**
22
+ * mock Context
23
+ * @function App#mockContext
24
+ * @param {Object} data - ctx data
25
+ * @param {Object} [options] - mock ctx options
26
+ * @example
27
+ * ```js
28
+ * const ctx = app.mockContext({
29
+ * user: {
30
+ * name: 'Jason'
31
+ * }
32
+ * });
33
+ * console.log(ctx.user.name); // Jason
34
+ *
35
+ * // controller
36
+ * module.exports = function*() {
37
+ * this.body = this.user.name;
38
+ * };
39
+ * ```
40
+ */
41
+ mockContext(data, options) {
42
+ data = data ?? {};
43
+ function mockRequest(req$1) {
44
+ for (const key in data?.headers) {
45
+ mock(req$1.headers, key, data.headers[key]);
46
+ mock(req$1.headers, key.toLowerCase(), data.headers[key]);
47
+ }
48
+ }
49
+ const mockCtxStorage = this.options.mockCtxStorage ?? true;
50
+ options = Object.assign({ mockCtxStorage }, options);
51
+ if ("_customMockContext" in this && typeof this._customMockContext === "function") this._customMockContext(data);
52
+ for (const key in data) mock(this.context, key, data[key]);
53
+ const req = this.mockRequest(data);
54
+ const res = new http.ServerResponse(req);
55
+ if (options.reuseCtxStorage !== false) {
56
+ if (this.currentContext && !this.currentContext[REUSED_CTX]) {
57
+ mockRequest(this.currentContext.request.req);
58
+ this.currentContext[REUSED_CTX] = true;
59
+ return this.currentContext;
60
+ }
61
+ }
62
+ const ctx = this.createContext(req, res);
63
+ if (options.mockCtxStorage) mock(this.ctxStorage, "getStore", () => ctx);
64
+ return ctx;
65
+ }
66
+ async mockContextScope(fn, data) {
67
+ const ctx = this.mockContext(data, {
68
+ mockCtxStorage: false,
69
+ reuseCtxStorage: false
70
+ });
71
+ return await this.ctxStorage.run(ctx, async () => {
72
+ return await fn(ctx);
73
+ });
74
+ }
75
+ /**
76
+ * mock cookie session
77
+ * @function App#mockSession
78
+ * @param {Object} data - session object
79
+ */
80
+ mockSession(data) {
81
+ if (!data) return this;
82
+ if (isObject(data) && !("save" in data)) Object.defineProperty(data, "save", {
83
+ value: () => {},
84
+ enumerable: false
85
+ });
86
+ mock(this.context, "session", data);
87
+ return this;
88
+ }
89
+ /**
90
+ * Mock service
91
+ * @function App#mockService
92
+ * @param {String} service - name
93
+ * @param {String} methodName - method
94
+ * @param {Object|Function|Error} fn - mock you data
95
+ */
96
+ mockService(service, methodName, fn) {
97
+ if (typeof service === "string") {
98
+ const splits = service.split(".");
99
+ service = this.serviceClasses;
100
+ for (const key of splits) service = service[key];
101
+ service = service.prototype || service;
102
+ }
103
+ this._mockFn(service, methodName, fn);
104
+ return this;
105
+ }
106
+ /**
107
+ * mock service that return error
108
+ * @function App#mockServiceError
109
+ * @param {String} service - name
110
+ * @param {String} methodName - method
111
+ * @param {Error} [err] - error information
112
+ */
113
+ mockServiceError(service, methodName, err) {
114
+ if (typeof err === "string") err = new Error(err);
115
+ if (!err) err = /* @__PURE__ */ new Error(`mock ${methodName} error`);
116
+ this.mockService(service, methodName, err);
117
+ return this;
118
+ }
119
+ _mockFn(obj, name, data) {
120
+ const origin = obj[name];
121
+ assert(typeof origin === "function", `property ${name} in original object must be function`);
122
+ if (!obj[ORIGIN_TYPES]) obj[ORIGIN_TYPES] = {};
123
+ let type = obj[ORIGIN_TYPES][name];
124
+ if (!type) type = obj[ORIGIN_TYPES][name] = isAsyncFunction(origin) ? "async" : "sync";
125
+ if (typeof data === "function") {
126
+ const fn = data;
127
+ if (type === "async" && !isAsyncFunction(fn)) {
128
+ mock(obj, name, function(...args) {
129
+ return new Promise((resolve) => {
130
+ resolve(fn.apply(this, args));
131
+ });
132
+ });
133
+ return;
134
+ }
135
+ mock(obj, name, fn);
136
+ return;
137
+ }
138
+ if (type === "async") {
139
+ mock(obj, name, () => {
140
+ return new Promise((resolve, reject) => {
141
+ if (data instanceof Error) return reject(data);
142
+ resolve(data);
143
+ });
144
+ });
145
+ return;
146
+ }
147
+ mock(obj, name, () => {
148
+ if (data instanceof Error) throw data;
149
+ return data;
150
+ });
151
+ }
152
+ /**
153
+ * mock request
154
+ * @function App#mockRequest
155
+ * @param {Request} req - mock request
156
+ */
157
+ mockRequest(req) {
158
+ req = { ...req };
159
+ const headers = req.headers ?? {};
160
+ for (const key in req.headers) headers[key.toLowerCase()] = req.headers[key];
161
+ if (!headers["x-forwarded-for"]) headers["x-forwarded-for"] = "127.0.0.1";
162
+ headers["x-mock-request-from"] = "@eggjs/mock";
163
+ req.headers = headers;
164
+ mergeDescriptors(req, {
165
+ query: {},
166
+ querystring: "",
167
+ host: "127.0.0.1",
168
+ hostname: "127.0.0.1",
169
+ protocol: "http",
170
+ secure: "false",
171
+ method: "GET",
172
+ url: "/",
173
+ path: "/",
174
+ socket: {
175
+ remoteAddress: "127.0.0.1",
176
+ remotePort: 7001
177
+ }
178
+ });
179
+ return req;
180
+ }
181
+ /**
182
+ * mock cookies
183
+ * @function App#mockCookies
184
+ */
185
+ mockCookies(cookies) {
186
+ if (!cookies) return this;
187
+ const createContext = this.createContext;
188
+ mock(this, "createContext", function(req, res) {
189
+ const ctx = createContext.call(this, req, res);
190
+ const getCookie = ctx.cookies.get;
191
+ mock(ctx.cookies, "get", function(key, opts) {
192
+ if (cookies[key]) return cookies[key];
193
+ return getCookie.call(this, key, opts);
194
+ });
195
+ return ctx;
196
+ });
197
+ return this;
198
+ }
199
+ /**
200
+ * mock header
201
+ * @function App#mockHeaders
202
+ */
203
+ mockHeaders(headers) {
204
+ if (!headers) return this;
205
+ const getHeader = this.request.get;
206
+ mock(this.request, "get", function(field) {
207
+ const value = findHeaders(headers, field);
208
+ if (value) return value;
209
+ return getHeader.call(this, field);
210
+ });
211
+ return this;
212
+ }
213
+ /**
214
+ * mock csrf
215
+ * @function App#mockCsrf
216
+ * @since 1.11
217
+ */
218
+ mockCsrf() {
219
+ mock(this.context, "assertCSRF", () => {});
220
+ mock(this.context, "assertCsrf", () => {});
221
+ return this;
222
+ }
223
+ /**
224
+ * mock httpclient
225
+ * @alias mockHttpClient
226
+ * @function App#mockHttpclient
227
+ */
228
+ mockHttpclient(mockUrl, mockMethod, mockResult) {
229
+ return this.mockHttpClient(mockUrl, mockMethod, mockResult);
230
+ }
231
+ /**
232
+ * mock httpclient
233
+ * @function App#mockHttpClient
234
+ */
235
+ mockHttpClient(mockUrl, mockMethod, mockResult) {
236
+ if (!this._mockHttpClient) this._mockHttpClient = createMockHttpClient(this);
237
+ this._mockHttpClient(mockUrl, mockMethod, mockResult);
238
+ return this;
239
+ }
240
+ /**
241
+ * @deprecated Please use app.mockHttpClient instead of app.mockUrllib
242
+ */
243
+ mockUrllib(mockUrl, mockMethod, mockResult) {
244
+ this.deprecate("[@eggjs/mock] Please use app.mockHttpClient instead of app.mockUrllib");
245
+ return this.mockHttpClient(mockUrl, mockMethod, mockResult);
246
+ }
247
+ /**
248
+ * get mock httpclient agent
249
+ * @function App#mockHttpclientAgent
250
+ */
251
+ mockAgent() {
252
+ return getMockAgent(this);
253
+ }
254
+ async mockAgentRestore() {
255
+ await restoreMockAgent();
256
+ }
257
+ /**
258
+ * @see mm#restore
259
+ * @function App#mockRestore
260
+ */
261
+ async mockRestore() {
262
+ await this.mockAgentRestore();
263
+ restore();
264
+ }
265
+ /**
266
+ * @see mm
267
+ * @function App#mm
268
+ */
269
+ get mm() {
270
+ return mock;
271
+ }
272
+ /**
273
+ * override loadAgent
274
+ * @function App#loadAgent
275
+ */
276
+ loadAgent() {}
277
+ /**
278
+ * mock serverEnv
279
+ * @function App#mockEnv
280
+ * @param {String} env - serverEnv
281
+ */
282
+ mockEnv(env) {
283
+ mock(this.config, "env", env);
284
+ mock(this.config, "serverEnv", env);
285
+ debug("mock env: %o", env);
286
+ return this;
287
+ }
288
+ /**
289
+ * http request helper
290
+ * @function App#httpRequest
291
+ * @return {SupertestRequest} req - supertest request
292
+ * @see https://github.com/visionmedia/supertest
293
+ */
294
+ httpRequest() {
295
+ return request(this);
296
+ }
297
+ /**
298
+ * collection logger message, then can be use on `expectLog()`
299
+ * @param {String|Logger} [logger] - logger instance, default is `app.logger`
300
+ * @function App#mockLog
301
+ */
302
+ mockLog(logger) {
303
+ logger = logger ?? this.logger;
304
+ if (typeof logger === "string") logger = this.getLogger(logger);
305
+ if ("_mockLogs" in logger && logger._mockLogs) return;
306
+ const transport = new Transport(logger.options);
307
+ const log = logger.log;
308
+ const mockLogs = [];
309
+ mock(logger, "_mockLogs", mockLogs);
310
+ mock(logger, "log", (level, args, meta) => {
311
+ const message = transport.log(level, args, meta);
312
+ mockLogs.push(message);
313
+ log.apply(logger, [
314
+ level,
315
+ args,
316
+ meta
317
+ ]);
318
+ });
319
+ }
320
+ __checkExpectLog(expectOrNot, str, logger) {
321
+ logger = logger || this.logger;
322
+ if (typeof logger === "string") logger = this.getLogger(logger);
323
+ const filepath = logger.options.file;
324
+ let content;
325
+ if ("_mockLogs" in logger && logger._mockLogs) content = logger._mockLogs.join("\n");
326
+ else content = fs.readFileSync(filepath, "utf8");
327
+ let match;
328
+ let type;
329
+ if (str instanceof RegExp) {
330
+ match = str.test(content);
331
+ type = "RegExp";
332
+ } else {
333
+ match = content.includes(String(str));
334
+ type = "String";
335
+ }
336
+ if (expectOrNot) assert(match, `Can't find ${type}:"${str}" in ${filepath}, log content: ...${content.substring(content.length - 500)}`);
337
+ else assert(!match, `Find ${type}:"${str}" in ${filepath}, log content: ...${content.substring(content.length - 500)}`);
338
+ }
339
+ /**
340
+ * expect str/regexp in the logger, if your server disk is slow, please call `mockLog()` first.
341
+ * @param {String|RegExp} str - test str or regexp
342
+ * @param {String|Logger} [logger] - logger instance, default is `ctx.logger`
343
+ * @function App#expectLog
344
+ */
345
+ expectLog(str, logger) {
346
+ this.__checkExpectLog(true, str, logger);
347
+ }
348
+ /**
349
+ * not expect str/regexp in the logger, if your server disk is slow, please call `mockLog()` first.
350
+ * @param {String|RegExp} str - test str or regexp
351
+ * @param {String|Logger} [logger] - logger instance, default is `ctx.logger`
352
+ * @function App#notExpectLog
353
+ */
354
+ notExpectLog(str, logger) {
355
+ this.__checkExpectLog(false, str, logger);
356
+ }
357
+ async backgroundTasksFinished() {
358
+ const tasks = this._backgroundTasks;
359
+ debug("waiting %d background tasks", tasks.length);
360
+ if (tasks.length === 0) return;
361
+ this._backgroundTasks = [];
362
+ await Promise.all(tasks);
363
+ debug("finished %d background tasks", tasks.length);
364
+ if (this._backgroundTasks.length) {
365
+ debug("new background tasks created: %s", this._backgroundTasks.length);
366
+ await this.backgroundTasksFinished();
367
+ }
368
+ }
369
+ get _backgroundTasks() {
370
+ if (!this[BACKGROUND_TASKS]) this[BACKGROUND_TASKS] = [];
371
+ return this[BACKGROUND_TASKS];
372
+ }
373
+ set _backgroundTasks(tasks) {
374
+ this[BACKGROUND_TASKS] = tasks;
375
+ }
376
+ };
377
+ function findHeaders(headers, key) {
378
+ if (!headers || !key) return null;
379
+ key = key.toLowerCase();
380
+ for (const headerKey in headers) if (key === headerKey.toLowerCase()) return headers[headerKey];
381
+ return null;
382
+ }
383
+
384
+ //#endregion
385
+ export { ApplicationUnittest as default };
@@ -0,0 +1,6 @@
1
+ import { Context, Next } from "@eggjs/core";
2
+
3
+ //#region src/app/middleware/cluster_app_mock.d.ts
4
+ declare const _default: () => (ctx: Context, next: Next) => Promise<void>;
5
+ //#endregion
6
+ export { _default as default };
@@ -0,0 +1,97 @@
1
+ import { Context } from "@eggjs/core";
2
+ import { debuglog } from "node:util";
3
+
4
+ //#region src/app/middleware/cluster_app_mock.ts
5
+ const debug = debuglog("egg/mock/app/middleware/cluster_app_mock");
6
+ var cluster_app_mock_default = () => {
7
+ return async function clusterAppMock(ctx, next) {
8
+ if (ctx.originalUrl !== "/__egg_mock_call_function") return next();
9
+ const body = ctx.request.body;
10
+ debug("%s %s, body: %j", ctx.method, ctx.url, body);
11
+ const { method, property, args, needResult } = body;
12
+ if (!method) {
13
+ ctx.status = 422;
14
+ ctx.body = {
15
+ success: false,
16
+ error: "Missing method"
17
+ };
18
+ return;
19
+ }
20
+ if (args && !Array.isArray(args)) {
21
+ ctx.status = 422;
22
+ ctx.body = {
23
+ success: false,
24
+ error: "args should be an Array instance"
25
+ };
26
+ return;
27
+ }
28
+ if (property) {
29
+ if (method === "__getter__") {
30
+ if (!ctx.app[property]) {
31
+ debug("property %s not exists on app", property);
32
+ ctx.status = 422;
33
+ ctx.body = {
34
+ success: false,
35
+ error: `property "${property}" not exists on app`
36
+ };
37
+ return;
38
+ }
39
+ ctx.body = {
40
+ success: true,
41
+ result: ctx.app[property]
42
+ };
43
+ return;
44
+ }
45
+ if (!ctx.app[property] || typeof ctx.app[property][method] !== "function") {
46
+ debug("property %s.%s not exists on app", property, method);
47
+ ctx.status = 422;
48
+ ctx.body = {
49
+ success: false,
50
+ error: `method "${method}" not exists on app.${property}`
51
+ };
52
+ return;
53
+ }
54
+ } else if (typeof ctx.app[method] !== "function") {
55
+ debug("method %s not exists on app", method);
56
+ ctx.status = 422;
57
+ ctx.body = {
58
+ success: false,
59
+ error: `method "${method}" not exists on app`
60
+ };
61
+ return;
62
+ }
63
+ debug("call %s with %j", method, args);
64
+ for (let i = 0; i < args.length; i++) {
65
+ const arg = args[i];
66
+ if (arg && typeof arg === "object") {
67
+ if (arg.__egg_mock_type === "function") args[i] = eval(`(function() { return ${arg.value} })()`);
68
+ else if (arg.__egg_mock_type === "error") {
69
+ const err = new Error(arg.message);
70
+ err.name = arg.name;
71
+ err.stack = arg.stack;
72
+ for (const key in arg) if (key !== "name" && key !== "message" && key !== "stack" && key !== "__egg_mock_type") err[key] = arg[key];
73
+ args[i] = err;
74
+ }
75
+ }
76
+ }
77
+ const target = property ? ctx.app[property] : ctx.app;
78
+ const fn = target[method];
79
+ try {
80
+ Promise.resolve(fn.call(target, ...args)).then((result) => {
81
+ ctx.body = needResult ? {
82
+ success: true,
83
+ result
84
+ } : { success: true };
85
+ });
86
+ } catch (err) {
87
+ ctx.status = 500;
88
+ ctx.body = {
89
+ success: false,
90
+ error: err.message
91
+ };
92
+ }
93
+ };
94
+ };
95
+
96
+ //#endregion
97
+ export { cluster_app_mock_default as default };
package/dist/app.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { EggCore, ILifecycleBoot } from "@eggjs/core";
2
+
3
+ //#region src/app.d.ts
4
+ declare class Boot implements ILifecycleBoot {
5
+ #private;
6
+ constructor(app: EggCore);
7
+ configWillLoad(): void;
8
+ }
9
+ //#endregion
10
+ export { Boot as default };
package/dist/app.js ADDED
@@ -0,0 +1,17 @@
1
+ import { EggCore } from "@eggjs/core";
2
+
3
+ //#region src/app.ts
4
+ var Boot = class {
5
+ #app;
6
+ constructor(app) {
7
+ this.#app = app;
8
+ }
9
+ configWillLoad() {
10
+ const index = this.#app.config.coreMiddleware.indexOf("securities");
11
+ if (index >= 0) this.#app.config.coreMiddleware.splice(index, 0, "clusterAppMock");
12
+ else this.#app.config.coreMiddleware.push("clusterAppMock");
13
+ }
14
+ };
15
+
16
+ //#endregion
17
+ export { Boot as default };
@@ -0,0 +1,9 @@
1
+ import ApplicationUnittest from "./app/extend/application.js";
2
+ import { getBootstrapApp } from "./lib/app_handler.js";
3
+ import proxyMock from "./index.js";
4
+ import { strict as assert } from "node:assert";
5
+
6
+ //#region src/bootstrap.d.ts
7
+ declare const app: ApplicationUnittest;
8
+ //#endregion
9
+ export { ApplicationUnittest as MockApplication, app, assert, getBootstrapApp, proxyMock as mm, proxyMock as mock };