Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic screenshots when test fail by Selenium Webdriver in Python

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 have any solution to this problem?

like image 889
d1minshakov Avatar asked Aug 19 '12 07:08

d1minshakov


3 Answers

do some webdriver stuff in Firefox... save screenshot on any exception to a dated image file:

from datetime import datetime
from selenium import webdriver

browser = webdriver.Firefox()

try:
    # do some webdriver stuff here
except Exception as e:
    print e
    now = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
    browser.get_screenshot_as_file('screenshot-%s.png' % now)
like image 176
Corey Goldberg Avatar answered Oct 23 '22 05:10

Corey Goldberg


Another method would be to add the following to your tearDown method:

if sys.exc_info()[0]:
    test_method_name = self._testMethodName
    self.driver.save_screenshot("Screenshots/%s.png" % test_method_name)

This would be assuming a test class like this:

class SeleniumTest(unittest2.TestCase):
    ...

    def tearDown(self):
        if sys.exc_info()[0]:
            test_method_name = self._testMethodName
            self.driver.save_screenshot("Screenshots/%s.png" % test_method_name)
        super(SeleniumTest, self).tearDown()

    def test_1(self):
        ...

    def test_2(self):
        ...
like image 11
Chirag verma Avatar answered Oct 23 '22 07:10

Chirag verma


For Future reference/People here is a solution that works in Python3, that works both for an Exception and on a failed Assert.

(Based on https://stackoverflow.com/a/23176373/9427691)

#!/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)

The

self._outcome.errors

are Python3 only, so for Python2 use

self._outcomeForDoCleanups.errors

instead.

For the ones that only want a Screen-shot on exceptions. You should take a look at this link: http://blog.likewise.org/2015/01/automatically-capture-browser-screenshots-after-failed-python-ghostdriver-tests/

like image 10
Michael Bach Kristensen Avatar answered Oct 23 '22 07:10

Michael Bach Kristensen