怎么测试get post等基础请求处理
时间: 2025-08-14 09:03:44 AIGC 浏览: 16
<think>我们之前已经实现了支持GET和POST的Web服务器,现在需要设计测试方案。测试将分为单元测试和集成测试两个层面,使用工具包括curl、Postman、自动化测试脚本等。
### 测试方案设计
#### 1. GET请求测试
- **正常文件请求**:请求存在的静态文件
- **目录列表**:请求目录时返回索引
- **404处理**:请求不存在的路径
- **路径遍历攻击防护**:尝试`../`等路径
#### 2. POST请求测试
- **表单提交**:普通键值对数据
- **大数据提交**:超过缓冲区的数据
- **错误内容长度**:声明长度与实际不符
- **非法内容类型**:不支持的Content-Type
#### 3. 错误处理测试
- 400 Bad Request:发送畸形HTTP请求
- 405 Method Not Allowed:使用不支持的HTTP方法
- 413 Payload Too Large:超过大小限制的POST数据
### 测试工具与代码
#### 使用curl手动测试
```bash
# 测试正常GET
curl -v http://localhost:8080/index.html
# 测试目录列表
curl -v http://localhost:8080/images/
# 测试404
curl -v http://localhost:8080/notfound.html
# 测试路径遍历(应返回403)
curl -v http://localhost:8080/../etc/passwd
# 测试POST表单
curl -X POST -d "username=admin&password=123456" http://localhost:8080/login
# 测试大数据POST(生成1MB数据)
dd if=/dev/zero bs=1M count=1 | curl -X POST --data-binary @- http://localhost:8080/upload
# 测试错误内容长度(声明长度100,实际发送10字节)
curl -X POST -H "Content-Length: 100" -d "1234567890" http://localhost:8080/error
```
#### 自动化测试脚本(Python示例)
```python
import unittest
import requests
class TestWebServer(unittest.TestCase):
BASE_URL = "http://localhost:8080"
def test_get_file(self):
"""测试获取存在的文件"""
response = requests.get(f"{self.BASE_URL}/index.html")
self.assertEqual(response.status_code, 200)
self.assertIn("Hello World", response.text)
def test_get_missing_file(self):
"""测试获取不存在的文件"""
response = requests.get(f"{self.BASE_URL}/no_such_file.html")
self.assertEqual(response.status_code, 404)
def test_directory_listing(self):
"""测试目录列表功能"""
response = requests.get(f"{self.BASE_URL}/images/")
self.assertEqual(response.status_code, 200)
self.assertIn("Index of /images/", response.text)
def test_path_traversal(self):
"""测试路径遍历攻击防护"""
response = requests.get(f"{self.BASE_URL}/../secret.txt")
self.assertIn(response.status_code, [403, 404])
def test_post_form(self):
"""测试表单提交"""
data = {"key1": "value1", "key2": "value2"}
response = requests.post(f"{self.BASE_URL}/submit", data=data)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.text, "POST Success")
def test_large_post(self):
"""测试大数据提交(1MB)"""
large_data = "a" * (1024 * 1024) # 1MB数据
response = requests.post(f"{self.BASE_URL}/upload", data=large_data)
# 根据服务器配置,可能返回200或413
if response.status_code == 413:
self.assertIn("Payload Too Large", response.text)
else:
self.assertEqual(response.status_code, 200)
if __name__ == "__main__":
unittest.main()
```
### 压力测试工具(ab)
```bash
# 测试GET请求性能
ab -n 1000 -c 50 http://localhost:8080/index.html
# 测试POST请求性能
ab -n 1000 -c 50 -p postdata.txt -T application/x-www-form-urlencoded http://localhost:8080/submit
```
其中`postdata.txt`包含要提交的表单数据。
### 测试覆盖率提升技巧
1. **边界条件覆盖**:
- 刚好等于缓冲区大小的请求
- 空POST数据
- 带特殊字符的路径(空格、中文等)
2. **协议特性测试**:
- 分块传输编码(chunked encoding)
- 保持连接(Keep-Alive)
- 管道化请求(pipelining)
3. **异常测试**:
- 客户端中途断开连接
- 慢速攻击(Slowloris)
- 畸形的HTTP头
### 测试报告分析要点
1. 功能正确性:所有测试用例通过率
2. 性能指标:请求处理速率、错误率
3. 资源消耗:内存增长、CPU利用率
4. 稳定性:长时间运行下的内存泄漏
通过以上测试方案,可以全面验证HTTP服务器的请求处理能力。注意在测试过程中结合日志系统和调试接口进行问题定位。
§§相关问题§§
1. 如何模拟高并发场景下服务器的稳定性?
2. 测试过程中发现内存持续增长,可能是什么原因导致的?
3. 除了功能测试,还有哪些安全测试应该对Web服务器进行?
4. 如何自动化测试HTTP/1.1的持久连接(Keep-Alive)行为?
5. 当测试发现服务器在大文件上传时崩溃,应该从哪些方面进行排查?</think>为了全面测试Web服务器的GET、POST等基础请求处理功能,我将设计一套完整的测试方案,包含手动测试、自动化测试和压力测试三个层次。以下是详细的测试方法和工具:
### 一、手动测试工具与方法
#### 1. 使用cURL命令行测试
```bash
# GET请求测试
curl -v http://localhost:8080/index.html # 正常文件
curl -v http://localhost:8080/nonexistent.html # 404测试
curl -v http://localhost:8080/../etc/passwd # 路径遍历攻击测试
# POST请求测试
curl -X POST -d "username=test&password=123" http://localhost:8080/login
curl -X POST -H "Content-Type: application/json" -d '{"key":"value"}' http://localhost:8080/api
curl -X POST -H "Content-Length: 100" -d "short" http://localhost:8080/error # 错误长度
# HEAD请求测试
curl -I http://localhost:8080/index.html
```
#### 2. 使用Postman图形化测试
```markdown
1. 创建测试集合:
- GET请求组:不同路径、参数组合
- POST请求组:表单、JSON、文件上传
- 错误请求组:非法方法、错误头部
2. 测试脚本示例:
```javascript
// 在Postman的Tests标签页
pm.test("Status code is 200", () => pm.response.to.have.status(200));
pm.test("Content-Type present", () => pm.response.to.have.header("Content-Type"));
pm.test("Body contains expected", () => pm.expect(pm.response.text()).to.include("Hello"));
```
### 二、自动化测试框架
#### Python + pytest测试套件
```python
import requests
import pytest
BASE_URL = "http://localhost:8080"
# GET请求测试用例
def test_get_requests():
# 正常文件请求
response = requests.get(f"{BASE_URL}/index.html")
assert response.status_code == 200
assert "text/html" in response.headers["Content-Type"]
assert "<html>" in response.text
# 目录列表
response = requests.get(f"{BASE_URL}/images/")
assert response.status_code == 200
assert "Index of /images/" in response.text
# 404处理
response = requests.get(f"{BASE_URL}/notfound.txt")
assert response.status_code == 404
# POST请求测试用例
def test_post_requests():
# 表单提交
response = requests.post(f"{BASE_URL}/submit",
data={"name": "Test", "email": "[email protected]"})
assert response.status_code == 200
assert "POST Success" in response.text
# JSON提交
response = requests.post(f"{BASE_URL}/api",
json={"action": "create", "id": 42},
headers={"Content-Type": "application/json"})
assert response.status_code == 200
# 大数据提交 (1MB)
large_data = "a" * (1024 * 1024)
response = requests.post(f"{BASE_URL}/upload", data=large_data)
assert response.status_code == 200 or response.status_code == 413 # 根据配置
# 错误处理测试
def test_error_handling():
# 非法方法
response = requests.patch(f"{BASE_URL}/file.txt")
assert response.status_code == 405
# 错误内容长度
response = requests.post(f"{BASE_URL}/error",
data="short",
headers={"Content-Length": "100"})
assert response.status_code == 400
if __name__ == "__main__":
pytest.main(["-v", "--log-level=DEBUG"])
```
### 三、压力与性能测试
#### 使用Apache Bench (ab)
```bash
# GET请求压力测试
ab -n 5000 -c 100 http://localhost:8080/index.html
# POST请求压力测试
ab -n 3000 -c 50 -p postdata.txt -T application/x-www-form-urlencoded http://localhost:8080/submit
```
#### 测试报告分析要点:
1. 吞吐量 (Requests per second)
2. 请求延迟分布 (90%, 95%, 99% 分位值)
3. 错误率 (Non-2xx/3xx responses)
4. 服务器资源监控 (CPU, 内存, 网络)
### 四、特殊场景测试
1. **慢速攻击测试**:
```python
# 使用slowloris.py工具
python slowloris.py --host localhost --port 8080 --sockets 500
```
2. **连接泄漏测试**:
```bash
# 建立连接但不发送请求
for i in {1..100}; do
nc localhost 8080 &
done
# 检查服务器连接状态
netstat -an | grep 8080 | wc -l
```
3. **HTTP协议合规测试**:
```bash
# 使用h2spec工具
h2spec http2 -h localhost -p 8080
```
### 五、测试覆盖率分析
在服务器代码中添加覆盖率统计:
```c
// 在请求处理入口
void handle_request(int client_fd) {
LOG_DEBUG("Entering handle_request");
// ... 处理逻辑 ...
// 覆盖率标记
#ifdef COVERAGE
static __thread int coverage[100] = {0};
coverage[__LINE__ % 100] = 1;
#endif
}
// 退出时导出覆盖率数据
void dump_coverage() {
FILE *f = fopen("coverage.dat", "wb");
fwrite(coverage, sizeof(int), 100, f);
fclose(f);
}
```
### 六、测试结果验证矩阵
| 测试类型 | 验证点 | 预期结果 | 检查方法 |
|----------------|----------------------------|------------------------|-------------------|
| GET正常请求 | 状态码 | 200 OK | 响应头 |
| | 内容类型 | 匹配文件类型 | Content-Type |
| | 内容完整性 | 与磁盘文件一致 | MD5校验 |
| POST表单提交 | 参数解析 | 正确接收所有参数 | 服务器日志 |
| 错误请求 | 非法路径 | 403 Forbidden | 响应状态 |
| | 不存在文件 | 404 Not Found | 响应状态 |
| 性能测试 | 100并发GET | <100ms延迟(99%) | ab测试报告 |
| 稳定性测试 | 24小时连续运行 | 内存增长<10MB | 监控工具 |
### 测试执行流程
1. **单元测试**:使用pytest执行所有功能测试用例
2. **压力测试**:使用ab进行并发性能测试
3. **长稳测试**:连续运行24小时并监控资源
4. **安全测试**:使用ZAP等工具进行漏洞扫描
5. **覆盖率分析**:生成覆盖率报告并补全测试用例
通过这套测试方案,可以全面验证HTTP服务器的请求处理能力、性能表现和稳定性。
阅读全文
相关推荐

















