[英]Prevent touching db during unit testing with SQLAlchemy
I've been using Django for several years, but have recently decided to try out Flask for a new API. 我已经使用Django几年了,但是最近决定尝试使用Flask来开发新的API。 Thanks to Carl Meyers excellent presentation on testing Django at PyCon, I've been using the following technique to prevent touching the database in my Django unit tests: 感谢Carl Meyers在PyCon上关于Django测试的出色演讲,我一直在使用以下技术来防止在Django单元测试中接触数据库:
cursor_wrapper = Mock()
cursor_wrapper.side_effect = RuntimeError("No touching the database!")
@patch('django.db.backends.util.CursorWrapper', cursor_wrapper)
class TestPurchaseModel(TestCase):
'''Purchase model test suite'''
...
My question is can anyone tell me how to do this same basic technique with SQLAlchemy? 我的问题是,有人可以告诉我如何使用SQLAlchemy进行相同的基本技术吗? In other words, I want any time I actually run a query against the database to produce a runtime error. 换句话说,我想在任何时候对数据库实际运行查询以产生运行时错误。
You can utilize SQLAlchemy's event system for this, which allows you to use a callback when SQLAlchemy performs different events. 您可以为此使用SQLAlchemy的事件系统 ,该系统允许您在SQLAlchemy执行不同事件时使用回调。
In your case, you would probably want to use the before_execute() or before_cursor_execute() events. 在您的情况下,您可能需要使用before_execute()或before_cursor_execute()事件。 For example... 例如...
from sqlalchemy import event
class TestCase(unittest.TestCase):
def setUp(self):
engine = ... # create or access your engine somehow
event.listen(engine, "before_cursor_execute", self._before_cursor_execute)
# We can also clean up the event handler after the test if we want to
def tearDown(self):
engine = ... # access your engine again
event.remove(engine, "before_cursor_execute", self._before_cursor_execute)
def _before_cusor_execute(self, conn, cursor, statement, parameters, context, executemany):
raise RuntimeError('No touching the database!')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.