python+pytest实现接口自动化框架
时间: 2023-10-07 10:10:16 浏览: 110
python接口自动化框架
Python + pytest 是一种常见的接口自动化测试框架组合,下面是一些实现步骤:
1. 安装 pytest:
```
pip install pytest
```
2. 创建项目目录结构:
```
- project
- api
- __init__.py
- auth.py
- user.py
- tests
- __init__.py
- test_auth.py
- test_user.py
- conftest.py
```
3. 编写 API 接口代码:
在 `api` 目录下创建 `auth.py` 和 `user.py` 文件,分别编写用户认证和用户管理的接口代码,例如:
```python
# auth.py
import requests
def login(username, password):
url = "http://api.example.com/login"
data = {"username": username, "password": password}
response = requests.post(url, data=data)
return response.json()
def logout(token):
url = "http://api.example.com/logout"
headers = {"Authorization": f"Bearer {token}"}
response = requests.post(url, headers=headers)
return response.json()
```
```python
# user.py
import requests
def get_user(user_id, token):
url = f"http://api.example.com/users/{user_id}"
headers = {"Authorization": f"Bearer {token}"}
response = requests.get(url, headers=headers)
return response.json()
def create_user(username, password, email, token):
url = "http://api.example.com/users"
headers = {"Authorization": f"Bearer {token}"}
data = {"username": username, "password": password, "email": email}
response = requests.post(url, headers=headers, data=data)
return response.json()
```
4. 编写测试代码:
在 `tests` 目录下创建 `test_auth.py` 和 `test_user.py` 文件,分别编写用户认证和用户管理的接口测试代码,例如:
```python
# test_auth.py
import pytest
from api.auth import login, logout
def test_login():
response = login("testuser", "testpass")
assert response["status"] == "success"
def test_logout():
token = "testtoken"
response = logout(token)
assert response["status"] == "success"
```
```python
# test_user.py
import pytest
from api.user import get_user, create_user
def test_get_user():
user_id = 1
token = "testtoken"
response = get_user(user_id, token)
assert response["id"] == user_id
def test_create_user():
username = "testuser"
password = "testpass"
email = "testuser@example.com"
token = "testtoken"
response = create_user(username, password, email, token)
assert response["username"] == username
```
5. 编写 conftest.py 文件:
在 `project` 目录下创建 `conftest.py` 文件,用于配置测试环境和共享 fixture,例如:
```python
import pytest
@pytest.fixture(scope="session")
def token():
return "testtoken"
```
6. 运行测试:
在命令行中进入 `project` 目录,执行以下命令运行所有测试:
```
pytest
```
以上是一个简单的 Python + pytest 的接口自动化测试框架,你可以根据实际需求进行扩展。
阅读全文