Python接口自动化浅析logging封装及实战操作

作者:软件测试自动化测试 时间:2022-12-04 12:21:44 

在上一篇Python接口自动化测试系列文章:Python接口自动化浅析logging日志原理及模块操作流程,主要介绍日志相关概念及logging日志模块的操作流程。

而在此之前介绍过yaml封装,数据驱动、配置文件、日志文件等独立的功能,我们将这些串联起来,形成一个完整的接口测试流程。

以下主要介绍将logging常用配置放入yaml配置文件、logging日志封装及结合登录用例讲解日志如何在接口测试中运用。

一、yaml配置文件

将日志中的常用配置,比如日志器名称、日志器等级及格式化放在配置文件中,在配置文件config.yaml中添加:


logger:
 name: ITester
 level: DEBUG
 format: '%(filename)s-%(lineno)d-%(asctime)s-%(levelname)s-%(message)s'

封装logging类,读取yaml中的日志配置。

二、读取yaml

之前读写yaml配置文件的类已经封装好,愉快的拿来用即可,读取yaml配置文件中的日志配置。

yaml_handler.py


import yaml
class YamlHandler:
   def __init__(self, file):
       self.file = file
   def read_yaml(self, encoding='utf-8'):
       """读取yaml数据"""
       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文件写入数据"""
       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中哪些数据可以作为参数?比如日志器名称、日志等级、日志文件路径、输出格式,可以将这些放到__init__方法里,作为参数。

  • 其次,要判断日志文件是否存在,存在就将日志输出到日志文件中。

  • 最后,logging模块已经封装好了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实战

在登录用例中运用日志模块,到底在登录代码的哪里使用日志?

  • 将读取的用例数据写入日志、用来检查当前的用例数据是否正确;

  • 将用例运行的结果写入日志,用来检查用例运行结果是否与预期一致;

  • 将断言失败的错误信息写入日志。

接下来直接上代码,在登录用例中添加日志。

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中的数据
   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('当前用例的测试数据:{}'.format(items))
       # 请求接口
       res = self.req.visit(method=items['method'],url=items['url'],json=json.loads(items['payload']),
                            headers=json.loads(items['headers']))
       try:
           # 断言:预期结果与实际结果对比
           self.assertEqual(res['code'], items['expected_result'])
           logger.info(res)
           result = 'Pass'
       except AssertionError as e:
           logger.error('用例执行失败:{}'.format(e))
           result = 'Fail'
           raise e
       finally:
           # 将响应的状态码,写到excel的第9列,即写入返回的状态码
           TestLogin.excel.write_excel("../data/cases.xlsx", 'login', items['case_id'] + 1, 9, res['code'])
           # 如果断言成功,则在第10行(测试结果)写入Pass,否则,写入Fail
           TestLogin.excel.write_excel("../data/cases.xlsx", 'login', items['case_id'] + 1, 10, result)
if __name__ == '__main__':
   unittest.main()

控制台日志输出部分截图:

Python接口自动化浅析logging封装及实战操作

日志文件输出部分截图:

Python接口自动化浅析logging封装及实战操作

来源:https://blog.csdn.net/ZangKang1/article/details/119765827

标签:Python,接口自动化,logging封装
0
投稿

猜你喜欢

  • 使用php语句将数据库*.sql文件导入数据库

    2023-11-23 05:11:22
  • 楼层数横排比竖排好

    2008-04-26 07:28:00
  • python-docx如何缩进两个字符

    2022-07-04 15:56:45
  • python opencv实现信用卡的数字识别

    2023-07-05 02:20:23
  • 浅谈vue中使用编辑器vue-quill-editor踩过的坑

    2024-04-10 13:46:00
  • 在django中,关于session的通用设置方法

    2023-09-26 09:53:52
  • jQuery 1.3的VS智能提示下载

    2009-01-18 12:54:00
  • python flask实现分页效果

    2022-07-18 06:19:22
  • Python网络爬虫实例讲解

    2023-09-11 23:18:10
  • MYSQL教程:数据列类型与查询效率

    2009-02-27 15:37:00
  • Python实现淘宝秒杀功能的示例代码

    2021-05-26 09:41:49
  • sqlserver给表添加新字段、给表和字段添加备注、更新备注及查询备注(sql语句)

    2024-01-24 10:54:57
  • PyQt5 PySide2 触摸测试功能的实现代码

    2022-06-23 22:22:25
  • JavaScript中的ArrayBuffer详细介绍

    2024-04-19 11:02:13
  • Django项目如何给数据库添加约束

    2023-08-10 14:49:39
  • python 中的 super详解

    2023-09-07 01:27:35
  • Python使用MapReduce编程模型统计销量

    2021-07-16 14:24:43
  • python爬取内容存入Excel实例

    2022-06-05 16:31:47
  • Tensorflow简单验证码识别应用

    2023-08-10 14:13:14
  • Python matplotlib实用绘图技巧汇总

    2023-10-05 01:12:39
  • asp之家 网络编程 m.aspxhome.com