Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用SQLAlchemy在单元测试期间防止触摸db_Python_Mocking_Sqlalchemy_Flask_Flask Sqlalchemy - Fatal编程技术网

Python 使用SQLAlchemy在单元测试期间防止触摸db

Python 使用SQLAlchemy在单元测试期间防止触摸db,python,mocking,sqlalchemy,flask,flask-sqlalchemy,Python,Mocking,Sqlalchemy,Flask,Flask Sqlalchemy,我已经使用Django好几年了,但最近决定试用Flask以获得新的API。由于Carl Meyers在PyCon上的出色演示,我一直在使用以下技术来防止在Django单元测试中触碰数据库: cursor_wrapper = Mock() cursor_wrapper.side_effect = RuntimeError("No touching the database!") @patch('django.db.backends.util.CursorWrapper', cursor_wrap

我已经使用Django好几年了,但最近决定试用Flask以获得新的API。由于Carl Meyers在PyCon上的出色演示,我一直在使用以下技术来防止在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进行此操作,这允许您在SQLAlchemy执行不同事件时使用回调

在您的情况下,您可能希望使用或事件。例如

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!')

谢谢你的回复!我将进行测试,如果有效,我将选择作为答案。如果没有,我会通过评论通知你。