test_formatter.py
Overview
`test_formatter.py` is a test module designed to verify the correctness and behavior of logging formatters used within the pytest framework, specifically focusing on colored logging output and handling of multiline log messages. It tests the integration of `ColoredLevelFormatter` and `PercentStyleMultiline` classes from the [_pytest.logging](/projects/286/67290) module, ensuring proper formatting of log records under various conditions such as color markup availability, message width/precision formatting, multiline messages, and different `auto_indent` settings.
This file contains only test functions (no classes) and primarily uses Python's built-in [logging.LogRecord](/projects/286/67290) to simulate log entries, combined with pytest's `TerminalWriter` to mimic terminal output capabilities.
Detailed Explanations
Functions
test_coloredlogformatter() -> None
**Purpose:** Tests the basic functionality of `ColoredLevelFormatter` with color markup enabled and disabled. It verifies that log records are formatted correctly with color when markup is supported and without color when markup is absent.
**Parameters:** None
**Returns:** None
**Behavior:**
Creates a
LogRecordwith an INFO level and a test message.Sets up a
TerminalWriterwith markup enabled, formats the record, and asserts the output contains ANSI color codes for the INFO level.Repeats with markup disabled, asserting the output is plain text without color codes.
**Example Usage:** This is a test function; it would be run automatically by the test framework and not called directly.
test_coloredlogformatter_with_width_precision() -> None
**Purpose:** Tests `ColoredLevelFormatter` with a log format string that includes width and precision specifiers (e.g., `%(levelname)-8.8s`). This ensures that the formatter respects these formatting constraints while applying color.
**Parameters:** None
**Returns:** None
**Behavior:**
Similar setup to
test_coloredlogformatterbut uses a format string specifying level name width and precision.Checks that the output correctly truncates or pads the level name while preserving color codes when markup is enabled and plain formatting when disabled.
test_multiline_message() -> None
**Purpose:** Tests the `PercentStyleMultiline` formatter's handling of multiline log messages and the effect of the `auto_indent` option on the indentation of subsequent lines.
**Parameters:** None
**Returns:** None
**Behavior:**
Creates a
LogRecordwith a multiline message ("Test Message line1\nline2").Tests three modes of
PercentStyleMultilineinitialization withauto_indentset to True,False, andNone.Verifies how multiline messages are formatted, whether subsequent lines are indented to align with the message start or left as-is.
Modifies record.auto_indent dynamically with various values (boolean, string representations of booleans, integers, invalid strings, and unrelated types) to test fallback and coercion logic for indentation behavior.
Ensures that indentation behaves consistently with the documented coercion rules of
auto_indent.
test_colored_short_level() -> None
**Purpose:** Tests the behavior of `ColoredLevelFormatter` when formatting a very short level name (only the first character of the level name, e.g., `%(levelname).1s`). This is important to verify that color codes are applied correctly even when the level name is truncated.
**Parameters:** None
**Returns:** None
**Behavior:**
Creates a
LogRecordwith INFO level.Uses a format string that only outputs the first character of the level name.
Verifies that the single character is properly colored when markup is enabled.
Important Implementation Details and Algorithms
ColoredLevelFormatter: This formatter applies ANSI color codes to the level name part of a log message when the terminal supports markup (color). It uses the
TerminalWriterinstance'shasmarkupproperty to decide whether to add colors.PercentStyleMultiline: Extends Python's standard logging.Formatter with support for multiline messages. It optionally auto-indents subsequent lines in multiline log messages to align with the message start, controlled by the
auto_indentflag. The indentation width can be numeric or coerced from strings representing integers or booleans.Auto Indentation Behavior:
The tests verify that ifauto_indentis:LogRecord Simulation: Test functions create artificial logging.LogRecord instances mimicking real log entries. This approach isolates the tests from actual logging infrastructure, focusing solely on formatter behavior.
Interaction with Other Parts of the System
Imports from _pytest.logging: The file depends on pytest's internal logging formatters
ColoredLevelFormatterandPercentStyleMultiline. These are custom formatters extending Python's logging module to support enhanced logging output in pytest.TerminalWriter: From
_pytest._io, this class abstracts terminal output capabilities and is used here to simulate whether the terminal supports color markup (hasmarkupattribute).Logging Module: Uses Python's standard logging module to create
LogRecordobjects, representing log entries.Test Runner Integration: This file is intended to be run by pytest or a similar test framework to verify logging formatter correctness during pytest's own development and testing.
Visual Diagram
flowchart TD
A[Logging LogRecord] --> B[ColoredLevelFormatter]
A --> C[PercentStyleMultiline]
B --> D[TerminalWriter (hasmarkup)]
C --> E[auto_indent flag]
subgraph Tests
F[test_coloredlogformatter]
G[test_coloredlogformatter_with_width_precision]
H[test_multiline_message]
I[test_colored_short_level]
end
F --> B
G --> B
H --> C
I --> B
**Diagram Explanation:**
LogRecordinstances are inputs to the two main formatters under test:ColoredLevelFormatterandPercentStyleMultiline.ColoredLevelFormatterusesTerminalWriter'shasmarkupproperty to decide on color application.PercentStyleMultilineuses theauto_indentflag to control indentation of multiline messages.The test functions invoke these formatters with simulated records and terminal environments.
Summary
`test_formatter.py` is a focused test suite ensuring that pytest's custom logging formatters behave correctly in formatting colored and multiline log messages. It verifies formatting output under different terminal capabilities and message structures, helping maintain robust and user-friendly logging output in pytest's test runs.