gpt4 book ai didi

python - 在异常时执行屏幕截图

转载 作者:太空狗 更新时间:2023-10-30 02:28:18 27 4
gpt4 key购买 nike

嘿,有没有办法在出现异常时捕获屏幕截图,任何异常。我的“失败”解决方案位于 BaseTestCaseunittest.TestCase 子类中:

class BaseTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
"""some code"""

@property
def failureException(self):
class MyFailureException(Exception):
def __init__(self_, *args, **kwargs):
screenshot_dir = '../error_log'
self.driver.save_screenshot('{0}/{1}.jpeg'.format(screenshot_dir, self.id()))
return super().__init__(*args, **kwargs)

MyFailureException.__name__ = Exception.__name__
return MyFailureException

最初它是 AssertionError 而不是 Exception 但它只会捕获断言错误,我对其他类型的错误更感兴趣

最佳答案

要在发生错误或失败时进行截图,请检查tearDown 方法中当前是否存在正在处理的异常:

import unittest, sys, exceptions
from selenium import webdriver


class TestCaseBase(unittest.TestCase):

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

def tearDown(self):
type, value, traceback = sys.exc_info()
if type is exceptions.AssertionError :
self.driver.save_screenshot(r'screenshot-failure.png')
elif type is exceptions.Exception :
self.driver.save_screenshot(r'screenshot-error.png')

self.driver.quit()

class MyTestCase(TestCaseBase):

def test_should_take_screenshot_on_failure(self):
self.driver.get("http://stackoverflow.com/")
self.assertTrue(False)

def test_should_take_screenshot_on_error(self):
self.driver.get("http://stackoverflow.com/")
raise Exception("my exception")


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

您还可以覆盖方法 TestResult.addErrorTestResult.addFailure:

import unittest
from selenium import webdriver


class TestCaseBase(unittest.TestCase):

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

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

def run(self, result=None):
super(TestCaseBase, self).run(TestResultEx(result, self))


class MyTestCase(TestCaseBase):

def test_should_take_screenshot_on_failure(self):
self.driver.get("http://stackoverflow.com/")
self.assertTrue(False)

def test_should_take_screenshot_on_error(self):
self.driver.get("http://stackoverflow.com/")
raise Exception("my exception")


class TestResultEx(object):

def __init__(self, result, testcase):
self.result = result
self.testcase = testcase

def __getattr__(self, name):
return object.__getattribute__(self.result, name)

def addError(self, test, err):
self.result.addError(test, err)
self.testcase.driver.save_screenshot(r'screenshot-error.png')

def addFailure(self, test, err):
self.result.addFailure(test, err)
self.testcase.driver.save_screenshot(r'screenshot-failure.png')


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

关于python - 在异常时执行屏幕截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37608768/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com