【问题标题】:Get number of retries from Wait Until Keyword Succeeds从等待关键字成功获取重试次数
【发布时间】:2021-01-26 11:19:44
【问题描述】:

我们正在使用 Robot Framework 来测试一个容易出错的组件,我们无法调试。该组件的行为有些不稳定,因此在几个地方我们使用关键字Wait Until Keyword Succeeds 10x 1s Connect Via SSH 尝试多次,即使它应该在第一次尝试时工作。

不,最好获取关键字的重试次数,以便在需要多次重试时发出警告Log 消息。

下面的 sn-p 说明了我想要实现的目标:

${result}   ${noRetries}=   Wait Until Keyword Suceeds with Return   10x   1s   Connect Via SSH
Run Keyword If   ${noRetries}>1     Log   ${noRetries} were necessary for Connect Via SSH   level=WARN

有没有办法通过 Robot Framework 轻松实现这一目标?

【问题讨论】:

  • 不使用 vanilla 关键字 - 它只返回被调用关键字的结果;它实际上是:return self.run_keyword(name, *args),在 try-catch 块内。您可能想要创建一个自定义关键字或 python 方法,它会返回结果和重试次数。

标签: robotframework built-in


【解决方案1】:

我会创建更高级别的关键字,其中包含不稳定的关键字并在其中增加尝试。

编辑。使用自定义库示例更新答案(选项 B)

库解决方案使机器人文件更干净,因为复杂性转移到了 Python 端。

选项 A。

使用机器人框架测试变量。

*** Settings ***
Test Setup    Set Test Variable  ${KW_RUNS}  ${0}

*** Keywords ***
Flaky Keyword
    Set Test Variable  ${KW_RUNS}   ${KW_RUNS+1}
    Connect Via SSH

*** Test Cases ***
Trying something here
    ${result}   Wait Until Keyword Succeeds   10   1s   Flaky Keyword
    Run Keyword If   ${KW_RUNS}>1     Log   ${KW_RUNS} were necessary for Connect Via SSH   level=WARN

选项 B。

使用 Robot Framework 自定义库。

flakylib.py

import time
from robot.libraries.BuiltIn import BuiltIn

KW_RUNS = 0


def custom_kw_runner(name, *args):
    global KW_RUNS
    KW_RUNS += 1
    return BuiltIn().run_keyword_and_return_status(name, *args)


def run_flaky_kw(retries=10, interval=1, name="", *args):
    global KW_RUNS
    KW_RUNS = 0
    status = False
    for _ in range(retries):
        status = custom_kw_runner(name, *args)
        if bool(status):
            break
        time.sleep(interval)
    if not bool(status):
        raise AssertionError(
            f"Keyword '{name}' failed after retrying for {retries*interval} seconds."
        )
    if bool(status) and KW_RUNS > 1:
        BuiltIn().log(f"{KW_RUNS} runs were necessary for '{name}'", level="WARN")
    return status, KW_RUNS

withlib.robot

*** Settings ***
Library  flakylib.py


*** Test Cases ***
Trying something here
    ${status}  ${runs}=  Run Flaky KW  name=Connect Via SSH

【讨论】:

  • 感谢您的快速回复。我经常使用等待关键字成功。也许还有一个更通用的解决方案,但我真的不知道该怎么做。仍然非常感谢您的解决方案,它至少可以正常工作。 :-)
  • 很好用 :) 另一种解决方案是使用关键字制作自己的自定义库,该关键字基本上可以完成我在示例中发布的内容。
  • 使用选项 2,调用者将无法取回被调用关键字的返回值,这在很多情况下可能需要。最可靠的方法是重新实现 wait_until_keyword_succeeds 关键字,同时返回重试次数。
猜你喜欢
  • 2021-09-18
  • 2019-01-01
  • 1970-01-01
  • 2023-02-07
  • 2020-11-18
  • 1970-01-01
  • 2013-12-29
  • 1970-01-01
  • 2020-11-23
相关资源
最近更新 更多