Detailed Explanation of Hook Mechanism of HttpRunner Interface Automation Framework

foreword

Httprunner 4.x can support the hook mechanism, do some pre-processing before sending the request or post-processing after the request is completed

setup_hooks: Mainly used for the front-end preparation of the interface, and can also perform operations such as request request parameter signature encryption
teardown_hooks: Mainly used for post-clearing work, and can also perform operations such as decryption of the returned response

Test step add hook

Create a new debugtalk.py in the project root directory, the name must be the same

# debugtalk.py


def hook_up():
    print("前置操作:setup!")

def hook_down():
    print("后置操作:teardown!")


Only add setup_hooks and teardown_hooks test_h.yml  in the first step

config:
    name: logincase
    variables: {}

teststeps:
-
    name: step1 login
    request:
        url: http://www.example.com
        method: GET
    setup_hooks:
      - ${hook_up()}
    teardown_hooks:
      - ${hook_down()}

Execution use case

hrp run test_h.yml --gen-html-report

Executing the use case found that there is an error

8:58AM ERR gRPC Call() failed error="rpc error: code = Unknown desc = Exception calling application: Function return type
 <class 'NoneType'> not supported!" funcArgs=[] funcName=hook_up
8:58AM ERR call function failed error="rpc error: code = Unknown desc = Exception calling application: Function return ty
pe <class 'NoneType'> not supported!" arguments=[] funcName=hook_up
8:58AM ERR run step end error="run setup hooks failed: rpc error: code = Unknown desc = Exception calling application: Fu
nction return type <class 'NoneType'> not supported!: call function failed" step="step1 login" success=false type=request
8:58AM ERR [Run] run testcase failed error="abort running due to failfast setting: run setup hooks failed: rpc error: cod
e = Unknown desc = Exception calling application: Function return type <class 'NoneType'> not supported!: call function f
ailed"

The prompt function cannot return NoneType (it may be that the go engine does not support return None when executing, and it is no problem to use python's pytest to execute)

Change it slightly, just give a return

# debugtalk.py


def hook_up():
    print("前置操作:setup!")
    return ""


def hook_down():
    print("后置操作:teardown!")
    return ""

Request request preprocessing

For the preprocessing of the parameters sent by the request request, setup_hooks can also be used, and a built-in request parameter needs to be passed. The debugtalk.py code is as follows

def request_sign(request):
    """请求sign签名"""
    print("请求body:", request.get("body"))
    # 新增 sign 参数
    request["body"]["sign"] = "sign xxxxxxxxxxxxxxx"
    print("sign 签名后请求body:", request.get("body"))
    return request

test_h1.yml

config:
    name: logincase
    variables: {}

teststeps:
-
    name: step1 login
    request:
        url: http://www.example.com
        method: POST
        json:
           user: test
           psw: "123456"
    setup_hooks:
      - ${request_sign($request)}

Execution use case

hrp run test_h1.yml --gen-html-report

Check the report, the request parameter is added to sign and the signature is successful

The request preprocessing here is a little different from the previous 3.x version. If you want to use the executed hrun to execute, you need to change the debugtalk.py file content

# debugtalk.py
def request_sign(request):
    """请求sign签名"""
    print("请求body:",request.get("req_json"))
    # 新增 sign 参数
    request["req_json"]["sign"] = "sign xxxxxxxxxxxxxxx"
    print("sign 签名后请求body:", request.get("req_json"))
    return request

(The body of the request parameter is changed to req_json)

Return response processing
If you need to process the returned result after the interface returns, you can add the response request parameter, for example, I changed the returned body to "momo"

def response_status(response):
    """修改返回状态码"""
    print("返回response body:", response["body"])
    response["body"] = "momo"
    print("修改后返回response body:", response["body"])
    return response

This is very helpful for the returned body is encrypted data, which can be decrypted by itself and returned to the decrypted content

config:
    name: logincase
    variables: {}

teststeps:
-
    name: step1 login
    request:
        url: http://www.example.com
        method: POST
        json:
           user: test
           psw: "123456"
    teardown_hooks:
      - ${response_status($response)}
    validate:
      - eq: [status_code, 200]
      - eq: [body, "momo"]

Finally, I would like to thank everyone who has read my article carefully. Reciprocity is always necessary. Although it is not a very valuable thing, you can take it away if you need it:

These materials should be the most comprehensive and complete preparation warehouse for [software testing] friends. This warehouse has also accompanied tens of thousands of test engineers through the most difficult journey, and I hope it can help you! Partners can click the small card below to receive   

Guess you like

Origin blog.csdn.net/okcross0/article/details/132211470