diff --git a/src/_pytest/mark/__init__.py b/src/_pytest/mark/__init__.py index e21e234e774..d96f782971f 100644 --- a/src/_pytest/mark/__init__.py +++ b/src/_pytest/mark/__init__.py @@ -65,6 +65,14 @@ def pytest_addoption(parser): "example: -m 'mark1 and not mark2'.", ) + group.addoption( + "--mark-fixture", + action="store", + help=( + "Add mark to tests using given fixture. Format: fixture[:mark] ('mark' defaults to the fixture name)." + ), + ) + group.addoption( "--markers", action="store_true", @@ -139,6 +147,22 @@ def deselect_by_mark(items, config): def pytest_collection_modifyitems(items, config): + mark_fixture = config.getoption("--mark-fixture") + if mark_fixture: + fixture, _, mark = mark_fixture.partition(":") + if not mark: + mark = fixture + if mark not in MARK_GEN._markers: + MARK_GEN._markers.add(mark) + for item in items: + try: + fixturenames = item.fixturenames + except AttributeError: + # DoctestItem + continue + if fixture in fixturenames: + item.add_marker(mark) + deselect_by_keyword(items, config) deselect_by_mark(items, config) diff --git a/testing/test_mark.py b/testing/test_mark.py index 2c12c0451c0..1d6555bb194 100644 --- a/testing/test_mark.py +++ b/testing/test_mark.py @@ -940,6 +940,44 @@ class TestBarClass(BaseTests): # assert skipped_k == failed_k == 0 +def test_mark_fixture(testdir): + testdir.makeini( + """ + [pytest] + markers = + regged: registered + """ + ) + testdir.makepyfile( + """ + import pytest + + @pytest.fixture + def fix(): + pass + + def test_1(fix): + pass + + @pytest.mark.FOO + def test_2(): + pass + + @pytest.mark.regged + def test_3(): + pass + """ + ) + reprec = testdir.inline_run("--mark-fixture", "fix:mymark", "-m", "mymark") + assert reprec.countoutcomes() == [1, 0, 0] + reprec = testdir.inline_run("--mark-fixture", "fix:FOO", "-m", "FOO") + assert reprec.countoutcomes() == [2, 0, 0] + reprec = testdir.inline_run("--mark-fixture", "fix", "-m", "fix") + assert reprec.countoutcomes() == [1, 0, 0] + reprec = testdir.inline_run("--mark-fixture", "fix:regged", "-m", "regged or FOO") + assert reprec.countoutcomes() == [3, 0, 0] + + def test_addmarker_order(): node = Node("Test", config=mock.Mock(), session=mock.Mock(), nodeid="Test") node.add_marker("foo")