Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

279
Views
No puedo ejecutar fastapi y pytest al mismo tiempo debido a un error en el módulo de importación

Tengo un problema circular que no puedo resolver. Comencé mi proyecto de la siguiente manera:

 . ├── conf │ ├── __init__.py │ └── server.py ├── __init__.py ├── main.py ├── requirements.txt └── tests ├── __init__.py └── v1 ├── __init__.py └── test_item.py

En main.py tengo:

 from fastapi import FastAPI import uvicorn from conf.server import HOST, PORT app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"} if __name__ == '__main__': uvicorn.run("main:app", host=HOST, port=PORT, reload=True)

En test_main.py

 from fastapi.testclient import TestClient from main import app client = TestClient(app) def test_read_main(): response = client.get("/") assert response.status_code == 200 assert response.json() == {"message": "Hello World"}

El error que recibo cuando ejecuto el script desde el mismo nivel que main.py con pytest :

 C:\Python39\lib\importlib\__init__.py:127: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests\v1\test_item.py:3: in <module> from main import app E ModuleNotFoundError: No module named 'main'

Si escribo el nombre de la carpeta antes de main:

 from api.main import app

Recibo un error con el módulo con/server.py:

 Hint: make sure your test modules/packages have valid Python names. Traceback: C:\Python39\lib\importlib\__init__.py:127: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests\v1\test_item.py:3: in <module> from api.main import app main.py:4: in <module> from conf.server import HOST, PORT E ModuleNotFoundError: No module named 'conf'

Si ahora cambio en main para incluir el nombre de la carpeta:

 from api.conf.server import HOST, PORT

La prueba finalmente funciona, pero ahora si trato de ejecutar el servidor con python main.py ya no funcionará:

 from api.conf.server import HOST, PORT ModuleNotFoundError: No module named 'api'

¿Qué estoy haciendo mal para entrar en este bucle?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Debe importar sus módulos usando importaciones absolutas, como ya describió en la parte final de su pregunta:

 from api.main import app from api.conf.server import HOST, PORT

y asegúrese de incluir el directorio que contiene el directorio de su paquete en PYTHONPATH , como se muestra aquí (Opción 3). Entonces, debería poder ejecutar su script. Otras opciones enumeradas en el enlace anterior también pueden ayudarlo.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!