Skip to content

Commit

Permalink
mockContext work
Browse files Browse the repository at this point in the history
  • Loading branch information
fengmk2 committed Dec 22, 2024
1 parent 7bf4b72 commit 04b10e6
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 12 deletions.
18 changes: 12 additions & 6 deletions src/app/extend/application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import mergeDescriptors from 'merge-descriptors';
import { isAsyncFunction, isObject } from 'is-type-of';
import { mock, restore } from 'mm';
import { Transport, Logger, LoggerLevel, LoggerMeta } from 'egg-logger';
import { EggCore, EggCoreOptions } from '@eggjs/core';
import { EggCore, EggCoreOptions, ContextDelegation } from '@eggjs/core';
import { getMockAgent, restoreMockAgent } from '../../lib/mock_agent.js';
import {
createMockHttpClient, MockResultFunction,
Expand Down Expand Up @@ -38,6 +38,10 @@ export interface MockContextData {
[key: string]: any;
}

export interface MockContextDelegation extends ContextDelegation {
service: any;
}

export default abstract class ApplicationUnittest extends EggCore {
declare options: MockOptions & EggCoreOptions;
_mockHttpClient: MockHttpClientMethod;
Expand All @@ -64,7 +68,7 @@ export default abstract class ApplicationUnittest extends EggCore {
* };
* ```
*/
mockContext(data?: MockContextData, options?: MockContextOptions) {
mockContext(data?: MockContextData, options?: MockContextOptions): MockContextDelegation {
data = data ?? {};
function mockRequest(req: IncomingMessage) {
for (const key in data?.headers) {
Expand Down Expand Up @@ -93,22 +97,24 @@ export default abstract class ApplicationUnittest extends EggCore {
if (this.currentContext && !this.currentContext[REUSED_CTX]) {
mockRequest(this.currentContext.request.req);
this.currentContext[REUSED_CTX] = true;
return this.currentContext;
return this.currentContext as MockContextDelegation;
}
}
const ctx = this.createContext(req, res);
if (options.mockCtxStorage) {
mock(this.ctxStorage, 'getStore', () => ctx);
}
return ctx;
return ctx as MockContextDelegation;
}

async mockContextScope(fn: () => Promise<any>, data: any) {
async mockContextScope(fn: (ctx?: MockContextDelegation) => Promise<any>, data?: MockContextData) {
const ctx = this.mockContext(data, {
mockCtxStorage: false,
reuseCtxStorage: false,
});
return await this.ctxStorage.run(ctx, fn);
return await this.ctxStorage.run(ctx, async () => {
return await fn(ctx);
});
}

/**
Expand Down
13 changes: 12 additions & 1 deletion src/lib/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,22 @@ export class MockApplication extends Base {
if (this.options.clean !== false) {
const logDir = path.join(this.options.baseDir, 'logs');
try {
if (os.platform() === 'win32') await sleep(1000);
if (os.platform() === 'win32') {
await sleep(1000);
}
await rimraf(logDir);
} catch (err: any) {
console.error(`remove log dir ${logDir} failed: ${err.stack}`);
}
const runDir = path.join(this.options.baseDir, 'run');
try {
if (os.platform() === 'win32') {
await sleep(1000);
}
await rimraf(runDir);
} catch (err: any) {
console.error(`remove run dir ${runDir} failed: ${err.stack}`);
}
}

this.options.clusterPort = await detectPort();
Expand Down
5 changes: 5 additions & 0 deletions src/lib/mock_custom_loader.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import { debuglog } from 'node:util';

const debug = debuglog('@eggjs/mock/lib/mock_custom_loader');

export function setCustomLoader(app: any) {
const customLoader = app.config.customLoader;
if (!customLoader) return;
Expand All @@ -15,6 +19,7 @@ export function setCustomLoader(app: any) {
app.coreLogger.warn('Can\'t override app.%s', appMethodName);
return;
}
debug('[addMethod] %s => %j', appMethodName, loaderConfig);
app[appMethodName] = function(service: any, methodName: string, fn: any) {
if (typeof service === 'string') {
const arr = service.split('.');
Expand Down
13 changes: 11 additions & 2 deletions test/ctx.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,13 @@ describe('test/ctx.test.ts', () => {
it('should ctx.ip work', () => {
const ctx = app.mockContext();
ctx.request.headers['x-forwarded-for'] = '';
assert(ctx.request.ip === '127.0.0.1');
assert.equal(ctx.request.ip, '127.0.0.1');
});

it('should has services', async () => {
const ctx = app.mockContext();
const data = await ctx.service.foo.get('foo');
assert(data === 'bar');
assert.equal(data, 'bar');
});

it('should not override mockData', async () => {
Expand All @@ -57,6 +57,15 @@ describe('test/ctx.test.ts', () => {
assert(nestCtx === currentStore);
});
});

await app.mockContextScope(async () => {
const ctx = app.ctxStorage.getStore();
await app.mockContextScope(async (newCtx: any) => {
const currentStore = app.ctxStorage.getStore();
assert.equal(newCtx, currentStore);
assert.notEqual(ctx, currentStore);
});
});
});

it('should not conflict with concurrent call', async () => {
Expand Down
4 changes: 1 addition & 3 deletions test/fixtures/demo/app/service/foo.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
'use strict';

module.exports = function(app) {
class Foo extends app.Service {
* get() {
async get() {
return 'bar';
}

Expand Down

0 comments on commit 04b10e6

Please sign in to comment.