Automate test execution with a custom pytest marker
Preconditions (3)
✅ Expected Result: Only tests marked with the 'slow' marker run and pass or fail as expected; other tests are skipped; test report shows correct test count
import pytest import subprocess import sys # test_sample.py content # Save this content in the same directory before running automation # # import pytest # # @pytest.mark.slow # def test_slow_example(): # assert True # # def test_fast_example(): # assert True def test_run_only_slow_marker(): # Run pytest with -m slow to run only tests marked as slow result = subprocess.run( [sys.executable, '-m', 'pytest', '-v', '-m', 'slow', 'test_sample.py'], capture_output=True, text=True ) output = result.stdout # Assert the command ran successfully assert result.returncode == 0, f"Pytest failed with output:\n{output}" # Check that the output contains the slow test name assert 'test_slow_example' in output, "Slow test did not run" # Check that the fast test did not run assert 'test_fast_example' not in output, "Fast test should not run when filtering by slow marker" # Check the test summary line for correct count # Example summary line: '1 passed in 0.03s' import re match = re.search(r'(\d+) passed', output) assert match is not None, "No tests passed" passed_count = int(match.group(1)) assert passed_count == 1, f"Expected 1 test to run, but {passed_count} ran"
This automation script runs pytest as a subprocess with the -m slow option to select only tests marked with the slow marker.
It captures the output and checks:
test_slow_example, confirming it ran.test_fast_example, confirming it was skipped.This approach uses subprocess to run pytest as a real user would, ensuring marker filtering works as expected.
Before running this automation, ensure test_sample.py exists with the given test functions and the slow marker is registered in pytest.ini to avoid warnings.
Now add data-driven testing with 3 different inputs to the slow test using pytest.mark.parametrize
slow?pytest -m slow?
import pytest
@pytest.mark.slow
def test_a():
assert True
def test_b():
assert True
@pytest.mark.slow
def test_c():
assert False
pytest -m slow doesimport pytest
@pytest.mark.slow()
def test_example():
assert True
database but exclude those also marked as slow. Which pytest command achieves this?Pass the test and this pattern moves unknown