Verify pytest marker registration and usage
Preconditions (2)
✅ Expected Result: Only the test_example function runs and passes without marker warnings
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.
Now add data-driven testing with 3 different test functions each marked with different custom markers registered in pytest.ini
pytest.ini?pytest.ini to inform pytest about custom markers.slow in pytest.ini?pytest.ini content and test code, what will be the result when running pytest -m slow?
[pytest] markers = slow: marks tests as slow
import pytest
@pytest.mark.slow
def test_example():
assert True
def test_fast():
assert True
-m slow option-m slow option runs only tests marked with @pytest.mark.slow.test_example is marked with @pytest.mark.slow, test_fast is not.database to your tests but pytest shows a warning: PytestUnknownMarkWarning. What is the most likely cause and how to fix it?pytest.ini.database marker under the [pytest] section in pytest.ini to register it and remove the warning.api but skip those marked as slow. Your pytest.ini contains:
[pytest]
markers =
api: marks API tests
slow: marks slow tests
Which command correctly runs only api tests excluding slow tests?-m option accepts boolean expressions combining markers using and, or, and not.api but not slow, so expression is api and not slow.Pass the test and this pattern moves unknown