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)文章!
相關(guān)文章
基于Python繪制美觀動態(tài)圓環(huán)圖、餅圖
這篇文章主要介紹了基于Python制作美觀動態(tài)圓環(huán)圖、餅圖,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-06-06利用Python模擬登錄pastebin.com的實現(xiàn)方法
這篇文章主要介紹了利用Python模擬登錄pastebin.com的實現(xiàn)方法,本文圖文并茂給大家介紹的非常詳細(xì),具有一定的參考借鑒價值 ,需要的朋友可以參考下2019-07-07Pytorch自動求導(dǎo)函數(shù)詳解流程以及與TensorFlow搭建網(wǎng)絡(luò)的對比
PyTorch是一個開源的Python機(jī)器學(xué)習(xí)庫,基于Torch,用于自然語言處理等應(yīng)用程序。2017年1月,由Facebook人工智能研究院(FAIR)基于Torch推出了PyTorch,這篇文章主要介紹了Pytorch自定義自動求導(dǎo)函數(shù),以及PyTorch與TensorFlow搭建網(wǎng)絡(luò)的對比2021-11-11Python中使用pprint函數(shù)進(jìn)行格式化輸出的教程
這篇文章主要介紹了Python中使用pprint函數(shù)進(jìn)行格式化輸出的教程,包括能夠控制輸出寬度等非常有用的特性,需要的朋友可以參考下2015-04-04python 中 .py文件 轉(zhuǎn) .pyd文件的操作
這篇文章主要介紹了python 中 .py文件 轉(zhuǎn) .pyd文件的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03