【问题标题】:Using try/except then throw a method inside a class使用 try/except 然后在类中抛出一个方法
【发布时间】:2021-02-24 09:16:59
【问题描述】:

我在下面有这段代码,我想在类WebInterface 中捕获方法click_on_element 的异常,方法capture_page_screenshot 也在该类中。我用过装饰器catch_exception,但没用。

请告诉我如何完成这个!

第一个:Traceback 是:self 未定义。

在 Timus 的帮助下修复代码后:我得到了第二个回溯:During.... 我的意思是当我raise Exception时它总是显示回溯消息

def catch_exception(f):
    @functools.wraps(f)
    def func(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except:
            WebInterface.capture_page_screenshot(self)
            raise Exception(traceback._context_message)
    return func

class WebInterface(object): 
    
    implicitly_timeout = 15
    page_load_timeout = 30
    set_driver_path = False

    def __init__(self, name = None):
        if not self.set_driver_path:
            env_path = env.get_env_var("PATH")
            env_path = ";".join([env_path, Utils.client_driver_path])
            env.set_env_var("PATH", env_path)
            self.set_driver_path = True
        self.screenshot_dir = None
        self.driver = SeleniumLibrary(self.page_load_timeout, self.implicitly_timeout,"")
        
  
    def capture_page_screenshot(self, file_name = None):
        file_name = str(file_name)
        if not self.screenshot_dir:
            self.screenshot_dir = os.path.join(Utils.get_output_dir(), "page_screenshot")
        Utils.create_directory_if_not_exist(self.screenshot_dir)
        _output = self.screenshot_dir
        if not file_name:
            file_name = self.driver.__hash__()
        _output = os.path.join(_output, file_name)
        if not _output.endswith(".png"):
            _output += ".png"
        image_path = self.driver.capture_page_screenshot(_output)
        Utils.add_file_to_report(image_path, file_name)
        return image_path
        
  
    @catch_exception
    def click_on_element(self, locator):
        _locator = Utils.get_values_if_be_a_keyword(locator)
        self.driver.find_element(_locator).click()

【问题讨论】:

  • 你能不能edit 这个来描述它是如何不起作用的。故障排除的很大一部分是能够了解事情如何偏离预期。
  • @sphennings:好的,我编辑了描述。
  • 请显示完整的回溯。
  • @BryanOakley:好的,我将添加一张图片完整的回溯。它表明 self 没有定义,因为我在一个类内部调用了一个方法,而我的方法在外部
  • 请不要添加回溯的图片。花时间将其复制并粘贴到您的问题中。无法搜索代码和错误的图像,视障者根本看不到它们。

标签: python selenium error-handling robotframework


【解决方案1】:

我的猜测:在catch_exception 的定义中将WebInterface.capture_page_screenshot(self) 替换为args[0].capture_page_screenshot()

装饰器定义中的函数对self一无所知:它没有在类定义中定义,给它的参数只有args(一个列表)和kwargs(一个字典):

def func(*args, **kwargs):
    ...

当您在类定义中使用装饰器时,args (args[0]) 的第一个元素是 self,因为它是给 click_on_element 的第一个参数。

【讨论】:

  • 我正在尝试这个。提前谢谢你,它抛出了一些回溯,我正在修复它。
  • 成功了。非常感谢。你能告诉我为什么我们写 args[0] 吗?
  • 还有一个麻烦,为什么它不能引发异常.. 请看我最近添加的第一张照片
  • @Scorpisces 好的,你能不能试试args[0].capture_page_screenshot() 而不是WebInterface.capture_page_screenshot(self)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 2015-09-18
  • 2019-07-14
  • 2021-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多