Skip to content

Commit

Permalink
增加依赖用例处理,调整部分代码
Browse files Browse the repository at this point in the history
  • Loading branch information
liwanlei committed Jan 16, 2022
1 parent a026cda commit fe2320d
Show file tree
Hide file tree
Showing 18 changed files with 165 additions and 465 deletions.
22 changes: 12 additions & 10 deletions Interface/testFengzhuang.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,21 @@


class TestApi(object):
def __init__(self, url, key, connent, fangshi):
def __init__(self, url, parame, method):
self.url = url
self.key = key
self.connent = connent
self.fangshi = fangshi
self.parame = parame
self.method = method

def testapi(self):
if self.fangshi == 'POST':
self.parem = {'key': self.key, 'info': self.connent}
self.response = reques.post(self.url, self.parem)
elif self.fangshi == "GET":
self.parem = {'key': self.key, 'info': self.connent}
self.response = reques.get(url=self.url, params=self.parem)
if self.method == 'POST':
self.response = reques.post(self.url, self.parame)
elif self.method == "GET":
self.response = reques.get(url=self.url, params=self.parame)
elif self.method == "PUT":
self.response = reques.putparams(url=self.url, params=self.parame)
elif self.method == "DELETE":
self.response = reques.delparams(url=self.url, params=self.parame)

return self.response

def getJson(self):
Expand Down
66 changes: 36 additions & 30 deletions Public/BSTestRunner.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@
import sys, copy
from io import StringIO as StringIO


# ------------------------------------------------------------------------
# The redirectors below are used to capture output during testing. Output
# sent to sys.stdout and sys.stderr are automatically captured. However
Expand Down Expand Up @@ -278,7 +279,7 @@ class Template_mixin(object):
<p class='description'>%(description)s</p>
</div> </div >
"""
HEADING_TMPL_New="""
HEADING_TMPL_New = """
<div class='heading'>
<div style='width: 50%%;float:left;margin-top:inherit'>
<h1>%(title)s</h1>
Expand Down Expand Up @@ -388,7 +389,7 @@ class Template_mixin(object):
#

ENDING_TMPL = """<div id='ending'>&nbsp;</div>"""
SCRPICTold="""
SCRPICTold = """
<script language='javascript' type='text/javascript'>
output_list = Array();
Expand Down Expand Up @@ -468,8 +469,7 @@ class Template_mixin(object):
</html>
"""


