搭建一个 python + unittest+request 接口自动化框架
时间: 2024-01-23 20:03:17 浏览: 100
搭建 Python + unittest + requests 接口自动化框架的步骤如下:
1. 安装 Python:首先需要在电脑上安装 Python,推荐安装 Python3.x 版本。
2. 安装 unittest:unittest 是 Python 自带的单元测试框架,无需额外安装。
3. 安装 requests:requests 是 Python 中的 HTTP 库,用来发送 HTTP 请求和获取 HTTP 响应。
安装命令:`pip install requests`
4. 创建项目目录:在电脑上创建一个项目目录,用来存放测试代码和测试数据。
5. 创建测试用例:在项目目录中创建一个 test_case.py 文件,用来编写接口测试用例。
6. 编写测试代码:在 test_case.py 文件中,编写测试代码,使用 unittest 框架中的 TestCase 和 assert 方法来编写测试用例。
7. 运行测试用例:在命令行中切换到项目目录,运行 `python -m unittest test_case.py` 命令来执行测试用例。
8. 可以将测试用例的执行结果输出到文件中,方便后面查看。
以上就是 Python + unittest + requests 接口自动化框架的搭建步骤,可以根据实际情况进行调整和优化。
相关问题
用python+requests+pytest+ddt+unnitest搭建一套自动化框架
搭建一个基于Python + requests + pytest + ddt + unittest 的自动化测试框架,可以按照以下步骤进行:
1. 安装所需依赖:在你的项目环境中安装 requests、pytest、ddt 和 unittest。
```
pip install requests pytest ddt unittest
```
2. 创建项目结构:在你的项目目录下创建以下文件和文件夹结构:
```
├── tests
│ ├── __init__.py
│ └── test_cases.py
├── data
│ └── test_data.xlsx
└── conftest.py
```
3. 编写测试用例:在 `test_cases.py` 文件中编写你的测试用例,可以使用 `ddt` 来实现数据驱动,示例:
```python
import unittest
import ddt
from data.test_data import TestData
from utils.api_helper import APIClient
@ddt.ddt
class APITestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.client = APIClient()
@ddt.data(*TestData.test_data)
def test_api(self, data):
response = self.client.send_request(data['url'], data['method'], data['payload'])
self.assertEqual(response.status_code, data['expected_status'])
self.assertEqual(response.json(), data['expected_response'])
```
4. 创建测试数据:在 `test_data.xlsx` 文件中创建测试数据,可以使用 `openpyxl` 库来读取 Excel 数据,示例:
```python
import openpyxl
class TestData:
workbook = openpyxl.load_workbook('data/test_data.xlsx')
sheet = workbook['Sheet1']
test_data = []
for row in sheet.iter_rows(min_row=2, values_only=True):
test_data.append({
'url': row[0],
'method': row[1],
'payload': row[2],
'expected_status': row[3],
'expected_response': row[4]
})
```
5. 创建 API 辅助类:在 `api_helper.py` 文件中创建一个 APIClient 类,用于发送 API 请求,示例:
```python
import requests
class APIClient:
def send_request(self, url, method, payload):
if method == 'GET':
response = requests.get(url, params=payload)
elif method == 'POST':
response = requests.post(url, json=payload)
elif method == 'PUT':
response = requests.put(url, json=payload)
elif method == 'DELETE':
response = requests.delete(url)
else:
raise ValueError('Invalid HTTP method')
return response
```
6. 创建 pytest 配置:在 `conftest.py` 文件中配置 pytest,示例:
```python
import pytest
def pytest_addoption(parser):
parser.addoption("--base-url", action="store", default="http://localhost:8000", help="Base URL for API tests")
@pytest.fixture(scope="session")
def base_url(request):
return request.config.getoption("--base-url")
```
7. 运行测试:在命令行中执行以下命令来运行测试用例:
```
pytest -s tests/
```
`-s` 参数用于显示打印信息。
这样,你就搭建了一个基于 Python + requests + pytest + ddt + unittest 的自动化测试框架,可以进行接口测试。你可以根据实际需求进一步扩展和优化这个框架。
python接口自动化框架搭建
### 构建 Python API 自动化测试框架
#### 使用的技术栈
为了实现接口自动化,可以采用 `python` 结合多个库来完成这一目标。具体来说,会用到 `unittest` 进行单元测试编写,`request` 发起 HTTP 请求,`openpyxl` 处理 Excel 文件中的测试数据,`myddt` 支持参数化测试案例,以及 `pymysql` 实现数据库操作[^1]。
#### 总体架构设计
整个框架的设计围绕着模块化展开,确保各个部分职责分明又相互协作。主要分为以下几个方面:
- **环境准备**:包括但不限于创建虚拟环境、安装依赖项等前置工作。
- **配置管理**:定义全局变量或常量用于存储项目路径、API URL 前缀等信息。
- **工具类封装**:针对特定功能如日志记录、邮件通知等功能进行抽象并提供统一接口。
- **核心业务逻辑层**:
- 测试结果收集与报告生成
- **扩展支持**:考虑未来可能增加的需求,比如与其他系统的集成或是新的特性引入。
#### 示例代码片段展示
以下是基于上述描述的一个简化版例子,展示了如何利用这些组件来进行一次完整的 API 调用测试流程。
```python
import unittest
from ddt import data, unpack, ddt
import requests
import pymysql
from openpyxl import load_workbook
@ddt
class TestApi(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.conn = pymysql.connect(host='localhost', user='root', password='', db='')
@data(('get_user_info', 'POST', '/api/user/info'), ('create_order', 'GET', '/api/order/create'))
@unpack
def test_api(self, name, method, url_path):
wb = load_workbook('cases.xlsx')
sheet = wb.active
row_data = next(sheet.iter_rows(min_row=2, max_col=3))
params = {cell.value for cell in row_data}
response = getattr(requests, method.lower())(f"http://example.com{url_path}", json=params)
cursor = self.conn.cursor()
sql_query = "SELECT * FROM users WHERE id=%s"
cursor.execute(sql_query, (params['id'], ))
result = cursor.fetchone()
expected_result = {"status": True} # Assume this is the expectation from excel file.
actual_result = {'status': bool(result)}
assertEqual(expected_result, actual_result)
if __name__ == '__main__':
unittest.main()
```
此段代码实现了对两个不同 API 的调用,并通过连接 MySQL 数据库获取预期的结果来进行比较校验[^5]。
阅读全文
相关推荐














