Skip to content

Commit

Permalink
pathlib: handle filenames starting with . in module_name_from_path
Browse files Browse the repository at this point in the history
  • Loading branch information
nicoddemus committed Mar 2, 2024
1 parent 4dea183 commit 5867426
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/_pytest/pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -648,6 +648,11 @@ def module_name_from_path(path: Path, root: Path) -> str:
if len(path_parts) >= 2 and path_parts[-1] == "__init__":
path_parts = path_parts[:-1]

# Module names cannot contain ".", normalize them to "_". This prevents
# a directory having a "." in the name (".env.310" for example) causing extra intermediate modules.
# Also, important to replace "." at the start of paths, as those are considered relative imports.
path_parts = [x.replace(".", "_") for x in path_parts]

return ".".join(path_parts)


Expand Down
12 changes: 12 additions & 0 deletions testing/test_pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,18 @@ def test_module_name_from_path(self, tmp_path: Path) -> None:
result = module_name_from_path(tmp_path / "__init__.py", tmp_path)
assert result == "__init__"

# Modules which start with "." are considered relative and will not be imported
# unless part of a package, so we replace it with a "_" when generating the fake module name.
result = module_name_from_path(tmp_path / ".env/tests/test_foo.py", tmp_path)
assert result == "_env.tests.test_foo"

# We want to avoid generating extra intermediate modules if some directory just happens
# to contain a "." in the name.
result = module_name_from_path(
tmp_path / ".env.310/tests/test_foo.py", tmp_path
)
assert result == "_env_310.tests.test_foo"

def test_insert_missing_modules(
self, monkeypatch: MonkeyPatch, tmp_path: Path
) -> None:
Expand Down

0 comments on commit 5867426

Please sign in to comment.