Python 测开28期 - 小锅巴 - Pytest测试框架(一)

Pytest单元测试框架

了解Pytest:

  • Pytest是python第三方单元测试框架,比python内置的单元测试框架unitest功能更完善。并且pytest兼容了用unittest编写的测试用例的执行。
    • pytest内置了参数化的装饰器
    • pytest可支持执行部分用例
    • pytest有强大的第三方插件库
    • pytest有钩子函数,可以自定义扩展功能
    • pytest有共享的胶水文件:conftest.py
    • pytest具有更多作用域的前置/后置
    • pytest具备自己独有的特性:可以自定义fixturn函数
  • pytest收集/执行用例的默认规则:
    • 测试用例文件、类、函数必须是:test_开头、_test结尾 — 这一项可通过pytest.ini配置文件进行更改
    • 测试类不能有__init__()方法
    • 测试包必须有__init__()方法
    • 执行用例的几种方式:
      • 执行某个文件夹下的用例:pytest 文件夹名
      • 执行一个py文件下的用例:pytest xxx.py
      • 执行用例名字包含某关键字的用例:pytest -k “关键字” --关键字可以是文件名字/测试类/测试用例任意一个中包含的
      • 按用例节点去执行:pytest 文件名.py::测试类名::测试用例名
      • 执行被标记的测试用例:pytest -m 关键字 (被:@ pytest.mark.关键字,被标记的用例,比如只执行冒烟用例)
  • pytest命令行参数:通过pytest -h 或者pytest -help查看。这些参数在执行pytest命令运行用例的时候带上,或写入到ini的配置文件中。
    • 通用参数( general):
      • -k:-k “关键字”–执行包含关键字的函数/类/文件用例 -k “not 关键字 and 类名”–不执行包含关键字和类的用例,执行剩余的用例
      • -m:执行被@ pytest.mark.关键字标记的用例
      • --markers:查看当前环境中所有的markers:定义的@pytest,mark.xxx
      • -x:碰到第一个error或failed的用例,就退出
      • --maxfail=num:可以设置error/failures用例数达到几个后,退出测试
      • -c file:从my.ini文件中加载配置
      • --continue-on-collection-errors:收集失败的用例,但是仍然强制执行测试
      • --rootdir=ROOTDIR:测试的根目录,相对路径
      • --fixtures:显示fixtures函数
      • --fixtures-per-test:显示每个test用到的fixture
      • --pdb:在error或KeyboardInterrupt时,启用默认的degugger
      • --pdbcls=modulename:classname:启用自定义 Python debugger,由 IPython.terminal.debugger module 下的 TerminalPdb class 定义
        • pytest --pdbcls=IPython.terminal.debugger:TerminalPdb
      • --trace:执行每个用例被break时,进入debugger
      • --capture=method
        • 文件描述符:pytest --capture=fd
        • stdout/stderr内存:pytest --capture=sys
        • 显示print:pytest --capture=no
        • tee-sys:pytest --capture=tee-sys
      • -s:等价于~~ --capture=no
      • --runxfail:强制运行被标记xfail的用例
      • --lf/--last-failed:重跑上次失败的用例,没有失败的则会重跑全部的用例
      • --ff/--failed-first:优先跑上一次失败的用例,之后再跑正常的用例
      • --nf/--new-first:优先跑新添加的用例,之后按文件的mtime顺序执行剩下的用例
      • --cache-show=[cacheshow]:显示缓存,默认是*(带参数的:–cache-show=cache/nodeids)
      • --cache-clear:运行开始时清空缓存
      • --sw/--stepwise:逐步运行,遇到失败的退出,下次运行时从失败的用例开始
      • --stepwise-skip:跳过第一个失败的用例,如果再有失败的退出测试
      • --skip-network:跳过需要连接网络才能运行的用例
      • --skip-slow:跳过执行比较慢的用例
      • --force-serial:强制串行执行测试用例
      • --allure-severities=SEVERITIES_SET:指定 allure severities 运行(pytest --allure-severities=blocker, critical, normal, minor, trivial)
      • --allure-epics=EPICS_SET:指定 allure epics 运行
      • --allure-features=FEATURES_SET:指定 allure features 运行
      • --allure-stories=STORIES_SET:指定 allure stories 运行
    • 报告相关( reporting):
      • --durations=N:显示n个最慢的setup/用例的耗时,N=0时是显示所有的耗时
      • -v:输出详细信息
      • -q:输出简要信息
      • --verbosity=等级数字:设置信息显示等级为X
      • -r :后面跟 f 或者 e、s、x、X、p、P、a,显示:失败、出错、跳过、预期失败、预期通过、成功、显示 Passed with output、显示 all except passed 的信息
      • -l/--showlocals:在tracebacks中显示局部变量,默认不显示
      • --tb=style:打印模式
        • style的值:auto、long、short、line、native、no
      • --show-capture=all:失败的用例如何显示,默认显示全部:all。其他参数:no、stdout、stderr、log、all
      • --full-trace:不截断traceback堆栈信息,默认是会截断
      • --color=xxx:yes–显示颜色、no–不显示颜色、auto–自动
    • 收集用例相关
      • --collect-only/--co:只收集用例,不执行,可以统计写了多少条用例
      • --pyargs:把所有的参数解释为python的包
      • --ignore=path:忽略不收集用例的路径,path可以同时写多个,用逗号隔开
      • --confcutdir=dir:只加载相对于 dir 路径的conftest.py文件
      • --noconftest:不加载conftest.py文件
      • --keep-duplicates:收集重复的test文件,默认只会收集 1item,加参数后会收集 2items(pytest test.py test.py --keep-duplicates)
      • --collect-in-virtualenv:收集本地虚拟环境目录的用例(tests)
    • 测试会话调试和配置:
      • –basetemp=dir:测试base的临时目录(如果临时目录存在,执行前先删除)
      • -V:pytest的版本
      • -h/–help:pytest的帮助文档
      • -p name:加载plugin module或entry point (pytest -p no:doctest 不加载doctest)
      • –trace-config:查看本地安装好的第三方插件
      • –debug:保存debug信息到pytestdebug.log文件中
      • -o OVERRIDE_INI/ --override-ini=OVERRIDE_INI:覆盖ini文件配置
      • –setup-only:只执行setup,不执行用例
      • –setup-show:执行用例的时候显示setup
      • –setup-plan:显示fixture函数和用例会执行什么,但是不执行,也可以用来统计自动化用例
    • 日志相关:
      • –log-level=LEVEL:默认没有设置,依赖log handler(WARNING DEBUG INFO ERROR)
      • –log-format=LOG_FORMAT:日志格式
      • –log-date-format=LOG_DATE_FORMAT:日期格式
      • –log-cli-level=LOG_CLI_LEVEL:cli日志级别
      • –log-cli-format=LOG_CLI_FORMAT:cli日志格式
      • –log-cli-date-format=LOG_CLI_DATE_FORMAT:cli日期格式
      • –log-file=LOG_FILE:日志文件路径
      • –log-file-level=LOG_FILE_LEVEL:日志文件级别
      • –log-file-format=LOG_FILE_FORMAT:日志文件格式
      • –log-file-date-format=LOG_FILE_DATE_FORMAT:日志文件日期格式–(pytest --log-file-date-format=“%Y-%m-%d %H:%M:%S”)
      • –log-auto-indent=LOG_AUTO_INDENT:自动换行 参数:true|flase on|off
    • Allure报告相关:
      • alluredir=DIR:allure数据生成的目录,注意不是html,是allure生成的原始的json文件。(需要allure generate data_dir -o html_dir才能生成 html)
      • –clean-alluredir:如果存在alluredir,先清楚
      • –allure-no-capture:报告不捕获pytest的logging/stout/stderr的信息
    • 自定义选项相关:
    • pytets.ini文件配置参数相关
      • markers:格式如下:
      # pytest.ini
      [pytest]
      markers =
        webtest:  Run the webtest case
        hello: Run the hello case
      
      • addopts (args):执行时带的默认参数(比如:-v --reruns=1 --count=2,allure的参数等)
      • norecursedirs (args):忽略一些目录文件,args的值为路径
      • testpaths (args):测试测试用例指定目录,args的值为路径
      • usefixtures (args):默认使用的fixtures。
      • 还有日志相关的配置同上面的命令行参数都可以在ini文件中配置
      • minversion (string):设置pytest的版本号,如果实际的版本号小于设置的会报错
    • 环境变量相关:
  • pytest常用的插件:
    • pytest-rerunfailures:失败用例重跑
      • 用法:–reruns 5 --reruns-delay 1 – 重跑5次,每次间隔1秒;指定特定用例:@pytest.mark.flaky(reruns=5,reruns-delay=1)
    • pytest-assume:多重校验
      • 用法:pytest.assume(1==3)
    • pytest-ordering:设置用例执行顺序
      • 用法:@pytest.mark.run(order=2)
    • pytest-dependency:用例依赖
      • 用法:@pytest.mark.dependency(depends=[“test_name”])引用依赖,test_name可以是多个。
    • pytest-xdist:分布式执行
      • 用法:pytest -n 2–2个进程执行 pytest -n auto --根据电脑的核数自动分配
    • pytest-html:生成html报告
      • 用法: pytest --html=report.html
    • pytest-repeat:重复运行(可以重复(可指定次数)执行单个或多个测试)
      • 用法:pytest --count=重复次数
    • pytest-timeout:超时机制,如果超过了设定的时间,用例标记失败
      • 用法:pytest --timeout=秒数
    • pytest-tmreport:测试报告
      • 用法:pytest --pytest-tmreport-name=报告名称.html