The request
fixture is a powerful feature and can be used to perform not just the above but a whole set of useful Pytest operations.
The Request Fixture
The request
fixture provides information about the context of the test function that requests it.
It can be used to control and inspect the current test environment and conditions under which the test is run.
With request
, tests can dynamically select resources or configurations, apply conditional markers, or perform specific cleanup actions based on the test outcome or setup requirements.
Moreover, the request
fixture helps control test dependencies and their lifecycles, through methods such as getfixturevalue
and addfinalizer
.
request.config.getoption
Let’s say you want your tests to connect to a database and pass the dburl
at runtime.
You can access the argument using Pytest Addoption and request.config.getoption
to get the value of this command line argument.
# tests/conftest.py
def pytest_addoption(parser):
parser.addoption(
"--dburl", # For Postgres use "postgresql://user:password@localhost/dbname"
action="store",
default="sqlite:///./test_db.db", # Default uses SQLite in memory db
help="Database URL to use for tests.",
)
# tests/test_config_getoption.py
def test_get_db_url(request):
db_url = request.config.getoption("--dburl")
print(f"db_url: {db_url}")
assert db_url is not None
We can extend this to work with fixtures.
@pytest.fixture(scope="session")
def db_url(request):
"""Fixture to retrieve the database URL."""
return request.config.getoption("--dburl")
def test_get_db_url_fixture(db_url):
print(f"db_url: {db_url}")
assert db_url is not None
request.addfinalizer
The addfinalizer
method allows you to register cleanup functions that are executed after a test has been completed, regardless of whether the test passed or failed.
This is similar to the yield
operation that occurs at the end of fixture setup and teardown.
request.getfixturevalue
This method is especially useful when the decision to use a specific fixture is not straightforward and needs to be made based on conditions that are only known during the test execution.
Accessing Test Properties using request
You can also access the test properties using the request
fixture.
This is very useful when you want to access properties like
-
Test function name
-
Module name
-
Filepath
-
Class name
def test_show_request_properties(request):
print(f"Test Function Name: {request.node.name}")
print(f"Test Module Name: {request.node.module.__name__}")
print(f"Test File Path: {request.node.fspath}")
print(f"Test Directory: {request.node.fspath.dirname}")
print(f"Test File Name: {request.node.fspath.basename}")
print(f"Test Function: {request.node.originalname}")
print(f"Test Class: {request.node.cls}")
print(f"Test Function Scope: {request.scope}")
print(f"Test Function Keywords: {request.keywords}")