如何从无到有搭建Python+pytest+allure的接口自动化测试框架

大家好,我是兰若,喜欢技术,热爱分享。用CSDN来记录及分享关于软件测试的一切,今天给大家分享的是如何从无到有搭建一个接口自动化测试框架。

目录结构

project_name/
│
├── config/
│   ├── __init__.py
│   ├── config.py
│
├── tests/
│   ├── __init__.py
│   ├── test_cases/
│   │   ├── __init__.py
│   │   ├── test_example.py
│   │
│   ├── test_data/
│   │   ├── __init__.py
│   │   ├── data_example.json
│   │
│   ├── test_utils/
│       ├── __init__.py
│       ├── utils.py
│
├── reports/
│   ├── README.md
│
├── logs/
│   ├── README.md
│
├── requirements.txt
├── .gitignore
├── pytest.ini
└── README.md

详细文件说明及代码示例

1. config/config.py

用于配置环境信息、API端点等。

# config/config.py
import os

class Config:
    BASE_URL = os.getenv("BASE_URL", "http://localhost:5000/api")
    TIMEOUT = 30

config = Config()
2. tests/test_cases/test_example.py

具体的测试用例文件。

# tests/test_cases/test_example.py
import requests
from config.config import config
from tests.test_utils.utils import send_get_request
import allure

@allure.feature('Example API')
@allure.story('Get Example')
def test_get_example():
    with allure.step("Send GET request to /example"):
        response = send_get_request("example")
    
    with allure.step("Verify the response status code"):
        assert response.status_code == 200
    
    with allure.step("Verify the response content"):
        assert response.json()["key"] == "value"
3. tests/test_data/data_example.json

测试数据文件。

{
    "key": "value"
}
4. tests/test_utils/utils.py

工具函数,包含通用的请求方法、数据处理等。

# tests/test_utils/utils.py
import requests
from config.config import config

def send_get_request(endpoint, params=None):
    url = f"{config.BASE_URL}/{endpoint}"
    response = requests.get(url, params=params, timeout=config.TIMEOUT)
    return response

def send_post_request(endpoint, data=None):
    url = f"{config.BASE_URL}/{endpoint}"
    response = requests.post(url, json=data, timeout=config.TIMEOUT)
    return response
5. requirements.txt

项目依赖包。

requests
pytest
allure-pytest
6. pytest.ini

配置pytest。

# pytest.ini
[pytest]
minversion = 6.0
addopts = --alluredir=reports --clean-alluredir
testpaths = tests/test_cases
7. .gitignore

忽略不需要提交到版本控制的文件。

/logs
/reports
__pycache__
*.pyc
.env
8. README.md

项目说明文档。

# Project Name

## Description
This is a project for API testing using Python, pytest, and Allure.

## Installation
1. Clone the repository
2. Create a virtual environment
3. Install dependencies:
    ```
    pip install -r requirements.txt
    ```

## Usage
Run tests:

pytest


Generate Allure report:

allure serve reports

详细步骤

  1. 创建虚拟环境并安装依赖

    • 创建虚拟环境:python -m venv venv
    • 激活虚拟环境并安装依赖:pip install -r requirements.txt
  2. 配置环境变量

    • 在项目根目录创建一个.env文件,用于存储环境变量,如API的基本URL。
    • 使用python-dotenv库读取.env文件中的环境变量。
  3. 编写测试用例

    • tests/test_cases/目录中编写具体的测试用例。
    • 使用requests库发送HTTP请求,验证响应。
    • 使用Allure的装饰器@allure.feature@allure.story标记测试用例。
    • 在测试用例中使用Allure的allure.step记录详细的测试步骤。
  4. 组织测试数据

    • tests/test_data/目录中组织测试数据,使用JSON格式存储。
  5. 编写工具函数

    • tests/test_utils/utils.py中编写常用的请求方法和数据处理函数,便于复用。
  6. 运行测试并生成报告

    • 使用pytest运行测试,并生成Allure格式的测试报告。
    • 配置pytest.ini文件,便于自定义pytest的行为和生成报告。
  7. 查看Allure报告

    • 使用allure serve reports命令生成并查看Allure测试报告。

实施自动化测试框架的详细步骤

1. 创建虚拟环境并安装依赖

在项目根目录下,运行以下命令创建并激活虚拟环境:

python -m venv venv
source venv/bin/activate  # Unix/macOS
venv\Scripts\activate  # Windows
pip install -r requirements.txt
2. 配置环境变量

在项目根目录下创建一个.env文件,内容如下:

BASE_URL=http://localhost:5000/api

使用python-dotenv库在config/config.py中读取环境变量:

from dotenv import load_dotenv
import os

load_dotenv()

class Config:
    BASE_URL = os.getenv("BASE_URL", "http://localhost:5000/api")
    TIMEOUT = 30

config = Config()
3. 编写测试用例

tests/test_cases/目录中编写具体的测试用例,例如:

# tests/test_cases/test_example.py
import requests
from config.config import config
from tests.test_utils.utils import send_get_request
import allure

@allure.feature('Example API')
@allure.story('Get Example')
def test_get_example():
    with allure.step("Send GET request to /example"):
        response = send_get_request("example")
    
    with allure.step("Verify the response status code"):
        assert response.status_code == 200
    
    with allure.step("Verify the response content"):
        assert response.json()["key"] == "value"
4. 组织测试数据

tests/test_data/目录中创建测试数据文件,例如:

{
    "key": "value"
}
5. 编写工具函数

tests/test_utils/utils.py中编写常用的请求方法和数据处理函数,例如:

