How can I access al the markers in a pytest fixture?

社会主义新天地 提交于 2021-01-07 04:34:25

问题


I'm using pytest and I want to tag my tests with markers which will specify to a fixture which page to load in my driver. This works easily with the behave context object, but I cannot find how to do it with pytest.

For this code for example

import pytest

@pytest.fixture
def text(request):
    if 'hello' in X:
        return 'found it!'
    return 'did not find it :('

@pytest.mark.hello
def test_hello(text):
    assert text == 'found it!'

what should X be so that I can pass this test? I tried request.node.own_markers, but that just gives me an empty list, even though I marked the test.


回答1:


There's either request.node.own_markers or request.node.iter_markers() which will give you access to the markers of the node

for example:

(Pdb) request.node.own_markers
[Mark(name='hello', args=(), kwargs={})]
(Pdb) request.node.iter_markers()
<generator object Node.iter_markers.<locals>.<genexpr> at 0x7f3a601a60a0>
(Pdb) p list(request.node.iter_markers())
[Mark(name='hello', args=(), kwargs={})]

these two will differ (for example) if markers are applied on a higher scope

there's some examples in the markers docs (none that use request but item is the same in those examples (which use pytest hooks instead))




回答2:


I found the answer by playing around. The fixture was marked 'scope=module' while my only the test function had the marker. It was therefore out of scope for the fixture, hence the empty list. When I made the fixture have default scope, the marker was found.



来源:https://stackoverflow.com/questions/59680959/how-can-i-access-al-the-markers-in-a-pytest-fixture

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!