數據驅動json文件的方式
test_data_list.json:
[
"鄧肯||蒂姆",
"喬丹||邁克爾",
"庫里||斯蒂芬",
"杜蘭特||凱文",
"詹姆斯||勒布朗"
]
ReportTemplate.py:
#encoding=utf-8
def htmlTemplate(trData):
htmlStr = u'''<!DOCTYPE HTML>
<html>
<head>
<title>單元測試報告</title>
<style>
body {
width: 80%; /*整個body區域占瀏覽器的寬度百分比*/
margin: 40px auto; /*整個body區域相對瀏覽器窗口擺放位置(左右,上下)*/
font-weight: bold; /*整個body區域的字體加粗*/
font-family: 'trebuchet MS', 'Lucida sans', SimSun; /*表格中文字的字體類型*/
font-size: 18px; /*表格中文字字體大小*/
color: #000; /*整個body區域字體的顏色*/
}
table {
*border-collapse: collapse; /*合並表格邊框*/
border-spacing: 0; /*表格的邊框寬度*/
width: 100%; /*整個表格相對父元素的寬度*/
}
.tableStyle {
/*border: solid #ggg 1px;*/
border-style: outset; /*整個表格外邊框樣式*/
border-width: 2px; /*整個表格外邊框寬度*/
/*border: 2px;*/
border-color: blue; /*整個表格外邊框顏色*/
}
.tableStyle tr:hover {
background: rgb(173,216,230); /*鼠標滑過一行時,動態顯示的顏色146,208,80*/
}
.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));
/*rgb(146,208,80)*/
}
</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頁面代碼
html = htmlStr + trData + endStr
print html
# 生成.html文件
with open(u"d:\\test\\testTemplate.html", "w") as fp:
fp.write(html.encode("gbk"))
data_drivern_by_file.py:
# encoding=utf-8
from selenium import webdriver
import unittest, time
import logging, traceback
import ddt
from ReportTemplate import htmlTemplate
from selenium.common.exceptions import NoSuchElementException
#如果有no json的報錯信息,請將json文件存儲為utf-8,with Bom
# 初始化日志對象
logging.basicConfig(
# 日志級別
level = logging.INFO,
# 日志格式
# 時間、代碼所在文件名、代碼行號、日志級別名字、日志信息
format = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
# 打印日志的時間
datefmt = '%a, %Y-%m-%d %H:%M:%S',
# 日志文件存放的目錄(目錄必須存在)及日志文件名
filename = 'd:/report.log',#’d:\\report.log’也可以
# 打開日志文件的方式
filemode = 'w'
)
@ddt.ddt
class TestDemo(unittest.TestCase):
@classmethod
def setUpClass(cls):
# 整個測試過程只被調用一次
TestDemo.trStr = ""
def setUp(self):
self.driver=webdriver.Firefox(executable_path="c:\\geckodriver")
status = None # 用於存放測試結果狀態,失敗'fail',成功'pass'
flag = 0 # 數據驅動測試結果的標志,失敗置0,成功置1
@ddt.file_data("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
# 將從.json文件中讀取出的數據用“||”進行分隔成測試數據
# 和期望數據
testdata, expectdata = tuple(value.strip().split("||"))
# 設置隱式等待時間為10秒
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(expectdata in self.driver.page_source)
except NoSuchElementException, e:
logging.error(u"查找的頁面元素不存在,異常堆棧信息:" \
+ str(traceback.format_exc()))
status = 'fail'
flag = 0
except AssertionError, e:
logging.info(u"搜索“%s”,期望“%s”,失敗" %(testdata, expectdata))
status = 'fail'
flag = 0
except Exception, e:
logging.error(u"未知錯誤,錯誤信息:" + str(traceback.format_exc()))
status = 'fail'
flag = 0
else:
logging.info(u"搜索“%s”,期望“%s”通過" %(testdata, expectdata))
status = 'pass'
flag = 1
# 計算耗時,從將測試數據輸入到輸入框中到斷言期望結果之間所耗時
wasteTime = time.time() - start - 3 # 減去強制等待的3秒
# 每一組數據測試結束后,都將其測試結果信息插入表格行
# 的HTML代碼中,並將這些行HTML代碼拼接到變量trStr變量中,
# 等所有測試數據都被測試結束后,傳入htmlTemplate()函數中
# 生成完整測試報告的HTML代碼
TestDemo.trStr += u'''
#這段兒會被多次拼接,每搜索一次就會把模板字符串后邊的字符拼接上
<tr>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%.2f</td>
<td style="color:%s">%s</td>
</tr><br />''' % (testdata, expectdata,startTime, wasteTime, flagDict[flag], status)
def tearDown(self):
self.driver.quit()
@classmethod
def tearDownClass(cls):
# 寫自定義的html測試報告
# 整個測試過程只被調用一次
htmlTemplate(TestDemo.trStr)
if __name__ == '__main__':
unittest.main()
結果:
D:\test>python test.py
鄧肯||蒂姆
testdata,expectdata: 鄧肯 蒂姆
.喬丹||邁克爾
testdata,expectdata: 喬丹 邁克爾
.庫里||斯蒂芬
testdata,expectdata: 庫里 斯蒂芬
.杜蘭特||凱文
testdata,expectdata: 杜蘭特 凱文
.詹姆斯||勒布朗
testdata,expectdata: 詹姆斯 勒布朗
.<!DOCTYPE HTML>
<html>
<head>
<title>單元測試報告</title>
<style>
body{
width:80%;/*整個body區域占瀏覽器的寬度百分比*/
margin:40px auto;/*整個body區域相對瀏覽器窗口擺放位置(左右,上下)*/
font-weight:bold;/*整個body區域的字體加粗*/
font-family:'trebuchet MS','Lucida sans',SimSun;/*表格中文字的字體類型*/
font-size:18px;/*表格中文字字體大小*/
color:#000;/*整個body區域字體的顏色*/
}
table{
*border-collapse:collapse;/*合並表格邊框*/
border-spacing:0;/*表格的邊框寬度*/
width:100%;
}
.tableStyle{
/*border:solid #ggg 1px;*/
border-style:outset;/*整個表格外邊框樣式*/
border-width:2px;/*整個表格外邊框寬度*/
/*border: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));/*rgb(14,208,80)*/
}
</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>
<tr>
<td>鄧肯</td>
<td>蒂姆</td>
<td>2018-06-27 21:38:14</td>
<td>0.58</td>
<td style="color:#00AC4E">pass</td>
</tr><br/>
<tr>
<td>喬丹</td>
<td>邁克爾</td>
<td>2018-06-27 21:38:29</td>
<td>0.53</td>
<td style="color:#00AC4E">pass</td>
</tr><br/>
<tr>
<td>庫里</td>
<td>斯蒂芬</td>
<td>2018-06-27 21:38:43</td>
<td>0.53</td>
<td style="color:#00AC4E">pass</td>
</tr><br/>
<tr>
<td>杜蘭特</td>
<td>凱文</td>
<td>2018-06-27 21:38:59</td>
<td>0.51</td>
<td style="color:#00AC4E">pass</td>
</tr><br/>
<tr>
<td>詹姆斯</td>
<td>勒布朗</td>
<td>2018-06-27 21:39:13</td>
<td>0.56</td>
<td style="color:#00AC4E">pass</td>
</tr><br/>
</table>
</body>
</html>
----------------------------------------------------------------------
Ran 5 tests in 74.468s
OK
html報告:
report0627.log:
Wed,2018-06-27 21:38:18 test.py[line:110] INFO 搜索"鄧肯",期望"蒂姆"通過
Wed,2018-06-27 21:38:33 test.py[line:110] INFO 搜索"喬丹",期望"邁克爾"通過
Wed,2018-06-27 21:38:47 test.py[line:110] INFO 搜索"庫里",期望"斯蒂芬"通過
Wed,2018-06-27 21:39:03 test.py[line:110] INFO 搜索"杜蘭特",期望"凱文"通過
Wed,2018-06-27 21:39:17 test.py[line:110] INFO 搜索"詹姆斯",期望"勒布朗"通過