首页 > 代码库 > python+selenium+unitest用例失败重运行

python+selenium+unitest用例失败重运行

经过多次研读和调试unittest代码,后来发现一个也可以重运行setUp()和dearDown()的解决办法,那就是修改源码,我们重新建一个模块套件类来覆盖原来的TestSuite类

实例代码:

[python] view plain copy
  1. class Suit(unittest.TestSuite):  
  2.     def run(self, result, debug=False):  
  3.         failcount = 1#失败总运行次数  
  4.         class_num = 1  
  5.         topLevel = False  
  6.         if getattr(result, ‘_testRunEntered‘, False) is False:  
  7.             result._testRunEntered = topLevel = True  
  8.   
  9.         for test in self:  
  10.             case_num = 1  
  11.             if result.shouldStop:  
  12.                 break  
  13.               
  14.             success_flag = True  
  15.             while success_flag:    
  16.                 if _isnotsuite(test):  
  17.                     self._tearDownPreviousClass(test, result)  
  18.                     self._handleModuleFixture(test, result)  
  19.                     self._handleClassSetUp(test, result)  
  20.                     result._previousTestClass = test.__class__  
  21.                     if (getattr(test.__class__, ‘_classSetupFailed‘, False) or  
  22.                         getattr(result, ‘_moduleSetUpFailed‘, False)):  
  23.                         if class_num > failcount:  
  24.                             success_flag = False  
  25.                         else:  
  26.                             time.sleep(5)  
  27.                             result._previousTestClass = None  
  28.                             print ‘类%s第%s次重新初始化执行‘%(test.__class__,class_num)  
  29.                             class_num += 1  
  30.                         continue  
  31.   
  32.                 if not debug:  
  33.                     test(result)  
  34.                 else:  
  35.                     test.debug()  
  36.                   
  37.                 if result.result[-1][0]==or result.result[-1][0]==2:#结果为fail和err用例判断  
  38.                     if case_num > failcount:  
  39.                         success_flag = False  
  40.                     else:    
  41.                         print ‘用例%s第%s次重新执行‘%(test,case_num)  
  42.                         case_num += 1  
  43.                 else:  
  44.                     success_flag = False  
  45.                       
  46.         if topLevel:  
  47.             self._tearDownPreviousClass(None, result)  
  48.             self._handleModuleTearDown(result)  
  49.             result._testRunEntered = False  
  50.         return result  



然后测试使用

alltests=suit.Suit()

alltests.addtest(WidgetTestCase("testDefaultSize"))

runner =HTMLTestRunner.HTMLTestRunner(stream=fp,verbosity=2,title=‘Android测试报告‘,description=‘用例执行情况:‘,)
runner.run(alltests)

运行完后,有失败重运行的用例都会打印在测试报告里,方便查阅

python+selenium+unitest用例失败重运行