pytest icon indicating copy to clipboard operation
pytest copied to clipboard

Allow dotted test filenames (`*.test.py`) via one-line change to `compute_module_name`

Open pasha-omni opened this issue 6 months ago • 6 comments

Proposal

Escape dots inside path parts in _pytest.pathlib.compute_module_name, the same way module_name_from_path already does:

  def compute_module_name(root: Path, module_path: Path) -> str | None:
      ...
      names = list(relative.parts)
      if not names:
          return None
      if names[-1] == "__init__":
          names.pop()
+     names = [p.replace(".", "_") for p in names]
      return ".".join(names)

This makes pkg/foo.test.py collect as module pkg.foo_test instead of the invalid pkg.foo.test.

Motivation

The *.test.py filename convention has a property that test_*.py and *_test.py do not: a test file colocated next to its target module cannot be imported by production code. A dot in the filename makes it an invalid Python module name, so the import system cannot reach it through any import statement. With this change, pytest becomes the only thing that can load it.

In practice this:

  • Allows colocating tests next to source (pkg/foo.py + pkg/foo.test.py) without any risk of production code importing test helpers, fixtures, or mock data
  • Eliminates a class of "we accidentally shipped/imported test code" bugs that naming conventions alone cannot prevent
  • Mirrors the widely-used foo.test.ts convention from the JS/TS ecosystem

Current behavior

compute_module_name joins path parts with . without escaping, so pkg/foo.test.py produces the module name pkg.foo.test. Under --import-mode=importlib, _import_module_using_spec then walks up looking for the parent package, concludes it needs pkg.foo, finds pkg/__init__.py adjacent, and loads pkg/__init__.py under the wrong name pkg.foo — silently aliasing the package onto a name that should belong to the sibling source module pkg/foo.py. Subsequent import pkg.foo from inside the test gets the package's __init__.py, not foo.py.

Under --import-mode=prepend|append, the failure is loud: ModuleNotFoundError: No module named 'pkg.foo.test'; 'pkg.foo' is not a package.

The fallback module_name_from_path already applies this exact dot-escape (line 796 of _pytest/pathlib.py):

path_parts = tuple(x.replace(".", "_") for x in path_parts)

But that fallback only runs when resolve_pkg_root_and_module_name fails (no __init__.py chain) — exactly the case where colocation is least useful.

Why this is safe

The proposed line is verbatim what pytest already does in its sibling code path. Applying it consistently in compute_module_name:

  • Has no effect on any filename without a dot (the vast majority of test files)
  • Doesn't change behavior for files where compute_module_name already produces a valid module name
  • Maps dotted filenames to a deterministic name (foo.test.py → foo_test)

Related

  • #1426 (closed, "warn about invalid test module names")
  • #6422 (closed as invalid, "filename contains more than one dot")

pasha-omni avatar May 24 '26 20:05 pasha-omni

Id welcome this as opt in butbid reject a default as of now

RonnyPfannschmidt avatar May 24 '26 21:05 RonnyPfannschmidt

Acknowledging the opt-in preference. Here is a concrete design that leaves the current default untouched.

Add a boolean ini option, off by default, that gates the dot-escaping in compute_module_name:

[tool.pytest.ini_options]
consider_dotted_test_files = true

When false (the default), compute_module_name behaves exactly as it does today. When true, it escapes dots in the path parts the same way module_name_from_path already does at pathlib.py (the x.replace(".", "_") step), so pkg/foo.test.py resolves to pkg.foo_test instead of the invalid pkg.foo.test.

Two things worth noting:

  • This also narrows an existing inconsistency: module_name_from_path already escapes dots, while compute_module_name does not. The option lets users opt into the consistent behaviour without changing the default for everyone.
  • A real pkg/foo_test.py sitting next to pkg/foo.test.py would collide on the escaped name. That surfaces through pytest's existing duplicate-module detection; I would add a test for it and call it out in the docs.

If this shape looks acceptable, I am happy to open the PR: the ini option, the gated change, tests for both states plus the collision case, and a docs and changelog entry. Open to a different option name if you prefer one.

golikovichev avatar Jun 14 '26 09:06 golikovichev

I would like to take on this issue , if that's fine

siddy-stack avatar Aug 18 '26 03:08 siddy-stack

I am preparing a focused opt-in implementation for this issue. The current default behavior will remain unchanged; the proposed ini option will escape dots in package-relative path parts and will include regression coverage for the opt-in and default cases. @siddy-stack, I saw your August 18 note and would appreciate a heads-up if you have active work in progress; otherwise I will proceed with a small branch and link it here.

fire-mirror avatar Sep 14 '26 01:09 fire-mirror

I reproduced the current failure with a package containing pkg/foo.py and pkg/foo.test.py (with python_files=*.py) on Python 3.13.5: all three import modes fail, while importlib loads the package's __init__.py as pkg.foo.

One detail from the reproduction: escaping the computed name to pkg.foo_test is sufficient for importlib mode, but prepend/append still cannot use importlib.import_module because no pkg/foo_test.py exists. I am testing a narrowly scoped opt-in path that keeps the existing defaults and uses pytest's path-based loader for the dotted file in those modes as well. If the intended scope is importlib-only, I can keep the option limited to that mode.

fire-mirror avatar Sep 14 '26 01:09 fire-mirror

Given the name mapping issue that creep up whenever people try im inclined to reject this on grounds of problematic differences to standard python behavior

RonnyPfannschmidt avatar Sep 14 '26 05:09 RonnyPfannschmidt