This commit is contained in:
lileilei
2020-05-09 21:24:18 +08:00
parent 49e45d00fa
commit e09917b396
30 changed files with 1952 additions and 1789 deletions

View File

@@ -3,24 +3,27 @@
@file: dubbo_feng.py
@time: 2018/3/29 12:26
"""
from pyhessian.client import HessianProxy
from pyhessian import protocol
from Public.log import LOG,logger
from pyhessian.client import HessianProxy
from pyhessian import protocol
from Public.log import LOG, logger
@logger('dubbo接口')
class DubboInterface:
def __init__(self,url,interface,method,param,**kwargs):
self.url=url
self.interface=interface
self.method=method
self.param=param
self.interfaceparam=protocol.object_factory(self.param,**kwargs)
def __init__(self, url, interface, method, param, **kwargs):
self.url = url
self.interface = interface
self.method = method
self.param = param
self.interfaceparam = protocol.object_factory(self.param, **kwargs)
def getresult(self):
try:
result=HessianProxy(self.url+self.interface)
return_result=getattr(result,self.method)(self.interfaceparam)
LOG.info('测试返回结果:%s'%return_result)
res={'code':0,'result':return_result}
result = HessianProxy(self.url + self.interface)
return_result = getattr(result, self.method)(self.interfaceparam)
LOG.info('测试返回结果:%s' % return_result)
res = {'code': 0, 'result': return_result}
except Exception as e:
LOG.info('测试失败,原因:%s'%e)
res={'code':1,'result':e}
return res
LOG.info('测试失败,原因:%s' % e)
res = {'code': 1, 'result': e}
return res

View File

@@ -4,21 +4,26 @@
# @Site :
# @File : testFengzhuang.py
from Public.test_requests import requ
reques=requ()
reques = requ()
class TestApi(object):
def __init__(self,url,key,connent,fangshi):
self.url=url
self.key=key
self.connent=connent
self.fangshi=fangshi
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)
return self.response
def getJson(self):
json_data = self.testapi()
return json_data
def __init__(self, url, key, connent, fangshi):
self.url = url
self.key = key
self.connent = connent
self.fangshi = fangshi
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)
return self.response
def getJson(self):
json_data = self.testapi()
return json_data

View File

@@ -1 +1 @@
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-

View File

@@ -61,11 +61,9 @@ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
__author__ = "Wai Yip Tung && Eason Han"
__version__ = "0.8.4"
"""
Change History
@@ -121,8 +119,10 @@ def to_unicode(s):
# # s is non ascii byte string
# return s.decode('unicode_escape')
class OutputRedirector(object):
""" Wrapper to redirect stdout or stderr """
def __init__(self, fp):
self.fp = fp
@@ -136,11 +136,11 @@ class OutputRedirector(object):
def flush(self):
self.fp.flush()
stdout_redirector = OutputRedirector(sys.stdout)
stderr_redirector = OutputRedirector(sys.stderr)
# ----------------------------------------------------------------------
# Template
@@ -185,9 +185,9 @@ class Template_mixin(object):
"""
STATUS = {
0: 'pass',
1: 'fail',
2: 'error',
0: 'pass',
1: 'fail',
2: 'error',
}
DEFAULT_TITLE = 'Unit Test Report'
@@ -322,7 +322,6 @@ function showOutput(id, name) {
"""
# variables: (title, generator, stylesheet, heading, report, ending)
# ------------------------------------------------------------------------
# Stylesheet
#
@@ -365,8 +364,6 @@ function showOutput(id, name) {
</style>
"""
# ------------------------------------------------------------------------
# Heading
#
@@ -377,12 +374,10 @@ function showOutput(id, name) {
<p class='description'>%(description)s</p>
</div>
""" # variables: (title, parameters, description)
""" # variables: (title, parameters, description)
HEADING_ATTRIBUTE_TMPL = """<p><strong>%(name)s:</strong> %(value)s</p>
""" # variables: (name, value)
""" # variables: (name, value)
# ------------------------------------------------------------------------
# Report
@@ -419,7 +414,7 @@ function showOutput(id, name) {
</tr>
</tfoot>
</table>
""" # variables: (test_list, count, Pass, fail, error)
""" # variables: (test_list, count, Pass, fail, error)
REPORT_CLASS_TMPL = r"""
<tr class='%(style)s'>
@@ -430,8 +425,7 @@ function showOutput(id, name) {
<td>%(error)s</td>
<td><a class="btn btn-xs btn-primary"href="javascript:showClassDetail('%(cid)s',%(count)s)">Detail</a></td>
</tr>
""" # variables: (style, desc, count, Pass, fail, error, cid)
""" # variables: (style, desc, count, Pass, fail, error, cid)
REPORT_TEST_WITH_OUTPUT_TMPL = r"""
<tr id='%(tid)s' class='%(Class)s'>
@@ -455,22 +449,18 @@ function showOutput(id, name) {
</td>
</tr>
""" # variables: (tid, Class, style, desc, status)
""" # variables: (tid, Class, style, desc, status)
REPORT_TEST_NO_OUTPUT_TMPL = r"""
<tr id='%(tid)s' class='%(Class)s'>
<td class='%(style)s'><div class='testcase'>%(desc)s</div></td>
<td colspan='5' align='center'>%(status)s</td>
</tr>
""" # variables: (tid, Class, style, desc, status)
""" # variables: (tid, Class, style, desc, status)
REPORT_TEST_OUTPUT_TMPL = r"""
%(id)s: %(output)s
""" # variables: (id, output)
""" # variables: (id, output)
# ------------------------------------------------------------------------
# ENDING
@@ -478,11 +468,13 @@ function showOutput(id, name) {
ENDING_TMPL = """<div id='ending'>&nbsp;</div>"""
# -------------------- The end of the Template class -------------------
TestResult = unittest.TestResult
class _TestResult(TestResult):
# note: _TestResult is a pure representation of results.
# It lacks the output and reporting ability compares to unittest._TextTestResult.
@@ -506,7 +498,6 @@ class _TestResult(TestResult):
# )
self.result = []
def startTest(self, test):
TestResult.startTest(self, test)
# just one buffer for both stdout and stderr 更改
@@ -518,7 +509,6 @@ class _TestResult(TestResult):
sys.stdout = stdout_redirector
sys.stderr = stderr_redirector
def complete_output(self):
"""
Disconnect output redirection and return buffer.
@@ -531,14 +521,12 @@ class _TestResult(TestResult):
self.stderr0 = None
return self.outputBuffer.getvalue()
def stopTest(self, test):
# Usually one of addSuccess, addError or addFailure would have been called.
# But there are some path in unittest that would bypass this.
# We must disconnect stdout in stopTest(), which is guaranteed to be called.
self.complete_output()
def addSuccess(self, test):
self.success_count += 1
TestResult.addSuccess(self, test)
@@ -581,6 +569,7 @@ class _TestResult(TestResult):
class BSTestRunner(Template_mixin):
"""
"""
def __init__(self, stream=sys.stdout, verbosity=1, title=None, description=None):
self.stream = stream
self.verbosity = verbosity
@@ -595,7 +584,6 @@ class BSTestRunner(Template_mixin):
self.startTime = datetime.datetime.now()
def run(self, test):
"Run the given test case or test suite."
result = _TestResult(self.verbosity)
@@ -605,25 +593,23 @@ class BSTestRunner(Template_mixin):
pass
self.stopTime = datetime.datetime.now()
self.generateReport(test, result)
print('\n测试耗时: %s' % (self.stopTime-self.startTime))
print('\n测试耗时: %s' % (self.stopTime - self.startTime))
return result
def sortResult(self, result_list):
# unittest does not seems to run in any particular order.
# Here at least we want to group them together by class.
rmap = {}
classes = []
for n,t,o,e in result_list:
for n, t, o, e in result_list:
cls = t.__class__
if not cls in rmap:
rmap[cls] = []
classes.append(cls)
rmap[cls].append((n,t,o,e))
rmap[cls].append((n, t, o, e))
r = [(cls, rmap[cls]) for cls in classes]
return r
def getReportAttributes(self, result):
"""
Return report attributes as a list of (name, value).
@@ -632,9 +618,12 @@ class BSTestRunner(Template_mixin):
startTime = str(self.startTime)[:19]
duration = str(self.stopTime - self.startTime)
status = []
if result.success_count: status.append('<span class="text text-success">Pass <strong>%s</strong></span>' % result.success_count)
if result.failure_count: status.append('<span class="text text-danger">Failure <strong>%s</strong></span>' % result.failure_count)
if result.error_count: status.append('<span class="text text-warning">Error <strong>%s</strong></span>' % result.error_count )
if result.success_count: status.append(
'<span class="text text-success">Pass <strong>%s</strong></span>' % result.success_count)
if result.failure_count: status.append(
'<span class="text text-danger">Failure <strong>%s</strong></span>' % result.failure_count)
if result.error_count: status.append(
'<span class="text text-warning">Error <strong>%s</strong></span>' % result.error_count)
if status:
status = ' '.join(status)
else:
@@ -645,7 +634,6 @@ class BSTestRunner(Template_mixin):
('Status', status),
]
def generateReport(self, test, result):
report_attrs = self.getReportAttributes(result)
generator = 'BSTestRunner %s' % __version__
@@ -654,48 +642,48 @@ class BSTestRunner(Template_mixin):
report = self._generate_report(result)
ending = self._generate_ending()
output = self.HTML_TMPL % dict(
title = saxutils.escape(self.title),
generator = generator,
stylesheet = stylesheet,
heading = heading,
report = report,
ending = ending,
title=saxutils.escape(self.title),
generator=generator,
stylesheet=stylesheet,
heading=heading,
report=report,
ending=ending,
)
self.stream.write(output.encode('utf-8'))
def _generate_stylesheet(self):
return self.STYLESHEET_TMPL
def _generate_heading(self, report_attrs):
a_lines = []
for name, value in report_attrs:
line = self.HEADING_ATTRIBUTE_TMPL % dict(
name = saxutils.escape(name),####更改
# value = saxutils.escape(value),
name=saxutils.escape(name), ####更改
# value = saxutils.escape(value),
value = value,
)
value=value,
)
a_lines.append(line)
heading = self.HEADING_TMPL % 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),
)
return heading
def _generate_report(self, result):
rows = []
sortedResult = self.sortResult(result.result)
for cid, (cls, cls_results) in enumerate(sortedResult):
# subtotal for a class
np = nf = ne = 0
for n,t,o,e in cls_results:
if n == 0: np += 1
elif n == 1: nf += 1
else: ne += 1
for n, t, o, e in cls_results:
if n == 0:
np += 1
elif n == 1:
nf += 1
else:
ne += 1
# format class description
if cls.__module__ == "__main__":
@@ -706,46 +694,45 @@ class BSTestRunner(Template_mixin):
desc = doc and '%s: %s' % (name, doc) or name
row = self.REPORT_CLASS_TMPL % dict(
style = ne > 0 and 'text text-warning' or nf > 0 and 'text text-danger' or 'text text-success',
desc = desc,
count = np+nf+ne,
Pass = np,
fail = nf,
error = ne,
cid = 'c%s' % (cid+1),
style=ne > 0 and 'text text-warning' or nf > 0 and 'text text-danger' or 'text text-success',
desc=desc,
count=np + nf + ne,
Pass=np,
fail=nf,
error=ne,
cid='c%s' % (cid + 1),
)
rows.append(row)
for tid, (n,t,o,e) in enumerate(cls_results):
for tid, (n, t, o, e) in enumerate(cls_results):
self._generate_report_test(rows, cid, tid, n, t, o, e)
report = self.REPORT_TMPL % dict(
test_list = ''.join(rows),
count = str(result.success_count+result.failure_count+result.error_count),
Pass = str(result.success_count),
fail = str(result.failure_count),
error = str(result.error_count),
test_list=''.join(rows),
count=str(result.success_count + result.failure_count + result.error_count),
Pass=str(result.success_count),
fail=str(result.failure_count),
error=str(result.error_count),
)
return report
def _generate_report_test(self, rows, cid, tid, n, t, o, e):
# e.g. 'pt1.1', 'ft1.1', etc
has_output = bool(o or e)
tid = (n == 0 and 'p' or 'f') + 't%s.%s' % (cid+1,tid+1)
tid = (n == 0 and 'p' or 'f') + 't%s.%s' % (cid + 1, tid + 1)
name = t.id().split('.')[-1]
doc = t.shortDescription() or ""
desc = doc and ('%s: %s' % (name, doc)) or name
tmpl = has_output and self.REPORT_TEST_WITH_OUTPUT_TMPL or self.REPORT_TEST_NO_OUTPUT_TMPL
# o and e should be byte string because they are collected from stdout and stderr?
if isinstance(o,str):
if isinstance(o, str):
# TODO: some problem with 'string_escape': it escape \n and mess up formating
# uo = unicode(o.encode('string_escape'))
uo = o
else:
uo = o
if isinstance(e,str):
if isinstance(e, str):
# TODO: some problem with 'string_escape': it escape \n and mess up formating
# ue = unicode(e.encode('string_escape'))
ue = e
@@ -753,19 +740,19 @@ class BSTestRunner(Template_mixin):
ue = e
script = self.REPORT_TEST_OUTPUT_TMPL % dict(
id = tid,
output = saxutils.escape(uo+ue),
id=tid,
output=saxutils.escape(uo + ue),
)
row = tmpl % dict(
tid = tid,
Class = (n == 0 and 'hiddenRow' or 'none'),
tid=tid,
Class=(n == 0 and 'hiddenRow' or 'none'),
# Class = (n == 0 and 'hiddenRow' or 'text text-success'),
# style = n == 2 and 'errorCase' or (n == 1 and 'failCase' or 'none'),
style = n == 2 and 'text text-warning' or (n == 1 and 'text text-danger' or 'text text-success'),
desc = desc,
script = script,
status = self.STATUS[n],
style=n == 2 and 'text text-warning' or (n == 1 and 'text text-danger' or 'text text-success'),
desc=desc,
script=script,
status=self.STATUS[n],
)
rows.append(row)
if not has_output:
@@ -787,6 +774,7 @@ class TestProgram(unittest.TestProgram):
A variation of the unittest.TestProgram. Please refer to the base
class for command line parameters.
"""
def runTests(self):
# Pick BSTestRunner as the default test runner.
# base class's testRunner parameter is not useful because it means
@@ -795,6 +783,7 @@ class TestProgram(unittest.TestProgram):
self.testRunner = BSTestRunner(verbosity=self.verbosity)
unittest.TestProgram.runTests(self)
main = TestProgram
##############################################################################

View File

@@ -4,8 +4,10 @@
@time: 2017/12/26 17:34
"""
'''封装钉钉群发消息'''
import requests,json
from config.config_T import Dingtalk_access_token
import requests, json
from config.config_T import Dingtalk_access_token
def send_ding(content):
url = Dingtalk_access_token
pagrem = {
@@ -17,9 +19,9 @@ def send_ding(content):
}
headers = {
'Content-Type': 'application/json'
}
}
f = requests.post(url, data=json.dumps(pagrem), headers=headers)
if f.status_code==200:
if f.status_code == 200:
return True
else:
return False

View File

@@ -4,13 +4,15 @@
@file: create_report.py
@time: 2017/8/3 12:27
"""
from Public.log import LOG,logger
from Public.log import LOG, logger
@logger('保存测试结果')
def save_result(testtime,toial,passnum,fail):
def save_result(testtime, toial, passnum, fail):
try:
f=open('result.txt','a')
f.write("%s=%s=%s=%s \n"%(testtime,toial,passnum,fail))
f = open('result.txt', 'a')
f.write("%s=%s=%s=%s \n" % (testtime, toial, passnum, fail))
f.close()
except:
LOG.info('保存测试结果出错,原因:%s'%Exception)
LOG.info('保存测试结果出错,原因:%s' % Exception)
print('记录测试结果失败')

View File

@@ -1,32 +1,35 @@
# -*- coding: utf-8 -*-
# @Author : leizi
import smtplib,time,os
from email.mime.text import MIMEText
from email.utils import formataddr,parseaddr
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
def load_emil_setting():#从配置文件中加载获取email的相关信息
import yaml
data_file = open(r".\\config\\email.yaml","r")
datas = yaml.load(data_file)
data_file.close()
return (datas['foremail'],datas['password'],datas['toeamil'],datas['title'])
def sendemali(filepath): #发送email
from_addr,password,mail_to,mail_body=load_emil_setting()
msg = MIMEMultipart()
msg['Subject'] = '接口自动化测试报告'
msg['From'] ='自动化测试平台'
msg['To'] = mail_to
msg['Date'] = time.strftime('%a, %d %b %Y %H:%M:%S %z')
att = MIMEText(open(r'%s'%filepath, 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="pyresult.html"'
txt = MIMEText("这是测试报告的邮件,详情见附件",'plain','gb2312')
msg.attach(txt)
msg.attach(att)
smtp = smtplib.SMTP()
server = smtplib.SMTP_SSL("smtp.qq.com",465)
server.login(from_addr, password)
server.sendmail(from_addr, mail_to, msg.as_string())
server.quit()
def load_emil_setting(): # 从配置文件中加载获取email的相关信息
import yaml
data_file = open(r".\\config\\email.yaml", "r")
datas = yaml.load(data_file)
data_file.close()
return (datas['foremail'], datas['password'], datas['toeamil'], datas['title'])
def sendemali(filepath): # 发送email
from_addr, password, mail_to, mail_body = load_emil_setting()
msg = MIMEMultipart()
msg['Subject'] = '接口自动化测试报告'
msg['From'] = '自动化测试平台'
msg['To'] = mail_to
msg['Date'] = time.strftime('%a, %d %b %Y %H:%M:%S %z')
att = MIMEText(open(r'%s' % filepath, 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="pyresult.html"'
txt = MIMEText("这是测试报告的邮件,详情见附件", 'plain', 'gb2312')
msg.attach(txt)
msg.attach(att)
smtp = smtplib.SMTP()
server = smtplib.SMTP_SSL("smtp.qq.com", 465)
server.login(from_addr, password)
server.sendmail(from_addr, mail_to, msg.as_string())
server.quit()

View File

@@ -4,29 +4,31 @@
@time: 2018/6/15 13:54
"""
'''字典取值'''
def res(d,code):
result=[]
def res(d, code):
result = []
if isinstance(d, dict) and code in d.keys():
value = d[code]
result.append(value)
return result
elif isinstance(d, (list, tuple)):
for item in d:
value=res(item,code)
if value =="None" or value is None:
pass
elif len(value)==0:
pass
else:
result.append(value)
return result
for item in d:
value = res(item, code)
if value == "None" or value is None:
pass
elif len(value) == 0:
pass
else:
result.append(value)
return result
else:
if isinstance(d, dict):
for k in d:
value=res(d[k], code)
if value =="None" or value is None :
value = res(d[k], code)
if value == "None" or value is None:
pass
elif len(value)==0:
elif len(value) == 0:
pass
else:
for item in value:

View File

@@ -3,30 +3,32 @@
# @Author : lileilei
# @File : get_excel.py
import xlrd
from Public.log import LOG,logger
from Public.log import LOG, logger
@logger('解析测试用例文件')
def datacel(filrpath):
try:
file=xlrd.open_workbook(filrpath)
me=file.sheets()[0]
nrows=me.nrows
listid=[]
listkey=[]
listconeent=[]
listurl=[]
listfangshi=[]
listqiwang=[]
listrelut=[]
listname=[]
for i in range(1,nrows):
listid.append(me.cell(i,0).value)
listkey.append(me.cell(i,2).value)
listconeent.append(me.cell(i,3).value)
listurl.append(me.cell(i,4).value)
listname.append(me.cell(i,1).value)
listfangshi.append((me.cell(i,5).value))
listqiwang.append((me.cell(i,6).value))
return listid,listkey,listconeent,listurl,listfangshi,listqiwang,listname
file = xlrd.open_workbook(filrpath)
me = file.sheets()[0]
nrows = me.nrows
listid = []
listkey = []
listconeent = []
listurl = []
listfangshi = []
listqiwang = []
listrelut = []
listname = []
for i in range(1, nrows):
listid.append(me.cell(i, 0).value)
listkey.append(me.cell(i, 2).value)
listconeent.append(me.cell(i, 3).value)
listurl.append(me.cell(i, 4).value)
listname.append(me.cell(i, 1).value)
listfangshi.append((me.cell(i, 5).value))
listqiwang.append((me.cell(i, 6).value))
return listid, listkey, listconeent, listurl, listfangshi, listqiwang, listname
except Exception as e:
LOG.info('打开测试用例失败,原因是:%s'%e)
LOG.info('打开测试用例失败,原因是:%s' % e)
return

View File

@@ -5,14 +5,16 @@
"""
'''读取Excel'''
import xlrd
def datacel(filrpath):
all_case=[]
file=xlrd.open_workbook(filrpath)
me=file.sheets()[0]
nrows=me.nrows
for i in range(1,nrows):
all_case.append({"id":me.cell(i,0).value,'key':me.cell(i,2).value,
'coneent':me.cell(i,3).value,'url':me.cell(i,4).value,
'name':me.cell(i,1).value,'fangshi':me.cell(i,5).value,
'assert':me.cell(i,6).value})
all_case = []
file = xlrd.open_workbook(filrpath)
me = file.sheets()[0]
nrows = me.nrows
for i in range(1, nrows):
all_case.append({"id": me.cell(i, 0).value, 'key': me.cell(i, 2).value,
'coneent': me.cell(i, 3).value, 'url': me.cell(i, 4).value,
'name': me.cell(i, 1).value, 'fangshi': me.cell(i, 5).value,
'assert': me.cell(i, 6).value})
return all_case

View File

@@ -6,12 +6,15 @@ import os
import logbook
from logbook.more import ColorizedStderrHandler
from functools import wraps
check_path='.'
check_path = '.'
LOG_DIR = os.path.join(check_path, 'log')
file_stream = False
if not os.path.exists(LOG_DIR):
os.makedirs(LOG_DIR)
file_stream = True
def get_logger(name='jiekou', file_log=file_stream, level=''):
""" get logger Factory function """
logbook.set_datetime_format('local')
@@ -20,11 +23,17 @@ def get_logger(name='jiekou', file_log=file_stream, level=''):
os.path.join(LOG_DIR, '%s.log' % name),
date_format='%Y-%m-%d-%H', bubble=True, encoding='utf-8').push_thread()
return logbook.Logger(name)
LOG = get_logger(file_log=file_stream, level='INFO')
def logger(param):
""" fcuntion from logger meta """
def wrap(function):
""" logger wrapper """
@wraps(function)
def _wrap(*args, **kwargs):
""" wrap tool """
@@ -32,5 +41,7 @@ def logger(param):
LOG.info("全部args参数参数信息 , {}".format(str(args)))
LOG.info("全部kwargs参数信息 , {}".format(str(kwargs)))
return function(*args, **kwargs)
return _wrap
return wrap

View File

@@ -2,21 +2,25 @@
# @Date : 2017-08-02 21:54:08
# @Author : lileilei
from Public.fengzhuang_dict import res
from .log import LOG,logger
from .log import LOG, logger
@logger('断言测试结果')
def assert_in(asserqiwang,fanhuijson):
def assert_in(asserqiwang, fanhuijson):
if len(asserqiwang.split('=')) > 1:
data = asserqiwang.split('&')
result = dict([(item.split('=')) for item in data])
value1=([(str(res(fanhuijson,key))) for key in result.keys()])
value2=([(str(value)) for value in result.values()])
if value1==value2:
return { 'code':0,"result":'pass'}
value1 = ([(str(res(fanhuijson, key))) for key in result.keys()])
value2 = ([(str(value)) for value in result.values()])
if value1 == value2:
return {'code': 0, "result": 'pass'}
else:
return {'code':1,'result':'fail'}
return {'code': 1, 'result': 'fail'}
else:
LOG.info('填写测试预期值')
return {"code":2,'result':'填写测试预期值'}
return {"code": 2, 'result': '填写测试预期值'}
@logger('断言测试结果')
def assertre(asserqingwang):
if len(asserqingwang.split('=')) > 1:
@@ -25,4 +29,4 @@ def assertre(asserqingwang):
return result
else:
LOG.info('填写测试预期值')
raise {"code":1,'result':'填写测试预期值'}
raise {"code": 1, 'result': '填写测试预期值'}

View File

@@ -4,10 +4,13 @@
@file: py_Html.py
@time: 2017/6/5 17:04
"""
import os
titles='接口测试'
import os
titles = '接口测试'
def title(titles):
title='''<!DOCTYPE html>
title = '''<!DOCTYPE html>
<html>
<head>
<title>%s</title>
@@ -28,13 +31,17 @@ def title(titles):
</style>
</head>
<body>
'''%(titles)
''' % (titles)
return title
connent='''
connent = '''
<div class='col-md-4 col-md-offset-4' style='margin-left:3%;'>
<h1>接口测试的结果</h1>'''
def shouye(starttime,endtime,passge,fail,excepthions,weizhicuowu):
beijing='''
def shouye(starttime, endtime, passge, fail, excepthions, weizhicuowu):
beijing = '''
<table class="table table-hover table-condensed">
<tbody>
<tr>
@@ -49,9 +56,11 @@ def shouye(starttime,endtime,passge,fail,excepthions,weizhicuowu):
weizhicuowu : <strong >%s</strong></span></td>
</tr>
</tbody></table>
</div> '''%(starttime,endtime,(endtime-starttime),passge,fail,excepthions,weizhicuowu)
</div> ''' % (starttime, endtime, (endtime - starttime), passge, fail, excepthions, weizhicuowu)
return beijing
shanghai='''<div class="row " style="margin:60px">
shanghai = '''<div class="row " style="margin:60px">
<div style=' margin-top: 18%;' >
<div class="btn-group" role="group" aria-label="...">
<button type="button" id="check-all" class="btn btn-primary">所有用例</button>
@@ -75,18 +84,22 @@ shanghai='''<div class="row " style="margin:60px">
<td><strong>结果</strong></td>
</tr>
'''
def passfail(tend):
if tend =='pass':
htl='''<td bgcolor="green">pass</td>'''
elif tend =='fail':
htl='''<td bgcolor="fail">fail</td>'''
elif tend=='weizhi':
htl='''<td bgcolor="red">error</td>'''
if tend == 'pass':
htl = '''<td bgcolor="green">pass</td>'''
elif tend == 'fail':
htl = '''<td bgcolor="fail">fail</td>'''
elif tend == 'weizhi':
htl = '''<td bgcolor="red">error</td>'''
else:
htl = '<td bgcolor="crimson">exect</td>'
return htl
def ceshixiangqing(reslt,id,name,key,coneent,url,meth,yuqi,json,relust):
xiangqing='''
def ceshixiangqing(reslt, id, name, key, coneent, url, meth, yuqi, json, relust):
xiangqing = '''
<tr class="case-tr %s">
<td>%s</td>
<td>%s</td>
@@ -98,9 +111,11 @@ def ceshixiangqing(reslt,id,name,key,coneent,url,meth,yuqi,json,relust):
<td>%s</td>
%s
</tr>
'''%(reslt,id,name,key,coneent,url,meth,yuqi,json,passfail(relust))
''' % (reslt, id, name, key, coneent, url, meth, yuqi, json, passfail(relust))
return xiangqing
weibu='''</div></div></table><script src="https://code.jquery.com/jquery.js"></script>
weibu = '''</div></div></table><script src="https://code.jquery.com/jquery.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script type="text/javascript">
$("#check-danger").click(function(e){
@@ -132,24 +147,35 @@ weibu='''</div></div></table><script src="https://code.jquery.com/jquery.js"></s
});
</script>
</body></html>'''
def relust(titles,starttime,endtime,passge,fail,id,name,key,coneent,url,meth,yuqi,json,relust,exceptions,weizhi):
if type(name) ==list:
relus=' '
def relust(titles, starttime, endtime, passge, fail, id, name, key, coneent, url, meth, yuqi, json, relust, exceptions,
weizhi):
if type(name) == list:
relus = ' '
for i in range(len(name)):
if relust[i] == "pass":
clazz = "success"
elif relust[i]== "fail":
elif relust[i] == "fail":
clazz = "warning"
elif relust[i]== "weizhi":
elif relust[i] == "weizhi":
clazz = "danger"
else:
clazz='error'
relus+=(ceshixiangqing(clazz,id[i],name[i],key[i],coneent[i],url[i],meth[i],yuqi[i],json[i],relust[i]))
text=title(titles)+connent+shouye(starttime,endtime,passge,fail,exceptions,weizhi)+shanghai+relus+weibu
clazz = 'error'
relus += (
ceshixiangqing(clazz, id[i], name[i], key[i], coneent[i], url[i], meth[i], yuqi[i], json[i], relust[i]))
text = title(titles) + connent + shouye(starttime, endtime, passge, fail, exceptions,
weizhi) + shanghai + relus + weibu
else:
text=title(titles)+connent+shouye(starttime,endtime,passge,fail,exceptions,weizhi)+shanghai+ceshixiangqing(id,name,key,coneent,url,meth,yuqi,json,relust)+weibu
text = title(titles) + connent + shouye(starttime, endtime, passge, fail, exceptions,
weizhi) + shanghai + ceshixiangqing(id, name, key, coneent, url, meth,
yuqi, json, relust) + weibu
return text
def createHtml(filepath,titles,starttime,endtime,passge,fail,id,name,key,coneent,url,meth,yuqi,json,relusts,exceptions,weizhi):
texts=relust(titles,starttime,endtime,passge,fail,id,name,key,coneent,url,meth,yuqi,json,relusts,exceptions,weizhi)
with open(filepath,'wb') as f:
def createHtml(filepath, titles, starttime, endtime, passge, fail, id, name, key, coneent, url, meth, yuqi, json,
relusts, exceptions, weizhi):
texts = relust(titles, starttime, endtime, passge, fail, id, name, key, coneent, url, meth, yuqi, json, relusts,
exceptions, weizhi)
with open(filepath, 'wb') as f:
f.write(texts.encode('utf-8'))

View File

@@ -4,8 +4,10 @@
@file: pyreport_excel.py
@time: 2017/6/7 8:47
"""
import xlrd ,os,xlwt,yaml,xlsxwriter #导入库
import xlrd, os, xlwt, yaml, xlsxwriter # 导入库
from xlwt import *
def yangshi1():
style = XFStyle()
fnt = Font()
@@ -18,85 +20,94 @@ def yangshi1():
style.alignment = alignment # 给样式添加文字居中属性
style.font.height = 430 # 设置字体大小
return style
def yangshi2():
style1 = XFStyle()
alignment = xlwt.Alignment()
alignment.horz = xlwt.Alignment.HORZ_CENTER
alignment.vert = xlwt.Alignment.VERT_CENTER
style1.alignment = alignment # 给样式添加文字居中属性
style1.font.height = 330 # 设置字体大小
return style1
style1 = XFStyle()
alignment = xlwt.Alignment()
alignment.horz = xlwt.Alignment.HORZ_CENTER
alignment.vert = xlwt.Alignment.VERT_CENTER
style1.alignment = alignment # 给样式添加文字居中属性
style1.font.height = 330 # 设置字体大小
return style1
def yangshi3():
style1 = XFStyle()
style1.font.height = 330 # 设置字体大小
return style1
style1 = XFStyle()
style1.font.height = 330 # 设置字体大小
return style1
def yangshique(me):
if me =='pass':
style=yangshi1()
Pattern=xlwt.Pattern()
Pattern.pattern=xlwt.Pattern.SOLID_PATTERN
Pattern.pattern_fore_colour=xlwt.Style.colour_map['green']
style.pattern=Pattern
else :
style=yangshi2()
Pattern=xlwt.Pattern()
Pattern.pattern=xlwt.Pattern.SOLID_PATTERN
Pattern.pattern_fore_colour=xlwt.Style.colour_map['red']
style.pattern=Pattern
return style
def create(filename,list_pass,list_fail,listids,listnames,listkeys,listconeents,listurls,listfangshis,listqiwangs,list_json,listrelust):
if me == 'pass':
style = yangshi1()
Pattern = xlwt.Pattern()
Pattern.pattern = xlwt.Pattern.SOLID_PATTERN
Pattern.pattern_fore_colour = xlwt.Style.colour_map['green']
style.pattern = Pattern
else:
style = yangshi2()
Pattern = xlwt.Pattern()
Pattern.pattern = xlwt.Pattern.SOLID_PATTERN
Pattern.pattern_fore_colour = xlwt.Style.colour_map['red']
style.pattern = Pattern
return style
def create(filename, list_pass, list_fail, listids, listnames, listkeys, listconeents, listurls, listfangshis,
listqiwangs, list_json, listrelust):
filepath = open(r'.\config\test_report.yaml', encoding='utf-8')
file_config = yaml.load(filepath)
file = Workbook(filename)
table = file.add_sheet('测试结果',cell_overwrite_ok=True)
style=yangshi1()
table = file.add_sheet('测试结果', cell_overwrite_ok=True)
style = yangshi1()
for i in range(0, 7):
table.col(i).width = 380*20
style1=yangshi2()
table.write_merge(0,0,0,6,'测试报告',style=style)
table.write_merge(1,1,0,6,'',style=style)
table.write_merge(2,3,0,6,'测试详情',style=style1)
table.write(4,0,'项目名称',style=style1)
table.write(5,0,'接口版本',style=style1)
table.write(6,0,'提测时间',style=style1)
table.write(7,0,'提测人',style=style1)
table.write(4,2,'测试人',style=style1)
table.write(5,2,'测试时间',style=style1)
table.write(6,2,'审核人',style=style1)
table.write(4,4,'通过',style=style1)
table.write(5,4,'失败',style=style1)
table.write(6,4,'成功率',style=style1)
table.write(4, 1, (file_config['projectname']),style=style1)
table.write(5, 1, file_config['interfaceVersion'],style=style1)
table.write(6, 1, file_config['tijiao_time'],style=style1)
table.write(7, 1, file_config['tijiao_person'],style=style1)
table.write(4, 3, file_config['ceshi_person'],style=style1)
table.write(5, 3, file_config['ceshi_time'],style=style1)
table.write(6, 3, file_config['shenhename'],style=style1)
table.col(i).width = 380 * 20
style1 = yangshi2()
table.write_merge(0, 0, 0, 6, '测试报告', style=style)
table.write_merge(1, 1, 0, 6, '', style=style)
table.write_merge(2, 3, 0, 6, '测试详情', style=style1)
table.write(4, 0, '项目名称', style=style1)
table.write(5, 0, '接口版本', style=style1)
table.write(6, 0, '提测时间', style=style1)
table.write(7, 0, '提测人', style=style1)
table.write(4, 2, '测试人', style=style1)
table.write(5, 2, '测试时间', style=style1)
table.write(6, 2, '审核人', style=style1)
table.write(4, 4, '通过', style=style1)
table.write(5, 4, '失败', style=style1)
table.write(6, 4, '成功率', style=style1)
table.write(4, 1, (file_config['projectname']), style=style1)
table.write(5, 1, file_config['interfaceVersion'], style=style1)
table.write(6, 1, file_config['tijiao_time'], style=style1)
table.write(7, 1, file_config['tijiao_person'], style=style1)
table.write(4, 3, file_config['ceshi_person'], style=style1)
table.write(5, 3, file_config['ceshi_time'], style=style1)
table.write(6, 3, file_config['shenhename'], style=style1)
table.write(4, 5, (list_pass), style=style1)
table.write(5, 5, (list_fail), style=style1)
table.write(6, 5, ('%.2f%%'%((list_pass)/(len(listrelust)))), style=style1)
table1 = file.add_sheet('测试详情',cell_overwrite_ok=True)
table1.write_merge(0,0,0,8,'测试详情',style=style)
table.write(6, 5, ('%.2f%%' % ((list_pass) / (len(listrelust)))), style=style1)
table1 = file.add_sheet('测试详情', cell_overwrite_ok=True)
table1.write_merge(0, 0, 0, 8, '测试详情', style=style)
for i in range(0, 8):
table1.col(i).width = 400*20
table1.write(1,0,'用例ID',style=yangshi3())
table1.write(1,1,'用例名字',style=yangshi3())
table1.write(1,2,'key',style=yangshi3())
table1.write(1,3,'请求内容',style=yangshi3())
table1.write(1,4,' url',style=yangshi3())
table1.write(1,5,'请求方式',style=yangshi3())
table1.write(1,6,'预期',style=yangshi3())
table1.write(1,7,'实际返回',style=yangshi3())
table1.write(1,8,'结果',style=yangshi3())
table1.col(i).width = 400 * 20
table1.write(1, 0, '用例ID', style=yangshi3())
table1.write(1, 1, '用例名字', style=yangshi3())
table1.write(1, 2, 'key', style=yangshi3())
table1.write(1, 3, '请求内容', style=yangshi3())
table1.write(1, 4, ' url', style=yangshi3())
table1.write(1, 5, '请求方式', style=yangshi3())
table1.write(1, 6, '预期', style=yangshi3())
table1.write(1, 7, '实际返回', style=yangshi3())
table1.write(1, 8, '结果', style=yangshi3())
for i in range(len(listids)):
table1.write(i+1, 0, listids[i],style=yangshi3())
table1.write(i+1, 1, listnames[i],style=yangshi3())
table1.write(i+1, 2, listkeys[i],style=yangshi3())
table1.write(i+1, 3, listconeents[i],style=yangshi3())
table1.write(i+1, 4, listurls[i],style=yangshi3())
table1.write(i+1, 5, listfangshis[i],style=yangshi3())
table1.write(i+1, 6, listqiwangs[i],style=yangshi3())
table1.write(i+1, 7, str(list_json[i]),style=yangshi3())
table1.write(i+1, 8, listrelust[i], style=yangshique(listrelust[i]))
table1.write(i + 1, 0, listids[i], style=yangshi3())
table1.write(i + 1, 1, listnames[i], style=yangshi3())
table1.write(i + 1, 2, listkeys[i], style=yangshi3())
table1.write(i + 1, 3, listconeents[i], style=yangshi3())
table1.write(i + 1, 4, listurls[i], style=yangshi3())
table1.write(i + 1, 5, listfangshis[i], style=yangshi3())
table1.write(i + 1, 6, listqiwangs[i], style=yangshi3())
table1.write(i + 1, 7, str(list_json[i]), style=yangshi3())
table1.write(i + 1, 8, listrelust[i], style=yangshique(listrelust[i]))
file.save(filename)

View File

@@ -1 +1 @@
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-

View File

@@ -3,6 +3,6 @@
@file: config_T.py
@time: 2018/4/12 14:17
"""
Dingtalk_access_token="" #钉钉配置
TestPlanUrl='http://www.tuling123.com' #基础url
Config_Try_Num=3#失败重试
Dingtalk_access_token = "" # 钉钉配置
TestPlanUrl = 'http://www.tuling123.com' # 基础url
Config_Try_Num = 3 # 失败重试

View File

@@ -1,26 +1,31 @@
# -*- coding: utf-8 -*-
# @Author : leizi
import os,datetime,time
import os, datetime, time
from testCase.dubbocase import testdubbointerface
from Public.py_Html import createHtml
from Public.get_excel import datacel
from Public.Dingtalk import send_ding
def start_dubbo_case():
starttime=datetime.datetime.now()
day= time.strftime("%Y%m%d%H%M", time.localtime(time.time()))
basdir=os.path.abspath(os.path.dirname(__file__))
starttime = datetime.datetime.now()
day = time.strftime("%Y%m%d%H%M", time.localtime(time.time()))
basdir = os.path.abspath(os.path.dirname(__file__))
path = os.getcwd() + '\\test_case_data\\dubbocase.xlsx'
listid, listkey, listconeent, listurl, listfangshi, listqiwang, listname = datacel(path)
listrelust, list_fail, list_pass, list_json,list_exption,list_weizhi = testdubbointerface()
filepath =os.path.join(basdir+'\\test_Report\\%s-result.html'%day)
listrelust, list_fail, list_pass, list_json, list_exption, list_weizhi = testdubbointerface()
filepath = os.path.join(basdir + '\\test_Report\\%s-result.html' % day)
if os.path.exists(filepath) is False:
os.system(r'touch %s' % filepath)
endtime=datetime.datetime.now()
createHtml(titles='dubbo接口自动化测试报告',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,weizhi=list_weizhi,exceptions=list_exption)
contec='dubbo接口自动化测试完成测试通过:%s,测试失败:%s,异常:%s,未知错误:%s,详情见:%s'%(list_pass,list_fail,list_exption,list_weizhi,filepath)
endtime = datetime.datetime.now()
createHtml(titles='dubbo接口自动化测试报告', 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, weizhi=list_weizhi, exceptions=list_exption)
contec = 'dubbo接口自动化测试完成测试通过:%s,测试失败:%s,异常:%s,未知错误:%s,详情见:%s' % (
list_pass, list_fail, list_exption, list_weizhi, filepath)
send_ding(content=contec)
if __name__ == '__main__':
start_dubbo_case()

View File

@@ -4,29 +4,35 @@
@file: run_excel_re.py
@time: 2017/6/9 12:45
"""
from Public.pyreport_excel import create
import os,threading,datetime
from Public.pyreport_excel import create
import os, threading, datetime
from testCase.case import testinterface
from Public.emmail import sendemali
from Public.get_excel import datacel
from Public.emmail import sendemali
from Public.get_excel import datacel
from Public.create_report import save_result
def start():
starttime=datetime.datetime.now()
m=datetime.datetime.now().strftime("%Y%m%d")
starttime = datetime.datetime.now()
m = datetime.datetime.now().strftime("%Y%m%d")
basdir = os.path.abspath(os.path.dirname(__file__))
listid,listkey,listconeent,listurl,listfangshi,listqiwang,listname=datacel()
listrelust,list_fail, list_pass, list_json =testinterface()
filepath = os.path.join(basdir + '\\test_Report\\%s-result.xls'%m)
listid, listkey, listconeent, listurl, listfangshi, listqiwang, listname = datacel()
listrelust, list_fail, list_pass, list_json = testinterface()
filepath = os.path.join(basdir + '\\test_Report\\%s-result.xls' % m)
if os.path.exists(filepath) is False:
os.system(r'touch %s' % filepath)
save_result(starttime, len(listrelust), ((list_pass)), list_fail)
create(filename=filepath,list_fail=list_fail, list_pass=list_pass, list_json=list_json, listurls=listurl,
listkeys=listkey,listconeents=listconeent, listfangshis=listfangshi, listqiwangs=listqiwang,
create(filename=filepath, list_fail=list_fail, list_pass=list_pass, list_json=list_json, listurls=listurl,
listkeys=listkey, listconeents=listconeent, listfangshis=listfangshi, listqiwangs=listqiwang,
listids=listid, listrelust=listrelust, listnames=listname)
def teThread():
st = datetime.datetime.now()
m = threading.Thread(target=start, args=())
m.run()
end = datetime.datetime.now()
if __name__ == '__main__':
teThread()

View File

@@ -1,34 +1,36 @@
# -*- coding: utf-8 -*-
# @Author : leizi
import unittest,os,datetime,time
import unittest, os, datetime, time
from testCase.case import testinterface
from Public.py_Html import createHtml
from Public.get_excel import datacel
from Public.emmail import sendemali
from Public.emmail import sendemali
from Public.create_report import save_result
import threading
import threading
def stast():
starttime=datetime.datetime.now()
day= time.strftime("%Y%m%d%H%M", time.localtime(time.time()))
basdir=os.path.abspath(os.path.dirname(__file__))
starttime = datetime.datetime.now()
day = time.strftime("%Y%m%d%H%M", time.localtime(time.time()))
basdir = os.path.abspath(os.path.dirname(__file__))
listid, listkey, listconeent, listurl, listfangshi, listqiwang, listname = datacel()
listrelust, list_fail, list_pass, list_json = testinterface()
filepath =os.path.join(basdir+'\\test_Report\\%s-result.html'%day)
filepath = 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)
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)
# sendemali(filepath)
def tThread():
m=threading.Thread(target=stast,args=())
m = threading.Thread(target=stast, args=())
m.run()
if __name__ == '__main__':
tThread()

View File

@@ -1,28 +1,33 @@
# -*- coding: utf-8 -*-
# @Author : leizi
import os,datetime,time
import os, datetime, time
from testCase.case import testinterface
from Public.py_Html import createHtml
from Public.get_excel import datacel
from Public.Dingtalk import send_ding
from Public.Dingtalk import send_ding
'''执行测试的主要文件'''
def start_interface_html_http():
starttime=datetime.datetime.now()
day= time.strftime("%Y%m%d%H%M", time.localtime(time.time()))
basdir=os.path.abspath(os.path.dirname(__file__))
starttime = datetime.datetime.now()
day = time.strftime("%Y%m%d%H%M", time.localtime(time.time()))
basdir = os.path.abspath(os.path.dirname(__file__))
path = os.getcwd() + '\\test_case_data\\case.xlsx'
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(basdir+'\\test_Report\\%s-result.html'%day)
listrelust, list_fail, list_pass, list_json, list_exption, list_weizhi = testinterface()
filepath = os.path.join(basdir + '\\test_Report\\%s-result.html' % day)
if os.path.exists(filepath) is False:
os.system(r'touch %s' % filepath)
endtime=datetime.datetime.now()
createHtml(titles=u'http接口自动化测试报告',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,weizhi=list_weizhi,exceptions=list_exption)
endtime = datetime.datetime.now()
createHtml(titles=u'http接口自动化测试报告', 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, weizhi=list_weizhi, exceptions=list_exption)
contec = u'http接口自动化测试完成测试通过:%s,测试失败:%s,异常:%s,未知错误:%s,详情见:%s' % (
list_pass, list_fail, list_exption, list_weizhi, filepath)
list_pass, list_fail, list_exption, list_weizhi, filepath)
send_ding(content=contec)
if __name__ == '__main__':
start_interface_html_http()

View File

@@ -1,9 +1,10 @@
# -*- coding: utf-8 -*-
# @Author : leizi
from testCase.ddt_case import MyTest
import unittest,time,os
from Public import BSTestRunner
if __name__=='__main__':
from testCase.ddt_case import MyTest
import unittest, time, os
from Public import BSTestRunner
if __name__ == '__main__':
suite = unittest.TestSuite()
suite.addTests(unittest.TestLoader().loadTestsFromTestCase(MyTest))
now = time.strftime('%Y-%m%d', time.localtime(time.time()))

View File

@@ -6,10 +6,13 @@ from Interface.testFengzhuang import TestApi
from Public.get_excel import datacel
from Public.log import LOG, logger
import os
from config.config_T import Config_Try_Num,TestPlanUrl
from config.config_T import Config_Try_Num, TestPlanUrl
path = os.getcwd() + '\\test_case_data\\case.xlsx'
listid, listkey, listconeent, listurl, listfangshi, listqiwang, listname = datacel(path)
from Public.panduan import assert_in
@logger('测试')
def testinterface():
list_pass = 0
@@ -18,10 +21,10 @@ def testinterface():
listrelust = []
list_weizhi = 0
list_exption = 0
error_num=0
error_num = 0
for i in range(len(listurl)):
while error_num<=Config_Try_Num+1:
api = TestApi(url=TestPlanUrl+listurl[i], key=listkey[i], connent=listconeent[i], fangshi=listfangshi[i])
while error_num <= Config_Try_Num + 1:
api = TestApi(url=TestPlanUrl + listurl[i], key=listkey[i], connent=listconeent[i], fangshi=listfangshi[i])
apijson = api.getJson()
if apijson['code'] == 0:
LOG.info('inputdata> 参数:%s, url:%s ,返回:%s,预期:%s' % (listconeent[i], listurl[i], apijson, listqiwang[i]))
@@ -30,48 +33,48 @@ def testinterface():
list_json.append(apijson['result'])
listrelust.append('pass')
list_pass += 1
error_num=0
error_num = 0
continue
elif assert_re['code'] == 1:
if error_num <=Config_Try_Num:
error_num+=1
if error_num <= Config_Try_Num:
error_num += 1
LOG.info('失败重试中')
else:
LOG.info('失败重试中次数用完,最后结果')
error_num=0
error_num = 0
list_fail += 1
listrelust.append('fail')
list_json.append(apijson['result'])
break
elif assert_re['code'] == 2:
if error_num <Config_Try_Num:
error_num+=1
if error_num < Config_Try_Num:
error_num += 1
LOG.info('失败重试中')
else:
LOG.info('失败重试中次数用完,最后结果')
error_num=0
error_num = 0
list_exption += 1
listrelust.append('exception')
list_json.append(assert_re['result'])
break
else:
if error_num <Config_Try_Num:
error_num+=1
if error_num < Config_Try_Num:
error_num += 1
LOG.info('失败重试中')
else:
LOG.info('失败重试中次数用完,最后结果')
error_num=0
error_num = 0
list_weizhi += 1
listrelust.append('未知错误')
list_json.append('未知错误')
break
else:
if error_num <Config_Try_Num:
error_num+=1
if error_num < Config_Try_Num:
error_num += 1
LOG.info('失败重试中')
else:
LOG.info('失败重试中次数用完,最后结果')
error_num=0
error_num = 0
list_exption += 1
listrelust.append('exception')
list_json.append(apijson['result'])

View File

@@ -1,20 +1,29 @@
from Interface.testFengzhuang import TestApi
from Public.get_excel import datacel,makedata
from Public.log import LOG,logger
from Interface.testFengzhuang import TestApi
from Public.get_excel import datacel, makedata
from Public.log import LOG, logger
from Public.panduan import assertre
import ddt,unittest,time,os
data_test=makedata()
import ddt, unittest, time, os
data_test = makedata()
@ddt.ddt
class MyTest(unittest.TestCase):
def setUp(self):
LOG.info('测试用例开始执行')
def tearDown(self):
LOG.info('测试用例执行完毕')
@ddt.data(*data_test)
def test_api(self,data_test):
api = TestApi(url=data_test['url'], key=data_test['key'], connent=data_test['coneent'], fangshi=data_test['fangshi'])
LOG.info('输入参数url:%s,key:%s,参数:%s,请求方式:%s'%(data_test['url'],data_test['key'],data_test['coneent'], LOG.info('输入参数url:%s,key:%s,参数:%s,请求方式:%s'%(data_test['url'],data_test['key'],data_test['coneent'],data_test['fangshi']))))
def test_api(self, data_test):
api = TestApi(url=data_test['url'], key=data_test['key'], connent=data_test['coneent'],
fangshi=data_test['fangshi'])
LOG.info('输入参数url:%s,key:%s,参数:%s,请求方式:%s' % (data_test['url'], data_test['key'], data_test['coneent'],
LOG.info('输入参数url:%s,key:%s,参数:%s,请求方式:%s' % (
data_test['url'], data_test['key'], data_test['coneent'],
data_test['fangshi']))))
apijson = api.getJson()
LOG.info('返回结果:%s'%apijson)
qingwang=assertre(asserqingwang=data_test['qiwang'])
self.assertNotEqual(dict(qingwang),dict(apijson),msg='预期和返回不一致')
LOG.info('返回结果:%s' % apijson)
qingwang = assertre(asserqingwang=data_test['qiwang'])
self.assertNotEqual(dict(qingwang), dict(apijson), msg='预期和返回不一致')

View File

@@ -4,12 +4,15 @@
@time: 2018/3/29 12:47
"""
from Interface.dubbo_feng import DubboInterface
from Public.log import LOG,logger
from Public.log import LOG, logger
from Public.panduan import assert_in
from Public.get_excel import datacel
from Public.get_excel import datacel
import os
path=os.getcwd()+'\\test_case_data\\dubbocase.xlsx'
listid,listurl,listinterface,listmeth,listfobject,listparam,listassert=datacel(path)
path = os.getcwd() + '\\test_case_data\\dubbocase.xlsx'
listid, listurl, listinterface, listmeth, listfobject, listparam, listassert = datacel(path)
@logger('dubbo接口测试')
def testdubbointerface():
list_pass = 0
@@ -19,8 +22,9 @@ def testdubbointerface():
list_weizhi = 0
list_exption = 0
for i in range(len(listid)):
dubboapi=DubboInterface(url=listurl,interface=listinterface[i],method=listmeth[i],param=listfobject[i],**(eval(listparam[i])))
dubboapireslu=dubboapi.getresult()
dubboapi = DubboInterface(url=listurl, interface=listinterface[i], method=listmeth[i], param=listfobject[i],
**(eval(listparam[i])))
dubboapireslu = dubboapi.getresult()
if dubboapireslu['code'] == 0:
LOG.info('inputdata> 参数:%s, url:%s ,返回:%s,预期:%s' % (listparam[i], listurl[i], dubboapireslu, listassert[i]))
assert_re = assert_in(asserqiwang=listassert[i], fanhuijson=dubboapireslu)

View File

@@ -1,6 +1,6 @@
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
@@ -9,48 +9,56 @@
<meta name="generator" content="BSTestRunner 0.8.4"/>
<link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css">
<style type="text/css" media="screen">
<style type="text/css" media="screen">
/* -- css div popup ------------------------------------------------------------------------ */
.popup_window {
display: none;
position: relative;
left: 0px;
top: 0px;
/*border: solid #627173 1px; */
padding: 10px;
background-color: #99CCFF;
font-family: "Lucida Console", "Courier New", Courier, monospace;
text-align: left;
font-size: 10pt;
width: 1200px;
}
/* -- css div popup ------------------------------------------------------------------------ */
.popup_window {
display: none;
position: relative;
left: 0px;
top: 0px;
/*border: solid #627173 1px; */
padding: 10px;
background-color: #99CCFF;
font-family: "Lucida Console", "Courier New", Courier, monospace;
text-align: left;
font-size: 10pt;
width: 1200px;
}
/* -- report ------------------------------------------------------------------------ */
/* -- report ------------------------------------------------------------------------ */
#show_detail_line .label {
font-size: 85%;
cursor: pointer;
}
#show_detail_line .label {
font-size: 85%;
cursor: pointer;
}
#show_detail_line {
margin: 2em auto 1em auto;
}
#show_detail_line {
margin: 2em auto 1em auto;
}
#total_row { font-weight: bold; }
.hiddenRow { display: none; }
.testcase { margin-left: 2em; }
#total_row {
font-weight: bold;
}
</style>
.hiddenRow {
display: none;
}
.testcase {
margin-left: 2em;
}
</style>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="http://cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="http://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
<script src="http://cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="http://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
</head>
<body>
<script language="javascript" type="text/javascript"><!--
output_list = Array();
@@ -61,19 +69,17 @@ function showCase(level) {
for (var i = 0; i < trs.length; i++) {
tr = trs[i];
id = tr.id;
if (id.substr(0,2) == 'ft') {
if (id.substr(0, 2) == 'ft') {
if (level < 1) {
tr.className = 'hiddenRow';
}
else {
} else {
tr.className = '';
}
}
if (id.substr(0,2) == 'pt') {
if (id.substr(0, 2) == 'pt') {
if (level > 1) {
tr.className = '';
}
else {
} else {
tr.className = 'hiddenRow';
}
}
@@ -85,7 +91,7 @@ function showClassDetail(cid, count) {
var id_list = Array(count);
var toHide = 1;
for (var i = 0; i < count; i++) {
tid0 = 't' + cid.substr(1) + '.' + (i+1);
tid0 = 't' + cid.substr(1) + '.' + (i + 1);
tid = 'f' + tid0;
tr = document.getElementById(tid);
if (!tr) {
@@ -100,34 +106,32 @@ function showClassDetail(cid, count) {
for (var i = 0; i < count; i++) {
tid = id_list[i];
if (toHide) {
document.getElementById('div_'+tid).style.display = 'none'
document.getElementById('div_' + tid).style.display = 'none'
document.getElementById(tid).className = 'hiddenRow';
}
else {
} else {
document.getElementById(tid).className = '';
}
}
}
function showTestDetail(div_id){
function showTestDetail(div_id) {
var details_div = document.getElementById(div_id)
var displayState = details_div.style.display
// alert(displayState)
if (displayState != 'block' ) {
if (displayState != 'block') {
displayState = 'block'
details_div.style.display = 'block'
}
else {
} else {
details_div.style.display = 'none'
}
}
function html_escape(s) {
s = s.replace(/&/g,'&amp;');
s = s.replace(/</g,'&lt;');
s = s.replace(/>/g,'&gt;');
s = s.replace(/&/g, '&amp;');
s = s.replace(/</g, '&lt;');
s = s.replace(/>/g, '&gt;');
return s;
}
@@ -149,57 +153,67 @@ function showOutput(id, name) {
<div class="container">
<div class='heading'>
<h1>接口测试报告</h1>
<p><strong>Start Time:</strong> 2017-11-01 10:25:40</p>
<p><strong>Duration:</strong> 0:00:00.070004</p>
<p><strong>Status:</strong> <span class="text text-success">Pass <strong>2</strong></span> <span class="text text-warning">Error <strong>1</strong></span></p>
<h1>接口测试报告</h1>
<p><strong>Start Time:</strong> 2017-11-01 10:25:40</p>
<p><strong>Duration:</strong> 0:00:00.070004</p>
<p><strong>Status:</strong> <span class="text text-success">Pass <strong>2</strong></span> <span
class="text text-warning">Error <strong>1</strong></span></p>
<p class='description'>测试结果</p>
</div>
<p class='description'>测试结果</p>
</div>
<p id='show_detail_line'>
<span class="label label-primary" onclick="showCase(0)">Summary</span>
<span class="label label-danger" onclick="showCase(1)">Failed</span>
<span class="label label-default" onclick="showCase(2)">All</span>
</p>
<table id='result_table' class="table">
<thead>
<p id='show_detail_line'>
<span class="label label-primary" onclick="showCase(0)">Summary</span>
<span class="label label-danger" onclick="showCase(1)">Failed</span>
<span class="label label-default" onclick="showCase(2)">All</span>
</p>
<table id='result_table' class="table">
<thead>
<tr id='header_row'>
<th>Test Group/Test case</td>
<th>Count</td>
<th>Pass</td>
<th>Fail</td>
<th>Error</td>
<th>View</td>
<th>Test Group/Test case
</td>
<th>Count
</td>
<th>Pass
</td>
<th>Fail
</td>
<th>Error
</td>
<th>View
</td>
</tr>
</thead>
<tbody>
</thead>
<tbody>
<tr class='text text-warning'>
<td>testCase.ddt_case.MyTest</td>
<td>3</td>
<td>2</td>
<td>0</td>
<td>1</td>
<td><a class="btn btn-xs btn-primary"href="javascript:showClassDetail('c1',3)">Detail</a></td>
</tr>
<tr class='text text-warning'>
<td>testCase.ddt_case.MyTest</td>
<td>3</td>
<td>2</td>
<td>0</td>
<td>1</td>
<td><a class="btn btn-xs btn-primary" href="javascript:showClassDetail('c1',3)">Detail</a></td>
</tr>
<tr id='pt1.1' class='hiddenRow'>
<td class='text text-success'><div class='testcase'>test_api_1</div></td>
<td colspan='5' align='center'>
<tr id='pt1.1' class='hiddenRow'>
<td class='text text-success'>
<div class='testcase'>test_api_1</div>
</td>
<td colspan='5' align='center'>
<!--css div popup start-->
<a class="popup_link btn btn-xs btn-default" onfocus='this.blur();' href="javascript:showTestDetail('div_pt1.1')" >
pass</a>
<!--css div popup start-->
<a class="popup_link btn btn-xs btn-default" onfocus='this.blur();'
href="javascript:showTestDetail('div_pt1.1')">
pass</a>
<div id='div_pt1.1' class="popup_window">
<div style='text-align: right;cursor:pointer'>
<a onfocus='this.blur();' onclick="document.getElementById('div_pt1.1').style.display = 'none' " >
[x]</a>
</div>
<pre>
<div id='div_pt1.1' class="popup_window">
<div style='text-align: right;cursor:pointer'>
<a onfocus='this.blur();'
onclick="document.getElementById('div_pt1.1').style.display = 'none' ">
[x]</a>
</div>
<pre>
pt1.1: [2017-11-01 10:25:40.109053] INFO: jiekou: 测试用例开始执行
[2017-11-01 10:25:40.109053] INFO: jiekou: 输入参数url:http://www.tuling123.com/openapi/api,key:aaaa,参数:sasa,请求方式POST
@@ -210,26 +224,30 @@ pt1.1: [2017-11-01 10:25:40.109053] INFO: jiekou: 测试用例开始执行
</pre>
</div>
<!--css div popup end-->
</div>
<!--css div popup end-->
</td>
</tr>
</td>
</tr>
<tr id='pt1.2' class='hiddenRow'>
<td class='text text-success'><div class='testcase'>test_api_2</div></td>
<td colspan='5' align='center'>
<tr id='pt1.2' class='hiddenRow'>
<td class='text text-success'>
<div class='testcase'>test_api_2</div>
</td>
<td colspan='5' align='center'>
<!--css div popup start-->
<a class="popup_link btn btn-xs btn-default" onfocus='this.blur();' href="javascript:showTestDetail('div_pt1.2')" >
pass</a>
<!--css div popup start-->
<a class="popup_link btn btn-xs btn-default" onfocus='this.blur();'
href="javascript:showTestDetail('div_pt1.2')">
pass</a>
<div id='div_pt1.2' class="popup_window">
<div style='text-align: right;cursor:pointer'>
<a onfocus='this.blur();' onclick="document.getElementById('div_pt1.2').style.display = 'none' " >
[x]</a>
</div>
<pre>
<div id='div_pt1.2' class="popup_window">
<div style='text-align: right;cursor:pointer'>
<a onfocus='this.blur();'
onclick="document.getElementById('div_pt1.2').style.display = 'none' ">
[x]</a>
</div>
<pre>
pt1.2: [2017-11-01 10:25:40.144055] INFO: jiekou: 测试用例开始执行
[2017-11-01 10:25:40.144055] INFO: jiekou: 输入参数url:http://www.tuling123.com/openapi/api
@@ -242,26 +260,30 @@ pt1.2: [2017-11-01 10:25:40.144055] INFO: jiekou: 测试用例开始执行
</pre>
</div>
<!--css div popup end-->
</div>
<!--css div popup end-->
</td>
</tr>
</td>
</tr>
<tr id='ft1.3' class='none'>
<td class='text text-warning'><div class='testcase'>test_api_3</div></td>
<td colspan='5' align='center'>
<tr id='ft1.3' class='none'>
<td class='text text-warning'>
<div class='testcase'>test_api_3</div>
</td>
<td colspan='5' align='center'>
<!--css div popup start-->
<a class="popup_link btn btn-xs btn-default" onfocus='this.blur();' href="javascript:showTestDetail('div_ft1.3')" >
error</a>
<!--css div popup start-->
<a class="popup_link btn btn-xs btn-default" onfocus='this.blur();'
href="javascript:showTestDetail('div_ft1.3')">
error</a>
<div id='div_ft1.3' class="popup_window">
<div style='text-align: right;cursor:pointer'>
<a onfocus='this.blur();' onclick="document.getElementById('div_ft1.3').style.display = 'none' " >
[x]</a>
</div>
<pre>
<div id='div_ft1.3' class="popup_window">
<div style='text-align: right;cursor:pointer'>
<a onfocus='this.blur();'
onclick="document.getElementById('div_ft1.3').style.display = 'none' ">
[x]</a>
</div>
<pre>
ft1.3: [2017-11-01 10:25:40.178057] INFO: jiekou: 测试用例开始执行
[2017-11-01 10:25:40.178057] INFO: jiekou: 输入参数url:https://api.douban.com/v2/photo/:id,key:,参数:,请求方式GET
@@ -280,14 +302,14 @@ TypeError: get() takes 2 positional arguments but 3 were given
</pre>
</div>
<!--css div popup end-->
</div>
<!--css div popup end-->
</td>
</tr>
</td>
</tr>
</tbody>
<tfoot>
</tbody>
<tfoot>
<tr id='total_row'>
<td>Total</td>
<td>3</td>
@@ -296,8 +318,8 @@ TypeError: get() takes 2 positional arguments but 3 were given
<td class="text text-warning">1</td>
<td>&nbsp;</td>
</tr>
</tfoot>
</table>
</tfoot>
</table>
<div id='ending'>&nbsp;</div>
</div>

View File

@@ -1,86 +1,89 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>接口测试报告</title>
<style type="text/css">
td{ width:40px; height:50px;}
</style>
</head>
<body>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>接口测试报告</title>
<style type="text/css">
td {
width: 40px;
height: 50px;
}
</style>
</head>
<body>
<div style='width: 1170px;margin-left: 15%'>
<h1>接口测试的结果</h1>
<p><strong>开始时间:</strong> 2017-10-16 20:54:47.323436</p>
<p><strong>结束时间:</strong> 2017-10-16 20:54:48.234489</p>
<p><strong>耗时:</strong> 0:00:00.911053</p>
<p><strong>结果:</strong>
<span >Pass: <strong >3</strong>
Fail: <strong >0</strong>
<h1>接口测试的结果</h1>
<p><strong>开始时间:</strong> 2017-10-16 20:54:47.323436</p>
<p><strong>结束时间:</strong> 2017-10-16 20:54:48.234489</p>
<p><strong>耗时:</strong> 0:00:00.911053</p>
<p><strong>结果:</strong>
<span>Pass: <strong>3</strong>
Fail: <strong>0</strong>
</span></p>
<p ><strong>测试详情如下</strong></p> </div>
<p><strong>测试详情如下</strong></p></div>
<p>&nbsp;</p>
<table border='2'cellspacing='1' cellpadding='1' width='1100'align="center" >
<tr >
<td ><strong>用例ID&nbsp;</strong></td>
<td><strong>用例名字</strong></td>
<td><strong>key</strong></td>
<td><strong>请求内容</strong></td>
<td><strong>url</strong></td>
<td><strong>请求方式</strong></td>
<td><strong>预期</strong></td>
<td><strong>实际返回</strong></td>
<td><strong>结果</strong></td>
</tr>
<p>&nbsp;</p>
<table border='2' cellspacing='1' cellpadding='1' width='1100' align="center">
<tr>
<td><strong>用例ID&nbsp;</strong></td>
<td><strong>用例名字</strong></td>
<td><strong>key</strong></td>
<td><strong>请求内容</strong></td>
<td><strong>url</strong></td>
<td><strong>请求方式</strong></td>
<td><strong>预期</strong></td>
<td><strong>实际返回</strong></td>
<td><strong>结果</strong></td>
</tr>
<tr>
<td>1.0</td>
<td>图灵api接口</td>
<tr>
<td>1.0</td>
<td>图灵api接口</td>
<td>aaaa</td>
<td>sasa
</td>
<td>http://www.tuling123.com/openapi/api</td>
<td>POST</td>
<td>code=40001</td>
<td>{'code': 40001, 'text': '亲爱的key不对哦。'}</td>
<td bgcolor="green">pass</td>
</tr>
<td>aaaa</td>
<td>sasa
</td>
<td>http://www.tuling123.com/openapi/api</td>
<td>POST</td>
<td>code=40001</td>
<td>{'code': 40001, 'text': '亲爱的key不对哦。'}</td>
<td bgcolor="green">pass</td>
</tr>
<tr>
<td>2.0</td>
<td>图灵api接口</td>
<tr>
<td>2.0</td>
<td>图灵api接口</td>
<td>dfeb1cc8125943d29764a2f2f5c33739</td>
<td>
</td>
<td>http://www.tuling123.com/openapi/api
</td>
<td>POST</td>
<td>code=40002</td>
<td>{'code': 40002, 'text': '有啥事吗?'}</td>
<td bgcolor="green">pass</td>
</tr>
<td>dfeb1cc8125943d29764a2f2f5c33739</td>
<td>
</td>
<td>http://www.tuling123.com/openapi/api
</td>
<td>POST</td>
<td>code=40002</td>
<td>{'code': 40002, 'text': '有啥事吗?'}</td>
<td bgcolor="green">pass</td>
</tr>
<tr>
<td>3.0</td>
<td>豆瓣api</td>
<tr>
<td>3.0</td>
<td>豆瓣api</td>
<td></td>
<td>
</td>
<td>https://api.douban.com/v2/photo/:id</td>
<td>GET</td>
<td>code=1001&msg=uri_not_found</td>
<td>{'msg': 'uri_not_found', 'code': 1001, 'request': 'POST /v2/photo/:id'}</td>
<td bgcolor="green">pass</td>
</tr>
<td></td>
<td>
</td>
<td>https://api.douban.com/v2/photo/:id</td>
<td>GET</td>
<td>code=1001&msg=uri_not_found</td>
<td>{'msg': 'uri_not_found', 'code': 1001, 'request': 'POST /v2/photo/:id'}</td>
<td bgcolor="green">pass</td>
</tr>
</table>
</body>
</html>
</table>
</body>
</html>

View File

@@ -1,6 +1,6 @@
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
@@ -9,48 +9,56 @@
<meta name="generator" content="BSTestRunner 0.8.4"/>
<link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css">
<style type="text/css" media="screen">
<style type="text/css" media="screen">
/* -- css div popup ------------------------------------------------------------------------ */
.popup_window {
display: none;
position: relative;
left: 0px;
top: 0px;
/*border: solid #627173 1px; */
padding: 10px;
background-color: #99CCFF;
font-family: "Lucida Console", "Courier New", Courier, monospace;
text-align: left;
font-size: 10pt;
width: 1200px;
}
/* -- css div popup ------------------------------------------------------------------------ */
.popup_window {
display: none;
position: relative;
left: 0px;
top: 0px;
/*border: solid #627173 1px; */
padding: 10px;
background-color: #99CCFF;
font-family: "Lucida Console", "Courier New", Courier, monospace;
text-align: left;
font-size: 10pt;
width: 1200px;
}
/* -- report ------------------------------------------------------------------------ */
/* -- report ------------------------------------------------------------------------ */
#show_detail_line .label {
font-size: 85%;
cursor: pointer;
}
#show_detail_line .label {
font-size: 85%;
cursor: pointer;
}
#show_detail_line {
margin: 2em auto 1em auto;
}
#show_detail_line {
margin: 2em auto 1em auto;
}
#total_row { font-weight: bold; }
.hiddenRow { display: none; }
.testcase { margin-left: 2em; }
#total_row {
font-weight: bold;
}
</style>
.hiddenRow {
display: none;
}
.testcase {
margin-left: 2em;
}
</style>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="http://cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="http://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
<script src="http://cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="http://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
</head>
<body>
<script language="javascript" type="text/javascript"><!--
output_list = Array();
@@ -61,19 +69,17 @@ function showCase(level) {
for (var i = 0; i < trs.length; i++) {
tr = trs[i];
id = tr.id;
if (id.substr(0,2) == 'ft') {
if (id.substr(0, 2) == 'ft') {
if (level < 1) {
tr.className = 'hiddenRow';
}
else {
} else {
tr.className = '';
}
}
if (id.substr(0,2) == 'pt') {
if (id.substr(0, 2) == 'pt') {
if (level > 1) {
tr.className = '';
}
else {
} else {
tr.className = 'hiddenRow';
}
}
@@ -85,7 +91,7 @@ function showClassDetail(cid, count) {
var id_list = Array(count);
var toHide = 1;
for (var i = 0; i < count; i++) {
tid0 = 't' + cid.substr(1) + '.' + (i+1);
tid0 = 't' + cid.substr(1) + '.' + (i + 1);
tid = 'f' + tid0;
tr = document.getElementById(tid);
if (!tr) {
@@ -100,34 +106,32 @@ function showClassDetail(cid, count) {
for (var i = 0; i < count; i++) {
tid = id_list[i];
if (toHide) {
document.getElementById('div_'+tid).style.display = 'none'
document.getElementById('div_' + tid).style.display = 'none'
document.getElementById(tid).className = 'hiddenRow';
}
else {
} else {
document.getElementById(tid).className = '';
}
}
}
function showTestDetail(div_id){
function showTestDetail(div_id) {
var details_div = document.getElementById(div_id)
var displayState = details_div.style.display
// alert(displayState)
if (displayState != 'block' ) {
if (displayState != 'block') {
displayState = 'block'
details_div.style.display = 'block'
}
else {
} else {
details_div.style.display = 'none'
}
}
function html_escape(s) {
s = s.replace(/&/g,'&amp;');
s = s.replace(/</g,'&lt;');
s = s.replace(/>/g,'&gt;');
s = s.replace(/&/g, '&amp;');
s = s.replace(/</g, '&lt;');
s = s.replace(/>/g, '&gt;');
return s;
}
@@ -149,57 +153,67 @@ function showOutput(id, name) {
<div class="container">
<div class='heading'>
<h1>http接口测试报告</h1>
<p><strong>Start Time:</strong> 2018-04-02 10:53:02</p>
<p><strong>Duration:</strong> 0:00:02.914166</p>
<p><strong>Status:</strong> <span class="text text-success">Pass <strong>2</strong></span> <span class="text text-warning">Error <strong>1</strong></span></p>
<h1>http接口测试报告</h1>
<p><strong>Start Time:</strong> 2018-04-02 10:53:02</p>
<p><strong>Duration:</strong> 0:00:02.914166</p>
<p><strong>Status:</strong> <span class="text text-success">Pass <strong>2</strong></span> <span
class="text text-warning">Error <strong>1</strong></span></p>
<p class='description'>测试结果</p>
</div>
<p class='description'>测试结果</p>
</div>
<p id='show_detail_line'>
<span class="label label-primary" onclick="showCase(0)">Summary</span>
<span class="label label-danger" onclick="showCase(1)">Failed</span>
<span class="label label-default" onclick="showCase(2)">All</span>
</p>
<table id='result_table' class="table">
<thead>
<p id='show_detail_line'>
<span class="label label-primary" onclick="showCase(0)">Summary</span>
<span class="label label-danger" onclick="showCase(1)">Failed</span>
<span class="label label-default" onclick="showCase(2)">All</span>
</p>
<table id='result_table' class="table">
<thead>
<tr id='header_row'>
<th>Test Group/Test case</td>
<th>Count</td>
<th>Pass</td>
<th>Fail</td>
<th>Error</td>
<th>View</td>
<th>Test Group/Test case
</td>
<th>Count
</td>
<th>Pass
</td>
<th>Fail
</td>
<th>Error
</td>
<th>View
</td>
</tr>
</thead>
<tbody>
</thead>
<tbody>
<tr class='text text-warning'>
<td>testCase.ddt_case.MyTest</td>
<td>3</td>
<td>2</td>
<td>0</td>
<td>1</td>
<td><a class="btn btn-xs btn-primary"href="javascript:showClassDetail('c1',3)">Detail</a></td>
</tr>
<tr class='text text-warning'>
<td>testCase.ddt_case.MyTest</td>
<td>3</td>
<td>2</td>
<td>0</td>
<td>1</td>
<td><a class="btn btn-xs btn-primary" href="javascript:showClassDetail('c1',3)">Detail</a></td>
</tr>
<tr id='pt1.1' class='hiddenRow'>
<td class='text text-success'><div class='testcase'>test_api_1</div></td>
<td colspan='5' align='center'>
<tr id='pt1.1' class='hiddenRow'>
<td class='text text-success'>
<div class='testcase'>test_api_1</div>
</td>
<td colspan='5' align='center'>
<!--css div popup start-->
<a class="popup_link btn btn-xs btn-default" onfocus='this.blur();' href="javascript:showTestDetail('div_pt1.1')" >
pass</a>
<!--css div popup start-->
<a class="popup_link btn btn-xs btn-default" onfocus='this.blur();'
href="javascript:showTestDetail('div_pt1.1')">
pass</a>
<div id='div_pt1.1' class="popup_window">
<div style='text-align: right;cursor:pointer'>
<a onfocus='this.blur();' onclick="document.getElementById('div_pt1.1').style.display = 'none' " >
[x]</a>
</div>
<pre>
<div id='div_pt1.1' class="popup_window">
<div style='text-align: right;cursor:pointer'>
<a onfocus='this.blur();'
onclick="document.getElementById('div_pt1.1').style.display = 'none' ">
[x]</a>
</div>
<pre>
pt1.1: [2018-04-02 10:53:02.332375] INFO: jiekou: 测试用例开始执行
[2018-04-02 10:53:02.332375] INFO: jiekou: 输入参数url:http://www.tuling123.com/openapi/api,key:aaaa,参数:{'password':'1222'},请求方式POST
@@ -212,26 +226,30 @@ pt1.1: [2018-04-02 10:53:02.332375] INFO: jiekou: 测试用例开始执行
</pre>
</div>
<!--css div popup end-->
</div>
<!--css div popup end-->
</td>
</tr>
</td>
</tr>
<tr id='pt1.2' class='hiddenRow'>
<td class='text text-success'><div class='testcase'>test_api_2</div></td>
<td colspan='5' align='center'>
<tr id='pt1.2' class='hiddenRow'>
<td class='text text-success'>
<div class='testcase'>test_api_2</div>
</td>
<td colspan='5' align='center'>
<!--css div popup start-->
<a class="popup_link btn btn-xs btn-default" onfocus='this.blur();' href="javascript:showTestDetail('div_pt1.2')" >
pass</a>
<!--css div popup start-->
<a class="popup_link btn btn-xs btn-default" onfocus='this.blur();'
href="javascript:showTestDetail('div_pt1.2')">
pass</a>
<div id='div_pt1.2' class="popup_window">
<div style='text-align: right;cursor:pointer'>
<a onfocus='this.blur();' onclick="document.getElementById('div_pt1.2').style.display = 'none' " >
[x]</a>
</div>
<pre>
<div id='div_pt1.2' class="popup_window">
<div style='text-align: right;cursor:pointer'>
<a onfocus='this.blur();'
onclick="document.getElementById('div_pt1.2').style.display = 'none' ">
[x]</a>
</div>
<pre>
pt1.2: [2018-04-02 10:53:02.364376] INFO: jiekou: 测试用例开始执行
[2018-04-02 10:53:02.364376] INFO: jiekou: 输入参数url:http://www.tuling123.com/openapi/api
@@ -246,26 +264,30 @@ pt1.2: [2018-04-02 10:53:02.364376] INFO: jiekou: 测试用例开始执行
</pre>
</div>
<!--css div popup end-->
</div>
<!--css div popup end-->
</td>
</tr>
</td>
</tr>
<tr id='ft1.3' class='none'>
<td class='text text-warning'><div class='testcase'>test_api_3</div></td>
<td colspan='5' align='center'>
<tr id='ft1.3' class='none'>
<td class='text text-warning'>
<div class='testcase'>test_api_3</div>
</td>
<td colspan='5' align='center'>
<!--css div popup start-->
<a class="popup_link btn btn-xs btn-default" onfocus='this.blur();' href="javascript:showTestDetail('div_ft1.3')" >
error</a>
<!--css div popup start-->
<a class="popup_link btn btn-xs btn-default" onfocus='this.blur();'
href="javascript:showTestDetail('div_ft1.3')">
error</a>
<div id='div_ft1.3' class="popup_window">
<div style='text-align: right;cursor:pointer'>
<a onfocus='this.blur();' onclick="document.getElementById('div_ft1.3').style.display = 'none' " >
[x]</a>
</div>
<pre>
<div id='div_ft1.3' class="popup_window">
<div style='text-align: right;cursor:pointer'>
<a onfocus='this.blur();'
onclick="document.getElementById('div_ft1.3').style.display = 'none' ">
[x]</a>
</div>
<pre>
ft1.3: [2018-04-02 10:53:02.391378] INFO: jiekou: 测试用例开始执行
[2018-04-02 10:53:02.391378] INFO: jiekou: 输入参数url:https://api.douban.com/v2/photo/:id,key:dfeb1cc8125943d29764a2f2f5c33739,参数:{'password':'1222'},请求方式GET
@@ -289,14 +311,14 @@ TypeError: exceptions must derive from BaseException
</pre>
</div>
<!--css div popup end-->
</div>
<!--css div popup end-->
</td>
</tr>
</td>
</tr>
</tbody>
<tfoot>
</tbody>
<tfoot>
<tr id='total_row'>
<td>Total</td>
<td>3</td>
@@ -305,8 +327,8 @@ TypeError: exceptions must derive from BaseException
<td class="text text-warning">1</td>
<td>&nbsp;</td>
</tr>
</tfoot>
</table>
</tfoot>
</table>
<div id='ending'>&nbsp;</div>
</div>

View File

@@ -1,43 +1,47 @@
<!DOCTYPE html>
<html>
<head>
<title>http接口自动化测试报告</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>http接口自动化测试报告</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 Shim 和 Respond.js 用于让 IE8 支持 HTML5元素和媒体查询 -->
<!-- 注意: 如果通过 file:// 引入 Respond.js 文件,则该文件无法起效果 -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
<style type="text/css">
.hidden-detail,.hidden-tr{
display:none;
.hidden-detail, .hidden-tr {
display: none;
}
</style>
</head>
<body>
<div class='col-md-4 col-md-offset-4' style='margin-left:3%;'>
<h1>接口测试的结果</h1>
<table class="table table-hover table-condensed">
<tbody>
<tr>
<td><strong>开始时间:</strong> 2018-09-04 11:48:05.475301</td>
</tr>
<td><strong>结束时间:</strong> 2018-09-04 11:48:13.579765</td></tr>
<td><strong>耗时:</strong> 0:00:08.104464</td></tr>
<td><strong>结果:</strong>
<span >Pass: <strong >0</strong>
Fail: <strong >0</strong>
exception: <strong >2</strong>
weizhicuowu : <strong >0</strong></span></td>
</tr>
</tbody></table>
</div> <div class="row " style="margin:60px">
<div style=' margin-top: 18%;' >
<div class='col-md-4 col-md-offset-4' style='margin-left:3%;'>
<h1>接口测试的结果</h1>
<table class="table table-hover table-condensed">
<tbody>
<tr>
<td><strong>开始时间:</strong> 2018-09-04 11:48:05.475301</td>
</tr>
<td><strong>结束时间:</strong> 2018-09-04 11:48:13.579765</td>
</tr>
<td><strong>耗时:</strong> 0:00:08.104464</td>
</tr>
<td><strong>结果:</strong>
<span>Pass: <strong>0</strong>
Fail: <strong>0</strong>
exception: <strong>2</strong>
weizhicuowu : <strong>0</strong></span></td>
</tr>
</tbody>
</table>
</div>
<div class="row " style="margin:60px">
<div style=' margin-top: 18%;'>
<div class="btn-group" role="group" aria-label="...">
<button type="button" id="check-all" class="btn btn-primary">所有用例</button>
<button type="button" id="check-success" class="btn btn-success">成功用例</button>
@@ -47,71 +51,86 @@
</div>
<div class="btn-group" role="group" aria-label="...">
</div>
<table class="table table-hover table-condensed table-bordered" style="word-wrap:break-word; word-break:break-all; margin-top: 7px;">
<tr >
<td ><strong>用例ID&nbsp;</strong></td>
<td><strong>用例名字</strong></td>
<td><strong>key</strong></td>
<td><strong>请求内容</strong></td>
<td><strong>url</strong></td>
<td><strong>请求方式</strong></td>
<td><strong>预期</strong></td>
<td><strong>实际返回</strong></td>
<td><strong>结果</strong></td>
</tr>
<table class="table table-hover table-condensed table-bordered"
style="word-wrap:break-word; word-break:break-all; margin-top: 7px;">
<tr>
<td><strong>用例ID&nbsp;</strong></td>
<td><strong>用例名字</strong></td>
<td><strong>key</strong></td>
<td><strong>请求内容</strong></td>
<td><strong>url</strong></td>
<td><strong>请求方式</strong></td>
<td><strong>预期</strong></td>
<td><strong>实际返回</strong></td>
<td><strong>结果</strong></td>
</tr>
<tr class="case-tr error">
<td>1.0</td>
<td>图灵api接口</td>
<td>aaaa</td>
<td>{'password':'1222'}</td>
<td>/openapi/api</td>
<td>POST</td>
<td>code=40001</td>
<td>post请求出错出错原因:HTTPConnectionPool(host='127.0.0.1', port=8888): Max retries exceeded with url: http://www.tuling123.com/openapi/api?%7B%22key%22:%20%22aaaa%22,%20%22info%22:%20%22%7B'password':'1222'%7D%22%7D (Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('<urllib3.connection.HTTPConnection object at 0x00000000035C5BA8>: Failed to establish a new connection: [WinError 10061] 由于目标计算机积极拒绝,无法连接。',)))</td>
<td bgcolor="crimson">exect</td>
</tr>
<tr class="case-tr error">
<td>1.0</td>
<td>图灵api接口</td>
<td>aaaa</td>
<td>{'password':'1222'}</td>
<td>/openapi/api</td>
<td>POST</td>
<td>code=40001</td>
<td>post请求出错出错原因:HTTPConnectionPool(host='127.0.0.1', port=8888): Max retries exceeded with url:
http://www.tuling123.com/openapi/api?%7B%22key%22:%20%22aaaa%22,%20%22info%22:%20%22%7B'password':'1222'%7D%22%7D
(Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('
<urllib3.connection.HTTPConnection object at 0x00000000035C5BA8>: Failed to establish a new
connection: [WinError 10061] 由于目标计算机积极拒绝,无法连接。',)))
</td>
<td bgcolor="crimson">exect</td>
</tr>
<tr class="case-tr error">
<td>2.0</td>
<td>图灵api接口</td>
<td>dfeb1cc8125943d29764a2f2f5c33739</td>
<td>{'password':'1222'}</td>
<td>/openapi/api</td>
<td>POST</td>
<td>code=40002</td>
<td>post请求出错出错原因:HTTPConnectionPool(host='127.0.0.1', port=8888): Max retries exceeded with url: http://www.tuling123.com/openapi/api?%7B%22key%22:%20%22dfeb1cc8125943d29764a2f2f5c33739%22,%20%22info%22:%20%22%7B'password':'1222'%7D%22%7D (Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000000000481D198>: Failed to establish a new connection: [WinError 10061] 由于目标计算机积极拒绝,无法连接。',)))</td>
<td bgcolor="crimson">exect</td>
</tr>
</div></div></table><script src="https://code.jquery.com/jquery.js"></script>
<tr class="case-tr error">
<td>2.0</td>
<td>图灵api接口</td>
<td>dfeb1cc8125943d29764a2f2f5c33739</td>
<td>{'password':'1222'}</td>
<td>/openapi/api</td>
<td>POST</td>
<td>code=40002</td>
<td>post请求出错出错原因:HTTPConnectionPool(host='127.0.0.1', port=8888): Max retries exceeded with url:
http://www.tuling123.com/openapi/api?%7B%22key%22:%20%22dfeb1cc8125943d29764a2f2f5c33739%22,%20%22info%22:%20%22%7B'password':'1222'%7D%22%7D
(Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('
<urllib3.connection.HTTPConnection object at 0x000000000481D198>: Failed to establish a new
connection: [WinError 10061] 由于目标计算机积极拒绝,无法连接。',)))
</td>
<td bgcolor="crimson">exect</td>
</tr>
</div>
</div>
</table>
<script src="https://code.jquery.com/jquery.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script type="text/javascript">
$("#check-danger").click(function(e){
$(".case-tr").removeClass("hidden-tr");
$("#check-danger").click(function (e) {
$(".case-tr").removeClass("hidden-tr");
$(".success").addClass("hidden-tr");
$(".warning").addClass("hidden-tr");
$(".error").addClass("hidden-tr");
});
$("#check-warning").click(function(e){
$(".case-tr").removeClass("hidden-tr");
});
$("#check-warning").click(function (e) {
$(".case-tr").removeClass("hidden-tr");
$(".success").addClass("hidden-tr");
$(".danger").addClass("hidden-tr");
$(".error").addClass("hidden-tr");
});
$("#check-success").click(function(e){
$(".case-tr").removeClass("hidden-tr");
});
$("#check-success").click(function (e) {
$(".case-tr").removeClass("hidden-tr");
$(".warning").addClass("hidden-tr");
$(".danger").addClass("hidden-tr");
$(".error").addClass("hidden-tr");
});
$("#check-except").click(function(e){
$(".case-tr").removeClass("hidden-tr");
});
$("#check-except").click(function (e) {
$(".case-tr").removeClass("hidden-tr");
$(".warning").addClass("hidden-tr");
$(".danger").addClass("hidden-tr");
$(".success").addClass("hidden-tr");
});
$("#check-all").click(function(e){
$(".case-tr").removeClass("hidden-tr");
});
});
$("#check-all").click(function (e) {
$(".case-tr").removeClass("hidden-tr");
});
</script>
</body></html>
</body>
</html>