pytest-dev/pytest · error · CouldNotResolvePathError

Could not resolve for {path}

Error message

Could not resolve for {path}

What it means

Thrown by resolve_pkg_root_and_module_name when a Python file path cannot be mapped to a package root because no ancestor directory contains an __init__.py (and, with namespace packages enabled, no importable namespace root is found). The function walks parents looking for the last directory holding __init__.py and computes the dotted module name; if both the regular and namespace-package searches fail it raises CouldNotResolvePathError. It typically surfaces during collection/import when pytest needs the module's importable name for the test's node id.

Source

Thrown at src/_pytest/pathlib.py:932

    pkg_root: Path | None = None
    pkg_path = resolve_package_path(path)
    if pkg_path is not None:
        pkg_root = pkg_path.parent
    if consider_namespace_packages:
        start = pkg_root if pkg_root is not None else path.parent
        for candidate in (start, *start.parents):
            module_name = compute_module_name(candidate, path)
            if module_name and is_importable(module_name, path):
                # Point the pkg_root to the root of the namespace package.
                pkg_root = candidate
                break

    if pkg_root is not None:
        module_name = compute_module_name(pkg_root, path)
        if module_name:
            return pkg_root, module_name

    raise CouldNotResolvePathError(f"Could not resolve for {path}")


def is_importable(module_name: str, module_path: Path) -> bool:
    """
    Return if the given module path could be imported normally by Python, akin to the user
    entering the REPL and importing the corresponding module name directly, and corresponds
    to the module_path specified.

    :param module_name:
        Full module name that we want to check if is importable.
        For example, "app.models".

    :param module_path:
        Full path to the python module/package we want to check if is importable.
        For example, "/projects/src/app/models.py".
    """
    try:
        # Note this is different from what we do in ``_import_module_using_spec``, where we explicitly search through

View on GitHub (pinned to 98b357f69e)

Solutions

  1. Add an empty __init__.py to the test file's directory (and ancestor dirs) so it forms a proper package.
  2. Ensure the directory names from the package root down to the file are valid Python identifiers (no hyphens, no leading digits).
  3. If you intend namespace packages, make sure the root directory is on sys.path (e.g. via pythonpath ini option or conftest.py) and enable namespace package consideration.
  4. Move the test file into the existing package tree (e.g. under src/pkgname/tests/) so it inherits an importable package root.

Example fix

// before (structure)
project/
  tests/
    test_foo.py          # no __init__.py anywhere
// after
project/
  tests/
    __init__.py
    test_foo.py
Defensive patterns

Strategy: validation

Validate before calling

from pathlib import Path

def has_package_root(path: Path) -> bool:
    return any((p / "__init__.py").is_file() and p.name.isidentifier()
               for p in [path.parent, *path.parents])

# before calling resolve_pkg_root_and_module_name
if not has_package_root(Path(mypath)):
    raise SystemExit(f"{mypath} is not inside a Python package; add __init__.py")

Try / catch

from _pytest.pathlib import CouldNotResolvePathError
try:
    pkg_root, modname = resolve_pkg_root_and_module_name(p)
except CouldNotResolvePathError:
    # fall back to treating as a standalone module or surface a clear error
    ...

Prevention

When it happens

Trigger: resolve_pkg_root_and_module_name(path) is called on a .py file whose entire parent chain has no __init__.py files (a standalone script outside any package), or whose candidate root directory name is not a valid Python identifier, or where the computed module name does not correspond to an importable path on sys.path.

Common situations: Running pytest against a loose test file with no __init__.py in its directory; tests placed in a project that uses a non-src layout where the test dir is not a package; renaming a package directory to something containing hyphens or starting with a digit; enabling consider_namespace_packages while sys.path does not include the namespace root.

Related errors


AI-assisted analysis of pytest-dev/pytest@98b357f69e (2026-08-04). Data as JSON: /data/errors/b66815e510f88e4e.json. Report an issue: GitHub.