Mark Decorator
Explore how the pytest mark decorator helps you categorize and manage tests by applying markers. Understand built-in markers like skip, xfail, and parametrize, and learn how to combine and filter tests using these markers. Discover techniques to define custom markers and apply them to customize test execution and integration with fixtures. This lesson equips you with skills to organize tests effectively for cleaner, more adaptable test suites.
Introduction
Pytest marking is a feature that enables categorizing tests and applying specific behaviors or actions to them. It involves tagging tests with markers, which can then be utilized to select, filter, or customize how the tests are executed. Pytest provides several built-in markers, such as @pytest.mark.skip to skip a test and @pytest.mark.parametrize to parametrize a test function with multiple input values. Additionally, users can create their custom markers to cater to specific testing requirements.
Marks are applied to test functions or classes using the @pytest.mark.<MARKER_NAME> decorator. We can also apply multiple marks to the same test function by using multiple @pytest.mark decorators.
Common markers
Note: In this lesson, we list the most commonly used pytest markers and their arguments. You can visit the official pytest documentation to learn more about each marker.
Expected failure
This marker marks the test as an expected failure (x instead of F). Marking a test as xfail can be beneficial when we encounter a known issue or bug in our code that we are currently working on fixing. By marking the test as xfail, we indicate that the test is expected to fail until the underlying issue is resolved. This approach allows us to proceed with running and developing other tests without being obstructed by a failing test that we already know will fail until the underlying problem is fixed.
Given below are the arguments we can pass in the marker.
Arguments | Use | Default Value |
| A boolean expression that determines whether to mark the test as an expected failure. |
|
| An optional string explaining why the test is expected to fail. |
|
| An optional exception class that the test is expected to raise. |
|
Let’s look at the code example for this marker.