在上一篇Python接口自動化測試系列文章:Python接口自動化淺析logging日志原理及模塊操作流程,主要介紹日志相關概念及l(fā)ogging日志模塊的操作流程。
而在此之前介紹過yaml封裝,數(shù)據(jù)驅(qū)動、配置文件、日志文件等獨立的功能,我們將這些串聯(lián)起來,形成一個完整的接口測試流程。
以下主要介紹將logging常用配置放入yaml配置文件、logging日志封裝及結(jié)合登錄用例講解日志如何在接口測試中運用。
將日志中的常用配置,比如日志器名稱、日志器等級及格式化放在配置文件中,在配置文件config.yaml中添加:
logger: name: ITester level: DEBUG format: '%(filename)s-%(lineno)d-%(asctime)s-%(levelname)s-%(message)s'
封裝logging類,讀取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()
在common目錄下新建文件logger_handler.py,用于存放封裝的logging類。
封裝思路:
這里截取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 ): # 設置收集器 super().__init__(name) # 設置收集器級別 self.setLevel(level) # 設置日志格式 fmt = logging.Formatter(format) # 如果存在文件,就設置文件處理器,日志輸出到文件 if file: file_handler = logging.FileHandler(file,encoding='utf-8') file_handler.setLevel(level) file_handler.setFormatter(fmt) self.addHandler(file_handler) # 設置StreamHandler,輸出日志到控制臺 stream_handler = logging.StreamHandler() stream_handler.setLevel(level) stream_handler.setFormatter(fmt) self.addHandler(stream_handler) # 從yaml配置文件中讀取logging相關配置 logger = LoggerHandler(name=yaml_data['logger']['name'], level=yaml_data['logger']['level'], file='../log/log.txt', format=yaml_data['logger']['format'])
在登錄用例中運用日志模塊,到底在登錄代碼的哪里使用日志?
接下來直接上代碼,在登錄用例中添加日志。
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): # 關閉session管理器 self.req.close_session() @ddt.data(*case_data) def test_login_success(self,items): logger.info('*'*88) logger.info('當前是第{}條用例:{}'.format(items['case_id'],items['case_title'])) logger.info('當前用例的測試數(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: # 斷言:預期結(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: # 將響應的狀態(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)操作的詳細內(nèi)容,更多關于Python接口自動化logging封裝的資料請關注腳本之家其它相關文章!