httprunner3.x hook机制

本文介绍了httprunner中的hook机制,用于处理接口自动化测试中的前置和后置条件。setup_hook在请求前运行,用于准备工作和参数校验,而teardown_hook在请求后运行,用于清理工作和响应值检查。通过在debugtalk.py文件定义普通函数作为hook,并在测试步骤中引用,可以实现自定义的前置和后置操作。文章提供了具体的函数定义和用例调用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

接口自动化测试中,难免会出现前置条件和后置条件的处理问题,unittest框架中使用最多的是setUp() 、tearDown() ;pytest中使用最多的是在夹层 conftest.py 文件中定义函数加 @pytest.fixture() 装饰器来处理;而httprunner中使用的是hook机制来处理前置后置。

 

在 .py文件的测试步骤的 teststeps 中新增关键字 setup_hook 和 teardown_hook:

import pytest
from httprunner import (HttpRunner, Config, Step, RunRequest, Parameters)


class TestCaseLogin(HttpRunner):

    @pytest.mark.parametrize('param', Parameters({"device_type": [1]}))
    def test_start(self, param):
        super().test_start(param)

    config = (
        Config("login")
        .base_url("${ENV(HOSTURL)}")
        .variables(
            **{"username": "${ENV(USERNAME)}",
               "password": "${ENV(PASSWORD)}",
               "company_id": "${ENV(COMPANYID)}"
               }
        )
        .verify(False)
    )
    teststeps = [
        Step(
            RunRequest('login')
            .with_variables(**{'token_length': 32, 'status_code': 201, 'status': 1})
            .setup_hook('${setup_hooks_request($request)}')
            .post('/client/user/auth')
            .with_headers(**{"Content-Type": "application/json"})
            .with_json({"scenario": "client", "company_id": '$company_id',
                        "user_name": "$username", "password": "$password",
                        "device_type": "$device_type", "device": ""})
            .teardown_hook('${teardown_assert_response($response)}')
            .extract()
            .with_jmespath("body.data.token", "token")
            .validate()
            .assert_equal('status_code', '$status_code', '断言失败')
            .assert_equal('body.status', '
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值