5.httprunner-hook机制

2022-12-23,,,

hook简介

httprunner3是基于python的pytest框架,里面也有前置和后置的概念
setup_hooks:开始执行前触发hook函数,主要用于请求预处理(签名,加密等)
teardown_hooks:结束执行后触发hook函数,主要用于返回预处理(解密等)
前后置函数编写

#debugtalk
#前后置函数编写在debugtalk文件里面
#函数名称可自定义
def setup_hook():
print('setup') def teardown_hook():
print('teardown')

前后置函数引用
前后置处理是针对每一个请求的步骤做预处理,所有在每个步骤里面引入对应处理函数
setup_hooks和teardown_hooks可以是list,可以引入多个前后置处理函数,在每个步骤里面两个参数的上下位置可以自定义
 
引入格式

 setup_hooks:
- ${前置函数名}
teardown_hooks:
- ${后置函数名}
teststeps:
-
name: step-登录
request:
url: /v1/login/
method: POST
params:
user: $user
password: $password
setup_hooks:#引入前置函数
- ${setup_hook()}
teardown_hooks:#引入后置函数
- ${teardown_hook()} extract:
uid: body.uid
validate:
- eq: [status_code,200]

场景案例
每次发送请求之前我们需要给该请求加一个签名

#debugtalk
def request_sign(request):
'''
获取request请求对象的body
定义签名
将签名传给body
给request传入有签名的body
'''
body = request.get('req_json')
sign = 'sign xxxxxxxxxxxxxxxxx'
body['sign'] = sign
request['req_json'] = body
#yaml引用
request:
url: /v1/login/
method: POST
json:
user: $user
password: $password
setup_hooks:
- ${setup_hook()}
- ${request_sign($request)} #引用签名处理前置函数,将request通过变量穿得给该函数
teardown_hooks:
- ${teardown_hook()}

5.httprunner-hook机制的相关教程结束。

《5.httprunner-hook机制.doc》

下载本文的Word格式文档,以方便收藏与打印。