test_code.py
Overview
`test_code.py` is a test suite designed to verify the functionality and behavior of various classes and functions from the `_pytest._code` module, which is part of the internal implementation of the `pytest` testing framework. This file primarily tests the handling of Python code objects, source code retrieval, frame inspection, exception information representation, traceback entries, and function argument representation.
The tests ensure that:
The
Codeabstraction correctly wraps Python code objects and provides source code access.Frame objects correctly expose source lines and arguments.
Exception and traceback representations behave as expected.
Unicode and encoding edge cases are properly handled.
Function argument representations do not raise errors with mixed encoding inputs.
This file is not part of the main application logic but is essential for maintaining the quality and correctness of the `_pytest._code` utilities, which are widely used for enhanced traceback rendering and introspection during test failures.
Classes and Functions
1. test_ne()
**Purpose:** Tests the equality and inequality comparisons of `Code` objects.
**Details:**
Creates two
Codeobjects from different compiled code snippets.Confirms that a
Codeobject equals itself.Confirms that two
Codeobjects wrapping different code are not equal.
**Usage:** Called by pytest automatically. No parameters or return values.
2. test_code_gives_back_name_for_not_existing_file()
**Purpose:** Verifies that a `Code` object correctly stores and returns the filename for a code object compiled with a non-existent file name.
**Details:**
Compiles code with a dummy filename.
Constructs a
Codeobject.Checks that the path matches the dummy name.
Confirms
fullsourceis None since the file does not exist.
3. test_code_from_function_with_class()
**Purpose:** Ensures that attempting to create a `Code` object from a class raises a `TypeError`.
**Details:**
Defines a class
A.Calls
Code.from_function(A), expecting aTypeError.
4. x()
**Purpose:** A simple function that raises `NotImplementedError`. Used as a target for source retrieval tests.
5. test_code_fullsource()
**Purpose:** Tests that the full source code of a function can be retrieved via [Code.from_function()](/projects/286/67337).
**Details:**
Obtains a
Codeobject from functionx.Verifies that the full source contains the function name.
6. test_code_source()
**Purpose:** Tests that the source code snippet of a function is retrieved correctly.
**Details:**
Gets
Codefrom functionx.Compares the stringified source to an expected value.
7. test_frame_getsourcelineno_myself()
**Purpose:** Validates that a `Frame` object correctly reports its source line and line number.
**Details:**
Defines a function returning its own frame.
Creates a
Framefrom that.Asserts the source line at the frame's line number matches the expected code.
8. test_getstatement_empty_fullsource()
**Purpose:** Tests that if a `Frame`'s code has no `fullsource`, its `statement` returns an empty [Source](/projects/286/67391) object.
**Details:**
Uses mocking to set
fullsourceto None.Checks that
statementis an empty source.
9. test_code_from_func()
**Purpose:** Checks that [Code.from_function()](/projects/286/67337) correctly sets line number and path for a given function.
10. test_unicode_handling()
**Purpose:** Ensures that exceptions with Unicode byte strings in their message can be raised and stringified without errors.
11. test_code_getargs()
**Purpose:** Tests [Code.getargs()](/projects/286/67391) method to correctly identify function argument names including positional, variable positional (`*args`), and variable keyword (`**kwargs`) arguments.
**Details:**
Defines multiple functions with different argument signatures.
Asserts
getargs(var=True)returns correct argument tuples.
12. test_frame_getargs()
**Purpose:** Tests [Frame.getargs()](/projects/286/67391) to retrieve argument names and values from the current frame.
**Details:**
Defines functions with various arguments.
Creates
Frameobjects from their calls.Verifies return values include argument names and passed values (including varargs and kwargs).
13. TestExceptionInfo (class)
Tests related to the `ExceptionInfo` class, which encapsulates exception information.
test_bad_getsource()
Ensures ExceptionInfo.getrepr() works even when the source retrieval is problematic.test_from_current_with_missing()
Confirms that calling ExceptionInfo.from_current() when no exception is active raisesAssertionError.
14. TestTracebackEntry (class)
Tests for the `TracebackEntry` class representing a single traceback frame.
test_getsource()
Checks that the source lines for a traceback entry are correct and contain expected code.test_tb_entry_str()
Tests the string representation of a traceback entry matches expected patterns.
15. TestReprFuncArgs (class)
Tests for the `ReprFuncArgs` class used for representing function arguments in tracebacks.
test_not_raise_exception_with_mixed_encoding(tw_mock)
Ensures that mixed Unicode and byte-string arguments do not cause exceptions during string representation.
16. test_ExceptionChainRepr()
Tests the `ExceptionChainRepr` class for representing chained exceptions.
Confirms that representations from two caught exceptions differ.
Checks that the representation objects are hashable and distinct.
Important Implementation Details
The file heavily relies on pytest fixtures and assertions to validate behavior.
It uses Python's introspection features (e.g.,
sys._getframe) to capture frames and extract source and argument information.Mocking is used to simulate edge cases, such as missing source code.
The tests validate both the internal data structures (
Code,Frame,ExceptionInfo) and their string representations which are critical for pytest's enhanced error reporting.Unicode handling is verified to ensure robustness across environments and source encodings.
Interaction with Other System Components
This test file interacts with the
_pytest._codemodule, which is integral to pytest's reporting and debugging features.The classes tested here are used by pytest to extract and display detailed error reports, including source code context and argument values.
By verifying these utilities, this file indirectly contributes to the reliability of pytest's feedback to users during test failures.
The tests also use
pytest's own exception capturing and assertion mechanisms to validate expected behaviors.The unittest.mock module is used for patching during tests.
Diagram: Class Structure and Key Methods Tested
classDiagram
class Code {
+from_function(func)
+getargs(var: bool)
+fullsource
+source()
+firstlineno
+path
+__eq__(other)
+__ne__(other)
}
class Frame {
+__init__(frame: FrameType)
+getargs(var: bool)
+statement
+code: Code
+lineno
}
class ExceptionInfo {
+from_current()
+getrepr()
+traceback
}
class TracebackEntry {
+getsource()
+__str__()
}
class ReprFuncArgs {
+__init__(args)
+toterminal(tw)
}
class ExceptionChainRepr {
<<hashable>>
}
Code <.. Frame : "used by"
ExceptionInfo "1" o-- "*" TracebackEntry : "has"
ExceptionInfo ..> ExceptionChainRepr : "returns"
ReprFuncArgs ..> ExceptionInfo : "used in repr"
Usage Examples
Example: Retrieving source code from a function
from _pytest._code import Code
def sample():
return 42
code_obj = Code.from_function(sample)
print(code_obj.fullsource)
Example: Getting frame arguments
import sys
from _pytest._code import Frame
def f(x, y):
frame = Frame(sys._getframe())
print(frame.getargs(var=True))
f(1, 2)
Summary
`test_code.py` is a comprehensive test suite that ensures the robustness of pytest's internal utilities for code and frame introspection, exception and traceback representation, and argument handling. These utilities form the backbone of pytest's enhanced error diagnostics, making this file critical for maintaining the quality of the testing framework itself.