如何在Python中模拟CX_ORACLE游标 [英] How to mock cx_Oracle cursor in Python

查看:0
本文介绍了如何在Python中模拟CX_ORACLE游标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个类中有以下两个函数,我需要模拟数据库连接和游标结果。Cx_Oracle.Connect已成功修补它按预期工作。但是游标、CALFUNC、FETCH_ALL没有被模拟。你知道正确的语法是什么吗?

class dbconnect:

    def db_connect(self, connection_details):
        connection = cx_Oracle.connect(user_name,pwd,<connection_string>)
        return connection

    def execute_function(self, sqlFunction, args):
        cursor = self.connection.cursor()
        res=cursor.callfunc(sqlFunction, cursor.var(cx_Oracle.CURSOR), args)
        results = {'headers' : [x[0] for x in res.description],
            'data': res.fetchall()
        }
        cursor.close()
        return results

我的模拟代码

with mock.patch('dbconnect.cx_Oracle.connect') as mockOracle:

   result_set = {}
   mockOracle.cursor.callfunc.fetch_all = result_set

推荐答案

您实际上根本不必"模拟"连接和游标!您只需自己创建连接和游标的子类,如下所示:

class MyConnection(cx_Oracle.Connection):

    def cursor(self, scrollable=False):
        return MyCursor(self, scrollable)

class MyCursor(cx_Oracle.Cursor):

    def execute(self, sql, args):
        result = super(MyConnection, self).execute(sql, args)
        print("My mock execute...")
        return result

我不确定这是否是您的本意,或者您是否知道这种可能性。使用此选项,您可以添加新函数,并且可以覆盖或扩展现有函数。

这篇关于如何在Python中模拟CX_ORACLE游标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