如何获取文件夹中所有 pytest 测试的 pythonic 列表?

How do I get a pythonic list of all the pytest tests in a folder?

类似 --collect 的东西,仅来自 python 而不是 cmd,即 returns 路径列表。我试图看看 pytest 是如何做到的,但我似乎找不到它。

谢谢!

所有收集的测试将存储为 session 的属性 items。 您可以通过

访问 session 对象
  1. 会话级别fixture
  2. pytest 插件,例如:pytest_runtestlooppytest_sessionstart

示例:

@pytest.fixture(scope='session', autouse=True)
def get_all_tests(request):
    items = request.session.items
    all_tests_names = [item.name for item in items]
    all_tests_locations = [item.location for item in items]
    # location is a tuple of (file_path, linenumber, Classname.methodname)

如果您想了解有关对象 sessionitem 的更多信息,您当然可以阅读文档或源代码,但我更喜欢使用 pdb.set_trace 来深入研究对象.