Back to Repositories

Testing Rich Card Component Rendering in Textualize/rich

This test suite validates the card rendering functionality in Rich, focusing on consistent output generation and link ID handling. It ensures proper console rendering of Rich’s test card component while managing system-specific elements for reproducible testing.

Test Coverage Overview

The test suite provides comprehensive coverage of Rich’s card rendering capabilities.

Key areas tested include:
  • Card rendering consistency across different environments
  • Link ID normalization for reproducible tests
  • Console output validation against expected results
  • True color support and legacy Windows compatibility

Implementation Analysis

The testing approach employs a combination of output comparison and string manipulation techniques. The implementation uses a custom Console configuration with controlled width and color settings, alongside regex-based link ID normalization to ensure consistent test results across different environments.

Notable patterns include:
  • StringIO buffer for output capture
  • Regular expression-based output normalization
  • Fixture-based expected output comparison

Technical Details

Testing infrastructure includes:
  • Rich Console configuration with truecolor support
  • Custom link ID replacement function
  • StringIO for output capture
  • Regular expression pattern matching
  • Automated test card generation
  • Expected output comparison mechanism

Best Practices Demonstrated

The test implementation showcases several testing best practices for console-based applications.

Notable practices include:
  • Isolated test environment with controlled console parameters
  • Reproducible test output handling
  • System-independent verification
  • Clear separation of test utilities and assertions
  • Automated test data generation

textualize/rich

tests/test_card.py

            
import io
import re

from rich.__main__ import make_test_card
from rich.console import Console, RenderableType

from ._card_render import expected

re_link_ids = re.compile(r"id=[\d\.\-]*?;.*?\x1b")


def replace_link_ids(render: str) -> str:
    """Link IDs have a random ID and system path which is a problem for
    reproducible tests.

    """
    return re_link_ids.sub("id=0;foo\x1b", render)


def render(renderable: RenderableType) -> str:
    console = Console(
        width=100, file=io.StringIO(), color_system="truecolor", legacy_windows=False
    )
    console.print(renderable)
    output = replace_link_ids(console.file.getvalue())
    return output


def test_card_render():
    card = make_test_card()
    result = render(card)
    print(repr(result))
    assert result == expected


if __name__ == "__main__":
    card = make_test_card()
    with open("_card_render.py", "wt") as fh:
        card_render = render(card)
        print(card_render)
        fh.write(f"expected={card_render!r}")