Testing
Click’s CliRunner runs a command in isolation. It feeds
input to Click’s own prompts and captures what the command prints. It does not know about Rich, so tests of
commands that use Rich prompts can go wrong:
- Password prompts (
Prompt.ask(..., password=True)) callgetpass. This reads from the terminal, not from theinputthat you give to the runner. - Rich’s global console (used by
rich.print()) keeps the colour setting it had when it was first created. If it was created in a real terminal, ANSI codes get intoresult.output.
rich_click.testing.CliRunner is a drop-in replacement that fixes this. Change the import and nothing else:
import click
def login() -> None:
def test_login() -> None: assert result.output == "Username: jane\nPassword: \nRemember me? [y/n]: y\nSaved login for jane\n"Prompts on every Rich Console read from input, and typed text is echoed as with click.prompt(), except for
passwords. If your tests already patch Console.input, the runner keeps your patch.
Rich output does not depend on the terminal that runs the tests:
- Rich’s global console follows the runner’s
colorsetting, even if your app set a colour system on it. Useinvoke(..., color=True)to keep colour codes. A separateConsole()that your app creates keeps the colour setting it detected when it was created. - The global console is not interactive, so progress bars and
Livedisplays print only their final state. - The runner unsets
FORCE_COLOR,NO_COLOR,TTY_COMPATIBLE,TTY_INTERACTIVE,TERMandCOLORTERM. It setsCOLUMNS=80andLINES=25, the width that Click uses. Withcolor=True, Rich uses its 16 standard colours. Pass any of these variables inenvto test with them. - A width that your app sets on the global console is kept.
Changes that a command makes to the global console, such as push_theme(), are undone after each invocation.