-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi-server.test.js
More file actions
276 lines (227 loc) · 8.31 KB
/
Copy pathapi-server.test.js
File metadata and controls
276 lines (227 loc) · 8.31 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
const http = require('http');
const ApiServer = require('./api-server');
/**
* API 端点集成测试
* 实现需求 4.1, 4.2, 4.3, 4.4, 4.5 的测试验证
*/
class ApiServerTest {
constructor() {
this.apiServer = null;
this.baseUrl = 'http://localhost:3001';
}
/**
* 发送 HTTP 请求的辅助方法
*/
async makeRequest(method, path, data = null) {
return new Promise((resolve, reject) => {
const url = new URL(path, this.baseUrl);
const options = {
method: method,
headers: {
'Content-Type': 'application/json'
}
};
const req = http.request(url, options, (res) => {
let body = '';
res.on('data', (chunk) => {
body += chunk;
});
res.on('end', () => {
try {
const jsonBody = body ? JSON.parse(body) : {};
resolve({
statusCode: res.statusCode,
headers: res.headers,
body: jsonBody
});
} catch (error) {
resolve({
statusCode: res.statusCode,
headers: res.headers,
body: body
});
}
});
});
req.on('error', reject);
if (data && (method === 'POST' || method === 'PUT')) {
req.write(JSON.stringify(data));
}
req.end();
});
}
/**
* 测试断言辅助方法
*/
assert(condition, message) {
if (!condition) {
throw new Error(`断言失败: ${message}`);
}
console.log(`✓ ${message}`);
}
/**
* 设置测试环境
*/
async setup() {
console.log('设置测试环境...');
this.apiServer = new ApiServer({ port: 3001 });
// 添加一些测试代理到代理池
const testProxies = [
{ ip: '192.168.1.1', port: 8080, protocol: 'http', country: 'US', anonymity: 'elite' },
{ ip: '192.168.1.2', port: 3128, protocol: 'http', country: 'UK', anonymity: 'anonymous' }
];
for (const proxy of testProxies) {
this.apiServer.getProxyPool().addProxy(proxy);
}
await this.apiServer.start();
console.log('测试环境设置完成');
}
/**
* 清理测试环境
*/
async cleanup() {
console.log('清理测试环境...');
if (this.apiServer) {
await this.apiServer.stop();
}
console.log('测试环境清理完成');
}
/**
* 测试 Express 应用和 JSON 中间件配置
* 验证需求 4.1
*/
async testExpressSetup() {
console.log('\n=== 测试 Express 应用配置 ===');
// 测试服务器是否正常启动
const response = await this.makeRequest('GET', '/status');
this.assert(response.statusCode === 200, 'Express 服务器正常启动');
this.assert(response.headers['content-type'].includes('application/json'), 'JSON 中间件配置正确');
this.assert(typeof response.body === 'object', '响应为 JSON 格式');
}
/**
* 测试 GET /proxy 端点 - 有可用代理的情况
* 验证需求 4.2, 4.3, 4.4
*/
async testGetProxySuccess() {
console.log('\n=== 测试 GET /proxy 端点 (成功情况) ===');
const response = await this.makeRequest('GET', '/proxy');
// 验证状态码
this.assert(response.statusCode === 200, '返回 200 状态码表示成功');
// 验证响应格式
this.assert(response.body.success === true, '响应包含 success: true');
this.assert(typeof response.body.data === 'object', '响应包含 data 对象');
this.assert(typeof response.body.message === 'string', '响应包含 message 字符串');
// 验证代理信息
const proxyData = response.body.data;
this.assert(typeof proxyData.ip === 'string', '代理信息包含 IP 地址');
this.assert(typeof proxyData.port === 'number', '代理信息包含端口号');
this.assert(typeof proxyData.protocol === 'string', '代理信息包含协议类型');
console.log(`获取到代理: ${proxyData.ip}:${proxyData.port}`);
}
/**
* 测试 GET /proxy 端点 - 无可用代理的情况
* 验证需求 4.2, 4.3, 4.4
*/
async testGetProxyNoProxy() {
console.log('\n=== 测试 GET /proxy 端点 (无代理情况) ===');
// 清空代理池
this.apiServer.getProxyPool().clear();
const response = await this.makeRequest('GET', '/proxy');
// 验证状态码
this.assert(response.statusCode === 503, '返回 503 状态码表示无可用代理');
// 验证响应格式
this.assert(response.body.success === false, '响应包含 success: false');
this.assert(typeof response.body.error === 'string', '响应包含错误信息');
this.assert(response.body.code === 'NO_PROXY_AVAILABLE', '响应包含正确的错误代码');
console.log(`错误信息: ${response.body.error}`);
}
/**
* 测试 GET /status 端点
*/
async testGetStatus() {
console.log('\n=== 测试 GET /status 端点 ===');
// 重新添加测试代理
this.apiServer.getProxyPool().addProxy({
ip: '192.168.1.3',
port: 8080,
protocol: 'http',
country: 'CN'
});
const response = await this.makeRequest('GET', '/status');
// 验证状态码和响应格式
this.assert(response.statusCode === 200, '返回 200 状态码');
this.assert(response.body.success === true, '响应包含 success: true');
this.assert(typeof response.body.data === 'object', '响应包含状态数据');
this.assert(typeof response.body.data.totalProxies === 'number', '状态包含代理总数');
this.assert(Array.isArray(response.body.data.proxies), '状态包含代理列表');
console.log(`代理池状态: ${response.body.data.totalProxies} 个代理`);
}
/**
* 测试 POST /refresh 端点
*/
async testPostRefresh() {
console.log('\n=== 测试 POST /refresh 端点 ===');
const response = await this.makeRequest('POST', '/refresh');
// 验证状态码和响应格式
this.assert(response.statusCode === 200, '返回 200 状态码');
this.assert(response.body.success === true, '响应包含 success: true');
this.assert(typeof response.body.data === 'object', '响应包含刷新数据');
this.assert(typeof response.body.data.addedProxies === 'number', '响应包含添加的代理数量');
console.log(`刷新结果: 添加了 ${response.body.data.addedProxies} 个代理`);
}
/**
* 测试 404 错误处理
*/
async testNotFound() {
console.log('\n=== 测试 404 错误处理 ===');
const response = await this.makeRequest('GET', '/nonexistent');
this.assert(response.statusCode === 404, '返回 404 状态码');
this.assert(response.body.success === false, '响应包含 success: false');
this.assert(response.body.code === 'NOT_FOUND', '响应包含正确的错误代码');
console.log('404 错误处理正常');
}
/**
* 测试服务器启动信息输出
* 验证需求 4.5
*/
async testServerStartup() {
console.log('\n=== 测试服务器启动信息 ===');
// 这个测试主要验证启动时的日志输出
// 在 setup() 方法中已经验证了服务器能够正常启动
this.assert(this.apiServer !== null, '服务器实例创建成功');
this.assert(typeof this.apiServer.getApp === 'function', '可以获取 Express 应用实例');
this.assert(typeof this.apiServer.getProxyPool === 'function', '可以获取代理池实例');
console.log('服务器启动信息输出正常');
}
/**
* 运行所有测试
*/
async runAllTests() {
console.log('开始运行 API 服务器集成测试...\n');
try {
await this.setup();
await this.testExpressSetup();
await this.testGetProxySuccess();
await this.testGetProxyNoProxy();
await this.testGetStatus();
await this.testPostRefresh();
await this.testNotFound();
await this.testServerStartup();
console.log('\n🎉 所有测试通过!');
} catch (error) {
console.error('\n❌ 测试失败:', error.message);
throw error;
} finally {
await this.cleanup();
}
}
}
// 如果直接运行此文件,执行测试
if (require.main === module) {
const test = new ApiServerTest();
test.runAllTests().catch(error => {
console.error('测试执行失败:', error);
process.exit(1);
});
}
module.exports = ApiServerTest;