1. 前言

pytest 配置文件可以改变 pytest 的运行方式,它是一个固定的文件 pytest.ini 文件,读取配置信息,按指定的方式去运行

2. 非test文件

pytest 里面有些文件是非test文件

  • pytest.ini:pytest 的主配置文件,可以改变 pytest 的默认行为
  • conftest.py:测试用例的一些 fixture 配置
  • init.py:识别该文件夹为 python 的 package 包(在 Python3 之后不是必需)

3. 查看pytest.ini的配置选项

cmd执行

  1. pytest --help

找到这部分内容

  1. [pytest] ini-options in the first pytest.ini|tox.ini|setup.cfg file found:
  2. markers (linelist): markers for test functions
  3. empty_parameter_set_mark (string):
  4. default marker for empty parametersets
  5. norecursedirs (args): directory patterns to avoid for recursion
  6. testpaths (args): directories to search for tests when no files or directories are given in the command line.
  7. usefixtures (args): list of default fixtures to be used with this project
  8. python_files (args): glob-style file patterns for Python test module discovery
  9. python_classes (args):
  10. prefixes or glob names for Python test class discovery
  11. python_functions (args):
  12. prefixes or glob names for Python test function and method discovery
  13. disable_test_id_escaping_and_forfeit_all_rights_to_community_support (bool):
  14. disable string escape non-ascii characters, might cause unwanted side effects(use at your own
  15. risk)
  16. console_output_style (string):
  17. console output: "classic", or with additional progress information ("progress" (percentage) |
  18. "count").
  19. xfail_strict (bool): default for the strict parameter of xfail markers when not given explicitly (default: False)
  20. enable_assertion_pass_hook (bool):
  21. Enables the pytest_assertion_pass hook.Make sure to delete any previously generated pyc cache
  22. files.
  23. junit_suite_name (string):
  24. Test suite name for JUnit report
  25. junit_logging (string):
  26. Write captured log messages to JUnit report: one of no|log|system-out|system-err|out-err|all
  27. junit_log_passing_tests (bool):
  28. Capture log information for passing tests to JUnit report:
  29. junit_duration_report (string):
  30. Duration time to report: one of total|call
  31. junit_family (string):
  32. Emit XML for schema: one of legacy|xunit1|xunit2
  33. doctest_optionflags (args):
  34. option flags for doctests
  35. doctest_encoding (string):
  36. encoding used for doctest files
  37. cache_dir (string): cache directory path.
  38. filterwarnings (linelist):
  39. Each line specifies a pattern for warnings.filterwarnings. Processed after -W/--pythonwarnings.
  40. log_print (bool): default value for --no-print-logs
  41. log_level (string): default value for --log-level
  42. log_format (string): default value for --log-format
  43. log_date_format (string):
  44. default value for --log-date-format
  45. log_cli (bool): enable log display during test run (also known as "live logging").
  46. log_cli_level (string):
  47. default value for --log-cli-level
  48. log_cli_format (string):
  49. default value for --log-cli-format
  50. log_cli_date_format (string):
  51. default value for --log-cli-date-format
  52. log_file (string): default value for --log-file
  53. log_file_level (string):
  54. default value for --log-file-level
  55. log_file_format (string):
  56. default value for --log-file-format
  57. log_file_date_format (string):
  58. default value for --log-file-date-format
  59. log_auto_indent (string):
  60. default value for --log-auto-indent
  61. faulthandler_timeout (string):
  62. Dump the traceback of all threads if a test takes more than TIMEOUT seconds to finish. Not
  63. available on Windows.
  64. addopts (args): extra command line options
  65. minversion (string): minimally required pytest version
  66. rsyncdirs (pathlist): list of (relative) paths to be rsynced for remote distributed testing.
  67. rsyncignore (pathlist):
  68. list of (relative) glob-style paths to be ignored for rsyncing.
  69. looponfailroots (pathlist):
  70. directories to check for changes

4. pytest.ini应该放哪里?

就放在项目根目录下 ,不要乱放,不要乱起其他名字

接下来讲下常用的配置项

5. marks

