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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值