pytest的使用
1、setup 和teardown函数
setup和teardown函数主要分为模块级、类级、功能级、函数级别。这两个函数存在测试类的内部。
作用:在函数调用之前执行setup,在函数调用之后执行teardown
使用 `pytest` 的 `fixture` 来处理设置和清理工作搭配setup和teardown
import pytest
@pytest.fixture(scope='class') # 或者 'function' 对于每个测试方法
def setup_teardown():
print('=====setup_fixture======')
yield # 在这里,测试方法会运行
print('=====teardown_fixture===')
class TestAbd:
@pytest.mark.usefixtures('setup_teardown')
def test_a(self):
print('test_a 11111111111')
assert True # 替换为实际的断言条件
@pytest.mark.usefixtures('setup_teardown')
def test_b(self):
print('test_b ttttttttttt')
assert True # 替换为实际的断言条件
2、跳过测试函数
使用skipif函数设置,可以根据特定条件,不执行标识的测试函数。 @pytest.mark.skipif(condition=True,reason=“xxx”)
参数说明: condition:跳过的条件,必传参数 reason:标注跳过的原因,必传参数,而且必须是string类型
import pytest
class TestAdb:
def test_three(self):
print('333333333')
@pytest.mark.skipif(condition=True, reason="演示无条件跳过")
def test_four(self):
print('4444444444')
def test_five(self):
print('5555555555')
if __name__ == '__main__':
# 假设文件名为 test_adb.py
pytest.main(["test_adb.py"])
3、函数数据参数化
作用:方便测试函数对测试属性的获取 方法: @pytest.mark.parametrize(argnames=“data_test”,argvalues=[(1,2,3),(4,5)],indirect=False,ids=None,scope=None)
常用参数: argnames:参数名 argvalues: 参数对应值,类型必须为List 2.当参数为一个时,参数的格式为:[value] 3.当参数个数大于一个时,格式为:[(param_value,param_value2),(param-value,param_value2)…]
import pytest
class TestAdb:
def test_three(self):
print('333333333')
@pytest.mark.parametrize("data_test", [(1, 2, 3), (4, 5, 6)]) # 确保所有元组长度一致
def test_four(self, data_test):
print(data_test)
print('4444444444')
def test_five(self):
print('5555555555')
# 通常,您不会在这里调用 pytest.main()。相反,您会在命令行中运行 pytest。
# 但是,如果您确实想从脚本中运行测试,请确保文件名正确,并且考虑使用以下方式(尽管不推荐):
if __name__ == '__main__':
# 使用当前脚本的文件名
pytest.main(["-v", __file__]) # 使用 -v 选项以更详细的模式运行测试