Rollback when using pytest #940
-
First Check
Commit to Help
Example Codeimport os
import pytest
import sqlalchemy as sa
from sqlalchemy.orm import sessionmaker
from sqlmodel import Session
url = f"postgresql+psycopg2://{os.getenv('PGUSER')}:{os.getenv('PGPASSWORD')}@{os.getenv('PGHOST')}/{os.getenv('MYDB')}"
engine = sa.create_engine(url)
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
@pytest.fixture()
def session():
connection = engine.connect()
transaction = connection.begin()
session = TestingSessionLocal(bind=connection)
nested = connection.begin_nested()
@sa.event.listens_for(session, "after_transaction_end")
def end_savepoint(session, transaction):
nonlocal nested
if not nested.is_active:
nested = connection.begin_nested()
yield session
# Run this after the test (regardless of status)
session.close()
transaction.rollback()
connection.close() DescriptionI want to test the API I'm writing with fastAPI and SQLModel. The API commits to the database, but I want to make a rollback when testing. The problem is that the If I change the line: I'm open for another solution as well. Operating SystemLinux Operating System DetailsNo response SQLModel Version0.0.16 Python VersionPython 3.12.0 Additional ContextInspiration found here. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I was able to solve this after many trials and errors (mostly errors). This is the code: import pytest
import sqlalchemy as sa
from sqlmodel import Session
from myapp.db.database import engine
@pytest.fixture()
def session():
connection = engine.connect()
transaction = connection.begin()
session = Session(bind=connection)
nested = connection.begin_nested()
@sa.event.listens_for(session, "after_transaction_end")
def end_savepoint(session, transaction):
nonlocal nested
if not nested.is_active:
nested = connection.begin_nested()
yield session
session.close()
transaction.rollback()
connection.close() The trick was to use |
Beta Was this translation helpful? Give feedback.
I was able to solve this after many trials and errors (mostly errors).
This is the code:
The trick was to use