Skip to main content

_python

Example

Let's start by importing our requisite libraries (import unittest for our test framework, from selenium import webdriver to drive the browser, and import sys to determine when there's a test failure), declare our test class, and write test setUp and tearDown methods.

# filename: screenshot.py
import sys
import unittest
from selenium import webdriver


class ScreenShotOnFailure(unittest.TestCase):

def setUp(self):
self.driver = webdriver.Chrome()

def tearDown(self):
if sys.exc_info():
self.driver.save_screenshot("failshot_%s.png" % self._testMethodName)
self.driver.quit()
# ...

In tearDown we check to see if sys.exc_info() exists. If it does, then there's been a test failure, and we capture a screenshot through the help of Selenium's .save_screenshot method. .save_screenshot accepts a filename as a string (e.g., 'failshot.png'). To make the filename unique we use the test method name (e.g., self._testMethodName). When this command executes it will save an image file to the local system in the current working directory.

Now to wire up a test which will fail.

# filename: screenshot.py
# ...
def test_example_1(self):
driver = self.driver
driver.get('http://the-internet.herokuapp.com')
assert driver.title == 'blah blah blah'

if __name__ == "__main__":
unittest.main()

Expected Behavior

When we save this file and run it (python screenshot.py from the command-line) here is what will happen:

  • Open the browser
  • Load the homepage of the-internet
  • Check the text of the page header and fail
  • Output a failure message in the terminal
  • Capture a screenshot in the current working directory
  • Close the browser

Summary

Having a screenshot to aid in troubleshooting failing tests along with a stack trace helps in having more insight. Using the import sys determines when there's been a test failure.

If you want truly unique filenames, then you should use a unique ID in the filename instead of a timestamp (e.g., something like uuid). This will prevent screenshots from getting overwritten when you have two (or more) tests taking screenshots at the same time.