视频教程传送门 -> 2022最新pytest接口自动化测试框架,三天带你精通pytest,带你写出最好的代码!(已更新2022新版)_哔哩哔哩_bilibili
目录
1.setup/teardown,setup_class/teardown_class
3.conftest.py和@pytest.fixture()结合使用
一、pytest单元测试框架
单元测试框架主要做什么
1.发现用例:从多个py文件收集并加载测试用例。
2.执行用例:按照一定的顺序执行并生成结果。
3.判断结果:通过断言判断预期结果和实际结果是否一致。
4.生成报告:统计测试进度、耗时通过率等。
二、pytest简介
1.pytest是一个非常成熟的python单元测试框架,比unittest更灵活,容易上手。
2.pytest可以和自动化测试工具或框架selenium,requests,appium等实现web自动化、接口自动化、app自动化。
3.pytest可以和allure生成美观的报告。
4.pytest可以和jenkins实现持续集成。
5.pytest有很多的强大的插件
pytest-html 生成html格式的自动化测试报告
pytest-xdist 测试用例分布式执行(多线程)
pytest-orderding 控制测试用例的执行顺序
pytest-rerunfailures 失败用例重跑
pytest-base-url 基础路径的配置
allure-pytest 生成allure报告
pytest安装命令:
pip install pytest
查看安装是否成功/查看版本
pytest –version
[root@k8s-node2 testcase]# pytest --version
pytest 7.1.2
[root@k8s-node2 testcase]#
批量插件安装命令:
(将上述待安装组件写入文件requirements.txt)
[root@k8s-node2 pytest]# cat requirements.txt
pytest-html
pytest-xdist
pytest-ordering
pytest-rerunfailures
pytest-base-url
allure-pytest
[root@k8s-node2 pytest]#
pip install -r requirements.txt
三、使用pytest,默认的测试用例的规则以及基础应用
1.模块名必须以test_开头或_test结尾
2.测试类必须以Test开头,并且不能有init方法
3.测试方法必须以test开头
四、pytest测试用例的运行方式
主函数模式
命令行模式
通过读取pytest.ini配置文件运行
【例】test_date.py内容如下
-*- coding:utf-8 -*-
import pytest
class TestLogin:
def test01date(self):
print("Today is Sep 2st.")
if __name__ == '__main__':
pytest.main()
目录结构(需要安装tree,yum install tree)
[root@k8s-node2 pytest]# tree pytestdemo/
pytestdemo/
└── testcase
├── __init__.py
└── test_date.py
1 directory, 2 files
[root@k8s-node2 pytest]#
执行结果(主函数模式和命令行模式)
1.主函数的运行方式
(1)运行所有 pytest.main()
(2)指定模块 pytest.main([‘-vs’,’test_date.py’])
(3)指定目录 pytest.main([‘-vs’,’./interface_tc’])
(4)通过nodeid指定用例运行:nodeid由模块名、分隔符、类名、方法名、函数名组成
pytest.main([‘-vs’,’./interface_tc/test_interface.py::test_04_func’])
pytest.main([‘-vs’,’./interface_tc/test_interface.py::RestInterface::test_03_func’])
参数-v,-s说明
if name == ‘main‘:
pytest.main([‘-v’])
输出结果中可以看到模块、类、方法的信息
if name == ‘main‘:
pytest.main([‘-s’])
输出结果中打印了函数中print的信息
if name == ‘main‘:
pytest.main([‘-vs’])
【例】执行全部用例
`
1) 目录结构
[root@k8s-node2 pytest]# tree pytestdemo/
pytestdemo/
└── testcase
├── all.py
├── init.py
├── test_date.py
└── test_plan.py
1 directory, 4 files
[root@k8s-node2 pytest]#
3) test_date.py内容
–– coding:utf-8 ––
import pytest
class TestDate:
def test01date(self):
print("Today is Sep 2st.")
def test02day(self):
print("Today is Friday.")
2) all.py内容
–– coding:utf-8 ––
import pytest
if name == ‘main‘:
pytest.main([‘-vs’,’./interface_tc’])
Original: https://blog.csdn.net/wy_hhxx/article/details/126576341
Author: wy_hhxx
Title: [pytest] 运行方式、常用参数、前后置条件
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/773106/
转载文章受原作者版权保护。转载请注明原作者出处!