目录
hello呀,铁铁们上一篇文章入门篇咱们介绍了pytest的基本使用,这一篇文章专门给大家讲解pytest中关于用例执行的前后置步骤处理,pytest中用例执行的前后置处理既可以通过测试夹具(fixtrue)来实现,也可以通过xunit 风格的前后置方法来实现。接下来我们一起看看如何具体使用。
一、xunit 风格的前后置方法
1、函数用例的前后置方法
在模块中以函数形式定义用例,可以通过 setup_function 和 teardown_function 来定义函数用例的前后置方法,使用案例如下:
def setup_function(function):
print("函数用例前置方法执行")
def teardown_function(function):
print("函数用例后置方法执行")
def test_01():
print('----用例方法01------')
运行结果:
C:\testcases>pytest -s
========================= test session starts =========================
platform win32 -- Python 3.7.3, pytest-5.4.2, py-1.8.0, pluggy-0.13.0
cachedir: .pytest_cache
rootdir: C:\testcases
plugins: testreport-1.1.2
collected 1 item
test_demo.py
函数用例前置方法执行
----用例方法01------ .
函数用例后置方法执行
========================= 1 passed in 0.27s =========================
2、测试类中用例的前后置方法
- 类级别的前后置方法
- pytest 中测试类级别的前后置方法 setup_class和teardown_class,分别在测试类中的用例执行之前执行,和测试类中所有用例执行完毕之后执行,具体使用如下:
- class TestDome: def test_01(self): print('----测试用例:test_01------') def test_02(self): print('----测试用例:test_02------') @classmethod def setup_class(cls): print("测试类前置方法---setup_class---") @classmethod def teardown_class(cls): print("测试类后置方法---teardown_class---")
- 用例级别的前后置方法
- pytest 中测试类中用例级别的的前后置方法 setup_method和teardown_method,分别在测试类中的用例执行之前执行,和测试类中所有用例执行完毕之后执行,具体使用如下:
- class TestDome: def test_01(self): print('----测试用例:test_01------') def test_02(self): print('----测试用例:test_02------') @classmethod def setup_class(cls): print("测试类前置方法---setup_class---") @classmethod def teardown_class(cls): print("测试类后置方法---teardown_class---") def setup_method(function): print("测试用例前置方法---setup_method---") def teardown_method(function): print("测试用例后置方法---teardown_method---")
运行结果:
C:\testcases>pytest -s
==================== test session starts ====================
platform win32 -- Python 3.7.3, pytest-5.4.2, py-1.8.0, pluggy-0.13.0
rootdir: C:\testcases
plugins: testreport-1.1.2
collected 2 items
test_demo.py
测试类前置方法---setup_class---
测试用例前置方法---setup_method---
----测试用例:test_01------.
测试用例后置方法---teardown_method---
测试用例前置方法---setup_method---
----测试用例:test_02------.
测试用例后置方法---teardown_method---
测试类后置方法---teardown_class---
==================== 2