#coding=utf-8
import unittest
import requests
import warnings
import json
from ddt import ddt,data
from tools.do_excel import DoExcel
from tools.my_log import MyLog
from tools import project_path
from tools.get_data import GetData
from tools.do_regx import DoRegx
import jsonpath
my_logger = MyLog()
res = DoExcel(project_path.excel_path)
test_data = res.get_data()
@ddt # 装饰测试类
class DoAssert(unittest.TestCase):
'''与预期进行判断,将报错写回文档及log日志'''
@classmethod
def setUpClass(cls):
warnings.simplefilter('ignore', ResourceWarning)
@data(*test_data) # 脱一层外套操作,装饰测试方法,拿到几条数据则执行几条用例
def test_assert(self,item):
result = requests.request(method=item['method'],url=item['url'],headers=eval(item['headers']),data=eval(DoRegx.do_regx(item['data'])),cookies=getattr(GetData,'cookies'))
result_list = []
# 判断,如果通了,执行下方遍历添加预期
for keys in eval(item['keys']):
if jsonpath.jsonpath(result.json()['body'], '$..' + keys) == False:
res.write_back(item['sheet_name'], item['case_id'] + 1, 9, 'false')
my_logger.my_log("报警!开发修改返回参数名称了,返回结果:{}".format(json.dumps(result.json(),sort_keys=False,separators=(',',':'),indent=2,ensure_ascii=False)), 'ERROR')
raise result.json()
else:
for result_values in jsonpath.jsonpath(result.json()['body'], '$..' + keys):
result_list.append(result_values)
for i in eval(item['expected']):
try:
self.assertIn(i,result_list)
res.write_back(item['sheet_name'], item['case_id'] + 1, 9, 'pass')
except AssertionError as e:
res.write_back(item['sheet_name'], item['case_id'] + 1, 9, 'false')
my_logger.my_log("校验失败:{0},请求结果:{1}".format(e,json.dumps(result.json(),sort_keys=False,separators=(',',':'),indent=2,ensure_ascii=False)), 'ERROR')
raise e
finally:
if item['sheet_name'] == 'login' and item['case_id'] == 3:
setattr(GetData, 'cookies', result.cookies)
elif item['depend']:
for i in eval(item['depend']):
setattr(GetData, i[1], jsonpath.jsonpath(result.json()['body'], '$..'+i[0])[-1])
my_logger.my_log("sheet_name:{0},case_id:{1},测试标题:{2}".format(item['sheet_name'],item['case_id'],item['title']),'DEBUG')
my_logger.my_log("请求数据:{0},请求结果:{1}".format(item,result.json()), 'INFO')
my_logger.my_log("请求结果:{}".format(result.json()), 'INFO')
my_logger.my_log("-"*100, 'INFO')
if __name__ == '__main__':
unittest.main()