While writing functional test cases using selenium tearDown() method is one of the greatest functionality/place to do all cleanup actions. This method called immediately after the test method has been called and the result recorded. This is called even if the test method raised an exception, so the implementation in subclasses may need to be particularly careful about checking internal state. Any exception raised by this method will be considered an error rather than a test failure. This method will only be called if the setUp() succeeds, regardless of the outcome of the test method. The default implementation does nothing.
So instead of adding screenshots functionality in each test cases, we can add this functionality in tearDown method as follows:
def tearDown(self):
if sys.exc_info()[0]:
test_method_name = self._testMethodName
now = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
self.driver.save_screenshot(os.getcwd() +'/screenshots/' + test_method_name + "-" + now + ".png")
--Make sure to import following packages for above code.
from selenium import webdriver from datetime import datetime import os


