什么是Python单元测试的Mock?相关的控制数据、使用程序和操作程序经过测试以确定它们是否适合使用。[1]直观地,可以将单元视为应用程序的最小可测试部分。简而言之,就是验证系统自动化测试功能是否正确的最小可测试单元。因此,单元测试的目的是“验证被测对象的职责”。在写单元测试之前,先明确被测对象的职责,然后你就会知道如何写单元测试了。根据测试的对象,单元测试可以分为两类:不依赖外部资源的组件的单元测试:依赖外部资源的组件的单元测试可以使用unittest的基本功能:mockunittest使用python单元测试库进行unittest的基本使用。如何编写单元测试模拟为什么要使用模拟?看了很多mock的讲解,写得最好的一篇是【NaftuliKay-AnIntroductiontoMockinginPython】,以删除文件为例,深入讲解了mock的使用。其他信息请参考:Python单元测试和Mock测试mock-autospec按照本文重写qk_log日志模块,qk_log.py代码如下#!/usr/bin/envpython#-*-编码:utf-8-*-importosimportsysimportdatetimeimportloggingimportlogging.handlers_console_logger=None_warn_logger=None_error_logger=NoneCONSOLE_FILENAME='log/console.log'WARNING_FILENAME='log/warn.log'ERROR_FILENAME='log/error.log'deflog_ifos():('log/')isTrue:passelse:os.mkdir('log/')global_console_logger,_warn_logger,_error_loggerhandler=logging.handlers.RotatingFileHandler(CONSOLE_FILENAME,maxBytes=20*1024*1024,backupCount=5)hdr=logging.StreamHandler()_console_logger=logging.getLogger('调试')_console_logger.addHandler(handler)_console_logger.addHandler(hdr)_console_logger.setLevel(logging.DEBUG)handler=logging.handlers.RotatingFileHandler(WARNING2max_FILENAMEs=1024*1024,backupCount=5)hdr=日志记录。流处理器()_warn_logger=logging.getLogger('warn')_warn_logger.addHandler(handler)_warn_logger.addHandler(hdr)_warn_logger.setLevel(logging.WARN)handler=logging.handlers.RotatingFileHandler(ERROR_FILENAME,maxBytes=20*1024*1024,backupCount=5)hdr=logging.StreamHandler()_error_logger=logging.getLogger('error')_error_logger.addHandler(handler)_error_logger.addHandler(hdr)_error_logger.setLevel(logging.ERROR)defdlog(msg):file_name,file_no,未使用=find_caler()time_str=datetime.datetime.now().strftime('%Y-%m-%d%H:%M:%S')_console_logger.debug('[%s][%s][%s,%d]%s'%(time_str,'debug',file_name,file_no,msg))defilog(msg):file_name,file_no,未使用=find_caler()time_str=datetime.datetime.now().strftime('%Y-%m-%d%H:%M:%S')_console_logger.info('[%s][%s][%s,%d]%s'%(time_str,'info',file_name,file_no,msg))defwlog(msg):file_name,file_no,unused=find_caler()time_str=datetime.datetime.now().strftime('%Y-%m-%d%H:%M:%S')_console_logger.warn('[%s][%s][%s,%d]%s'%(time_str,'warning',file_name,file_no,msg))_warn_logger.warn('[%s][%s][%s,%d]%s'%(time_str,'warning',file_name,file_no,msg))defelog(msg):file_name,file_no,unused=find_caler()time_str=datetime.datetime.now().strftime('%Y-%m-%d%H:%M:%S')_console_logger.error('[%s][%s][%s,%d]%s'%(time_str,'error',file_name,file_no,msg))_error_logger.error('[%s][%s][%s,%d]%s'%(time_str,'error',file_name,file_no,msg))deffind_caler():f=sys._getframe(2)co=f.f_code返回(os.path.basename(co.co_filename),f.f_lineno,co.co_name)ifco!=Noneelse('unknown',0,'unknown')if__name__=='__main__':log_init()dlog('测试.log%d'%(123))ilog('test.log%d'%(123))wlog('test.log%d'%(123))elog('test.log%d'%(123))元测试代码如下:#!/usr/bin/envpython#-*-coding:utf-8-*-"""创建于10/10/1711:27AM@author:ChenLiang@function:日志模块元测试"""importsysreload(sys)sys.setdefaultencoding('utf-8')importunittestimportmockimportdatetimefromqk_logimportlog_init,dlog,ilog,wlog,elogclassTestQkLog(unittest.TestCase):dt_str=datetime.datetime.strptime('2017-10-1111:08:59','%Y-%m-%d%H:%M:%S')@mock.patch('qk_log.os.path')@mock.patch('qk_log.datetime.datetime')@mock.patch('qk_log.logging')@mock.patch('qk_log.find_caler')deftest_dlog(self,mock_caler,mock_logging,mock_datetime,mock_path):mock_path.exists.return_value=Truelog_init()self.assertFalse(mock_logging.getLogger('debug').debug.called,"无法不写入日志.")mock_caler.return_value=('qk_log_test',12,'')mock_datetime.now.return_value=self.dt_strdlog('anymsg')mock_logging.getLogger('debug').debug.assert_called_with('[%s][%s][%s,%d]%s'%('2017-10-1111:08:59','debug','qk_log_test',12,'anymsg'))@mock.patch('qk_log.os.path')@mock.patch('qk_log.datetime.datetime')@mock.patch('qk_log.logging')@mock.patch('qk_log.find_caler')deftest_ilog(self,mock_caler,mock_logging,mock_datetime,mock_path):mock_path.exists.return_value=Truelog_init()self.assertFalse(mock_logging.getLogger('debug').info.called,"Failedtonotwritelog.")mock_caler.return_value=('qk_log_test',12,'')mock_datetime.now.return_value=self.dt_strilog('anymsg')mock_logging.getLogger('debug').info.assert_called_with('[%s][%s][%s,%d]%s'%('2017-10-1111:08:59','info','qk_log_test',12,'anymsg'))@mock.patch('qk_log.os.path')@mock.patch('qk_log.datetime.datetime')@mock.patch('qk_log.logging')@mock.patch('qk_log.find_caler')deftest_wlog(self,mock_caler,mock_logging,mock_datetime,mock_path):mock_path.exists.return_value=Truelog_init()self.assertFalse(mock_logging.getLogger('warn').info.called,"Failedtonotwritelog.")mock_caler.return_value=('qk_log_test',12,'')mock_datetime.now.return_value=self.dt_strwlog('anymsg')mock_logging.getLogger('warn').warn.assert_called_with('[%s][%s][%s,%d]%s'%('2017-10-1111:08:59','warning','qk_log_test',12,'anymsg'))@mock.patch('qk_log.os.path')@mock.patch('qk_log.datetime.datetime')@mock.patch('qk_log.logging')@mock.patch('qk_log.find_caler')deftest_elog(self,mock_caler,mock_logging,mock_datetime,mock_path):mock_path.exists.return_value=Truelog_init()self.assertFalse(mock_logging.getLogger('error').info.called,"Failedtonotwritelog.")mock_caler.return_value=('qk_log_test',12,'')mock_datetime.now.return_value=self.dt_strelog('任何消息')mock_logging.getLogger('error').error.assert_called_with('[%s][%s][%s,%d]%s'%('2017-10-1111:08:59','错误','qk_log_test',12,'anymsg'))if__name__=='__main__':unittest.main()对单元测试的看法是在Python数据统计分析项目的整体改造中引入单元测试。在编写了公共库的单元测试后,发现更多的时间花在了单元测试上,而公共库并没有经常变化,业务逻辑也比较混乱,所以团队决定放弃单元测试。没必要急着写单元测试,因为当所有的变化都可能发生的时候,相应的单元测试也会随着代码的废弃而废弃,浪费了太多的人力。所以创业团队不建议写单元测试,做好程序埋点和监控报警即可。记得给我点赞哦!对计算机各个方向的视频课程和电子书,从入门、进阶、实用进行了认真梳理,并按照目录进行合理分类。你总能找到你需要的学习资料。你在等什么?立即关注并下载!!!念念不忘,必有回响,朋友们,请点个赞,万分感谢。我是职场亮哥,四年工作经验的YY高级软件工程师,拒绝当领导的斜杠程序员。听我说,我进步很大。如果有幸帮到你,请给我一个【点赞】,给我一个关注,如能评论鼓励,将不胜感激。职场凉阁文章列表:更多文章我的所有文章和回答均与版权保护平台合作,版权归职场凉阁所有。未经授权转载必究!
