主頁 > 知識庫 > Python接口自動化淺析logging封裝及實戰(zhàn)操作

Python接口自動化淺析logging封裝及實戰(zhàn)操作

熱門標簽:西藏房產(chǎn)智能外呼系統(tǒng)要多少錢 地圖標注審核表 宿遷星美防封電銷卡 外呼并發(fā)線路 湛江智能外呼系統(tǒng)廠家 ai電話機器人哪里好 ai電銷機器人源碼 長沙高頻外呼系統(tǒng)原理是什么 百度地圖標注沒有了

在上一篇Python接口自動化測試系列文章:Python接口自動化淺析logging日志原理及模塊操作流程,主要介紹日志相關概念及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
                 ):
        # 設置收集器
        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'])

四、logging實戰(zhàn)

在登錄用例中運用日志模塊,到底在登錄代碼的哪里使用日志?

  • 將讀取的用例數(shù)據(jù)寫入日志、用來檢查當前的用例數(shù)據(jù)是否正確;
  • 將用例運行的結(jié)果寫入日志,用來檢查用例運行結(jié)果是否與預期一致;
  • 將斷言失敗的錯誤信息寫入日志。

接下來直接上代碼,在登錄用例中添加日志。

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封裝的資料請關注腳本之家其它相關文章!

您可能感興趣的文章:
  • Python日志模塊logging簡介
  • Python基礎之logging模塊知識總結(jié)
  • Python 解決logging功能使用過程中遇到的一個問題
  • Python的logging模塊基本用法
  • Python logging簡介詳解

標簽:林芝 大同 寧夏 普洱 海南 漯河 盤錦 南平

巨人網(wǎng)絡通訊聲明:本文標題《Python接口自動化淺析logging封裝及實戰(zhàn)操作》,本文關鍵詞  Python,接口,自動化,淺析,;如發(fā)現(xiàn)本文內(nèi)容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《Python接口自動化淺析logging封裝及實戰(zhàn)操作》相關的同類信息!
  • 本頁收集關于Python接口自動化淺析logging封裝及實戰(zhàn)操作的相關信息資訊供網(wǎng)民參考!
  • 企业400电话

    智能AI客服机器人
    15000

    在线订购

    合计11份范本:公司章程+合伙协议+出资协议+合作协议+股权转让协议+增资扩股协议+股权激励+股东会决议+董事会决议

    推薦文章