pytest接口自动化测试框架搭建

搭建一个基于 pytest的接口自动化测试框架,可以帮助开发者和测试人员更高效地执行和管理API测试。pytest是一个功能强大且灵活的Python测试框架,支持多种测试需求,包括单元测试、集成测试和功能测试。本文将详细介绍如何搭建一个高效的 pytest接口自动化测试框架。

1. 环境准备

首先,确保已经安装了Python和 pip。然后安装 pytest和其他必要的库。

pip install pytest requests
 

2. 项目结构

一个清晰的项目结构有助于管理测试用例和配置文件。以下是推荐的项目结构:

api_test/
├── tests/
│   ├── __init__.py
│   ├── test_api.py
├── config/
│   ├── __init__.py
│   ├── config.py
├── utils/
│   ├── __init__.py
│   ├── request_helper.py
├── conftest.py
├── requirements.txt
├── pytest.ini
 

3. 配置文件

创建 config/config.py,存放API的基本配置信息,例如base URL和API密钥。

# config/config.py

BASE_URL = "https://api.example.com"
API_KEY = "your_api_key"
 

4. 请求辅助模块

编写一个请求辅助模块来封装HTTP请求的逻辑,方便复用。

# utils/request_helper.py

import requests
from config import config

def get(endpoint, params=None, headers=None):
    url = f"{config.BASE_URL}/{endpoint}"
    default_headers = {"Authorization": f"Bearer {config.API_KEY}"}
    if headers:
        default_headers.update(headers)
    response = requests.get(url, params=params, headers=default_headers)
    return response

def post(endpoint, data=None, headers=None):
    url = f"{config.BASE_URL}/{endpoint}"
    default_headers = {"Authorization": f"Bearer {config.API_KEY}"}
    if headers:
        default_headers.update(headers)
    response = requests.post(url, json=data, headers=default_headers)
    return response
 

5. 编写测试用例

在 tests目录下编写测试用例,使用 pytest的特性进行测试和验证。

# tests/test_api.py

import pytest
from utils import request_helper

def test_get_example():
    response = request_helper.get("example_endpoint")
    assert response.status_code == 200
    assert "expected_key" in response.json()

def test_post_example():
    data = {"key": "value"}
    response = request_helper.post("example_endpoint", data=data)
    assert response.status_code == 201
    assert response.json()["key"] == "value"
 

6. 共享资源与前置条件

使用 conftest.py文件定义共享资源和前置条件。

# conftest.py

import pytest

@pytest.fixture(scope="module")
def setup_module():
    # 模块级别的前置条件
    print("Setting up module")
    yield
    # 模块级别的后置条件
    print("Tearing down module")

@pytest.fixture(scope="function")
def setup_function():
    # 函数级别的前置条件
    print("Setting up function")
    yield
    # 函数级别的后置条件
    print("Tearing down function")
 

7. 配置pytest

在项目根目录下创建 pytest.ini文件,配置pytest的相关选项。

# pytest.ini

[pytest]
minversion = 6.0
addopts = -ra -q
testpaths = tests
 

8. 运行测试

在项目根目录下执行 pytest命令运行测试。

pytest
posted @ 2025-08-24 10:28  u95900090  阅读(36)  评论(0)    收藏  举报