前言

pytest配置檔案可以改變pytest的執行方式,它是一個固定的檔案pytest.ini檔案,讀取配置資訊,按指定的方式去執行。

常用的配置項

marks

作用:測試用例中添加了自定義標記( @pytest.mark.xxx 裝飾器),如果不新增marks選項的話,就會報warnings

格式:list列表型別

寫法:

[pytest]
# 自定義標記說明
markers =
tencent: tencent
toutiao: toutiao
alibaba: alibaba

xfail_strict

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

格式:True 、False(預設),1、0

寫法:

[pytest]

# 自定義標記說明
markers =
tencent: tencent
toutiao: toutiao
alibaba: alibaba xfail_strict = True

上程式碼

@pytest.mark.xfail()
def test_case1():
a = "a"
b = "b"
assert a != b
  • 未設定 xfail_strict = True 時,測試結果顯示xpassed

  • 已設定 xfail_strict = True 時,測試結果顯示failed

addopts

作用:addopts引數可以更改預設命令列選項,這個當我們在cmd輸入一堆指令去執行用例的時候,就可以用該引數代替了,省去重複性的敲命令工作

比如:想測試完生成報告,失敗重跑兩次,一共執行兩次,如果在cmd中寫的話,命令會很長

pytest -v --rerun=2 --count=2 --html=report.html --self-contained-html

每次都這樣敲不太現實,addopts就可以完美解決這個問題

[pytest]

# 自定義標記說明
markers =
tencent: tencent
toutiao: toutiao
alibaba: alibaba xfail_strict = True # 命令列引數
addopts = -v --reruns=1 --count=2 --html=reports.html --self-contained-html

log_cli

作用:控制檯實時輸出日誌

格式:log_cli=True 或False(預設),或者log_cli=1 或 0

log_cli=0執行結果

log_cli=1執行結果

加了log_cli=1之後,可以清晰看到哪個package下的哪個module下的哪個測試用例是否passed還是failed

norecursedirs

作用:pytest 收集測試用例時,會遞迴遍歷所有子目錄,包括某些你明知道沒必要遍歷的目錄,遇到這種情況,可以使用 norecursedirs 引數簡化 pytest 的搜尋工作

預設設定: norecursedirs = .* build dist CVS _darcs {arch} *.egg

正確寫法:多個路徑用空格隔開

舉個,想要不遍歷 venv、src、resources、log、report、util資料夾,可以進行如下設定

[pytest]

norecursedirs = .* build dist CVS _darcs {arch} *.egg venv src resources log report util

更改測試用例收集規則

pytest預設的測試用例收集規則

檔名以 test_*.py 檔案和 *_test.py

以 test_ 開頭的函式

以 Test 開頭的類,不能包含 init 方法

以 test_ 開頭的類裡面的方法

我們是可以修改或者新增這個用例收集規則的(建議在原有的規則上新增),如下配置

[pytest]

python_files =     test_*  *_test  test*
python_classes = Test* test*
python_functions = test_* test*

注意事項

pytest.ini檔案應該放在專案根目錄下,不要修改名字,否則無法被識別

整理參考

小菠蘿測試筆記