Textualize / rich

Rich is a Python library for rich text and beautiful formatting in the terminal.
https://rich.readthedocs.io/en/latest/
MIT License
48.13k stars 1.69k forks source link

[QUESTION] How can be tested the way a Text object is rendered? #3310

Closed mmartinortiz closed 2 months ago

mmartinortiz commented 3 months ago

Hi,

I'd like to test that a Text object is rendered in a specific way. For example, given the following function:

def greetings(who: str) -> Text:
    greeting = Text("Hello")
    return greeting.append(f" {who}", style="blue")

I would like to write a test that makes sure that the format is as expected, kind of:

def test_greetings():
    assert greetings("Jon") == "Hello [blue]Jon[/blue]"

Looking into possible solution I found this suggestion about capturing the output. In that case, I can compare with something like Hello\x1b[34m Jon\x1b[0m\n, but I find this a bit cryptic for a test.

github-actions[bot] commented 3 months ago

We found the following entry in the FAQ which you may find helpful:

Feel free to close this issue if you found an answer in the FAQ. Otherwise, please give us a little time to review.

This is an automated reply, generated by FAQtory

willmcgugan commented 2 months ago

Text objects have markup attribute which returns the equivalent console markup.

mmartinortiz commented 2 months ago

Thanks,

That is exactly what I was looking for. As reference, this is how the test would look like:

def test_greetings():
    assert greetings("Jon").markup == "Hello [blue]Jon[/blue]"
github-actions[bot] commented 2 months ago

I hope we solved your problem.

If you like using Rich, you might also enjoy Textual