2、HttpRunner_测试用例和hook机制

2019-12-03  本文已影响0人  猪儿打滚

PS.本系列的内容主要来自HttpRunner官方文档,因为个人习惯,在学习的时候会写笔记用以加深记忆(cv大法),所以有本系列的笔记。
https://cn.httprunner.org/


测试用例结构

一、概念

PS.在单个测试用例,它的数据存储结构是list of dict的形式,里面可能包含一个全局配置项config和若干个测试步骤test

二、变量空间作用域/context作用域

在一个测试用例中,划分了两层变量空间作用域:

三、全局变量config的字段介绍
key 必需? 类型 介绍
name string 测试用例的名称,会在测试报告中作为标题显示
variables list / dict 定义的全局变量,作用域是当前测试用例
parameters list / dict q全局参数,作用域是当前测试用例,用于实现数据化驱动
request dict request的公共参数,作用域是当前测试用例,常用参数有base_url、headers

官方例子(json):

"config": {
    "name": "testcase description",
    "parameters": [
        {"user_agent": ["iOS/10.1", "iOS/10.2", "iOS/10.3"]},
        {"app_version": "${P(app_version.csv)}"},
        {"os_platform": "${get_os_platform()}"}
    ],
    "variables": [
        {"user_agent": "iOS/10.3"},
        {"device_sn": "${gen_random_string(15)}"},
        {"os_platform": "ios"}
    ],
    "request": {
        "base_url": "http://127.0.0.1:5000",
        "headers": {
            "Content-Type": "application/json",
            "device_sn": "$device_sn"
        }
    },
    "output": [
        "token"
    ]
}
四、测试步骤test的字段介绍
Key 必需? 类型 备注
name string 测试步骤的名称,会在测试报告中座位测试步骤的名称显示
request dict http请求的详细内容,具体参数可见python.request
variables list / dict 变量,作用域为所在test
extract list 从当前请求的响应结果中提取参数,并保存在参数变量中(比如token),在后续测试用例就可以通$变量(比如$token)进行引用
validate list 结果校验项,对当前请求的响应结果进行判断,作为当前测试用例是否通过的依据
setup_hooks list 在发送请求之前先执行hook函数,主要用于准备工作
teardown_hooks list 在发送请求值后执行hook函数,主要用于测试完毕后的清理工作
api str 引用接口定义,填写对应接口定义文件的绝对路径或相对路径,推荐使用相对路径,根路径是 debugtalk.py所在的目录路径。
testcase str 引用其它测试用例,填写测试用例的绝对路径或相对路径,推荐使用相对路径,根路径是debugtalk.py所在的目录路径。
output str / 其他? 当前测试步骤输出的值,比如输出token:output: - session_token
1.extract

根据响应结果的数据结果,再采用不同的提取方式:

2.validate

支持下面两种格式(yaml):

# 1
- 判断规则:"需判断的属性key","预期中的属性value"
# 2
-{check:"需判断的属性key", comparator:"判断规则", expect:"预期中的属性value"}
3.预期结果/expect

顾名思义,填写预期结果即可。是json层级关系,比如说请求的响应内容中code的值是0,那么“需判断的属性key是”content.code,“预期中的属性value”是:0

五、hooks/钩子

HttpRunner的钩子机制分为两个层面:

1.测试用例层面/testcase

在测试用例的config中提供了setup_hooksteardown_hooks这两个关键字

- config:
    name: basic test with httpbin
    request:
        base_url: http://127.0.0.1:3458/
    setup_hooks:
        - ${hook_print(setup)}
    teardown_hooks:
        - ${hook_print(teardown)}
2.测试步骤层面/teststep

同样的,在测试步骤的test中提供了setup_hooksteardown_hooks这两个关键字

"test": {
    "name": "get token with $user_agent, $os_platform, $app_version",
    "request": {
        "url": "/api/get-token",
        "method": "POST",
        "headers": {
            "app_version": "$app_version",
            "os_platform": "$os_platform",
            "user_agent": "$user_agent"
        },
        "json": {
            "sign": "${get_sign($user_agent, $device_sn, $os_platform, $app_version)}"
        }
    },
    "validate": [
        {"eq": ["status_code", 200]}
    ],
    "setup_hooks": [
        "${setup_hook_prepare_kwargs($request)}",
        "${setup_hook_httpntlmauth($request)}"
    ],
    "teardown_hooks": [
        "${teardown_hook_sleep_N_secs($response, 2)}"
    ]
}
3.hook函数/勾子函数的编写

hook函数需要在debugtalk.py文件中,依旧是采用$(func($a, $b))的形式去调用hook函数

def hook_print(msg):
    print(msg)
4.测试步骤层面的setup_hooks

除了可以传入自定义参数以外,还可以传入$request,对应着当前测试步骤$request的所有内容。并且因为$request是可变参数类型/dict,所以可以通过request["key"]的方式,灵活获取request的信息。这让在对请求参数进行预处理时更加方便。

def setup_hook_prepare_kwargs(request):
    """
    根据请求的Content-Type来对请求的data进行加工处理
    """
    if request["method"] == "POST":
        content_type = request.get("headers", {}).get("content-type")
        if content_type and "data" in request:
            # if request content-type is application/json, request data should be dumped
            if content_type.startswith("application/json") and isinstance(request["data"], (dict, list)):
                request["data"] = json.dumps(request["data"])

            if isinstance(request["data"], str):
                request["data"] = request["data"].encode('utf-8')

def setup_hook_httpntlmauth(request):
    """
    HttpNtlmAuth权限授权。
    """
    if "httpntlmauth" in request:
        from requests_ntlm import HttpNtlmAuth
        auth_account = request.pop("httpntlmauth")
        request["auth"] = HttpNtlmAuth(
            auth_account["username"], auth_account["password"])
5.测试步骤层面的teardown_hooks

同样的,在测试步骤层面的teardown_hooks函数中,除了可以传入自定义参数以外,还可以传入response,这个参数对应当前测试步骤的请求的响应,也就是requests.resposne
经常用于对响应内容进行处理,比如说解密、参数运算等,然后再进行参数提取extract和参数校验validate

def alter_response(response):
    response.status_code = 500
    response.headers["Content-Type"] = "html/text"
- test:
    name: alter response
    request:
        url: /headers
        method: GET
    teardown_hooks:
        - ${alter_response($response)}
    validate:
        - eq: ["status_code", 500]
        - eq: ["headers.content-type", "html/text"]
上一篇 下一篇

猜你喜欢

热点阅读