Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve the markers for py.test in conftest.py?

Tags:

python

pytest

I am running tests with py.test and want to access the markers I have set on the command line. I have tried the following code inside conftest.py (based on the documentation I found here) in a fixture that is used by every running test (i.e. a fixture that setup the test):

@pytest.fixture
def basedriver(request):
    ...
    node = request.node
    print("Marker: %s" % str(node.get_marker('set1')))
    ...

but when I invoke the test like follows:

py.test -s -m "set1 or ready"

I get the following output

Marker: None

I seem to do it wrong. How to do it right?

Ideally, I can retrieve the whole string, i.e. "set1 or ready"...

like image 220
Alex Avatar asked Oct 01 '18 06:10

Alex


People also ask

How do I run markers in pytest?

To use markers, we have to import pytest module in the test file. We can define our own marker names to the tests and run the tests having those marker names. -m <markername> represents the marker name of the tests to be executed. Update our test files test_compare.py and test_square.py with the following code.

What goes in Conftest py?

Folder Structure conftest.py is where you setup test configurations and store the testcases that are used by test functions. The configurations and the testcases are called fixture in pytest.

Where does Conftest py go?

You can put fixtures into individual test files, but to share fixtures among multiple test files, you need to use a conftest.py file somewhere centrally located for all of the tests. For the Tasks project, all of the fixtures will be in tasks_proj/tests/conftest.py. From there, the fixtures can be shared by any test.

Can you have multiple Conftest py?

You can have multiple nested directories/packages containing your tests, and each directory can have its own conftest.py with its own fixtures, adding on to the ones provided by the conftest.py files in parent directories.


1 Answers

request.node is the test function object, so request.node.get_closest_marker('set1') returns the marker attached to the test currently being executed, or None if a marker with the name cannot be found. For example, running a test

@pytest.fixture
def basedriver(request):
    node = request.node
    print('Marker:', node.get_closest_marker('set1'))

@pytest.mark.set1
def test_spam(basedriver):
    assert True

def test_eggs(basedriver):
    assert True

will print

test_spam.py::test_spam Marker: MarkInfo(_marks=[Mark(name='set1', args=(), kwargs={})])
PASSED
test_spam.py::test_eggs Marker: None
PASSED

What you want is the passed value of the command line argument -m. Access it via config fixture:

@pytest.fixture
def basedriver(pytestconfig):
    markers_arg = pytestconfig.getoption('-m')
    print('markers passed from command line:', markers_arg)
    ...
like image 197
hoefling Avatar answered Sep 18 '22 01:09

hoefling