python+selenium(9)---用例中新增日誌
阿新 • • 發佈:2021-02-01
技術標籤:selenium
在工程中新增一個日誌模組
我們採用的是在用例中拋異常,列印日誌。列印日誌使用的是logging
log.py如下:
import logging from logging import handlers class Logger(object): level_relations = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'crit': logging.CRITICAL } # 日誌級別關係對映 def __init__(self, filename, level='info', when='D', backCount=3, fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'): self.logger = logging.getLogger(filename) format_str = logging.Formatter(fmt) # 設定日誌格式 self.logger.setLevel(self.level_relations.get(level)) # 設定日誌級別 sh = logging.StreamHandler() # 往螢幕上輸出 sh.setFormatter(format_str) # 設定螢幕上顯示的格式 th = handlers.TimedRotatingFileHandler(filename=filename, when=when, backupCount=backCount, encoding='utf-8') # 往檔案裡寫入#指定間隔時間自動生成檔案的處理器 # 例項化TimedRotatingFileHandler # interval是時間間隔,backupCount是備份檔案的個數,如果超過這個個數,就會自動刪除,when是間隔的時間單位,單位有以下幾種: # S 秒 # M 分 # H 小時、 # D 天、 # W 每星期(interval==0時代表星期一) # midnight 每天凌晨 th.setFormatter(format_str) # 設定檔案裡寫入的格式 self.logger.addHandler(sh) # 把物件加到logger裡 self.logger.addHandler(th) if __name__ == '__main__': log = Logger('run.log', level='debug') log.logger.debug('debug') log.logger.info('info') log.logger.warning('警告') log.logger.error('報錯') log.logger.critical('嚴重') Logger('error.log', level='error').logger.error('error')
在conftest.py中將其引數化:
from log.log import Logger
@pytest.fixture(scope="session")
def log():
log = Logger('F:\\selenium\\IRS\\log\\run.log', level='info')
return log
在測試用例中呼叫:
from case.public import Public import time import pytest test_login_data = [("admin", "123456"), ("root", "admin")] @pytest.mark.parametrize("user,pw", test_login_data) # 用來傳遞引數,user,pw引數名稱 def test_dengluyz(browser, user, pw, log): # dr = webdriver.Chrome()在conftest.py中已經封裝了函式為browser,直接在用例中呼叫該方法 # 引用封裝好的登入模組,注意引數值需要用引號引起來 public = Public() public.login_in(browser, user, pw) time.sleep(5) now_url = browser.current_url # 這就是斷言 try: assert now_url == "http://127.0.0.1:8989/index.html" log.logger.info("使用者名稱{0},密碼{1}登入成功".format(user, pw)) except AssertionError: msg = "使用者名稱{0},密碼{1}斷言失敗,返回url{2}".format(user, pw, now_url) log.logger.error(msg) pytest.fail(msg) finally: log.logger.info("使用者名稱{0},密碼{1}登入驗證完成".format(user, pw))
執行用例,列印的日誌如下:
額外插入關於format的使用:
它增強了字串格式化的功能。基本語法是通過{}和:來代替以前的%
log.logger.info("使用者名稱{0},密碼{1}登入驗證完成".format(user, pw) ----0對應的是user,1對應的是pw