[Python] How to import submodules under tests/ and still run only tests in subdirectory in...

Discussão em 'Python' iniciado por Stack, Maio 15, 2025.

  1. Stack

    Stack Membro Participativo

    I have a the following test folder layout:

    tests
    ├── __init__.py
    ├── conftest.py
    ├── data_validation
    │ └── test_data_validation.py
    └── per_vendor
    ├── __init__.py
    ├── vendor_a
    │ ├── conftest.py
    │ └── test_vendor_a.py
    └── vendor_b
    ├── __init__.py
    ├── conftest.py
    └── test_vendor_b.py


    In tests/conftest.py I do:

    import pytest

    from tests import per_vendor

    @pytest.fixture
    def database_with_data(empty_database: Engine) -> Engine:
    helpers = [
    per_vendor.vendor_a.conftest.fill_with_data_for_a,
    per_vendor.vendor_b.conftest.fill_with_data_for_b,
    ]
    for cur in helpers:
    cur(empty_database)
    return Engine


    Here, empty_database is another fixture providing an empty database for my tests.

    This setup works if I run all tests: python -m pytest tests/. However, if I only want to run tests in a specific subfolder, e.g. python -m pytest tests/data_validation/, all tests relying on the fixture database_with_data fail due to an error: AttributeError: module 'tests.per_vendor' has no attribute 'vendor_a'.

    Note that tests.per_vendor still can be imported. However, the submodules there are not picked up.

    I'd like to understand better why in one case the submodules are picked up and in the other they aren't. Also, if possible, I'd like to find a solution that allows the modular setup and running tests in subfolders.

    Continue reading...

Compartilhe esta Página