代码之家  ›  专栏  ›  技术社区  ›  Beni Keyserman

Robot框架-根据输入更改变量

  •  0
  • Beni Keyserman  · 技术社区  · 6 年前

    我有以下css选择器

    ${Table_Row}      css=.tr > td:nth-child(2)
    

    此选择器将获取表中的第一个实例。问题是这个表可能包含数百个实例,我不想有数百个变量。如何使变量更具动态性,以便在不使用关键字的情况下传递另一个变量来确定“第n个子”计数?

    下面是我的意思的python示例:

    table_row = ".tr > td:nth-child(%s)"
    

    如果我调用这个变量

    table_row % 5
    

    结果将是

    .tr > td:nth-child(5)
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   A. Kootstra    6 年前

    如果这是经常重复的事情,并且您希望集中化逻辑,而不必处理变量,那么 Custom Locator Strategy ,则,

    受您问题启发的示例:

    *** Test Cases ***
    Test Case
        Add Location Strategy   table   Custom Locator Strategy
        Page Should Contain Element table=3
    
    *** Keywords ***
    Custom Locator Strategy 
        [Arguments]    ${browser}    ${criteria}    ${tag}    ${constraints}
        ${element}=    Get Webelement   css=.tr > td:nth-child(${criteria}) 
        [Return]    ${element}
    

    这将适用于将定位器作为输入参数的所有关键字。自定义定位器策略只需要返回一个Web元素。

    在我看来,另一种方法满足内联标准,但在我看来不太可读(留给读者),那就是使用字符串对象函数。它们在 Advanced Variable Syntax 机器人框架指南部分:

    *** Variables ***
    ${locator_template}    css=.tr > td:nth-child(%) 
    
    *** Test Cases ***
    TC
        Log    Locator Template: "${locator_template}"
        ${locator}    Set Variable    ${locator_template.replace("%", "9")}
    
        Log    Locator Variable: "${locator}"
        Log    Inline Variable: "${locator_template.replace("%", "9")}"
        Log    Locator Template: "${locator_template}"
    

    此示例显示如何内联使用对象函数。由于Python字符串对象具有replace方法,因此它将提供一种稳定的方法来替换相同的变量,并使用它的replace输出来进一步分配关键字。

    它将产生以下结果:

    Starting test: Robot.String Replace.TC
    20180513 12:25:21.057 : INFO : Locator Template: "css=.tr > td:nth-child(%)
    20180513 12:25:21.058 : INFO : ${locator} = css=.tr > td:nth-child(9)
    20180513 12:25:21.059 : INFO : Locator Variable: "css=.tr > td:nth-child(9)"
    20180513 12:25:21.060 : INFO : Inline Variable: "css=.tr > td:nth-child(9)"
    20180513 12:25:21.061 : INFO : Locator Template: "css=.tr > td:nth-child(%)"
    Ending test: Robot.String Replace.TC
    

    可以看出,replace函数返回结果,而不更新原始字符串。这使得它可以用作可重用模板。