0
点赞
收藏
分享

微信扫一扫

pytest中的setup和teardown函数

code_balance 2022-10-22 阅读 36

1、setup和teardown函数的作用

setup函数:主要用来做初始化作用,比如数据库连接、前置参数的赋值等

teardown函数:测试后的清除作用,比如参数的还原或销毁,关闭数据库连接等

2、分类

2.1、不定义在测试类中:

模块级:指的是一个py文件

​​​setup_module()/teardown_module()​:开始于模块始末,全局的

def setup_module():
print('setup_module...')


def test_01():
print('test_01...')


def test_02():
print('test_02...')


def teardown_module():
print('teardown_module...')

pytest中的setup和teardown函数_pytest

函数级:类外定义的方法叫函数

​​​​setup_function()/teardown_function()​​:只对函数用例生效(不在类中)。

def setup_function():
print('setup_function...')


def test_01():
print('test_01...')


def test_02():
print('test_02...')


class Test(object):
def test_03(self):
print('test_03...')


def teardown_function():
print('teardown_function...')

pytest中的setup和teardown函数_pytest_02

2.2、定义在测试类中

类级:指的是一个class类

​​​setup_class()/teardown_class()​:只在类中前后运行一次(在类中)。

def test_01():
print('test_01...')


def test_02():
print('test_02...')


class Test(object):
@staticmethod
def setup_class():
print('setup_class...')

def test_03(self):
print('test_03...')

def test_04(self):
print('test_04...')

@staticmethod
def teardown_class():
print('teardown_class...')

pytest中的setup和teardown函数_pytest_03

方法级:类中定义的方法叫方法

​​setup_method()/teardown_method():开始于方法始末(在类中)。

def test_01():
print('test_01...')


def test_02():
print('test_02...')


class Test(object):
@staticmethod
def setup_method():
print('setup_method...')

def test_03(self):
print('test_03...')

def test_04(self):
print('test_04...')

@staticmethod
def teardown_method():
print('teardown_method...')

pytest中的setup和teardown函数_pytest_04

2.3、既可以写在类中,也可以写在类外

自由的:​​setup()/teardown()​​:

2.3.1、写在类外,与模块级别类似

def setup():
print('setup...')


def test_01():
print('test_01...')


def test_02():
print('test_02...')


class Test(object):

def test_03(self):
print('test_03...')

def test_04(self):
print('test_04...')


def teardown():
print('teardown...')

pytest中的setup和teardown函数_pytest_05

2.3.2、写在类中:与方法级别类似

def test_01():
print('test_01...')


def test_02():
print('test_02...')


class Test(object):

@staticmethod
def setup():
print('setup...')

def test_03(self):
print('test_03...')

def test_04(self):
print('test_04...')

@staticmethod
def teardown():
print('teardown...')

pytest中的setup和teardown函数_pytest_06


举报

相关推荐

0 条评论