简体   繁体   中英

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?

Perhaps having a Context Manager class that removes the listener and add it again on exit could do the trick.

Something like:

class SADeListener(object):
    def __init__(self, class_, event, callable_):
        self.class_ = class_
        self.event = event
        self.callable_ = callable_

    def __enter__(self):
        sqlalchemy.event.remove(self.class_, self.event, self.callable_)

    def __exit__(self, type_, value, tb):
        sqlalchemy.event.listen(self.class_, self.event, self.callable_)

And then just use it:

with SADeListener(User, "after_insert", do_something),
   SADeListener(User, "after_update", do_something):
    .. code ...

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM