0
0
PyTesttesting~15 mins

Marker registration in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify pytest marker registration and usage
Preconditions (2)
Step 1: Create a test file test_sample.py
Step 2: Add a test function test_example marked with @pytest.mark.smoke
Step 3: Run pytest with the -m smoke option to select tests with the smoke marker
✅ Expected Result: Only the test_example function runs and passes without marker warnings
Automation Requirements - pytest
Assertions Needed:
Verify test_example runs when using -m smoke
Verify no warnings about unregistered markers appear
Best Practices:
Register custom markers in pytest.ini
Use @pytest.mark.<marker_name> decorator
Use pytest command line option -m to select tests by marker
Avoid hardcoding marker names in test code
Automated Solution
PyTest
import subprocess
import sys
import pytest

# pytest.ini content to register marker
pytest_ini_content = """
[pytest]
markers =
    smoke: mark a test as smoke test
"""

# Write pytest.ini file
with open('pytest.ini', 'w') as f:
    f.write(pytest_ini_content)

# test_sample.py content
test_code = '''
import pytest

@pytest.mark.smoke

def test_example():
    assert True
'''

with open('test_sample.py', 'w') as f:
    f.write(test_code)

# Run pytest with -m smoke
result = subprocess.run([sys.executable, '-m', 'pytest', '-m', 'smoke', '--tb=short', '-q'], capture_output=True, text=True)

# Check output for test run and no warnings
assert 'test_example' in result.stdout, 'test_example did not run'
assert 'WARNING' not in result.stdout, 'Found warnings about markers'
assert result.returncode == 0, f'Pytest failed with code {result.returncode}'

print('Test passed: marker registration and usage works correctly')

This script automates the verification of pytest marker registration.

First, it creates a pytest.ini file registering the smoke marker to avoid warnings.

Then it writes a test file test_sample.py with a test function marked with @pytest.mark.smoke.

It runs pytest with the -m smoke option to select only tests with the smoke marker.

Assertions check that the test ran, no warnings about markers appeared, and pytest exited successfully.

This approach ensures the marker is properly registered and used, following best practices.

Common Mistakes - 4 Pitfalls
Not registering custom markers in pytest.ini
Using marker names inconsistently or misspelling them
Hardcoding marker names in test code without registration
Running pytest without the -m option to select markers
Bonus Challenge

Now add data-driven testing with 3 different test functions each marked with different custom markers registered in pytest.ini

Show Hint