帮我写一个接口自动化框架:python+pytest+requests
时间: 2023-09-11 10:05:07 浏览: 115
Python、Requests 和 Pytest 搭建接口自动化测试框架(附完整框架代码).rar
好的,下面是一个简单的接口自动化框架:
1. 安装依赖库
```
pip install pytest
pip install requests
```
2. 创建项目目录结构
```
project
├── api
│ ├── __init__.py
│ └── user_api.py
├── config
│ └── config.ini
├── testcases
│ ├── __init__.py
│ └── test_user_api.py
├── conftest.py
└── pytest.ini
```
3. 编写配置文件
config/config.ini
```
[host]
url = http://localhost:8080/api/
```
4. 编写 API 接口封装
api/user_api.py
```python
import requests
import json
from configparser import ConfigParser
class UserApi:
def __init__(self):
self.config = ConfigParser()
self.config.read('config/config.ini')
self.url = self.config.get('host', 'url')
def get_user(self, user_id):
url = self.url + f'user/{user_id}'
response = requests.get(url)
return json.loads(response.text)
def add_user(self, data):
url = self.url + 'user'
headers = {'Content-Type': 'application/json'}
response = requests.post(url, data=json.dumps(data), headers=headers)
return json.loads(response.text)
def update_user(self, user_id, data):
url = self.url + f'user/{user_id}'
headers = {'Content-Type': 'application/json'}
response = requests.put(url, data=json.dumps(data), headers=headers)
return json.loads(response.text)
def delete_user(self, user_id):
url = self.url + f'user/{user_id}'
response = requests.delete(url)
return json.loads(response.text)
```
5. 编写测试用例
testcases/test_user_api.py
```python
from api.user_api import UserApi
class TestUserApi:
def setup_class(self):
self.api = UserApi()
def test_get_user(self):
user_id = 1
user = self.api.get_user(user_id)
assert user['id'] == user_id
def test_add_user(self):
data = {'name': 'test', 'age': 20}
user = self.api.add_user(data)
assert user['name'] == data['name']
def test_update_user(self):
user_id = 1
data = {'name': 'test1'}
user = self.api.update_user(user_id, data)
assert user['name'] == data['name']
def test_delete_user(self):
user_id = 1
user = self.api.delete_user(user_id)
assert user['id'] == user_id
```
6. 运行测试
在项目根目录下运行以下命令:
```
pytest
```
运行结果如下:
```
============================= test session starts ==============================
platform win32 -- Python 3.9.5, pytest-6.2.4, py-1.10.0, pluggy-0.13.1
rootdir: D:\project
plugins: Faker-8.13.0
collected 4 items
testcases\test_user_api.py .... [100%]
============================== 4 passed in 0.48s ==============================
```
以上就是一个简单的接口自动化框架,你可以根据实际情况进行修改和扩展。
阅读全文