如何快速上手写 robot 自动化用例, 网上有一大堆关于 ride 的教程, 但是对于从脚本角度来写, 一直零零散散, 语焉不详, 本文以互联网最常见的 API 接口自动化为目标, 给出方向性指引, 文字不多, 足够你理解, 想要深入, 请依循文中的文字, 再去百度 / 谷歌, 逐步精深
用例编写前提: 已经部署好了 robot/python 环境
第一个 http 接口
- *** Settings ***
- Library Collections
- Library Process
- Library RequestsLibrary
- *** Variables ***
- ${DOMAIN} http://10.xx.xx.xx:8091
- ${URI} /test/backend/xxxxlogin
- ${HEADER} {"Content-Type":"application/json"}
- ${USER} {"accountType":"1", "phonenumStr":"iamusername", "password":"iampassword"}
- ${LIST_ANIMALS} ["cat", "dog"]
- *** Test Cases ***
- my first http test case
- create session myhttp ${DOMAIN}
- ${uri} set variable ${URI}
- # headers 一定要转成 json, 不然 data 传不过去
- ${header} to json ${HEADER}
- ${postdata} to json ${DATA}
- ${resp} post request myhttp uri=${uri} data=${postdata} headers=${header}
- # 校验 http 的状态
- should be equal as integers 200 ${resp.status_code}
- # 打印 调测信息
- #log ${resp.content}
- #log ${json}
- #log ${json[0]}
- #log ${json[1]["id"]}
- ${json} to json ${resp.content}
- # 校验返回数据的关键值
- should be equal as strings 2.0 ${json[1]["jsonrpc"]}
多步操作
所有的返回值都是字符串类型, 转成 json 后就可以像字典型一样随意取用了
${json} to json ${resp.content}
把取到值当成下一次调用的入参
建议每个 testcase 只测试一个功能, 接口测试阶段, 不要构造过于复杂的场景(用例代码超过一屏将被视为复杂, 需要拆分)
结果校验
请求 http 获得的返回都是字符串类型, 解析成 json 才可以自由取用值
提供多种校验函数如下:
- should be equal as integers
- should be equal as numbers
- should be equal as strings
- should be true
- should be empty
- should contain
- should contain any
- # not 也支持
- should not be equal as integers
- should not be equal as numbers
- should not be equal as strings
- should not be true
- should not be empty
- should not contain
- should not contain any
数据驱动
robot 宣称支持数据驱动, 支持按照 template 从表格读数据来跑用例, 但是问题是, 如果要对数据表格里的 case 做拣选和拆分就会无力了, 所以, 数据驱动适合比较大规模的协议测试, 而对于有细力度的统计 case 的需求是不好用的, 我们的建议是用测试数据分散在 testcase 里, 保持 case 的独立性和灵活性, 如果确实有大量的手工操作的话, 提供小工具自动创建 testcase
前置条件(可选)
一个用例文件中包含很多 testcase, 我想统一加些动作该怎么办? 框架提供两个方法, 如果是前置条件 (每个用例开始前执行) 就用 Set up, 在 setting 里编写你的动作即可, 如果动作很复杂, 可以做成关键字调用即可, 就像下面一样:
- *** Settings ***
- Test Setup Get config
- Keywords
- Get config
log 正在初始化...
- set suite variable ${config} {"env":"uat", "user":"haha"}
- # 清理动作 (可选)> 如果是后置条件(每个 testcase 结束后调用), 就用 Tear down, 样例如下:
- Settings
- Test Teardown Do clean
- Keywords
- Do clean
log 正在清理...
- # 关键字驱动> 框架提供自定义的关键字方案, 只需要在 Keywords 下面书写你的逻辑动作即可, 关键字可以是英文, 也可以是中文, 顶格写, 不限制空格和特殊字符, 你可以像书写自然语言一样写用例代码啦
- Keywords
- My first keywords
- log hello keywords
我的第一个关键字
log 你好, 我的关键字
来源: http://www.bubuko.com/infodetail-2532121.html