cozos cozos - 1 month ago 18
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)
foo.do_something_to_database()


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

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


However, my tests fail because it seems like the
do_something
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
@patch('sqlalchemy.event.registrat._listen_fn')
) but to no avail.

Has anyone ever encountered this before?

Answer

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)

    @patch('my_package.user.do_something')
    def test_user(mock_do_something):
        user = User() 
        assertSomething(user)