title: Pytest Flask rollback transactions after tests when using the Unit of Work pattern
body: <p>I am studying the &quot;Cosmic Python&quot; book and chapter 6 explains how to use the Unit of Work pattern to change the interaction with the database/repository.</p>
  <p>Chapter 6 of the book can be accessed here:
  <a href="https://www.cosmicpython.com/book/chapter_06_uow.html" rel="nofollow noreferrer">https://www.cosmicpython.com/book/chapter_06_uow.html</a></p>
  <p>The code provided by the author is the following:</p>
  <pre><code>from __future__ import annotations
  import abc
  from sqlalchemy import create_engine
  from sqlalchemy.orm import sessionmaker
  from sqlalchemy.orm.session import Session
  
  from allocation import config
  from allocation.adapters import repository
  
  
  class AbstractUnitOfWork(abc.ABC):
      products: repository.AbstractRepository
  
      def __enter__(self) -&gt; AbstractUnitOfWork:
          return self
  
      def __exit__(self, *args):
          self.rollback()
  
      @abc.abstractmethod
      def commit(self):
          raise NotImplementedError
  
      @abc.abstractmethod
      def rollback(self):
          raise NotImplementedError
  
  
  
  DEFAULT_SESSION_FACTORY = sessionmaker(bind=create_engine(
      config.get_postgres_uri(),
      isolation_level=&quot;REPEATABLE READ&quot;,
  ))
  
  class SqlAlchemyUnitOfWork(AbstractUnitOfWork):
  
      def __init__(self, session_factory=DEFAULT_SESSION_FACTORY):
          self.session_factory = session_factory
  
      def __enter__(self):
          self.session = self.session_factory()  # type: Session
          self.products = repository.SqlAlchemyRepository(self.session)
          return super().__enter__()
  
      def __exit__(self, *args):
          super().__exit__(*args)
          self.session.close()
  
      def commit(self):
          self.session.commit()
  
      def rollback(self):
          self.session.rollback()
  </code></pre>
  <p>I am trying to test my endpoints on Flask but I could not make it rollback the data inserted after each test.</p>
  <p>To solve that I tried to install the package <code>pytest-flask-sqlalchemy</code> but with the following error:</p>
  <p><code>'SqlAlchemyUnitOfWork' object has no attribute 'engine'</code></p>
  <p>I do not quite understand how <code>pytest-flask-sqlalchemy</code> works and I have no clue on how to make the Unit of Work rollback transactions after a test.</p>
  <p>Is it possible to make it work the way the author implemented it?</p>
  <h1>Edited</h1>
  <p>It is possible to replicate my situation through the following repository:</p>
  <p><a href="https://github.com/Santana94/CosmicPythonRollbackTest" rel="nofollow noreferrer">https://github.com/Santana94/CosmicPythonRollbackTest</a></p>
  <p>You should get that the test is not rolling back previous actions by cloning it and running <code>make all</code>.</p>