还是以本地搭建的接口测试平台的登录接口为例,发送请求,生成报告,查看结果等一系列操作,代码都是经过本地调试,运行通过的:
1、api目录下的demo_api.yml代码:
name: 登录接口 base_url: ${ENV(BASE_URL)} variables: username: $username password: $password status: $status request: url: /user/login/ method: POST headers: Content-Type: "application/json" json: username: $username password: $password validate: - eq: ["status_code", 200]
2、testcases/demo_testcase.yml代码:
config: variables: title: $title status: $status contains_msg: $contains_msg teststeps: - name: $title api: api/demo_api.yml validate: - eq: ["status_code", $status] - {check: "content", comparator: "contains", expect: $contains_msg}
3、testsuites/demo_testsuite.yml代码:
testcases: - name: $title testcase: testcases/demo_testcase.yml parameters: - title-username-password-status-contains_msg: ${get_login_datas()} # - ["正常登录", "benben", "123456", 200, "token"] # - ["用户名错误", "bb", "123456", 400, "non_field_errors"] # - ["密码错误", "benben", "111111", 400, "non_field_errors"]
说明:
demo_testsuite中的parameters参数化实现:
1、可以直接写测试数据,如上边注释掉的代码
2、使用CSV文件来保存测试数据:- title-username-password-status-contains_msg: ${P(datas/accounts.csv)}
3、使用函数动态生成参数,将测试数据写到debugtalk.py中,函数返回嵌套字典的列表即可,例如:
def get_login_datas(): user_info = [ {"title": "正常登录", "username": "benben", "password": "123456", "status": 200, "contains_msg": "token"}, {"title": "用户名错误", "username": "bb", "password": "123456", "status": 400, "contains_msg": "non_field_errors"}, {"title": "密码错误", "username": "benben", "password": "111111", "status": 400, "contains_msg": "non_field_errors"}, ] return user_info
4、将BASE_URL变量存放到.env文件中:
BASE_URL=http://127.0.0.1:8000
5、运行,使用扩展模板:
hrun testsuites/demo_testsuite.yml --report-template templates/ext_reports_template.html
6、查看运行结果: