-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
100 lines (90 loc) · 2.52 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
'use strict';
const fs = require('fs');
const path = require('path');
const http = require('http');
const mm = require('egg-mock');
const fixtures = path.join(__dirname, 'fixtures');
const eggPath = path.join(__dirname, '..');
const egg = require('..');
const request = require('supertest');
exports.app = (name, options) => {
options = formatOptions(name, options);
const app = mm.app(options);
return app;
};
/**
* start app with single process mode
*
* @param {String} baseDir - base dir.
* @param {Object} [options] - optional
* @return {App} app - Application object.
*/
exports.singleProcessApp = async (baseDir, options = {}) => {
if (!baseDir.startsWith('/')) baseDir = path.join(__dirname, 'fixtures', baseDir);
options.env = options.env || 'unittest';
options.baseDir = baseDir;
const app = await egg.start(options);
app.httpRequest = () => request(app.callback());
return app;
};
/**
* start app with cluster mode
*
* @param {String} name - cluster name.
* @param {Object} [options] - optional
* @return {App} app - Application object.
*/
exports.cluster = (name, options) => {
options = formatOptions(name, options);
return mm.cluster(options);
};
let localServer;
exports.startLocalServer = () => {
return new Promise((resolve, reject) => {
if (localServer) {
return resolve('http://127.0.0.1:' + localServer.address().port);
}
localServer = http.createServer((req, res) => {
req.resume();
req.on('end', () => {
res.statusCode = 200;
if (req.url === '/get_headers') {
res.setHeader('Content-Type', 'json');
res.end(JSON.stringify(req.headers));
} else if (req.url === '/timeout') {
setTimeout(() => {
res.end(`${req.method} ${req.url}`);
}, 10000);
return;
} else {
res.end(`${req.method} ${req.url}`);
}
});
});
localServer.listen(0, err => {
if (err) return reject(err);
return resolve('http://127.0.0.1:' + localServer.address().port);
});
});
};
process.once('exit', () => localServer && localServer.close());
exports.getFilepath = name => {
return path.join(fixtures, name);
};
exports.getJSON = name => {
return JSON.parse(fs.readFileSync(exports.getFilepath(name)));
};
function formatOptions(name, options) {
let baseDir;
if (typeof name === 'string') {
baseDir = name;
} else {
// name is options
options = name;
}
return Object.assign({}, {
baseDir,
customEgg: eggPath,
cache: false,
}, options);
}