安装与基础配置

确保已安装Python 3.7+,通过pip安装pytest:

pip install pytest

创建项目结构,示例目录如下:

project/
├── tests/
│   ├── __init__.py
│   └── test_sample.py
└── src/
    └── calculator.py

基础测试用例设计

编写被测对象示例(calculator.py):

def add(a, b):
    return a + b

def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b

对应测试文件(test_sample.py):

from src.calculator import add, divide

def test_add_positive_numbers():
    assert add(2, 3) == 5

def test_add_negative_numbers():
    assert add(-1, -1) == -2

def test_divide_normal_case():
    assert divide(6, 3) == 2

def test_divide_by_zero():
    import pytest
    with pytest.raises(ValueError):
        divide(1, 0)

参数化测试

使用@pytest.mark.parametrize减少重复代码:

import pytest
from src.calculator import add

@pytest.mark.parametrize("a,b,expected", [
    (1, 2, 3),
    (0, 0, 0),
    (-1, 1, 0),
])
def test_add_multiple_cases(a, b, expected):
    assert add(a, b) == expected

Fixture使用

创建共享测试资源(conftest.py):

import pytest

@pytest.fixture
def sample_data():
    return {"key": "value"}

@pytest.fixture(scope="module")
def db_connection():
    conn = create_test_db()
    yield conn
    conn.close()

在测试中使用fixture:

def test_fixture_usage(sample_data):
    assert sample_data["key"] == "value"

插件与高级功能

生成HTML测试报告:

pip install pytest-html
pytest --html=report.html

使用mock进行单元测试:

from unittest.mock import patch

def test_api_call():
    with patch('requests.get') as mock_get:
        mock_get.return_value.status_code = 200
        response = make_api_call()
        assert response.status_code == 200

测试覆盖率统计

安装覆盖率插件并运行:

pip install pytest-cov
pytest --cov=src tests/

生成覆盖率报告:

pytest --cov=src --cov-report=html tests/

持续集成配置

示例GitHub Actions配置(.github/workflows/test.yml):

name: Python Test

on: [push]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Set up Python
        uses: actions/setup-python@v2
        with:
          python-version: '3.9'
      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install pytest pytest-cov
      - name: Test with pytest
        run: |
          pytest --cov=src --cov-report=xml
      - name: Upload coverage
        uses: codecov/codecov-action@v1

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