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

 

 

HttpRequests.py

 1 #-*- coding:utf-8 -*-
 2 
 3 import requests
 4 class HttpRequests():
 5     def http_requests(self,url,params,http_mothed,cookies=None):
 6         if http_mothed=='get':
 7             res=requests.get(url,params,cookies=cookies)
 8             return res
 9         else:
10             res=requests.post(url,params,cookies=cookies)
11             return res

 

my_log.py

 1 #-*- coding:utf-8 -*-
 2 
 3 
 4 import logging
 5 from common import project_path
 6 from common.read_config import ReadConfig
 7 class MyLog:
 8 
 9  def my_log(self,level,msg):
10   # 创建一个日志收集器并命名
11     my_logger=logging.getLogger(ReadConfig().read_config(project_path.conf_path,'LOGS','logger_name'))
12     my_logger.setLevel(ReadConfig().read_config(project_path.conf_path,'LOGS','log_level'))# 设置收集器的级别
13 
14   # 设置输出格式
15     formatter = logging.Formatter(ReadConfig().read_config(project_path.conf_path,'LOGS','formatter'))
16 
17   # 指定输出渠道,输出到控制台
18     ch=logging.StreamHandler()#输入到控制台
19     ch.setLevel(ReadConfig().read_config(project_path.conf_path,'LOGS','console_handle'))# 设置输出渠道的级别;
20   # 如果收集器中的级别与输出渠道级别不同,取两者的交集
21     ch.setFormatter(formatter)#日志输出时,按指定的输出格式输出
22 
23   #输出到本地文件
24     fh=logging.FileHandler(project_path.log_path,encoding='utf-8')#输出到本地log_file文档中;日志中有中文,需要设置编码
25     fh.setLevel(ReadConfig().read_config(project_path.conf_path,'LOGS','file_handle'))#输出级别为debug
26     fh.setFormatter(formatter)#日志输出时,按指定的输出格式输出
27 
28   #对接:收集器与输出渠道
29     my_logger.addHandler(ch)
30     my_logger.addHandler(fh)
31 
32     if level == 'DEBUG':
33         my_logger.debug(msg)
34     elif level == 'INFO':
35         my_logger.info(msg)
36     elif level == 'WARNING':
37         my_logger.warning(msg)
38     elif level == 'ERROR':
39         my_logger.error(msg)
40     elif level == 'CRITICAL':
41         my_logger.critical(msg)
42 
43     #将渠道移除
44     my_logger.removeHandler(ch)
45     my_logger.removeHandler(fh)
46     fh.close()
47 
48 
49  def debug(self,msg):
50     self.my_log('DEBUG',msg)
51  def info(self,msg):
52     self.my_log('INFO',msg)
53  def warning(self,msg):
54     self.my_log('WARNING',msg)
55  def error(self,msg):
56     self.my_log('ERROR',msg)
57  def crtical(self,msg):
58     self.my_log('CRTICAL',msg)
59 
60 
61 if __name__ == '__main__':
62   my_logger=MyLog()
63   my_logger.debug('haha')
64   my_logger.info('heng')

 

project_path.py

 1 # @File : project_path.py
 2 
 3 #-*- coding:utf-8 -*-
 4 #存放路径变量
 5 import os
 6 base_path=os.path.split(os.path.split(os.path.realpath(__file__))[0])[0] #api_auto目录
 7 
 8 #配置文件路径
 9 conf_path=os.path.join(base_path,'conf','test_api.conf')
10 
11 #测试报告路径
12 report_path=os.path.join(base_path,'test_result','report','test_api.html')
13 
14 #测试用例的路径
15 case_path=os.path.join(base_path,'test_case','http_requests.xlsx')
16 
17 #日志的路径
18 log_path=os.path.join(base_path,'test_result','log','log_file.txt')

 

read_config.py

 1 # @File : read_config.py
 2 
 3 #-*- coding:utf-8 -*-
 4 
 5 import configparser
 6 class ReadConfig():
 7     def read_config(self,file_name,section,option):
 8         cf = configparser.ConfigParser()#创建对象
 9         cf.read(file_name,encoding ='utf-8')#打开配置文件
10         value=cf.get(section,option)
11         return value
12 if __name__ == '__main__':
13     value=ReadConfig().read_config('test_api.conf','student1','name')
14     print(value)

 

 

