现在有个项目需要用pytest框架做接口自动化测试,请详细说明项目是如何从零开展并完成项目
时间: 2025-07-21 13:51:54 浏览: 5
<think>我们使用pytest框架从零开展接口自动化测试项目,通常包括以下步骤:
1. **环境准备**:
- 安装Python(建议3.6以上版本)
- 安装pytest:`pip install pytest`
- 安装requests库用于HTTP请求:`pip install requests`
- 可选:安装pytest插件(如pytest-html生成报告,pytest-xdist分布式测试,pytest-rerunfailures失败重试等)
2. **项目结构设计**:
- 创建项目目录,例如:
```
project/
├── conftest.py # pytest配置文件,可以定义fixture等
├── pytest.ini # pytest配置文件,配置命令行参数等
├── requirements.txt # 依赖包列表
├── test_cases/ # 测试用例目录
│ ├── test_demo.py
│ └── ...
├── common/ # 公共模块
│ ├── __init__.py
│ ├── request_util.py # 封装请求工具
│ └── ...
├── data/ # 测试数据管理
├── reports/ # 测试报告存放目录
└── README.md
```
3. **封装请求工具**:
- 在`common/request_util.py`中封装一个通用的请求函数,支持GET、POST等方法,并处理请求头、参数等。
4. **编写测试用例**:
- 在`test_cases`目录下创建测试文件,以`test_`开头。
- 使用pytest的fixture来管理前置后置操作,比如登录获取token。
- 使用参数化(@pytest.mark.parametrize)来管理多组测试数据。
- 每个测试函数应该尽量独立,不依赖其他测试函数。
5. **测试数据管理**:
- 可以将测试数据放在yaml、json或excel文件中,然后在测试用例中读取。
- 使用pytest的fixture来读取测试数据。
6. **配置文件管理**:
- 使用`config.ini`或`settings.py`来管理环境配置(如测试环境、预发环境、生产环境的URL等)。
7. **断言设计**:
- 对接口返回的状态码、响应体中的关键字段进行断言。
- 可以使用pytest的`assert`语句,也可以使用第三方断言库如`assertpy`来增强断言。
8. **生成测试报告**:
- 使用pytest-html生成HTML报告:`pytest --html=reports/report.html`
- 也可以使用Allure报告,需要安装Allure并配置。
9. **持续集成**:
- 将项目接入CI/CD工具(如Jenkins、GitLab CI等),实现自动化触发测试。
10. **异常处理与日志**:
- 在请求工具和测试用例中加入异常处理。
- 使用Python的logging模块记录日志。
11. **测试用例标记与运行**:
- 使用pytest的mark功能标记测试用例(如冒烟测试、回归测试等)。
- 通过命令行选择运行特定标记的用例:`pytest -m smoke`
12. **代码版本控制**:
- 使用Git进行代码版本控制。
下面是一个简单的示例:
**request_util.py**
```python
import requests
class RequestUtil:
def send_request(self, method, url, data=None, headers=None, **kwargs):
if headers is None:
headers = {}
method = method.lower()
if method == 'get':
res = requests.get(url, params=data, headers=headers, **kwargs)
elif method == 'post':
res = requests.post(url, json=data, headers=headers, **kwargs)
else:
# 其他请求方法类似
res = None
return res
```
**test_demo.py**
```python
import pytest
from common.request_util import RequestUtil
class TestDemo:
@pytest.mark.parametrize('param', [1, 2, 3])
def test_demo(self, param):
request = RequestUtil()
url = "https://httpbin.org/get"
params = {"key": param}
res = request.send_request('get', url, data=params)
assert res.status_code == 200
assert res.json()['args']['key'] == str(param)
```
**conftest.py**
```python
import pytest
@pytest.fixture(scope='session')
def token():
# 这里可以获取token,并返回
return "fake_token"
```
**pytest.ini**
```ini
[pytest]
markers =
smoke: smoke test
regression: regression test
```
运行测试:`pytest -v -s --html=reports/report.html`
这样,一个基本的接口自动化测试项目就搭建完成了。根据项目复杂度的增加,可以继续扩展功能,比如接口依赖、数据库校验、性能监控等。
§§相关问题§§
1. 在pytest框架中,如何管理不同环境的配置(如测试环境、生产环境)?
2. 如何利用pytest的fixture来管理测试用例的前置和后置操作?
3. 在接口自动化测试中,如何处理需要登录的接口(例如token的获取和传递)?
4. 如何使用pytest参数化来管理多组测试数据,并实现数据驱动?
5. 如何生成美观的测试报告(如Allure报告)并集成到持续集成流程中?</think>### 从零开展pytest接口自动化测试项目全流程
#### 1. 环境搭建与工具准备
- **安装核心工具**:
```bash
pip install pytest requests pytest-html allure-pytest
```
- **常用工具链**:
- HTTP请求:`requests`库
- 测试报告:`pytest-html`(基础报告)或`Allure`(高级报告)
- 数据驱动:`pytest-cov`(覆盖率)、`pytest-xdist`(分布式执行)
- Mock服务:`pytest-mock`或`WireMock`
#### 2. 项目结构设计(标准化目录)
```bash
api_auto_test/
├── conftest.py # 全局fixture配置
├── pytest.ini # 配置文件
├── testcases/ # 测试用例
│ ├── __init__.py
│ ├── test_login.py # 模块化用例文件
│ └── test_order.py
├── common/ # 公共模块
│ ├── request_util.py # 请求封装
│ ├── assert_util.py # 断言工具
│ └── config.py # 环境配置
├── data/ # 测试数据
│ ├── login_data.yaml
│ └── order_data.json
├── reports/ # 测试报告
└── logs/ # 运行日志
```
#### 3. 核心模块实现
**request_util.py**(请求封装示例):
```python
import requests
from common.config import BASE_URL
class RequestUtil:
@staticmethod
def send_request(method, endpoint, params=None, json=None, headers=None):
url = f"{BASE_URL}{endpoint}"
response = requests.request(
method=method,
url=url,
params=params,
json=json,
headers=headers,
timeout=10
)
return response
```
**assert_util.py**(增强断言):
```python
def assert_status_code(response, expected_code):
assert response.status_code == expected_code, \
f"实际状态码{response.status_code}, 预期{expected_code}"
def assert_json_key(response, key):
json_data = response.json()
assert key in json_data, f"响应体缺失关键字段: {key}"
```
#### 4. 测试用例编写(test_login.py示例)
```python
import pytest
from common.request_util import RequestUtil
from common.assert_util import assert_status_code
class TestLogin:
@pytest.mark.parametrize("username,password", [
("admin", "correct_pwd"),
("test", "wrong_pwd")
])
def test_login(self, username, password):
# 准备测试数据
payload = {"username": username, "password": password}
# 发送请求
response = RequestUtil.send_request(
method="POST",
endpoint="/api/login",
json=payload
)
# 断言验证
assert_status_code(response, 200)
if username == "admin":
assert "access_token" in response.json()
else:
assert response.json()["error"] == "invalid_credentials"
```
#### 5. 高级功能实现
- **Fixture管理**(conftest.py):
```python
import pytest
@pytest.fixture(scope="session")
def auth_token():
# 获取全局token
response = RequestUtil.send_request(...)
return response.json()["access_token"]
@pytest.fixture(autouse=True)
def log_test_start(request):
print(f"\n=== 开始测试: {request.node.name} ===")
```
- **参数化数据驱动**:
```python
# data/login_data.yaml
- case: 正确管理员登录
username: admin
password: Admin@123
expected_token: true
- case: 错误密码
username: test
password: Wrong!
expected_error: "invalid_credentials"
```
#### 6. 执行与报告生成
- **命令行执行**:
```bash
# 基础执行
pytest -v
# 生成HTML报告
pytest --html=reports/report.html
# Allure报告
pytest --alluredir=reports/allure_results
allure serve reports/allure_results
```
- **持续集成**(Jenkins示例):
```groovy
pipeline {
stages {
stage('Test') {
steps {
sh 'pytest --alluredir=results'
allure includeProperties: false, jdk: '', results: [[path: 'results']]
}
}
}
}
```
#### 7. 项目维护优化
- **异常处理机制**:
```python
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
# 捕获用例失败时截图/日志
if call.when == "call" and call.excinfo is not None:
save_debug_info(item.name)
```
- **自动生成API文档**:
```bash
# 使用pytest-recording生成Swagger文档
pytest --record-mode=rewrite
```
阅读全文
相关推荐


















