python pytest測試框架介紹五---日誌實時輸出
阿新 • • 發佈:2018-11-05
同樣的,在使用pytest進行自動化測試時,需要將實時日誌打印出來,而不是跑完後才在報告中出結果。
不過,好在pytest在3.3版本開始,就支援這一功能了,而不用再像nose一樣,再去裝第三方外掛。
網上也有相關實時的日誌輸入說明,但我嘗試後,不是我想要的,比如:pytest輸出Log
看看我們下面這樣一段程式碼,以unittest模式寫的:
#coding:utf-8 ''' Created on 2017年8月31日 @author: huzq ''' from __future__ import print_function import pytest fromunittest import TestCase from selenium import webdriver import logging,sys log = logging.getLogger(__name__) class TestClass(TestCase): @classmethod def setUpClass(cls): log.info('setup_class()') cls.driver = webdriver.Firefox() cls.driver.get("http://www.baidu.com") log.info("xxxxxxxxxxxxxxx") @classmethod def teardown_class(cls): log.info('teardown_class()') def setUp(self): log.info('\nsetup_method()') self.addCleanup(self.screen_shot) def screen_shot(self): log.info("yyyyyyyyyyyyyy") log.info("sereen_shot") def qqq(self): log.info("xxxxxxxxxxxqqqq") assert 4==5 #def teardown_method(self, method): def tearDown(self): log.info("ffjiafuiodafdfj___teardown") @pytest.mark.slow def test_7(self): import time time.sleep(10) log.info('- test_7()') @pytest.mark.qq def test_4(self): import pdb;pdb.set_trace() self.result=self.addCleanup(self.qqq) log.info('- test_4()') def test_5(self): log.info('- test_4()') assert 4==5
如果沒有加日誌實時輸出會是怎麼樣的,如下:
可以看出,日誌在過程中沒有實時輸出,在實際跑項目錄,這個有點不太好看。
解決:
看看pytest是怎麼解決的呢。
首先pytest是從pytest.ini中讀取log_cli配置的,預設是關閉的。如上圖中顯示,我們的pytest.ini檔案是空的
再看看pytest -h檔案:
關於log的help有以下:
--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.View Code
然後你還會發現一行:
[pytest] ini-options in the first pytest.ini|tox.ini|setup.cfg file found:
所以,有兩種方法解決
1) 在當前資料夾下寫pytest.ini或tox.ini或setup.cfg檔案,然後將日誌相關寫在裡面,如下:
[pytest] log_cli = 1 log_cli_level = INFO log_cli_format = %(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s) log_cli_date_format=%Y-%m-%d %H:%M:%S
這時就可以正常列印日誌出來。
2) 直接用pytest -o方式重寫,這個功能在pytest 3.4之後才實現,如下
pytest pytest_lean2.py -o log_cli=true -o log_cli_level=INFO
結果如下: