programiss
programiss

Reputation: 255

Create screenshot only on test failure

Currently I have a function that creates a screenshot and I call it here

def tearDown(self):
    self.save_screenshot()
    self.driver.quit()

There is also a folder being created which is used to store the screenshots.

I don't want this to happen when the test passes.

What do I have to add in order for this not to happen?

Thanks for all the help

Upvotes: 2

Views: 2976

Answers (3)

Sergei Kuznetcov
Sergei Kuznetcov

Reputation: 165

If your test failed, the sys.exc_info will have an exception. So you can use it as pass/fail result of your test:

if sys.exc_info()[0]:
    # 'Test Failed'
else:
    # 'Test Passed'

And if you want to take a screenshot on failure:

import unittest
import sys
from selenium import webdriver

class UrlTest(unittest.TestCase):

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

    def test_correct_url(self):
        self.driver.get('https://google.com')
        self.assertTrue('something.com' in self.driver.current_url)

    def tearDown(self):
        if sys.exc_info()[0]:
            self.driver.get_screenshot_as_file('screenshot.png')
        self.driver.quit

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

Upvotes: 2

Hai Vu
Hai Vu

Reputation: 40688

Here is one way to capture screenshot only when failure:

def setUp(self):
    # Assume test will fail
    self.test_failed = True

def tearDown(self):
    if self.test_failed:
        self.save_screenshot()

def test_something(self):
    # do some tests
    # Last line of the test:
    self.test_failed = False

The rationale behind this approach is when the test reaches the last line, we know that the test passed (e.g. all the self.assert* passed). At this point, we reset the test_failed member, which was set to True in the setUp. In tearDown, we now can tell if a test passed or failed and take screenshot when appropriate.

Upvotes: 1

Steve Barnes
Steve Barnes

Reputation: 28360

In your initialisation method set a self.NoFailuresSnapped = 0 and check your test environment for the current number of failures being > self.NoFailuresSnapped before calling or within your function and of course set it again before returning.

Upvotes: 1

Related Questions