Back to Repositories

Testing JSON Serialization with Custom Type Handlers in Textualize/Rich

This test suite validates JSON data handling and serialization capabilities in Rich’s JSON module, focusing on custom data type conversions and formatting. The tests specifically examine the handling of datetime objects and default serialization behavior.

Test Coverage Overview

The test coverage focuses on Rich’s JSON serialization functionality, particularly the handling of non-standard Python objects.

Key areas tested include:
  • DateTime object serialization
  • Custom default serialization handlers
  • JSON string formatting and structure validation
  • Integration with Rich’s text rendering system

Implementation Analysis

The testing approach implements a focused unit test that verifies the JSON.from_data method’s ability to handle custom Python objects through default serialization functions. The test utilizes Python’s datetime module to validate complex object serialization, employing lambda functions for custom type conversion.

Technical Details

Testing tools and configuration:
  • Python’s built-in datetime module
  • Rich’s JSON class implementation
  • Custom lambda function for date serialization
  • String comparison for output validation
  • Assertion-based verification

Best Practices Demonstrated

The test demonstrates several quality testing practices including isolated test cases, clear input/output validation, and proper handling of complex data types. It shows effective use of custom serialization handlers and proper formatting verification, while maintaining simple and readable test structure.

textualize/rich

tests/test_json.py

            
from rich.json import JSON
import datetime


def test_print_json_data_with_default():
    date = datetime.date(2021, 1, 1)
    json = JSON.from_data({"date": date}, default=lambda d: d.isoformat())
    assert str(json.text) == '{
  "date": "2021-01-01"
}'