Create screenshot only on test failure

生来就可爱ヽ(ⅴ<●) 提交于 2020-02-22 08:41:55

问题


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


回答1:


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.




回答2:


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()



回答3:


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.



来源:https://stackoverflow.com/questions/27879640/create-screenshot-only-on-test-failure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!