方式一
JSON数据文件
[
"北京||北京","上海||上海","广州||广州","深圳||深圳","香港||香港"
]
测试代码
"""
__title__ = ''
__author__ = 'davieyang'
__mtime__ = '2018/4/21'
"""
from selenium import webdriver
import unittest
import time
import logging
import traceback
import ddt
from selenium.common.exceptions import NoSuchElementException
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(filename)s[line: %(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='F:\\DataDriven\\TestResults\TestResults.TestResults',
filemode='w'
)
@ddt.ddt
class DataDrivenTestByDDTHTR(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome(executable_path="F:\\automation\\webdriver\\chromedriver.exe")
@ddt.file_data("F:\\DataDriven\\testData\\test_data_list.json")
def test_dataDrivenHTRByFile(self, value):
url = "http://www.baidu.com"
self.driver.get(url)
self.driver.maximize_window()
print(value)
testdata, execptdata = tuple(value.strip().split("||"))
self.driver.implicitly_wait(10)
try:
self.driver.find_element_by_id("kw").send_keys(testdata)
self.driver.find_element_by_id("su").click()
time.sleep(3)
self.assertTrue(execptdata in self.driver.page_source)
except NoSuchElementException as e:
logging.error(u"查找的页面元素不存在,异常堆栈信息为:" + str(traceback.format_exc()))
except AssertionError as e:
logging.info(u"搜索 '%s',期望 '%s' ,失败" % (testdata, execptdata))
except Exception as e:
logging.error(u"未知错误,错误信息:" + str(traceback.format_exc()))
else:
logging.info(u"搜索 '%s',期望 '%s' ,通过" % (testdata, execptdata))
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
unittest.main()
方式二
JSON数据文件
[
"北京||北京","上海||上海","广州||广州","深圳||深圳","香港||香港"
]
测试报告模板
# encoding = utf-8
"""
__title__ = 'DataDrivenTestByDDT use this template for generating testing report'
__author__ = 'davieyang'
__mtime__ = '2018/4/21'
"""
# encoding = utf-8
def htmlTemplate(trData):
htmlStr = u'''<!DOCTYPE HTML>
<html>
<head>
<title>单元测试报告</title>
<style>
body {
width:80%;
margin:40px auto;
font-weight:bold;
font-family: 'trebuchet MS', 'Lucida sans', SimSun;
font-size:18px;
color: #000;
}
table {
* border-collapse:collapse;
border-spacing:0;
width:100%;
}
.tableStyle {
border-style:outset;
border-width:2px;
border-color:blue;
}
.tableStyle tr:hover {
background: rgb(173.216.230);
}
.tableStyle td,.tableStyle th{
border-left:solid 1px rgb(146,208,80);
border-top:1px solid rgb(146,208,80);
padding:15px
text-align:center
}
.tableStyle th{
padding:15px;
background-color:rgb(146,208,80);
background-image: -webkit -gradient(linear, left top, left bottom, from(#92D050), to(#A2D668))
}
</style>
</head>
<body>
<center><h1>测试报告</h1></center><br />
<table class="tableStyle">
<thead>
<tr>
<th>Search Words</th>
<th>Assert Words</th>
<th>Start Time</th>
<th>Waste Time(s)</th>
<th>Status</th>
</tr>
</thead>'''
endStr = u'''
</table>
</body>
</html>'''
html = htmlStr + trData + endStr
print(html)
with open("D:\\\Programs\\\Python\\\PythonUnittest\\\Reports\\testTemplate.html", "wb") as fp:
fp.write(html.encode("gbk"))
测试脚本
"""
__title__ = ''
__author__ = 'davieyang'
__mtime__ = '2018/4/21'
"""
from selenium import webdriver
import unittest
import time
import logging
import traceback
import ddt
from DataDrivenTest.ReportTemplate import htmlTemplate
from selenium.common.exceptions import NoSuchElementException
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(filename)s[line: %(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='D:\\Programs\\Python\\PythonUnittest\\Reports\\TestResults.TestResults',
filemode='w'
)
@ddt.ddt
class DataDrivenTestByDDT(unittest.TestCase):
@classmethod
def setUpClass(cls):
DataDrivenTestByDDT.trStr = ""
def setUp(self):
self.driver = webdriver.Chrome(executable_path="D:\\Programs\\Python\\PythonUnittest\\BrowserDrivers\\chromedriver.exe")
status = None
flag = 0
@ddt.file_data("D:\\Programs\\Python\\PythonUnittest\\TestData\\test_data_list.json")
def test_dataDrivenByFile(self, value):
flagDict = {0: 'red', 1: '#00AC4E'}
url = "http://www.baidu.com"
self.driver.get(url)
self.driver.maximize_window()
print(value)
testdata, execptdata = tuple(value.strip().split("||"))
self.driver.implicitly_wait(10)
try:
start = time.time()
startTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.driver.find_element_by_id("kw").send_keys(testdata)
self.driver.find_element_by_id("su").click()
time.sleep(3)
self.assertTrue(execptdata in self.driver.page_source)
except NoSuchElementException as e:
logging.error(u"查找的页面元素不存在,异常堆栈信息为:"+ str(traceback.format_exc()))
status = 'fail'
flag = 0
except AssertionError as e:
logging.info(u"搜索 ‘%s’,期望 ‘%s’ ,失败" %(testdata, execptdata))
status = 'fail'
flag = 0
except Exception as e:
logging.error(u"未知错误,错误信息:" + str(traceback.format_exc()))
status = 'fail'
flag = 0
else:
logging.info(u"搜索 ‘%s’,期望 ‘%s’ ,通过" %(testdata, execptdata))
status = 'pass'
flag = 1
wasteTime = time.time() - start - 3
DataDrivenTestByDDT.trStr += u'''
<tr>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%.2f</td>
<td style = "color: %s">%s</td>
</tr><br/>''' % (testdata, execptdata, startTime, wasteTime, flagDict[flag], status)
def tearDown(self):
self.driver.quit()
@classmethod
def tearDownClass(cls):
htmlTemplate(DataDrivenTestByDDT.trStr)
if __name__ == '__main__':
unittest.main()
生成日志
Fri, 07 Dec 2018 15:05:36 DataDrivenTestByDDT.py[line: 81] INFO 搜索 ‘北京’,期望 ‘北京’ ,通过
Fri, 07 Dec 2018 15:05:50 DataDrivenTestByDDT.py[line: 81] INFO 搜索 ‘上海’,期望 ‘上海’ ,通过
Fri, 07 Dec 2018 15:06:04 DataDrivenTestByDDT.py[line: 81] INFO 搜索 ‘广州’,期望 ‘广州’ ,通过
Fri, 07 Dec 2018 15:06:18 DataDrivenTestByDDT.py[line: 81] INFO 搜索 ‘深圳’,期望 ‘深圳’ ,通过
Fri, 07 Dec 2018 15:06:32 DataDrivenTestByDDT.py[line: 81] INFO 搜索 ‘香港’,期望 ‘香港’ ,通过
HTML报告