6

I've been using Django for several years, but have recently decided to try out Flask for a new API. Thanks to Carl Meyers excellent presentation on testing Django at PyCon, I've been using the following technique to prevent touching the database in my Django unit tests:

cursor_wrapper = Mock()
cursor_wrapper.side_effect = RuntimeError("No touching the database!")

@patch('django.db.backends.util.CursorWrapper', cursor_wrapper)
class TestPurchaseModel(TestCase):
   '''Purchase model test suite'''
   ...

My question is can anyone tell me how to do this same basic technique with SQLAlchemy? In other words, I want any time I actually run a query against the database to produce a runtime error.

1 Answer 1

5

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 event

class 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!')
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the reply! I will test, and if it works I will select as the answer. If it doesn't, then I will notify via comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.