0
0
PyTesttesting~15 mins

Registering markers in pytest.ini - Build an Automation Script

Choose your learning style9 modes available
Verify custom pytest markers are registered and used correctly
Preconditions (2)
Step 1: Open pytest.ini file
Step 2: Add a custom marker named 'slow' with description 'marks tests as slow'
Step 3: Create a test file test_sample.py
Step 4: Add two test functions: one marked with @pytest.mark.slow and one without any marker
Step 5: Run pytest with the option '-m slow' to run only tests marked as slow
✅ Expected Result: Only the test function marked with @pytest.mark.slow runs successfully, and pytest does not show any warnings about unregistered markers
Automation Requirements - pytest
Assertions Needed:
Verify that tests marked with 'slow' run when using '-m slow'
Verify no warnings about unregistered markers appear during test run
Best Practices:
Register custom markers in pytest.ini under [pytest] section
Use descriptive marker names and descriptions
Avoid hardcoding markers in test code without registration
Run pytest with '-m' option to filter tests by marker
Automated Solution
PyTest
[pytest]
markers =
    slow: marks tests as slow

# test_sample.py
import pytest

def test_fast():
    assert 1 + 1 == 2

@pytest.mark.slow
def test_slow():
    assert sum([1, 2, 3]) == 6

# Command to run in terminal:
# pytest -m slow

The pytest.ini file registers the custom marker slow under the [pytest] section. This prevents pytest from showing warnings about unregistered markers.

The test file test_sample.py contains two tests: test_fast without any marker and test_slow marked with @pytest.mark.slow.

Running pytest -m slow runs only the tests marked with slow. The assertion verifies the test logic is correct.

This setup ensures marker registration and usage are correct and warnings are avoided.

Common Mistakes - 3 Pitfalls
Not registering custom markers in pytest.ini
Using marker names inconsistently between pytest.ini and test code
{'mistake': "Running pytest without the '-m' option to filter by marker", 'why_bad': 'All tests run, so marker filtering is not tested or used', 'correct_approach': "Use 'pytest -m <marker>' to run only tests with that marker"}
Bonus Challenge

Add two more custom markers 'fast' and 'database' in pytest.ini and create tests using them. Run tests filtered by each marker.

Show Hint