SCRPICTDATA=r"""
SCRPICTDATA = r"""
<script language='javascript' type='text/javascript'>
var dom = document.getElementById('containerchart');
var myChart = echarts.init(dom);
Expand Down Expand Up @@ -608,10 +608,14 @@ class Template_mixin(object):
</body>
</html>
"""


# -------------------- The end of the Template class -------------------


TestResult = unittest.TestResult


class MyResult(TestResult):
def __init__(self, verbosity=1, trynum=1):
# 默认次数是0
Expand Down Expand Up @@ -714,7 +718,6 @@ def stop(self) -> None:
pass



class _TestResult(MyResult):
# note: _TestResult is a pure representation of results.
# It lacks the output and reporting ability compares to unittest._TextTestResult.
Expand All @@ -738,8 +741,8 @@ def __init__(self, stream=sys.stdout,
self.stream = stream
self.verbosity = verbosity
self.trynum = trynum
self.is_show=is_show
self.filepath=filepath
self.is_show = is_show
self.filepath = filepath
if title is None:
self.title = self.DEFAULT_TITLE
else:
Expand All @@ -760,9 +763,10 @@ def run(self, test):
pass
self.stopTime = datetime.datetime.now()
if self.is_show:
name=os.path.join(self.filepath,self.stopTime.strftime('%Y_%m_%d_%H_%M_%S')+'.txt')
with open(name,'w+') as f:
f.write(result.success_count.__str__()+"_"+result.error_count.__str__()+"_"+result.failure_count.__str__())
name = os.path.join(self.filepath, self.stopTime.strftime('%Y_%m_%d_%H_%M_%S') + '.txt')
with open(name, 'w+') as f:
f.write(
result.success_count.__str__() + "_" + result.error_count.__str__() + "_" + result.failure_count.__str__())
f.close()
self.generateReport(test, result)
print('\n测试耗时: %s' % (self.stopTime - self.startTime))
Expand Down Expand Up @@ -814,9 +818,9 @@ def generateReport(self, test, result):
report = self._generate_report(result)
ending = self._generate_ending()
if self.is_show:
scrpit=self.___generate_scrpitone()
scrpit = self.___generate_scrpitone()
else:
scrpit=self._generate_scrpit()
scrpit = self._generate_scrpit()
output = self.HTML_TMPL % dict(
title=saxutils.escape(self.title),
generator=generator,
Expand All @@ -832,7 +836,7 @@ def _generate_stylesheet(self):
return self.STYLESHEET_TMPL

def _generate_heading(self, report_attrs):
ISSHOWPERDATA=True
ISSHOWPERDATA = True
if ISSHOWPERDATA:
a_lines = []
for name, value in report_attrs:
Expand All @@ -845,7 +849,8 @@ def _generate_heading(self, report_attrs):
a_lines.append(line)
if self.is_show:
heading = self.HEADING_TMPL_New % dict(
title=saxutils.escape(self.title),parameters=''.join(a_lines),description=saxutils.escape(self.description),)
title=saxutils.escape(self.title), parameters=''.join(a_lines),
description=saxutils.escape(self.description), )
else:
heading = self.HEADING_TMPL % dict(
title=saxutils.escape(self.title),
Expand Down Expand Up @@ -959,27 +964,30 @@ def _generate_report_test(self, rows, cid, tid, n, t, o, e):

def _generate_ending(self):
return self.ENDING_TMPL

def ___generate_scrpitone(self):
namerun,faillist,success,error=self._readresult()
return self.SCRPICTDATA% dict(reslutname=namerun,
success=success,
fail=faillist,
error=error)
def _readresult(self):
namerun=[]
faillist=[]
success=[]
error=[]
for root,dirs,files in os.walk(self.filepath):
namerun, faillist, success, error = self._readresult()
return self.SCRPICTDATA % dict(reslutname=namerun,
success=success,
fail=faillist,
error=error)

def _readresult(self):
namerun = []
faillist = []
success = []
error = []
for root, dirs, files in os.walk(self.filepath):
for file in files:
if file.endswith(".txt"):
namerun.append(file.split(".")[0].split("/")[-1])
with open(os.path.join(root,file),'r') as f:
reslut=f.readline().split('\n')[0].split("_")
with open(os.path.join(root, file), 'r') as f:
reslut = f.readline().split('\n')[0].split("_")
success.append(reslut[0])
error.append(reslut[1])
faillist.append(reslut[2])
return namerun,faillist,success,error
return namerun, faillist, success, error

def _generate_scrpit(self):
return self.SCRPICTold

Expand Down Expand Up @@ -1011,5 +1019,3 @@ def runTests(self):
##############################################################################
# Executing this module from the command line
##############################################################################


2 changes: 1 addition & 1 deletion Public/Dingtalk.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"""
'''封装钉钉群发消息'''
import requests, json
from config.config_T import Dingtalk_access_token
from config.config import Dingtalk_access_token


def send_ding(content):
Expand Down
10 changes: 5 additions & 5 deletions Public/emmail.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@
# @Author : leizi
import smtplib, time, os
from email.mime.text import MIMEText
from email.utils import formataddr, parseaddr
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
import yaml


def load_emil_setting(): # 从配置文件中加载获取email的相关信息
import yaml
data_file = open(r".\\config\\email.yaml", "r")
datas = yaml.load(data_file)
filepath = os.path.join(os.path.join(os.getcwd(), 'config'), 'email.yaml')

data_file = open(filepath, "r")
datas = yaml.load(data_file, Loader=yaml.FullLoader)
data_file.close()
return (datas['foremail'], datas['password'], datas['toeamil'], datas['title'])

Expand Down
20 changes: 13 additions & 7 deletions Public/get_excel.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# @Time : 2017/6/4 20:35
# @Author : lileilei
# @File : get_excel.py
import xlrd,os
import xlrd, os
from Public.log import LOG, logger


Expand Down Expand Up @@ -33,13 +33,19 @@ def datacel(filepath):
print(e)
LOG.info('打开测试用例失败,原因是:%s' % e)
return


@logger('生成数据驱动所用数据')
def makedata():
path = os.path.join(os.path.join(os.getcwd(),'test_case_data'),'case.xlsx')
listid, listkey, listconeent, listurl, listfangshi, listqiwang, listname=datacel(path)
i=0
make_data=[]
path = os.path.join(os.path.join(os.getcwd(), 'test_case_data'), 'case.xlsx')
listid, listkey, listconeent, listurl, listfangshi, listqiwang, listname = datacel(path)

