pytest之配置文件pytest.ini


  pytest.ini文件是pytest的主配置文件,可以改變pytest的運行方式,它是一個固定的文件pytest.ini文件,讀取配置信息,按指定的方式去運行。

pytest.ini文件的位置一般放在項目的根目錄下,不能隨便放,也不能更改名字。

查看pytest.ini文件的配置選項

  cmd下執行pytest -h 或者 pytest --help 可以查看配置選項,找到如下內容:

[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

常用的配置選項

markers

作用:測試用例中使用@pytest.mark.slow裝飾器,如果不添加markers選項就會報warning

格式:list列表類型

寫法:

# file_name: pytest.ini

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

xfail_strict

作用:設置xfail_strict=true可以讓那邊標記為@pytest.mark.xfail 但實際通過顯示為XPASS 的測試用例被報告為失敗

格式:True、False(默認)、1、0

寫法:

# file_name: pytest.ini

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

xfail_strict = true

舉例說明:

# 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'])

沒有設置xfail_strict = True 時,測試結果顯示XPASS

  設置xfail_strict = True 時,測試結果顯示failed

 addopts

作用:addopts參數可以更改默認的命令行選項,這個參數在我們需要在命令行中輸入大一堆指令來執行測試用例時會用到,這個時候就可以配置文件中配置這個參數來代替,省掉很多重復的工作

例如:我想在測試結束之后,生成測試報告,失敗的測試用例重跑兩次,如果通過命令行輸入指令來執行的話,指令會很長:

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

如果沒有執行都要輸入上面的指令會很繁瑣,這個時候我們通過配置addopts參數來解決這個問題:

# 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  # 多個命令行參數用空格分隔開,可以添加多個命令行參數

這樣加上addopts后,我們再次進入cmd命令行執行時,只要輸入pytest就可以默認帶上這些參數了。

log_cli

作用:控制台實時輸出日志

格式:log_cli=True 或False(默認),或者log_cli=1 或 0

設置log_cli=True時,運行結果為:

 

 

 設置log_cli=False時,運行結果為:

 

 

 結論:當我們設置log_cli=True時,可以非常清晰的看出具體的是哪個package下的哪個module下的哪個測試用例是passed還是failed;

所以我們平時在調試代碼是否有問題時推薦加上log_cli=True,當測試用例調試通過之后批量執行時就可以去掉了。

norecursedirs

作用:pytest在收集測試用例的時候,會遞歸遍歷當前目錄下的所有子目錄,當我們需要某些目錄下的用例不要執行時,就可以通過設置norecursedirs參數來實現這個功能。

# 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  # 多個目錄需要空格分開,可以配置多個

上面的配置表示venv report util log這4個目錄下的用例需要過濾掉不執行。

更改測試用例的收集規則

pytest默認的測試用例收集規則為:

  • 文件名匹配test_*.py或*_test.py
  • 以test_開頭的函數
  • 以Test_開頭的類,不能包含_init_方法
  • 類中以test_開頭的方法

上面的默認規則我們是可以通過配置文件的設置來修改的

# file_name: pytest.ini

[pytest]
testpaths = xdist_study
python_files
= test*.py python_classes = Test* python_functions = test_*

testpaths:配置在哪個目錄下搜索測試用例,可自定義,可以配置多個,多個用空格隔開

python_files:用來配置搜索的測試用例的文件名稱,可自定義,可以配置多個,多個用空格隔開

python_classes:配置搜索的測試用例的類名,可自定義,可以配置多個,多個用空格隔開

python_functions:配置搜索的測試用例的方法名,可自定義,可以配置多個,多個用空格隔開

上面的配置表示:在xdist_study目錄下,搜索以test開頭,以.py結尾的文件,以Test開頭的類,以test_開頭的方法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM