Pytest学习笔记

1.pytest命名规范

2.pytest运行方式

3.pytest常用的执行参数

4.pytest框架结构

5.Fixture的作用

6.Fixture 用法

7.conftest.py 用法

8.pytest.ini 的用法

9.pytest常用插件

10.测试用例基本原则

11.pytest 插件

12.allure 用法

  • py文件要以test_开头,或者_test结尾
  • 类要以Test开头,方法要以test_开头
  • pychram界面运行
  • 右键文件/目录运行
  • 使用命令行的方式运行
  • pytest 模块名(执行模块中test_开头的方法)
  • pytest –collect-only (只收集用例)
  • pytest -k “add “(匹配所有名称中包含add的用例)
  • pytest -m 自定义的标记名(@pytest.mark.自定义标记名)
  • pytest – – junitxml=./result.xml(生成执行结果文件)
  • pytest –setup-show (回溯fixture的执行过程)
  • 模块级(setup_module/teardown_module)模块始末,全局的(优先级最高)
  • 函数级(setup_function/teardown_function)只对函数用例生效(不在类中)
  • 类级(setup_class/teardown_class)在类中前后运行一次(在类中)
  • 方法级(setup_method/teardown_method)开始于方法始末(在类中)
  • 类里面的(setup/teardown)运行在调用方法的前后(同方法级)
  • Fixture是在测试函数运行前后,由pytest执行的外壳函数,代码可以定制,满足多变的测试需求,功能包括:
  • 定义传入测试中的数据集
  • 配置测试前系统的初始状态
  • 为批量测试提供数据源等
  • Fixture 是pytest 用于将测试前后进行预备,清理工作的代码分离出核心测试逻辑的一种机制
  • Fixture 是为了测试⽤例的执⾏,初始化⼀些数据和⽅法
  • 1、类似 setUp, tearDown 功能,但⽐ setUp, tearDown 更灵活
  • 2、直接通过函数名字调⽤或使用装饰器@pytest.mark.usefixtures(‘test1’)
  • 3、允许使用多个Fixture
  • 4、使用 autouse 自动应用,如果要返回值,需要传fixture函数名
  • 5、作用域(session>module>class>function)
  • 6、也可以提供测试数据,实现参数化的功能
  • 7、Fixture也可以调用Fixture
  • -setup-show 回溯 fixture 的执行过程
  • 数据共享的文件,名字是固定的,不能修改
  • 可以存放fixture , hook 函数
  • 就近生效(如果不在同一个文件夹下,离测试文件最近的conftest.py 生效)
  • 当前目录一定要有__init__.py 文件,也就是要创建一个包

参考 pytest --help

Demo:

[pytest]
markers = login
          search

python_files = check_* test_*
python_functions = check_* test_*
addopts = -vs --alluredir=./result
  • pytest-ordering 控制用例的执行顺序
  • pytest-dependency 控制用例的依赖关系
  • pytest-xdist 分布式并发执行执行测试用例
  • pytest-rerunfailures 失败重跑
  • pytest-assume 多重校验
  • pytest-random-order 用例随机执行
  • pytest-html 测试报告
  • 不要让 case 有顺序
  • 不要让测试用例有依赖
  • 如果你无法做到,可以临时性的用插件解决
  • 内置plugin(hook函数):
  • 从代码内部的_pytest目录加载
  • 外部插件(第三方插件):
  • 通过 setuptools entry points 机制发现的第三方插件
  • pip install 安装的插件
    https://docs.pytest.org/en/latest/plugins.html)
  • conftest.py存放的本地插件:
  • 自动模块发现机制
  • pytest –trace-config 查看当前pytest中所有的plugin(带有hook方法的文件)

  • 为测试用例分类:

@allure.feature("name")
@allure.story("name")
  • 为测试 用例加标题
@allure.title()
  • 生成测试报告
Allure2 解析过程:
1. 安装 allure2
2. Allure help  帮助文档
3. 生成 allure 测试结果 :pytest —alluredir=./report/
4. 展示报告:allure serve ./report
5. 生成最终版本的报告:   allure generate ./report
在本地搭建一个网站服务(例如:Django)
python manage.py runserver  (http://127.0.0.1:8000/)

Original: https://blog.csdn.net/sunny2429/article/details/113442526
Author: 飞鸟暮雨
Title: Pytest学习笔记

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/776169/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球