文章目录
1.pytest安装
pip install pytest
环境配置:需要设置项目的默认运行方式为unittest
2.用例运行规则
- pytest将在当前目录及其子目录中运行所有格式为
test_*.py
开头或*_test.py
结尾的文件 - 测试方法/测试函数 默认必须是test开头
- 测试类必须是Test开头
- 测试类不能有构造方法
__init__
示例:
运行时可以扫描到当前目录和当前子目录下的用例:
3.常用参数
断言
断言借助Python中的运算符号和assert关键字实现;
# -*- coding: utf-8 -*-
# @Time : 2024/2/19 17:56
# @Author : 居里夫人吃橘子
# @File : test_demo03.py
# @Software: PyCharm
import pytest
"""
测试不相等 !=
<=
>=
测试包含 in
测试不包含 not in
判断是否为true: is True
判断是否不为true: is not True/is False
and
or
"""
def test_demo03():
print('kkkkkkk')
# assert 1 == 1
# assert 1 != 2
# assert 1 < 2
# assert 1 > 2
# assert 'a' in 'abc'
# assert 'a' not in 'abc'
# assert True
# assert False
# assert 1 == 1 and 1 < 2
assert 1 == 2 or 1 < 2
if __name__ == '__main__':
pytest.main(['-s'])
运行参数
“-s” 参数 用于关闭捕捉,从而输出打印信息到控制台
“-v” 参数 用于显示具体的用例执行信息‘
“-k” 运行名称中包含某字符串的测试用例,类似于模糊查找
‘-q’ 简化输出信息
‘-x’ 如果出现一条测试用例失败,则退出测试
指定运行测试文件中的方法或特定的类
pytest.main([‘-s’, ‘./son_dir/test_son01.py::TestDemo01’])
用例控制
- 在第N个用例失败后,结束测试;
pytest.main(['-s','test_demo03.py','--maxfail=1'])
- 失败用例重跑
安装插件pytest-rerunfailures,注意Python版本需要>3.5;pytest>5.0
pip install pytest-rerunfailures
# '--reruns'表示重跑次数;'--reruns-delay'表示失败后间隔几秒
pytest.main(['--reruns', '3', '--reruns-delay', '1', 'test_demo03.py'])
- 通过标记表达式执行指定的用例
通过@pytest.mark.标记名
装饰器标记指定的测试用例,使用pytest.main(['-m', '标记名'])
执行;
注:标记名需要提前注册,创建pytest.ini文件;标记名称冒号后面的为注释,最好使用英文;
[pytest]
markers =
ma: marks tests as smoke
slow: slow testcase
@pytest.mark.slow
def test_demo05():
print('5555555555')
if __name__ == '__main__':
pytest.main(['-s', 'test_demo03.py', '-m', 'slow'])
- 多进程执行测试用例
安装插件pytest-xdist;
pip install pytest-xdist
pytest.main(['-n', 'auto', 'test_demo03.py']) #auto为自动分配与计算机相匹配的进程;也可以指定数字
setup和teardown
- 不含有类的用例前置和后置
1.setup_module/teardown_module: 在当前文件中,在所有测试用例执行之前与之后执行
2.setup_function/teardown_function:在每个测试函数之前与之后执行
# -*- coding: utf-8 -*-
# @Time : 2024/2/20 10:49
# @Author : 居里夫人吃橘子
# @File : test_set01.py
# @Software: PyCharm
# 功能函数,相乘
import pytest
def multiply(a, b):
return a * b
"""
不含有类的用例预置和后置函数
第一批次:setup_module/teardown_module: 在当前文件中,在所有测试用例执行之前与之后执行
第二批次:setup_function/teardown_function:在每个测试函数之前与之后执行,不能在类中使用
ps:执行的顺序按优先级来的,改变方法位置结果也一样
"""
# 在当前文件前置后置
def setup_module(module):
print("setup_module===================")
def teardown_module(module):
print("teardown_module================")
# 每个用例前置后置
def setup_function(function):
print("setup_function===================")
def teardown_function(function):
print("teardown_function================")
# ========测试用例=========
def test01():
print("第一个用例")
print(multiply(3, 4))
def test02