make_data = []
for i in range(len(listid)):
make_data.append({'url':listurl[i],'key':listkey[i],'coneent':listconeent[i],'fangshi':listfangshi[i],'qiwang':listqiwang[i]})
i+=1
make_data.append({'url': listurl[i], 'key': listkey[i],
'coneent': listconeent[i], 'fangshi': listfangshi[i],
'qiwang': listqiwang[i],
'id': listid[i]},
)
i += 1
return make_data
1 change: 0 additions & 1 deletion Public/py_Html.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
@file: py_Html.py
@time: 2017/6/5 17:04
"""
import os

titles = '接口测试'

Expand Down
7 changes: 3 additions & 4 deletions Public/pyreport_excel.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
@file: pyreport_excel.py
@time: 2017/6/7 8:47
"""
import xlrd, os, xlwt, yaml, xlsxwriter # 导入库
import os, xlwt, yaml
from xlwt import *


Expand Down Expand Up @@ -56,9 +56,8 @@ def yangshique(me):

def create(filename, list_pass, list_fail, listids, listnames, listkeys, listconeents, listurls, listfangshis,
listqiwangs, list_json, listrelust):

filepath = open( os.path.join(os.path.join(os.getcwd(),'config'),'test_report.yaml'), encoding='utf-8')
file_config = yaml.load(filepath,Loader=yaml.FullLoader)
filepath = open(os.path.join(os.path.join(os.getcwd(), 'config'), 'test_report.yaml'), encoding='utf-8')
file_config = yaml.load(filepath, Loader=yaml.FullLoader)
file = Workbook(filename)
table = file.add_sheet('测试结果', cell_overwrite_ok=True)
style = yangshi1()
Expand Down
2 changes: 1 addition & 1 deletion Public/test_requests.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
# -*- coding: utf-8 -*-# @Author : leiziimport requests, jsonfrom requests import Timeout,RequestExceptionclass requ(): def __init__(self): self.headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:51.0) Gecko/20100101 Firefox/51.0"} def get(self, url, params): # get消息 try: r = requests.get(url, params=params, headers=self.headers) r.encoding = 'UTF-8' if r.status_code==200: json_response = json.loads(r.text) return {'code': 0, 'result': json_response} else: return {'code': 1, 'result': '接口请求失败,返回状态码:%s'%str(r.status_code)} except Timeout as e: return {'code': 1, 'result': '请求超时:%s' % e} except RequestException as e: return {'code': 1, 'result': '请求异常:%s' % e} except Exception as e: return {'code': 1, 'result': 'get请求出错,出错原因:%s' % e} def post(self, url, params): # post消息 data = json.dumps(params) try: r = requests.post(url, params=data, headers=self.headers) if r.status_code == 200: json_response = json.loads(r.text) return {'code': 0, 'result': json_response} else: return {'code': 1, 'result': '接口请求失败,返回状态码:%s' % str(r.status_code)} except Timeout as e: return {'code': 1, 'result': '请求超时:%s' % e} except RequestException as e: return {'code': 1, 'result': '请求异常:%s' % e} except Exception as e: return {'code': 1, 'result': 'post请求出错,出错原因:%s' % e} def delparams(self, url, params): # 删除的请求 try: del_word = requests.delete(url, params=params, headers=self.headers) if del_word.status_code == 200: json_response = json.loads(r.text) return {'code': 0, 'result': json_response} else: return {'code': 1, 'result': '接口请求失败,返回状态码:%s' % str(del_word.status_code)} except Timeout as e: return {'code': 1, 'result': '请求超时:%s' % e} except RequestException as e: return {'code': 1, 'result': '请求异常:%s' % e} except Exception as e: return {'code': 1, 'result': 'del请求出错,出错原因:%s' % e} def putparams(self, url, params): # put请求 try: data = json.dumps(params) result = requests.put(url, data) if result.status_code == 200: json_response = json.loads(r.text) return {'code': 0, 'result': json_response} else: return {'code': 1, 'result': '接口请求失败,返回状态码:%s' % str(result.status_code)} except Timeout as e: return {'code': 1, 'result': '请求超时:%s' % e} except RequestException as e: return {'code': 1, 'result': '请求异常:%s' % e} except Exception as e: return {'code': 1, 'result': 'put请求出错,出错原因:%s' % e}
# -*- coding: utf-8 -*-# @Author : leiziimport requests, jsonfrom requests import Timeout, RequestExceptionclass requ(): def __init__(self): self.headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:51.0) Gecko/20100101 Firefox/51.0"} def get(self, url, params): # get消息 try: r = requests.get(url, params=params, headers=self.headers) r.encoding = 'UTF-8' if r.status_code == 200: json_response = json.loads(r.text) return {'code': 0, 'result': json_response} else: return {'code': 1, 'result': '接口请求失败,返回状态码:%s' % str(r.status_code)} except Timeout as e: return {'code': 1, 'result': '请求超时:%s' % e} except RequestException as e: return {'code': 1, 'result': '请求异常:%s' % e} except Exception as e: return {'code': 1, 'result': 'get请求出错,出错原因:%s' % e} def post(self, url, params): # post消息 data = json.dumps(params) try: r = requests.post(url, params=data, headers=self.headers) if r.status_code == 200: json_response = json.loads(r.text) return {'code': 0, 'result': json_response} else: return {'code': 1, 'result': '接口请求失败,返回状态码:%s' % str(r.status_code)} except Timeout as e: return {'code': 1, 'result': '请求超时:%s' % e} except RequestException as e: return {'code': 1, 'result': '请求异常:%s' % e} except Exception as e: return {'code': 1, 'result': 'post请求出错,出错原因:%s' % e} def delparams(self, url, params): # 删除的请求 try: del_word = requests.delete(url, params=params, headers=self.headers) if del_word.status_code == 200: json_response = json.loads(r.text) return {'code': 0, 'result': json_response} else: return {'code': 1, 'result': '接口请求失败,返回状态码:%s' % str(del_word.status_code)} except Timeout as e: return {'code': 1, 'result': '请求超时:%s' % e} except RequestException as e: return {'code': 1, 'result': '请求异常:%s' % e} except Exception as e: return {'code': 1, 'result': 'del请求出错,出错原因:%s' % e} def putparams(self, url, params): # put请求 try: data = json.dumps(params) result = requests.put(url, data) if result.status_code == 200: json_response = json.loads(r.text) return {'code': 0, 'result': json_response} else: return {'code': 1, 'result': '接口请求失败,返回状态码:%s' % str(result.status_code)} except Timeout as e: return {'code': 1, 'result': '请求超时:%s' % e} except RequestException as e: return {'code': 1, 'result': '请求异常:%s' % e} except Exception as e: return {'code': 1, 'result': 'put请求出错,出错原因:%s' % e}
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# 接口测试框架(基于json格式、http请求,python3,不兼容python2.x版本)
## 注:现在基于Excel文件管理测试用例基本实现,)
## 备注:大家在运行的时候,如果参数不需要key,只需要字典,可以在ddt_case.py和case.py改造parame,注释掉现在的parem,启用新的即可
## 依赖用例支持用例执行,在testCase的ddt_case.py有实现,逻辑在代码中有写,参数的格式{"name":"$case1=data"}即代表name的值是case1的data字段,简单的实现。
## 依赖用例是简单的实现,具体在业务上面还有很多复杂的要处理,知识实现了,部分的思路。
## (目前在部分window上会出现FileNotFoundError [Errno 2] No such file or directory,这个bug是路径过长,解决方案为吧log日志放在当前目录,或者修改动态生成的文件的名字,给了第一种方式,测试日志放在当前目录)
## qq交流群:194704520  
### 使用的库 requests,绝大部分是基于Python原有的库进行的,这样简单方便,
Expand Down
2 changes: 1 addition & 1 deletion config/config_T.py → config/config.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""
@author: lileilei
@file: config_T.py
@file: config.py
@time: 2018/4/12 14:17
"""
Dingtalk_access_token = "" # 钉钉配置
Expand Down
8 changes: 4 additions & 4 deletions run_html.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,19 @@
def stast():
starttime = datetime.datetime.now()
day = time.strftime("%Y%m%d%H%M", time.localtime(time.time()))
path=os.path.join(os.path.join(os.getcwd(),'test_case_data'),'case.xlsx')
path = os.path.join(os.path.join(os.getcwd(), 'test_case_data'), 'case.xlsx')
basdir = os.path.abspath(os.path.dirname(__file__))
listid, listkey, listconeent, listurl, listfangshi, listqiwang, listname = datacel(path)
listrelust, list_fail, list_pass, list_json, list_exption, list_weizhi= testinterface()
filepath = os.path.join(os.path.join(basdir,'test_Report'), '%s-result.html' % day)
listrelust, list_fail, list_pass, list_json, list_exption, list_weizhi = testinterface()
filepath = os.path.join(os.path.join(basdir, 'test_Report'), '%s-result.html' % day)
if os.path.exists(filepath) is False:
os.system(r'touch %s' % filepath)
save_result(starttime, len(listrelust), ((list_pass)), list_fail)
endtime = datetime.datetime.now()
createHtml(titles='接口测试报告', filepath=filepath, starttime=starttime,
endtime=endtime, passge=list_pass, fail=list_fail,
id=listid, name=listname, key=listkey, coneent=listconeent, url=listurl, meth=listfangshi,
yuqi=listqiwang, json=list_json, relusts=listrelust,exceptions=list_exption,weizhi=list_weizhi)
yuqi=listqiwang, json=list_json, relusts=listrelust, exceptions=list_exption, weizhi=list_weizhi)
# sendemali(filepath)


Expand Down
Loading

0 comments on commit fe2320d

Please sign in to comment.