read_excel.py

 1 #-*- coding:utf-8 -*-
 2 
 3 from openpyxl import load_workbook
 4 import configparser
 5 
 6 
 7 class TestExcel():
 8 
 9     def get_TestExcel(self,file_name,sheet_name,button):
10         workbook = load_workbook(file_name)#打开表格
11         sheet = workbook[sheet_name]#定位表单
12 
13         test_data = []#把所有行的数据放到列表中
14 
15         for i in range(2,sheet.max_row+1):
16             sub_data = {}#把每行的数据放到字典中
17             for j in range(1,sheet.max_column+1):
18 
19                 sub_data[sheet.cell(1,j).value] = sheet.cell(i,j).value
20 
21             test_data.append(sub_data)#把每一行数据添加到test_data列表里
22 
23         final_data=[]#最后的测试数据
24         if button == 'all':
25             final_data=test_data
26         else:
27             for item in test_data: #遍历test_data里面的数据
28                 if item['case_id'] in eval(button):
29                     #如果表格中case_id在button里面,就把这条用例加到final_data里面
30                     final_data.append(item)
31 
32         return final_data

 

test_HttpRequests.py

 1 #-*- coding:utf-8 -*-
 2 
 3 #存放测试用例
 4 import unittest
 5 
 6 from ddt import ddt,data
 7 
 8 from common.HttpRequests import HttpRequests
 9 from common.read_config import ReadConfig
10 from common.read_excel import TestExcel
11 from common.my_log import MyLog
12 from common import project_path
13 
14 COOKIES=None
15 
16 #利用配置类,从配置文件case.conf里面读取section:case;option:button的values值
17 button=ReadConfig().read_config(project_path.conf_path,'case','button')
18 
19 #调用task_04_do_excel这个模块里面的TestExcel类里面的get_TestExcel方法
20 #此方法需要 文件名,表单名,配置的值 这几个参数
21 test_data=TestExcel().get_TestExcel(project_path.case_path,'Sheet1',button)
22 
23 @ddt
24 class TestHttpRequests(unittest.TestCase):
25 
26 
27     def setUp(self):
28         # self.url='http://47.107.168.87:8080/futureloan/mvc/api/member/login'
29         pass
30 
31     @data(*test_data)
32     def test_api(self,item):#登录成功 :手机号正确、密码正确;用例里面不可以传参数;但是如果用@data装饰以后,要用等量的变量接收,必须赋值
33         global COOKIES#声明全局变量
34         my_logger=MyLog()
35 
36         my_logger.info('目前正在执行第{}条用例:{}'.format(item['case_id'],item['title']))
37         my_logger.info('------开始检查url地址----------')
38         my_logger.info('url:{}'.format(item['url']))
39         my_logger.info('------开始检查params----------')
40         my_logger.info('params:{}'.format(item['params']))
41         my_logger.info('---------开始http请求----------')
42 
43         res=HttpRequests().http_requests(item['url'],eval(item['params']),item['http_method'],COOKIES)
44         my_logger.info('---------结束http请求----------')
45 
46 
47         try:
48             self.assertEqual(item['excepted'],res.json()['msg'])
49             # TestReslt='pass'
50         except AssertionError as e:
51             # TestReslt='Failed'
52             my_logger.error('断言结果是:{}'.format(e))
53             raise e
54         # finally:
55         #     my_logger.info('本次用例的测试结论是:{}'.format(e))
56         #     my_logger.info('看看TestReslt的值')
57 
58         if res.cookies:
59             COOKIES=res.cookies#当res.cookies非空时,修改COOKIES的值

 

test_runner.py

 1 #-*- coding:utf-8 -*-
 2 
 3 
 4 import unittest
 5 from common import project_path
 6 import HTMLTestRunnerNew
 7 
 8 
 9 from common.test_HttpRequests import TestHttpRequests
10 
11 
12 suit=unittest.TestSuite()##装用例的地方
13 loader=unittest.TestLoader()
14 suit.addTest(loader.loadTestsFromTestCase(TestHttpRequests))
15 
16 
17 #执行用例
18 with open(project_path.report_path,'bw+') as file:
19     Runner=HTMLTestRunnerNew.HTMLTestRunner(stream=file,verbosity=2,
20                                             title='HTTP请求作业-单元测试报告',description='测试一下HTTP请求',tester='huimin'
21                                             )
22     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

 

 

执行结果

 

posted @ 2018-12-20 17:35  赵小丫  阅读(498)  评论(0编辑  收藏  举报