当前位置: 首页> 财经> 创投人物 > pytest基础

pytest基础

时间:2025/7/11 22:48:45来源:https://blog.csdn.net/qq_43215246/article/details/139442617 浏览次数:0次
一、pytest默认的用例规范
  1. 用例文件:以test开头
  2. 类名称:以Test开头的类会被当成测试用例类
  3. 方法名称:以test开头的方法会被当成测试用例方法
二、用例的前后置方法
  1. 方式一:
# 用例级别:setup、teardown
# 类级别:setup_class、teardown_class
class TestRegister:def setup(self):print("setup:每个用例开始前都会执行" + '11')def teardown(self):print("teardown:每个用例结束后都会执行" + '222')def setup_class(self):print('这是类的前置方法')def teardown_class(self):print('这是类的后置方法')def test_register(self):assert 100 == 100def test_register01(self):assert 66 == 55
  1. 方式二:
# 通过pytest.fixture
# 定义用例级别的前后置
@pytest.fixture(scope='function')
def setup_case():print('这是用例的前置方法')yieldprint('这是用例的后置方法')# 定义类级别的前后置
@pytest.fixture(scope='class')
def setupclass_case():print('这是类的前置方法')yieldprint('这是类的后置方法')

调用:

# 1、在用例方法的参数中,写上前后置的方法名
class TestRegister01:def test_register(self, setup_case, setupclass_case):assert 100 == 99def test_register01(self, setup_case):assert 66 == 66
# 2、在定义前后置方法的时候(设置参数:autouse=Ture),可以设置为自动执行(用的较少)
三、用例执行的顺行
  1. 同一文件中的用例:按照用例的顺序执行
  2. 不同文件的执行顺行:按照文件的ascii码来执行
四、用例打标签
  1. 在pytest.ini文件中使用markets这个配置项注册标签
  2. 给用例加标签
class TestDemo:# 1、通过pytestmark = [pytest.mark.max]给测试类中的所有测试方法打上该标签# 2、通过@pytest.mark.标签名给测试用例方法打标签pytestmark = [pytest.mark.zm]@pytest.mark.max@pytest.mark.mindef testlogin00(self):assert 100 == 100@pytest.mark.maxdef testlogin01(self):assert 100 == 100
  1. 通过标签选择用例执行
# 命令行执行被标签max标记的测试用例
python -m max
# 运行run文件
python.main(['-m', 'max'])
# 筛选多个标签
python -m not 'max'
python -m 'max' and 'min'
python -m 'max' or 'min'
  1. 内置的标签
class TestDemo:num = 100# 被skip标签标记的用例不会被执行@pytest.mark.skipdef testlogin00(self):assert 100 == 100# skipif中的判断条件成立,则被skipif标签标记的用例不会被执行。注意:reason参数必须要有,不然会报错@pytest.mark.skipif(num == 100, reason='num不等于100')def testlogin04(self):assert 100 == 100
五、用例运行的方式
  1. 运行方式
命令行:pytest 参数
pytest.main运行:pytest.main([参数列表])
  1. 通过标签筛选用例执行
命令行:pytest -m 标签名
pytest.main运行:pytest.main(['-m', '标签名'])
  1. 筛选执行的用例
# 1、执行指定用例文件 pytest 文件名.py
# 2、执行指定用例目录 pytest 目录名
# 3、执行指定用例类 pytest 文件名.py::类名
# 4、执行指定用例方法 pytest 文件名.py::类名::方法名
六、断言

使用assert进行断言

七、参数化(等同于unittest中的ddt)
# 用例方法添加@pytest.mark.parametrize('item', cases)
class TestLogin:cases = [0, 7 , 1, 4, 5]@pytest.mark.parametrize('item', cases)def testlogin(self, item):print(item)
八、测试报告(集成allure报告平台)
  1. 下载allure 进行解压
  2. 将解压后的allure中的bin目录路径配知道环境变量
  3. 安装allure-pytest插件
  4. 执行用例时加上参数 --alluredir=报告数据存放的目录
  5. 在命令行启动allure服务,获取报告
allure serve 报告数据的路径
九、失败重试
  1. 安装pytest-rerunfailures
  2. 命令行执行
pytest test.py --reruns 3 reruns-delay 1 --alluredir=allure_reports/
  1. 通过pytest.main执行
pytest.main(['test_reporter.py', '--reruns', '3', '--reruns-delay', '1', '--alluredir=allure_reports/'])
关键字:pytest基础

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: