pytest-setup和teardown

setup和teardown

pytest中有类似unittest中setUp,tearDown方法

一、运行级别

  • 模块级
    作用于一个模块内的所有class和def,对于所有class和def,setup和teardown只执行一次
setup_module
teardown_module
  • 类级  
    作用于一个class内中的所有test,所有用例只执行一次setup,当所有用例执行完成后,才会执行teardown
setup_class
teardown_class
  • 函数级  
    作用于单个测试用例(不在类中的函数)
setup_function
teardown_function
  • 方法级
    作用于单个测试用例(类中的方法)
setup_method
teardown_method
  • setup/teardown
    定义在类里面和方法级相同
    定义在类外面和函数级相同
setup
teardown

二、举例

#!/usr/bin/python3
#-*- conding:utf-8 -*-

def setup_module():
    print('模块级,整个py文件运行前执行一次')
def teardown_module():
    print('模块级,整个py文件运行后执行一次')
    
def setup_function():
    print('函数级,每个函数用例运行前执行一次')
def teardown_function():
    print('函数级,每个函数用例运行后执行一次')


class Test_class():
    @classmethod
    def setup_class(cls):
        print('类级,整个测试类运行前执行一次')
    @classmethod
    def teardown_class(cls):
        print('类级,整个测试类运行后执行一次')

    def setup_method(self):
        print('方法级,类中的每个方法用例运行前执行一次')
    def teardown_method(self):
        print('方法级,类中的每个方法用例运行后执行一次')

    def setup(self):
        print('定义在类内部,与方法级相同')
    def teardown(self):
        print('定义在类内部,与方法级相同')

    def test_1(self):
        print('正在运行 test_1')

    def test_2(self):
        print('正在运行 test_2')

def test_3():
    print('正在运行 test_3')

def test_4():
    print('正在运行 test_4')

运行结果

pytest -s

================================================== test session starts ===================================================
platform linux -- Python 3.5.3, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: /media/_dde_data/python
collected 4 items                                                                                                        

test_001.py 模块级,整个py文件运行前执行一次
类级,整个测试类运行前执行一次
方法级,类中的每个方法用例运行前执行一次
定义在类内部,与方法级相同
正在运行 test_1
.定义在类内部,与方法级相同
方法级,类中的每个方法用例运行后执行一次
方法级,类中的每个方法用例运行前执行一次
定义在类内部,与方法级相同
正在运行 test_2
.定义在类内部,与方法级相同
方法级,类中的每个方法用例运行后执行一次
类级,整个测试类运行后执行一次
函数级,每个函数用例运行前执行一次
正在运行 test_3
.函数级,每个函数用例运行后执行一次
函数级,每个函数用例运行前执行一次
正在运行 test_4
.函数级,每个函数用例运行后执行一次
模块级,整个py文件运行后执行一次


=================================================== 4 passed in 0.03s ====================================================
posted @ 2020-06-08 22:57  静心&得意  阅读(173)  评论(0编辑  收藏  举报