|
I'm encountering an issue where pytest fails to run tests in my local development environment due to a ModuleNotFoundError, specifically stating that there is "No module named 'app'". However, my backend application runs perfectly fine within a Docker container, and the app module is recognized without any issues in that environment. Project Structure: project-root/ ├── app/ │ ├── main.py │ ├── config.py │ ├── setup/ │ │ ├── __init__.py │ ├── data/ │ │ ├── technology/ │ │ │ ├── enums/ │ │ │ ├── __init__.py │ │ │ ├── technology_type_enum.py │ ├── tests/ │ │ ├── data/ │ │ │ ├── __init__.py │ │ │ ├── test_import.py │ │ ├── conftest.py ├── pyproject.toml ├── README.md ├── CHANGELOG.md conftest.py: from config import config from setup import create_app, db import os import pytest @pytest.fixture(scope='session') def app(): os.environ['ENV'] = 'test' app = create_app(config.SCHEDULER_API_ENABLED) yield app @pytest.fixture(scope='session') def client(app): with app.test_client() as client: with app.app_context(): db.create_all() yield client test_import.py: def test_import(): try: from data.technology.enums import TechnologyTypeEnum assert True except ModuleNotFoundError: assert False, "Import failed" Error Message: ERROR app/tests - ModuleNotFoundError: No module named 'data.technology' What I’ve Tried:PYTHONPATH Adjustments: I set PYTHONPATH=$(pwd)/app and PYTHONPATH=$(pwd) before running pytest, but neither resolved the issue. I also created a pytest.ini file in the root directory to specify the pythonpath, but it didn’t resolve the issues either: [pytest] pythonpath = app [pytest] pythonpath = absolute/path/to/project/appDocker Environment: The backend runs without issues inside a Docker container. The app module is correctly recognized, and everything works as expected. Running pytest in Docker: I also tried running pytest inside the Docker container to ensure consistency with the environment where the backend works correctly. Unfortunately, I encountered the same ModuleNotFoundError for the app module even within the Docker environment. Path Modifications: I tried modifying sys.path directly in conftest.py to include the project root directory, but this also didn’t resolve the issue. Question:Why does pytest fail to recognize the app module both locally and in Docker, when the backend runs perfectly fine in Docker? How can I configure my environment to allow pytest to recognize the app module, or what might I be missing in my setup? Any guidance on resolving this discrepancy between the working backend and the failing pytest would be greatly appreciated. (责任编辑:) |
