conftest.py
Overview
The `conftest.py` file is a special configuration file used by the **pytest** testing framework. It provides hooks and fixtures that apply across multiple test modules within the same directory or subdirectories. This particular `conftest.py` customizes the test setup phase by implementing the `pytest_runtest_setup` hook.
Its main purpose is to modify or extend the behavior before each test function runs. Specifically, it checks whether the test function belongs to a module within the current directory and, if the module defines a `hello` attribute, it prints the representation of that attribute. This can be useful for debugging or for providing additional context during test execution.
Detailed Explanation
Global Variables
mydir:
mydir = os.path.dirname(__file__)Stores the directory path of the current
conftest.pyfile. Used later to determine if a test function resides within this directory.
Function: pytest_runtest_setup(item)
def pytest_runtest_setup(item):
if isinstance(item, pytest.Function):
if not item.fspath.relto(mydir):
return
mod = item.getparent(pytest.Module).obj
if hasattr(mod, "hello"):
print(f"mod.hello {mod.hello!r}")
Purpose
This function is a pytest hook that runs **before** each test function is executed. It is called with a single argument `item`, which represents the test function or test item about to be run.
Parameters
item(pytest.Item): The test item object representing the test function being set up.
Behavior & Logic
Check if the test item is a function
The hook only applies to test functions (pytest.Functioninstances).Check if the test file is within the current directory
Usingitem.fspath.relto(mydir), it determines if the test file is relative to the directory of thisconftest.py. If not, the setup function returns immediately, doing nothing.Retrieve the test module object
Accesses the parent pytest node of type
pytest.Moduleusingitem.getparent(pytest.Module).Extracts the actual Python module object via
.obj.
Check for the presence of
helloattribute in the module
If the module has an attribute namedhello, it prints it using:print(f"mod.hello {mod.hello!r}")where
{mod.hello!r}uses therepr()format of the attribute.
Return Value
None (side-effects only: prints output if conditions are met).
Usage Example
Suppose you have a test module `test_example.py` in the same directory as this `conftest.py`:
# test_example.py
hello = "world"
def test_sample():
assert True
When running pytest, before `test_sample` executes, the setup hook will print:
mod.hello 'world'
If the module does not define `hello`, or the test is outside this directory, no output is printed.
Implementation Details
Uses pytest's hook system to customize test setup behavior globally for the directory.
Leverages pytest's test item hierarchy (
item.getparent()) to access module-level information.Uses
os.path.dirname(__file__)anditem.fspath.relto()to determine test file location relative toconftest.py.Prints information conditionally to aid debugging or test context awareness.
Interaction with the System
This file is part of the test suite infrastructure and is automatically loaded by pytest when running tests in its directory subtree.
It influences test execution by injecting behavior before each test function runs.
It does not modify test outcomes but provides additional console output based on module attributes.
Works alongside test modules, potentially recognizing custom attributes (like
hello) defined there.No external dependencies other than pytest and standard Python libraries.
Mermaid Diagram: Flowchart of pytest_runtest_setup
flowchart TD
A[pytest_runtest_setup(item)] --> B{Is item a pytest.Function?}
B -- No --> Z[Return (do nothing)]
B -- Yes --> C{Is item's file within mydir?}
C -- No --> Z
C -- Yes --> D[Get module object via item.getparent(pytest.Module).obj]
D --> E{Does module have attribute "hello"?}
E -- No --> Z
E -- Yes --> F[Print repr of mod.hello]
F --> Z
Summary
The `conftest.py` file configures pytest to print the `hello` attribute of any test module located within the same directory as the configuration file, before running each test function. This is achieved through the `pytest_runtest_setup` hook, which inspects the test item and module attributes at runtime. This setup is useful for debugging or injecting dynamic information into test runs without modifying individual test files.