python-单元测试优化,加入日志

时间:2022-10-01 05:14:25

python-单元测试优化,加入日志

HttpRequests.py

 #-*- coding:utf-8 -*-

 import requests
class HttpRequests():
def http_requests(self,url,params,http_mothed,cookies=None):
if http_mothed=='get':
res=requests.get(url,params,cookies=cookies)
return res
else:
res=requests.post(url,params,cookies=cookies)
return res

my_log.py

 #-*- coding:utf-8 -*-

 import logging
from common import project_path
from common.read_config import ReadConfig
class MyLog: def my_log(self,level,msg):
# 创建一个日志收集器并命名
my_logger=logging.getLogger(ReadConfig().read_config(project_path.conf_path,'LOGS','logger_name'))
my_logger.setLevel(ReadConfig().read_config(project_path.conf_path,'LOGS','log_level'))# 设置收集器的级别 # 设置输出格式
formatter = logging.Formatter(ReadConfig().read_config(project_path.conf_path,'LOGS','formatter')) # 指定输出渠道,输出到控制台
ch=logging.StreamHandler()#输入到控制台
ch.setLevel(ReadConfig().read_config(project_path.conf_path,'LOGS','console_handle'))# 设置输出渠道的级别;
# 如果收集器中的级别与输出渠道级别不同,取两者的交集
ch.setFormatter(formatter)#日志输出时,按指定的输出格式输出 #输出到本地文件
fh=logging.FileHandler(project_path.log_path,encoding='utf-8')#输出到本地log_file文档中;日志中有中文,需要设置编码
fh.setLevel(ReadConfig().read_config(project_path.conf_path,'LOGS','file_handle'))#输出级别为debug
fh.setFormatter(formatter)#日志输出时,按指定的输出格式输出 #对接:收集器与输出渠道
my_logger.addHandler(ch)
my_logger.addHandler(fh) if level == 'DEBUG':
my_logger.debug(msg)
elif level == 'INFO':
my_logger.info(msg)
elif level == 'WARNING':
my_logger.warning(msg)
elif level == 'ERROR':
my_logger.error(msg)
elif level == 'CRITICAL':
my_logger.critical(msg) #将渠道移除
my_logger.removeHandler(ch)
my_logger.removeHandler(fh)
fh.close() def debug(self,msg):
self.my_log('DEBUG',msg)
def info(self,msg):
self.my_log('INFO',msg)
def warning(self,msg):
self.my_log('WARNING',msg)
def error(self,msg):
self.my_log('ERROR',msg)
def crtical(self,msg):
self.my_log('CRTICAL',msg) if __name__ == '__main__':
my_logger=MyLog()
my_logger.debug('haha')
my_logger.info('heng')

project_path.py

 # @File : project_path.py

 #-*- coding:utf-8 -*-
#存放路径变量
import os
base_path=os.path.split(os.path.split(os.path.realpath(__file__))[0])[0] #api_auto目录 #配置文件路径
conf_path=os.path.join(base_path,'conf','test_api.conf') #测试报告路径
report_path=os.path.join(base_path,'test_result','report','test_api.html') #测试用例的路径
case_path=os.path.join(base_path,'test_case','http_requests.xlsx') #日志的路径
log_path=os.path.join(base_path,'test_result','log','log_file.txt')

read_config.py

 # @File : read_config.py

 #-*- coding:utf-8 -*-

 import configparser
class ReadConfig():
def read_config(self,file_name,section,option):
cf = configparser.ConfigParser()#创建对象
cf.read(file_name,encoding ='utf-8')#打开配置文件
value=cf.get(section,option)
return value
if __name__ == '__main__':
value=ReadConfig().read_config('test_api.conf','student1','name')
print(value)

read_excel.py

 #-*- coding:utf-8 -*-

 from openpyxl import load_workbook
