解决unittest中断言失败,后续的断言都不执行的问题

  在unittest测试用例中,在含有多个断言时,一个断言失败后,测试用例会结束运行,无法知道其他断言是否成功。unittest不同与pytest,在pytest中,

可以使用pytest.assume(表达式),检查点失败继续运行,所以为了解决unittest的这个弊端,本文解决方式:
      1)把多个断言合成一个断言,判断多个断言的综合结果是True还是False
      2)判断每个断言结果,失败则汇总,在最终断言中输出
 
之前多断言代码:
def checkCMSTab(self, tabLabelInfo, tabName):
  self.assertNotEqual(len(tabLabelInfo[0][0]) + len(tabLabelInfo[1]), 0,
'导航2N楼层的{}tab下数据异常:tab数据为空'.format(tabName))
  self.assertNotEqual(len(tabLabelInfo[0][0]), 0,
'导航2N楼层的{}tab下数据异常:无商品数据'.format(tabName))

  self.assertEqual(len(unsaleWareInfoList), 0, '{tabName}tab下存在已售罄商品,具体信息为{unsaleWareInfos}'.format(
tabName=tabName,
unsaleWareInfos=unsaleWareInfos))
  self.assertEqual(len(offlineWareInfoList), 0, '{tabName}tab下存在已下架商品,具体信息为{offlineWareInfoList}'.format(
tabName=tabName,
offlineWareInfoList=offlineWareInfoList))
  # 验证tab下图片坑位是否无跳转链接
  self.assertEqual(len(pictureEroorList), 0, "{tabName}下图片坑位无跳转链接,具体信息为{pictureEroorInfos}".format(tabName=tabName,
pictureEroorInfos=pictureEroorInfos))

优化后代码如下:

    def checkCMSTab(self, tabLabelInfo, tabName):
        # 解决unittest中断言失败,后续的断言都不执行的问题
        res = True
        msg = []
        res = res and (len(tabLabelInfo[0][0]) + len(tabLabelInfo[1]) > 0)  # 验证tab下商品+图片数据为空
        res = res and (len(tabLabelInfo[0][0]) > 0)    # 验证tab下商品为空
        res = res and (len(unsaleWareInfoList) == 0)   # tab下是否存在已售罄
        res = res and (len(offlineWareInfoList) == 0)  # tab下是否存在已下架
        res = res and (len(pictureEroorList) == 0)  # 验证tab下图片坑位是否无跳转链

        if len(tabLabelInfo[0][0]) + len(tabLabelInfo[1]) == 0:
            msg.append('导航2N楼层的{}tab下数据异常:tab数据为空'.format(tabName))
        if len(tabLabelInfo[0][0]) == 0:
            msg.append('导航2N楼层的{}tab下数据异常:无商品数据'.format(tabName))
        if len(unsaleWareInfoList) > 0:
            msg.append('{tabName}tab下存在已售罄商品,具体信息为{unsaleWareInfos}'.format(tabName=tabName,
                                                                                        unsaleWareInfos=unsaleWareInfos))
        if len(offlineWareInfoList) > 0:
            msg.append('{tabName}tab下存在已下架商品,具体信息为{offlineWareInfoList}'.format(tabName=tabName,
                                                                                        offlineWareInfoList=offlineWareInfoList))
        if len(pictureEroorList) > 0:
            msg.append("{tabName}下图片坑位无跳转链接,具体信息为{pictureEroorInfos}".format(tabName=tabName,
                                                                                                         pictureEroorInfos=pictureEroorInfos))
        self.assertEqual(res, "\n".join(msg))

 此种方式在用例设计中相对实现起来会比较麻烦,为断言优化初级版;可参考下一篇文章《解决unittest断言失败,后续的断言不执行进阶之重新封装断言》,重新封装unittest断言,

码字不易,如有转载请注明出处,感谢~

posted @ 2021-01-10 16:31  不吃鱼的猫大  阅读(2042)  评论(0编辑  收藏  举报