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