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
277
278
279
280
281
282
283
| // API自动化测试框架
class APITestFramework {
constructor() {
this.testSuites = new Map();
this.testResults = [];
this.config = {
baseUrl: '',
timeout: 5000,
retryCount: 3,
parallel: false
};
}
// 设置配置
configure(config) {
this.config = { ...this.config, ...config };
}
// 创建测试套件
createTestSuite(name) {
const suite = new APITestSuite(name, this.config);
this.testSuites.set(name, suite);
return suite;
}
// 运行所有测试
async runAllTests() {
const results = [];
for (const [name, suite] of this.testSuites) {
console.log(`Running test suite: ${name}`);
const suiteResult = await suite.run();
results.push(suiteResult);
}
this.testResults = results;
this.generateReport(results);
return results;
}
// 运行特定测试套件
async runTestSuite(suiteName) {
const suite = this.testSuites.get(suiteName);
if (!suite) {
throw new Error(`Test suite '${suiteName}' not found`);
}
const result = await suite.run();
this.testResults.push(result);
return result;
}
// 生成测试报告
generateReport(results) {
const report = {
timestamp: new Date().toISOString(),
summary: {
totalSuites: results.length,
passedSuites: results.filter(r => r.status === 'passed').length,
failedSuites: results.filter(r => r.status === 'failed').length,
totalTests: results.reduce((sum, r) => sum + r.totalTests, 0),
passedTests: results.reduce((sum, r) => sum + r.passedTests, 0),
failedTests: results.reduce((sum, r) => sum + r.failedTests, 0),
duration: results.reduce((sum, r) => sum + r.duration, 0)
},
suites: results
};
this.displayReport(report);
return report;
}
// 显示报告
displayReport(report) {
console.group('🧪 API Test Report');
console.log('Summary:', report.summary);
console.log('Suite Results:', report.suites);
console.groupEnd();
// 可以生成HTML报告或其他格式的报告
}
}
// API测试套件
class APITestSuite {
constructor(name, config) {
this.name = name;
this.config = config;
this.tests = [];
this.beforeEachCallbacks = [];
this.afterEachCallbacks = [];
}
// 添加测试
test(description, testFunction) {
this.tests.push({
description,
testFunction,
timeout: this.config.timeout
});
}
// 添加前置回调
beforeEach(callback) {
this.beforeEachCallbacks.push(callback);
}
// 添加后置回调
afterEach(callback) {
this.afterEachCallbacks.push(callback);
}
// 运行测试套件
async run() {
const startTime = Date.now();
const results = {
suiteName: this.name,
status: 'passed',
totalTests: this.tests.length,
passedTests: 0,
failedTests: 0,
testResults: [],
duration: 0
};
for (const test of this.tests) {
try {
// 执行前置回调
for (const callback of this.beforeEachCallbacks) {
await callback();
}
// 执行测试
const testResult = await this.runSingleTest(test);
results.testResults.push(testResult);
if (testResult.status === 'passed') {
results.passedTests++;
} else {
results.failedTests++;
results.status = 'failed';
}
// 执行后置回调
for (const callback of this.afterEachCallbacks) {
await callback();
}
} catch (error) {
results.failedTests++;
results.status = 'failed';
results.testResults.push({
description: test.description,
status: 'error',
error: error.message,
duration: 0
});
}
}
results.duration = Date.now() - startTime;
return results;
}
// 运行单个测试
async runSingleTest(test) {
const startTime = Date.now();
try {
const result = await Promise.race([
test.testFunction(),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Test timeout')), test.timeout)
)
]);
return {
description: test.description,
status: 'passed',
result,
duration: Date.now() - startTime
};
} catch (error) {
return {
description: test.description,
status: 'failed',
error: error.message,
duration: Date.now() - startTime
};
}
}
}
// 测试断言库
class APIAssertions {
static assertEqual(actual, expected, message = '') {
if (actual !== expected) {
throw new Error(`Assertion failed: expected ${expected}, got ${actual}. ${message}`);
}
}
static assertContains(haystack, needle, message = '') {
if (!haystack.includes(needle)) {
throw new Error(`Assertion failed: ${haystack} does not contain ${needle}. ${message}`);
}
}
static assertStatus(response, expectedStatus, message = '') {
if (response.status !== expectedStatus) {
throw new Error(`Expected status ${expectedStatus}, got ${response.status}. ${message}`);
}
}
static assertJSONStructure(data, expectedStructure, message = '') {
for (const key in expectedStructure) {
if (!(key in data)) {
throw new Error(`Missing key '${key}' in response. ${message}`);
}
if (typeof expectedStructure[key] === 'object' && !Array.isArray(expectedStructure[key])) {
this.assertJSONStructure(data[key], expectedStructure[key], message);
}
}
}
static async assertResponseTime(url, maxTime, message = '') {
const startTime = Date.now();
await fetch(url);
const duration = Date.now() - startTime;
if (duration > maxTime) {
throw new Error(`Response time ${duration}ms exceeds maximum ${maxTime}ms. ${message}`);
}
}
}
// 使用示例
const testFramework = new APITestFramework();
testFramework.configure({
baseUrl: 'https://api.example.com',
timeout: 10000
});
const userAPISuite = testFramework.createTestSuite('User API Tests');
userAPISuite.test('GET /users should return list of users', async () => {
const response = await fetch('/users');
APIAssertions.assertStatus(response, 200);
const data = await response.json();
APIAssertions.assertJSONStructure(data, {
users: [],
pagination: {}
});
APIAssertions.assertContains(data.users[0].email, '@');
});
userAPISuite.test('POST /users should create new user', async () => {
const newUser = {
name: 'Test User',
email: 'test@example.com'
};
const response = await fetch('/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newUser)
});
APIAssertions.assertStatus(response, 201);
const data = await response.json();
APIAssertions.assertEqual(data.name, newUser.name);
APIAssertions.assertEqual(data.email, newUser.email);
});
// 运行测试
testFramework.runAllTests();
|