Python接口自動化淺析logging封裝及實戰(zhàn)操作
在上一篇Python接口自動化測試系列文章:Python接口自動化淺析logging日志原理及模塊操作流程,主要介紹日志相關(guān)概念及l(fā)ogging日志模塊的操作流程。
而在此之前介紹過yaml封裝,數(shù)據(jù)驅(qū)動、配置文件、日志文件等獨立的功能,我們將這些串聯(lián)起來,形成一個完整的接口測試流程。
以下主要介紹將logging常用配置放入yaml配置文件、logging日志封裝及結(jié)合登錄用例講解日志如何在接口測試中運用。
一、yaml配置文件
將日志中的常用配置,比如日志器名稱、日志器等級及格式化放在配置文件中,在配置文件config.yaml中添加:
logger: name: ITester level: DEBUG format: '%(filename)s-%(lineno)d-%(asctime)s-%(levelname)s-%(message)s'
封裝logging類,讀取yaml中的日志配置。
二、讀取yaml
之前讀寫yaml配置文件的類已經(jīng)封裝好,愉快的拿來用即可,讀取yaml配置文件中的日志配置。
yaml_handler.py
import yaml class YamlHandler: def __init__(self, file): self.file = file def read_yaml(self, encoding='utf-8'): """讀取yaml數(shù)據(jù)""" with open(self.file, encoding=encoding) as f: return yaml.load(f.read(), Loader=yaml.FullLoader) def write_yaml(self, data, encoding='utf-8'): """向yaml文件寫入數(shù)據(jù)""" with open(self.file, encoding=encoding, mode='w') as f: return yaml.dump(data, stream=f, allow_unicode=True) yaml_data = YamlHandler('../config/config.yaml').read_yaml()
三、封裝logging類
在common目錄下新建文件logger_handler.py,用于存放封裝的logging類。
封裝思路:
- 首先分析一下,logging中哪些數(shù)據(jù)可以作為參數(shù)?比如日志器名稱、日志等級、日志文件路徑、輸出格式,可以將這些放到__init__方法里,作為參數(shù)。
- 其次,要判斷日志文件是否存在,存在就將日志輸出到日志文件中。
- 最后,logging模塊已經(jīng)封裝好了Logger類,可以直接繼承,減少代碼量。
這里截取logging模塊中Logger類的部分源碼。
class Logger(Filterer): """ Instances of the Logger class represent a single logging channel. A "logging channel" indicates an area of an application. Exactly how an "area" is defined is up to the application developer. Since an application can have any number of areas, logging channels are identified by a unique string. Application areas can be nested (e.g. an area of "input processing" might include sub-areas "read CSV files", "read XLS files" and "read Gnumeric files"). To cater for this natural nesting, channel names are organized into a namespace hierarchy where levels are separated by periods, much like the Java or Python package namespace. So in the instance given above, channel names might be "input" for the upper level, and "input.csv", "input.xls" and "input.gnu" for the sub-levels. There is no arbitrary limit to the depth of nesting. """ def __init__(self, name, level=NOTSET): """ Initialize the logger with a name and an optional level. """ Filterer.__init__(self) self.name = name self.level = _checkLevel(level) self.parent = None self.propagate = True self.handlers = [] self.disabled = False def setLevel(self, level): """ Set the logging level of this logger. level must be an int or a str. """ self.level = _checkLevel(level)
接下來,我們開始封裝logging類。
logger_handler.py
import logging from common.yaml_handler import yaml_data class LoggerHandler(logging.Logger): # 繼承Logger類 def __init__(self, name='root', level='DEBUG', file=None, format=None ): # 設(shè)置收集器 super().__init__(name) # 設(shè)置收集器級別 self.setLevel(level) # 設(shè)置日志格式 fmt = logging.Formatter(format) # 如果存在文件,就設(shè)置文件處理器,日志輸出到文件 if file: file_handler = logging.FileHandler(file,encoding='utf-8') file_handler.setLevel(level) file_handler.setFormatter(fmt) self.addHandler(file_handler) # 設(shè)置StreamHandler,輸出日志到控制臺 stream_handler = logging.StreamHandler() stream_handler.setLevel(level) stream_handler.setFormatter(fmt) self.addHandler(stream_handler) # 從yaml配置文件中讀取logging相關(guān)配置 logger = LoggerHandler(name=yaml_data['logger']['name'], level=yaml_data['logger']['level'], file='../log/log.txt', format=yaml_data['logger']['format'])
四、logging實戰(zhàn)
在登錄用例中運用日志模塊,到底在登錄代碼的哪里使用日志?
- 將讀取的用例數(shù)據(jù)寫入日志、用來檢查當(dāng)前的用例數(shù)據(jù)是否正確;
- 將用例運行的結(jié)果寫入日志,用來檢查用例運行結(jié)果是否與預(yù)期一致;
- 將斷言失敗的錯誤信息寫入日志。
接下來直接上代碼,在登錄用例中添加日志。
test_login.py
import unittest from common.requests_handler import RequestsHandler from common.excel_handler import ExcelHandler import ddt import json from common.logger_handler import logger @ddt.ddt class TestLogin(unittest.TestCase): # 讀取excel中的數(shù)據(jù) excel = ExcelHandler('../data/cases.xlsx') case_data = excel.read_excel('login') print(case_data) def setUp(self): # 請求類實例化 self.req = RequestsHandler() def tearDown(self): # 關(guān)閉session管理器 self.req.close_session() @ddt.data(*case_data) def test_login_success(self,items): logger.info('*'*88) logger.info('當(dāng)前是第{}條用例:{}'.format(items['case_id'],items['case_title'])) logger.info('當(dāng)前用例的測試數(shù)據(jù):{}'.format(items)) # 請求接口 res = self.req.visit(method=items['method'],url=items['url'],json=json.loads(items['payload']), headers=json.loads(items['headers'])) try: # 斷言:預(yù)期結(jié)果與實際結(jié)果對比 self.assertEqual(res['code'], items['expected_result']) logger.info(res) result = 'Pass' except AssertionError as e: logger.error('用例執(zhí)行失?。簕}'.format(e)) result = 'Fail' raise e finally: # 將響應(yīng)的狀態(tài)碼,寫到excel的第9列,即寫入返回的狀態(tài)碼 TestLogin.excel.write_excel("../data/cases.xlsx", 'login', items['case_id'] + 1, 9, res['code']) # 如果斷言成功,則在第10行(測試結(jié)果)寫入Pass,否則,寫入Fail TestLogin.excel.write_excel("../data/cases.xlsx", 'login', items['case_id'] + 1, 10, result) if __name__ == '__main__': unittest.main()
控制臺日志輸出部分截圖:
日志文件輸出部分截圖:
以上就是Python接口自動化淺析logging封裝及實戰(zhàn)操作的詳細(xì)內(nèi)容,更多關(guān)于Python接口自動化logging封裝的資料請關(guān)注本站其它相關(guān)文章!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。