MichielP
MichielP

Reputation: 81

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

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.

Upvotes: 5

Views: 3275

Answers (2)

MichielP
MichielP

Reputation: 81

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.

Upvotes: 3

anthony sottile
anthony sottile

Reputation: 69914

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))

Upvotes: 5

Related Questions