python unittest addCleanup中也加失敗截圖功能

python web自動化測試中失敗截圖方法彙總一文中提到了失敗截圖的方法html

但在實際測試中,若是咱們的測試用例中加了addCleanups動做,若是addCleanups中動做失敗了,就不會截圖。那麼該怎麼作呢,解鈴還得繫鈴人,仍是得從addCleanups下手python

 

思路:web

我將在 addCleanup中再加一個截圖的函數,但怎麼判斷用例是用例內失敗仍是addCleanup中失敗呢,方法以下less

咱們在執行完用例後,看看self的屬性,包括以下:ssh

(Pdb) print dir(self)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_addSkip', '_baseAssert
Equal', '_classSetupFailed', '_cleanups', '_deprecate', '_diffThreshold', '_formatMessage', '_getAssertEqualityFunc', '_resultForDoCleanups', '_testMethodDoc', '_testMethodName', '_truncateMessage', '_type_equality_funcs', 'addCleanup', 'addTypeEqualityFunc', 'assertAlmostEqual', 'assertAlmostEquals', 'asser
tDictContainsSubset', 'assertDictEqual', 'assertEqual', 'assertEquals', 'assertFalse', 'assertGreater', 'assertGreaterEqual', 'assertIn', 'assertIs', 'assertIsInstance', 'assertIsNone', 'assertIsNot', 'assertIsNotNone', 'assertItemsEqual', 'assertLess', 'assertLessEqual', 'assertListEqual', 'assertMultiLineE
qual', 'assertNotAlmostEqual', 'assertNotAlmostEquals', 'assertNotEqual', 'assertNotEquals', 'assertNotIn', 'assertNotIsInstance', 'assertNotRegexpMatches', 'assertRaises', 'assertRaisesRegexp', 'assertRegexpMatches', 'assertSequenceEqual', 'assertSetEqual', 'assertTrue', 'assertTupleEqual', 'assert_', 'atta
ch_png', 'class_handle_png', 'clean_resource', 'config', 'countTestCases', 'debug', 'defaultTestResult', 'doCleanups', 'execute_from', 'fail', 'failIf', 'failIfAlmostEqual', 'failIfEqual', 'failUnless', 'failUnlessAlmostEqual', 'failUnlessEqual', 'failUnlessRaises', 'failureException', 'ff', 'handle_png', 'i
d', 'longMessage', 'maxDiff', 'run', 'setUp', 'setUpClass', 'setup_resource', 'shortDescription', 'skipTest', 'skip_check', 'tearDown', 'tearDownClass', 'landhu.cnblogs.com', 'web_driver']

你看看有一個resultForDoCleanups參數,咱們看看函數

(Pdb) print self._resultForDoCleanups
<nose.result.TextTestResult run=1 errors=0 failures=1>
(Pdb) print self._resultForDoCleanups()

很好,咱們就從這裏下手,tearDown與上文截圖連接不變,只需加入返回resultForDoCleanup值,以下測試

        if sys.exc_info()[0]:
            .......
        self.errors,self.failures = len(self._resultForDoCleanups.errors),len(self._resultForDoCleanups.failures)

接着,咱們加一個用於addCleanup截圖的函數,以下spa

     def ff(self):
        errors, failures = len(self._resultForDoCleanups.errors), len(
            self._resultForDoCleanups.failures)
        if (errors-self.errors or failures-self.failures) != 0:
            log.info(u"截圖")
            log.info("Add cleanup save")
            screen_shot = self.web_driver.get_screenshot_as_png()
            

而後在setUp里加addCleanup就行debug

self.addCleanup(self.ff)code

相關文章
相關標籤/搜索