项目进行自动化测试,采用python 的unittest架构进行。
架构代码如下:
lib
data
config
Report
.pyt
lib 为封装好的公共lib库,比如发送邮件、测试报告模板、访问数据库、hbase等
cofig为生成的公共配置
data 为测试数据集
Report 为生产报告结果目录
all_test.py 为执行用例入库
Test*.py为测试的具体用例
all_test.py 详解
通过discover 生成测试用例集合,调用报告,发送邮件
# coding=utf-8
import unittest
from lib import HTMLTestRunner
from lib import SendEmail
import time
from unittest import TestLoader
#用例目录
test_suite_dir=r'C:\Users\Administrator\PycharmProjects\OpenAPI_new\\'
#test_suite_dir=r'/opt/openapi/' #145部署环境
#报告目录
Report_dir= r'C:\Users\Administrator\PycharmProjects\OpenAPI_new\Report\\'
#Report_dir=r'/opt/openapi/Report/' #145部署环境
def creatsuite():
testunit = unittest.TestSuite()
# 定义测试文件查找的目录
test_dir =test_suite_dir
# 定义 discover 方法的参数
package_tests = unittest.defaultTestLoader.discover(test_dir,
pattern='Test*.py',
top_level_dir=None)
# package_tests=TestLoader.discover(start_dir=test_dir, pattern='Test*.py')
# discover 方法筛选出来的用例,循环添加到测试套件中
for test_suite in package_tests:
for test_case in test_suite:
testunit.addTests(test_case)
print(testunit)
return testunit
alltestnames = creatsuite()
if __name__ == "__main__":
now = time.strftime("%Y-%m-%d %H_%M_%S")
test_report =Report_dir
filename = test_report + now + 'result.html'
print filename
fp = open(filename, 'wb')
runner = HTMLTestRunner.HTMLTestRunner(
stream=fp,
title=u'OpenAPI测试报告',
description=u'测试用例执行结果'
)
runner.run(alltestnames)
fp.close()
new_report = SendEmail.new_report(test_report)
SendEmail.send_file(new_report) # 发送测试报告
SendEmail.py 为发送邮件模板
# encoding=utf-8
from HTMLTestRunner import HTMLTestRunner
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.utils import parseaddr, formataddr
import smtplib
import unittest
import time
import os
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr(( \
Header(name, 'utf-8').encode(), \
addr.encode('utf-8') if isinstance(addr, unicode) else addr))
## ==============定义发送附件邮件==========
def send_file(file_new):
smtpserver='smtp.exmail.qq.com'
user='***@***.com'
password='***'
sender='***'
receiver=['[email protected]','[email protected]']
# subject='**自动化测试报告'
file=open(file_new,'r').read()
now = time.strftime("%Y-%m-%d %H_%M_%S")
subject = 'OpenAPI自动化测试报告--'+now
# att=MIMEText(sendfile,"base64","utf-8")
att =MIMEText(file, "html", "utf-8")
att["Content-Type"]="application/octet-stream"
att["ContenT-Disposition"]="attachment;filename = 'OpenAPI自动化测试报告.html '"
msgRoot=MIMEMultipart('related')
msgRoot['Subject']=subject
msgRoot['From'] = _format_addr(u'**测试组 <%s>' % sender)
msgRoot['To'] = _format_addr(u'OpenAPI项目组 <%s>' % receiver)
# msgRoot.attach(att)
msgRoot.attach(att)
smtp=smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(user,password)
smtp.sendmail(sender,receiver,msgRoot.as_string())
smtp.quit()
# ======查找测试目录,找到最新生成的测试报告文件======
def new_report(test_report):
lists = os.listdir(test_report) # 列出目录的下所有文件和文件夹保存到lists
# lists.sort(key=lambda fn: os.path.getmtime(test_report + "\\" + fn)) # 按时间排序 win
lists.sort(key=lambda fn: os.path.getmtime(test_report + "/" + fn)) #linux
file_new = os.path.join(test_report, lists[-1]) # 获取最新的文件保存到file_new
print(file_new)
return file_new
# if __name__ == "__main__":
#
# send_file( r'C:\Users\Administrator\PycharmProjects\OpenAPI_new\Report\2017-10-26 20_08_07result.html')
# encoding=utf-8
import time
import unittest
import urllib, urllib2, httplib
import requests
from lib import HTMLTestRunner
import json
from poster.streaminghttp import register_openers
'''authenticate'''
# 鉴权认证模块
class Test001_Authenticate(unittest.TestCase):
def setUp(self):
# 预设环境信息
self.app_key = '**'
self.scope = 'scope'
self.redirect_uri = 'redirect_uri'
self.app_secret = "**"
self.grant_type = 'authorization_code'
self.access_token_url = 'http://**/oauth2/access_token'
self.refresh_token_url = "http://**/oauth2/refresh_token"
self.url= "http:/***/oauth2/authorize"
def tearDown(self):
# 清理环境信息
pass
# GET方法获取令牌access_token
# @unittest.skip('')
def test_001_get_access_token(self):
url = self.access_token_url
params = urllib.urlencode(
{'app_key': self.app_key, 'app_secret': self.app_secret, 'grant_type': self.grant_type})
response = requests.get(url, params=params)
print response.status_code, response.text
data=response.json()
access_token = data["access_token"]
self.assertIsNotNone(data["access_token"],"get access_token ok ")
self.assertEqual(response.status_code, 200, 'status_code is not 200,error')
# POST方法获取令牌access_token
# @unittest.skip('')
def test_002_post_access_token(self):
url = self.access_token_url
params = urllib.urlencode(
{'app_key': self.app_key, 'app_secret': self.app_secret, 'grant_type': self.grant_type})
response = requests.post(url, params=params)
print response.status_code, response.text
data=response.json()
access_token = data["access_token"]
self.assertIsNotNone(data["access_token"],"get access_token ok ")
self.assertEqual(response.status_code, 200, 'status_code is not 200,error')
# POST方法access_token写入config目录下面的access_token.txt供后续程序调用
def test_005_post_access_token(self):
url = self.access_token_url
params = urllib.urlencode(
{'app_key': self.app_key, 'app_secret': self.app_secret, 'grant_type': self.grant_type})
response = requests.post(url, params=params)
print response.status_code, response.text
data = response.json()
access_token= data["access_token"]
access_token_file_path='./config/access_token.txt'
f=open(access_token_file_path,'r+')
f.write(access_token)
f.close()
Test002_Nudityfilter.py 具体用例2
# encoding=utf-8
import unittest, os
import requests
from poster.streaminghttp import register_openers
'''nudityfilter'''
# 色情识别模块
class Test002_Nudityfilter(unittest.TestCase):
def setUp(self):
# 预设环境信息
self.url = "http:/**/nudityRecog"
self.mark = 'room-201'
self.timestamp = 1846123456
self.random = 123
self.app_key = '**'
# self.access_token = '**'
access_token_file_path = './config/access_token.txt'
f=open(access_token_file_path,'r+')
self.access_token=f.read()
# print self.access_token
f.close()
def tearDown(self):
# 清理环境信息
pass
# 四种类型图片测试 -- normal
def test_001_normal_img(self):
post_data = {'mark': self.mark,'timestamp': self.timestamp,'random': self.random}
headers = {'app_key': self.app_key, 'access_token': self.access_token}
file_path = './data/test/normal'
path_list = os.listdir(file_path)
for image in path_list:
image_path = file_path + '/' + image
register_openers()
file = {'file': (image, open(image_path, 'rb'))}
request = requests.post(self.url, files=file, data=post_data, headers=headers)
data = request.json()
print data
# 判断是否成功调用
self.assertEqual(data['result_code'], 0)
# fileType 是否等于 1
self.assertEqual(data['result'][-1]['fileType'], 1)
# recogType 是否等于 normal
self.assertEqual(data['result'][-1]['recogType'], 'normal')
HTMLTestRunner.py python 2.7版本测试报告模板
"""
A TestRunner for use with the Python unit testing framework. It
generates a HTML report to show the result at a glance.
The simplest way to use this is to invoke its main method. E.g.
import unittest
import HTMLTestRunner
... define your tests ...
if __name__ == '__main__':
HTMLTestRunner.main()
For more customization options, instantiates a HTMLTestRunner object.
HTMLTestRunner is a counterpart to unittest's TextTestRunner. E.g.
# output to a file
fp = file('my_report.html', 'wb')
runner = HTMLTestRunner.HTMLTestRunner(
stream=fp,
title='My unit test',
description='This demonstrates the report output by HTMLTestRunner.'
)
# Use an external stylesheet.
# See the Template_mixin class for more customizable options
runner.STYLESHEET_TMPL = ''
# run the test
runner.run(my_test_suite)
------------------------------------------------------------------------
Copyright (c) 2004-2007, Wai Yip Tung
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name Wai Yip Tung nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
# URL: http://tungwaiyip.info/software/HTMLTestRunner.html
__author__ = "Wai Yip Tung"
__version__ = "0.8.2"
"""
Change History
Version 0.8.2
* Show output inline instead of popup window (Viorel Lupu).
Version in 0.8.1
* Validated XHTML (Wolfgang Borgert).
* Added description of test classes and test cases.
Version in 0.8.0
* Define Template_mixin class for customization.
* Workaround a IE 6 bug that it does not treat
%(heading)s
%(report)s
%(ending)s