@midwayjs/mock 3.0.0-alpha.9 → 3.0.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,49 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ # [3.0.0-beta.4](https://github.com/midwayjs/midway/compare/v3.0.0-beta.3...v3.0.0-beta.4) (2021-11-24)
7
+
8
+
9
+ ### Features
10
+
11
+ * add i18n ([#1375](https://github.com/midwayjs/midway/issues/1375)) ([bffefe0](https://github.com/midwayjs/midway/commit/bffefe07afe45777d49b5a76b9ab17fc2b9d9a55))
12
+
13
+
14
+
15
+
16
+
17
+ # [3.0.0-beta.3](https://github.com/midwayjs/midway/compare/v3.0.0-beta.2...v3.0.0-beta.3) (2021-11-18)
18
+
19
+ **Note:** Version bump only for package @midwayjs/mock
20
+
21
+
22
+
23
+
24
+
25
+ # [3.0.0-beta.2](https://github.com/midwayjs/midway/compare/v3.0.0-beta.1...v3.0.0-beta.2) (2021-11-16)
26
+
27
+ **Note:** Version bump only for package @midwayjs/mock
28
+
29
+
30
+
31
+
32
+
33
+ # [3.0.0-beta.1](https://github.com/midwayjs/midway/compare/v2.12.4...v3.0.0-beta.1) (2021-11-14)
34
+
35
+
36
+ ### Bug Fixes
37
+
38
+ * static prefix ([#1321](https://github.com/midwayjs/midway/issues/1321)) ([31fe961](https://github.com/midwayjs/midway/commit/31fe961931fed7656a144b1682ee4c4bb25fdff5))
39
+
40
+
41
+ ### Features
42
+
43
+ * add redis component ([#1270](https://github.com/midwayjs/midway/issues/1270)) ([09c993a](https://github.com/midwayjs/midway/commit/09c993ac308d26fa9c742a659471c3f4cf5c5782))
44
+
45
+
46
+
47
+
48
+
6
49
  ## [2.12.3](https://github.com/midwayjs/midway/compare/v2.12.2...v2.12.3) (2021-08-09)
7
50
 
8
51
  **Note:** Version bump only for package @midwayjs/mock
@@ -0,0 +1,5 @@
1
+ export * from './http';
2
+ export * from './rabbitMQ';
3
+ export * from './socketio';
4
+ export * from './ws';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
+ };
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ __exportStar(require("./http"), exports);
14
+ __exportStar(require("./rabbitMQ"), exports);
15
+ __exportStar(require("./socketio"), exports);
16
+ __exportStar(require("./ws"), exports);
17
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,18 @@
1
+ import { IMidwayApplication, IMidwayFramework } from '@midwayjs/core';
2
+ import { ComponentModule, MockAppConfigurationOptions } from './interface';
3
+ export declare function create<T extends IMidwayFramework<any, any, U>, U = T['configurationOptions']>(appDir?: string, options?: MockAppConfigurationOptions, customFramework?: {
4
+ new (...args: any[]): T;
5
+ } | ComponentModule): Promise<T>;
6
+ export declare function createApp<T extends IMidwayFramework<any, any, U>, U = T['configurationOptions'], Y = ReturnType<T['getApplication']>>(baseDir?: string, options?: U & MockAppConfigurationOptions, customFramework?: {
7
+ new (...args: any[]): T;
8
+ } | ComponentModule): Promise<IMidwayApplication<any, any>>;
9
+ export declare function close(app: IMidwayApplication, options?: {
10
+ cleanLogsDir?: boolean;
11
+ cleanTempDir?: boolean;
12
+ sleep?: number;
13
+ }): Promise<void>;
14
+ export declare function createFunctionApp<T extends IMidwayFramework<any, any, U>, U = T['configurationOptions'], Y = ReturnType<T['getApplication']>>(baseDir?: string, options?: MockAppConfigurationOptions, customFrameworkName?: {
15
+ new (...args: any[]): T;
16
+ } | ComponentModule): Promise<Y>;
17
+ export declare function createLightApp(baseDir?: string, options?: MockAppConfigurationOptions): Promise<IMidwayApplication>;
18
+ //# sourceMappingURL=creator.d.ts.map
@@ -0,0 +1,147 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createLightApp = exports.createFunctionApp = exports.close = exports.createApp = exports.create = void 0;
4
+ const core_1 = require("@midwayjs/core");
5
+ const path_1 = require("path");
6
+ const fs_extra_1 = require("fs-extra");
7
+ const decorator_1 = require("@midwayjs/decorator");
8
+ const logger_1 = require("@midwayjs/logger");
9
+ const utils_1 = require("./utils");
10
+ const util_1 = require("util");
11
+ const debug = (0, util_1.debuglog)('midway:debug');
12
+ process.setMaxListeners(0);
13
+ async function create(appDir = process.cwd(), options, customFramework) {
14
+ debug(`[mock]: Create app, appDir="${appDir}"`);
15
+ process.env.MIDWAY_TS_MODE = 'true';
16
+ // 处理测试的 fixtures
17
+ if (!(0, path_1.isAbsolute)(appDir)) {
18
+ appDir = (0, path_1.join)(process.cwd(), 'test', 'fixtures', appDir);
19
+ }
20
+ (0, logger_1.clearAllLoggers)();
21
+ options = options || {};
22
+ if (options.baseDir) {
23
+ (0, core_1.safeRequire)((0, path_1.join)(`${options.baseDir}`, 'interface'));
24
+ }
25
+ else {
26
+ options.baseDir = `${appDir}/src`;
27
+ (0, core_1.safeRequire)((0, path_1.join)(`${options.baseDir}`, 'interface'));
28
+ }
29
+ if (!options.configurationModule && customFramework) {
30
+ options.configurationModule =
31
+ (0, utils_1.transformFrameworkToConfiguration)(customFramework);
32
+ }
33
+ if (customFramework === null || customFramework === void 0 ? void 0 : customFramework['Configuration']) {
34
+ options.configurationModule = customFramework;
35
+ customFramework = customFramework['Framework'];
36
+ }
37
+ const container = new core_1.MidwayContainer();
38
+ const bindModuleMap = new WeakMap();
39
+ // 这里设置是因为在 midway 单测中会不断的复用装饰器元信息,又不能清理缓存,所以在这里做一些过滤
40
+ container.onBeforeBind(target => {
41
+ bindModuleMap.set(target, true);
42
+ });
43
+ const originMethod = container.listModule;
44
+ container.listModule = key => {
45
+ const modules = originMethod.call(container, key);
46
+ if (key === decorator_1.CONFIGURATION_KEY) {
47
+ return modules;
48
+ }
49
+ return modules.filter((module) => {
50
+ var _a;
51
+ if (bindModuleMap.has(module)) {
52
+ return true;
53
+ }
54
+ else {
55
+ debug('[mock] Filter "%o" module without binding when list module %s.', (_a = module.name) !== null && _a !== void 0 ? _a : module, key);
56
+ return false;
57
+ }
58
+ });
59
+ };
60
+ options.applicationContext = container;
61
+ await (0, core_1.initializeGlobalApplicationContext)({
62
+ ...options,
63
+ appDir,
64
+ configurationModule: []
65
+ .concat(options.configurationModule)
66
+ .concat((0, core_1.safeRequire)((0, path_1.join)(options.baseDir, 'configuration'))),
67
+ });
68
+ if (customFramework) {
69
+ return container.getAsync(customFramework);
70
+ }
71
+ else {
72
+ const frameworkService = await container.getAsync(core_1.MidwayFrameworkService);
73
+ return frameworkService.getMainFramework();
74
+ }
75
+ }
76
+ exports.create = create;
77
+ async function createApp(baseDir = process.cwd(), options, customFramework) {
78
+ const framework = await create(baseDir, options, customFramework);
79
+ return framework.getApplication();
80
+ }
81
+ exports.createApp = createApp;
82
+ async function close(app, options) {
83
+ if (!app)
84
+ return;
85
+ debug(`[mock]: Closing app, appDir=${app.getAppDir()}`);
86
+ options = options || {};
87
+ await (0, core_1.destroyGlobalApplicationContext)(app.getApplicationContext());
88
+ if ((0, utils_1.isTestEnvironment)()) {
89
+ // clean first
90
+ if (options.cleanLogsDir && !(0, utils_1.isWin32)()) {
91
+ await (0, fs_extra_1.remove)((0, path_1.join)(app.getAppDir(), 'logs'));
92
+ }
93
+ if (core_1.MidwayFrameworkType.WEB === app.getFrameworkType()) {
94
+ if (options.cleanTempDir && !(0, utils_1.isWin32)()) {
95
+ await (0, fs_extra_1.remove)((0, path_1.join)(app.getAppDir(), 'run'));
96
+ }
97
+ }
98
+ if (options.sleep > 0) {
99
+ await (0, decorator_1.sleep)(options.sleep);
100
+ }
101
+ else {
102
+ await (0, decorator_1.sleep)(50);
103
+ }
104
+ }
105
+ }
106
+ exports.close = close;
107
+ async function createFunctionApp(baseDir = process.cwd(), options, customFrameworkName) {
108
+ const customFramework = customFrameworkName !== null && customFrameworkName !== void 0 ? customFrameworkName : (0, utils_1.findFirstExistModule)([
109
+ process.env.MIDWAY_SERVERLESS_APP_NAME,
110
+ '@ali/serverless-app',
111
+ '@midwayjs/serverless-app',
112
+ ]);
113
+ const framework = await createApp(baseDir, {
114
+ ...options,
115
+ configurationModule: (0, utils_1.transformFrameworkToConfiguration)(customFramework),
116
+ });
117
+ framework.configurationOptions = options;
118
+ return framework;
119
+ }
120
+ exports.createFunctionApp = createFunctionApp;
121
+ /**
122
+ * 一个全量的空框架
123
+ */
124
+ class LightFramework extends core_1.BaseFramework {
125
+ getFrameworkType() {
126
+ return core_1.MidwayFrameworkType.LIGHT;
127
+ }
128
+ async run() { }
129
+ async applicationInitialize(options) {
130
+ this.app = {};
131
+ this.defineApplicationProperties();
132
+ }
133
+ configure() {
134
+ return {};
135
+ }
136
+ }
137
+ async function createLightApp(baseDir = '', options = {}) {
138
+ (0, decorator_1.Framework)()(LightFramework);
139
+ return createApp(baseDir, {
140
+ ...options,
141
+ configurationModule: [
142
+ (0, utils_1.transformFrameworkToConfiguration)(LightFramework),
143
+ ].concat(options === null || options === void 0 ? void 0 : options.configurationModule),
144
+ });
145
+ }
146
+ exports.createLightApp = createLightApp;
147
+ //# sourceMappingURL=creator.js.map
package/dist/index.d.ts CHANGED
@@ -1,11 +1,4 @@
1
- export { create, close, createApp, createFunctionApp, createBootstrap, } from './utils';
2
- export * from './client/http';
3
- export * from './client/rabbitMQ';
4
- export * from './client/socketio';
5
- export * from './client/ws';
6
- /**
7
- * @deprecated below
8
- */
9
- export * from 'egg-mock';
10
- export * from './interface';
1
+ export { create, close, createApp, createFunctionApp, createLightApp, } from './creator';
2
+ export * from './client/index';
3
+ export { transformFrameworkToConfiguration } from './utils';
11
4
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -10,20 +10,14 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
10
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
11
  };
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
- exports.createBootstrap = exports.createFunctionApp = exports.createApp = exports.close = exports.create = void 0;
13
+ exports.transformFrameworkToConfiguration = exports.createLightApp = exports.createFunctionApp = exports.createApp = exports.close = exports.create = void 0;
14
+ var creator_1 = require("./creator");
15
+ Object.defineProperty(exports, "create", { enumerable: true, get: function () { return creator_1.create; } });
16
+ Object.defineProperty(exports, "close", { enumerable: true, get: function () { return creator_1.close; } });
17
+ Object.defineProperty(exports, "createApp", { enumerable: true, get: function () { return creator_1.createApp; } });
18
+ Object.defineProperty(exports, "createFunctionApp", { enumerable: true, get: function () { return creator_1.createFunctionApp; } });
19
+ Object.defineProperty(exports, "createLightApp", { enumerable: true, get: function () { return creator_1.createLightApp; } });
20
+ __exportStar(require("./client/index"), exports);
14
21
  var utils_1 = require("./utils");
15
- Object.defineProperty(exports, "create", { enumerable: true, get: function () { return utils_1.create; } });
16
- Object.defineProperty(exports, "close", { enumerable: true, get: function () { return utils_1.close; } });
17
- Object.defineProperty(exports, "createApp", { enumerable: true, get: function () { return utils_1.createApp; } });
18
- Object.defineProperty(exports, "createFunctionApp", { enumerable: true, get: function () { return utils_1.createFunctionApp; } });
19
- Object.defineProperty(exports, "createBootstrap", { enumerable: true, get: function () { return utils_1.createBootstrap; } });
20
- __exportStar(require("./client/http"), exports);
21
- __exportStar(require("./client/rabbitMQ"), exports);
22
- __exportStar(require("./client/socketio"), exports);
23
- __exportStar(require("./client/ws"), exports);
24
- /**
25
- * @deprecated below
26
- */
27
- __exportStar(require("egg-mock"), exports);
28
- __exportStar(require("./interface"), exports);
22
+ Object.defineProperty(exports, "transformFrameworkToConfiguration", { enumerable: true, get: function () { return utils_1.transformFrameworkToConfiguration; } });
29
23
  //# sourceMappingURL=index.js.map
@@ -1,83 +1,9 @@
1
- import { MockApplication, MockOption } from 'egg-mock';
2
- import { IApplicationContext, IMidwayContainer } from '@midwayjs/core';
3
- /**
4
- * @deprecated
5
- */
6
- export interface MidwayApplicationOptions extends MockOption {
7
- baseDir?: string;
8
- framework?: string;
9
- plugin?: any;
10
- plugins?: any;
11
- container?: any;
12
- typescript?: boolean;
13
- worker?: number;
14
- }
15
- /**
16
- * @deprecated
17
- */
18
- declare type EggContext = ReturnType<MockApplication['mockContext']>;
19
- /**
20
- * @deprecated
21
- */
22
- export interface MidwayMockContext extends EggContext {
23
- requestContext: IMidwayContainer;
24
- }
25
- /**
26
- * @deprecated
27
- */
28
- export declare type MockClassFunctionHandler = (this: MidwayMockApplication, className: string, methodName: string, fnOrData: any) => any;
29
- /**
30
- * @deprecated
31
- */
32
- export interface MidwayMockApplication extends MockApplication {
33
- applicationContext: IMidwayContainer;
34
- pluginContext: IMidwayContainer;
35
- appDir: string;
36
- baseDir: string;
37
- enablePlugins: any;
38
- getApplicationContext(): IMidwayContainer;
39
- getPluginContext(): IApplicationContext;
40
- getPlugin(pluginName: string): any;
41
- getLogger(name?: string): any;
42
- getConfig(key?: string): any;
43
- mockContext(data?: any): MidwayMockContext;
44
- mockClassFunction: MockClassFunctionHandler;
45
- }
46
- interface ResultObject {
47
- data?: string | object;
48
- status?: number;
49
- headers?: any;
50
- }
51
- declare type ResultFunction = (url?: string, opts?: any) => ResultObject | string | void;
52
- declare type MockHttpClientResult = ResultObject | ResultFunction | string;
53
- declare module 'egg' {
54
- interface Application {
55
- /**
56
- * mock Context
57
- */
58
- mockContext(data?: any): Context;
59
- /**
60
- * mock cookie session
61
- */
62
- mockSession(data: any): Application;
63
- mockCookies(cookies: any): Application;
64
- mockHeaders(headers: any): Application;
65
- /**
66
- * Mock service
67
- */
68
- mockService(service: string, methodName: string, fn: any): Application;
69
- /**
70
- * mock service that return error
71
- */
72
- mockServiceError(service: string, methodName: string, err?: Error): Application;
73
- mockHttpclient(mockUrl: string | RegExp, mockMethod: string | string[], mockResult: MockHttpClientResult): Application;
74
- mockHttpclient(mockUrl: string | RegExp, mockResult: MockHttpClientResult): Application;
75
- /**
76
- * mock csrf
77
- */
78
- mockCsrf(): Application;
79
- mockClassFunction(className: string, methodName: string, fnOrData: any): Application;
80
- }
81
- }
82
- export {};
1
+ import { IMidwayBootstrapOptions } from '@midwayjs/core';
2
+ export interface MockAppConfigurationOptions extends IMidwayBootstrapOptions {
3
+ cleanLogsDir?: boolean;
4
+ cleanTempDir?: boolean;
5
+ }
6
+ export declare type ComponentModule = {
7
+ Configuration: new () => any;
8
+ };
83
9
  //# sourceMappingURL=interface.d.ts.map
package/dist/utils.d.ts CHANGED
@@ -1,25 +1,13 @@
1
- import { IMidwayApplication, IMidwayFramework, MidwayFrameworkType } from '@midwayjs/core';
2
- export declare type MockAppConfigurationOptions = {
3
- cleanLogsDir?: boolean;
4
- cleanTempDir?: boolean;
5
- entryFile?: string;
6
- baseDir?: string;
7
- bootstrapTimeout?: number;
1
+ import { IMidwayFramework } from '@midwayjs/core';
2
+ export declare function isTestEnvironment(): boolean;
3
+ export declare function isWin32(): boolean;
4
+ export declare function findFirstExistModule(moduleList: any): string;
5
+ /**
6
+ * transform a framework component or framework module to configuration class
7
+ * @param Framework
8
+ */
9
+ export declare function transformFrameworkToConfiguration<T extends IMidwayFramework<any, any, any>>(Framework: any): {
10
+ [key: string]: any;
11
+ Configuration: any;
8
12
  };
9
- export declare function create<T extends IMidwayFramework<any, U>, U = T['configurationOptions']>(appDir?: string, options?: U & MockAppConfigurationOptions, customFrameworkName?: string | MidwayFrameworkType | any): Promise<T>;
10
- export declare function createApp<T extends IMidwayFramework<any, U>, U = T['configurationOptions'], Y = ReturnType<T['getApplication']>>(baseDir?: string, options?: U & MockAppConfigurationOptions, customFrameworkName?: string | MidwayFrameworkType | any): Promise<Y>;
11
- export declare function close(app: IMidwayApplication | IMidwayFramework<any, any>, options?: {
12
- cleanLogsDir?: boolean;
13
- cleanTempDir?: boolean;
14
- sleep?: number;
15
- }): Promise<void>;
16
- export declare function createFunctionApp<T extends IMidwayFramework<any, U>, U = T['configurationOptions'], Y = ReturnType<T['getApplication']>>(baseDir?: string, options?: U & MockAppConfigurationOptions, customFrameworkName?: string | MidwayFrameworkType | any): Promise<Y>;
17
- declare class BootstrapAppStarter {
18
- getApp(type: MidwayFrameworkType): IMidwayApplication<any>;
19
- close(options?: {
20
- sleep?: number;
21
- }): Promise<void>;
22
- }
23
- export declare function createBootstrap(entryFile: string): Promise<BootstrapAppStarter>;
24
- export {};
25
13
  //# sourceMappingURL=utils.d.ts.map
package/dist/utils.js CHANGED
@@ -1,23 +1,27 @@
1
1
  "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
2
8
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createBootstrap = exports.createFunctionApp = exports.close = exports.createApp = exports.create = void 0;
4
- const bootstrap_1 = require("@midwayjs/bootstrap");
9
+ exports.transformFrameworkToConfiguration = exports.findFirstExistModule = exports.isWin32 = exports.isTestEnvironment = void 0;
5
10
  const core_1 = require("@midwayjs/core");
6
- const path_1 = require("path");
7
- const fs_extra_1 = require("fs-extra");
8
11
  const decorator_1 = require("@midwayjs/decorator");
9
- const logger_1 = require("@midwayjs/logger");
10
12
  const os = require("os");
11
- process.setMaxListeners(0);
13
+ const assert = require("assert");
12
14
  function isTestEnvironment() {
13
15
  const testEnv = ['test', 'unittest'];
14
16
  return (testEnv.includes(process.env.MIDWAY_SERVER_ENV) ||
15
17
  testEnv.includes(process.env.EGG_SERVER_ENV) ||
16
18
  testEnv.includes(process.env.NODE_ENV));
17
19
  }
20
+ exports.isTestEnvironment = isTestEnvironment;
18
21
  function isWin32() {
19
22
  return os.platform() === 'win32';
20
23
  }
24
+ exports.isWin32 = isWin32;
21
25
  function findFirstExistModule(moduleList) {
22
26
  for (const name of moduleList) {
23
27
  if (!name)
@@ -31,210 +35,39 @@ function findFirstExistModule(moduleList) {
31
35
  }
32
36
  }
33
37
  }
34
- const appMap = new WeakMap();
35
- const bootstrapAppSet = (global['MIDWAY_BOOTSTRAP_APP_SET'] = new Set());
36
- function getIncludeFramework(dependencies) {
37
- const currentFramework = [
38
- '@midwayjs/web',
39
- '@midwayjs/koa',
40
- '@midwayjs/express',
41
- '@midwayjs/serverless-app',
42
- '@midwayjs/grpc',
43
- '@midwayjs/rabbitmq',
44
- '@midwayjs/socketio',
45
- '@midwayjs/faas',
46
- ];
47
- for (const frameworkName of currentFramework) {
48
- if (dependencies[frameworkName]) {
49
- return frameworkName;
50
- }
51
- }
52
- }
53
- function formatPath(baseDir, p) {
54
- if (path_1.isAbsolute(p)) {
55
- return p;
56
- }
57
- else {
58
- return path_1.resolve(baseDir, p);
59
- }
60
- }
61
- let lastAppDir;
62
- async function create(appDir = process.cwd(), options, customFrameworkName) {
63
- process.env.MIDWAY_TS_MODE = 'true';
64
- // 处理测试的 fixtures
65
- if (!path_1.isAbsolute(appDir)) {
66
- appDir = path_1.join(process.cwd(), 'test', 'fixtures', appDir);
67
- }
68
- if (lastAppDir && lastAppDir !== appDir) {
69
- // 当目录不同才清理缓存,相同目录的装饰器只加载一次,清理了就没了
70
- decorator_1.clearAllModule();
71
- }
72
- lastAppDir = appDir;
73
- global['MIDWAY_BOOTSTRAP_APP_SET'].clear();
74
- // clearContainerCache();
75
- logger_1.clearAllLoggers();
76
- options = options || {};
77
- if (options.baseDir) {
78
- core_1.safeRequire(path_1.join(`${options.baseDir}`, 'interface'));
79
- }
80
- else {
81
- core_1.safeRequire(path_1.join(`${appDir}`, 'src/interface'));
82
- }
83
- if (options.entryFile) {
84
- // start from entry file, like bootstrap.js
85
- options.entryFile = formatPath(appDir, options.entryFile);
86
- global['MIDWAY_BOOTSTRAP_APP_READY'] = false;
87
- // set app in @midwayjs/bootstrap
88
- require(options.entryFile);
89
- await new Promise((resolve, reject) => {
90
- const timeoutHandler = setTimeout(() => {
91
- clearInterval(internalHandler);
92
- reject(new Error('[midway]: bootstrap timeout'));
93
- }, options.bootstrapTimeout || 30 * 1000);
94
- const internalHandler = setInterval(() => {
95
- if (global['MIDWAY_BOOTSTRAP_APP_READY'] === true) {
96
- clearInterval(internalHandler);
97
- clearTimeout(timeoutHandler);
98
- resolve();
99
- }
100
- }, 200);
101
- });
102
- // 这里为了兼容下 cli 的老逻辑
103
- if (bootstrapAppSet.size) {
104
- const obj = bootstrapAppSet.values().next().value;
105
- return obj.framework;
106
- }
107
- return;
108
- }
109
- let framework = null;
110
- let DefaultFramework;
111
- // find framework
112
- if (customFrameworkName) {
113
- if (typeof customFrameworkName === 'string') {
114
- DefaultFramework = require(customFrameworkName).Framework;
115
- }
116
- else {
117
- DefaultFramework = customFrameworkName;
118
- }
119
- }
120
- else {
121
- // find default framework from pkg
122
- const pkg = require(path_1.join(appDir, 'package.json'));
123
- if (pkg.dependencies || pkg.devDependencies) {
124
- customFrameworkName = getIncludeFramework(Object.assign({}, pkg.dependencies || {}, pkg.devDependencies || {}));
125
- }
126
- DefaultFramework = require(customFrameworkName).Framework;
127
- }
128
- options = options !== null && options !== void 0 ? options : {};
129
- // got options from framework
130
- if (DefaultFramework) {
131
- framework = new DefaultFramework();
132
- if (framework.getFrameworkType() === core_1.MidwayFrameworkType.WEB) {
133
- // add egg-mock plugin for @midwayjs/web test, provide mock method
134
- options = Object.assign(options || {}, {
135
- plugins: {
136
- 'egg-mock': {
137
- enable: true,
138
- package: 'egg-mock',
139
- },
140
- 'midway-mock': {
141
- enable: true,
142
- package: '@midwayjs/mock',
143
- },
144
- watcher: false,
145
- development: false,
146
- },
147
- });
148
- }
149
- framework.configure(options);
150
- }
151
- else {
152
- throw new Error('framework not found');
153
- }
154
- const starter = new bootstrap_1.BootstrapStarter();
155
- starter
156
- .configure({
157
- appDir,
158
- baseDir: options.baseDir,
159
- })
160
- .load(framework);
161
- await starter.init();
162
- await starter.run();
163
- appMap.set(framework.getApplication(), starter);
164
- return framework;
165
- }
166
- exports.create = create;
167
- async function createApp(baseDir = process.cwd(), options, customFrameworkName) {
168
- const framework = await create(baseDir, options, customFrameworkName);
169
- return framework.getApplication();
170
- }
171
- exports.createApp = createApp;
172
- async function close(app, options) {
173
- if (!app)
174
- return;
175
- options = options || {};
176
- let newApp;
177
- if (app.getApplication) {
178
- newApp = app.getApplication();
38
+ exports.findFirstExistModule = findFirstExistModule;
39
+ /**
40
+ * transform a framework component or framework module to configuration class
41
+ * @param Framework
42
+ */
43
+ function transformFrameworkToConfiguration(Framework) {
44
+ let CustomFramework = Framework;
45
+ if (typeof Framework === 'string') {
46
+ Framework = (0, core_1.safeRequire)(Framework);
47
+ }
48
+ if (Framework.Configuration) {
49
+ return Framework;
50
+ }
51
+ if (Framework.Framework) {
52
+ CustomFramework = Framework.Framework;
179
53
  }
180
54
  else {
181
- newApp = app;
182
- }
183
- const starter = appMap.get(newApp);
184
- if (starter) {
185
- await starter.stop();
186
- appMap.delete(newApp);
187
- bootstrapAppSet.clear();
55
+ CustomFramework = Framework;
188
56
  }
189
- if (isTestEnvironment()) {
190
- // clean first
191
- if (options.cleanLogsDir && !isWin32()) {
192
- await fs_extra_1.remove(path_1.join(newApp.getAppDir(), 'logs'));
193
- }
194
- if (core_1.MidwayFrameworkType.WEB === newApp.getFrameworkType()) {
195
- if (options.cleanTempDir && !isWin32()) {
196
- await fs_extra_1.remove(path_1.join(newApp.getAppDir(), 'run'));
197
- }
198
- }
199
- if (options.sleep > 0) {
200
- await decorator_1.sleep(options.sleep);
57
+ assert(CustomFramework, `can't found custom framework ${Framework}`);
58
+ let CustomConfiguration = class CustomConfiguration {
59
+ async onServerReady(container) {
60
+ const customFramework = (await container.getAsync(CustomFramework));
61
+ await customFramework.run();
201
62
  }
202
- else {
203
- await decorator_1.sleep(50);
204
- }
205
- }
206
- }
207
- exports.close = close;
208
- async function createFunctionApp(baseDir = process.cwd(), options, customFrameworkName) {
209
- const customFramework = customFrameworkName !== null && customFrameworkName !== void 0 ? customFrameworkName : findFirstExistModule([
210
- process.env.MIDWAY_SERVERLESS_APP_NAME,
211
- '@ali/serverless-app',
212
- '@midwayjs/serverless-app',
213
- ]);
214
- const framework = await create(baseDir, options, customFramework);
215
- return framework.getApplication();
216
- }
217
- exports.createFunctionApp = createFunctionApp;
218
- class BootstrapAppStarter {
219
- getApp(type) {
220
- const appMap = bootstrap_1.Bootstrap.starter.getBootstrapAppMap();
221
- return appMap.get(type);
222
- }
223
- async close(options = {}) {
224
- await bootstrap_1.Bootstrap.stop();
225
- if (options.sleep > 0) {
226
- await decorator_1.sleep(options.sleep);
227
- }
228
- else {
229
- await decorator_1.sleep(50);
230
- }
231
- }
232
- }
233
- async function createBootstrap(entryFile) {
234
- await create(undefined, {
235
- entryFile,
236
- });
237
- return new BootstrapAppStarter();
63
+ };
64
+ CustomConfiguration = __decorate([
65
+ (0, decorator_1.Configuration)()
66
+ ], CustomConfiguration);
67
+ return {
68
+ Configuration: CustomConfiguration,
69
+ Framework,
70
+ };
238
71
  }
239
- exports.createBootstrap = createBootstrap;
72
+ exports.transformFrameworkToConfiguration = transformFrameworkToConfiguration;
240
73
  //# sourceMappingURL=utils.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midwayjs/mock",
3
- "version": "3.0.0-alpha.9+d5acc750",
3
+ "version": "3.0.0-beta.4",
4
4
  "description": "create your test app from midway framework",
5
5
  "main": "dist/index",
6
6
  "typings": "dist/index.d.ts",
@@ -19,18 +19,16 @@
19
19
  ],
20
20
  "files": [
21
21
  "dist/**/*.js",
22
- "dist/**/*.d.ts",
23
- "app",
24
- "config"
22
+ "dist/**/*.d.ts"
25
23
  ],
26
- "eggPlugin": {
27
- "name": "midway-mock"
24
+ "engines": {
25
+ "node": ">=12"
28
26
  },
29
27
  "license": "MIT",
30
28
  "devDependencies": {
31
- "@midwayjs/core": "^3.0.0-alpha.9+d5acc750",
32
- "@midwayjs/decorator": "^3.0.0-alpha.2",
33
- "@midwayjs/logger": "^2.11.3",
29
+ "@midwayjs/core": "^3.0.0-beta.4",
30
+ "@midwayjs/decorator": "^3.0.0-beta.4",
31
+ "@midwayjs/logger": "^3.0.0-beta.4",
34
32
  "@types/amqplib": "*",
35
33
  "amqplib": "*",
36
34
  "socket.io": "^4.0.0",
@@ -38,8 +36,6 @@
38
36
  "ws": "^7.4.5"
39
37
  },
40
38
  "dependencies": {
41
- "@midwayjs/bootstrap": "^3.0.0-alpha.9+d5acc750",
42
- "egg-mock": "^3.21.0",
43
39
  "fs-extra": "^8.0.1",
44
40
  "supertest": "^6.0.0"
45
41
  },
@@ -48,5 +44,5 @@
48
44
  "type": "git",
49
45
  "url": "http://github.com/midwayjs/midway.git"
50
46
  },
51
- "gitHead": "d5acc7505275ea9d566edd38e5e0377141e0abc1"
47
+ "gitHead": "02e2144e302f807770b512b0d89da3145b1cbf2e"
52
48
  }
@@ -1,3 +0,0 @@
1
- 'use strict';
2
-
3
- module.exports = require('../../dist/app/extend/application');
@@ -1,10 +0,0 @@
1
- 'use strict';
2
-
3
- module.exports = {
4
- watcher: {
5
- enable: false,
6
- },
7
- development: {
8
- enable: false,
9
- },
10
- };
@@ -1,3 +0,0 @@
1
- import { MockClassFunctionHandler } from '../../interface';
2
- export declare const mockClassFunction: MockClassFunctionHandler;
3
- //# sourceMappingURL=application.d.ts.map
@@ -1,16 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.mockClassFunction = void 0;
4
- const mockClassFunction = function (className, methodName, fnOrData) {
5
- const { applicationContext } = this;
6
- const def = applicationContext.registry.getDefinition(className);
7
- if (!def) {
8
- throw new TypeError(`def undefined with className: "${className}", methodName: "${methodName}"`);
9
- }
10
- else {
11
- const clazz = def.path;
12
- this._mockFn(clazz.prototype, methodName, fnOrData);
13
- }
14
- };
15
- exports.mockClassFunction = mockClassFunction;
16
- //# sourceMappingURL=application.js.map