Search code examples
pythonpytestfastapi

import file mismatch when running pytest


I am following the testdriven.io Test-Driven Development with FastAPI and Docker tutorial and I am stuck on the Pytest setup step. I have checked over an over again to see what I am missing, and keep coming up short.

The code sample from the tutorial shows that, in conftest.py, you are to ahve the following from statement:

from app import main
from app.config import get_settings, Settings

For starters, Pycharm is telling me that it is unable to import anything from above. My Folder Structure: enter image description here

main.py:

import os

from fastapi import FastAPI, Depends
from tortoise.contrib.fastapi import register_tortoise

from .config import get_settings, Settings

app = FastAPI()

register_tortoise(
    app,
    db_url=os.environ.get("DATABASE_URL"),
    modules={"models": ["app.models.tortoise"]},
    generate_schemas=False,
    add_exception_handlers=True,
)


@app.get("/ping")
async def pong(settings: Settings = Depends(get_settings)):
    return {"ping": "pong", "environment": settings.environment, "testing": settings.testing}

conftest.py

import os

import pytest
from starlette.testclient import TestClient

from app import main
from app.config import get_settings, Settings


def get_settings_override():
    return Settings(testing=1, database_url=os.environ.get("DATABASE_TEST_URL"))


@pytest.fixture(scope="module")
def test_app():
    # set up
    main.app.dependency_overrides[get_settings] = get_settings_override
    with TestClient(main.app) as test_client:
        # testing
        yield test_client

    # tear down

The tutorial has you run the tests using docker-compose exec web python -m pytest

This is the output I get when running the tests: enter image description here

Any help would be appreciated. I feel like this is entry level stuff that is causing an extreme headache.


Solution

  • Thanks to @MatsLindh for the help. As he mentioned in his comments above, the tutorial has you running pytest on the entire project instead of just the tests folder. Running directly on tests solved my issue with pytest failing. He also gave good advice on getting imports to work correctly in an IDE by suggesting to look at the pytest documentation for further integration steps.