pastebin.py
Overview
The `pastebin.py` file provides functionality to submit failure or entire test session information from pytest runs to an external pastebin service (specifically [bpaste.net](https://bpa.st)). This integration aids developers and testers by automatically uploading verbose test output — such as failure tracebacks or full test session logs — to a web-accessible paste service, allowing easier sharing and debugging.
The file implements pytest plugin hooks and CLI options to enable users to select which information to send ("failed" tests only, or "all" terminal output). It captures test output during runs, creates pastes programmatically via HTTP POST requests, and reports URLs to users in the terminal summary.
Detailed Explanation of Classes, Functions, and Methods
Constants and Keys
pastebinfile_key:
AStashKeyused to store a temporary binary file in the pytest configuration stash that accumulates terminal output when the--pastebin=alloption is selected.
pytest_addoption(parser: Parser) -> None
**Purpose:** Adds the `--pastebin` command-line option to pytest.
**Parameters:**
parser(Parser): pytest’s argument parser object.
**Behavior:**
Defines a new CLI option
--pastebinwhich accepts either "failed" or"all"."failed" means only failed test info will be sent after the session.
"all"means the entire terminal output will be captured and sent.
**Usage Example:**
pytest --pastebin=failed
pytest --pastebin=all
pytest_configure(config: Config) -> None
**Purpose:** Pytest hook called after command-line options have been parsed and pytest initialized.
**Parameters:**
config(Config): pytest configuration object.
**Behavior:**
If
--pastebin=allis specified, it hooks into the terminal reporter's output stream to capture all terminal output into a temporary file (pastebinfile_keyin config stash).It does this by monkey-patching the terminal reporter's
writemethod to write simultaneously to the original output and the temporary file.
**Implementation Details:**
Uses
tempfile.TemporaryFile("w+b")to create a writable binary temporary file.The patched
writemethod encodes strings as UTF-8 bytes before writing.
pytest_unconfigure(config: Config) -> None
**Purpose:** Pytest hook called during cleanup/unloading of plugins.
**Parameters:**
config(Config): pytest configuration object.
**Behavior:**
If a pastebin file was created (
pastebinfile_keyexists inconfig.stash), reads its contents, closes and deletes the temporary file.Reverts the terminal reporter's patched
writemethod to its original state.Calls
create_new_paste()to upload the captured terminal log and prints the pastebin URL to the terminal.
create_new_paste(contents: str | bytes) -> str
**Purpose:** Uploads a given string or bytes content to the bpaste.net pastebin service and returns the resulting paste URL.
**Parameters:**
contents(str | bytes): The text content to paste.
**Returns:**
str: The URL of the created paste, or an error message if the upload failed.
**Implementation Details:**
Uses
urllib.request.urlopento POST data tohttps://bpa.st.The posted form data includes parameters:
code: the contents to paste,lexer:"text",expiry:"1week"(paste expires in 1 week).
Parses the HTML response to extract the paste ID via regex on the
href="/raw/(\w+)"pattern.If successful, returns a URL like
https://bpa.st/show/<paste_id>.Handles HTTP and OS errors gracefully, returning descriptive error messages.
**Usage Example:**
url = create_new_paste("This is a test paste")
print(f"Paste created at: {url}")
pytest_terminal_summary(terminalreporter: TerminalReporter) -> None
**Purpose:** Pytest hook to add additional summaries at the end of test runs in the terminal.
**Parameters:**
terminalreporter(TerminalReporter): The terminal reporter plugin instance.
**Behavior:**
Triggered only if
--pastebin=failedis specified.For each failed test, extracts the failure traceback and other info, formats it, creates a paste via
create_new_paste(), and prints the paste URL alongside the failure location in the terminal summary.
**Implementation Details:**
Uses
StringIOand pytest’screate_terminal_writerto capture the failure report output as a string.Attempts to extract the file location of failure to provide context next to the paste URL.
Important Implementation Details
Stashing terminal output in a temporary file:
For the"all"mode, the plugin captures all terminal output by monkey-patching the terminal reporter's internal writer_tw.writemethod to "tee" writes into a temporary file.Robust error handling in paste creation:
Network errors or unexpected responses from the pastebin service do not crash pytest; instead, informative error messages are returned and printed.Selective behavior based on CLI option:
The plugin only activates its capture and paste functionality if the user explicitly requests it via--pastebin.Integration with pytest hooks:
Uses multiple pytest hook implementations (pytest_addoption,pytest_configure,pytest_unconfigure,pytest_terminal_summary) to seamlessly integrate pastebin functionality into the test lifecycle.
Interaction with Other Parts of the System
pytest core and plugins:
The plugin hooks into pytest’s CLI argument parsing and test lifecycle hooks. It interacts primarily with theTerminalReporterplugin to access terminal output and test failure information._pytest.configandStashKey:
UsesStashKeyto safely store the temporary file handle in pytest's configuration stash, ensuring proper lifecycle management.External pastebin service (
bpa.staka bpaste.net):
Sends HTTP POST requests to create pastes and parses the response to extract URLs.
Visual Diagram: Class and Function Structure
flowchart TD
A[pytest_addoption(parser)]
B[pytest_configure(config)]
C[pytest_unconfigure(config)]
D[create_new_paste(contents)]
E[pytest_terminal_summary(terminalreporter)]
A -->|adds CLI option| B
B -->|patch terminal reporter write| C
C -->|send paste with terminal output| D
E -->|send paste for each failed test| D
Summary
This `pastebin.py` file implements a pytest plugin that improves the test debugging experience by automatically uploading test failure summaries or full session logs to an online pastebin service. It cleanly integrates with pytest’s plugin system and terminal output mechanisms, providing users with easy sharing of verbose test outputs via URLs printed at the end of test runs. The implementation balances simplicity with robustness, handling network errors gracefully and supporting two modes of operation controlled by a CLI option.
Example Usage
Run pytest with pastebin integration for failed tests only:
pytest --pastebin=failed
After test completion, URLs to pastes of failure details will be printed in the terminal.
Run pytest with full terminal output uploaded:
pytest --pastebin=all
The entire test session output is captured and uploaded, with a single URL printed at the end.