setuponly.py
Overview
The [setuponly.py](/projects/286/67468) module is a plugin extension for the pytest testing framework that enhances control and visibility over test fixture setup and teardown phases. Its primary purpose is to:
Provide command-line options to only run fixture setup without executing actual tests.
Allow users to display detailed setup and teardown activity of fixtures during test runs.
This functionality is useful for debugging, understanding test fixture dependencies, or initializing complex test environments without running the test logic itself.
Detailed Explanation of Components
1. pytest_addoption(parser: Parser) -> None
**Purpose:** Adds two command-line options to pytest's CLI interface:
--setuponly/--setup-only: When enabled, pytest will only perform fixture setup phases and skip test execution.--setupshow/--setup-show: When enabled, pytest displays information about fixture setup and teardown during test runs.
**Parameters:**
parser(Parser): The pytest argument parser object used to add CLI options.
**Return:**
None
**Usage Example:**
pytest --setuponly
pytest --setupshow
2. pytest_fixture_setup(fixturedef: FixtureDef[object], request: SubRequest) -> Generator[None, object, object]
**Purpose:** This hook wraps around the fixture setup process. It allows:
Pausing the fixture setup to yield control.
After setup, if
--setupshowis active, it logs the fixture setup action including fixture parameters if any.
**Parameters:**
fixturedef(FixtureDef[object]): The fixture definition object containing metadata about the fixture.request(SubRequest): Provides context about the requesting test function or fixture, including runtime options.
**Return:**
A generator that yields control during fixture setup and resumes afterwards.
**Implementation Details:**
The function uses a
try-finallyto yield control during the fixture setup phase.After the fixture is set up, it conditionally displays the setup action.
If the fixture is parameterized, it attempts to determine and cache the current parameter value to display it in the setup output.
**Usage Context:** Invoked by pytest internally during fixture setup.
3. pytest_fixture_post_finalizer(fixturedef: FixtureDef[object], request: SubRequest) -> None
**Purpose:** Hook that runs immediately after a fixture’s finalizer (teardown) has executed. It:
Displays the teardown action if
--setupshowis enabled.Cleans up cached parameter information after teardown.
**Parameters:**
fixturedef(FixtureDef[object]): The fixture definition object.request(SubRequest): Context of the current test request.
**Return:**
None
4. _show_fixture_action(fixturedef: FixtureDef[object], config: Config, msg: str) -> None
**Purpose:** Internal utility function to output formatted messages about fixture setup or teardown actions to the terminal.
**Parameters:**
fixturedef(FixtureDef[object]): Fixture metadata.config(Config): Pytest configuration object, used to obtain terminal writer and capture manager.msg(str): Message prefix, either"SETUP"or"TEARDOWN".
**Return:**
None
**Implementation Details:**
Suspends pytest's global output capture to ensure messages are visible immediately.
Writes an indented message line to the terminal showing:
The action (SETUP or TEARDOWN)
Fixture scope as a single uppercase letter (e.g., 'S' for session)
Fixture name
Dependencies of the fixture (other fixtures it uses), if applicable
Parameter value, if the fixture is parameterized.
Resumes output capture after writing.
5. pytest_cmdline_main(config: Config) -> int | ExitCode | None
**Purpose:** Pytest hook executed early in the command line processing phase.
If
--setuponlyis provided, it automatically enables--setupshowto ensure fixture setup actions are displayed.Returns
Noneto allow normal pytest command line processing to continue.
**Parameters:**
config(Config): Pytest configuration object.
**Return:**
int | ExitCode | None: ReturnsNoneto continue normal execution.
Important Implementation Details and Algorithms
Generator Usage in Fixture Setup:
The use of a generator (yield) inpytest_fixture_setupenables wrapping the fixture setup phase, allowing code before and after the actual setup to run, facilitating the display of setup actions post-setup.Scope-Based Indentation:
The indentation of output messages in_show_fixture_actiondepends on the fixture scope (session, package, module, class, function). This provides a visual hierarchy in the terminal output, making it easier to understand fixture nesting.Parameter Representation:
The plugin attempts to represent fixture parameters in a readable form usingsaferepr, limiting size for clarity.Integration with Pytest Capture Manager:
The plugin suspends pytest’s output capturing during printing of setup/teardown to ensure messages are not swallowed or delayed.
Interaction with Other Parts of the System
Pytest Core:
Integrates deeply with pytest’s fixture management system via hooks (
pytest_fixture_setup,pytest_fixture_post_finalizer).Hooks into command-line option parsing (
pytest_addoption) and command line main execution (pytest_cmdline_main).
Capture Manager Plugin:
Uses the capture manager plugin to suspend/resume output capture during message printing.
Terminal Writer:
Uses pytest’s terminal writer to output to the console with formatting.
Fixture Definitions:
Interacts with
FixtureDefobjects to access fixture metadata such as scope, name, dependencies, and parameters.
Usage Example
Run pytest to **only set up fixtures and not execute tests**, showing setup and teardown information:
pytest --setuponly
Run pytest normally but show setup/teardown info:
pytest --setupshow
Mermaid Diagram: Flowchart of Main Functions and Their Relationships
flowchart TD
A[pytest_addoption(parser)] --> B[Register CLI options: --setuponly, --setupshow]
C[pytest_cmdline_main(config)] --> D{--setuponly?}
D -- Yes --> E[Enable --setupshow]
D -- No --> F[Continue normal execution]
G[pytest_fixture_setup(fixturedef, request)] --> H[Yield control to fixture setup]
H --> I{After setup completes}
I --> J[If --setupshow: call _show_fixture_action(SETUP)]
K[pytest_fixture_post_finalizer(fixturedef, request)] --> L{If --setupshow}
L --> M[_show_fixture_action(TEARDOWN) + cleanup cache]
subgraph Output Flow
J --> N[_show_fixture_action(fixturedef, config, msg)]
M --> N
end
N --> O[Suspend capture -> Write message -> Resume capture]
Summary
[setuponly.py](/projects/286/67468) is a specialized pytest plugin module that enhances fixture lifecycle visibility and control by adding options to only run fixture setup and display detailed setup/teardown actions. It hooks into pytest’s CLI, fixture setup, and teardown lifecycle events, using generators and terminal output manipulation to achieve its goals. This module is valuable for users needing fine-grained control and insight into their test fixture behavior without running the full test suite.