pytest.ini配置小记

pytest.ini:pytest的主配置文件,可以改变pytest的默认行为。
conftest.py:本地的插件库,其中的hook函数和fixture将作用于该文件所在的目录以及所有子目录。
__init__.py:每个测试子目录都包含该文件时,再多个测试目录中可以出现同名测试文件。

1、查看ini文件选项

可以在terminal中使用pytest-help命令查看pytest.ini的所有设置选项。

(venv) C:Users***DesktopRecentlytest_result0>pytest --help
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

                        ......
                        ......
                        ......
[pytest] ini-options in the first pytest.ini|tox.ini|setup.cfg file found:

  markers (linelist):   markers for test functions
  empty_parameter_set_mark (string):
                        default marker for empty parametersets
  norecursedirs (args): directory patterns to avoid for recursion
  testpaths (args):     directories to search for tests when no files or directories are given in the command
                        line.
  python_files (args):  glob-style file patterns for Python test module discovery
  python_classes (args):
                        prefixes or glob names for Python
  cache_dir (string):   cache directory path.
environment variables:
  PYTEST_ADDOPTS           extra command line options
  PYTEST_PLUGINS           comma-separated plugins to load during startup
  PYTEST_DISABLE_PLUGIN_AUTOLOAD set to disable plugin auto-loading
  PYTEST_DEBUG             set to enable debug tracing of pytest's internals
  
(venv) C:Users****DesktopRecentlytest_result0>

2、插件可以添加ini文件选项

更改默认命令行选项:需要用到很多选项,又不想每次运行时重复输入这么多命令行参数,就可以用pytest.ini文件里的addopts设置

[pytest]
addopts = --rsxX -l --tb=short -strict --html=report/html/reports.html --self-contained-html

其中–rsxX表示pytest报告所有测试用例被跳过、预计失败、预计失败但实际通过的实例。-l 表示pytest报告所有失败测试的堆栈中的局部变量。 --tb=short 表示简化堆栈回溯信息,只保留文件和行数。 --strict选项表示禁止使用未在配置文件中注册的标记。
除此之外,还有***-k***:允许使用表达式指定希望运行的测试用例,***-m***:标记测试并分组,***-x***:遇到失败立即停止整个会话,***–maxfail=num***:明确指定可以失败几次,***-s***:关闭输出,***-lf***:定位最后一个失败的测试重新运行,***-ff***:运行完剩余的测试用例并定位到最后一个失败的用例重新运行,***-v***:输出信息更详细,***-q***:简化输出信息,***-l***:显示局部变量及其值,***–tb=style***:(short输出一行,line使用一行显示所有错误信息,no屏蔽全部回溯信息),–duration=N:加快测试节奏

注册标记,防范拼写错误

[pytest]
markers = 
	smoke:Run the smoke test functions for task project
	get:Run the test functions that test tasks.get()

默认情况下,如果不注册标记,@pytest.mark.smoke误拼成@pytest.mark.somke也不会报错,pytest会以为这是你创建的另一个标记。为了避免拼写错误,在pytest.ini文件里注册标记。

More and more

ini文件还可以配置更多,例如:

指定pytest的最低版本号:
[pytest]
minversion = 3.0
指定pytest忽略某些目录
[pytest]
norecursedirs = .* venv src *.egg dist build
指定测试目录
[pytest]
testpaths = tests
更改测试搜索的规则
[pytest]
#更改测试类的命名方式
python_classes = *Test Test* *Suite
禁用XPASS
避免文件名冲突

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码

)">
< <上一篇
下一篇>>