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"...
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.
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.
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.
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.
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)
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With