By using the pytest.mark helper you can instantiate decorators that will set named metadata on test functions.
You can “mark” a test function with metadata like this:
import pytest
@pytest.mark.webtest
def test_send_http():
...
This will set the function attribute webtest to a MarkInfo instance. You can also specify parametrized metadata like this:
# content of test_mark.py
import pytest
@pytest.mark.webtest(firefox=30)
def test_receive():
pass
@pytest.mark.webtest("functional", firefox=30)
def test_run_and_look():
pass
and access it from other places like this:
test_receive.webtest.kwargs['firefox'] == 30
test_run_and_look.webtest.args[0] == "functional"
If you are programming with Python2.6 you may use pytest.mark decorators with classes to apply markers to all of its test methods:
# content of test_mark_classlevel.py
import pytest
@pytest.mark.webtest
class TestClass:
def test_startup(self):
pass
def test_startup_and_more(self):
pass
This is equivalent to directly applying the decorator to the two test functions.
To remain compatible with Python2.5 you can also set a pytestmark attribute on a TestClass like this:
import pytest
class TestClass:
pytestmark = pytest.mark.webtest
or if you need to use multiple markers you can use a list:
import pytest
class TestClass:
pytestmark = [pytest.mark.webtest, pytest.mark.slowtest]
You can also set a module level marker:
import pytest
pytestmark = pytest.mark.webtest
in which case it will be applied to all functions and methods defined in the module.
You can use the -k command line option to select tests:
$ py.test -k webtest # running with the above defined examples yields
=========================== test session starts ============================
platform darwin -- Python 2.7.1 -- pytest-2.1.3
collecting ... collected 4 items
test_mark.py ..
test_mark_classlevel.py ..
========================= 4 passed in 0.03 seconds =========================
And you can also run all tests except the ones that match the keyword:
$ py.test -k-webtest
=========================== test session starts ============================
platform darwin -- Python 2.7.1 -- pytest-2.1.3
collecting ... collected 4 items
===================== 4 tests deselected by '-webtest' =====================
======================= 4 deselected in 0.02 seconds =======================
Or to only select the class:
$ py.test -kTestClass
=========================== test session starts ============================
platform darwin -- Python 2.7.1 -- pytest-2.1.3
collecting ... collected 4 items
test_mark_classlevel.py ..
==================== 2 tests deselected by 'TestClass' =====================
================== 2 passed, 2 deselected in 0.02 seconds ==================