[Python] Issue with pytest: ImportError - attempted relative import with no known parent...

Discussão em 'Python' iniciado por Stack, Fevereiro 21, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working with pytest in a FastAPI project and trying to run unit tests.

    Project Structure:

    app
    └── fastapi_app
    ├── __init__.py
    ├── celery_worker.py
    ├── Dockerfile
    ├── main.py
    ├── middlewares
    │ ├── middlewares.py
    ├── requirements.txt
    ├── routes
    │ ├── process.py
    ├── tests
    │ ├── test_process.py


    I run pytest from the app directory:

    (venv) PS C:\Users\Administrador\Desktop\code\repo\fastapi_celery_redis\app> pytest


    But I get the following error:

    ================================================= test session starts =================================================
    platform win32 -- Python 3.13.2, pytest-8.3.4, pluggy-1.5.0
    rootdir: C:\Users\Administrador\Desktop\code\repo\fastapi_celery_redis\app
    plugins: anyio-4.8.0
    collected 0 items / 1 error

    ======================================================= ERRORS ========================================================
    _________________________________ ERROR collecting fastapi_app/tests/test_process.py __________________________________
    ImportError while importing test module 'C:\Users\Administrador\Desktop\code\repo\fastapi_celery_redis\app\fastapi_app\tests\test_process.py'.
    Hint: make sure your test modules/packages have valid Python names.
    Traceback:
    ..\..\..\..\..\AppData\Local\Programs\Python\Python313\Lib\importlib\__init__.py:88: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
    fastapi_app\tests\test_process.py:3: in <module>
    from ..main import app
    E ImportError: attempted relative import with no known parent package
    =============================================== short test summary info ===============================================
    ERROR fastapi_app/tests/test_process.py
    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    ================================================== 1 error in 0.90s ===================================================


    test_process.py content:

    import pytest
    from fastapi.testclient import TestClient
    from ..main import app

    # Cliente de pruebas
    client = TestClient(app)

    def test_add_task_success():
    """Prueba cuando la tarea se envía exitosamente"""
    data = {"number": 10, "text": "Test task"}
    response = client.post("/add-task", json=data)

    assert response.status_code == 200
    result = response.json()
    assert result["error"] is False
    assert result["message"] == "Tarea enviada exitosamente"
    assert result["result"]["message"] == "Tarea enviada"



    What I've Tried So Far:

    1. Running pytest from both app and fastapi_app directories.
    2. Changing the import in test_process.py to an absolute import

    from fastapi_app.main import app



    None of these have solved the issue. How can I properly import app in my test file and make pytest recognize my package structure?

    Continue reading...

Compartilhe esta Página