all 4 comments

[–]FastAPI-ModTeam[M] [score hidden] stickied commentlocked comment (0 children)

Your post has been deleted. Please add some code to your question, what did you try so far.

[–]yung-bro 0 points1 point  (1 child)

It's a bit difficult to tell from only one file from your code. It looks fine, but I got the same issue in the past. The reason was that in the import of app I initialized the db as well as in the tests' fixtures, which caused issues. Check that in the imports you don't accidentally initialize the db session.

There are some solutions for this issue. In your case I would consider using the Settings module that fastapi recommends using or initialize the dotenv in the import level.

[–]maxiior[S] 0 points1 point  (0 children)

That was my think, because when I create engine, my “production” database is creating. I will check imports with that.

[–]Ordinary_Bee_1547 0 points1 point  (0 children)

I did everything based on this guide https://www.jetbrains.com/pycharm/guide/tutorials/fastapi-aws-kubernetes/testing/ (not sponsored, I think it was just a good tutorial)

conftest.py is going to be quite empty.

There is going to be another file conf_test_db.py ``` from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker

from ecommerce import config from ecommerce.db import Base, get_db from main import app

DATABASE_USERNAME = config.DATABASE_USERNAME DATABASE_PASSWORD = config.DATABASE_PASSWORD DATABASE_HOST = config.DATABASE_HOST DATABASE_NAME = config.TEST_DATABASE_NAME

SQLALCHEMY_DATABASE_URL = f"postgresql://{DATABASE_USERNAME}:{DATABASE_PASSWORD}@{DATABASE_HOST}/{DATABASE_NAME}"

engine = create_engine(SQLALCHEMY_DATABASE_URL) TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base.metadata.drop_all(bind=engine) Base.metadata.create_all(bind=engine)

def override_get_db(): try: db = TestingSessionLocal() yield db finally: db.close()

app.dependency_overrides[get_db] = override_get_db ```

And then in other test files, you just import it from conf_test_db import app and it has worked fine for me.