import configparser class TestExcel(): def get_TestExcel(self,file_name,sheet_name,button):
workbook = load_workbook(file_name)#打开表格
sheet = workbook[sheet_name]#定位表单 test_data = []#把所有行的数据放到列表中 for i in range(2,sheet.max_row+1):
sub_data = {}#把每行的数据放到字典中
for j in range(1,sheet.max_column+1): sub_data[sheet.cell(1,j).value] = sheet.cell(i,j).value test_data.append(sub_data)#把每一行数据添加到test_data列表里 final_data=[]#最后的测试数据
if button == 'all':
final_data=test_data
else:
for item in test_data: #遍历test_data里面的数据
if item['case_id'] in eval(button):
#如果表格中case_id在button里面,就把这条用例加到final_data里面
final_data.append(item) return final_data

test_HttpRequests.py

 #-*- coding:utf-8 -*-

 #存放测试用例
import unittest from ddt import ddt,data from common.HttpRequests import HttpRequests
from common.read_config import ReadConfig
from common.read_excel import TestExcel
from common.my_log import MyLog
from common import project_path COOKIES=None #利用配置类,从配置文件case.conf里面读取section:case;option:button的values值
button=ReadConfig().read_config(project_path.conf_path,'case','button') #调用task_04_do_excel这个模块里面的TestExcel类里面的get_TestExcel方法
#此方法需要 文件名,表单名,配置的值 这几个参数
test_data=TestExcel().get_TestExcel(project_path.case_path,'Sheet1',button) @ddt
class TestHttpRequests(unittest.TestCase): def setUp(self):
# self.url='http://47.107.168.87:8080/futureloan/mvc/api/member/login'
pass @data(*test_data)
def test_api(self,item):#登录成功 :手机号正确、密码正确;用例里面不可以传参数;但是如果用@data装饰以后,要用等量的变量接收,必须赋值
global COOKIES#声明全局变量
my_logger=MyLog() my_logger.info('目前正在执行第{}条用例:{}'.format(item['case_id'],item['title']))
my_logger.info('------开始检查url地址----------')
my_logger.info('url:{}'.format(item['url']))
my_logger.info('------开始检查params----------')
my_logger.info('params:{}'.format(item['params']))
my_logger.info('---------开始http请求----------') res=HttpRequests().http_requests(item['url'],eval(item['params']),item['http_method'],COOKIES)
my_logger.info('---------结束http请求----------') try:
self.assertEqual(item['excepted'],res.json()['msg'])
# TestReslt='pass'
except AssertionError as e:
# TestReslt='Failed'
my_logger.error('断言结果是:{}'.format(e))
raise e
# finally:
# my_logger.info('本次用例的测试结论是:{}'.format(e))
# my_logger.info('看看TestReslt的值') if res.cookies:
COOKIES=res.cookies#当res.cookies非空时,修改COOKIES的值

test_runner.py

 #-*- coding:utf-8 -*-

 import unittest
from common import project_path
import HTMLTestRunnerNew from common.test_HttpRequests import TestHttpRequests suit=unittest.TestSuite()##装用例的地方
loader=unittest.TestLoader()
suit.addTest(loader.loadTestsFromTestCase(TestHttpRequests)) #执行用例
with open(project_path.report_path,'bw+') as file:
Runner=HTMLTestRunnerNew.HTMLTestRunner(stream=file,verbosity=2,
title='HTTP请求作业-单元测试报告',description='测试一下HTTP请求',tester='*'
)
Runner.run(suit)

test_api.conf

#button = all 执行表格中所有用例
#button=[x,y] int(x)<int(y),执行x-y行之间的用例

[case]
button=all

[LOGS]
log_level=DEBUG
console_handle=ERROR
file_handle=DEBUG
formatter=%%(asctime)s - %%(filename)s - %%(name)s - %%(levelname)s - 日志信息: %%(message)s
logger_name=Mina

http_requests.xlsx

python-单元测试优化,加入日志

执行结果

python-单元测试优化,加入日志