pytest configuration file pytest.ini

Foreword:

The pytest.ini file is the main configuration file of pytest, which can change the operation mode of pytest. It is a fixed file pytest.ini file, which reads the configuration information and runs according to the specified method.

The location of the pytest.ini file is generally placed in the root directory of the project, it cannot be placed casually, and the name cannot be changed.

View the configuration options of the pytest.ini file

  Execute pytest -h or pytest --help under cmd to view the configuration options and find the following:

[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.
  filterwarnings (linelist):
                        Each line specifies a pattern for warnings.filterwarnings. Processed after -W/--pythonwarnings.
  usefixtures (args):   list of default fixtures to be used with this project
  python_files (args):  glob-style file patterns for Python test module discovery
  python_classes (args):
                        prefixes or glob names for Python test class discovery
  python_functions (args):
                        prefixes or glob names for Python test function and method discovery
  disable_test_id_escaping_and_forfeit_all_rights_to_community_support (bool):
                        disable string escape non-ascii characters, might cause unwanted side effects(use at your own risk)
  console_output_style (string):
                        console output: "classic", or with additional progress information ("progress" (percentage) | "count").
  xfail_strict (bool):  default for the strict parameter of xfail markers when not given explicitly (default: False)
  enable_assertion_pass_hook (bool):
                        Enables the pytest_assertion_pass hook.Make sure to delete any previously generated pyc cache files.
  junit_suite_name (string):
                        Test suite name for JUnit report
  junit_logging (string):
                        Write captured log messages to JUnit report: one of no|log|system-out|system-err|out-err|all
  junit_log_passing_tests (bool):
                        Capture log information for passing tests to JUnit report:
  junit_duration_report (string):
                        Duration time to report: one of total|call
  junit_family (string):
                        Emit XML for schema: one of legacy|xunit1|xunit2
  doctest_optionflags (args):
                        option flags for doctests
  doctest_encoding (string):
                        encoding used for doctest files
  cache_dir (string):   cache directory path.
  log_level (string):   default value for --log-level
  log_format (string):  default value for --log-format
  log_date_format (string):
                        default value for --log-date-format
  log_cli (bool):       enable log display during test run (also known as "live logging").
  log_cli_level (string):
                        default value for --log-cli-level
  log_cli_format (string):
                        default value for --log-cli-format
  log_cli_date_format (string):
                        default value for --log-cli-date-format
  log_file (string):    default value for --log-file
  log_file_level (string):
                        default value for --log-file-level
  log_file_format (string):
                        default value for --log-file-format
  log_file_date_format (string):
                        default value for --log-file-date-format
  log_auto_indent (string):
                        default value for --log-auto-indent
  faulthandler_timeout (string):
                        Dump the traceback of all threads if a test takes more than TIMEOUT seconds to finish.
  addopts (args):       extra command line options
  minversion (string):  minimally required pytest version
  required_plugins (args):
                        plugins that must be present for pytest to run
  render_collapsed (bool):
                        Open the report with all rows collapsed. Useful for very large reports
  max_asset_filename_length (string):
                        set the maximum filename length for assets attached to the html report.
  rsyncdirs (pathlist): list of (relative) paths to be rsynced for remote distributed testing.
  rsyncignore (pathlist):
                        list of (relative) glob-style paths to be ignored for rsyncing.
  looponfailroots (pathlist):
                        directories to check for changes

Common configuration options

markers

Function: use the @pytest.mark.slow decorator in the test case, if the markers option is not added, a warning will be reported

Format: list list type

Writing:

# file_name: pytest.ini

[pytest]
markers =
    slow: run slow mark case
    fast: run fast mark case

xfail_strict

Function: Setting xfail_strict=true allows those test cases marked as @pytest.mark.xfail but actually passed as XPASS to be reported as failed

Format: True, False (default), 1, 0

Writing:

# file_name: pytest.ini

[pytest]
markers =
    slow: run slow mark case
    fast: run fast mark case

xfail_strict = true

for example:

# file_name: test_xfail.py

import pytest


class Test_C:

    @pytest.mark.xfail
    def test_c(self):
        print('\n------------------> test_c has ran')
        a = 'hello'
        b = 'hello world'
        assert a != b


if __name__ == '__main__':
    pytest.main(['-s', 'test_xfail.py'])

When xfail_strict = True is not set, the test result shows XPASS

When setting xfail_strict = True, the test result shows failed

addopts

Function: The addopts parameter can change the default command line options. This parameter will be used when we need to enter a large number of instructions on the command line to execute the test case. At this time, we can configure this parameter in the configuration file instead, saving drop a lot of repetitive work

For example: I want to generate a test report after the test is over, and rerun the failed test case twice. If the command is executed through the command line, the command will be very long:

pytest -v --reruns=2 --html=report.html --self-contained-html

It would be cumbersome to enter the above command every time it is executed. At this time, we can solve this problem by configuring the addopts parameter:

# file_name: pytest.ini

[pytest]
markers =
    slow: run slow mark case
    fast: run fast mark case

xfail_strict = True

addopts = -v --reruns=2 --html=report.html --self-contained-html  # 多个命令行参数用空格分隔开,可以添加多个命令行参数

After adding addopts in this way, when we enter the cmd command line to execute again, we can bring these parameters by default as long as we enter pytest.

log_cli

Role: console real-time output log

Format: log_cli=True or False (default), or log_cli=1 or 0

When log_cli=True is set, the running result is:

When log_cli=False is set, the running result is:

Conclusion: When we set log_cli=True, we can clearly see which test case under which module under which package is passed or failed;

Therefore, we usually recommend adding log_cli=True when debugging whether there is a problem with the code, and it can be removed when the test case is debugged and executed in batches.

norecursedirs

Function: When pytest collects test cases, it will recursively traverse all subdirectories in the current directory. When we need to not execute test cases in certain directories, we can achieve this function by setting the norecursedirs parameter.

# file_name: pytest.ini

[pytest]
markers =
    slow: run slow mark case
    fast: run fast mark case

xfail_strict = True

addopts = -v --reruns=2 --html=report.html --self-contained-html

log_cli = False

norecursedirs = venv report util log  # 多个目录需要空格分开,可以配置多个

The above configuration indicates that the use cases in the 4 directories of venv report util log need to be filtered out and not executed.

Change collection rules for test cases

The default test case collection rules of pytest are:

  • Filenames matching test_*.py or *_test.py
  • Functions beginning with test_
  • Classes beginning with Test_ cannot contain _init_ methods
  • Methods starting with test_ in the class

We can modify the above default rules through the settings of the configuration file

# file_name: pytest.ini

[pytest]
testpaths = xdist_study

python_files = test*.py

python_classes = Test*

python_functions = test_*

testpaths: configure which directory to search for test cases, can be customized, multiple configurations can be configured, and multiples are separated by spaces

python_files: The file name of the test case used to configure the search, can be customized, multiple configurations can be configured, and multiples are separated by spaces

python_classes: Configure the class name of the test case to be searched, can be customized, multiple configurations can be configured, and multiples are separated by spaces

python_functions: configure the method name of the test case to be searched, can be customized, multiple configurations can be configured, and multiples are separated by spaces

The above configuration means: in the xdist_study directory, search for files starting with test and ending with .py, classes starting with Test, and methods starting with test_.

Summarize:

Thanks to everyone who read my article carefully! ! !

 I personally sorted out some technical materials I have compiled in my software testing career in the past few years, including: e-books, resume modules, various job templates, interview books, self-study projects, etc. Everyone is welcome to leave a message in the comment area 333 to get it for free, don't miss it.

 

Guess you like

Origin blog.csdn.net/MXB_1220/article/details/131585847