pytest ini

pytest.ini 是 Pytest 的配置文件之一,它用于集中管理测试的默认配置,避免在命令行重复输入参数。除了 pytest.ini,其他可选的配置文件包括 tox.inipyproject.toml

pytest.ini 配置项

1. 基本结构

[pytest]
# 1. 添加默认的命令行选项
addopts = -v -s --tb=short 

# 2. 指定测试文件目录(默认是当前目录)
testpaths = tests

# 3. 匹配测试文件的模式
python_files = test_*.py *_test.py

# 4. 匹配测试类
python_classes = Test*

# 5. 匹配测试函数
python_functions = test_*

# 6. 禁用特定警告
filterwarnings =
    ignore::DeprecationWarning

2. 详细参数介绍

🔹 1. addopts - 额外的命令行选项

用于指定默认的 pytest 运行参数,例如:

[pytest]
addopts = -v -s --maxfail=3 --tb=short
  • -v :详细模式(verbose),显示更多信息
  • -s :允许 print() 输出到终端
  • --maxfail=3 :如果出现 3 个失败,则停止运行
  • --tb=short :显示精简的 traceback(回溯)

🔹 2. testpaths - 指定测试目录

默认情况下,pytest 会搜索当前目录下的测试文件。
可以使用 testpaths 限定 pytest 只在特定目录中查找测试:

[pytest]
testpaths = tests integration_tests

✅ 这意味着 pytest 只会在 tests/integration_tests/ 目录下寻找测试。


🔹 3. python_files - 指定测试文件匹配模式

默认情况下,pytest 认为 test_*.py 是测试文件。
可以自定义匹配模式:

[pytest]
python_files = test_*.py *_test.py mytest_*.py

✅ 这意味着 pytest 会识别 test_xxx.pyxxx_test.pymytest_xxx.py 作为测试文件。


🔹 4. python_classes - 指定测试类匹配模式

默认情况下,pytest 只会识别以 Test 开头的类作为测试类。
可以自定义匹配:

[pytest]
python_classes = Test* Check*

✅ 这样 pytest 会识别 TestLoginCheckAPI 作为测试类。

注意:

  • 类名 不能test_ 开头,否则 pytest 不会执行其中的方法。

🔹 5. python_functions - 指定测试函数匹配模式

默认情况下,pytest 只会识别 test_ 开头的函数。
可以自定义匹配:

[pytest]
python_functions = test_* check_*

✅ 这样 pytest 会执行 test_login()check_api_response() 作为测试函数。


🔹 6. filterwarnings - 过滤警告

如果你的测试代码里有 DeprecationWarning,可以忽略它:

[pytest]
filterwarnings =
    ignore::DeprecationWarning

✅ 这样 pytest 不会再显示 DeprecationWarning


🔹 7. log_cli - 启用 CLI 日志

pytest 在终端输出 logging 日志:

[pytest]
log_cli = true
log_cli_level = INFO
log_cli_format = %(asctime)s [%(levelname)s] %(message)s
log_cli_date_format = %Y-%m-%d %H:%M:%S

✅ 这样 pytest 会以 INFO 级别实时输出日志。


🔹 8. timeout - 设置测试超时时间

可以给 所有测试 设置超时时间:

[pytest]
timeout = 10  # 每个测试最多运行 10 秒

✅ 如果某个测试运行超过 10 秒,pytest 会强制终止它。


🔹 9. markers - 自定义标记

如果你使用 @pytest.mark.xxx 自定义标记,需要在 pytest.ini 里声明:

[pytest]
markers =
    smoke: 重要的冒烟测试
    regression: 回归测试
    slow: 运行较慢的测试

然后在测试代码中使用:

import pytest

@pytest.mark.smoke
def test_login():
    assert 1 + 1 == 2

✅ 这样你可以运行 pytest -m smoke 只执行 smoke 测试。


🔹 10. cache_dir - 缓存目录

指定 pytest 缓存测试结果的位置:

[pytest]
cache_dir = /tmp/pytest_cache

✅ 这样 pytest 会把缓存文件存到 /tmp/pytest_cache


总结

选项作用
addopts 设置默认 pytest 运行参数
testpaths 限定测试目录
python_files 匹配测试文件
python_classes 匹配测试类
python_functions 匹配测试函数
filterwarnings 过滤警告
log_cli 终端日志输出
timeout 设置超时时间
markers 自定义标记
cache_dir 指定缓存目录

你可以根据自己的测试需求配置 pytest.ini,让 pytest 更加智能化!🚀

posted @ 2025-03-11 14:12  不带R的墨菲特  阅读(74)  评论(0)    收藏  举报