<5>pytest:前置后置

目录:测试自动化学习 - pytest
说明:本篇博客基于pytest 6.2.5



总览

范围 前置 后置 代码位置 运行规则
模块级 setup_moudle teardown_moudle 模块 模块调用时,运行一次
函数级 setup_function teardown_function 模块 函数调用时,每次运行
类级 setup_class teardown_class 运行一次
方法级 setup_method teardown_method 方法调用时,每次运行
类中 setup teardown 方法调用时,每次运行

执行顺序

类外

setup_moudle
setup_function
case
teardown_function
teardown_moudle

类中

setup_moudle
setup_class
setup_method
setup
case
teardown
teardown_method
teardown_class
teardown_moudle

代码举例

代码

def setup_module():
    print("\nsetup_module")


def teardown_module():
    print("teardown_module")


def setup_function():
    print("\nsetup_function")


def teardown_function():
    print("teardown_function")


def test_case1():
    print("测试用例_函数1")


def test_case2():
    print("测试用例_函数2")


class TestClass:
    def setup_class(self):
        print("\nsetup_class")

    def teardown_class(self):
        print("teardown_class")

    def setup_method(self):
        print("\nsetup_method")

    def teardown_method(self):
        print("teardown_method")

    def setup(self):
        print("setup")

    def teardown(self):
        print("teardown")

    def test_class_case1(self):
        print("测试用例_类_方法1")

    def test_class_case2(self):
        print("测试用例_类_方法2")

输出

============================= test session starts =============================
collecting ... collected 4 items

setup_and_teardown.py::test_case1 
setup_module

setup_function
PASSED                                 [ 25%]测试用例_函数1
teardown_function

setup_and_teardown.py::test_case2 
setup_function
PASSED                                 [ 50%]测试用例_函数2
teardown_function

setup_and_teardown.py::TestClass::test_class_case1 
setup_class

setup_method
setup
PASSED                [ 75%]测试用例_类_方法1
teardown
teardown_method

setup_and_teardown.py::TestClass::test_class_case2 
setup_method
setup
PASSED                [100%]测试用例_类_方法2
teardown
teardown_method
teardown_class
teardown_module


============================== 4 passed in 0.03s ==============================

进程已结束,退出代码为 0
posted @ 2021-12-06 17:31  漓白  阅读(69)  评论(0编辑  收藏  举报