pytest学习和使用18-pytest.ini配置文件如何使用?

1 配置文件的作用
  • 改变pytest的运行方式;
  • pytest.ini是一个固定的文件;
  • pytest.ini用来读取配置信息。
2 文件格式
  1. # 文件名为:pytest.ini

  2. [pytest]

  3. addopts =

  4. xfail_strict =

3 查看pytest.ini的选项
  • 使用命令:
pytest --help
  • 如下:
  1. C:\Users\Administrator>pytest --help

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

  3. positional arguments:

  4. file_or_dir

  5. general:

  6. -k EXPRESSION only run tests which match the given substring expression. An expression is a python evaluatable

  7. expression where all names are substring-matched against test names and their parent classes.

  8. Example: -k 'test_method or test_other' matches all test functions and classes whose name

  9. contains 'test_method'or'test_other', while -k 'not test_method' matches those that don't

  10. contain 'test_method' in their names. -k 'not test_method andnot test_other' will eliminate the

  11. matches. Additionally keywords are matched to classes and functions containing extra names in

  12. their 'extra_keyword_matches' set, as well as functions which have names assigned directly to

  13. them. The matching is case-insensitive.

  14. -m MARKEXPR only run tests matching given mark expression.

  15. For example: -m 'mark1 andnot mark2'.

  16. --markers show markers (builtin, plugin and per-project ones).

  17. -x, --exitfirst exit instantly on first error or failed test.

  18. --fixtures, --funcargs

  19. show available fixtures, sorted by plugin appearance (fixtures with leading '_' are only shown

  20. with '-v')

  21. --fixtures-per-test show fixtures per test

  22. --pdb start the interactive Python debugger on errors or KeyboardInterrupt.

  23. --pdbcls=modulename:classname

  24. start a custom interactive Python debugger on errors. For example:

  25. --pdbcls=IPython.terminal.debugger:TerminalPdb

  26. --trace Immediately break when running each test.

  27. --capture=method per-test capturing method: one of fd|sys|no|tee-sys.

  28. -s shortcut for --capture=no.

  29. --runxfail report the results of xfail tests as if they were not marked

  30. --lf, --last-failed rerun only the tests that failed at the last run (or all if none failed)

  31. --ff, --failed-first run all tests, but run the last failures first.

  32. This may re-order tests and thus lead to repeated fixture setup/teardown.

  33. --nf, --new-first run tests from new files first, then the rest of the tests sorted by file mtime

  34. --cache-show=[CACHESHOW]

  35. show cache contents, don't perform collection or tests. Optional argument: glob (default: '*').

  36. --cache-clear remove all cache contents at start of test run.

  37. --lfnf={all,none}, --last-failed-no-failures={all,none}

  38. which tests to run with no previously (known) failures.

  39. --sw, --stepwise exit on test failure andcontinuefrom last failing test next time

  40. --sw-skip, --stepwise-skip

  41. ignore the first failing test but stop on the next failing test

  42. --allure-severities=SEVERITIES_SET

  43. Comma-separated list of severity names.

  44. Tests only with these severities will be run.

  45. Possible values are: blocker, critical, normal, minor, trivial.

  46. --allure-epics=EPICS_SET

  47. Comma-separated list of epic names.

  48. Run tests that have at least one of the specified feature labels.

  49. --allure-features=FEATURES_SET

  50. Comma-separated list of feature names.

  51. Run tests that have at least one of the specified feature labels.

  52. --allure-stories=STORIES_SET

  53. Comma-separated list of story names.

  54. Run tests that have at least one of the specified story labels.

  55. --allure-link-pattern=LINK_TYPE:LINK_PATTERN

  56. Url pattern for link type. Allows short links in test,

  57. like 'issue-1'. Text will be formatted to full url with python

  58. str.format().

  59. reporting:

  60. --durations=N show N slowest setup/test durations (N=0for all).

  61. --durations-min=N Minimal duration in seconds for inclusion in slowest list. Default 0.005

  62. -v, --verbose increase verbosity.

  63. --no-header disable header

  64. --no-summary disable summary

  65. -q, --quiet decrease verbosity.

  66. --verbosity=VERBOSE set verbosity. Default is0.

  67. -r chars show extra test summary info as specified by chars: (f)ailed, (E)rror, (s)kipped, (x)failed,

  68. (X)passed, (p)assed, (P)assed with output, (a)ll except passed (p/P), or (A)ll. (w)arnings are

  69. enabled by default (see --disable-warnings), 'N' can be used to reset the list. (default: 'fE').

  70. --disable-warnings, --disable-pytest-warnings

  71. disable warnings summary

  72. -l, --showlocals show locals in tracebacks (disabled by default).

  73. --tb=style traceback print mode (auto/long/short/line/native/no).

  74. --show-capture={no,stdout,stderr,log,all}

  75. Controls how captured stdout/stderr/log is shown on failed tests. Default is'all'.

  76. --full-trace don't cut any tracebacks (default is to cut).

  77. --color=color color terminal output (yes/no/auto).

  78. --code-highlight={yes,no}

  79. Whether code should be highlighted (only if --color is also enabled)

  80. --pastebin=mode send failed|all info to bpaste.net pastebin service.

  81. --junit-xml=path create junit-xml style report file at given path.

  82. --junit-prefix=str prepend prefix to classnames in junit-xml output

  83. --html=path create html report file at given path.

  84. --self-contained-html

  85. create a self-contained html file containing all necessary styles, scripts, and images - this

  86. means that the report may not render or function where CSP restrictions are in place (see

  87. https://developer.mozilla.org/docs/Web/Security/CSP)

  88. --css=path append given css file content to report style file.

  89. pytest-warnings:

  90. -W PYTHONWARNINGS, --pythonwarnings=PYTHONWARNINGS

  91. set which warnings to report, see -W option of python itself.

  92. --maxfail=num exit after first num failures or errors.

  93. --strict-config any warnings encountered while parsing the `pytest` section of the configuration file raise

  94. errors.

  95. --strict-markers markers not registered in the `markers` section of the configuration file raise errors.

  96. --strict (deprecated) alias to --strict-markers.

  97. -c file load configuration from `file` instead of trying to locate one of the implicit configuration

  98. files.

  99. --continue-on-collection-errors

  100. Force test execution even if collection errors occur.

  101. --rootdir=ROOTDIR Define root directory for tests. Can be relative path: 'root_dir', './root_dir',

  102. 'root_dir/another_dir/'; absolute path: '/home/user/root_dir'; path with variables:

  103. '$HOME/root_dir'.

  104. collection:

  105. --collect-only, --co only collect tests, don't execute them.

  106. --pyargs try to interpret all arguments as python packages.

  107. --ignore=path ignore path during collection (multi-allowed).

  108. --ignore-glob=path ignore path pattern during collection (multi-allowed).

  109. --deselect=nodeid_prefix

  110. deselect item (via node id prefix) during collection (multi-allowed).

  111. --confcutdir=dir only load conftest.py's relative to specified dir.

  112. --noconftest Don't load any conftest.py files.

  113. --keep-duplicates Keep duplicate tests.

  114. --collect-in-virtualenv

  115. Don't ignore tests in a local virtualenv directory

  116. --import-mode={prepend,append,importlib}

  117. prepend/append to sys.path when importing test modules and conftest files, default is to

  118. prepend.

  119. --doctest-modules run doctests in all .py modules

  120. --doctest-report={none,cdiff,ndiff,udiff,only_first_failure}

  121. choose another output format for diffs on doctest failure

  122. --doctest-glob=pat doctests file matching pattern, default: test*.txt

  123. --doctest-ignore-import-errors

  124. ignore doctest ImportErrors

  125. --doctest-continue-on-failure

  126. for a given doctest, continue to run after the first failure

  127. test session debugging and configuration:

  128. --basetemp=dir base temporary directory for this test run.(warning: this directory is removed if it exists)

  129. -V, --version display pytest version and information about plugins.When given twice, also display information

  130. about plugins.

  131. -h, --help show help message and configuration info

  132. -p name early-load given plugin module name or entry point (multi-allowed).

  133. To avoid loading of plugins, use the `no:` prefix, e.g. `no:doctest`.

  134. --trace-config trace considerations of conftest.py files.

  135. --debug store internal tracing debug information in 'pytestdebug.log'.

  136. -o OVERRIDE_INI, --override-ini=OVERRIDE_INI

  137. override ini option with "option=value" style, e.g. `-o xfail_strict=True -o cache_dir=cache`.

  138. --assert=MODE Control assertion debugging tools.

  139. 'plain' performs no assertion debugging.

  140. 'rewrite' (the default) rewrites assert statements in test modules on import to provide assert

  141. expression information.

  142. --setup-only only setup fixtures, do not execute tests.

  143. --setup-show show setup of fixtures while executing tests.

  144. --setup-plan show what fixtures and tests would be executed but don't execute anything.

  145. logging:

  146. --log-level=LEVEL level of messages to catch/display.

  147. Not set by default, so it depends on the root/parent log handler's effective level, where it is

  148. "WARNING" by default.

  149. --log-format=LOG_FORMAT

  150. log format as used by the logging module.

  151. --log-date-format=LOG_DATE_FORMAT

  152. log date format as used by the logging module.

  153. --log-cli-level=LOG_CLI_LEVEL

  154. cli logging level.

  155. --log-cli-format=LOG_CLI_FORMAT

  156. log format as used by the logging module.

  157. --log-cli-date-format=LOG_CLI_DATE_FORMAT

  158. log date format as used by the logging module.

  159. --log-file=LOG_FILE path to a file when logging will be written to.

  160. --log-file-level=LOG_FILE_LEVEL

  161. log file logging level.

  162. --log-file-format=LOG_FILE_FORMAT

  163. log format as used by the logging module.

  164. --log-file-date-format=LOG_FILE_DATE_FORMAT

  165. log date format as used by the logging module.

  166. --log-auto-indent=LOG_AUTO_INDENT

  167. Auto-indent multiline messages passed to the logging module. Accepts true|on, false|off or an

  168. integer.

  169. reporting:

  170. --alluredir=DIR Generate Allure report in the specified directory (may not exist)

  171. --clean-alluredir Clean alluredir folder if it exists

  172. --allure-no-capture Do not attach pytest captured logging/stdout/stderr to report

  173. coverage reporting with distributed testing support:

  174. --cov=[SOURCE] Path or package name to measure during execution (multi-allowed). Use --cov= to not do any

  175. source filtering and record everything.

  176. --cov-report=TYPE Type of report to generate: term, term-missing, annotate, html, xml (multi-allowed). term, term-

  177. missing may be followed by ":skip-covered". annotate, html and xml may be followed by ":DEST"

  178. where DEST specifies the output location. Use --cov-report= to not generate any output.

  179. --cov-config=PATH Config file for coverage. Default: .coveragerc

  180. --no-cov-on-fail Do not report coverage if test run fails. Default: False

  181. --no-cov Disable coverage report completely (useful for debuggers). Default: False

  182. --cov-fail-under=MIN Fail if the total coverage is less than MIN.

  183. --cov-append Do not delete coverage but append to current. Default: False

  184. --cov-branch Enable branch coverage.

  185. --cov-context=CONTEXT

  186. Dynamic contexts to use. "test" for now.

  187. forked subprocess test execution:

  188. --forked box each test run in a separate process (unix)

  189. re-run failing tests to eliminate flaky failures:

  190. --only-rerun=ONLY_RERUN

  191. If passed, only rerun errors matching the regex provided. Pass this flag multiple times to

  192. accumulate a list of regexes to match

  193. --reruns=RERUNS number of times to re-run failed tests. defaults to 0.

  194. --reruns-delay=RERUNS_DELAY

  195. add time (seconds) delay between reruns.

  196. --rerun-except=RERUN_EXCEPT

  197. If passed, only rerun errors other than matching the regex provided. Pass this flag multiple

  198. times to accumulate a list of regexes to match

  199. distributed and subprocess testing:

  200. -n numprocesses, --numprocesses=numprocesses

  201. shortcut for '--dist=load --tx=NUM*popen', you can use 'auto' here for auto detection CPUs

  202. number on host system and it will be 0 when used with --pdb

  203. --maxprocesses=maxprocesses

  204. limit the maximum number of workers to process the tests when using --numprocesses=auto

  205. --max-worker-restart=MAXWORKERRESTART, --max-slave-restart=MAXWORKERRESTART

  206. maximum number of workers that can be restarted when crashed (set to zero to disable this

  207. feature)

  208. '--max-slave-restart' option is deprecated and will be removed in a future release

  209. --dist=distmode set mode for distributing tests to exec environments.

  210. each: send each test to all available environments.

  211. load: load balance by sending any pending test to any available environment.

  212. loadscope: load balance by sending pending groups of tests in the same scope to any available

  213. environment.

  214. loadfile: load balance by sending test grouped by file to any available environment.

  215. (default) no: run tests inprocess, don't distribute.

  216. --tx=xspec add a test execution environment. some examples: --tx popen//python=python2.5 --tx

  217. socket=192.168.1.102:8888 --tx ssh=user@codespeak.net//chdir=testcache

  218. -d load-balance tests. shortcut for'--dist=load'

  219. --rsyncdir=DIR add directory for rsyncing to remote tx nodes.

  220. --rsyncignore=GLOB add expression for ignores when rsyncing to remote tx nodes.

  221. --boxed backward compatibility alias for pytest-forked --forked

  222. -f, --looponfail run tests in subprocess, wait for modified files and re-run failing test set until all pass.

  223. custom options:

  224. --metadata=key value additional metadata.

  225. --count=COUNT Number of times to repeat each test

  226. --repeat-scope={function,class,module,session}

  227. Scope for repeating tests

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

  229. markers (linelist): markers for test functions

  230. empty_parameter_set_mark (string):

  231. default marker for empty parametersets

  232. norecursedirs (args): directory patterns to avoid for recursion

  233. testpaths (args): directories to search for tests when no files or directories are given in the command line.

  234. filterwarnings (linelist):

  235. Each line specifies a pattern for warnings.filterwarnings. Processed after -W/--pythonwarnings.

  236. usefixtures (args): list of default fixtures to be used with this project

  237. python_files (args): glob-style file patterns for Python test module discovery

  238. python_classes (args):

  239. prefixes or glob names for Python test class discovery

  240. python_functions (args):

  241. prefixes or glob names for Python test function and method discovery

  242. disable_test_id_escaping_and_forfeit_all_rights_to_community_support (bool):

  243. disable string escape non-ascii characters, might cause unwanted side effects(use at your own

  244. risk)

  245. console_output_style (string):

  246. console output: "classic", orwith additional progress information ("progress" (percentage) |

  247. "count").

  248. xfail_strict (bool): default for the strict parameter of xfail markers when not given explicitly (default: False)

  249. enable_assertion_pass_hook (bool):

  250. Enables the pytest_assertion_pass hook.Make sure to delete any previously generated pyc cache

  251. files.

  252. junit_suite_name (string):

  253. Test suite name for JUnit report

  254. junit_logging (string):

  255. Write captured log messages to JUnit report: one of no|log|system-out|system-err|out-err|all

  256. junit_log_passing_tests (bool):

  257. Capture log information for passing tests to JUnit report:

  258. junit_duration_report (string):

  259. Duration time to report: one of total|call

  260. junit_family (string):

  261. Emit XML for schema: one of legacy|xunit1|xunit2

  262. doctest_optionflags (args):

  263. option flags for doctests

  264. doctest_encoding (string):

  265. encoding used for doctest files

  266. cache_dir (string): cache directory path.

  267. log_level (string): default value for --log-level

  268. log_format (string): default value for --log-format

  269. log_date_format (string):

  270. default value for --log-date-format

  271. log_cli (bool): enable log display during test run (also known as"live logging").

  272. log_cli_level (string):

  273. default value for --log-cli-level

  274. log_cli_format (string):

  275. default value for --log-cli-format

  276. log_cli_date_format (string):

  277. default value for --log-cli-date-format

  278. log_file (string): default value for --log-file

  279. log_file_level (string):

  280. default value for --log-file-level

  281. log_file_format (string):

  282. default value for --log-file-format

  283. log_file_date_format (string):

  284. default value for --log-file-date-format

  285. log_auto_indent (string):

  286. default value for --log-auto-indent

  287. faulthandler_timeout (string):

  288. Dump the traceback of all threads if a test takes more than TIMEOUT seconds to finish.

  289. addopts (args): extra command line options

  290. minversion (string): minimally required pytest version

  291. required_plugins (args):

  292. plugins that must be present for pytest to run

  293. rsyncdirs (pathlist): list of (relative) paths to be rsynced for remote distributed testing.

  294. rsyncignore (pathlist):

  295. list of (relative) glob-style paths to be ignored for rsyncing.

  296. looponfailroots (pathlist):

  297. directories to check for changes

  298. environment variables:

  299. PYTEST_ADDOPTS extra command line options

  300. PYTEST_PLUGINS comma-separated plugins to load during startup

  301. PYTEST_DISABLE_PLUGIN_AUTOLOAD set to disable plugin auto-loading

  302. PYTEST_DEBUG set to enable debug tracing of pytest's internals

  303. to see available markers type: pytest --markers

  304. to see available fixtures type: pytest --fixtures

  305. (shown according to specified file_or_dir or current dir if not specified; fixtures with leading '_' are only shown with the '-v' option

  • 其中pytest.ini选项内容如下:
 
  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. filterwarnings (linelist):

  8. Each line specifies a pattern for warnings.filterwarnings. Processed after -W/--pythonwarnings.

  9. usefixtures (args): list of default fixtures to be used with this project

  10. python_files (args): glob-style file patterns for Python test module discovery

  11. python_classes (args):

  12. prefixes or glob names for Python test class discovery

  13. python_functions (args):

  14. prefixes or glob names for Python test function and method discovery

  15. disable_test_id_escaping_and_forfeit_all_rights_to_community_support (bool):

  16. disable string escape non-ascii characters, might cause unwanted side effects(use at your own

  17. risk)

  18. console_output_style (string):

  19. console output: "classic", orwith additional progress information ("progress" (percentage) |

  20. "count").

  21. xfail_strict (bool): default for the strict parameter of xfail markers when not given explicitly (default: False)

  22. enable_assertion_pass_hook (bool):

  23. Enables the pytest_assertion_pass hook.Make sure to delete any previously generated pyc cache

  24. files.

  25. junit_suite_name (string):

  26. Test suite name for JUnit report

  27. junit_logging (string):

  28. Write captured log messages to JUnit report: one of no|log|system-out|system-err|out-err|all

  29. junit_log_passing_tests (bool):

  30. Capture log information for passing tests to JUnit report:

  31. junit_duration_report (string):

  32. Duration time to report: one of total|call

  33. junit_family (string):

  34. Emit XML for schema: one of legacy|xunit1|xunit2

  35. doctest_optionflags (args):

  36. option flags for doctests

  37. doctest_encoding (string):

  38. encoding used for doctest files

  39. cache_dir (string): cache directory path.

  40. log_level (string): default value for --log-level

  41. log_format (string): default value for --log-format

  42. log_date_format (string):

  43. default value for --log-date-format

  44. log_cli (bool): enable log display during test run (also known as"live logging").

  45. log_cli_level (string):

  46. default value for --log-cli-level

  47. log_cli_format (string):

  48. default value for --log-cli-format

  49. log_cli_date_format (string):

  50. default value for --log-cli-date-format

  51. log_file (string): default value for --log-file

  52. log_file_level (string):

  53. default value for --log-file-level

  54. log_file_format (string):

  55. default value for --log-file-format

  56. log_file_date_format (string):

  57. default value for --log-file-date-format

  58. log_auto_indent (string):

  59. default value for --log-auto-indent

  60. faulthandler_timeout (string):

  61. Dump the traceback of all threads if a test takes more than TIMEOUT seconds to finish.

  62. addopts (args): extra command line options

  63. minversion (string): minimally required pytest version

  64. required_plugins (args):

  65. plugins that must be present for pytest to run

  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 常用选项
5.1 marks
  • 以下是使用@pytest.mark.xxx方法:
  1. import pytest

  2. @pytest.mark.name

  3. def one_name():

  4. print("name is xiaoming")

  5. @pytest.mark.old

  6. def two_old():

  7. print("old is 20")

  8. def th_weight():

  9. print("weight is 50")

  10. @pytest.mark.case

  11. class TestCase:

  12. def test_case_01(self):

  13. print("case_01")

  14. def test_case_02(self):

  15. print("case_02")

  16. if __name__ == '__main__':

  17. pytest.main(["-v", "test_ini.py", "-m=case"])

  • 标签多容易出错,可以写入到pytest.ini:
  1. # pytest.ini

  2. [pytest]

  3. markers =

  4. name: run the name

  5. old: run the old

  6. case: run the test_case

  • 标记后可使用pytest --markers查看:
 
  1. (venv) F:\pytest_study\test_case\test_i>pytest --markers

  2. @pytest.mark.name: run the name

  3. @pytest.mark.old: run the old

  4. @pytest.mark.case: run the test_case

  5. @pytest.mark.forked: Always fork for this test.

  6. @pytest.mark.flaky(reruns=1, reruns_delay=0): mark test to re-run up to 'reruns' times. Add a delay of 'rerun

  7. s_delay' seconds between re-runs.

  8. @pytest.mark.repeat(n): run the given test function `n` times.

  9. @pytest.mark.run: specify ordering information for when tests should run in relation to one another. Provided

  10. by pytest-ordering. See also: http://pytest-ordering.readthedocs.org/

  11. @pytest.mark.no_cover: disable coverage for this test.

  12. @pytest.mark.allure_label: allure label marker

  13. @pytest.mark.allure_link: allure link marker

  14. @pytest.mark.allure_display_name: allure test name marker

  15. @pytest.mark.allure_description: allure description

  16. @pytest.mark.allure_description_html: allure description html

  17. @pytest.mark.filterwarnings(warning): add a warning filter to the given test. see https://docs.pytest.org/en/

  18. stable/warnings.html#pytest-mark-filterwarnings

  19. @pytest.mark.skip(reason=None): skip the given test function with an optional reason. Example: skip(reason="n

  20. o way of currently testing this") skips the test.

  21. @pytest.mark.skipif(condition, ..., *, reason=...): skip the given test function if any of the conditions eva

  22. luate to True. Example: skipif(sys.platform == 'win32') skips the test if we are on the win32 platform. See h

  23. ttps://docs.pytest.org/en/stable/reference.html#pytest-mark-skipif

  24. @pytest.mark.xfail(condition, ..., *, reason=..., run=True, raises=None, strict=xfail_strict): mark the test

  25. function as an expected failure if any of the conditions evaluate to True. Optionally specify a reason for be

  26. tter reporting and run=False if you don't even want to execute the test function. If only specific exception(

  27. s) are expected, you can list them in raises, andif the test fails in other ways, it will be reported as a t

  28. rue failure. See https://docs.pytest.org/en/stable/reference.html#pytest-mark-xfail

  29. @pytest.mark.parametrize(argnames, argvalues): call a test function multiple times passing in different argum

  30. ents in turn. argvalues generally needs to be a list of values if argnames specifies only one name or a list

  31. of tuples of values if argnames specifies multiple names. Example: @parametrize('arg1', [1,2]) would lead to

  32. two calls of the decorated test function, one with arg1=1and another with arg1=2.see https://docs.pytest.org

  33. /en/stable/parametrize.html for more info and examples.

  34. @pytest.mark.usefixtures(fixturename1, fixturename2, ...): mark tests as needing all of the specified fixture

  35. s. see https://docs.pytest.org/en/stable/fixture.html#usefixtures

  36. @pytest.mark.tryfirst: mark a hook implementation function such that the plugin machinery will try to call it

  37. first/as early as possible.

  38. @pytest.mark.trylast: mark a hook implementation function such that the plugin machinery will try to call it

  39. last/as late as possible.

5.2 xfail_strict
  • 设置xfail_strict = True可以让那些标记为@pytest.mark.xfail但实际通过显示XPASS的测试用例被报告标记为失败;
  • pytest.ini的写法:
  1. [pytest]

  2. markers =

  3. name: run the name

  4. old: run the old

  5. case: run the test_case

  6. xfail_strict = True

  • 代码为:
 
  1. # -*- coding:utf-8 -*-

  2. # 作者:虫无涯

  3. # 日期:2023/3/15

  4. # 文件名称:test_ini01.py

  5. # 作用:pytest.ini的使用

  6. # 联系:VX(NoamaNelson)

  7. # 博客:https://blog.csdn.net/NoamaNelson

  8. import pytest

  9. @pytest.mark.name

  10. def test_name():

  11. print("name is xiaoming")

  12. @pytest.mark.old

  13. def test_old():

  14. print("old is 20")

  15. @pytest.mark.xfail()

  16. def test_weight():

  17. a = 30

  18. b = 60

  19. assert a != b

  20. @pytest.mark.case

  21. class TestCase:

  22. def test_case_01(self):

  23. print("case_01")

  24. def test_case_02(self):

  25. print("case_02")

  26. if __name__ == '__main__':

  27. pytest.main(["-v", "test_ini01.py", "-m=case"])

  • 结果如下,可以看到测试结果为失败:

test_ini01.py::test_name PASSED [ 20%]name is xiaoming

  1. test_ini01.py::test_old PASSED [ 40%]old is20

  2. test_ini01.py::test_weight FAILED [ 60%]

  3. test_case\test_i\test_ini01.py:18 (test_weight)

  4. [XPASS(strict)]

  5. test_ini01.py::TestCase::test_case_01 PASSED [ 80%]case_01

  6. test_ini01.py::TestCase::test_case_02 PASSED [100%]case_02

  7. ================================== FAILURES ===================================

  8. _________________________________ test_weight _________________________________

  9. [XPASS(strict)]

  10. =========================== short test summary info ===========================

  11. FAILED test_ini01.py::test_weight

  12. ========================= 1 failed, 4 passed in0.05s =========================

5.3 addopts
  • addopts参数可以更改默认命令行选项;
  • 比如测试完生成报告,失败重跑3次,一共运行2次,通过分布式去测试:
addopts = -v --reruns=2 --count=2 --html=reports.html --self-contained-html -n=auto
  • 把以上命令加入pytest.ini,就不用在命令行重复去写这些参数:
  1. [pytest]

  2. markers =

  3. name: run the name

  4. old: run the old

  5. case: run the test_case

  6. xfail_strict = True

  7. addopts = -v --reruns=2 --count=2 --html=reports.html --self-contained-html -n=auto

  • 运行结果:
  1. test_ini01.py::test_old[1-2]

  2. test_ini01.py::test_old[2-2]

  3. test_ini01.py::test_weight[1-2]

  4. test_ini01.py::test_weight[2-2]

  5. test_ini01.py::test_name[1-2]

  6. test_ini01.py::TestCase::test_case_01[2-2]

  7. test_ini01.py::test_name[2-2]

  8. test_ini01.py::TestCase::test_case_01[1-2]

  9. [gw3] [ 10%] PASSED test_ini01.py::test_old[2-2]

  10. [gw6] [ 20%] PASSED test_ini01.py::TestCase::test_case_01[1-2]

  11. [gw2] [ 30%] PASSED test_ini01.py::test_old[1-2]

  12. [gw0] [ 40%] PASSED test_ini01.py::test_name[1-2]

  13. test_ini01.py::TestCase::test_case_02[1-2]

  14. [gw0] [ 50%] PASSED test_ini01.py::TestCase::test_case_02[1-2]

  15. [gw1] [ 60%] PASSED test_ini01.py::test_name[2-2]

  16. test_ini01.py::TestCase::test_case_02[2-2]

  17. [gw7] [ 70%] PASSED test_ini01.py::TestCase::test_case_01[2-2]

  18. [gw1] [ 80%] PASSED test_ini01.py::TestCase::test_case_02[2-2]

  19. [gw5] [ 90%] RERUN test_ini01.py::test_weight[2-2]

  20. test_ini01.py::test_weight[2-2]

  21. [gw4] [100%] RERUN test_ini01.py::test_weight[1-2]

  22. test_ini01.py::test_weight[1-2]

  23. [gw5] [100%] RERUN test_ini01.py::test_weight[2-2]

  24. test_ini01.py::test_weight[2-2]

  25. [gw5] [100%] FAILED test_ini01.py::test_weight[2-2]

  26. test_case\test_i\test_ini01.py:18 (test_weight[2-2])

  27. [XPASS(strict)]

  28. [gw4] [100%] RERUN test_ini01.py::test_weight[1-2]

  29. test_ini01.py::test_weight[1-2]

  30. [gw4] [100%] FAILED test_ini01.py::test_weight[1-2]

  31. test_case\test_i\test_ini01.py:18 (test_weight[1-2])

  32. [XPASS(strict)]

  33. ================================== FAILURES ===================================

  34. ______________________________ test_weight[2-2] _______________________________

  35. [gw5] win32 -- Python 3.7.0 F:\pytest_study\venv\Scripts\python.exe

  36. [XPASS(strict)]

  37. ______________________________ test_weight[1-2] _______________________________

  38. [gw4] win32 -- Python 3.7.0 F:\pytest_study\venv\Scripts\python.exe

  39. [XPASS(strict)]

  40. -- generated html file: file://F:\pytest_study\test_case\test_i\reports.html --

  41. =========================== short test summary info ===========================

  42. FAILED test_ini01.py::test_weight[2-2]

  43. FAILED test_ini01.py::test_weight[1-2]

  44. ==================== 2 failed, 8 passed, 4 rerun in3.11s =====================

  • addopts常用参数:

5.4 log_cli
  • 控制台实时输出日志;
  • log_cli=True 或False(默认);
  • log_cli=True :
  1. collecting ... collected 5 items

  2. test_ini01.py::test_name PASSED [ 20%]name is xiaoming

  3. test_ini01.py::test_old PASSED [ 40%]old is20

  4. test_ini01.py::test_weight FAILED [ 60%]

  5. test_case\test_i\test_ini01.py:18 (test_weight)

  6. [XPASS(strict)]

  7. test_ini01.py::TestCase::test_case_01 PASSED [ 80%]case_01

  8. test_ini01.py::TestCase::test_case_02 PASSED [100%]case_02

  9. ================================== FAILURES ===================================

  10. _________________________________ test_weight _________________________________

  11. [XPASS(strict)]

  12. =========================== short test summary info ===========================

  13. FAILED test_ini01.py::test_weight

  14. ========================= 1 failed, 4 passed in0.05s =========================

  • 加了log_cli=True之后,可以清晰看到哪个package、module下的用例执行情况。
5.5 norecursedirs
  • pytest 收集测试用例时,会递归遍历所有子目录;
  • 如果有些目录不需要执行,可使用norecursedirs参数简化 pytest 的搜索工作;
  • 方法如下,多个路径用空格隔开:
norecursedirs = .* build dist CVS _darcs {arch} *.egg
  • 比如:
  1. [pytest]

  2. markers =

  3. name: run the name

  4. old: run the old

  5. case: run the test_case

  6. xfail_strict = True

  7. # addopts = -v --reruns=2 --count=2 --html=reports.html --self-contained-html -n=auto

  8. log_cli = False

  9. norecursedirs = .* build dist CVS _darcs {arch} *.egg report test_case log

  • 也可以使用norecursedirs修改pytest的默认用例收集规则;
  • 其中默认用例收集规则为:
  1. 文件名以 test_*.py 文件和 *_test.py

  2. 以test_ 开头的函数

  3. 以Test 开头的类,不能包含 __init__ 方法

  4. 以test_ 开头的类里面的方法

  • 比如修改为:
  1. [pytest]

  2. python_files = test* test_* *_test

  3. python_classes = Test* test*

  4. python_functions = test_* test*

6 本文涉及的pytest.ini源码
  1. [pytest]

  2. markers =

  3. name: run the name

  4. old: run the old

  5. case: run the test_case

  6. xfail_strict = True

  7. addopts = -v --reruns=2 --count=2 --html=reports.html --self-contained-html -n=auto

  8. log_cli = False

  9. norecursedirs = .* build dist CVS _darcs {arch} *.egg report test_case log

  10. python_files = test* test_* *_test

  11. python_classes = Test* test*

  12. python_functions = test_* test*

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值