Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Make better error message for invalid --app string #3977

Merged
merged 5 commits into from
Feb 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions litestar/cli/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@


if TYPE_CHECKING:
from types import ModuleType

from litestar.openapi import OpenAPIConfig
from litestar.routes import ASGIRoute, HTTPRoute, WebSocketRoute
from litestar.types import AnyCallable
Expand Down Expand Up @@ -272,9 +274,24 @@ def _bool_from_env(key: str, default: bool = False) -> bool:
return value in ("true", "1")


def _validate_app_path(app_path: str) -> tuple[ModuleType, str]:
try:
module_path, app_name = app_path.split(":")
except ValueError:
console.print(f"[bold red] Invalid argument passed --app {app_path!r}: Expected 'module_path:app'")
sys.exit(1)

try:
module = importlib.import_module(module_path)
except ImportError:
console.print(f"[bold red] Invalid argument passed --app {app_path!r}: Module not found")
sys.exit(1)

return module, app_name


def _load_app_from_path(app_path: str) -> LoadedApp:
module_path, app_name = app_path.split(":")
module = importlib.import_module(module_path)
module, app_name = _validate_app_path(app_path)
app = getattr(module, app_name)
is_factory = False
if not isinstance(app, Litestar) and callable(app):
Expand Down
24 changes: 24 additions & 0 deletions tests/unit/test_cli/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,27 @@ def custom_command(app: Litestar) -> None:

assert result.exit_code == 0
mock_command_callback.assert_called_once()


@pytest.mark.xdist_group("cli_autodiscovery")
@pytest.mark.parametrize("invalid_app", ["invalid", "info_with_app_dir"])
def test_incorrect_app_argument(
invalid_app: str, mocker: "MockerFixture", runner: "CliRunner", create_app_file: CreateAppFileFixture
) -> None:
app_file = "main.py"
app_file_without_extension = app_file.split(".")[0]

create_app_file(
file=app_file,
directory="src",
content=CREATE_APP_FILE_CONTENT,
subdir="info_with_app_dir",
init_content=f"from .{app_file_without_extension} import create_app",
)

mock = mocker.patch("litestar.cli.commands.core.show_app_info")
result = runner.invoke(cli_command, ["--app", invalid_app, "--app-dir", "src", "info"])

assert result.exit_code == 1

mock.assert_not_called()
Loading