首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

[D]python中怎么mock一个类的静态方法

2012-04-12 
[D]python中如何mock一个类的静态方法大家好,最近在项目中写集成测试的时候遇到一个比较棘手的问题。就是在

[D]python中如何mock一个类的静态方法
大家好,最近在项目中写集成测试的时候遇到一个比较棘手的问题。就是在程序中有一个工具类utils,里面大多都是写static方法,在其他类中直接使用类名(utils)来引用这些static方法。
utils类代码结果大致如下:

Python code
class utils(object):    '''    Some common tool functions used by other scripts    '''    @staticmethod    def run_statement(hql, conf="", init_file=""):        '''        Run an HQL statement through Hive cli        '''        cmd_str = ""        if init_file == "":            cmd_str = "hive -e \"%s\" " % hql        else:            cmd_str = "hive -i \"%s\" -e \"%s\" " % (init_file, hql)                if conf == "":            pass        else:            conf_list = conf.split(',')            for c in conf_list:                c_pair = c.split('=')                cmd_str = cmd_str + "-hiveconf %s=%s " % (c_pair[0], c_pair[1])                        utils.run_os_cmd(cmd_str)     @staticmethod           def run_file(hql_file):        '''        Run an HQL script through Hive cli        '''        cmd_str = "hive -f %s" % hql_file        utils.run_os_cmd(cmd_str)            @staticmethod    def run_os_cmd(cmd_str):        (status, output) = commands.getstatusoutput(cmd_str)        if status == 0:            print ("%s finished\n%s" % (cmd_str, output))        else:            raise Exception, ("%s failed" % cmd_str)


run_file和run_statement等方法的功能是构造命令字符串,然后通过调用run_os_cmd来真正的执行。现在在写集成测试的时候我的想法是不让这些命令真正执行,想把run_os_cmd给mock掉,比如让它直接把命令打印出来,然后与预期的结果命令串assertEqual一下,如果相等则测试通过。毕竟主要目的是想测试utils类中的run_file拼接命令字符串功能。

昨天我搜了几个python中常用的mock模块,没有发现有什么方式可以mock掉某个类中的static方法。
后来我又想不通过使用mock,而是通过子类化utils类来改变run_os_cmd的行为,可是又发现由于之前这些方法都是static的,即便子类化了run_os_cmd,然后通过子类调用run_file等其他方法时,在其中真正引用的还是utils.run_os_cmd(父类的run_os_cmd)。

以前没怎么用过python的mock,不知道有没有什么哪个模块可以实现上面的功能?
或者说即便不使用mock,有什么其他方式可以完成对这个utils类的自动化单测呢?(子类化?)
还望大家不吝赐教,谢谢!
--------------
Double行动:
原帖分数:100
加分:100

[解决办法]
把run_os_cmd函数改写或者注视了重新写个函数叫print_parameter(...),里面就是专门print
[解决办法]
上面只是示意代码吧。实际应该用import把类载入,再修改,不用重写...

热点排行