| 1 |
import io |
| 2 |
|
| 3 |
from rich.abc import RichRenderable |
| 4 |
from rich.console import Console |
| 5 |
from rich.panel import Panel |
| 6 |
from rich.text import Text |
| 7 |
|
| 8 |
|
| 9 |
class Foo: |
| 10 |
def __rich__(self) -> Text: |
| 11 |
return Text("Foo") |
| 12 |
|
| 13 |
|
| 14 |
def test_rich_cast(): |
| 15 |
foo = Foo() |
| 16 |
console = Console(file=io.StringIO()) |
| 17 |
console.print(foo) |
| 18 |
assert console.file.getvalue() == "Foo\n" |
| 19 |
|
| 20 |
|
| 21 |
class Fake: |
| 22 |
def __getattr__(self, name): |
| 23 |
return 12 |
| 24 |
|
| 25 |
def __repr__(self) -> str: |
| 26 |
return "Fake()" |
| 27 |
|
| 28 |
|
| 29 |
def test_rich_cast_fake(): |
| 30 |
fake = Fake() |
| 31 |
console = Console(file=io.StringIO()) |
| 32 |
console.print(fake) |
| 33 |
assert console.file.getvalue() == "Fake()\n" |
| 34 |
|
| 35 |
|
| 36 |
def test_rich_cast_container(): |
| 37 |
foo = Foo() |
| 38 |
console = Console(file=io.StringIO(), legacy_windows=False) |
| 39 |
console.print(Panel.fit(foo, padding=0)) |
| 40 |
assert console.file.getvalue() == "╭───╮\n│Foo│\n╰───╯\n" |
| 41 |
|
| 42 |
|
| 43 |
def test_abc(): |
| 44 |
foo = Foo() |
| 45 |
assert isinstance(foo, RichRenderable) |
| 46 |
assert isinstance(Text("hello"), RichRenderable) |
| 47 |
assert isinstance(Panel("hello"), RichRenderable) |
| 48 |
assert not isinstance(foo, str) |
| 49 |
assert not isinstance("foo", RichRenderable) |
| 50 |
assert not isinstance([], RichRenderable) |
| 51 |
|
| 52 |
|
| 53 |
def test_cast_deep(): |
| 54 |
class B: |
| 55 |
def __rich__(self) -> Foo: |
| 56 |
return Foo() |
| 57 |
|
| 58 |
class A: |
| 59 |
def __rich__(self) -> B: |
| 60 |
return B() |
| 61 |
|
| 62 |
console = Console(file=io.StringIO()) |
| 63 |
console.print(A()) |
| 64 |
assert console.file.getvalue() == "Foo\n" |
| 65 |
|
| 66 |
|
| 67 |
def test_cast_recursive(): |
| 68 |
class B: |
| 69 |
def __rich__(self) -> "A": |
| 70 |
return A() |
| 71 |
|
| 72 |
def __repr__(self) -> str: |
| 73 |
return "<B>" |
| 74 |
|
| 75 |
class A: |
| 76 |
def __rich__(self) -> B: |
| 77 |
return B() |
| 78 |
|
| 79 |
def __repr__(self) -> str: |
| 80 |
return "<A>" |
| 81 |
|
| 82 |
console = Console(file=io.StringIO()) |
| 83 |
console.print(A()) |
| 84 |
assert console.file.getvalue() == "<B>\n" |