# tests/test_utils/utils.py
import requests
from config.config import config

def send_get_request(endpoint, params=None):
    url = f"{config.BASE_URL}/{endpoint}"
    response = requests.get(url, params=params, timeout=config.TIMEOUT)
    return response

def send_post_request(endpoint, data=None):
    url = f"{config.BASE_URL}/{endpoint}"
    response = requests.post(url, json=data, timeout=config.TIMEOUT)
    return response
6. 运行测试并生成报告

运行以下命令来运行测试并生成Allure报告:

pytest
allure serve reports
7. 查看Allure报告

使用allure serve reports命令生成并查看Allure测试报告,该命令将启动一个临时的Web服务器,并在浏览器中打开报告。

通过以上步骤和文件组织,可以构建一个高效的接口测试自动化框架,使用Allure生成详细的测试报告,提升测试的覆盖率和可维护性。

  • 23
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的 Python + Pytest + Allure 实现接口自动化 POM 框架的示例: 1. 安装依赖库 ``` pip install requests pip install pytest pip install allure-pytest ``` 2. 创建项目目录结构: ``` ├── api │ ├── __init__.py │ ├── base_api.py │ └── user_api.py ├── common │ ├── __init__.py │ ├── constants.py │ ├── logger.py │ └── utils.py ├── config │ ├── __init__.py │ └── config.py ├── data │ ├── __init__.py │ └── users.json ├── pytest.ini ├── README.md ├── requirements.txt ├── testcases │ ├── __init__.py │ ├── conftest.py │ ├── test_login.py │ └── test_user.py └── pytest.ini ``` 3. 编写配置文件 `config.py`、常量文件 `constants.py` 等。 `config.py`: ```python class Config: API_BASE_URL = 'https://xxx.com/api' USERNAME = 'testuser' PASSWORD = 'testpass' ``` `constants.py`: ```python class StatusCode: SUCCESS = 200 CLIENT_ERROR = 400 SERVER_ERROR = 500 ``` 4. 创建 HTTP 请求封装类 `base_api.py` 和业务接口类 `user_api.py` `base_api.py`: ```python import requests from common.logger import logger from common.constants import StatusCode from config.config import Config class BaseApi: def __init__(self): self.session = requests.session() self.base_url = Config.API_BASE_URL def request(self, method, url, **kwargs): url = self.base_url + url response = self.session.request(method, url, **kwargs) logger.info(f'{method} {url} {kwargs} response: {response.json()}') return response def get(self, url, params=None, **kwargs): return self.request('get', url, params=params, **kwargs) def post(self, url, data=None, json=None, **kwargs): return self.request('post', url, data=data, json=json, **kwargs) def put(self, url, data=None, **kwargs): return self.request('put', url, data=data, **kwargs) def delete(self, url, **kwargs): return self.request('delete', url, **kwargs) def assert_status_code(self, response, expected_status_code): assert response.status_code == expected_status_code, \ f'Expected status code is {expected_status_code}, but actual is {response.status_code}' response_json = response.json() assert response_json['code'] == StatusCode.SUCCESS, \ f'Response code is {response_json["code"]}, message is {response_json["message"]}' ``` `user_api.py`: ```python from api.base_api import BaseApi from common.constants import StatusCode from config.config import Config from common.utils import json_load class UserApi(BaseApi): def __init__(self): super().__init__() def login(self): url = '/login' data = { 'username': Config.USERNAME, 'password': Config.PASSWORD } response = self.post(url, json=data) self.assert_status_code(response, StatusCode.SUCCESS) return response.json()['data']['access_token'] def get_user_info(self, user_id): url = f'/users/{user_id}' headers = { 'Authorization': f'Bearer {self.login()}' } response = self.get(url, headers=headers) self.assert_status_code(response, StatusCode.SUCCESS) return response.json()['data'] def create_user(self, data): url = '/users' headers = { 'Authorization': f'Bearer {self.login()}' } response = self.post(url, json=data, headers=headers) self.assert_status_code(response, StatusCode.SUCCESS) return response.json()['data'] def delete_user(self, user_id): url = f'/users/{user_id}' headers = { 'Authorization': f'Bearer {self.login()}' } response = self.delete(url, headers=headers) self.assert_status_code(response, StatusCode.SUCCESS) return response.json()['data'] def get_random_user(self): users = json_load('data/users.json') return users[0] ``` 5. 编写测试用例 `test_user.py` 和 `test_login.py` `test_user.py`: ```python import pytest from api.user_api import UserApi class TestUser: @pytest.fixture(scope='class') def user(self): return UserApi().get_random_user() def test_create_and_delete_user(self, user): user_api = UserApi() new_user = user_api.create_user(user) assert new_user['username'] == user['username'] user_api.delete_user(new_user['id']) def test_get_user_info(self): user_api = UserApi() user_info = user_api.get_user_info(1) assert user_info['username'] == 'admin' ``` `test_login.py`: ```python import pytest from api.user_api import UserApi class TestLogin: def test_login(self): user_api = UserApi() access_token = user_api.login() assert access_token is not None ``` 6. 运行测试用例 在项目根目录下执行以下命令: ``` pytest --alluredir=./allure-results testcases/ ``` 7. 生成报告 在项目根目录下执行以下命令: ``` allure serve ./allure-results ``` 此时会启动一个本地服务,打开浏览器输入 `http://localhost:port` 即可查看测试报告。 以上就是一个简单的 Python + Pytest + Allure 实现接口自动化 POM 框架的示例,希望对你有帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值