Robot Framework调用REST API时如何跨测试用例传递token变量?
问题核心原因
Robot Framework 测试用例内默认创建的变量为局部作用域,仅支持当前用例内部访问,是跨用例传参失败的主要原因,同时你的代码还存在3处疏漏:
Refresh token用例中引用token时错误使用了字典变量引用符&,字符串变量需使用$引用- 未存储
Login接口返回的refresh_token值,Refresh token用例中${refresh_token}也会出现未定义报错 - 刷新token的请求
grant_type参数错误填写为password,刷新场景应为refresh_token
解决步骤
- 在
Login用例中,使用Set Suite Variable关键字将token、refresh_token设置为套件级作用域变量,套件内所有测试用例均可访问 - 修正
Refresh token用例的变量引用语法、grant_type参数值 - 保持测试用例执行顺序为
Login在前、Refresh token在后(Robot Framework 默认按编写顺序执行,无需额外配置)
修改后完整代码
Library RequestsLibrary Library JSONLibrary Library OperatingSystem *** Variable *** ${base_url} https://api.sportpartnerxxx.vn/v1 ${identity_URL} https://identity.sportpartnerxxx.vn *** Test Cases *** Login ${body}= Create Dictionary client_id=sportpartner-mobile-app client_secret=ifd-sportpartner-secret-2021-mobile-app grant_type=password username=abc password=123456 ${header}= Create Dictionary Content-Type=application/x-www-form-urlencoded ${response}= Post ${identity_URL}/connect/token headers=${header} data=${body} Status Should Be 200 # 存储token为套件级变量 ${token}= Set Variable Bearer ${response.json()["access_token"]} Set Suite Variable ${token} # 存储refresh_token为套件级变量 ${refresh_token}= Set Variable ${response.json()["refresh_token"]} Set Suite Variable ${refresh_token} Refresh token ${body}= Create Dictionary client_id=sportpartner-mobile-app client_secret=ifd-sportpartner-secret-2021-mobile-app grant_type=refresh_token refresh_token=${refresh_token} ${header}= Create Dictionary Content-Type=application/x-www-form-urlencoded Authorization=${token} ${response}= Post ${identity_URL}/connect/token headers=${header} data=${body} Status Should Be 200
内容的提问来源于stack exchange,提问作者hanh nguyen
相关产品推荐
相关产品推荐

