diff --git a/litestar/utils/module_loader.py b/litestar/utils/module_loader.py index 09dbf9f8d6..1fab629dd5 100644 --- a/litestar/utils/module_loader.py +++ b/litestar/utils/module_loader.py @@ -2,7 +2,6 @@ from __future__ import annotations -import os.path import sys from importlib import import_module from importlib.util import find_spec @@ -39,7 +38,8 @@ def module_to_os_path(dotted_path: str = "app") -> Path: except ModuleNotFoundError as e: raise TypeError(f"Couldn't find the path for {dotted_path}") from e - return Path(str(src.origin).rsplit(os.path.sep + "__init__.py", maxsplit=1)[0]) + path = Path(str(src.origin)) + return path.parent if path.is_file() else path def import_string(dotted_path: str) -> Any: diff --git a/tests/unit/test_utils/test_module_loader.py b/tests/unit/test_utils/test_module_loader.py index b76315980f..dec9993b72 100644 --- a/tests/unit/test_utils/test_module_loader.py +++ b/tests/unit/test_utils/test_module_loader.py @@ -17,10 +17,14 @@ def test_import_string() -> None: _ = import_string("imaginary_module_that_doesnt_exist.Config") # a random nonexistent class -def test_module_path() -> None: +def test_module_path(tmp_path: Path, monkeypatch: MonkeyPatch) -> None: the_path = module_to_os_path("litestar.config.compression") assert the_path.exists() + tmp_path.joinpath("simple_module.py").write_text("x = 'foo'") + monkeypatch.syspath_prepend(tmp_path) + os_path = module_to_os_path("simple_module") + assert os_path == Path(tmp_path) with pytest.raises(TypeError): _ = module_to_os_path("litestar.config.compression.Config") _ = module_to_os_path("litestar.config.compression.extra.module") @@ -35,5 +39,4 @@ def test_import_string_cached(tmp_path: Path, monkeypatch: MonkeyPatch) -> None: tmp_path.joinpath("testmodule.py").write_text("x = 'foo'") monkeypatch.chdir(tmp_path) monkeypatch.syspath_prepend(tmp_path) - assert import_string("testmodule.x") == "foo"