| 1 | import textwrap |
| 2 | from io import StringIO |
| 3 | |
| 4 | from rich.console import Console |
| 5 | from rich.text import Text |
| 6 | |
| 7 | from cyclopts.panel import CycloptsPanel |
| 8 | |
| 9 | |
| 10 | def _render(panel) -> str: |
| 11 | buf = StringIO() |
| 12 | console = Console(file=buf, width=70, force_terminal=True, highlight=False, color_system=None, legacy_windows=False) |
| 13 | console.print(panel) |
| 14 | return buf.getvalue() |
| 15 | |
| 16 | |
| 17 | def test_cyclopts_panel_stringifies_plain_message(): |
| 18 | """A plain object without rich-protocol attrs is rendered via str().""" |
| 19 | output = _render(CycloptsPanel("hello world")) |
| 20 | expected = textwrap.dedent( |
| 21 | """\ |
| 22 | ╭─ Error ────────────────────────────────────────────────────────────╮ |
| 23 | │ hello world │ |
| 24 | ╰────────────────────────────────────────────────────────────────────╯ |
| 25 | """ |
| 26 | ) |
| 27 | assert output == expected |
| 28 | |
| 29 | |
| 30 | def test_cyclopts_panel_passes_through_rich_renderable(): |
| 31 | """A message implementing __rich__ is passed through unwrapped.""" |
| 32 | |
| 33 | class HasRich: |
| 34 | def __str__(self) -> str: |
| 35 | return "string fallback" |
| 36 | |
| 37 | def __rich__(self) -> Text: |
| 38 | return Text("rich body") |
| 39 | |
| 40 | output = _render(CycloptsPanel(HasRich())) |
| 41 | assert "rich body" in output |
| 42 | assert "string fallback" not in output |
| 43 | |
| 44 | |
| 45 | def test_cyclopts_panel_passes_through_rich_console_renderable(): |
| 46 | """A message implementing __rich_console__ is also passed through.""" |
| 47 | |
| 48 | class HasRichConsole: |
| 49 | def __str__(self) -> str: |
| 50 | return "string fallback" |
| 51 | |
| 52 | def __rich_console__(self, console, options): |
| 53 | yield Text("console body") |
| 54 | |
| 55 | output = _render(CycloptsPanel(HasRichConsole())) |
| 56 | assert "console body" in output |
| 57 | assert "string fallback" not in output |