You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调整pytest.ini配置解决单元测试重复执行问题?

解决pytest测试重复执行的问题

问题详情

我的pytest.ini配置如下:

[pytest]
testpaths = tests/database/* tests/*
addopts = -v --cov="merlot"  --cov="merlot/sql" --cov-report term-missing

测试目录结构:

tests ── test1.py
       ── test2.py
       └── subfolder ── test3.py
                     ── test4.py
                     ── test5.py

遇到的问题:

  • 若设置testpaths = tests/*,subfolder里的测试不会被执行
  • 当前配置会让database目录下的测试重复运行,执行结果示例:
tests/database/testDatabase.py::TestMerlotDB::testDbName PASSED                                                                                              [ 12%]
tests/database/testDatabase.py::TestMerlotDB::testResetIndex PASSED                                                                                          [ 25%]
tests/database/testDatabase.py::TestMerlotDB::testInsertRecord PASSED                                                                                        [ 37%]
tests/database/testDatabase.py::TestMerlotDB::testDbName PASSED                                                                                              [ 37%]
tests/database/testDatabase.py::TestMerlotDB::testResetIndex PASSED                                                                                          [ 37%]
tests/database/testDatabase.py::TestMerlotDB::testInsertRecord PASSED                                                                                        [ 37%]
tests/testMerlot.py::TestMerlotBrowser::testBrowser PASSED                                                                                                   [ 50%]
tests/testMerlot.py::TestMerlotBrowser::test_go_to_URL PASSED                                                                                                [ 62%]

需要修改pytest.ini,让所有单元测试只运行一次。

解决办法

问题根源是testpaths的配置冲突:tests/database/*会匹配该目录下的所有测试文件,而tests/*会匹配tests下的所有子目录(包括database),导致database里的测试被两次扫描执行。

你可以用下面两种方式修改:

方式1:直接指定根测试目录(推荐)

pytest默认会递归扫描指定目录下的所有测试文件,包括各级子目录,所以只需要把testpaths简化为:

[pytest]
testpaths = tests
addopts = -v --cov="merlot"  --cov="merlot/sql" --cov-report term-missing

这样既会执行tests根目录的test1.py、test2.py,也会递归执行subfolder和database里的所有测试,且不会重复。

方式2:精确指定需要扫描的目录(按需使用)

如果需要明确列出要扫描的子目录,避免重复指定,可调整为:

[pytest]
testpaths = tests/database tests/subfolder tests
addopts = -v --cov="merlot"  --cov="merlot/sql" --cov-report term-missing

不过这种方式不如方式1简洁,后续新增子目录还需要手动添加,所以优先推荐方式1。

内容的提问来源于stack exchange,提问作者Adam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 08:10:24