前言
如果熟悉其他框架的同学都知道,每个框架都有它自己的配置文件,只需要做简单的配置就可以实现一些常用的功能,减少我们编程的时间。
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
示例代码:
""""
# @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 自定义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
测试代码示例:
""""
# @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 ,查看结果:  注意点:目前配置的日志无法保留所有执行日志,每次写入都是覆盖写入,等同于 open 的 w 模式
- 通过修改源码的写入方式可以保存所有执行日志,改成
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 文件里面不能使用任何中文符号,包括汉字、空格、引号、冒号等;
- 修改了用例搜索规则后,在编写用例时也需要同步修改,最好默认即可,以防出错
- 命令行日志在正式运行时,需要记得关闭,只输出到文件即可,记得修改日志文件写入模式,具体看上述方法
以上为内容纯属个人理解,如有不足,欢迎各位大神指正,转载请注明出处!
如果觉得文章不错,欢迎关注微信公众号,微信公众号每天推送相关测试技术文章 
|