Defining a custom marker in pytest allows you to annotate your test functions with additional metadata that you can use to categorize, filter, or modify the behavior of your tests. Here's a breakdown of how you can define and use a custom marker such as patient_params in your pytest setup:
Example Breakdown
-
Defining a Custom Marker:
You will first define a marker using @pytest.mark. The marker can carry parameters, which you can use in your tests to pass data.
import pytest
@pytest.mark.patient_params("my_id1", "my_id2")
def test_my_function(patient_params):
# Here you can access patient_params from the fixture
assert patient_params == ("my_id1", "my_id2")
-
Creating a Fixture:
The fixture patient_params can be defined to extract values from the request object, specifically the parameters from the marker.
@pytest.fixture
def patient_params(request) -> tuple[str, str]:
# Get the `patient_params` from the markers
marker = request.node.get_closest_marker("patient_params")
if marker is not None:
return marker.args # This will return a tuple of the parameters
else:
return ("default_id1", "default_id2") # Or some default values
Here, request.node.get_closest_marker("patient_params") retrieves the closest marker for the running test. It will return None if the marker isn't found.
-
Registering Your Marker:
To avoid warnings from pytest about unknown markers, you should register your custom marker in your project's pyproject.toml (or pytest.ini, if you use that). You can do this under the [tool.pytest.ini_options] section:
[tool.pytest.ini_options]
markers = [
"patient_params: load patient id and run id which can be used to load further data"
]
This informs pytest about your custom marker, so it won't issue warnings for it.
Complete Example
Here’s a full example that combines all of the pieces:
# test_patient.py
import pytest
@pytest.mark.patient_params("id_123", "run_456")
def test_my_function(patient_params):
assert patient_params == ("id_123", "run_456") # Example assertion
@pytest.fixture
def patient_params(request) -> tuple[str, str]:
marker = request.node.get_closest_marker("patient_params")
if marker is not None:
return marker.args # Return the IDs from the marker
return ("default_id1", "default_id2") # Or some default values
And your pyproject.toml should have:
[tool.pytest.ini_options]
markers = [
"patient_params: load patient id and run id which can be used to load further data"
]
Usage:
You can run your tests with pytest normally, and the patient_params marker will facilitate the process of passing those identifiers to the fixture, allowing you to load or manipulate data based on those parameters.
Benefits of Custom Markers:
- Improved organization of your tests.
- Ability to run subsets of tests based on their markers.
- Enhanced readability and maintainability of your test suite.
You can run tests marked with patient_params using the -m flag in the command line:
pytest -m patient_params
This command will run only the tests that are decorated with the @pytest.mark.patient_params.
In Python, the use of / and * in function definitions serves to define the parameters' positional and keyword characteristics, helping to specify which parameters must be passed positionally and which can be passed either positionally or as keywords. Here's how they work:
Using / for Mandatory Positional Parameters
The / symbol is used to indicate that all parameters before it must be provided as positional arguments. They cannot be passed as keyword arguments.
def example(a, b, /):
print(a, b)
# Valid usage
example(1, 2) # Output: 1 2
# Invalid usage
example(a=1, b=2) # Raises TypeError
In this example, both a and b must be supplied as positional arguments. Attempting to supply them as keyword arguments results in an error.
Using * for Mandatory Keyword Parameters
The * symbol is used to indicate that all parameters following it must be provided as keyword arguments (i.e., they cannot be passed positionally).
def example(a, *, b):
print(a, b)
# Valid usage
example(1, b=2) # Output: 1 2
# Invalid usage
example(1, 2) # Raises TypeError since b must be specified as a keyword argument
In this case, a can be passed positionally, but b must be passed as a keyword argument.
Combining / and *
You can combine both / and * to create functions that have a mix of positional and keyword-only parameters.
def example(a, b, /, c, *, d):
print(a, b, c, d)
# Valid usage
example(1, 2, 3, d=4) # Output: 1 2 3 4
# Invalid usage
example(1, 2, 3, 4) # Raises TypeError since d must be a keyword argument
example(1, 2, c=3, d=4) # Valid usage
Summary
/: Enforces that all preceding parameters are positional-only.
*: Enforces that all following parameters are keyword-only.
Example Function Definitions
Here are some additional examples for clarity:
-
Positional Only Parameters:
def add(x, y, /):
return x + y
add(1, 2) # Valid
# add(x=1, y=2) # Invalid
-
Keyword Only Parameters:
def configure(setting, *, value=None):
pass
configure('color', value='blue') # Valid
# configure('color', 'blue') # Invalid
-
Combining Both:
def func(a, b, /, c, *, d):
return a, b, c, d
func(1, 2, 3, d=4) # Valid
# func(1, 2, 3, 4) # Invalid
Using these conventions allows for greater clarity and flexibility in your function definitions, helping you control how users of your functions provide arguments.