repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/progress.py
rich/progress.py
from __future__ import annotations import io import typing import warnings from abc import ABC, abstractmethod from collections import deque from dataclasses import dataclass, field from datetime import timedelta from io import RawIOBase, UnsupportedOperation from math import ceil from mmap import mmap from operator import length_hint from os import PathLike, stat from threading import Event, RLock, Thread from types import TracebackType from typing import ( TYPE_CHECKING, Any, BinaryIO, Callable, ContextManager, Deque, Dict, Generic, Iterable, List, Literal, NamedTuple, NewType, Optional, TextIO, Tuple, Type, TypeVar, Union, ) if TYPE_CHECKING: # Can be replaced with `from typing import Self` in Python 3.11+ from typing_extensions import Self # pragma: no cover from . import filesize, get_console from .console import Console, Group, JustifyMethod, RenderableType from .highlighter import Highlighter from .jupyter import JupyterMixin from .live import Live from .progress_bar import ProgressBar from .spinner import Spinner from .style import StyleType from .table import Column, Table from .text import Text, TextType TaskID = NewType("TaskID", int) ProgressType = TypeVar("ProgressType") GetTimeCallable = Callable[[], float] _I = typing.TypeVar("_I", TextIO, BinaryIO) class _TrackThread(Thread): """A thread to periodically update progress.""" def __init__(self, progress: "Progress", task_id: "TaskID", update_period: float): self.progress = progress self.task_id = task_id self.update_period = update_period self.done = Event() self.completed = 0 super().__init__(daemon=True) def run(self) -> None: task_id = self.task_id advance = self.progress.advance update_period = self.update_period last_completed = 0 wait = self.done.wait while not wait(update_period) and self.progress.live.is_started: completed = self.completed if last_completed != completed: advance(task_id, completed - last_completed) last_completed = completed self.progress.update(self.task_id, completed=self.completed, refresh=True) def __enter__(self) -> "_TrackThread": self.start() return self def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> None: self.done.set() self.join() def track( sequence: Iterable[ProgressType], description: str = "Working...", total: Optional[float] = None, completed: int = 0, auto_refresh: bool = True, console: Optional[Console] = None, transient: bool = False, get_time: Optional[Callable[[], float]] = None, refresh_per_second: float = 10, style: StyleType = "bar.back", complete_style: StyleType = "bar.complete", finished_style: StyleType = "bar.finished", pulse_style: StyleType = "bar.pulse", update_period: float = 0.1, disable: bool = False, show_speed: bool = True, ) -> Iterable[ProgressType]: """Track progress by iterating over a sequence. You can also track progress of an iterable, which might require that you additionally specify ``total``. Args: sequence (Iterable[ProgressType]): Values you wish to iterate over and track progress. description (str, optional): Description of task show next to progress bar. Defaults to "Working". total: (float, optional): Total number of steps. Default is len(sequence). completed (int, optional): Number of steps completed so far. Defaults to 0. auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True. transient: (bool, optional): Clear the progress on exit. Defaults to False. console (Console, optional): Console to write to. Default creates internal Console instance. refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10. style (StyleType, optional): Style for the bar background. Defaults to "bar.back". complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete". finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished". pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse". update_period (float, optional): Minimum time (in seconds) between calls to update(). Defaults to 0.1. disable (bool, optional): Disable display of progress. show_speed (bool, optional): Show speed if total isn't known. Defaults to True. Returns: Iterable[ProgressType]: An iterable of the values in the sequence. """ columns: List["ProgressColumn"] = ( [TextColumn("[progress.description]{task.description}")] if description else [] ) columns.extend( ( BarColumn( style=style, complete_style=complete_style, finished_style=finished_style, pulse_style=pulse_style, ), TaskProgressColumn(show_speed=show_speed), TimeRemainingColumn(elapsed_when_finished=True), ) ) progress = Progress( *columns, auto_refresh=auto_refresh, console=console, transient=transient, get_time=get_time, refresh_per_second=refresh_per_second or 10, disable=disable, ) with progress: yield from progress.track( sequence, total=total, completed=completed, description=description, update_period=update_period, ) class _Reader(RawIOBase, BinaryIO): """A reader that tracks progress while it's being read from.""" def __init__( self, handle: BinaryIO, progress: "Progress", task: TaskID, close_handle: bool = True, ) -> None: self.handle = handle self.progress = progress self.task = task self.close_handle = close_handle self._closed = False def __enter__(self) -> "_Reader": self.handle.__enter__() return self def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> None: self.close() def __iter__(self) -> BinaryIO: return self def __next__(self) -> bytes: line = next(self.handle) self.progress.advance(self.task, advance=len(line)) return line @property def closed(self) -> bool: return self._closed def fileno(self) -> int: return self.handle.fileno() def isatty(self) -> bool: return self.handle.isatty() @property def mode(self) -> str: return self.handle.mode @property def name(self) -> str: return self.handle.name def readable(self) -> bool: return self.handle.readable() def seekable(self) -> bool: return self.handle.seekable() def writable(self) -> bool: return False def read(self, size: int = -1) -> bytes: block = self.handle.read(size) self.progress.advance(self.task, advance=len(block)) return block def readinto(self, b: Union[bytearray, memoryview, mmap]): # type: ignore[no-untyped-def, override] n = self.handle.readinto(b) # type: ignore[attr-defined] self.progress.advance(self.task, advance=n) return n def readline(self, size: int = -1) -> bytes: # type: ignore[override] line = self.handle.readline(size) self.progress.advance(self.task, advance=len(line)) return line def readlines(self, hint: int = -1) -> List[bytes]: lines = self.handle.readlines(hint) self.progress.advance(self.task, advance=sum(map(len, lines))) return lines def close(self) -> None: if self.close_handle: self.handle.close() self._closed = True def seek(self, offset: int, whence: int = 0) -> int: pos = self.handle.seek(offset, whence) self.progress.update(self.task, completed=pos) return pos def tell(self) -> int: return self.handle.tell() def write(self, s: Any) -> int: raise UnsupportedOperation("write") def writelines(self, lines: Iterable[Any]) -> None: raise UnsupportedOperation("writelines") class _ReadContext(ContextManager[_I], Generic[_I]): """A utility class to handle a context for both a reader and a progress.""" def __init__(self, progress: "Progress", reader: _I) -> None: self.progress = progress self.reader: _I = reader def __enter__(self) -> _I: self.progress.start() return self.reader.__enter__() def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> None: self.progress.stop() self.reader.__exit__(exc_type, exc_val, exc_tb) def wrap_file( file: BinaryIO, total: int, *, description: str = "Reading...", auto_refresh: bool = True, console: Optional[Console] = None, transient: bool = False, get_time: Optional[Callable[[], float]] = None, refresh_per_second: float = 10, style: StyleType = "bar.back", complete_style: StyleType = "bar.complete", finished_style: StyleType = "bar.finished", pulse_style: StyleType = "bar.pulse", disable: bool = False, ) -> ContextManager[BinaryIO]: """Read bytes from a file while tracking progress. Args: file (Union[str, PathLike[str], BinaryIO]): The path to the file to read, or a file-like object in binary mode. total (int): Total number of bytes to read. description (str, optional): Description of task show next to progress bar. Defaults to "Reading". auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True. transient: (bool, optional): Clear the progress on exit. Defaults to False. console (Console, optional): Console to write to. Default creates internal Console instance. refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10. style (StyleType, optional): Style for the bar background. Defaults to "bar.back". complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete". finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished". pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse". disable (bool, optional): Disable display of progress. Returns: ContextManager[BinaryIO]: A context manager yielding a progress reader. """ columns: List["ProgressColumn"] = ( [TextColumn("[progress.description]{task.description}")] if description else [] ) columns.extend( ( BarColumn( style=style, complete_style=complete_style, finished_style=finished_style, pulse_style=pulse_style, ), DownloadColumn(), TimeRemainingColumn(), ) ) progress = Progress( *columns, auto_refresh=auto_refresh, console=console, transient=transient, get_time=get_time, refresh_per_second=refresh_per_second or 10, disable=disable, ) reader = progress.wrap_file(file, total=total, description=description) return _ReadContext(progress, reader) @typing.overload def open( file: Union[str, "PathLike[str]", bytes], mode: Union[Literal["rt"], Literal["r"]], buffering: int = -1, encoding: Optional[str] = None, errors: Optional[str] = None, newline: Optional[str] = None, *, total: Optional[int] = None, description: str = "Reading...", auto_refresh: bool = True, console: Optional[Console] = None, transient: bool = False, get_time: Optional[Callable[[], float]] = None, refresh_per_second: float = 10, style: StyleType = "bar.back", complete_style: StyleType = "bar.complete", finished_style: StyleType = "bar.finished", pulse_style: StyleType = "bar.pulse", disable: bool = False, ) -> ContextManager[TextIO]: pass @typing.overload def open( file: Union[str, "PathLike[str]", bytes], mode: Literal["rb"], buffering: int = -1, encoding: Optional[str] = None, errors: Optional[str] = None, newline: Optional[str] = None, *, total: Optional[int] = None, description: str = "Reading...", auto_refresh: bool = True, console: Optional[Console] = None, transient: bool = False, get_time: Optional[Callable[[], float]] = None, refresh_per_second: float = 10, style: StyleType = "bar.back", complete_style: StyleType = "bar.complete", finished_style: StyleType = "bar.finished", pulse_style: StyleType = "bar.pulse", disable: bool = False, ) -> ContextManager[BinaryIO]: pass def open( file: Union[str, "PathLike[str]", bytes], mode: Union[Literal["rb"], Literal["rt"], Literal["r"]] = "r", buffering: int = -1, encoding: Optional[str] = None, errors: Optional[str] = None, newline: Optional[str] = None, *, total: Optional[int] = None, description: str = "Reading...", auto_refresh: bool = True, console: Optional[Console] = None, transient: bool = False, get_time: Optional[Callable[[], float]] = None, refresh_per_second: float = 10, style: StyleType = "bar.back", complete_style: StyleType = "bar.complete", finished_style: StyleType = "bar.finished", pulse_style: StyleType = "bar.pulse", disable: bool = False, ) -> Union[ContextManager[BinaryIO], ContextManager[TextIO]]: """Read bytes from a file while tracking progress. Args: path (Union[str, PathLike[str], BinaryIO]): The path to the file to read, or a file-like object in binary mode. mode (str): The mode to use to open the file. Only supports "r", "rb" or "rt". buffering (int): The buffering strategy to use, see :func:`io.open`. encoding (str, optional): The encoding to use when reading in text mode, see :func:`io.open`. errors (str, optional): The error handling strategy for decoding errors, see :func:`io.open`. newline (str, optional): The strategy for handling newlines in text mode, see :func:`io.open` total: (int, optional): Total number of bytes to read. Must be provided if reading from a file handle. Default for a path is os.stat(file).st_size. description (str, optional): Description of task show next to progress bar. Defaults to "Reading". auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True. transient: (bool, optional): Clear the progress on exit. Defaults to False. console (Console, optional): Console to write to. Default creates internal Console instance. refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10. style (StyleType, optional): Style for the bar background. Defaults to "bar.back". complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete". finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished". pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse". disable (bool, optional): Disable display of progress. encoding (str, optional): The encoding to use when reading in text mode. Returns: ContextManager[BinaryIO]: A context manager yielding a progress reader. """ columns: List["ProgressColumn"] = ( [TextColumn("[progress.description]{task.description}")] if description else [] ) columns.extend( ( BarColumn( style=style, complete_style=complete_style, finished_style=finished_style, pulse_style=pulse_style, ), DownloadColumn(), TimeRemainingColumn(), ) ) progress = Progress( *columns, auto_refresh=auto_refresh, console=console, transient=transient, get_time=get_time, refresh_per_second=refresh_per_second or 10, disable=disable, ) reader = progress.open( file, mode=mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline, total=total, description=description, ) return _ReadContext(progress, reader) # type: ignore[return-value, type-var] class ProgressColumn(ABC): """Base class for a widget to use in progress display.""" max_refresh: Optional[float] = None def __init__(self, table_column: Optional[Column] = None) -> None: self._table_column = table_column self._renderable_cache: Dict[TaskID, Tuple[float, RenderableType]] = {} self._update_time: Optional[float] = None def get_table_column(self) -> Column: """Get a table column, used to build tasks table.""" return self._table_column or Column() def __call__(self, task: "Task") -> RenderableType: """Called by the Progress object to return a renderable for the given task. Args: task (Task): An object containing information regarding the task. Returns: RenderableType: Anything renderable (including str). """ current_time = task.get_time() if self.max_refresh is not None and not task.completed: try: timestamp, renderable = self._renderable_cache[task.id] except KeyError: pass else: if timestamp + self.max_refresh > current_time: return renderable renderable = self.render(task) self._renderable_cache[task.id] = (current_time, renderable) return renderable @abstractmethod def render(self, task: "Task") -> RenderableType: """Should return a renderable object.""" class RenderableColumn(ProgressColumn): """A column to insert an arbitrary column. Args: renderable (RenderableType, optional): Any renderable. Defaults to empty string. """ def __init__( self, renderable: RenderableType = "", *, table_column: Optional[Column] = None ): self.renderable = renderable super().__init__(table_column=table_column) def render(self, task: "Task") -> RenderableType: return self.renderable class SpinnerColumn(ProgressColumn): """A column with a 'spinner' animation. Args: spinner_name (str, optional): Name of spinner animation. Defaults to "dots". style (StyleType, optional): Style of spinner. Defaults to "progress.spinner". speed (float, optional): Speed factor of spinner. Defaults to 1.0. finished_text (TextType, optional): Text used when task is finished. Defaults to " ". """ def __init__( self, spinner_name: str = "dots", style: Optional[StyleType] = "progress.spinner", speed: float = 1.0, finished_text: TextType = " ", table_column: Optional[Column] = None, ): self.spinner = Spinner(spinner_name, style=style, speed=speed) self.finished_text = ( Text.from_markup(finished_text) if isinstance(finished_text, str) else finished_text ) super().__init__(table_column=table_column) def set_spinner( self, spinner_name: str, spinner_style: Optional[StyleType] = "progress.spinner", speed: float = 1.0, ) -> None: """Set a new spinner. Args: spinner_name (str): Spinner name, see python -m rich.spinner. spinner_style (Optional[StyleType], optional): Spinner style. Defaults to "progress.spinner". speed (float, optional): Speed factor of spinner. Defaults to 1.0. """ self.spinner = Spinner(spinner_name, style=spinner_style, speed=speed) def render(self, task: "Task") -> RenderableType: text = ( self.finished_text if task.finished else self.spinner.render(task.get_time()) ) return text class TextColumn(ProgressColumn): """A column containing text.""" def __init__( self, text_format: str, style: StyleType = "none", justify: JustifyMethod = "left", markup: bool = True, highlighter: Optional[Highlighter] = None, table_column: Optional[Column] = None, ) -> None: self.text_format = text_format self.justify: JustifyMethod = justify self.style = style self.markup = markup self.highlighter = highlighter super().__init__(table_column=table_column or Column(no_wrap=True)) def render(self, task: "Task") -> Text: _text = self.text_format.format(task=task) if self.markup: text = Text.from_markup(_text, style=self.style, justify=self.justify) else: text = Text(_text, style=self.style, justify=self.justify) if self.highlighter: self.highlighter.highlight(text) return text class BarColumn(ProgressColumn): """Renders a visual progress bar. Args: bar_width (Optional[int], optional): Width of bar or None for full width. Defaults to 40. style (StyleType, optional): Style for the bar background. Defaults to "bar.back". complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete". finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished". pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse". """ def __init__( self, bar_width: Optional[int] = 40, style: StyleType = "bar.back", complete_style: StyleType = "bar.complete", finished_style: StyleType = "bar.finished", pulse_style: StyleType = "bar.pulse", table_column: Optional[Column] = None, ) -> None: self.bar_width = bar_width self.style = style self.complete_style = complete_style self.finished_style = finished_style self.pulse_style = pulse_style super().__init__(table_column=table_column) def render(self, task: "Task") -> ProgressBar: """Gets a progress bar widget for a task.""" return ProgressBar( total=max(0, task.total) if task.total is not None else None, completed=max(0, task.completed), width=None if self.bar_width is None else max(1, self.bar_width), pulse=not task.started, animation_time=task.get_time(), style=self.style, complete_style=self.complete_style, finished_style=self.finished_style, pulse_style=self.pulse_style, ) class TimeElapsedColumn(ProgressColumn): """Renders time elapsed.""" def render(self, task: "Task") -> Text: """Show time elapsed.""" elapsed = task.finished_time if task.finished else task.elapsed if elapsed is None: return Text("-:--:--", style="progress.elapsed") delta = timedelta(seconds=max(0, int(elapsed))) return Text(str(delta), style="progress.elapsed") class TaskProgressColumn(TextColumn): """Show task progress as a percentage. Args: text_format (str, optional): Format for percentage display. Defaults to "[progress.percentage]{task.percentage:>3.0f}%". text_format_no_percentage (str, optional): Format if percentage is unknown. Defaults to "". style (StyleType, optional): Style of output. Defaults to "none". justify (JustifyMethod, optional): Text justification. Defaults to "left". markup (bool, optional): Enable markup. Defaults to True. highlighter (Optional[Highlighter], optional): Highlighter to apply to output. Defaults to None. table_column (Optional[Column], optional): Table Column to use. Defaults to None. show_speed (bool, optional): Show speed if total is unknown. Defaults to False. """ def __init__( self, text_format: str = "[progress.percentage]{task.percentage:>3.0f}%", text_format_no_percentage: str = "", style: StyleType = "none", justify: JustifyMethod = "left", markup: bool = True, highlighter: Optional[Highlighter] = None, table_column: Optional[Column] = None, show_speed: bool = False, ) -> None: self.text_format_no_percentage = text_format_no_percentage self.show_speed = show_speed super().__init__( text_format=text_format, style=style, justify=justify, markup=markup, highlighter=highlighter, table_column=table_column, ) @classmethod def render_speed(cls, speed: Optional[float]) -> Text: """Render the speed in iterations per second. Args: task (Task): A Task object. Returns: Text: Text object containing the task speed. """ if speed is None: return Text("", style="progress.percentage") unit, suffix = filesize.pick_unit_and_suffix( int(speed), ["", "×10³", "×10⁶", "×10⁹", "×10¹²"], 1000, ) data_speed = speed / unit return Text(f"{data_speed:.1f}{suffix} it/s", style="progress.percentage") def render(self, task: "Task") -> Text: if task.total is None and self.show_speed: return self.render_speed(task.finished_speed or task.speed) text_format = ( self.text_format_no_percentage if task.total is None else self.text_format ) _text = text_format.format(task=task) if self.markup: text = Text.from_markup(_text, style=self.style, justify=self.justify) else: text = Text(_text, style=self.style, justify=self.justify) if self.highlighter: self.highlighter.highlight(text) return text class TimeRemainingColumn(ProgressColumn): """Renders estimated time remaining. Args: compact (bool, optional): Render MM:SS when time remaining is less than an hour. Defaults to False. elapsed_when_finished (bool, optional): Render time elapsed when the task is finished. Defaults to False. """ # Only refresh twice a second to prevent jitter max_refresh = 0.5 def __init__( self, compact: bool = False, elapsed_when_finished: bool = False, table_column: Optional[Column] = None, ): self.compact = compact self.elapsed_when_finished = elapsed_when_finished super().__init__(table_column=table_column) def render(self, task: "Task") -> Text: """Show time remaining.""" if self.elapsed_when_finished and task.finished: task_time = task.finished_time style = "progress.elapsed" else: task_time = task.time_remaining style = "progress.remaining" if task.total is None: return Text("", style=style) if task_time is None: return Text("--:--" if self.compact else "-:--:--", style=style) # Based on https://github.com/tqdm/tqdm/blob/master/tqdm/std.py minutes, seconds = divmod(int(task_time), 60) hours, minutes = divmod(minutes, 60) if self.compact and not hours: formatted = f"{minutes:02d}:{seconds:02d}" else: formatted = f"{hours:d}:{minutes:02d}:{seconds:02d}" return Text(formatted, style=style) class FileSizeColumn(ProgressColumn): """Renders completed filesize.""" def render(self, task: "Task") -> Text: """Show data completed.""" data_size = filesize.decimal(int(task.completed)) return Text(data_size, style="progress.filesize") class TotalFileSizeColumn(ProgressColumn): """Renders total filesize.""" def render(self, task: "Task") -> Text: """Show data completed.""" data_size = filesize.decimal(int(task.total)) if task.total is not None else "" return Text(data_size, style="progress.filesize.total") class MofNCompleteColumn(ProgressColumn): """Renders completed count/total, e.g. ' 10/1000'. Best for bounded tasks with int quantities. Space pads the completed count so that progress length does not change as task progresses past powers of 10. Args: separator (str, optional): Text to separate completed and total values. Defaults to "/". """ def __init__(self, separator: str = "/", table_column: Optional[Column] = None): self.separator = separator super().__init__(table_column=table_column) def render(self, task: "Task") -> Text: """Show completed/total.""" completed = int(task.completed) total = int(task.total) if task.total is not None else "?" total_width = len(str(total)) return Text( f"{completed:{total_width}d}{self.separator}{total}", style="progress.download", ) class DownloadColumn(ProgressColumn): """Renders file size downloaded and total, e.g. '0.5/2.3 GB'. Args: binary_units (bool, optional): Use binary units, KiB, MiB etc. Defaults to False. """ def __init__( self, binary_units: bool = False, table_column: Optional[Column] = None ) -> None: self.binary_units = binary_units super().__init__(table_column=table_column) def render(self, task: "Task") -> Text: """Calculate common unit for completed and total.""" completed = int(task.completed) unit_and_suffix_calculation_base = ( int(task.total) if task.total is not None else completed ) if self.binary_units: unit, suffix = filesize.pick_unit_and_suffix( unit_and_suffix_calculation_base, ["bytes", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"], 1024, ) else: unit, suffix = filesize.pick_unit_and_suffix( unit_and_suffix_calculation_base, ["bytes", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"], 1000, ) precision = 0 if unit == 1 else 1 completed_ratio = completed / unit completed_str = f"{completed_ratio:,.{precision}f}" if task.total is not None: total = int(task.total) total_ratio = total / unit total_str = f"{total_ratio:,.{precision}f}" else: total_str = "?" download_status = f"{completed_str}/{total_str} {suffix}" download_text = Text(download_status, style="progress.download") return download_text class TransferSpeedColumn(ProgressColumn): """Renders human readable transfer speed.""" def render(self, task: "Task") -> Text: """Show data transfer speed.""" speed = task.finished_speed or task.speed if speed is None: return Text("?", style="progress.data.speed") data_speed = filesize.decimal(int(speed)) return Text(f"{data_speed}/s", style="progress.data.speed") class ProgressSample(NamedTuple): """Sample of progress for a given time.""" timestamp: float """Timestamp of sample.""" completed: float """Number of steps completed.""" @dataclass class Task: """Information regarding a progress task. This object should be considered read-only outside of the :class:`~Progress` class. """ id: TaskID """Task ID associated with this task (used in Progress methods).""" description: str """str: Description of the task.""" total: Optional[float]
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
true
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/region.py
rich/region.py
from typing import NamedTuple class Region(NamedTuple): """Defines a rectangular region of the screen.""" x: int y: int width: int height: int
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/highlighter.py
rich/highlighter.py
import re from abc import ABC, abstractmethod from typing import List, Union from .text import Span, Text def _combine_regex(*regexes: str) -> str: """Combine a number of regexes in to a single regex. Returns: str: New regex with all regexes ORed together. """ return "|".join(regexes) class Highlighter(ABC): """Abstract base class for highlighters.""" def __call__(self, text: Union[str, Text]) -> Text: """Highlight a str or Text instance. Args: text (Union[str, ~Text]): Text to highlight. Raises: TypeError: If not called with text or str. Returns: Text: A test instance with highlighting applied. """ if isinstance(text, str): highlight_text = Text(text) elif isinstance(text, Text): highlight_text = text.copy() else: raise TypeError(f"str or Text instance required, not {text!r}") self.highlight(highlight_text) return highlight_text @abstractmethod def highlight(self, text: Text) -> None: """Apply highlighting in place to text. Args: text (~Text): A text object highlight. """ class NullHighlighter(Highlighter): """A highlighter object that doesn't highlight. May be used to disable highlighting entirely. """ def highlight(self, text: Text) -> None: """Nothing to do""" class RegexHighlighter(Highlighter): """Applies highlighting from a list of regular expressions.""" highlights: List[str] = [] base_style: str = "" def highlight(self, text: Text) -> None: """Highlight :class:`rich.text.Text` using regular expressions. Args: text (~Text): Text to highlighted. """ highlight_regex = text.highlight_regex for re_highlight in self.highlights: highlight_regex(re_highlight, style_prefix=self.base_style) class ReprHighlighter(RegexHighlighter): """Highlights the text typically produced from ``__repr__`` methods.""" base_style = "repr." highlights = [ r"(?P<tag_start><)(?P<tag_name>[-\w.:|]*)(?P<tag_contents>[\w\W]*)(?P<tag_end>>)", r'(?P<attrib_name>[\w_]{1,50})=(?P<attrib_value>"?[\w_]+"?)?', r"(?P<brace>[][{}()])", _combine_regex( r"(?P<ipv4>[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})", r"(?P<ipv6>([A-Fa-f0-9]{1,4}::?){1,7}[A-Fa-f0-9]{1,4})", r"(?P<eui64>(?:[0-9A-Fa-f]{1,2}-){7}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{1,2}:){7}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{4}\.){3}[0-9A-Fa-f]{4})", r"(?P<eui48>(?:[0-9A-Fa-f]{1,2}-){5}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{1,2}:){5}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{4}\.){2}[0-9A-Fa-f]{4})", r"(?P<uuid>[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})", r"(?P<call>[\w.]*?)\(", r"\b(?P<bool_true>True)\b|\b(?P<bool_false>False)\b|\b(?P<none>None)\b", r"(?P<ellipsis>\.\.\.)", r"(?P<number_complex>(?<!\w)(?:\-?[0-9]+\.?[0-9]*(?:e[-+]?\d+?)?)(?:[-+](?:[0-9]+\.?[0-9]*(?:e[-+]?\d+)?))?j)", r"(?P<number>(?<!\w)\-?[0-9]+\.?[0-9]*(e[-+]?\d+?)?\b|0x[0-9a-fA-F]*)", r"(?P<path>\B(/[-\w._+]+)*\/)(?P<filename>[-\w._+]*)?", r"(?<![\\\w])(?P<str>b?'''.*?(?<!\\)'''|b?'.*?(?<!\\)'|b?\"\"\".*?(?<!\\)\"\"\"|b?\".*?(?<!\\)\")", r"(?P<url>(file|https|http|ws|wss)://[-0-9a-zA-Z$_+!`(),.?/;:&=%#~@]*)", ), ] class JSONHighlighter(RegexHighlighter): """Highlights JSON""" # Captures the start and end of JSON strings, handling escaped quotes JSON_STR = r"(?<![\\\w])(?P<str>b?\".*?(?<!\\)\")" JSON_WHITESPACE = {" ", "\n", "\r", "\t"} base_style = "json." highlights = [ _combine_regex( r"(?P<brace>[\{\[\(\)\]\}])", r"\b(?P<bool_true>true)\b|\b(?P<bool_false>false)\b|\b(?P<null>null)\b", r"(?P<number>(?<!\w)\-?[0-9]+\.?[0-9]*(e[\-\+]?\d+?)?\b|0x[0-9a-fA-F]*)", JSON_STR, ), ] def highlight(self, text: Text) -> None: super().highlight(text) # Additional work to handle highlighting JSON keys plain = text.plain append = text.spans.append whitespace = self.JSON_WHITESPACE for match in re.finditer(self.JSON_STR, plain): start, end = match.span() cursor = end while cursor < len(plain): char = plain[cursor] cursor += 1 if char == ":": append(Span(start, end, "json.key")) elif char in whitespace: continue break class ISO8601Highlighter(RegexHighlighter): """Highlights the ISO8601 date time strings. Regex reference: https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch04s07.html """ base_style = "iso8601." highlights = [ # # Dates # # Calendar month (e.g. 2008-08). The hyphen is required r"^(?P<year>[0-9]{4})-(?P<month>1[0-2]|0[1-9])$", # Calendar date w/o hyphens (e.g. 20080830) r"^(?P<date>(?P<year>[0-9]{4})(?P<month>1[0-2]|0[1-9])(?P<day>3[01]|0[1-9]|[12][0-9]))$", # Ordinal date (e.g. 2008-243). The hyphen is optional r"^(?P<date>(?P<year>[0-9]{4})-?(?P<day>36[0-6]|3[0-5][0-9]|[12][0-9]{2}|0[1-9][0-9]|00[1-9]))$", # # Weeks # # Week of the year (e.g., 2008-W35). The hyphen is optional r"^(?P<date>(?P<year>[0-9]{4})-?W(?P<week>5[0-3]|[1-4][0-9]|0[1-9]))$", # Week date (e.g., 2008-W35-6). The hyphens are optional r"^(?P<date>(?P<year>[0-9]{4})-?W(?P<week>5[0-3]|[1-4][0-9]|0[1-9])-?(?P<day>[1-7]))$", # # Times # # Hours and minutes (e.g., 17:21). The colon is optional r"^(?P<time>(?P<hour>2[0-3]|[01][0-9]):?(?P<minute>[0-5][0-9]))$", # Hours, minutes, and seconds w/o colons (e.g., 172159) r"^(?P<time>(?P<hour>2[0-3]|[01][0-9])(?P<minute>[0-5][0-9])(?P<second>[0-5][0-9]))$", # Time zone designator (e.g., Z, +07 or +07:00). The colons and the minutes are optional r"^(?P<timezone>(Z|[+-](?:2[0-3]|[01][0-9])(?::?(?:[0-5][0-9]))?))$", # Hours, minutes, and seconds with time zone designator (e.g., 17:21:59+07:00). # All the colons are optional. The minutes in the time zone designator are also optional r"^(?P<time>(?P<hour>2[0-3]|[01][0-9])(?P<minute>[0-5][0-9])(?P<second>[0-5][0-9]))(?P<timezone>Z|[+-](?:2[0-3]|[01][0-9])(?::?(?:[0-5][0-9]))?)$", # # Date and Time # # Calendar date with hours, minutes, and seconds (e.g., 2008-08-30 17:21:59 or 20080830 172159). # A space is required between the date and the time. The hyphens and colons are optional. # This regex matches dates and times that specify some hyphens or colons but omit others. # This does not follow ISO 8601 r"^(?P<date>(?P<year>[0-9]{4})(?P<hyphen>-)?(?P<month>1[0-2]|0[1-9])(?(hyphen)-)(?P<day>3[01]|0[1-9]|[12][0-9])) (?P<time>(?P<hour>2[0-3]|[01][0-9])(?(hyphen):)(?P<minute>[0-5][0-9])(?(hyphen):)(?P<second>[0-5][0-9]))$", # # XML Schema dates and times # # Date, with optional time zone (e.g., 2008-08-30 or 2008-08-30+07:00). # Hyphens are required. This is the XML Schema 'date' type r"^(?P<date>(?P<year>-?(?:[1-9][0-9]*)?[0-9]{4})-(?P<month>1[0-2]|0[1-9])-(?P<day>3[01]|0[1-9]|[12][0-9]))(?P<timezone>Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$", # Time, with optional fractional seconds and time zone (e.g., 01:45:36 or 01:45:36.123+07:00). # There is no limit on the number of digits for the fractional seconds. This is the XML Schema 'time' type r"^(?P<time>(?P<hour>2[0-3]|[01][0-9]):(?P<minute>[0-5][0-9]):(?P<second>[0-5][0-9])(?P<frac>\.[0-9]+)?)(?P<timezone>Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$", # Date and time, with optional fractional seconds and time zone (e.g., 2008-08-30T01:45:36 or 2008-08-30T01:45:36.123Z). # This is the XML Schema 'dateTime' type r"^(?P<date>(?P<year>-?(?:[1-9][0-9]*)?[0-9]{4})-(?P<month>1[0-2]|0[1-9])-(?P<day>3[01]|0[1-9]|[12][0-9]))T(?P<time>(?P<hour>2[0-3]|[01][0-9]):(?P<minute>[0-5][0-9]):(?P<second>[0-5][0-9])(?P<ms>\.[0-9]+)?)(?P<timezone>Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$", ] if __name__ == "__main__": # pragma: no cover from .console import Console console = Console() console.print("[bold green]hello world![/bold green]") console.print("'[bold green]hello world![/bold green]'") console.print(" /foo") console.print("/foo/") console.print("/foo/bar") console.print("foo/bar/baz") console.print("/foo/bar/baz?foo=bar+egg&egg=baz") console.print("/foo/bar/baz/") console.print("/foo/bar/baz/egg") console.print("/foo/bar/baz/egg.py") console.print("/foo/bar/baz/egg.py word") console.print(" /foo/bar/baz/egg.py word") console.print("foo /foo/bar/baz/egg.py word") console.print("foo /foo/bar/ba._++z/egg+.py word") console.print("https://example.org?foo=bar#header") console.print(1234567.34) console.print(1 / 2) console.print(-1 / 123123123123) console.print( "127.0.1.1 bar 192.168.1.4 2001:0db8:85a3:0000:0000:8a2e:0370:7334 foo" ) import json console.print_json(json.dumps(obj={"name": "apple", "count": 1}), indent=None)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/_palettes.py
rich/_palettes.py
from .palette import Palette # Taken from https://en.wikipedia.org/wiki/ANSI_escape_code (Windows 10 column) WINDOWS_PALETTE = Palette( [ (12, 12, 12), (197, 15, 31), (19, 161, 14), (193, 156, 0), (0, 55, 218), (136, 23, 152), (58, 150, 221), (204, 204, 204), (118, 118, 118), (231, 72, 86), (22, 198, 12), (249, 241, 165), (59, 120, 255), (180, 0, 158), (97, 214, 214), (242, 242, 242), ] ) # # The standard ansi colors (including bright variants) STANDARD_PALETTE = Palette( [ (0, 0, 0), (170, 0, 0), (0, 170, 0), (170, 85, 0), (0, 0, 170), (170, 0, 170), (0, 170, 170), (170, 170, 170), (85, 85, 85), (255, 85, 85), (85, 255, 85), (255, 255, 85), (85, 85, 255), (255, 85, 255), (85, 255, 255), (255, 255, 255), ] ) # The 256 color palette EIGHT_BIT_PALETTE = Palette( [ (0, 0, 0), (128, 0, 0), (0, 128, 0), (128, 128, 0), (0, 0, 128), (128, 0, 128), (0, 128, 128), (192, 192, 192), (128, 128, 128), (255, 0, 0), (0, 255, 0), (255, 255, 0), (0, 0, 255), (255, 0, 255), (0, 255, 255), (255, 255, 255), (0, 0, 0), (0, 0, 95), (0, 0, 135), (0, 0, 175), (0, 0, 215), (0, 0, 255), (0, 95, 0), (0, 95, 95), (0, 95, 135), (0, 95, 175), (0, 95, 215), (0, 95, 255), (0, 135, 0), (0, 135, 95), (0, 135, 135), (0, 135, 175), (0, 135, 215), (0, 135, 255), (0, 175, 0), (0, 175, 95), (0, 175, 135), (0, 175, 175), (0, 175, 215), (0, 175, 255), (0, 215, 0), (0, 215, 95), (0, 215, 135), (0, 215, 175), (0, 215, 215), (0, 215, 255), (0, 255, 0), (0, 255, 95), (0, 255, 135), (0, 255, 175), (0, 255, 215), (0, 255, 255), (95, 0, 0), (95, 0, 95), (95, 0, 135), (95, 0, 175), (95, 0, 215), (95, 0, 255), (95, 95, 0), (95, 95, 95), (95, 95, 135), (95, 95, 175), (95, 95, 215), (95, 95, 255), (95, 135, 0), (95, 135, 95), (95, 135, 135), (95, 135, 175), (95, 135, 215), (95, 135, 255), (95, 175, 0), (95, 175, 95), (95, 175, 135), (95, 175, 175), (95, 175, 215), (95, 175, 255), (95, 215, 0), (95, 215, 95), (95, 215, 135), (95, 215, 175), (95, 215, 215), (95, 215, 255), (95, 255, 0), (95, 255, 95), (95, 255, 135), (95, 255, 175), (95, 255, 215), (95, 255, 255), (135, 0, 0), (135, 0, 95), (135, 0, 135), (135, 0, 175), (135, 0, 215), (135, 0, 255), (135, 95, 0), (135, 95, 95), (135, 95, 135), (135, 95, 175), (135, 95, 215), (135, 95, 255), (135, 135, 0), (135, 135, 95), (135, 135, 135), (135, 135, 175), (135, 135, 215), (135, 135, 255), (135, 175, 0), (135, 175, 95), (135, 175, 135), (135, 175, 175), (135, 175, 215), (135, 175, 255), (135, 215, 0), (135, 215, 95), (135, 215, 135), (135, 215, 175), (135, 215, 215), (135, 215, 255), (135, 255, 0), (135, 255, 95), (135, 255, 135), (135, 255, 175), (135, 255, 215), (135, 255, 255), (175, 0, 0), (175, 0, 95), (175, 0, 135), (175, 0, 175), (175, 0, 215), (175, 0, 255), (175, 95, 0), (175, 95, 95), (175, 95, 135), (175, 95, 175), (175, 95, 215), (175, 95, 255), (175, 135, 0), (175, 135, 95), (175, 135, 135), (175, 135, 175), (175, 135, 215), (175, 135, 255), (175, 175, 0), (175, 175, 95), (175, 175, 135), (175, 175, 175), (175, 175, 215), (175, 175, 255), (175, 215, 0), (175, 215, 95), (175, 215, 135), (175, 215, 175), (175, 215, 215), (175, 215, 255), (175, 255, 0), (175, 255, 95), (175, 255, 135), (175, 255, 175), (175, 255, 215), (175, 255, 255), (215, 0, 0), (215, 0, 95), (215, 0, 135), (215, 0, 175), (215, 0, 215), (215, 0, 255), (215, 95, 0), (215, 95, 95), (215, 95, 135), (215, 95, 175), (215, 95, 215), (215, 95, 255), (215, 135, 0), (215, 135, 95), (215, 135, 135), (215, 135, 175), (215, 135, 215), (215, 135, 255), (215, 175, 0), (215, 175, 95), (215, 175, 135), (215, 175, 175), (215, 175, 215), (215, 175, 255), (215, 215, 0), (215, 215, 95), (215, 215, 135), (215, 215, 175), (215, 215, 215), (215, 215, 255), (215, 255, 0), (215, 255, 95), (215, 255, 135), (215, 255, 175), (215, 255, 215), (215, 255, 255), (255, 0, 0), (255, 0, 95), (255, 0, 135), (255, 0, 175), (255, 0, 215), (255, 0, 255), (255, 95, 0), (255, 95, 95), (255, 95, 135), (255, 95, 175), (255, 95, 215), (255, 95, 255), (255, 135, 0), (255, 135, 95), (255, 135, 135), (255, 135, 175), (255, 135, 215), (255, 135, 255), (255, 175, 0), (255, 175, 95), (255, 175, 135), (255, 175, 175), (255, 175, 215), (255, 175, 255), (255, 215, 0), (255, 215, 95), (255, 215, 135), (255, 215, 175), (255, 215, 215), (255, 215, 255), (255, 255, 0), (255, 255, 95), (255, 255, 135), (255, 255, 175), (255, 255, 215), (255, 255, 255), (8, 8, 8), (18, 18, 18), (28, 28, 28), (38, 38, 38), (48, 48, 48), (58, 58, 58), (68, 68, 68), (78, 78, 78), (88, 88, 88), (98, 98, 98), (108, 108, 108), (118, 118, 118), (128, 128, 128), (138, 138, 138), (148, 148, 148), (158, 158, 158), (168, 168, 168), (178, 178, 178), (188, 188, 188), (198, 198, 198), (208, 208, 208), (218, 218, 218), (228, 228, 228), (238, 238, 238), ] )
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/pretty.py
rich/pretty.py
import builtins import collections import dataclasses import inspect import os import reprlib import sys from array import array from collections import Counter, UserDict, UserList, defaultdict, deque from dataclasses import dataclass, fields, is_dataclass from inspect import isclass from itertools import islice from types import MappingProxyType from typing import ( TYPE_CHECKING, Any, Callable, DefaultDict, Deque, Dict, Iterable, List, Optional, Sequence, Set, Tuple, Union, ) from rich.repr import RichReprResult try: import attr as _attr_module _has_attrs = hasattr(_attr_module, "ib") except ImportError: # pragma: no cover _has_attrs = False from . import get_console from ._loop import loop_last from ._pick import pick_bool from .abc import RichRenderable from .cells import cell_len from .highlighter import ReprHighlighter from .jupyter import JupyterMixin, JupyterRenderable from .measure import Measurement from .text import Text if TYPE_CHECKING: from .console import ( Console, ConsoleOptions, HighlighterType, JustifyMethod, OverflowMethod, RenderResult, ) def _is_attr_object(obj: Any) -> bool: """Check if an object was created with attrs module.""" return _has_attrs and _attr_module.has(type(obj)) def _get_attr_fields(obj: Any) -> Sequence["_attr_module.Attribute[Any]"]: """Get fields for an attrs object.""" return _attr_module.fields(type(obj)) if _has_attrs else [] def _is_dataclass_repr(obj: object) -> bool: """Check if an instance of a dataclass contains the default repr. Args: obj (object): A dataclass instance. Returns: bool: True if the default repr is used, False if there is a custom repr. """ # Digging in to a lot of internals here # Catching all exceptions in case something is missing on a non CPython implementation try: return obj.__repr__.__code__.co_filename in ( dataclasses.__file__, reprlib.__file__, ) except Exception: # pragma: no coverage return False _dummy_namedtuple = collections.namedtuple("_dummy_namedtuple", []) def _has_default_namedtuple_repr(obj: object) -> bool: """Check if an instance of namedtuple contains the default repr Args: obj (object): A namedtuple Returns: bool: True if the default repr is used, False if there's a custom repr. """ obj_file = None try: obj_file = inspect.getfile(obj.__repr__) except (OSError, TypeError): # OSError handles case where object is defined in __main__ scope, e.g. REPL - no filename available. # TypeError trapped defensively, in case of object without filename slips through. pass default_repr_file = inspect.getfile(_dummy_namedtuple.__repr__) return obj_file == default_repr_file def _ipy_display_hook( value: Any, console: Optional["Console"] = None, overflow: "OverflowMethod" = "ignore", crop: bool = False, indent_guides: bool = False, max_length: Optional[int] = None, max_string: Optional[int] = None, max_depth: Optional[int] = None, expand_all: bool = False, ) -> Union[str, None]: # needed here to prevent circular import: from .console import ConsoleRenderable # always skip rich generated jupyter renderables or None values if _safe_isinstance(value, JupyterRenderable) or value is None: return None console = console or get_console() with console.capture() as capture: # certain renderables should start on a new line if _safe_isinstance(value, ConsoleRenderable): console.line() console.print( ( value if _safe_isinstance(value, RichRenderable) else Pretty( value, overflow=overflow, indent_guides=indent_guides, max_length=max_length, max_string=max_string, max_depth=max_depth, expand_all=expand_all, margin=12, ) ), crop=crop, new_line_start=True, end="", ) # strip trailing newline, not usually part of a text repr # I'm not sure if this should be prevented at a lower level return capture.get().rstrip("\n") def _safe_isinstance( obj: object, class_or_tuple: Union[type, Tuple[type, ...]] ) -> bool: """isinstance can fail in rare cases, for example types with no __class__""" try: return isinstance(obj, class_or_tuple) except Exception: return False def install( console: Optional["Console"] = None, overflow: "OverflowMethod" = "ignore", crop: bool = False, indent_guides: bool = False, max_length: Optional[int] = None, max_string: Optional[int] = None, max_depth: Optional[int] = None, expand_all: bool = False, ) -> None: """Install automatic pretty printing in the Python REPL. Args: console (Console, optional): Console instance or ``None`` to use global console. Defaults to None. overflow (Optional[OverflowMethod], optional): Overflow method. Defaults to "ignore". crop (Optional[bool], optional): Enable cropping of long lines. Defaults to False. indent_guides (bool, optional): Enable indentation guides. Defaults to False. max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation. Defaults to None. max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to None. max_depth (int, optional): Maximum depth of nested data structures, or None for no maximum. Defaults to None. expand_all (bool, optional): Expand all containers. Defaults to False. max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100. """ from rich import get_console console = console or get_console() assert console is not None def display_hook(value: Any) -> None: """Replacement sys.displayhook which prettifies objects with Rich.""" if value is not None: assert console is not None builtins._ = None # type: ignore[attr-defined] console.print( ( value if _safe_isinstance(value, RichRenderable) else Pretty( value, overflow=overflow, indent_guides=indent_guides, max_length=max_length, max_string=max_string, max_depth=max_depth, expand_all=expand_all, ) ), crop=crop, ) builtins._ = value # type: ignore[attr-defined] try: ip = get_ipython() # type: ignore[name-defined] except NameError: sys.displayhook = display_hook else: from IPython.core.formatters import BaseFormatter class RichFormatter(BaseFormatter): # type: ignore[misc] pprint: bool = True def __call__(self, value: Any) -> Any: if self.pprint: return _ipy_display_hook( value, console=get_console(), overflow=overflow, indent_guides=indent_guides, max_length=max_length, max_string=max_string, max_depth=max_depth, expand_all=expand_all, ) else: return repr(value) # replace plain text formatter with rich formatter rich_formatter = RichFormatter() ip.display_formatter.formatters["text/plain"] = rich_formatter class Pretty(JupyterMixin): """A rich renderable that pretty prints an object. Args: _object (Any): An object to pretty print. highlighter (HighlighterType, optional): Highlighter object to apply to result, or None for ReprHighlighter. Defaults to None. indent_size (int, optional): Number of spaces in indent. Defaults to 4. justify (JustifyMethod, optional): Justify method, or None for default. Defaults to None. overflow (OverflowMethod, optional): Overflow method, or None for default. Defaults to None. no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to False. indent_guides (bool, optional): Enable indentation guides. Defaults to False. max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation. Defaults to None. max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to None. max_depth (int, optional): Maximum depth of nested data structures, or None for no maximum. Defaults to None. expand_all (bool, optional): Expand all containers. Defaults to False. margin (int, optional): Subtrace a margin from width to force containers to expand earlier. Defaults to 0. insert_line (bool, optional): Insert a new line if the output has multiple new lines. Defaults to False. """ def __init__( self, _object: Any, highlighter: Optional["HighlighterType"] = None, *, indent_size: int = 4, justify: Optional["JustifyMethod"] = None, overflow: Optional["OverflowMethod"] = None, no_wrap: Optional[bool] = False, indent_guides: bool = False, max_length: Optional[int] = None, max_string: Optional[int] = None, max_depth: Optional[int] = None, expand_all: bool = False, margin: int = 0, insert_line: bool = False, ) -> None: self._object = _object self.highlighter = highlighter or ReprHighlighter() self.indent_size = indent_size self.justify: Optional["JustifyMethod"] = justify self.overflow: Optional["OverflowMethod"] = overflow self.no_wrap = no_wrap self.indent_guides = indent_guides self.max_length = max_length self.max_string = max_string self.max_depth = max_depth self.expand_all = expand_all self.margin = margin self.insert_line = insert_line def __rich_console__( self, console: "Console", options: "ConsoleOptions" ) -> "RenderResult": pretty_str = pretty_repr( self._object, max_width=options.max_width - self.margin, indent_size=self.indent_size, max_length=self.max_length, max_string=self.max_string, max_depth=self.max_depth, expand_all=self.expand_all, ) pretty_text = Text.from_ansi( pretty_str, justify=self.justify or options.justify, overflow=self.overflow or options.overflow, no_wrap=pick_bool(self.no_wrap, options.no_wrap), style="pretty", ) pretty_text = ( self.highlighter(pretty_text) if pretty_text else Text( f"{type(self._object)}.__repr__ returned empty string", style="dim italic", ) ) if self.indent_guides and not options.ascii_only: pretty_text = pretty_text.with_indent_guides( self.indent_size, style="repr.indent" ) if self.insert_line and "\n" in pretty_text: yield "" yield pretty_text def __rich_measure__( self, console: "Console", options: "ConsoleOptions" ) -> "Measurement": pretty_str = pretty_repr( self._object, max_width=options.max_width, indent_size=self.indent_size, max_length=self.max_length, max_string=self.max_string, max_depth=self.max_depth, expand_all=self.expand_all, ) text_width = ( max(cell_len(line) for line in pretty_str.splitlines()) if pretty_str else 0 ) return Measurement(text_width, text_width) def _get_braces_for_defaultdict(_object: DefaultDict[Any, Any]) -> Tuple[str, str, str]: return ( f"defaultdict({_object.default_factory!r}, {{", "})", f"defaultdict({_object.default_factory!r}, {{}})", ) def _get_braces_for_deque(_object: Deque[Any]) -> Tuple[str, str, str]: if _object.maxlen is None: return ("deque([", "])", "deque()") return ( "deque([", f"], maxlen={_object.maxlen})", f"deque(maxlen={_object.maxlen})", ) def _get_braces_for_array(_object: "array[Any]") -> Tuple[str, str, str]: return (f"array({_object.typecode!r}, [", "])", f"array({_object.typecode!r})") _BRACES: Dict[type, Callable[[Any], Tuple[str, str, str]]] = { os._Environ: lambda _object: ("environ({", "})", "environ({})"), array: _get_braces_for_array, defaultdict: _get_braces_for_defaultdict, Counter: lambda _object: ("Counter({", "})", "Counter()"), deque: _get_braces_for_deque, dict: lambda _object: ("{", "}", "{}"), UserDict: lambda _object: ("{", "}", "{}"), frozenset: lambda _object: ("frozenset({", "})", "frozenset()"), list: lambda _object: ("[", "]", "[]"), UserList: lambda _object: ("[", "]", "[]"), set: lambda _object: ("{", "}", "set()"), tuple: lambda _object: ("(", ")", "()"), MappingProxyType: lambda _object: ("mappingproxy({", "})", "mappingproxy({})"), } _CONTAINERS = tuple(_BRACES.keys()) _MAPPING_CONTAINERS = (dict, os._Environ, MappingProxyType, UserDict) def is_expandable(obj: Any) -> bool: """Check if an object may be expanded by pretty print.""" return ( _safe_isinstance(obj, _CONTAINERS) or (is_dataclass(obj)) or (hasattr(obj, "__rich_repr__")) or _is_attr_object(obj) ) and not isclass(obj) @dataclass class Node: """A node in a repr tree. May be atomic or a container.""" key_repr: str = "" value_repr: str = "" open_brace: str = "" close_brace: str = "" empty: str = "" last: bool = False is_tuple: bool = False is_namedtuple: bool = False children: Optional[List["Node"]] = None key_separator: str = ": " separator: str = ", " def iter_tokens(self) -> Iterable[str]: """Generate tokens for this node.""" if self.key_repr: yield self.key_repr yield self.key_separator if self.value_repr: yield self.value_repr elif self.children is not None: if self.children: yield self.open_brace if self.is_tuple and not self.is_namedtuple and len(self.children) == 1: yield from self.children[0].iter_tokens() yield "," else: for child in self.children: yield from child.iter_tokens() if not child.last: yield self.separator yield self.close_brace else: yield self.empty def check_length(self, start_length: int, max_length: int) -> bool: """Check the length fits within a limit. Args: start_length (int): Starting length of the line (indent, prefix, suffix). max_length (int): Maximum length. Returns: bool: True if the node can be rendered within max length, otherwise False. """ total_length = start_length for token in self.iter_tokens(): total_length += cell_len(token) if total_length > max_length: return False return True def __str__(self) -> str: repr_text = "".join(self.iter_tokens()) return repr_text def render( self, max_width: int = 80, indent_size: int = 4, expand_all: bool = False ) -> str: """Render the node to a pretty repr. Args: max_width (int, optional): Maximum width of the repr. Defaults to 80. indent_size (int, optional): Size of indents. Defaults to 4. expand_all (bool, optional): Expand all levels. Defaults to False. Returns: str: A repr string of the original object. """ lines = [_Line(node=self, is_root=True)] line_no = 0 while line_no < len(lines): line = lines[line_no] if line.expandable and not line.expanded: if expand_all or not line.check_length(max_width): lines[line_no : line_no + 1] = line.expand(indent_size) line_no += 1 repr_str = "\n".join(str(line) for line in lines) return repr_str @dataclass class _Line: """A line in repr output.""" parent: Optional["_Line"] = None is_root: bool = False node: Optional[Node] = None text: str = "" suffix: str = "" whitespace: str = "" expanded: bool = False last: bool = False @property def expandable(self) -> bool: """Check if the line may be expanded.""" return bool(self.node is not None and self.node.children) def check_length(self, max_length: int) -> bool: """Check this line fits within a given number of cells.""" start_length = ( len(self.whitespace) + cell_len(self.text) + cell_len(self.suffix) ) assert self.node is not None return self.node.check_length(start_length, max_length) def expand(self, indent_size: int) -> Iterable["_Line"]: """Expand this line by adding children on their own line.""" node = self.node assert node is not None whitespace = self.whitespace assert node.children if node.key_repr: new_line = yield _Line( text=f"{node.key_repr}{node.key_separator}{node.open_brace}", whitespace=whitespace, ) else: new_line = yield _Line(text=node.open_brace, whitespace=whitespace) child_whitespace = self.whitespace + " " * indent_size tuple_of_one = node.is_tuple and len(node.children) == 1 for last, child in loop_last(node.children): separator = "," if tuple_of_one else node.separator line = _Line( parent=new_line, node=child, whitespace=child_whitespace, suffix=separator, last=last and not tuple_of_one, ) yield line yield _Line( text=node.close_brace, whitespace=whitespace, suffix=self.suffix, last=self.last, ) def __str__(self) -> str: if self.last: return f"{self.whitespace}{self.text}{self.node or ''}" else: return ( f"{self.whitespace}{self.text}{self.node or ''}{self.suffix.rstrip()}" ) def _is_namedtuple(obj: Any) -> bool: """Checks if an object is most likely a namedtuple. It is possible to craft an object that passes this check and isn't a namedtuple, but there is only a minuscule chance of this happening unintentionally. Args: obj (Any): The object to test Returns: bool: True if the object is a namedtuple. False otherwise. """ try: fields = getattr(obj, "_fields", None) except Exception: # Being very defensive - if we cannot get the attr then its not a namedtuple return False return isinstance(obj, tuple) and isinstance(fields, tuple) def traverse( _object: Any, max_length: Optional[int] = None, max_string: Optional[int] = None, max_depth: Optional[int] = None, ) -> Node: """Traverse object and generate a tree. Args: _object (Any): Object to be traversed. max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation. Defaults to None. max_string (int, optional): Maximum length of string before truncating, or None to disable truncating. Defaults to None. max_depth (int, optional): Maximum depth of data structures, or None for no maximum. Defaults to None. Returns: Node: The root of a tree structure which can be used to render a pretty repr. """ def to_repr(obj: Any) -> str: """Get repr string for an object, but catch errors.""" if ( max_string is not None and _safe_isinstance(obj, (bytes, str)) and len(obj) > max_string ): truncated = len(obj) - max_string obj_repr = f"{obj[:max_string]!r}+{truncated}" else: try: obj_repr = repr(obj) except Exception as error: obj_repr = f"<repr-error {str(error)!r}>" return obj_repr visited_ids: Set[int] = set() push_visited = visited_ids.add pop_visited = visited_ids.remove def _traverse(obj: Any, root: bool = False, depth: int = 0) -> Node: """Walk the object depth first.""" obj_id = id(obj) if obj_id in visited_ids: # Recursion detected return Node(value_repr="...") obj_type = type(obj) children: List[Node] reached_max_depth = max_depth is not None and depth >= max_depth def iter_rich_args(rich_args: Any) -> Iterable[Union[Any, Tuple[str, Any]]]: for arg in rich_args: if _safe_isinstance(arg, tuple): if len(arg) == 3: key, child, default = arg if default == child: continue yield key, child elif len(arg) == 2: key, child = arg yield key, child elif len(arg) == 1: yield arg[0] else: yield arg try: fake_attributes = hasattr( obj, "awehoi234_wdfjwljet234_234wdfoijsdfmmnxpi492" ) except Exception: fake_attributes = False rich_repr_result: Optional[RichReprResult] = None if not fake_attributes: try: if hasattr(obj, "__rich_repr__") and not isclass(obj): rich_repr_result = obj.__rich_repr__() except Exception: pass if rich_repr_result is not None: push_visited(obj_id) angular = getattr(obj.__rich_repr__, "angular", False) args = list(iter_rich_args(rich_repr_result)) class_name = obj.__class__.__name__ if args: children = [] append = children.append if reached_max_depth: if angular: node = Node(value_repr=f"<{class_name}...>") else: node = Node(value_repr=f"{class_name}(...)") else: if angular: node = Node( open_brace=f"<{class_name} ", close_brace=">", children=children, last=root, separator=" ", ) else: node = Node( open_brace=f"{class_name}(", close_brace=")", children=children, last=root, ) for last, arg in loop_last(args): if _safe_isinstance(arg, tuple): key, child = arg child_node = _traverse(child, depth=depth + 1) child_node.last = last child_node.key_repr = key child_node.key_separator = "=" append(child_node) else: child_node = _traverse(arg, depth=depth + 1) child_node.last = last append(child_node) else: node = Node( value_repr=f"<{class_name}>" if angular else f"{class_name}()", children=[], last=root, ) pop_visited(obj_id) elif _is_attr_object(obj) and not fake_attributes: push_visited(obj_id) children = [] append = children.append attr_fields = _get_attr_fields(obj) if attr_fields: if reached_max_depth: node = Node(value_repr=f"{obj.__class__.__name__}(...)") else: node = Node( open_brace=f"{obj.__class__.__name__}(", close_brace=")", children=children, last=root, ) def iter_attrs() -> ( Iterable[Tuple[str, Any, Optional[Callable[[Any], str]]]] ): """Iterate over attr fields and values.""" for attr in attr_fields: if attr.repr: try: value = getattr(obj, attr.name) except Exception as error: # Can happen, albeit rarely yield (attr.name, error, None) else: yield ( attr.name, value, attr.repr if callable(attr.repr) else None, ) for last, (name, value, repr_callable) in loop_last(iter_attrs()): if repr_callable: child_node = Node(value_repr=str(repr_callable(value))) else: child_node = _traverse(value, depth=depth + 1) child_node.last = last child_node.key_repr = name child_node.key_separator = "=" append(child_node) else: node = Node( value_repr=f"{obj.__class__.__name__}()", children=[], last=root ) pop_visited(obj_id) elif ( is_dataclass(obj) and not _safe_isinstance(obj, type) and not fake_attributes and _is_dataclass_repr(obj) ): push_visited(obj_id) children = [] append = children.append if reached_max_depth: node = Node(value_repr=f"{obj.__class__.__name__}(...)") else: node = Node( open_brace=f"{obj.__class__.__name__}(", close_brace=")", children=children, last=root, empty=f"{obj.__class__.__name__}()", ) for last, field in loop_last( field for field in fields(obj) if field.repr and hasattr(obj, field.name) ): child_node = _traverse(getattr(obj, field.name), depth=depth + 1) child_node.key_repr = field.name child_node.last = last child_node.key_separator = "=" append(child_node) pop_visited(obj_id) elif _is_namedtuple(obj) and _has_default_namedtuple_repr(obj): push_visited(obj_id) class_name = obj.__class__.__name__ if reached_max_depth: # If we've reached the max depth, we still show the class name, but not its contents node = Node( value_repr=f"{class_name}(...)", ) else: children = [] append = children.append node = Node( open_brace=f"{class_name}(", close_brace=")", children=children, empty=f"{class_name}()", ) for last, (key, value) in loop_last(obj._asdict().items()): child_node = _traverse(value, depth=depth + 1) child_node.key_repr = key child_node.last = last child_node.key_separator = "=" append(child_node) pop_visited(obj_id) elif _safe_isinstance(obj, _CONTAINERS): for container_type in _CONTAINERS: if _safe_isinstance(obj, container_type): obj_type = container_type break push_visited(obj_id) open_brace, close_brace, empty = _BRACES[obj_type](obj) if reached_max_depth: node = Node(value_repr=f"{open_brace}...{close_brace}") elif obj_type.__repr__ != type(obj).__repr__: node = Node(value_repr=to_repr(obj), last=root) elif obj: children = [] node = Node( open_brace=open_brace, close_brace=close_brace, children=children, last=root, ) append = children.append num_items = len(obj) last_item_index = num_items - 1 if _safe_isinstance(obj, _MAPPING_CONTAINERS): iter_items = iter(obj.items()) if max_length is not None: iter_items = islice(iter_items, max_length) for index, (key, child) in enumerate(iter_items): child_node = _traverse(child, depth=depth + 1) child_node.key_repr = to_repr(key) child_node.last = index == last_item_index append(child_node) else: iter_values = iter(obj) if max_length is not None: iter_values = islice(iter_values, max_length) for index, child in enumerate(iter_values): child_node = _traverse(child, depth=depth + 1) child_node.last = index == last_item_index append(child_node) if max_length is not None and num_items > max_length: append(Node(value_repr=f"... +{num_items - max_length}", last=True)) else: node = Node(empty=empty, children=[], last=root) pop_visited(obj_id) else: node = Node(value_repr=to_repr(obj), last=root) node.is_tuple = type(obj) == tuple node.is_namedtuple = _is_namedtuple(obj) return node node = _traverse(_object, root=True) return node def pretty_repr( _object: Any, *, max_width: int = 80, indent_size: int = 4, max_length: Optional[int] = None, max_string: Optional[int] = None, max_depth: Optional[int] = None, expand_all: bool = False, ) -> str: """Prettify repr string by expanding on to new lines to fit within a given width. Args: _object (Any): Object to repr. max_width (int, optional): Desired maximum width of repr string. Defaults to 80. indent_size (int, optional): Number of spaces to indent. Defaults to 4. max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation. Defaults to None. max_string (int, optional): Maximum length of string before truncating, or None to disable truncating. Defaults to None.
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
true
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/__init__.py
rich/__init__.py
"""Rich text and beautiful formatting in the terminal.""" import os from typing import IO, TYPE_CHECKING, Any, Callable, Optional, Union from ._extension import load_ipython_extension # noqa: F401 __all__ = ["get_console", "reconfigure", "print", "inspect", "print_json"] if TYPE_CHECKING: from .console import Console # Global console used by alternative print _console: Optional["Console"] = None try: _IMPORT_CWD = os.path.abspath(os.getcwd()) except FileNotFoundError: # Can happen if the cwd has been deleted _IMPORT_CWD = "" def get_console() -> "Console": """Get a global :class:`~rich.console.Console` instance. This function is used when Rich requires a Console, and hasn't been explicitly given one. Returns: Console: A console instance. """ global _console if _console is None: from .console import Console _console = Console() return _console def reconfigure(*args: Any, **kwargs: Any) -> None: """Reconfigures the global console by replacing it with another. Args: *args (Any): Positional arguments for the replacement :class:`~rich.console.Console`. **kwargs (Any): Keyword arguments for the replacement :class:`~rich.console.Console`. """ from rich.console import Console new_console = Console(*args, **kwargs) _console = get_console() _console.__dict__ = new_console.__dict__ def print( *objects: Any, sep: str = " ", end: str = "\n", file: Optional[IO[str]] = None, flush: bool = False, ) -> None: r"""Print object(s) supplied via positional arguments. This function has an identical signature to the built-in print. For more advanced features, see the :class:`~rich.console.Console` class. Args: sep (str, optional): Separator between printed objects. Defaults to " ". end (str, optional): Character to write at end of output. Defaults to "\\n". file (IO[str], optional): File to write to, or None for stdout. Defaults to None. flush (bool, optional): Has no effect as Rich always flushes output. Defaults to False. """ from .console import Console write_console = get_console() if file is None else Console(file=file) return write_console.print(*objects, sep=sep, end=end) def print_json( json: Optional[str] = None, *, data: Any = None, indent: Union[None, int, str] = 2, highlight: bool = True, skip_keys: bool = False, ensure_ascii: bool = False, check_circular: bool = True, allow_nan: bool = True, default: Optional[Callable[[Any], Any]] = None, sort_keys: bool = False, ) -> None: """Pretty prints JSON. Output will be valid JSON. Args: json (str): A string containing JSON. data (Any): If json is not supplied, then encode this data. indent (int, optional): Number of spaces to indent. Defaults to 2. highlight (bool, optional): Enable highlighting of output: Defaults to True. skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False. ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False. check_circular (bool, optional): Check for circular references. Defaults to True. allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True. default (Callable, optional): A callable that converts values that can not be encoded in to something that can be JSON encoded. Defaults to None. sort_keys (bool, optional): Sort dictionary keys. Defaults to False. """ get_console().print_json( json, data=data, indent=indent, highlight=highlight, skip_keys=skip_keys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, default=default, sort_keys=sort_keys, ) def inspect( obj: Any, *, console: Optional["Console"] = None, title: Optional[str] = None, help: bool = False, methods: bool = False, docs: bool = True, private: bool = False, dunder: bool = False, sort: bool = True, all: bool = False, value: bool = True, ) -> None: """Inspect any Python object. * inspect(<OBJECT>) to see summarized info. * inspect(<OBJECT>, methods=True) to see methods. * inspect(<OBJECT>, help=True) to see full (non-abbreviated) help. * inspect(<OBJECT>, private=True) to see private attributes (single underscore). * inspect(<OBJECT>, dunder=True) to see attributes beginning with double underscore. * inspect(<OBJECT>, all=True) to see all attributes. Args: obj (Any): An object to inspect. title (str, optional): Title to display over inspect result, or None use type. Defaults to None. help (bool, optional): Show full help text rather than just first paragraph. Defaults to False. methods (bool, optional): Enable inspection of callables. Defaults to False. docs (bool, optional): Also render doc strings. Defaults to True. private (bool, optional): Show private attributes (beginning with underscore). Defaults to False. dunder (bool, optional): Show attributes starting with double underscore. Defaults to False. sort (bool, optional): Sort attributes alphabetically. Defaults to True. all (bool, optional): Show all attributes. Defaults to False. value (bool, optional): Pretty print value. Defaults to True. """ _console = console or get_console() from rich._inspect import Inspect # Special case for inspect(inspect) is_inspect = obj is inspect _inspect = Inspect( obj, title=title, help=is_inspect or help, methods=is_inspect or methods, docs=is_inspect or docs, private=private, dunder=dunder, sort=sort, all=all, value=value, ) _console.print(_inspect) if __name__ == "__main__": # pragma: no cover print("Hello, **World**")
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/protocol.py
rich/protocol.py
from typing import Any, cast, Set, TYPE_CHECKING from inspect import isclass if TYPE_CHECKING: from rich.console import RenderableType _GIBBERISH = """aihwerij235234ljsdnp34ksodfipwoe234234jlskjdf""" def is_renderable(check_object: Any) -> bool: """Check if an object may be rendered by Rich.""" return ( isinstance(check_object, str) or hasattr(check_object, "__rich__") or hasattr(check_object, "__rich_console__") ) def rich_cast(renderable: object) -> "RenderableType": """Cast an object to a renderable by calling __rich__ if present. Args: renderable (object): A potentially renderable object Returns: object: The result of recursively calling __rich__. """ from rich.console import RenderableType rich_visited_set: Set[type] = set() # Prevent potential infinite loop while hasattr(renderable, "__rich__") and not isclass(renderable): # Detect object which claim to have all the attributes if hasattr(renderable, _GIBBERISH): return repr(renderable) cast_method = getattr(renderable, "__rich__") renderable = cast_method() renderable_type = type(renderable) if renderable_type in rich_visited_set: break rich_visited_set.add(renderable_type) return cast(RenderableType, renderable)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/emoji.py
rich/emoji.py
import sys from typing import TYPE_CHECKING, Optional, Union, Literal from .jupyter import JupyterMixin from .segment import Segment from .style import Style from ._emoji_codes import EMOJI from ._emoji_replace import _emoji_replace if TYPE_CHECKING: from .console import Console, ConsoleOptions, RenderResult EmojiVariant = Literal["emoji", "text"] class NoEmoji(Exception): """No emoji by that name.""" class Emoji(JupyterMixin): __slots__ = ["name", "style", "_char", "variant"] VARIANTS = {"text": "\uFE0E", "emoji": "\uFE0F"} def __init__( self, name: str, style: Union[str, Style] = "none", variant: Optional[EmojiVariant] = None, ) -> None: """A single emoji character. Args: name (str): Name of emoji. style (Union[str, Style], optional): Optional style. Defaults to None. Raises: NoEmoji: If the emoji doesn't exist. """ self.name = name self.style = style self.variant = variant try: self._char = EMOJI[name] except KeyError: raise NoEmoji(f"No emoji called {name!r}") if variant is not None: self._char += self.VARIANTS.get(variant, "") @classmethod def replace(cls, text: str) -> str: """Replace emoji markup with corresponding unicode characters. Args: text (str): A string with emojis codes, e.g. "Hello :smiley:!" Returns: str: A string with emoji codes replaces with actual emoji. """ return _emoji_replace(text) def __repr__(self) -> str: return f"<emoji {self.name!r}>" def __str__(self) -> str: return self._char def __rich_console__( self, console: "Console", options: "ConsoleOptions" ) -> "RenderResult": yield Segment(self._char, console.get_style(self.style)) if __name__ == "__main__": # pragma: no cover import sys from rich.columns import Columns from rich.console import Console console = Console(record=True) columns = Columns( (f":{name}: {name}" for name in sorted(EMOJI.keys()) if "\u200D" not in name), column_first=True, ) console.print(columns) if len(sys.argv) > 1: console.save_html(sys.argv[1])
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/abc.py
rich/abc.py
from abc import ABC class RichRenderable(ABC): """An abstract base class for Rich renderables. Note that there is no need to extend this class, the intended use is to check if an object supports the Rich renderable protocol. For example:: if isinstance(my_object, RichRenderable): console.print(my_object) """ @classmethod def __subclasshook__(cls, other: type) -> bool: """Check if this class supports the rich render protocol.""" return hasattr(other, "__rich_console__") or hasattr(other, "__rich__") if __name__ == "__main__": # pragma: no cover from rich.text import Text t = Text() print(isinstance(Text, RichRenderable)) print(isinstance(t, RichRenderable)) class Foo: pass f = Foo() print(isinstance(f, RichRenderable)) print(isinstance("", RichRenderable))
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/_stack.py
rich/_stack.py
from typing import List, TypeVar T = TypeVar("T") class Stack(List[T]): """A small shim over builtin list.""" @property def top(self) -> T: """Get top of stack.""" return self[-1] def push(self, item: T) -> None: """Push an item on to the stack (append in stack nomenclature).""" self.append(item)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/status.py
rich/status.py
from types import TracebackType from typing import Optional, Type from .console import Console, RenderableType from .jupyter import JupyterMixin from .live import Live from .spinner import Spinner from .style import StyleType class Status(JupyterMixin): """Displays a status indicator with a 'spinner' animation. Args: status (RenderableType): A status renderable (str or Text typically). console (Console, optional): Console instance to use, or None for global console. Defaults to None. spinner (str, optional): Name of spinner animation (see python -m rich.spinner). Defaults to "dots". spinner_style (StyleType, optional): Style of spinner. Defaults to "status.spinner". speed (float, optional): Speed factor for spinner animation. Defaults to 1.0. refresh_per_second (float, optional): Number of refreshes per second. Defaults to 12.5. """ def __init__( self, status: RenderableType, *, console: Optional[Console] = None, spinner: str = "dots", spinner_style: StyleType = "status.spinner", speed: float = 1.0, refresh_per_second: float = 12.5, ): self.status = status self.spinner_style = spinner_style self.speed = speed self._spinner = Spinner(spinner, text=status, style=spinner_style, speed=speed) self._live = Live( self.renderable, console=console, refresh_per_second=refresh_per_second, transient=True, ) @property def renderable(self) -> Spinner: return self._spinner @property def console(self) -> "Console": """Get the Console used by the Status objects.""" return self._live.console def update( self, status: Optional[RenderableType] = None, *, spinner: Optional[str] = None, spinner_style: Optional[StyleType] = None, speed: Optional[float] = None, ) -> None: """Update status. Args: status (Optional[RenderableType], optional): New status renderable or None for no change. Defaults to None. spinner (Optional[str], optional): New spinner or None for no change. Defaults to None. spinner_style (Optional[StyleType], optional): New spinner style or None for no change. Defaults to None. speed (Optional[float], optional): Speed factor for spinner animation or None for no change. Defaults to None. """ if status is not None: self.status = status if spinner_style is not None: self.spinner_style = spinner_style if speed is not None: self.speed = speed if spinner is not None: self._spinner = Spinner( spinner, text=self.status, style=self.spinner_style, speed=self.speed ) self._live.update(self.renderable, refresh=True) else: self._spinner.update( text=self.status, style=self.spinner_style, speed=self.speed ) def start(self) -> None: """Start the status animation.""" self._live.start() def stop(self) -> None: """Stop the spinner animation.""" self._live.stop() def __rich__(self) -> RenderableType: return self.renderable def __enter__(self) -> "Status": self.start() return self def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> None: self.stop() if __name__ == "__main__": # pragma: no cover from time import sleep from .console import Console console = Console() with console.status("[magenta]Covid detector booting up") as status: sleep(3) console.log("Importing advanced AI") sleep(3) console.log("Advanced Covid AI Ready") sleep(3) status.update(status="[bold blue] Scanning for Covid", spinner="earth") sleep(3) console.log("Found 10,000,000,000 copies of Covid32.exe") sleep(3) status.update( status="[bold red]Moving Covid32.exe to Trash", spinner="bouncingBall", spinner_style="yellow", ) sleep(5) console.print("[bold green]Covid deleted successfully")
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/json.py
rich/json.py
from pathlib import Path from json import loads, dumps from typing import Any, Callable, Optional, Union from .text import Text from .highlighter import JSONHighlighter, NullHighlighter class JSON: """A renderable which pretty prints JSON. Args: json (str): JSON encoded data. indent (Union[None, int, str], optional): Number of characters to indent by. Defaults to 2. highlight (bool, optional): Enable highlighting. Defaults to True. skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False. ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False. check_circular (bool, optional): Check for circular references. Defaults to True. allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True. default (Callable, optional): A callable that converts values that can not be encoded in to something that can be JSON encoded. Defaults to None. sort_keys (bool, optional): Sort dictionary keys. Defaults to False. """ def __init__( self, json: str, indent: Union[None, int, str] = 2, highlight: bool = True, skip_keys: bool = False, ensure_ascii: bool = False, check_circular: bool = True, allow_nan: bool = True, default: Optional[Callable[[Any], Any]] = None, sort_keys: bool = False, ) -> None: data = loads(json) json = dumps( data, indent=indent, skipkeys=skip_keys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, default=default, sort_keys=sort_keys, ) highlighter = JSONHighlighter() if highlight else NullHighlighter() self.text = highlighter(json) self.text.no_wrap = True self.text.overflow = None @classmethod def from_data( cls, data: Any, indent: Union[None, int, str] = 2, highlight: bool = True, skip_keys: bool = False, ensure_ascii: bool = False, check_circular: bool = True, allow_nan: bool = True, default: Optional[Callable[[Any], Any]] = None, sort_keys: bool = False, ) -> "JSON": """Encodes a JSON object from arbitrary data. Args: data (Any): An object that may be encoded in to JSON indent (Union[None, int, str], optional): Number of characters to indent by. Defaults to 2. highlight (bool, optional): Enable highlighting. Defaults to True. default (Callable, optional): Optional callable which will be called for objects that cannot be serialized. Defaults to None. skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False. ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False. check_circular (bool, optional): Check for circular references. Defaults to True. allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True. default (Callable, optional): A callable that converts values that can not be encoded in to something that can be JSON encoded. Defaults to None. sort_keys (bool, optional): Sort dictionary keys. Defaults to False. Returns: JSON: New JSON object from the given data. """ json_instance: "JSON" = cls.__new__(cls) json = dumps( data, indent=indent, skipkeys=skip_keys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, default=default, sort_keys=sort_keys, ) highlighter = JSONHighlighter() if highlight else NullHighlighter() json_instance.text = highlighter(json) json_instance.text.no_wrap = True json_instance.text.overflow = None return json_instance def __rich__(self) -> Text: return self.text if __name__ == "__main__": import argparse import sys parser = argparse.ArgumentParser(description="Pretty print json") parser.add_argument( "path", metavar="PATH", help="path to file, or - for stdin", ) parser.add_argument( "-i", "--indent", metavar="SPACES", type=int, help="Number of spaces in an indent", default=2, ) args = parser.parse_args() from rich.console import Console console = Console() error_console = Console(stderr=True) try: if args.path == "-": json_data = sys.stdin.read() else: json_data = Path(args.path).read_text() except Exception as error: error_console.print(f"Unable to read {args.path!r}; {error}") sys.exit(-1) console.print(JSON(json_data, indent=args.indent), soft_wrap=True)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/color.py
rich/color.py
import re import sys from colorsys import rgb_to_hls from enum import IntEnum from functools import lru_cache from typing import TYPE_CHECKING, NamedTuple, Optional, Tuple from ._palettes import EIGHT_BIT_PALETTE, STANDARD_PALETTE, WINDOWS_PALETTE from .color_triplet import ColorTriplet from .repr import Result, rich_repr from .terminal_theme import DEFAULT_TERMINAL_THEME if TYPE_CHECKING: # pragma: no cover from .terminal_theme import TerminalTheme from .text import Text WINDOWS = sys.platform == "win32" class ColorSystem(IntEnum): """One of the 3 color system supported by terminals.""" STANDARD = 1 EIGHT_BIT = 2 TRUECOLOR = 3 WINDOWS = 4 def __repr__(self) -> str: return f"ColorSystem.{self.name}" def __str__(self) -> str: return repr(self) class ColorType(IntEnum): """Type of color stored in Color class.""" DEFAULT = 0 STANDARD = 1 EIGHT_BIT = 2 TRUECOLOR = 3 WINDOWS = 4 def __repr__(self) -> str: return f"ColorType.{self.name}" ANSI_COLOR_NAMES = { "black": 0, "red": 1, "green": 2, "yellow": 3, "blue": 4, "magenta": 5, "cyan": 6, "white": 7, "bright_black": 8, "bright_red": 9, "bright_green": 10, "bright_yellow": 11, "bright_blue": 12, "bright_magenta": 13, "bright_cyan": 14, "bright_white": 15, "grey0": 16, "gray0": 16, "navy_blue": 17, "dark_blue": 18, "blue3": 20, "blue1": 21, "dark_green": 22, "deep_sky_blue4": 25, "dodger_blue3": 26, "dodger_blue2": 27, "green4": 28, "spring_green4": 29, "turquoise4": 30, "deep_sky_blue3": 32, "dodger_blue1": 33, "green3": 40, "spring_green3": 41, "dark_cyan": 36, "light_sea_green": 37, "deep_sky_blue2": 38, "deep_sky_blue1": 39, "spring_green2": 47, "cyan3": 43, "dark_turquoise": 44, "turquoise2": 45, "green1": 46, "spring_green1": 48, "medium_spring_green": 49, "cyan2": 50, "cyan1": 51, "dark_red": 88, "deep_pink4": 125, "purple4": 55, "purple3": 56, "blue_violet": 57, "orange4": 94, "grey37": 59, "gray37": 59, "medium_purple4": 60, "slate_blue3": 62, "royal_blue1": 63, "chartreuse4": 64, "dark_sea_green4": 71, "pale_turquoise4": 66, "steel_blue": 67, "steel_blue3": 68, "cornflower_blue": 69, "chartreuse3": 76, "cadet_blue": 73, "sky_blue3": 74, "steel_blue1": 81, "pale_green3": 114, "sea_green3": 78, "aquamarine3": 79, "medium_turquoise": 80, "chartreuse2": 112, "sea_green2": 83, "sea_green1": 85, "aquamarine1": 122, "dark_slate_gray2": 87, "dark_magenta": 91, "dark_violet": 128, "purple": 129, "light_pink4": 95, "plum4": 96, "medium_purple3": 98, "slate_blue1": 99, "yellow4": 106, "wheat4": 101, "grey53": 102, "gray53": 102, "light_slate_grey": 103, "light_slate_gray": 103, "medium_purple": 104, "light_slate_blue": 105, "dark_olive_green3": 149, "dark_sea_green": 108, "light_sky_blue3": 110, "sky_blue2": 111, "dark_sea_green3": 150, "dark_slate_gray3": 116, "sky_blue1": 117, "chartreuse1": 118, "light_green": 120, "pale_green1": 156, "dark_slate_gray1": 123, "red3": 160, "medium_violet_red": 126, "magenta3": 164, "dark_orange3": 166, "indian_red": 167, "hot_pink3": 168, "medium_orchid3": 133, "medium_orchid": 134, "medium_purple2": 140, "dark_goldenrod": 136, "light_salmon3": 173, "rosy_brown": 138, "grey63": 139, "gray63": 139, "medium_purple1": 141, "gold3": 178, "dark_khaki": 143, "navajo_white3": 144, "grey69": 145, "gray69": 145, "light_steel_blue3": 146, "light_steel_blue": 147, "yellow3": 184, "dark_sea_green2": 157, "light_cyan3": 152, "light_sky_blue1": 153, "green_yellow": 154, "dark_olive_green2": 155, "dark_sea_green1": 193, "pale_turquoise1": 159, "deep_pink3": 162, "magenta2": 200, "hot_pink2": 169, "orchid": 170, "medium_orchid1": 207, "orange3": 172, "light_pink3": 174, "pink3": 175, "plum3": 176, "violet": 177, "light_goldenrod3": 179, "tan": 180, "misty_rose3": 181, "thistle3": 182, "plum2": 183, "khaki3": 185, "light_goldenrod2": 222, "light_yellow3": 187, "grey84": 188, "gray84": 188, "light_steel_blue1": 189, "yellow2": 190, "dark_olive_green1": 192, "honeydew2": 194, "light_cyan1": 195, "red1": 196, "deep_pink2": 197, "deep_pink1": 199, "magenta1": 201, "orange_red1": 202, "indian_red1": 204, "hot_pink": 206, "dark_orange": 208, "salmon1": 209, "light_coral": 210, "pale_violet_red1": 211, "orchid2": 212, "orchid1": 213, "orange1": 214, "sandy_brown": 215, "light_salmon1": 216, "light_pink1": 217, "pink1": 218, "plum1": 219, "gold1": 220, "navajo_white1": 223, "misty_rose1": 224, "thistle1": 225, "yellow1": 226, "light_goldenrod1": 227, "khaki1": 228, "wheat1": 229, "cornsilk1": 230, "grey100": 231, "gray100": 231, "grey3": 232, "gray3": 232, "grey7": 233, "gray7": 233, "grey11": 234, "gray11": 234, "grey15": 235, "gray15": 235, "grey19": 236, "gray19": 236, "grey23": 237, "gray23": 237, "grey27": 238, "gray27": 238, "grey30": 239, "gray30": 239, "grey35": 240, "gray35": 240, "grey39": 241, "gray39": 241, "grey42": 242, "gray42": 242, "grey46": 243, "gray46": 243, "grey50": 244, "gray50": 244, "grey54": 245, "gray54": 245, "grey58": 246, "gray58": 246, "grey62": 247, "gray62": 247, "grey66": 248, "gray66": 248, "grey70": 249, "gray70": 249, "grey74": 250, "gray74": 250, "grey78": 251, "gray78": 251, "grey82": 252, "gray82": 252, "grey85": 253, "gray85": 253, "grey89": 254, "gray89": 254, "grey93": 255, "gray93": 255, } class ColorParseError(Exception): """The color could not be parsed.""" RE_COLOR = re.compile( r"""^ \#([0-9a-f]{6})$| color\(([0-9]{1,3})\)$| rgb\(([\d\s,]+)\)$ """, re.VERBOSE, ) @rich_repr class Color(NamedTuple): """Terminal color definition.""" name: str """The name of the color (typically the input to Color.parse).""" type: ColorType """The type of the color.""" number: Optional[int] = None """The color number, if a standard color, or None.""" triplet: Optional[ColorTriplet] = None """A triplet of color components, if an RGB color.""" def __rich__(self) -> "Text": """Displays the actual color if Rich printed.""" from .style import Style from .text import Text return Text.assemble( f"<color {self.name!r} ({self.type.name.lower()})", ("⬤", Style(color=self)), " >", ) def __rich_repr__(self) -> Result: yield self.name yield self.type yield "number", self.number, None yield "triplet", self.triplet, None @property def system(self) -> ColorSystem: """Get the native color system for this color.""" if self.type == ColorType.DEFAULT: return ColorSystem.STANDARD return ColorSystem(int(self.type)) @property def is_system_defined(self) -> bool: """Check if the color is ultimately defined by the system.""" return self.system not in (ColorSystem.EIGHT_BIT, ColorSystem.TRUECOLOR) @property def is_default(self) -> bool: """Check if the color is a default color.""" return self.type == ColorType.DEFAULT def get_truecolor( self, theme: Optional["TerminalTheme"] = None, foreground: bool = True ) -> ColorTriplet: """Get an equivalent color triplet for this color. Args: theme (TerminalTheme, optional): Optional terminal theme, or None to use default. Defaults to None. foreground (bool, optional): True for a foreground color, or False for background. Defaults to True. Returns: ColorTriplet: A color triplet containing RGB components. """ if theme is None: theme = DEFAULT_TERMINAL_THEME if self.type == ColorType.TRUECOLOR: assert self.triplet is not None return self.triplet elif self.type == ColorType.EIGHT_BIT: assert self.number is not None return EIGHT_BIT_PALETTE[self.number] elif self.type == ColorType.STANDARD: assert self.number is not None return theme.ansi_colors[self.number] elif self.type == ColorType.WINDOWS: assert self.number is not None return WINDOWS_PALETTE[self.number] else: # self.type == ColorType.DEFAULT: assert self.number is None return theme.foreground_color if foreground else theme.background_color @classmethod def from_ansi(cls, number: int) -> "Color": """Create a Color number from it's 8-bit ansi number. Args: number (int): A number between 0-255 inclusive. Returns: Color: A new Color instance. """ return cls( name=f"color({number})", type=(ColorType.STANDARD if number < 16 else ColorType.EIGHT_BIT), number=number, ) @classmethod def from_triplet(cls, triplet: "ColorTriplet") -> "Color": """Create a truecolor RGB color from a triplet of values. Args: triplet (ColorTriplet): A color triplet containing red, green and blue components. Returns: Color: A new color object. """ return cls(name=triplet.hex, type=ColorType.TRUECOLOR, triplet=triplet) @classmethod def from_rgb(cls, red: float, green: float, blue: float) -> "Color": """Create a truecolor from three color components in the range(0->255). Args: red (float): Red component in range 0-255. green (float): Green component in range 0-255. blue (float): Blue component in range 0-255. Returns: Color: A new color object. """ return cls.from_triplet(ColorTriplet(int(red), int(green), int(blue))) @classmethod def default(cls) -> "Color": """Get a Color instance representing the default color. Returns: Color: Default color. """ return cls(name="default", type=ColorType.DEFAULT) @classmethod @lru_cache(maxsize=1024) def parse(cls, color: str) -> "Color": """Parse a color definition.""" original_color = color color = color.lower().strip() if color == "default": return cls(color, type=ColorType.DEFAULT) color_number = ANSI_COLOR_NAMES.get(color) if color_number is not None: return cls( color, type=(ColorType.STANDARD if color_number < 16 else ColorType.EIGHT_BIT), number=color_number, ) color_match = RE_COLOR.match(color) if color_match is None: raise ColorParseError(f"{original_color!r} is not a valid color") color_24, color_8, color_rgb = color_match.groups() if color_24: triplet = ColorTriplet( int(color_24[0:2], 16), int(color_24[2:4], 16), int(color_24[4:6], 16) ) return cls(color, ColorType.TRUECOLOR, triplet=triplet) elif color_8: number = int(color_8) if number > 255: raise ColorParseError(f"color number must be <= 255 in {color!r}") return cls( color, type=(ColorType.STANDARD if number < 16 else ColorType.EIGHT_BIT), number=number, ) else: # color_rgb: components = color_rgb.split(",") if len(components) != 3: raise ColorParseError( f"expected three components in {original_color!r}" ) red, green, blue = components triplet = ColorTriplet(int(red), int(green), int(blue)) if not all(component <= 255 for component in triplet): raise ColorParseError( f"color components must be <= 255 in {original_color!r}" ) return cls(color, ColorType.TRUECOLOR, triplet=triplet) @lru_cache(maxsize=1024) def get_ansi_codes(self, foreground: bool = True) -> Tuple[str, ...]: """Get the ANSI escape codes for this color.""" _type = self.type if _type == ColorType.DEFAULT: return ("39" if foreground else "49",) elif _type == ColorType.WINDOWS: number = self.number assert number is not None fore, back = (30, 40) if number < 8 else (82, 92) return (str(fore + number if foreground else back + number),) elif _type == ColorType.STANDARD: number = self.number assert number is not None fore, back = (30, 40) if number < 8 else (82, 92) return (str(fore + number if foreground else back + number),) elif _type == ColorType.EIGHT_BIT: assert self.number is not None return ("38" if foreground else "48", "5", str(self.number)) else: # self.standard == ColorStandard.TRUECOLOR: assert self.triplet is not None red, green, blue = self.triplet return ("38" if foreground else "48", "2", str(red), str(green), str(blue)) @lru_cache(maxsize=1024) def downgrade(self, system: ColorSystem) -> "Color": """Downgrade a color system to a system with fewer colors.""" if self.type in (ColorType.DEFAULT, system): return self # Convert to 8-bit color from truecolor color if system == ColorSystem.EIGHT_BIT and self.system == ColorSystem.TRUECOLOR: assert self.triplet is not None _h, l, s = rgb_to_hls(*self.triplet.normalized) # If saturation is under 15% assume it is grayscale if s < 0.15: gray = round(l * 25.0) if gray == 0: color_number = 16 elif gray == 25: color_number = 231 else: color_number = 231 + gray return Color(self.name, ColorType.EIGHT_BIT, number=color_number) red, green, blue = self.triplet six_red = red / 95 if red < 95 else 1 + (red - 95) / 40 six_green = green / 95 if green < 95 else 1 + (green - 95) / 40 six_blue = blue / 95 if blue < 95 else 1 + (blue - 95) / 40 color_number = ( 16 + 36 * round(six_red) + 6 * round(six_green) + round(six_blue) ) return Color(self.name, ColorType.EIGHT_BIT, number=color_number) # Convert to standard from truecolor or 8-bit elif system == ColorSystem.STANDARD: if self.system == ColorSystem.TRUECOLOR: assert self.triplet is not None triplet = self.triplet else: # self.system == ColorSystem.EIGHT_BIT assert self.number is not None triplet = ColorTriplet(*EIGHT_BIT_PALETTE[self.number]) color_number = STANDARD_PALETTE.match(triplet) return Color(self.name, ColorType.STANDARD, number=color_number) elif system == ColorSystem.WINDOWS: if self.system == ColorSystem.TRUECOLOR: assert self.triplet is not None triplet = self.triplet else: # self.system == ColorSystem.EIGHT_BIT assert self.number is not None if self.number < 16: return Color(self.name, ColorType.WINDOWS, number=self.number) triplet = ColorTriplet(*EIGHT_BIT_PALETTE[self.number]) color_number = WINDOWS_PALETTE.match(triplet) return Color(self.name, ColorType.WINDOWS, number=color_number) return self def parse_rgb_hex(hex_color: str) -> ColorTriplet: """Parse six hex characters in to RGB triplet.""" assert len(hex_color) == 6, "must be 6 characters" color = ColorTriplet( int(hex_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16) ) return color def blend_rgb( color1: ColorTriplet, color2: ColorTriplet, cross_fade: float = 0.5 ) -> ColorTriplet: """Blend one RGB color in to another.""" r1, g1, b1 = color1 r2, g2, b2 = color2 new_color = ColorTriplet( int(r1 + (r2 - r1) * cross_fade), int(g1 + (g2 - g1) * cross_fade), int(b1 + (b2 - b1) * cross_fade), ) return new_color if __name__ == "__main__": # pragma: no cover from .console import Console from .table import Table from .text import Text console = Console() table = Table(show_footer=False, show_edge=True) table.add_column("Color", width=10, overflow="ellipsis") table.add_column("Number", justify="right", style="yellow") table.add_column("Name", style="green") table.add_column("Hex", style="blue") table.add_column("RGB", style="magenta") colors = sorted((v, k) for k, v in ANSI_COLOR_NAMES.items()) for color_number, name in colors: if "grey" in name: continue color_cell = Text(" " * 10, style=f"on {name}") if color_number < 16: table.add_row(color_cell, f"{color_number}", Text(f'"{name}"')) else: color = EIGHT_BIT_PALETTE[color_number] # type: ignore[has-type] table.add_row( color_cell, str(color_number), Text(f'"{name}"'), color.hex, color.rgb ) console.print(table)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/constrain.py
rich/constrain.py
from typing import Optional, TYPE_CHECKING from .jupyter import JupyterMixin from .measure import Measurement if TYPE_CHECKING: from .console import Console, ConsoleOptions, RenderableType, RenderResult class Constrain(JupyterMixin): """Constrain the width of a renderable to a given number of characters. Args: renderable (RenderableType): A renderable object. width (int, optional): The maximum width (in characters) to render. Defaults to 80. """ def __init__(self, renderable: "RenderableType", width: Optional[int] = 80) -> None: self.renderable = renderable self.width = width def __rich_console__( self, console: "Console", options: "ConsoleOptions" ) -> "RenderResult": if self.width is None: yield self.renderable else: child_options = options.update_width(min(self.width, options.max_width)) yield from console.render(self.renderable, child_options) def __rich_measure__( self, console: "Console", options: "ConsoleOptions" ) -> "Measurement": if self.width is not None: options = options.update_width(self.width) measurement = Measurement.get(console, options, self.renderable) return measurement
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/text.py
rich/text.py
import re from functools import partial, reduce from math import gcd from operator import itemgetter from typing import ( TYPE_CHECKING, Any, Callable, Dict, Iterable, List, NamedTuple, Optional, Pattern, Tuple, Union, ) from ._loop import loop_last from ._pick import pick_bool from ._wrap import divide_line from .align import AlignMethod from .cells import cell_len, set_cell_size from .containers import Lines from .control import strip_control_codes from .emoji import EmojiVariant from .jupyter import JupyterMixin from .measure import Measurement from .segment import Segment from .style import Style, StyleType if TYPE_CHECKING: # pragma: no cover from .console import Console, ConsoleOptions, JustifyMethod, OverflowMethod DEFAULT_JUSTIFY: "JustifyMethod" = "default" DEFAULT_OVERFLOW: "OverflowMethod" = "fold" _re_whitespace = re.compile(r"\s+$") TextType = Union[str, "Text"] """A plain string or a :class:`Text` instance.""" GetStyleCallable = Callable[[str], Optional[StyleType]] class Span(NamedTuple): """A marked up region in some text.""" start: int """Span start index.""" end: int """Span end index.""" style: Union[str, Style] """Style associated with the span.""" def __repr__(self) -> str: return f"Span({self.start}, {self.end}, {self.style!r})" def __bool__(self) -> bool: return self.end > self.start def split(self, offset: int) -> Tuple["Span", Optional["Span"]]: """Split a span in to 2 from a given offset.""" if offset < self.start: return self, None if offset >= self.end: return self, None start, end, style = self span1 = Span(start, min(end, offset), style) span2 = Span(span1.end, end, style) return span1, span2 def move(self, offset: int) -> "Span": """Move start and end by a given offset. Args: offset (int): Number of characters to add to start and end. Returns: TextSpan: A new TextSpan with adjusted position. """ start, end, style = self return Span(start + offset, end + offset, style) def right_crop(self, offset: int) -> "Span": """Crop the span at the given offset. Args: offset (int): A value between start and end. Returns: Span: A new (possibly smaller) span. """ start, end, style = self if offset >= end: return self return Span(start, min(offset, end), style) def extend(self, cells: int) -> "Span": """Extend the span by the given number of cells. Args: cells (int): Additional space to add to end of span. Returns: Span: A span. """ if cells: start, end, style = self return Span(start, end + cells, style) else: return self class Text(JupyterMixin): """Text with color / style. Args: text (str, optional): Default unstyled text. Defaults to "". style (Union[str, Style], optional): Base style for text. Defaults to "". justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None. overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None. no_wrap (bool, optional): Disable text wrapping, or None for default. Defaults to None. end (str, optional): Character to end text with. Defaults to "\\\\n". tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to None. spans (List[Span], optional). A list of predefined style spans. Defaults to None. """ __slots__ = [ "_text", "style", "justify", "overflow", "no_wrap", "end", "tab_size", "_spans", "_length", ] def __init__( self, text: str = "", style: Union[str, Style] = "", *, justify: Optional["JustifyMethod"] = None, overflow: Optional["OverflowMethod"] = None, no_wrap: Optional[bool] = None, end: str = "\n", tab_size: Optional[int] = None, spans: Optional[List[Span]] = None, ) -> None: sanitized_text = strip_control_codes(text) self._text = [sanitized_text] self.style = style self.justify: Optional["JustifyMethod"] = justify self.overflow: Optional["OverflowMethod"] = overflow self.no_wrap = no_wrap self.end = end self.tab_size = tab_size self._spans: List[Span] = spans or [] self._length: int = len(sanitized_text) def __len__(self) -> int: return self._length def __bool__(self) -> bool: return bool(self._length) def __str__(self) -> str: return self.plain def __repr__(self) -> str: return f"<text {self.plain!r} {self._spans!r} {self.style!r}>" def __add__(self, other: Any) -> "Text": if isinstance(other, (str, Text)): result = self.copy() result.append(other) return result return NotImplemented def __eq__(self, other: object) -> bool: if not isinstance(other, Text): return NotImplemented return self.plain == other.plain and self._spans == other._spans def __contains__(self, other: object) -> bool: if isinstance(other, str): return other in self.plain elif isinstance(other, Text): return other.plain in self.plain return False def __getitem__(self, slice: Union[int, slice]) -> "Text": def get_text_at(offset: int) -> "Text": _Span = Span text = Text( self.plain[offset], spans=[ _Span(0, 1, style) for start, end, style in self._spans if end > offset >= start ], end="", ) return text if isinstance(slice, int): return get_text_at(slice) else: start, stop, step = slice.indices(len(self.plain)) if step == 1: lines = self.divide([start, stop]) return lines[1] else: # This would be a bit of work to implement efficiently # For now, its not required raise TypeError("slices with step!=1 are not supported") @property def cell_len(self) -> int: """Get the number of cells required to render this text.""" return cell_len(self.plain) @property def markup(self) -> str: """Get console markup to render this Text. Returns: str: A string potentially creating markup tags. """ from .markup import escape output: List[str] = [] plain = self.plain markup_spans = [ (0, False, self.style), *((span.start, False, span.style) for span in self._spans), *((span.end, True, span.style) for span in self._spans), (len(plain), True, self.style), ] markup_spans.sort(key=itemgetter(0, 1)) position = 0 append = output.append for offset, closing, style in markup_spans: if offset > position: append(escape(plain[position:offset])) position = offset if style: append(f"[/{style}]" if closing else f"[{style}]") markup = "".join(output) return markup @classmethod def from_markup( cls, text: str, *, style: Union[str, Style] = "", emoji: bool = True, emoji_variant: Optional[EmojiVariant] = None, justify: Optional["JustifyMethod"] = None, overflow: Optional["OverflowMethod"] = None, end: str = "\n", ) -> "Text": """Create Text instance from markup. Args: text (str): A string containing console markup. style (Union[str, Style], optional): Base style for text. Defaults to "". emoji (bool, optional): Also render emoji code. Defaults to True. emoji_variant (str, optional): Optional emoji variant, either "text" or "emoji". Defaults to None. justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None. overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None. end (str, optional): Character to end text with. Defaults to "\\\\n". Returns: Text: A Text instance with markup rendered. """ from .markup import render rendered_text = render(text, style, emoji=emoji, emoji_variant=emoji_variant) rendered_text.justify = justify rendered_text.overflow = overflow rendered_text.end = end return rendered_text @classmethod def from_ansi( cls, text: str, *, style: Union[str, Style] = "", justify: Optional["JustifyMethod"] = None, overflow: Optional["OverflowMethod"] = None, no_wrap: Optional[bool] = None, end: str = "\n", tab_size: Optional[int] = 8, ) -> "Text": """Create a Text object from a string containing ANSI escape codes. Args: text (str): A string containing escape codes. style (Union[str, Style], optional): Base style for text. Defaults to "". justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None. overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None. no_wrap (bool, optional): Disable text wrapping, or None for default. Defaults to None. end (str, optional): Character to end text with. Defaults to "\\\\n". tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to None. """ from .ansi import AnsiDecoder joiner = Text( "\n", justify=justify, overflow=overflow, no_wrap=no_wrap, end=end, tab_size=tab_size, style=style, ) decoder = AnsiDecoder() result = joiner.join(line for line in decoder.decode(text)) return result @classmethod def styled( cls, text: str, style: StyleType = "", *, justify: Optional["JustifyMethod"] = None, overflow: Optional["OverflowMethod"] = None, ) -> "Text": """Construct a Text instance with a pre-applied styled. A style applied in this way won't be used to pad the text when it is justified. Args: text (str): A string containing console markup. style (Union[str, Style]): Style to apply to the text. Defaults to "". justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None. overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None. Returns: Text: A text instance with a style applied to the entire string. """ styled_text = cls(text, justify=justify, overflow=overflow) styled_text.stylize(style) return styled_text @classmethod def assemble( cls, *parts: Union[str, "Text", Tuple[str, StyleType]], style: Union[str, Style] = "", justify: Optional["JustifyMethod"] = None, overflow: Optional["OverflowMethod"] = None, no_wrap: Optional[bool] = None, end: str = "\n", tab_size: int = 8, meta: Optional[Dict[str, Any]] = None, ) -> "Text": """Construct a text instance by combining a sequence of strings with optional styles. The positional arguments should be either strings, or a tuple of string + style. Args: style (Union[str, Style], optional): Base style for text. Defaults to "". justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None. overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None. no_wrap (bool, optional): Disable text wrapping, or None for default. Defaults to None. end (str, optional): Character to end text with. Defaults to "\\\\n". tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to None. meta (Dict[str, Any], optional). Meta data to apply to text, or None for no meta data. Default to None Returns: Text: A new text instance. """ text = cls( style=style, justify=justify, overflow=overflow, no_wrap=no_wrap, end=end, tab_size=tab_size, ) append = text.append _Text = Text for part in parts: if isinstance(part, (_Text, str)): append(part) else: append(*part) if meta: text.apply_meta(meta) return text @property def plain(self) -> str: """Get the text as a single string.""" if len(self._text) != 1: self._text[:] = ["".join(self._text)] return self._text[0] @plain.setter def plain(self, new_text: str) -> None: """Set the text to a new value.""" if new_text != self.plain: sanitized_text = strip_control_codes(new_text) self._text[:] = [sanitized_text] old_length = self._length self._length = len(sanitized_text) if old_length > self._length: self._trim_spans() @property def spans(self) -> List[Span]: """Get a reference to the internal list of spans.""" return self._spans @spans.setter def spans(self, spans: List[Span]) -> None: """Set spans.""" self._spans = spans[:] def blank_copy(self, plain: str = "") -> "Text": """Return a new Text instance with copied metadata (but not the string or spans).""" copy_self = Text( plain, style=self.style, justify=self.justify, overflow=self.overflow, no_wrap=self.no_wrap, end=self.end, tab_size=self.tab_size, ) return copy_self def copy(self) -> "Text": """Return a copy of this instance.""" copy_self = Text( self.plain, style=self.style, justify=self.justify, overflow=self.overflow, no_wrap=self.no_wrap, end=self.end, tab_size=self.tab_size, ) copy_self._spans[:] = self._spans return copy_self def stylize( self, style: Union[str, Style], start: int = 0, end: Optional[int] = None, ) -> None: """Apply a style to the text, or a portion of the text. Args: style (Union[str, Style]): Style instance or style definition to apply. start (int): Start offset (negative indexing is supported). Defaults to 0. end (Optional[int], optional): End offset (negative indexing is supported), or None for end of text. Defaults to None. """ if style: length = len(self) if start < 0: start = length + start if end is None: end = length if end < 0: end = length + end if start >= length or end <= start: # Span not in text or not valid return self._spans.append(Span(start, min(length, end), style)) def stylize_before( self, style: Union[str, Style], start: int = 0, end: Optional[int] = None, ) -> None: """Apply a style to the text, or a portion of the text. Styles will be applied before other styles already present. Args: style (Union[str, Style]): Style instance or style definition to apply. start (int): Start offset (negative indexing is supported). Defaults to 0. end (Optional[int], optional): End offset (negative indexing is supported), or None for end of text. Defaults to None. """ if style: length = len(self) if start < 0: start = length + start if end is None: end = length if end < 0: end = length + end if start >= length or end <= start: # Span not in text or not valid return self._spans.insert(0, Span(start, min(length, end), style)) def apply_meta( self, meta: Dict[str, Any], start: int = 0, end: Optional[int] = None ) -> None: """Apply metadata to the text, or a portion of the text. Args: meta (Dict[str, Any]): A dict of meta information. start (int): Start offset (negative indexing is supported). Defaults to 0. end (Optional[int], optional): End offset (negative indexing is supported), or None for end of text. Defaults to None. """ style = Style.from_meta(meta) self.stylize(style, start=start, end=end) def on(self, meta: Optional[Dict[str, Any]] = None, **handlers: Any) -> "Text": """Apply event handlers (used by Textual project). Example: >>> from rich.text import Text >>> text = Text("hello world") >>> text.on(click="view.toggle('world')") Args: meta (Dict[str, Any]): Mapping of meta information. **handlers: Keyword args are prefixed with "@" to defined handlers. Returns: Text: Self is returned to method may be chained. """ meta = {} if meta is None else meta meta.update({f"@{key}": value for key, value in handlers.items()}) self.stylize(Style.from_meta(meta)) return self def remove_suffix(self, suffix: str) -> None: """Remove a suffix if it exists. Args: suffix (str): Suffix to remove. """ if self.plain.endswith(suffix): self.right_crop(len(suffix)) def get_style_at_offset(self, console: "Console", offset: int) -> Style: """Get the style of a character at give offset. Args: console (~Console): Console where text will be rendered. offset (int): Offset in to text (negative indexing supported) Returns: Style: A Style instance. """ # TODO: This is a little inefficient, it is only used by full justify if offset < 0: offset = len(self) + offset get_style = console.get_style style = get_style(self.style).copy() for start, end, span_style in self._spans: if end > offset >= start: style += get_style(span_style, default="") return style def extend_style(self, spaces: int) -> None: """Extend the Text given number of spaces where the spaces have the same style as the last character. Args: spaces (int): Number of spaces to add to the Text. """ if spaces <= 0: return spans = self.spans new_spaces = " " * spaces if spans: end_offset = len(self) self._spans[:] = [ span.extend(spaces) if span.end >= end_offset else span for span in spans ] self._text.append(new_spaces) self._length += spaces else: self.plain += new_spaces def highlight_regex( self, re_highlight: Union[Pattern[str], str], style: Optional[Union[GetStyleCallable, StyleType]] = None, *, style_prefix: str = "", ) -> int: """Highlight text with a regular expression, where group names are translated to styles. Args: re_highlight (Union[re.Pattern, str]): A regular expression object or string. style (Union[GetStyleCallable, StyleType]): Optional style to apply to whole match, or a callable which accepts the matched text and returns a style. Defaults to None. style_prefix (str, optional): Optional prefix to add to style group names. Returns: int: Number of regex matches """ count = 0 append_span = self._spans.append _Span = Span plain = self.plain if isinstance(re_highlight, str): re_highlight = re.compile(re_highlight) for match in re_highlight.finditer(plain): get_span = match.span if style: start, end = get_span() match_style = style(plain[start:end]) if callable(style) else style if match_style is not None and end > start: append_span(_Span(start, end, match_style)) count += 1 for name in match.groupdict().keys(): start, end = get_span(name) if start != -1 and end > start: append_span(_Span(start, end, f"{style_prefix}{name}")) return count def highlight_words( self, words: Iterable[str], style: Union[str, Style], *, case_sensitive: bool = True, ) -> int: """Highlight words with a style. Args: words (Iterable[str]): Words to highlight. style (Union[str, Style]): Style to apply. case_sensitive (bool, optional): Enable case sensitive matching. Defaults to True. Returns: int: Number of words highlighted. """ re_words = "|".join(re.escape(word) for word in words) add_span = self._spans.append count = 0 _Span = Span for match in re.finditer( re_words, self.plain, flags=0 if case_sensitive else re.IGNORECASE ): start, end = match.span(0) add_span(_Span(start, end, style)) count += 1 return count def rstrip(self) -> None: """Strip whitespace from end of text.""" self.plain = self.plain.rstrip() def rstrip_end(self, size: int) -> None: """Remove whitespace beyond a certain width at the end of the text. Args: size (int): The desired size of the text. """ text_length = len(self) if text_length > size: excess = text_length - size whitespace_match = _re_whitespace.search(self.plain) if whitespace_match is not None: whitespace_count = len(whitespace_match.group(0)) self.right_crop(min(whitespace_count, excess)) def set_length(self, new_length: int) -> None: """Set new length of the text, clipping or padding is required.""" length = len(self) if length != new_length: if length < new_length: self.pad_right(new_length - length) else: self.right_crop(length - new_length) def __rich_console__( self, console: "Console", options: "ConsoleOptions" ) -> Iterable[Segment]: tab_size: int = console.tab_size if self.tab_size is None else self.tab_size justify = self.justify or options.justify or DEFAULT_JUSTIFY overflow = self.overflow or options.overflow or DEFAULT_OVERFLOW lines = self.wrap( console, options.max_width, justify=justify, overflow=overflow, tab_size=tab_size or 8, no_wrap=pick_bool(self.no_wrap, options.no_wrap, False), ) all_lines = Text("\n").join(lines) yield from all_lines.render(console, end=self.end) def __rich_measure__( self, console: "Console", options: "ConsoleOptions" ) -> Measurement: text = self.plain lines = text.splitlines() max_text_width = max(cell_len(line) for line in lines) if lines else 0 words = text.split() min_text_width = ( max(cell_len(word) for word in words) if words else max_text_width ) return Measurement(min_text_width, max_text_width) def render(self, console: "Console", end: str = "") -> Iterable["Segment"]: """Render the text as Segments. Args: console (Console): Console instance. end (Optional[str], optional): Optional end character. Returns: Iterable[Segment]: Result of render that may be written to the console. """ _Segment = Segment text = self.plain if not self._spans: yield Segment(text) if end: yield _Segment(end) return get_style = partial(console.get_style, default=Style.null()) enumerated_spans = list(enumerate(self._spans, 1)) style_map = {index: get_style(span.style) for index, span in enumerated_spans} style_map[0] = get_style(self.style) spans = [ (0, False, 0), *((span.start, False, index) for index, span in enumerated_spans), *((span.end, True, index) for index, span in enumerated_spans), (len(text), True, 0), ] spans.sort(key=itemgetter(0, 1)) stack: List[int] = [] stack_append = stack.append stack_pop = stack.remove style_cache: Dict[Tuple[Style, ...], Style] = {} style_cache_get = style_cache.get combine = Style.combine def get_current_style() -> Style: """Construct current style from stack.""" styles = tuple(style_map[_style_id] for _style_id in sorted(stack)) cached_style = style_cache_get(styles) if cached_style is not None: return cached_style current_style = combine(styles) style_cache[styles] = current_style return current_style for (offset, leaving, style_id), (next_offset, _, _) in zip(spans, spans[1:]): if leaving: stack_pop(style_id) else: stack_append(style_id) if next_offset > offset: yield _Segment(text[offset:next_offset], get_current_style()) if end: yield _Segment(end) def join(self, lines: Iterable["Text"]) -> "Text": """Join text together with this instance as the separator. Args: lines (Iterable[Text]): An iterable of Text instances to join. Returns: Text: A new text instance containing join text. """ new_text = self.blank_copy() def iter_text() -> Iterable["Text"]: if self.plain: for last, line in loop_last(lines): yield line if not last: yield self else: yield from lines extend_text = new_text._text.extend append_span = new_text._spans.append extend_spans = new_text._spans.extend offset = 0 _Span = Span for text in iter_text(): extend_text(text._text) if text.style: append_span(_Span(offset, offset + len(text), text.style)) extend_spans( _Span(offset + start, offset + end, style) for start, end, style in text._spans ) offset += len(text) new_text._length = offset return new_text def expand_tabs(self, tab_size: Optional[int] = None) -> None: """Converts tabs to spaces. Args: tab_size (int, optional): Size of tabs. Defaults to 8. """ if "\t" not in self.plain: return if tab_size is None: tab_size = self.tab_size if tab_size is None: tab_size = 8 new_text: List[Text] = [] append = new_text.append for line in self.split("\n", include_separator=True): if "\t" not in line.plain: append(line) else: cell_position = 0 parts = line.split("\t", include_separator=True) for part in parts: if part.plain.endswith("\t"): part._text[-1] = part._text[-1][:-1] + " " cell_position += part.cell_len tab_remainder = cell_position % tab_size if tab_remainder: spaces = tab_size - tab_remainder part.extend_style(spaces) cell_position += spaces else: cell_position += part.cell_len append(part) result = Text("").join(new_text) self._text = [result.plain] self._length = len(self.plain) self._spans[:] = result._spans def truncate( self, max_width: int, *, overflow: Optional["OverflowMethod"] = None, pad: bool = False, ) -> None: """Truncate text if it is longer that a given width. Args: max_width (int): Maximum number of characters in text. overflow (str, optional): Overflow method: "crop", "fold", or "ellipsis". Defaults to None, to use self.overflow. pad (bool, optional): Pad with spaces if the length is less than max_width. Defaults to False. """ _overflow = overflow or self.overflow or DEFAULT_OVERFLOW if _overflow != "ignore": length = cell_len(self.plain) if length > max_width: if _overflow == "ellipsis": self.plain = set_cell_size(self.plain, max_width - 1) + "…" else: self.plain = set_cell_size(self.plain, max_width) if pad and length < max_width: spaces = max_width - length self._text = [f"{self.plain}{' ' * spaces}"] self._length = len(self.plain) def _trim_spans(self) -> None: """Remove or modify any spans that are over the end of the text.""" max_offset = len(self.plain) _Span = Span self._spans[:] = [ ( span if span.end < max_offset else _Span(span.start, min(max_offset, span.end), span.style) ) for span in self._spans if span.start < max_offset ] def pad(self, count: int, character: str = " ") -> None: """Pad left and right with a given number of characters. Args: count (int): Width of padding. character (str): The character to pad with. Must be a string of length 1. """ assert len(character) == 1, "Character must be a string of length 1" if count: pad_characters = character * count self.plain = f"{pad_characters}{self.plain}{pad_characters}" _Span = Span self._spans[:] = [ _Span(start + count, end + count, style) for start, end, style in self._spans ] def pad_left(self, count: int, character: str = " ") -> None: """Pad the left with a given character. Args: count (int): Number of characters to pad. character (str, optional): Character to pad with. Defaults to " ". """ assert len(character) == 1, "Character must be a string of length 1" if count: self.plain = f"{character * count}{self.plain}" _Span = Span self._spans[:] = [ _Span(start + count, end + count, style) for start, end, style in self._spans ] def pad_right(self, count: int, character: str = " ") -> None: """Pad the right with a given character. Args: count (int): Number of characters to pad. character (str, optional): Character to pad with. Defaults to " ". """ assert len(character) == 1, "Character must be a string of length 1" if count:
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
true
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/ansi.py
rich/ansi.py
import re import sys from contextlib import suppress from typing import Iterable, NamedTuple, Optional from .color import Color from .style import Style from .text import Text re_ansi = re.compile( r""" (?:\x1b[0-?])| (?:\x1b\](.*?)\x1b\\)| (?:\x1b([(@-Z\\-_]|\[[0-?]*[ -/]*[@-~])) """, re.VERBOSE, ) class _AnsiToken(NamedTuple): """Result of ansi tokenized string.""" plain: str = "" sgr: Optional[str] = "" osc: Optional[str] = "" def _ansi_tokenize(ansi_text: str) -> Iterable[_AnsiToken]: """Tokenize a string in to plain text and ANSI codes. Args: ansi_text (str): A String containing ANSI codes. Yields: AnsiToken: A named tuple of (plain, sgr, osc) """ position = 0 sgr: Optional[str] osc: Optional[str] for match in re_ansi.finditer(ansi_text): start, end = match.span(0) osc, sgr = match.groups() if start > position: yield _AnsiToken(ansi_text[position:start]) if sgr: if sgr == "(": position = end + 1 continue if sgr.endswith("m"): yield _AnsiToken("", sgr[1:-1], osc) else: yield _AnsiToken("", sgr, osc) position = end if position < len(ansi_text): yield _AnsiToken(ansi_text[position:]) SGR_STYLE_MAP = { 1: "bold", 2: "dim", 3: "italic", 4: "underline", 5: "blink", 6: "blink2", 7: "reverse", 8: "conceal", 9: "strike", 21: "underline2", 22: "not dim not bold", 23: "not italic", 24: "not underline", 25: "not blink", 26: "not blink2", 27: "not reverse", 28: "not conceal", 29: "not strike", 30: "color(0)", 31: "color(1)", 32: "color(2)", 33: "color(3)", 34: "color(4)", 35: "color(5)", 36: "color(6)", 37: "color(7)", 39: "default", 40: "on color(0)", 41: "on color(1)", 42: "on color(2)", 43: "on color(3)", 44: "on color(4)", 45: "on color(5)", 46: "on color(6)", 47: "on color(7)", 49: "on default", 51: "frame", 52: "encircle", 53: "overline", 54: "not frame not encircle", 55: "not overline", 90: "color(8)", 91: "color(9)", 92: "color(10)", 93: "color(11)", 94: "color(12)", 95: "color(13)", 96: "color(14)", 97: "color(15)", 100: "on color(8)", 101: "on color(9)", 102: "on color(10)", 103: "on color(11)", 104: "on color(12)", 105: "on color(13)", 106: "on color(14)", 107: "on color(15)", } class AnsiDecoder: """Translate ANSI code in to styled Text.""" def __init__(self) -> None: self.style = Style.null() def decode(self, terminal_text: str) -> Iterable[Text]: """Decode ANSI codes in an iterable of lines. Args: lines (Iterable[str]): An iterable of lines of terminal output. Yields: Text: Marked up Text. """ for line in terminal_text.splitlines(): yield self.decode_line(line) def decode_line(self, line: str) -> Text: """Decode a line containing ansi codes. Args: line (str): A line of terminal output. Returns: Text: A Text instance marked up according to ansi codes. """ from_ansi = Color.from_ansi from_rgb = Color.from_rgb _Style = Style text = Text() append = text.append line = line.rsplit("\r", 1)[-1] for plain_text, sgr, osc in _ansi_tokenize(line): if plain_text: append(plain_text, self.style or None) elif osc is not None: if osc.startswith("8;"): _params, semicolon, link = osc[2:].partition(";") if semicolon: self.style = self.style.update_link(link or None) elif sgr is not None: # Translate in to semi-colon separated codes # Ignore invalid codes, because we want to be lenient codes = [ min(255, int(_code) if _code else 0) for _code in sgr.split(";") if _code.isdigit() or _code == "" ] iter_codes = iter(codes) for code in iter_codes: if code == 0: # reset self.style = _Style.null() elif code in SGR_STYLE_MAP: # styles self.style += _Style.parse(SGR_STYLE_MAP[code]) elif code == 38: #  Foreground with suppress(StopIteration): color_type = next(iter_codes) if color_type == 5: self.style += _Style.from_color( from_ansi(next(iter_codes)) ) elif color_type == 2: self.style += _Style.from_color( from_rgb( next(iter_codes), next(iter_codes), next(iter_codes), ) ) elif code == 48: # Background with suppress(StopIteration): color_type = next(iter_codes) if color_type == 5: self.style += _Style.from_color( None, from_ansi(next(iter_codes)) ) elif color_type == 2: self.style += _Style.from_color( None, from_rgb( next(iter_codes), next(iter_codes), next(iter_codes), ), ) return text if sys.platform != "win32" and __name__ == "__main__": # pragma: no cover import io import os import pty import sys decoder = AnsiDecoder() stdout = io.BytesIO() def read(fd: int) -> bytes: data = os.read(fd, 1024) stdout.write(data) return data pty.spawn(sys.argv[1:], read) from .console import Console console = Console(record=True) stdout_result = stdout.getvalue().decode("utf-8") print(stdout_result) for line in decoder.decode(stdout_result): console.print(line) console.save_html("stdout.html")
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/syntax.py
rich/syntax.py
from __future__ import annotations import os.path import re import sys import textwrap from abc import ABC, abstractmethod from pathlib import Path from typing import ( Any, Dict, Iterable, List, NamedTuple, Optional, Sequence, Set, Tuple, Type, Union, ) from pygments.lexer import Lexer from pygments.lexers import get_lexer_by_name, guess_lexer_for_filename from pygments.style import Style as PygmentsStyle from pygments.styles import get_style_by_name from pygments.token import ( Comment, Error, Generic, Keyword, Name, Number, Operator, String, Token, Whitespace, ) from pygments.util import ClassNotFound from rich.containers import Lines from rich.padding import Padding, PaddingDimensions from ._loop import loop_first from .cells import cell_len from .color import Color, blend_rgb from .console import Console, ConsoleOptions, JustifyMethod, RenderResult from .jupyter import JupyterMixin from .measure import Measurement from .segment import Segment, Segments from .style import Style, StyleType from .text import Text TokenType = Tuple[str, ...] WINDOWS = sys.platform == "win32" DEFAULT_THEME = "monokai" # The following styles are based on https://github.com/pygments/pygments/blob/master/pygments/formatters/terminal.py # A few modifications were made ANSI_LIGHT: Dict[TokenType, Style] = { Token: Style(), Whitespace: Style(color="white"), Comment: Style(dim=True), Comment.Preproc: Style(color="cyan"), Keyword: Style(color="blue"), Keyword.Type: Style(color="cyan"), Operator.Word: Style(color="magenta"), Name.Builtin: Style(color="cyan"), Name.Function: Style(color="green"), Name.Namespace: Style(color="cyan", underline=True), Name.Class: Style(color="green", underline=True), Name.Exception: Style(color="cyan"), Name.Decorator: Style(color="magenta", bold=True), Name.Variable: Style(color="red"), Name.Constant: Style(color="red"), Name.Attribute: Style(color="cyan"), Name.Tag: Style(color="bright_blue"), String: Style(color="yellow"), Number: Style(color="blue"), Generic.Deleted: Style(color="bright_red"), Generic.Inserted: Style(color="green"), Generic.Heading: Style(bold=True), Generic.Subheading: Style(color="magenta", bold=True), Generic.Prompt: Style(bold=True), Generic.Error: Style(color="bright_red"), Error: Style(color="red", underline=True), } ANSI_DARK: Dict[TokenType, Style] = { Token: Style(), Whitespace: Style(color="bright_black"), Comment: Style(dim=True), Comment.Preproc: Style(color="bright_cyan"), Keyword: Style(color="bright_blue"), Keyword.Type: Style(color="bright_cyan"), Operator.Word: Style(color="bright_magenta"), Name.Builtin: Style(color="bright_cyan"), Name.Function: Style(color="bright_green"), Name.Namespace: Style(color="bright_cyan", underline=True), Name.Class: Style(color="bright_green", underline=True), Name.Exception: Style(color="bright_cyan"), Name.Decorator: Style(color="bright_magenta", bold=True), Name.Variable: Style(color="bright_red"), Name.Constant: Style(color="bright_red"), Name.Attribute: Style(color="bright_cyan"), Name.Tag: Style(color="bright_blue"), String: Style(color="yellow"), Number: Style(color="bright_blue"), Generic.Deleted: Style(color="bright_red"), Generic.Inserted: Style(color="bright_green"), Generic.Heading: Style(bold=True), Generic.Subheading: Style(color="bright_magenta", bold=True), Generic.Prompt: Style(bold=True), Generic.Error: Style(color="bright_red"), Error: Style(color="red", underline=True), } RICH_SYNTAX_THEMES = {"ansi_light": ANSI_LIGHT, "ansi_dark": ANSI_DARK} NUMBERS_COLUMN_DEFAULT_PADDING = 2 class SyntaxTheme(ABC): """Base class for a syntax theme.""" @abstractmethod def get_style_for_token(self, token_type: TokenType) -> Style: """Get a style for a given Pygments token.""" raise NotImplementedError # pragma: no cover @abstractmethod def get_background_style(self) -> Style: """Get the background color.""" raise NotImplementedError # pragma: no cover class PygmentsSyntaxTheme(SyntaxTheme): """Syntax theme that delegates to Pygments theme.""" def __init__(self, theme: Union[str, Type[PygmentsStyle]]) -> None: self._style_cache: Dict[TokenType, Style] = {} if isinstance(theme, str): try: self._pygments_style_class = get_style_by_name(theme) except ClassNotFound: self._pygments_style_class = get_style_by_name("default") else: self._pygments_style_class = theme self._background_color = self._pygments_style_class.background_color self._background_style = Style(bgcolor=self._background_color) def get_style_for_token(self, token_type: TokenType) -> Style: """Get a style from a Pygments class.""" try: return self._style_cache[token_type] except KeyError: try: pygments_style = self._pygments_style_class.style_for_token(token_type) except KeyError: style = Style.null() else: color = pygments_style["color"] bgcolor = pygments_style["bgcolor"] style = Style( color="#" + color if color else "#000000", bgcolor="#" + bgcolor if bgcolor else self._background_color, bold=pygments_style["bold"], italic=pygments_style["italic"], underline=pygments_style["underline"], ) self._style_cache[token_type] = style return style def get_background_style(self) -> Style: return self._background_style class ANSISyntaxTheme(SyntaxTheme): """Syntax theme to use standard colors.""" def __init__(self, style_map: Dict[TokenType, Style]) -> None: self.style_map = style_map self._missing_style = Style.null() self._background_style = Style.null() self._style_cache: Dict[TokenType, Style] = {} def get_style_for_token(self, token_type: TokenType) -> Style: """Look up style in the style map.""" try: return self._style_cache[token_type] except KeyError: # Styles form a hierarchy # We need to go from most to least specific # e.g. ("foo", "bar", "baz") to ("foo", "bar") to ("foo",) get_style = self.style_map.get token = tuple(token_type) style = self._missing_style while token: _style = get_style(token) if _style is not None: style = _style break token = token[:-1] self._style_cache[token_type] = style return style def get_background_style(self) -> Style: return self._background_style SyntaxPosition = Tuple[int, int] class _SyntaxHighlightRange(NamedTuple): """ A range to highlight in a Syntax object. `start` and `end` are 2-integers tuples, where the first integer is the line number (starting from 1) and the second integer is the column index (starting from 0). """ style: StyleType start: SyntaxPosition end: SyntaxPosition style_before: bool = False class PaddingProperty: """Descriptor to get and set padding.""" def __get__(self, obj: Syntax, objtype: Type[Syntax]) -> Tuple[int, int, int, int]: """Space around the Syntax.""" return obj._padding def __set__(self, obj: Syntax, padding: PaddingDimensions) -> None: obj._padding = Padding.unpack(padding) class Syntax(JupyterMixin): """Construct a Syntax object to render syntax highlighted code. Args: code (str): Code to highlight. lexer (Lexer | str): Lexer to use (see https://pygments.org/docs/lexers/) theme (str, optional): Color theme, aka Pygments style (see https://pygments.org/docs/styles/#getting-a-list-of-available-styles). Defaults to "monokai". dedent (bool, optional): Enable stripping of initial whitespace. Defaults to False. line_numbers (bool, optional): Enable rendering of line numbers. Defaults to False. start_line (int, optional): Starting number for line numbers. Defaults to 1. line_range (Tuple[int | None, int | None], optional): If given should be a tuple of the start and end line to render. A value of None in the tuple indicates the range is open in that direction. highlight_lines (Set[int]): A set of line numbers to highlight. code_width: Width of code to render (not including line numbers), or ``None`` to use all available width. tab_size (int, optional): Size of tabs. Defaults to 4. word_wrap (bool, optional): Enable word wrapping. background_color (str, optional): Optional background color, or None to use theme color. Defaults to None. indent_guides (bool, optional): Show indent guides. Defaults to False. padding (PaddingDimensions): Padding to apply around the syntax. Defaults to 0 (no padding). """ _pygments_style_class: Type[PygmentsStyle] _theme: SyntaxTheme @classmethod def get_theme(cls, name: Union[str, SyntaxTheme]) -> SyntaxTheme: """Get a syntax theme instance.""" if isinstance(name, SyntaxTheme): return name theme: SyntaxTheme if name in RICH_SYNTAX_THEMES: theme = ANSISyntaxTheme(RICH_SYNTAX_THEMES[name]) else: theme = PygmentsSyntaxTheme(name) return theme def __init__( self, code: str, lexer: Union[Lexer, str], *, theme: Union[str, SyntaxTheme] = DEFAULT_THEME, dedent: bool = False, line_numbers: bool = False, start_line: int = 1, line_range: Optional[Tuple[Optional[int], Optional[int]]] = None, highlight_lines: Optional[Set[int]] = None, code_width: Optional[int] = None, tab_size: int = 4, word_wrap: bool = False, background_color: Optional[str] = None, indent_guides: bool = False, padding: PaddingDimensions = 0, ) -> None: self.code = code self._lexer = lexer self.dedent = dedent self.line_numbers = line_numbers self.start_line = start_line self.line_range = line_range self.highlight_lines = highlight_lines or set() self.code_width = code_width self.tab_size = tab_size self.word_wrap = word_wrap self.background_color = background_color self.background_style = ( Style(bgcolor=background_color) if background_color else Style() ) self.indent_guides = indent_guides self._padding = Padding.unpack(padding) self._theme = self.get_theme(theme) self._stylized_ranges: List[_SyntaxHighlightRange] = [] padding = PaddingProperty() @classmethod def from_path( cls, path: str, encoding: str = "utf-8", lexer: Optional[Union[Lexer, str]] = None, theme: Union[str, SyntaxTheme] = DEFAULT_THEME, dedent: bool = False, line_numbers: bool = False, line_range: Optional[Tuple[int, int]] = None, start_line: int = 1, highlight_lines: Optional[Set[int]] = None, code_width: Optional[int] = None, tab_size: int = 4, word_wrap: bool = False, background_color: Optional[str] = None, indent_guides: bool = False, padding: PaddingDimensions = 0, ) -> "Syntax": """Construct a Syntax object from a file. Args: path (str): Path to file to highlight. encoding (str): Encoding of file. lexer (str | Lexer, optional): Lexer to use. If None, lexer will be auto-detected from path/file content. theme (str, optional): Color theme, aka Pygments style (see https://pygments.org/docs/styles/#getting-a-list-of-available-styles). Defaults to "emacs". dedent (bool, optional): Enable stripping of initial whitespace. Defaults to True. line_numbers (bool, optional): Enable rendering of line numbers. Defaults to False. start_line (int, optional): Starting number for line numbers. Defaults to 1. line_range (Tuple[int, int], optional): If given should be a tuple of the start and end line to render. highlight_lines (Set[int]): A set of line numbers to highlight. code_width: Width of code to render (not including line numbers), or ``None`` to use all available width. tab_size (int, optional): Size of tabs. Defaults to 4. word_wrap (bool, optional): Enable word wrapping of code. background_color (str, optional): Optional background color, or None to use theme color. Defaults to None. indent_guides (bool, optional): Show indent guides. Defaults to False. padding (PaddingDimensions): Padding to apply around the syntax. Defaults to 0 (no padding). Returns: [Syntax]: A Syntax object that may be printed to the console """ code = Path(path).read_text(encoding=encoding) if not lexer: lexer = cls.guess_lexer(path, code=code) return cls( code, lexer, theme=theme, dedent=dedent, line_numbers=line_numbers, line_range=line_range, start_line=start_line, highlight_lines=highlight_lines, code_width=code_width, tab_size=tab_size, word_wrap=word_wrap, background_color=background_color, indent_guides=indent_guides, padding=padding, ) @classmethod def guess_lexer(cls, path: str, code: Optional[str] = None) -> str: """Guess the alias of the Pygments lexer to use based on a path and an optional string of code. If code is supplied, it will use a combination of the code and the filename to determine the best lexer to use. For example, if the file is ``index.html`` and the file contains Django templating syntax, then "html+django" will be returned. If the file is ``index.html``, and no templating language is used, the "html" lexer will be used. If no string of code is supplied, the lexer will be chosen based on the file extension.. Args: path (AnyStr): The path to the file containing the code you wish to know the lexer for. code (str, optional): Optional string of code that will be used as a fallback if no lexer is found for the supplied path. Returns: str: The name of the Pygments lexer that best matches the supplied path/code. """ lexer: Optional[Lexer] = None lexer_name = "default" if code: try: lexer = guess_lexer_for_filename(path, code) except ClassNotFound: pass if not lexer: try: _, ext = os.path.splitext(path) if ext: extension = ext.lstrip(".").lower() lexer = get_lexer_by_name(extension) except ClassNotFound: pass if lexer: if lexer.aliases: lexer_name = lexer.aliases[0] else: lexer_name = lexer.name return lexer_name def _get_base_style(self) -> Style: """Get the base style.""" default_style = self._theme.get_background_style() + self.background_style return default_style def _get_token_color(self, token_type: TokenType) -> Optional[Color]: """Get a color (if any) for the given token. Args: token_type (TokenType): A token type tuple from Pygments. Returns: Optional[Color]: Color from theme, or None for no color. """ style = self._theme.get_style_for_token(token_type) return style.color @property def lexer(self) -> Optional[Lexer]: """The lexer for this syntax, or None if no lexer was found. Tries to find the lexer by name if a string was passed to the constructor. """ if isinstance(self._lexer, Lexer): return self._lexer try: return get_lexer_by_name( self._lexer, stripnl=False, ensurenl=True, tabsize=self.tab_size, ) except ClassNotFound: return None @property def default_lexer(self) -> Lexer: """A Pygments Lexer to use if one is not specified or invalid.""" return get_lexer_by_name( "text", stripnl=False, ensurenl=True, tabsize=self.tab_size, ) def highlight( self, code: str, line_range: Optional[Tuple[Optional[int], Optional[int]]] = None, ) -> Text: """Highlight code and return a Text instance. Args: code (str): Code to highlight. line_range(Tuple[int, int], optional): Optional line range to highlight. Returns: Text: A text instance containing highlighted syntax. """ base_style = self._get_base_style() justify: JustifyMethod = ( "default" if base_style.transparent_background else "left" ) text = Text( justify=justify, style=base_style, tab_size=self.tab_size, no_wrap=not self.word_wrap, ) _get_theme_style = self._theme.get_style_for_token lexer = self.lexer or self.default_lexer if lexer is None: text.append(code) else: if line_range: # More complicated path to only stylize a portion of the code # This speeds up further operations as there are less spans to process line_start, line_end = line_range def line_tokenize() -> Iterable[Tuple[Any, str]]: """Split tokens to one per line.""" assert lexer # required to make MyPy happy - we know lexer is not None at this point for token_type, token in lexer.get_tokens(code): while token: line_token, new_line, token = token.partition("\n") yield token_type, line_token + new_line def tokens_to_spans() -> Iterable[Tuple[str, Optional[Style]]]: """Convert tokens to spans.""" tokens = iter(line_tokenize()) line_no = 0 _line_start = line_start - 1 if line_start else 0 # Skip over tokens until line start while line_no < _line_start: try: _token_type, token = next(tokens) except StopIteration: break yield (token, None) if token.endswith("\n"): line_no += 1 # Generate spans until line end for token_type, token in tokens: yield (token, _get_theme_style(token_type)) if token.endswith("\n"): line_no += 1 if line_end and line_no >= line_end: break text.append_tokens(tokens_to_spans()) else: text.append_tokens( (token, _get_theme_style(token_type)) for token_type, token in lexer.get_tokens(code) ) if self.background_color is not None: text.stylize(f"on {self.background_color}") if self._stylized_ranges: self._apply_stylized_ranges(text) return text def stylize_range( self, style: StyleType, start: SyntaxPosition, end: SyntaxPosition, style_before: bool = False, ) -> None: """ Adds a custom style on a part of the code, that will be applied to the syntax display when it's rendered. Line numbers are 1-based, while column indexes are 0-based. Args: style (StyleType): The style to apply. start (Tuple[int, int]): The start of the range, in the form `[line number, column index]`. end (Tuple[int, int]): The end of the range, in the form `[line number, column index]`. style_before (bool): Apply the style before any existing styles. """ self._stylized_ranges.append( _SyntaxHighlightRange(style, start, end, style_before) ) def _get_line_numbers_color(self, blend: float = 0.3) -> Color: background_style = self._theme.get_background_style() + self.background_style background_color = background_style.bgcolor if background_color is None or background_color.is_system_defined: return Color.default() foreground_color = self._get_token_color(Token.Text) if foreground_color is None or foreground_color.is_system_defined: return foreground_color or Color.default() new_color = blend_rgb( background_color.get_truecolor(), foreground_color.get_truecolor(), cross_fade=blend, ) return Color.from_triplet(new_color) @property def _numbers_column_width(self) -> int: """Get the number of characters used to render the numbers column.""" column_width = 0 if self.line_numbers: column_width = ( len(str(self.start_line + self.code.count("\n"))) + NUMBERS_COLUMN_DEFAULT_PADDING ) return column_width def _get_number_styles(self, console: Console) -> Tuple[Style, Style, Style]: """Get background, number, and highlight styles for line numbers.""" background_style = self._get_base_style() if background_style.transparent_background: return Style.null(), Style(dim=True), Style.null() if console.color_system in ("256", "truecolor"): number_style = Style.chain( background_style, self._theme.get_style_for_token(Token.Text), Style(color=self._get_line_numbers_color()), self.background_style, ) highlight_number_style = Style.chain( background_style, self._theme.get_style_for_token(Token.Text), Style(bold=True, color=self._get_line_numbers_color(0.9)), self.background_style, ) else: number_style = background_style + Style(dim=True) highlight_number_style = background_style + Style(dim=False) return background_style, number_style, highlight_number_style def __rich_measure__( self, console: "Console", options: "ConsoleOptions" ) -> "Measurement": _, right, _, left = self.padding padding = left + right if self.code_width is not None: width = self.code_width + self._numbers_column_width + padding + 1 return Measurement(self._numbers_column_width, width) lines = self.code.splitlines() width = ( self._numbers_column_width + padding + (max(cell_len(line) for line in lines) if lines else 0) ) if self.line_numbers: width += 1 return Measurement(self._numbers_column_width, width) def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: segments = Segments(self._get_syntax(console, options)) if any(self.padding): yield Padding(segments, style=self._get_base_style(), pad=self.padding) else: yield segments def _get_syntax( self, console: Console, options: ConsoleOptions, ) -> Iterable[Segment]: """ Get the Segments for the Syntax object, excluding any vertical/horizontal padding """ transparent_background = self._get_base_style().transparent_background _pad_top, pad_right, _pad_bottom, pad_left = self.padding horizontal_padding = pad_left + pad_right code_width = ( ( (options.max_width - self._numbers_column_width - 1) if self.line_numbers else options.max_width ) - horizontal_padding if self.code_width is None else self.code_width ) code_width = max(0, code_width) ends_on_nl, processed_code = self._process_code(self.code) text = self.highlight(processed_code, self.line_range) if not self.line_numbers and not self.word_wrap and not self.line_range: if not ends_on_nl: text.remove_suffix("\n") # Simple case of just rendering text style = ( self._get_base_style() + self._theme.get_style_for_token(Comment) + Style(dim=True) + self.background_style ) if self.indent_guides and not options.ascii_only: text = text.with_indent_guides(self.tab_size, style=style) text.overflow = "crop" if style.transparent_background: yield from console.render( text, options=options.update(width=code_width) ) else: syntax_lines = console.render_lines( text, options.update(width=code_width, height=None, justify="left"), style=self.background_style, pad=True, new_lines=True, ) for syntax_line in syntax_lines: yield from syntax_line return start_line, end_line = self.line_range or (None, None) line_offset = 0 if start_line: line_offset = max(0, start_line - 1) lines: Union[List[Text], Lines] = text.split("\n", allow_blank=ends_on_nl) if self.line_range: if line_offset > len(lines): return lines = lines[line_offset:end_line] if self.indent_guides and not options.ascii_only: style = ( self._get_base_style() + self._theme.get_style_for_token(Comment) + Style(dim=True) + self.background_style ) lines = ( Text("\n") .join(lines) .with_indent_guides(self.tab_size, style=style + Style(italic=False)) .split("\n", allow_blank=True) ) numbers_column_width = self._numbers_column_width render_options = options.update(width=code_width) highlight_line = self.highlight_lines.__contains__ _Segment = Segment new_line = _Segment("\n") line_pointer = "> " if options.legacy_windows else "❱ " ( background_style, number_style, highlight_number_style, ) = self._get_number_styles(console) for line_no, line in enumerate(lines, self.start_line + line_offset): if self.word_wrap: wrapped_lines = console.render_lines( line, render_options.update(height=None, justify="left"), style=background_style, pad=not transparent_background, ) else: segments = list(line.render(console, end="")) if options.no_wrap: wrapped_lines = [segments] else: wrapped_lines = [ _Segment.adjust_line_length( segments, render_options.max_width, style=background_style, pad=not transparent_background, ) ] if self.line_numbers: wrapped_line_left_pad = _Segment( " " * numbers_column_width + " ", background_style ) for first, wrapped_line in loop_first(wrapped_lines): if first: line_column = str(line_no).rjust(numbers_column_width - 2) + " " if highlight_line(line_no): yield _Segment(line_pointer, Style(color="red")) yield _Segment(line_column, highlight_number_style) else: yield _Segment(" ", highlight_number_style) yield _Segment(line_column, number_style) else: yield wrapped_line_left_pad yield from wrapped_line yield new_line else: for wrapped_line in wrapped_lines: yield from wrapped_line yield new_line def _apply_stylized_ranges(self, text: Text) -> None: """ Apply stylized ranges to a text instance, using the given code to determine the right portion to apply the style to. Args: text (Text): Text instance to apply the style to. """ code = text.plain newlines_offsets = [ # Let's add outer boundaries at each side of the list: 0, # N.B. using "\n" here is much faster than using metacharacters such as "^" or "\Z": *[ match.start() + 1 for match in re.finditer("\n", code, flags=re.MULTILINE) ], len(code) + 1, ] for stylized_range in self._stylized_ranges: start = _get_code_index_for_syntax_position( newlines_offsets, stylized_range.start ) end = _get_code_index_for_syntax_position( newlines_offsets, stylized_range.end ) if start is not None and end is not None: if stylized_range.style_before: text.stylize_before(stylized_range.style, start, end) else: text.stylize(stylized_range.style, start, end) def _process_code(self, code: str) -> Tuple[bool, str]: """ Applies various processing to a raw code string (normalises it so it always ends with a line return, dedents it if necessary, etc.) Args: code (str): The raw code string to process Returns: Tuple[bool, str]: the boolean indicates whether the raw code ends with a line return, while the string is the processed code. """ ends_on_nl = code.endswith("\n") processed_code = code if ends_on_nl else code + "\n" processed_code = ( textwrap.dedent(processed_code) if self.dedent else processed_code ) processed_code = processed_code.expandtabs(self.tab_size) return ends_on_nl, processed_code def _get_code_index_for_syntax_position( newlines_offsets: Sequence[int], position: SyntaxPosition ) -> Optional[int]: """ Returns the index of the code string for the given positions. Args: newlines_offsets (Sequence[int]): The offset of each newline character found in the code snippet. position (SyntaxPosition): The position to search for. Returns: Optional[int]: The index of the code string for this position, or `None` if the given position's line number is out of range (if it's the column that is out of range we silently clamp its value so that it reaches the end of the line) """ lines_count = len(newlines_offsets) line_number, column_index = position if line_number > lines_count or len(newlines_offsets) < (line_number + 1):
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
true
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/_cell_widths.py
rich/_cell_widths.py
# Auto generated by make_terminal_widths.py CELL_WIDTHS = [ (0, 0, 0), (1, 31, -1), (127, 159, -1), (173, 173, 0), (768, 879, 0), (1155, 1161, 0), (1425, 1469, 0), (1471, 1471, 0), (1473, 1474, 0), (1476, 1477, 0), (1479, 1479, 0), (1536, 1541, 0), (1552, 1562, 0), (1564, 1564, 0), (1611, 1631, 0), (1648, 1648, 0), (1750, 1757, 0), (1759, 1764, 0), (1767, 1768, 0), (1770, 1773, 0), (1807, 1807, 0), (1809, 1809, 0), (1840, 1866, 0), (1958, 1968, 0), (2027, 2035, 0), (2045, 2045, 0), (2070, 2073, 0), (2075, 2083, 0), (2085, 2087, 0), (2089, 2093, 0), (2137, 2139, 0), (2192, 2193, 0), (2200, 2207, 0), (2250, 2307, 0), (2362, 2364, 0), (2366, 2383, 0), (2385, 2391, 0), (2402, 2403, 0), (2433, 2435, 0), (2492, 2492, 0), (2494, 2500, 0), (2503, 2504, 0), (2507, 2509, 0), (2519, 2519, 0), (2530, 2531, 0), (2558, 2558, 0), (2561, 2563, 0), (2620, 2620, 0), (2622, 2626, 0), (2631, 2632, 0), (2635, 2637, 0), (2641, 2641, 0), (2672, 2673, 0), (2677, 2677, 0), (2689, 2691, 0), (2748, 2748, 0), (2750, 2757, 0), (2759, 2761, 0), (2763, 2765, 0), (2786, 2787, 0), (2810, 2815, 0), (2817, 2819, 0), (2876, 2876, 0), (2878, 2884, 0), (2887, 2888, 0), (2891, 2893, 0), (2901, 2903, 0), (2914, 2915, 0), (2946, 2946, 0), (3006, 3010, 0), (3014, 3016, 0), (3018, 3021, 0), (3031, 3031, 0), (3072, 3076, 0), (3132, 3132, 0), (3134, 3140, 0), (3142, 3144, 0), (3146, 3149, 0), (3157, 3158, 0), (3170, 3171, 0), (3201, 3203, 0), (3260, 3260, 0), (3262, 3268, 0), (3270, 3272, 0), (3274, 3277, 0), (3285, 3286, 0), (3298, 3299, 0), (3315, 3315, 0), (3328, 3331, 0), (3387, 3388, 0), (3390, 3396, 0), (3398, 3400, 0), (3402, 3405, 0), (3415, 3415, 0), (3426, 3427, 0), (3457, 3459, 0), (3530, 3530, 0), (3535, 3540, 0), (3542, 3542, 0), (3544, 3551, 0), (3570, 3571, 0), (3633, 3633, 0), (3636, 3642, 0), (3655, 3662, 0), (3761, 3761, 0), (3764, 3772, 0), (3784, 3790, 0), (3864, 3865, 0), (3893, 3893, 0), (3895, 3895, 0), (3897, 3897, 0), (3902, 3903, 0), (3953, 3972, 0), (3974, 3975, 0), (3981, 3991, 0), (3993, 4028, 0), (4038, 4038, 0), (4139, 4158, 0), (4182, 4185, 0), (4190, 4192, 0), (4194, 4196, 0), (4199, 4205, 0), (4209, 4212, 0), (4226, 4237, 0), (4239, 4239, 0), (4250, 4253, 0), (4352, 4447, 2), (4448, 4607, 0), (4957, 4959, 0), (5906, 5909, 0), (5938, 5940, 0), (5970, 5971, 0), (6002, 6003, 0), (6068, 6099, 0), (6109, 6109, 0), (6155, 6159, 0), (6277, 6278, 0), (6313, 6313, 0), (6432, 6443, 0), (6448, 6459, 0), (6679, 6683, 0), (6741, 6750, 0), (6752, 6780, 0), (6783, 6783, 0), (6832, 6862, 0), (6912, 6916, 0), (6964, 6980, 0), (7019, 7027, 0), (7040, 7042, 0), (7073, 7085, 0), (7142, 7155, 0), (7204, 7223, 0), (7376, 7378, 0), (7380, 7400, 0), (7405, 7405, 0), (7412, 7412, 0), (7415, 7417, 0), (7616, 7679, 0), (8203, 8207, 0), (8232, 8238, 0), (8288, 8292, 0), (8294, 8303, 0), (8400, 8432, 0), (8986, 8987, 2), (9001, 9002, 2), (9193, 9196, 2), (9200, 9200, 2), (9203, 9203, 2), (9725, 9726, 2), (9748, 9749, 2), (9800, 9811, 2), (9855, 9855, 2), (9875, 9875, 2), (9889, 9889, 2), (9898, 9899, 2), (9917, 9918, 2), (9924, 9925, 2), (9934, 9934, 2), (9940, 9940, 2), (9962, 9962, 2), (9970, 9971, 2), (9973, 9973, 2), (9978, 9978, 2), (9981, 9981, 2), (9989, 9989, 2), (9994, 9995, 2), (10024, 10024, 2), (10060, 10060, 2), (10062, 10062, 2), (10067, 10069, 2), (10071, 10071, 2), (10133, 10135, 2), (10160, 10160, 2), (10175, 10175, 2), (11035, 11036, 2), (11088, 11088, 2), (11093, 11093, 2), (11503, 11505, 0), (11647, 11647, 0), (11744, 11775, 0), (11904, 11929, 2), (11931, 12019, 2), (12032, 12245, 2), (12272, 12329, 2), (12330, 12335, 0), (12336, 12350, 2), (12353, 12438, 2), (12441, 12442, 0), (12443, 12543, 2), (12549, 12591, 2), (12593, 12686, 2), (12688, 12771, 2), (12783, 12830, 2), (12832, 12871, 2), (12880, 19903, 2), (19968, 42124, 2), (42128, 42182, 2), (42607, 42610, 0), (42612, 42621, 0), (42654, 42655, 0), (42736, 42737, 0), (43010, 43010, 0), (43014, 43014, 0), (43019, 43019, 0), (43043, 43047, 0), (43052, 43052, 0), (43136, 43137, 0), (43188, 43205, 0), (43232, 43249, 0), (43263, 43263, 0), (43302, 43309, 0), (43335, 43347, 0), (43360, 43388, 2), (43392, 43395, 0), (43443, 43456, 0), (43493, 43493, 0), (43561, 43574, 0), (43587, 43587, 0), (43596, 43597, 0), (43643, 43645, 0), (43696, 43696, 0), (43698, 43700, 0), (43703, 43704, 0), (43710, 43711, 0), (43713, 43713, 0), (43755, 43759, 0), (43765, 43766, 0), (44003, 44010, 0), (44012, 44013, 0), (44032, 55203, 2), (55216, 55295, 0), (63744, 64255, 2), (64286, 64286, 0), (65024, 65039, 0), (65040, 65049, 2), (65056, 65071, 0), (65072, 65106, 2), (65108, 65126, 2), (65128, 65131, 2), (65279, 65279, 0), (65281, 65376, 2), (65504, 65510, 2), (65529, 65531, 0), (66045, 66045, 0), (66272, 66272, 0), (66422, 66426, 0), (68097, 68099, 0), (68101, 68102, 0), (68108, 68111, 0), (68152, 68154, 0), (68159, 68159, 0), (68325, 68326, 0), (68900, 68903, 0), (69291, 69292, 0), (69373, 69375, 0), (69446, 69456, 0), (69506, 69509, 0), (69632, 69634, 0), (69688, 69702, 0), (69744, 69744, 0), (69747, 69748, 0), (69759, 69762, 0), (69808, 69818, 0), (69821, 69821, 0), (69826, 69826, 0), (69837, 69837, 0), (69888, 69890, 0), (69927, 69940, 0), (69957, 69958, 0), (70003, 70003, 0), (70016, 70018, 0), (70067, 70080, 0), (70089, 70092, 0), (70094, 70095, 0), (70188, 70199, 0), (70206, 70206, 0), (70209, 70209, 0), (70367, 70378, 0), (70400, 70403, 0), (70459, 70460, 0), (70462, 70468, 0), (70471, 70472, 0), (70475, 70477, 0), (70487, 70487, 0), (70498, 70499, 0), (70502, 70508, 0), (70512, 70516, 0), (70709, 70726, 0), (70750, 70750, 0), (70832, 70851, 0), (71087, 71093, 0), (71096, 71104, 0), (71132, 71133, 0), (71216, 71232, 0), (71339, 71351, 0), (71453, 71467, 0), (71724, 71738, 0), (71984, 71989, 0), (71991, 71992, 0), (71995, 71998, 0), (72000, 72000, 0), (72002, 72003, 0), (72145, 72151, 0), (72154, 72160, 0), (72164, 72164, 0), (72193, 72202, 0), (72243, 72249, 0), (72251, 72254, 0), (72263, 72263, 0), (72273, 72283, 0), (72330, 72345, 0), (72751, 72758, 0), (72760, 72767, 0), (72850, 72871, 0), (72873, 72886, 0), (73009, 73014, 0), (73018, 73018, 0), (73020, 73021, 0), (73023, 73029, 0), (73031, 73031, 0), (73098, 73102, 0), (73104, 73105, 0), (73107, 73111, 0), (73459, 73462, 0), (73472, 73473, 0), (73475, 73475, 0), (73524, 73530, 0), (73534, 73538, 0), (78896, 78912, 0), (78919, 78933, 0), (92912, 92916, 0), (92976, 92982, 0), (94031, 94031, 0), (94033, 94087, 0), (94095, 94098, 0), (94176, 94179, 2), (94180, 94180, 0), (94192, 94193, 0), (94208, 100343, 2), (100352, 101589, 2), (101632, 101640, 2), (110576, 110579, 2), (110581, 110587, 2), (110589, 110590, 2), (110592, 110882, 2), (110898, 110898, 2), (110928, 110930, 2), (110933, 110933, 2), (110948, 110951, 2), (110960, 111355, 2), (113821, 113822, 0), (113824, 113827, 0), (118528, 118573, 0), (118576, 118598, 0), (119141, 119145, 0), (119149, 119170, 0), (119173, 119179, 0), (119210, 119213, 0), (119362, 119364, 0), (121344, 121398, 0), (121403, 121452, 0), (121461, 121461, 0), (121476, 121476, 0), (121499, 121503, 0), (121505, 121519, 0), (122880, 122886, 0), (122888, 122904, 0), (122907, 122913, 0), (122915, 122916, 0), (122918, 122922, 0), (123023, 123023, 0), (123184, 123190, 0), (123566, 123566, 0), (123628, 123631, 0), (124140, 124143, 0), (125136, 125142, 0), (125252, 125258, 0), (126980, 126980, 2), (127183, 127183, 2), (127374, 127374, 2), (127377, 127386, 2), (127488, 127490, 2), (127504, 127547, 2), (127552, 127560, 2), (127568, 127569, 2), (127584, 127589, 2), (127744, 127776, 2), (127789, 127797, 2), (127799, 127868, 2), (127870, 127891, 2), (127904, 127946, 2), (127951, 127955, 2), (127968, 127984, 2), (127988, 127988, 2), (127992, 127994, 2), (127995, 127999, 0), (128000, 128062, 2), (128064, 128064, 2), (128066, 128252, 2), (128255, 128317, 2), (128331, 128334, 2), (128336, 128359, 2), (128378, 128378, 2), (128405, 128406, 2), (128420, 128420, 2), (128507, 128591, 2), (128640, 128709, 2), (128716, 128716, 2), (128720, 128722, 2), (128725, 128727, 2), (128732, 128735, 2), (128747, 128748, 2), (128756, 128764, 2), (128992, 129003, 2), (129008, 129008, 2), (129292, 129338, 2), (129340, 129349, 2), (129351, 129535, 2), (129648, 129660, 2), (129664, 129672, 2), (129680, 129725, 2), (129727, 129733, 2), (129742, 129755, 2), (129760, 129768, 2), (129776, 129784, 2), (131072, 196605, 2), (196608, 262141, 2), (917505, 917505, 0), (917536, 917631, 0), (917760, 917999, 0), ]
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/progress_bar.py
rich/progress_bar.py
import math from functools import lru_cache from time import monotonic from typing import Iterable, List, Optional from .color import Color, blend_rgb from .color_triplet import ColorTriplet from .console import Console, ConsoleOptions, RenderResult from .jupyter import JupyterMixin from .measure import Measurement from .segment import Segment from .style import Style, StyleType # Number of characters before 'pulse' animation repeats PULSE_SIZE = 20 class ProgressBar(JupyterMixin): """Renders a (progress) bar. Used by rich.progress. Args: total (float, optional): Number of steps in the bar. Defaults to 100. Set to None to render a pulsing animation. completed (float, optional): Number of steps completed. Defaults to 0. width (int, optional): Width of the bar, or ``None`` for maximum width. Defaults to None. pulse (bool, optional): Enable pulse effect. Defaults to False. Will pulse if a None total was passed. style (StyleType, optional): Style for the bar background. Defaults to "bar.back". complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete". finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished". pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse". animation_time (Optional[float], optional): Time in seconds to use for animation, or None to use system time. """ def __init__( self, total: Optional[float] = 100.0, completed: float = 0, width: Optional[int] = None, pulse: bool = False, style: StyleType = "bar.back", complete_style: StyleType = "bar.complete", finished_style: StyleType = "bar.finished", pulse_style: StyleType = "bar.pulse", animation_time: Optional[float] = None, ): self.total = total self.completed = completed self.width = width self.pulse = pulse self.style = style self.complete_style = complete_style self.finished_style = finished_style self.pulse_style = pulse_style self.animation_time = animation_time self._pulse_segments: Optional[List[Segment]] = None def __repr__(self) -> str: return f"<Bar {self.completed!r} of {self.total!r}>" @property def percentage_completed(self) -> Optional[float]: """Calculate percentage complete.""" if self.total is None: return None completed = (self.completed / self.total) * 100.0 completed = min(100, max(0.0, completed)) return completed @lru_cache(maxsize=16) def _get_pulse_segments( self, fore_style: Style, back_style: Style, color_system: str, no_color: bool, ascii: bool = False, ) -> List[Segment]: """Get a list of segments to render a pulse animation. Returns: List[Segment]: A list of segments, one segment per character. """ bar = "-" if ascii else "━" segments: List[Segment] = [] if color_system not in ("standard", "eight_bit", "truecolor") or no_color: segments += [Segment(bar, fore_style)] * (PULSE_SIZE // 2) segments += [Segment(" " if no_color else bar, back_style)] * ( PULSE_SIZE - (PULSE_SIZE // 2) ) return segments append = segments.append fore_color = ( fore_style.color.get_truecolor() if fore_style.color else ColorTriplet(255, 0, 255) ) back_color = ( back_style.color.get_truecolor() if back_style.color else ColorTriplet(0, 0, 0) ) cos = math.cos pi = math.pi _Segment = Segment _Style = Style from_triplet = Color.from_triplet for index in range(PULSE_SIZE): position = index / PULSE_SIZE fade = 0.5 + cos(position * pi * 2) / 2.0 color = blend_rgb(fore_color, back_color, cross_fade=fade) append(_Segment(bar, _Style(color=from_triplet(color)))) return segments def update(self, completed: float, total: Optional[float] = None) -> None: """Update progress with new values. Args: completed (float): Number of steps completed. total (float, optional): Total number of steps, or ``None`` to not change. Defaults to None. """ self.completed = completed self.total = total if total is not None else self.total def _render_pulse( self, console: Console, width: int, ascii: bool = False ) -> Iterable[Segment]: """Renders the pulse animation. Args: console (Console): Console instance. width (int): Width in characters of pulse animation. Returns: RenderResult: [description] Yields: Iterator[Segment]: Segments to render pulse """ fore_style = console.get_style(self.pulse_style, default="white") back_style = console.get_style(self.style, default="black") pulse_segments = self._get_pulse_segments( fore_style, back_style, console.color_system, console.no_color, ascii=ascii ) segment_count = len(pulse_segments) current_time = ( monotonic() if self.animation_time is None else self.animation_time ) segments = pulse_segments * (int(width / segment_count) + 2) offset = int(-current_time * 15) % segment_count segments = segments[offset : offset + width] yield from segments def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: width = min(self.width or options.max_width, options.max_width) ascii = options.legacy_windows or options.ascii_only should_pulse = self.pulse or self.total is None if should_pulse: yield from self._render_pulse(console, width, ascii=ascii) return completed: Optional[float] = ( min(self.total, max(0, self.completed)) if self.total is not None else None ) bar = "-" if ascii else "━" half_bar_right = " " if ascii else "╸" half_bar_left = " " if ascii else "╺" complete_halves = ( int(width * 2 * completed / self.total) if self.total and completed is not None else width * 2 ) bar_count = complete_halves // 2 half_bar_count = complete_halves % 2 style = console.get_style(self.style) is_finished = self.total is None or self.completed >= self.total complete_style = console.get_style( self.finished_style if is_finished else self.complete_style ) _Segment = Segment if bar_count: yield _Segment(bar * bar_count, complete_style) if half_bar_count: yield _Segment(half_bar_right * half_bar_count, complete_style) if not console.no_color: remaining_bars = width - bar_count - half_bar_count if remaining_bars and console.color_system is not None: if not half_bar_count and bar_count: yield _Segment(half_bar_left, style) remaining_bars -= 1 if remaining_bars: yield _Segment(bar * remaining_bars, style) def __rich_measure__( self, console: Console, options: ConsoleOptions ) -> Measurement: return ( Measurement(self.width, self.width) if self.width is not None else Measurement(4, options.max_width) ) if __name__ == "__main__": # pragma: no cover console = Console() bar = ProgressBar(width=50, total=100) import time console.show_cursor(False) for n in range(0, 101, 1): bar.update(n) console.print(bar) console.file.write("\r") time.sleep(0.05) console.show_cursor(True) console.print()
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/_timer.py
rich/_timer.py
""" Timer context manager, only used in debug. """ from time import time import contextlib from typing import Generator @contextlib.contextmanager def timer(subject: str = "time") -> Generator[None, None, None]: """print the elapsed time. (only used in debugging)""" start = time() yield elapsed = time() - start elapsed_ms = elapsed * 1000 print(f"{subject} elapsed {elapsed_ms:.1f}ms")
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/repr.py
rich/repr.py
import inspect from functools import partial from typing import ( Any, Callable, Iterable, List, Optional, Tuple, Type, TypeVar, Union, overload, ) T = TypeVar("T") Result = Iterable[Union[Any, Tuple[Any], Tuple[str, Any], Tuple[str, Any, Any]]] RichReprResult = Result class ReprError(Exception): """An error occurred when attempting to build a repr.""" @overload def auto(cls: Optional[Type[T]]) -> Type[T]: ... @overload def auto(*, angular: bool = False) -> Callable[[Type[T]], Type[T]]: ... def auto( cls: Optional[Type[T]] = None, *, angular: Optional[bool] = None ) -> Union[Type[T], Callable[[Type[T]], Type[T]]]: """Class decorator to create __repr__ from __rich_repr__""" def do_replace(cls: Type[T], angular: Optional[bool] = None) -> Type[T]: def auto_repr(self: T) -> str: """Create repr string from __rich_repr__""" repr_str: List[str] = [] append = repr_str.append angular: bool = getattr(self.__rich_repr__, "angular", False) # type: ignore[attr-defined] for arg in self.__rich_repr__(): # type: ignore[attr-defined] if isinstance(arg, tuple): if len(arg) == 1: append(repr(arg[0])) else: key, value, *default = arg if key is None: append(repr(value)) else: if default and default[0] == value: continue append(f"{key}={value!r}") else: append(repr(arg)) if angular: return f"<{self.__class__.__name__} {' '.join(repr_str)}>" else: return f"{self.__class__.__name__}({', '.join(repr_str)})" def auto_rich_repr(self: Type[T]) -> Result: """Auto generate __rich_rep__ from signature of __init__""" try: signature = inspect.signature(self.__init__) for name, param in signature.parameters.items(): if param.kind == param.POSITIONAL_ONLY: yield getattr(self, name) elif param.kind in ( param.POSITIONAL_OR_KEYWORD, param.KEYWORD_ONLY, ): if param.default is param.empty: yield getattr(self, param.name) else: yield param.name, getattr(self, param.name), param.default except Exception as error: raise ReprError( f"Failed to auto generate __rich_repr__; {error}" ) from None if not hasattr(cls, "__rich_repr__"): auto_rich_repr.__doc__ = "Build a rich repr" cls.__rich_repr__ = auto_rich_repr # type: ignore[attr-defined] auto_repr.__doc__ = "Return repr(self)" cls.__repr__ = auto_repr # type: ignore[assignment] if angular is not None: cls.__rich_repr__.angular = angular # type: ignore[attr-defined] return cls if cls is None: return partial(do_replace, angular=angular) else: return do_replace(cls, angular=angular) @overload def rich_repr(cls: Optional[Type[T]]) -> Type[T]: ... @overload def rich_repr(*, angular: bool = False) -> Callable[[Type[T]], Type[T]]: ... def rich_repr( cls: Optional[Type[T]] = None, *, angular: bool = False ) -> Union[Type[T], Callable[[Type[T]], Type[T]]]: if cls is None: return auto(angular=angular) else: return auto(cls) if __name__ == "__main__": @auto class Foo: def __rich_repr__(self) -> Result: yield "foo" yield "bar", {"shopping": ["eggs", "ham", "pineapple"]} yield "buy", "hand sanitizer" foo = Foo() from rich.console import Console console = Console() console.rule("Standard repr") console.print(foo) console.print(foo, width=60) console.print(foo, width=30) console.rule("Angular repr") Foo.__rich_repr__.angular = True # type: ignore[attr-defined] console.print(foo) console.print(foo, width=60) console.print(foo, width=30)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/_emoji_codes.py
rich/_emoji_codes.py
EMOJI = { "1st_place_medal": "🥇", "2nd_place_medal": "🥈", "3rd_place_medal": "🥉", "ab_button_(blood_type)": "🆎", "atm_sign": "🏧", "a_button_(blood_type)": "🅰", "afghanistan": "🇦🇫", "albania": "🇦🇱", "algeria": "🇩🇿", "american_samoa": "🇦🇸", "andorra": "🇦🇩", "angola": "🇦🇴", "anguilla": "🇦🇮", "antarctica": "🇦🇶", "antigua_&_barbuda": "🇦🇬", "aquarius": "♒", "argentina": "🇦🇷", "aries": "♈", "armenia": "🇦🇲", "aruba": "🇦🇼", "ascension_island": "🇦🇨", "australia": "🇦🇺", "austria": "🇦🇹", "azerbaijan": "🇦🇿", "back_arrow": "🔙", "b_button_(blood_type)": "🅱", "bahamas": "🇧🇸", "bahrain": "🇧🇭", "bangladesh": "🇧🇩", "barbados": "🇧🇧", "belarus": "🇧🇾", "belgium": "🇧🇪", "belize": "🇧🇿", "benin": "🇧🇯", "bermuda": "🇧🇲", "bhutan": "🇧🇹", "bolivia": "🇧🇴", "bosnia_&_herzegovina": "🇧🇦", "botswana": "🇧🇼", "bouvet_island": "🇧🇻", "brazil": "🇧🇷", "british_indian_ocean_territory": "🇮🇴", "british_virgin_islands": "🇻🇬", "brunei": "🇧🇳", "bulgaria": "🇧🇬", "burkina_faso": "🇧🇫", "burundi": "🇧🇮", "cl_button": "🆑", "cool_button": "🆒", "cambodia": "🇰🇭", "cameroon": "🇨🇲", "canada": "🇨🇦", "canary_islands": "🇮🇨", "cancer": "♋", "cape_verde": "🇨🇻", "capricorn": "♑", "caribbean_netherlands": "🇧🇶", "cayman_islands": "🇰🇾", "central_african_republic": "🇨🇫", "ceuta_&_melilla": "🇪🇦", "chad": "🇹🇩", "chile": "🇨🇱", "china": "🇨🇳", "christmas_island": "🇨🇽", "christmas_tree": "🎄", "clipperton_island": "🇨🇵", "cocos_(keeling)_islands": "🇨🇨", "colombia": "🇨🇴", "comoros": "🇰🇲", "congo_-_brazzaville": "🇨🇬", "congo_-_kinshasa": "🇨🇩", "cook_islands": "🇨🇰", "costa_rica": "🇨🇷", "croatia": "🇭🇷", "cuba": "🇨🇺", "curaçao": "🇨🇼", "cyprus": "🇨🇾", "czechia": "🇨🇿", "côte_d’ivoire": "🇨🇮", "denmark": "🇩🇰", "diego_garcia": "🇩🇬", "djibouti": "🇩🇯", "dominica": "🇩🇲", "dominican_republic": "🇩🇴", "end_arrow": "🔚", "ecuador": "🇪🇨", "egypt": "🇪🇬", "el_salvador": "🇸🇻", "england": "🏴\U000e0067\U000e0062\U000e0065\U000e006e\U000e0067\U000e007f", "equatorial_guinea": "🇬🇶", "eritrea": "🇪🇷", "estonia": "🇪🇪", "ethiopia": "🇪🇹", "european_union": "🇪🇺", "free_button": "🆓", "falkland_islands": "🇫🇰", "faroe_islands": "🇫🇴", "fiji": "🇫🇯", "finland": "🇫🇮", "france": "🇫🇷", "french_guiana": "🇬🇫", "french_polynesia": "🇵🇫", "french_southern_territories": "🇹🇫", "gabon": "🇬🇦", "gambia": "🇬🇲", "gemini": "♊", "georgia": "🇬🇪", "germany": "🇩🇪", "ghana": "🇬🇭", "gibraltar": "🇬🇮", "greece": "🇬🇷", "greenland": "🇬🇱", "grenada": "🇬🇩", "guadeloupe": "🇬🇵", "guam": "🇬🇺", "guatemala": "🇬🇹", "guernsey": "🇬🇬", "guinea": "🇬🇳", "guinea-bissau": "🇬🇼", "guyana": "🇬🇾", "haiti": "🇭🇹", "heard_&_mcdonald_islands": "🇭🇲", "honduras": "🇭🇳", "hong_kong_sar_china": "🇭🇰", "hungary": "🇭🇺", "id_button": "🆔", "iceland": "🇮🇸", "india": "🇮🇳", "indonesia": "🇮🇩", "iran": "🇮🇷", "iraq": "🇮🇶", "ireland": "🇮🇪", "isle_of_man": "🇮🇲", "israel": "🇮🇱", "italy": "🇮🇹", "jamaica": "🇯🇲", "japan": "🗾", "japanese_acceptable_button": "🉑", "japanese_application_button": "🈸", "japanese_bargain_button": "🉐", "japanese_castle": "🏯", "japanese_congratulations_button": "㊗", "japanese_discount_button": "🈹", "japanese_dolls": "🎎", "japanese_free_of_charge_button": "🈚", "japanese_here_button": "🈁", "japanese_monthly_amount_button": "🈷", "japanese_no_vacancy_button": "🈵", "japanese_not_free_of_charge_button": "🈶", "japanese_open_for_business_button": "🈺", "japanese_passing_grade_button": "🈴", "japanese_post_office": "🏣", "japanese_prohibited_button": "🈲", "japanese_reserved_button": "🈯", "japanese_secret_button": "㊙", "japanese_service_charge_button": "🈂", "japanese_symbol_for_beginner": "🔰", "japanese_vacancy_button": "🈳", "jersey": "🇯🇪", "jordan": "🇯🇴", "kazakhstan": "🇰🇿", "kenya": "🇰🇪", "kiribati": "🇰🇮", "kosovo": "🇽🇰", "kuwait": "🇰🇼", "kyrgyzstan": "🇰🇬", "laos": "🇱🇦", "latvia": "🇱🇻", "lebanon": "🇱🇧", "leo": "♌", "lesotho": "🇱🇸", "liberia": "🇱🇷", "libra": "♎", "libya": "🇱🇾", "liechtenstein": "🇱🇮", "lithuania": "🇱🇹", "luxembourg": "🇱🇺", "macau_sar_china": "🇲🇴", "macedonia": "🇲🇰", "madagascar": "🇲🇬", "malawi": "🇲🇼", "malaysia": "🇲🇾", "maldives": "🇲🇻", "mali": "🇲🇱", "malta": "🇲🇹", "marshall_islands": "🇲🇭", "martinique": "🇲🇶", "mauritania": "🇲🇷", "mauritius": "🇲🇺", "mayotte": "🇾🇹", "mexico": "🇲🇽", "micronesia": "🇫🇲", "moldova": "🇲🇩", "monaco": "🇲🇨", "mongolia": "🇲🇳", "montenegro": "🇲🇪", "montserrat": "🇲🇸", "morocco": "🇲🇦", "mozambique": "🇲🇿", "mrs._claus": "🤶", "mrs._claus_dark_skin_tone": "🤶🏿", "mrs._claus_light_skin_tone": "🤶🏻", "mrs._claus_medium-dark_skin_tone": "🤶🏾", "mrs._claus_medium-light_skin_tone": "🤶🏼", "mrs._claus_medium_skin_tone": "🤶🏽", "myanmar_(burma)": "🇲🇲", "new_button": "🆕", "ng_button": "🆖", "namibia": "🇳🇦", "nauru": "🇳🇷", "nepal": "🇳🇵", "netherlands": "🇳🇱", "new_caledonia": "🇳🇨", "new_zealand": "🇳🇿", "nicaragua": "🇳🇮", "niger": "🇳🇪", "nigeria": "🇳🇬", "niue": "🇳🇺", "norfolk_island": "🇳🇫", "north_korea": "🇰🇵", "northern_mariana_islands": "🇲🇵", "norway": "🇳🇴", "ok_button": "🆗", "ok_hand": "👌", "ok_hand_dark_skin_tone": "👌🏿", "ok_hand_light_skin_tone": "👌🏻", "ok_hand_medium-dark_skin_tone": "👌🏾", "ok_hand_medium-light_skin_tone": "👌🏼", "ok_hand_medium_skin_tone": "👌🏽", "on!_arrow": "🔛", "o_button_(blood_type)": "🅾", "oman": "🇴🇲", "ophiuchus": "⛎", "p_button": "🅿", "pakistan": "🇵🇰", "palau": "🇵🇼", "palestinian_territories": "🇵🇸", "panama": "🇵🇦", "papua_new_guinea": "🇵🇬", "paraguay": "🇵🇾", "peru": "🇵🇪", "philippines": "🇵🇭", "pisces": "♓", "pitcairn_islands": "🇵🇳", "poland": "🇵🇱", "portugal": "🇵🇹", "puerto_rico": "🇵🇷", "qatar": "🇶🇦", "romania": "🇷🇴", "russia": "🇷🇺", "rwanda": "🇷🇼", "réunion": "🇷🇪", "soon_arrow": "🔜", "sos_button": "🆘", "sagittarius": "♐", "samoa": "🇼🇸", "san_marino": "🇸🇲", "santa_claus": "🎅", "santa_claus_dark_skin_tone": "🎅🏿", "santa_claus_light_skin_tone": "🎅🏻", "santa_claus_medium-dark_skin_tone": "🎅🏾", "santa_claus_medium-light_skin_tone": "🎅🏼", "santa_claus_medium_skin_tone": "🎅🏽", "saudi_arabia": "🇸🇦", "scorpio": "♏", "scotland": "🏴\U000e0067\U000e0062\U000e0073\U000e0063\U000e0074\U000e007f", "senegal": "🇸🇳", "serbia": "🇷🇸", "seychelles": "🇸🇨", "sierra_leone": "🇸🇱", "singapore": "🇸🇬", "sint_maarten": "🇸🇽", "slovakia": "🇸🇰", "slovenia": "🇸🇮", "solomon_islands": "🇸🇧", "somalia": "🇸🇴", "south_africa": "🇿🇦", "south_georgia_&_south_sandwich_islands": "🇬🇸", "south_korea": "🇰🇷", "south_sudan": "🇸🇸", "spain": "🇪🇸", "sri_lanka": "🇱🇰", "st._barthélemy": "🇧🇱", "st._helena": "🇸🇭", "st._kitts_&_nevis": "🇰🇳", "st._lucia": "🇱🇨", "st._martin": "🇲🇫", "st._pierre_&_miquelon": "🇵🇲", "st._vincent_&_grenadines": "🇻🇨", "statue_of_liberty": "🗽", "sudan": "🇸🇩", "suriname": "🇸🇷", "svalbard_&_jan_mayen": "🇸🇯", "swaziland": "🇸🇿", "sweden": "🇸🇪", "switzerland": "🇨🇭", "syria": "🇸🇾", "são_tomé_&_príncipe": "🇸🇹", "t-rex": "🦖", "top_arrow": "🔝", "taiwan": "🇹🇼", "tajikistan": "🇹🇯", "tanzania": "🇹🇿", "taurus": "♉", "thailand": "🇹🇭", "timor-leste": "🇹🇱", "togo": "🇹🇬", "tokelau": "🇹🇰", "tokyo_tower": "🗼", "tonga": "🇹🇴", "trinidad_&_tobago": "🇹🇹", "tristan_da_cunha": "🇹🇦", "tunisia": "🇹🇳", "turkey": "🦃", "turkmenistan": "🇹🇲", "turks_&_caicos_islands": "🇹🇨", "tuvalu": "🇹🇻", "u.s._outlying_islands": "🇺🇲", "u.s._virgin_islands": "🇻🇮", "up!_button": "🆙", "uganda": "🇺🇬", "ukraine": "🇺🇦", "united_arab_emirates": "🇦🇪", "united_kingdom": "🇬🇧", "united_nations": "🇺🇳", "united_states": "🇺🇸", "uruguay": "🇺🇾", "uzbekistan": "🇺🇿", "vs_button": "🆚", "vanuatu": "🇻🇺", "vatican_city": "🇻🇦", "venezuela": "🇻🇪", "vietnam": "🇻🇳", "virgo": "♍", "wales": "🏴\U000e0067\U000e0062\U000e0077\U000e006c\U000e0073\U000e007f", "wallis_&_futuna": "🇼🇫", "western_sahara": "🇪🇭", "yemen": "🇾🇪", "zambia": "🇿🇲", "zimbabwe": "🇿🇼", "abacus": "🧮", "adhesive_bandage": "🩹", "admission_tickets": "🎟", "adult": "🧑", "adult_dark_skin_tone": "🧑🏿", "adult_light_skin_tone": "🧑🏻", "adult_medium-dark_skin_tone": "🧑🏾", "adult_medium-light_skin_tone": "🧑🏼", "adult_medium_skin_tone": "🧑🏽", "aerial_tramway": "🚡", "airplane": "✈", "airplane_arrival": "🛬", "airplane_departure": "🛫", "alarm_clock": "⏰", "alembic": "⚗", "alien": "👽", "alien_monster": "👾", "ambulance": "🚑", "american_football": "🏈", "amphora": "🏺", "anchor": "⚓", "anger_symbol": "💢", "angry_face": "😠", "angry_face_with_horns": "👿", "anguished_face": "😧", "ant": "🐜", "antenna_bars": "📶", "anxious_face_with_sweat": "😰", "articulated_lorry": "🚛", "artist_palette": "🎨", "astonished_face": "😲", "atom_symbol": "⚛", "auto_rickshaw": "🛺", "automobile": "🚗", "avocado": "🥑", "axe": "🪓", "baby": "👶", "baby_angel": "👼", "baby_angel_dark_skin_tone": "👼🏿", "baby_angel_light_skin_tone": "👼🏻", "baby_angel_medium-dark_skin_tone": "👼🏾", "baby_angel_medium-light_skin_tone": "👼🏼", "baby_angel_medium_skin_tone": "👼🏽", "baby_bottle": "🍼", "baby_chick": "🐤", "baby_dark_skin_tone": "👶🏿", "baby_light_skin_tone": "👶🏻", "baby_medium-dark_skin_tone": "👶🏾", "baby_medium-light_skin_tone": "👶🏼", "baby_medium_skin_tone": "👶🏽", "baby_symbol": "🚼", "backhand_index_pointing_down": "👇", "backhand_index_pointing_down_dark_skin_tone": "👇🏿", "backhand_index_pointing_down_light_skin_tone": "👇🏻", "backhand_index_pointing_down_medium-dark_skin_tone": "👇🏾", "backhand_index_pointing_down_medium-light_skin_tone": "👇🏼", "backhand_index_pointing_down_medium_skin_tone": "👇🏽", "backhand_index_pointing_left": "👈", "backhand_index_pointing_left_dark_skin_tone": "👈🏿", "backhand_index_pointing_left_light_skin_tone": "👈🏻", "backhand_index_pointing_left_medium-dark_skin_tone": "👈🏾", "backhand_index_pointing_left_medium-light_skin_tone": "👈🏼", "backhand_index_pointing_left_medium_skin_tone": "👈🏽", "backhand_index_pointing_right": "👉", "backhand_index_pointing_right_dark_skin_tone": "👉🏿", "backhand_index_pointing_right_light_skin_tone": "👉🏻", "backhand_index_pointing_right_medium-dark_skin_tone": "👉🏾", "backhand_index_pointing_right_medium-light_skin_tone": "👉🏼", "backhand_index_pointing_right_medium_skin_tone": "👉🏽", "backhand_index_pointing_up": "👆", "backhand_index_pointing_up_dark_skin_tone": "👆🏿", "backhand_index_pointing_up_light_skin_tone": "👆🏻", "backhand_index_pointing_up_medium-dark_skin_tone": "👆🏾", "backhand_index_pointing_up_medium-light_skin_tone": "👆🏼", "backhand_index_pointing_up_medium_skin_tone": "👆🏽", "bacon": "🥓", "badger": "🦡", "badminton": "🏸", "bagel": "🥯", "baggage_claim": "🛄", "baguette_bread": "🥖", "balance_scale": "⚖", "bald": "🦲", "bald_man": "👨\u200d🦲", "bald_woman": "👩\u200d🦲", "ballet_shoes": "🩰", "balloon": "🎈", "ballot_box_with_ballot": "🗳", "ballot_box_with_check": "☑", "banana": "🍌", "banjo": "🪕", "bank": "🏦", "bar_chart": "📊", "barber_pole": "💈", "baseball": "⚾", "basket": "🧺", "basketball": "🏀", "bat": "🦇", "bathtub": "🛁", "battery": "🔋", "beach_with_umbrella": "🏖", "beaming_face_with_smiling_eyes": "😁", "bear_face": "🐻", "bearded_person": "🧔", "bearded_person_dark_skin_tone": "🧔🏿", "bearded_person_light_skin_tone": "🧔🏻", "bearded_person_medium-dark_skin_tone": "🧔🏾", "bearded_person_medium-light_skin_tone": "🧔🏼", "bearded_person_medium_skin_tone": "🧔🏽", "beating_heart": "💓", "bed": "🛏", "beer_mug": "🍺", "bell": "🔔", "bell_with_slash": "🔕", "bellhop_bell": "🛎", "bento_box": "🍱", "beverage_box": "🧃", "bicycle": "🚲", "bikini": "👙", "billed_cap": "🧢", "biohazard": "☣", "bird": "🐦", "birthday_cake": "🎂", "black_circle": "⚫", "black_flag": "🏴", "black_heart": "🖤", "black_large_square": "⬛", "black_medium-small_square": "◾", "black_medium_square": "◼", "black_nib": "✒", "black_small_square": "▪", "black_square_button": "🔲", "blond-haired_man": "👱\u200d♂️", "blond-haired_man_dark_skin_tone": "👱🏿\u200d♂️", "blond-haired_man_light_skin_tone": "👱🏻\u200d♂️", "blond-haired_man_medium-dark_skin_tone": "👱🏾\u200d♂️", "blond-haired_man_medium-light_skin_tone": "👱🏼\u200d♂️", "blond-haired_man_medium_skin_tone": "👱🏽\u200d♂️", "blond-haired_person": "👱", "blond-haired_person_dark_skin_tone": "👱🏿", "blond-haired_person_light_skin_tone": "👱🏻", "blond-haired_person_medium-dark_skin_tone": "👱🏾", "blond-haired_person_medium-light_skin_tone": "👱🏼", "blond-haired_person_medium_skin_tone": "👱🏽", "blond-haired_woman": "👱\u200d♀️", "blond-haired_woman_dark_skin_tone": "👱🏿\u200d♀️", "blond-haired_woman_light_skin_tone": "👱🏻\u200d♀️", "blond-haired_woman_medium-dark_skin_tone": "👱🏾\u200d♀️", "blond-haired_woman_medium-light_skin_tone": "👱🏼\u200d♀️", "blond-haired_woman_medium_skin_tone": "👱🏽\u200d♀️", "blossom": "🌼", "blowfish": "🐡", "blue_book": "📘", "blue_circle": "🔵", "blue_heart": "💙", "blue_square": "🟦", "boar": "🐗", "bomb": "💣", "bone": "🦴", "bookmark": "🔖", "bookmark_tabs": "📑", "books": "📚", "bottle_with_popping_cork": "🍾", "bouquet": "💐", "bow_and_arrow": "🏹", "bowl_with_spoon": "🥣", "bowling": "🎳", "boxing_glove": "🥊", "boy": "👦", "boy_dark_skin_tone": "👦🏿", "boy_light_skin_tone": "👦🏻", "boy_medium-dark_skin_tone": "👦🏾", "boy_medium-light_skin_tone": "👦🏼", "boy_medium_skin_tone": "👦🏽", "brain": "🧠", "bread": "🍞", "breast-feeding": "🤱", "breast-feeding_dark_skin_tone": "🤱🏿", "breast-feeding_light_skin_tone": "🤱🏻", "breast-feeding_medium-dark_skin_tone": "🤱🏾", "breast-feeding_medium-light_skin_tone": "🤱🏼", "breast-feeding_medium_skin_tone": "🤱🏽", "brick": "🧱", "bride_with_veil": "👰", "bride_with_veil_dark_skin_tone": "👰🏿", "bride_with_veil_light_skin_tone": "👰🏻", "bride_with_veil_medium-dark_skin_tone": "👰🏾", "bride_with_veil_medium-light_skin_tone": "👰🏼", "bride_with_veil_medium_skin_tone": "👰🏽", "bridge_at_night": "🌉", "briefcase": "💼", "briefs": "🩲", "bright_button": "🔆", "broccoli": "🥦", "broken_heart": "💔", "broom": "🧹", "brown_circle": "🟤", "brown_heart": "🤎", "brown_square": "🟫", "bug": "🐛", "building_construction": "🏗", "bullet_train": "🚅", "burrito": "🌯", "bus": "🚌", "bus_stop": "🚏", "bust_in_silhouette": "👤", "busts_in_silhouette": "👥", "butter": "🧈", "butterfly": "🦋", "cactus": "🌵", "calendar": "📆", "call_me_hand": "🤙", "call_me_hand_dark_skin_tone": "🤙🏿", "call_me_hand_light_skin_tone": "🤙🏻", "call_me_hand_medium-dark_skin_tone": "🤙🏾", "call_me_hand_medium-light_skin_tone": "🤙🏼", "call_me_hand_medium_skin_tone": "🤙🏽", "camel": "🐫", "camera": "📷", "camera_with_flash": "📸", "camping": "🏕", "candle": "🕯", "candy": "🍬", "canned_food": "🥫", "canoe": "🛶", "card_file_box": "🗃", "card_index": "📇", "card_index_dividers": "🗂", "carousel_horse": "🎠", "carp_streamer": "🎏", "carrot": "🥕", "castle": "🏰", "cat": "🐱", "cat_face": "🐱", "cat_face_with_tears_of_joy": "😹", "cat_face_with_wry_smile": "😼", "chains": "⛓", "chair": "🪑", "chart_decreasing": "📉", "chart_increasing": "📈", "chart_increasing_with_yen": "💹", "cheese_wedge": "🧀", "chequered_flag": "🏁", "cherries": "🍒", "cherry_blossom": "🌸", "chess_pawn": "♟", "chestnut": "🌰", "chicken": "🐔", "child": "🧒", "child_dark_skin_tone": "🧒🏿", "child_light_skin_tone": "🧒🏻", "child_medium-dark_skin_tone": "🧒🏾", "child_medium-light_skin_tone": "🧒🏼", "child_medium_skin_tone": "🧒🏽", "children_crossing": "🚸", "chipmunk": "🐿", "chocolate_bar": "🍫", "chopsticks": "🥢", "church": "⛪", "cigarette": "🚬", "cinema": "🎦", "circled_m": "Ⓜ", "circus_tent": "🎪", "cityscape": "🏙", "cityscape_at_dusk": "🌆", "clamp": "🗜", "clapper_board": "🎬", "clapping_hands": "👏", "clapping_hands_dark_skin_tone": "👏🏿", "clapping_hands_light_skin_tone": "👏🏻", "clapping_hands_medium-dark_skin_tone": "👏🏾", "clapping_hands_medium-light_skin_tone": "👏🏼", "clapping_hands_medium_skin_tone": "👏🏽", "classical_building": "🏛", "clinking_beer_mugs": "🍻", "clinking_glasses": "🥂", "clipboard": "📋", "clockwise_vertical_arrows": "🔃", "closed_book": "📕", "closed_mailbox_with_lowered_flag": "📪", "closed_mailbox_with_raised_flag": "📫", "closed_umbrella": "🌂", "cloud": "☁", "cloud_with_lightning": "🌩", "cloud_with_lightning_and_rain": "⛈", "cloud_with_rain": "🌧", "cloud_with_snow": "🌨", "clown_face": "🤡", "club_suit": "♣", "clutch_bag": "👝", "coat": "🧥", "cocktail_glass": "🍸", "coconut": "🥥", "coffin": "⚰", "cold_face": "🥶", "collision": "💥", "comet": "☄", "compass": "🧭", "computer_disk": "💽", "computer_mouse": "🖱", "confetti_ball": "🎊", "confounded_face": "😖", "confused_face": "😕", "construction": "🚧", "construction_worker": "👷", "construction_worker_dark_skin_tone": "👷🏿", "construction_worker_light_skin_tone": "👷🏻", "construction_worker_medium-dark_skin_tone": "👷🏾", "construction_worker_medium-light_skin_tone": "👷🏼", "construction_worker_medium_skin_tone": "👷🏽", "control_knobs": "🎛", "convenience_store": "🏪", "cooked_rice": "🍚", "cookie": "🍪", "cooking": "🍳", "copyright": "©", "couch_and_lamp": "🛋", "counterclockwise_arrows_button": "🔄", "couple_with_heart": "💑", "couple_with_heart_man_man": "👨\u200d❤️\u200d👨", "couple_with_heart_woman_man": "👩\u200d❤️\u200d👨", "couple_with_heart_woman_woman": "👩\u200d❤️\u200d👩", "cow": "🐮", "cow_face": "🐮", "cowboy_hat_face": "🤠", "crab": "🦀", "crayon": "🖍", "credit_card": "💳", "crescent_moon": "🌙", "cricket": "🦗", "cricket_game": "🏏", "crocodile": "🐊", "croissant": "🥐", "cross_mark": "❌", "cross_mark_button": "❎", "crossed_fingers": "🤞", "crossed_fingers_dark_skin_tone": "🤞🏿", "crossed_fingers_light_skin_tone": "🤞🏻", "crossed_fingers_medium-dark_skin_tone": "🤞🏾", "crossed_fingers_medium-light_skin_tone": "🤞🏼", "crossed_fingers_medium_skin_tone": "🤞🏽", "crossed_flags": "🎌", "crossed_swords": "⚔", "crown": "👑", "crying_cat_face": "😿", "crying_face": "😢", "crystal_ball": "🔮", "cucumber": "🥒", "cupcake": "🧁", "cup_with_straw": "🥤", "curling_stone": "🥌", "curly_hair": "🦱", "curly-haired_man": "👨\u200d🦱", "curly-haired_woman": "👩\u200d🦱", "curly_loop": "➰", "currency_exchange": "💱", "curry_rice": "🍛", "custard": "🍮", "customs": "🛃", "cut_of_meat": "🥩", "cyclone": "🌀", "dagger": "🗡", "dango": "🍡", "dashing_away": "💨", "deaf_person": "🧏", "deciduous_tree": "🌳", "deer": "🦌", "delivery_truck": "🚚", "department_store": "🏬", "derelict_house": "🏚", "desert": "🏜", "desert_island": "🏝", "desktop_computer": "🖥", "detective": "🕵", "detective_dark_skin_tone": "🕵🏿", "detective_light_skin_tone": "🕵🏻", "detective_medium-dark_skin_tone": "🕵🏾", "detective_medium-light_skin_tone": "🕵🏼", "detective_medium_skin_tone": "🕵🏽", "diamond_suit": "♦", "diamond_with_a_dot": "💠", "dim_button": "🔅", "direct_hit": "🎯", "disappointed_face": "😞", "diving_mask": "🤿", "diya_lamp": "🪔", "dizzy": "💫", "dizzy_face": "😵", "dna": "🧬", "dog": "🐶", "dog_face": "🐶", "dollar_banknote": "💵", "dolphin": "🐬", "door": "🚪", "dotted_six-pointed_star": "🔯", "double_curly_loop": "➿", "double_exclamation_mark": "‼", "doughnut": "🍩", "dove": "🕊", "down-left_arrow": "↙", "down-right_arrow": "↘", "down_arrow": "⬇", "downcast_face_with_sweat": "😓", "downwards_button": "🔽", "dragon": "🐉", "dragon_face": "🐲", "dress": "👗", "drooling_face": "🤤", "drop_of_blood": "🩸", "droplet": "💧", "drum": "🥁", "duck": "🦆", "dumpling": "🥟", "dvd": "📀", "e-mail": "📧", "eagle": "🦅", "ear": "👂", "ear_dark_skin_tone": "👂🏿", "ear_light_skin_tone": "👂🏻", "ear_medium-dark_skin_tone": "👂🏾", "ear_medium-light_skin_tone": "👂🏼", "ear_medium_skin_tone": "👂🏽", "ear_of_corn": "🌽", "ear_with_hearing_aid": "🦻", "egg": "🍳", "eggplant": "🍆", "eight-pointed_star": "✴", "eight-spoked_asterisk": "✳", "eight-thirty": "🕣", "eight_o’clock": "🕗", "eject_button": "⏏", "electric_plug": "🔌", "elephant": "🐘", "eleven-thirty": "🕦", "eleven_o’clock": "🕚", "elf": "🧝", "elf_dark_skin_tone": "🧝🏿", "elf_light_skin_tone": "🧝🏻", "elf_medium-dark_skin_tone": "🧝🏾", "elf_medium-light_skin_tone": "🧝🏼", "elf_medium_skin_tone": "🧝🏽", "envelope": "✉", "envelope_with_arrow": "📩", "euro_banknote": "💶", "evergreen_tree": "🌲", "ewe": "🐑", "exclamation_mark": "❗", "exclamation_question_mark": "⁉", "exploding_head": "🤯", "expressionless_face": "😑", "eye": "👁", "eye_in_speech_bubble": "👁️\u200d🗨️", "eyes": "👀", "face_blowing_a_kiss": "😘", "face_savoring_food": "😋", "face_screaming_in_fear": "😱", "face_vomiting": "🤮", "face_with_hand_over_mouth": "🤭", "face_with_head-bandage": "🤕", "face_with_medical_mask": "😷", "face_with_monocle": "🧐", "face_with_open_mouth": "😮", "face_with_raised_eyebrow": "🤨", "face_with_rolling_eyes": "🙄", "face_with_steam_from_nose": "😤", "face_with_symbols_on_mouth": "🤬", "face_with_tears_of_joy": "😂", "face_with_thermometer": "🤒", "face_with_tongue": "😛", "face_without_mouth": "😶", "factory": "🏭", "fairy": "🧚", "fairy_dark_skin_tone": "🧚🏿", "fairy_light_skin_tone": "🧚🏻", "fairy_medium-dark_skin_tone": "🧚🏾", "fairy_medium-light_skin_tone": "🧚🏼", "fairy_medium_skin_tone": "🧚🏽", "falafel": "🧆", "fallen_leaf": "🍂", "family": "👪", "family_man_boy": "👨\u200d👦", "family_man_boy_boy": "👨\u200d👦\u200d👦", "family_man_girl": "👨\u200d👧", "family_man_girl_boy": "👨\u200d👧\u200d👦", "family_man_girl_girl": "👨\u200d👧\u200d👧", "family_man_man_boy": "👨\u200d👨\u200d👦", "family_man_man_boy_boy": "👨\u200d👨\u200d👦\u200d👦", "family_man_man_girl": "👨\u200d👨\u200d👧", "family_man_man_girl_boy": "👨\u200d👨\u200d👧\u200d👦", "family_man_man_girl_girl": "👨\u200d👨\u200d👧\u200d👧", "family_man_woman_boy": "👨\u200d👩\u200d👦", "family_man_woman_boy_boy": "👨\u200d👩\u200d👦\u200d👦", "family_man_woman_girl": "👨\u200d👩\u200d👧", "family_man_woman_girl_boy": "👨\u200d👩\u200d👧\u200d👦", "family_man_woman_girl_girl": "👨\u200d👩\u200d👧\u200d👧", "family_woman_boy": "👩\u200d👦", "family_woman_boy_boy": "👩\u200d👦\u200d👦", "family_woman_girl": "👩\u200d👧", "family_woman_girl_boy": "👩\u200d👧\u200d👦", "family_woman_girl_girl": "👩\u200d👧\u200d👧", "family_woman_woman_boy": "👩\u200d👩\u200d👦", "family_woman_woman_boy_boy": "👩\u200d👩\u200d👦\u200d👦", "family_woman_woman_girl": "👩\u200d👩\u200d👧", "family_woman_woman_girl_boy": "👩\u200d👩\u200d👧\u200d👦", "family_woman_woman_girl_girl": "👩\u200d👩\u200d👧\u200d👧", "fast-forward_button": "⏩", "fast_down_button": "⏬", "fast_reverse_button": "⏪", "fast_up_button": "⏫", "fax_machine": "📠", "fearful_face": "😨", "female_sign": "♀", "ferris_wheel": "🎡", "ferry": "⛴", "field_hockey": "🏑", "file_cabinet": "🗄", "file_folder": "📁", "film_frames": "🎞", "film_projector": "📽", "fire": "🔥", "fire_extinguisher": "🧯", "firecracker": "🧨", "fire_engine": "🚒", "fireworks": "🎆", "first_quarter_moon": "🌓", "first_quarter_moon_face": "🌛", "fish": "🐟", "fish_cake_with_swirl": "🍥", "fishing_pole": "🎣", "five-thirty": "🕠", "five_o’clock": "🕔", "flag_in_hole": "⛳", "flamingo": "🦩", "flashlight": "🔦", "flat_shoe": "🥿", "fleur-de-lis": "⚜", "flexed_biceps": "💪", "flexed_biceps_dark_skin_tone": "💪🏿", "flexed_biceps_light_skin_tone": "💪🏻", "flexed_biceps_medium-dark_skin_tone": "💪🏾", "flexed_biceps_medium-light_skin_tone": "💪🏼", "flexed_biceps_medium_skin_tone": "💪🏽", "floppy_disk": "💾", "flower_playing_cards": "🎴", "flushed_face": "😳", "flying_disc": "🥏", "flying_saucer": "🛸", "fog": "🌫", "foggy": "🌁", "folded_hands": "🙏", "folded_hands_dark_skin_tone": "🙏🏿", "folded_hands_light_skin_tone": "🙏🏻", "folded_hands_medium-dark_skin_tone": "🙏🏾", "folded_hands_medium-light_skin_tone": "🙏🏼", "folded_hands_medium_skin_tone": "🙏🏽", "foot": "🦶", "footprints": "👣", "fork_and_knife": "🍴", "fork_and_knife_with_plate": "🍽", "fortune_cookie": "🥠", "fountain": "⛲", "fountain_pen": "🖋", "four-thirty": "🕟", "four_leaf_clover": "🍀", "four_o’clock": "🕓", "fox_face": "🦊", "framed_picture": "🖼", "french_fries": "🍟", "fried_shrimp": "🍤", "frog_face": "🐸", "front-facing_baby_chick": "🐥", "frowning_face": "☹", "frowning_face_with_open_mouth": "😦", "fuel_pump": "⛽", "full_moon": "🌕", "full_moon_face": "🌝", "funeral_urn": "⚱", "game_die": "🎲", "garlic": "🧄", "gear": "⚙", "gem_stone": "💎", "genie": "🧞", "ghost": "👻", "giraffe": "🦒", "girl": "👧", "girl_dark_skin_tone": "👧🏿", "girl_light_skin_tone": "👧🏻", "girl_medium-dark_skin_tone": "👧🏾", "girl_medium-light_skin_tone": "👧🏼", "girl_medium_skin_tone": "👧🏽", "glass_of_milk": "🥛", "glasses": "👓", "globe_showing_americas": "🌎", "globe_showing_asia-australia": "🌏", "globe_showing_europe-africa": "🌍", "globe_with_meridians": "🌐", "gloves": "🧤", "glowing_star": "🌟", "goal_net": "🥅", "goat": "🐐", "goblin": "👺", "goggles": "🥽", "gorilla": "🦍", "graduation_cap": "🎓", "grapes": "🍇", "green_apple": "🍏", "green_book": "📗", "green_circle": "🟢", "green_heart": "💚", "green_salad": "🥗", "green_square": "🟩", "grimacing_face": "😬", "grinning_cat_face": "😺", "grinning_cat_face_with_smiling_eyes": "😸", "grinning_face": "😀", "grinning_face_with_big_eyes": "😃", "grinning_face_with_smiling_eyes": "😄", "grinning_face_with_sweat": "😅", "grinning_squinting_face": "😆", "growing_heart": "💗", "guard": "💂", "guard_dark_skin_tone": "💂🏿", "guard_light_skin_tone": "💂🏻", "guard_medium-dark_skin_tone": "💂🏾", "guard_medium-light_skin_tone": "💂🏼", "guard_medium_skin_tone": "💂🏽", "guide_dog": "🦮", "guitar": "🎸", "hamburger": "🍔", "hammer": "🔨", "hammer_and_pick": "⚒", "hammer_and_wrench": "🛠", "hamster_face": "🐹", "hand_with_fingers_splayed": "🖐", "hand_with_fingers_splayed_dark_skin_tone": "🖐🏿", "hand_with_fingers_splayed_light_skin_tone": "🖐🏻",
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
true
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/live_render.py
rich/live_render.py
from typing import Optional, Tuple, Literal from ._loop import loop_last from .console import Console, ConsoleOptions, RenderableType, RenderResult from .control import Control from .segment import ControlType, Segment from .style import StyleType from .text import Text VerticalOverflowMethod = Literal["crop", "ellipsis", "visible"] class LiveRender: """Creates a renderable that may be updated. Args: renderable (RenderableType): Any renderable object. style (StyleType, optional): An optional style to apply to the renderable. Defaults to "". """ def __init__( self, renderable: RenderableType, style: StyleType = "", vertical_overflow: VerticalOverflowMethod = "ellipsis", ) -> None: self.renderable = renderable self.style = style self.vertical_overflow = vertical_overflow self._shape: Optional[Tuple[int, int]] = None def set_renderable(self, renderable: RenderableType) -> None: """Set a new renderable. Args: renderable (RenderableType): Any renderable object, including str. """ self.renderable = renderable def position_cursor(self) -> Control: """Get control codes to move cursor to beginning of live render. Returns: Control: A control instance that may be printed. """ if self._shape is not None: _, height = self._shape return Control( ControlType.CARRIAGE_RETURN, (ControlType.ERASE_IN_LINE, 2), *( ( (ControlType.CURSOR_UP, 1), (ControlType.ERASE_IN_LINE, 2), ) * (height - 1) ) ) return Control() def restore_cursor(self) -> Control: """Get control codes to clear the render and restore the cursor to its previous position. Returns: Control: A Control instance that may be printed. """ if self._shape is not None: _, height = self._shape return Control( ControlType.CARRIAGE_RETURN, *((ControlType.CURSOR_UP, 1), (ControlType.ERASE_IN_LINE, 2)) * height ) return Control() def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: renderable = self.renderable style = console.get_style(self.style) lines = console.render_lines(renderable, options, style=style, pad=False) shape = Segment.get_shape(lines) _, height = shape if height > options.size.height: if self.vertical_overflow == "crop": lines = lines[: options.size.height] shape = Segment.get_shape(lines) elif self.vertical_overflow == "ellipsis": lines = lines[: (options.size.height - 1)] overflow_text = Text( "...", overflow="crop", justify="center", end="", style="live.ellipsis", ) lines.append(list(console.render(overflow_text))) shape = Segment.get_shape(lines) self._shape = shape new_line = Segment.line() for last, line in loop_last(lines): yield from line if not last: yield new_line
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/_extension.py
rich/_extension.py
from typing import Any def load_ipython_extension(ip: Any) -> None: # pragma: no cover # prevent circular import from rich.pretty import install from rich.traceback import install as tr_install install() tr_install()
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/rule.py
rich/rule.py
from typing import Union from .align import AlignMethod from .cells import cell_len, set_cell_size from .console import Console, ConsoleOptions, RenderResult from .jupyter import JupyterMixin from .measure import Measurement from .style import Style from .text import Text class Rule(JupyterMixin): """A console renderable to draw a horizontal rule (line). Args: title (Union[str, Text], optional): Text to render in the rule. Defaults to "". characters (str, optional): Character(s) used to draw the line. Defaults to "─". style (StyleType, optional): Style of Rule. Defaults to "rule.line". end (str, optional): Character at end of Rule. defaults to "\\\\n" align (str, optional): How to align the title, one of "left", "center", or "right". Defaults to "center". """ def __init__( self, title: Union[str, Text] = "", *, characters: str = "─", style: Union[str, Style] = "rule.line", end: str = "\n", align: AlignMethod = "center", ) -> None: if cell_len(characters) < 1: raise ValueError( "'characters' argument must have a cell width of at least 1" ) if align not in ("left", "center", "right"): raise ValueError( f'invalid value for align, expected "left", "center", "right" (not {align!r})' ) self.title = title self.characters = characters self.style = style self.end = end self.align = align def __repr__(self) -> str: return f"Rule({self.title!r}, {self.characters!r})" def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: width = options.max_width characters = ( "-" if (options.ascii_only and not self.characters.isascii()) else self.characters ) chars_len = cell_len(characters) if not self.title: yield self._rule_line(chars_len, width) return if isinstance(self.title, Text): title_text = self.title else: title_text = console.render_str(self.title, style="rule.text") title_text.plain = title_text.plain.replace("\n", " ") title_text.expand_tabs() required_space = 4 if self.align == "center" else 2 truncate_width = max(0, width - required_space) if not truncate_width: yield self._rule_line(chars_len, width) return rule_text = Text(end=self.end) if self.align == "center": title_text.truncate(truncate_width, overflow="ellipsis") side_width = (width - cell_len(title_text.plain)) // 2 left = Text(characters * (side_width // chars_len + 1)) left.truncate(side_width - 1) right_length = width - cell_len(left.plain) - cell_len(title_text.plain) right = Text(characters * (side_width // chars_len + 1)) right.truncate(right_length) rule_text.append(left.plain + " ", self.style) rule_text.append(title_text) rule_text.append(" " + right.plain, self.style) elif self.align == "left": title_text.truncate(truncate_width, overflow="ellipsis") rule_text.append(title_text) rule_text.append(" ") rule_text.append(characters * (width - rule_text.cell_len), self.style) elif self.align == "right": title_text.truncate(truncate_width, overflow="ellipsis") rule_text.append(characters * (width - title_text.cell_len - 1), self.style) rule_text.append(" ") rule_text.append(title_text) rule_text.plain = set_cell_size(rule_text.plain, width) yield rule_text def _rule_line(self, chars_len: int, width: int) -> Text: rule_text = Text(self.characters * ((width // chars_len) + 1), self.style) rule_text.truncate(width) rule_text.plain = set_cell_size(rule_text.plain, width) return rule_text def __rich_measure__( self, console: Console, options: ConsoleOptions ) -> Measurement: return Measurement(1, 1) if __name__ == "__main__": # pragma: no cover import sys from rich.console import Console try: text = sys.argv[1] except IndexError: text = "Hello, World" console = Console() console.print(Rule(title=text)) console = Console() console.print(Rule("foo"), width=4)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/diagnose.py
rich/diagnose.py
import os import platform from rich import inspect from rich.console import Console, get_windows_console_features from rich.panel import Panel from rich.pretty import Pretty def report() -> None: # pragma: no cover """Print a report to the terminal with debugging information""" console = Console() inspect(console) features = get_windows_console_features() inspect(features) env_names = ( "CLICOLOR", "COLORTERM", "COLUMNS", "JPY_PARENT_PID", "JUPYTER_COLUMNS", "JUPYTER_LINES", "LINES", "NO_COLOR", "TERM_PROGRAM", "TERM", "TTY_COMPATIBLE", "TTY_INTERACTIVE", "VSCODE_VERBOSE_LOGGING", ) env = {name: os.getenv(name) for name in env_names} console.print(Panel.fit((Pretty(env)), title="[b]Environment Variables")) console.print(f'platform="{platform.system()}"') if __name__ == "__main__": # pragma: no cover report()
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/style.py
rich/style.py
import sys from functools import lru_cache from operator import attrgetter from pickle import dumps, loads from random import randint from typing import Any, Dict, Iterable, List, Optional, Type, Union, cast from . import errors from .color import Color, ColorParseError, ColorSystem, blend_rgb from .repr import Result, rich_repr from .terminal_theme import DEFAULT_TERMINAL_THEME, TerminalTheme _hash_getter = attrgetter( "_color", "_bgcolor", "_attributes", "_set_attributes", "_link", "_meta" ) # Style instances and style definitions are often interchangeable StyleType = Union[str, "Style"] class _Bit: """A descriptor to get/set a style attribute bit.""" __slots__ = ["bit"] def __init__(self, bit_no: int) -> None: self.bit = 1 << bit_no def __get__(self, obj: "Style", objtype: Type["Style"]) -> Optional[bool]: if obj._set_attributes & self.bit: return obj._attributes & self.bit != 0 return None @rich_repr class Style: """A terminal style. A terminal style consists of a color (`color`), a background color (`bgcolor`), and a number of attributes, such as bold, italic etc. The attributes have 3 states: they can either be on (``True``), off (``False``), or not set (``None``). Args: color (Union[Color, str], optional): Color of terminal text. Defaults to None. bgcolor (Union[Color, str], optional): Color of terminal background. Defaults to None. bold (bool, optional): Enable bold text. Defaults to None. dim (bool, optional): Enable dim text. Defaults to None. italic (bool, optional): Enable italic text. Defaults to None. underline (bool, optional): Enable underlined text. Defaults to None. blink (bool, optional): Enabled blinking text. Defaults to None. blink2 (bool, optional): Enable fast blinking text. Defaults to None. reverse (bool, optional): Enabled reverse text. Defaults to None. conceal (bool, optional): Enable concealed text. Defaults to None. strike (bool, optional): Enable strikethrough text. Defaults to None. underline2 (bool, optional): Enable doubly underlined text. Defaults to None. frame (bool, optional): Enable framed text. Defaults to None. encircle (bool, optional): Enable encircled text. Defaults to None. overline (bool, optional): Enable overlined text. Defaults to None. link (str, link): Link URL. Defaults to None. """ _color: Optional[Color] _bgcolor: Optional[Color] _attributes: int _set_attributes: int _hash: Optional[int] _null: bool _meta: Optional[bytes] __slots__ = [ "_color", "_bgcolor", "_attributes", "_set_attributes", "_link", "_link_id", "_ansi", "_style_definition", "_hash", "_null", "_meta", ] # maps bits on to SGR parameter _style_map = { 0: "1", 1: "2", 2: "3", 3: "4", 4: "5", 5: "6", 6: "7", 7: "8", 8: "9", 9: "21", 10: "51", 11: "52", 12: "53", } STYLE_ATTRIBUTES = { "dim": "dim", "d": "dim", "bold": "bold", "b": "bold", "italic": "italic", "i": "italic", "underline": "underline", "u": "underline", "blink": "blink", "blink2": "blink2", "reverse": "reverse", "r": "reverse", "conceal": "conceal", "c": "conceal", "strike": "strike", "s": "strike", "underline2": "underline2", "uu": "underline2", "frame": "frame", "encircle": "encircle", "overline": "overline", "o": "overline", } def __init__( self, *, color: Optional[Union[Color, str]] = None, bgcolor: Optional[Union[Color, str]] = None, bold: Optional[bool] = None, dim: Optional[bool] = None, italic: Optional[bool] = None, underline: Optional[bool] = None, blink: Optional[bool] = None, blink2: Optional[bool] = None, reverse: Optional[bool] = None, conceal: Optional[bool] = None, strike: Optional[bool] = None, underline2: Optional[bool] = None, frame: Optional[bool] = None, encircle: Optional[bool] = None, overline: Optional[bool] = None, link: Optional[str] = None, meta: Optional[Dict[str, Any]] = None, ): self._ansi: Optional[str] = None self._style_definition: Optional[str] = None def _make_color(color: Union[Color, str]) -> Color: return color if isinstance(color, Color) else Color.parse(color) self._color = None if color is None else _make_color(color) self._bgcolor = None if bgcolor is None else _make_color(bgcolor) self._set_attributes = sum( ( bold is not None, dim is not None and 2, italic is not None and 4, underline is not None and 8, blink is not None and 16, blink2 is not None and 32, reverse is not None and 64, conceal is not None and 128, strike is not None and 256, underline2 is not None and 512, frame is not None and 1024, encircle is not None and 2048, overline is not None and 4096, ) ) self._attributes = ( sum( ( bold and 1 or 0, dim and 2 or 0, italic and 4 or 0, underline and 8 or 0, blink and 16 or 0, blink2 and 32 or 0, reverse and 64 or 0, conceal and 128 or 0, strike and 256 or 0, underline2 and 512 or 0, frame and 1024 or 0, encircle and 2048 or 0, overline and 4096 or 0, ) ) if self._set_attributes else 0 ) self._link = link self._meta = None if meta is None else dumps(meta) self._link_id = ( f"{randint(0, 999999)}{hash(self._meta)}" if (link or meta) else "" ) self._hash: Optional[int] = None self._null = not (self._set_attributes or color or bgcolor or link or meta) @classmethod def null(cls) -> "Style": """Create an 'null' style, equivalent to Style(), but more performant.""" return NULL_STYLE @classmethod def from_color( cls, color: Optional[Color] = None, bgcolor: Optional[Color] = None ) -> "Style": """Create a new style with colors and no attributes. Returns: color (Optional[Color]): A (foreground) color, or None for no color. Defaults to None. bgcolor (Optional[Color]): A (background) color, or None for no color. Defaults to None. """ style: Style = cls.__new__(Style) style._ansi = None style._style_definition = None style._color = color style._bgcolor = bgcolor style._set_attributes = 0 style._attributes = 0 style._link = None style._link_id = "" style._meta = None style._null = not (color or bgcolor) style._hash = None return style @classmethod def from_meta(cls, meta: Optional[Dict[str, Any]]) -> "Style": """Create a new style with meta data. Returns: meta (Optional[Dict[str, Any]]): A dictionary of meta data. Defaults to None. """ style: Style = cls.__new__(Style) style._ansi = None style._style_definition = None style._color = None style._bgcolor = None style._set_attributes = 0 style._attributes = 0 style._link = None style._meta = dumps(meta) style._link_id = f"{randint(0, 999999)}{hash(style._meta)}" style._hash = None style._null = not (meta) return style @classmethod def on(cls, meta: Optional[Dict[str, Any]] = None, **handlers: Any) -> "Style": """Create a blank style with meta information. Example: style = Style.on(click=self.on_click) Args: meta (Optional[Dict[str, Any]], optional): An optional dict of meta information. **handlers (Any): Keyword arguments are translated in to handlers. Returns: Style: A Style with meta information attached. """ meta = {} if meta is None else meta meta.update({f"@{key}": value for key, value in handlers.items()}) return cls.from_meta(meta) bold = _Bit(0) dim = _Bit(1) italic = _Bit(2) underline = _Bit(3) blink = _Bit(4) blink2 = _Bit(5) reverse = _Bit(6) conceal = _Bit(7) strike = _Bit(8) underline2 = _Bit(9) frame = _Bit(10) encircle = _Bit(11) overline = _Bit(12) @property def link_id(self) -> str: """Get a link id, used in ansi code for links.""" return self._link_id def __str__(self) -> str: """Re-generate style definition from attributes.""" if self._style_definition is None: attributes: List[str] = [] append = attributes.append bits = self._set_attributes if bits & 0b0000000001111: if bits & 1: append("bold" if self.bold else "not bold") if bits & (1 << 1): append("dim" if self.dim else "not dim") if bits & (1 << 2): append("italic" if self.italic else "not italic") if bits & (1 << 3): append("underline" if self.underline else "not underline") if bits & 0b0000111110000: if bits & (1 << 4): append("blink" if self.blink else "not blink") if bits & (1 << 5): append("blink2" if self.blink2 else "not blink2") if bits & (1 << 6): append("reverse" if self.reverse else "not reverse") if bits & (1 << 7): append("conceal" if self.conceal else "not conceal") if bits & (1 << 8): append("strike" if self.strike else "not strike") if bits & 0b1111000000000: if bits & (1 << 9): append("underline2" if self.underline2 else "not underline2") if bits & (1 << 10): append("frame" if self.frame else "not frame") if bits & (1 << 11): append("encircle" if self.encircle else "not encircle") if bits & (1 << 12): append("overline" if self.overline else "not overline") if self._color is not None: append(self._color.name) if self._bgcolor is not None: append("on") append(self._bgcolor.name) if self._link: append("link") append(self._link) self._style_definition = " ".join(attributes) or "none" return self._style_definition def __bool__(self) -> bool: """A Style is false if it has no attributes, colors, or links.""" return not self._null def _make_ansi_codes(self, color_system: ColorSystem) -> str: """Generate ANSI codes for this style. Args: color_system (ColorSystem): Color system. Returns: str: String containing codes. """ if self._ansi is None: sgr: List[str] = [] append = sgr.append _style_map = self._style_map attributes = self._attributes & self._set_attributes if attributes: if attributes & 1: append(_style_map[0]) if attributes & 2: append(_style_map[1]) if attributes & 4: append(_style_map[2]) if attributes & 8: append(_style_map[3]) if attributes & 0b0000111110000: for bit in range(4, 9): if attributes & (1 << bit): append(_style_map[bit]) if attributes & 0b1111000000000: for bit in range(9, 13): if attributes & (1 << bit): append(_style_map[bit]) if self._color is not None: sgr.extend(self._color.downgrade(color_system).get_ansi_codes()) if self._bgcolor is not None: sgr.extend( self._bgcolor.downgrade(color_system).get_ansi_codes( foreground=False ) ) self._ansi = ";".join(sgr) return self._ansi @classmethod @lru_cache(maxsize=1024) def normalize(cls, style: str) -> str: """Normalize a style definition so that styles with the same effect have the same string representation. Args: style (str): A style definition. Returns: str: Normal form of style definition. """ try: return str(cls.parse(style)) except errors.StyleSyntaxError: return style.strip().lower() @classmethod def pick_first(cls, *values: Optional[StyleType]) -> StyleType: """Pick first non-None style.""" for value in values: if value is not None: return value raise ValueError("expected at least one non-None style") def __rich_repr__(self) -> Result: yield "color", self.color, None yield "bgcolor", self.bgcolor, None yield "bold", self.bold, None, yield "dim", self.dim, None, yield "italic", self.italic, None yield "underline", self.underline, None, yield "blink", self.blink, None yield "blink2", self.blink2, None yield "reverse", self.reverse, None yield "conceal", self.conceal, None yield "strike", self.strike, None yield "underline2", self.underline2, None yield "frame", self.frame, None yield "encircle", self.encircle, None yield "link", self.link, None if self._meta: yield "meta", self.meta def __eq__(self, other: Any) -> bool: if not isinstance(other, Style): return NotImplemented return self.__hash__() == other.__hash__() def __ne__(self, other: Any) -> bool: if not isinstance(other, Style): return NotImplemented return self.__hash__() != other.__hash__() def __hash__(self) -> int: if self._hash is not None: return self._hash self._hash = hash(_hash_getter(self)) return self._hash @property def color(self) -> Optional[Color]: """The foreground color or None if it is not set.""" return self._color @property def bgcolor(self) -> Optional[Color]: """The background color or None if it is not set.""" return self._bgcolor @property def link(self) -> Optional[str]: """Link text, if set.""" return self._link @property def transparent_background(self) -> bool: """Check if the style specified a transparent background.""" return self.bgcolor is None or self.bgcolor.is_default @property def background_style(self) -> "Style": """A Style with background only.""" return Style(bgcolor=self.bgcolor) @property def meta(self) -> Dict[str, Any]: """Get meta information (can not be changed after construction).""" return {} if self._meta is None else cast(Dict[str, Any], loads(self._meta)) @property def without_color(self) -> "Style": """Get a copy of the style with color removed.""" if self._null: return NULL_STYLE style: Style = self.__new__(Style) style._ansi = None style._style_definition = None style._color = None style._bgcolor = None style._attributes = self._attributes style._set_attributes = self._set_attributes style._link = self._link style._link_id = f"{randint(0, 999999)}" if self._link else "" style._null = False style._meta = None style._hash = None return style @classmethod @lru_cache(maxsize=4096) def parse(cls, style_definition: str) -> "Style": """Parse a style definition. Args: style_definition (str): A string containing a style. Raises: errors.StyleSyntaxError: If the style definition syntax is invalid. Returns: `Style`: A Style instance. """ if style_definition.strip() == "none" or not style_definition: return cls.null() STYLE_ATTRIBUTES = cls.STYLE_ATTRIBUTES color: Optional[str] = None bgcolor: Optional[str] = None attributes: Dict[str, Optional[Any]] = {} link: Optional[str] = None words = iter(style_definition.split()) for original_word in words: word = original_word.lower() if word == "on": word = next(words, "") if not word: raise errors.StyleSyntaxError("color expected after 'on'") try: Color.parse(word) except ColorParseError as error: raise errors.StyleSyntaxError( f"unable to parse {word!r} as background color; {error}" ) from None bgcolor = word elif word == "not": word = next(words, "") attribute = STYLE_ATTRIBUTES.get(word) if attribute is None: raise errors.StyleSyntaxError( f"expected style attribute after 'not', found {word!r}" ) attributes[attribute] = False elif word == "link": word = next(words, "") if not word: raise errors.StyleSyntaxError("URL expected after 'link'") link = word elif word in STYLE_ATTRIBUTES: attributes[STYLE_ATTRIBUTES[word]] = True else: try: Color.parse(word) except ColorParseError as error: raise errors.StyleSyntaxError( f"unable to parse {word!r} as color; {error}" ) from None color = word style = Style(color=color, bgcolor=bgcolor, link=link, **attributes) return style @lru_cache(maxsize=1024) def get_html_style(self, theme: Optional[TerminalTheme] = None) -> str: """Get a CSS style rule.""" theme = theme or DEFAULT_TERMINAL_THEME css: List[str] = [] append = css.append color = self.color bgcolor = self.bgcolor if self.reverse: color, bgcolor = bgcolor, color if self.dim: foreground_color = ( theme.foreground_color if color is None else color.get_truecolor(theme) ) color = Color.from_triplet( blend_rgb(foreground_color, theme.background_color, 0.5) ) if color is not None: theme_color = color.get_truecolor(theme) append(f"color: {theme_color.hex}") append(f"text-decoration-color: {theme_color.hex}") if bgcolor is not None: theme_color = bgcolor.get_truecolor(theme, foreground=False) append(f"background-color: {theme_color.hex}") if self.bold: append("font-weight: bold") if self.italic: append("font-style: italic") if self.underline: append("text-decoration: underline") if self.strike: append("text-decoration: line-through") if self.overline: append("text-decoration: overline") return "; ".join(css) @classmethod def combine(cls, styles: Iterable["Style"]) -> "Style": """Combine styles and get result. Args: styles (Iterable[Style]): Styles to combine. Returns: Style: A new style instance. """ iter_styles = iter(styles) return sum(iter_styles, next(iter_styles)) @classmethod def chain(cls, *styles: "Style") -> "Style": """Combine styles from positional argument in to a single style. Args: *styles (Iterable[Style]): Styles to combine. Returns: Style: A new style instance. """ iter_styles = iter(styles) return sum(iter_styles, next(iter_styles)) def copy(self) -> "Style": """Get a copy of this style. Returns: Style: A new Style instance with identical attributes. """ if self._null: return NULL_STYLE style: Style = self.__new__(Style) style._ansi = self._ansi style._style_definition = self._style_definition style._color = self._color style._bgcolor = self._bgcolor style._attributes = self._attributes style._set_attributes = self._set_attributes style._link = self._link style._link_id = f"{randint(0, 999999)}" if self._link else "" style._hash = self._hash style._null = False style._meta = self._meta return style @lru_cache(maxsize=128) def clear_meta_and_links(self) -> "Style": """Get a copy of this style with link and meta information removed. Returns: Style: New style object. """ if self._null: return NULL_STYLE style: Style = self.__new__(Style) style._ansi = self._ansi style._style_definition = self._style_definition style._color = self._color style._bgcolor = self._bgcolor style._attributes = self._attributes style._set_attributes = self._set_attributes style._link = None style._link_id = "" style._hash = None style._null = False style._meta = None return style def update_link(self, link: Optional[str] = None) -> "Style": """Get a copy with a different value for link. Args: link (str, optional): New value for link. Defaults to None. Returns: Style: A new Style instance. """ style: Style = self.__new__(Style) style._ansi = self._ansi style._style_definition = self._style_definition style._color = self._color style._bgcolor = self._bgcolor style._attributes = self._attributes style._set_attributes = self._set_attributes style._link = link style._link_id = f"{randint(0, 999999)}" if link else "" style._hash = None style._null = False style._meta = self._meta return style def render( self, text: str = "", *, color_system: Optional[ColorSystem] = ColorSystem.TRUECOLOR, legacy_windows: bool = False, ) -> str: """Render the ANSI codes for the style. Args: text (str, optional): A string to style. Defaults to "". color_system (Optional[ColorSystem], optional): Color system to render to. Defaults to ColorSystem.TRUECOLOR. Returns: str: A string containing ANSI style codes. """ if not text or color_system is None: return text attrs = self._ansi or self._make_ansi_codes(color_system) rendered = f"\x1b[{attrs}m{text}\x1b[0m" if attrs else text if self._link and not legacy_windows: rendered = ( f"\x1b]8;id={self._link_id};{self._link}\x1b\\{rendered}\x1b]8;;\x1b\\" ) return rendered def test(self, text: Optional[str] = None) -> None: """Write text with style directly to terminal. This method is for testing purposes only. Args: text (Optional[str], optional): Text to style or None for style name. """ text = text or str(self) sys.stdout.write(f"{self.render(text)}\n") @lru_cache(maxsize=1024) def _add(self, style: Optional["Style"]) -> "Style": if style is None or style._null: return self if self._null: return style new_style: Style = self.__new__(Style) new_style._ansi = None new_style._style_definition = None new_style._color = style._color or self._color new_style._bgcolor = style._bgcolor or self._bgcolor new_style._attributes = (self._attributes & ~style._set_attributes) | ( style._attributes & style._set_attributes ) new_style._set_attributes = self._set_attributes | style._set_attributes new_style._link = style._link or self._link new_style._link_id = style._link_id or self._link_id new_style._null = style._null if self._meta and style._meta: new_style._meta = dumps({**self.meta, **style.meta}) else: new_style._meta = self._meta or style._meta new_style._hash = None return new_style def __add__(self, style: Optional["Style"]) -> "Style": combined_style = self._add(style) return combined_style.copy() if combined_style.link else combined_style NULL_STYLE = Style() class StyleStack: """A stack of styles.""" __slots__ = ["_stack"] def __init__(self, default_style: "Style") -> None: self._stack: List[Style] = [default_style] def __repr__(self) -> str: return f"<stylestack {self._stack!r}>" @property def current(self) -> Style: """Get the Style at the top of the stack.""" return self._stack[-1] def push(self, style: Style) -> None: """Push a new style on to the stack. Args: style (Style): New style to combine with current style. """ self._stack.append(self._stack[-1] + style) def pop(self) -> Style: """Pop last style and discard. Returns: Style: New current style (also available as stack.current) """ self._stack.pop() return self._stack[-1]
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/padding.py
rich/padding.py
from typing import TYPE_CHECKING, List, Optional, Tuple, Union if TYPE_CHECKING: from .console import ( Console, ConsoleOptions, RenderableType, RenderResult, ) from .jupyter import JupyterMixin from .measure import Measurement from .segment import Segment from .style import Style PaddingDimensions = Union[int, Tuple[int], Tuple[int, int], Tuple[int, int, int, int]] class Padding(JupyterMixin): """Draw space around content. Example: >>> print(Padding("Hello", (2, 4), style="on blue")) Args: renderable (RenderableType): String or other renderable. pad (Union[int, Tuple[int]]): Padding for top, right, bottom, and left borders. May be specified with 1, 2, or 4 integers (CSS style). style (Union[str, Style], optional): Style for padding characters. Defaults to "none". expand (bool, optional): Expand padding to fit available width. Defaults to True. """ def __init__( self, renderable: "RenderableType", pad: "PaddingDimensions" = (0, 0, 0, 0), *, style: Union[str, Style] = "none", expand: bool = True, ): self.renderable = renderable self.top, self.right, self.bottom, self.left = self.unpack(pad) self.style = style self.expand = expand @classmethod def indent(cls, renderable: "RenderableType", level: int) -> "Padding": """Make padding instance to render an indent. Args: renderable (RenderableType): String or other renderable. level (int): Number of characters to indent. Returns: Padding: A Padding instance. """ return Padding(renderable, pad=(0, 0, 0, level), expand=False) @staticmethod def unpack(pad: "PaddingDimensions") -> Tuple[int, int, int, int]: """Unpack padding specified in CSS style.""" if isinstance(pad, int): return (pad, pad, pad, pad) if len(pad) == 1: _pad = pad[0] return (_pad, _pad, _pad, _pad) if len(pad) == 2: pad_top, pad_right = pad return (pad_top, pad_right, pad_top, pad_right) if len(pad) == 4: top, right, bottom, left = pad return (top, right, bottom, left) raise ValueError(f"1, 2 or 4 integers required for padding; {len(pad)} given") def __repr__(self) -> str: return f"Padding({self.renderable!r}, ({self.top},{self.right},{self.bottom},{self.left}))" def __rich_console__( self, console: "Console", options: "ConsoleOptions" ) -> "RenderResult": style = console.get_style(self.style) if self.expand: width = options.max_width else: width = min( Measurement.get(console, options, self.renderable).maximum + self.left + self.right, options.max_width, ) render_options = options.update_width(width - self.left - self.right) if render_options.height is not None: render_options = render_options.update_height( height=render_options.height - self.top - self.bottom ) lines = console.render_lines( self.renderable, render_options, style=style, pad=True ) _Segment = Segment left = _Segment(" " * self.left, style) if self.left else None right = ( [_Segment(f'{" " * self.right}', style), _Segment.line()] if self.right else [_Segment.line()] ) blank_line: Optional[List[Segment]] = None if self.top: blank_line = [_Segment(f'{" " * width}\n', style)] yield from blank_line * self.top if left: for line in lines: yield left yield from line yield from right else: for line in lines: yield from line yield from right if self.bottom: blank_line = blank_line or [_Segment(f'{" " * width}\n', style)] yield from blank_line * self.bottom def __rich_measure__( self, console: "Console", options: "ConsoleOptions" ) -> "Measurement": max_width = options.max_width extra_width = self.left + self.right if max_width - extra_width < 1: return Measurement(max_width, max_width) measure_min, measure_max = Measurement.get(console, options, self.renderable) measurement = Measurement(measure_min + extra_width, measure_max + extra_width) measurement = measurement.with_maximum(max_width) return measurement if __name__ == "__main__": # pragma: no cover from rich import print print(Padding("Hello, World", (2, 4), style="on blue"))
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/rich/layout.py
rich/layout.py
from abc import ABC, abstractmethod from itertools import islice from operator import itemgetter from threading import RLock from typing import ( TYPE_CHECKING, Dict, Iterable, List, NamedTuple, Optional, Sequence, Tuple, Union, ) from ._ratio import ratio_resolve from .align import Align from .console import Console, ConsoleOptions, RenderableType, RenderResult from .highlighter import ReprHighlighter from .panel import Panel from .pretty import Pretty from .region import Region from .repr import Result, rich_repr from .segment import Segment from .style import StyleType if TYPE_CHECKING: from rich.tree import Tree class LayoutRender(NamedTuple): """An individual layout render.""" region: Region render: List[List[Segment]] RegionMap = Dict["Layout", Region] RenderMap = Dict["Layout", LayoutRender] class LayoutError(Exception): """Layout related error.""" class NoSplitter(LayoutError): """Requested splitter does not exist.""" class _Placeholder: """An internal renderable used as a Layout placeholder.""" highlighter = ReprHighlighter() def __init__(self, layout: "Layout", style: StyleType = "") -> None: self.layout = layout self.style = style def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: width = options.max_width height = options.height or options.size.height layout = self.layout title = ( f"{layout.name!r} ({width} x {height})" if layout.name else f"({width} x {height})" ) yield Panel( Align.center(Pretty(layout), vertical="middle"), style=self.style, title=self.highlighter(title), border_style="blue", height=height, ) class Splitter(ABC): """Base class for a splitter.""" name: str = "" @abstractmethod def get_tree_icon(self) -> str: """Get the icon (emoji) used in layout.tree""" @abstractmethod def divide( self, children: Sequence["Layout"], region: Region ) -> Iterable[Tuple["Layout", Region]]: """Divide a region amongst several child layouts. Args: children (Sequence(Layout)): A number of child layouts. region (Region): A rectangular region to divide. """ class RowSplitter(Splitter): """Split a layout region in to rows.""" name = "row" def get_tree_icon(self) -> str: return "[layout.tree.row]⬌" def divide( self, children: Sequence["Layout"], region: Region ) -> Iterable[Tuple["Layout", Region]]: x, y, width, height = region render_widths = ratio_resolve(width, children) offset = 0 _Region = Region for child, child_width in zip(children, render_widths): yield child, _Region(x + offset, y, child_width, height) offset += child_width class ColumnSplitter(Splitter): """Split a layout region in to columns.""" name = "column" def get_tree_icon(self) -> str: return "[layout.tree.column]⬍" def divide( self, children: Sequence["Layout"], region: Region ) -> Iterable[Tuple["Layout", Region]]: x, y, width, height = region render_heights = ratio_resolve(height, children) offset = 0 _Region = Region for child, child_height in zip(children, render_heights): yield child, _Region(x, y + offset, width, child_height) offset += child_height @rich_repr class Layout: """A renderable to divide a fixed height in to rows or columns. Args: renderable (RenderableType, optional): Renderable content, or None for placeholder. Defaults to None. name (str, optional): Optional identifier for Layout. Defaults to None. size (int, optional): Optional fixed size of layout. Defaults to None. minimum_size (int, optional): Minimum size of layout. Defaults to 1. ratio (int, optional): Optional ratio for flexible layout. Defaults to 1. visible (bool, optional): Visibility of layout. Defaults to True. """ splitters = {"row": RowSplitter, "column": ColumnSplitter} def __init__( self, renderable: Optional[RenderableType] = None, *, name: Optional[str] = None, size: Optional[int] = None, minimum_size: int = 1, ratio: int = 1, visible: bool = True, ) -> None: self._renderable = renderable or _Placeholder(self) self.size = size self.minimum_size = minimum_size self.ratio = ratio self.name = name self.visible = visible self.splitter: Splitter = self.splitters["column"]() self._children: List[Layout] = [] self._render_map: RenderMap = {} self._lock = RLock() def __rich_repr__(self) -> Result: yield "name", self.name, None yield "size", self.size, None yield "minimum_size", self.minimum_size, 1 yield "ratio", self.ratio, 1 @property def renderable(self) -> RenderableType: """Layout renderable.""" return self if self._children else self._renderable @property def children(self) -> List["Layout"]: """Gets (visible) layout children.""" return [child for child in self._children if child.visible] @property def map(self) -> RenderMap: """Get a map of the last render.""" return self._render_map def get(self, name: str) -> Optional["Layout"]: """Get a named layout, or None if it doesn't exist. Args: name (str): Name of layout. Returns: Optional[Layout]: Layout instance or None if no layout was found. """ if self.name == name: return self else: for child in self._children: named_layout = child.get(name) if named_layout is not None: return named_layout return None def __getitem__(self, name: str) -> "Layout": layout = self.get(name) if layout is None: raise KeyError(f"No layout with name {name!r}") return layout @property def tree(self) -> "Tree": """Get a tree renderable to show layout structure.""" from rich.styled import Styled from rich.table import Table from rich.tree import Tree def summary(layout: "Layout") -> Table: icon = layout.splitter.get_tree_icon() table = Table.grid(padding=(0, 1, 0, 0)) text: RenderableType = ( Pretty(layout) if layout.visible else Styled(Pretty(layout), "dim") ) table.add_row(icon, text) _summary = table return _summary layout = self tree = Tree( summary(layout), guide_style=f"layout.tree.{layout.splitter.name}", highlight=True, ) def recurse(tree: "Tree", layout: "Layout") -> None: for child in layout._children: recurse( tree.add( summary(child), guide_style=f"layout.tree.{child.splitter.name}", ), child, ) recurse(tree, self) return tree def split( self, *layouts: Union["Layout", RenderableType], splitter: Union[Splitter, str] = "column", ) -> None: """Split the layout in to multiple sub-layouts. Args: *layouts (Layout): Positional arguments should be (sub) Layout instances. splitter (Union[Splitter, str]): Splitter instance or name of splitter. """ _layouts = [ layout if isinstance(layout, Layout) else Layout(layout) for layout in layouts ] try: self.splitter = ( splitter if isinstance(splitter, Splitter) else self.splitters[splitter]() ) except KeyError: raise NoSplitter(f"No splitter called {splitter!r}") self._children[:] = _layouts def add_split(self, *layouts: Union["Layout", RenderableType]) -> None: """Add a new layout(s) to existing split. Args: *layouts (Union[Layout, RenderableType]): Positional arguments should be renderables or (sub) Layout instances. """ _layouts = ( layout if isinstance(layout, Layout) else Layout(layout) for layout in layouts ) self._children.extend(_layouts) def split_row(self, *layouts: Union["Layout", RenderableType]) -> None: """Split the layout in to a row (layouts side by side). Args: *layouts (Layout): Positional arguments should be (sub) Layout instances. """ self.split(*layouts, splitter="row") def split_column(self, *layouts: Union["Layout", RenderableType]) -> None: """Split the layout in to a column (layouts stacked on top of each other). Args: *layouts (Layout): Positional arguments should be (sub) Layout instances. """ self.split(*layouts, splitter="column") def unsplit(self) -> None: """Reset splits to initial state.""" del self._children[:] def update(self, renderable: RenderableType) -> None: """Update renderable. Args: renderable (RenderableType): New renderable object. """ with self._lock: self._renderable = renderable def refresh_screen(self, console: "Console", layout_name: str) -> None: """Refresh a sub-layout. Args: console (Console): Console instance where Layout is to be rendered. layout_name (str): Name of layout. """ with self._lock: layout = self[layout_name] region, _lines = self._render_map[layout] (x, y, width, height) = region lines = console.render_lines( layout, console.options.update_dimensions(width, height) ) self._render_map[layout] = LayoutRender(region, lines) console.update_screen_lines(lines, x, y) def _make_region_map(self, width: int, height: int) -> RegionMap: """Create a dict that maps layout on to Region.""" stack: List[Tuple[Layout, Region]] = [(self, Region(0, 0, width, height))] push = stack.append pop = stack.pop layout_regions: List[Tuple[Layout, Region]] = [] append_layout_region = layout_regions.append while stack: append_layout_region(pop()) layout, region = layout_regions[-1] children = layout.children if children: for child_and_region in layout.splitter.divide(children, region): push(child_and_region) region_map = { layout: region for layout, region in sorted(layout_regions, key=itemgetter(1)) } return region_map def render(self, console: Console, options: ConsoleOptions) -> RenderMap: """Render the sub_layouts. Args: console (Console): Console instance. options (ConsoleOptions): Console options. Returns: RenderMap: A dict that maps Layout on to a tuple of Region, lines """ render_width = options.max_width render_height = options.height or console.height region_map = self._make_region_map(render_width, render_height) layout_regions = [ (layout, region) for layout, region in region_map.items() if not layout.children ] render_map: Dict["Layout", "LayoutRender"] = {} render_lines = console.render_lines update_dimensions = options.update_dimensions for layout, region in layout_regions: lines = render_lines( layout.renderable, update_dimensions(region.width, region.height) ) render_map[layout] = LayoutRender(region, lines) return render_map def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: with self._lock: width = options.max_width or console.width height = options.height or console.height render_map = self.render(console, options.update_dimensions(width, height)) self._render_map = render_map layout_lines: List[List[Segment]] = [[] for _ in range(height)] _islice = islice for region, lines in render_map.values(): _x, y, _layout_width, layout_height = region for row, line in zip( _islice(layout_lines, y, y + layout_height), lines ): row.extend(line) new_line = Segment.line() for layout_row in layout_lines: yield from layout_row yield new_line if __name__ == "__main__": from rich.console import Console console = Console() layout = Layout() layout.split_column( Layout(name="header", size=3), Layout(ratio=1, name="main"), Layout(size=10, name="footer"), ) layout["main"].split_row(Layout(name="side"), Layout(name="body", ratio=2)) layout["body"].split_row(Layout(name="content", ratio=2), Layout(name="s2")) layout["s2"].split_column( Layout(name="top"), Layout(name="middle"), Layout(name="bottom") ) layout["side"].split_column(Layout(layout.tree, name="left1"), Layout(name="left2")) layout["content"].update("foo") console.print(layout)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_theme.py
tests/test_theme.py
import io import os import tempfile import pytest from rich.style import Style from rich.theme import Theme, ThemeStack, ThemeStackError def test_inherit(): theme = Theme({"warning": "red"}) assert theme.styles["warning"] == Style(color="red") assert theme.styles["dim"] == Style(dim=True) def test_config(): theme = Theme({"warning": "red"}) config = theme.config assert "warning = red\n" in config def test_from_file(): theme = Theme({"warning": "red"}) text_file = io.StringIO() text_file.write(theme.config) text_file.seek(0) load_theme = Theme.from_file(text_file) assert theme.styles == load_theme.styles def test_read(): theme = Theme({"warning": "red"}) with tempfile.TemporaryDirectory("richtheme") as name: filename = os.path.join(name, "theme.cfg") with open(filename, "wt") as write_theme: write_theme.write(theme.config) load_theme = Theme.read(filename) assert theme.styles == load_theme.styles def test_theme_stack(): theme = Theme({"warning": "red"}) stack = ThemeStack(theme) assert stack.get("warning") == Style.parse("red") new_theme = Theme({"warning": "bold yellow"}) stack.push_theme(new_theme) assert stack.get("warning") == Style.parse("bold yellow") stack.pop_theme() assert stack.get("warning") == Style.parse("red") with pytest.raises(ThemeStackError): stack.pop_theme()
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_live.py
tests/test_live.py
# encoding=utf-8 import time from typing import Optional # import pytest from rich.console import Console from rich.live import Live from rich.text import Text def create_capture_console( *, width: int = 60, height: int = 80, force_terminal: Optional[bool] = True ) -> Console: return Console( width=width, height=height, force_terminal=force_terminal, legacy_windows=False, color_system=None, # use no color system to reduce complexity of output, _environ={}, ) def test_live_state() -> None: with Live("") as live: assert live._started live.start() assert live.get_renderable() == "" assert live._started live.stop() assert not live._started assert not live._started def test_growing_display() -> None: console = create_capture_console() console.begin_capture() with Live(console=console, auto_refresh=False) as live: display = "" for step in range(10): display += f"Step {step}\n" live.update(display, refresh=True) output = console.end_capture() print(repr(output)) assert ( output == "\x1b[?25lStep 0\n\r\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\nStep 6\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\nStep 6\nStep 7\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\nStep 6\nStep 7\nStep 8\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\nStep 6\nStep 7\nStep 8\nStep 9\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\nStep 6\nStep 7\nStep 8\nStep 9\n\n\x1b[?25h" ) def test_growing_display_transient() -> None: console = create_capture_console() console.begin_capture() with Live(console=console, auto_refresh=False, transient=True) as live: display = "" for step in range(10): display += f"Step {step}\n" live.update(display, refresh=True) output = console.end_capture() assert ( output == "\x1b[?25lStep 0\n\r\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\nStep 6\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\nStep 6\nStep 7\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\nStep 6\nStep 7\nStep 8\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\nStep 6\nStep 7\nStep 8\nStep 9\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\nStep 6\nStep 7\nStep 8\nStep 9\n\n\x1b[?25h\r\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K" ) def test_growing_display_overflow_ellipsis() -> None: console = create_capture_console(height=5) console.begin_capture() with Live( console=console, auto_refresh=False, vertical_overflow="ellipsis" ) as live: display = "" for step in range(10): display += f"Step {step}\n" live.update(display, refresh=True) output = console.end_capture() assert ( output == "\x1b[?25lStep 0\n\r\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\n ... \r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\n ... \r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\n ... \r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\n ... \r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\n ... \r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\n ... \r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\nStep 6\nStep 7\nStep 8\nStep 9\n\n\x1b[?25h" ) def test_growing_display_overflow_crop() -> None: console = create_capture_console(height=5) console.begin_capture() with Live(console=console, auto_refresh=False, vertical_overflow="crop") as live: display = "" for step in range(10): display += f"Step {step}\n" live.update(display, refresh=True) output = console.end_capture() assert ( output == "\x1b[?25lStep 0\n\r\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\nStep 6\nStep 7\nStep 8\nStep 9\n\n\x1b[?25h" ) def test_growing_display_overflow_visible() -> None: console = create_capture_console(height=5) console.begin_capture() with Live(console=console, auto_refresh=False, vertical_overflow="visible") as live: display = "" for step in range(10): display += f"Step {step}\n" live.update(display, refresh=True) output = console.end_capture() assert ( output == "\x1b[?25lStep 0\n\r\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\nStep 6\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\nStep 6\nStep 7\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\nStep 6\nStep 7\nStep 8\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\nStep 6\nStep 7\nStep 8\nStep 9\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\nStep 6\nStep 7\nStep 8\nStep 9\n\n\x1b[?25h" ) def test_growing_display_autorefresh() -> None: """Test generating a table but using auto-refresh from threading""" console = create_capture_console(height=5) console.begin_capture() with Live(console=console, auto_refresh=True, vertical_overflow="visible") as live: display = "" for step in range(10): display += f"Step {step}\n" live.update(display) time.sleep(0.2) # no way to truly test w/ multithreading, just make sure it doesn't crash def test_growing_display_console_redirect() -> None: console = create_capture_console() console.begin_capture() with Live(console=console, auto_refresh=False) as live: display = "" for step in range(10): console.print(f"Running step {step}") display += f"Step {step}\n" live.update(display, refresh=True) output = console.end_capture() assert ( output == "\x1b[?25lRunning step 0\n\r\x1b[2KStep 0\n\r\x1b[2K\x1b[1A\x1b[2KRunning step 1\nStep 0\n\r\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KRunning step 2\nStep 0\nStep 1\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KRunning step 3\nStep 0\nStep 1\nStep 2\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KRunning step 4\nStep 0\nStep 1\nStep 2\nStep 3\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KRunning step 5\nStep 0\nStep 1\nStep 2\nStep 3\nStep 4\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KRunning step 6\nStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\nStep 6\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KRunning step 7\nStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\nStep 6\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\nStep 6\nStep 7\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KRunning step 8\nStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\nStep 6\nStep 7\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\nStep 6\nStep 7\nStep 8\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KRunning step 9\nStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\nStep 6\nStep 7\nStep 8\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\nStep 6\nStep 7\nStep 8\nStep 9\n\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2KStep 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\nStep 6\nStep 7\nStep 8\nStep 9\n\n\x1b[?25h" ) def test_growing_display_file_console() -> None: console = create_capture_console(force_terminal=False) console.begin_capture() with Live(console=console, auto_refresh=False) as live: display = "" for step in range(10): display += f"Step {step}\n" live.update(display, refresh=True) output = console.end_capture() assert ( output == "Step 0\nStep 1\nStep 2\nStep 3\nStep 4\nStep 5\nStep 6\nStep 7\nStep 8\nStep 9\n" ) def test_live_screen() -> None: console = create_capture_console(width=20, height=5) console.begin_capture() with Live(Text("foo"), screen=True, console=console, auto_refresh=False) as live: live.refresh() result = console.end_capture() print(repr(result)) expected = "\x1b[?1049h\x1b[H\x1b[?25l\x1b[Hfoo \n \n \n \n \x1b[Hfoo \n \n \n \n \x1b[?25h\x1b[?1049l" assert result == expected
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_color.py
tests/test_color.py
from rich.color import ( blend_rgb, parse_rgb_hex, Color, ColorParseError, ColorSystem, ColorType, ColorTriplet, ) from rich.style import Style from rich.text import Text, Span import pytest def test_str() -> None: assert str(Color.parse("red")) == "Color('red', ColorType.STANDARD, number=1)" def test_repr() -> None: assert repr(Color.parse("red")) == "Color('red', ColorType.STANDARD, number=1)" def test_color_system_repr() -> None: assert repr(ColorSystem.EIGHT_BIT) == "ColorSystem.EIGHT_BIT" def test_rich() -> None: color = Color.parse("red") as_text = color.__rich__() print(repr(as_text)) print(repr(as_text.spans)) assert as_text == Text( "<color 'red' (standard)⬤ >", spans=[Span(23, 24, Style(color=color))] ) def test_system() -> None: assert Color.parse("default").system == ColorSystem.STANDARD assert Color.parse("red").system == ColorSystem.STANDARD assert Color.parse("#ff0000").system == ColorSystem.TRUECOLOR def test_windows() -> None: assert Color("red", ColorType.WINDOWS, number=1).get_ansi_codes() == ("31",) def test_truecolor() -> None: assert Color.parse("#ff0000").get_truecolor() == ColorTriplet(255, 0, 0) assert Color.parse("red").get_truecolor() == ColorTriplet(128, 0, 0) assert Color.parse("color(1)").get_truecolor() == ColorTriplet(128, 0, 0) assert Color.parse("color(17)").get_truecolor() == ColorTriplet(0, 0, 95) assert Color.parse("default").get_truecolor() == ColorTriplet(0, 0, 0) assert Color.parse("default").get_truecolor(foreground=False) == ColorTriplet( 255, 255, 255 ) assert Color("red", ColorType.WINDOWS, number=1).get_truecolor() == ColorTriplet( 197, 15, 31 ) def test_parse_success() -> None: assert Color.parse("default") == Color("default", ColorType.DEFAULT, None, None) assert Color.parse("red") == Color("red", ColorType.STANDARD, 1, None) assert Color.parse("bright_red") == Color("bright_red", ColorType.STANDARD, 9, None) assert Color.parse("yellow4") == Color("yellow4", ColorType.EIGHT_BIT, 106, None) assert Color.parse("color(100)") == Color( "color(100)", ColorType.EIGHT_BIT, 100, None ) assert Color.parse("#112233") == Color( "#112233", ColorType.TRUECOLOR, None, ColorTriplet(0x11, 0x22, 0x33) ) assert Color.parse("rgb(90,100,110)") == Color( "rgb(90,100,110)", ColorType.TRUECOLOR, None, ColorTriplet(90, 100, 110) ) def test_from_triplet() -> None: assert Color.from_triplet(ColorTriplet(0x10, 0x20, 0x30)) == Color( "#102030", ColorType.TRUECOLOR, None, ColorTriplet(0x10, 0x20, 0x30) ) def test_from_rgb() -> None: assert Color.from_rgb(0x10, 0x20, 0x30) == Color( "#102030", ColorType.TRUECOLOR, None, ColorTriplet(0x10, 0x20, 0x30) ) def test_from_ansi() -> None: assert Color.from_ansi(1) == Color("color(1)", ColorType.STANDARD, 1) def test_default() -> None: assert Color.default() == Color("default", ColorType.DEFAULT, None, None) def test_parse_error() -> None: with pytest.raises(ColorParseError): Color.parse("256") with pytest.raises(ColorParseError): Color.parse("color(256)") with pytest.raises(ColorParseError): Color.parse("rgb(999,0,0)") with pytest.raises(ColorParseError): Color.parse("rgb(0,0)") with pytest.raises(ColorParseError): Color.parse("rgb(0,0,0,0)") with pytest.raises(ColorParseError): Color.parse("nosuchcolor") with pytest.raises(ColorParseError): Color.parse("#xxyyzz") def test_get_ansi_codes() -> None: assert Color.parse("default").get_ansi_codes() == ("39",) assert Color.parse("default").get_ansi_codes(False) == ("49",) assert Color.parse("red").get_ansi_codes() == ("31",) assert Color.parse("red").get_ansi_codes(False) == ("41",) assert Color.parse("color(1)").get_ansi_codes() == ("31",) assert Color.parse("color(1)").get_ansi_codes(False) == ("41",) assert Color.parse("#ff0000").get_ansi_codes() == ("38", "2", "255", "0", "0") assert Color.parse("#ff0000").get_ansi_codes(False) == ("48", "2", "255", "0", "0") def test_downgrade() -> None: assert Color.parse("color(9)").downgrade(0) == Color( "color(9)", ColorType.STANDARD, 9, None ) assert Color.parse("#000000").downgrade(ColorSystem.EIGHT_BIT) == Color( "#000000", ColorType.EIGHT_BIT, 16, None ) assert Color.parse("#ffffff").downgrade(ColorSystem.EIGHT_BIT) == Color( "#ffffff", ColorType.EIGHT_BIT, 231, None ) assert Color.parse("#404142").downgrade(ColorSystem.EIGHT_BIT) == Color( "#404142", ColorType.EIGHT_BIT, 237, None ) assert Color.parse("#ff0000").downgrade(ColorSystem.EIGHT_BIT) == Color( "#ff0000", ColorType.EIGHT_BIT, 196, None ) assert Color.parse("#ff0000").downgrade(ColorSystem.STANDARD) == Color( "#ff0000", ColorType.STANDARD, 1, None ) assert Color.parse("color(9)").downgrade(ColorSystem.STANDARD) == Color( "color(9)", ColorType.STANDARD, 9, None ) assert Color.parse("color(20)").downgrade(ColorSystem.STANDARD) == Color( "color(20)", ColorType.STANDARD, 4, None ) assert Color.parse("red").downgrade(ColorSystem.WINDOWS) == Color( "red", ColorType.WINDOWS, 1, None ) assert Color.parse("bright_red").downgrade(ColorSystem.WINDOWS) == Color( "bright_red", ColorType.WINDOWS, 9, None ) assert Color.parse("#ff0000").downgrade(ColorSystem.WINDOWS) == Color( "#ff0000", ColorType.WINDOWS, 1, None ) assert Color.parse("color(255)").downgrade(ColorSystem.WINDOWS) == Color( "color(255)", ColorType.WINDOWS, 15, None ) assert Color.parse("#00ff00").downgrade(ColorSystem.STANDARD) == Color( "#00ff00", ColorType.STANDARD, 2, None ) def test_parse_rgb_hex() -> None: assert parse_rgb_hex("aabbcc") == ColorTriplet(0xAA, 0xBB, 0xCC) def test_blend_rgb() -> None: assert blend_rgb( ColorTriplet(10, 20, 30), ColorTriplet(30, 40, 50) ) == ColorTriplet(20, 30, 40)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_highlighter.py
tests/test_highlighter.py
"""Tests for the highlighter classes.""" import json from typing import List import pytest from rich.highlighter import ( ISO8601Highlighter, JSONHighlighter, NullHighlighter, ReprHighlighter, ) from rich.text import Span, Text def test_wrong_type(): highlighter = NullHighlighter() with pytest.raises(TypeError): highlighter([]) highlight_tests = [ ("", []), (" ", []), ( "<foo>", [ Span(0, 1, "repr.tag_start"), Span(1, 4, "repr.tag_name"), Span(4, 5, "repr.tag_end"), ], ), ( "<foo: 23>", [ Span(0, 1, "repr.tag_start"), Span(1, 5, "repr.tag_name"), Span(5, 8, "repr.tag_contents"), Span(8, 9, "repr.tag_end"), Span(6, 8, "repr.number"), ], ), ( "<foo: <bar: 23>>", [ Span(0, 1, "repr.tag_start"), Span(1, 5, "repr.tag_name"), Span(5, 15, "repr.tag_contents"), Span(15, 16, "repr.tag_end"), Span(12, 14, "repr.number"), ], ), ( "False True None", [ Span(0, 5, "repr.bool_false"), Span(6, 10, "repr.bool_true"), Span(11, 15, "repr.none"), ], ), ("foo=bar", [Span(0, 3, "repr.attrib_name"), Span(4, 7, "repr.attrib_value")]), ( 'foo="bar"', [ Span(0, 3, "repr.attrib_name"), Span(4, 9, "repr.attrib_value"), Span(4, 9, "repr.str"), ], ), ( "<Permission.WRITE|READ: 3>", [ Span(0, 1, "repr.tag_start"), Span(1, 23, "repr.tag_name"), Span(23, 25, "repr.tag_contents"), Span(25, 26, "repr.tag_end"), Span(24, 25, "repr.number"), ], ), ("( )", [Span(0, 1, "repr.brace"), Span(2, 3, "repr.brace")]), ("[ ]", [Span(0, 1, "repr.brace"), Span(2, 3, "repr.brace")]), ("{ }", [Span(0, 1, "repr.brace"), Span(2, 3, "repr.brace")]), (" 1 ", [Span(1, 2, "repr.number")]), (" 1.2 ", [Span(1, 4, "repr.number")]), (" 0xff ", [Span(1, 5, "repr.number")]), (" 1e10 ", [Span(1, 5, "repr.number")]), (" 1j ", [Span(1, 3, "repr.number_complex")]), (" 3.14j ", [Span(1, 6, "repr.number_complex")]), ( " (3.14+2.06j) ", [ Span(1, 2, "repr.brace"), Span(12, 13, "repr.brace"), Span(2, 12, "repr.number_complex"), ], ), ( " (3+2j) ", [ Span(1, 2, "repr.brace"), Span(6, 7, "repr.brace"), Span(2, 6, "repr.number_complex"), ], ), ( " (123456.4321-1234.5678j) ", [ Span(1, 2, "repr.brace"), Span(24, 25, "repr.brace"), Span(2, 24, "repr.number_complex"), ], ), ( " (-123123-2.1312342342423422e+25j) ", [ Span(1, 2, "repr.brace"), Span(33, 34, "repr.brace"), Span(2, 33, "repr.number_complex"), ], ), (" /foo ", [Span(1, 2, "repr.path"), Span(2, 5, "repr.filename")]), (" /foo/bar.html ", [Span(1, 6, "repr.path"), Span(6, 14, "repr.filename")]), ("01-23-45-67-89-AB", [Span(0, 17, "repr.eui48")]), # 6x2 hyphen ("01-23-45-FF-FE-67-89-AB", [Span(0, 23, "repr.eui64")]), # 8x2 hyphen ("01:23:45:67:89:AB", [Span(0, 17, "repr.ipv6")]), # 6x2 colon ("01:23:45:FF:FE:67:89:AB", [Span(0, 23, "repr.ipv6")]), # 8x2 colon ("0123.4567.89AB", [Span(0, 14, "repr.eui48")]), # 3x4 dot ("0123.45FF.FE67.89AB", [Span(0, 19, "repr.eui64")]), # 4x4 dot ("ed-ed-ed-ed-ed-ed", [Span(0, 17, "repr.eui48")]), # lowercase ("ED-ED-ED-ED-ED-ED", [Span(0, 17, "repr.eui48")]), # uppercase ("Ed-Ed-Ed-Ed-Ed-Ed", [Span(0, 17, "repr.eui48")]), # mixed case ("0-00-1-01-2-02", [Span(0, 14, "repr.eui48")]), # dropped zero (" https://example.org ", [Span(1, 20, "repr.url")]), (" http://example.org ", [Span(1, 19, "repr.url")]), (" http://example.org/index.html ", [Span(1, 30, "repr.url")]), (" http://example.org/index.html#anchor ", [Span(1, 37, "repr.url")]), ("https://www.youtube.com/@LinusTechTips", [Span(0, 38, "repr.url")]), ( " http://example.org/index.html?param1=value1 ", [ Span(31, 37, "repr.attrib_name"), Span(38, 44, "repr.attrib_value"), Span(1, 44, "repr.url"), ], ), (" http://example.org/~folder ", [Span(1, 27, "repr.url")]), ("No place like 127.0.0.1", [Span(14, 23, "repr.ipv4")]), ("''", [Span(0, 2, "repr.str")]), ("'hello'", [Span(0, 7, "repr.str")]), ("'''hello'''", [Span(0, 11, "repr.str")]), ('""', [Span(0, 2, "repr.str")]), ('"hello"', [Span(0, 7, "repr.str")]), ('"""hello"""', [Span(0, 11, "repr.str")]), ("\\'foo'", []), ("it's no 'string'", [Span(8, 16, "repr.str")]), ("78351748-9b32-4e08-ad3e-7e9ff124d541", [Span(0, 36, "repr.uuid")]), ] @pytest.mark.parametrize("test, spans", highlight_tests) def test_highlight_regex(test: str, spans: List[Span]): """Tests for the regular expressions used in ReprHighlighter.""" text = Text(test) highlighter = ReprHighlighter() highlighter.highlight(text) print(text.spans) assert text.spans == spans def test_highlight_json_with_indent(): json_string = json.dumps({"name": "apple", "count": 1}, indent=4) text = Text(json_string) highlighter = JSONHighlighter() highlighter.highlight(text) assert text.spans == [ Span(0, 1, "json.brace"), Span(6, 12, "json.str"), Span(14, 21, "json.str"), Span(27, 34, "json.str"), Span(36, 37, "json.number"), Span(38, 39, "json.brace"), Span(6, 12, "json.key"), Span(27, 34, "json.key"), ] def test_highlight_json_string_only(): json_string = '"abc"' text = Text(json_string) highlighter = JSONHighlighter() highlighter.highlight(text) assert text.spans == [Span(0, 5, "json.str")] def test_highlight_json_empty_string_only(): json_string = '""' text = Text(json_string) highlighter = JSONHighlighter() highlighter.highlight(text) assert text.spans == [Span(0, 2, "json.str")] def test_highlight_json_no_indent(): json_string = json.dumps({"name": "apple", "count": 1}, indent=None) text = Text(json_string) highlighter = JSONHighlighter() highlighter.highlight(text) assert text.spans == [ Span(0, 1, "json.brace"), Span(1, 7, "json.str"), Span(9, 16, "json.str"), Span(18, 25, "json.str"), Span(27, 28, "json.number"), Span(28, 29, "json.brace"), Span(1, 7, "json.key"), Span(18, 25, "json.key"), ] iso8601_highlight_tests = [ ("2008-08", [Span(0, 4, "iso8601.year"), Span(5, 7, "iso8601.month")]), ( "2008-08-30", [ Span(0, 10, "iso8601.date"), Span(0, 4, "iso8601.year"), Span(5, 7, "iso8601.month"), Span(8, 10, "iso8601.day"), ], ), ( "20080830", [ Span(0, 8, "iso8601.date"), Span(0, 4, "iso8601.year"), Span(4, 6, "iso8601.month"), Span(6, 8, "iso8601.day"), ], ), ( "2008-243", [ Span(0, 8, "iso8601.date"), Span(0, 4, "iso8601.year"), Span(5, 8, "iso8601.day"), ], ), ( "2008243", [ Span(0, 7, "iso8601.date"), Span(0, 4, "iso8601.year"), Span(4, 7, "iso8601.day"), ], ), ( "2008-W35", [ Span(0, 8, "iso8601.date"), Span(0, 4, "iso8601.year"), Span(6, 8, "iso8601.week"), ], ), ( "2008W35", [ Span(0, 7, "iso8601.date"), Span(0, 4, "iso8601.year"), Span(5, 7, "iso8601.week"), ], ), ( "2008-W35-6", [ Span(0, 10, "iso8601.date"), Span(0, 4, "iso8601.year"), Span(6, 8, "iso8601.week"), Span(9, 10, "iso8601.day"), ], ), ( "2008W356", [ Span(0, 8, "iso8601.date"), Span(0, 4, "iso8601.year"), Span(5, 7, "iso8601.week"), Span(7, 8, "iso8601.day"), ], ), ( "17:21", [ Span(0, 5, "iso8601.time"), Span(0, 2, "iso8601.hour"), Span(3, 5, "iso8601.minute"), ], ), ( "1721", [ Span(0, 4, "iso8601.time"), Span(0, 2, "iso8601.hour"), Span(2, 4, "iso8601.minute"), ], ), ( "172159", [ Span(0, 6, "iso8601.time"), Span(0, 2, "iso8601.hour"), Span(2, 4, "iso8601.minute"), Span(4, 6, "iso8601.second"), ], ), ("Z", [Span(0, 1, "iso8601.timezone")]), ("+07", [Span(0, 3, "iso8601.timezone")]), ("+07:00", [Span(0, 6, "iso8601.timezone")]), ( "17:21:59+07:00", [ Span(0, 8, "iso8601.time"), Span(0, 2, "iso8601.hour"), Span(3, 5, "iso8601.minute"), Span(6, 8, "iso8601.second"), Span(8, 14, "iso8601.timezone"), ], ), ( "172159+0700", [ Span(0, 6, "iso8601.time"), Span(0, 2, "iso8601.hour"), Span(2, 4, "iso8601.minute"), Span(4, 6, "iso8601.second"), Span(6, 11, "iso8601.timezone"), ], ), ( "172159+07", [ Span(0, 6, "iso8601.time"), Span(0, 2, "iso8601.hour"), Span(2, 4, "iso8601.minute"), Span(4, 6, "iso8601.second"), Span(6, 9, "iso8601.timezone"), ], ), ( "2008-08-30 17:21:59", [ Span(0, 10, "iso8601.date"), Span(0, 4, "iso8601.year"), Span(4, 5, "iso8601.hyphen"), Span(5, 7, "iso8601.month"), Span(8, 10, "iso8601.day"), Span(11, 19, "iso8601.time"), Span(11, 13, "iso8601.hour"), Span(14, 16, "iso8601.minute"), Span(17, 19, "iso8601.second"), ], ), ( "20080830 172159", [ Span(0, 8, "iso8601.date"), Span(0, 4, "iso8601.year"), Span(4, 6, "iso8601.month"), Span(6, 8, "iso8601.day"), Span(9, 15, "iso8601.time"), Span(9, 11, "iso8601.hour"), Span(11, 13, "iso8601.minute"), Span(13, 15, "iso8601.second"), ], ), ( "2008-08-30", [ Span(0, 10, "iso8601.date"), Span(0, 4, "iso8601.year"), Span(5, 7, "iso8601.month"), Span(8, 10, "iso8601.day"), ], ), ( "2008-08-30+07:00", [ Span(0, 10, "iso8601.date"), Span(0, 4, "iso8601.year"), Span(5, 7, "iso8601.month"), Span(8, 10, "iso8601.day"), Span(10, 16, "iso8601.timezone"), ], ), ( "01:45:36", [ Span(0, 8, "iso8601.time"), Span(0, 2, "iso8601.hour"), Span(3, 5, "iso8601.minute"), Span(6, 8, "iso8601.second"), ], ), ( "01:45:36.123+07:00", [ Span(0, 12, "iso8601.time"), Span(0, 2, "iso8601.hour"), Span(3, 5, "iso8601.minute"), Span(6, 8, "iso8601.second"), Span(8, 12, "iso8601.frac"), Span(12, 18, "iso8601.timezone"), ], ), ( "01:45:36.123+07:00", [ Span(0, 12, "iso8601.time"), Span(0, 2, "iso8601.hour"), Span(3, 5, "iso8601.minute"), Span(6, 8, "iso8601.second"), Span(8, 12, "iso8601.frac"), Span(12, 18, "iso8601.timezone"), ], ), ( "2008-08-30T01:45:36", [ Span(0, 10, "iso8601.date"), Span(0, 4, "iso8601.year"), Span(5, 7, "iso8601.month"), Span(8, 10, "iso8601.day"), Span(11, 19, "iso8601.time"), Span(11, 13, "iso8601.hour"), Span(14, 16, "iso8601.minute"), Span(17, 19, "iso8601.second"), ], ), ( "2008-08-30T01:45:36.123Z", [ Span(0, 10, "iso8601.date"), Span(0, 4, "iso8601.year"), Span(5, 7, "iso8601.month"), Span(8, 10, "iso8601.day"), Span(11, 23, "iso8601.time"), Span(11, 13, "iso8601.hour"), Span(14, 16, "iso8601.minute"), Span(17, 19, "iso8601.second"), Span(19, 23, "iso8601.ms"), Span(23, 24, "iso8601.timezone"), ], ), ] @pytest.mark.parametrize("test, spans", iso8601_highlight_tests) def test_highlight_iso8601_regex(test: str, spans: List[Span]): """Tests for the regular expressions used in ISO8601Highlighter.""" text = Text(test) highlighter = ISO8601Highlighter() highlighter.highlight(text) print(text.spans) assert text.spans == spans
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_rich_print.py
tests/test_rich_print.py
import io import json import rich from rich.console import Console def test_get_console(): console = rich.get_console() assert isinstance(console, Console) def test_reconfigure_console(): rich.reconfigure(width=100) assert rich.get_console().width == 100 def test_rich_print(): console = rich.get_console() output = io.StringIO() backup_file = console.file try: console.file = output rich.print("foo", "bar") rich.print("foo\n") rich.print("foo\n\n") assert output.getvalue() == "foo bar\nfoo\n\nfoo\n\n\n" finally: console.file = backup_file def test_rich_print_json(): console = rich.get_console() with console.capture() as capture: rich.print_json('[false, true, null, "foo"]', indent=4) result = capture.get() print(repr(result)) expected = '[\n false,\n true,\n null,\n "foo"\n]\n' assert result == expected def test_rich_print_json_round_trip(): data = ["x" * 100, 2e128] console = rich.get_console() with console.capture() as capture: rich.print_json(data=data, indent=4) result = capture.get() print(repr(result)) result_data = json.loads(result) assert result_data == data def test_rich_print_json_no_truncation(): console = rich.get_console() with console.capture() as capture: rich.print_json(f'["{"x" * 100}", {int(2e128)}]', indent=4) result = capture.get() print(repr(result)) assert ("x" * 100) in result assert str(int(2e128)) in result def test_rich_print_X(): console = rich.get_console() output = io.StringIO() backup_file = console.file try: console.file = output rich.print("foo") rich.print("fooX") rich.print("fooXX") assert output.getvalue() == "foo\nfooX\nfooXX\n" finally: console.file = backup_file
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/render.py
tests/render.py
import io import re from rich.console import Console, RenderableType 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, no_wrap: bool = False) -> str: console = Console( width=100, file=io.StringIO(), color_system="truecolor", legacy_windows=False ) console.print(renderable, no_wrap=no_wrap) output = replace_link_ids(console.file.getvalue()) return output
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_status.py
tests/test_status.py
from time import sleep from rich.console import Console from rich.spinner import Spinner from rich.status import Status def test_status(): console = Console( color_system=None, width=80, legacy_windows=False, get_time=lambda: 0.0 ) status = Status("foo", console=console) assert status.console == console previous_status_renderable = status.renderable status.update(status="bar", spinner_style="red", speed=2.0) assert previous_status_renderable == status.renderable assert isinstance(status.renderable, Spinner) status.update(spinner="dots2") assert previous_status_renderable != status.renderable # TODO: Testing output is tricky with threads with status: sleep(0.2) def test_renderable(): console = Console( color_system=None, width=80, legacy_windows=False, get_time=lambda: 0.0 ) status = Status("foo", console=console) console.begin_capture() console.print(status) assert console.end_capture() == "⠋ foo\n"
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_logging.py
tests/test_logging.py
import io import os import logging from typing import Optional import pytest from rich.console import Console from rich.logging import RichHandler handler = RichHandler( console=Console( file=io.StringIO(), force_terminal=True, width=80, color_system="truecolor", _environ={}, ), enable_link_path=False, ) logging.basicConfig( level="NOTSET", format="%(message)s", datefmt="[DATE]", handlers=[handler] ) log = logging.getLogger("rich") skip_win = pytest.mark.skipif( os.name == "nt", reason="rendered differently on windows", ) @skip_win def test_exception(): console = Console( file=io.StringIO(), force_terminal=True, width=140, color_system=None, _environ={}, ) handler_with_tracebacks = RichHandler( console=console, enable_link_path=False, rich_tracebacks=True ) formatter = logging.Formatter("FORMATTER %(message)s %(asctime)s") handler_with_tracebacks.setFormatter(formatter) log.addHandler(handler_with_tracebacks) log.error("foo") try: 1 / 0 except ZeroDivisionError: log.exception("message") render = handler_with_tracebacks.console.file.getvalue() print(render) assert "FORMATTER foo" in render assert "ZeroDivisionError" in render assert "message" in render assert "division by zero" in render def test_exception_with_extra_lines(): console = Console( file=io.StringIO(), force_terminal=True, width=140, color_system=None, _environ={}, ) handler_extra_lines = RichHandler( console=console, enable_link_path=False, markup=True, rich_tracebacks=True, tracebacks_extra_lines=5, ) log.addHandler(handler_extra_lines) try: 1 / 0 except ZeroDivisionError: log.exception("message") render = handler_extra_lines.console.file.getvalue() print(render) assert "ZeroDivisionError" in render assert "message" in render assert "division by zero" in render def test_stderr_and_stdout_are_none(monkeypatch): # This test is specifically to handle cases when using pythonw on # windows and stderr and stdout are set to None. # See https://bugs.python.org/issue13807 monkeypatch.setattr("sys.stdout", None) monkeypatch.setattr("sys.stderr", None) console = Console(_environ={}) target_handler = RichHandler(console=console) actual_record: Optional[logging.LogRecord] = None def mock_handle_error(record): nonlocal actual_record actual_record = record target_handler.handleError = mock_handle_error log.addHandler(target_handler) try: 1 / 0 except ZeroDivisionError: log.exception("message") finally: log.removeHandler(target_handler) assert actual_record is not None assert "message" in actual_record.msg def test_markup_and_highlight(): console = Console( file=io.StringIO(), force_terminal=True, width=140, color_system="truecolor", _environ={}, ) handler = RichHandler(console=console) # Check defaults are as expected assert handler.highlighter assert not handler.markup formatter = logging.Formatter("FORMATTER %(message)s %(asctime)s") handler.setFormatter(formatter) log.addHandler(handler) log_message = "foo 3.141 127.0.0.1 [red]alert[/red]" log.error(log_message) render_fancy = handler.console.file.getvalue() assert "FORMATTER" in render_fancy assert log_message not in render_fancy assert "red" in render_fancy handler.console.file = io.StringIO() log.error(log_message, extra={"markup": True}) render_markup = handler.console.file.getvalue() assert "FORMATTER" in render_markup assert log_message not in render_markup assert "red" not in render_markup handler.console.file = io.StringIO() log.error(log_message, extra={"highlighter": None}) render_plain = handler.console.file.getvalue() assert "FORMATTER" in render_plain assert log_message in render_plain
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_pretty.py
tests/test_pretty.py
import collections import io import sys from array import array from collections import UserDict, defaultdict, deque from dataclasses import dataclass, field from typing import Any, List, NamedTuple import attr import pytest from rich.console import Console from rich.measure import Measurement from rich.pretty import Node, Pretty, _ipy_display_hook, install, pprint, pretty_repr from rich.text import Text skip_py38 = pytest.mark.skipif( sys.version_info.minor == 8 and sys.version_info.major == 3, reason="rendered differently on py3.8", ) skip_py39 = pytest.mark.skipif( sys.version_info.minor == 9 and sys.version_info.major == 3, reason="rendered differently on py3.9", ) skip_py310 = pytest.mark.skipif( sys.version_info.minor == 10 and sys.version_info.major == 3, reason="rendered differently on py3.10", ) skip_py311 = pytest.mark.skipif( sys.version_info.minor == 11 and sys.version_info.major == 3, reason="rendered differently on py3.11", ) skip_py312 = pytest.mark.skipif( sys.version_info.minor == 12 and sys.version_info.major == 3, reason="rendered differently on py3.12", ) skip_py313 = pytest.mark.skipif( sys.version_info.minor == 13 and sys.version_info.major == 3, reason="rendered differently on py3.13", ) skip_py314 = pytest.mark.skipif( sys.version_info.minor == 14 and sys.version_info.major == 3, reason="rendered differently on py3.14", ) def test_install() -> None: console = Console(file=io.StringIO()) dh = sys.displayhook install(console) sys.displayhook("foo") assert console.file.getvalue() == "'foo'\n" assert sys.displayhook is not dh def test_install_max_depth() -> None: console = Console(file=io.StringIO()) dh = sys.displayhook install(console, max_depth=1) sys.displayhook({"foo": {"bar": True}}) assert console.file.getvalue() == "{'foo': {...}}\n" assert sys.displayhook is not dh def test_ipy_display_hook__repr_html() -> None: console = Console(file=io.StringIO(), force_jupyter=True) class Thing: def _repr_html_(self): return "hello" console.begin_capture() _ipy_display_hook(Thing(), console=console) # Rendering delegated to notebook because _repr_html_ method exists assert console.end_capture() == "" def test_ipy_display_hook__multiple_special_reprs() -> None: """ The case where there are multiple IPython special _repr_*_ methods on the object, and one of them returns None but another one does not. """ console = Console(file=io.StringIO(), force_jupyter=True) class Thing: def __repr__(self): return "A Thing" def _repr_latex_(self): return None def _repr_html_(self): return "hello" result = _ipy_display_hook(Thing(), console=console) assert result == "A Thing" def test_ipy_display_hook__no_special_repr_methods() -> None: console = Console(file=io.StringIO(), force_jupyter=True) class Thing: def __repr__(self) -> str: return "hello" result = _ipy_display_hook(Thing(), console=console) # should be repr as-is assert result == "hello" def test_ipy_display_hook__special_repr_raises_exception() -> None: """ When an IPython special repr method raises an exception, we treat it as if it doesn't exist and look for the next. """ console = Console(file=io.StringIO(), force_jupyter=True) class Thing: def _repr_markdown_(self): raise Exception() def _repr_latex_(self): return None def _repr_html_(self): return "hello" def __repr__(self): return "therepr" result = _ipy_display_hook(Thing(), console=console) assert result == "therepr" def test_ipy_display_hook__console_renderables_on_newline() -> None: console = Console(file=io.StringIO(), force_jupyter=True) console.begin_capture() result = _ipy_display_hook(Text("hello"), console=console) assert result == "\nhello" def test_pretty() -> None: test = { "foo": [1, 2, 3, (4, 5, {6}, 7, 8, {9}), {}], "bar": {"egg": "baz", "words": ["Hello World"] * 10}, False: "foo", True: "", "text": ("Hello World", "foo bar baz egg"), } result = pretty_repr(test, max_width=80) print(result) expected = "{\n 'foo': [1, 2, 3, (4, 5, {6}, 7, 8, {9}), {}],\n 'bar': {\n 'egg': 'baz',\n 'words': [\n 'Hello World',\n 'Hello World',\n 'Hello World',\n 'Hello World',\n 'Hello World',\n 'Hello World',\n 'Hello World',\n 'Hello World',\n 'Hello World',\n 'Hello World'\n ]\n },\n False: 'foo',\n True: '',\n 'text': ('Hello World', 'foo bar baz egg')\n}" print(expected) assert result == expected @dataclass class ExampleDataclass: foo: int bar: str ignore: int = field(repr=False) baz: List[str] = field(default_factory=list) last: int = field(default=1, repr=False) @dataclass class Empty: pass def test_pretty_dataclass() -> None: dc = ExampleDataclass(1000, "Hello, World", 999, ["foo", "bar", "baz"]) result = pretty_repr(dc, max_width=80) print(repr(result)) assert ( result == "ExampleDataclass(foo=1000, bar='Hello, World', baz=['foo', 'bar', 'baz'])" ) result = pretty_repr(dc, max_width=16) print(repr(result)) assert ( result == "ExampleDataclass(\n foo=1000,\n bar='Hello, World',\n baz=[\n 'foo',\n 'bar',\n 'baz'\n ]\n)" ) dc.bar = dc result = pretty_repr(dc, max_width=80) print(repr(result)) assert result == "ExampleDataclass(foo=1000, bar=..., baz=['foo', 'bar', 'baz'])" def test_empty_dataclass() -> None: assert pretty_repr(Empty()) == "Empty()" assert pretty_repr([Empty()]) == "[Empty()]" class StockKeepingUnit(NamedTuple): name: str description: str price: float category: str reviews: List[str] def test_pretty_namedtuple() -> None: console = Console(color_system=None) console.begin_capture() example_namedtuple = StockKeepingUnit( "Sparkling British Spring Water", "Carbonated spring water", 0.9, "water", ["its amazing!", "its terrible!"], ) result = pretty_repr(example_namedtuple) print(result) assert ( result == """StockKeepingUnit( name='Sparkling British Spring Water', description='Carbonated spring water', price=0.9, category='water', reviews=['its amazing!', 'its terrible!'] )""" ) def test_pretty_namedtuple_length_one_no_trailing_comma() -> None: instance = collections.namedtuple("Thing", ["name"])(name="Bob") assert pretty_repr(instance) == "Thing(name='Bob')" def test_pretty_namedtuple_empty() -> None: instance = collections.namedtuple("Thing", [])() assert pretty_repr(instance) == "Thing()" def test_pretty_namedtuple_custom_repr() -> None: class Thing(NamedTuple): def __repr__(self): return "XX" assert pretty_repr(Thing()) == "XX" def test_pretty_namedtuple_fields_invalid_type() -> None: class LooksLikeANamedTupleButIsnt(tuple): _fields = "blah" instance = LooksLikeANamedTupleButIsnt() result = pretty_repr(instance) assert result == "()" # Treated as tuple def test_pretty_namedtuple_max_depth() -> None: instance = {"unit": StockKeepingUnit("a", "b", 1.0, "c", ["d", "e"])} result = pretty_repr(instance, max_depth=1) assert result == "{'unit': StockKeepingUnit(...)}" def test_small_width() -> None: test = ["Hello world! 12345"] result = pretty_repr(test, max_width=10) expected = "[\n 'Hello world! 12345'\n]" assert result == expected def test_ansi_in_pretty_repr() -> None: class Hello: def __repr__(self): return "Hello \x1b[38;5;239mWorld!" pretty = Pretty(Hello()) console = Console(file=io.StringIO(), record=True) console.print(pretty) result = console.export_text() assert result == "Hello World!\n" def test_broken_repr() -> None: class BrokenRepr: def __repr__(self): 1 / 0 test = [BrokenRepr()] result = pretty_repr(test) expected = "[<repr-error 'division by zero'>]" assert result == expected def test_broken_getattr() -> None: class BrokenAttr: def __getattr__(self, name): 1 / 0 def __repr__(self): return "BrokenAttr()" test = BrokenAttr() result = pretty_repr(test) assert result == "BrokenAttr()" def test_reference_cycle_container() -> None: test = [] test.append(test) res = pretty_repr(test) assert res == "[...]" test = [1, []] test[1].append(test) res = pretty_repr(test) assert res == "[1, [...]]" # Not a cyclic reference, just a repeated reference a = [2] test = [1, [a, a]] res = pretty_repr(test) assert res == "[1, [[2], [2]]]" def test_reference_cycle_namedtuple() -> None: class Example(NamedTuple): x: int y: Any test = Example(1, [Example(2, [])]) test.y[0].y.append(test) res = pretty_repr(test) assert res == "Example(x=1, y=[Example(x=2, y=[...])])" # Not a cyclic reference, just a repeated reference a = Example(2, None) test = Example(1, [a, a]) res = pretty_repr(test) assert res == "Example(x=1, y=[Example(x=2, y=None), Example(x=2, y=None)])" def test_reference_cycle_dataclass() -> None: @dataclass class Example: x: int y: Any test = Example(1, None) test.y = test res = pretty_repr(test) assert res == "Example(x=1, y=...)" test = Example(1, Example(2, None)) test.y.y = test res = pretty_repr(test) assert res == "Example(x=1, y=Example(x=2, y=...))" # Not a cyclic reference, just a repeated reference a = Example(2, None) test = Example(1, [a, a]) res = pretty_repr(test) assert res == "Example(x=1, y=[Example(x=2, y=None), Example(x=2, y=None)])" def test_reference_cycle_attrs() -> None: @attr.define class Example: x: int y: Any test = Example(1, None) test.y = test res = pretty_repr(test) assert res == "Example(x=1, y=...)" test = Example(1, Example(2, None)) test.y.y = test res = pretty_repr(test) assert res == "Example(x=1, y=Example(x=2, y=...))" # Not a cyclic reference, just a repeated reference a = Example(2, None) test = Example(1, [a, a]) res = pretty_repr(test) assert res == "Example(x=1, y=[Example(x=2, y=None), Example(x=2, y=None)])" def test_reference_cycle_custom_repr() -> None: class Example: def __init__(self, x, y): self.x = x self.y = y def __rich_repr__(self): yield ("x", self.x) yield ("y", self.y) test = Example(1, None) test.y = test res = pretty_repr(test) assert res == "Example(x=1, y=...)" test = Example(1, Example(2, None)) test.y.y = test res = pretty_repr(test) assert res == "Example(x=1, y=Example(x=2, y=...))" # Not a cyclic reference, just a repeated reference a = Example(2, None) test = Example(1, [a, a]) res = pretty_repr(test) assert res == "Example(x=1, y=[Example(x=2, y=None), Example(x=2, y=None)])" def test_max_depth() -> None: d = {} d["foo"] = {"fob": {"a": [1, 2, 3], "b": {"z": "x", "y": ["a", "b", "c"]}}} assert pretty_repr(d, max_depth=0) == "{...}" assert pretty_repr(d, max_depth=1) == "{'foo': {...}}" assert pretty_repr(d, max_depth=2) == "{'foo': {'fob': {...}}}" assert pretty_repr(d, max_depth=3) == "{'foo': {'fob': {'a': [...], 'b': {...}}}}" assert ( pretty_repr(d, max_width=100, max_depth=4) == "{'foo': {'fob': {'a': [1, 2, 3], 'b': {'z': 'x', 'y': [...]}}}}" ) assert ( pretty_repr(d, max_width=100, max_depth=5) == "{'foo': {'fob': {'a': [1, 2, 3], 'b': {'z': 'x', 'y': ['a', 'b', 'c']}}}}" ) assert ( pretty_repr(d, max_width=100, max_depth=None) == "{'foo': {'fob': {'a': [1, 2, 3], 'b': {'z': 'x', 'y': ['a', 'b', 'c']}}}}" ) def test_max_depth_rich_repr() -> None: class Foo: def __init__(self, foo): self.foo = foo def __rich_repr__(self): yield "foo", self.foo class Bar: def __init__(self, bar): self.bar = bar def __rich_repr__(self): yield "bar", self.bar assert ( pretty_repr(Foo(foo=Bar(bar=Foo(foo=[]))), max_depth=2) == "Foo(foo=Bar(bar=Foo(...)))" ) def test_max_depth_attrs() -> None: @attr.define class Foo: foo = attr.field() @attr.define class Bar: bar = attr.field() assert ( pretty_repr(Foo(foo=Bar(bar=Foo(foo=[]))), max_depth=2) == "Foo(foo=Bar(bar=Foo(...)))" ) def test_max_depth_dataclass() -> None: @dataclass class Foo: foo: object @dataclass class Bar: bar: object assert ( pretty_repr(Foo(foo=Bar(bar=Foo(foo=[]))), max_depth=2) == "Foo(foo=Bar(bar=Foo(...)))" ) def test_defaultdict() -> None: test_dict = defaultdict(int, {"foo": 2}) result = pretty_repr(test_dict) assert result == "defaultdict(<class 'int'>, {'foo': 2})" def test_deque() -> None: test_deque = deque([1, 2, 3]) result = pretty_repr(test_deque) assert result == "deque([1, 2, 3])" test_deque = deque([1, 2, 3], maxlen=None) result = pretty_repr(test_deque) assert result == "deque([1, 2, 3])" test_deque = deque([1, 2, 3], maxlen=5) result = pretty_repr(test_deque) assert result == "deque([1, 2, 3], maxlen=5)" test_deque = deque([1, 2, 3], maxlen=0) result = pretty_repr(test_deque) assert result == "deque(maxlen=0)" test_deque = deque([]) result = pretty_repr(test_deque) assert result == "deque()" test_deque = deque([], maxlen=None) result = pretty_repr(test_deque) assert result == "deque()" test_deque = deque([], maxlen=5) result = pretty_repr(test_deque) assert result == "deque(maxlen=5)" test_deque = deque([], maxlen=0) result = pretty_repr(test_deque) assert result == "deque(maxlen=0)" def test_array() -> None: test_array = array("I", [1, 2, 3]) result = pretty_repr(test_array) assert result == "array('I', [1, 2, 3])" def test_tuple_of_one() -> None: assert pretty_repr((1,)) == "(1,)" def test_node() -> None: node = Node("abc") assert pretty_repr(node) == "abc: " def test_indent_lines() -> None: console = Console(width=100, color_system=None) console.begin_capture() console.print(Pretty([100, 200], indent_guides=True), width=8) expected = """\ [ │ 100, │ 200 ] """ result = console.end_capture() print(repr(result)) print(result) assert result == expected def test_pprint() -> None: console = Console(color_system=None) console.begin_capture() pprint(1, console=console) assert console.end_capture() == "1\n" def test_pprint_max_values() -> None: console = Console(color_system=None) console.begin_capture() pprint([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], console=console, max_length=2) assert console.end_capture() == "[1, 2, ... +8]\n" def test_pprint_max_items() -> None: console = Console(color_system=None) console.begin_capture() pprint({"foo": 1, "bar": 2, "egg": 3}, console=console, max_length=2) assert console.end_capture() == """{'foo': 1, 'bar': 2, ... +1}\n""" def test_pprint_max_string() -> None: console = Console(color_system=None) console.begin_capture() pprint(["Hello" * 20], console=console, max_string=8) assert console.end_capture() == """['HelloHel'+92]\n""" def test_tuples() -> None: console = Console(color_system=None) console.begin_capture() pprint((1,), console=console) pprint((1,), expand_all=True, console=console) pprint(((1,),), expand_all=True, console=console) result = console.end_capture() print(repr(result)) expected = "(1,)\n(\n│ 1,\n)\n(\n│ (\n│ │ 1,\n│ ),\n)\n" print(result) print("--") print(expected) assert result == expected def test_newline() -> None: console = Console(color_system=None) console.begin_capture() console.print(Pretty((1,), insert_line=True, expand_all=True)) result = console.end_capture() expected = "\n(\n 1,\n)\n" assert result == expected def test_empty_repr() -> None: class Foo: def __repr__(self): return "" assert pretty_repr(Foo()) == "" def test_attrs() -> None: @attr.define class Point: x: int y: int foo: str = attr.field(repr=str.upper) z: int = 0 result = pretty_repr(Point(1, 2, foo="bar")) print(repr(result)) expected = "Point(x=1, y=2, foo=BAR, z=0)" assert result == expected def test_attrs_empty() -> None: @attr.define class Nada: pass result = pretty_repr(Nada()) print(repr(result)) expected = "Nada()" assert result == expected @skip_py310 @skip_py311 @skip_py312 @skip_py313 @skip_py314 def test_attrs_broken() -> None: @attr.define class Foo: bar: int foo = Foo(1) del foo.bar result = pretty_repr(foo) print(repr(result)) expected = "Foo(bar=AttributeError('bar'))" assert result == expected @skip_py38 @skip_py39 def test_attrs_broken_310() -> None: @attr.define class Foo: bar: int foo = Foo(1) del foo.bar result = pretty_repr(foo) print(repr(result)) if sys.version_info >= (3, 13): expected = "Foo(\n bar=AttributeError(\"'tests.test_pretty.test_attrs_broken_310.<locals>.Foo' object has no attribute 'bar'\")\n)" else: expected = "Foo(bar=AttributeError(\"'Foo' object has no attribute 'bar'\"))" assert result == expected def test_user_dict() -> None: class D1(UserDict): pass class D2(UserDict): def __repr__(self): return "FOO" d1 = D1({"foo": "bar"}) d2 = D2({"foo": "bar"}) result = pretty_repr(d1, expand_all=True) print(repr(result)) assert result == "{\n 'foo': 'bar'\n}" result = pretty_repr(d2, expand_all=True) print(repr(result)) assert result == "FOO" def test_lying_attribute() -> None: """Test getattr doesn't break rich repr protocol""" class Foo: def __getattr__(self, attr): return "foo" foo = Foo() result = pretty_repr(foo) assert "Foo" in result def test_measure_pretty() -> None: """Test measure respects expand_all""" # https://github.com/Textualize/rich/issues/1998 console = Console() pretty = Pretty(["alpha", "beta", "delta", "gamma"], expand_all=True) measurement = console.measure(pretty) assert measurement == Measurement(12, 12) def test_tuple_rich_repr() -> None: """ Test that can use None as key to have tuple positional values. """ class Foo: def __rich_repr__(self): yield None, (1,) assert pretty_repr(Foo()) == "Foo((1,))" def test_tuple_rich_repr_default() -> None: """ Test that can use None as key to have tuple positional values and with a default. """ class Foo: def __rich_repr__(self): yield None, (1,), (1,) assert pretty_repr(Foo()) == "Foo()" def test_dataclass_no_attribute() -> None: """Regression test for https://github.com/Textualize/rich/issues/3417""" from dataclasses import dataclass, field @dataclass(eq=False) class BadDataclass: item: int = field(init=False) # item is not provided bad_data_class = BadDataclass() console = Console() with console.capture() as capture: console.print(bad_data_class) expected = "BadDataclass()\n" result = capture.get() assert result == expected
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_traceback.py
tests/test_traceback.py
import io import re import sys from typing import List import pytest from rich.console import Console from rich.theme import Theme from rich.traceback import Traceback, install def test_handler(): console = Console(file=io.StringIO(), width=100, color_system=None) expected_old_handler = sys.excepthook def level1(): level2() def level2(): return 1 / 0 try: old_handler = install(console=console) try: level1() except Exception: exc_type, exc_value, traceback = sys.exc_info() sys.excepthook(exc_type, exc_value, traceback) rendered_exception = console.file.getvalue() print(repr(rendered_exception)) assert "Traceback" in rendered_exception assert "ZeroDivisionError" in rendered_exception frame_blank_line_possible_preambles = ( # Start of the stack rendering: "╭─────────────────────────────── Traceback (most recent call last) ────────────────────────────────╮", # Each subsequent frame (starting with the file name) should then be preceded with a blank line: "│" + (" " * 98) + "│", ) for frame_start in re.finditer( "^│ .+rich/tests/test_traceback.py:", rendered_exception, flags=re.MULTILINE, ): frame_start_index = frame_start.start() for preamble in frame_blank_line_possible_preambles: preamble_start, preamble_end = ( frame_start_index - len(preamble) - 1, frame_start_index - 1, ) if rendered_exception[preamble_start:preamble_end] == preamble: break else: pytest.fail( f"Frame {frame_start[0]} doesn't have the expected preamble" ) finally: sys.excepthook = old_handler assert old_handler == expected_old_handler def test_capture(): try: 1 / 0 except Exception: tb = Traceback() assert tb.trace.stacks[0].exc_type == "ZeroDivisionError" def test_no_exception(): with pytest.raises(ValueError): tb = Traceback() def get_exception() -> Traceback: def bar(a): print(1 / a) def foo(a): bar(a) try: try: foo(0) except: foobarbaz except: tb = Traceback() return tb def test_print_exception(): console = Console(width=100, file=io.StringIO()) try: 1 / 0 except Exception: console.print_exception() exception_text = console.file.getvalue() assert "ZeroDivisionError" in exception_text def test_print_exception_no_msg(): console = Console(width=100, file=io.StringIO()) try: raise RuntimeError except Exception: console.print_exception() exception_text = console.file.getvalue() assert "RuntimeError" in exception_text assert "RuntimeError:" not in exception_text def test_print_exception_locals(): console = Console(width=100, file=io.StringIO()) try: 1 / 0 except Exception: console.print_exception(show_locals=True) exception_text = console.file.getvalue() print(exception_text) assert "ZeroDivisionError" in exception_text assert "locals" in exception_text assert "console = <console width=100 None>" in exception_text def test_syntax_error(): console = Console(width=100, file=io.StringIO()) try: # raises SyntaxError: unexpected EOF while parsing eval("(2+2") except SyntaxError: console.print_exception() exception_text = console.file.getvalue() assert "SyntaxError" in exception_text def test_nested_exception(): console = Console(width=100, file=io.StringIO()) value_error_message = "ValueError because of ZeroDivisionError" try: try: 1 / 0 except ZeroDivisionError: raise ValueError(value_error_message) except Exception: console.print_exception() exception_text = console.file.getvalue() text_should_contain = [ value_error_message, "ZeroDivisionError", "ValueError", "During handling of the above exception", ] for msg in text_should_contain: assert msg in exception_text # ZeroDivisionError should come before ValueError assert exception_text.find("ZeroDivisionError") < exception_text.find("ValueError") def test_caused_exception(): console = Console(width=100, file=io.StringIO()) value_error_message = "ValueError caused by ZeroDivisionError" try: try: 1 / 0 except ZeroDivisionError as e: raise ValueError(value_error_message) from e except Exception: console.print_exception() exception_text = console.file.getvalue() text_should_contain = [ value_error_message, "ZeroDivisionError", "ValueError", "The above exception was the direct cause", ] for msg in text_should_contain: assert msg in exception_text # ZeroDivisionError should come before ValueError assert exception_text.find("ZeroDivisionError") < exception_text.find("ValueError") def test_filename_with_bracket(): console = Console(width=100, file=io.StringIO()) try: exec(compile("1/0", filename="<string>", mode="exec")) except Exception: console.print_exception() exception_text = console.file.getvalue() assert "<string>" in exception_text def test_filename_not_a_file(): console = Console(width=100, file=io.StringIO()) try: exec(compile("1/0", filename="string", mode="exec")) except Exception: console.print_exception() exception_text = console.file.getvalue() assert "string" in exception_text @pytest.mark.skipif(sys.platform == "win32", reason="renders different on windows") def test_traceback_console_theme_applies(): """ Ensure that themes supplied via Console init work on Tracebacks. Regression test for https://github.com/Textualize/rich/issues/1786 """ r, g, b = 123, 234, 123 console = Console( force_terminal=True, _environ={"COLORTERM": "truecolor"}, theme=Theme({"traceback.title": f"rgb({r},{g},{b})"}), ) console.begin_capture() try: 1 / 0 except Exception: console.print_exception() result = console.end_capture() assert f"\\x1b[38;2;{r};{g};{b}mTraceback \\x1b[0m" in repr(result) def test_broken_str(): class BrokenStr(Exception): def __str__(self): 1 / 0 console = Console(width=100, file=io.StringIO()) try: raise BrokenStr() except Exception: console.print_exception() result = console.file.getvalue() print(result) assert "<exception str() failed>" in result def test_guess_lexer(): assert Traceback._guess_lexer("foo.py", "code") == "python" code_python = "#! usr/bin/env python\nimport this" assert Traceback._guess_lexer("foo", code_python) == "python" assert Traceback._guess_lexer("foo", "foo\nbnar") == "text" def test_guess_lexer_yaml_j2(): # https://github.com/Textualize/rich/issues/2018 code = """\ foobar: something: {{ raiser() }} else: {{ 5 + 5 }} """ assert Traceback._guess_lexer("test.yaml.j2", code) in ("text", "YAML+Jinja") def test_recursive(): def foo(n): return bar(n) def bar(n): return foo(n) console = Console(width=100, file=io.StringIO()) try: foo(1) except Exception: console.print_exception(max_frames=6) result = console.file.getvalue() print(result) assert "frames hidden" in result assert result.count("in foo") < 4 def test_suppress(): try: 1 / 0 except Exception: traceback = Traceback(suppress=[pytest, "foo"]) assert len(traceback.suppress) == 2 assert "pytest" in traceback.suppress[0] assert "foo" in traceback.suppress[1] @pytest.mark.parametrize( "rich_traceback_omit_for_level2,expected_frames_length,expected_frame_names", ( # fmt: off [True, 3, ["test_rich_traceback_omit_optional_local_flag", "level1", "level3"]], [False, 4, ["test_rich_traceback_omit_optional_local_flag", "level1", "level2", "level3"]], # fmt: on ), ) def test_rich_traceback_omit_optional_local_flag( rich_traceback_omit_for_level2: bool, expected_frames_length: int, expected_frame_names: List[str], ): def level1(): return level2() def level2(): # true-ish values are enough to trigger the opt-out: _rich_traceback_omit = 1 if rich_traceback_omit_for_level2 else 0 return level3() def level3(): return 1 / 0 try: level1() except Exception: exc_type, exc_value, traceback = sys.exc_info() trace = Traceback.from_exception(exc_type, exc_value, traceback).trace frames = trace.stacks[0].frames assert len(frames) == expected_frames_length frame_names = [f.name for f in frames] assert frame_names == expected_frame_names @pytest.mark.skipif( sys.version_info.minor >= 11, reason="Not applicable after Python 3.11" ) def test_traceback_finely_grained_missing() -> None: """Before 3.11, the last_instruction should be None""" try: 1 / 0 except: traceback = Traceback() last_instruction = traceback.trace.stacks[-1].frames[-1].last_instruction assert last_instruction is None @pytest.mark.skipif( sys.version_info.minor < 11, reason="Not applicable before Python 3.11" ) def test_traceback_finely_grained() -> None: """Check that last instruction is populated.""" try: 1 / 0 except: traceback = Traceback() last_instruction = traceback.trace.stacks[-1].frames[-1].last_instruction assert last_instruction is not None assert isinstance(last_instruction, tuple) assert len(last_instruction) == 2 start, end = last_instruction print(start, end) assert start[0] == end[0] @pytest.mark.skipif( sys.version_info.minor < 11, reason="Not supported before Python 3.11" ) def test_notes() -> None: """Check traceback captures __note__.""" try: 1 / 0 except Exception as error: error.add_note("Hello") error.add_note("World") traceback = Traceback() assert traceback.trace.stacks[0].notes == ["Hello", "World"] def test_recursive_exception() -> None: """Regression test for https://github.com/Textualize/rich/issues/3708 Test this doesn't create an infinite loop. """ console = Console() def foo() -> None: try: raise RuntimeError("Hello") except Exception as e: raise e from e def bar() -> None: try: foo() except Exception as e: assert e is e.__cause__ console.print_exception(show_locals=True) bar()
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_markdown_no_hyperlinks.py
tests/test_markdown_no_hyperlinks.py
# coding=utf-8 MARKDOWN = """Heading ======= Sub-heading ----------- ### Heading #### H4 Heading ##### H5 Heading ###### H6 Heading Paragraphs are separated by a blank line. Two spaces at the end of a line produces a line break. Text attributes _italic_, **bold**, `monospace`. Horizontal rule: --- Bullet list: * apples * oranges * pears Numbered list: 1. lather 2. rinse 3. repeat An [example](http://example.com). > Markdown uses email-style > characters for blockquoting. > > Lorem ipsum ![progress](https://github.com/textualize/rich/raw/master/imgs/progress.gif) ``` a=1 ``` ```python import this ``` ```somelang foobar ``` """ import io import re from rich.console import Console, RenderableType from rich.markdown import Markdown 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_markdown_render(): markdown = Markdown(MARKDOWN, hyperlinks=False) rendered_markdown = render(markdown) print(repr(rendered_markdown)) expected = "┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n┃ \x1b[1mHeading\x1b[0m ┃\n┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛\n\n\n \x1b[1;4mSub-heading\x1b[0m \n\n \x1b[1mHeading\x1b[0m \n\n \x1b[1;2mH4 Heading\x1b[0m \n\n \x1b[4mH5 Heading\x1b[0m \n\n \x1b[3mH6 Heading\x1b[0m \n\nParagraphs are separated by a blank line. \n\nTwo spaces at the end of a line \nproduces a line break. \n\nText attributes \x1b[3mitalic\x1b[0m, \x1b[1mbold\x1b[0m, \x1b[1;36;40mmonospace\x1b[0m. \n\nHorizontal rule: \n\n\x1b[33m────────────────────────────────────────────────────────────────────────────────────────────────────\x1b[0m\nBullet list: \n\n\x1b[1;33m • \x1b[0mapples \n\x1b[1;33m • \x1b[0moranges \n\x1b[1;33m • \x1b[0mpears \n\nNumbered list: \n\n\x1b[1;33m 1 \x1b[0mlather \n\x1b[1;33m 2 \x1b[0mrinse \n\x1b[1;33m 3 \x1b[0mrepeat \n\nAn \x1b[94mexample\x1b[0m (\x1b[4;34mhttp://example.com\x1b[0m). \n\n\x1b[35m▌ \x1b[0m\x1b[35mMarkdown uses email-style > characters for blockquoting.\x1b[0m\x1b[35m \x1b[0m\n\x1b[35m▌ \x1b[0m\x1b[35mLorem ipsum\x1b[0m\x1b[35m \x1b[0m\n\n🌆 progress \n\n\x1b[48;2;39;40;34m \x1b[0m\n\x1b[48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34ma=1\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[48;2;39;40;34m \x1b[0m\n\n\x1b[48;2;39;40;34m \x1b[0m\n\x1b[48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34mimport\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mthis\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[48;2;39;40;34m \x1b[0m\n\n\x1b[48;2;39;40;34m \x1b[0m\n\x1b[48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mfoobar\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[48;2;39;40;34m \x1b[0m\n" assert rendered_markdown == expected if __name__ == "__main__": markdown = Markdown(MARKDOWN, hyperlinks=False) rendered = render(markdown) print(rendered) print(repr(rendered))
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_control.py
tests/test_control.py
from rich.control import Control, escape_control_codes, strip_control_codes from rich.segment import ControlType, Segment def test_control(): control = Control(ControlType.BELL) assert str(control) == "\x07" def test_strip_control_codes(): assert strip_control_codes("") == "" assert strip_control_codes("foo\rbar") == "foobar" assert strip_control_codes("Fear is the mind killer") == "Fear is the mind killer" def test_escape_control_codes(): assert escape_control_codes("") == "" assert escape_control_codes("foo\rbar") == "foo\\rbar" assert escape_control_codes("Fear is the mind killer") == "Fear is the mind killer" def test_control_move_to(): control = Control.move_to(5, 10) print(control.segment) assert control.segment == Segment( "\x1b[11;6H", None, [(ControlType.CURSOR_MOVE_TO, 5, 10)] ) def test_control_move(): assert Control.move(0, 0).segment == Segment("", None, []) control = Control.move(3, 4) print(repr(control.segment)) assert control.segment == Segment( "\x1b[3C\x1b[4B", None, [(ControlType.CURSOR_FORWARD, 3), (ControlType.CURSOR_DOWN, 4)], ) def test_move_to_column(): print(repr(Control.move_to_column(10, 20).segment)) assert Control.move_to_column(10, 20).segment == Segment( "\x1b[11G\x1b[20B", None, [(ControlType.CURSOR_MOVE_TO_COLUMN, 10), (ControlType.CURSOR_DOWN, 20)], ) assert Control.move_to_column(10, -20).segment == Segment( "\x1b[11G\x1b[20A", None, [(ControlType.CURSOR_MOVE_TO_COLUMN, 10), (ControlType.CURSOR_UP, 20)], ) def test_title(): control_segment = Control.title("hello").segment assert control_segment == Segment( "\x1b]0;hello\x07", None, [(ControlType.SET_WINDOW_TITLE, "hello")], )
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_progress.py
tests/test_progress.py
# encoding=utf-8 import io import os import tempfile from types import SimpleNamespace import pytest import rich.progress from rich.console import Console from rich.highlighter import NullHighlighter from rich.progress import ( BarColumn, DownloadColumn, FileSizeColumn, MofNCompleteColumn, Progress, RenderableColumn, SpinnerColumn, Task, TaskID, TaskProgressColumn, TextColumn, TimeElapsedColumn, TimeRemainingColumn, TotalFileSizeColumn, TransferSpeedColumn, _TrackThread, track, ) from rich.progress_bar import ProgressBar from rich.text import Text class MockClock: """A clock that is manually advanced.""" def __init__(self, time=0.0, auto=True) -> None: self.time = time self.auto = auto def __call__(self) -> float: try: return self.time finally: if self.auto: self.time += 1 def tick(self, advance: float = 1) -> None: self.time += advance def test_bar_columns(): bar_column = BarColumn(100) assert bar_column.bar_width == 100 task = Task(1, "test", 100, 20, _get_time=lambda: 1.0) bar = bar_column(task) assert isinstance(bar, ProgressBar) assert bar.completed == 20 assert bar.total == 100 def test_text_column(): text_column = TextColumn("[b]foo", highlighter=NullHighlighter()) task = Task(1, "test", 100, 20, _get_time=lambda: 1.0) text = text_column.render(task) assert str(text) == "foo" text_column = TextColumn("[b]bar", markup=False) task = Task(1, "test", 100, 20, _get_time=lambda: 1.0) text = text_column.render(task) assert text == Text("[b]bar") def test_time_elapsed_column(): column = TimeElapsedColumn() task = Task(1, "test", 100, 20, _get_time=lambda: 1.0) text = column.render(task) assert str(text) == "-:--:--" def test_time_remaining_column(): class FakeTask(Task): time_remaining = 60 column = TimeRemainingColumn() task = Task(1, "test", 100, 20, _get_time=lambda: 1.0) text = column(task) assert str(text) == "-:--:--" text = column(FakeTask(1, "test", 100, 20, _get_time=lambda: 1.0)) assert str(text) == "0:01:00" @pytest.mark.parametrize( "task_time, formatted", [ (None, "--:--"), (0, "00:00"), (59, "00:59"), (71, "01:11"), (4210, "1:10:10"), ], ) def test_compact_time_remaining_column(task_time, formatted): task = SimpleNamespace(finished=False, time_remaining=task_time, total=100) column = TimeRemainingColumn(compact=True) assert str(column.render(task)) == formatted def test_time_remaining_column_elapsed_when_finished(): task_time = 71 formatted = "0:01:11" task = SimpleNamespace(finished=True, finished_time=task_time, total=100) column = TimeRemainingColumn(elapsed_when_finished=True) assert str(column.render(task)) == formatted def test_renderable_column(): column = RenderableColumn("foo") task = Task(1, "test", 100, 20, _get_time=lambda: 1.0) assert column.render(task) == "foo" def test_spinner_column(): time = 1.0 def get_time(): nonlocal time return time column = SpinnerColumn() column.set_spinner("dots2") task = Task(1, "test", 100, 20, _get_time=get_time) result = column.render(task) print(repr(result)) expected = "⣾" assert str(result) == expected time += 1.0 column.spinner.update(speed=0.5) result = column.render(task) print(repr(result)) expected = "⡿" assert str(result) == expected def test_download_progress_uses_decimal_units() -> None: column = DownloadColumn() test_task = Task(1, "test", 1000, 500, _get_time=lambda: 1.0) rendered_progress = str(column.render(test_task)) expected = "0.5/1.0 kB" assert rendered_progress == expected def test_download_progress_uses_binary_units() -> None: column = DownloadColumn(binary_units=True) test_task = Task(1, "test", 1024, 512, _get_time=lambda: 1.0) rendered_progress = str(column.render(test_task)) expected = "0.5/1.0 KiB" assert rendered_progress == expected def test_task_ids(): progress = make_progress() assert progress.task_ids == [0, 1, 2, 4] def test_finished(): progress = make_progress() assert not progress.finished def make_progress() -> Progress: _time = 0.0 def fake_time(): nonlocal _time try: return _time finally: _time += 1 console = Console( file=io.StringIO(), force_terminal=True, color_system="truecolor", width=80, legacy_windows=False, _environ={}, ) progress = Progress(console=console, get_time=fake_time, auto_refresh=False) task1 = progress.add_task("foo") task2 = progress.add_task("bar", total=30) progress.advance(task2, 16) task3 = progress.add_task("baz", visible=False) task4 = progress.add_task("egg") progress.remove_task(task4) task4 = progress.add_task("foo2", completed=50, start=False) progress.stop_task(task4) progress.start_task(task4) progress.update( task4, total=200, advance=50, completed=200, visible=True, refresh=True ) progress.stop_task(task4) return progress def render_progress() -> str: progress = make_progress() progress.start() # superfluous noop with progress: pass progress.stop() # superfluous noop progress_render = progress.console.file.getvalue() return progress_render def test_expand_bar() -> None: console = Console( file=io.StringIO(), force_terminal=True, width=10, color_system="truecolor", legacy_windows=False, _environ={}, ) progress = Progress( BarColumn(bar_width=None), console=console, get_time=lambda: 1.0, auto_refresh=False, ) progress.add_task("foo") with progress: pass expected = "\x1b[?25l\x1b[38;5;237m━━━━━━━━━━\x1b[0m\r\x1b[2K\x1b[38;5;237m━━━━━━━━━━\x1b[0m\n\x1b[?25h" render_result = console.file.getvalue() print("RESULT\n", repr(render_result)) print("EXPECTED\n", repr(expected)) assert render_result == expected def test_progress_with_none_total_renders_a_pulsing_bar() -> None: console = Console( file=io.StringIO(), force_terminal=True, width=10, color_system="truecolor", legacy_windows=False, _environ={}, ) progress = Progress( BarColumn(bar_width=None), console=console, get_time=lambda: 1.0, auto_refresh=False, ) progress.add_task("foo", total=None) with progress: pass expected = "\x1b[?25l\x1b[38;2;153;48;86m━\x1b[0m\x1b[38;2;183;44;94m━\x1b[0m\x1b[38;2;209;42;102m━\x1b[0m\x1b[38;2;230;39;108m━\x1b[0m\x1b[38;2;244;38;112m━\x1b[0m\x1b[38;2;249;38;114m━\x1b[0m\x1b[38;2;244;38;112m━\x1b[0m\x1b[38;2;230;39;108m━\x1b[0m\x1b[38;2;209;42;102m━\x1b[0m\x1b[38;2;183;44;94m━\x1b[0m\r\x1b[2K\x1b[38;2;153;48;86m━\x1b[0m\x1b[38;2;183;44;94m━\x1b[0m\x1b[38;2;209;42;102m━\x1b[0m\x1b[38;2;230;39;108m━\x1b[0m\x1b[38;2;244;38;112m━\x1b[0m\x1b[38;2;249;38;114m━\x1b[0m\x1b[38;2;244;38;112m━\x1b[0m\x1b[38;2;230;39;108m━\x1b[0m\x1b[38;2;209;42;102m━\x1b[0m\x1b[38;2;183;44;94m━\x1b[0m\n\x1b[?25h" render_result = console.file.getvalue() print("RESULT\n", repr(render_result)) print("EXPECTED\n", repr(expected)) assert render_result == expected def test_render() -> None: expected = "\x1b[?25lfoo \x1b[38;5;237m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\x1b[0m \x1b[35m 0%\x1b[0m \x1b[36m-:--:--\x1b[0m\nbar \x1b[38;2;249;38;114m━━━━━━━━━━━━━━━━━━━━━\x1b[0m\x1b[38;5;237m╺\x1b[0m\x1b[38;5;237m━━━━━━━━━━━━━━━━━━\x1b[0m \x1b[35m 53%\x1b[0m \x1b[36m-:--:--\x1b[0m\nfoo2 \x1b[38;2;114;156;31m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\x1b[0m \x1b[35m100%\x1b[0m \x1b[36m0:00:00\x1b[0m\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2Kfoo \x1b[38;5;237m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\x1b[0m \x1b[35m 0%\x1b[0m \x1b[36m-:--:--\x1b[0m\nbar \x1b[38;2;249;38;114m━━━━━━━━━━━━━━━━━━━━━\x1b[0m\x1b[38;5;237m╺\x1b[0m\x1b[38;5;237m━━━━━━━━━━━━━━━━━━\x1b[0m \x1b[35m 53%\x1b[0m \x1b[36m-:--:--\x1b[0m\nfoo2 \x1b[38;2;114;156;31m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\x1b[0m \x1b[35m100%\x1b[0m \x1b[36m0:00:00\x1b[0m\n\x1b[?25h" render_result = render_progress() print(repr(render_result)) assert render_result == expected def test_track() -> None: console = Console( file=io.StringIO(), force_terminal=True, width=60, color_system="truecolor", legacy_windows=False, _environ={}, ) test = ["foo", "bar", "baz"] expected_values = iter(test) for value in track( test, "test", console=console, auto_refresh=False, get_time=MockClock(auto=True) ): assert value == next(expected_values) result = console.file.getvalue() print(repr(result)) expected = "\x1b[?25l\r\x1b[2Ktest \x1b[38;5;237m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\x1b[0m \x1b[35m 0%\x1b[0m \x1b[36m-:--:--\x1b[0m\r\x1b[2Ktest \x1b[38;2;249;38;114m━━━━━━━━━━━━━\x1b[0m\x1b[38;5;237m╺\x1b[0m\x1b[38;5;237m━━━━━━━━━━━━━━━━━━━━━━━━━━\x1b[0m \x1b[35m 33%\x1b[0m \x1b[36m-:--:--\x1b[0m\r\x1b[2Ktest \x1b[38;2;249;38;114m━━━━━━━━━━━━━━━━━━━━━━━━━━\x1b[0m\x1b[38;2;249;38;114m╸\x1b[0m\x1b[38;5;237m━━━━━━━━━━━━━\x1b[0m \x1b[35m 67%\x1b[0m \x1b[36m0:00:06\x1b[0m\r\x1b[2Ktest \x1b[38;2;114;156;31m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\x1b[0m \x1b[35m100%\x1b[0m \x1b[33m0:00:19\x1b[0m\r\x1b[2Ktest \x1b[38;2;114;156;31m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\x1b[0m \x1b[35m100%\x1b[0m \x1b[33m0:00:19\x1b[0m\n\x1b[?25h" print("--") print("RESULT:") print(result) print(repr(result)) print("EXPECTED:") print(expected) print(repr(expected)) assert result == expected def test_progress_track() -> None: console = Console( file=io.StringIO(), force_terminal=True, width=60, color_system="truecolor", legacy_windows=False, _environ={}, ) progress = Progress( console=console, auto_refresh=False, get_time=MockClock(auto=True) ) test = ["foo", "bar", "baz"] expected_values = iter(test) with progress: for value in progress.track(test, description="test"): assert value == next(expected_values) result = console.file.getvalue() print(repr(result)) expected = "\x1b[?25l\r\x1b[2Ktest \x1b[38;5;237m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\x1b[0m \x1b[35m 0%\x1b[0m \x1b[36m-:--:--\x1b[0m\r\x1b[2Ktest \x1b[38;2;249;38;114m━━━━━━━━━━━━━\x1b[0m\x1b[38;5;237m╺\x1b[0m\x1b[38;5;237m━━━━━━━━━━━━━━━━━━━━━━━━━━\x1b[0m \x1b[35m 33%\x1b[0m \x1b[36m-:--:--\x1b[0m\r\x1b[2Ktest \x1b[38;2;249;38;114m━━━━━━━━━━━━━━━━━━━━━━━━━━\x1b[0m\x1b[38;2;249;38;114m╸\x1b[0m\x1b[38;5;237m━━━━━━━━━━━━━\x1b[0m \x1b[35m 67%\x1b[0m \x1b[36m0:00:06\x1b[0m\r\x1b[2Ktest \x1b[38;2;114;156;31m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\x1b[0m \x1b[35m100%\x1b[0m \x1b[36m0:00:00\x1b[0m\r\x1b[2Ktest \x1b[38;2;114;156;31m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\x1b[0m \x1b[35m100%\x1b[0m \x1b[36m0:00:00\x1b[0m\n\x1b[?25h" print(expected) print(repr(expected)) print(result) print(repr(result)) assert result == expected def test_columns() -> None: console = Console( file=io.StringIO(), force_terminal=True, width=80, log_time_format="[TIME]", color_system="truecolor", legacy_windows=False, log_path=False, _environ={}, ) progress = Progress( "test", TextColumn("{task.description}"), BarColumn(bar_width=None), TimeRemainingColumn(), TimeElapsedColumn(), FileSizeColumn(), TotalFileSizeColumn(), DownloadColumn(), TransferSpeedColumn(), MofNCompleteColumn(), MofNCompleteColumn(separator=" of "), transient=True, console=console, auto_refresh=False, get_time=MockClock(), ) task1 = progress.add_task("foo", total=10) task2 = progress.add_task("bar", total=7) with progress: for n in range(4): progress.advance(task1, 3) progress.advance(task2, 4) print("foo") console.log("hello") console.print("world") progress.refresh() from .render import replace_link_ids result = replace_link_ids(console.file.getvalue()) print(repr(result)) expected = "\x1b[?25ltest foo \x1b[38;5;237m━━━━━━━━━━\x1b[0m \x1b[36m-:--:--\x1b[0m \x1b[33m0:00:07\x1b[0m \x1b[32m0 bytes\x1b[0m \x1b[32m10 bytes\x1b[0m \x1b[32m0/10 bytes\x1b[0m \x1b[31m?\x1b[0m \x1b[32m 0/10\x1b[0m \x1b[32m 0 of 10\x1b[0m\ntest bar \x1b[38;5;237m━━━━━━━━━━\x1b[0m \x1b[36m-:--:--\x1b[0m \x1b[33m0:00:18\x1b[0m \x1b[32m0 bytes\x1b[0m \x1b[32m7 bytes \x1b[0m \x1b[32m0/7 bytes \x1b[0m \x1b[31m?\x1b[0m \x1b[32m0/7 \x1b[0m \x1b[32m0 of 7 \x1b[0m\r\x1b[2K\x1b[1A\x1b[2Kfoo\ntest foo \x1b[38;5;237m━━━━━━━━━━\x1b[0m \x1b[36m-:--:--\x1b[0m \x1b[33m0:00:07\x1b[0m \x1b[32m0 bytes\x1b[0m \x1b[32m10 bytes\x1b[0m \x1b[32m0/10 bytes\x1b[0m \x1b[31m?\x1b[0m \x1b[32m 0/10\x1b[0m \x1b[32m 0 of 10\x1b[0m\ntest bar \x1b[38;5;237m━━━━━━━━━━\x1b[0m \x1b[36m-:--:--\x1b[0m \x1b[33m0:00:18\x1b[0m \x1b[32m0 bytes\x1b[0m \x1b[32m7 bytes \x1b[0m \x1b[32m0/7 bytes \x1b[0m \x1b[31m?\x1b[0m \x1b[32m0/7 \x1b[0m \x1b[32m0 of 7 \x1b[0m\r\x1b[2K\x1b[1A\x1b[2K\x1b[2;36m[TIME]\x1b[0m\x1b[2;36m \x1b[0mhello \ntest foo \x1b[38;5;237m━━━━━━━━━━\x1b[0m \x1b[36m-:--:--\x1b[0m \x1b[33m0:00:07\x1b[0m \x1b[32m0 bytes\x1b[0m \x1b[32m10 bytes\x1b[0m \x1b[32m0/10 bytes\x1b[0m \x1b[31m?\x1b[0m \x1b[32m 0/10\x1b[0m \x1b[32m 0 of 10\x1b[0m\ntest bar \x1b[38;5;237m━━━━━━━━━━\x1b[0m \x1b[36m-:--:--\x1b[0m \x1b[33m0:00:18\x1b[0m \x1b[32m0 bytes\x1b[0m \x1b[32m7 bytes \x1b[0m \x1b[32m0/7 bytes \x1b[0m \x1b[31m?\x1b[0m \x1b[32m0/7 \x1b[0m \x1b[32m0 of 7 \x1b[0m\r\x1b[2K\x1b[1A\x1b[2Kworld\ntest foo \x1b[38;5;237m━━━━━━━━━━\x1b[0m \x1b[36m-:--:--\x1b[0m \x1b[33m0:00:07\x1b[0m \x1b[32m0 bytes\x1b[0m \x1b[32m10 bytes\x1b[0m \x1b[32m0/10 bytes\x1b[0m \x1b[31m?\x1b[0m \x1b[32m 0/10\x1b[0m \x1b[32m 0 of 10\x1b[0m\ntest bar \x1b[38;5;237m━━━━━━━━━━\x1b[0m \x1b[36m-:--:--\x1b[0m \x1b[33m0:00:18\x1b[0m \x1b[32m0 bytes\x1b[0m \x1b[32m7 bytes \x1b[0m \x1b[32m0/7 bytes \x1b[0m \x1b[31m?\x1b[0m \x1b[32m0/7 \x1b[0m \x1b[32m0 of 7 \x1b[0m\r\x1b[2K\x1b[1A\x1b[2Ktest foo \x1b[38;2;114;156;31m━━━━━━━\x1b[0m \x1b[36m0:00:00\x1b[0m \x1b[33m0:00:34\x1b[0m \x1b[32m12 \x1b[0m \x1b[32m10 \x1b[0m \x1b[32m12/10 \x1b[0m \x1b[31m1 \x1b[0m \x1b[32m12/10\x1b[0m \x1b[32m12 of 10\x1b[0m\n \x1b[32mbytes \x1b[0m \x1b[32mbytes \x1b[0m \x1b[32mbytes \x1b[0m \x1b[31mbyte/s \x1b[0m \ntest bar \x1b[38;2;114;156;31m━━━━━━━\x1b[0m \x1b[36m0:00:00\x1b[0m \x1b[33m0:00:29\x1b[0m \x1b[32m16 \x1b[0m \x1b[32m7 bytes\x1b[0m \x1b[32m16/7 \x1b[0m \x1b[31m2 \x1b[0m \x1b[32m16/7 \x1b[0m \x1b[32m16 of 7 \x1b[0m\n \x1b[32mbytes \x1b[0m \x1b[32mbytes \x1b[0m \x1b[31mbytes/s\x1b[0m \r\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2Ktest foo \x1b[38;2;114;156;31m━━━━━━━\x1b[0m \x1b[36m0:00:00\x1b[0m \x1b[33m0:00:34\x1b[0m \x1b[32m12 \x1b[0m \x1b[32m10 \x1b[0m \x1b[32m12/10 \x1b[0m \x1b[31m1 \x1b[0m \x1b[32m12/10\x1b[0m \x1b[32m12 of 10\x1b[0m\n \x1b[32mbytes \x1b[0m \x1b[32mbytes \x1b[0m \x1b[32mbytes \x1b[0m \x1b[31mbyte/s \x1b[0m \ntest bar \x1b[38;2;114;156;31m━━━━━━━\x1b[0m \x1b[36m0:00:00\x1b[0m \x1b[33m0:00:29\x1b[0m \x1b[32m16 \x1b[0m \x1b[32m7 bytes\x1b[0m \x1b[32m16/7 \x1b[0m \x1b[31m2 \x1b[0m \x1b[32m16/7 \x1b[0m \x1b[32m16 of 7 \x1b[0m\n \x1b[32mbytes \x1b[0m \x1b[32mbytes \x1b[0m \x1b[31mbytes/s\x1b[0m \n\x1b[?25h\r\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K" assert result == expected def test_using_default_columns() -> None: # can only check types, as the instances do not '==' each other expected_default_types = [ TextColumn, BarColumn, TaskProgressColumn, TimeRemainingColumn, ] progress = Progress() assert [type(c) for c in progress.columns] == expected_default_types progress = Progress( SpinnerColumn(), *Progress.get_default_columns(), "Elapsed:", TimeElapsedColumn(), ) assert [type(c) for c in progress.columns] == [ SpinnerColumn, *expected_default_types, str, TimeElapsedColumn, ] def test_task_create() -> None: task = Task(TaskID(1), "foo", 100, 0, _get_time=lambda: 1) assert task.elapsed is None assert not task.finished assert task.percentage == 0.0 assert task.speed is None assert task.time_remaining is None def test_task_start() -> None: current_time = 1 def get_time(): nonlocal current_time return current_time task = Task(TaskID(1), "foo", 100, 0, _get_time=get_time) task.start_time = get_time() assert task.started == True assert task.elapsed == 0 current_time += 1 assert task.elapsed == 1 current_time += 1 task.stop_time = get_time() current_time += 1 assert task.elapsed == 2 def test_task_zero_total() -> None: task = Task(TaskID(1), "foo", 0, 0, _get_time=lambda: 1) assert task.percentage == 0 def test_progress_create() -> None: progress = Progress() assert progress.finished assert progress.tasks == [] assert progress.task_ids == [] def test_track_thread() -> None: progress = Progress() task_id = progress.add_task("foo") track_thread = _TrackThread(progress, task_id, 0.1) assert track_thread.completed == 0 from time import sleep with track_thread: track_thread.completed = 1 sleep(0.3) assert progress.tasks[task_id].completed >= 1 track_thread.completed += 1 def test_reset() -> None: progress = Progress() task_id = progress.add_task("foo") progress.advance(task_id, 1) progress.advance(task_id, 1) progress.advance(task_id, 1) progress.advance(task_id, 7) task = progress.tasks[task_id] assert task.completed == 10 progress.reset( task_id, total=200, completed=20, visible=False, description="bar", example="egg", ) assert task.total == 200 assert task.completed == 20 assert task.visible == False assert task.description == "bar" assert task.fields == {"example": "egg"} assert not task._progress def test_progress_max_refresh() -> None: """Test max_refresh argument.""" time = 0.0 def get_time() -> float: nonlocal time try: return time finally: time = time + 1.0 console = Console( color_system=None, width=80, legacy_windows=False, force_terminal=True, _environ={}, ) column = TextColumn("{task.description}") column.max_refresh = 3 progress = Progress( column, get_time=get_time, auto_refresh=False, console=console, ) console.begin_capture() with progress: task_id = progress.add_task("start") for tick in range(6): progress.update(task_id, description=f"tick {tick}") progress.refresh() result = console.end_capture() print(repr(result)) assert ( result == "\x1b[?25l\r\x1b[2Kstart\r\x1b[2Kstart\r\x1b[2Ktick 1\r\x1b[2Ktick 1\r\x1b[2Ktick 3\r\x1b[2Ktick 3\r\x1b[2Ktick 5\r\x1b[2Ktick 5\n\x1b[?25h" ) def test_live_is_started_if_progress_is_enabled() -> None: progress = Progress(auto_refresh=False, disable=False) with progress: assert progress.live._started def test_live_is_not_started_if_progress_is_disabled() -> None: progress = Progress(auto_refresh=False, disable=True) with progress: assert not progress.live._started def test_no_output_if_progress_is_disabled() -> None: console = Console( file=io.StringIO(), force_terminal=True, width=60, color_system="truecolor", legacy_windows=False, _environ={}, ) progress = Progress( console=console, disable=True, ) test = ["foo", "bar", "baz"] expected_values = iter(test) with progress: for value in progress.track(test, description="test"): assert value == next(expected_values) result = console.file.getvalue() print(repr(result)) expected = "" assert result == expected def test_open() -> None: console = Console( file=io.StringIO(), force_terminal=True, width=60, color_system="truecolor", legacy_windows=False, _environ={}, ) progress = Progress( console=console, ) fd, filename = tempfile.mkstemp() with os.fdopen(fd, "wb") as f: f.write(b"Hello, World!") try: with rich.progress.open(filename) as f: assert f.read() == "Hello, World!" assert f.closed finally: os.remove(filename) def test_open_text_mode() -> None: fd, filename = tempfile.mkstemp() with os.fdopen(fd, "wb") as f: f.write(b"Hello, World!") try: with rich.progress.open(filename, "r") as f: assert f.read() == "Hello, World!" assert f.name == filename assert f.closed finally: os.remove(filename) def test_wrap_file() -> None: fd, filename = tempfile.mkstemp() with os.fdopen(fd, "wb") as f: total = f.write(b"Hello, World!") try: with open(filename, "rb") as file: with rich.progress.wrap_file(file, total=total) as f: assert f.read() == b"Hello, World!" assert f.mode == "rb" assert f.name == filename assert f.closed assert not f.handle.closed assert not file.closed assert file.closed finally: os.remove(filename) def test_wrap_file_task_total() -> None: console = Console( file=io.StringIO(), force_terminal=True, width=60, color_system="truecolor", legacy_windows=False, _environ={}, ) progress = Progress( console=console, ) fd, filename = tempfile.mkstemp() with os.fdopen(fd, "wb") as f: total = f.write(b"Hello, World!") try: with progress: with open(filename, "rb") as file: task_id = progress.add_task("Reading", total=total) with progress.wrap_file(file, task_id=task_id) as f: assert f.read() == b"Hello, World!" finally: os.remove(filename) def test_task_progress_column_speed() -> None: speed_text = TaskProgressColumn.render_speed(None) assert speed_text.plain == "" speed_text = TaskProgressColumn.render_speed(5) assert speed_text.plain == "5.0 it/s" speed_text = TaskProgressColumn.render_speed(5000) assert speed_text.plain == "5.0×10³ it/s" speed_text = TaskProgressColumn.render_speed(8888888) assert speed_text.plain == "8.9×10⁶ it/s" if __name__ == "__main__": _render = render_progress() print(_render) print(repr(_render))
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_syntax.py
tests/test_syntax.py
import io import os import sys import tempfile from importlib.metadata import Distribution import pytest from pygments.lexers import PythonLexer from rich.measure import Measurement from rich.panel import Panel from rich.style import Style from rich.syntax import ( ANSISyntaxTheme, Color, Console, PygmentsSyntaxTheme, Syntax, _SyntaxHighlightRange, ) from .render import render PYGMENTS_VERSION = Distribution.from_name("pygments").version OLD_PYGMENTS = PYGMENTS_VERSION == "2.13.0" CODE = '''\ def loop_first_last(values: Iterable[T]) -> Iterable[Tuple[bool, bool, T]]: """Iterate and generate a tuple with a flag for first and last value.""" iter_values = iter(values) try: previous_value = next(iter_values) except StopIteration: return first = True for value in iter_values: yield first, False, previous_value first = False previous_value = value yield first, True, previous_value''' def test_blank_lines() -> None: code = "\n\nimport this\n\n" syntax = Syntax( code, lexer="python", theme="ascii_light", code_width=30, line_numbers=True ) result = render(syntax) print(repr(result)) assert ( result == "\x1b[1;38;2;24;24;24;48;2;248;248;248m \x1b[0m\x1b[38;2;173;173;173;48;2;248;248;248m1 \x1b[0m\x1b[48;2;248;248;248m \x1b[0m\n\x1b[1;38;2;24;24;24;48;2;248;248;248m \x1b[0m\x1b[38;2;173;173;173;48;2;248;248;248m2 \x1b[0m\x1b[48;2;248;248;248m \x1b[0m\n\x1b[1;38;2;24;24;24;48;2;248;248;248m \x1b[0m\x1b[38;2;173;173;173;48;2;248;248;248m3 \x1b[0m\x1b[1;38;2;0;128;0;48;2;248;248;248mimport\x1b[0m\x1b[38;2;187;187;187;48;2;248;248;248m \x1b[0m\x1b[1;38;2;0;0;255;48;2;248;248;248mthis\x1b[0m\x1b[48;2;248;248;248m \x1b[0m\n\x1b[1;38;2;24;24;24;48;2;248;248;248m \x1b[0m\x1b[38;2;173;173;173;48;2;248;248;248m4 \x1b[0m\x1b[48;2;248;248;248m \x1b[0m\n\x1b[1;38;2;24;24;24;48;2;248;248;248m \x1b[0m\x1b[38;2;173;173;173;48;2;248;248;248m5 \x1b[0m\x1b[48;2;248;248;248m \x1b[0m\n" ) def test_python_render() -> None: syntax = Panel.fit( Syntax( CODE, lexer="python", line_numbers=True, line_range=(2, 10), theme="monokai", code_width=60, word_wrap=True, ), padding=0, ) rendered_syntax = render(syntax) print(repr(rendered_syntax)) expected = '╭─────────────────────────────────────────────────────────────────╮\n│\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 2 \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;230;219;116;48;2;39;40;34m"""Iterate and generate a tuple with a flag for first \x1b[0m\x1b[48;2;39;40;34m \x1b[0m│\n│\x1b[48;2;39;40;34m \x1b[0m\x1b[38;2;230;219;116;48;2;39;40;34mand last value."""\x1b[0m\x1b[48;2;39;40;34m \x1b[0m│\n│\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 3 \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34miter_values\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34m=\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34miter\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m(\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mvalues\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m)\x1b[0m\x1b[48;2;39;40;34m \x1b[0m│\n│\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 4 \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mtry\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m:\x1b[0m\x1b[48;2;39;40;34m \x1b[0m│\n│\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 5 \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mprevious_value\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34m=\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mnext\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m(\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34miter_values\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m)\x1b[0m\x1b[48;2;39;40;34m \x1b[0m│\n│\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 6 \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mexcept\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;166;226;46;48;2;39;40;34mStopIteration\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m:\x1b[0m\x1b[48;2;39;40;34m \x1b[0m│\n│\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 7 \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mreturn\x1b[0m\x1b[48;2;39;40;34m \x1b[0m│\n│\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 8 \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mfirst\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34m=\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mTrue\x1b[0m\x1b[48;2;39;40;34m \x1b[0m│\n│\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 9 \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mfor\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mvalue\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34min\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34miter_values\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m:\x1b[0m\x1b[48;2;39;40;34m \x1b[0m│\n│\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m10 \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34myield\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mfirst\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m,\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mFalse\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m,\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mprevious_value\x1b[0m\x1b[48;2;39;40;34m \x1b[0m│\n╰─────────────────────────────────────────────────────────────────╯\n' assert rendered_syntax == expected def test_python_render_simple() -> None: syntax = Syntax( CODE, lexer="python", line_numbers=False, theme="monokai", code_width=60, word_wrap=False, ) rendered_syntax = render(syntax) print(repr(rendered_syntax)) expected = '\x1b[38;2;102;217;239;48;2;39;40;34mdef\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;166;226;46;48;2;39;40;34mloop_first_last\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m(\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mvalues\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m:\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mIterable\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m[\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mT\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m]\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m)\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34m-\x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34m>\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mIterable\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m[\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mTuple\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m[\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mb\x1b[0m\n\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;230;219;116;48;2;39;40;34m"""Iterate and generate a tuple with a flag for first an\x1b[0m\n\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34miter_values\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34m=\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34miter\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m(\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mvalues\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m)\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mtry\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m:\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mprevious_value\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34m=\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mnext\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m(\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34miter_values\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m)\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mexcept\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;166;226;46;48;2;39;40;34mStopIteration\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m:\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mreturn\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mfirst\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34m=\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mTrue\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mfor\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mvalue\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34min\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34miter_values\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m:\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34myield\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mfirst\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m,\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mFalse\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m,\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mprevious_value\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mfirst\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34m=\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mFalse\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mprevious_value\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34m=\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mvalue\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34myield\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mfirst\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m,\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mTrue\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m,\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mprevious_value\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n' assert rendered_syntax == expected def test_python_render_simple_passing_lexer_instance() -> None: syntax = Syntax( CODE, lexer=PythonLexer(), line_numbers=False, theme="monokai", code_width=60, word_wrap=False, ) rendered_syntax = render(syntax) print(repr(rendered_syntax)) expected = '\x1b[38;2;102;217;239;48;2;39;40;34mdef\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;166;226;46;48;2;39;40;34mloop_first_last\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m(\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mvalues\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m:\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mIterable\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m[\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mT\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m]\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m)\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34m-\x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34m>\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mIterable\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m[\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mTuple\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m[\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mb\x1b[0m\n\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;230;219;116;48;2;39;40;34m"""Iterate and generate a tuple with a flag for first an\x1b[0m\n\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34miter_values\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34m=\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34miter\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m(\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mvalues\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m)\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mtry\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m:\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mprevious_value\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34m=\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mnext\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m(\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34miter_values\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m)\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mexcept\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;166;226;46;48;2;39;40;34mStopIteration\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m:\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mreturn\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mfirst\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34m=\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mTrue\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mfor\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mvalue\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34min\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34miter_values\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m:\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34myield\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mfirst\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m,\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mFalse\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m,\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mprevious_value\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mfirst\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34m=\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mFalse\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mprevious_value\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34m=\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mvalue\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34myield\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mfirst\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m,\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mTrue\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m,\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mprevious_value\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n' assert rendered_syntax == expected @pytest.mark.skipif(OLD_PYGMENTS, reason="Pygments changed their tokenizer") def test_python_render_simple_indent_guides() -> None: syntax = Syntax( CODE, lexer="python", line_numbers=False, theme="ansi_light", code_width=60, word_wrap=False, indent_guides=True, ) rendered_syntax = render(syntax) print(repr(rendered_syntax)) expected = '\x1b[34mdef\x1b[0m\x1b[37m \x1b[0m\x1b[32mloop_first_last\x1b[0m(values: Iterable[T]) -> Iterable[Tuple[\x1b[36mb\x1b[0m\n\x1b[2;37m│ \x1b[0m\x1b[33m"""Iterate and generate a tuple with a flag for first an\x1b[0m\n\x1b[2m│ \x1b[0miter_values = \x1b[36miter\x1b[0m(values)\n\x1b[2m│ \x1b[0m\x1b[34mtry\x1b[0m:\n\x1b[2m│ │ \x1b[0mprevious_value = \x1b[36mnext\x1b[0m(iter_values)\n\x1b[2m│ \x1b[0m\x1b[34mexcept\x1b[0m \x1b[36mStopIteration\x1b[0m:\n\x1b[2m│ │ \x1b[0m\x1b[34mreturn\x1b[0m\n\x1b[2m│ \x1b[0mfirst = \x1b[34mTrue\x1b[0m\n\x1b[2m│ \x1b[0m\x1b[34mfor\x1b[0m value \x1b[35min\x1b[0m iter_values:\n\x1b[2m│ │ \x1b[0m\x1b[34myield\x1b[0m first, \x1b[34mFalse\x1b[0m, previous_value\n\x1b[2m│ │ \x1b[0mfirst = \x1b[34mFalse\x1b[0m\n\x1b[2m│ │ \x1b[0mprevious_value = value\n\x1b[2m│ \x1b[0m\x1b[34myield\x1b[0m first, \x1b[34mTrue\x1b[0m, previous_value\n' assert rendered_syntax == expected @pytest.mark.skipif(OLD_PYGMENTS, reason="Pygments changed their tokenizer") def test_python_render_line_range_indent_guides() -> None: syntax = Syntax( CODE, lexer="python", line_numbers=False, theme="ansi_light", code_width=60, word_wrap=False, line_range=(2, 3), indent_guides=True, ) rendered_syntax = render(syntax) print(repr(rendered_syntax)) expected = '\x1b[2;37m│ \x1b[0m\x1b[33m"""Iterate and generate a tuple with a flag for first an\x1b[0m\n\x1b[2m│ \x1b[0miter_values = \x1b[36miter\x1b[0m(values)\n' assert rendered_syntax == expected def test_python_render_indent_guides() -> None: syntax = Panel.fit( Syntax( CODE, lexer="python", line_numbers=True, line_range=(2, 10), theme="monokai", code_width=60, word_wrap=True, indent_guides=True, ), padding=0, ) rendered_syntax = render(syntax) print(repr(rendered_syntax)) expected = '╭─────────────────────────────────────────────────────────────────╮\n│\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 2 \x1b[0m\x1b[2;38;2;149;144;119;48;2;39;40;34m│ \x1b[0m\x1b[38;2;230;219;116;48;2;39;40;34m"""Iterate and generate a tuple with a flag for first \x1b[0m\x1b[48;2;39;40;34m \x1b[0m│\n│\x1b[48;2;39;40;34m \x1b[0m\x1b[38;2;230;219;116;48;2;39;40;34mand last value."""\x1b[0m\x1b[48;2;39;40;34m \x1b[0m│\n│\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 3 \x1b[0m\x1b[2;38;2;149;144;119;48;2;39;40;34m│ \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34miter_values\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34m=\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34miter\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m(\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mvalues\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m)\x1b[0m\x1b[48;2;39;40;34m \x1b[0m│\n│\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 4 \x1b[0m\x1b[2;38;2;149;144;119;48;2;39;40;34m│ \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mtry\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m:\x1b[0m\x1b[48;2;39;40;34m \x1b[0m│\n│\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 5 \x1b[0m\x1b[2;38;2;149;144;119;48;2;39;40;34m│ │ \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mprevious_value\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34m=\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mnext\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m(\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34miter_values\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m)\x1b[0m\x1b[48;2;39;40;34m \x1b[0m│\n│\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 6 \x1b[0m\x1b[2;38;2;149;144;119;48;2;39;40;34m│ \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mexcept\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;166;226;46;48;2;39;40;34mStopIteration\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m:\x1b[0m\x1b[48;2;39;40;34m \x1b[0m│\n│\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 7 \x1b[0m\x1b[2;38;2;149;144;119;48;2;39;40;34m│ │ \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mreturn\x1b[0m\x1b[48;2;39;40;34m \x1b[0m│\n│\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 8 \x1b[0m\x1b[2;38;2;149;144;119;48;2;39;40;34m│ \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mfirst\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34m=\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mTrue\x1b[0m\x1b[48;2;39;40;34m \x1b[0m│\n│\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 9 \x1b[0m\x1b[2;38;2;149;144;119;48;2;39;40;34m│ \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mfor\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mvalue\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34min\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34miter_values\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m:\x1b[0m\x1b[48;2;39;40;34m \x1b[0m│\n│\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m10 \x1b[0m\x1b[2;38;2;149;144;119;48;2;39;40;34m│ │ \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34myield\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mfirst\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m,\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mFalse\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m,\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mprevious_value\x1b[0m\x1b[48;2;39;40;34m \x1b[0m│\n╰─────────────────────────────────────────────────────────────────╯\n' assert rendered_syntax == expected def test_pygments_syntax_theme_non_str() -> None: from pygments.style import Style as PygmentsStyle style = PygmentsSyntaxTheme(PygmentsStyle()) assert style.get_background_style().bgcolor == Color.parse("#ffffff") def test_pygments_syntax_theme() -> None: style = PygmentsSyntaxTheme("default") assert style.get_style_for_token("abc") == Style.parse("none") def test_get_line_color_none() -> None: style = PygmentsSyntaxTheme("default") style._background_style = Style(bgcolor=None) syntax = Syntax( CODE, lexer="python", line_numbers=True, line_range=(2, 10), theme=style, code_width=60, word_wrap=True, background_color="red", ) assert syntax._get_line_numbers_color() == Color.default() def test_highlight_background_color() -> None: syntax = Syntax( CODE, lexer="python", line_numbers=True, line_range=(2, 10), theme="foo", code_width=60, word_wrap=True, background_color="red", ) assert syntax.highlight(CODE).style == Style.parse("on red") def test_get_number_styles() -> None: syntax = Syntax(CODE, "python", theme="monokai", line_numbers=True) console = Console(color_system="windows") assert syntax._get_number_styles(console=console) == ( Style.parse("on #272822"), Style.parse("dim on #272822"), Style.parse("not dim on #272822"), ) def test_get_style_for_token() -> None: # from pygments.style import Style as PygmentsStyle # pygments_style = PygmentsStyle() from pygments.style import Token style = PygmentsSyntaxTheme("default") style_dict = {Token.Text: Style(color=None)} style._style_cache = style_dict syntax = Syntax( CODE, lexer="python", line_numbers=True, line_range=(2, 10), theme=style, code_width=60, word_wrap=True, background_color="red", ) assert syntax._get_line_numbers_color() == Color.default() def test_option_no_wrap() -> None: syntax = Syntax( CODE, lexer="python", line_numbers=True, line_range=(2, 10), code_width=60, word_wrap=False, background_color="red", ) rendered_syntax = render(syntax, True) print(repr(rendered_syntax)) expected = '\x1b[1;39;41m \x1b[0m\x1b[39;41m 2 \x1b[0m\x1b[38;2;248;248;242;41m \x1b[0m\x1b[38;2;230;219;116;41m"""Iterate and generate a tuple with a flag for first and last value."""\x1b[0m\n\x1b[1;39;41m \x1b[0m\x1b[39;41m 3 \x1b[0m\x1b[38;2;248;248;242;41m \x1b[0m\x1b[38;2;248;248;242;41miter_values\x1b[0m\x1b[38;2;248;248;242;41m \x1b[0m\x1b[38;2;255;70;137;41m=\x1b[0m\x1b[38;2;248;248;242;41m \x1b[0m\x1b[38;2;248;248;242;41miter\x1b[0m\x1b[38;2;248;248;242;41m(\x1b[0m\x1b[38;2;248;248;242;41mvalues\x1b[0m\x1b[38;2;248;248;242;41m)\x1b[0m\n\x1b[1;39;41m \x1b[0m\x1b[39;41m 4 \x1b[0m\x1b[38;2;248;248;242;41m \x1b[0m\x1b[38;2;102;217;239;41mtry\x1b[0m\x1b[38;2;248;248;242;41m:\x1b[0m\n\x1b[1;39;41m \x1b[0m\x1b[39;41m 5 \x1b[0m\x1b[38;2;248;248;242;41m \x1b[0m\x1b[38;2;248;248;242;41mprevious_value\x1b[0m\x1b[38;2;248;248;242;41m \x1b[0m\x1b[38;2;255;70;137;41m=\x1b[0m\x1b[38;2;248;248;242;41m \x1b[0m\x1b[38;2;248;248;242;41mnext\x1b[0m\x1b[38;2;248;248;242;41m(\x1b[0m\x1b[38;2;248;248;242;41miter_values\x1b[0m\x1b[38;2;248;248;242;41m)\x1b[0m\n\x1b[1;39;41m \x1b[0m\x1b[39;41m 6 \x1b[0m\x1b[38;2;248;248;242;41m \x1b[0m\x1b[38;2;102;217;239;41mexcept\x1b[0m\x1b[38;2;248;248;242;41m \x1b[0m\x1b[38;2;166;226;46;41mStopIteration\x1b[0m\x1b[38;2;248;248;242;41m:\x1b[0m\n\x1b[1;39;41m \x1b[0m\x1b[39;41m 7 \x1b[0m\x1b[38;2;248;248;242;41m \x1b[0m\x1b[38;2;102;217;239;41mreturn\x1b[0m\n\x1b[1;39;41m \x1b[0m\x1b[39;41m 8 \x1b[0m\x1b[38;2;248;248;242;41m \x1b[0m\x1b[38;2;248;248;242;41mfirst\x1b[0m\x1b[38;2;248;248;242;41m \x1b[0m\x1b[38;2;255;70;137;41m=\x1b[0m\x1b[38;2;248;248;242;41m \x1b[0m\x1b[38;2;102;217;239;41mTrue\x1b[0m\n\x1b[1;39;41m \x1b[0m\x1b[39;41m 9 \x1b[0m\x1b[38;2;248;248;242;41m \x1b[0m\x1b[38;2;102;217;239;41mfor\x1b[0m\x1b[38;2;248;248;242;41m \x1b[0m\x1b[38;2;248;248;242;41mvalue\x1b[0m\x1b[38;2;248;248;242;41m \x1b[0m\x1b[38;2;255;70;137;41min\x1b[0m\x1b[38;2;248;248;242;41m \x1b[0m\x1b[38;2;248;248;242;41miter_values\x1b[0m\x1b[38;2;248;248;242;41m:\x1b[0m\n\x1b[1;39;41m \x1b[0m\x1b[39;41m10 \x1b[0m\x1b[38;2;248;248;242;41m \x1b[0m\x1b[38;2;102;217;239;41myield\x1b[0m\x1b[38;2;248;248;242;41m \x1b[0m\x1b[38;2;248;248;242;41mfirst\x1b[0m\x1b[38;2;248;248;242;41m,\x1b[0m\x1b[38;2;248;248;242;41m \x1b[0m\x1b[38;2;102;217;239;41mFalse\x1b[0m\x1b[38;2;248;248;242;41m,\x1b[0m\x1b[38;2;248;248;242;41m \x1b[0m\x1b[38;2;248;248;242;41mprevious_value\x1b[0m\n' assert rendered_syntax == expected def test_syntax_highlight_ranges() -> None: syntax = Syntax( CODE, lexer="python", line_numbers=True, word_wrap=False, ) stylized_ranges = [ _SyntaxHighlightRange( # overline the 2nd char of the 1st line: start=(1, 1), end=(1, 2), style=Style(overline=True), ), _SyntaxHighlightRange( start=(1, len("def loop_")), end=(1, len("def loop_first_last")), style=Style(underline=True), ), _SyntaxHighlightRange( start=(1, len("def loop_first")), end=(3, len(" iter_values = iter")), style=Style(bold=True), ), _SyntaxHighlightRange( start=(9, len(" for ")), end=(9, len(" for value in")), style=Style(strike=True), ), _SyntaxHighlightRange( start=(6, len(" except ")), end=(6, len(" except StopIteration")), style=Style(reverse=True), ), _SyntaxHighlightRange( start=(10, len(" yield first,")), # `column_index` is out of range: should be clamped to the line length: end=(10, 300), style=Style(bold=True), ), # For this one the end `line_number` is out of range, so it should have no impact: _SyntaxHighlightRange( start=(1, 1), end=(30, 2), style=Style(bold=True), ), ] for range_ in stylized_ranges: syntax.stylize_range(range_.style, range_.start, range_.end) rendered_syntax = render(syntax, True) print(repr(rendered_syntax))
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
true
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_columns_align.py
tests/test_columns_align.py
# encoding=utf-8 import io from rich import box from rich.columns import Columns from rich.console import Console from rich.panel import Panel def render(): console = Console(file=io.StringIO(), width=100, legacy_windows=False) panel = Panel.fit("foo", box=box.SQUARE, padding=0) columns = Columns([panel] * 4) columns.expand = True console.rule("no align") console.print(columns) columns.align = "left" console.rule("left align") console.print(columns) columns.align = "center" console.rule("center align") console.print(columns) columns.align = "right" console.rule("right align") console.print(columns) return console.file.getvalue() def test_align(): result = render() expected = "───────────────────────────────────────────── no align ─────────────────────────────────────────────\n┌───┐ ┌───┐ ┌───┐ ┌───┐ \n│foo│ │foo│ │foo│ │foo│ \n└───┘ └───┘ └───┘ └───┘ \n──────────────────────────────────────────── left align ────────────────────────────────────────────\n┌───┐ ┌───┐ ┌───┐ ┌───┐ \n│foo│ │foo│ │foo│ │foo│ \n└───┘ └───┘ └───┘ └───┘ \n─────────────────────────────────────────── center align ───────────────────────────────────────────\n ┌───┐ ┌───┐ ┌───┐ ┌───┐ \n │foo│ │foo│ │foo│ │foo│ \n └───┘ └───┘ └───┘ └───┘ \n─────────────────────────────────────────── right align ────────────────────────────────────────────\n ┌───┐ ┌───┐ ┌───┐ ┌───┐\n │foo│ │foo│ │foo│ │foo│\n └───┘ └───┘ └───┘ └───┘\n" assert result == expected if __name__ == "__main__": rendered = render() print(rendered) print(repr(rendered))
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_screen.py
tests/test_screen.py
from rich.console import Console from rich.screen import Screen def test_screen(): console = Console(color_system=None, width=20, height=5, legacy_windows=False) with console.capture() as capture: console.print(Screen("foo\nbar\nbaz\nfoo\nbar\nbaz\foo")) result = capture.get() print(repr(result)) expected = "foo \nbar \nbaz \nfoo \nbar " assert result == expected
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_layout.py
tests/test_layout.py
import sys import pytest from rich.console import Console from rich.layout import Layout, NoSplitter from rich.panel import Panel def test_no_layout(): layout = Layout() with pytest.raises(NoSplitter): layout.split(Layout(), Layout(), splitter="nope") def test_add_split(): layout = Layout() layout.split(Layout(), Layout()) assert len(layout.children) == 2 layout.add_split(Layout(name="foo")) assert len(layout.children) == 3 assert layout.children[2].name == "foo" def test_unsplit(): layout = Layout() layout.split(Layout(), Layout()) assert len(layout.children) == 2 layout.unsplit() assert len(layout.children) == 0 @pytest.mark.skipif(sys.platform == "win32", reason="does not run on windows") def test_render(): layout = Layout(name="root") repr(layout) layout.split_column(Layout(name="top"), Layout(name="bottom")) top = layout["top"] top.update(Panel("foo")) print(type(top._renderable)) assert isinstance(top.renderable, Panel) layout["bottom"].split_row(Layout(name="left"), Layout(name="right")) assert layout["root"].name == "root" assert layout["left"].name == "left" assert isinstance(layout.map, dict) with pytest.raises(KeyError): top["asdasd"] layout["left"].update("foobar") print(layout["left"].children) console = Console(width=60, color_system=None) with console.capture() as capture: console.print(layout, height=10) result = capture.get() print(repr(result)) expected = "╭──────────────────────────────────────────────────────────╮\n│ foo │\n│ │\n│ │\n╰──────────────────────────────────────────────────────────╯\nfoobar ╭───── 'right' (30 x 5) ─────╮\n │ │\n │ Layout(name='right') │\n │ │\n ╰────────────────────────────╯\n" assert result == expected def test_tree(): layout = Layout(name="root") layout.split(Layout("foo", size=2), Layout("bar", name="bar")) layout["bar"].split_row(Layout(), Layout()) console = Console(width=60, color_system=None) with console.capture() as capture: console.print(layout.tree, height=10) result = capture.get() print(repr(result)) expected = "⬍ Layout(name='root')\n├── ⬍ Layout(size=2)\n└── ⬌ Layout(name='bar')\n ├── ⬍ Layout()\n └── ⬍ Layout()\n" print(result, "\n", expected) assert result == expected @pytest.mark.skipif(sys.platform == "win32", reason="does not run on windows") def test_refresh_screen(): layout = Layout() layout.split_row(Layout(name="foo"), Layout(name="bar")) console = Console(force_terminal=True, width=20, height=5, _environ={}) with console.capture(): console.print(layout) with console.screen(): with console.capture() as capture: layout.refresh_screen(console, "foo") result = capture.get() print() print(repr(result)) expected = "\x1b[1;1H\x1b[34m╭─\x1b[0m\x1b[34m \x1b[0m\x1b[32m'foo'\x1b[0m\x1b[34m─╮\x1b[0m\x1b[2;1H\x1b[34m│\x1b[0m \x1b[1;35mLayout\x1b[0m \x1b[34m│\x1b[0m\x1b[3;1H\x1b[34m│\x1b[0m \x1b[1m(\x1b[0m \x1b[34m│\x1b[0m\x1b[4;1H\x1b[34m│\x1b[0m \x1b[33mna\x1b[0m \x1b[34m│\x1b[0m\x1b[5;1H\x1b[34m╰────────╯\x1b[0m" assert result == expected
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_pick.py
tests/test_pick.py
from rich._pick import pick_bool def test_pick_bool(): assert pick_bool(False) == False assert pick_bool(True) == True assert pick_bool(None) == False assert pick_bool(False, True) == False assert pick_bool(None, True) == True assert pick_bool(True, None) == True assert pick_bool(False, None) == False assert pick_bool(None, None) == False assert pick_bool(None, None, False, True) == False assert pick_bool(None, None, True, False) == True
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_stack.py
tests/test_stack.py
from rich._stack import Stack def test_stack(): stack = Stack() stack.push("foo") stack.push("bar") assert stack.top == "bar" assert stack.pop() == "bar" assert stack.top == "foo"
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_json.py
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) == '{\n "date": "2021-01-01"\n}'
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_tools.py
tests/test_tools.py
from rich._loop import loop_first, loop_last, loop_first_last from rich._ratio import ratio_distribute def test_loop_first(): assert list(loop_first([])) == [] iterable = loop_first(["apples", "oranges", "pears", "lemons"]) assert next(iterable) == (True, "apples") assert next(iterable) == (False, "oranges") assert next(iterable) == (False, "pears") assert next(iterable) == (False, "lemons") def test_loop_last(): assert list(loop_last([])) == [] iterable = loop_last(["apples", "oranges", "pears", "lemons"]) assert next(iterable) == (False, "apples") assert next(iterable) == (False, "oranges") assert next(iterable) == (False, "pears") assert next(iterable) == (True, "lemons") def test_loop_first_last(): assert list(loop_first_last([])) == [] iterable = loop_first_last(["apples", "oranges", "pears", "lemons"]) assert next(iterable) == (True, False, "apples") assert next(iterable) == (False, False, "oranges") assert next(iterable) == (False, False, "pears") assert next(iterable) == (False, True, "lemons") def test_ratio_distribute(): assert ratio_distribute(10, [1]) == [10] assert ratio_distribute(10, [1, 1]) == [5, 5] assert ratio_distribute(12, [1, 3]) == [3, 9] assert ratio_distribute(0, [1, 3]) == [0, 0] assert ratio_distribute(0, [1, 3], [1, 1]) == [1, 1] assert ratio_distribute(10, [1, 0]) == [10, 0]
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_inspect.py
tests/test_inspect.py
import io import sys from types import ModuleType from typing import Sequence, Type import pytest from rich import inspect from rich._inspect import ( get_object_types_mro, get_object_types_mro_as_strings, is_object_one_of_types, ) from rich.console import Console skip_py38 = pytest.mark.skipif( sys.version_info.minor == 8 and sys.version_info.major == 3, reason="rendered differently on py3.8", ) skip_py39 = pytest.mark.skipif( sys.version_info.minor == 9 and sys.version_info.major == 3, reason="rendered differently on py3.9", ) skip_py310 = pytest.mark.skipif( sys.version_info.minor == 10 and sys.version_info.major == 3, reason="rendered differently on py3.10", ) skip_py311 = pytest.mark.skipif( sys.version_info.minor == 11 and sys.version_info.major == 3, reason="rendered differently on py3.11", ) skip_py312 = pytest.mark.skipif( sys.version_info.minor == 12 and sys.version_info.major == 3, reason="rendered differently on py3.12", ) skip_py313 = pytest.mark.skipif( sys.version_info.minor == 13 and sys.version_info.major == 3, reason="rendered differently on py3.13", ) skip_py314 = pytest.mark.skipif( sys.version_info.minor == 14 and sys.version_info.major == 3, reason="rendered differently on py3.14", ) skip_pypy3 = pytest.mark.skipif( hasattr(sys, "pypy_version_info"), reason="rendered differently on pypy3", ) def render(obj, methods=False, value=False, width=50) -> str: console = Console(file=io.StringIO(), width=width, legacy_windows=False) inspect(obj, console=console, methods=methods, value=value) return console.file.getvalue() class InspectError(Exception): def __str__(self) -> str: return "INSPECT ERROR" class Foo: """Foo test Second line """ def __init__(self, foo: int) -> None: """constructor docs.""" self.foo = foo @property def broken(self): raise InspectError() def method(self, a, b) -> str: """Multi line docs. """ return "test" def __dir__(self): return ["__init__", "broken", "method"] class FooSubclass(Foo): pass def test_render(): console = Console(width=100, file=io.StringIO(), legacy_windows=False) foo = Foo("hello") inspect(foo, console=console, all=True, value=False) result = console.file.getvalue() print(repr(result)) expected = "╭────────────── <class 'tests.test_inspect.Foo'> ──────────────╮\n│ Foo test │\n│ │\n│ broken = InspectError() │\n│ __init__ = def __init__(foo: int) -> None: constructor docs. │\n│ method = def method(a, b) -> str: Multi line │\n╰──────────────────────────────────────────────────────────────╯\n" assert result == expected @skip_pypy3 def test_inspect_text(): num_attributes = 34 if sys.version_info >= (3, 11) else 33 expected = ( "╭──────────────── <class 'str'> ─────────────────╮\n" "│ str(object='') -> str │\n" "│ str(bytes_or_buffer[, encoding[, errors]]) -> │\n" "│ str │\n" "│ │\n" f"│ {num_attributes} attribute(s) not shown. Run │\n" "│ inspect(inspect) for options. │\n" "╰────────────────────────────────────────────────╯\n" ) print(repr(expected)) assert render("Hello") == expected @skip_pypy3 def test_inspect_empty_dict(): expected = ( "╭──────────────── <class 'dict'> ────────────────╮\n" "│ dict() -> new empty dictionary │\n" "│ dict(mapping) -> new dictionary initialized │\n" "│ from a mapping object's │\n" "│ (key, value) pairs │\n" "│ dict(iterable) -> new dictionary initialized │\n" "│ as if via: │\n" "│ d = {} │\n" "│ for k, v in iterable: │\n" "│ d[k] = v │\n" "│ dict(**kwargs) -> new dictionary initialized │\n" "│ with the name=value pairs │\n" "│ in the keyword argument list. For │\n" "│ example: dict(one=1, two=2) │\n" "│ │\n" ) assert render({}).startswith(expected) @skip_py314 @skip_py313 @skip_py312 @skip_py311 @skip_pypy3 def test_inspect_builtin_function_except_python311(): # Pre-3.11 Python versions - print builtin has no signature available expected = ( "╭────────── <built-in function print> ───────────╮\n" "│ def print(...) │\n" "│ │\n" "│ print(value, ..., sep=' ', end='\\n', │\n" "│ file=sys.stdout, flush=False) │\n" "│ │\n" "│ 29 attribute(s) not shown. Run │\n" "│ inspect(inspect) for options. │\n" "╰────────────────────────────────────────────────╯\n" ) assert render(print) == expected @pytest.mark.skipif( sys.version_info < (3, 11), reason="print builtin signature only available on 3.11+" ) @skip_pypy3 def test_inspect_builtin_function_only_python311(): # On 3.11, the print builtin *does* have a signature, unlike in prior versions expected = ( "╭────────── <built-in function print> ───────────╮\n" "│ def print(*args, sep=' ', end='\\n', file=None, │\n" "│ flush=False): │\n" "│ │\n" "│ Prints the values to a stream, or to │\n" "│ sys.stdout by default. │\n" "│ │\n" "│ 30 attribute(s) not shown. Run │\n" "│ inspect(inspect) for options. │\n" "╰────────────────────────────────────────────────╯\n" ) assert render(print) == expected @skip_pypy3 def test_inspect_coroutine(): async def coroutine(): pass expected = ( "╭─ <function test_inspect_coroutine.<locals>.cor─╮\n" "│ async def │\n" "│ test_inspect_coroutine.<locals>.coroutine(): │\n" ) assert render(coroutine).startswith(expected) def test_inspect_integer(): expected = ( "╭────── <class 'int'> ───────╮\n" "│ int([x]) -> integer │\n" "│ int(x, base=10) -> integer │\n" "│ │\n" "│ denominator = 1 │\n" "│ imag = 0 │\n" "│ numerator = 1 │\n" "│ real = 1 │\n" "╰────────────────────────────╯\n" ) assert expected == render(1) def test_inspect_integer_with_value(): expected = "╭────── <class 'int'> ───────╮\n│ int([x]) -> integer │\n│ int(x, base=10) -> integer │\n│ │\n│ ╭────────────────────────╮ │\n│ │ 1 │ │\n│ ╰────────────────────────╯ │\n│ │\n│ denominator = 1 │\n│ imag = 0 │\n│ numerator = 1 │\n│ real = 1 │\n╰────────────────────────────╯\n" value = render(1, value=True) print(repr(value)) assert value == expected @skip_py310 @skip_py311 @skip_py312 @skip_py313 @skip_py314 def test_inspect_integer_with_methods_python38_and_python39(): expected = ( "╭──────────────── <class 'int'> ─────────────────╮\n" "│ int([x]) -> integer │\n" "│ int(x, base=10) -> integer │\n" "│ │\n" "│ denominator = 1 │\n" "│ imag = 0 │\n" "│ numerator = 1 │\n" "│ real = 1 │\n" "│ as_integer_ratio = def as_integer_ratio(): │\n" "│ Return integer ratio. │\n" "│ bit_length = def bit_length(): Number of │\n" "│ bits necessary to represent │\n" "│ self in binary. │\n" "│ conjugate = def conjugate(...) Returns │\n" "│ self, the complex conjugate │\n" "│ of any int. │\n" "│ from_bytes = def from_bytes(bytes, │\n" "│ byteorder, *, │\n" "│ signed=False): Return the │\n" "│ integer represented by the │\n" "│ given array of bytes. │\n" "│ to_bytes = def to_bytes(length, │\n" "│ byteorder, *, │\n" "│ signed=False): Return an │\n" "│ array of bytes representing │\n" "│ an integer. │\n" "╰────────────────────────────────────────────────╯\n" ) assert render(1, methods=True) == expected @skip_py38 @skip_py39 @skip_py311 @skip_py312 @skip_py313 @skip_py314 def test_inspect_integer_with_methods_python310only(): expected = ( "╭──────────────── <class 'int'> ─────────────────╮\n" "│ int([x]) -> integer │\n" "│ int(x, base=10) -> integer │\n" "│ │\n" "│ denominator = 1 │\n" "│ imag = 0 │\n" "│ numerator = 1 │\n" "│ real = 1 │\n" "│ as_integer_ratio = def as_integer_ratio(): │\n" "│ Return integer ratio. │\n" "│ bit_count = def bit_count(): Number of │\n" "│ ones in the binary │\n" "│ representation of the │\n" "│ absolute value of self. │\n" "│ bit_length = def bit_length(): Number of │\n" "│ bits necessary to represent │\n" "│ self in binary. │\n" "│ conjugate = def conjugate(...) Returns │\n" "│ self, the complex conjugate │\n" "│ of any int. │\n" "│ from_bytes = def from_bytes(bytes, │\n" "│ byteorder, *, │\n" "│ signed=False): Return the │\n" "│ integer represented by the │\n" "│ given array of bytes. │\n" "│ to_bytes = def to_bytes(length, │\n" "│ byteorder, *, │\n" "│ signed=False): Return an │\n" "│ array of bytes representing │\n" "│ an integer. │\n" "╰────────────────────────────────────────────────╯\n" ) assert render(1, methods=True) == expected @skip_py38 @skip_py39 @skip_py310 @skip_py312 @skip_py313 @skip_py314 def test_inspect_integer_with_methods_python311(): # to_bytes and from_bytes methods on int had minor signature change - # they now, as of 3.11, have default values for all of their parameters expected = ( "╭──────────────── <class 'int'> ─────────────────╮\n" "│ int([x]) -> integer │\n" "│ int(x, base=10) -> integer │\n" "│ │\n" "│ denominator = 1 │\n" "│ imag = 0 │\n" "│ numerator = 1 │\n" "│ real = 1 │\n" "│ as_integer_ratio = def as_integer_ratio(): │\n" "│ Return integer ratio. │\n" "│ bit_count = def bit_count(): Number of │\n" "│ ones in the binary │\n" "│ representation of the │\n" "│ absolute value of self. │\n" "│ bit_length = def bit_length(): Number of │\n" "│ bits necessary to represent │\n" "│ self in binary. │\n" "│ conjugate = def conjugate(...) Returns │\n" "│ self, the complex conjugate │\n" "│ of any int. │\n" "│ from_bytes = def from_bytes(bytes, │\n" "│ byteorder='big', *, │\n" "│ signed=False): Return the │\n" "│ integer represented by the │\n" "│ given array of bytes. │\n" "│ to_bytes = def to_bytes(length=1, │\n" "│ byteorder='big', *, │\n" "│ signed=False): Return an │\n" "│ array of bytes representing │\n" "│ an integer. │\n" "╰────────────────────────────────────────────────╯\n" ) assert render(1, methods=True) == expected @skip_pypy3 def test_broken_call_attr(): class NotCallable: __call__ = 5 # Passes callable() but isn't really callable def __repr__(self): return "NotCallable()" class Foo: foo = NotCallable() foo = Foo() assert callable(foo.foo) expected = "╭─ <class 'tests.test_inspect.test_broken_call_attr.<locals>.Foo'> ─╮\n│ foo = NotCallable() │\n╰───────────────────────────────────────────────────────────────────╯\n" result = render(foo, methods=True, width=100) print(repr(result)) assert expected == result def test_inspect_swig_edge_case(): """Issue #1838 - Edge case with Faiss library - object with empty dir()""" class Thing: @property def __class__(self): raise AttributeError thing = Thing() try: inspect(thing) except Exception as e: assert False, f"Object with no __class__ shouldn't raise {e}" def test_inspect_module_with_class(): def function(): pass class Thing: """Docstring""" pass module = ModuleType("my_module") module.SomeClass = Thing module.function = function expected = ( "╭────────── <module 'my_module'> ──────────╮\n" "│ function = def function(): │\n" "│ SomeClass = class SomeClass(): Docstring │\n" "╰──────────────────────────────────────────╯\n" ) assert render(module, methods=True) == expected @pytest.mark.parametrize( "special_character,expected_replacement", ( ("\a", "\\a"), ("\b", "\\b"), ("\f", "\\f"), ("\r", "\\r"), ("\v", "\\v"), ), ) def test_can_handle_special_characters_in_docstrings( special_character: str, expected_replacement: str ) -> None: class Something: class Thing: pass Something.Thing.__doc__ = f""" Multiline docstring with {special_character} should be handled """ expected = """\ ╭─ <class 'tests.test_inspect.test_can_handle_sp─╮ │ class │ │ test_can_handle_special_characters_in_docstrin │ │ gs.<locals>.Something(): │ │ │ │ Thing = class Thing(): │ │ Multiline docstring │ │ with %s should be handled │ ╰────────────────────────────────────────────────╯ """ % ( expected_replacement ) assert render(Something, methods=True) == expected @pytest.mark.parametrize( "obj,expected_result", ( [object, (object,)], [object(), (object,)], ["hi", (str, object)], [str, (str, object)], [Foo(1), (Foo, object)], [Foo, (Foo, object)], [FooSubclass(1), (FooSubclass, Foo, object)], [FooSubclass, (FooSubclass, Foo, object)], ), ) def test_object_types_mro(obj: object, expected_result: Sequence[Type]): assert get_object_types_mro(obj) == expected_result @pytest.mark.parametrize( "obj,expected_result", ( # fmt: off ["hi", ["builtins.str", "builtins.object"]], [str, ["builtins.str", "builtins.object"]], [Foo(1), [f"{__name__}.Foo", "builtins.object"]], [Foo, [f"{__name__}.Foo", "builtins.object"]], [FooSubclass(1), [f"{__name__}.FooSubclass", f"{__name__}.Foo", "builtins.object"]], [FooSubclass, [f"{__name__}.FooSubclass", f"{__name__}.Foo", "builtins.object"]], # fmt: on ), ) def test_object_types_mro_as_strings(obj: object, expected_result: Sequence[str]): assert get_object_types_mro_as_strings(obj) == expected_result @pytest.mark.parametrize( "obj,types,expected_result", ( # fmt: off ["hi", ["builtins.str"], True], [str, ["builtins.str"], True], ["hi", ["builtins.str", "foo"], True], [str, ["builtins.str", "foo"], True], [Foo(1), [f"{__name__}.Foo"], True], [Foo, [f"{__name__}.Foo"], True], [Foo(1), ["builtins.str", f"{__name__}.Foo"], True], [Foo, ["builtins.int", f"{__name__}.Foo"], True], [Foo(1), [f"{__name__}.FooSubclass"], False], [Foo, [f"{__name__}.FooSubclass"], False], [Foo(1), [f"{__name__}.FooSubclass", f"{__name__}.Foo"], True], [Foo, [f"{__name__}.Foo", f"{__name__}.FooSubclass"], True], # fmt: on ), ) def test_object_is_one_of_types( obj: object, types: Sequence[str], expected_result: bool ): assert is_object_one_of_types(obj, types) is expected_result
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_measure.py
tests/test_measure.py
from rich.text import Text import pytest from rich.errors import NotRenderableError from rich.console import Console from rich.measure import Measurement, measure_renderables def test_span(): measurement = Measurement(10, 100) assert measurement.span == 90 def test_no_renderable(): console = Console() text = Text() with pytest.raises(NotRenderableError): Measurement.get(console, console.options, None) def test_measure_renderables(): console = Console() assert measure_renderables(console, console.options, "") == Measurement(0, 0) assert measure_renderables( console, console.options.update_width(0), "hello" ) == Measurement(0, 0) def test_clamp(): measurement = Measurement(20, 100) assert measurement.clamp(10, 50) == Measurement(20, 50) assert measurement.clamp(30, 50) == Measurement(30, 50) assert measurement.clamp(None, 50) == Measurement(20, 50) assert measurement.clamp(30, None) == Measurement(30, 100) assert measurement.clamp(None, None) == Measurement(20, 100)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_markup.py
tests/test_markup.py
import pytest from rich.console import Console from rich.errors import MarkupError from rich.markup import RE_TAGS, Tag, _parse, escape, render from rich.text import Span, Text def test_re_no_match(): assert RE_TAGS.match("[True]") == None assert RE_TAGS.match("[False]") == None assert RE_TAGS.match("[None]") == None assert RE_TAGS.match("[1]") == None assert RE_TAGS.match("[2]") == None assert RE_TAGS.match("[]") == None def test_re_match(): assert RE_TAGS.match("[true]") assert RE_TAGS.match("[false]") assert RE_TAGS.match("[none]") assert RE_TAGS.match("[color(1)]") assert RE_TAGS.match("[#ff00ff]") assert RE_TAGS.match("[/]") assert RE_TAGS.match("[@]") assert RE_TAGS.match("[@foo]") assert RE_TAGS.match("[@foo=bar]") def test_escape(): # Potential tags assert escape("foo[bar]") == r"foo\[bar]" assert escape(r"foo\[bar]") == r"foo\\\[bar]" # Not tags (escape not required) assert escape("[5]") == "[5]" assert escape("\\[5]") == "\\[5]" # Test @ escape assert escape("[@foo]") == "\\[@foo]" assert escape("[@]") == "\\[@]" # https://github.com/Textualize/rich/issues/2187 assert escape("[nil, [nil]]") == r"[nil, \[nil]]" def test_escape_backslash_end(): # https://github.com/Textualize/rich/issues/2987 value = "C:\\" assert escape(value) == "C:\\\\" escaped_tags = f"[red]{escape(value)}[/red]" assert escaped_tags == "[red]C:\\\\[/red]" escaped_text = Text.from_markup(escaped_tags) assert escaped_text.plain == "C:\\" assert escaped_text.spans == [Span(0, 3, "red")] def test_render_escape(): console = Console(width=80, color_system=None) console.begin_capture() console.print( escape(r"[red]"), escape(r"\[red]"), escape(r"\\[red]"), escape(r"\\\[red]") ) result = console.end_capture() expected = r"[red] \[red] \\[red] \\\[red]" + "\n" assert result == expected def test_parse(): result = list(_parse(r"[foo]hello[/foo][bar]world[/]\[escaped]")) expected = [ (0, None, Tag(name="foo", parameters=None)), (10, "hello", None), (10, None, Tag(name="/foo", parameters=None)), (16, None, Tag(name="bar", parameters=None)), (26, "world", None), (26, None, Tag(name="/", parameters=None)), (29, "[escaped]", None), ] print(repr(result)) assert result == expected def test_parse_link(): result = list(_parse("[link=foo]bar[/link]")) expected = [ (0, None, Tag(name="link", parameters="foo")), (13, "bar", None), (13, None, Tag(name="/link", parameters=None)), ] assert result == expected def test_render(): result = render("[bold]FOO[/bold]") assert str(result) == "FOO" assert result.spans == [Span(0, 3, "bold")] def test_render_not_tags(): result = render('[[1], [1,2,3,4], ["hello"], [None], [False], [True]] []') assert str(result) == '[[1], [1,2,3,4], ["hello"], [None], [False], [True]] []' assert result.spans == [] def test_render_link(): result = render("[link=foo]FOO[/link]") assert str(result) == "FOO" assert result.spans == [Span(0, 3, "link foo")] def test_render_combine(): result = render("[green]X[blue]Y[/blue]Z[/green]") assert str(result) == "XYZ" assert result.spans == [ Span(0, 3, "green"), Span(1, 2, "blue"), ] def test_render_overlap(): result = render("[green]X[bold]Y[/green]Z[/bold]") assert str(result) == "XYZ" assert result.spans == [ Span(0, 2, "green"), Span(1, 3, "bold"), ] def test_adjoint(): result = render("[red][blue]B[/blue]R[/red]") print(repr(result)) assert result.spans == [Span(0, 2, "red"), Span(0, 1, "blue")] def test_render_close(): result = render("[bold]X[/]Y") assert str(result) == "XY" assert result.spans == [Span(0, 1, "bold")] def test_render_close_ambiguous(): result = render("[green]X[bold]Y[/]Z[/]") assert str(result) == "XYZ" assert result.spans == [Span(0, 3, "green"), Span(1, 2, "bold")] def test_markup_error(): with pytest.raises(MarkupError): assert render("foo[/]") with pytest.raises(MarkupError): assert render("foo[/bar]") with pytest.raises(MarkupError): assert render("[foo]hello[/bar]") def test_markup_escape(): result = str(render("[dim white][url=[/]")) assert result == "[url=" def test_escape_escape(): # Escaped escapes (i.e. double backslash)should be treated as literal result = render(r"\\[bold]FOO") assert str(result) == r"\FOO" # Single backslash makes the tag literal result = render(r"\[bold]FOO") assert str(result) == "[bold]FOO" # Double backslash produces a backslash result = render(r"\\[bold]some text[/]") assert str(result) == r"\some text" # Triple backslash parsed as literal backslash plus escaped tag result = render(r"\\\[bold]some text\[/]") assert str(result) == r"\[bold]some text[/]" # Backslash escaping only happens when preceding a tag result = render(r"\\") assert str(result) == r"\\" result = render(r"\\\\") assert str(result) == r"\\\\" def test_events(): result = render("[@click]Hello[/@click] [@click='view.toggle', 'left']World[/]") assert str(result) == "Hello World" def test_events_broken(): with pytest.raises(MarkupError): render("[@click=sdfwer(sfs)]foo[/]") with pytest.raises(MarkupError): render("[@click='view.toggle]foo[/]") def test_render_meta(): console = Console() text = render("foo[@click=close]bar[/]baz") assert text.get_style_at_offset(console, 3).meta == {"@click": ("close", ())} text = render("foo[@click=close()]bar[/]baz") assert text.get_style_at_offset(console, 3).meta == {"@click": ("close", ())} text = render("foo[@click=close('dialog')]bar[/]baz") assert text.get_style_at_offset(console, 3).meta == { "@click": ("close", ("dialog",)) } text = render("foo[@click=close('dialog', 3)]bar[/]baz") assert text.get_style_at_offset(console, 3).meta == { "@click": ("close", ("dialog", 3)) } text = render("foo[@click=(1, 2, 3)]bar[/]baz") assert text.get_style_at_offset(console, 3).meta == {"@click": (1, 2, 3)}
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_spinner.py
tests/test_spinner.py
import pytest from rich.console import Console from rich.measure import Measurement from rich.rule import Rule from rich.spinner import Spinner from rich.text import Text def test_spinner_create(): Spinner("dots") with pytest.raises(KeyError): Spinner("foobar") def test_spinner_render(): time = 0.0 def get_time(): nonlocal time return time console = Console( width=80, color_system=None, force_terminal=True, get_time=get_time ) console.begin_capture() spinner = Spinner("dots", "Foo") console.print(spinner) time += 80 / 1000 console.print(spinner) result = console.end_capture() print(repr(result)) expected = "⠋ Foo\n⠙ Foo\n" assert result == expected def test_spinner_update(): time = 0.0 def get_time(): nonlocal time return time console = Console(width=20, force_terminal=True, get_time=get_time, _environ={}) console.begin_capture() spinner = Spinner("dots") console.print(spinner) rule = Rule("Bar") spinner.update(text=rule) time += 80 / 1000 console.print(spinner) result = console.end_capture() print(repr(result)) expected = "⠋\n⠙ \x1b[92m─\x1b[0m\n" assert result == expected def test_rich_measure(): console = Console(width=80, color_system=None, force_terminal=True) spinner = Spinner("dots", "Foo") min_width, max_width = Measurement.get(console, console.options, spinner) assert min_width == 3 assert max_width == 5 def test_spinner_markup(): spinner = Spinner("dots", "[bold]spinning[/bold]") assert isinstance(spinner.text, Text) assert str(spinner.text) == "spinning"
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_style.py
tests/test_style.py
import pytest from rich import errors from rich.color import Color, ColorSystem, ColorType from rich.style import Style, StyleStack def test_str(): assert str(Style(bold=False)) == "not bold" assert str(Style(color="red", bold=False)) == "not bold red" assert str(Style(color="red", bold=False, italic=True)) == "not bold italic red" assert str(Style()) == "none" assert str(Style(bold=True)) == "bold" assert str(Style(color="red", bold=True)) == "bold red" assert str(Style(color="red", bgcolor="black", bold=True)) == "bold red on black" all_styles = Style( color="red", bgcolor="black", bold=True, dim=True, italic=True, underline=True, blink=True, blink2=True, reverse=True, conceal=True, strike=True, underline2=True, frame=True, encircle=True, overline=True, ) expected = "bold dim italic underline blink blink2 reverse conceal strike underline2 frame encircle overline red on black" assert str(all_styles) == expected assert str(Style(link="foo")) == "link foo" def test_ansi_codes(): all_styles = Style( color="red", bgcolor="black", bold=True, dim=True, italic=True, underline=True, blink=True, blink2=True, reverse=True, conceal=True, strike=True, underline2=True, frame=True, encircle=True, overline=True, ) expected = "1;2;3;4;5;6;7;8;9;21;51;52;53;31;40" assert all_styles._make_ansi_codes(ColorSystem.TRUECOLOR) == expected def test_repr(): assert ( repr(Style(bold=True, color="red")) == "Style(color=Color('red', ColorType.STANDARD, number=1), bold=True)" ) def test_eq(): assert Style(bold=True, color="red") == Style(bold=True, color="red") assert Style(bold=True, color="red") != Style(bold=True, color="green") assert Style().__eq__("foo") == NotImplemented def test_hash(): assert isinstance(hash(Style()), int) def test_empty(): assert Style.null() == Style() def test_bool(): assert bool(Style()) is False assert bool(Style(bold=True)) is True assert bool(Style(color="red")) is True assert bool(Style.parse("")) is False def test_color_property(): assert Style(color="red").color == Color("red", ColorType.STANDARD, 1, None) def test_bgcolor_property(): assert Style(bgcolor="black").bgcolor == Color("black", ColorType.STANDARD, 0, None) def test_parse(): assert Style.parse("") == Style() assert Style.parse("red") == Style(color="red") assert Style.parse("not bold") == Style(bold=False) assert Style.parse("bold red on black") == Style( color="red", bgcolor="black", bold=True ) assert Style.parse("bold link https://example.org") == Style( bold=True, link="https://example.org" ) with pytest.raises(errors.StyleSyntaxError): Style.parse("on") with pytest.raises(errors.StyleSyntaxError): Style.parse("on nothing") with pytest.raises(errors.StyleSyntaxError): Style.parse("rgb(999,999,999)") with pytest.raises(errors.StyleSyntaxError): Style.parse("not monkey") with pytest.raises(errors.StyleSyntaxError): Style.parse("link") def test_link_id(): assert Style().link_id == "" assert Style.parse("").link_id == "" assert Style.parse("red").link_id == "" style = Style.parse("red link https://example.org") assert isinstance(style.link_id, str) assert len(style.link_id) > 1 def test_get_html_style(): expected = "color: #7f7fbf; text-decoration-color: #7f7fbf; background-color: #800000; font-weight: bold; font-style: italic; text-decoration: underline; text-decoration: line-through; text-decoration: overline" html_style = Style( reverse=True, dim=True, color="red", bgcolor="blue", bold=True, italic=True, underline=True, strike=True, overline=True, ).get_html_style() print(repr(html_style)) assert html_style == expected def test_chain(): assert Style.chain(Style(color="red"), Style(bold=True)) == Style( color="red", bold=True ) def test_copy(): style = Style(color="red", bgcolor="black", italic=True) assert style == style.copy() assert style is not style.copy() def test_render(): assert Style(color="red").render("foo", color_system=None) == "foo" assert ( Style(color="red", bgcolor="black", bold=True).render("foo") == "\x1b[1;31;40mfoo\x1b[0m" ) assert Style().render("foo") == "foo" def test_test(): Style(color="red").test("hello") def test_add(): assert Style(color="red") + None == Style(color="red") def test_iadd(): style = Style(color="red") style += Style(bold=True) assert style == Style(color="red", bold=True) style += None assert style == Style(color="red", bold=True) def test_style_stack(): stack = StyleStack(Style(color="red")) repr(stack) assert stack.current == Style(color="red") stack.push(Style(bold=True)) assert stack.current == Style(color="red", bold=True) stack.pop() assert stack.current == Style(color="red") def test_pick_first(): with pytest.raises(ValueError): Style.pick_first() def test_background_style(): assert Style(bold=True, color="yellow", bgcolor="red").background_style == Style( bgcolor="red" ) def test_without_color(): style = Style(bold=True, color="red", bgcolor="blue") colorless_style = style.without_color assert colorless_style.color == None assert colorless_style.bgcolor == None assert colorless_style.bold == True null_style = Style.null() assert null_style.without_color == null_style def test_meta(): style = Style(bold=True, meta={"foo": "bar"}) assert style.meta["foo"] == "bar" style += Style(meta={"egg": "baz"}) assert style.meta == {"foo": "bar", "egg": "baz"} assert repr(style) == "Style(bold=True, meta={'foo': 'bar', 'egg': 'baz'})" def test_from_meta(): style = Style.from_meta({"foo": "bar"}) assert style.color is None assert style.bold is None def test_on(): style = Style.on({"foo": "bar"}, click="CLICK") + Style(color="red") assert style.meta == {"foo": "bar", "@click": "CLICK"} def test_clear_meta_and_links(): style = Style.parse("bold red on black link https://example.org") + Style.on( click="CLICK" ) assert style.meta == {"@click": "CLICK"} assert style.link == "https://example.org" assert style.color == Color.parse("red") assert style.bgcolor == Color.parse("black") assert style.bold assert not style.italic clear_style = style.clear_meta_and_links() assert clear_style.meta == {} assert clear_style.link == None assert clear_style.color == Color.parse("red") assert clear_style.bgcolor == Color.parse("black") assert clear_style.bold assert not clear_style.italic def test_clear_meta_and_links_clears_hash(): """Regression test for https://github.com/Textualize/rich/issues/2942.""" style = Style.parse("bold red on black link https://example.org") + Style.on( click="CLICK" ) hash(style) # Force hash caching. assert style._hash is not None clear_style = style.clear_meta_and_links() assert clear_style._hash is None
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_tree.py
tests/test_tree.py
import sys import pytest from rich.console import Console from rich.measure import Measurement from rich.tree import Tree def test_render_single_node(): tree = Tree("foo") console = Console(color_system=None, width=20) console.begin_capture() console.print(tree) assert console.end_capture() == "foo\n" def test_render_single_branch(): tree = Tree("foo") tree.add("bar") console = Console(color_system=None, width=20) console.begin_capture() console.print(tree) result = console.end_capture() print(repr(result)) expected = "foo\n└── bar\n" assert result == expected def test_render_double_branch(): tree = Tree("foo") tree.add("bar") tree.add("baz") console = Console(color_system=None, width=20) console.begin_capture() console.print(tree) result = console.end_capture() print(repr(result)) expected = "foo\n├── bar\n└── baz\n" assert result == expected def test_render_ascii(): tree = Tree("foo") tree.add("bar") tree.add("baz") class AsciiConsole(Console): @property def encoding(self): return "ascii" console = AsciiConsole(color_system=None, width=20) console.begin_capture() console.print(tree) result = console.end_capture() expected = "foo\n+-- bar\n`-- baz\n" assert result == expected @pytest.mark.skipif(sys.platform == "win32", reason="different on Windows") def test_render_tree_non_win32(): tree = Tree("foo") tree.add("bar", style="italic") baz_tree = tree.add("baz", guide_style="bold red", style="on blue") baz_tree.add("1") baz_tree.add("2") tree.add("egg") console = Console( width=20, force_terminal=True, color_system="standard", _environ={} ) console.begin_capture() console.print(tree) result = console.end_capture() print(repr(result)) expected = "foo\n├── \x1b[3mbar\x1b[0m\n\x1b[44m├── \x1b[0m\x1b[44mbaz\x1b[0m\n\x1b[44m│ \x1b[0m\x1b[31;44m┣━━ \x1b[0m\x1b[44m1\x1b[0m\n\x1b[44m│ \x1b[0m\x1b[31;44m┗━━ \x1b[0m\x1b[44m2\x1b[0m\n└── egg\n" assert result == expected @pytest.mark.skipif(sys.platform != "win32", reason="Windows specific") def test_render_tree_win32(): tree = Tree("foo") tree.add("bar", style="italic") baz_tree = tree.add("baz", guide_style="bold red", style="on blue") baz_tree.add("1") baz_tree.add("2") tree.add("egg") console = Console( width=20, force_terminal=True, color_system="standard", legacy_windows=True ) console.begin_capture() console.print(tree) result = console.end_capture() print(repr(result)) expected = "foo\n├── \x1b[3mbar\x1b[0m\n\x1b[44m├── \x1b[0m\x1b[44mbaz\x1b[0m\n\x1b[44m│ \x1b[0m\x1b[31;44m├── \x1b[0m\x1b[44m1\x1b[0m\n\x1b[44m│ \x1b[0m\x1b[31;44m└── \x1b[0m\x1b[44m2\x1b[0m\n└── egg\n" assert result == expected @pytest.mark.skipif(sys.platform == "win32", reason="different on Windows") def test_render_tree_hide_root_non_win32(): tree = Tree("foo", hide_root=True) tree.add("bar", style="italic") baz_tree = tree.add("baz", guide_style="bold red", style="on blue") baz_tree.add("1") baz_tree.add("2") tree.add("egg") console = Console( width=20, force_terminal=True, color_system="standard", _environ={} ) console.begin_capture() console.print(tree) result = console.end_capture() print(repr(result)) expected = "\x1b[3mbar\x1b[0m\n\x1b[44mbaz\x1b[0m\n\x1b[31;44m┣━━ \x1b[0m\x1b[44m1\x1b[0m\n\x1b[31;44m┗━━ \x1b[0m\x1b[44m2\x1b[0m\negg\n" assert result == expected @pytest.mark.skipif(sys.platform != "win32", reason="Windows specific") def test_render_tree_hide_root_win32(): tree = Tree("foo", hide_root=True) tree.add("bar", style="italic") baz_tree = tree.add("baz", guide_style="bold red", style="on blue") baz_tree.add("1") baz_tree.add("2") tree.add("egg") console = Console(width=20, force_terminal=True, color_system="standard") console.begin_capture() console.print(tree) result = console.end_capture() print(repr(result)) expected = "\x1b[3mbar\x1b[0m\n\x1b[44mbaz\x1b[0m\n\x1b[31;44m├── \x1b[0m\x1b[44m1\x1b[0m\n\x1b[31;44m└── \x1b[0m\x1b[44m2\x1b[0m\negg\n" assert result == expected def test_tree_measure(): tree = Tree("foo") tree.add("bar") tree.add("mushroom risotto") console = Console() measurement = Measurement.get(console, console.options, tree) assert measurement == Measurement(12, 20)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_cells.py
tests/test_cells.py
import string from rich import cells from rich.cells import _is_single_cell_widths, chop_cells def test_cell_len_long_string(): # Long strings don't use cached cell length implementation assert cells.cell_len("abc" * 200) == 3 * 200 # Boundary case assert cells.cell_len("a" * 512) == 512 def test_cell_len_short_string(): # Short strings use cached cell length implementation assert cells.cell_len("abc" * 100) == 3 * 100 # Boundary case assert cells.cell_len("a" * 511) == 511 def test_set_cell_size(): assert cells.set_cell_size("foo", 0) == "" assert cells.set_cell_size("f", 0) == "" assert cells.set_cell_size("", 0) == "" assert cells.set_cell_size("😽😽", 0) == "" assert cells.set_cell_size("foo", 2) == "fo" assert cells.set_cell_size("foo", 3) == "foo" assert cells.set_cell_size("foo", 4) == "foo " assert cells.set_cell_size("😽😽", 4) == "😽😽" assert cells.set_cell_size("😽😽", 3) == "😽 " assert cells.set_cell_size("😽😽", 2) == "😽" assert cells.set_cell_size("😽😽", 1) == " " assert cells.set_cell_size("😽😽", 5) == "😽😽 " def test_set_cell_size_infinite(): for size in range(38): assert ( cells.cell_len( cells.set_cell_size( "เป็นเกมที่ต้องมีความอดทนมากที่สุดตั้งเเต่เคยเล่นมา", size ) ) == size ) def test_chop_cells(): """Simple example of splitting cells into lines of width 3.""" text = "abcdefghijk" assert chop_cells(text, 3) == ["abc", "def", "ghi", "jk"] def test_chop_cells_double_width_boundary(): """The available width lies within a double-width character.""" text = "ありがとう" assert chop_cells(text, 3) == ["あ", "り", "が", "と", "う"] def test_chop_cells_mixed_width(): """Mixed single and double-width characters.""" text = "あ1り234が5と6う78" assert chop_cells(text, 3) == ["あ1", "り2", "34", "が5", "と6", "う7", "8"] def test_is_single_cell_widths() -> None: # Check _is_single_cell_widths reports correctly for character in string.printable: if ord(character) >= 32: assert _is_single_cell_widths(character) BOX = "┌─┬┐│ ││├─┼┤│ ││├─┼┤├─┼┤│ ││└─┴┘" for character in BOX: assert _is_single_cell_widths(character) for character in "💩😽": assert not _is_single_cell_widths(character) for character in "わさび": assert not _is_single_cell_widths(character)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_containers.py
tests/test_containers.py
from rich.console import Console from rich.containers import Lines, Renderables from rich.text import Span, Text from rich.style import Style def test_renderables_measure(): console = Console() text = Text("foo") renderables = Renderables([text]) result = renderables.__rich_measure__(console, console.options) _min, _max = result assert _min == 3 assert _max == 3 assert list(renderables) == [text] def test_renderables_empty(): console = Console() renderables = Renderables() result = renderables.__rich_measure__(console, console.options) _min, _max = result assert _min == 1 assert _max == 1 def test_lines_rich_console(): console = Console() lines = Lines([Text("foo")]) result = list(lines.__rich_console__(console, console.options)) assert result == [Text("foo")] def test_lines_justify(): console = Console() lines1 = Lines([Text("foo", style="b"), Text("test", style="b")]) lines1.justify(console, 10, justify="left") assert lines1._lines == [Text("foo "), Text("test ")] lines1.justify(console, 10, justify="center") assert lines1._lines == [Text(" foo "), Text(" test ")] lines1.justify(console, 10, justify="right") assert lines1._lines == [Text(" foo"), Text(" test")] lines2 = Lines([Text("foo bar", style="b"), Text("test", style="b")]) lines2.justify(console, 7, justify="full") print(repr(lines2._lines[0].spans)) assert lines2._lines == [ Text( "foo bar", spans=[Span(0, 3, "b"), Span(3, 4, Style.parse("bold")), Span(4, 7, "b")], ), Text("test"), ]
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_constrain.py
tests/test_constrain.py
from rich.console import Console from rich.constrain import Constrain from rich.text import Text def test_width_of_none(): console = Console() constrain = Constrain(Text("foo"), width=None) min_width, max_width = constrain.__rich_measure__( console, console.options.update_width(80) ) assert min_width == 3 assert max_width == 3
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_prompt.py
tests/test_prompt.py
import io from rich.console import Console from rich.prompt import Confirm, IntPrompt, Prompt def test_prompt_str(): INPUT = "egg\nfoo" console = Console(file=io.StringIO()) name = Prompt.ask( "what is your name", console=console, choices=["foo", "bar"], default="baz", stream=io.StringIO(INPUT), ) assert name == "foo" expected = "what is your name [foo/bar] (baz): Please select one of the available options\nwhat is your name [foo/bar] (baz): " output = console.file.getvalue() print(repr(output)) assert output == expected def test_prompt_str_case_insensitive(): INPUT = "egg\nFoO" console = Console(file=io.StringIO()) name = Prompt.ask( "what is your name", console=console, choices=["foo", "bar"], default="baz", case_sensitive=False, stream=io.StringIO(INPUT), ) assert name == "foo" expected = "what is your name [foo/bar] (baz): Please select one of the available options\nwhat is your name [foo/bar] (baz): " output = console.file.getvalue() print(repr(output)) assert output == expected def test_prompt_str_default(): INPUT = "" console = Console(file=io.StringIO()) name = Prompt.ask( "what is your name", console=console, default="Will", stream=io.StringIO(INPUT), ) assert name == "Will" expected = "what is your name (Will): " output = console.file.getvalue() print(repr(output)) assert output == expected def test_prompt_int(): INPUT = "foo\n100" console = Console(file=io.StringIO()) number = IntPrompt.ask( "Enter a number", console=console, stream=io.StringIO(INPUT), ) assert number == 100 expected = "Enter a number: Please enter a valid integer number\nEnter a number: " output = console.file.getvalue() print(repr(output)) assert output == expected def test_prompt_confirm_no(): INPUT = "foo\nNO\nn" console = Console(file=io.StringIO()) answer = Confirm.ask( "continue", console=console, stream=io.StringIO(INPUT), ) assert answer is False expected = "continue [y/n]: Please enter Y or N\ncontinue [y/n]: Please enter Y or N\ncontinue [y/n]: " output = console.file.getvalue() print(repr(output)) assert output == expected def test_prompt_confirm_yes(): INPUT = "foo\nNO\ny" console = Console(file=io.StringIO()) answer = Confirm.ask( "continue", console=console, stream=io.StringIO(INPUT), ) assert answer is True expected = "continue [y/n]: Please enter Y or N\ncontinue [y/n]: Please enter Y or N\ncontinue [y/n]: " output = console.file.getvalue() print(repr(output)) assert output == expected def test_prompt_confirm_default(): INPUT = "foo\nNO\ny" console = Console(file=io.StringIO()) answer = Confirm.ask( "continue", console=console, stream=io.StringIO(INPUT), default=True ) assert answer is True expected = "continue [y/n] (y): Please enter Y or N\ncontinue [y/n] (y): Please enter Y or N\ncontinue [y/n] (y): " output = console.file.getvalue() print(repr(output)) assert output == expected
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_rule_in_table.py
tests/test_rule_in_table.py
import io from textwrap import dedent import pytest from rich import box from rich.console import Console from rich.rule import Rule from rich.table import Table @pytest.mark.parametrize("expand_kwarg", ({}, {"expand": False})) def test_rule_in_unexpanded_table(expand_kwarg): console = Console(width=32, file=io.StringIO(), legacy_windows=False, _environ={}) table = Table(box=box.ASCII, show_header=False, **expand_kwarg) table.add_column() table.add_column() table.add_row("COL1", "COL2") table.add_row("COL1", Rule()) table.add_row("COL1", "COL2") console.print(table) expected = dedent( """\ +-------------+ | COL1 | COL2 | | COL1 | ──── | | COL1 | COL2 | +-------------+ """ ) result = console.file.getvalue() assert result == expected def test_rule_in_expanded_table(): console = Console(width=32, file=io.StringIO(), legacy_windows=False, _environ={}) table = Table(box=box.ASCII, expand=True, show_header=False) table.add_column() table.add_column() table.add_row("COL1", "COL2") table.add_row("COL1", Rule(style=None)) table.add_row("COL1", "COL2") console.print(table) expected = dedent( """\ +------------------------------+ | COL1 | COL2 | | COL1 | ──────────── | | COL1 | COL2 | +------------------------------+ """ ) result = console.file.getvalue() assert result == expected def test_rule_in_ratio_table(): console = Console(width=32, file=io.StringIO(), legacy_windows=False, _environ={}) table = Table(box=box.ASCII, expand=True, show_header=False) table.add_column(ratio=1) table.add_column() table.add_row("COL1", "COL2") table.add_row("COL1", Rule(style=None)) table.add_row("COL1", "COL2") console.print(table) expected = dedent( """\ +------------------------------+ | COL1 | COL2 | | COL1 | ──── | | COL1 | COL2 | +------------------------------+ """ ) result = console.file.getvalue() assert result == expected
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_live_render.py
tests/test_live_render.py
import pytest from rich.live_render import LiveRender from rich.console import Console, ConsoleDimensions, ConsoleOptions from rich.style import Style from rich.segment import Segment @pytest.fixture def live_render(): return LiveRender(renderable="my string") def test_renderable(live_render): assert live_render.renderable == "my string" live_render.set_renderable("another string") assert live_render.renderable == "another string" def test_position_cursor(live_render): assert str(live_render.position_cursor()) == "" live_render._shape = (80, 2) assert str(live_render.position_cursor()) == "\r\x1b[2K\x1b[1A\x1b[2K" def test_restore_cursor(live_render): assert str(live_render.restore_cursor()) == "" live_render._shape = (80, 2) assert str(live_render.restore_cursor()) == "\r\x1b[1A\x1b[2K\x1b[1A\x1b[2K" def test_rich_console(live_render): options = ConsoleOptions( ConsoleDimensions(80, 25), max_height=25, legacy_windows=False, min_width=10, max_width=20, is_terminal=False, encoding="utf-8", ) rich_console = live_render.__rich_console__(Console(), options) assert [Segment("my string", None)] == list(rich_console) live_render.style = "red" rich_console = live_render.__rich_console__(Console(), options) assert [Segment("my string", Style.parse("red"))] == list(rich_console)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_columns.py
tests/test_columns.py
# encoding=utf-8 import io from rich.columns import Columns from rich.console import Console COLUMN_DATA = [ "Ursus americanus", "American buffalo", "Bison bison", "American crow", "Corvus brachyrhynchos", "American marten", "Martes americana", "American racer", "Coluber constrictor", "American woodcock", "Scolopax minor", "Anaconda (unidentified)", "Eunectes sp.", "Andean goose", "Chloephaga melanoptera", "Ant", "Anteater, australian spiny", "Tachyglossus aculeatus", "Anteater, giant", ] def render(): console = Console(file=io.StringIO(), width=100, legacy_windows=False) console.rule("empty") empty_columns = Columns([]) console.print(empty_columns) columns = Columns(COLUMN_DATA) columns.add_renderable("Myrmecophaga tridactyla") console.rule("optimal") console.print(columns) console.rule("optimal, expand") columns.expand = True console.print(columns) console.rule("column first, optimal") columns.column_first = True columns.expand = False console.print(columns) console.rule("column first, right to left") columns.right_to_left = True console.print(columns) console.rule("equal columns, expand") columns.equal = True columns.expand = True console.print(columns) console.rule("fixed width") columns.width = 16 columns.expand = False console.print(columns) console.print() render_result = console.file.getvalue() return render_result def test_render(): expected = "────────────────────────────────────────────── empty ───────────────────────────────────────────────\n───────────────────────────────────────────── optimal ──────────────────────────────────────────────\nUrsus americanus American buffalo Bison bison American crow \nCorvus brachyrhynchos American marten Martes americana American racer \nColuber constrictor American woodcock Scolopax minor Anaconda (unidentified)\nEunectes sp. Andean goose Chloephaga melanoptera Ant \nAnteater, australian spiny Tachyglossus aculeatus Anteater, giant Myrmecophaga tridactyla\n───────────────────────────────────────── optimal, expand ──────────────────────────────────────────\nUrsus americanus American buffalo Bison bison American crow \nCorvus brachyrhynchos American marten Martes americana American racer \nColuber constrictor American woodcock Scolopax minor Anaconda (unidentified)\nEunectes sp. Andean goose Chloephaga melanoptera Ant \nAnteater, australian spiny Tachyglossus aculeatus Anteater, giant Myrmecophaga tridactyla\n────────────────────────────────────── column first, optimal ───────────────────────────────────────\nUrsus americanus American marten Scolopax minor Ant \nAmerican buffalo Martes americana Anaconda (unidentified) Anteater, australian spiny\nBison bison American racer Eunectes sp. Tachyglossus aculeatus \nAmerican crow Coluber constrictor Andean goose Anteater, giant \nCorvus brachyrhynchos American woodcock Chloephaga melanoptera Myrmecophaga tridactyla \n─────────────────────────────────── column first, right to left ────────────────────────────────────\nAnt Scolopax minor American marten Ursus americanus \nAnteater, australian spiny Anaconda (unidentified) Martes americana American buffalo \nTachyglossus aculeatus Eunectes sp. American racer Bison bison \nAnteater, giant Andean goose Coluber constrictor American crow \nMyrmecophaga tridactyla Chloephaga melanoptera American woodcock Corvus brachyrhynchos\n────────────────────────────────────── equal columns, expand ───────────────────────────────────────\nChloephaga melanoptera American racer Ursus americanus \nAnt Coluber constrictor American buffalo \nAnteater, australian spiny American woodcock Bison bison \nTachyglossus aculeatus Scolopax minor American crow \nAnteater, giant Anaconda (unidentified) Corvus brachyrhynchos \nMyrmecophaga tridactyla Eunectes sp. American marten \n Andean goose Martes americana \n─────────────────────────────────────────── fixed width ────────────────────────────────────────────\nAnteater, Eunectes sp. Coluber Corvus Ursus americanus \naustralian spiny constrictor brachyrhynchos \nTachyglossus Andean goose American American marten American buffalo \naculeatus woodcock \nAnteater, giant Chloephaga Scolopax minor Martes americana Bison bison \n melanoptera \nMyrmecophaga Ant Anaconda American racer American crow \ntridactyla (unidentified) \n\n" assert render() == expected if __name__ == "__main__": result = render() print(result) print(repr(result))
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_log.py
tests/test_log.py
# encoding=utf-8 import io import re from rich.console import Console 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) test_data = [1, 2, 3] def render_log(): console = Console( file=io.StringIO(), width=80, force_terminal=True, log_time_format="[TIME]", color_system="truecolor", legacy_windows=False, ) console.log() console.log("Hello from", console, "!") console.log(test_data, log_locals=True) return replace_link_ids(console.file.getvalue()).replace("test_log.py", "source.py") def test_log(): expected = replace_link_ids( "\x1b[2;36m[TIME]\x1b[0m\x1b[2;36m \x1b[0m \x1b]8;id=0;foo\x1b\\\x1b[2msource.py\x1b[0m\x1b]8;;\x1b\\\x1b[2m:\x1b[0m\x1b]8;id=0;foo\x1b\\\x1b[2m32\x1b[0m\x1b]8;;\x1b\\\n\x1b[2;36m \x1b[0m\x1b[2;36m \x1b[0mHello from \x1b[1m<\x1b[0m\x1b[1;95mconsole\x1b[0m\x1b[39m \x1b[0m\x1b[33mwidth\x1b[0m\x1b[39m=\x1b[0m\x1b[1;36m80\x1b[0m\x1b[39m ColorSystem.TRUECOLOR\x1b[0m\x1b[1m>\x1b[0m ! \x1b]8;id=0;foo\x1b\\\x1b[2msource.py\x1b[0m\x1b]8;;\x1b\\\x1b[2m:\x1b[0m\x1b]8;id=0;foo\x1b\\\x1b[2m33\x1b[0m\x1b]8;;\x1b\\\n\x1b[2;36m \x1b[0m\x1b[2;36m \x1b[0m\x1b[1m[\x1b[0m\x1b[1;36m1\x1b[0m, \x1b[1;36m2\x1b[0m, \x1b[1;36m3\x1b[0m\x1b[1m]\x1b[0m \x1b]8;id=0;foo\x1b\\\x1b[2msource.py\x1b[0m\x1b]8;;\x1b\\\x1b[2m:\x1b[0m\x1b]8;id=0;foo\x1b\\\x1b[2m34\x1b[0m\x1b]8;;\x1b\\\n\x1b[2;36m \x1b[0m\x1b[34m╭─\x1b[0m\x1b[34m─────────────────────\x1b[0m\x1b[34m \x1b[0m\x1b[3;34mlocals\x1b[0m\x1b[34m \x1b[0m\x1b[34m─────────────────────\x1b[0m\x1b[34m─╮\x1b[0m \x1b[2m \x1b[0m\n\x1b[2;36m \x1b[0m\x1b[34m│\x1b[0m \x1b[3;33mconsole\x1b[0m\x1b[31m =\x1b[0m \x1b[1m<\x1b[0m\x1b[1;95mconsole\x1b[0m\x1b[39m \x1b[0m\x1b[33mwidth\x1b[0m\x1b[39m=\x1b[0m\x1b[1;36m80\x1b[0m\x1b[39m ColorSystem.TRUECOLOR\x1b[0m\x1b[1m>\x1b[0m \x1b[34m│\x1b[0m \x1b[2m \x1b[0m\n\x1b[2;36m \x1b[0m\x1b[34m╰────────────────────────────────────────────────────╯\x1b[0m \x1b[2m \x1b[0m\n" ) rendered = render_log() print(repr(rendered)) assert rendered == expected def test_log_caller_frame_info(): for i in range(2): assert Console._caller_frame_info(i) == Console._caller_frame_info( i, lambda: None ) def test_justify(): console = Console(width=20, log_path=False, log_time=False, color_system=None) console.begin_capture() console.log("foo", justify="right") result = console.end_capture() assert result == " foo\n" if __name__ == "__main__": render = render_log() print(render) print(repr(render))
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_table.py
tests/test_table.py
# encoding=utf-8 import io from textwrap import dedent import pytest from rich import box, errors from rich.console import Console from rich.measure import Measurement from rich.style import Style from rich.table import Column, Table from rich.text import Text def render_tables(): console = Console( width=60, force_terminal=True, file=io.StringIO(), legacy_windows=False, color_system=None, _environ={}, ) table = Table(title="test table", caption="table caption", expand=False) table.add_column("foo", footer=Text("total"), no_wrap=True, overflow="ellipsis") table.add_column("bar", justify="center") table.add_column("baz", justify="right") table.add_row("Averlongwordgoeshere", "banana pancakes", None) assert Measurement.get(console, console.options, table) == Measurement(41, 48) table.expand = True assert Measurement.get(console, console.options, table) == Measurement(41, 48) for width in range(10, 60, 5): console.print(table, width=width) table.expand = False console.print(table, justify="left") console.print(table, justify="center") console.print(table, justify="right") assert table.row_count == 1 table.row_styles = ["red", "yellow"] table.add_row("Coffee") table.add_row("Coffee", "Chocolate", None, "cinnamon") assert table.row_count == 3 console.print(table) table.show_lines = True console.print(table) table.show_footer = True console.print(table) table.show_edge = False console.print(table) table.padding = 1 console.print(table) table.width = 20 assert Measurement.get(console, console.options, table) == Measurement(20, 20) table.expand = False assert Measurement.get(console, console.options, table) == Measurement(20, 20) table.expand = True console.print(table) table.columns[0].no_wrap = True table.columns[1].no_wrap = True table.columns[2].no_wrap = True console.print(table) table.padding = 0 table.width = 60 table.leading = 1 console.print(table) return console.file.getvalue() def test_render_table(): expected = "test table\n┏━━━━━━┳┳┓\n┃ foo ┃┃┃\n┡━━━━━━╇╇┩\n│ Ave… │││\n└──────┴┴┘\n table \n caption \n test table \n┏━━━━━━━━━━━┳┳┓\n┃ foo ┃┃┃\n┡━━━━━━━━━━━╇╇┩\n│ Averlong… │││\n└───────────┴┴┘\n table caption \n test table \n┏━━━━━━━━━━━━━━━━┳┳┓\n┃ foo ┃┃┃\n┡━━━━━━━━━━━━━━━━╇╇┩\n│ Averlongwordg… │││\n└────────────────┴┴┘\n table caption \n test table \n┏━━━━━━━━━━━━━━━━━━━━━┳┳┓\n┃ foo ┃┃┃\n┡━━━━━━━━━━━━━━━━━━━━━╇╇┩\n│ Averlongwordgoeshe… │││\n└─────────────────────┴┴┘\n table caption \n test table \n┏━━━━━━━━━━━━━━━━━━━━━━┳━━┳━━┓\n┃ foo ┃ ┃ ┃\n┡━━━━━━━━━━━━━━━━━━━━━━╇━━╇━━┩\n│ Averlongwordgoeshere │ │ │\n└──────────────────────┴──┴──┘\n table caption \n test table \n┏━━━━━━━━━━━━━━━━━━━━━━┳━━━━━┳━━━━┓\n┃ foo ┃ bar ┃ b… ┃\n┡━━━━━━━━━━━━━━━━━━━━━━╇━━━━━╇━━━━┩\n│ Averlongwordgoeshere │ ba… │ │\n│ │ pa… │ │\n└──────────────────────┴─────┴────┘\n table caption \n test table \n┏━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━┓\n┃ foo ┃ bar ┃ baz ┃\n┡━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━┩\n│ Averlongwordgoeshere │ banana │ │\n│ │ pancak… │ │\n└──────────────────────┴─────────┴─────┘\n table caption \n test table \n┏━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━┓\n┃ foo ┃ bar ┃ baz ┃\n┡━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━┩\n│ Averlongwordgoeshere │ banana │ │\n│ │ pancakes │ │\n└──────────────────────┴──────────────┴─────┘\n table caption \n test table \n┏━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━┳━━━━━┓\n┃ foo ┃ bar ┃ baz ┃\n┡━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━╇━━━━━┩\n│ Averlongwordgoeshere │ banana pancakes │ │\n└───────────────────────┴──────────────────┴─────┘\n table caption \n test table \n┏━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━┳━━━━━┓\n┃ foo ┃ bar ┃ baz ┃\n┡━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━╇━━━━━┩\n│ Averlongwordgoeshere │ banana pancakes │ │\n└──────────────────────────┴────────────────────┴─────┘\n table caption \n test table \n┏━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━┓ \n┃ foo ┃ bar ┃ baz ┃ \n┡━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━┩ \n│ Averlongwordgoeshere │ banana pancakes │ │ \n└──────────────────────┴─────────────────┴─────┘ \n table caption \n test table \n ┏━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━┓ \n ┃ foo ┃ bar ┃ baz ┃ \n ┡━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━┩ \n │ Averlongwordgoeshere │ banana pancakes │ │ \n └──────────────────────┴─────────────────┴─────┘ \n table caption \n test table \n ┏━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━┓\n ┃ foo ┃ bar ┃ baz ┃\n ┡━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━┩\n │ Averlongwordgoeshere │ banana pancakes │ │\n └──────────────────────┴─────────────────┴─────┘\n table caption \n test table \n┏━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━┳━━━━━━━━━━┓\n┃ foo ┃ bar ┃ baz ┃ ┃\n┡━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━╇━━━━━━━━━━┩\n│ Averlongwordgoeshere │ banana pancakes │ │ │\n│ Coffee │ │ │ │\n│ Coffee │ Chocolate │ │ cinnamon │\n└──────────────────────┴─────────────────┴─────┴──────────┘\n table caption \n test table \n┏━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━┳━━━━━━━━━━┓\n┃ foo ┃ bar ┃ baz ┃ ┃\n┡━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━╇━━━━━━━━━━┩\n│ Averlongwordgoeshere │ banana pancakes │ │ │\n├──────────────────────┼─────────────────┼─────┼──────────┤\n│ Coffee │ │ │ │\n├──────────────────────┼─────────────────┼─────┼──────────┤\n│ Coffee │ Chocolate │ │ cinnamon │\n└──────────────────────┴─────────────────┴─────┴──────────┘\n table caption \n test table \n┏━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━┳━━━━━━━━━━┓\n┃ foo ┃ bar ┃ baz ┃ ┃\n┡━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━╇━━━━━━━━━━┩\n│ Averlongwordgoeshere │ banana pancakes │ │ │\n├──────────────────────┼─────────────────┼─────┼──────────┤\n│ Coffee │ │ │ │\n├──────────────────────┼─────────────────┼─────┼──────────┤\n│ Coffee │ Chocolate │ │ cinnamon │\n├──────────────────────┼─────────────────┼─────┼──────────┤\n│ total │ │ │ │\n└──────────────────────┴─────────────────┴─────┴──────────┘\n table caption \n test table \n foo ┃ bar ┃ baz ┃ \n━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━╇━━━━━━━━━━\n Averlongwordgoeshere │ banana pancakes │ │ \n──────────────────────┼─────────────────┼─────┼──────────\n Coffee │ │ │ \n──────────────────────┼─────────────────┼─────┼──────────\n Coffee │ Chocolate │ │ cinnamon \n──────────────────────┼─────────────────┼─────┼──────────\n total │ │ │ \n table caption \n test table \n ┃ ┃ ┃ \n foo ┃ bar ┃ baz ┃ \n ┃ ┃ ┃ \n━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━╇━━━━━━━━━━\n │ │ │ \n Averlongwordgoeshere │ banana pancakes │ │ \n │ │ │ \n──────────────────────┼─────────────────┼─────┼──────────\n │ │ │ \n Coffee │ │ │ \n │ │ │ \n──────────────────────┼─────────────────┼─────┼──────────\n │ │ │ \n Coffee │ Chocolate │ │ cinnamon \n │ │ │ \n──────────────────────┼─────────────────┼─────┼──────────\n │ │ │ \n total │ │ │ \n │ │ │ \n table caption \n test table \n ┃┃┃\n foo ┃┃┃\n ┃┃┃\n━━━━━━━━━━━━━━━━━╇╇╇\n │││\n Averlongwordgo… │││\n │││\n─────────────────┼┼┼\n │││\n Coffee │││\n │││\n─────────────────┼┼┼\n │││\n Coffee │││\n │││\n─────────────────┼┼┼\n │││\n total │││\n │││\n table caption \n test table \n ┃ ┃┃\n foo ┃ bar ┃┃\n ┃ ┃┃\n━━━━━━━━━━╇━━━━━━━━━╇╇\n │ ││\n Averlon… │ banana… ││\n │ ││\n──────────┼─────────┼┼\n │ ││\n Coffee │ ││\n │ ││\n──────────┼─────────┼┼\n │ ││\n Coffee │ Chocol… ││\n │ ││\n──────────┼─────────┼┼\n │ ││\n total │ ││\n │ ││\n table caption \n test table \nfoo ┃ bar ┃ baz┃ \n━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━━╇━━━━━━━━━\nAverlongwordgoeshere │ banana pancakes │ │ \n │ │ │ \nCoffee │ │ │ \n │ │ │ \nCoffee │ Chocolate │ │cinnamon \n─────────────────────────┼───────────────────┼────┼─────────\ntotal │ │ │ \n table caption \n" result = render_tables() print(repr(result)) assert result == expected def test_not_renderable(): class Foo: pass table = Table() with pytest.raises(errors.NotRenderableError): table.add_row(Foo()) def test_init_append_column(): header_names = ["header1", "header2", "header3"] test_columns = [ Column(_index=index, header=header) for index, header in enumerate(header_names) ] # Test appending of strings for header names assert Table(*header_names).columns == test_columns # Test directly passing a Table Column objects assert Table(*test_columns).columns == test_columns def test_rich_measure(): console = Console() assert Table("test_header", width=-1).__rich_measure__( console, console.options ) == Measurement(0, 0) # Check __rich_measure__() for a positive width passed as an argument assert Table("test_header", width=None).__rich_measure__( console, console.options.update_width(10) ) == Measurement(10, 10) def test_min_width(): table = Table("foo", min_width=30) table.add_row("bar") console = Console() assert table.__rich_measure__( console, console.options.update_width(100) ) == Measurement(30, 30) console = Console(color_system=None) console.begin_capture() console.print(table) output = console.end_capture() print(output) assert all(len(line) == 30 for line in output.splitlines()) def test_no_columns(): console = Console(color_system=None) console.begin_capture() console.print(Table()) output = console.end_capture() print(repr(output)) assert output == "\n" def test_get_row_style(): console = Console() table = Table() table.add_row("foo") table.add_row("bar", style="on red") assert table.get_row_style(console, 0) == Style.parse("") assert table.get_row_style(console, 1) == Style.parse("on red") def test_vertical_align_top(): console = Console(_environ={}) def make_table(vertical_align): table = Table(show_header=False, box=box.SQUARE) table.add_column(vertical=vertical_align) table.add_row("foo", "\n".join(["bar"] * 5)) return table with console.capture() as capture: console.print(make_table("top")) console.print() console.print(make_table("middle")) console.print() console.print(make_table("bottom")) console.print() result = capture.get() print(repr(result)) expected = "┌─────┬─────┐\n│ foo │ bar │\n│ │ bar │\n│ │ bar │\n│ │ bar │\n│ │ bar │\n└─────┴─────┘\n\n┌─────┬─────┐\n│ │ bar │\n│ │ bar │\n│ foo │ bar │\n│ │ bar │\n│ │ bar │\n└─────┴─────┘\n\n┌─────┬─────┐\n│ │ bar │\n│ │ bar │\n│ │ bar │\n│ │ bar │\n│ foo │ bar │\n└─────┴─────┘\n\n" assert result == expected @pytest.mark.parametrize( "box,result", [ (None, " 1 2 \n 3 4 \n"), (box.HEAVY_HEAD, "┌───┬───┐\n│ 1 │ 2 │\n│ 3 │ 4 │\n└───┴───┘\n"), (box.SQUARE_DOUBLE_HEAD, "┌───┬───┐\n│ 1 │ 2 │\n│ 3 │ 4 │\n└───┴───┘\n"), (box.MINIMAL_DOUBLE_HEAD, " ╷ \n 1 │ 2 \n 3 │ 4 \n ╵ \n"), (box.MINIMAL_HEAVY_HEAD, " ╷ \n 1 │ 2 \n 3 │ 4 \n ╵ \n"), (box.ASCII_DOUBLE_HEAD, "+---+---+\n| 1 | 2 |\n| 3 | 4 |\n+---+---+\n"), ], ) def test_table_show_header_false_substitution(box, result): """When the box style is one with a custom header edge, it should be substituted for the equivalent box that does not have a custom header when show_header=False""" table = Table(show_header=False, box=box) table.add_column() table.add_column() table.add_row("1", "2") table.add_row("3", "4") console = Console(record=True) console.print(table) output = console.export_text() assert output == result def test_section(): table = Table("foo") table.add_section() # Null-op table.add_row("row1") table.add_row("row2", end_section=True) table.add_row("row3") table.add_row("row4") table.add_section() table.add_row("row5") table.add_section() # Null-op console = Console( width=80, force_terminal=True, color_system="truecolor", legacy_windows=False, record=True, ) console.print(table) output = console.export_text() print(repr(output)) expected = "┏━━━━━━┓\n┃ foo ┃\n┡━━━━━━┩\n│ row1 │\n│ row2 │\n├──────┤\n│ row3 │\n│ row4 │\n├──────┤\n│ row5 │\n└──────┘\n" assert output == expected @pytest.mark.parametrize( "show_header,show_footer,expected", [ ( False, False, dedent( """ abbbbbcbbbbbbbbbcbbbbcbbbbbd 1Dec 2Skywalker2275M2375M 3 4May 5Solo 5275M5393M 6 ijjjjjkjjjjjjjjjkjjjjkjjjjjl 7Dec 8Last Jedi8262M81333M9 qrrrrrsrrrrrrrrrsrrrrsrrrrrt """ ).lstrip(), ), ( True, False, dedent( """ abbbbbcbbbbbbbbbcbbbbcbbbbbd 1Month2Nickname 2Cost2Gross3 efffffgfffffffffgffffgfffffh 4Dec 5Skywalker5275M5375M 6 4May 5Solo 5275M5393M 6 ijjjjjkjjjjjjjjjkjjjjkjjjjjl 7Dec 8Last Jedi8262M81333M9 qrrrrrsrrrrrrrrrsrrrrsrrrrrt """ ).lstrip(), ), ( False, True, dedent( """ abbbbbcbbbbbbbbbcbbbbcbbbbbd 1Dec 2Skywalker2275M2375M 3 4May 5Solo 5275M5393M 6 ijjjjjkjjjjjjjjjkjjjjkjjjjjl 4Dec 5Last Jedi5262M51333M6 mnnnnnonnnnnnnnnonnnnonnnnnp 7MONTH8NICKNAME 8COST8GROSS9 qrrrrrsrrrrrrrrrsrrrrsrrrrrt """ ).lstrip(), ), ( True, True, dedent( """ abbbbbcbbbbbbbbbcbbbbcbbbbbd 1Month2Nickname 2Cost2Gross3 efffffgfffffffffgffffgfffffh 4Dec 5Skywalker5275M5375M 6 4May 5Solo 5275M5393M 6 ijjjjjkjjjjjjjjjkjjjjkjjjjjl 4Dec 5Last Jedi5262M51333M6 mnnnnnonnnnnnnnnonnnnonnnnnp 7MONTH8NICKNAME 8COST8GROSS9 qrrrrrsrrrrrrrrrsrrrrsrrrrrt """ ).lstrip(), ), ], ) def test_placement_table_box_elements(show_header, show_footer, expected): """Ensure box drawing characters correctly positioned.""" table = Table( box=box.ASCII, show_header=show_header, show_footer=show_footer, padding=0 ) # content rows indicated by numerals, pure dividers by letters table.box.__dict__.update( top_left="a", top="b", top_divider="c", top_right="d", head_left="1", head_vertical="2", head_right="3", head_row_left="e", head_row_horizontal="f", head_row_cross="g", head_row_right="h", mid_left="4", mid_vertical="5", mid_right="6", row_left="i", row_horizontal="j", row_cross="k", row_right="l", foot_left="7", foot_vertical="8", foot_right="9", foot_row_left="m", foot_row_horizontal="n", foot_row_cross="o", foot_row_right="p", bottom_left="q", bottom="r", bottom_divider="s", bottom_right="t", ) # add content - note headers title case, footers upper case table.add_column("Month", "MONTH", width=5) table.add_column("Nickname", "NICKNAME", width=9) table.add_column("Cost", "COST", width=4) table.add_column("Gross", "GROSS", width=5) table.add_row("Dec", "Skywalker", "275M", "375M") table.add_row("May", "Solo", "275M", "393M") table.add_section() table.add_row("Dec", "Last Jedi", "262M", "1333M") console = Console(record=True, width=28) console.print(table) output = console.export_text() print(repr(output)) assert output == expected def test_columns_highlight_added_by_add_row() -> None: """Regression test for https://github.com/Textualize/rich/issues/3517""" table = Table(show_header=False, highlight=True) table.add_row("1", repr("FOO")) assert table.columns[0].highlight == table.highlight assert table.columns[1].highlight == table.highlight console = Console(record=True) console.print(table) output = console.export_text(styles=True) print(repr(output)) expected = ( "┌───┬───────┐\n│ \x1b[1;36m1\x1b[0m │ \x1b[32m'FOO'\x1b[0m │\n└───┴───────┘\n" ) assert output == expected if __name__ == "__main__": render = render_tables() print(render) print(repr(render))
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/conftest.py
tests/conftest.py
import pytest @pytest.fixture(autouse=True) def reset_color_envvars(monkeypatch): """Remove color-related envvars to fix test output""" monkeypatch.delenv("FORCE_COLOR", raising=False) monkeypatch.delenv("NO_COLOR", raising=False)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_markdown.py
tests/test_markdown.py
# coding=utf-8 MARKDOWN = """Heading ======= Sub-heading ----------- ### Heading #### H4 Heading ##### H5 Heading ###### H6 Heading Paragraphs are separated by a blank line. Two spaces at the end of a line produces a line break. Text attributes _italic_, **bold**, `monospace`. Horizontal rule: --- Bullet list: * apples * oranges * pears Numbered list: 1. lather 2. rinse 3. repeat An [example](http://example.com). > Markdown uses email-style > characters for blockquoting. > > Lorem ipsum ![progress](https://github.com/textualize/rich/raw/master/imgs/progress.gif) ``` a=1 ``` ```python import this ``` ```somelang foobar ``` import this 1. List item Code block """ import io import re from rich.console import Console, RenderableType from rich.markdown import Markdown 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()) print(repr(output)) return output def test_markdown_render(): markdown = Markdown(MARKDOWN) rendered_markdown = render(markdown) expected = "┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n┃ \x1b[1mHeading\x1b[0m ┃\n┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛\n\n\n \x1b[1;4mSub-heading\x1b[0m \n\n \x1b[1mHeading\x1b[0m \n\n \x1b[1;2mH4 Heading\x1b[0m \n\n \x1b[4mH5 Heading\x1b[0m \n\n \x1b[3mH6 Heading\x1b[0m \n\nParagraphs are separated by a blank line. \n\nTwo spaces at the end of a line produces a line break. \n\nText attributes \x1b[3mitalic\x1b[0m, \x1b[1mbold\x1b[0m, \x1b[1;36;40mmonospace\x1b[0m. \n\nHorizontal rule: \n\n\x1b[33m────────────────────────────────────────────────────────────────────────────────────────────────────\x1b[0m\nBullet list: \n\n\x1b[1;33m • \x1b[0mapples \n\x1b[1;33m • \x1b[0moranges \n\x1b[1;33m • \x1b[0mpears \n\nNumbered list: \n\n\x1b[1;33m 1 \x1b[0mlather \n\x1b[1;33m 2 \x1b[0mrinse \n\x1b[1;33m 3 \x1b[0mrepeat \n\nAn \x1b]8;id=0;foo\x1b\\\x1b[4;34mexample\x1b[0m\x1b]8;;\x1b\\. \n\n\x1b[35m▌ \x1b[0m\x1b[35mMarkdown uses email-style > characters for blockquoting.\x1b[0m\x1b[35m \x1b[0m\n\x1b[35m▌ \x1b[0m\x1b[35mLorem ipsum\x1b[0m\x1b[35m \x1b[0m\n\n🌆 \x1b]8;id=0;foo\x1b\\progress\x1b]8;;\x1b\\ \n\n\x1b[48;2;39;40;34m \x1b[0m\n\x1b[48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34ma=1\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[48;2;39;40;34m \x1b[0m\n\n\x1b[48;2;39;40;34m \x1b[0m\n\x1b[48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34mimport\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mthis\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[48;2;39;40;34m \x1b[0m\n\n\x1b[48;2;39;40;34m \x1b[0m\n\x1b[48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mfoobar\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[48;2;39;40;34m \x1b[0m\n\n\x1b[48;2;39;40;34m \x1b[0m\n\x1b[48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mimport this\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[48;2;39;40;34m \x1b[0m\n\n\x1b[1;33m 1 \x1b[0mList item \n\x1b[1;33m \x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[1;33m \x1b[0m\x1b[48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mCode block\x1b[0m\x1b[48;2;39;40;34m \x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n\x1b[1;33m \x1b[0m\x1b[48;2;39;40;34m \x1b[0m\n" assert rendered_markdown == expected def test_inline_code(): markdown = Markdown( "inline `import this` code", inline_code_lexer="python", inline_code_theme="emacs", ) result = render(markdown) expected = "inline \x1b[1;38;2;170;34;255;48;2;248;248;248mimport\x1b[0m\x1b[38;2;187;187;187;48;2;248;248;248m \x1b[0m\x1b[1;38;2;0;0;255;48;2;248;248;248mthis\x1b[0m code \n" print(result) print(repr(result)) assert result == expected def test_markdown_table(): markdown = Markdown( """\ | Year | Title | Director | Box Office (USD) | |------|:------------------------------------------------:|:------------------|------------------:| | 1982 | *E.T. the Extra-Terrestrial* | Steven Spielberg | $792.9 million | | 1980 | Star Wars: Episode V – The Empire Strikes Back | Irvin Kershner | $538.4 million | | 1983 | Star Wars: Episode VI – Return of the Jedi | Richard Marquand | $475.1 million | | 1981 | Raiders of the Lost Ark | Steven Spielberg | $389.9 million | | 1984 | Indiana Jones and the Temple of Doom | Steven Spielberg | $333.1 million | """ ) result = render(markdown) expected = "\n \n \x1b[1m \x1b[0m\x1b[1mYear\x1b[0m\x1b[1m \x1b[0m \x1b[1m \x1b[0m\x1b[1m Title \x1b[0m\x1b[1m \x1b[0m \x1b[1m \x1b[0m\x1b[1mDirector \x1b[0m\x1b[1m \x1b[0m \x1b[1m \x1b[0m\x1b[1mBox Office (USD)\x1b[0m\x1b[1m \x1b[0m \n ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ \n 1982 \x1b[3mE.T. the Extra-Terrestrial\x1b[0m Steven Spielberg $792.9 million \n 1980 Star Wars: Episode V – The Empire Strikes Back Irvin Kershner $538.4 million \n 1983 Star Wars: Episode VI – Return of the Jedi Richard Marquand $475.1 million \n 1981 Raiders of the Lost Ark Steven Spielberg $389.9 million \n 1984 Indiana Jones and the Temple of Doom Steven Spielberg $333.1 million \n \n" assert result == expected def test_inline_styles_in_table(): """Regression test for https://github.com/Textualize/rich/issues/3115""" markdown = Markdown( """\ | Year | This **column** displays _the_ movie _title_ ~~description~~ | Director | Box Office (USD) | |------|:----------------------------------------------------------:|:------------------|------------------:| | 1982 | *E.T. the Extra-Terrestrial* ([Wikipedia article](https://en.wikipedia.org/wiki/E.T._the_Extra-Terrestrial)) | Steven Spielberg | $792.9 million | | 1980 | Star Wars: Episode V – The *Empire* **Strikes** ~~Back~~ | Irvin Kershner | $538.4 million | """ ) result = render(markdown) expected = "\n \n \x1b[1m \x1b[0m\x1b[1mYear\x1b[0m\x1b[1m \x1b[0m \x1b[1m \x1b[0m\x1b[1mThis \x1b[0m\x1b[1mcolumn\x1b[0m\x1b[1m displays \x1b[0m\x1b[1;3mthe\x1b[0m\x1b[1m movie \x1b[0m\x1b[1;3mtitle\x1b[0m\x1b[1m \x1b[0m\x1b[1;9mdescription\x1b[0m\x1b[1m \x1b[0m \x1b[1m \x1b[0m\x1b[1mDirector \x1b[0m\x1b[1m \x1b[0m \x1b[1m \x1b[0m\x1b[1mBox Office (USD)\x1b[0m\x1b[1m \x1b[0m \n ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ \n 1982 \x1b[3mE.T. the Extra-Terrestrial\x1b[0m (\x1b]8;id=0;foo\x1b\\\x1b[4;34mWikipedia article\x1b[0m\x1b]8;;\x1b\\) Steven Spielberg $792.9 million \n 1980 Star Wars: Episode V – The \x1b[3mEmpire\x1b[0m \x1b[1mStrikes\x1b[0m \x1b[9mBack\x1b[0m Irvin Kershner $538.4 million \n \n" assert result == expected def test_inline_styles_with_justification(): """Regression test for https://github.com/Textualize/rich/issues/3115 In particular, this tests the interaction between the change that was made to fix #3115 and column text justification. """ markdown = Markdown( """\ | left | center | right | | :- | :-: | -: | | This is a long row | because it contains | a fairly long sentence. | | a*b* _c_ ~~d~~ e | a*b* _c_ ~~d~~ e | a*b* _c_ ~~d~~ e |""" ) result = render(markdown) expected = "\n \n \x1b[1m \x1b[0m\x1b[1mleft \x1b[0m\x1b[1m \x1b[0m \x1b[1m \x1b[0m\x1b[1m center \x1b[0m\x1b[1m \x1b[0m \x1b[1m \x1b[0m\x1b[1m right\x1b[0m\x1b[1m \x1b[0m \n ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ \n This is a long row because it contains a fairly long sentence. \n a\x1b[3mb\x1b[0m \x1b[3mc\x1b[0m \x1b[9md\x1b[0m e a\x1b[3mb\x1b[0m \x1b[3mc\x1b[0m \x1b[9md\x1b[0m e a\x1b[3mb\x1b[0m \x1b[3mc\x1b[0m \x1b[9md\x1b[0m e \n \n" assert result == expected def test_partial_table(): markdown = Markdown("| Simple | Table |\n| ------ | ----- ") result = render(markdown) print(repr(result)) expected = "\n \n \x1b[1m \x1b[0m\x1b[1mSimple\x1b[0m\x1b[1m \x1b[0m \x1b[1m \x1b[0m\x1b[1mTable\x1b[0m\x1b[1m \x1b[0m \n ━━━━━━━━━━━━━━━━ \n \n" assert result == expected def test_table_with_empty_cells() -> None: """Test a table with empty cells is rendered without extra newlines above. Regression test for #3027 https://github.com/Textualize/rich/issues/3027 """ complete_table = Markdown( """\ | First Header | Second Header | | ------------- | ------------- | | Content Cell | Content Cell | | Content Cell | Content Cell | """ ) table_with_empty_cells = Markdown( """\ | First Header | | | ------------- | ------------- | | Content Cell | Content Cell | | | Content Cell | """ ) result = len(render(table_with_empty_cells).splitlines()) expected = len(render(complete_table).splitlines()) assert result == expected if __name__ == "__main__": markdown = Markdown(MARKDOWN) rendered = render(markdown) print(rendered) print(repr(rendered))
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_box.py
tests/test_box.py
import pytest from rich.console import ConsoleOptions, ConsoleDimensions from rich.box import ( ASCII, DOUBLE, ROUNDED, HEAVY, SQUARE, MINIMAL_HEAVY_HEAD, MINIMAL, SIMPLE_HEAVY, SIMPLE, HEAVY_EDGE, HEAVY_HEAD, ) def test_str(): assert str(ASCII) == "+--+\n| ||\n|-+|\n| ||\n|-+|\n|-+|\n| ||\n+--+\n" def test_repr(): assert repr(ASCII) == "Box(...)" def test_get_top(): top = HEAVY.get_top(widths=[1, 2]) assert top == "┏━┳━━┓" def test_get_row(): head_row = DOUBLE.get_row(widths=[3, 2, 1], level="head") assert head_row == "╠═══╬══╬═╣" row = ASCII.get_row(widths=[1, 2, 3], level="row") assert row == "|-+--+---|" foot_row = ROUNDED.get_row(widths=[2, 1, 3], level="foot") assert foot_row == "├──┼─┼───┤" with pytest.raises(ValueError): ROUNDED.get_row(widths=[1, 2, 3], level="FOO") def test_get_bottom(): bottom = HEAVY.get_bottom(widths=[1, 2, 3]) assert bottom == "┗━┻━━┻━━━┛" def test_box_substitute_for_same_box(): options = ConsoleOptions( ConsoleDimensions(80, 25), legacy_windows=False, min_width=1, max_width=100, is_terminal=True, encoding="utf-8", max_height=25, ) assert ROUNDED.substitute(options) == ROUNDED assert MINIMAL_HEAVY_HEAD.substitute(options) == MINIMAL_HEAVY_HEAD assert SIMPLE_HEAVY.substitute(options) == SIMPLE_HEAVY assert HEAVY.substitute(options) == HEAVY assert HEAVY_EDGE.substitute(options) == HEAVY_EDGE assert HEAVY_HEAD.substitute(options) == HEAVY_HEAD def test_box_substitute_for_different_box_legacy_windows(): options = ConsoleOptions( ConsoleDimensions(80, 25), legacy_windows=True, min_width=1, max_width=100, is_terminal=True, encoding="utf-8", max_height=25, ) assert ROUNDED.substitute(options) == SQUARE assert MINIMAL_HEAVY_HEAD.substitute(options) == MINIMAL assert SIMPLE_HEAVY.substitute(options) == SIMPLE assert HEAVY.substitute(options) == SQUARE assert HEAVY_EDGE.substitute(options) == SQUARE assert HEAVY_HEAD.substitute(options) == SQUARE def test_box_substitute_for_different_box_ascii_encoding(): options = ConsoleOptions( ConsoleDimensions(80, 25), legacy_windows=True, min_width=1, max_width=100, is_terminal=True, encoding="ascii", max_height=25, ) assert ROUNDED.substitute(options) == ASCII assert MINIMAL_HEAVY_HEAD.substitute(options) == ASCII assert SIMPLE_HEAVY.substitute(options) == ASCII assert HEAVY.substitute(options) == ASCII assert HEAVY_EDGE.substitute(options) == ASCII assert HEAVY_HEAD.substitute(options) == ASCII
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_color_triplet.py
tests/test_color_triplet.py
from rich.color_triplet import ColorTriplet def test_hex(): assert ColorTriplet(255, 255, 255).hex == "#ffffff" assert ColorTriplet(0, 255, 0).hex == "#00ff00" def test_rgb(): assert ColorTriplet(255, 255, 255).rgb == "rgb(255,255,255)" assert ColorTriplet(0, 255, 0).rgb == "rgb(0,255,0)" def test_normalized(): assert ColorTriplet(255, 255, 255).normalized == (1.0, 1.0, 1.0) assert ColorTriplet(0, 255, 0).normalized == (0.0, 1.0, 0.0)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_segment.py
tests/test_segment.py
from io import StringIO import pytest from rich.cells import cell_len from rich.segment import ControlType, Segment, SegmentLines, Segments from rich.style import Style def test_repr(): assert repr(Segment("foo")) == "Segment('foo')" home = (ControlType.HOME, 0) assert ( repr(Segment("foo", None, [home])) == "Segment('foo', None, [(<ControlType.HOME: 3>, 0)])" ) def test_line(): assert Segment.line() == Segment("\n") def test_apply_style(): segments = [Segment("foo"), Segment("bar", Style(bold=True))] assert Segment.apply_style(segments, None) is segments assert list(Segment.apply_style(segments, Style(italic=True))) == [ Segment("foo", Style(italic=True)), Segment("bar", Style(italic=True, bold=True)), ] def test_split_lines(): lines = [Segment("Hello\nWorld")] assert list(Segment.split_lines(lines)) == [[Segment("Hello")], [Segment("World")]] def test_split_and_crop_lines(): assert list( Segment.split_and_crop_lines([Segment("Hello\nWorld!\n"), Segment("foo")], 4) ) == [ [Segment("Hell"), Segment("\n", None)], [Segment("Worl"), Segment("\n", None)], [Segment("foo"), Segment(" ")], ] def test_adjust_line_length(): line = [Segment("Hello", "foo")] assert Segment.adjust_line_length(line, 10, style="bar") == [ Segment("Hello", "foo"), Segment(" ", "bar"), ] line = [Segment("H"), Segment("ello, World!")] assert Segment.adjust_line_length(line, 5) == [Segment("H"), Segment("ello")] line = [Segment("Hello")] assert Segment.adjust_line_length(line, 5) == line def test_get_line_length(): assert Segment.get_line_length([Segment("foo"), Segment("bar")]) == 6 def test_get_shape(): assert Segment.get_shape([[Segment("Hello")]]) == (5, 1) assert Segment.get_shape([[Segment("Hello")], [Segment("World!")]]) == (6, 2) def test_set_shape(): assert Segment.set_shape([[Segment("Hello")]], 10) == [ [Segment("Hello"), Segment(" ")] ] assert Segment.set_shape([[Segment("Hello")]], 10, 2) == [ [Segment("Hello"), Segment(" ")], [Segment(" " * 10)], ] def test_simplify(): assert list( Segment.simplify([Segment("Hello"), Segment(" "), Segment("World!")]) ) == [Segment("Hello World!")] assert list( Segment.simplify( [Segment("Hello", "red"), Segment(" ", "red"), Segment("World!", "blue")] ) ) == [Segment("Hello ", "red"), Segment("World!", "blue")] assert list(Segment.simplify([])) == [] def test_filter_control(): control_code = (ControlType.HOME, 0) segments = [Segment("foo"), Segment("bar", None, (control_code,))] assert list(Segment.filter_control(segments)) == [Segment("foo")] assert list(Segment.filter_control(segments, is_control=True)) == [ Segment("bar", None, (control_code,)) ] def test_strip_styles(): segments = [Segment("foo", Style(bold=True))] assert list(Segment.strip_styles(segments)) == [Segment("foo", None)] def test_strip_links(): segments = [Segment("foo", Style(bold=True, link="https://www.example.org"))] assert list(Segment.strip_links(segments)) == [Segment("foo", Style(bold=True))] def test_remove_color(): segments = [ Segment("foo", Style(bold=True, color="red")), Segment("bar", None), ] assert list(Segment.remove_color(segments)) == [ Segment("foo", Style(bold=True)), Segment("bar", None), ] def test_is_control(): assert Segment("foo", Style(bold=True)).is_control == False assert Segment("foo", Style(bold=True), []).is_control == True assert Segment("foo", Style(bold=True), [(ControlType.HOME, 0)]).is_control == True def test_segments_renderable(): segments = Segments([Segment("foo")]) assert list(segments.__rich_console__(None, None)) == [Segment("foo")] segments = Segments([Segment("foo")], new_lines=True) assert list(segments.__rich_console__(None, None)) == [ Segment("foo"), Segment.line(), ] def test_divide(): bold = Style(bold=True) italic = Style(italic=True) segments = [ Segment("Hello", bold), Segment(" World!", italic), ] assert list(Segment.divide(segments, [])) == [] assert list(Segment.divide([], [1])) == [[]] assert list(Segment.divide(segments, [1])) == [[Segment("H", bold)]] assert list(Segment.divide(segments, [1, 2])) == [ [Segment("H", bold)], [Segment("e", bold)], ] assert list(Segment.divide(segments, [1, 2, 12])) == [ [Segment("H", bold)], [Segment("e", bold)], [Segment("llo", bold), Segment(" World!", italic)], ] assert list(Segment.divide(segments, [4, 20])) == [ [Segment("Hell", bold)], [Segment("o", bold), Segment(" World!", italic)], ] # https://github.com/textualize/rich/issues/1755 def test_divide_complex(): MAP = ( "[on orange4] [on green]XX[on orange4] \n" " \n" " \n" " \n" " [bright_red on black]Y[on orange4] \n" "[on green]X[on orange4] [on green]X[on orange4] \n" " [on green]X[on orange4] [on green]X\n" "[on orange4] \n" " [on green]XX[on orange4] \n" ) from rich.console import Console from rich.text import Text text = Text.from_markup(MAP) console = Console( color_system="truecolor", width=30, force_terminal=True, file=StringIO() ) console.print(text) result = console.file.getvalue() print(repr(result)) expected = "\x1b[48;5;94m \x1b[0m\x1b[42mXX\x1b[0m\x1b[48;5;94m \x1b[0m\n\x1b[48;5;94m \x1b[0m\n\x1b[48;5;94m \x1b[0m\n\x1b[48;5;94m \x1b[0m\n\x1b[48;5;94m \x1b[0m\x1b[91;40mY\x1b[0m\x1b[91;48;5;94m \x1b[0m\n\x1b[91;42mX\x1b[0m\x1b[91;48;5;94m \x1b[0m\x1b[91;42mX\x1b[0m\x1b[91;48;5;94m \x1b[0m\n\x1b[91;48;5;94m \x1b[0m\x1b[91;42mX\x1b[0m\x1b[91;48;5;94m \x1b[0m\x1b[91;42mX\x1b[0m\n\x1b[91;48;5;94m \x1b[0m\n\x1b[91;48;5;94m \x1b[0m\x1b[91;42mXX\x1b[0m\x1b[91;48;5;94m \x1b[0m\n\n" assert result == expected def test_divide_emoji(): bold = Style(bold=True) italic = Style(italic=True) segments = [ Segment("Hello", bold), Segment("💩💩💩", italic), ] assert list(Segment.divide(segments, [7])) == [ [Segment("Hello", bold), Segment("💩", italic)], ] assert list(Segment.divide(segments, [8])) == [ [Segment("Hello", bold), Segment("💩 ", italic)], ] assert list(Segment.divide(segments, [9])) == [ [Segment("Hello", bold), Segment("💩💩", italic)], ] assert list(Segment.divide(segments, [8, 11])) == [ [Segment("Hello", bold), Segment("💩 ", italic)], [Segment(" 💩", italic)], ] assert list(Segment.divide(segments, [9, 11])) == [ [Segment("Hello", bold), Segment("💩💩", italic)], [Segment("💩", italic)], ] def test_divide_edge(): segments = [Segment("foo"), Segment("bar"), Segment("baz")] result = list(Segment.divide(segments, [1, 3, 9])) print(result) assert result == [ [Segment("f")], [Segment("oo")], [Segment("bar"), Segment("baz")], ] def test_divide_edge_2(): segments = [ Segment("╭─"), Segment( "────── Placeholder ───────", ), Segment( "─╮", ), ] result = list(Segment.divide(segments, [30, 60])) expected = [segments, []] print(repr(result)) assert result == expected @pytest.mark.parametrize( "text,split,result", [ ("XX", 4, (Segment("XX"), Segment(""))), ("X", 1, (Segment("X"), Segment(""))), ("💩", 1, (Segment(" "), Segment(" "))), ("XY", 1, (Segment("X"), Segment("Y"))), ("💩X", 1, (Segment(" "), Segment(" X"))), ("💩💩", 1, (Segment(" "), Segment(" 💩"))), ("X💩Y", 2, (Segment("X "), Segment(" Y"))), ("X💩YZ", 2, (Segment("X "), Segment(" YZ"))), ("X💩💩Z", 2, (Segment("X "), Segment(" 💩Z"))), ("X💩💩Z", 3, (Segment("X💩"), Segment("💩Z"))), ("X💩💩Z", 4, (Segment("X💩 "), Segment(" Z"))), ("X💩💩Z", 5, (Segment("X💩💩"), Segment("Z"))), ("X💩💩Z", 6, (Segment("X💩💩Z"), Segment(""))), ("XYZABC💩💩", 6, (Segment("XYZABC"), Segment("💩💩"))), ("XYZABC💩💩", 7, (Segment("XYZABC "), Segment(" 💩"))), ("XYZABC💩💩", 8, (Segment("XYZABC💩"), Segment("💩"))), ("XYZABC💩💩", 9, (Segment("XYZABC💩 "), Segment(" "))), ("XYZABC💩💩", 10, (Segment("XYZABC💩💩"), Segment(""))), ("💩💩💩💩💩", 3, (Segment("💩 "), Segment(" 💩💩💩"))), ("💩💩💩💩💩", 4, (Segment("💩💩"), Segment("💩💩💩"))), ("💩X💩Y💩Z💩A💩", 4, (Segment("💩X "), Segment(" Y💩Z💩A💩"))), ("XYZABC", 4, (Segment("XYZA"), Segment("BC"))), ("XYZABC", 5, (Segment("XYZAB"), Segment("C"))), ( "a1あ11bcdaef", 9, (Segment("a1あ11b"), Segment("cdaef")), ), ], ) def test_split_cells_emoji(text, split, result): assert Segment(text).split_cells(split) == result @pytest.mark.parametrize( "segment", [ Segment("早乙女リリエル (CV: 徳井青)"), Segment("メイド・イン・きゅんクチュアリ☆ "), Segment("TVアニメ「メルクストーリア -無気力少年と瓶の中の少女-」 主題歌CD"), Segment("南無阿弥JKうらめしや?! "), Segment("メルク (CV: 水瀬いのり) "), Segment(" メルク (CV: 水瀬いのり) "), Segment(" メルク (CV: 水瀬いのり) "), Segment(" メルク (CV: 水瀬いのり) "), ], ) def test_split_cells_mixed(segment: Segment) -> None: """Check that split cells splits on cell positions.""" # Caused https://github.com/Textualize/textual/issues/4996 in Textual for position in range(0, segment.cell_length + 1): left, right = Segment.split_cells(segment, position) assert all( cell_len(c) > 0 for c in segment.text ) # Sanity check there aren't any sneaky control codes assert cell_len(left.text) == position assert cell_len(right.text) == segment.cell_length - position def test_split_cells_doubles() -> None: """Check that split cells splits on cell positions with all double width characters.""" test = Segment("早" * 20) for position in range(1, test.cell_length): left, right = Segment.split_cells(test, position) assert cell_len(left.text) == position assert cell_len(right.text) == test.cell_length - position def test_split_cells_single() -> None: """Check that split cells splits on cell positions with all single width characters.""" test = Segment("A" * 20) for position in range(1, test.cell_length): left, right = Segment.split_cells(test, position) assert cell_len(left.text) == position assert cell_len(right.text) == test.cell_length - position def test_segment_lines_renderable(): lines = [[Segment("hello"), Segment(" "), Segment("world")], [Segment("foo")]] segment_lines = SegmentLines(lines) assert list(segment_lines.__rich_console__(None, None)) == [ Segment("hello"), Segment(" "), Segment("world"), Segment("foo"), ] segment_lines = SegmentLines(lines, new_lines=True) assert list(segment_lines.__rich_console__(None, None)) == [ Segment("hello"), Segment(" "), Segment("world"), Segment("\n"), Segment("foo"), Segment("\n"), ] def test_align_top(): lines = [[Segment("X")]] assert Segment.align_top(lines, 3, 1, Style()) == lines assert Segment.align_top(lines, 3, 3, Style()) == [ [Segment("X")], [Segment(" ", Style())], [Segment(" ", Style())], ] def test_align_middle(): lines = [[Segment("X")]] assert Segment.align_middle(lines, 3, 1, Style()) == lines assert Segment.align_middle(lines, 3, 3, Style()) == [ [Segment(" ", Style())], [Segment("X")], [Segment(" ", Style())], ] def test_align_bottom(): lines = [[Segment("X")]] assert Segment.align_bottom(lines, 3, 1, Style()) == lines assert Segment.align_bottom(lines, 3, 3, Style()) == [ [Segment(" ", Style())], [Segment(" ", Style())], [Segment("X")], ]
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_panel.py
tests/test_panel.py
import io import pytest from rich.console import Console from rich.panel import Panel from rich.segment import Segment from rich.style import Style from rich.text import Text tests = [ Panel("Hello, World", padding=0), Panel("Hello, World", expand=False, padding=0), Panel.fit("Hello, World", padding=0), Panel("Hello, World", width=8, padding=0), Panel(Panel("Hello, World", padding=0), padding=0), Panel("Hello, World", title="FOO", padding=0), Panel("Hello, World", subtitle="FOO", padding=0), ] expected = [ "╭────────────────────────────────────────────────╮\n│Hello, World │\n╰────────────────────────────────────────────────╯\n", "╭────────────╮\n│Hello, World│\n╰────────────╯\n", "╭────────────╮\n│Hello, World│\n╰────────────╯\n", "╭──────╮\n│Hello,│\n│World │\n╰──────╯\n", "╭────────────────────────────────────────────────╮\n│╭──────────────────────────────────────────────╮│\n││Hello, World ││\n│╰──────────────────────────────────────────────╯│\n╰────────────────────────────────────────────────╯\n", "╭───────────────────── FOO ──────────────────────╮\n│Hello, World │\n╰────────────────────────────────────────────────╯\n", "╭────────────────────────────────────────────────╮\n│Hello, World │\n╰───────────────────── FOO ──────────────────────╯\n", ] def render(panel, width=50) -> str: console = Console(file=io.StringIO(), width=50, legacy_windows=False) console.print(panel) result = console.file.getvalue() print(result) return result @pytest.mark.parametrize("panel,expected", zip(tests, expected)) def test_render_panel(panel, expected) -> None: assert render(panel) == expected def test_console_width() -> None: console = Console(file=io.StringIO(), width=50, legacy_windows=False) panel = Panel("Hello, World", expand=False) min_width, max_width = panel.__rich_measure__(console, console.options) assert min_width == 16 assert max_width == 16 def test_fixed_width() -> None: console = Console(file=io.StringIO(), width=50, legacy_windows=False) panel = Panel("Hello World", width=20) min_width, max_width = panel.__rich_measure__(console, console.options) assert min_width == 20 assert max_width == 20 def test_render_size() -> None: console = Console(width=63, height=46, legacy_windows=False) options = console.options.update_dimensions(80, 4) lines = console.render_lines(Panel("foo", title="Hello"), options=options) print(repr(lines)) expected = [ [ Segment("╭─", Style()), Segment( "────────────────────────────────── Hello ───────────────────────────────────" ), Segment("─╮", Style()), ], [ Segment("│", Style()), Segment(" ", Style()), Segment("foo"), Segment( " ", Style(), ), Segment(" ", Style()), Segment("│", Style()), ], [ Segment("│", Style()), Segment(" ", Style()), Segment( " ", Style(), ), Segment(" ", Style()), Segment("│", Style()), ], [ Segment( "╰──────────────────────────────────────────────────────────────────────────────╯", Style(), ) ], ] assert lines == expected def test_title_text() -> None: panel = Panel( "Hello, World", title=Text("title", style="red"), subtitle=Text("subtitle", style="magenta bold"), ) console = Console( file=io.StringIO(), width=50, height=20, legacy_windows=False, force_terminal=True, color_system="truecolor", ) console.print(panel) result = console.file.getvalue() print(repr(result)) expected = "╭────────────────────\x1b[31m title \x1b[0m─────────────────────╮\n│ Hello, World │\n╰───────────────────\x1b[1;35m subtitle \x1b[0m───────────────────╯\n" assert result == expected def test_title_text_with_border_color() -> None: """Regression test for https://github.com/Textualize/rich/issues/2745""" panel = Panel( "Hello, World", border_style="blue", title=Text("title", style="red"), subtitle=Text("subtitle", style="magenta bold"), ) console = Console( file=io.StringIO(), width=50, height=20, legacy_windows=False, force_terminal=True, color_system="truecolor", ) console.print(panel) result = console.file.getvalue() print(repr(result)) expected = "\x1b[34m╭─\x1b[0m\x1b[34m───────────────────\x1b[0m\x1b[31m title \x1b[0m\x1b[34m────────────────────\x1b[0m\x1b[34m─╮\x1b[0m\n\x1b[34m│\x1b[0m Hello, World \x1b[34m│\x1b[0m\n\x1b[34m╰─\x1b[0m\x1b[34m──────────────────\x1b[0m\x1b[1;35m subtitle \x1b[0m\x1b[34m──────────────────\x1b[0m\x1b[34m─╯\x1b[0m\n" assert result == expected def test_title_text_with_panel_background() -> None: """Regression test for https://github.com/Textualize/rich/issues/3569""" panel = Panel( "Hello, World", style="on blue", title=Text("title", style="red"), subtitle=Text("subtitle", style="magenta bold"), ) console = Console( file=io.StringIO(), width=50, height=20, legacy_windows=False, force_terminal=True, color_system="truecolor", ) console.print(panel) result = console.file.getvalue() print(repr(result)) expected = "\x1b[44m╭─\x1b[0m\x1b[44m───────────────────\x1b[0m\x1b[31;44m title \x1b[0m\x1b[44m────────────────────\x1b[0m\x1b[44m─╮\x1b[0m\n\x1b[44m│\x1b[0m\x1b[44m \x1b[0m\x1b[44mHello, World\x1b[0m\x1b[44m \x1b[0m\x1b[44m \x1b[0m\x1b[44m│\x1b[0m\n\x1b[44m╰─\x1b[0m\x1b[44m──────────────────\x1b[0m\x1b[1;35;44m subtitle \x1b[0m\x1b[44m──────────────────\x1b[0m\x1b[44m─╯\x1b[0m\n" assert result == expected if __name__ == "__main__": expected = [] for panel in tests: result = render(panel) print(result) expected.append(result) print("--") print() print(f"expected={repr(expected)}")
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_text.py
tests/test_text.py
import re from io import StringIO from typing import List import pytest from rich.console import Console, Group from rich.measure import Measurement from rich.style import Style from rich.text import Span, Text def test_span(): span = Span(1, 10, "foo") repr(span) assert bool(span) assert not Span(10, 10, "foo") def test_span_split(): assert Span(5, 10, "foo").split(2) == (Span(5, 10, "foo"), None) assert Span(5, 10, "foo").split(15) == (Span(5, 10, "foo"), None) assert Span(0, 10, "foo").split(5) == (Span(0, 5, "foo"), Span(5, 10, "foo")) def test_span_move(): assert Span(5, 10, "foo").move(2) == Span(7, 12, "foo") def test_span_right_crop(): assert Span(5, 10, "foo").right_crop(15) == Span(5, 10, "foo") assert Span(5, 10, "foo").right_crop(7) == Span(5, 7, "foo") def test_len(): assert len(Text("foo")) == 3 def test_cell_len(): assert Text("foo").cell_len == 3 assert Text("😀").cell_len == 2 def test_bool(): assert Text("foo") assert not Text("") def test_str(): assert str(Text("foo")) == "foo" def test_repr(): assert isinstance(repr(Text("foo")), str) def test_add(): text = Text("foo") + Text("bar") assert str(text) == "foobar" assert Text("foo").__add__(1) == NotImplemented def test_eq(): assert Text("foo") == Text("foo") assert Text("foo") != Text("bar") assert Text("foo").__eq__(1) == NotImplemented def test_contain(): text = Text("foobar") assert "foo" in text assert "foo " not in text assert Text("bar") in text assert None not in text def test_plain_property(): text = Text("foo") text.append("bar") text.append("baz") assert text.plain == "foobarbaz" def test_plain_property_setter(): text = Text("foo") text.plain = "bar" assert str(text) == "bar" text = Text() text.append("Hello, World", "bold") text.plain = "Hello" assert str(text) == "Hello" assert text._spans == [Span(0, 5, "bold")] def test_from_markup(): text = Text.from_markup("Hello, [bold]World![/bold]") assert str(text) == "Hello, World!" assert text._spans == [Span(7, 13, "bold")] def test_from_ansi(): text = Text.from_ansi("Hello, \033[1mWorld!\033[0m") assert str(text) == "Hello, World!" assert text._spans == [Span(7, 13, Style(bold=True))] text = Text.from_ansi("Hello, \033[1m\nWorld!\033[0m") assert str(text) == "Hello, \nWorld!" assert text._spans == [Span(8, 14, Style(bold=True))] text = Text.from_ansi("\033[1mBOLD\033[m not bold") assert str(text) == "BOLD not bold" assert text._spans == [Span(0, 4, Style(bold=True))] text = Text.from_ansi("\033[1m\033[Kfoo barmbaz") assert str(text) == "foo barmbaz" assert text._spans == [Span(0, 11, Style(bold=True))] def test_copy(): text = Text() text.append("Hello", "bold") text.append(" ") text.append("World", "italic") test_copy = text.copy() assert text == test_copy assert text is not test_copy def test_rstrip(): text = Text("Hello, World! ") text.rstrip() assert str(text) == "Hello, World!" def test_rstrip_end(): text = Text("Hello, World! ") text.rstrip_end(14) assert str(text) == "Hello, World! " def test_stylize(): text = Text("Hello, World!") text.stylize("bold", 7, 11) assert text._spans == [Span(7, 11, "bold")] text.stylize("bold", 20, 25) assert text._spans == [Span(7, 11, "bold")] def test_stylize_before(): text = Text("Hello, World!") text.stylize("bold", 0, 5) text.stylize_before("italic", 2, 7) assert text._spans == [Span(2, 7, "italic"), Span(0, 5, "bold")] def test_stylize_negative_index(): text = Text("Hello, World!") text.stylize("bold", -6, -1) assert text._spans == [Span(7, 12, "bold")] def test_highlight_regex(): # As a string text = Text("peek-a-boo") count = text.highlight_regex(r"NEVER_MATCH", "red") assert count == 0 assert len(text._spans) == 0 # text: peek-a-boo # indx: 0123456789 count = text.highlight_regex(r"[a|e|o]+", "red") assert count == 3 assert sorted(text._spans) == [ Span(1, 3, "red"), Span(5, 6, "red"), Span(8, 10, "red"), ] text = Text("Ada Lovelace, Alan Turing") count = text.highlight_regex( r"(?P<yellow>[A-Za-z]+)[ ]+(?P<red>[A-Za-z]+)(?P<NEVER_MATCH>NEVER_MATCH)*" ) # The number of matched name should be 2 assert count == 2 assert sorted(text._spans) == [ Span(0, 3, "yellow"), # Ada Span(4, 12, "red"), # Lovelace Span(14, 18, "yellow"), # Alan Span(19, 25, "red"), # Turing ] # As a regular expression object text = Text("peek-a-boo") count = text.highlight_regex(re.compile(r"NEVER_MATCH"), "red") assert count == 0 assert len(text._spans) == 0 # text: peek-a-boo # indx: 0123456789 count = text.highlight_regex(re.compile(r"[a|e|o]+"), "red") assert count == 3 assert sorted(text._spans) == [ Span(1, 3, "red"), Span(5, 6, "red"), Span(8, 10, "red"), ] text = Text("Ada Lovelace, Alan Turing") count = text.highlight_regex( re.compile( r"(?P<yellow>[A-Za-z]+)[ ]+(?P<red>[A-Za-z]+)(?P<NEVER_MATCH>NEVER_MATCH)*" ) ) # The number of matched name should be 2 assert count == 2 assert sorted(text._spans) == [ Span(0, 3, "yellow"), # Ada Span(4, 12, "red"), # Lovelace Span(14, 18, "yellow"), # Alan Span(19, 25, "red"), # Turing ] def test_highlight_regex_callable(): text = Text("Vulnerability CVE-2018-6543 detected") re_cve = r"CVE-\d{4}-\d+" compiled_re_cve = re.compile(r"CVE-\d{4}-\d+") def get_style(text: str) -> Style: return Style.parse( f"bold yellow link https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword={text}" ) # string count = text.highlight_regex(re_cve, get_style) assert count == 1 assert len(text._spans) == 1 assert text._spans[0].start == 14 assert text._spans[0].end == 27 assert ( text._spans[0].style.link == "https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=CVE-2018-6543" ) # Clear the tracked _spans for the regular expression object's use text._spans.clear() # regular expression object count = text.highlight_regex(compiled_re_cve, get_style) assert count == 1 assert len(text._spans) == 1 assert text._spans[0].start == 14 assert text._spans[0].end == 27 assert ( text._spans[0].style.link == "https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=CVE-2018-6543" ) def test_highlight_words(): text = Text("Do NOT! touch anything!") words = ["NOT", "!"] count = text.highlight_words(words, "red") assert count == 3 assert sorted(text._spans) == [ Span(3, 6, "red"), # NOT Span(6, 7, "red"), # ! Span(22, 23, "red"), # ! ] # regex escape test text = Text("[o|u]aeiou") words = ["[a|e|i]", "[o|u]"] count = text.highlight_words(words, "red") assert count == 1 assert text._spans == [Span(0, 5, "red")] # case sensitive text = Text("AB Ab aB ab") words = ["AB"] count = text.highlight_words(words, "red") assert count == 1 assert text._spans == [Span(0, 2, "red")] text = Text("AB Ab aB ab") count = text.highlight_words(words, "red", case_sensitive=False) assert count == 4 def test_set_length(): text = Text("Hello") text.set_length(5) assert text == Text("Hello") text = Text("Hello") text.set_length(10) assert text == Text("Hello ") text = Text("Hello World") text.stylize("bold", 0, 5) text.stylize("italic", 7, 9) text.set_length(3) expected = Text() expected.append("Hel", "bold") assert text == expected def test_console_width(): console = Console() text = Text("Hello World!\nfoobarbaz") assert text.__rich_measure__(console, 80) == Measurement(9, 12) assert Text(" " * 4).__rich_measure__(console, 80) == Measurement(4, 4) assert Text(" \n \n ").__rich_measure__(console, 80) == Measurement(3, 3) def test_join(): text = Text("bar").join([Text("foo", "red"), Text("baz", "blue")]) assert str(text) == "foobarbaz" assert text._spans == [Span(0, 3, "red"), Span(6, 9, "blue")] def test_trim_spans(): text = Text("Hello") text._spans[:] = [Span(0, 3, "red"), Span(3, 6, "green"), Span(6, 9, "blue")] text._trim_spans() assert text._spans == [Span(0, 3, "red"), Span(3, 5, "green")] def test_pad_left(): text = Text("foo") text.pad_left(3, "X") assert str(text) == "XXXfoo" def test_pad_right(): text = Text("foo") text.pad_right(3, "X") assert str(text) == "fooXXX" def test_append(): text = Text("foo") text.append("bar") assert str(text) == "foobar" text.append(Text("baz", "bold")) assert str(text) == "foobarbaz" assert text._spans == [Span(6, 9, "bold")] with pytest.raises(ValueError): text.append(Text("foo"), "bar") with pytest.raises(TypeError): text.append(1) def test_append_text(): text = Text("foo") text.append_text(Text("bar", style="bold")) assert str(text) == "foobar" assert text._spans == [Span(3, 6, "bold")] def test_end(): console = Console(width=20, file=StringIO()) text = Group(Text.from_markup("foo", end=" "), Text.from_markup("bar")) console.print(text) assert console.file.getvalue() == "foo bar\n" def test_split(): text = Text() text.append("foo", "red") text.append("\n") text.append("bar", "green") text.append("\n") line1 = Text() line1.append("foo", "red") line2 = Text() line2.append("bar", "green") split = text.split("\n") assert len(split) == 2 assert split[0] == line1 assert split[1] == line2 assert list(Text("foo").split("\n")) == [Text("foo")] def test_split_spans(): text = Text.from_markup("[red]Hello\n[b]World") lines = text.split("\n") assert lines[0].plain == "Hello" assert lines[1].plain == "World" assert lines[0].spans == [Span(0, 5, "red")] assert lines[1].spans == [Span(0, 5, "red"), Span(0, 5, "bold")] def test_divide(): lines = Text("foo").divide([]) assert len(lines) == 1 assert lines[0] == Text("foo") text = Text() text.append("foo", "bold") lines = text.divide([1, 2]) assert len(lines) == 3 assert str(lines[0]) == "f" assert str(lines[1]) == "o" assert str(lines[2]) == "o" assert lines[0]._spans == [Span(0, 1, "bold")] assert lines[1]._spans == [Span(0, 1, "bold")] assert lines[2]._spans == [Span(0, 1, "bold")] text = Text() text.append("foo", "red") text.append("bar", "green") text.append("baz", "blue") lines = text.divide([8]) assert len(lines) == 2 assert str(lines[0]) == "foobarba" assert str(lines[1]) == "z" assert lines[0]._spans == [ Span(0, 3, "red"), Span(3, 6, "green"), Span(6, 8, "blue"), ] assert lines[1]._spans == [Span(0, 1, "blue")] lines = text.divide([1]) assert len(lines) == 2 assert str(lines[0]) == "f" assert str(lines[1]) == "oobarbaz" assert lines[0]._spans == [Span(0, 1, "red")] assert lines[1]._spans == [ Span(0, 2, "red"), Span(2, 5, "green"), Span(5, 8, "blue"), ] def test_right_crop(): text = Text() text.append("foobar", "red") text.right_crop(3) assert str(text) == "foo" assert text._spans == [Span(0, 3, "red")] def test_wrap_3(): text = Text("foo bar baz") lines = text.wrap(Console(), 3) print(repr(lines)) assert len(lines) == 3 assert lines[0] == Text("foo") assert lines[1] == Text("bar") assert lines[2] == Text("baz") def test_wrap_4(): text = Text("foo bar baz", justify="left") lines = text.wrap(Console(), 4) assert len(lines) == 3 assert lines[0] == Text("foo ") assert lines[1] == Text("bar ") assert lines[2] == Text("baz ") def test_wrap_wrapped_word_length_greater_than_available_width(): text = Text("1234 12345678") lines = text.wrap(Console(), 7) assert lines._lines == [ Text("1234 "), Text("1234567"), Text("8"), ] def test_wrap_cjk(): text = Text("わさび") lines = text.wrap(Console(), 4) assert lines._lines == [ Text("わさ"), Text("び"), ] def test_wrap_cjk_width_mid_character(): text = Text("わさび") lines = text.wrap(Console(), 3) assert lines._lines == [ Text("わ"), Text("さ"), Text("び"), ] def test_wrap_cjk_mixed(): """Regression test covering https://github.com/Textualize/rich/issues/3176 and https://github.com/Textualize/textual/issues/3567 - double width characters could result in text going missing when wrapping.""" text = Text("123ありがとうございました") console = Console(width=20) # let's ensure the width passed to wrap() wins. wrapped_lines = text.wrap(console, width=8) with console.capture() as capture: console.print(wrapped_lines) assert capture.get() == "123あり\nがとうご\nざいまし\nた\n" def test_wrap_long(): text = Text("abracadabra", justify="left") lines = text.wrap(Console(), 4) assert len(lines) == 3 assert lines[0] == Text("abra") assert lines[1] == Text("cada") assert lines[2] == Text("bra ") def test_wrap_overflow(): text = Text("Some more words") lines = text.wrap(Console(), 4, overflow="ellipsis") assert (len(lines)) == 3 assert lines[0] == Text("Some") assert lines[1] == Text("more") assert lines[2] == Text("wor…") def test_wrap_overflow_long(): text = Text("bigword" * 10) lines = text.wrap(Console(), 4, overflow="ellipsis") assert len(lines) == 1 assert lines[0] == Text("big…") def test_wrap_long_words(): text = Text("XX 12345678912") lines = text.wrap(Console(), 4) assert lines._lines == [ Text("XX "), Text("1234"), Text("5678"), Text("912"), ] def test_wrap_long_words_2(): # https://github.com/Textualize/rich/issues/2273 text = Text("Hello, World...123") lines = text.wrap(Console(), 10) assert lines._lines == [ Text("Hello, "), Text("World...12"), Text("3"), ] def test_wrap_long_words_followed_by_other_words(): """After folding a word across multiple lines, we should continue from the next word immediately after the folded word (don't take a newline following completion of the folded word).""" text = Text("123 12345678 123 123") lines = text.wrap(Console(), 6) assert lines._lines == [ Text("123 "), Text("123456"), Text("78 123"), Text("123"), ] def test_wrap_long_word_preceeded_by_word_of_full_line_length(): """The width of the first word is the same as the available width. Ensures that folding works correctly when there's no space available on the current line.""" text = Text("123456 12345678 123 123") lines = text.wrap(Console(), 6) assert lines._lines == [ Text("123456"), Text("123456"), Text("78 123"), Text("123"), ] def test_wrap_multiple_consecutive_spaces(): """Adding multiple consecutive spaces at the end of a line does not impact the location at which a break will be added during the process of wrapping.""" text = Text("123456 12345678 123 123") lines = text.wrap(Console(), 6) assert lines._lines == [ Text("123456"), Text("123456"), Text("78 123"), Text("123"), ] def test_wrap_long_words_justify_left(): text = Text("X 123456789", justify="left") lines = text.wrap(Console(), 4) assert len(lines) == 4 assert lines[0] == Text("X ") assert lines[1] == Text("1234") assert lines[2] == Text("5678") assert lines[3] == Text("9 ") def test_wrap_leading_and_trailing_whitespace(): text = Text(" 123 456 789 ") lines = text.wrap(Console(), 4) assert lines._lines == [ Text(" 1"), Text("23 "), Text("456 "), Text("789 "), ] def test_no_wrap_no_crop(): text = Text("Hello World!" * 3) console = Console(width=20, file=StringIO()) console.print(text, no_wrap=True) console.print(text, no_wrap=True, crop=False, overflow="ignore") print(repr(console.file.getvalue())) assert ( console.file.getvalue() == "Hello World!Hello Wo\nHello World!Hello World!Hello World!\n" ) def test_fit(): text = Text("Hello\nWorld") lines = text.fit(3) assert str(lines[0]) == "Hel" assert str(lines[1]) == "Wor" def test_wrap_tabs(): text = Text("foo\tbar", justify="left") lines = text.wrap(Console(), 4) assert len(lines) == 2 assert str(lines[0]) == "foo " assert str(lines[1]) == "bar " def test_render(): console = Console(width=15, record=True) text = Text.from_markup( "[u][b]Where[/b] there is a [i]Will[/i], there is a Way.[/u]" ) console.print(text) output = console.export_text(styles=True) expected = "\x1b[1;4mWhere\x1b[0m\x1b[4m there is \x1b[0m\n\x1b[4ma \x1b[0m\x1b[3;4mWill\x1b[0m\x1b[4m, there \x1b[0m\n\x1b[4mis a Way.\x1b[0m\n" assert output == expected def test_render_simple(): console = Console(width=80) console.begin_capture() console.print(Text("foo")) result = console.end_capture() assert result == "foo\n" @pytest.mark.parametrize( "print_text,result", [ (("."), ".\n"), ((".", "."), ". .\n"), (("Hello", "World", "!"), "Hello World !\n"), ], ) def test_print(print_text, result): console = Console(record=True) console.print(*print_text) assert console.export_text(styles=False) == result @pytest.mark.parametrize( "print_text,result", [ (("."), ".X"), ((".", "."), "..X"), (("Hello", "World", "!"), "HelloWorld!X"), ], ) def test_print_sep_end(print_text, result): console = Console(record=True, file=StringIO()) console.print(*print_text, sep="", end="X") assert console.file.getvalue() == result def test_tabs_to_spaces(): text = Text("\tHello\tWorld", tab_size=8) text.expand_tabs() assert text.plain == " Hello World" text = Text("\tHello\tWorld", tab_size=4) text.expand_tabs() assert text.plain == " Hello World" text = Text(".\t..\t...\t....\t", tab_size=4) text.expand_tabs() assert text.plain == ". .. ... .... " text = Text("No Tabs") text.expand_tabs() assert text.plain == "No Tabs" text = Text("No Tabs", style="bold") text.expand_tabs() assert text.plain == "No Tabs" assert text.style == "bold" @pytest.mark.parametrize( "markup,tab_size,expected_text,expected_spans", [ ("", 4, "", []), ("\t", 4, " ", []), ("\tbar", 4, " bar", []), ("foo\tbar", 4, "foo bar", []), ("foo\nbar\nbaz", 4, "foo\nbar\nbaz", []), ( "[bold]foo\tbar", 4, "foo bar", [ Span(0, 4, "bold"), Span(4, 7, "bold"), ], ), ( "[bold]\tbar", 4, " bar", [ Span(0, 4, "bold"), Span(4, 7, "bold"), ], ), ( "\t[bold]bar", 4, " bar", [ Span(4, 7, "bold"), ], ), ( "[red]foo\tbar\n[green]egg\tbaz", 8, "foo bar\negg baz", [ Span(0, 8, "red"), Span(8, 12, "red"), Span(12, 20, "red"), Span(12, 20, "green"), Span(20, 23, "red"), Span(20, 23, "green"), ], ), ( "[bold]X\tY", 8, "X Y", [ Span(0, 8, "bold"), Span(8, 9, "bold"), ], ), ( "[bold]💩\t💩", 8, "💩 💩", [ Span(0, 7, "bold"), Span(7, 8, "bold"), ], ), ( "[bold]💩💩💩💩\t💩", 8, "💩💩💩💩 💩", [ Span(0, 12, "bold"), Span(12, 13, "bold"), ], ), ], ) def test_tabs_to_spaces_spans( markup: str, tab_size: int, expected_text: str, expected_spans: List[Span] ): """Test spans are correct after expand_tabs""" text = Text.from_markup(markup) text.expand_tabs(tab_size) print(text._spans) assert text.plain == expected_text assert text._spans == expected_spans def test_markup_switch(): """Test markup can be disabled.""" console = Console(file=StringIO(), markup=False) console.print("[bold]foo[/bold]") assert console.file.getvalue() == "[bold]foo[/bold]\n" def test_emoji(): """Test printing emoji codes.""" console = Console(file=StringIO()) console.print(":+1:") assert console.file.getvalue() == "👍\n" def test_emoji_switch(): """Test emoji can be disabled.""" console = Console(file=StringIO(), emoji=False) console.print(":+1:") assert console.file.getvalue() == ":+1:\n" def test_assemble(): text = Text.assemble("foo", ("bar", "bold")) assert str(text) == "foobar" assert text._spans == [Span(3, 6, "bold")] def test_assemble_meta(): text = Text.assemble("foo", ("bar", "bold"), meta={"foo": "bar"}) assert str(text) == "foobar" spans = text._spans expected = [Span(3, 6, "bold"), Span(0, 6, Style(meta={"foo": "bar"}))] assert spans == expected console = Console() assert text.get_style_at_offset(console, 0).meta == {"foo": "bar"} def test_styled(): text = Text.styled("foo", "bold red") assert text.style == "" assert str(text) == "foo" assert text._spans == [Span(0, 3, "bold red")] def test_strip_control_codes(): text = Text("foo\rbar") assert str(text) == "foobar" text.append("\x08") assert str(text) == "foobar" def test_get_style_at_offset(): console = Console() text = Text.from_markup("Hello [b]World[/b]") assert text.get_style_at_offset(console, 0) == Style() assert text.get_style_at_offset(console, 6) == Style(bold=True) @pytest.mark.parametrize( "input, count, expected", [ ("Hello", 10, "Hello"), ("Hello", 5, "Hello"), ("Hello", 4, "Hel…"), ("Hello", 3, "He…"), ("Hello", 2, "H…"), ("Hello", 1, "…"), ], ) def test_truncate_ellipsis(input, count, expected): text = Text(input) text.truncate(count, overflow="ellipsis") assert text.plain == expected @pytest.mark.parametrize( "input, count, expected", [ ("Hello", 5, "Hello"), ("Hello", 10, "Hello "), ("Hello", 3, "He…"), ], ) def test_truncate_ellipsis_pad(input, count, expected): text = Text(input) text.truncate(count, overflow="ellipsis", pad=True) assert text.plain == expected def test_pad(): text = Text("foo") text.pad(2) assert text.plain == " foo " def test_align_left(): text = Text("foo") text.align("left", 10) assert text.plain == "foo " def test_align_right(): text = Text("foo") text.align("right", 10) assert text.plain == " foo" def test_align_center(): text = Text("foo") text.align("center", 10) assert text.plain == " foo " def test_detect_indentation(): text = """\ foo bar """ assert Text(text).detect_indentation() == 4 text = """\ foo bar baz """ assert Text(text).detect_indentation() == 2 assert Text("").detect_indentation() == 1 assert Text(" ").detect_indentation() == 1 def test_indentation_guides(): text = Text( """\ for a in range(10): print(a) foo = [ 1, { 2 } ] """ ) result = text.with_indent_guides() print(result.plain) print(repr(result.plain)) expected = "for a in range(10):\n│ print(a)\n\nfoo = [\n│ 1,\n│ {\n│ │ 2\n│ }\n]\n\n" assert result.plain == expected def test_slice(): text = Text.from_markup("[red]foo [bold]bar[/red] baz[/bold]") assert text[0] == Text("f", spans=[Span(0, 1, "red")]) assert text[4] == Text("b", spans=[Span(0, 1, "red"), Span(0, 1, "bold")]) assert text[:3] == Text("foo", spans=[Span(0, 3, "red")]) assert text[:4] == Text("foo ", spans=[Span(0, 4, "red")]) assert text[:5] == Text("foo b", spans=[Span(0, 5, "red"), Span(4, 5, "bold")]) assert text[4:] == Text("bar baz", spans=[Span(0, 3, "red"), Span(0, 7, "bold")]) with pytest.raises(TypeError): text[::-1] def test_wrap_invalid_style(): # https://github.com/textualize/rich/issues/987 console = Console(width=100, color_system="truecolor") a = "[#######.................] xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx [#######.................]" console.print(a, justify="full") def test_apply_meta(): text = Text("foobar") text.apply_meta({"foo": "bar"}, 1, 3) console = Console() assert text.get_style_at_offset(console, 0).meta == {} assert text.get_style_at_offset(console, 1).meta == {"foo": "bar"} assert text.get_style_at_offset(console, 2).meta == {"foo": "bar"} assert text.get_style_at_offset(console, 3).meta == {} def test_on(): console = Console() text = Text("foo") text.on({"foo": "bar"}, click="CLICK") expected = {"foo": "bar", "@click": "CLICK"} assert text.get_style_at_offset(console, 0).meta == expected assert text.get_style_at_offset(console, 1).meta == expected assert text.get_style_at_offset(console, 2).meta == expected def test_markup_property(): assert Text("").markup == "" assert Text("foo").markup == "foo" assert Text("foo", style="bold").markup == "[bold]foo[/bold]" assert Text.from_markup("foo [red]bar[/red]").markup == "foo [red]bar[/red]" assert ( Text.from_markup("foo [red]bar[/red]", style="bold").markup == "[bold]foo [red]bar[/red][/bold]" ) assert ( Text.from_markup("[bold]foo [italic]bar[/bold] baz[/italic]").markup == "[bold]foo [italic]bar[/bold] baz[/italic]" ) assert Text("[bold]foo").markup == "\\[bold]foo" def test_extend_style(): text = Text.from_markup("[red]foo[/red] [bold]bar") text.extend_style(0) assert text.plain == "foo bar" assert text.spans == [Span(0, 3, "red"), Span(4, 7, "bold")] text.extend_style(-1) assert text.plain == "foo bar" assert text.spans == [Span(0, 3, "red"), Span(4, 7, "bold")] text.extend_style(2) assert text.plain == "foo bar " assert text.spans == [Span(0, 3, "red"), Span(4, 9, "bold")] def test_append_tokens() -> None: """Regression test for https://github.com/Textualize/rich/issues/3014""" console = Console() t = Text().append_tokens( [ ( "long text that will be wrapped with a control code \r\n", "red", ), ] ) with console.capture() as capture: console.print(t, width=40) output = capture.get() print(repr(output)) assert output == "long text that will be wrapped with a \ncontrol code \n\n" def test_append_loop_regression() -> None: """Regression text for https://github.com/Textualize/rich/issues/3479""" a = Text("one", "blue") a.append(a) assert a.plain == "oneone" b = Text("two", "blue") b.append_text(b) assert b.plain == "twotwo"
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_bar.py
tests/test_bar.py
from rich.console import Console from rich.progress_bar import ProgressBar from rich.segment import Segment from rich.style import Style from .render import render def test_init(): bar = ProgressBar(completed=50) repr(bar) assert bar.percentage_completed == 50.0 def test_update(): bar = ProgressBar() assert bar.completed == 0 assert bar.total == 100 bar.update(10, 20) assert bar.completed == 10 assert bar.total == 20 assert bar.percentage_completed == 50 bar.update(100) assert bar.percentage_completed == 100 expected = [ "\x1b[38;2;249;38;114m━━━━━\x1b[0m\x1b[38;2;249;38;114m╸\x1b[0m\x1b[38;5;237m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\x1b[0m", "\x1b[38;2;249;38;114m━━━━━━\x1b[0m\x1b[38;5;237m╺\x1b[0m\x1b[38;5;237m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\x1b[0m", ] def test_render(): bar = ProgressBar(completed=11, width=50) bar_render = render(bar) assert bar_render == expected[0] bar.update(completed=12) bar_render = render(bar) assert bar_render == expected[1] def test_measure(): console = Console(width=120) bar = ProgressBar() measurement = bar.__rich_measure__(console, console.options) assert measurement.minimum == 4 assert measurement.maximum == 120 def test_zero_total(): # Shouldn't throw zero division error bar = ProgressBar(total=0) render(bar) def test_pulse(): bar = ProgressBar(pulse=True, animation_time=10) bar_render = render(bar) print(repr(bar_render)) expected = "\x1b[38;2;249;38;114m━\x1b[0m\x1b[38;2;244;38;112m━\x1b[0m\x1b[38;2;230;39;108m━\x1b[0m\x1b[38;2;209;42;102m━\x1b[0m\x1b[38;2;183;44;94m━\x1b[0m\x1b[38;2;153;48;86m━\x1b[0m\x1b[38;2;123;51;77m━\x1b[0m\x1b[38;2;97;53;69m━\x1b[0m\x1b[38;2;76;56;63m━\x1b[0m\x1b[38;2;62;57;59m━\x1b[0m\x1b[38;2;58;58;58m━\x1b[0m\x1b[38;2;62;57;59m━\x1b[0m\x1b[38;2;76;56;63m━\x1b[0m\x1b[38;2;97;53;69m━\x1b[0m\x1b[38;2;123;51;77m━\x1b[0m\x1b[38;2;153;48;86m━\x1b[0m\x1b[38;2;183;44;94m━\x1b[0m\x1b[38;2;209;42;102m━\x1b[0m\x1b[38;2;230;39;108m━\x1b[0m\x1b[38;2;244;38;112m━\x1b[0m\x1b[38;2;249;38;114m━\x1b[0m\x1b[38;2;244;38;112m━\x1b[0m\x1b[38;2;230;39;108m━\x1b[0m\x1b[38;2;209;42;102m━\x1b[0m\x1b[38;2;183;44;94m━\x1b[0m\x1b[38;2;153;48;86m━\x1b[0m\x1b[38;2;123;51;77m━\x1b[0m\x1b[38;2;97;53;69m━\x1b[0m\x1b[38;2;76;56;63m━\x1b[0m\x1b[38;2;62;57;59m━\x1b[0m\x1b[38;2;58;58;58m━\x1b[0m\x1b[38;2;62;57;59m━\x1b[0m\x1b[38;2;76;56;63m━\x1b[0m\x1b[38;2;97;53;69m━\x1b[0m\x1b[38;2;123;51;77m━\x1b[0m\x1b[38;2;153;48;86m━\x1b[0m\x1b[38;2;183;44;94m━\x1b[0m\x1b[38;2;209;42;102m━\x1b[0m\x1b[38;2;230;39;108m━\x1b[0m\x1b[38;2;244;38;112m━\x1b[0m\x1b[38;2;249;38;114m━\x1b[0m\x1b[38;2;244;38;112m━\x1b[0m\x1b[38;2;230;39;108m━\x1b[0m\x1b[38;2;209;42;102m━\x1b[0m\x1b[38;2;183;44;94m━\x1b[0m\x1b[38;2;153;48;86m━\x1b[0m\x1b[38;2;123;51;77m━\x1b[0m\x1b[38;2;97;53;69m━\x1b[0m\x1b[38;2;76;56;63m━\x1b[0m\x1b[38;2;62;57;59m━\x1b[0m\x1b[38;2;58;58;58m━\x1b[0m\x1b[38;2;62;57;59m━\x1b[0m\x1b[38;2;76;56;63m━\x1b[0m\x1b[38;2;97;53;69m━\x1b[0m\x1b[38;2;123;51;77m━\x1b[0m\x1b[38;2;153;48;86m━\x1b[0m\x1b[38;2;183;44;94m━\x1b[0m\x1b[38;2;209;42;102m━\x1b[0m\x1b[38;2;230;39;108m━\x1b[0m\x1b[38;2;244;38;112m━\x1b[0m\x1b[38;2;249;38;114m━\x1b[0m\x1b[38;2;244;38;112m━\x1b[0m\x1b[38;2;230;39;108m━\x1b[0m\x1b[38;2;209;42;102m━\x1b[0m\x1b[38;2;183;44;94m━\x1b[0m\x1b[38;2;153;48;86m━\x1b[0m\x1b[38;2;123;51;77m━\x1b[0m\x1b[38;2;97;53;69m━\x1b[0m\x1b[38;2;76;56;63m━\x1b[0m\x1b[38;2;62;57;59m━\x1b[0m\x1b[38;2;58;58;58m━\x1b[0m\x1b[38;2;62;57;59m━\x1b[0m\x1b[38;2;76;56;63m━\x1b[0m\x1b[38;2;97;53;69m━\x1b[0m\x1b[38;2;123;51;77m━\x1b[0m\x1b[38;2;153;48;86m━\x1b[0m\x1b[38;2;183;44;94m━\x1b[0m\x1b[38;2;209;42;102m━\x1b[0m\x1b[38;2;230;39;108m━\x1b[0m\x1b[38;2;244;38;112m━\x1b[0m\x1b[38;2;249;38;114m━\x1b[0m\x1b[38;2;244;38;112m━\x1b[0m\x1b[38;2;230;39;108m━\x1b[0m\x1b[38;2;209;42;102m━\x1b[0m\x1b[38;2;183;44;94m━\x1b[0m\x1b[38;2;153;48;86m━\x1b[0m\x1b[38;2;123;51;77m━\x1b[0m\x1b[38;2;97;53;69m━\x1b[0m\x1b[38;2;76;56;63m━\x1b[0m\x1b[38;2;62;57;59m━\x1b[0m\x1b[38;2;58;58;58m━\x1b[0m\x1b[38;2;62;57;59m━\x1b[0m\x1b[38;2;76;56;63m━\x1b[0m\x1b[38;2;97;53;69m━\x1b[0m\x1b[38;2;123;51;77m━\x1b[0m\x1b[38;2;153;48;86m━\x1b[0m\x1b[38;2;183;44;94m━\x1b[0m\x1b[38;2;209;42;102m━\x1b[0m\x1b[38;2;230;39;108m━\x1b[0m\x1b[38;2;244;38;112m━\x1b[0m" assert bar_render == expected def test_get_pulse_segments(): bar = ProgressBar() segments = bar._get_pulse_segments( Style.parse("red"), Style.parse("yellow"), None, False, False ) print(repr(segments)) expected = [ Segment("━", Style.parse("red")), Segment("━", Style.parse("red")), Segment("━", Style.parse("red")), Segment("━", Style.parse("red")), Segment("━", Style.parse("red")), Segment("━", Style.parse("red")), Segment("━", Style.parse("red")), Segment("━", Style.parse("red")), Segment("━", Style.parse("red")), Segment("━", Style.parse("red")), Segment("━", Style.parse("yellow")), Segment("━", Style.parse("yellow")), Segment("━", Style.parse("yellow")), Segment("━", Style.parse("yellow")), Segment("━", Style.parse("yellow")), Segment("━", Style.parse("yellow")), Segment("━", Style.parse("yellow")), Segment("━", Style.parse("yellow")), Segment("━", Style.parse("yellow")), Segment("━", Style.parse("yellow")), ] assert segments == expected if __name__ == "__main__": bar = ProgressBar(completed=11, width=50) bar_render = render(bar) print(repr(bar_render)) bar.update(completed=12) bar_render = render(bar) print(repr(bar_render))
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_padding.py
tests/test_padding.py
import pytest from rich.padding import Padding from rich.console import Console, ConsoleDimensions, ConsoleOptions from rich.style import Style from rich.segment import Segment def test_repr(): padding = Padding("foo", (1, 2)) assert isinstance(repr(padding), str) def test_indent(): indent_result = Padding.indent("test", 4) assert indent_result.top == 0 assert indent_result.right == 0 assert indent_result.bottom == 0 assert indent_result.left == 4 def test_unpack(): assert Padding.unpack(3) == (3, 3, 3, 3) assert Padding.unpack((3,)) == (3, 3, 3, 3) assert Padding.unpack((3, 4)) == (3, 4, 3, 4) assert Padding.unpack((3, 4, 5, 6)) == (3, 4, 5, 6) with pytest.raises(ValueError): Padding.unpack((1, 2, 3)) def test_expand_false(): console = Console(width=100, color_system=None) console.begin_capture() console.print(Padding("foo", 1, expand=False)) assert console.end_capture() == " \n foo \n \n" def test_rich_console(): renderable = "test renderable" style = Style(color="red") options = ConsoleOptions( ConsoleDimensions(80, 25), max_height=25, legacy_windows=False, min_width=10, max_width=20, is_terminal=False, encoding="utf-8", ) expected_outputs = [ Segment(renderable, style=style), Segment(" " * (20 - len(renderable)), style=style), Segment("\n", style=None), ] padding_generator = Padding(renderable, style=style).__rich_console__( Console(), options ) for output, expected in zip(padding_generator, expected_outputs): assert output == expected
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_ansi.py
tests/test_ansi.py
import pytest from rich.ansi import AnsiDecoder from rich.console import Console from rich.style import Style from rich.text import Span, Text def test_decode(): console = Console( force_terminal=True, legacy_windows=False, color_system="truecolor" ) console.begin_capture() console.print("Hello") console.print("[b]foo[/b]") console.print("[link http://example.org]bar") console.print("[#ff0000 on color(200)]red") console.print("[color(200) on #ff0000]red") terminal_codes = console.end_capture() decoder = AnsiDecoder() lines = list(decoder.decode(terminal_codes)) expected = [ Text("Hello"), Text("foo", spans=[Span(0, 3, Style.parse("bold"))]), Text("bar", spans=[Span(0, 3, Style.parse("link http://example.org"))]), Text("red", spans=[Span(0, 3, Style.parse("#ff0000 on color(200)"))]), Text("red", spans=[Span(0, 3, Style.parse("color(200) on #ff0000"))]), ] assert lines == expected def test_decode_example(): ansi_bytes = b"\x1b[01m\x1b[KC:\\Users\\stefa\\AppData\\Local\\Temp\\tmp3ydingba:\x1b[m\x1b[K In function '\x1b[01m\x1b[Kmain\x1b[m\x1b[K':\n\x1b[01m\x1b[KC:\\Users\\stefa\\AppData\\Local\\Temp\\tmp3ydingba:3:5:\x1b[m\x1b[K \x1b[01;35m\x1b[Kwarning: \x1b[m\x1b[Kunused variable '\x1b[01m\x1b[Ka\x1b[m\x1b[K' [\x1b[01;35m\x1b[K-Wunused-variable\x1b[m\x1b[K]\n 3 | int \x1b[01;35m\x1b[Ka\x1b[m\x1b[K=1;\n | \x1b[01;35m\x1b[K^\x1b[m\x1b[K\n" ansi_text = ansi_bytes.decode("utf-8") text = Text.from_ansi(ansi_text) console = Console( force_terminal=True, legacy_windows=False, color_system="truecolor" ) with console.capture() as capture: console.print(text) result = capture.get() print(repr(result)) expected = "\x1b[1mC:\\Users\\stefa\\AppData\\Local\\Temp\\tmp3ydingba:\x1b[0m In function '\x1b[1mmain\x1b[0m':\n\x1b[1mC:\\Users\\stefa\\AppData\\Local\\Temp\\tmp3ydingba:3:5:\x1b[0m \x1b[1;35mwarning: \x1b[0munused variable '\x1b[1ma\x1b[0m' \n[\x1b[1;35m-Wunused-variable\x1b[0m]\n 3 | int \x1b[1;35ma\x1b[0m=1;\n | \x1b[1;35m^\x1b[0m\n" assert result == expected @pytest.mark.parametrize( "ansi_bytes, expected_text", [ # https://github.com/Textualize/rich/issues/2688 ( b"\x1b[31mFound 4 errors in 2 files (checked 18 source files)\x1b(B\x1b[m\n", "Found 4 errors in 2 files (checked 18 source files)", ), # https://mail.python.org/pipermail/python-list/2007-December/424756.html (b"Hallo", "Hallo"), (b"\x1b(BHallo", "Hallo"), (b"\x1b(JHallo", "Hallo"), (b"\x1b(BHal\x1b(Jlo", "Hallo"), ], ) def test_decode_issue_2688(ansi_bytes, expected_text): text = Text.from_ansi(ansi_bytes.decode()) assert str(text) == expected_text @pytest.mark.parametrize("code", [*"0123456789:;<=>?"]) def test_strip_private_escape_sequences(code): text = Text.from_ansi(f"\x1b{code}x") console = Console(force_terminal=True) with console.capture() as capture: console.print(text) expected = "x\n" assert capture.get() == expected
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/__init__.py
tests/__init__.py
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_repr.py
tests/test_repr.py
from typing import Optional import pytest import rich.repr from rich.console import Console from inspect import Parameter @rich.repr.auto class Foo: def __init__(self, foo: str, bar: Optional[int] = None, egg: int = 1): self.foo = foo self.bar = bar self.egg = egg def __rich_repr__(self): yield self.foo yield None, self.foo, yield "bar", self.bar, None yield "egg", self.egg @rich.repr.auto class Egg: def __init__(self, foo: str, bar: Optional[int] = None, egg: int = 1): self.foo = foo self.bar = bar self.egg = egg @rich.repr.auto class BrokenEgg: def __init__(self, foo: str, *, bar: Optional[int] = None, egg: int = 1): self.foo = foo self.fubar = bar self.egg = egg @rich.repr.auto(angular=True) class AngularEgg: def __init__(self, foo: str, *, bar: Optional[int] = None, egg: int = 1): self.foo = foo self.bar = bar self.egg = egg @rich.repr.auto class Bar(Foo): def __rich_repr__(self): yield (self.foo,) yield None, self.foo, yield "bar", self.bar, None yield "egg", self.egg __rich_repr__.angular = True class StupidClass: def __init__(self, a): self.a = a def __eq__(self, other) -> bool: if other is Parameter.empty: return True try: return self.a == other.a except Exception: return False def __ne__(self, other: object) -> bool: return not self.__eq__(other) class NotStupid: pass @rich.repr.auto class Bird: def __init__( self, name, eats, fly=True, another=StupidClass(2), extinct=NotStupid() ): self.name = name self.eats = eats self.fly = fly self.another = another self.extinct = extinct def test_rich_repr() -> None: assert (repr(Foo("hello"))) == "Foo('hello', 'hello', egg=1)" assert (repr(Foo("hello", bar=3))) == "Foo('hello', 'hello', bar=3, egg=1)" def test_rich_repr_positional_only() -> None: _locals = locals().copy() exec( """\ @rich.repr.auto class PosOnly: def __init__(self, foo, /): self.foo = 1 """, globals(), _locals, ) p = _locals["PosOnly"](1) assert repr(p) == "PosOnly(1)" def test_rich_angular() -> None: assert (repr(Bar("hello"))) == "<Bar 'hello' 'hello' egg=1>" assert (repr(Bar("hello", bar=3))) == "<Bar 'hello' 'hello' bar=3 egg=1>" def test_rich_repr_auto() -> None: assert repr(Egg("hello", egg=2)) == "Egg('hello', egg=2)" stupid_class = StupidClass(9) not_stupid = NotStupid() assert ( repr(Bird("penguin", ["fish"], another=stupid_class, extinct=not_stupid)) == f"Bird('penguin', ['fish'], another={repr(stupid_class)}, extinct={repr(not_stupid)})" ) def test_rich_repr_auto_angular() -> None: assert repr(AngularEgg("hello", egg=2)) == "<AngularEgg 'hello' egg=2>" def test_broken_egg() -> None: with pytest.raises(rich.repr.ReprError): repr(BrokenEgg("foo")) def test_rich_pretty() -> None: console = Console() with console.capture() as capture: console.print(Foo("hello", bar=3)) result = capture.get() expected = "Foo('hello', 'hello', bar=3, egg=1)\n" assert result == expected def test_rich_pretty_angular() -> None: console = Console() with console.capture() as capture: console.print(Bar("hello", bar=3)) result = capture.get() expected = "<Bar 'hello' 'hello' bar=3 egg=1>\n" assert result == expected
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_block_bar.py
tests/test_block_bar.py
from rich.bar import Bar from rich.console import Console from .render import render expected = [ "\x1b[39;49m ▐█████████████████████████ \x1b[0m\n", "\x1b[39;49m ██████████████████████▌ \x1b[0m\n", "\x1b[39;49m \x1b[0m\n", ] def test_repr(): bar = Bar(size=100, begin=11, end=62, width=50) assert repr(bar) == "Bar(100, 11, 62)" def test_render(): bar = Bar(size=100, begin=11, end=62, width=50) bar_render = render(bar) assert bar_render == expected[0] bar = Bar(size=100, begin=12, end=57, width=50) bar_render = render(bar) assert bar_render == expected[1] # begin after end bar = Bar(size=100, begin=60, end=40, width=50) bar_render = render(bar) assert bar_render == expected[2] def test_measure(): console = Console(width=120) bar = Bar(size=100, begin=11, end=62) measurement = bar.__rich_measure__(console, console.options) assert measurement.minimum == 4 assert measurement.maximum == 120 def test_zero_total(): # Shouldn't throw zero division error bar = Bar(size=0, begin=0, end=0) render(bar) if __name__ == "__main__": bar = Bar(size=100, begin=11, end=62, width=50) bar_render = render(bar) print(repr(bar_render)) bar = Bar(size=100, begin=12, end=57, width=50) bar_render = render(bar) print(repr(bar_render)) bar = Bar(size=100, begin=60, end=40, width=50) bar_render = render(bar) print(repr(bar_render))
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_filesize.py
tests/test_filesize.py
from rich import filesize def test_traditional(): assert filesize.decimal(0) == "0 bytes" assert filesize.decimal(1) == "1 byte" assert filesize.decimal(2) == "2 bytes" assert filesize.decimal(1000) == "1.0 kB" assert filesize.decimal(1.5 * 1000 * 1000) == "1.5 MB" assert filesize.decimal(0, precision=2) == "0 bytes" assert filesize.decimal(1111, precision=0) == "1 kB" assert filesize.decimal(1111, precision=1) == "1.1 kB" assert filesize.decimal(1111, precision=2) == "1.11 kB" assert filesize.decimal(1111, separator="") == "1.1kB" def test_pick_unit_and_suffix(): units = ["bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"] assert filesize.pick_unit_and_suffix(50, units, 1024) == (1, "bytes") assert filesize.pick_unit_and_suffix(2048, units, 1024) == (1024, "KB")
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_card.py
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}")
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_ratio.py
tests/test_ratio.py
import pytest from typing import NamedTuple, Optional from rich._ratio import ratio_reduce, ratio_resolve class Edge(NamedTuple): size: Optional[int] = None ratio: int = 1 minimum_size: int = 1 @pytest.mark.parametrize( "total,ratios,maximums,values,result", [ (20, [2, 4], [20, 20], [5, 5], [-2, -8]), (20, [2, 4], [1, 1], [5, 5], [4, 4]), (20, [2, 4], [1, 1], [2, 2], [1, 1]), (3, [2, 4], [3, 3], [2, 2], [1, 0]), (3, [2, 4], [3, 3], [0, 0], [-1, -2]), (3, [0, 0], [3, 3], [4, 4], [4, 4]), ], ) def test_ratio_reduce(total, ratios, maximums, values, result): assert ratio_reduce(total, ratios, maximums, values) == result def test_ratio_resolve(): assert ratio_resolve(100, []) == [] assert ratio_resolve(100, [Edge(size=100), Edge(ratio=1)]) == [100, 1] assert ratio_resolve(100, [Edge(ratio=1)]) == [100] assert ratio_resolve(100, [Edge(ratio=1), Edge(ratio=1)]) == [50, 50] assert ratio_resolve(100, [Edge(size=20), Edge(ratio=1), Edge(ratio=1)]) == [ 20, 40, 40, ] assert ratio_resolve(100, [Edge(size=40), Edge(ratio=2), Edge(ratio=1)]) == [ 40, 40, 20, ] assert ratio_resolve( 100, [Edge(size=40), Edge(ratio=2), Edge(ratio=1, minimum_size=25)] ) == [40, 35, 25] assert ratio_resolve(100, [Edge(ratio=1), Edge(ratio=1), Edge(ratio=1)]) == [ 33, 33, 34, ] assert ratio_resolve( 50, [Edge(size=30), Edge(ratio=1, minimum_size=10), Edge(size=30)] ) == [30, 10, 30] assert ratio_resolve(110, [Edge(ratio=1), Edge(ratio=1), Edge(ratio=1)]) == [ 36, 37, 37, ]
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_styled.py
tests/test_styled.py
import io from rich.console import Console from rich.measure import Measurement from rich.styled import Styled def test_styled(): styled_foo = Styled("foo", "on red") console = Console(file=io.StringIO(), force_terminal=True, _environ={}) assert Measurement.get(console, console.options, styled_foo) == Measurement(3, 3) console.print(styled_foo) result = console.file.getvalue() expected = "\x1b[41mfoo\x1b[0m\n" assert result == expected
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_getfileno.py
tests/test_getfileno.py
from rich._fileno import get_fileno def test_get_fileno(): class FileLike: def fileno(self) -> int: return 123 assert get_fileno(FileLike()) == 123 def test_get_fileno_missing(): class FileLike: pass assert get_fileno(FileLike()) is None def test_get_fileno_broken(): class FileLike: def fileno(self) -> int: 1 / 0 return 123 assert get_fileno(FileLike()) is None
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_file_proxy.py
tests/test_file_proxy.py
import io import sys import pytest from rich.console import Console from rich.file_proxy import FileProxy def test_empty_bytes(): console = Console() file_proxy = FileProxy(console, sys.stdout) # File should raise TypeError when writing bytes with pytest.raises(TypeError): file_proxy.write(b"") # type: ignore with pytest.raises(TypeError): file_proxy.write(b"foo") # type: ignore def test_flush(): file = io.StringIO() console = Console(file=file) file_proxy = FileProxy(console, file) file_proxy.write("foo") assert file.getvalue() == "" file_proxy.flush() assert file.getvalue() == "foo\n" def test_new_lines(): file = io.StringIO() console = Console(file=file) file_proxy = FileProxy(console, file) file_proxy.write("-\n-") assert file.getvalue() == "-\n" file_proxy.flush() assert file.getvalue() == "-\n-\n"
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_protocol.py
tests/test_protocol.py
import io from rich.abc import RichRenderable from rich.console import Console from rich.panel import Panel from rich.text import Text class Foo: def __rich__(self) -> Text: return Text("Foo") def test_rich_cast(): foo = Foo() console = Console(file=io.StringIO()) console.print(foo) assert console.file.getvalue() == "Foo\n" class Fake: def __getattr__(self, name): return 12 def __repr__(self) -> str: return "Fake()" def test_rich_cast_fake(): fake = Fake() console = Console(file=io.StringIO()) console.print(fake) assert console.file.getvalue() == "Fake()\n" def test_rich_cast_container(): foo = Foo() console = Console(file=io.StringIO(), legacy_windows=False) console.print(Panel.fit(foo, padding=0)) assert console.file.getvalue() == "╭───╮\n│Foo│\n╰───╯\n" def test_abc(): foo = Foo() assert isinstance(foo, RichRenderable) assert isinstance(Text("hello"), RichRenderable) assert isinstance(Panel("hello"), RichRenderable) assert not isinstance(foo, str) assert not isinstance("foo", RichRenderable) assert not isinstance([], RichRenderable) def test_cast_deep(): class B: def __rich__(self) -> Foo: return Foo() class A: def __rich__(self) -> B: return B() console = Console(file=io.StringIO()) console.print(A()) assert console.file.getvalue() == "Foo\n" def test_cast_recursive(): class B: def __rich__(self) -> "A": return A() def __repr__(self) -> str: return "<B>" class A: def __rich__(self) -> B: return B() def __repr__(self) -> str: return "<A>" console = Console(file=io.StringIO()) console.print(A()) assert console.file.getvalue() == "<B>\n"
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_null_file.py
tests/test_null_file.py
from rich._null_file import NullFile def test_null_file(): file = NullFile() with file: assert file.write("abc") == 0 assert file.close() is None assert not file.isatty() assert file.read() == "" assert not file.readable() assert file.readline() == "" assert file.readlines() == [] assert file.seek(0, 0) == 0 assert not file.seekable() assert file.tell() == 0 assert file.truncate() == 0 assert file.writable() == False assert file.writelines([""]) is None assert next(file) == "" assert next(iter(file)) == "" assert file.fileno() == -1 assert file.flush() is None
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_jupyter.py
tests/test_jupyter.py
from rich.console import Console def test_jupyter(): console = Console(force_jupyter=True) assert console.width == 115 assert console.height == 100 assert console.color_system == "truecolor" def test_jupyter_columns_env(): console = Console(_environ={"JUPYTER_COLUMNS": "314"}, force_jupyter=True) assert console.width == 314 # width take precedence console = Console(width=40, _environ={"JUPYTER_COLUMNS": "314"}, force_jupyter=True) assert console.width == 40 # Should not fail console = Console( width=40, _environ={"JUPYTER_COLUMNS": "broken"}, force_jupyter=True ) def test_jupyter_lines_env(): console = Console(_environ={"JUPYTER_LINES": "220"}, force_jupyter=True) assert console.height == 220 # height take precedence console = Console(height=40, _environ={"JUPYTER_LINES": "220"}, force_jupyter=True) assert console.height == 40 # Should not fail console = Console( width=40, _environ={"JUPYTER_LINES": "broken"}, force_jupyter=True )
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_rule.py
tests/test_rule.py
import io import pytest from rich.console import Console from rich.rule import Rule from rich.text import Text def test_rule(): console = Console( width=16, file=io.StringIO(), force_terminal=True, legacy_windows=False, _environ={}, ) console.print(Rule()) console.print(Rule("foo")) console.rule(Text("foo", style="bold")) console.rule("foobarbazeggfoobarbazegg") expected = "\x1b[92m────────────────\x1b[0m\n" expected += "\x1b[92m───── \x1b[0mfoo\x1b[92m ──────\x1b[0m\n" expected += "\x1b[92m───── \x1b[0m\x1b[1mfoo\x1b[0m\x1b[92m ──────\x1b[0m\n" expected += "\x1b[92m─ \x1b[0mfoobarbazeg…\x1b[92m ─\x1b[0m\n" result = console.file.getvalue() assert result == expected def test_rule_error(): console = Console(width=16, file=io.StringIO(), legacy_windows=False, _environ={}) with pytest.raises(ValueError): console.rule("foo", align="foo") def test_rule_align(): console = Console(width=16, file=io.StringIO(), legacy_windows=False, _environ={}) console.rule("foo") console.rule("foo", align="left") console.rule("foo", align="center") console.rule("foo", align="right") console.rule() result = console.file.getvalue() print(repr(result)) expected = "───── foo ──────\nfoo ────────────\n───── foo ──────\n──────────── foo\n────────────────\n" assert result == expected def test_rule_cjk(): console = Console( width=16, file=io.StringIO(), force_terminal=True, color_system=None, legacy_windows=False, _environ={}, ) console.rule("欢迎!") expected = "──── 欢迎! ────\n" assert console.file.getvalue() == expected @pytest.mark.parametrize( "align,outcome", [ ("center", "───\n"), ("left", "… ─\n"), ("right", "─ …\n"), ], ) def test_rule_not_enough_space_for_title_text(align, outcome): console = Console(width=3, file=io.StringIO(), record=True) console.rule("Hello!", align=align) assert console.file.getvalue() == outcome def test_rule_center_aligned_title_not_enough_space_for_rule(): console = Console(width=4, file=io.StringIO(), record=True) console.rule("ABCD") assert console.file.getvalue() == "────\n" @pytest.mark.parametrize("align", ["left", "right"]) def test_rule_side_aligned_not_enough_space_for_rule(align): console = Console(width=2, file=io.StringIO(), record=True) console.rule("ABCD", align=align) assert console.file.getvalue() == "──\n" @pytest.mark.parametrize( "align,outcome", [ ("center", "─ … ─\n"), ("left", "AB… ─\n"), ("right", "─ AB…\n"), ], ) def test_rule_just_enough_width_available_for_title(align, outcome): console = Console(width=5, file=io.StringIO(), record=True) console.rule("ABCD", align=align) assert console.file.getvalue() == outcome def test_characters(): console = Console( width=16, file=io.StringIO(), force_terminal=True, color_system=None, legacy_windows=False, _environ={}, ) console.rule(characters="+*") console.rule("foo", characters="+*") console.print(Rule(characters=".,")) expected = "+*+*+*+*+*+*+*+*\n" expected += "+*+*+ foo +*+*+*\n" expected += ".,.,.,.,.,.,.,.,\n" assert console.file.getvalue() == expected def test_repr(): rule = Rule("foo") assert isinstance(repr(rule), str) def test_error(): with pytest.raises(ValueError): Rule(characters="")
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_emoji.py
tests/test_emoji.py
import pytest from rich.emoji import Emoji, NoEmoji from .render import render def test_no_emoji(): with pytest.raises(NoEmoji): Emoji("ambivalent_bunny") def test_str_repr(): assert str(Emoji("pile_of_poo")) == "💩" assert repr(Emoji("pile_of_poo")) == "<emoji 'pile_of_poo'>" def test_replace(): assert Emoji.replace("my code is :pile_of_poo:") == "my code is 💩" def test_render(): render_result = render(Emoji("pile_of_poo")) assert render_result == "💩" def test_variant(): print(repr(Emoji.replace(":warning:"))) assert Emoji.replace(":warning:") == "⚠" assert Emoji.replace(":warning-text:") == "⚠" + "\uFE0E" assert Emoji.replace(":warning-emoji:") == "⚠" + "\uFE0F" assert Emoji.replace(":warning-foo:") == ":warning-foo:" def test_variant_non_default(): render_result = render(Emoji("warning", variant="emoji")) assert render_result == "⚠" + "\uFE0F"
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_win32_console.py
tests/test_win32_console.py
import dataclasses import sys from unittest import mock from unittest.mock import patch import pytest from rich.style import Style if sys.platform == "win32": from rich import _win32_console from rich._win32_console import COORD, LegacyWindowsTerm, WindowsCoordinates CURSOR_X = 1 CURSOR_Y = 2 CURSOR_POSITION = WindowsCoordinates(row=CURSOR_Y, col=CURSOR_X) SCREEN_WIDTH = 20 SCREEN_HEIGHT = 30 DEFAULT_STYLE_ATTRIBUTE = 16 CURSOR_SIZE = 25 @dataclasses.dataclass class StubScreenBufferInfo: dwCursorPosition: COORD = COORD(CURSOR_X, CURSOR_Y) dwSize: COORD = COORD(SCREEN_WIDTH, SCREEN_HEIGHT) wAttributes: int = DEFAULT_STYLE_ATTRIBUTE pytestmark = pytest.mark.skipif(sys.platform != "win32", reason="windows only") def test_windows_coordinates_to_ctype(): coord = WindowsCoordinates.from_param(WindowsCoordinates(row=1, col=2)) assert coord.X == 2 assert coord.Y == 1 @pytest.fixture def win32_handle(): handle = mock.sentinel with mock.patch.object(_win32_console, "GetStdHandle", return_value=handle): yield handle @pytest.fixture def win32_console_getters(): def stub_console_cursor_info(std_handle, cursor_info): cursor_info.dwSize = CURSOR_SIZE cursor_info.bVisible = True with mock.patch.object( _win32_console, "GetConsoleScreenBufferInfo", return_value=StubScreenBufferInfo, ) as GetConsoleScreenBufferInfo, mock.patch.object( _win32_console, "GetConsoleCursorInfo", side_effect=stub_console_cursor_info ) as GetConsoleCursorInfo: yield { "GetConsoleScreenBufferInfo": GetConsoleScreenBufferInfo, "GetConsoleCursorInfo": GetConsoleCursorInfo, } def test_cursor_position(win32_console_getters): term = LegacyWindowsTerm(sys.stdout) assert term.cursor_position == WindowsCoordinates(row=CURSOR_Y, col=CURSOR_X) def test_screen_size(win32_console_getters): term = LegacyWindowsTerm(sys.stdout) assert term.screen_size == WindowsCoordinates( row=SCREEN_HEIGHT, col=SCREEN_WIDTH ) def test_write_text(win32_console_getters, win32_handle, capsys): text = "Hello, world!" term = LegacyWindowsTerm(sys.stdout) term.write_text(text) captured = capsys.readouterr() assert captured.out == text @patch.object(_win32_console, "SetConsoleTextAttribute") def test_write_styled( SetConsoleTextAttribute, win32_console_getters, win32_handle, capsys, ): style = Style.parse("black on red") text = "Hello, world!" term = LegacyWindowsTerm(sys.stdout) term.write_styled(text, style) captured = capsys.readouterr() assert captured.out == text # Ensure we set the text attributes and then reset them after writing styled text call_args = SetConsoleTextAttribute.call_args_list assert len(call_args) == 2 first_args, first_kwargs = call_args[0] second_args, second_kwargs = call_args[1] assert first_args == (win32_handle,) assert first_kwargs["attributes"].value == 64 assert second_args == (win32_handle,) assert second_kwargs["attributes"] == DEFAULT_STYLE_ATTRIBUTE @patch.object(_win32_console, "SetConsoleTextAttribute") def test_write_styled_bold( SetConsoleTextAttribute, win32_console_getters, win32_handle ): style = Style.parse("bold black on red") text = "Hello, world!" term = LegacyWindowsTerm(sys.stdout) term.write_styled(text, style) call_args = SetConsoleTextAttribute.call_args_list first_args, first_kwargs = call_args[0] expected_attr = 64 + 8 # 64 for red bg, +8 for bright black assert first_args == (win32_handle,) assert first_kwargs["attributes"].value == expected_attr @patch.object(_win32_console, "SetConsoleTextAttribute") def test_write_styled_reverse( SetConsoleTextAttribute, win32_console_getters, win32_handle ): style = Style.parse("reverse red on blue") text = "Hello, world!" term = LegacyWindowsTerm(sys.stdout) term.write_styled(text, style) call_args = SetConsoleTextAttribute.call_args_list first_args, first_kwargs = call_args[0] expected_attr = 64 + 1 # 64 for red bg (after reverse), +1 for blue fg assert first_args == (win32_handle,) assert first_kwargs["attributes"].value == expected_attr @patch.object(_win32_console, "SetConsoleTextAttribute") def test_write_styled_reverse( SetConsoleTextAttribute, win32_console_getters, win32_handle ): style = Style.parse("dim bright_red on blue") text = "Hello, world!" term = LegacyWindowsTerm(sys.stdout) term.write_styled(text, style) call_args = SetConsoleTextAttribute.call_args_list first_args, first_kwargs = call_args[0] expected_attr = 4 + 16 # 4 for red text (after dim), +16 for blue bg assert first_args == (win32_handle,) assert first_kwargs["attributes"].value == expected_attr @patch.object(_win32_console, "SetConsoleTextAttribute") def test_write_styled_no_foreground_color( SetConsoleTextAttribute, win32_console_getters, win32_handle ): style = Style.parse("on blue") text = "Hello, world!" term = LegacyWindowsTerm(sys.stdout) term.write_styled(text, style) call_args = SetConsoleTextAttribute.call_args_list first_args, first_kwargs = call_args[0] expected_attr = 16 | term._default_fore # 16 for blue bg, plus default fg color assert first_args == (win32_handle,) assert first_kwargs["attributes"].value == expected_attr @patch.object(_win32_console, "SetConsoleTextAttribute") def test_write_styled_no_background_color( SetConsoleTextAttribute, win32_console_getters, win32_handle ): style = Style.parse("blue") text = "Hello, world!" term = LegacyWindowsTerm(sys.stdout) term.write_styled(text, style) call_args = SetConsoleTextAttribute.call_args_list first_args, first_kwargs = call_args[0] expected_attr = ( 16 | term._default_back ) # 16 for blue foreground, plus default bg color assert first_args == (win32_handle,) assert first_kwargs["attributes"].value == expected_attr @patch.object(_win32_console, "FillConsoleOutputCharacter", return_value=None) @patch.object(_win32_console, "FillConsoleOutputAttribute", return_value=None) def test_erase_line( FillConsoleOutputAttribute, FillConsoleOutputCharacter, win32_console_getters, win32_handle, ): term = LegacyWindowsTerm(sys.stdout) term.erase_line() start = WindowsCoordinates(row=CURSOR_Y, col=0) FillConsoleOutputCharacter.assert_called_once_with( win32_handle, " ", length=SCREEN_WIDTH, start=start ) FillConsoleOutputAttribute.assert_called_once_with( win32_handle, DEFAULT_STYLE_ATTRIBUTE, length=SCREEN_WIDTH, start=start ) @patch.object(_win32_console, "FillConsoleOutputCharacter", return_value=None) @patch.object(_win32_console, "FillConsoleOutputAttribute", return_value=None) def test_erase_end_of_line( FillConsoleOutputAttribute, FillConsoleOutputCharacter, win32_console_getters, win32_handle, ): term = LegacyWindowsTerm(sys.stdout) term.erase_end_of_line() FillConsoleOutputCharacter.assert_called_once_with( win32_handle, " ", length=SCREEN_WIDTH - CURSOR_X, start=CURSOR_POSITION ) FillConsoleOutputAttribute.assert_called_once_with( win32_handle, DEFAULT_STYLE_ATTRIBUTE, length=SCREEN_WIDTH - CURSOR_X, start=CURSOR_POSITION, ) @patch.object(_win32_console, "FillConsoleOutputCharacter", return_value=None) @patch.object(_win32_console, "FillConsoleOutputAttribute", return_value=None) def test_erase_start_of_line( FillConsoleOutputAttribute, FillConsoleOutputCharacter, win32_console_getters, win32_handle, ): term = LegacyWindowsTerm(sys.stdout) term.erase_start_of_line() start = WindowsCoordinates(CURSOR_Y, 0) FillConsoleOutputCharacter.assert_called_once_with( win32_handle, " ", length=CURSOR_X, start=start ) FillConsoleOutputAttribute.assert_called_once_with( win32_handle, DEFAULT_STYLE_ATTRIBUTE, length=CURSOR_X, start=start ) @patch.object(_win32_console, "SetConsoleCursorPosition", return_value=None) def test_move_cursor_to( SetConsoleCursorPosition, win32_console_getters, win32_handle ): coords = WindowsCoordinates(row=4, col=5) term = LegacyWindowsTerm(sys.stdout) term.move_cursor_to(coords) SetConsoleCursorPosition.assert_called_once_with(win32_handle, coords=coords) @patch.object(_win32_console, "SetConsoleCursorPosition", return_value=None) def test_move_cursor_to_out_of_bounds_row( SetConsoleCursorPosition, win32_console_getters, win32_handle ): coords = WindowsCoordinates(row=-1, col=4) term = LegacyWindowsTerm(sys.stdout) term.move_cursor_to(coords) assert not SetConsoleCursorPosition.called @patch.object(_win32_console, "SetConsoleCursorPosition", return_value=None) def test_move_cursor_to_out_of_bounds_col( SetConsoleCursorPosition, win32_console_getters, win32_handle ): coords = WindowsCoordinates(row=10, col=-4) term = LegacyWindowsTerm(sys.stdout) term.move_cursor_to(coords) assert not SetConsoleCursorPosition.called @patch.object(_win32_console, "SetConsoleCursorPosition", return_value=None) def test_move_cursor_up( SetConsoleCursorPosition, win32_console_getters, win32_handle ): term = LegacyWindowsTerm(sys.stdout) term.move_cursor_up() SetConsoleCursorPosition.assert_called_once_with( win32_handle, coords=WindowsCoordinates(row=CURSOR_Y - 1, col=CURSOR_X) ) @patch.object(_win32_console, "SetConsoleCursorPosition", return_value=None) def test_move_cursor_down( SetConsoleCursorPosition, win32_console_getters, win32_handle ): term = LegacyWindowsTerm(sys.stdout) term.move_cursor_down() SetConsoleCursorPosition.assert_called_once_with( win32_handle, coords=WindowsCoordinates(row=CURSOR_Y + 1, col=CURSOR_X) ) @patch.object(_win32_console, "SetConsoleCursorPosition", return_value=None) def test_move_cursor_forward( SetConsoleCursorPosition, win32_console_getters, win32_handle ): term = LegacyWindowsTerm(sys.stdout) term.move_cursor_forward() SetConsoleCursorPosition.assert_called_once_with( win32_handle, coords=WindowsCoordinates(row=CURSOR_Y, col=CURSOR_X + 1) ) @patch.object(_win32_console, "SetConsoleCursorPosition", return_value=None) def test_move_cursor_forward_newline_wrap( SetConsoleCursorPosition, win32_console_getters, win32_handle ): cursor_at_end_of_line = StubScreenBufferInfo( dwCursorPosition=COORD(SCREEN_WIDTH - 1, CURSOR_Y) ) win32_console_getters[ "GetConsoleScreenBufferInfo" ].return_value = cursor_at_end_of_line term = LegacyWindowsTerm(sys.stdout) term.move_cursor_forward() SetConsoleCursorPosition.assert_called_once_with( win32_handle, coords=WindowsCoordinates(row=CURSOR_Y + 1, col=0) ) @patch.object(_win32_console, "SetConsoleCursorPosition", return_value=None) def test_move_cursor_to_column( SetConsoleCursorPosition, win32_console_getters, win32_handle ): term = LegacyWindowsTerm(sys.stdout) term.move_cursor_to_column(5) SetConsoleCursorPosition.assert_called_once_with( win32_handle, coords=WindowsCoordinates(CURSOR_Y, 5) ) @patch.object(_win32_console, "SetConsoleCursorPosition", return_value=None) def test_move_cursor_backward( SetConsoleCursorPosition, win32_console_getters, win32_handle ): term = LegacyWindowsTerm(sys.stdout) term.move_cursor_backward() SetConsoleCursorPosition.assert_called_once_with( win32_handle, coords=WindowsCoordinates(row=CURSOR_Y, col=CURSOR_X - 1) ) @patch.object(_win32_console, "SetConsoleCursorPosition", return_value=None) def test_move_cursor_backward_prev_line_wrap( SetConsoleCursorPosition, win32_console_getters, win32_handle ): cursor_at_start_of_line = StubScreenBufferInfo( dwCursorPosition=COORD(0, CURSOR_Y) ) win32_console_getters[ "GetConsoleScreenBufferInfo" ].return_value = cursor_at_start_of_line term = LegacyWindowsTerm(sys.stdout) term.move_cursor_backward() SetConsoleCursorPosition.assert_called_once_with( win32_handle, coords=WindowsCoordinates(row=CURSOR_Y - 1, col=SCREEN_WIDTH - 1), ) @patch.object(_win32_console, "SetConsoleCursorInfo", return_value=None) def test_hide_cursor(SetConsoleCursorInfo, win32_console_getters, win32_handle): term = LegacyWindowsTerm(sys.stdout) term.hide_cursor() call_args = SetConsoleCursorInfo.call_args_list assert len(call_args) == 1 args, kwargs = call_args[0] assert kwargs["cursor_info"].bVisible == 0 assert kwargs["cursor_info"].dwSize == CURSOR_SIZE @patch.object(_win32_console, "SetConsoleCursorInfo", return_value=None) def test_show_cursor(SetConsoleCursorInfo, win32_console_getters, win32_handle): term = LegacyWindowsTerm(sys.stdout) term.show_cursor() call_args = SetConsoleCursorInfo.call_args_list assert len(call_args) == 1 args, kwargs = call_args[0] assert kwargs["cursor_info"].bVisible == 1 assert kwargs["cursor_info"].dwSize == CURSOR_SIZE @patch.object(_win32_console, "SetConsoleTitle", return_value=None) def test_set_title(SetConsoleTitle, win32_console_getters): term = LegacyWindowsTerm(sys.stdout) term.set_title("title") SetConsoleTitle.assert_called_once_with("title") @patch.object(_win32_console, "SetConsoleTitle", return_value=None) def test_set_title_too_long(_, win32_console_getters): term = LegacyWindowsTerm(sys.stdout) with pytest.raises(AssertionError): term.set_title("a" * 255)
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_windows_renderer.py
tests/test_windows_renderer.py
import sys from unittest.mock import call, create_autospec import pytest try: from rich._win32_console import LegacyWindowsTerm, WindowsCoordinates from rich._windows_renderer import legacy_windows_render except: # These modules can only be imported on Windows pass from rich.segment import ControlType, Segment from rich.style import Style pytestmark = pytest.mark.skipif(sys.platform != "win32", reason="windows only") @pytest.fixture def legacy_term_mock(): return create_autospec(LegacyWindowsTerm) def test_text_only(legacy_term_mock): text = "Hello, world!" buffer = [Segment(text)] legacy_windows_render(buffer, legacy_term_mock) legacy_term_mock.write_text.assert_called_once_with(text) def test_text_multiple_segments(legacy_term_mock): buffer = [Segment("Hello, "), Segment("world!")] legacy_windows_render(buffer, legacy_term_mock) assert legacy_term_mock.write_text.call_args_list == [ call("Hello, "), call("world!"), ] def test_text_with_style(legacy_term_mock): text = "Hello, world!" style = Style.parse("black on red") buffer = [Segment(text, style)] legacy_windows_render(buffer, legacy_term_mock) legacy_term_mock.write_styled.assert_called_once_with(text, style) def test_control_cursor_move_to(legacy_term_mock): buffer = [Segment("", None, [(ControlType.CURSOR_MOVE_TO, 20, 30)])] legacy_windows_render(buffer, legacy_term_mock) legacy_term_mock.move_cursor_to.assert_called_once_with( WindowsCoordinates(row=29, col=19) ) def test_control_carriage_return(legacy_term_mock): buffer = [Segment("", None, [(ControlType.CARRIAGE_RETURN,)])] legacy_windows_render(buffer, legacy_term_mock) legacy_term_mock.write_text.assert_called_once_with("\r") def test_control_home(legacy_term_mock): buffer = [Segment("", None, [(ControlType.HOME,)])] legacy_windows_render(buffer, legacy_term_mock) legacy_term_mock.move_cursor_to.assert_called_once_with(WindowsCoordinates(0, 0)) @pytest.mark.parametrize( "control_type, method_name", [ (ControlType.CURSOR_UP, "move_cursor_up"), (ControlType.CURSOR_DOWN, "move_cursor_down"), (ControlType.CURSOR_FORWARD, "move_cursor_forward"), (ControlType.CURSOR_BACKWARD, "move_cursor_backward"), ], ) def test_control_cursor_single_cell_movement( legacy_term_mock, control_type, method_name ): buffer = [Segment("", None, [(control_type,)])] legacy_windows_render(buffer, legacy_term_mock) getattr(legacy_term_mock, method_name).assert_called_once_with() @pytest.mark.parametrize( "erase_mode, method_name", [ (0, "erase_end_of_line"), (1, "erase_start_of_line"), (2, "erase_line"), ], ) def test_control_erase_line(legacy_term_mock, erase_mode, method_name): buffer = [Segment("", None, [(ControlType.ERASE_IN_LINE, erase_mode)])] legacy_windows_render(buffer, legacy_term_mock) getattr(legacy_term_mock, method_name).assert_called_once_with() def test_control_show_cursor(legacy_term_mock): buffer = [Segment("", None, [(ControlType.SHOW_CURSOR,)])] legacy_windows_render(buffer, legacy_term_mock) legacy_term_mock.show_cursor.assert_called_once_with() def test_control_hide_cursor(legacy_term_mock): buffer = [Segment("", None, [(ControlType.HIDE_CURSOR,)])] legacy_windows_render(buffer, legacy_term_mock) legacy_term_mock.hide_cursor.assert_called_once_with() def test_control_cursor_move_to_column(legacy_term_mock): buffer = [Segment("", None, [(ControlType.CURSOR_MOVE_TO_COLUMN, 3)])] legacy_windows_render(buffer, legacy_term_mock) legacy_term_mock.move_cursor_to_column.assert_called_once_with(2) def test_control_set_terminal_window_title(legacy_term_mock): buffer = [Segment("", None, [(ControlType.SET_WINDOW_TITLE, "Hello, world!")])] legacy_windows_render(buffer, legacy_term_mock) legacy_term_mock.set_title.assert_called_once_with("Hello, world!")
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_palette.py
tests/test_palette.py
from rich._palettes import STANDARD_PALETTE from rich.table import Table def test_rich_cast(): table = STANDARD_PALETTE.__rich__() assert isinstance(table, Table) assert table.row_count == 16
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_align.py
tests/test_align.py
import io import pytest from rich.console import Console from rich.align import Align, VerticalCenter from rich.measure import Measurement def test_bad_align_legal(): # Legal Align("foo", "left") Align("foo", "center") Align("foo", "right") # illegal with pytest.raises(ValueError): Align("foo", None) with pytest.raises(ValueError): Align("foo", "middle") with pytest.raises(ValueError): Align("foo", "") with pytest.raises(ValueError): Align("foo", "LEFT") with pytest.raises(ValueError): Align("foo", vertical="somewhere") def test_repr(): repr(Align("foo", "left")) repr(Align("foo", "center")) repr(Align("foo", "right")) def test_align_left(): console = Console(file=io.StringIO(), width=10) console.print(Align("foo", "left")) assert console.file.getvalue() == "foo \n" def test_align_center(): console = Console(file=io.StringIO(), width=10) console.print(Align("foo", "center")) assert console.file.getvalue() == " foo \n" def test_align_right(): console = Console(file=io.StringIO(), width=10) console.print(Align("foo", "right")) assert console.file.getvalue() == " foo\n" def test_align_top(): console = Console(file=io.StringIO(), width=10) console.print(Align("foo", vertical="top"), height=5) expected = "foo \n \n \n \n \n" result = console.file.getvalue() print(repr(result)) assert result == expected def test_align_middle(): console = Console(file=io.StringIO(), width=10) console.print(Align("foo", vertical="middle"), height=5) expected = " \n \nfoo \n \n \n" result = console.file.getvalue() print(repr(result)) assert result == expected def test_align_bottom(): console = Console(file=io.StringIO(), width=10) console.print(Align("foo", vertical="bottom"), height=5) expected = " \n \n \n \nfoo \n" result = console.file.getvalue() print(repr(result)) assert result == expected def test_align_center_middle(): console = Console(file=io.StringIO(), width=10) console.print(Align("foo\nbar", "center", vertical="middle"), height=5) expected = " \n foo \n bar \n \n \n" result = console.file.getvalue() print(repr(result)) assert result == expected def test_align_fit(): console = Console(file=io.StringIO(), width=10) console.print(Align("foobarbaze", "center")) assert console.file.getvalue() == "foobarbaze\n" def test_align_right_style(): console = Console( file=io.StringIO(), width=10, color_system="truecolor", force_terminal=True, _environ={}, ) console.print(Align("foo", "right", style="on blue")) assert console.file.getvalue() == "\x1b[44m \x1b[0m\x1b[44mfoo\x1b[0m\n" def test_measure(): console = Console(file=io.StringIO(), width=20) _min, _max = Measurement.get(console, console.options, Align("foo bar", "left")) assert _min == 3 assert _max == 7 def test_align_no_pad(): console = Console(file=io.StringIO(), width=10) console.print(Align("foo", "center", pad=False)) console.print(Align("foo", "left", pad=False)) assert console.file.getvalue() == " foo\nfoo\n" def test_align_width(): console = Console(file=io.StringIO(), width=40) words = "Deep in the human unconscious is a pervasive need for a logical universe that makes sense. But the real universe is always one step beyond logic" console.print(Align(words, "center", width=30)) result = console.file.getvalue() expected = " Deep in the human unconscious \n is a pervasive need for a \n logical universe that makes \n sense. But the real universe \n is always one step beyond \n logic \n" assert result == expected def test_shortcuts(): assert Align.left("foo").align == "left" assert Align.left("foo").renderable == "foo" assert Align.right("foo").align == "right" assert Align.right("foo").renderable == "foo" assert Align.center("foo").align == "center" assert Align.center("foo").renderable == "foo" def test_vertical_center(): console = Console(color_system=None, height=6) console.begin_capture() vertical_center = VerticalCenter("foo") repr(vertical_center) console.print(vertical_center) result = console.end_capture() print(repr(result)) expected = " \n \nfoo\n \n \n \n" assert result == expected assert Measurement.get(console, console.options, vertical_center) == Measurement( 3, 3 )
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/_card_render.py
tests/_card_render.py
expected = "\x1b[3m Rich features \x1b[0m\n\x1b[1;31m \x1b[0m \n\x1b[1;31m \x1b[0m\x1b[1;31m Colors \x1b[0m\x1b[1;31m \x1b[0m✓ \x1b[1;32m4-bit color\x1b[0m \x1b[38;2;86;0;0;48;2;51;0;0m▄\x1b[0m\x1b[38;2;86;9;0;48;2;51;5;0m▄\x1b[0m\x1b[38;2;86;18;0;48;2;51;11;0m▄\x1b[0m\x1b[38;2;86;28;0;48;2;51;16;0m▄\x1b[0m\x1b[38;2;86;37;0;48;2;51;22;0m▄\x1b[0m\x1b[38;2;86;47;0;48;2;51;27;0m▄\x1b[0m\x1b[38;2;86;56;0;48;2;51;33;0m▄\x1b[0m\x1b[38;2;86;66;0;48;2;51;38;0m▄\x1b[0m\x1b[38;2;86;75;0;48;2;51;44;0m▄\x1b[0m\x1b[38;2;86;85;0;48;2;51;50;0m▄\x1b[0m\x1b[38;2;78;86;0;48;2;46;51;0m▄\x1b[0m\x1b[38;2;69;86;0;48;2;40;51;0m▄\x1b[0m\x1b[38;2;59;86;0;48;2;35;51;0m▄\x1b[0m\x1b[38;2;50;86;0;48;2;29;51;0m▄\x1b[0m\x1b[38;2;40;86;0;48;2;24;51;0m▄\x1b[0m\x1b[38;2;31;86;0;48;2;18;51;0m▄\x1b[0m\x1b[38;2;22;86;0;48;2;12;51;0m▄\x1b[0m\x1b[38;2;12;86;0;48;2;7;51;0m▄\x1b[0m\x1b[38;2;3;86;0;48;2;1;51;0m▄\x1b[0m\x1b[38;2;0;86;6;48;2;0;51;3m▄\x1b[0m\x1b[38;2;0;86;15;48;2;0;51;9m▄\x1b[0m\x1b[38;2;0;86;25;48;2;0;51;14m▄\x1b[0m\x1b[38;2;0;86;34;48;2;0;51;20m▄\x1b[0m\x1b[38;2;0;86;44;48;2;0;51;25m▄\x1b[0m\x1b[38;2;0;86;53;48;2;0;51;31m▄\x1b[0m\x1b[38;2;0;86;63;48;2;0;51;37m▄\x1b[0m\x1b[38;2;0;86;72;48;2;0;51;42m▄\x1b[0m\x1b[38;2;0;86;81;48;2;0;51;48m▄\x1b[0m\x1b[38;2;0;81;86;48;2;0;48;51m▄\x1b[0m\x1b[38;2;0;72;86;48;2;0;42;51m▄\x1b[0m\x1b[38;2;0;63;86;48;2;0;37;51m▄\x1b[0m\x1b[38;2;0;53;86;48;2;0;31;51m▄\x1b[0m\x1b[38;2;0;44;86;48;2;0;25;51m▄\x1b[0m\x1b[38;2;0;34;86;48;2;0;20;51m▄\x1b[0m\x1b[38;2;0;25;86;48;2;0;14;51m▄\x1b[0m\x1b[38;2;0;15;86;48;2;0;9;51m▄\x1b[0m\x1b[38;2;0;6;86;48;2;0;3;51m▄\x1b[0m\x1b[38;2;3;0;86;48;2;1;0;51m▄\x1b[0m\x1b[38;2;12;0;86;48;2;7;0;51m▄\x1b[0m\x1b[38;2;22;0;86;48;2;12;0;51m▄\x1b[0m\x1b[38;2;31;0;86;48;2;18;0;51m▄\x1b[0m\x1b[38;2;40;0;86;48;2;24;0;51m▄\x1b[0m\x1b[38;2;50;0;86;48;2;29;0;51m▄\x1b[0m\x1b[38;2;59;0;86;48;2;35;0;51m▄\x1b[0m\x1b[38;2;69;0;86;48;2;40;0;51m▄\x1b[0m\x1b[38;2;78;0;86;48;2;46;0;51m▄\x1b[0m\x1b[38;2;86;0;85;48;2;51;0;50m▄\x1b[0m\x1b[38;2;86;0;75;48;2;51;0;44m▄\x1b[0m\x1b[38;2;86;0;66;48;2;51;0;38m▄\x1b[0m\x1b[38;2;86;0;56;48;2;51;0;33m▄\x1b[0m\x1b[38;2;86;0;47;48;2;51;0;27m▄\x1b[0m\x1b[38;2;86;0;37;48;2;51;0;22m▄\x1b[0m\x1b[38;2;86;0;28;48;2;51;0;16m▄\x1b[0m\x1b[38;2;86;0;18;48;2;51;0;11m▄\x1b[0m\x1b[38;2;86;0;9;48;2;51;0;5m▄\x1b[0m \n\x1b[1;31m \x1b[0m✓ \x1b[1;34m8-bit color\x1b[0m \x1b[38;2;158;0;0;48;2;122;0;0m▄\x1b[0m\x1b[38;2;158;17;0;48;2;122;13;0m▄\x1b[0m\x1b[38;2;158;34;0;48;2;122;26;0m▄\x1b[0m\x1b[38;2;158;51;0;48;2;122;40;0m▄\x1b[0m\x1b[38;2;158;68;0;48;2;122;53;0m▄\x1b[0m\x1b[38;2;158;86;0;48;2;122;66;0m▄\x1b[0m\x1b[38;2;158;103;0;48;2;122;80;0m▄\x1b[0m\x1b[38;2;158;120;0;48;2;122;93;0m▄\x1b[0m\x1b[38;2;158;137;0;48;2;122;106;0m▄\x1b[0m\x1b[38;2;158;155;0;48;2;122;120;0m▄\x1b[0m\x1b[38;2;143;158;0;48;2;111;122;0m▄\x1b[0m\x1b[38;2;126;158;0;48;2;97;122;0m▄\x1b[0m\x1b[38;2;109;158;0;48;2;84;122;0m▄\x1b[0m\x1b[38;2;91;158;0;48;2;71;122;0m▄\x1b[0m\x1b[38;2;74;158;0;48;2;57;122;0m▄\x1b[0m\x1b[38;2;57;158;0;48;2;44;122;0m▄\x1b[0m\x1b[38;2;40;158;0;48;2;31;122;0m▄\x1b[0m\x1b[38;2;22;158;0;48;2;17;122;0m▄\x1b[0m\x1b[38;2;5;158;0;48;2;4;122;0m▄\x1b[0m\x1b[38;2;0;158;11;48;2;0;122;8m▄\x1b[0m\x1b[38;2;0;158;28;48;2;0;122;22m▄\x1b[0m\x1b[38;2;0;158;45;48;2;0;122;35m▄\x1b[0m\x1b[38;2;0;158;63;48;2;0;122;48m▄\x1b[0m\x1b[38;2;0;158;80;48;2;0;122;62m▄\x1b[0m\x1b[38;2;0;158;97;48;2;0;122;75m▄\x1b[0m\x1b[38;2;0;158;114;48;2;0;122;89m▄\x1b[0m\x1b[38;2;0;158;132;48;2;0;122;102m▄\x1b[0m\x1b[38;2;0;158;149;48;2;0;122;115m▄\x1b[0m\x1b[38;2;0;149;158;48;2;0;115;122m▄\x1b[0m\x1b[38;2;0;132;158;48;2;0;102;122m▄\x1b[0m\x1b[38;2;0;114;158;48;2;0;89;122m▄\x1b[0m\x1b[38;2;0;97;158;48;2;0;75;122m▄\x1b[0m\x1b[38;2;0;80;158;48;2;0;62;122m▄\x1b[0m\x1b[38;2;0;63;158;48;2;0;48;122m▄\x1b[0m\x1b[38;2;0;45;158;48;2;0;35;122m▄\x1b[0m\x1b[38;2;0;28;158;48;2;0;22;122m▄\x1b[0m\x1b[38;2;0;11;158;48;2;0;8;122m▄\x1b[0m\x1b[38;2;5;0;158;48;2;4;0;122m▄\x1b[0m\x1b[38;2;22;0;158;48;2;17;0;122m▄\x1b[0m\x1b[38;2;40;0;158;48;2;31;0;122m▄\x1b[0m\x1b[38;2;57;0;158;48;2;44;0;122m▄\x1b[0m\x1b[38;2;74;0;158;48;2;57;0;122m▄\x1b[0m\x1b[38;2;91;0;158;48;2;71;0;122m▄\x1b[0m\x1b[38;2;109;0;158;48;2;84;0;122m▄\x1b[0m\x1b[38;2;126;0;158;48;2;97;0;122m▄\x1b[0m\x1b[38;2;143;0;158;48;2;111;0;122m▄\x1b[0m\x1b[38;2;158;0;155;48;2;122;0;120m▄\x1b[0m\x1b[38;2;158;0;137;48;2;122;0;106m▄\x1b[0m\x1b[38;2;158;0;120;48;2;122;0;93m▄\x1b[0m\x1b[38;2;158;0;103;48;2;122;0;80m▄\x1b[0m\x1b[38;2;158;0;86;48;2;122;0;66m▄\x1b[0m\x1b[38;2;158;0;68;48;2;122;0;53m▄\x1b[0m\x1b[38;2;158;0;51;48;2;122;0;40m▄\x1b[0m\x1b[38;2;158;0;34;48;2;122;0;26m▄\x1b[0m\x1b[38;2;158;0;17;48;2;122;0;13m▄\x1b[0m \n\x1b[1;31m \x1b[0m✓ \x1b[1;35mTruecolor (16.7 million)\x1b[0m \x1b[38;2;229;0;0;48;2;193;0;0m▄\x1b[0m\x1b[38;2;229;25;0;48;2;193;21;0m▄\x1b[0m\x1b[38;2;229;50;0;48;2;193;42;0m▄\x1b[0m\x1b[38;2;229;75;0;48;2;193;63;0m▄\x1b[0m\x1b[38;2;229;100;0;48;2;193;84;0m▄\x1b[0m\x1b[38;2;229;125;0;48;2;193;105;0m▄\x1b[0m\x1b[38;2;229;150;0;48;2;193;126;0m▄\x1b[0m\x1b[38;2;229;175;0;48;2;193;147;0m▄\x1b[0m\x1b[38;2;229;200;0;48;2;193;169;0m▄\x1b[0m\x1b[38;2;229;225;0;48;2;193;190;0m▄\x1b[0m\x1b[38;2;208;229;0;48;2;176;193;0m▄\x1b[0m\x1b[38;2;183;229;0;48;2;155;193;0m▄\x1b[0m\x1b[38;2;158;229;0;48;2;133;193;0m▄\x1b[0m\x1b[38;2;133;229;0;48;2;112;193;0m▄\x1b[0m\x1b[38;2;108;229;0;48;2;91;193;0m▄\x1b[0m\x1b[38;2;83;229;0;48;2;70;193;0m▄\x1b[0m\x1b[38;2;58;229;0;48;2;49;193;0m▄\x1b[0m\x1b[38;2;33;229;0;48;2;28;193;0m▄\x1b[0m\x1b[38;2;8;229;0;48;2;7;193;0m▄\x1b[0m\x1b[38;2;0;229;16;48;2;0;193;14m▄\x1b[0m\x1b[38;2;0;229;41;48;2;0;193;35m▄\x1b[0m\x1b[38;2;0;229;66;48;2;0;193;56m▄\x1b[0m\x1b[38;2;0;229;91;48;2;0;193;77m▄\x1b[0m\x1b[38;2;0;229;116;48;2;0;193;98m▄\x1b[0m\x1b[38;2;0;229;141;48;2;0;193;119m▄\x1b[0m\x1b[38;2;0;229;166;48;2;0;193;140m▄\x1b[0m\x1b[38;2;0;229;191;48;2;0;193;162m▄\x1b[0m\x1b[38;2;0;229;216;48;2;0;193;183m▄\x1b[0m\x1b[38;2;0;216;229;48;2;0;183;193m▄\x1b[0m\x1b[38;2;0;191;229;48;2;0;162;193m▄\x1b[0m\x1b[38;2;0;166;229;48;2;0;140;193m▄\x1b[0m\x1b[38;2;0;141;229;48;2;0;119;193m▄\x1b[0m\x1b[38;2;0;116;229;48;2;0;98;193m▄\x1b[0m\x1b[38;2;0;91;229;48;2;0;77;193m▄\x1b[0m\x1b[38;2;0;66;229;48;2;0;56;193m▄\x1b[0m\x1b[38;2;0;41;229;48;2;0;35;193m▄\x1b[0m\x1b[38;2;0;16;229;48;2;0;14;193m▄\x1b[0m\x1b[38;2;8;0;229;48;2;7;0;193m▄\x1b[0m\x1b[38;2;33;0;229;48;2;28;0;193m▄\x1b[0m\x1b[38;2;58;0;229;48;2;49;0;193m▄\x1b[0m\x1b[38;2;83;0;229;48;2;70;0;193m▄\x1b[0m\x1b[38;2;108;0;229;48;2;91;0;193m▄\x1b[0m\x1b[38;2;133;0;229;48;2;112;0;193m▄\x1b[0m\x1b[38;2;158;0;229;48;2;133;0;193m▄\x1b[0m\x1b[38;2;183;0;229;48;2;155;0;193m▄\x1b[0m\x1b[38;2;208;0;229;48;2;176;0;193m▄\x1b[0m\x1b[38;2;229;0;225;48;2;193;0;190m▄\x1b[0m\x1b[38;2;229;0;200;48;2;193;0;169m▄\x1b[0m\x1b[38;2;229;0;175;48;2;193;0;147m▄\x1b[0m\x1b[38;2;229;0;150;48;2;193;0;126m▄\x1b[0m\x1b[38;2;229;0;125;48;2;193;0;105m▄\x1b[0m\x1b[38;2;229;0;100;48;2;193;0;84m▄\x1b[0m\x1b[38;2;229;0;75;48;2;193;0;63m▄\x1b[0m\x1b[38;2;229;0;50;48;2;193;0;42m▄\x1b[0m\x1b[38;2;229;0;25;48;2;193;0;21m▄\x1b[0m \n\x1b[1;31m \x1b[0m✓ \x1b[1;33mDumb terminals\x1b[0m \x1b[38;2;254;45;45;48;2;255;10;10m▄\x1b[0m\x1b[38;2;254;68;45;48;2;255;36;10m▄\x1b[0m\x1b[38;2;254;91;45;48;2;255;63;10m▄\x1b[0m\x1b[38;2;254;114;45;48;2;255;90;10m▄\x1b[0m\x1b[38;2;254;137;45;48;2;255;117;10m▄\x1b[0m\x1b[38;2;254;159;45;48;2;255;143;10m▄\x1b[0m\x1b[38;2;254;182;45;48;2;255;170;10m▄\x1b[0m\x1b[38;2;254;205;45;48;2;255;197;10m▄\x1b[0m\x1b[38;2;254;228;45;48;2;255;223;10m▄\x1b[0m\x1b[38;2;254;251;45;48;2;255;250;10m▄\x1b[0m\x1b[38;2;235;254;45;48;2;232;255;10m▄\x1b[0m\x1b[38;2;213;254;45;48;2;206;255;10m▄\x1b[0m\x1b[38;2;190;254;45;48;2;179;255;10m▄\x1b[0m\x1b[38;2;167;254;45;48;2;152;255;10m▄\x1b[0m\x1b[38;2;144;254;45;48;2;125;255;10m▄\x1b[0m\x1b[38;2;121;254;45;48;2;99;255;10m▄\x1b[0m\x1b[38;2;99;254;45;48;2;72;255;10m▄\x1b[0m\x1b[38;2;76;254;45;48;2;45;255;10m▄\x1b[0m\x1b[38;2;53;254;45;48;2;19;255;10m▄\x1b[0m\x1b[38;2;45;254;61;48;2;10;255;28m▄\x1b[0m\x1b[38;2;45;254;83;48;2;10;255;54m▄\x1b[0m\x1b[38;2;45;254;106;48;2;10;255;81m▄\x1b[0m\x1b[38;2;45;254;129;48;2;10;255;108m▄\x1b[0m\x1b[38;2;45;254;152;48;2;10;255;134m▄\x1b[0m\x1b[38;2;45;254;175;48;2;10;255;161m▄\x1b[0m\x1b[38;2;45;254;197;48;2;10;255;188m▄\x1b[0m\x1b[38;2;45;254;220;48;2;10;255;214m▄\x1b[0m\x1b[38;2;45;254;243;48;2;10;255;241m▄\x1b[0m\x1b[38;2;45;243;254;48;2;10;241;255m▄\x1b[0m\x1b[38;2;45;220;254;48;2;10;214;255m▄\x1b[0m\x1b[38;2;45;197;254;48;2;10;188;255m▄\x1b[0m\x1b[38;2;45;175;254;48;2;10;161;255m▄\x1b[0m\x1b[38;2;45;152;254;48;2;10;134;255m▄\x1b[0m\x1b[38;2;45;129;254;48;2;10;108;255m▄\x1b[0m\x1b[38;2;45;106;254;48;2;10;81;255m▄\x1b[0m\x1b[38;2;45;83;254;48;2;10;54;255m▄\x1b[0m\x1b[38;2;45;61;254;48;2;10;28;255m▄\x1b[0m\x1b[38;2;53;45;254;48;2;19;10;255m▄\x1b[0m\x1b[38;2;76;45;254;48;2;45;10;255m▄\x1b[0m\x1b[38;2;99;45;254;48;2;72;10;255m▄\x1b[0m\x1b[38;2;121;45;254;48;2;99;10;255m▄\x1b[0m\x1b[38;2;144;45;254;48;2;125;10;255m▄\x1b[0m\x1b[38;2;167;45;254;48;2;152;10;255m▄\x1b[0m\x1b[38;2;190;45;254;48;2;179;10;255m▄\x1b[0m\x1b[38;2;213;45;254;48;2;206;10;255m▄\x1b[0m\x1b[38;2;235;45;254;48;2;232;10;255m▄\x1b[0m\x1b[38;2;254;45;251;48;2;255;10;250m▄\x1b[0m\x1b[38;2;254;45;228;48;2;255;10;223m▄\x1b[0m\x1b[38;2;254;45;205;48;2;255;10;197m▄\x1b[0m\x1b[38;2;254;45;182;48;2;255;10;170m▄\x1b[0m\x1b[38;2;254;45;159;48;2;255;10;143m▄\x1b[0m\x1b[38;2;254;45;137;48;2;255;10;117m▄\x1b[0m\x1b[38;2;254;45;114;48;2;255;10;90m▄\x1b[0m\x1b[38;2;254;45;91;48;2;255;10;63m▄\x1b[0m\x1b[38;2;254;45;68;48;2;255;10;36m▄\x1b[0m \n\x1b[1;31m \x1b[0m✓ \x1b[1;36mAutomatic color conversion\x1b[0m \x1b[38;2;255;117;117;48;2;255;81;81m▄\x1b[0m\x1b[38;2;255;132;117;48;2;255;100;81m▄\x1b[0m\x1b[38;2;255;147;117;48;2;255;119;81m▄\x1b[0m\x1b[38;2;255;162;117;48;2;255;138;81m▄\x1b[0m\x1b[38;2;255;177;117;48;2;255;157;81m▄\x1b[0m\x1b[38;2;255;192;117;48;2;255;176;81m▄\x1b[0m\x1b[38;2;255;207;117;48;2;255;195;81m▄\x1b[0m\x1b[38;2;255;222;117;48;2;255;214;81m▄\x1b[0m\x1b[38;2;255;237;117;48;2;255;232;81m▄\x1b[0m\x1b[38;2;255;252;117;48;2;255;251;81m▄\x1b[0m\x1b[38;2;242;255;117;48;2;239;255;81m▄\x1b[0m\x1b[38;2;227;255;117;48;2;220;255;81m▄\x1b[0m\x1b[38;2;212;255;117;48;2;201;255;81m▄\x1b[0m\x1b[38;2;197;255;117;48;2;182;255;81m▄\x1b[0m\x1b[38;2;182;255;117;48;2;163;255;81m▄\x1b[0m\x1b[38;2;167;255;117;48;2;144;255;81m▄\x1b[0m\x1b[38;2;152;255;117;48;2;125;255;81m▄\x1b[0m\x1b[38;2;137;255;117;48;2;106;255;81m▄\x1b[0m\x1b[38;2;122;255;117;48;2;87;255;81m▄\x1b[0m\x1b[38;2;117;255;127;48;2;81;255;94m▄\x1b[0m\x1b[38;2;117;255;142;48;2;81;255;113m▄\x1b[0m\x1b[38;2;117;255;157;48;2;81;255;132m▄\x1b[0m\x1b[38;2;117;255;172;48;2;81;255;150m▄\x1b[0m\x1b[38;2;117;255;187;48;2;81;255;169m▄\x1b[0m\x1b[38;2;117;255;202;48;2;81;255;188m▄\x1b[0m\x1b[38;2;117;255;217;48;2;81;255;207m▄\x1b[0m\x1b[38;2;117;255;232;48;2;81;255;226m▄\x1b[0m\x1b[38;2;117;255;247;48;2;81;255;245m▄\x1b[0m\x1b[38;2;117;247;255;48;2;81;245;255m▄\x1b[0m\x1b[38;2;117;232;255;48;2;81;226;255m▄\x1b[0m\x1b[38;2;117;217;255;48;2;81;207;255m▄\x1b[0m\x1b[38;2;117;202;255;48;2;81;188;255m▄\x1b[0m\x1b[38;2;117;187;255;48;2;81;169;255m▄\x1b[0m\x1b[38;2;117;172;255;48;2;81;150;255m▄\x1b[0m\x1b[38;2;117;157;255;48;2;81;132;255m▄\x1b[0m\x1b[38;2;117;142;255;48;2;81;113;255m▄\x1b[0m\x1b[38;2;117;127;255;48;2;81;94;255m▄\x1b[0m\x1b[38;2;122;117;255;48;2;87;81;255m▄\x1b[0m\x1b[38;2;137;117;255;48;2;106;81;255m▄\x1b[0m\x1b[38;2;152;117;255;48;2;125;81;255m▄\x1b[0m\x1b[38;2;167;117;255;48;2;144;81;255m▄\x1b[0m\x1b[38;2;182;117;255;48;2;163;81;255m▄\x1b[0m\x1b[38;2;197;117;255;48;2;182;81;255m▄\x1b[0m\x1b[38;2;212;117;255;48;2;201;81;255m▄\x1b[0m\x1b[38;2;227;117;255;48;2;220;81;255m▄\x1b[0m\x1b[38;2;242;117;255;48;2;239;81;255m▄\x1b[0m\x1b[38;2;255;117;252;48;2;255;81;251m▄\x1b[0m\x1b[38;2;255;117;237;48;2;255;81;232m▄\x1b[0m\x1b[38;2;255;117;222;48;2;255;81;214m▄\x1b[0m\x1b[38;2;255;117;207;48;2;255;81;195m▄\x1b[0m\x1b[38;2;255;117;192;48;2;255;81;176m▄\x1b[0m\x1b[38;2;255;117;177;48;2;255;81;157m▄\x1b[0m\x1b[38;2;255;117;162;48;2;255;81;138m▄\x1b[0m\x1b[38;2;255;117;147;48;2;255;81;119m▄\x1b[0m\x1b[38;2;255;117;132;48;2;255;81;100m▄\x1b[0m \n\x1b[1;31m \x1b[0m \n\x1b[1;31m \x1b[0m\x1b[1;31m Styles \x1b[0m\x1b[1;31m \x1b[0mAll ansi styles: \x1b[1mbold\x1b[0m, \x1b[2mdim\x1b[0m, \x1b[3mitalic\x1b[0m, \x1b[4munderline\x1b[0m, \x1b[9mstrikethrough\x1b[0m, \x1b[7mreverse\x1b[0m, and even \n\x1b[1;31m \x1b[0m\x1b[5mblink\x1b[0m. \n\x1b[1;31m \x1b[0m \n\x1b[1;31m \x1b[0m\x1b[1;31m Text \x1b[0m\x1b[1;31m \x1b[0mWord wrap text. Justify \x1b[32mleft\x1b[0m, \x1b[33mcenter\x1b[0m, \x1b[34mright\x1b[0m or \x1b[31mfull\x1b[0m. \n\x1b[1;31m \x1b[0m \n\x1b[1;31m \x1b[0m\x1b[32mLorem ipsum dolor \x1b[0m \x1b[33m Lorem ipsum dolor \x1b[0m \x1b[34m Lorem ipsum dolor\x1b[0m \x1b[31mLorem\x1b[0m\x1b[31m \x1b[0m\x1b[31mipsum\x1b[0m\x1b[31m \x1b[0m\x1b[31mdolor\x1b[0m\x1b[31m \x1b[0m\x1b[31msit\x1b[0m \n\x1b[1;31m \x1b[0m\x1b[32msit amet, \x1b[0m \x1b[33m sit amet, \x1b[0m \x1b[34m sit amet,\x1b[0m \x1b[31mamet,\x1b[0m\x1b[31m \x1b[0m\x1b[31mconsectetur\x1b[0m \n\x1b[1;31m \x1b[0m\x1b[32mconsectetur \x1b[0m \x1b[33m consectetur \x1b[0m \x1b[34m consectetur\x1b[0m \x1b[31madipiscing\x1b[0m\x1b[31m \x1b[0m\x1b[31melit.\x1b[0m \n\x1b[1;31m \x1b[0m\x1b[32madipiscing elit. \x1b[0m \x1b[33m adipiscing elit. \x1b[0m \x1b[34m adipiscing elit.\x1b[0m \x1b[31mQuisque\x1b[0m\x1b[31m \x1b[0m\x1b[31min\x1b[0m\x1b[31m \x1b[0m\x1b[31mmetus\x1b[0m\x1b[31m \x1b[0m\x1b[31msed\x1b[0m \n\x1b[1;31m \x1b[0m\x1b[32mQuisque in metus sed\x1b[0m \x1b[33mQuisque in metus sed\x1b[0m \x1b[34mQuisque in metus sed\x1b[0m \x1b[31msapien\x1b[0m\x1b[31m \x1b[0m\x1b[31multricies\x1b[0m \n\x1b[1;31m \x1b[0m\x1b[32msapien ultricies \x1b[0m \x1b[33m sapien ultricies \x1b[0m \x1b[34m sapien ultricies\x1b[0m \x1b[31mpretium\x1b[0m\x1b[31m \x1b[0m\x1b[31ma\x1b[0m\x1b[31m \x1b[0m\x1b[31mat\x1b[0m\x1b[31m \x1b[0m\x1b[31mjusto.\x1b[0m \n\x1b[1;31m \x1b[0m\x1b[32mpretium a at justo. \x1b[0m \x1b[33mpretium a at justo. \x1b[0m \x1b[34m pretium a at justo.\x1b[0m \x1b[31mMaecenas\x1b[0m\x1b[31m \x1b[0m\x1b[31mluctus\x1b[0m\x1b[31m \x1b[0m\x1b[31mvelit\x1b[0m \n\x1b[1;31m \x1b[0m\x1b[32mMaecenas luctus \x1b[0m \x1b[33m Maecenas luctus \x1b[0m \x1b[34m Maecenas luctus\x1b[0m \x1b[31met auctor maximus.\x1b[0m \n\x1b[1;31m \x1b[0m\x1b[32mvelit et auctor \x1b[0m \x1b[33m velit et auctor \x1b[0m \x1b[34m velit et auctor\x1b[0m \n\x1b[1;31m \x1b[0m\x1b[32mmaximus. \x1b[0m \x1b[33m maximus. \x1b[0m \x1b[34m maximus.\x1b[0m \n\x1b[1;31m \x1b[0m \n\x1b[1;31m \x1b[0m\x1b[1;31m Asian \x1b[0m\x1b[1;31m \x1b[0m🇨🇳 该库支持中文,日文和韩文文本! \n\x1b[1;31m \x1b[0m\x1b[1;31m language \x1b[0m\x1b[1;31m \x1b[0m🇯🇵 ライブラリは中国語、日本語、韓国語のテキストをサポートしています \n\x1b[1;31m \x1b[0m\x1b[1;31m support \x1b[0m\x1b[1;31m \x1b[0m🇰🇷 이 라이브러리는 중국어, 일본어 및 한국어 텍스트를 지원합니다 \n\x1b[1;31m \x1b[0m \n\x1b[1;31m \x1b[0m\x1b[1;31m Markup \x1b[0m\x1b[1;31m \x1b[0m\x1b[1;35mRich\x1b[0m supports a simple \x1b[3mbbcode\x1b[0m-like \x1b[1mmarkup\x1b[0m for \x1b[33mcolor\x1b[0m, \x1b[4mstyle\x1b[0m, and emoji! 👍 🍎 🐜 🐻 … \n\x1b[1;31m \x1b[0m🚌 \n\x1b[1;31m \x1b[0m \n\x1b[1;31m \x1b[0m\x1b[1;31m Tables \x1b[0m\x1b[1;31m \x1b[0m\x1b[1m \x1b[0m\x1b[1;32mDate\x1b[0m\x1b[1m \x1b[0m\x1b[1m \x1b[0m \x1b[1m \x1b[0m\x1b[1;34mTitle\x1b[0m\x1b[1m \x1b[0m\x1b[1m \x1b[0m \x1b[1m \x1b[0m\x1b[1;36mProduction Budget\x1b[0m\x1b[1m \x1b[0m \x1b[1m \x1b[0m\x1b[1m \x1b[0m\x1b[1;35mBox Office\x1b[0m\x1b[1m \x1b[0m \n\x1b[1;31m \x1b[0m───────────────────────────────────────────────────────────────────────────────────── \n\x1b[1;31m \x1b[0m\x1b[32m \x1b[0m\x1b[32mDec 20, 2019\x1b[0m\x1b[32m \x1b[0m \x1b[34m \x1b[0m\x1b[34mStar Wars: The Rise of \x1b[0m\x1b[34m \x1b[0m \x1b[36m \x1b[0m\x1b[36m $275,000,000\x1b[0m\x1b[36m \x1b[0m \x1b[35m \x1b[0m\x1b[35m $375,126,118\x1b[0m\x1b[35m \x1b[0m \n\x1b[1;31m \x1b[0m\x1b[32m \x1b[0m \x1b[34m \x1b[0m\x1b[34mSkywalker \x1b[0m\x1b[34m \x1b[0m \x1b[36m \x1b[0m \x1b[35m \x1b[0m \n\x1b[1;31m \x1b[0m\x1b[2;32m \x1b[0m\x1b[2;32mMay 25, 2018\x1b[0m\x1b[2;32m \x1b[0m \x1b[2;34m \x1b[0m\x1b[1;2;34mSolo\x1b[0m\x1b[2;34m: A Star Wars Story \x1b[0m\x1b[2;34m \x1b[0m \x1b[2;36m \x1b[0m\x1b[2;36m $275,000,000\x1b[0m\x1b[2;36m \x1b[0m \x1b[2;35m \x1b[0m\x1b[2;35m $393,151,347\x1b[0m\x1b[2;35m \x1b[0m \n\x1b[1;31m \x1b[0m\x1b[32m \x1b[0m\x1b[32mDec 15, 2017\x1b[0m\x1b[32m \x1b[0m \x1b[34m \x1b[0m\x1b[34mStar Wars Ep. VIII: The Last \x1b[0m\x1b[34m \x1b[0m \x1b[36m \x1b[0m\x1b[36m $262,000,000\x1b[0m\x1b[36m \x1b[0m \x1b[35m \x1b[0m\x1b[1;35m$1,332,539,889\x1b[0m\x1b[35m \x1b[0m \n\x1b[1;31m \x1b[0m\x1b[32m \x1b[0m \x1b[34m \x1b[0m\x1b[34mJedi \x1b[0m\x1b[34m \x1b[0m \x1b[36m \x1b[0m \x1b[35m \x1b[0m \n\x1b[1;31m \x1b[0m\x1b[2;32m \x1b[0m\x1b[2;32mMay 19, 1999\x1b[0m\x1b[2;32m \x1b[0m \x1b[2;34m \x1b[0m\x1b[2;34mStar Wars Ep. \x1b[0m\x1b[1;2;34mI\x1b[0m\x1b[2;34m: \x1b[0m\x1b[2;3;34mThe phantom \x1b[0m\x1b[2;34m \x1b[0m\x1b[2;34m \x1b[0m \x1b[2;36m \x1b[0m\x1b[2;36m $115,000,000\x1b[0m\x1b[2;36m \x1b[0m \x1b[2;35m \x1b[0m\x1b[2;35m$1,027,044,677\x1b[0m\x1b[2;35m \x1b[0m \n\x1b[1;31m \x1b[0m\x1b[2;32m \x1b[0m \x1b[2;34m \x1b[0m\x1b[2;3;34mMenace\x1b[0m\x1b[2;34m \x1b[0m\x1b[2;34m \x1b[0m \x1b[2;36m \x1b[0m \x1b[2;35m \x1b[0m \n\x1b[1;31m \x1b[0m \n\x1b[1;31m \x1b[0m\x1b[1;31m Syntax \x1b[0m\x1b[1;31m \x1b[0m\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 1 \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mdef\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;166;226;46;48;2;39;40;34miter_last\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m(\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mvalues\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m:\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mIterable\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m[\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mT\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m]\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m)\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34m-\x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34m>\x1b[0m \x1b[1m{\x1b[0m \n\x1b[1;31m \x1b[0m\x1b[1;31mhighlighting\x1b[0m\x1b[1;31m \x1b[0m\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 2 \x1b[0m\x1b[2;38;2;149;144;119;48;2;39;40;34m│ \x1b[0m\x1b[38;2;230;219;116;48;2;39;40;34m\"\"\"Iterate and generate a tuple w\x1b[0m \x1b[2;32m│ \x1b[0m\x1b[32m'foo'\x1b[0m: \x1b[1m[\x1b[0m \n\x1b[1;31m \x1b[0m\x1b[1;31m & \x1b[0m\x1b[1;31m \x1b[0m\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 3 \x1b[0m\x1b[2;38;2;149;144;119;48;2;39;40;34m│ \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34miter_values\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34m=\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34miter\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m(\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mvalues\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m)\x1b[0m\x1b[48;2;39;40;34m \x1b[0m \x1b[2;32m│ │ \x1b[0m\x1b[1;36m3.1427\x1b[0m, \n\x1b[1;31m \x1b[0m\x1b[1;31m pretty \x1b[0m\x1b[1;31m \x1b[0m\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 4 \x1b[0m\x1b[2;38;2;149;144;119;48;2;39;40;34m│ \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mtry\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m:\x1b[0m\x1b[48;2;39;40;34m \x1b[0m \x1b[2;32m│ │ \x1b[0m\x1b[1m(\x1b[0m \n\x1b[1;31m \x1b[0m\x1b[1;31m printing \x1b[0m\x1b[1;31m \x1b[0m\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 5 \x1b[0m\x1b[2;38;2;149;144;119;48;2;39;40;34m│ │ \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mprevious_value\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34m=\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mnext\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m(\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34miter_va\x1b[0m \x1b[2;32m│ │ │ \x1b[0m\x1b[32m'Paul Atreides'\x1b[0m, \n\x1b[1;31m \x1b[0m\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 6 \x1b[0m\x1b[2;38;2;149;144;119;48;2;39;40;34m│ \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mexcept\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;166;226;46;48;2;39;40;34mStopIteration\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m:\x1b[0m\x1b[48;2;39;40;34m \x1b[0m \x1b[2;32m│ │ │ \x1b[0m\x1b[32m'Vladimir Harkonnen'\x1b[0m, \n\x1b[1;31m \x1b[0m\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 7 \x1b[0m\x1b[2;38;2;149;144;119;48;2;39;40;34m│ │ \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mreturn\x1b[0m\x1b[48;2;39;40;34m \x1b[0m \x1b[2;32m│ │ │ \x1b[0m\x1b[32m'Thufir Hawat'\x1b[0m \n\x1b[1;31m \x1b[0m\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 8 \x1b[0m\x1b[2;38;2;149;144;119;48;2;39;40;34m│ \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mfor\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mvalue\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34min\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34miter_values\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m:\x1b[0m\x1b[48;2;39;40;34m \x1b[0m \x1b[2;32m│ │ \x1b[0m\x1b[1m)\x1b[0m \n\x1b[1;31m \x1b[0m\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 9 \x1b[0m\x1b[2;38;2;149;144;119;48;2;39;40;34m│ │ \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34myield\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mFalse\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m,\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mprevious_value\x1b[0m\x1b[48;2;39;40;34m \x1b[0m \x1b[2;32m│ \x1b[0m\x1b[1m]\x1b[0m, \n\x1b[1;31m \x1b[0m\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m10 \x1b[0m\x1b[2;38;2;149;144;119;48;2;39;40;34m│ │ \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mprevious_value\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;255;70;137;48;2;39;40;34m=\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mvalue\x1b[0m\x1b[48;2;39;40;34m \x1b[0m \x1b[2;32m│ \x1b[0m\x1b[32m'atomic'\x1b[0m: \x1b[1m(\x1b[0m\x1b[3;91mFalse\x1b[0m, \x1b[3;92mTrue\x1b[0m, \x1b[3;35mNone\x1b[0m\x1b[1m)\x1b[0m \n\x1b[1;31m \x1b[0m\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m11 \x1b[0m\x1b[2;38;2;149;144;119;48;2;39;40;34m│ \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34myield\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mTrue\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m,\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mprevious_value\x1b[0m\x1b[48;2;39;40;34m \x1b[0m \x1b[1m}\x1b[0m \n\x1b[1;31m \x1b[0m \n\x1b[1;31m \x1b[0m\x1b[1;31m Markdown \x1b[0m\x1b[1;31m \x1b[0m\x1b[36m# Markdown\x1b[0m ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ \n\x1b[1;31m \x1b[0m ┃ \x1b[1mMarkdown\x1b[0m ┃ \n\x1b[1;31m \x1b[0m\x1b[36mSupports much of the *markdown* \x1b[0m ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ \n\x1b[1;31m \x1b[0m\x1b[36m__syntax__!\x1b[0m \n\x1b[1;31m \x1b[0m Supports much of the \x1b[3mmarkdown\x1b[0m \x1b[1msyntax\x1b[0m! \n\x1b[1;31m \x1b[0m\x1b[36m- Headers\x1b[0m \n\x1b[1;31m \x1b[0m\x1b[36m- Basic formatting: **bold**, *italic*, \x1b[0m \x1b[1;33m • \x1b[0mHeaders \n\x1b[1;31m \x1b[0m\x1b[36m`code`\x1b[0m \x1b[1;33m • \x1b[0mBasic formatting: \x1b[1mbold\x1b[0m, \x1b[3mitalic\x1b[0m, \x1b[1;36;40mcode\x1b[0m \n\x1b[1;31m \x1b[0m\x1b[36m- Block quotes\x1b[0m \x1b[1;33m • \x1b[0mBlock quotes \n\x1b[1;31m \x1b[0m\x1b[36m- Lists, and more...\x1b[0m \x1b[1;33m • \x1b[0mLists, and more... \n\x1b[1;31m \x1b[0m\x1b[36m \x1b[0m \n\x1b[1;31m \x1b[0m \n\x1b[1;31m \x1b[0m\x1b[1;31m +more! \x1b[0m\x1b[1;31m \x1b[0mProgress bars, columns, styled logging handler, tracebacks, etc... \n\x1b[1;31m \x1b[0m \n"
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/tests/test_console.py
tests/test_console.py
import datetime import io import os import subprocess import sys import tempfile from typing import Optional, Tuple, Type, Union from unittest import mock import pytest from rich import errors from rich._null_file import NullFile from rich.color import ColorSystem from rich.console import ( CaptureError, Console, ConsoleDimensions, ConsoleOptions, ScreenUpdate, group, ) from rich.control import Control from rich.measure import measure_renderables from rich.padding import Padding from rich.pager import SystemPager from rich.panel import Panel from rich.region import Region from rich.segment import Segment from rich.status import Status from rich.style import Style from rich.text import Text os.get_terminal_size def test_dumb_terminal() -> None: console = Console(force_terminal=True, _environ={}) assert console.color_system is not None console = Console(force_terminal=True, _environ={"TERM": "dumb"}) assert console.color_system is None width, height = console.size assert width == 80 assert height == 25 def test_soft_wrap() -> None: console = Console(file=io.StringIO(), width=20, soft_wrap=True) console.print("foo " * 10) assert console.file.getvalue() == "foo " * 20 @pytest.mark.skipif(sys.platform == "win32", reason="does not run on windows") def test_16color_terminal() -> None: console = Console( force_terminal=True, _environ={"TERM": "xterm-16color"}, legacy_windows=False ) assert console.color_system == "standard" @pytest.mark.skipif(sys.platform == "win32", reason="does not run on windows") def test_truecolor_terminal() -> None: console = Console( force_terminal=True, legacy_windows=False, _environ={"COLORTERM": "truecolor", "TERM": "xterm-16color"}, ) assert console.color_system == "truecolor" @pytest.mark.skipif(sys.platform == "win32", reason="does not run on windows") def test_kitty_terminal() -> None: console = Console( force_terminal=True, legacy_windows=False, _environ={"TERM": "xterm-kitty"}, ) assert console.color_system == "256" def test_console_options_update() -> None: options = ConsoleOptions( ConsoleDimensions(80, 25), max_height=25, legacy_windows=False, min_width=10, max_width=20, is_terminal=False, encoding="utf-8", ) options1 = options.update(width=15) assert options1.min_width == 15 and options1.max_width == 15 options2 = options.update(min_width=5, max_width=15, justify="right") assert ( options2.min_width == 5 and options2.max_width == 15 and options2.justify == "right" ) options_copy = options.update() assert options_copy == options and options_copy is not options def test_console_options_update_height() -> None: options = ConsoleOptions( ConsoleDimensions(80, 25), max_height=25, legacy_windows=False, min_width=10, max_width=20, is_terminal=False, encoding="utf-8", ) assert options.height is None render_options = options.update_height(12) assert options.height is None assert render_options.height == 12 assert render_options.max_height == 12 def test_init() -> None: console = Console(color_system=None) assert console._color_system == None console = Console(color_system="standard") assert console._color_system == ColorSystem.STANDARD console = Console(color_system="auto") def test_size() -> None: console = Console() w, h = console.size assert console.width == w console = Console(width=99, height=101, legacy_windows=False) w, h = console.size assert w == 99 and h == 101 @pytest.mark.parametrize( "is_windows,no_descriptor_size,stdin_size,stdout_size,stderr_size,expected_size", [ # on Windows we'll use `os.get_terminal_size()` without arguments... (True, (133, 24), ValueError, ValueError, ValueError, (80, 25)), (False, (133, 24), ValueError, ValueError, ValueError, (80, 25)), # ...while on other OS we'll try to pass stdin, then stdout, then stderr to it: (False, ValueError, (133, 24), ValueError, ValueError, (133, 24)), (False, ValueError, ValueError, (133, 24), ValueError, (133, 24)), (False, ValueError, ValueError, ValueError, (133, 24), (133, 24)), (False, ValueError, ValueError, ValueError, ValueError, (80, 25)), ], ) @mock.patch("rich.console.os.get_terminal_size") def test_size_can_fall_back_to_std_descriptors( get_terminal_size_mock: mock.MagicMock, is_windows: bool, no_descriptor_size: Union[Tuple[int, int], Type[ValueError]], stdin_size: Union[Tuple[int, int], Type[ValueError]], stdout_size: Union[Tuple[int, int], Type[ValueError]], stderr_size: Union[Tuple[int, int], Type[ValueError]], expected_size: Tuple[int, int], ) -> None: def get_terminal_size_mock_impl(fileno: int = None) -> Tuple[int, int]: value = { None: no_descriptor_size, sys.__stdin__.fileno(): stdin_size, sys.__stdout__.fileno(): stdout_size, sys.__stderr__.fileno(): stderr_size, }[fileno] if value is ValueError: raise value return value get_terminal_size_mock.side_effect = get_terminal_size_mock_impl console = Console(legacy_windows=False) with mock.patch("rich.console.WINDOWS", new=is_windows): w, h = console.size assert (w, h) == expected_size def test_repr() -> None: console = Console() assert isinstance(repr(console), str) assert isinstance(str(console), str) def test_print() -> None: console = Console(file=io.StringIO(), color_system="truecolor") console.print("foo") assert console.file.getvalue() == "foo\n" def test_print_multiple() -> None: console = Console(file=io.StringIO(), color_system="truecolor") console.print("foo", "bar") assert console.file.getvalue() == "foo bar\n" def test_print_text() -> None: console = Console(file=io.StringIO(), color_system="truecolor") console.print(Text("foo", style="bold")) assert console.file.getvalue() == "\x1b[1mfoo\x1b[0m\n" def test_print_text_multiple() -> None: console = Console(file=io.StringIO(), color_system="truecolor") console.print(Text("foo", style="bold"), Text("bar"), "baz") assert console.file.getvalue() == "\x1b[1mfoo\x1b[0m bar baz\n" def test_print_json() -> None: console = Console(file=io.StringIO(), color_system="truecolor") console.print_json('[false, true, null, "foo"]', indent=4) result = console.file.getvalue() print(repr(result)) expected = '\x1b[1m[\x1b[0m\n \x1b[3;91mfalse\x1b[0m,\n \x1b[3;92mtrue\x1b[0m,\n \x1b[3;35mnull\x1b[0m,\n \x1b[32m"foo"\x1b[0m\n\x1b[1m]\x1b[0m\n' assert result == expected def test_print_json_error() -> None: console = Console(file=io.StringIO(), color_system="truecolor") with pytest.raises(TypeError): console.print_json(["foo"], indent=4) def test_print_json_data() -> None: console = Console(file=io.StringIO(), color_system="truecolor") console.print_json(data=[False, True, None, "foo"], indent=4) result = console.file.getvalue() print(repr(result)) expected = '\x1b[1m[\x1b[0m\n \x1b[3;91mfalse\x1b[0m,\n \x1b[3;92mtrue\x1b[0m,\n \x1b[3;35mnull\x1b[0m,\n \x1b[32m"foo"\x1b[0m\n\x1b[1m]\x1b[0m\n' assert result == expected def test_print_json_ensure_ascii() -> None: console = Console(file=io.StringIO(), color_system="truecolor") console.print_json(data={"foo": "💩"}, ensure_ascii=False) result = console.file.getvalue() print(repr(result)) expected = '\x1b[1m{\x1b[0m\n \x1b[1;34m"foo"\x1b[0m: \x1b[32m"💩"\x1b[0m\n\x1b[1m}\x1b[0m\n' assert result == expected def test_print_json_with_default_ensure_ascii() -> None: console = Console(file=io.StringIO(), color_system="truecolor") console.print_json(data={"foo": "💩"}) result = console.file.getvalue() print(repr(result)) expected = '\x1b[1m{\x1b[0m\n \x1b[1;34m"foo"\x1b[0m: \x1b[32m"💩"\x1b[0m\n\x1b[1m}\x1b[0m\n' assert result == expected def test_print_json_indent_none() -> None: console = Console(file=io.StringIO(), color_system="truecolor") data = {"name": "apple", "count": 1} console.print_json(data=data, indent=None) result = console.file.getvalue() expected = '\x1b[1m{\x1b[0m\x1b[1;34m"name"\x1b[0m: \x1b[32m"apple"\x1b[0m, \x1b[1;34m"count"\x1b[0m: \x1b[1;36m1\x1b[0m\x1b[1m}\x1b[0m\n' assert result == expected def test_console_null_file(monkeypatch) -> None: # When stdout and stderr are null, Console.file should be replaced with NullFile monkeypatch.setattr("sys.stdout", None) monkeypatch.setattr("sys.stderr", None) console = Console() assert isinstance(console.file, NullFile) def test_log() -> None: console = Console( file=io.StringIO(), width=80, color_system="truecolor", log_time_format="TIME", log_path=False, _environ={}, ) console.log("foo", style="red") expected = "\x1b[2;36mTIME\x1b[0m\x1b[2;36m \x1b[0m\x1b[31mfoo \x1b[0m\n" result = console.file.getvalue() print(repr(result)) assert result == expected def test_log_milliseconds() -> None: def time_formatter(timestamp: datetime) -> Text: return Text("TIME") console = Console( file=io.StringIO(), width=40, log_time_format=time_formatter, log_path=False ) console.log("foo") result = console.file.getvalue() assert result == "TIME foo \n" def test_print_empty() -> None: console = Console(file=io.StringIO(), color_system="truecolor") console.print() assert console.file.getvalue() == "\n" def test_markup_highlight() -> None: console = Console(file=io.StringIO(), color_system="truecolor") console.print("'[bold]foo[/bold]'") assert ( console.file.getvalue() == "\x1b[32m'\x1b[0m\x1b[1;32mfoo\x1b[0m\x1b[32m'\x1b[0m\n" ) def test_print_style() -> None: console = Console(file=io.StringIO(), color_system="truecolor") console.print("foo", style="bold") assert console.file.getvalue() == "\x1b[1mfoo\x1b[0m\n" def test_show_cursor() -> None: console = Console( file=io.StringIO(), force_terminal=True, legacy_windows=False, _environ={} ) console.show_cursor(False) console.print("foo") console.show_cursor(True) assert console.file.getvalue() == "\x1b[?25lfoo\n\x1b[?25h" def test_clear() -> None: console = Console(file=io.StringIO(), force_terminal=True, _environ={}) console.clear() console.clear(home=False) assert console.file.getvalue() == "\033[2J\033[H" + "\033[2J" def test_clear_no_terminal() -> None: console = Console(file=io.StringIO()) console.clear() console.clear(home=False) assert console.file.getvalue() == "" def test_get_style() -> None: console = Console() console.get_style("repr.brace") == Style(bold=True) def test_get_style_default() -> None: console = Console() console.get_style("foobar", default="red") == Style(color="red") def test_get_style_error() -> None: console = Console() with pytest.raises(errors.MissingStyle): console.get_style("nosuchstyle") with pytest.raises(errors.MissingStyle): console.get_style("foo bar") def test_render_error() -> None: console = Console() with pytest.raises(errors.NotRenderableError): list(console.render([], console.options)) def test_control() -> None: console = Console(file=io.StringIO(), force_terminal=True, _environ={}) console.control(Control.clear()) console.print("BAR") assert console.file.getvalue() == "\x1b[2JBAR\n" def test_capture() -> None: console = Console() with console.capture() as capture: with pytest.raises(CaptureError): capture.get() console.print("Hello") assert capture.get() == "Hello\n" def test_input(monkeypatch, capsys) -> None: def fake_input(prompt=""): console.file.write(prompt) return "bar" monkeypatch.setattr("builtins.input", fake_input) console = Console() user_input = console.input(prompt="foo:") assert capsys.readouterr().out == "foo:" assert user_input == "bar" def test_input_password(monkeypatch, capsys) -> None: def fake_input(prompt, stream=None): console.file.write(prompt) return "bar" import rich.console monkeypatch.setattr(rich.console, "getpass", fake_input) console = Console() user_input = console.input(prompt="foo:", password=True) assert capsys.readouterr().out == "foo:" assert user_input == "bar" def test_status() -> None: console = Console(file=io.StringIO(), force_terminal=True, width=20) status = console.status("foo") assert isinstance(status, Status) def test_justify_none() -> None: console = Console(file=io.StringIO(), force_terminal=True, width=20) console.print("FOO", justify=None) assert console.file.getvalue() == "FOO\n" def test_justify_left() -> None: console = Console(file=io.StringIO(), force_terminal=True, width=20, _environ={}) console.print("FOO", justify="left") assert console.file.getvalue() == "FOO \n" def test_justify_center() -> None: console = Console(file=io.StringIO(), force_terminal=True, width=20, _environ={}) console.print("FOO", justify="center") assert console.file.getvalue() == " FOO \n" def test_justify_right() -> None: console = Console(file=io.StringIO(), force_terminal=True, width=20, _environ={}) console.print("FOO", justify="right") assert console.file.getvalue() == " FOO\n" def test_justify_renderable_none() -> None: console = Console( file=io.StringIO(), force_terminal=True, width=20, legacy_windows=False, _environ={}, ) console.print(Panel("FOO", expand=False, padding=0), justify=None) assert console.file.getvalue() == "╭───╮\n│FOO│\n╰───╯\n" def test_justify_renderable_left() -> None: console = Console( file=io.StringIO(), force_terminal=True, width=10, legacy_windows=False, _environ={}, ) console.print(Panel("FOO", expand=False, padding=0), justify="left") assert console.file.getvalue() == "╭───╮ \n│FOO│ \n╰───╯ \n" def test_justify_renderable_center() -> None: console = Console( file=io.StringIO(), force_terminal=True, width=10, legacy_windows=False, _environ={}, ) console.print(Panel("FOO", expand=False, padding=0), justify="center") assert console.file.getvalue() == " ╭───╮ \n │FOO│ \n ╰───╯ \n" def test_justify_renderable_right() -> None: console = Console( file=io.StringIO(), force_terminal=True, width=20, legacy_windows=False, _environ={}, ) console.print(Panel("FOO", expand=False, padding=0), justify="right") assert ( console.file.getvalue() == " ╭───╮\n │FOO│\n ╰───╯\n" ) class BrokenRenderable: def __rich_console__(self, console, options): pass def test_render_broken_renderable() -> None: console = Console() broken = BrokenRenderable() with pytest.raises(errors.NotRenderableError): list(console.render(broken, console.options)) def test_export_text() -> None: console = Console(record=True, width=100) console.print("[b]foo") text = console.export_text() expected = "foo\n" assert text == expected def test_export_html() -> None: console = Console(record=True, width=100) console.print("[b]foo <script> 'test' [link=https://example.org]Click[/link]") html = console.export_html() print(repr(html)) expected = '<!DOCTYPE html>\n<html>\n<head>\n<meta charset="UTF-8">\n<style>\n.r1 {font-weight: bold}\n.r2 {color: #ff00ff; text-decoration-color: #ff00ff; font-weight: bold}\n.r3 {color: #008000; text-decoration-color: #008000; font-weight: bold}\nbody {\n color: #000000;\n background-color: #ffffff;\n}\n</style>\n</head>\n<body>\n <pre style="font-family:Menlo,\'DejaVu Sans Mono\',consolas,\'Courier New\',monospace"><code style="font-family:inherit"><span class="r1">foo &lt;</span><span class="r2">script</span><span class="r1">&gt; </span><span class="r3">&#x27;test&#x27;</span><span class="r1"> </span><a class="r1" href="https://example.org">Click</a>\n</code></pre>\n</body>\n</html>\n' assert html == expected def test_export_html_inline() -> None: console = Console(record=True, width=100) console.print("[b]foo [link=https://example.org]Click[/link]") html = console.export_html(inline_styles=True) print(repr(html)) expected = '<!DOCTYPE html>\n<html>\n<head>\n<meta charset="UTF-8">\n<style>\n\nbody {\n color: #000000;\n background-color: #ffffff;\n}\n</style>\n</head>\n<body>\n <pre style="font-family:Menlo,\'DejaVu Sans Mono\',consolas,\'Courier New\',monospace"><code style="font-family:inherit"><span style="font-weight: bold">foo </span><span style="font-weight: bold"><a href="https://example.org">Click</a></span>\n</code></pre>\n</body>\n</html>\n' assert html == expected EXPECTED_SVG = '<svg class="rich-terminal" viewBox="0 0 1238 74.4" xmlns="http://www.w3.org/2000/svg">\n <!-- Generated with Rich https://www.textualize.io -->\n <style>\n\n @font-face {\n font-family: "Fira Code";\n src: local("FiraCode-Regular"),\n url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Regular.woff2") format("woff2"),\n url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Regular.woff") format("woff");\n font-style: normal;\n font-weight: 400;\n }\n @font-face {\n font-family: "Fira Code";\n src: local("FiraCode-Bold"),\n url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Bold.woff2") format("woff2"),\n url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Bold.woff") format("woff");\n font-style: bold;\n font-weight: 700;\n }\n\n .terminal-3526644552-matrix {\n font-family: Fira Code, monospace;\n font-size: 20px;\n line-height: 24.4px;\n font-variant-east-asian: full-width;\n }\n\n .terminal-3526644552-title {\n font-size: 18px;\n font-weight: bold;\n font-family: arial;\n }\n\n .terminal-3526644552-r1 { fill: #608ab1;font-weight: bold }\n.terminal-3526644552-r2 { fill: #c5c8c6 }\n </style>\n\n <defs>\n <clipPath id="terminal-3526644552-clip-terminal">\n <rect x="0" y="0" width="1219.0" height="23.4" />\n </clipPath>\n \n </defs>\n\n <rect fill="#292929" stroke="rgba(255,255,255,0.35)" stroke-width="1" x="1" y="1" width="1236" height="72.4" rx="8"/><text class="terminal-3526644552-title" fill="#c5c8c6" text-anchor="middle" x="618" y="27">Rich</text>\n <g transform="translate(26,22)">\n <circle cx="0" cy="0" r="7" fill="#ff5f57"/>\n <circle cx="22" cy="0" r="7" fill="#febc2e"/>\n <circle cx="44" cy="0" r="7" fill="#28c840"/>\n </g>\n \n <g transform="translate(9, 41)" clip-path="url(#terminal-3526644552-clip-terminal)">\n <rect fill="#cc555a" x="0" y="1.5" width="36.6" height="24.65" shape-rendering="crispEdges"/>\n <g class="terminal-3526644552-matrix">\n <text class="terminal-3526644552-r1" x="0" y="20" textLength="36.6" clip-path="url(#terminal-3526644552-line-0)">foo</text><text class="terminal-3526644552-r2" x="48.8" y="20" textLength="61" clip-path="url(#terminal-3526644552-line-0)">Click</text><text class="terminal-3526644552-r2" x="1220" y="20" textLength="12.2" clip-path="url(#terminal-3526644552-line-0)">\n</text>\n </g>\n </g>\n</svg>\n' def test_export_svg() -> None: console = Console(record=True, width=100) console.print( "[b red on blue reverse]foo[/] [blink][link=https://example.org]Click[/link]" ) svg = console.export_svg() print(repr(svg)) assert svg == EXPECTED_SVG def test_export_svg_specified_unique_id() -> None: expected_svg = EXPECTED_SVG.replace("terminal-3526644552", "given-id") console = Console(record=True, width=100) console.print( "[b red on blue reverse]foo[/] [blink][link=https://example.org]Click[/link]" ) svg = console.export_svg(unique_id="given-id") print(repr(svg)) assert svg == expected_svg def test_save_svg() -> None: console = Console(record=True, width=100) console.print( "[b red on blue reverse]foo[/] [blink][link=https://example.org]Click[/link]" ) with tempfile.TemporaryDirectory() as path: export_path = os.path.join(path, "example.svg") console.save_svg(export_path) with open(export_path, "rt", encoding="utf-8") as svg_file: assert svg_file.read() == EXPECTED_SVG def test_save_text() -> None: console = Console(record=True, width=100) console.print("foo") with tempfile.TemporaryDirectory() as path: export_path = os.path.join(path, "rich.txt") console.save_text(export_path) with open(export_path, "rt") as text_file: assert text_file.read() == "foo\n" def test_save_html() -> None: expected = '<!DOCTYPE html>\n<html>\n<head>\n<meta charset="UTF-8">\n<style>\n\nbody {\n color: #000000;\n background-color: #ffffff;\n}\n</style>\n</head>\n<body>\n <pre style="font-family:Menlo,\'DejaVu Sans Mono\',consolas,\'Courier New\',monospace"><code style="font-family:inherit">foo\n</code></pre>\n</body>\n</html>\n' console = Console(record=True, width=100) console.print("foo") with tempfile.TemporaryDirectory() as path: export_path = os.path.join(path, "example.html") console.save_html(export_path) with open(export_path, "rt") as html_file: html = html_file.read() print(repr(html)) assert html == expected def test_no_wrap() -> None: console = Console(width=10, file=io.StringIO()) console.print("foo bar baz egg", no_wrap=True) assert console.file.getvalue() == "foo bar ba\n" def test_soft_wrap() -> None: console = Console(width=10, file=io.StringIO()) console.print("foo bar baz egg", soft_wrap=True) assert console.file.getvalue() == "foo bar baz egg\n" def test_unicode_error() -> None: try: with tempfile.TemporaryFile("wt", encoding="ascii") as tmpfile: console = Console(file=tmpfile) console.print(":vampire:") except UnicodeEncodeError as error: assert "PYTHONIOENCODING" in str(error) else: assert False, "didn't raise UnicodeEncodeError" def test_bell() -> None: console = Console(force_terminal=True, _environ={}) console.begin_capture() console.bell() assert console.end_capture() == "\x07" def test_pager() -> None: console = Console(_environ={}) pager_content: Optional[str] = None def mock_pager(content: str) -> None: nonlocal pager_content pager_content = content pager = SystemPager() pager._pager = mock_pager with console.pager(pager): console.print("[bold]Hello World") assert pager_content == "Hello World\n" with console.pager(pager, styles=True, links=False): console.print("[bold link https:/example.org]Hello World") assert pager_content == "Hello World\n" def test_out() -> None: console = Console(width=10) console.begin_capture() console.out(*(["foo bar"] * 5), sep=".", end="X") assert console.end_capture() == "foo bar.foo bar.foo bar.foo bar.foo barX" def test_render_group() -> None: @group(fit=False) def renderable(): yield "one" yield "two" yield "three" # <- largest width of 5 yield "four" renderables = [renderable() for _ in range(4)] console = Console(width=42) min_width, _ = measure_renderables(console, console.options, renderables) assert min_width == 42 def test_render_group_fit() -> None: @group() def renderable(): yield "one" yield "two" yield "three" # <- largest width of 5 yield "four" renderables = [renderable() for _ in range(4)] console = Console(width=42) min_width, _ = measure_renderables(console, console.options, renderables) assert min_width == 5 def test_get_time() -> None: console = Console( get_time=lambda: 99, get_datetime=lambda: datetime.datetime(1974, 7, 5) ) assert console.get_time() == 99 assert console.get_datetime() == datetime.datetime(1974, 7, 5) def test_console_style() -> None: console = Console( file=io.StringIO(), color_system="truecolor", force_terminal=True, style="red" ) console.print("foo") expected = "\x1b[31mfoo\x1b[0m\n" result = console.file.getvalue() assert result == expected def test_no_color() -> None: console = Console( file=io.StringIO(), color_system="truecolor", force_terminal=True, no_color=True ) console.print("[bold magenta on red]FOO") expected = "\x1b[1mFOO\x1b[0m\n" result = console.file.getvalue() print(repr(result)) assert result == expected def test_quiet() -> None: console = Console(file=io.StringIO(), quiet=True) console.print("Hello, World!") assert console.file.getvalue() == "" @pytest.mark.skipif(sys.platform == "win32", reason="does not run on windows") def test_screen() -> None: console = Console( color_system=None, force_terminal=True, force_interactive=True, _environ={} ) with console.capture() as capture: with console.screen(): console.print("Don't panic") expected = "\x1b[?1049h\x1b[H\x1b[?25lDon't panic\n\x1b[?1049l\x1b[?25h" result = capture.get() print(repr(result)) assert result == expected @pytest.mark.skipif(sys.platform == "win32", reason="does not run on windows") def test_screen_update() -> None: console = Console( width=20, height=4, color_system="truecolor", force_terminal=True, _environ={} ) with console.capture() as capture: with console.screen() as screen: screen.update("foo", style="blue") screen.update("bar") screen.update() result = capture.get() print(repr(result)) expected = "\x1b[?1049h\x1b[H\x1b[?25l\x1b[34mfoo\x1b[0m\x1b[34m \x1b[0m\n\x1b[34m \x1b[0m\n\x1b[34m \x1b[0m\n\x1b[34m \x1b[0m\x1b[34mbar\x1b[0m\x1b[34m \x1b[0m\n\x1b[34m \x1b[0m\n\x1b[34m \x1b[0m\n\x1b[34m \x1b[0m\x1b[34mbar\x1b[0m\x1b[34m \x1b[0m\n\x1b[34m \x1b[0m\n\x1b[34m \x1b[0m\n\x1b[34m \x1b[0m\x1b[?1049l\x1b[?25h" assert result == expected def test_height() -> None: console = Console(width=80, height=46) assert console.height == 46 def test_columns_env() -> None: console = Console(_environ={"COLUMNS": "314"}, legacy_windows=False) assert console.width == 314 # width take precedence console = Console(width=40, _environ={"COLUMNS": "314"}, legacy_windows=False) assert console.width == 40 # Should not fail console = Console(width=40, _environ={"COLUMNS": "broken"}, legacy_windows=False) def test_lines_env() -> None: console = Console(_environ={"LINES": "220"}) assert console.height == 220 # height take precedence console = Console(height=40, _environ={"LINES": "220"}) assert console.height == 40 # Should not fail console = Console(width=40, _environ={"LINES": "broken"}) def test_screen_update_class() -> None: screen_update = ScreenUpdate([[Segment("foo")], [Segment("bar")]], 5, 10) assert screen_update.x == 5 assert screen_update.y == 10 console = Console(force_terminal=True) console.begin_capture() console.print(screen_update) result = console.end_capture() print(repr(result)) expected = "\x1b[11;6Hfoo\x1b[12;6Hbar" assert result == expected def test_is_alt_screen() -> None: console = Console(force_terminal=True) if console.legacy_windows: return assert not console.is_alt_screen with console.screen(): assert console.is_alt_screen assert not console.is_alt_screen def test_set_console_title() -> None: console = Console(force_terminal=True, _environ={}) if console.legacy_windows: return with console.capture() as captured: console.set_window_title("hello") result = captured.get() assert result == "\x1b]0;hello\x07" def test_update_screen() -> None: console = Console(force_terminal=True, width=20, height=5, _environ={}) if console.legacy_windows: return with pytest.raises(errors.NoAltScreen): console.update_screen("foo") console.begin_capture() with console.screen(): console.update_screen("foo") console.update_screen("bar", region=Region(2, 3, 8, 4)) result = console.end_capture() print(repr(result)) expected = "\x1b[?1049h\x1b[H\x1b[?25l\x1b[1;1Hfoo \x1b[2;1H \x1b[3;1H \x1b[4;1H \x1b[5;1H \x1b[4;3Hbar \x1b[5;3H \x1b[6;3H \x1b[7;3H \x1b[?1049l\x1b[?25h" assert result == expected def test_update_screen_lines() -> None: console = Console(force_terminal=True, width=20, height=5) if console.legacy_windows: return with pytest.raises(errors.NoAltScreen): console.update_screen_lines([]) def test_update_options_markup() -> None: console = Console() options = console.options assert options.update(markup=False).markup == False assert options.update(markup=True).markup == True def test_print_width_zero() -> None: console = Console() with console.capture() as capture: console.print("Hello", width=0) assert capture.get() == "" def test_size_properties() -> None: console = Console(width=80, height=25, legacy_windows=False) assert console.size == ConsoleDimensions(80, 25) console.size = (10, 20) assert console.size == ConsoleDimensions(10, 20) console.width = 5 assert console.size == ConsoleDimensions(5, 20) console.height = 10 assert console.size == ConsoleDimensions(5, 10) def test_print_newline_start() -> None: console = Console(width=80, height=25) console.begin_capture() console.print("Foo", new_line_start=True) console.print("Foo\nbar\n", new_line_start=True) result = console.end_capture() assert result == "Foo\n\nFoo\nbar\n\n" def test_is_terminal_broken_file() -> None: console = Console() def _mock_isatty(): raise ValueError() console.file.isatty = _mock_isatty assert console.is_terminal == False @pytest.mark.skipif(sys.platform == "win32", reason="not relevant on Windows") def test_detect_color_system() -> None: console = Console(_environ={"TERM": "rxvt-unicode-256color"}, force_terminal=True) assert console._detect_color_system() == ColorSystem.EIGHT_BIT def test_reset_height() -> None: """Test height is reset when rendering complex renderables.""" # https://github.com/Textualize/rich/issues/2042 class Panels: def __rich_console__(self, console, options): yield Panel("foo") yield Panel("bar") console = Console( force_terminal=True, color_system="truecolor", width=20, height=40, legacy_windows=False, ) with console.capture() as capture: console.print(Panel(Panels()), height=12) result = capture.get() print(repr(result))
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
true
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/docs/source/conf.py
docs/source/conf.py
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- Project information ----------------------------------------------------- import sphinx_rtd_theme from importlib.metadata import Distribution html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] project = "Rich" copyright = "Will McGugan" author = "Will McGugan" # The full version, including alpha/beta/rc tags release = Distribution.from_name("rich").version # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ "sphinx.ext.autodoc", "sphinx.ext.viewcode", "sphinx.ext.napoleon", "sphinx.ext.intersphinx", "sphinx.ext.autosectionlabel", "sphinx_copybutton", "sphinx_rtd_theme", ] # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = [] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # # html_theme = "alabaster" # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] intersphinx_mapping = {"python": ("http://docs.python.org/3", None)} autodoc_typehints = "description" html_css_files = [ "https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/fira_code.min.css" ]
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/examples/columns.py
examples/columns.py
""" This example shows how to display content in columns. The data is pulled from https://randomuser.me """ import json from urllib.request import urlopen from rich.console import Console from rich.columns import Columns from rich.panel import Panel def get_content(user): """Extract text from user dict.""" country = user["location"]["country"] name = f"{user['name']['first']} {user['name']['last']}" return f"[b]{name}[/b]\n[yellow]{country}" console = Console() users = json.loads(urlopen("https://randomuser.me/api/?results=30").read())["results"] console.print(users, overflow="ignore", crop=False) user_renderables = [Panel(get_content(user), expand=True) for user in users] console.print(Columns(user_renderables))
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/examples/rainbow.py
examples/rainbow.py
""" This example demonstrates how to write a custom highlighter. """ from random import randint from rich import print from rich.highlighter import Highlighter class RainbowHighlighter(Highlighter): def highlight(self, text): for index in range(len(text)): text.stylize(f"color({randint(16, 255)})", index, index + 1) rainbow = RainbowHighlighter() print(rainbow("I must not fear. Fear is the mind-killer."))
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/examples/justify2.py
examples/justify2.py
""" This example demonstrates the justify argument to print. """ from rich.console import Console from rich.panel import Panel console = Console(width=20) style = "bold white on blue" panel = Panel("Rich", style="on red", expand=False) console.print(panel, style=style) console.print(panel, style=style, justify="left") console.print(panel, style=style, justify="center") console.print(panel, style=style, justify="right")
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false
Textualize/rich
https://github.com/Textualize/rich/blob/53757bc234cf18977cade41a5b64f3abaccb0b85/examples/save_table_svg.py
examples/save_table_svg.py
""" Demonstrates how to export a SVG """ from rich.console import Console from rich.table import Table table = Table(title="Star Wars Movies") table.add_column("Released", style="cyan", no_wrap=True) table.add_column("Title", style="magenta") table.add_column("Box Office", justify="right", style="green") table.add_row("Dec 20, 2019", "Star Wars: The Rise of Skywalker", "$952,110,690") table.add_row("May 25, 2018", "Solo: A Star Wars Story", "$393,151,347") table.add_row("Dec 15, 2017", "Star Wars Ep. V111: The Last Jedi", "$1,332,539,889") table.add_row("Dec 16, 2016", "Rogue One: A Star Wars Story", "$1,332,439,889") console = Console(record=True) console.print(table, justify="center") console.save_svg("table.svg", title="save_table_svg.py") import os import webbrowser webbrowser.open(f"file://{os.path.abspath('table.svg')}")
python
MIT
53757bc234cf18977cade41a5b64f3abaccb0b85
2026-01-04T14:39:17.105051Z
false