Skip to content

Commit

Permalink
fix(#3554): correct module_to_os_path to return directory paths (#…
Browse files Browse the repository at this point in the history
…3565)

* Update module_loader.py

* feat: adds a test for single file module

---------

Co-authored-by: Cody Fincher <[email protected]>
  • Loading branch information
supercoder-dev and cofin authored Aug 25, 2024
1 parent 5223d2d commit b1f7134
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 4 deletions.
4 changes: 2 additions & 2 deletions litestar/utils/module_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from __future__ import annotations

import os.path
import sys
from importlib import import_module
from importlib.util import find_spec
Expand Down Expand Up @@ -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:
Expand Down
7 changes: 5 additions & 2 deletions tests/unit/test_utils/test_module_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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"

0 comments on commit b1f7134

Please sign in to comment.