cleanpy 0.1.3

Python 3.12+ 最佳实践知识库 - MCP 服务器
Documentation
---
topic: parametrized_tests
title: 参数化测试
when_to_use: 需要用不同输入运行相同测试逻辑时
keywords:
  - 参数化
  - pytest.mark.parametrize
  - 数据驱动测试
---

# 参数化测试

## 基本参数化

```python
import pytest

@pytest.mark.parametrize("input,expected", [
    ("hello", "HELLO"),
    ("World", "WORLD"),
    ("123", "123"),
])
def test_uppercase(input, expected):
    assert input.upper() == expected
```

## 多个参数

```python
@pytest.mark.parametrize("a,b,expected", [
    (1, 2, 3),
    (5, 5, 10),
    (-1, 1, 0),
])
def test_addition(a, b, expected):
    assert a + b == expected
```

## 参数化 fixtures

```python
@pytest.fixture(params=["chrome", "firefox", "safari"])
def browser(request):
    return request.param

def test_browser_compatibility(browser):
    # 测试将对每个浏览器运行
    assert browser in ["chrome", "firefox", "safari"]
```

## 组合参数化

```python
@pytest.mark.parametrize("browser", ["chrome", "firefox"])
@pytest.mark.parametrize("language", ["en", "zh", "ja"])
def test_combinations(browser, language):
    # 测试将运行 2 × 3 = 6 次
    pass
```

## 相关链接

- [Pytest 参数化文档]https://docs.pytest.org/en/latest/how-to/parametrize.html