前言
保存工作中常用的日志一般來說有兩種方式。
①pytest測試框架有自己的日志管理開關。(如果開啟pytest測試框架的日志功能,則pytest命令行方式運行測試用例時,在Terminal終端同樣會打印日志信息。)
【注意】同時滿足①開啟pytest測試框架的日志功能②使用python的日志庫兩個條件,Terminal終端打印的日志格式以及日志級別是我們在log模塊中設置的格式。


log_cli參數為true:


log_cli參數為false:

②使用python的日志庫。(一般使用此種方式記錄用例執行期間的日志)
【注意】當單獨運行單個模塊的測試用例時,日志內容會根據log配置模塊中設置的日志格式以及級別來打印或者保存(比如log等級為error會打印至控制台,log等級為info會保存至log文件),而命令行方式運行時,
一般來說,在測試用例的執行過程中日志記錄沒有實時輸出或者保存至日志文件。顯得測試用例的執行結果不夠權威。(根據日志的級別將日志分發至不同的終端)
【注意】在項目中應用:①log設置模塊;②pytest測試框架日志log_cli參數為true。(這樣保證不管是單獨運行某個模塊的測試用例或者是pytest命令行方式運行測試用例都可以在控制台或者Terminal終端查看到相應的日志信息)
pytest測試框架關於log的命令行參數如下:
--no-print-logs disable printing caught logs on failed tests. --log-level=LOG_LEVEL logging level used by the logging module --log-format=LOG_FORMAT log format as used by the logging module. --log-date-format=LOG_DATE_FORMAT log date format as used by the logging module. --log-cli-level=LOG_CLI_LEVEL cli logging level. --log-cli-format=LOG_CLI_FORMAT log format as used by the logging module. --log-cli-date-format=LOG_CLI_DATE_FORMAT log date format as used by the logging module. --log-file=LOG_FILE path to a file when logging will be written to. --log-file-level=LOG_FILE_LEVEL log file logging level. --log-file-format=LOG_FILE_FORMAT log format as used by the logging module. --log-file-date-format=LOG_FILE_DATE_FORMAT log date format as used by the logging module.
還有一行:
[pytest] ini-options in the first pytest.ini|tox.ini|setup.cfg file found:
具體操作
①首先pytest測試框架是從pytest.ini中讀取log_cli配置的,默認是關閉的即false。【log_cli參數為true代表開啟pytest測試框架自己的日志功能,為false表示關閉。】
②在文件根目錄下新建一個pytest.ini或tox.ini或setup.cfg文件,然后將日志相關寫入,如下:
[pytest] log_cli=true ; # 開啟日記 log_level=NOTSET ; # 日志等級 log_format = %(asctime)s %(levelname)s %(message)s # 日記日期 log_date_format = %Y-%m-%d %H:%M:%S # 日記時間 addopts = -vs # 日志執行的命令 log_file = ./test.log # 日志存放地方 log_file_level = info # 記錄日志等級 log_file_format = %(asctime)s %(levelname)s %(message)s # 同記錄時間一樣 log_file_date_format = %Y-%m-%d %H:%M:%S
③可以使用用pytest -o方式重寫(即覆蓋ini文件中的log相關的命令行參數);這個功能在pytest 3.4版本之后才實現,如下:
pytest pytest_lean2.py -o log_cli=true -o log_cli_level=INFO
