Python測試框架pytest命令行參數用法
在Shell執行pytest -h
可以看到pytest的命令行參數有這10大類,共132個
序號 |
類別 | 中文名 | 包含命令行參數數量 |
---|---|---|---|
1 | positional arguments | 形參 | 1 |
2 | general | 通用 | 31 |
3 | reporting | 報告 | 18 |
4 | collection | 收集 | 15 |
5 | test session debugging and configuration | 測試session調試和配置 | 11 |
6 | pytest-warnings | pytest警告 | 1 |
7 | logging | 日誌 | 11 |
8 | reporting-allure | allure測試報告 | 3 |
9 | ini-options | pytest.ini/tox.ini/setup.cfg 配置文件 |
37 |
10 | environment variables | 環境變數 | 4 |
1.positional arguments
file_or_dir
指定一個或多個文件/目錄
pytest [file_or_dir] [file_or_dir] [...]
2.general
-k EXPRESSION
名字包含test_method或test_other的函數或類
-k "test_method or test_other"
名字不包含test_method
-k "not test_method"
名字不包含test_method不包含test_other
-k 'not test_method and not test_other'
大小寫敏感。
源碼這裡不是很明白,先放這,以後再補充解釋吧
@classmethod
def from_item(cls, item: "Item") -> "KeywordMatcher":
mapped_names = set()
# Add the names of the current item and any parent items.
import pytest
for node in item.listchain():
if not isinstance(node, (pytest.Instance, pytest.Session)):
mapped_names.add(node.name)
# Add the names added as extra keywords to current or parent items.
mapped_names.update(item.listextrakeywords())
# Add the names attached to the current function through direct assignment.
function_obj = getattr(item, "function", None)
if function_obj:
mapped_names.update(function_obj.__dict__)
# Add the markers to the keywords as we no longer handle them correctly.
mapped_names.update(mark.name for mark in item.iter_markers())
return cls(mapped_names)
-m MARKEXPR
包含mark1,不包含mark2
-m 'mark1 and not mark2'
–markers
顯示markers
pytest --markers
-x, –exitfirst
第一個error或failed的test就退出,2個參數等價
pytest -x
pytest --exitfirst
–maxfail=num
2個errors或failures就退出
pytest --maxfail=2
–strict-config
解析配置文件中pytest
部分時,遇到warning就拋出error
pytest --strict-config
-c file
從my.ini
文件載入配置
pytest -c my.ini
–continue-on-collection-errors
收集test失敗,仍然強制繼續執行
pytest --continue-on-collection-errors
–rootdir=ROOTDIR
tests根目錄,相對路徑
pytest --rootdir="root_dir"
pytest --rootdir="./root_dir"
pytest --rootdir="root_dir/another_dir/"
絕對路徑
pytest --rootdir="/home/user/root_dir"
帶變數
pytest --rootdir="$HOME/root_dir"
–fixtures, –funcargs
顯示fixtures,以下等價
pytest --fixtures
pytest --funcargs
顯示以_開頭的fixture
pytest --fixtures -v
–fixtures-per-test
顯示每個test用到的fixture
pytest --fixtures-per-test
–pdb
在errors或KeyboardInterrupt時,啟用默認Python debugger
pytest --pdb
–pdbcls=modulename:classname
啟用自定義Python debugger,由IPython.terminal.debugger
module下的TerminalPdb
class定義
pytest --pdbcls=IPython.terminal.debugger:TerminalPdb
–trace
run每個test時break,進入debugger交互
pytest --trace
–capture=method
文件描述符(默認)
pytest --capture=fd
stdout/stderr 記憶體
pytest --capture=sys
顯示print
pytest --capture=no
tee-sys
pytest --capture=tee-sys
-s
等價於--capture=no
–runxfail
強制運行xfail標記的test
pytest --runxfail
–lf, –last-failed
重跑上次失敗的tests,如果沒有失敗就重跑全部,以下等價
pytest -lf
pytest --last-failed
–ff, –failed-first
優先跑上次失敗的test,tests的順序會被打亂,以下等價
pytest -ff
pytest --failed-first
–nf, –new-first
優先跑新添加的tests,剩餘的按文件mtime順序,以下等價
pytest --nf
pytest --new-first
–cache-show=[CACHESHOW]
顯示快取,默認*
pytest --cache-show
顯示快取,帶參數cache\nodeids
pytest --cache-show=cache\nodeids
–cache-clear
運行開始時清快取
pytest --cache-clear
–lfnf={all,none}, –last-failed-no-failures={all,none}
沒有last-failed快取數據,或上次沒有失敗時,
跑全部tests
pytest --lfnf=all
pytest --last-failed-no-failures=all
不運行
pytest --lfnf=none
pytest --last-failed-no-failures=none
–sw, –stepwise
逐步運行,在失敗時退出,下次運行時從失敗的用例開始
pytest -sw
pytest --stepwise
–stepwise-skip
跳過第一個失敗的test,如果再遇到失敗就退出
pytest --stepwise-skip
–allure-severities=SEVERITIES_SET
指定allure severities運行
pytest --allure-severities=blocker, critical, normal, minor, trivial
–allure-epics=EPICS_SET
指定allure epics運行
pytest --allure-epics=my_epic
–allure-features=FEATURES_SET
指定allure features運行
pytest --allure-features=my_feature
–allure-stories=STORIES_SET
指定allure stories運行
pytest --allure-stories=my_story
–allure-link-pattern=LINK_TYPE:LINK_PATTERN
不知道怎麼用,溜了溜了
pytest --allure-link-pattern=
3.reporting
–durations=N
顯示2個最慢的setup/test的耗時
pytest --durations=2
顯示所有耗時
pytest --durations=0
-v, –verbose
輸出詳細資訊
pytest -v
pytest --verbose
-q, –quiet
輸出簡要資訊
pytest -q
pytest --quiet
–verbosity=VERBOSE
設置資訊顯示等級為2
pytest --verbosity=2
-r chars
默認”fE”
顯示failed的資訊
pytest -r f
顯示Error的資訊
pytest -r E
顯示skipped的資訊
pytest -r s
顯示xfailed的資訊
pytest -r x
顯示Xpassed的資訊
pytest -r X
顯示passed的資訊
pytest -r p
顯示Passed with output的資訊
pytest -r P
顯示all except passed的資訊
pytest -r a
pytest -r A
顯示warnings are enabled by default (–disable-warnings)的資訊
pytest -r w
重置list
pytest -r N
-l, –showlocals
在tracebacks中顯示局部變數,默認不顯示
pytest -l
pytest --showlocals
–tb=style
traceback列印模式
pytest --tb=auto
pytest --tb=long
pytest --tb=short
pytest --tb=line
pytest --tb=native
pytest --tb=no
–show-capture
失敗的tests如何顯示,默認”all”
pytest --show-capture=no
pytest --show-capture=stdout
pytest --show-capture=stderr
pytest --show-capture=log
pytest --show-capture=all
–full-trace
不截取traceback,默認會截斷
pytest --full-trace
–color=color
顯示顏色
pytest --color=yes
不顯示顏色
pytest --color=no
自動
pytest --color=auto
–pastebin=mode
沒什麼用
pytest --pastebin=mode
–junit-xml=path
創建junit-xml風格的測試報告
pytest --junit-xml=path
–junit-prefix=str
junit-xml輸出中的classnames添加前綴hello
pytest --junit-prefix="hello"
–result-log=path
不建議使用
pytest --result-log=path
4.collection
–collect-only, –co
只收集,不執行。可以用來統計寫了多少條自動化用例
pytest --collect-only
pytest --co
–pyargs
把所有參數解釋為python包(package)
pytest --pyargs
–ignore=path
忽略不收集,可以多個(逗號隔開)
pytest --ignore=path1,path2,path3
–ignore-glob=path
path匹配,可以多個(逗號隔開)
pytest --ignore-glob="*_01.py"
–deselect=nodeid_prefix
通過node id prefix反選。可以多個(逗號隔開)
取消選擇tests/foobar/test_foobar_01.py::test_a
--deselect="tests/foobar/test_foobar_01.py::test_a"
–confcutdir=dir
只載入相對於tests/foobar/目錄的conftest.py文件
pytest --confcutdir="tests/foobar/"
–noconftest
不載入conftest.py文件
pytest --noconftest
–keep-duplicates
收集重複的test文件,默認只會收集1item,加參數後會收集2items
pytest test.py test.py --keep-duplicates
–collect-in-virtualenv
收集本地虛擬環境目錄的tests
pytest --collect-in-virtualenv
–doctest-modules
doctest沒啥用
pytest --doctest-modules
–doctest-report={none,cdiff,ndiff,udiff,only_first_failure}
doctest沒啥用
pytest --doctest-report={none,cdiff,ndiff,udiff,only_first_failure}
–doctest-glob=pat
doctest沒啥用
pytest --doctest-glob=pat
–doctest-ignore-import-errors
doctest沒啥用
pytest --doctest-ignore-import-errors
–doctest-continue-on-failure
doctest沒啥用
pytest --doctest-continue-on-failure
5.test session debugging and configuration
–basetemp=dir
test run的base臨時目錄(如果存在會先刪除)
pytest --basetemp=dir
-V, –version
pytest版本
pytest -V
pytest --version
-h, –help
pytest幫助
pytest -h
pytest --help
-p name
載入plugin module或 entry point
pytest -p name
不載入doctest
pytest -p no:doctest
–trace-config
查看本地安裝好的第三方插件
pytest --trace-config
–debug
保存debug資訊到’pytestdebug.log’文件
pytest --debug
-o OVERRIDE_INI, –override-ini=OVERRIDE_INI
覆蓋ini文件配置
pytest -o xfail_strict=True -o cache_dir=cache
pytest --override-ini=OVERRIDE_INI
–assert=MODE
默認rewrite
pytest --assert=rewrite
無assertion debugging
pytest --assert=plain
–setup-only
只setup fixtures,不執行tests
pytest --setup-only
–setup-show
執行tests的時候顯示fixture setup
pytest --setup-show
–setup-plan
顯示fixtures和tests計劃會執行什麼,但是不執行
也可以用來統計自動化用例
pytest --setup-plan
6.pytest-warnings
-W PYTHONWARNINGS, –pythonwarnings=PYTHONWARNINGS
設置報告哪些warnings
pytest -W PYTHONWARNINGS
pytest --pythonwarnings=PYTHONWARNINGS
7.logging
推薦直接使用loguru第三方庫。
–log-level=LEVEL
默認沒有設置,依賴log handler
WARNING DEBUG INFO ERROR
pytest --log-level=LEVEL
–log-format=LOG_FORMAT
日誌格式
pytest --log-format="%(asctime)s %(levelname)s %(message)s"
–log-date-format=LOG_DATE_FORMAT
日期格式
pytest --log-date-format="%Y-%m-%d %H:%M:%S"
–log-cli-level=LOG_CLI_LEVEL
cli日誌級別
pytest --log-cli-level=LOG_CLI_LEVEL
–log-cli-format=LOG_CLI_FORMAT
cli日誌格式
pytest --log-cli-format="%(asctime)s %(levelname)s %(message)s"
–log-cli-date-format=LOG_CLI_DATE_FORMAT
cli日誌級別
pytest --log-cli-date-format="%Y-%m-%d %H:%M:%S"
–log-file=LOG_FILE
日誌文件路徑
pytest --log-file=LOG_FILE
–log-file-level=LOG_FILE_LEVEL
日誌文件級別
pytest --log-file-level=LOG_FILE_LEVEL
–log-file-format=LOG_FILE_FORMAT
日誌文件格式
pytest --log-file-format="%(asctime)s %(levelname)s %(message)s"
–log-file-date-format=LOG_FILE_DATE_FORMAT
日誌文件日期
pytest --log-file-date-format="%Y-%m-%d %H:%M:%S"
–log-auto-indent=LOG_AUTO_INDENT
自動換行
true|flase on|off
pytest --log-auto-indent=LOG_AUTO_INDENT
8.reporting-allure
–alluredir=DIR
allure數據生成目錄,注意不是html哦,而是json文件,需要allure generate data_dir -o html_dir
才能生成html
pytest --alluredir=DIR
–clean-alluredir
如果存在alluredir,先清除
pytest --clean-alluredir
–allure-no-capture
報告不捕獲pytest的logging/stdout/stderr資訊
pytest --allure-no-capture
9.ini-options
ini文件用例設置一些初始化默認值。
部分內容其實質跟參數是一樣用法。
markers (linelist)
自定義marker
# pytest.ini
[pytest]
markers =
webtest: Run the webtest case
hello: Run the hello case
empty_parameter_set_mark (string)
默認情況下,如果@pytest.mark.parametrize
的argnames
中的參數沒有接收到任何的實參的話,用例的結果將會被置為SKIPPED
;empty_parameter_set_mark可以設置為skip、xfail、fail_at_collect。
norecursedirs (args)
忽略一些目錄
# pytest.ini
[pytest]
norecursedirs = .* build dist CVS _darcs {arch} *.egg venv src
testpaths (args)
指定目錄
# pytest.ini
[pytest]
testpaths = test_path
usefixtures (args)
默認使用fixtures。
python_files (args)
glob文件匹配模式的python test modules。
python_classes (args)
前綴/glob文件匹配模式的python test classes。
python_functions (args)
前綴/glob文件匹配模式的python test functions。
ty_support (bool)
有風險,沒用。
console_output_style (string)
控制台輸出樣式
- classic 經典樣式
- progress: 帶進度百分比
- count 計數而不是百分比
xfail_strict (bool)
默認false,true時@pytest.mark.xfail的test,會被強制失敗,即使是成功的。
enable_assertion_pass_hook (bool)
確保刪除之前生成的pyc快取文件。
junit_suite_name (string)
不用學。
junit_logging (string)
不用學。
junit_log_passing_tests (bool)
不用學。
junit_duration_report (string)
不用學。
junit_family (string)
不用學。
doctest_optionflags (args)
不用學。
doctest_encoding (string)
不用學。
cache_dir (string)
快取目錄。
filterwarnings (linelist)
同 -W/–pythonwarnings。
log_level (string)
同命令行參數。
log_format (string)
同命令行參數。
log_date_format (string)
同命令行參數。
log_cli (bool)
true,test run的時候,實時顯示日誌。
log_cli_level (string)
同命令行參數。
log_cli_format (string)
同命令行參數。
log_cli_date_format (string)
同命令行參數。
log_file (string)
同命令行參數。
log_file_level (string)
同命令行參數。
log_file_format (string)
同命令行參數。
log_file_date_format (string)
同命令行參數。
log_auto_indent (string)
同命令行參數。
faulthandler_timeout (string)
如果test的運行時間超過設定的時間(超時),會列印相關traceback。
addopts (args)
執行時帶的默認參數,可以避免每次都要輸入一遍
addopts = -rsxX -v --reruns=1 --count=2
minversion (string)
pytest最小版本號。如果pytest低於這個版本,運行會報錯。
required_plugins (args)
必須的插件。
10.environment variables
PYTEST_ADDOPTS
命令行選項
export PYTEST_ADDOPTS=
PYTEST_PLUGINS
包含應作為插件載入的以逗號分隔的模組列表
export PYTEST_PLUGINS=mymodule.plugin,xdist
PYTEST_DISABLE_PLUGIN_AUTOLOAD
禁用插件自動載入
export PYTEST_DISABLE_PLUGIN_AUTOLOAD=
PYTEST_DEBUG
啟用pytest調試
export PYTEST_DEBUG=
版權申明:本文為部落客原創文章,轉載請保留原文鏈接及作者。
如果您喜歡我寫的文章,請關注公眾號支援一下,謝謝哈哈哈。