cozos cozos - 11 months ago 82
Python Question

Python: How to mock SQLAlchemy event handlers (using mock.unittest)

So I have a SQLAlchemy model that has an event listener:

class User(db.Model):
id = db.Column(db.Integer, primary_key=True)

@event.listens_for(User, "after_insert")
@event.listens_for(User, "after_update")
def do_something(mapper, connection, self):
foo = SomeClass(self)

And I have a unit test that needs to update/insert the Model

def test_user(mock_do_something):
user = User() # This insert will invoke 'do_something' via the event listener.

However, my tests fail because it seems like the
function is still being called and hasn't been mocked successfully. I tried reading through how patching here (it is calling this function right?) and I have tried to look through the SQLAlchemy source code here to find the appropriate module to patch (something like
) but to no avail.

Has anyone ever encountered this before?

Answer Source

I've found a workaround to disable events on unit tests

import sqlalchemy as sa
from unittest import TestCase
from mypackage.models.user import User

class TestUser(TestCase):
    def setUp(self):
        super(TestUser, self).setUp()
        sa.event.remove(User, "after_insert", do_something)
        sa.event.remove(User, "after_update", do_something)

    def tearDown(self):
        super(TestUser, self).tearDown()
        sa.event.listen(User, "after_insert", do_something)
        sa.event.listen(User, "after_update", do_something)

    def test_user(mock_do_something):
        user = User()