FetchMany循环的Python单元测试

2024-09-30 20:22:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我想对一段代码进行单元测试,从SQLServer数据库中获取结果,然后使用fetchmany进行循环。我没有使用fetchall,因为我希望结果集是巨大的

然而,模拟它会导致无限循环,因为我认为我无法正确设置返回值

这就是我想测试的代码

with(MsSqlIntegratedHook(mssql_conn_id="detbds")).get_conn() as conndet:
                    with conndet.cursor() as cursordet:
                        while True:
                            current_data = cursorswh.fetchmany(100)
                            if not current_data:
                                break
                            cursordet.executemany("insert into input.Events (EventTime, EventTypeID, EventPayload) values (getdate() ,1, ?)", current_data)
                            conndet.commit()
                        conndet.commit()

然而,像下面这样的模拟是由于线的原因导致它是无限的

current_data = cursorswh.fetchmany(100)

以下是我试图嘲弄的方式:

cursor_mock = mock_MsSqlIntegratedHook.return_value.__enter__.return_value
cursor_mock.execute.return_value.fetchmany.return_value=[("123","SH", "1", "AUD", "100", "100", "100")]

也试过

mock_MsSqlIntegratedHook.get_conn.__enter__.cursor.__enter__.fetchmany.return_value=[("123","SH", "1", "AUD", "100", "100", "100")]

但因为当前的_数据是一个模拟对象,“如果不是当前的_数据”永远不会返回false

我认为模拟没有正常进行,因为fetchmany返回一个模拟对象,而不是我在模拟的return_值中指定的值

我应该如何处理这个问题

如果你需要我的任何解释或澄清,就开枪吧

这是很新的


Tags: 代码datagetreturnvalueaswithcurrent
1条回答
网友
1楼 · 发布于 2024-09-30 20:22:58

所以,我终于明白了ThisS.O post谈到了这一点,Martijn Pieters的回答谈到了使用“with”子句时的“enter”方法

因此,最终的解决方案是

class MoveTest(unittest.TestCase):

    @mock.patch('Module_positionmove.MsSqlIntegratedHook')
   
       
    def test_method(self, mock_MsSqlIntegratedHook):
        mock_con_cm = mock_MsSqlIntegratedHook.return_value
        mock_con = mock_con_cm.get_conn.return_value.__enter__.return_value  #because of using the with block, we get a __enter__
        mock_con.cursor.return_value.__enter__.return_value.fetchmany.side_effect = [("123","SH", "1", "AUD", "100", "100", "100"), None]
        
        livepositionswith52weeklowInstruments (("1","2"))

        mock_con.cursor.return_value.__enter__.return_value.fetchmany.assert_called()

副作用和第二个成员为None的列表分配确保了循环在调用“break”时退出

相关问题 更多 >