IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 开发测试 -> pytest测试框架系列 - 学会使用配置文件pytest.ini,带来的效果居然这么好? -> 正文阅读

[开发测试]pytest测试框架系列 - 学会使用配置文件pytest.ini,带来的效果居然这么好?

前言

如果熟悉其他框架的同学都知道,每个框架都有它自己的配置文件,只需要做简单的配置就可以实现一些常用的功能,减少我们编程的时间。

pytest 配置文件可以改变 pytest 的运行方式,它是一个固定的文件 pytest.ini文件,读取配置信息,按指定的方式去运行框架的功能,我们能够配置哪些功能下面详细说明。

pytest.ini 详解

用法:在项目根目录创建一个 pytest.ini 的文件,名字固定不能改为其他的。
例如:
项目根目录
首先我们怎么知道配置文件,可以配置哪些功能呢?这就需要我们看帮助文档,一般都是--help会出来可以操作的功能说明,下面我们先在命令行窗口输入: pytest --help 或者 pytest -h,查看结果:

usage: pytest [options] [file_or_dir] [file_or_dir] [...]

positional arguments:
  file_or_dir

general:
  -k EXPRESSION         only run tests which match the given substring expression. An expression is a python evaluatable expression where all names are substring-matched

                        against test names and their parent classes. Example: -k 'test_method or test_other' matches all test functions and classes whose name contains
                        'test_method' or 'test_other', while -k 'not test_method' matches those that don't contain 'test_method' in their names. -k 'not test_method and
                        not test_other' will eliminate the matches. Additionally keywords are matched to classes and functions containing extra names in their
                        'extra_keyword_matches' set, as well as functions which have names assigned directly to them. The matching is case-insensitive.
  -m MARKEXPR           only run tests matching given mark expression.
                        For example: -m 'mark1 and not mark2'.
  --markers             show markers (builtin, plugin and per-project ones).
  -x, --exitfirst       exit instantly on first error or failed test.
  --fixtures, --funcargs
                        show available fixtures, sorted by plugin appearance (fixtures with leading '_' are only shown with '-v')
  --fixtures-per-test   show fixtures per test
  --pdb                 start the interactive Python debugger on errors or KeyboardInterrupt.
  --pdbcls=modulename:classname
                        start a custom interactive Python debugger on errors. For example: --pdbcls=IPython.terminal.debugger:TerminalPdb
  --trace               Immediately break when running each test.
  --capture=method      per-test capturing method: one of fd|sys|no|tee-sys.
  -s                    shortcut for --capture=no.
  --runxfail            report the results of xfail tests as if they were not marked
  --lf, --last-failed   rerun only the tests that failed at the last run (or all if none failed)
  --ff, --failed-first  run all tests, but run the last failures first.
                        This may re-order tests and thus lead to repeated fixture setup/teardown.
  --nf, --new-first     run tests from new files first, then the rest of the tests sorted by file mtime
  --cache-show=[CACHESHOW]
  ..........

我们看见上面这么多说明及参数,我们只需要熟悉常用的几种类型即可。

我们常用的参数使用分类:

  • 更改命令行选项
  • 自定义标记注册
  • 用例搜索规则
  • 日志配置参数
  • 常用插件参数

更改命令行选项

说明:通常我们在执行的时候添加上常用命令行参数,如pytest -v -s -x --maxfail=1,我们把这些命令行参数放到pytest.ini 中:

[pytest]
addopts = -v -s --maxfail=1

示例代码:

# !/usr/bin/python3
# _*_coding:utf-8 _*_
""""
# @Time  :2021/7/12 22:27
# @Author  : king
# @File    :test_addopts.py
# @Software  :PyCharm
# @blog     :https://blog.csdn.net/u010454117
# @WeChat Official Account: 【测试之路笔记】
"""
import pytest
import logging

def test_01():
    logging.info("我是 test_01 测试用例")
    assert True

def test_02():
    logging.info("我是 test_02 测试用例")
    assert False

def test_03():
    logging.info("我是 test_03 测试用例")
    assert True

def test_04():
    """我是测试标题"""
    logging.info("我是 test_04 测试用例")
    assert False

if __name__ == '__main__':
    pytest.main()

我们执行只需要输入 pytest test_addopts.py 即可,可以看出来命令行参数成功生效。
执行pytest test_addopts.py 结果

自定义标记注册

说明:这个在自定义标记文章讲解,可以参考 Pytest 自定义mark标记筛选用例实战,主要解决自定义标记的warnings提示信息。

示例:

[pytest]
markers=
    web: web 测试用例
    app: app测试用例

用例搜索规则

  • 指定测试用例目录搜索规则 testpaths = testcase/
  • 排除掉一些目录规则 norecursedirs = evn reports/
  • 指定测试类搜索规则 python_classes = Test* *Test
  • 指定测试文件搜索规则 python_files = test_*.py *_test.py
  • 指定测试函数搜索规则 python_functions = test* *test

pytest.ini文件里面:

testpaths = testcase/
norecursedirs = evn reports/
python_classes = King* *King
python_files = king_*.py *_king.py
python_functions = king* *king

测试代码示例:

# !/usr/bin/python3
# _*_coding:utf-8 _*_
""""
# @Time  :2021/7/12 22:27
# @Author  : king
# @File    :king_case.py
# @Software  :PyCharm
# @blog     :https://blog.csdn.net/u010454117
# @WeChat Official Account: 【测试之路笔记】
"""
import pytest
import logging

def king_01():
    logging.info("我是 king_01 测试用例")
    assert True

def king_02():
    logging.info("我是 king_02 测试用例")
    assert False

def king_03():
    logging.info("我是 king_03 测试用例")
    assert True

def king_04():
    """我是测试标题"""
    logging.info("我是 king_04 测试用例")
    assert False

class KingDemo:
    def king_05(self):
        """我是测试标题"""
        logging.info("我是 king_05 测试用例")
        assert False

if __name__ == '__main__':
    pytest.main()

命令窗口输入 pytest ,查看结果:
修改用例搜索规则执行结果

日志配置参数

说明:正常来说自动化测试项目都需要日志,在编写代码时需要调式日志,执行时需要执行日志输出到日志文件。

pytest.ini 文件日志配置

"""
 命令行窗口日志输出配置
 log_cli 可以输入0, False 代码不输出日志, 1、True 代表开启日志输出
 log_cli_level 代表日志输出级别
 log_cli_date_format 日期格式
 log_cli_format 日志模板格式
"""
log_cli=1
log_cli_level=info
log_cli_date_format=%Y-%m-%d-%H-%M-%S
log_cli_format=%(asctime)s-%(filename)s-%(module)s-%(funcName)s-%(lineno)d-%(levelname)s-%(message)s

"""
 日志输出到文件配置
 log_file 日志文件
 log_file_level 代表日志输出级别
 log_file_date_format 日期格式
 log_file_format 日志模板格式
"""
log_file=outputs/logs/test.log
log_file_level=INFO
log_file_date_format=%Y-%m-%d %H:%M:%S
log_file_format=%(asctime)s %(filename)s %(module)s %(funcName)s %(lineno)d %(levelname)s: %(message)s

pytest.ini 日志配置
命令窗口输入 pytest ,查看结果:
命令窗口日志输出和输出到日志文件
注意点:目前配置的日志无法保留所有执行日志,每次写入都是覆盖写入,等同于 openw 模式

  • 通过修改源码的写入方式可以保存所有执行日志,改成 a 模式
  • 修改文件位置 ../Lib/site-packages/_pytest/logging.py
  • 552行self.log_file_handler = _FileHandler(log_file, mode="w", encoding="UTF-8") 修改为:self.log_file_handler = _FileHandler(log_file, mode="a", encoding="UTF-8")

常用插件参数

说明:像我们经常需要将失败重试、生成HTML报告等需要每次都生成,为了方便,就会将这些命令加到配置文件

pytest.ini示例:

addopts = --reruns=1 --reruns-delay=5 --html=reports.html --self-contained-html

完成的一个配置

pytest.ini 文件:

[pytest]
addopts = -v -s --reruns=1 --reruns-delay=5 --html=reports.html --self-contained-html


markers=
    web: web 测试用例
    app: app 测试用例

testpaths = testcase/
norecursedirs = evn reports/
python_classes = King* *King
python_files = king_*.py *_king.py
python_functions = king* *king


log_cli=1
log_cli_level=info
log_cli_date_format=%Y-%m-%d-%H-%M-%S
log_cli_format=%(asctime)s-%(filename)s-%(module)s-%(funcName)s-%(lineno)d-%(levelname)s-%(message)s


log_file=test.log
log_file_level=INFO
log_file_date_format=%Y-%m-%d %H:%M:%S
log_file_format=%(asctime)s %(filename)s %(module)s %(funcName)s %(lineno)d %(levelname)s: %(message)s

总结

  • 本章节主要讲解了全局配置文件 pytest.ini 的使用及注意点
  • pytest.ini 文件里面不能使用任何中文符号,包括汉字、空格、引号、冒号等;
  • 修改了用例搜索规则后,在编写用例时也需要同步修改,最好默认即可,以防出错
  • 命令行日志在正式运行时,需要记得关闭,只输出到文件即可,记得修改日志文件写入模式,具体看上述方法

以上为内容纯属个人理解,如有不足,欢迎各位大神指正,转载请注明出处!

如果觉得文章不错,欢迎关注微信公众号,微信公众号每天推送相关测试技术文章
个人微信号

  开发测试 最新文章
pytest系列——allure之生成测试报告(Wind
某大厂软件测试岗一面笔试题+二面问答题面试
iperf 学习笔记
关于Python中使用selenium八大定位方法
【软件测试】为什么提升不了?8年测试总结再
软件测试复习
PHP笔记-Smarty模板引擎的使用
C++Test使用入门
【Java】单元测试
Net core 3.x 获取客户端地址
上一篇文章      下一篇文章      查看所有文章
加:2021-07-14 23:15:03  更:2021-07-14 23:15:24 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/7 14:21:20-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码