作用:测试用例中添加了 @pytest.mark.webtest 装饰器,如果不添加 marks 选项的话,就会报 warnings
格式:list 列表类型
写法:

  1. [pytest]
  2. markers =
  3. weibo: this is weibo page
  4. toutiao: toutiao
  5. xinlang: xinlang

6. xfail_strict

作用:设置 xfail_strict = True 可以让那些标记为 @pytest.mark.xfail 但实际通过显示 XPASS 的测试用例被报告为失败
格式:True 、False(默认),1、0
写法:

  1. [pytest]
  2. # mark标记说明
  3. markers =
  4. weibo: this is weibo page
  5. toutiao: toutiao
  6. xinlang: xinlang
  7. xfail_strict = True

6.1 具体代码栗子

未设置 xfail_strict = True 时,测试结果显示XPASS

  1. @pytest.mark.xfail()
  2. def test_case1():
  3. a = "a"
  4. b = "b"
  5. assert a != b

6.2 执行结果

  1. collecting ... collected 1 item
  2. 02断言异常.py::test_case1 XPASS [100%]
  3. ============================= 1 xpassed in 0.02s ==============================

6.3 已设置 xfail_strict = True 时,测试结果显示 failed

  1. collecting ... collected 1 item
  2. 02断言异常.py::test_case1 FAILED [100%]
  3. 02断言异常.py:54 (test_case1)
  4. [XPASS(strict)]
  5. ================================== FAILURES ===================================
  6. _________________________________ test_case1 __________________________________
  7. [XPASS(strict)]
  8. =========================== short test summary info ===========================
  9. FAILED 02断言异常.py::test_case1
  10. ============================== 1 failed in 0.02s ==============================

7. addopts

作用:addopts 参数可以更改默认命令行选项,这个当我们在 cmd 输入一堆指令去执行用例的时候,就可以用该参数代替了,省去重复性的敲命令工作
比如:想测试完生成报告,失败重跑两次,一共运行两次,通过分布式去测试,如果在cmd中写的话,命令会很长
pytest -v --rerun=2 --count=2 --html=report.html --self-contained-html -n=auto

每次都这样敲不太现实,addopts 就可以完美解决这个问题

  1. [pytest]
  2. # mark
  3. markers =
  4. weibo: this is weibo page
  5. toutiao: toutiao
  6. xinlang: xinlang
  7. xfail_strict = True
  8. # 命令行参数
  9. addopts = -v --reruns=1 --count=2 --html=reports.html --self-contained-html -n=auto

加了 addopts 之后,我们在 cmd 中只需要敲 pytest 就可以生效了!!

8. log_cli

作用:控制台实时输出日志
格式:log_cli=True 或 False(默认),或者 log_cli=1 或 0

8.1 log_cli=0的运行结果

image.png

8.2 log_cli=1的运行结果

image.png

8.3 结论

很明显,加了 log_cli=1 之后,可以清晰看到哪个 package 下的哪个 module 下的哪个测试用例是否 passed 还是failed;
所以平时测试代码是否有问题的情况下推荐加!!!但如果拿去批量跑测试用例的话不建议加,谁知道会不会影响运行性能呢?

9. norecursedirs

作用:pytest 收集测试用例时,默认会递归遍历当前目录以及所有子目录,包括某些你明知道没必要遍历的目录,遇到这种情况,可以使用 norecursedirs 参数简化 pytest 的搜索工作【还是挺有用的!!!】
默认设置: norecursedirs = . build dist CVS _darcs {arch} .egg
正确写法:多个路径用空格隔开

  1. [pytest]
  2. norecursedirs = .* build dist CVS _darcs {arch} *.egg venv src resources log report util

10. 更改测试用例收集规则

pytest 默认的测试用例收集规则

  • 文件名以 test_.py 文件和 _test.py
  • 以 test_ 开头的函数
  • 以 Test 开头的类,不能包含 init 方法
  • 以 test_ 开头的类里面的方法

我们是可以修改或者添加这个用例收集规则的;当然啦,是建议在原有的规则上添加的,如下配置

  1. [pytest]
  2. python_files = test_* *_test test*
  3. python_classes = Test* test*
  4. python_functions = test_* test*