python unittest addCleanup中也加失败截图功能
在python web自动化测试中失败截图方法汇总一文中提到了失败截图的方法
但在实际测试中,如果我们的测试用例中加了addCleanups动作,如果addCleanups中动作失败了,就不会截图。那么该怎么做呢,解铃还得系铃人,还是得从addCleanups下手
思路:
我将在 addCleanup中再加一个截图的函数,但怎么判断用例是用例内失败还是addCleanup中失败呢,方法如下
我们在执行完用例后,看看self的属性,包括如下:
(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截图的函数,如下
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就行
self.addCleanup(self.ff)
以上是 python unittest addCleanup中也加失败截图功能 的全部内容, 来源链接: utcz.com/z/388381.html