一、摘要

本博文将介绍Python和Selenium做自动化测试的时候,基于unittest框架,借助ddt模块使用json文件作为数据文件作为测试输入,最后生成html测试报告

二、json文件

[
"北京||北京","上海||上海","广州||广州","深圳||深圳","香港||香港"
]

三、ReportTemplate.py

# 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: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(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 = htmlStr + trData + endStr
print(html)
with open("D:\\\Programs\\\Python\\\PythonUnittest\\\Reports\\testTemplate.html", "wb") as fp:
fp.write(html.encode("gbk"))

四、测试脚本

# encoding = utf-8
"""
__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 # 用于存放测试结果状态,失败‘fail’,成功‘pass’
flag = 0 # 数据驱动测试结果的标志,失败置0,成功置1 @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)
# 从.json文件中读取出的数据用“||”分割成测试数据和期望的数据
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 # 减去强制等待3秒
# 每一组数据测试结束后,都将其测试结果信息插入表格行的HTML代码中,并将这些行HTML代码拼接到变量trStr变量中,
# 等所有测试数据都被测试结束后,传入htmlTemplate()函数中,生成完整测试报告的HTML代码
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):
# 写自定义的HTML测试报告,整个过程只被调用一次
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 搜索 ‘香港’,期望 ‘香港’ ,通过

六、测试报告

Python&Selenium 数据驱动【unittest+ddt+json】的更多相关文章

  1. python selenium 使用unittest 示例

    python selenium 使用unittest 示例 并等待某个元素示例 from selenium.webdriver.support.ui import WebDriverWait from ...

  2. python+requests+excel+unittest+ddt接口自动化数据驱动并生成html报告

    1.环境准备: python3.6 requests xlrd openpyxl HTMLTestRunner_api 2.目前实现的功能: 封装requests请求方法 在excel填写接口请求参数 ...

  3. python+requests+excel+unittest+ddt接口自动化数据驱动并生成html报告(二)

    可以参考 python+requests接口自动化完整项目设计源码(一)https://www.cnblogs.com/111testing/p/9612671.html 原文地址https://ww ...

  4. python+requests+excel+unittest+ddt接口自动化数据驱动并生成html报告(已弃用)

    前言 1.环境准备: python3.6 requests xlrd openpyxl HTMLTestRunner_api 2.目前实现的功能: 封装requests请求方法 在excel填写接口请 ...

  5. Python 数据驱动 unittest + ddt

    一数据驱动测试的含义: 在百度百科上的解释是: 数据驱动测试,即黑盒测试(Black-box Testing),又称为功能测试,是把测试对象看作一个黑盒子.利用黑盒测试法进行动态测试时,需要测试软件产 ...

  6. python+selenium九:ddt数据驱动

    第一种,测试数据放在Excel里面 test_Login: import unittestimport timeimport ddtimport osfrom selenium import webd ...

  7. Python&Selenium 数据驱动【unittest+ddt+json+HTMLTestRunner】

    一.摘要 本博文将介绍Python和Selenium做自动化测试的时候,基于unittest框架,借助ddt模块使用json文件作为数据文件作为测试输入,最后借助著名的HTMLTestRunner.p ...

  8. Python&Selenium 数据驱动【unittest+ddt】

    一.摘要 本博文将介绍Python和Selenium做自动化测试的时候,基于unittest框架,借助ddt实现数据驱动 二.测试代码 # encoding = utf-8 ""& ...

  9. Python&Selenium 数据驱动测试【unittest+ddt+xml】

    一.摘要 本博文将介绍Python和Selenium做自动化测试时,基于unittest框架,借助ddt模块,使用xml文件作为测试输入. 二.xml文件 保存路径:D:\\Programs\\Pyt ...

随机推荐

  1. lua介绍及环境搭建(一)

    一.介绍 1.简介 Lua 是一种轻量小巧的脚本语言,用标准C语言编写并以源代码形式开放, 其设计目的是为了嵌入应用程序中,从而为应用程序提供灵活的扩展和定制功能. 其设计目的是为了嵌入应用程序中,从 ...

  2. 【AtCoder】ARC063

    ARC063 C - 一次元リバーシ / 1D Reversi 不同的颜色段数-1 #include <bits/stdc++.h> #define fi first #define se ...

  3. php静态调用非静态方法

    <?php /** * php静态调用非静态方法 * author: 百里 * Date: 2019/7/18 * Time: 17:28 */ function dump(...$var) { ...

  4. python 入门(基础)

    1. python的常见数据类型(str , list ,dict,set) str (字符串的操作方法) astr = " Hello Workd " astr.strip() ...

  5. jquery tablesorter 动态加载数据时,排序。过滤失效解决方案

    解决方案:重置更新: $("table").trigger("update"); 1 官方 ajax表格数据添加实例: $(document).ready(fu ...

  6. sentinel与hystrix对比

    近期有同事再提要不要使用sentinel.所以我就对现在已经用hystrix.先看两者的线程模型.大部分对比项是sentinel开源工程对比的,本人做了一些修改以及增加了一些对比项和说明. 从线程模型 ...

  7. 进程程序替换(自主实现shell)

    进程替换 替换进程所运行的程序 流程:将另一段代码加载到内存中,通过页表将原来进程的映射关系重新建立到新的程序在内存中的地址,相当于替换了进程所运行程序以及所要处理的数据 (替换了代码段,重新初始化数 ...

  8. Django2.0 应用 Xadmin 报错解决(转载)

    原文地址:https://blog.csdn.net/GoAheadNeverTurnBack/article/details/8143362 1.TypeError at /xadmin/    l ...

  9. Oracle 以及 PLSQL安装

    今天重装系统遇到oracle 安装的问题咯 ,oracle安装过程中很多疑难杂症咯 1如果之前装过,记得去删除注册表的Oracle 相关的文件 ,请百度有很多教程咯 2这个必须要勾选的!因为的是11g ...

  10. 【shell脚本】字符串和数组的使用

    字符串 可以使用单引号和双引号定义字符串变量但是单引号中不支持变量解析 #! /bin/bashusername="mayuan" str_1="hello ${user ...