python+requests+pytest+allure+yaml+DDT+logs 接口自动化框架终极版怎么将环境配置成自己的
时间: 2025-01-01 14:02:40 浏览: 5
要在Python中使用requests、pytest、allure、yaml、DDT和logs构建接口自动化框架,并将环境配置成自己的,可以按照以下步骤进行:
### 1. 安装必要的库
首先,确保安装了必要的Python库。你可以使用pip来安装这些库:
```bash
pip install requests pytest allure-pytest PyYAML
```
### 2. 项目结构
创建一个项目目录,并按照以下结构组织文件:
```
project/
│
├── tests/
│ ├── test_cases/
│ │ ├── test_example.py
│ ├── conftest.py
│
├── data/
│ ├── test_data.yaml
│
├── utils/
│ ├── logger.py
│ ├── request_utils.py
│
├── reports/
│
├── config/
│ ├── config.yaml
│
└── requirements.txt
```
### 3. 配置环境
在`config/config.yaml`文件中配置环境变量:
```yaml
base_url: "https://api.example.com"
timeout: 10
```
### 4. 日志配置
在`utils/logger.py`中配置日志:
```python
import logging
import os
def get_logger():
logger = logging.getLogger("api_logger")
logger.setLevel(logging.DEBUG)
if not logger.handlers:
fh = logging.FileHandler("logs/api.log")
fh.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(ch)
return logger
```
### 5. 请求工具
在`utils/request_utils.py`中编写请求工具:
```python
import requests
from utils.logger import get_logger
import yaml
logger = get_logger()
def send_request(method, url, **kwargs):
response = requests.request(method, url, **kwargs)
logger.info(f"Request: {method} {url} {kwargs}")
logger.info(f"Response: {response.status_code} {response.text}")
return response
```
### 6. 测试用例
在`tests/test_cases/test_example.py`中编写测试用例:
```python
import pytest
import yaml
from utils.request_utils import send_request
@pytest.fixture(scope="module")
def config():
with open("config/config.yaml", "r") as file:
config = yaml.safe_load(file)
return config
def test_example(config):
url = config["base_url"] + "/endpoint"
response = send_request("GET", url)
assert response.status_code == 200
```
### 7. 运行测试
使用pytest运行测试,并生成Allure报告:
```bash
pytest --alluredir=reports
allure serve reports
```
### 8. 数据驱动
使用DDT进行数据驱动测试。在`tests/test_cases/test_ddt_example.py`中:
```python
import pytest
import yaml
from utils.request_utils import send_request
@pytest.fixture(scope="module")
def config():
with open("config/config.yaml", "r") as file:
config = yaml.safe_load(file)
return config
@pytest.mark.parametrize("data", yaml.safe_load(open("data/test_data.yaml", "r")))
def test_ddt_example(config, data):
url = config["base_url"] + "/endpoint"
response = send_request("POST", url, json=data)
assert response.status_code == 200
```
### 9. 报告生成
Allure会生成详细的测试报告,可以通过浏览器查看。
阅读全文