test_saferepr.py
Overview
The `test_saferepr.py` file contains a suite of automated tests designed to verify the correctness, robustness, and edge-case behaviors of the `saferepr` and `saferepr_unlimited` functions from the `_pytest._io.saferepr` module. These functions provide safe, truncated, and exception-handling string representations (`repr`) of Python objects, which are vital in testing frameworks such as `pytest` for displaying readable and failure-resilient representations of test data and exceptions.
The tests cover a wide range of scenarios, including:
Basic and large object representations with truncation.
Handling of objects whose
__repr__method raises exceptions.Special treatment of BaseException subclasses.
Simulations of buggy built-in type representations.
Unicode handling.
Classes with broken or raising
__getattribute__or__repr__.Functionality of the unlimited representation variant
saferepr_unlimited.
These tests ensure that `saferepr` behaves reliably even under unusual or error-prone conditions, which is critical for stable test output formatting in `pytest`.
Detailed Explanation of Functions and Tests
Imported Entities
DEFAULT_REPR_MAX_SIZE: Default maximum size for truncated representations.saferepr: The main safe representation function with optional truncation.saferepr_unlimited: Variant ofsafereprwithout size limitations.pytest: Testing framework used for exception assertion and test management.
Test Functions
Each function is prefixed with `test_` to be recognized by `pytest`.
test_simple_repr()
**Purpose:** Tests basic usage of `saferepr` with simple objects.
**Behavior:**
Ensures integer and
Noneare represented as"1"and"None"respectively.
**Example:**
assert saferepr(1) == "1"
assert saferepr(None) == "None"
test_maxsize()
**Purpose:** Tests behavior of `saferepr` truncation when `maxsize` is specified.
**Parameters:**
Uses a string of 50
"x"characters.Sets
maxsize=25.
**Behavior:**
Resulting string length equals
maxsize.Output matches truncated form with ellipsis in the middle, e.g.
'xxxxxxxxxx...xxxxxxxxxx'.
test_no_maxsize()
**Purpose:** Tests `saferepr` without truncation (`maxsize=None`).
**Behavior:**
A very long string (10x
DEFAULT_REPR_MAX_SIZE) is fully represented without truncation.Output matches
repr()of the string.
test_maxsize_error_on_instance()
**Purpose:** Verifies `saferepr` handles tuple containing an object whose `__repr__` raises an error, respecting truncation.
**Details:**
Defines class
Awith__repr__raisingValueError.Passes a tuple with a long string and an instance of
A.Checks output length is truncated and starts and ends with tuple parentheses.
test_exceptions()
**Purpose:** Extensive test of `saferepr` on objects whose `__repr__` or `__str__` methods raise exceptions.
**Classes:**
BrokenRepr: Raises a provided exception in__repr__.BrokenReprException: Exception subclass with broken__str__and__repr__.
**Behavior:**
Asserts that string "Exception" or "TypeError" appears in the representations.
Tests cascading exceptions inside
saferepr, ensuring fallback outputs show unpresentable exceptions.Verifies the output format includes object type and memory address.
test_baseexception()
**Purpose:** Tests `saferepr` on `BaseException` subclasses that raise exceptions during their `__str__` or `__repr__`.
**Classes:**
RaisingOnStrRepr: Raises exceptions when__str__or__repr__is called.BrokenObj: Raises an exception in__repr__and__str__.
**Behavior:**
Validates fallback messages for unpresentable exceptions.
Ensures
KeyboardInterruptandSystemExitexceptions propagate normally (not swallowed).Confirms
safereprhandles deeply nested exceptions gracefully.
test_buggy_builtin_repr()
**Purpose:** Simulates a built-in type (`int`) with a buggy `__repr__` that raises an exception.
**Behavior:**
Checks that the exception message is contained in the safe representation.
test_big_repr()
**Purpose:** Tests that the representation of large iterables (e.g., `range(1000)`) does not exceed expected length limits.
test_repr_on_newstyle()
**Purpose:** Validates `saferepr` on an object with a user-defined `__repr__` referencing an attribute that may not exist.
test_unicode()
**Purpose:** Tests `saferepr` on Unicode strings to verify correct quoting and encoding in output.
test_broken_getattribute()
**Purpose:** Tests `saferepr` on objects with broken `__getattribute__` and `__repr__` methods that raise exceptions.
**Behavior:**
Ensures that a fallback, informative string is produced containing the exception type and object address.
test_saferepr_unlimited()
**Purpose:** Tests `saferepr_unlimited` which produces full, non-truncated representations.
**Details:**
Tests on a small dictionary (5 items) and a large dictionary (1000 items).
Asserts no truncation markers ("...") or newlines are present in output.
test_saferepr_unlimited_exc()
**Purpose:** Tests `saferepr_unlimited` on an object whose `__repr__` raises an exception.
**Behavior:**
Output starts with a fallback message indicating the exception type and object address.
Important Implementation Details and Algorithms
These tests rely heavily on the behavior of
safereprto handle exceptions gracefully rather than letting them propagate, which is critical to avoid masking errors in test output.The truncation algorithm in
safereprreplaces the middle of long strings or sequences with ellipsis (...), preserving the start and end parts.For representations that fail due to exceptions,
safereprproduces a descriptive fallback string including the type of exception, the exception message (if available), and the object's memory address.Special care is taken to allow
KeyboardInterruptandSystemExitexceptions to propagate normally, as these should not be caught silently.The unlimited variant
saferepr_unlimitedomits size limits but retains exception safety.
Interaction with Other Parts of the System
This file tests functionality in the
_pytest._io.safereprmodule, a core part of thepytestIO subsystem responsible for safely rendering objects in test output.The tests indirectly ensure that
pytest's test reporting and assertion introspection can display object representations reliably.The
pytesttesting framework is used for running these tests and asserting expected behaviors and exception raising.The file does not modify or extend
safereprbut validates its correctness and resilience, supportingpytest's robustness goals.
Usage Examples
Below are simplified usage examples inspired by the tests:
from _pytest._io.saferepr import saferepr
# Basic usage
print(saferepr(123)) # Output: "123"
# Truncated representation
long_str = "x" * 50
print(saferepr(long_str, maxsize=25)) # Output: "'xxxxxxxxxx...xxxxxxxxxx'"
# Handling object with broken __repr__
class Broken:
def __repr__(self):
raise ValueError("error")
print(saferepr(Broken()))
# Output: "<[ValueError('error') raised in repr()] Broken object at 0x...>"
Mermaid Diagram: Flowchart of Main Test Functions and Their Relationships
flowchart TD
A[test_saferepr.py] --> B[test_simple_repr]
A --> C[test_maxsize]
A --> D[test_no_maxsize]
A --> E[test_maxsize_error_on_instance]
A --> F[test_exceptions]
A --> G[test_baseexception]
A --> H[test_buggy_builtin_repr]
A --> I[test_big_repr]
A --> J[test_repr_on_newstyle]
A --> K[test_unicode]
A --> L[test_broken_getattribute]
A --> M[test_saferepr_unlimited]
A --> N[test_saferepr_unlimited_exc]
style A fill:#f9f,stroke:#333,stroke-width:2px
style B,C,D,E,F,G,H,I,J,K,L,M,N fill:#bbf,stroke:#333,stroke-width:1px
Summary
`test_saferepr.py` is a critical test suite ensuring that the `saferepr` functions from pytest provide safe, readable, and robust string representations of Python objects, even in the presence of faulty or exception-raising `__repr__` methods. It covers truncation behavior, exception safety, and special cases for exception objects, supporting pytest’s goal of clear and stable test output display.