Python使用pytest实现接口自动化的框架代码示例
时间: 2023-10-07 21:08:50 浏览: 130
好的,以下是一个简单的使用pytest实现接口自动化的框架代码示例:
```python
import pytest
import requests
@pytest.fixture()
def api_url():
return "https://jsonplaceholder.typicode.com"
def test_get_users(api_url):
response = requests.get(api_url + "/users")
assert response.status_code == 200
assert len(response.json()) > 0
def test_get_user(api_url):
response = requests.get(api_url + "/users/1")
assert response.status_code == 200
assert response.json()["name"] == "Leanne Graham"
def test_create_user(api_url):
new_user = {
"name": "John Doe",
"email": "johndoe@example.com",
"username": "johndoe",
"address": {
"street": "123 Main St",
"suite": "Apt 4",
"city": "Anytown",
"zipcode": "12345-6789",
"geo": {
"lat": "40.1234",
"lng": "-73.5678"
}
},
"phone": "555-1234",
"website": "http://example.com",
"company": {
"name": "Example Inc.",
"catchPhrase": "Making examples since 1999",
"bs": "Software development"
}
}
response = requests.post(api_url + "/users", json=new_user)
assert response.status_code == 201
assert response.json()["name"] == "John Doe"
```
这个例子中,我们使用了pytest的fixture机制来传递API的基础URL。然后,我们编写了三个测试用例来测试获取用户列表、获取单个用户和创建用户功能。每个测试用例都使用requests库发送API请求,并对响应进行断言,以确保API响应符合预期。使用pytest可以更加方便地组织和运行测试用例,并且能够自动生成测试报告等辅助功能。
阅读全文