0
0
PyTesttesting~15 mins

Running tests by marker (-m) in PyTest - Build an Automation Script

Choose your learning style9 modes available
Run pytest tests filtered by marker
Preconditions (2)
Step 1: Open terminal or command prompt
Step 2: Navigate to the directory containing the test file
Step 3: Run pytest with the -m option to specify the marker 'smoke'
Step 4: Observe that only tests marked with @pytest.mark.smoke are executed
✅ Expected Result: Only tests with the 'smoke' marker run and pass or fail accordingly
Automation Requirements - pytest
Assertions Needed:
Verify that only tests with the specified marker run
Verify that tests without the marker do not run
Best Practices:
Use @pytest.mark.<marker_name> to mark tests
Use pytest command line option -m '<marker_name>' to filter tests
Keep test markers meaningful and documented
Automated Solution
PyTest
import pytest

@pytest.mark.smoke
 def test_smoke_1():
     assert 1 + 1 == 2

@pytest.mark.smoke
 def test_smoke_2():
     assert 'a' * 3 == 'aaa'

@pytest.mark.regression
 def test_regression_1():
     assert 5 > 2

@pytest.mark.regression
 def test_regression_2():
     assert len([1, 2, 3]) == 3

# To run only smoke tests, execute in terminal:
# pytest -m smoke

# Expected output: only test_smoke_1 and test_smoke_2 run

The code defines four test functions with two different markers: smoke and regression.

Using @pytest.mark.smoke marks tests as smoke tests, and @pytest.mark.regression marks others as regression tests.

Running pytest -m smoke in the terminal runs only the tests marked with smoke. This filters tests by marker, so tests without the marker are skipped.

This approach helps run specific groups of tests quickly, like smoke tests for basic checks.

Common Mistakes - 3 Pitfalls
{'mistake': 'Not marking tests with @pytest.mark before running with -m', 'why_bad': "The -m option filters by markers, so if tests are not marked, they won't be selected.", 'correct_approach': 'Always decorate tests with @pytest.mark.<marker_name> before using -m to filter.'}
Using incorrect marker name in the -m option
Hardcoding test names instead of using markers for filtering
Bonus Challenge

Add a new marker 'fast' and create two tests with it. Run tests filtered by 'fast' marker.

Show Hint