Skip to content

Commit f6a1dbc

Browse files
authored
fix: misleading error message upon ImportError with --app argument to CLI (#4152)
1 parent d2fd22f commit f6a1dbc

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

litestar/cli/_utils.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -283,10 +283,12 @@ def _validate_app_path(app_path: str) -> tuple[ModuleType, str]:
283283

284284
try:
285285
module = importlib.import_module(module_path)
286-
except ImportError:
287-
console.print(f"[bold red] Invalid argument passed --app {app_path!r}: Module not found")
288-
sys.exit(1)
289-
286+
except ImportError as e:
287+
if e.name == module_path:
288+
console.print(f"[bold red] Invalid argument passed --app {app_path!r}: Module not found")
289+
sys.exit(1)
290+
else:
291+
raise (e)
290292
return module, app_name
291293

292294

tests/unit/test_cli/test_cli.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,3 +114,20 @@ def test_incorrect_app_argument(
114114
assert result.exit_code == 1
115115

116116
mock.assert_not_called()
117+
118+
119+
@pytest.mark.xdist_group("cli_autodiscovery")
120+
def test_invalid_import_in_app_argument(
121+
runner: "CliRunner", create_app_file: CreateAppFileFixture, tmp_project_dir: "Path"
122+
) -> None:
123+
app_file = "main.py"
124+
125+
create_app_file(
126+
file=app_file,
127+
content="from something import bar\n" + CREATE_APP_FILE_CONTENT,
128+
)
129+
130+
app_dir = str(tmp_project_dir.absolute())
131+
132+
result = runner.invoke(cli_command, ["--app", "main:create_app", "--app-dir", app_dir, "info"])
133+
assert isinstance(result.exception, ModuleNotFoundError)

0 commit comments

Comments
 (0)