Robotframework

RobotFramework 中${var} 和 $var 的区

2017-10-24  本文已影响2人  Rethink

从 Robot Framework 2.9开始 (the latest: v3.0.2),表示变量的表达式可以使用$var,那么和${var}相比,这两种写法有什么区别呢?

先来看一下BuiltIn 库官方文档 中是怎么介绍的:

Starting from Robot Framework 2.9, variables themselves are automatically available in the evaluation namespace. They can be accessed using special variable syntax without the curly braces like $variable. These variables should never be quoted, and in fact they are not even replaced inside strings.

并且还给出了例子:


其实这段话的重点就在于最后一句话,大意是 “这些变量(指$var) 不会被引用,事实上它们甚至都没有被替换成字符串。”

怎么理解这句话呢,那就要先来了解一下${var}种写法:

When a variable is used in the expressing using the normal ${variable} syntax, its value is replaces before the expression is evaluated. This means that the value used in the expression will be the string representation of the variable value, not the variable value itself. This is not a problem with numbers and other objects that have a string representation that can be evaluated directly, but with other objects the behavior depends on the string representation. Most importantly, strings must always be quoted, and if they can contain newlines, they must be triple quoted.

翻译一下: 当变量用正常的表达式语法${variable}表示时,变量的值实际上在表达式被计算之前就被替换掉了,这意味着 表达式中所使用的值将会是变量的字符串形式,而不是变量本身 。这对于数值型和那些本身有可以直接计算的字符串表示形式的对象,并不是一个问题,但对于其他对象来说,行为结果取决于字符串形式。更重要的是,字符串必须始终被引用,并且如果包含换行,则必须使用三重引用。

翻译水平有限,但是这段话并不难理解,还是以官方例子来说明:${rc}<10,在运算符两边的值在比较之前,左边的变量${rc} 会先被替换为对应的值,然后再去和右边比较:

再举个通俗易懂的例子:

${var}    Set Variable    123  
${type}    Evaluate    type(${var}) 

运行结果:

最后的结果为什么会是type int呢?在Evaluate运算过程中, 会先把{var} 替换为对应的值123,然后再去计算type(123),结果当然是type 'int'了; 再继续看,在这个例子中如果我把{var}的值改为hello,那结果又会是怎么样呢?

    ${var}    Set Variable    hello
    ${type}    Evaluate    type(${var})

运行结果会报错,报错的原因我们在上面的翻译原文的最后一句话也有提到,那就是字符串必须被引用,因此,type(hello)会报‘name is not defined’ . 我们应该写成:Evaluate type('${var}')${var} Set Variable 'hello'
这样的话在运行,结果就是正确的:


说完了{var},再来看var,套用上面的例子,但是把{var}改成了var:

    ${var}    Set Variable    hello
    ${type}    Evaluate    type($var)

运行一下,发现并没有像上次那样报错:

虽然没有报错,但是结果为什么不是type 'str',而是type 'unicode'呢?这是因为{var}和var 两种写法的运算机制不一样,var的运算机制可以分为一下几步: (1).var在运算之前不会像{var}那样直接被替换,而是会将字符串切开,比如例子中的type(var)会被切成 type 、( 、、var、)几部分; (2).接下来再去找 紧随其后的部分,也就是var, 然后在RF的命名空间中找到这个变量,如果有,就把var标记为RF_VAR_var, 同时将真实值一并对应;
(3).最后一步才是Evaluate运算,运算出的结果和python算出来的是一样的。
这里还有一点要注意的是,如果没做特殊处理,RF中的变量type结果的都是unicode类型。

最后再来用一个例子来对比理解:

    ${dict}    Create Dictionary    user    admin    passwd    123456
    ${userNew}    Set Variable    brian
    Evaluate    ${dict}.update({'user':'${userNew}'})
    Log Dictionary    ${dict}

运行结果:

{var}修改为var后:

    ${dict}    Create Dictionary    user    admin    passwd    123456
    ${userNew}    Set Variable    brian
    Evaluate    $dict.update({'user':$userNew})
    Log Dictionary    ${dict}

再看此时的运行结果:

end<

上一篇下一篇

猜你喜欢

热点阅读