RobotFramework---变量新玩法

本文回顾了RobotFramework中变量的创建方法,包括内置关键字、变量文件和函数返回值。重点讨论了新发现的创建变量的等价方式,强调了使用`${}`或`${}`语法以避免意外创建新变量的问题。通过执行实例展示了如何避免此类问题,特别是在已存在变量的情况下,如何正确赋值和避免创建新的同名变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

🌷 回顾一下

RF创建使用变量有多种形式,大致有三类

(1)使用内置关键字创建

1.set variable
2.set global variable
3.set suite variable
4.set test variable
5.set local variable
6.create list
7.create Dictionary

(2)使用变量文件,这个是我目前最常用的

创建一个python文件,然后在这个python文件里使用python语法创建各种变量, 供RF来调用

在testcase文件里引用该变量文件

(3) 函数的返回值

例如 获取关键字的执行结果和状态用两个变量存储

${status}    ${return_value}    Run Keyword And Ignore Error    click button    ${upload_xpath}

log    ${status}+${return_value}

run keyword if    "${status}" != "PASS"    ExectureJSClick    ${upload_xpath} 

在实际应用中,根据自己的需求可自由选择和组合

🌷 新发现

之前我们创建一个变量的时候,总是使用标量的形式

Set Suite Variable${name} value 

但也有等价的方式,你可以这样创建

Set Suite Variable$name value
Set Suite Variable${name}value 

之所以会出现后续两种创建方式,是因为,我们可以原英文的解释

A problem with using the normal ${variable} syntax is that these keywords cannot easily know is the idea to create a variable with exactly that name or does that variable actually contain the name of the variable to create. If the variable does not initially exist, it will always be created. If it exists and its value is a variable name either in the normal or in the escaped syntax, variable with that name is created instead. For example, if ${name} variable would exist and contain value $example, these examples would create different variables:

Set Suite Variable${name} value# Creates ${example}.
Set Suite Variable$name value# Creates ${name}.
Set Suite Variable\${name}value# Creates ${name}. 

Because the behavior when using the normal ${variable} syntax depends on the possible existing value of the variable, it is highly recommended to use the escaped $variable or ${variable} format instead.

大致意思是说,使用常见的方式创建一个变量,我们不能确定这个变量是已知存在的,还是从来没有被创建过,如果是已知存在的,会有一些自己意向不到的值,所以强烈建议使用后面两种方式创建

这样还是很不好理解对不对,那么我们执行个实例

🌷 执行实例

我是用变量文件创建一个已知变量 url

url="$example" 

然后在robot文件里,这样写

*** Test Cases ***

001_TC_Example

    Set Suite Variable  ${url}   new_url

    Set Suite Variable  $url   new_url

    Set Suite Variable  \${url}   new_url 

让我们执行看看

从执行结果看出,当一个已存在的变量variable含有这种“{variable}含有这种“variable含有这种“xx”形式, 你在脚本中给她重新赋值时,并不会赋值成功,而是创建了一个新的变量“xx”,其他两种方式就可避免这种问题,其实这也很好理解,“{xx}”, 其他两种方式就可避免这种问题,其实这也很好理解,“xx”,其他两种方式就可避免这种问题,其实这也很好理解,“”在RF中有特殊含义

那么我们这样试试看

url="a$example" 

这样三个都一致了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值