Pytest系列(三)配置檔案
阿新 • • 發佈:2020-08-27
一、pytest 配置檔案使用
pytest 命令列執行時,每次都需要帶入各種各樣的引數,比較麻煩,我們可以將 pytest 執行的引數定義在配置檔案中,這個檔案可以是 pytest.ini ,pyproject.toml,tox.ini, setup.cfg 檔案(通常位於專案根目錄下),這樣每次執行時只需要輸入 pytest 命令就可以了。
更多配置選項可參考官方文件:https://docs.pytest.org/en/latest/reference.html#ini-options-ref,也可以使用 pytest -h 找到 [pytest] ini-options 這一部分來檢視所有的配置項。
二、pytest.ini 檔案
pytest.ini 檔案中不能有中文,註釋也不行,可能出現編碼錯誤。基礎 pytest.ini 配置檔案如下:
# pytest.ini 檔案 [pytest] # 執行測試所需的最低 pytest 版本 minversion = 6.0 # 新增命令列執行引數 addopts = -s --maxfail=2 -rf # 啟用控制檯日誌輸出,預設為false log_cli = True # 日誌寫入檔案 log_file = logs/pytest_logs.txt # 格式化輸出到日誌檔案中的日誌日期 log_file_date_format = %Y-%m-%d %H:%M:%S # 格式化輸出到日誌檔案中的日誌訊息 log_file_format = %(asctime)s %(levelname)s %(message)s # 設定輸出到日誌檔案的日誌級別 log_file_level = INFO # 格式化輸出到控制檯的日誌訊息 log_format = %(asctime)s %(levelname)s %(message)s # 設定輸出到控制檯的日誌級別 log_level = INFO # 配置測試搜尋的路徑 testpaths = ./testcases # 配置測試搜尋的檔案 python_files = test_*.py # 配置測試搜尋的類名 python_classes = Test* # 配置測試搜尋的測試用例名 python_functions = test* # 如果測試用例中添加了 @pytest.mark.webtest,配置檔案中不新增 markers 選項就會報 warnings markers = weibo: this is weibo page toutiao: toutiao # 將標記為 @pytest.mark.xfail 的用例設定為失敗,不論測試是否通過 xfail_strict = True # pytest.ini 檔案配置完成後,直接在命令列使用 pytest 即可執行測試
三、tox.ini 檔案
tox.ini 檔案是 tox 專案的配置檔案,也可以用於儲存 pytest 配置
# tox.ini 檔案
[pytest]
minversion=6.0
addopts=-ra -q
testpaths=
tests
integration
四、setup.cfg 檔案
setup.cfg 檔案是通用配置檔案,最初由 distutils 使用,也可以通過section [tool:pytest] 來儲存 pytest 配置
# setup.cfg 檔案 [tool:pytest] minversion=6.0 addopts=-ra -q testpaths= tests integration