1

I'm trying to create a test at pytest.

The test I'm doing is this one:

def test_read_main_endpoint(client):
    response = client.get("/")
    assert response.status_code == 200
    assert response.json()["status_code"] == "200"
    assert response.json()["detail"] == "ok"
    assert response.json()["result"] == "working"

conftest file is this one:

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


@pytest.fixture(scope="session")
def client():
    return TestClient(app=app)

The problem is that it doesn't find the file.

tests/conftest.py:3: in <module>
    from app.main import app
app/main.py:3: in <module>
    from core.config import settings
E   ModuleNotFoundError: No module named 'core'

The file where it's trying to get is in the folder of the app/core not the folder of the test:

- app/
  |- __init__.py
  |- main.py
  |- core/
     |- __init__.py
     |- config.py
- tests/
  |- __init__.py
  |- conftest.py
  |- test_main.py

main file is this one:

import uvicorn
from fastapi import FastAPI
from core.config import settings


app = FastAPI()


@app.get("/")
async def root():
    return {
        "status_code": "200",
        "detail": "ok",
        "result": "working",
        }


if __name__ == "__main__":
    uvicorn.run("main:app", host=settings.host,
                port=settings.port, reload=True)

conf file is this one:

import os
from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    model_config = SettingsConfigDict(env_file='.env')
    host: str = Field('127.0.0.1', env='HOST')
    port: int = Field('8008', env='PORT')
    base_dir: str = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


settings = Settings()

Why doesn't the pytest get files from the folder?

ENIAC
  • 813
  • 1
  • 8
  • 19
Daricyos
  • 11
  • 2
  • One way is to modify your python path in you `tests/conftest.py` script https://stackoverflow.com/questions/70172116/modulenotfounderror-no-module-named/70172229#70172229 – Tzane Aug 03 '23 at 12:56
  • 1
    change the core.config to app.core.config. See if it helps – ozs Aug 03 '23 at 13:15

1 Answers1

0

You need to change the core.config to app.core.config.

the pythonpath should be configure to parent folder of app and tests and once you run it from the tests you need to specify the full namespace of the module

ozs
  • 3,051
  • 1
  • 10
  • 19
  • If I change `core.config` to `app.core.config`. Pytest works but app dont work when I try to run the `python app/main.py` application. `from app.core.config import settings ModuleNotFoundError: No module named 'app'` – Daricyos Aug 03 '23 at 16:01
  • how do you run the app ? do u know if the PYTHONPATH sets to the parent folder of app ? – ozs Aug 03 '23 at 17:14