Python:如何模拟SQLAlchemy事件处理程序(使用mock.unittest) [英] Python: How to mock SQLAlchemy event handlers (using mock.unittest)
问题描述
所以我有一个带有事件侦听器的SQLAlchemy模型:
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)
但是,我的测试失败了,因为似乎 do_something
函数仍在被调用并且没有被成功模拟.我尝试阅读此处的修补程序(它正在调用此函数,对吗?),并且尝试查找通过SQLAlchemy源代码此处至找到要修补的适当模块(例如 @patch('sqlalchemy.event.registrat._listen_fn')
),但无济于事.
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.
以前有没有人遇到过?
推荐答案
也许拥有一个上下文管理器类可以删除侦听器,并在退出时再次添加它可以解决问题.
Perhaps having a Context Manager class that removes the listener and add it again on exit could do the trick.
类似的东西:
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_)
然后使用它:
with SADeListener(User, "after_insert", do_something),
SADeListener(User, "after_update", do_something):
.. code ...
这篇关于Python:如何模拟SQLAlchemy事件处理程序(使用mock.unittest)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!