SQLAlchemy use Transactions for E2E Testing

Viewed 21

I am writing E2E tests for our software and would like to figure out why the rollback call does not roll the DB back to the state when the test started.

I use a decorator for my pytest test functions.

The issue I get is that data that I write to the DB during the tests persists, even though I call the rollback() in the final statement. Which indicates that the transaction is not setup or SQLAlchemy is doing something else in the background.

I see SQLAlchemy has the SAVEPOINT feature but I am not sure if this is what I really need. I think my request is pretty simple yet the framework obfuscates it. Or simply that I am not too experienced with it...

Note - the functions tested can have multiple commit calls...

def get_postgres_db():
    
    v2_session = sessionmaker(
        autocommit=False,
        autoflush=False,
        bind=v2_engine
    )
    
    try:
        yield v2_session
    finally:
        v2_session.close()

def postgres_test_decorator(test_function):
    """
    Decorator to open db connection and roll back regardless of test outcome
    Can be ported into pytest later
    """

    def the_decorator(*args, **kwargs):

        try:
            postgres_session = list(get_postgres_db())[0]

            # IN MY SQL MIND I WOULD LIKE TO DO HERE 

            # BEGIN TRANSACTION

            test_function(postgres_session)

        finally:
            # THIS SHOULD ROLLBACK TO ORIGINAL STATE

            # ROLLBACK
            postgres_session.rollback()

    return the_decorator
0 Answers
Related