测试框架学习之HttpRunner用例调试hook机制(四)

hook机制
一、介绍
1.1、使用用于请求前 / 请求后的准备 / 清理工作调用的钩子函数
1.2、使用范围:测试用例层面(testcase)、测试步骤层面(teststep)
1.3、关键字:setup_hooks 和 teardown_hooks

二、作用范围

测试用例层面(testcase)YAML / JSON 的config下
setup_hooks: 在整个用例开始执行前触发hook函数,主要用于准备工作。
teardown_hooks: 在整个用例结束执行后触发hook函数,主要用于测试后的清理工作。

示例如下:
在项目下的debugtalk.py写入


def hook_print(msg):
print(msg)


msg传参说明:
1、可传入自定义参数
2、可以传入与当前测试用例相关的信息(比如请求的$request和响应的$response)

测试用例中引用

- 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)}

测试步骤层面(teststep) YAML / JSON 的test下 
setup_hooks: 在HTTP请求发送前执行hook函数,主要用于准备工作;也可以实现对请求的request内容进行预处理。
teardown_hooks: 在HTTP请求发送后执行hook函数,主要用于测试后的清理工作;也可以实现对响应的response进行修改,例如进行加解密等处理。

示例如:
在项目下的debugtalk.py写入

setup_hooks


def setup_hook_prepare_kwargs(request):
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):
if "httpntlmauth" in request:
from requests_ntlm import HttpNtlmAuth
auth_account = request.pop("httpntlmauth")
request["auth"] = HttpNtlmAuth(
auth_account["username"], auth_account["password"])


脚本说明:
1、可传入自定义参数
2、可以传入 $request全部内容(可变参数类型(dict))
3、setup_hook_prepare_kwargs实现根据请求方法和请求的Content - Type来对请求的data进行加工处理
4、setup_hook_httpntlmauth实现ttpNtlmAuth权限授权

teardown_hooks


def teardown_hook_sleep_N_secs(response, n_secs):
""" sleep n seconds after request """
if response.status_code == 200:
time.sleep(0.1)
else:
time.sleep(n_secs)


def alter_response(response):
response.status_code = 500
response.headers["Content-Type"] = "html/text"


脚本说明:
1、根据接口响应的状态码来进行不同时间的延迟等待
2、可以对response进行修改(比如加解密、参数运算),以便于参数提取(extract)和校验(validate)

测试步骤中引用

"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]}
{“eq”: ["headers.content-type", "html/text"]
}
],
"setup_hooks": [
"${setup_hook_prepare_kwargs($request)}",
"${setup_hook_httpntlmauth($request)}"
],
"teardown_hooks": [
"${teardown_hook_sleep_N_secs($response, 2)}"
"${alter_response($response)}
"
]}
原文地址:https://www.cnblogs.com/mys6/p/14776483.html