Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

289
Visualizações
I can not run fastapi and pytest at the same time due to an import module error

I'm having a circular problem that I'm not able to solve. I started my project as follows:

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

In main.py I have:

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)

In 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"}

The error I get when I run the script from the same level as main.py with 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'

If I write the name of the folder before main:

from api.main import app

I get an error with the con/server.py module:

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'

If I now change in main to include the name of the folder:

from api.conf.server import HOST, PORT

The test finally works, but now If I try to run the server wiht python main.py it will not work anymore:

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

What I'm doing wrong to get into this loop?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Your should import your modules using absolute imports, as you already described in the final part of your question:

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

and make sure to include the directory containing your package directory in PYTHONPATH, as shown here (Option 3). Then, you should be able to run your script. Other options listed in the above link might help you as well.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda