Verify access to test function name using pytest fixture request object
Preconditions (2)
✅ Expected Result: The test passes, confirming the fixture correctly accessed the test function name via the request object
import pytest @pytest.fixture def test_name_fixture(request): # Access the current test function name return request.node.name def test_example(test_name_fixture): # The fixture should return the name of this test function assert test_name_fixture == 'test_example', f"Expected 'test_example' but got {test_name_fixture}"
This code defines a fixture test_name_fixture that takes the special request object provided by pytest. The fixture uses request.node.name to get the name of the currently running test function.
The test function test_example uses this fixture and asserts that the returned name matches its own name. This confirms the fixture correctly accessed the test context.
Using the request object is a common way in pytest to get information about the test being run, which helps in writing dynamic or context-aware fixtures.
Now add data-driven testing with 3 different test function names using the fixture to verify each name dynamically
request object in pytest fixtures?request object in pytest is passed to fixtures to give them context about the current test being run.request object?request object has a node attribute representing the test item.request.node.name.test_example runs?
import pytest
@pytest.fixture
def show_test_name(request):
print(f"Running test: {request.node.name}")
def test_example(show_test_name):
assert True
show_test_name prints the current test function name using request.node.name.test_example, so request.node.name will be "test_example".request object:
@pytest.fixture
def check_marker(request):
marker = request.marker.get('slow')
if marker:
print("Slow test")
request.node.get_closest_marker('name'), not request.marker.request.node.get_closest_marker('slow') to get the marker.request object inside a fixture to dynamically use another fixture by name?request object.request.getfixturevalue('fixture_name').Pass the test and this pattern moves unknown