Automatic screenshots when test fail by Selenium Webdriver in Python

前端 未结 7 1188
小蘑菇
小蘑菇 2020-12-13 04:42

I want to automatic capturing screenshots if my webdriver tests failed (any exception or assertion error). I am using Python unittest and Selenium Webdriver. Does anyone hav

相关标签:
7条回答
  • 2020-12-13 05:19

    Here is a solution using a decorator that wrapps every method on a class that starts test_ with a wrapper that takes a screenshot if the method raises and Exception. The browser_attr is used to tell the decorator how to obtain the web browser (driver).

    from functools import partialmethod
    
    
    def sreenshotOnFail(browser_attr='browser'):
        def decorator(cls):
            def with_screen_shot(self, fn, *args, **kwargs):
                """Take a Screen-shot of the drive page, when a function fails."""
                try:
                    return fn(self, *args, **kwargs)
                except Exception:
                    # This will only be reached if the test fails
                    browser = getattr(self, browser_attr)
                    filename = 'screenshot-%s.png' % fn.__name__
                    browser.get_screenshot_as_file(filename)
                    print('Screenshot saved as %s' % filename)
                    raise
    
            for attr, fn in cls.__dict__.items():
                if attr[:5] == 'test_' and callable(fn):
                    setattr(cls, attr, partialmethod(with_screen_shot, fn))
    
            return cls
        return decorator
    
    
    @sreenshotOnFail()
    class TestDemo(unittest.TestCase):
        def setUp(self):
            """Set up the Firefox Browser and the Tear Down."""
            self.browser = webdriver.Firefox()
    
        def test_demo2(self):
            """A test case that fails because assert."""
            self.driver.get("https://stackoverflow.com")
            self.assertEqual(True, False)
    
    0 讨论(0)
提交回复
热议问题