2

I have created a wrapper which takes screenshot when a failure occurs.

from functools import wraps
import datetime
import os

def screenshot_on_error(test):

"""Taking screenshot on error
This decorators will take a screenshot of the browser
when the test failed or when exception raised on the test.
Screenshot will be saved as PNG inside screenshots folder.
"""
@wraps(test)
def wrapper(*args, **kwargs):
    try:
        test(*args, **kwargs)
    except:
        test_object = args[0]
        testcase_value = str(test_object)
        '''
        Fetching the name of the test case
        '''
        testcase_id = testcase_value.split(" ", 1)
        testcase_name = testcase_id[0]
        print(testcase_name)
        '''
        Fetching the class name for the test case
        '''
        testcase_class_id = testcase_value.split(".", 1)
        testcase_class = testcase_class_id[1].split(")", 1) 
        testcase_class_name=testcase_class[0]
        print(testcase_class_name) 
        screenshot_dir = './screenshots'
        if not os.path.exists(screenshot_dir):
            os.makedirs(screenshot_dir)
        date_string = datetime.datetime.now().strftime(
            '%m%d%y-%H%M%S')
        filename = '%s/SS-%s.png' % (screenshot_dir, date_string)
        print("filename")     
        test_object.browser.get_screenshot_as_file(filename)
return wrapper

My problem statement is taking screenshot for 2 browsers based on where the error occurs.

For example:

from Decorators import screenshot_on_error
import unittest
from selenium import webdriver
class ScreenshotTest(unittest.TestCase):

@classmethod
def setUp(self):
    self.browser = webdriver.Firefox()
    self.browser.get('http://gmail.com')
    self.b = webdriver.Firefox()
    self.b.get("http://google.com")

@screenshot_on_error
def test_01_check(self):

    self.browser.find_element_by_xpath("//div[@class='card signin-card fix']")

@screenshot_on_error
def test_02_check(self):

    self.b.find_element_by_xpath("//div[@class='card signin-card fix']")

@classmethod
def tearDown(self):
    self.browser.quit()
    self.b.quit()


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

Here I want to switch between the Web driver browser and b automatically. If you could tell me how to provide the current browser where a failure occurs in the line, it would be of great help.

test_object.browser.get_screenshot_as_file(filename)
kenorb
  • 155,785
  • 88
  • 678
  • 743
Sushanth
  • 51
  • 2
  • 6

0 Answers0