用python做接口自动化详细案例
时间: 2024-01-21 21:04:06 浏览: 103
接口自动化测试是通过编写脚本来模拟客户端发送请求,调用API接口并验证返回结果是否符合预期的一种测试方式。下面是一个简单的Python接口自动化测试案例。
1. 安装必要的库
我们需要使用requests库来发送http请求,以及jsonpath库来解析返回的json数据。在命令行中输入以下命令安装:
```
pip install requests
pip install jsonpath
```
2. 编写测试脚本
我们以一个获取天气信息的API接口为例,测试用例如下:
```python
import requests
import jsonpath
# 发送http请求获取天气信息
def test_weather_api():
url = "http://www.weather.com.cn/data/sk/101010100.html"
response = requests.get(url)
assert response.status_code == 200
# 解析返回的json数据
data = response.json()
city = jsonpath.jsonpath(data, '$.weatherinfo.city')[0]
temp = jsonpath.jsonpath(data, '$.weatherinfo.temp')[0]
wind = jsonpath.jsonpath(data, '$.weatherinfo.WD')[0]
# 验证返回结果是否符合预期
assert city == "北京"
assert temp[-1] == "℃"
assert wind == "北风"
```
3. 运行测试
我们可以使用pytest库来运行测试脚本。在命令行中进入脚本所在目录,并运行以下命令:
```
pytest test_weather.py
```
如果一切顺利,我们应该会看到类似如下的输出:
```
====================================== test session starts ======================================
platform win32 -- Python 3.7.3, pytest-5.4.3, py-1.9.0, pluggy-0.13.1
rootdir: C:\path\to\test\script
collected 1 item
test_weather.py . [100%]
======================================= 1 passed in 0.42s =======================================
```
这表示我们的测试用例通过了。如果有任何一个断言失败,pytest会输出详细的错误信息,帮助我们快速定位问题。
以上是一个简单的Python接口自动化测试案例。实际上,我们还可以使用更多的库和工具来进行更加复杂的接口自动化测试。
阅读全文
相关推荐

















