From:
# 在自动化测试过程中,需要有日志,方便出现问题时快速定位分析,这里采用python内置的logging日志模块记录。
#
# 首先先封装要记录的日志级别、输出方式等方法。
# !/usr/bin/python3
# -*- coding:utf-8 -*-
# @Time : 2023/6/11 14:07
# @Author : 凌雪
# @File : logger.py
# @Software: PyCharm
# 功能说明:封装日志方法
import logging
import os
import time
from datetime import datetime
LEVELS = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL
}
logger = logging.getLogger()
level = 'default'
def create_file(filename):
"""
创建日志文件
:param filename: 日志文件名
:return:
"""
path = filename[0:filename.rfind('/')]
if not os.path.isdir(path): # 判断路径是否为目录
os.makedirs(path) # 递归创建目录
if not os.path.isfile(filename):
fd = open(filename, mode='w', encoding='utf-8')
fd.close()
else:
pass
def set_handler(levels):
if levels == "error":
logger.addHandler(MyLog.err_handler)
logger.addHandler(MyLog.handler)
logger.addHandler(MyLog.console)
def remove_handler(levels):
if levels == 'error':
logger.removeHandler(MyLog.err_handler)
logger.removeHandler(MyLog.handler)
logger.removeHandler(MyLog.console)
def get_current_time():
"""
获取当前时间
:return:
"""
return time.strftime(MyLog.date, time.localtime(time.time()))
class MyLog:
path = os.path.dirname(os.getcwd())
# 获取当前日期
filename = datetime.now().strftime('%Y%m%d')
# print(filename)
# log_file = path + '/log/log.log'
# err_file = path + '/log/err.log'
log_file = path + f"/log/{'log' + filename}.log"
err_file = path + f"/log/{'err' + filename}.log"
create_file(log_file)
create_file(err_file)
date = '%Y-%m-%d %H:%M:%S'
# 将日志输出到屏幕
console = logging.StreamHandler()
console.setLevel(LEVELS.get(level, logging.NOTSET))
# 将日志输出到文件
logger.setLevel(LEVELS.get(level, logging.NOTSET))
handler = logging.FileHandler(log_file, encoding="utf-8")
err_handler = logging.FileHandler(err_file, encoding="utf-8")
@staticmethod
def debug(log_meg):
set_handler('debug')
logger.debug("[DEBUG " + get_current_time() + "]" + log_meg)
remove_handler('debug')
@staticmethod
def info(log_meg):
set_handler('info')
logger.info("[INFO " + get_current_time() + "]" + log_meg)
remove_handler('info')
@staticmethod
def warning(log_meg):
set_handler('warning')
logger.warning("[WARNING " + get_current_time() + "]" + log_meg)
remove_handler('warning')
@staticmethod
def error(log_meg):
set_handler('error')
logger.error("[ERROR " + get_current_time() + "]" + log_meg)
remove_handler('error')
@staticmethod
def critical(log_meg):
set_handler('critical')
logger.error("[CRITICAL " + get_current_time() + "]" + log_meg)
remove_handler('critical')
if __name__ == "__main__":
MyLog.debug("debug信息")
# 然后在前面封装的send_request.py文件中调用,实现对每个接口测试过程的日志记录。
# !/usr/bin/python3
# -*- coding:utf-8 -*-
# @Time : 2023/5/28 11:54
# @Author : 凌雪
# @File : send_request.py
# @Software: PyCharm
# 功能说明:封装request统一请求,异常处理、日志监控等
import requests
from common.yaml_util import *
import json
import re
import jsonpath
import common.logger as logger
from common.allure_step import *
class Send_Request():
def __init__(self, two_node):
"""
私有方法,自动管理cookie
"""
self.__session = requests.Session()
self.base_url = read_config('Host', two_node)
# self.obj = obj
self.log = logger.MyLog()
def send_request(self, method, url, **kwargs):
method = str(method).lower() # 转换小写
# 基础路径的拼接和替换
url = self.base_url + self.replace_value(url)
# print(url)
# 参数替换
for key, value in kwargs.items():
if key in ['params', 'data', 'json', 'headers']:
kwargs[key] = self.replace_value(value)
elif key == "files":
for file_key, file_path in value.items():
value[file_key] = open(file_path, 'rb')
self.__request_log(method, url, **kwargs)
try:
res = self.__session.request(method, url, **kwargs)
if res.status_code == 200:
self.__response_log(res)
return res
else:
self.log.warning("请检查接口%s" % url)
except TimeoutError:
self.log.warning("请求失败,请检查网络!")
return None
# print(res.text)
self.__response_log(res)
return res
def __request_log(self, method, url, **kwargs):
"""
请求日志
:param method:
:param url:
:param kwargs:
:return:
"""
self.log.info("接口请求地址:{}".format(url))
self.log.info("接口请求方式:{}".format(method))
for key, value in kwargs.items():
if key in ['params', 'data', 'json', 'headers']:
self.log.info(
"接口请求体{}参数:{}".format(key, json.dumps(self.replace_value(value), indent=4, ensure_ascii=False)))
def __response_log(self, res):
"""
响应日志
:param res:
:return:
"""
try:
self.log.info("返回状态码:{}".format(res.status_code, ensure_ascii=False))
# self.log.info("返回响应内容:{}".format(res.text, ensure_ascii=False))
except Exception as e:
self.log.error("系统错误:{}".format(e))
# 在其他需要记录日志的地方,比如规范yaml测试用例、断言等都可以根据实际情况添加日志记录。