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:

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:**

**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:**


3. test_code_from_function_with_class()

**Purpose:** Ensures that attempting to create a `Code` object from a class raises a `TypeError`.

**Details:**


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:**


6. test_code_source()

**Purpose:** Tests that the source code snippet of a function is retrieved correctly.

**Details:**


7. test_frame_getsourcelineno_myself()

**Purpose:** Validates that a `Frame` object correctly reports its source line and line number.

**Details:**


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:**


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:**


12. test_frame_getargs()

**Purpose:** Tests [Frame.getargs()](/projects/286/67391) to retrieve argument names and values from the current frame.

**Details:**


13. TestExceptionInfo (class)

Tests related to the `ExceptionInfo` class, which encapsulates exception information.


14. TestTracebackEntry (class)

Tests for the `TracebackEntry` class representing a single traceback frame.


15. TestReprFuncArgs (class)

Tests for the `ReprFuncArgs` class used for representing function arguments in tracebacks.


16. test_ExceptionChainRepr()

Tests the `ExceptionChainRepr` class for representing chained exceptions.


Important Implementation Details


Interaction with Other System Components


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.