接口自动化测试中,难免会出现前置条件和后置条件的处理问题,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', '