三步实现高效参数化
1. 基础参数化模板
import pytest
@pytest.mark.parametrize("username,password", 
    [("admin", "123456"), ("test", "Test@2023")])
def test_login(username, password):
    assert len(username) >= 5, "用户名长度不达标"
    assert any(c.isupper() for c in password), "密码需包含大写字母"
2. 动态参数生成器
def generate_test_data():
    return [(x, x*2) for x in range(1, 6)]
@pytest.mark.parametrize("input,expected", generate_test_data())
def test_double(input, expected):
    assert input*2 == expected
3. 条件参数化决策
config_params = [
    pytest.param("chrome", "win10", marks=pytest.mark.smoke),
    pytest.param("firefox", "ubuntu", marks=pytest.mark.regression)
]
@pytest.mark.parametrize("browser,os", config_params)
def test_cross_browser(browser, os):
    print(f"正在执行{browser}@{os}环境测试")
企业级外部数据接入方案
| 数据类型 | 加载方式 | 适用场景 | 维护成本 | 
|---|---|---|---|
| YAML | PyYAML库 | 多层嵌套配置 | ★★☆ | 
| JSON | json模块 | 前后端交互数据 | ★☆☆ | 
| Excel | pandas+openpyxl | 业务流数据 | ★★★ | 
| CSV | csv模块 | 大规模数据集 | ★☆☆ | 
| 数据库 | SQLAlchemy | 动态实时数据 | ★★★★ | 
YAML实战示例
# test_data.yaml
test_cases:
  - case_id: TC_001
    input: 
      username: "user_pro"
      password: "SecurePwd!123"
    expected: "登录成功"
  - case_id: TC_002
    input:
      username: "guest"
      password: "weak"
    expected: "密码强度不足"
配套加载器代码:
import yaml
import pytest
def load_yaml_data(file_path):
    with open(file_path) as f:
        return yaml.safe_load(f)['test_cases']
@pytest.mark.parametrize("test_case", load_yaml_data("test_data.yaml"))
def test_yaml_driven(test_case):
    print(f"执行用例{test_case['case_id']}")
    assert "成功" in test_case['expected'], "预期结果验证失败"
 
高级测试套件管理
分布式执行方案:
1. 安装插件:pip install pytest-xdist
2. 终端命令:pytest -n 4(启动4个worker并行执行)
3. 资源监控:增加--boxed参数隔离测试进程
性能对比数据:
┌────────────┬──────────┬───────────┐
│ 用例数量   │ 串行耗时 │ 4核并行   │
├────────────┼──────────┼───────────┤
│ 1000条     │ 18min23s │ 4min51s   │
│ 5000条     │ 1h32min  │ 23min17s  │
└────────────┴──────────┴───────────┘
TIP:在pytest.ini中配置默认参数:
[pytest]
addopts = -n auto --html=report.html --self-contained-html
遇到参数化数据过载时,可通过
pytest --lf仅执行上次失败的用例,快速定位问题。
原创文章,作者:,如若转载,请注明出处:https://zube.cn/archives/140
 赞 (0)
                                                    