加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 使用模拟对象的Dillemma

发布时间:2020-12-20 13:27:42 所属栏目:Python 来源:网络整理
导读:假设我想声明结果是特定格式,我可能会将返回值设置为(True,’Success’) def batch_move(self,*args,**kwargs): ''' Move a batch of files to its respective destinations. Return type: tuple (boolean,message) T/F,'string' / str(exception) ''' srcs=
假设我想声明结果是特定格式,我可能会将返回值设置为(True,’Success’)

def batch_move(self,*args,**kwargs):
  ''' 
  Move a batch of files to its respective destinations.
  Return type: tuple (boolean,message)
                      T/F,'string' / str(exception)
  '''

  srcs= kwargs.get('srcs',None)
  dests = kwargs.get('dests',None)

  try:
    if srcs and dests:
       # map srcs and dests into dictionary (srcs --> keys,dests --> values)
       src_dest= dict(zip(srcs,dests))     

       for src,dest in src_dest:
         if os.path.exists(src):
           if os.path.exists(dest):
              shutil.rmtree(dest)
           shutil.move(src,dest)   # either way we will proceed to move
         else:
           return (False,'%s does not exist!' % src)
       return (True,'Success!')

    else:
       return (False,'Something gone wrong with those kwargs...')
  except Exception as e:
    return (False,e)

为了回归(True,’成功!’)

>使用True作为返回值修补os.path.exists.但是在一个单元测试中我想跳过这个,我如何修补os.path.exists?

06001

>如何修补shutil.move(src,dest)?我只是给予True,这样就不会产生错误吗?如果我想要它失败并且发现异常怎么办?我该如何模拟呢? (我不会总是知道要捕获哪个异常,主要原因是将Exception用作e).
>如果我真的通过了这个功能,它是否真的意味着没有异常被捕获并且它经历了每一行?或者是因为我设置了’mock_object.return_value =(True,’Success!’)?
>我只使用两个依赖项,我是否需要修补所有外部依赖项,如(os,sys,math,datetime)?或者,如果我的函数正在使用其他函数(重构)

06002

谢谢.对不起,很长的问题.我真的很想擅长编写单元测试.

解决方法

我必须说,在这个特定的用例中,我认为修补/嘲笑不是最好的选择……

对于这个单元测试,我在文件系统中创建一个结构,在磁盘中的该结构上运行算法并检查不同的结果(所有这些都没有模拟os或shutil).

通常我倾向于使用补丁,主要是在外部设置困难或缓慢时(即:可能需要设置一些外部数据库)或者当它停止测试时(即:打开一些对话框)或者当我想做一些困难的事情时另外检查(例如计算是否实际访问了某些缓存).

除此之外,修补/嘲讽太多让我觉得你的设计有问题(没有考虑到单元测试),所以,用较小的块进行测试可能会有所帮助……

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读