pytest接口自动化框架简单编写代码示范一下?
时间: 2023-09-04 21:13:08 浏览: 85
下面是一个简单的pytest接口自动化测试框架的代码示例:
1. 创建一个test_api.py文件,编写测试用例代码:
```python
import pytest
import requests
@pytest.fixture
def api_url():
return "https://jsonplaceholder.typicode.com"
def test_get_posts(api_url):
response = requests.get(api_url + "/posts")
assert response.status_code == 200
def test_get_post(api_url):
response = requests.get(api_url + "/posts/1")
assert response.status_code == 200
assert response.json()["id"] == 1
def test_create_post(api_url):
data = {"title": "pytest", "body": "api testing", "userId": 1}
response = requests.post(api_url + "/posts", json=data)
assert response.status_code == 201
assert response.json()["id"] == 101
```
2. 在命令行中运行pytest命令,执行测试用例:
```
pytest test_api.py
```
3. 结果输出:
```
============================= test session starts =============================
platform win32 -- Python 3.9.6, pytest-6.2.4, py-1.10.0, pluggy-0.13.1
rootdir: D:\projects\pytest
collected 3 items
test_api.py ... [100%]
============================== 3 passed in 0.56s ==============================
```
这个示例展示了如何使用pytest框架编写简单的接口自动化测试,其中使用了pytest的fixture机制来管理测试数据和测试环境。通过编写简单的测试用例代码,可以快速验证API的正确性,从而提高软件质量和开发效率。
阅读全文