这里有一个在Python3中工作的解决方案,它既适用于异常,也适用于失败的断言。#!/usr/bin/env python
"""
An Example code to show the set-up with screen-shot on exception.
"""
import unittest
from selenium import webdriver
class TestDemo(unittest.TestCase):
"""An Example test Case, to show off the set-up of a screen-shot on exception."""
def setUp(self):
"""Set up the Firefox Browser and the Tear Down."""
self.driver = webdriver.Firefox()
self.driver.delete_all_cookies()
# NOTE: In addCleanup, the first in, is executed last.
self.addCleanup(self.driver.quit)
self.addCleanup(self.screen_shot)
self.driver.implicitly_wait(5)
def screen_shot(self):
"""Take a Screen-shot of the drive homepage, when it Failed."""
for method, error in self._outcome.errors:
if error:
self.driver.get_screenshot_as_file("screenshot" + self.id() + ".png")
def test_demo(self):
"""A test case that fails because of missing element."""
self.driver.get("http://www.google.com")
self.driver.find_element_by_css_selector("div.that-does-not-exist")
def test_demo2(self):
"""A test case that fails because assert."""
self.driver.get("https://stackoverflow.com")
self.assertEqual(True, False)
if __name__ == '__main__':
unittest.main(verbosity=2)
那个self._outcome.errors
只有Python3号,所以对于Python2号来说self._outcomeForDoCleanups.errors
相反。