Dav*_*d S 5 python sqlalchemy mocking flask flask-sqlalchemy
我已经使用Django好几年了,但最近决定尝试使用Flask来获得新的API.感谢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'''
...
Run Code Online (Sandbox Code Playgroud)
我的问题是,任何人都可以告诉我如何使用SQLAlchemy执行相同的基本技术吗?换句话说,我希望任何时候我实际上对数据库运行查询以产生运行时错误.
为此,您可以利用 SQLAlchemy 的事件系统,该系统允许您在 SQLAlchemy 执行不同事件时使用回调。
在您的情况下,您可能需要使用before_execute()或before_cursor_execute()事件。例如...
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!')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1067 次 |
| 最近记录: |