pytest官方文档 6.2 中文翻译版(第十七章):经典XUnit风格的setup

经典XUnit风格的setup

这一节描述在module/class/function上面,如何实现夹具的最经典也是最受欢迎的方法。

注意:虽然说 setup/teardown 在之前的unittest和nose中都十分常见,我们也很熟悉这种写法,但是pytest的这种结合了依赖注入概念的夹具的思想是十分值得思考的,这种方式给大型的项目的测试和功能测试提供可更加模块化和更加可扩展的方式来管理测试状态。你可以在一个文件中混合这几种方式,但是继承自unittest.TestCase的类不能接收夹具参数。

17.1 Module 级别的 setup/teardown

如果你在一个模块中有多个测试函数和测试类,你可以实现下面的夹具方法,这会让setup的代码在模块测试函数执行之前执行一遍:

def setup_module(module):
	""" setup any state specific to the execution of the given module."""
def teardown_module(module):
	""" 
	teardown any state that was previously setup with a setup_modulemethod.
	"""

在pytest3.0中,module参数是可选的。

17.2 Class 级别的 setup/teardown

相同的,下面的方法实现了类层次上的准备和清理方法:

@classmethod
def setup_class(cls):
	""" setup any state specific to the execution of the given class (which
	usually contains tests).
	"""
@classmethod
def teardown_class(cls):
""" teardown any state that was previously setup with a call to
setup_class.
"""

17.3 方法级别的 setup/teardown

相同,下面的方法会在每次测试方法调用之前调用

def setup_method(self, method):
	""" setup any state tied to the execution of the given method in a
	class. setup_method is invoked for every test method of a class.
	"""
def teardown_method(self, method):
	""" teardown any state that was previously setup with a setup_method
	call.
	"""

在pytest-3.0,method参数是可选的。
如果你想在模块级别定义方法级的测试夹具,你可以实现function夹具:

def setup_function(function):
	""" setup any state tied to the execution of the given function.
	Invoked for every test function in the module.
	"""
	
def teardown_function(function):
	""" teardown any state that was previously setup with a setup_function
	call.
	"""

在pytest-3.0,function参数是可选的。

备注:

  • 在一个测试中 setup/teardown可能被多次调用
  • 如果setup方法报错或者被跳过了,对应的teardown就不会被调用了
  • 在pytest-4.2之前,xunit风格的方法不遵循夹具的scope规则,所以下面的情况是有可能的 setup_method 的方法在session-scope自动使用的夹具之前被调用。现在xunit风格的方法已经与夹具机制进行了集成,会遵循目前的范围规范。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值