@eggjs/mock 6.0.6 → 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 -171
  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 -171
  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 -510
  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
@@ -1,510 +0,0 @@
1
- import { debuglog } from 'node:util';
2
- import http, { IncomingMessage } from 'node:http';
3
- import fs from 'node:fs';
4
- import assert from 'node:assert';
5
- import mergeDescriptors from 'merge-descriptors';
6
- import { isAsyncFunction, isObject } from 'is-type-of';
7
- import { mock, restore } from 'mm';
8
- import type { HttpClient } from 'urllib';
9
- import { Transport, Logger, LoggerLevel, LoggerMeta } from 'egg-logger';
10
- import { EggCore, EggCoreOptions, Context } from '@eggjs/core';
11
- import { getMockAgent, restoreMockAgent } from '../../lib/mock_agent.js';
12
- import {
13
- createMockHttpClient, MockResultFunction,
14
- MockResultOptions,
15
- MockHttpClientMethod,
16
- } from '../../lib/mock_httpclient.js';
17
- import { request as supertestRequest, EggTestRequest } from '../../lib/supertest.js';
18
- import { MockOptions } from '../../lib/types.js';
19
-
20
- const debug = debuglog('@eggjs/mock/app/extend/application');
21
-
22
- const ORIGIN_TYPES = Symbol('@eggjs/mock originTypes');
23
- const BACKGROUND_TASKS = Symbol('Application#backgroundTasks');
24
- const REUSED_CTX = Symbol('Context#reusedInSuite');
25
-
26
- export interface MockContextOptions {
27
- /**
28
- * mock ctxStorage or not, default is `true`
29
- */
30
- mockCtxStorage?: boolean;
31
- /**
32
- * reuse ctxStorage or not, default is `true`
33
- */
34
- reuseCtxStorage?: boolean;
35
- }
36
-
37
- export interface MockContextData {
38
- headers?: Record<string, string | string[]>;
39
- [key: string]: any;
40
- }
41
-
42
- export interface MockContext extends Context {
43
- service: any;
44
- }
45
-
46
- export default abstract class ApplicationUnittest extends EggCore {
47
- [key: string]: any;
48
- declare options: MockOptions & EggCoreOptions;
49
- _mockHttpClient?: MockHttpClientMethod;
50
- declare httpclient: HttpClient;
51
-
52
- /**
53
- * mock Context
54
- * @function App#mockContext
55
- * @param {Object} data - ctx data
56
- * @param {Object} [options] - mock ctx options
57
- * @example
58
- * ```js
59
- * const ctx = app.mockContext({
60
- * user: {
61
- * name: 'Jason'
62
- * }
63
- * });
64
- * console.log(ctx.user.name); // Jason
65
- *
66
- * // controller
67
- * module.exports = function*() {
68
- * this.body = this.user.name;
69
- * };
70
- * ```
71
- */
72
- mockContext(data?: MockContextData, options?: MockContextOptions): MockContext {
73
- data = data ?? {};
74
- function mockRequest(req: IncomingMessage) {
75
- for (const key in data?.headers) {
76
- mock(req.headers, key, data.headers[key]);
77
- mock(req.headers, key.toLowerCase(), data.headers[key]);
78
- }
79
- }
80
-
81
- // try to use app.options.mockCtxStorage first
82
- const mockCtxStorage = this.options.mockCtxStorage ?? true;
83
- options = Object.assign({ mockCtxStorage }, options);
84
-
85
- if ('_customMockContext' in this && typeof this._customMockContext === 'function') {
86
- this._customMockContext(data);
87
- }
88
-
89
- // 使用者自定义mock,可以覆盖上面的 mock
90
- for (const key in data) {
91
- mock(this.context, key, data[key]);
92
- }
93
-
94
- const req = this.mockRequest(data);
95
- const res = new http.ServerResponse(req);
96
-
97
- if (options.reuseCtxStorage !== false) {
98
- if (this.currentContext && !this.currentContext[REUSED_CTX]) {
99
- mockRequest(this.currentContext.request.req);
100
- this.currentContext[REUSED_CTX] = true;
101
- return this.currentContext as MockContext;
102
- }
103
- }
104
- const ctx = this.createContext(req, res);
105
- if (options.mockCtxStorage) {
106
- mock(this.ctxStorage, 'getStore', () => ctx);
107
- }
108
- return ctx as MockContext;
109
- }
110
-
111
- async mockContextScope(fn: (ctx?: MockContext) => Promise<any>, data?: MockContextData) {
112
- const ctx = this.mockContext(data, {
113
- mockCtxStorage: false,
114
- reuseCtxStorage: false,
115
- });
116
- return await this.ctxStorage.run(ctx as any, async () => {
117
- return await fn(ctx);
118
- });
119
- }
120
-
121
- /**
122
- * mock cookie session
123
- * @function App#mockSession
124
- * @param {Object} data - session object
125
- */
126
- mockSession(data: any) {
127
- if (!data) {
128
- return this;
129
- }
130
-
131
- if (isObject(data) && !('save' in data)) {
132
- // keep session.save() work
133
- Object.defineProperty(data, 'save', {
134
- value: () => {},
135
- enumerable: false,
136
- });
137
- }
138
- mock(this.context, 'session', data);
139
- return this;
140
- }
141
-
142
- /**
143
- * Mock service
144
- * @function App#mockService
145
- * @param {String} service - name
146
- * @param {String} methodName - method
147
- * @param {Object|Function|Error} fn - mock you data
148
- */
149
- mockService(service: string | any, methodName: string, fn: any) {
150
- if (typeof service === 'string') {
151
- const splits = service.split('.');
152
- service = this.serviceClasses;
153
- for (const key of splits) {
154
- service = service[key];
155
- }
156
- service = service.prototype || service;
157
- }
158
- this._mockFn(service, methodName, fn);
159
- return this;
160
- }
161
-
162
- /**
163
- * mock service that return error
164
- * @function App#mockServiceError
165
- * @param {String} service - name
166
- * @param {String} methodName - method
167
- * @param {Error} [err] - error information
168
- */
169
- mockServiceError(service: string | any, methodName: string, err?: string | Error) {
170
- if (typeof err === 'string') {
171
- err = new Error(err);
172
- }
173
- if (!err) {
174
- // mockServiceError(service, methodName)
175
- err = new Error(`mock ${methodName} error`);
176
- }
177
- this.mockService(service, methodName, err);
178
- return this;
179
- }
180
-
181
- _mockFn(obj: any, name: string, data: any) {
182
- const origin = obj[name];
183
- assert(typeof origin === 'function', `property ${name} in original object must be function`);
184
-
185
- // keep origin properties' type to support mock multi times
186
- if (!obj[ORIGIN_TYPES]) obj[ORIGIN_TYPES] = {};
187
- let type = obj[ORIGIN_TYPES][name];
188
- if (!type) {
189
- type = obj[ORIGIN_TYPES][name] = isAsyncFunction(origin) ? 'async' : 'sync';
190
- }
191
-
192
- if (typeof data === 'function') {
193
- const fn = data;
194
- // if original is async function
195
- // but the mock function is normal function, need to change it return a promise
196
- if (type === 'async' && !isAsyncFunction(fn)) {
197
- mock(obj, name, function(this: any, ...args: any[]) {
198
- return new Promise(resolve => {
199
- resolve(fn.apply(this, args));
200
- });
201
- });
202
- return;
203
- }
204
-
205
- mock(obj, name, fn);
206
- return;
207
- }
208
-
209
- if (type === 'async') {
210
- mock(obj, name, () => {
211
- return new Promise((resolve, reject) => {
212
- if (data instanceof Error) return reject(data);
213
- resolve(data);
214
- });
215
- });
216
- return;
217
- }
218
-
219
- mock(obj, name, () => {
220
- if (data instanceof Error) {
221
- throw data;
222
- }
223
- return data;
224
- });
225
- }
226
-
227
- /**
228
- * mock request
229
- * @function App#mockRequest
230
- * @param {Request} req - mock request
231
- */
232
- mockRequest(req: MockContextData) {
233
- req = { ...req };
234
- const headers = req.headers ?? {};
235
- for (const key in req.headers) {
236
- headers[key.toLowerCase()] = req.headers[key];
237
- }
238
- if (!headers['x-forwarded-for']) {
239
- headers['x-forwarded-for'] = '127.0.0.1';
240
- }
241
- headers['x-mock-request-from'] = '@eggjs/mock';
242
- req.headers = headers;
243
- mergeDescriptors(req, {
244
- query: {},
245
- querystring: '',
246
- host: '127.0.0.1',
247
- hostname: '127.0.0.1',
248
- protocol: 'http',
249
- secure: 'false',
250
- method: 'GET',
251
- url: '/',
252
- path: '/',
253
- socket: {
254
- remoteAddress: '127.0.0.1',
255
- remotePort: 7001,
256
- },
257
- });
258
- return req as IncomingMessage;
259
- }
260
-
261
- /**
262
- * mock cookies
263
- * @function App#mockCookies
264
- */
265
- mockCookies(cookies: Record<string, string | string[]>) {
266
- if (!cookies) {
267
- return this;
268
- }
269
- const createContext = this.createContext;
270
- mock(this, 'createContext', function(this: any, req: any, res: any) {
271
- const ctx = createContext.call(this, req, res);
272
- const getCookie = ctx.cookies.get;
273
- mock(ctx.cookies, 'get', function(this: any, key: string, opts: any) {
274
- if (cookies[key]) {
275
- return cookies[key];
276
- }
277
- return getCookie.call(this, key, opts);
278
- });
279
- return ctx;
280
- });
281
- return this;
282
- }
283
-
284
- /**
285
- * mock header
286
- * @function App#mockHeaders
287
- */
288
- mockHeaders(headers: Record<string, string | string[]>) {
289
- if (!headers) {
290
- return this;
291
- }
292
- const getHeader = this.request.get;
293
- mock(this.request, 'get', function(this: unknown, field: string) {
294
- const value = findHeaders(headers, field);
295
- if (value) return value;
296
- return getHeader.call(this, field);
297
- });
298
- return this;
299
- }
300
-
301
- /**
302
- * mock csrf
303
- * @function App#mockCsrf
304
- * @since 1.11
305
- */
306
- mockCsrf() {
307
- mock(this.context, 'assertCSRF', () => {});
308
- mock(this.context, 'assertCsrf', () => {});
309
- return this;
310
- }
311
-
312
- /**
313
- * mock httpclient
314
- * @alias mockHttpClient
315
- * @function App#mockHttpclient
316
- */
317
- mockHttpclient(mockUrl: string | RegExp, mockMethod: string | string[] | MockResultOptions | MockResultFunction, mockResult?: MockResultOptions | MockResultFunction | string) {
318
- return this.mockHttpClient(mockUrl, mockMethod, mockResult);
319
- }
320
-
321
- /**
322
- * mock httpclient
323
- * @function App#mockHttpClient
324
- */
325
- mockHttpClient(mockUrl: string | RegExp, mockMethod: string | string[] | MockResultOptions | MockResultFunction, mockResult?: MockResultOptions | MockResultFunction | string) {
326
- if (!this._mockHttpClient) {
327
- this._mockHttpClient = createMockHttpClient(this);
328
- }
329
- this._mockHttpClient(mockUrl, mockMethod, mockResult);
330
- return this;
331
- }
332
-
333
- /**
334
- * @deprecated Please use app.mockHttpClient instead of app.mockUrllib
335
- */
336
- mockUrllib(mockUrl: string | RegExp, mockMethod: string | string[] | MockResultOptions | MockResultFunction, mockResult?: MockResultOptions | MockResultFunction | string) {
337
- this.deprecate('[@eggjs/mock] Please use app.mockHttpClient instead of app.mockUrllib');
338
- return this.mockHttpClient(mockUrl, mockMethod, mockResult);
339
- }
340
-
341
- /**
342
- * get mock httpclient agent
343
- * @function App#mockHttpclientAgent
344
- */
345
- mockAgent() {
346
- return getMockAgent(this);
347
- }
348
-
349
- async mockAgentRestore() {
350
- await restoreMockAgent();
351
- }
352
-
353
- /**
354
- * @see mm#restore
355
- * @function App#mockRestore
356
- */
357
- async mockRestore() {
358
- await this.mockAgentRestore();
359
- restore();
360
- }
361
-
362
- /**
363
- * @see mm
364
- * @function App#mm
365
- */
366
- get mm() {
367
- return mock;
368
- }
369
-
370
- /**
371
- * override loadAgent
372
- * @function App#loadAgent
373
- */
374
- loadAgent() {}
375
-
376
- /**
377
- * mock serverEnv
378
- * @function App#mockEnv
379
- * @param {String} env - serverEnv
380
- */
381
- mockEnv(env: string) {
382
- mock(this.config, 'env', env);
383
- mock(this.config, 'serverEnv', env);
384
- debug('mock env: %o', env);
385
- return this;
386
- }
387
-
388
- /**
389
- * http request helper
390
- * @function App#httpRequest
391
- * @return {SupertestRequest} req - supertest request
392
- * @see https://github.com/visionmedia/supertest
393
- */
394
- httpRequest(): EggTestRequest {
395
- return supertestRequest(this);
396
- }
397
-
398
- /**
399
- * collection logger message, then can be use on `expectLog()`
400
- * @param {String|Logger} [logger] - logger instance, default is `app.logger`
401
- * @function App#mockLog
402
- */
403
- mockLog(logger?: string | Logger) {
404
- logger = logger ?? this.logger;
405
- if (typeof logger === 'string') {
406
- logger = this.getLogger(logger);
407
- }
408
- // make sure mock once
409
- if ('_mockLogs' in logger && logger._mockLogs) return;
410
-
411
- const transport = new Transport(logger.options);
412
- // https://github.com/eggjs/egg-logger/blob/master/lib/logger.js#L64
413
- const log = logger.log;
414
- const mockLogs: string[] = [];
415
- mock(logger, '_mockLogs', mockLogs);
416
- mock(logger, 'log', (level: LoggerLevel, args: any[], meta: LoggerMeta) => {
417
- const message = transport.log(level, args, meta);
418
- mockLogs.push(message);
419
- log.apply(logger, [ level, args, meta ]);
420
- });
421
- }
422
-
423
- __checkExpectLog(expectOrNot: boolean, str: string | RegExp, logger?: string | Logger) {
424
- logger = logger || this.logger;
425
- if (typeof logger === 'string') {
426
- logger = this.getLogger(logger);
427
- }
428
- const filepath = logger.options.file;
429
- let content;
430
- if ('_mockLogs' in logger && logger._mockLogs) {
431
- content = (logger._mockLogs as string[]).join('\n');
432
- } else {
433
- content = fs.readFileSync(filepath, 'utf8');
434
- }
435
- let match;
436
- let type;
437
- if (str instanceof RegExp) {
438
- match = str.test(content);
439
- type = 'RegExp';
440
- } else {
441
- match = content.includes(String(str));
442
- type = 'String';
443
- }
444
- if (expectOrNot) {
445
- assert(match,
446
- `Can't find ${type}:"${str}" in ${filepath}, log content: ...${content.substring(content.length - 500)}`);
447
- } else {
448
- assert(!match,
449
- `Find ${type}:"${str}" in ${filepath}, log content: ...${content.substring(content.length - 500)}`);
450
- }
451
- }
452
-
453
- /**
454
- * expect str/regexp in the logger, if your server disk is slow, please call `mockLog()` first.
455
- * @param {String|RegExp} str - test str or regexp
456
- * @param {String|Logger} [logger] - logger instance, default is `ctx.logger`
457
- * @function App#expectLog
458
- */
459
- expectLog(str: string | RegExp, logger?: string | Logger) {
460
- this.__checkExpectLog(true, str, logger);
461
- }
462
-
463
- /**
464
- * not expect str/regexp in the logger, if your server disk is slow, please call `mockLog()` first.
465
- * @param {String|RegExp} str - test str or regexp
466
- * @param {String|Logger} [logger] - logger instance, default is `ctx.logger`
467
- * @function App#notExpectLog
468
- */
469
- notExpectLog(str: string | RegExp, logger?: string | Logger) {
470
- this.__checkExpectLog(false, str, logger);
471
- }
472
-
473
- async backgroundTasksFinished() {
474
- const tasks = this._backgroundTasks;
475
- debug('waiting %d background tasks', tasks.length);
476
- if (tasks.length === 0) return;
477
-
478
- this._backgroundTasks = [];
479
- await Promise.all(tasks);
480
- debug('finished %d background tasks', tasks.length);
481
- if (this._backgroundTasks.length) {
482
- debug('new background tasks created: %s', this._backgroundTasks.length);
483
- await this.backgroundTasksFinished();
484
- }
485
- }
486
-
487
- get _backgroundTasks() {
488
- if (!this[BACKGROUND_TASKS]) {
489
- this[BACKGROUND_TASKS] = [];
490
- }
491
- return this[BACKGROUND_TASKS] as Promise<any>[];
492
- }
493
-
494
- set _backgroundTasks(tasks) {
495
- this[BACKGROUND_TASKS] = tasks;
496
- }
497
- }
498
-
499
- function findHeaders(headers: Record<string, any>, key: string) {
500
- if (!headers || !key) {
501
- return null;
502
- }
503
- key = key.toLowerCase();
504
- for (const headerKey in headers) {
505
- if (key === headerKey.toLowerCase()) {
506
- return headers[headerKey];
507
- }
508
- }
509
- return null;
510
- }
@@ -1,102 +0,0 @@
1
- import { debuglog } from 'node:util';
2
- import { Context, Next } from '@eggjs/core';
3
-
4
- const debug = debuglog('@eggjs/mock/app/middleware/cluster_app_mock');
5
-
6
- export default () => {
7
- return async function clusterAppMock(ctx: Context, next: Next) {
8
- // use originalUrl to make sure other middlewares can't change request url
9
- if (ctx.originalUrl !== '/__egg_mock_call_function') {
10
- return next();
11
- }
12
- const body = (ctx.request as any).body;
13
- debug('%s %s, body: %j', ctx.method, ctx.url, body);
14
- const { method, property, args, needResult } = body;
15
- if (!method) {
16
- ctx.status = 422;
17
- ctx.body = {
18
- success: false,
19
- error: 'Missing method',
20
- };
21
- return;
22
- }
23
- if (args && !Array.isArray(args)) {
24
- ctx.status = 422;
25
- ctx.body = {
26
- success: false,
27
- error: 'args should be an Array instance',
28
- };
29
- return;
30
- }
31
- if (property) {
32
- // method: '__getter__' and property: 'config'
33
- if (method === '__getter__') {
34
- if (!ctx.app[property]) {
35
- debug('property %s not exists on app', property);
36
- ctx.status = 422;
37
- ctx.body = {
38
- success: false,
39
- error: `property "${property}" not exists on app`,
40
- };
41
- return;
42
- }
43
- ctx.body = { success: true, result: ctx.app[property] };
44
- return;
45
- }
46
-
47
- if (!ctx.app[property] || typeof (ctx.app as any)[property][method] !== 'function') {
48
- debug('property %s.%s not exists on app', property, method);
49
- ctx.status = 422;
50
- ctx.body = {
51
- success: false,
52
- error: `method "${method}" not exists on app.${property}`,
53
- };
54
- return;
55
- }
56
- } else {
57
- if (typeof ctx.app[method] !== 'function') {
58
- debug('method %s not exists on app', method);
59
- ctx.status = 422;
60
- ctx.body = {
61
- success: false,
62
- error: `method "${method}" not exists on app`,
63
- };
64
- return;
65
- }
66
- }
67
-
68
- debug('call %s with %j', method, args);
69
-
70
- for (let i = 0; i < args.length; i++) {
71
- const arg = args[i];
72
- if (arg && typeof arg === 'object') {
73
- // convert __egg_mock_type back to function
74
- if (arg.__egg_mock_type === 'function') {
75
- // eslint-disable-next-line
76
- args[i] = eval(`(function() { return ${arg.value} })()`);
77
- } else if (arg.__egg_mock_type === 'error') {
78
- const err: any = new Error(arg.message);
79
- err.name = arg.name;
80
- err.stack = arg.stack;
81
- for (const key in arg) {
82
- if (key !== 'name' && key !== 'message' && key !== 'stack' && key !== '__egg_mock_type') {
83
- err[key] = arg[key];
84
- }
85
- }
86
- args[i] = err;
87
- }
88
- }
89
- }
90
-
91
- const target: any = property ? ctx.app[property] : ctx.app;
92
- const fn = target[method];
93
- try {
94
- Promise.resolve(fn.call(target, ...args)).then(result => {
95
- ctx.body = needResult ? { success: true, result } : { success: true };
96
- });
97
- } catch (err: any) {
98
- ctx.status = 500;
99
- ctx.body = { success: false, error: err.message };
100
- }
101
- };
102
- };
package/src/app.ts DELETED
@@ -1,18 +0,0 @@
1
- import { ILifecycleBoot, EggCore } from '@eggjs/core';
2
-
3
- export default class Boot implements ILifecycleBoot {
4
- #app: EggCore;
5
- constructor(app: EggCore) {
6
- this.#app = app;
7
- }
8
-
9
- configWillLoad() {
10
- // make sure clusterAppMock position before securities
11
- const index = this.#app.config.coreMiddleware.indexOf('securities');
12
- if (index >= 0) {
13
- this.#app.config.coreMiddleware.splice(index, 0, 'clusterAppMock');
14
- } else {
15
- this.#app.config.coreMiddleware.push('clusterAppMock');
16
- }
17
- }
18
- }
package/src/bootstrap.ts DELETED
@@ -1,25 +0,0 @@
1
- import { strict as assert } from 'node:assert';
2
- import path from 'node:path';
3
- import { readJSONSync } from 'utility';
4
- import mm, { mock, MockApplication } from './index.js';
5
- import { getBootstrapApp, setupApp } from './lib/app_handler.js';
6
- import { getEggOptions } from './lib/utils.js';
7
-
8
- const options = getEggOptions();
9
-
10
- // throw error when an egg plugin test is using bootstrap
11
- const pkgInfo = readJSONSync(path.join(options.baseDir || process.cwd(), 'package.json'));
12
- if (pkgInfo.eggPlugin) {
13
- throw new Error('DO NOT USE bootstrap to test plugin');
14
- }
15
-
16
- const app = setupApp();
17
-
18
- export {
19
- assert,
20
- getBootstrapApp,
21
- app,
22
- mm,
23
- mock,
24
- MockApplication,
25
- };