### Docker CI/CD Setup Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/usage-examples.md Create a Dockerfile to build an image for running Django tests. Installs dependencies and sets environment variables. ```dockerfile # Dockerfile FROM python:3.12 WORKDIR /app COPY . . RUN pip install -e . ENV COLUMNS=120 CMD ["python", "manage.py", "test"] ``` -------------------------------- ### GitLab CI/CD Setup Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/usage-examples.md Set up GitLab CI for testing Python applications using a specified Docker image. Install dependencies and run tests. ```yaml # .gitlab-ci.yml test: image: python:3.12 script: - pip install -e . - COLUMNS=120 python manage.py test ``` -------------------------------- ### GitHub Actions CI/CD Setup Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/usage-examples.md Configure GitHub Actions to run tests on push and pull requests. Ensure Python is set up and dependencies are installed. ```yaml # .github/workflows/tests.yml name: Tests on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-python@v4 with: python-version: "3.12" - run: pip install -e . - run: COLUMNS=120 python manage.py test ``` -------------------------------- ### Install django-rich Source: https://github.com/adamchainz/django-rich/blob/main/README.rst Install the django-rich package using pip. This is the first step to enable its features. ```sh python -m pip install django-rich ``` -------------------------------- ### RichCommand make_rich_console() Customization Example Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-richcommand.md This example demonstrates how to override make_rich_console to customize the Rich Console, disabling markup and highlighting. ```python from django_rich.management import RichCommand from rich.console import Console class Command(RichCommand): def make_rich_console(self, **kwargs): # Disable markup and highlighting return super().make_rich_console( **kwargs, markup=False, highlight=False ) def handle(self, *args, **options): # [bold red]Text[/bold red] will print literally without formatting self.console.print("[bold red]Alert![/bold red]") ``` -------------------------------- ### Start Django Shell Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-shell-command.md Launches the Django interactive shell. This is the entry point for using the `inspect` and `pprint` functions. ```bash $ python manage.py shell ``` -------------------------------- ### Launch Django Shells Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/quick-start.md Commands to launch the default Python shell, or IPython/bpython if installed. Pretty-printing is enabled by default. ```bash # Python shell (default) python manage.py shell ``` ```bash # IPython (if installed) python manage.py shell -i ipython ``` ```bash # bpython (if installed) python manage.py shell -i bpython ``` -------------------------------- ### RichCommand execute() Example Usage Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-richcommand.md This example shows how the RichCommand.execute() method is invoked by Django. ```python # This is called by Django automatically: # python manage.py mycommand --force-color ``` -------------------------------- ### Rich Traceback Example Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-richrunner.md Example of a Rich traceback showing source code context, local variables, and frame information upon test failure. ```text Traceback (most recent call last): File "/path/to/test.py", line 42, in test_something self.assertEqual(result, expected) ─ locals ─ result = {'status': 'error'} expected = {'status': 'success'} ``` -------------------------------- ### Django Rich Test Runner Examples Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/quick-start.md Demonstrates various command-line options for running Django tests with the Rich test runner, including verbose output, slowest tests, and SQL debugging. ```bash # Normal mode (dots for tests) python manage.py test ``` ```bash # Verbose (show test names) python manage.py test -v 2 ``` ```bash # Show slowest tests python manage.py test --durations 10 ``` ```bash # Debug SQL on failure python manage.py test --debug-sql ``` -------------------------------- ### Running Django Tests with RichRunner Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-richrunner.md Examples of how to invoke the Django test command with RichRunner, including options for debug SQL output and PDB debugging. ```bash python manage.py test python manage.py test --debug-sql python manage.py test --pdb ``` -------------------------------- ### Rich Test Durations Output Example Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-internal-classes.md Shows an example of the Rich Table output generated by _printDurations, displaying the slowest test durations and their corresponding test names. ```text Slowest test durations ┏━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ Duration ┃ Test ┃ ┡━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩ │ 2.345s │ tests.test_views.IndexViewTests.test_get │ │ 1.234s │ tests.test_models.ItemTests.test_create │ │ 0.567s │ tests.test_models.ItemTests.test_update │ └──────────┴───────────────────────────────────────────────┘ ``` -------------------------------- ### Command with Table Output Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/usage-examples.md Generate a formatted table of users using `rich.table.Table`. This example includes argument parsing for limiting results and displays user ID, username, email, and active status. ```python # myapp/management/commands/list_users.py from django_rich.management import RichCommand from rich.table import Table from django.contrib.auth.models import User class Command(RichCommand): def add_arguments(self, parser): parser.add_argument( '--limit', type=int, default=10, help='Number of users to display' ) def handle(self, *args, **options): limit = options['limit'] users = User.objects.all()[:limit] table = Table(title=f"Users (showing {len(users)})") table.add_column("ID", style="cyan") table.add_column("Username", style="magenta") table.add_column("Email", style="green") table.add_column("Active", style="yellow") for user in users: status = "✓" if user.is_active else "✗" table.add_row( str(user.id), user.username, user.email, status ) self.console.print(table) ``` ```bash python manage.py list_users --limit 20 ``` -------------------------------- ### Example: Using RichCommand in a Django Management Command Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-richcommand.md Demonstrates how to create a custom Django management command that inherits from RichCommand. The 'self.console' attribute is automatically available for use. ```python from django_rich.management import RichCommand class Command(RichCommand): def handle(self, *args, **options): # self.console is automatically available self.console.print("[bold blue]Processing...[/bold blue]") ``` -------------------------------- ### Instantiate RichTextTestResult Manually Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-internal-classes.md Example of manually creating a RichTextTestResult instance for testing purposes. This is typically handled by RichTestRunner. ```python # Normally created automatically by RichTestRunner, # but can be instantiated manually for testing: from unittest import _WritelnDecorator from io import StringIO from django_rich.test import RichTextTestResult stream_wrapper = _WritelnDecorator(StringIO()) result = RichTextTestResult(stream_wrapper, descriptions=True, verbosity=2) ``` -------------------------------- ### RichCommand Constructor Signature Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-richcommand.md Shows the signature for the RichCommand constructor. It accepts parameters similar to Django's BaseCommand and handles Rich Console setup. ```python def __init__( self, stdout: TextIO | None = None, stderr: TextIO | None = None, no_color: bool = False, force_color: bool = False, ) ``` -------------------------------- ### Example output of auto-imported Rich functions Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-shell-command.md On Django 5.2+, the following Rich functions are automatically available in the shell environment without explicit import. ```python >>> # The following are available without explicit import: >>> inspect >>> pprint >>> print_json > ``` -------------------------------- ### Use shell enhancement Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/README.md Start the Django shell with 'python manage.py shell' to leverage enhanced features like auto-imported inspect and pprint for inspecting model instances. ```bash python manage.py shell >>> from django.contrib.auth.models import User >>> inspect(User) # Auto-imported >>> pprint(list(User.objects.all()[:3])) # Auto-imported ``` -------------------------------- ### Create a Rich Management Command Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/README.md Extend RichCommand to create custom Django management commands with Rich output capabilities. This example shows how to print a colored message. ```python from django_rich.management import RichCommand class Command(RichCommand): def handle(self, *args, **options): self.console.print("[bold blue]Hello![/bold blue]") ``` -------------------------------- ### Use enhanced Django shell Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/quick-start.md Start the enhanced Django shell with 'python manage.py shell'. Rich utilities like inspect, pprint, and colored printing are automatically available. ```python >>> from django.contrib.auth.models import User >>> inspect(User) # Shows object details >>> pprint(list(User.objects.all()[:3])) # Pretty-prints data >>> print("[bold green]Success![/bold green]") # Colored output ``` -------------------------------- ### Custom RichCommand with Status and Logging Source: https://github.com/adamchainz/django-rich/blob/main/README.rst Example of a custom Django management command using RichCommand. It demonstrates the use of Rich's status display and logging capabilities within a command. ```python from time import sleep from django_rich.management import RichCommand class Command(RichCommand): def handle(self, *args, **options): self.console.print("[bold blue]Frobnicating widgets:[/bold blue]") with self.console.status("Starting...") as status: for i in range(1, 11): status.update(f"Widget {i}...") sleep(1) self.console.log(f"Widget {i} frobnicated.") ``` -------------------------------- ### Use Rich Console Methods in Django Management Commands Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/quick-start.md Example of using various Rich Console methods like print with markup, logging, status indicators, progress bars, tables, and rules within a custom Django management command. ```python from django_rich.management import RichCommand class Command(RichCommand): def handle(self, *args, **options): # Print with markup self.console.print("[bold red]Error[/bold red]") # Log with timestamps self.console.log("Something important") # Status indicators with self.console.status("Loading...") as status: status.update("Processing...") # Progress bars from rich.progress import track for item in track(items, description="Working..."): pass # Tables from rich.table import Table table = Table(title="Results") table.add_column("Name") table.add_column("Value") table.add_row("Item", "123") self.console.print(table) # Rules and separators from rich.rule import Rule self.console.print(Rule("Section Title")) ``` -------------------------------- ### Customizing RichConsole in RichCommand Source: https://github.com/adamchainz/django-rich/blob/main/README.rst Example of overriding the make_rich_console method in a custom RichCommand to disable Rich's default markup and highlighting. This allows for more control over console output. ```python from functools import partial from django_rich.management import RichCommand from rich.console import Console class Command(RichCommand): def make_rich_console(self, **kwargs): return super().make_rich_console(**kwargs, markup=False, highlight=False) def handle(self, *args, **options): ... ``` -------------------------------- ### Set up django-rich Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/README.md Add 'django_rich' to INSTALLED_APPS and set TEST_RUNNER in your settings.py file. ```python # settings.py INSTALLED_APPS = [..., "django_rich"] TEST_RUNNER = "django_rich.test.RichRunner" ``` -------------------------------- ### RichCommand _setup_console() Method Signature Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-richcommand.md This is the internal method signature for RichCommand._setup_console(). It configures the console based on color flags. ```python def _setup_console( self, stdout: TextIO | None, no_color: bool | None, force_color: bool | None, ) -> None: """Internal method that configures the console based on color flags. Called during initialization and again in `execute()` to respect runtime flag changes.""" pass ``` -------------------------------- ### RichCommand Constructor Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-richcommand.md Initializes a RichCommand instance. It accepts parameters similar to Django's BaseCommand and automatically sets up a Rich Console instance. ```APIDOC ## RichCommand.__init__() ### Description Initializes a RichCommand instance. Accepts the same parameters as Django's `BaseCommand` and automatically sets up a Rich Console instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **stdout** (TextIO | None) - Optional - Output stream for command output. Defaults to sys.stdout. - **stderr** (TextIO | None) - Optional - Stream for error output. Defaults to sys.stderr. - **no_color** (bool) - Optional - Disable color output. Defaults to False. - **force_color** (bool) - Optional - Force color output even on non-TTY terminals. Defaults to False. ### Request Example ```python from django_rich.management import RichCommand class Command(RichCommand): def handle(self, *args, **options): # self.console is automatically available self.console.print("[bold blue]Processing...[/bold blue]") ``` ### Response #### Success Response (200) None #### Response Example None ### Notes This signature is fully compatible with Django's `BaseCommand.__init__()` to maintain drop-in compatibility. ``` -------------------------------- ### RichCommand Class Definition Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-richcommand.md Defines the RichCommand class, a subclass of Django's BaseCommand. It includes methods for initialization, execution, and console setup. ```python class RichCommand(BaseCommand): def __init__( self, stdout: TextIO | None = None, stderr: TextIO | None = None, no_color: bool = False, force_color: bool = False, ) def execute( self, *args: Any, **options: Any, ) -> str | None def _setup_console( self, stdout: TextIO | None, no_color: bool | None, force_color: bool | None, ) -> None def make_rich_console( self, **kwargs: Any, ) -> Console ``` -------------------------------- ### startTest() Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-internal-classes.md Called when a test begins. Sets the `_newline` flag appropriately for Python 3.10 compatibility. ```APIDOC ## startTest() ### Description Called when a test begins. Sets the `_newline` flag appropriately for Python 3.10 compatibility. ### Parameters #### Path Parameters - `test` (TestCase) - Required - The test case that is starting ``` -------------------------------- ### Override get_resultclass for Test Runners Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/module-overview.md Subclass `RichRunner` and override `get_resultclass` to customize the result class used by the test runner. This example simply calls the superclass method. ```python class MyTestRunner(RichRunner): def get_resultclass(self): return super().get_resultclass() ``` -------------------------------- ### Using RichCommand Features Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-richcommand.md Demonstrates the use of multiple Rich Console features within a Django management command, including print with markup, status updates, and logging. ```python from time import sleep from django_rich.management import RichCommand class Command(RichCommand): def handle(self, *args, **options): self.console.print("[bold blue]Frobnicating widgets:[/bold blue]") with self.console.status("Starting...") as status: for i in range(1, 11): status.update(f"Widget {i}...") sleep(0.1) self.console.log(f"Widget {i} frobnicated.") ``` -------------------------------- ### Basic Command with Rich Output Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/usage-examples.md Implement a simple Django management command using RichCommand to display colored text output. ```python # myapp/management/commands/greet.py from django_rich.management import RichCommand class Command(RichCommand): def handle(self, *args, **options): self.console.print("[bold blue]Hello, World![/bold blue]") ``` ```bash python manage.py greet ``` -------------------------------- ### Import RichCommand Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/module-overview.md Import the base RichCommand class for creating custom management commands. ```python from django_rich.management import RichCommand ``` -------------------------------- ### Create a command with Rich output Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/README.md Inherit from RichCommand to create management commands that utilize Rich for colored output. ```python from django_rich.management import RichCommand class Command(RichCommand): def handle(self, *args, **options): self.console.print("[bold]Task:[/bold] Processing") ``` -------------------------------- ### Subclassing RichTextTestResult for Custom Success Handling Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-internal-classes.md Example of subclassing `RichTextTestResult` to add custom logic to the `addSuccess` method. This allows for extended success reporting beyond the default behavior. ```python from django_rich.test import RichTextTestResult class CustomResultClass(RichTextTestResult): def addSuccess(self, test): # Custom success handling super().addSuccess(test) # Do something additional ``` -------------------------------- ### Using Rich Console in a Command Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-richcommand.md Demonstrates how to access and use the Rich Console instance within a custom Django management command for enhanced output formatting and logging. ```python from django_rich.management import RichCommand class Command(RichCommand): def handle(self, *args, **options): # Use all Rich console features self.console.print("[bold green]Success![/bold green]") self.console.log("Important information") with self.console.status("Loading...") as status: # Do work status.update("Processing...") # More work ``` -------------------------------- ### Run Django Tests with Rich Output Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-richrunner.md Execute Django tests using the manage.py command. Various options control verbosity, debugging, and output formatting. ```bash # Normal execution with Rich output python manage.py test ``` ```bash # Verbose output with test names python manage.py test -v 2 ``` ```bash # Quiet mode with just the summary python manage.py test -v 0 ``` ```bash # Debug SQL queries on failures python manage.py test --debug-sql ``` ```bash # Drop into PDB debugger on failures python manage.py test --pdb ``` ```bash # Show slowest tests (Python 3.12+, Django 5.0+) python manage.py test --durations 10 ``` ```bash # Custom terminal width for CI COLUMNS=120 python manage.py test ``` -------------------------------- ### Activating Slowest Test Durations Output Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-internal-classes.md Demonstrates command-line usage for displaying test durations. Use --durations with a number to show top N slowest tests, or 0 for all. Verbose mode (-v 2) shows all durations, including very fast ones. ```bash # Show top 10 slowest tests python manage.py test --durations 10 # Show all durations python manage.py test --durations 0 # Verbose mode shows durations < 0.001s python manage.py test --durations 10 -v 2 ``` -------------------------------- ### Custom Test Runner Subclass for RichRunner Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/usage-examples.md Extend the RichRunner class to implement custom test environment setup or result class handling. The settings.py file must be updated to point to the custom runner. ```python # tests/test_runner.py from django_rich.test import RichRunner class CustomTestRunner(RichRunner): def setup_test_environment(self): super().setup_test_environment() # Custom setup here def get_resultclass(self): # Use custom result classes if needed return super().get_resultclass() # settings.py TEST_RUNNER = "tests.test_runner.CustomTestRunner" ``` -------------------------------- ### _exc_info_to_string() Method Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-richrunner.md Converts exception information to a formatted string using Rich Traceback rendering. Features include local variables, filtered frames, and syntax highlighting. ```python def _exc_info_to_string( self, err: _SysExcInfoType, test: TestCase, ) -> str: ``` -------------------------------- ### Run Rich Management Command Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/quick-start.md Execute custom Rich management commands using 'python manage.py '. Options like --force-color and --no-color can control output. ```bash python manage.py mycommand python manage.py mycommand --force-color # Force color on non-TTY python manage.py mycommand --no-color # Disable color ``` -------------------------------- ### Enable Django Rich in Settings Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/README.md Add 'django_rich' to INSTALLED_APPS to enable shell enhancements. Set TEST_RUNNER to 'django_rich.test.RichRunner' to use the Rich test runner. ```python INSTALLED_APPS = ["django_rich"] # Enable shell TEST_RUNNER = "django_rich.test.RichRunner" # Use test runner ``` -------------------------------- ### Pretty-Printed Dictionary Output Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-shell-command.md Demonstrates the difference in output formatting for a dictionary between the standard Python REPL and Rich's pretty-printer. ```python # Before (standard Python REPL): >>> {'name': 'Alice', 'age': 30, 'scores': [95, 87, 92]} {'name': 'Alice', 'age': 30, 'scores': [95, 87, 92]} ``` ```python # After (with Rich pretty-printing): >>> {'name': 'Alice', 'age': 30, 'scores': [95, 87, 92]} { 'name': 'Alice', 'age': 30, 'scores': [95, 87, 92] } ``` -------------------------------- ### Create a Rich Management Command Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/quick-start.md Extend RichCommand to create custom Django management commands with colored output and markup support. Use self.console for Rich functionalities. ```python # myapp/management/commands/mycommand.py from django_rich.management import RichCommand class Command(RichCommand): def handle(self, *args, **options): # self.console is a Rich Console instance self.console.print("[bold blue]Processing...[/bold blue]") with self.console.status("Working...") as status: for i in range(10): status.update(f"Item {i+1}/10") # Do work here self.console.print("[bold green]Complete![/bold green]") ``` -------------------------------- ### Launch Django shell with Rich pretty-printing Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-shell-command.md Use the manage.py shell command to launch the Python REPL with Rich pretty-printing enabled. This command respects Django's shell configuration and can utilize Python, IPython, or bpython interpreters. ```bash # Launch the standard Python shell with Rich pretty-printing python manage.py shell ``` ```bash # Use IPython with Rich pretty-printing python manage.py shell -i ipython ``` ```bash # Use bpython with Rich pretty-printing python manage.py shell -i bpython ``` -------------------------------- ### Running Django Tests with Rich Formatting Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/usage-examples.md Execute Django tests using the command line. RichRunner provides colored output by default. Use -v 2 for verbose output showing test names, or -v 0 for quiet mode. ```bash # Colored output with rich formatting python manage.py test tests.test_models ``` ```bash # Verbose output showing test names python manage.py test tests.test_models -v 2 ``` ```bash # Quiet mode python manage.py test tests.test_models -v 0 ``` -------------------------------- ### Command with Progress Tracking Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/usage-examples.md Use RichCommand with `rich.progress.track` to display a progress bar during item processing. Ensure your models have a `process` method and `save` functionality. ```python # myapp/management/commands/process_items.py from django_rich.management import RichCommand from rich.progress import track from myapp.models import Item class Command(RichCommand): def handle(self, *args, **options): items = Item.objects.all() for item in track(items, description="Processing items..."): # Process each item item.process() item.save() self.console.print("[green]✓ All items processed[/green]") ``` ```bash python manage.py process_items ``` -------------------------------- ### RichCommand make_rich_console() Method Signature Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-richcommand.md This is the method signature for RichCommand.make_rich_console(). It is a factory method for creating Rich Console instances. ```python def make_rich_console( self, **kwargs: Any, ) -> Console: """Factory method that creates and returns a Rich Console instance. Override this method to customize Console behavior with additional parameters.""" pass ``` -------------------------------- ### Print JSON with Syntax Highlighting Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-shell-command.md Outputs a Python dictionary as JSON with automatic syntax highlighting using the `print_json` function. ```python >>> import json >>> data = {'status': 'success', 'count': 42} >>> print_json(data) ``` -------------------------------- ### _exc_info_to_string() Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-richrunner.md Converts exception information to a formatted string using Rich Traceback rendering. Features include displaying local variables, filtering framework frames, and syntax highlighting. ```APIDOC ## _exc_info_to_string() ### Description Converts exception information to a formatted string using Rich Traceback rendering. ### Returns `str` — Formatted traceback with syntax highlighting and local variable display. ### Features: - Shows local variables at each stack frame - Filters out unittest and Django test framework frames - Line numbers and source code context - Syntax highlighting for code snippets ### Parameters #### Path Parameters - **err** (_SysExcInfoType) - Tuple of (exception type, exception value, traceback). - **test** (TestCase) - The test that raised the exception. ### Method Signature ```python def _exc_info_to_string( self, err: _SysExcInfoType, test: TestCase, ) -> str ``` ``` -------------------------------- ### addSkip() Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-richrunner.md Called when a test is skipped. In verbose mode, it prints the test description and 'skipped "reason"' in yellow. In dot mode, it prints a single 's' in yellow. ```APIDOC ## addSkip() ### Description Called when a test is skipped. ### Output: - Verbose mode: Test description and "skipped 'reason'" in yellow - Dot mode: Single "s" character in yellow ### Method Signature ```python def addSkip(self, test: TestCase, reason: str) -> None ``` ``` -------------------------------- ### Import RichRunner Class Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/module-overview.md Import the RichRunner class for custom test execution configurations. ```python from django_rich.test import RichRunner ``` -------------------------------- ### Import pprint from rich.pretty Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-shell-command.md Imports the pprint function from the rich.pretty module for pretty-printing Python objects with rich formatting and color. ```python from rich.pretty import pprint ``` -------------------------------- ### Minimal Django Rich Configuration Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/configuration.md Activate all django-rich features by adding 'django_rich' to INSTALLED_APPS and setting TEST_RUNNER. This enables enhanced shell commands and colorized test output. ```python # settings.py INSTALLED_APPS = [ # ... your existing apps ... "django_rich", ] TEST_RUNNER = "django_rich.test.RichRunner" ``` -------------------------------- ### Run tests with Rich output Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/README.md Execute Django tests using manage.py test with various options to enhance output, including showing slow tests, SQL queries, or dropping into a debugger. ```bash python manage.py test # Basic python manage.py test --durations 10 # Show slow tests python manage.py test --debug-sql # Show SQL queries python manage.py test --pdb # Drop into debugger ``` -------------------------------- ### Import Console and print_json Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-shell-command.md Imports the Console class and demonstrates accessing the print_json method. This is used for printing JSON data with syntax highlighting and automatic formatting. ```python from rich.console import Console console = Console() console.print_json ``` -------------------------------- ### Rich Markup for Colored Output Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-shell-command.md Demonstrates using Rich markup tags within print statements to render colored text and symbols in the console. ```python >>> print("[bold green]✓ Success[/bold green]") >>> print("[bold red]✗ Failed[/bold red]") >>> print("[yellow]⚠ Warning[/yellow]") ``` -------------------------------- ### Set Output Width on CI Source: https://github.com/adamchainz/django-rich/blob/main/README.rst Override the default terminal width for test output on CI systems by setting the COLUMNS environment variable. ```console $ COLUMNS=120 ./manage.py test ``` -------------------------------- ### Print JSON Data with Rich Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-shell-command.md Shows how to print JSON data using Rich's print_json function, which provides syntax highlighting and automatic formatting for better readability. ```python >>> data = {"users": [{"id": 1, "name": "Alice"}]} >>> print_json(data) ``` -------------------------------- ### Configuring Django Settings for Custom Test Runner Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-internal-classes.md Shows how to configure Django's `settings.py` to use a custom test runner by setting the `TEST_RUNNER` variable to the import path of the custom runner class. ```python # settings.py TEST_RUNNER = "myapp.test_runners.CustomTestRunner" ``` -------------------------------- ### Run Django Tests Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/quick-start.md Execute your Django tests using the manage.py command. The RichRunner provides enhanced output. ```bash python manage.py test ``` -------------------------------- ### Running Django Tests with Debug SQL Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/usage-examples.md Enable SQL query logging for failed tests. This command helps in debugging database-related issues by showing all executed SQL queries during test failures. ```bash # Show SQL queries executed during failed tests python manage.py test tests.test_models --debug-sql ``` -------------------------------- ### Basic Django Test with RichRunner Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/usage-examples.md A standard Django TestCase demonstrating item creation and string representation. This serves as a base for testing with RichRunner. ```python # tests/test_models.py from django.test import TestCase from myapp.models import Item class ItemTests(TestCase): def test_create_item(self): item = Item.objects.create(name="Test Item") self.assertEqual(item.name, "Test Item") def test_item_string_representation(self): item = Item.objects.create(name="Test Item") self.assertEqual(str(item), "Test Item") ``` -------------------------------- ### Integrating with Django Management Commands Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-richcommand.md Illustrates how to define a custom Django management command that inherits from RichCommand, supporting standard Django features like argument parsing and verbose output. ```python from django.core.management import call_command from django_rich.management import RichCommand class MyCommand(RichCommand): def add_arguments(self, parser): parser.add_argument('--verbose', action='store_true') def handle(self, *args, **options): if options['verbose']: self.console.print("Verbose mode enabled") ``` -------------------------------- ### Controlling Color Output Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-richcommand.md Shows how to manage color output for Django management commands using flags like --force-color and --no-color. The console auto-detects color support by default. ```bash python manage.py mycommand # Color if terminal supports it ``` ```bash python manage.py mycommand --force-color ``` ```bash python manage.py mycommand --no-color ``` -------------------------------- ### Minimal RichConsole Configuration Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/configuration.md Configure RichConsole to disable markup, highlighting, and emoji rendering for a minimal output experience. ```python class Command(RichCommand): def make_rich_console(self, **kwargs): return super().make_rich_console( **kwargs, markup=False, highlight=False, emoji=False, ) ``` -------------------------------- ### RichTextTestResult Initialization Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-richrunner.md Initializes the RichTextTestResult with a Rich Console and pre-rendered separators. The console is created from the provided stream. ```python def __init( self, stream: _WritelnDecorator, *args: Any, **kwargs: Any, ) -> None ``` -------------------------------- ### RichCommand.execute() Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-richcommand.md Executes the command, validating color flags and setting up the console before calling the parent implementation. This method is typically called automatically by Django's management system. ```APIDOC ## RichCommand.execute() ### Description Executes the command. This method intercepts Django's `execute()` to validate color flags and set up the console before calling the parent implementation. ### Method `execute(*args: Any, **options: Any)` ### Parameters #### Positional Arguments * `*args` (Any) - Positional arguments passed to the command handler. #### Keyword Arguments * `**options` (Any) - Command options, including `stdout`, `no_color`, and `force_color`. ### Returns `str | None` — The return value from the parent `execute()` method. ### Raises * `CommandError` — If both `--no-color` and `--force-color` flags are provided simultaneously. ### Example ```python # This is called by Django automatically: # python manage.py mycommand --force-color ``` ``` -------------------------------- ### Run Django Shell Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/module-overview.md Execute the Django shell command. This is automatically available when django-rich is included in INSTALLED_APPS. ```bash python manage.py shell ``` -------------------------------- ### Enable Django Rich Shell Enhancement Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/INDEX.md Add 'django_rich' to your INSTALLED_APPS to enable shell enhancement. ```python INSTALLED_APPS = ["django_rich", ...] ``` -------------------------------- ### Pretty Print Data in Shell (Auto-Imported) Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/usage-examples.md Django 5.2+ shells automatically provide `pprint` and `print_json` for nicely formatted output of Python objects and JSON data. Rich markup also works with `print()`. ```python # pprint() is automatically available >>> users = list(User.objects.values('id', 'username')[:3]) >>> pprint(users) # Output nicely formatted and indented # print_json() is automatically available >>> import json >>> data = {"status": "ok", "count": 42} >>> print_json(data) # Rich pretty-printing is enabled by default >>> {"name": "Alice", "age": 30, "scores": [95, 87, 92]} { 'name': 'Alice', 'age': 30, 'scores': [95, 87, 92] } # Rich markup works in print() >>> print("[bold cyan]Hello[/bold cyan] [yellow]World[/yellow]!") ``` -------------------------------- ### Force Color Output with Django Commands Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/configuration.md Use the `--force-color` flag to ensure color output even when the terminal does not support it. ```bash python manage.py mycommand --force-color ``` -------------------------------- ### PDB Interactive Debugging Session Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-internal-classes.md Illustrates an interactive PDB session that occurs when a test fails with the --pdb flag enabled. Shows commands like 'p' to print and 'c' to continue. ```bash Found 1 test(s). System check identified no issues (0 silenced). Opening PDB: AssertionError('1 != 2') > /path/to/test.py(42)test_something() -> self.assertEqual(1, 2) (Pdb) p result {'value': 1} (Pdb) c # continue to next failure ``` -------------------------------- ### Verbose Test Output with Django Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/configuration.md Use `-v 2` for verbose test output, displaying test names and their status. ```bash python manage.py test -v 2 ``` -------------------------------- ### Custom Rich Console Theme in Django Command Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/configuration.md Subclass `RichCommand` and override `make_rich_console` to apply a custom `rich.theme.Theme` to the console. ```python from django_rich.management import RichCommand from rich.theme import Theme class Command(RichCommand): def make_rich_console(self, **kwargs): custom_theme = Theme({ "info": "cyan", "warning": "yellow", "danger": "bold red", }) return super().make_rich_console( **kwargs, theme=custom_theme, ) def handle(self, *args, **options): self.console.print("[info]Info message[/info]") self.console.print("[warning]Warning message[/warning]") self.console.print("[danger]Danger message[/danger]") ``` -------------------------------- ### Docker and Container Configuration Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/configuration.md Set the COLUMNS environment variable to 120 for proper formatting in Docker and containerized environments. ```dockerfile # Dockerfile ENV COLUMNS=120 CMD python manage.py test ``` ```yaml # docker-compose.yml services: web: environment: COLUMNS: "120" ``` -------------------------------- ### Add django_rich to INSTALLED_APPS Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-shell-command.md Ensure 'django_rich' is included in your project's INSTALLED_APPS setting to enable pretty-printing. ```python # settings.py INSTALLED_APPS = [ "django.contrib.auth", "django.contrib.contenttypes", # ... "django_rich", # Must be present ] ``` -------------------------------- ### RichCommand.make_rich_console() Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-richcommand.md A factory method that creates and returns a Rich Console instance. It can be overridden to customize Console behavior with additional parameters. ```APIDOC ## RichCommand.make_rich_console() ### Description Factory method that creates and returns a Rich Console instance. Override this method to customize Console behavior with additional parameters. ### Method `make_rich_console(**kwargs: Any)` ### Parameters #### Keyword Arguments * `**kwargs` (Any) - Keyword arguments passed directly to the `Console` constructor. Typically includes `file` (the output stream) and `force_terminal` (bool). ### Returns `Console` — A Rich Console instance configured with the provided kwargs. ### Raises None ### Example ```python from django_rich.management import RichCommand from rich.console import Console class Command(RichCommand): def make_rich_console(self, **kwargs): # Disable markup and highlighting return super().make_rich_console( **kwargs, markup=False, highlight=False ) def handle(self, *args, **options): # [bold red]Text[/bold red] will print literally without formatting self.console.print("[bold red]Alert![/bold red]") ``` ``` -------------------------------- ### Import Key Types for Mypy Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/module-overview.md Imports necessary types for static type checking with mypy. Ensure these are available in your environment. ```python from typing import Any, TextIO from unittest.case import TestCase from rich.console import Console ``` -------------------------------- ### GitHub Actions CI/CD Integration Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/configuration.md Configure GitHub Actions to set the COLUMNS environment variable to 120 before running tests. ```yaml # .github/workflows/tests.yml name: Tests on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-python@v4 with: python-version: "3.12" - run: pip install -e . - run: COLUMNS=120 python manage.py test ``` -------------------------------- ### Print Formatted Text with Rich Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-shell-command.md Demonstrates using Rich's print function to display text with embedded markup for styling, such as bold blue and red colors. ```python >>> print("[bold blue]Hello[/bold blue] [red]World[/red]") ``` -------------------------------- ### addSkip() Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-internal-classes.md Called when a test is skipped. Indicates the reason for skipping. ```APIDOC ## addSkip() ### Description Called when a test is skipped. Indicates the reason for skipping. ### Parameters #### Path Parameters - `test` (TestCase) - Required - The skipped test - `reason` (str) - Required - The skip reason message ### Output - **Verbose mode:** Test description followed by `skipped 'reason'` in yellow ``` test_something (tests.MyTest) ... skipped 'not implemented' ``` - **Dot mode:** Yellow "s" ### Example ```python # When this test is skipped: @skip("not implemented") def test_future_feature(self): pass # Or programmatically: def test_conditional(self): if not has_feature(): self.skipTest("feature not available") # ... test code ``` ``` -------------------------------- ### Subclassing RichTestRunner with a Custom Result Class Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-internal-classes.md Demonstrates subclassing `RichTestRunner` to specify a custom result class (`CustomResultClass`) and override methods like `_printDurations` for custom formatting. This allows for a fully customized test running experience. ```python from django_rich.test import RichTestRunner, RichTextTestResult class CustomResultClass(RichTextTestResult): def addSuccess(self, test): super().addSuccess(test) class CustomTestRunner(RichTestRunner): resultclass = CustomResultClass def _printDurations(self, result): # Custom duration formatting super()._printDurations(result) ``` -------------------------------- ### Run Django Tests with Rich Runner Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/module-overview.md Execute Django tests using the configured RichRunner. Options like --debug-sql and --durations can be used to enable specific Rich runner features. ```bash python manage.py test python manage.py test --debug-sql python manage.py test --durations 10 ``` -------------------------------- ### Command with Status Updates Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/usage-examples.md Utilize RichCommand's console status context manager to show ongoing operations like API connections or data fetching. Requires `time.sleep` for simulation. ```python # myapp/management/commands/sync_data.py from time import sleep from django_rich.management import RichCommand from django.core.management import CommandError class Command(RichCommand): def handle(self, *args, **options): self.console.print("[bold]Starting data sync...[/bold]") with self.console.status("Connecting to API...") as status: sleep(1) # Simulate API call status.update("Fetching data...") sleep(1) status.update("Processing data...") sleep(1) self.console.print("[green]✓ Sync complete[/green]") ``` -------------------------------- ### Activate Extended Django Shell with Rich Pretty-Printing Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/module-overview.md Add 'django_rich' to INSTALLED_APPS in settings.py to enable Rich pretty-printing and auto-imports in the Django shell. This enhances the REPL experience for Python, IPython, and bpython interpreters. ```python # settings.py INSTALLED_APPS = [..., "django_rich"] ``` -------------------------------- ### Configure Django Rich Test Runner Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/quick-start.md Set the TEST_RUNNER setting in your Django settings.py file to use the RichRunner. ```python # settings.py TEST_RUNNER = "django_rich.test.RichRunner" ``` -------------------------------- ### addSkip() Method Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/api-reference-richrunner.md Called when a test is skipped. Outputs 'skipped 'reason'' in verbose mode or 's' in dot mode, colored yellow. ```python def addSkip(self, test: TestCase, reason: str) -> None: ``` -------------------------------- ### Django Management Command with Table Output Source: https://github.com/adamchainz/django-rich/blob/main/_autodocs/quick-start.md Utilize `rich.table.Table` to display data in a structured, colored table format within a `RichCommand`. This is useful for presenting query results or structured information. ```python from django_rich.management import RichCommand from rich.table import Table from django.contrib.auth.models import User class Command(RichCommand): def handle(self, *args, **options): table = Table(title="Users") table.add_column("ID", style="cyan") table.add_column("Username", style="magenta") table.add_column("Email") for user in User.objects.all(): table.add_row(str(user.id), user.username, user.email) self.console.print(table) ```