Pytest:获取所有测试的地址

Pytest: Getting addresses of all tests

当我 运行 pytest --collect-only 获取我的测试列表时,我得到它们的格式类似于 <Function: test_whatever>。但是,当我使用 pytest -k ... 到 运行 特定测试时,我需要以 foo::test_whatever 格式输入测试的 "address" 。是否有可能以 -k 采用的相同格式获取所有测试的所有地址列表?

用法与您指定的不符。从文档中: http://doc.pytest.org/en/latest/usage.html

pytest -k stringexpr  # only run tests with names that match the
                      # "string expression", e.g. "MyClass and not method"
                      # will select TestMyClass.test_something
                      # but not TestMyClass.test_method_simple

所以你需要传递给'-k'的是一个包含在你想要检查的所有可调用函数中的字符串(你可以在这些字符串之间使用逻辑运算符)。对于您的示例(假设所有 def 都以 foo:::

为前缀
pytest -k "foo::"

在 conftest.py 中,您可以覆盖 'collection' 挂钩以打印有关收集的测试的信息 'items'。

您可以引入自己的命令行选项(如--collect-only)。如果指定了此选项,则打印测试项目(以您喜欢的方式)并退出。

下面的示例 conftest.py(本地测试):

import pytest

def pytest_addoption(parser):
    parser.addoption("--my_test_dump", action="store", default=None,
        help="Print test items in my custom format")

def pytest_collection_finish(session):
    if session.config.option.my_test_dump is not None:
        for item in session.items:
            print('{}::{}'.format(item.fspath, item.name))
        pytest.exit('Done!')

有关 pytest 挂钩的更多信息,请参阅:

http://doc.pytest.org/en/latest/_modules/_pytest/hookspec.html

如果您使用 -k 开关,则无需指定以冒号分隔的完整路径。如果路径是唯一的,您可以只使用路径的一部分。仅当您不使用 -k 开关时才需要完整的测试路径。

例如

pytest -k "unique_part_of_path_name"

对于pytest tests/a/b/c.py::test_x,可以使用pytest -k "a and b and c and x"

您可以为 -k 开关使用布尔逻辑。

顺便说一句,pytest --collect-only 确实在文件测试名称上方的 <Module 行中给出了测试文件名。