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

时间秒杀一切 提交于 2021-02-10 12:06:18

问题


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?


回答1:


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 ...



回答2:


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)


来源:https://stackoverflow.com/questions/36473283/python-how-to-mock-sqlalchemy-event-handlers-using-mock-unittest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!