Pytest配置文件pytest.ini

pytest.ini 配置

pytest.ini 是什麼

  • pytest.ini 是 pytest 的配置文件
  • 可以修改 pytest 的默認行爲
  • 不能使用任何中文符號,包括漢字、空格、引號、冒號等等

pytest.ini

  • 修改用例的命名規則
  • 配置日誌格式,比代碼配置更方便
  • 添加標籤,防止運行過程報警告錯誤
  • 指定執行目錄
  • 排除搜索目錄

pytest 配置- 改變運行規則

# 執行check_開頭和 test_開頭的所有的文件,後面一定要加*
python_files = check_* test_*
# 執行所有的以Test和Check開頭的類
python_classes = Test*  Check*
# 執行所有以test_和check_開頭的方法
python_functions= test_* check_*

pytest 配置- 添加默認參數

addopts = -v -s --alluredir=./results

添加默認參數後,輸入pytest後,相當於下面這樣直接輸入一行,更方便

pytest 配置- 指定/忽略執行目錄

# 設置執行的路徑
testpaths = bilibili baidu
# 忽略某些文件夾/目錄
norecursedirs = result logs datas test_demo*

pytest 配置- 日誌

配置參考鏈接:pytest logging 收集日誌
pytest.ini 文件配置日誌級別,保存地址等內容。

  • 注意:
    windows系統 需要把中文 註釋去掉。
[pytest]
# 日誌開關 true false
log_cli = true

# 輸出到terminal
# 日誌級別
log_cli_level = info
# 打印詳細日誌,相當於命令行加 -vs
addopts = --capture=no
# 日誌格式
log_cli_format = %(asctime)s [%(levelname)s] %(message)s (%(filename)s:%(lineno)s)
# 日誌時間格式
log_cli_date_format = %Y-%m-%d %H:%M:%S

# 輸出到文件,log文件需要手動創建
# 日誌文件位置
log_file = ./log/test.log
# 日誌文件等級
log_file_level = info
# 日誌文件格式
log_file_format = %(asctime)s [%(levelname)s] %(message)s (%(filename)s:%(lineno)s)
# 日誌文件日期格式
log_file_date_format = %Y-%m-%d %H:%M:%S
# 可以動態生成log文件的名稱,不過需要的pytest版本比較高
@pytest.fixture(scope="session", autouse=True)
def manage_logs(request):
    """Set log file name same as test name"""
    now = time.strftime("%Y-%m-%d %H-%M-%S")
    log_name = 'output/log/' + now + '.logs'

    request.config.pluginmanager.get_plugin("logging-plugin") \
        .set_log_path(return_path(log_name))

總結 pytest.ini

  • 修改用例的命名規則
  • 配置日誌格式,比代碼配置更方便
  • 指定執行目錄
  • 排除搜索目錄
  • 添加標籤,防止運行過程報警告錯誤
  • 添加默認參數
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章