httprunner学习4-variables变量声明与引用

前言

在 HttpRunner 中,支持变量声明(variables)和引用($var)的机制。在 config 和 test 中均可以通过 variables 关键字定义变量,然后在测试步骤中可以通过 $ + 变量名称 的方式引用变量。
区别在于,在 config 中定义的变量为全局的,整个测试用例(testcase)的所有地方均可以引用;在 test 中定义的变量作用域仅局限于当前测试步骤(teststep)
httprunner==1.5.8

局部变量

在登录案例中,账号和密码是写死的,一般写用例的时候,我们最好把这种可能会变的参数单独写个变量。做到测试数据和代码的分离,以便后续维护。
如果我们在test下声明的变量,作用域只在当前test下有效。声明变量用variables,变量和对应值用键值对,如

- test:
    name: login case1
    variables:
        user: test
        psw: 123456

引用user和psw变量用$user,$psw,完整的test_var.yml脚本如下

# 上海悠悠,QQ交流群:750815713
- config:
    name: logincase
    variables: {}
- test:
    name: login case1
    variables:
        user: test
        psw: 123456
    request:
        url: http://127.0.0.1:8000/api/v1/login/
        method: POST
        headers:
            Content-Type: application/json
            User-Agent: python-requests/2.18.4
        json:
            username: $user
            password: $psw
    extract:
        - token: content.token         # 提取token
    validate:
        - eq: [status_code, 200]
        - eq: [headers.Content-Type, application/json]
        - eq: [content.msg, login success!]
        - eq: [content.code, 0]

局部变量只在当前的test用例生效,在其它的test用例不会生效

运行用例

使用hrun运行结果

D:\soft\untitled>hrun test_var.yml
login case1
INFO     POST http://127.0.0.1:8000/api/v1/login/
INFO     status_code: 200, response_time(ms): 384.72 ms, response_length: 109 bytes
INFO     start to extract from response object.
INFO     start to validate.
.

----------------------------------------------------------------------
Ran 1 test in 0.394s

OK
INFO     Start to render Html report ...
INFO     Generated Html report: D:\soft\untitled\reports\1569114664.html

全局变量

如果要设置一个全局变量,需把变量声明(variables)放到config下,这样就在整个.yml文件生效了

- config:
    name: logincase
    variables:
        user: test
        psw: 123456
- test:
    name: login case1
    request:
        url: http://127.0.0.1:8000/api/v1/login/
        method: POST
        headers:
            Content-Type: application/json
            User-Agent: python-requests/2.18.4
        json:
            username: $user
            password: $psw
    extract:
        - token: content.token         # 提取token
    validate:
        - eq: [status_code, 200]
        - eq: [headers.Content-Type, application/json]
        - eq: [content.msg, login success!]
        - eq: [content.code, 0]

运行结果

D:\soft\untitled>hrun test_config_var.yml
login case1
INFO     POST http://127.0.0.1:8000/api/v1/login/
INFO     status_code: 200, response_time(ms): 580.17 ms, response_length: 109 bytes
INFO     start to extract from response object.
INFO     start to validate.
.

----------------------------------------------------------------------
Ran 1 test in 0.584s

OK
INFO     Start to render Html report ...
INFO     Generated Html report: D:\soft\untitled\reports\1569114978.html


httprunner 2.x实战教程点我 ->立即报名

posted @ 2019-09-22 09:17  上海-悠悠  阅读(4827)  评论(0编辑  收藏  举报