fastapi / typer

Typer, build great CLIs. Easy to code. Based on Python type hints.
https://typer.tiangolo.com/
MIT License
15.92k stars 675 forks source link

Testing: runner.invoke reuses 'app' object, causing cached properties to exist when they're not supposed to #364

Open Dymstro opened 2 years ago

Dymstro commented 2 years ago

First Check

Commit to Help

Example Code

from typer.testing import CliRunner
from .main import app

runner = CliRunner()

def test_list_databases() -> None:
    # This command causes an internal 'databases' object to be cached.

    result = runner.invoke(app, ["databases", "list"]
    assert result.exit_code == 0

def test_create_database() -> None:
    # This command accesses some cached properties (using cached-property package).
    # Those objects aren't supposed to exist yet, but they were already created in previous tests.
    # This causes the command to use old data and crash.

    result = runner.invoke(app, ["databases", "create", "tests-db", "MariaDB"])
    assert result.exit_code == 0

Description

CliRunner.invoke reuses 'app' causing different behavior than just running them outside tests.

My code uses some cached properties that get cached in earlier tests. This causes some commands to use old data, which causes it to crash. Normally this would never happen as the program exits after a single command.

Operating System

Linux

Operating System Details

No response

Typer Version

0.4.0

Python Version

3.7

Additional Context

No response

DvdNss commented 2 months ago

happening for me as well, some options get cached and re-used in the following tests, making the tests fail