如何获取py.test会话的标记列表?



我在 Mac (Mojave( 上运行py.test4.3.1 和python3.7.6,我想在运行开始时获取"会话"的标记列表。

conftest.py我尝试使用以下功能:

@pytest.fixture(scope="session", autouse=True)
def collab_setup(request):
print([marker.name for marker in request.function.pytestmark])

但是,这会导致错误

E       AttributeError: function not available in session-scoped context

当我调用虚拟测试时,例如

py.test -s -m "mark1 and mark2" tests/tests_dummy.py

为我的测试会话只提供一次标记列表很重要,因为最后我想为测试套件中的所有测试设置一些东西。这就是为什么我不能在每个测试会话中多次调用此函数的原因。

这有可能实现吗?

request夹具是一个"功能"范围夹具,仅包含有关要执行的当前测试级别的信息。这不是我们想要的。

我们想要夹具pytestconfig。这是一个"会话"范围装置,其中包含调用py.test中使用的参数。在这里,您可以使用名为getoption的方法获取标记:

@pytest.fixture(scope="session", autouse=True)
def collab_setup(pytestconfig):
print(pytestconfig.getoption("-m"))

如果collab_setup是类范围的一部分,即

class TestExampleTest:
@pytest.fixture(scope="session", autouse=True)
def collab_setup(self, request):
pass

您可以在self中使用pytestmark来获取标记

def collab_setup(self, request):
marks = [mark.name for mark in self.pytestmark]

最新更新