为什么套件变量的值在从资源文件导入后会丢失?

Why is the value of a suite variable lost after importing it from a resource file?

根据我在 robotframework doc 中阅读的关于变量范围和导入资源文件的内容,我希望它能工作(python 2.7,RF 2.8.7):

测试文件:

*** Settings *** 
Resource          VarRes.txt 
Suite Setup       Preconditions

*** Variables ***

*** Test Cases ***
VarDemo
    Log To Console    imported [${TODAY}]

*** Keywords *** 

资源文件:

*** Settings ***
Library           DateTime

*** Variables ***
${TODAY}          ${EMPTY}    # Initialised during setup, see keyword Preconditions

*** Keywords ***
Format Local Date
    [Arguments]    ${inc}    ${format}    
    ${date} =    Get Current Date    time_zone=local    increment=${inc} day    result_format=${format}
    [Return]    ${date}    # formatted date

Preconditions
    ${TODAY} =   Format Local Date    0    %Y-%m-%d
    Log To Console    inited [${TODAY}]

然而输出是:

inited [2015-03-20]
imported []

RF 文档指出:

Variables with the test suite scope are available anywhere in the test suite where they are defined or imported. They can be created in Variable tables, imported from resource and ....

我认为这里已经完成了。

如果我像这样在关键字先决条件中添加一行,它会起作用:

Preconditions
    ${TODAY} =   Format Local Date    0    %Y-%m-%d
    Set Suite Variable  ${TODAY}
    Log To Console    inited [${TODAY}]

原因是第一行定义了一个局部变量,而不是初始化变量table中声明的测试套件变量。 RF 文档中的一段暗示:

Variables set during the test execution either using return values from keywords or using Set Test/Suite/Global Variable keywords always override possible existing variables in the scope where they are set

我认为RF的一个主要缺点是你不能在变量table中动态定义变量。我尽量避免在关键字内设置变量的范围。

对于动态变量,您可以使用Python中的变量文件。请参阅 "Implementing variable file as Python or Java class" in the User Guide.

部分

例如,我使用 variables.py 和:

if platform.system() in ['Darwin', 'Linux']:
    OS_FAMILY = 'unix'
elif platform.system() == 'Windows':
    OS_FAMILY = 'windows'
else:
    OS_FAMILY = 'unknown'
OS_FAMILY_IS_UNIX = OS_FAMILY == 'unix'      
OS_FAMILY_IS_WINDOWS = OS_FAMILY == 'windows'   

然后在机器人测试中,我可以在任何地方使用动态变量 ${OS_FAMILY}、${OS_FAMILY_IS_UNIX} 和 ${OS_FAMILY_IS_WINDOWS}。

您应该能够创建您的 ${TODAY} 变量。