Skip to content

Pytest Discovery broken when multiple modules have overlapping paths #11275

Open

Description

@rowillia

Issue

Pytest Discovery appears to get confused if a module previously imported by a conftest.py module has a path that's a prefix of the module currently being imported. As the conftests are being imported in _getconftestmodules (https://github.com/pytest-dev/pytest/blob/main/src/_pytest/config/__init__.py#L608-L616) we can get path conflicts.

In our case it's causing a crash, in more pathalogical cases it could cause the wrong conftest.py file to be imported and referenced.

pytest and operating system versions

pytest==7.4.0
macOS 13.5 & Ubuntu

Minimal Example

mkdir -p pytest_discover_failure && cd pytest_discover_failure
mkdir -p a/tests/helpers
touch a/tests/__init__.py
touch a/tests/helpers/__init__.py
cat <<EOF > a/tests/helpers/test_helpers.py
def get_a():
    return 'a'
EOF
cat <<EOF > a/tests/test_a.py
def test_a():
    assert 1 == 1
EOF
cat <<EOF > a/conftest.py
import pytest
from tests.helpers.test_helpers import get_a


@pytest.fixture()
def some_fixture():
    return get_a()
EOF
mkdir -p b/tests
touch b/tests/__init__.py
cat <<EOF > b/tests/conftest.py
import pytest

@pytest.fixture()
def some_fixture():
    return 'b'
EOF
cat <<EOF > b/tests/test_b.py
def test_a():
    assert 1 == 1
EOF

pytest --collect-only ./a ./b

Output:

$ pytest --collect-only ./a ./b
ImportError while loading conftest '/Users/roy/code/oss/pytest_discover_failure/b/tests/conftest.py'.
ModuleNotFoundError: No module named 'tests.conftest'

Note that pytest --collect-only works for ./a and ./b individually.

Activity

  1. RonnyPfannschmidt commented on Aug 3, 2023

    @RonnyPfannschmidt
    Member

    Currently you'd need init files in both a and b

    The import roots proposal is supposed to resolve the issue

  2. added
    topic: configrelated to config handling, argument parsing and config file
    on Aug 8, 2023
  3. Zac-HD commented on Aug 9, 2023

    @Zac-HD
    Member

    @RonnyPfannschmidt the import roots proposal is #10824, right?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: collectionrelated to the collection phasetopic: configrelated to config handling, argument parsing and config file

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions