Prevent touching db during unit testing with SQLAlchemy Prevent touching db during unit testing with SQLAlchemy flask flask

Prevent touching db during unit testing with SQLAlchemy


You can utilize SQLAlchemy's event system for this, which allows you to use a callback when SQLAlchemy performs different events.

In your case, you would probably want to use the before_execute() or before_cursor_execute() events. For example...

from sqlalchemy import eventclass TestCase(unittest.TestCase):    def setUp(self):        engine = ... # create or access your engine somehow        event.listen(engine, "before_cursor_execute", self._before_cursor_execute)    # We can also clean up the event handler after the test if we want to    def tearDown(self):        engine = ... # access your engine again        event.remove(engine, "before_cursor_execute", self._before_cursor_execute)    def _before_cusor_execute(self, conn, cursor, statement, parameters, context, executemany):        raise RuntimeError('No touching the database!')