加入了Excel来管理测试用例,对测试代码进行优化

This commit is contained in:
leileili126@163.com
2017-06-04 20:52:17 +08:00
parent 5a9c6b041a
commit cf429014df
23 changed files with 206 additions and 272 deletions

25
Case/ceshiyongli.py Normal file
View File

@@ -0,0 +1,25 @@
# -*- coding: utf-8 -*-
# @Time : 2017/6/4 20:15
# @Author : lileilei
# @Site :
# @File : ceshiyongli.py
# @Software: PyCharm
import unittest,os
from Public import BSTestRunner
from Interface.get_excel import datacel
from Interface.testFengzhuang import TestApi
listkey,listconeent,listurl,listfangshi,listqiwang=datacel()
class Testinface(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testinterface(self):
for i in range(len(listurl)):
api=TestApi(url=listurl[i],key=listkey[i],connent=listconeent[i],fangshi=listfangshi[i])
apicode=api.getcode()
apijson=api.getJson()
if apicode==int(listqiwang[i]):
print('%s:测试成功。json数据为:%s'%(i + 1 ,apijson))
else:
print('%s:测试失败.json数据为:%s'%(i + 1 ,apijson))

48
Case/post.py Normal file
View File

@@ -0,0 +1,48 @@
# -*- coding: utf-8 -*-
# @Author : leizi
from Interface.feng import reques
import yaml,unittest
reques=reques()
class Test_tuling(unittest.TestCase):
def setUp(self):
self.data_file = open(r".\data\data.yaml","r",encoding= "utf-8")
self.data = yaml.load(self.data_file)
self.post_data=self.data['post']
def tearDown(self):
pass
def test_post1(self):
self.url=self.post_data['post1']['url']
self.key=self.post_data['post1']['key']
self.coneent=self.post_data['post1']['coneent']
self.fangshi=self.post_data['post1']['fangshi']
self.code=self.post_data['post1']['code']
self.parem={'key':self.key,'info':self.coneent}
self.me=reques.post(url=self.url,params=self.parem)
self.assertEqual(self.me['code'],int(self.code),msg='接口返回标识符有误')
def test_post2(self):
self.url=self.post_data['post2']['url']
self.key=self.post_data['post2']['key']
self.coneent=self.post_data['post2']['coneent']
self.fangshi=self.post_data['post2']['fangshi']
self.code=self.post_data['post2']['code']
self.parem={'key':self.key,'info':self.coneent}
self.me=reques.post(url=self.url,params=self.parem)
self.assertEqual(self.me['code'],int(self.code),msg='接口返回标识符有误')
def test_post3(self):
self.url=self.post_data['post3']['url']
self.key=self.post_data['post3']['key']
self.coneent=self.post_data['post3']['coneent']
self.fangshi=self.post_data['post3']['fangshi']
self.code=self.post_data['post3']['code']
self.parem={'key':self.key,'info':self.coneent}
self.me=reques.post(url=self.url,params=self.parem)
self.assertEqual(self.me['code'],int(self.code),msg='接口返回标识符有误')
def test_post4(self):
self.url=self.post_data['post4']['url']
self.key=self.post_data['post4']['key']
self.coneent=self.post_data['post4']['coneent']
self.fangshi=self.post_data['post4']['fangshi']
self.code=self.post_data['post4']['code']
self.parem={'key':self.key,'info':self.coneent}
self.me=reques.post(url=self.url,params=self.parem)
self.assertEqual(self.me['code'],int(self.code),msg='接口返回标识符有误')

BIN
Data/data.xlsx Normal file

Binary file not shown.

View File

@@ -1,4 +1,4 @@
foremail: '952943386@qq.com'
password: "wphtrjajdhnbbbfc"
password: "zzaikjtenujtbaif"
toeamil: "leileili126@163.com,952943386@qq.com"
title: "测试报告"

View File

@@ -7,19 +7,18 @@ from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
def load_emil_setting():#从配置文件中加载获取email的相关信息
import yaml
data_file = open(r"C:\Users\\Administrator\\Desktop\\jiejko\\data\\email.yaml","r")
data_file = open(r".\\Data\\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 = 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')
@@ -32,5 +31,5 @@ def sendemali(filepath): #发送email
server.quit()
print("邮件发送成功")
if __name__ == '__main__':
project_path=r'C:\Users\Administrator\Desktop\jiejko\report\pyresult.html'
project_path=r'..\report\pyresult.html'
sendemali(project_path)

27
Interface/get_excel.py Normal file
View File

@@ -0,0 +1,27 @@
# -*- coding: utf-8 -*-
# @Time : 2017/6/4 20:35
# @Author : lileilei
# @Site :
# @File : get_excel.py
# @Software: PyCharm
import xlrd,xlwt
import unittest,sys
from xlutils.copy import copy
from Interface.feng import reques
def datacel():
filepath='.\\Data\\Data.xlsx'
file=xlrd.open_workbook(filepath)
me=file.sheets()[0]
nrows=me.nrows
listkey=[]
listconeent=[]
listurl=[]
listfangshi=[]
listqiwang=[]
for i in range(1,nrows):
listkey.append(me.cell(i,2).value)
listconeent.append(me.cell(i,3).value)
listurl.append(me.cell(i,4).value)
listfangshi.append((me.cell(i,5).value))
listqiwang.append((me.cell(i,6).value))
return listkey,listconeent,listurl,listfangshi,listqiwang

View File

@@ -0,0 +1,28 @@
# -*- coding: utf-8 -*-
# @Time : 2017/6/4 20:36
# @Author : lileilei
# @Site :
# @File : testFengzhuang.py
# @Software: PyCharm
from Interface.feng import reques
reques=reques()
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}
r=reques.post(self.url,self.parem)
elif self.fangshi=="GET":
self.parem = {'key': self.key, 'info': self.connent}
r = reques.post(self.url, self.parem)
return r
def getcode(self):
code=self.testapi()['code']
return code
def getJson(self):
json_data = self.testapi()
return json_data

View File

@@ -89,7 +89,7 @@ Version in 0.8.0
Version in 0.7.1
* Back port to Python 2.3 (Frank Horowitz).
* Fix missing scroll bars in detail log (Podi).
* Fix missing scroll bars in detail Log (Podi).
"""
# TODO: color stderr
@@ -191,7 +191,7 @@ class Template_mixin(object):
2: 'error',
}
DEFAULT_TITLE = 'Unit Test Report'
DEFAULT_TITLE = 'Unit Test report'
DEFAULT_DESCRIPTION = ''
# ------------------------------------------------------------------------
@@ -386,7 +386,7 @@ function showOutput(id, name) {
# ------------------------------------------------------------------------
# Report
# report
#
REPORT_TMPL = """
@@ -398,7 +398,7 @@ function showOutput(id, name) {
<table id='result_table' class="table">
<thead>
<tr id='header_row'>
<th>Test Group/Test case</td>
<th>Test Group/Test Case</td>
<th>Count</td>
<th>Pass</td>
<th>Fail</td>
@@ -501,7 +501,7 @@ class _TestResult(TestResult):
# result is a list of result in 4 tuple
# (
# result code (0: success; 1: fail; 2: error),
# TestCase object,
# Case object,
# Test output (byte string),
# stack trace,
# )
@@ -598,7 +598,7 @@ class BSTestRunner(Template_mixin):
def run(self, test):
"Run the given test case or test suite."
"Run the given test Case or test suite."
result = _TestResult(self.verbosity)
try:
test(result)

View File

@@ -84,7 +84,7 @@ Version in 0.8.0
Version in 0.7.1
* Back port to Python 2.3 (Frank Horowitz).
* Fix missing scroll bars in detail log (Podi).
* Fix missing scroll bars in detail Log (Podi).
"""
# TODO: color stderr
@@ -177,7 +177,7 @@ class Template_mixin(object):
2: 'error',
}
DEFAULT_TITLE = 'Unit Test Report'
DEFAULT_TITLE = 'Unit Test report'
DEFAULT_DESCRIPTION = ''
# ------------------------------------------------------------------------
@@ -410,7 +410,7 @@ a.popup_link:hover {
# ------------------------------------------------------------------------
# Report
# report
#
REPORT_TMPL = """
@@ -526,7 +526,7 @@ class _TestResult(TestResult):
# result is a list of result in 4 tuple
# (
# result code (0: success; 1: fail; 2: error),
# TestCase object,
# Case object,
# Test output (byte string),
# stack trace,
# )
@@ -623,7 +623,7 @@ class HTMLTestRunner(Template_mixin):
def run(self, test):
"Run the given test case or test suite."
"Run the given test Case or test suite."
result = _TestResult(self.verbosity)
test(result)
self.stopTime = datetime.datetime.now()

6
Public/__init__.py Normal file
View File

@@ -0,0 +1,6 @@
# -*- coding: utf-8 -*-
# @Time : 2017/6/4 17:34
# @Author : lileilei
# @Site :
# @File : __init__.py.py
# @Software: PyCharm

View File

@@ -1,4 +1,8 @@
这是我自己写的接口测试的,
使用的库 requests绝大部分是基于Python原有的库进行的这样简单方便
使用参数和脚本的分离可以让我们方便去维护我们的测试脚本。
# 这是我自己写的接口测试的,
### 使用的库 requests绝大部分是基于Python原有的库进行的这样简单方便
### 使用参数和脚本的分离可以让我们方便去维护我们的测试脚本。
### 目前对功能进行了从新的拆分和优化现在只需要在Data中的data.xlsx 文件中对用例进行编写后然后点击main运行就可以
### 产生的测试报告后续需要优化当前生成的测试报告以及对测试用例中的预期进行优化目前使用的yaml管理的用来不能
### 直接运行需要接下来优化的功能。

View File

@@ -1,47 +0,0 @@
import xlrd,xlwt
import unittest,sys
from xlutils.copy import copy
from fengzhuang.feng import reques
def datacel():
filepath='C:\\Users\\Administrator\\Desktop\\jiekou\\data\\data.xlsx'
file=xlrd.open_workbook(filepath)
me=file.sheets()[0]
nrows=me.nrows
listkey=[]
listconeent=[]
listurl=[]
listfangshi=[]
listqiwang=[]
for i in range(1,nrows):
listkey.append(me.cell(i,2).value)
listconeent.append(me.cell(i,3).value)
listurl.append(me.cell(i,4).value)
listfangshi.append((me.cell(i,5).value))
listqiwang.append(int(me.cell(i,6).value))
return listkey,listconeent,listfangshi,listqiwang,listurl
class TestTuling(unittest.TestCase):
def setup(self):
self.listkey,self.listconeent,self.listfangshi,self.listqiwang,self.listurl=datacel()
def tearDown(self):
sys.exit()
def testpost1(self):
try:
self.url=self.listurl[0]
self.key=self.listkey[0]
self.coneent=self.listconeent[0]
self.fangshi=self.listfangshi[0]
self.code=self.listqiwang
self.parem={'key':self.key,'info':self.coneent}
if self.fangshi == 'POST':
self.me=reques.post(url=self.url,params=self.parem)
self.assertEqual(self.me['code'],self.code,msg='接口返回标识符有误')
else:
print('用例1执行失败!请求方式不正确')
except Exception as e:
print('用例1测试失败,原因:%s'%e)
if __name__ == '__main__':
un=unittest.TestSuite()
un.addTest(Test_tuling('test_post1'))
ren=unittest.runner()
ren.run(un)

View File

@@ -1,74 +0,0 @@
# -*- coding: utf-8 -*-
# @Author : leizi
from fengzhuang.feng import reques
import yaml,unittest
class Test_tuling(unittest.TestCase):
def setUp(self):
title=u'登陆测试'
self.data_file = open(r"C:\\Users\\Administrator\\Desktop\\jiekou\\data\\data.yaml","r",encoding= "utf-8")
self.data = yaml.load(self.data_file)
self.post_data=self.data['post']
def tearDown(self):
pass
def test_post1(self):
try:
self.url=self.post_data['post1']['url']
self.key=self.post_data['post1']['key']
self.coneent=self.post_data['post1']['coneent']
self.fangshi=self.post_data['post1']['fangshi']
self.code=self.post_data['post1']['code']
self.parem={'key':self.key,'info':self.coneent}
if self.fangshi == 'POST':
self.me=reques.post(url=self.url,params=self.parem)
self.assertEqual(self.me['code'],self.code,msg='接口返回标识符有误')
else:
print('不支持%s方式请求'%self.fangshi)
except Exception as e:
print('用例1测试失败,原因:%s'%e)
def test_post2(self):
try:
self.url=self.post_data['post2']['url']
self.key=self.post_data['post2']['key']
self.coneent=self.post_data['post2']['coneent']
self.fangshi=self.post_data['post2']['fangshi']
self.code=self.post_data['post2']['code']
self.parem={'key':self.key,'info':self.coneent}
if self.fangshi == 'POST':
self.me=reques.post(url=self.url,params=self.parem)
self.assertEqual(self.me['code'],self.code,msg='接口返回标识符有误')
else:
print('不支持%s方式请求'%self.fangshi)
except Exception as e:
print('用例2测试失败,原因:%s'%e)
def test_post3(self):
try:
self.url=self.post_data['post3']['url']
self.key=self.post_data['post3']['key']
self.coneent=self.post_data['post3']['coneent']
self.fangshi=self.post_data['post3']['fangshi']
self.code=self.post_data['post3']['code']
self.parem={'key':self.key,'info':self.coneent}
if self.fangshi == 'POST':
self.me=reques.post(url=self.url,params=self.parem)
self.assertEqual(self.me['code'],self.code,msg='接口返回标识符有误')
else:
print('不支持%s方式请求'%self.fangshi)
except Exception as e:
print('用例3测试失败,原因:%s'%e)
def test_post4(self):
try:
self.url=self.post_data['post4']['url']
self.key=self.post_data['post4']['key']
self.coneent=self.post_data['post4']['coneent']
self.fangshi=self.post_data['post4']['fangshi']
self.code=self.post_data['post4']['code']
self.parem={'key':self.key,'info':self.coneent}
if self.fangshi == 'POST':
self.me=reques.post(url=self.url,params=self.parem)
self.assertEqual(self.me['code'],self.code,msg='接口返回标识符有误')
else:
print('不支持%s方式请求'%self.fangshi)
except Exception as e:
print('用例4测试失败,原因:%s'%e)

Binary file not shown.

View File

View File

@@ -1,29 +0,0 @@
# -*- coding: utf-8 -*-
# @Author : leizi
import logging,os,time
class log_message:
def __init__(self,title):
# time
self.day=time.strftime("%Y%m%d",time.localtime(time.time()))
#创建一个logger
self.logger=logging.getLogger(title)
self.logger.setLevel(logging.INFO)
#创建Heandler 用于写入文件
self.logfile=logging.FileHandler(r'C:\Users\Administrator\Desktop\te_blogf\lo\%s.log'%self.day)
self.logfile.setLevel(logging.INFO)
#创建Heandler 用于显示控制台
self.control=logging.StreamHandler()
self.control.setLevel(logging.INFO)
#定义输出格式
self.formatter=logging.Formatter("%(key)s - %(coneent)s - %(coneent)s - %(message)s")
self.logfile.setFormatter(self.formatter)
self.control.setFormatter(self.formatter)
#给logger添加handler
self.logger.addHandler(self.logfile)
self.logger.addHandler(self.control)
def debug_log(self,message):
self.logger.debug(message)
def info_log(self,message):
self.logger.info(message)
def ware_log(self,message):
self.logger.ware(message)

43
main.py
View File

@@ -1,25 +1,36 @@
# -*- coding: utf-8 -*-
# @Author : leizi
from report.emmail import sendemali
import time,unittest
from report import HTMLTestRunner
import os,time,unittest
from Case.ceshiyongli import Testinface
'''
这里你可以分开执行上面你case里面包含的用例。也可以单独执行里面
的某一个的测试用例
'''
from case.post import Test_tuling
from report import BSTestRunner
from Case.post import Test_tuling
from Public import BSTestRunner
from Interface.emmail import sendemali
if __name__ == '__main__':
project_path=r'C:\Users\Administrator\Desktop\jiekou'
# suite = unittest.TestSuite()
# suite.addTest(Test_tuling("test_post4"))
# suite.addTest(Test_tuling('test_post3'))
# suite.addTest(Test_tuling('test_post2'))
# suite.addTest(Test_tuling('test_post1'))
# filedir=".\\report\\"
# filename="pyresult.html"
# filepath=filedir+filename
# if os.path.exists(filepath) is False:
# os.system(r'touch %s' % filename)
# fp=open(filepath,'wb')
# runner= BSTestRunner.BSTestRunner(stream=fp, title=u'接口测试的结果', description='这是post接口测试报告如下')
# runner.run(suite)
# # sendemali(filepath)#这里的路径需要时需要填写路径,
suite = unittest.TestSuite()
suite.addTest(Test_tuling("test_post4"))
suite.addTest(Test_tuling('test_post3'))
suite.addTest(Test_tuling('test_post2'))
suite.addTest(Test_tuling('test_post1'))
filedir=project_path+"\\report\\"
filename="pyresult.html"
filepath=filedir+filename
fp=open(filepath,'wb')
runner=BSTestRunner.BSTestRunner(stream=fp,title=u'接口测试的结果',description='这是post接口测试报告如下')
suite.addTest(Testinface("testinterface"))
filedir = ".\\report\\"
filename = "pyresult.html"
filepath =filedir+filename
if os.path.exists(filepath) is False:
os.system(r'touch %s' % filename)
fp = open(filepath, 'wb')
runner = BSTestRunner.BSTestRunner(stream=fp, title=u'接口测试的结果', description='这是post接口测试报告如下')
runner.run(suite)
time.sleep(2)

View File

@@ -150,9 +150,9 @@ function showOutput(id, name) {
<div class="container">
<div class='heading'>
<h1>接口测试的结果</h1>
<p><strong>Start Time:</strong> 2017-05-31 15:30:56</p>
<p><strong>Duration:</strong> 0:00:00.015001</p>
<p><strong>Status:</strong> <span class="text text-success">Pass <strong>4</strong></span></p>
<p><strong>Start Time:</strong> 2017-06-04 20:43:22</p>
<p><strong>Duration:</strong> 0:00:00.790001</p>
<p><strong>Status:</strong> <span class="text text-success">Pass <strong>1</strong></span></p>
<p class='description'>这是post接口测试报告如下</p>
</div>
@@ -167,7 +167,7 @@ function showOutput(id, name) {
<table id='result_table' class="table">
<thead>
<tr id='header_row'>
<th>Test Group/Test case</td>
<th>Test Group/Test Case</td>
<th>Count</td>
<th>Pass</td>
<th>Fail</td>
@@ -178,16 +178,16 @@ function showOutput(id, name) {
<tbody>
<tr class='text text-success'>
<td>case.post.Test_tuling</td>
<td>4</td>
<td>4</td>
<td>Case.ceshiyongli.Testinface</td>
<td>1</td>
<td>1</td>
<td>0</td>
<td>0</td>
<td><a class="btn btn-xs btn-primary"href="javascript:showClassDetail('c1',4)">Detail</a></td>
<td><a class="btn btn-xs btn-primary"href="javascript:showClassDetail('c1',1)">Detail</a></td>
</tr>
<tr id='pt1.1' class='hiddenRow'>
<td class='text text-success'><div class='testcase'>test_post4</div></td>
<td class='text text-success'><div class='testcase'>testinterface</div></td>
<td colspan='5' align='center'>
<!--css div popup start-->
@@ -201,82 +201,18 @@ function showOutput(id, name) {
</div>
<pre>
pt1.1: 用例4测试失败,原因:post() missing 1 required positional argument: 'self'
</pre>
</div>
<!--css div popup end-->
</td>
</tr>
<tr id='pt1.2' class='hiddenRow'>
<td class='text text-success'><div class='testcase'>test_post3</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>
<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: 用例3测试失败,原因:post() missing 1 required positional argument: 'self'
</pre>
</div>
<!--css div popup end-->
</td>
</tr>
<tr id='pt1.3' class='hiddenRow'>
<td class='text text-success'><div class='testcase'>test_post2</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.3')" >
pass</a>
<div id='div_pt1.3' class="popup_window">
<div style='text-align: right;cursor:pointer'>
<a onfocus='this.blur();' onclick="document.getElementById('div_pt1.3').style.display = 'none' " >
[x]</a>
</div>
<pre>
pt1.3: 用例2测试失败,原因:post() missing 1 required positional argument: 'self'
</pre>
</div>
<!--css div popup end-->
</td>
</tr>
<tr id='pt1.4' class='hiddenRow'>
<td class='text text-success'><div class='testcase'>test_post1</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.4')" >
pass</a>
<div id='div_pt1.4' class="popup_window">
<div style='text-align: right;cursor:pointer'>
<a onfocus='this.blur();' onclick="document.getElementById('div_pt1.4').style.display = 'none' " >
[x]</a>
</div>
<pre>
pt1.4: 用例1测试失败,原因:post() missing 1 required positional argument: 'self'
pt1.1: 1:测试成功。json数据为:{'code': 40001, 'text': '亲爱的key不对哦。'}
2:测试成功。json数据为:{'code': 40002, 'text': '有啥事吗?'}
3:测试成功。json数据为:{'code': 40007, 'text': '您的请求内容为空。'}
4:测试成功。json数据为:{'code': 40007, 'text': '您的请求内容为空。'}
5:测试成功。json数据为:{'code': 40001, 'text': '亲爱的key不对哦。'}
6:测试成功。json数据为:{'code': 40002, 'text': '有些话,难以说出口?'}
7:测试成功。json数据为:{'code': 40007, 'text': '您的请求内容为空。'}
8:测试成功。json数据为:{'code': 40007, 'text': '您的请求内容为空。'}
9:测试成功。json数据为:{'code': 40001, 'text': '亲爱的key不对哦。'}
10:测试成功。json数据为:{'code': 40002, 'text': '有些话,难以说出口?'}
11:测试成功。json数据为:{'code': 40007, 'text': '您的请求内容为空。'}
12:测试成功。json数据为:{'code': 40007, 'text': '您的请求内容为空。'}
</pre>
@@ -290,8 +226,8 @@ pt1.4: 用例1测试失败,原因:post() missing 1 required positional argument:
<tfoot>
<tr id='total_row'>
<td>Total</td>
<td>4</td>
<td class="text text-success">4</td>
<td>1</td>
<td class="text text-success">1</td>
<td class="text text-danger">0</td>
<td class="text text-warning">0</td>
<td>&nbsp;</td>