我创建了一个包装器,在发生故障时会截取屏幕截图。
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
我的问题陈述是根据错误发生的位置为2个浏览器截取屏幕截图。
例如:
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()
这里我想自动在Web驱动程序浏览器和b之间切换。 如果您可以告诉我如何提供当前浏览器中出现故障的情况,那将会有很大帮助。
test_object.browser.get_screenshot_as_file(filename)