用python中的pytest写一个接口自动化
时间: 2023-10-07 08:08:59 浏览: 83
好的,下面是一个简单的接口自动化测试示例:
1. 安装pytest和requests库
```
pip install pytest requests
```
2. 创建一个测试用例文件test_api.py
```python
import requests
def test_get_user():
url = "https://jsonplaceholder.typicode.com/users/1"
response = requests.get(url)
assert response.status_code == 200
assert response.json()["name"] == "Leanne Graham"
def test_create_user():
url = "https://jsonplaceholder.typicode.com/users"
data = {
"name": "John Doe",
"username": "johndoe",
"email": "johndoe@example.com"
}
response = requests.post(url, json=data)
assert response.status_code == 201
assert response.json()["id"] == 11
```
3. 在命令行中运行pytest
```
pytest
```
测试结果将会输出到控制台,如果所有的测试都通过,那么输出结果为:
```
=============================== test session starts ===============================
collected 2 items
test_api.py .. [100%]
=============================== 2 passed in 0.52s ================================
```
以上就是一个简单的接口自动化测试示例,你可以根据实际需求对测试用例进行扩展和修改。
阅读全文