Skip to content

Rollback when using pytest #940

Closed Answered by DanielAndreasen
DanielAndreasen asked this question in Questions
Discussion options

You must be logged in to vote

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

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by DanielAndreasen
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
1 participant