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


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

Behavior & Logic

  1. Check if the test item is a function
    The hook only applies to test functions (pytest.Function instances).

  2. Check if the test file is within the current directory
    Using item.fspath.relto(mydir), it determines if the test file is relative to the directory of this conftest.py. If not, the setup function returns immediately, doing nothing.

  3. Retrieve the test module object

    • Accesses the parent pytest node of type pytest.Module using item.getparent(pytest.Module).

    • Extracts the actual Python module object via .obj.

  4. Check for the presence of hello attribute in the module
    If the module has an attribute named hello, it prints it using:

    print(f"mod.hello {mod.hello!r}")
    

    where {mod.hello!r} uses the repr() format of the attribute.

Return Value

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


Interaction with the System


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.