加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 使用SQLAlchemy防止在单元测试期间触摸数据库

发布时间:2020-12-16 23:52:40 所属栏目:Python 来源:网络整理
导读:我已经使用Django好几年了,但最近决定尝试使用Flask来获得新的API.感谢Carl Meyers在PyCon上testing Django的精彩演示,我一直在使用以下技术来防止在我的Django单元测试中触摸数据库: cursor_wrapper = Mock()cursor_wrapper.side_effect = RuntimeError("N

我已经使用Django好几年了,但最近决定尝试使用Flask来获得新的API.感谢Carl Meyers在PyCon上testing 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'''
   ...

我的问题是,任何人都可以告诉我如何使用SQLAlchemy执行相同的基本技术吗?换句话说,我希望任何时候我实际上对数据库运行查询以产生运行时错误.

最佳答案
您可以使用SQLAlchemy的event system,这允许您在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,self._before_cursor_execute)

    def _before_cusor_execute(self,conn,cursor,statement,parameters,context,executemany):
        raise RuntimeError('No touching the database!')

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读