Pytest:如何发现以不同前缀开头的文件名?

问题描述 投票:0回答:3

我正在使用 VS Code + Python 测试资源管理器扩展。

目前,仅自动发现命名约定为

test_<somefilename>.py
的测试文件。

是否有我可以更改的设置,以便它可以检查以不同前缀开头的文件,例如

moduletest_<somefilename>.py

我真的不想更改这些文件的文件名。

谢谢!

python visual-studio-code pytest filenames prefix
3个回答
2
投票

这是我的解决方案:

  1. 在根目录中创建

    pytest.ini
    ,测试位于
    root/tests
    中。在
    pytest.ini
    中,添加以下配置:

     [pytest]
     testpaths= tests
     python_files = moduletest_*.py
    
  2. 在Settings.json中,添加

    "python.testing.pytestArgs": [
        "-c",
        "pytest.ini"
     ],
     "python.testing.unittestEnabled": false,
     "python.testing.pytestEnabled": true,
    

然后打开测试资源管理器,应该检测到

moduletest_*.py
并显示在那里:


0
投票

自6.0版本起

pytest
支持
pyproject.toml
设置。为了使其发挥作用,请使用

# pyproject.toml
[tool.pytest.ini_options]
minversion = "6.0"
addopts = "-ra -q"
testpaths = [
    "tests",
    "integration",
]
python_files = [
    "moduletest_*.py",
    "*_moduletest.py",
    "test_*.py",
    "*_test.py",
]

请注意:

有人可能想知道为什么像其他工具一样使用

[tool.pytest.ini_options]
而不是
[tool.pytest]

原因是pytest团队打算在未来充分利用丰富的TOML数据格式进行配置,为此保留了

[tool.pytest]
表。目前,ini_options 表被用作现有 .ini 配置系统和未来配置格式之间的桥梁。


0
投票

您应该在

pytest.ini
中将 moduletest_*.py 设置为 python_files,如下所示。 *默认情况下,如果您没有根据
文档
:
test_*.py
 中设置 
*_test.py
,则会查找 
python_filespytest.ini

# "pytest.ini"

[pytest]
python_files = moduletest_*.py # Here
© www.soinside.com 2019 - 2024. All rights reserved.