告诉大家通过设置pytest.ini 中参数来提升测试效率的方法

pytest.ini 是 pytest 的配置文件,用于定义 pytest 的默认行为和自定义规则。除了我们熟知的 addoptstestpaths 和 markers,还有多个常用参数可以配置。在实际工作中,使用好这些参数可以大大提升我们的测试效率。

1. 基本配置参数

addopts
  • 作用:定义默认的命令行参数,每次运行 pytest 时自动添加这些参数。

  • 示例

    [pytest]
    addopts = -v --tb=short --strict-markers
testpaths
  • 作用:指定 pytest 搜索测试文件的目录(默认是当前目录)。

  • 示例

    [pytest]
    testpaths = tests/ unit_tests/
markers
  • 作用:注册自定义标记,避免未注册标记的警告。

  • 示例

    [pytest]
    markers =
        slow: 标记为运行缓慢的测试
        smoke: 冒烟测试

2. 测试发现规则

python_files
  • 作用:定义 pytest 识别为测试文件的文件名模式(默认是 test_*.py 和 *_test.py)。

  • 示例

    [pytest]
    python_files = check_*.py  # 匹配如 check_login.py
python_classes
  • 作用:定义 pytest 识别为测试类的类名模式(默认是 Test*)。

  • 示例

    [pytest]
    python_classes = *Test  # 匹配如 LoginTest
python_functions
  • 作用:定义 pytest 识别为测试函数的函数名模式(默认是 test_*)。

  • 示例

    [pytest]
    python_functions = test_*  # 默认值,匹配如 test_login()
norecursedirs
  • 作用:指定 pytest 忽略的目录(默认忽略 .*builddistnode_modules 等)。

  • 示例

    [pytest]
    norecursedirs = .git venv cache

3. 报告与日志

junit_suite_name
  • 作用:指定 JUnit XML 报告中的测试套件名称。

  • 示例

    [pytest]
    junit_suite_name = MyTestSuite
log_cli
  • 作用:控制是否在控制台实时输出日志(需配合 -s 禁用输出捕获)。

  • 示例

    [pytest]
    log_cli = true  # 启用实时日志
    log_cli_level = INFO  # 设置日志级别

4. 警告处理

filterwarnings
  • 作用:过滤 Python 警告(支持 ignoreerror 等操作)。

  • 示例

    [pytest]
    filterwarnings =
        ignore:.*deprecated.*  # 忽略包含 "deprecated" 的警告
        error:ResourceWarning  # 将 ResourceWarning 转为错误

5. 缓存与插件

cache_dir
  • 作用:指定 pytest 缓存目录(默认是 .pytest_cache)。

  • 示例

    [pytest]
    cache_dir = /tmp/pytest_cache
required_plugins
  • 作用:强制要求安装指定的 pytest 插件(未安装时报错)。

  • 示例

    [pytest]
    required_plugins = pytest-html pytest-cov

6. 文档测试(Doctest)

doctest_optionflags
  • 作用:配置文档测试的选项(如 NORMALIZE_WHITESPACE)。

  • 示例

    [pytest]
    doctest_optionflags = NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL

7. 其他常用参数

timeout
  • 作用:设置单个测试用例的超时时间(需安装 pytest-timeout)。

  • 示例

    [pytest]
    timeout = 30  # 每个测试最多运行 30 秒
asyncio_mode
  • 作用:配置异步测试模式(需安装 pytest-asyncio)。

  • 示例

    [pytest]
    asyncio_mode = auto

完整示例

[pytest]
# 基本配置
addopts = -v --tb=short
testpaths = tests/
markers =
    slow: 标记慢速测试
    smoke: 冒烟测试

# 测试发现
python_files = test_*.py
python_classes = *Test
python_functions = test_*
norecursedirs = .git venv

# 报告与日志
junit_suite_name = API_Tests
log_cli = true
log_cli_level = INFO

# 警告处理
filterwarnings =
    ignore:.*deprecated.*

# 缓存
cache_dir = .pytest_cache

验证配置

运行以下命令检查配置是否生效:

pytest --help | grep "cachedir"  # 查看缓存目录配置
pytest --markers                # 查看注册的标记

通过这些配置,可以统一团队测试规范,减少重复命令行输入,提高测试效率。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

测试开发Kevin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值