说明:httprunner 结合 pytest 的前后置方式
1. 用例级别前后置
1.1. setup teardown
class TestCaseRefTestcase(HttpRunner):
# 用例级别前后置
def setup(self):
logger.warning("------用例级别前置")
def teardown(self):
logger.warning("------用例级别后置")
config = (
Config("request methods testcase: reference testcase")
.variables(
**{
"foo1": "testsuite_config_bar1",
"expect_foo1": "testsuite_config_bar1",
"expect_foo2": "config_bar2",
}
)
.base_url("https://postman-echo.com")
.verify(False)
)
teststeps = [
Step(
RunTestCase("request with functions")
.with_variables(
**{"foo1": "testcase_ref_bar1", "expect_foo1": "testcase_ref_bar1"}
)
.call(Requests)
.export(*["foo3"])
),
Step(
RunRequest("post form data")
.with_variables(**{"foo1": "bar1"})
.post("/post")
.with_headers(
**{
"User-Agent": "${get_user_agent()}",
"Content-Type": "application/x-www-form-urlencoded",
}
)
.with_data("foo1=$foo1&foo2=$foo3")
.validate()
.assert_equal("status_code", 200)
.assert_equal("body.form.foo1", "bar1")
.assert_equal("body.form.foo2", "bar21")
),
]
if __name__ == "__main__":
TestCaseRefTestcase().test_start()
2. 类级别前后置
2.1. setup_class
def setup_class(self):
logger.warning("------类级别前置")
2.2. teardown_class
def teardown_class(self):
logger.warning("------类级别后置")
3. 模块级别前后置
3.1. conftest.py
import uuid
from typing import List
import pytest
from httprunner import Config, Step
from loguru import logger
@pytest.fixture(scope="session", autouse=True)
def session_fixture(request):
"""setup and teardown each task"""
logger.warning(f"-------conftest模块级别前置---------")
total_testcases_num = request.node.testscollected
testcases = []
for item in request.node.items:
testcase = {
"name": item.cls.config.name,
"path": item.cls.config.path,
"node_id": item.nodeid,
}
testcases.append(testcase)
logger.debug(f"collected {total_testcases_num} testcases: {testcases}")
yield
logger.debug(f"teardown task fixture")
logger.warning(f"-------conftest模块级别后置---------")
# teardown task
# TODO: upload task summary
@pytest.fixture(scope="function", autouse=True)
def testcase_fixture(request):
"""setup and teardown each testcase"""
logger.warning(f"-------conftest函数级别前置---------")
config: Config = request.cls.config
teststeps: List[Step] = request.cls.teststeps
logger.debug(f"setup testcase fixture: {config.name} - {request.module.__name__}")
def update_request_headers(steps, index):
for teststep in steps:
if teststep.request:
index += 1
teststep.request.headers["X-Request-ID"] = f"{prefix}-{index}"
elif teststep.testcase and hasattr(teststep.testcase, "teststeps"):
update_request_headers(teststep.testcase.teststeps, index)
# you can update testcase teststep like this
prefix = f"HRUN-{uuid.uuid4()}"
update_request_headers(teststeps, 0)
yield
logger.warning(f"-------conftest函数级别前置---------")
logger.debug(
f"teardown testcase fixture: {config.name} - {request.module.__name__}"
)
summary = request.instance.get_summary()
logger.debug(f"testcase result summary: {summary}")
4. 优先级顺序效果展示
testcases\debug\ref_testcase_test.py 2024-03-01 17:55:21.271 | WARNING | testcases.debug.conftest:session_fixture:12 - -------conftest模块级别前置---------
2024-03-01 17:55:21.273 | DEBUG | testcases.debug.conftest:session_fixture:23 - collected 1 testcases: [{'name': 'request methods testcase: reference testcase', 'path': 'D:\\httprunner\\demo\\testcases\\debug\\ref_testcase_test.py', 'node_id': 'testcases/debug/ref_testcase_test.py::TestCaseRefTestcase::test_start'}]
2024-03-01 17:55:21.274 | WARNING | testcases.debug.ref_testcase_test:setup_class:18 - ------类级别前置
2024-03-01 17:55:21.275 | WARNING | testcases.debug.conftest:testcase_fixture:37 - -------conftest函数级别前置---------
2024-03-01 17:55:21.275 | DEBUG | testcases.debug.conftest:testcase_fixture:41 - setup testcase fixture: request methods testcase: reference testcase - testcases.debug.ref_testcase_test
2024-03-01 17:55:21.276 | WARNING | testcases.debug.ref_testcase_test:setup:25 - ------用例级别前置