Skip to content

Commit

Permalink
feat: add app.expectLog() for app and cluster (#77)
Browse files Browse the repository at this point in the history
helper function to assert string value in logger
  • Loading branch information
fengmk2 authored Aug 3, 2018
1 parent ef13618 commit f25c50a
Show file tree
Hide file tree
Showing 12 changed files with 109 additions and 7 deletions.
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ language: node_js
node_js:
- '6'
- '8'
- '9'
- '10'
install:
- npm i npminstall && npminstall
script:
Expand Down
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,23 @@ Clean all logs directory, default is true.

If you are using `ava`, disable it.

### app.expectLog(str[, logger])

Assert some string value in the logger instance.

```js
it('should work', async () => {
await app.httpRequest()
.get('/')
.expect('hello world')
.expect(200);

app.expectLog('foo in logger');
app.expectLog('foo in coreLogger', 'coreLogger');
app.expectLog('foo in myCustomLogger', 'myCustomLogger');
});
```

### app.httpRequest()

Request current app http server.
Expand Down
17 changes: 17 additions & 0 deletions README.zh_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,23 @@ mm.app({

如果是通过 ava 等并行测试框架进行测试,需要手动在执行测试前进行统一的日志清理,不能通过 mm 来处理,设置 `clean``false`

### app.expectLog(str[, logger])

断言指定的字符串记录在指定的日志中。

```js
it('should work', async () => {
await app.httpRequest()
.get('/')
.expect('hello world')
.expect(200);

app.expectLog('foo in logger');
app.expectLog('foo in coreLogger', 'coreLogger');
app.expectLog('foo in myCustomLogger', 'myCustomLogger');
});
```

### app.httpRequest()

请求当前应用 http 服务的辅助工具。
Expand Down
22 changes: 22 additions & 0 deletions app/extend/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const mm = require('mm');
const http = require('http');
const fs = require('fs');
const merge = require('merge-descriptors');
const is = require('is-type-of');
const assert = require('assert');
Expand Down Expand Up @@ -400,6 +401,27 @@ module.exports = {
httpRequest() {
return supertestRequest(this);
},

/**
* expect str/regexp in the logger
* @param {String|RegExp} str - test str or regexp
* @param {String|Logger} [logger] - logger instance, default is `ctx.logger`
* @method App#expectLog
*/
expectLog(str, logger) {
logger = logger || this.logger;
if (typeof logger === 'string') {
logger = this.getLogger(logger);
}
const filepath = logger.options.file;
const content = fs.readFileSync(filepath, 'utf8');
if (str instanceof RegExp) {
assert(str.test(content), `Can't find RegExp:"${str}" in ${filepath}`);
} else {
str = String(str);
assert(content.includes(str), `Can't find String:"${str}" in ${filepath}`);
}
},
};

function findHeaders(headers, key) {
Expand Down
2 changes: 1 addition & 1 deletion appveyor.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ environment:
matrix:
- nodejs_version: '6'
- nodejs_version: '8'
- nodejs_version: '9'
- nodejs_version: '10'

install:
- ps: Install-Product node $env:nodejs_version
Expand Down
13 changes: 13 additions & 0 deletions lib/cluster.js
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,19 @@ class ClusterApplication extends Coffee {
};
}

/**
* expect str in the logger
* it's different from `app.expectLog()`, only support string params.
*
* @param {String} str - test str
* @param {String} [logger] - logger instance name, default is `logger`
* @method ClusterApplication#expectLog
*/
expectLog(str, logger) {
logger = logger || 'logger';
this._callFunctionOnAppWorker('expectLog', [ str, logger ], null, true);
}

httpRequest() {
return supertestRequest(this);
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
"sdk-base": "^3.0.1"
},
"ci": {
"version": "6, 8, 9"
"version": "6, 8, 10"
},
"homepage": "https://github.com/eggjs/egg-mock",
"repository": {
Expand Down
27 changes: 27 additions & 0 deletions test/app.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,33 @@ function call(method) {
keepAliveTimeout: 5000,
});
});

it('should app.expectLog() work', function* () {
yield app.httpRequest()
.get('/logger')
.expect(200)
.expect({
ok: true,
});
app.expectLog('[app.expectLog() test] ok');
app.expectLog('[app.expectLog() test] ok', 'logger');
app.expectLog('[app.expectLog(coreLogger) test] ok', 'coreLogger');

if (method === 'app') {
app.expectLog(/\[app\.expectLog\(\) test\] ok/);
app.expectLog(/\[app\.expectLog\(\) test\] ok/, app.logger);
app.expectLog('[app.expectLog(coreLogger) test] ok', app.coreLogger);
app.expectLog(/\[app\.expectLog\(coreLogger\) test\] ok/, 'coreLogger');
}

try {
app.expectLog('[app.expectLog(coreLogger) test] ok');
throw new Error('should not run this');
} catch (err) {
assert(err.message.includes('Can\'t find String:"[app.expectLog(coreLogger) test] ok" in '));
assert(err.message.includes('app-web.log'));
}
});
});

describe(`mm.${method}({ baseDir, plugin=string })`, () => {
Expand Down
6 changes: 6 additions & 0 deletions test/fixtures/app/app/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,10 @@ module.exports = app => {
keepAliveTimeout: this.app.serverKeepAliveTimeout,
};
});

app.get('/logger', function* () {
this.logger.info('[app.expectLog() test] ok');
this.coreLogger.info('[app.expectLog(coreLogger) test] ok');
this.body = { ok: true };
});
};
2 changes: 1 addition & 1 deletion test/format_options.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ describe('test/format_options.test.js', () => {
formatOptions({
plugin: true,
});
}, `should set eggPlugin in ${baseDir}/package.json`);
}, new RegExp(`should set eggPlugin in ${baseDir}/package.json`));
});

it('should mock process.env.HOME when EGG_SERVER_ENV is default, test, prod', () => {
Expand Down
4 changes: 2 additions & 2 deletions test/mock_service.async.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const assert = require('assert');
const mm = require('..');
const fixtures = path.join(__dirname, 'fixtures');

describe('test/mock_service.test.js', () => {
describe('test/mock_service.async.js', () => {
let app;
before(async () => {
app = mm.app({
Expand Down Expand Up @@ -59,7 +59,7 @@ describe('test/mock_service.test.js', () => {
it('should throw', () => {
assert.throws(() => {
app.mockService('foo', 'not_exist', 'foo');
}, 'property not_exist in original object must be function');
}, /property not_exist in original object must be function/);
});

it('should return from service when mock with generator', done => {
Expand Down
2 changes: 1 addition & 1 deletion test/mock_service.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ describe('test/mock_service.test.js', () => {
it('should throw', () => {
assert.throws(() => {
app.mockService('foo', 'not_exist', 'foo');
}, 'property not_exist in original object must be function');
}, /property not_exist in original object must be function/);
});

it('should return from service when mock with generator', done => {
Expand Down

0 comments on commit f25c50a

Please sign in to comment.