快速构建一个完整的Selenium框架
今天跟大家细讲如何构建一个完整的selenium框架,当你学会了这一篇你就也可以说自己会selenium自动化测试了。
1、新建项目,结构如图:
注意:整个项目除了最外层的是文件夹,其他的都是包(package)。也就是说每一个文件夹下面都是有一个_init _.py文件的。只有包才能顺利的用import导入哦~~
2、文件介绍及代码
baseinfo
这里面只有一个__init __.py文件,里面放的是常量:比如邮件的设置信息、发送的固定URL等。
# coding: utf-8'''
发送邮件参数
'''Smtp_Server = 'smtp.mxhichina.com'Smtp_Sender = 'abc@tenez.cn'Smtp_Sender_Password = '**********'Smtp_Receiver = ['312652826@qq.com', 'warrior_meng08@163.com']
module
这个包下面有:__init __.py(确定它是包而不是文件夹的文件),getTestcase.py——获取测试用例文件;getTestResult.py——获取用例执行结果文件,以及sendEmail.py——发送邮件文件。这个包里放的都是封装好的方法,也就是说以后我们只需要调用这些方法就可以实现相应的功能了。
__init __.py
这个文件里面的内容:
# coding: utf-8import getTestcasesimport sendEmailimport getTestResult
正如大家看到的,这里面只有几个import,这样写是为了后面利用from module import * 这种导入方式,如果不在__init __.py里写这些导入的话,前面的那种导入方式是不能用的。
getTestcase.py
# coding: utf-8import unittestimport osdef testcaseDir(test_directory): '''
os.walk()传入顶层文件夹路径,返回三个内容: 1、根路径; 2、路径下所有文件夹名; 3、路径下所有非文件夹名【2,3都是以列表形式返回】
这个是遍历文件夹,然后遍历对应文件夹下面的文件
''' # for a, b, c in os.walk(test_directory):
# for dirs in b:
# test_dir = '%s\\%s' % (test_directory, dirs)
# test_discover = unittest.defaultTestLoader.discover(test_dir, pattern='test*.py', top_level_dir=test_dir)
# return test_discover '''
事实证明加了文件夹也没关系,但是不能是文件夹,必须是包,也就是你新建的时候必须选package(必须有__init__.py文件)
''' discover = unittest.defaultTestLoader.discover(test_directory, pattern='test*.py', top_level_dir=test_directory) return discover
这个方法是读取testcase文件夹(包)里面的测试用例。大家也看到了,一开始我建的就是文件夹,然后怎么样都读不出testcase文件夹下面的文件夹里面的用例,最后我写了一个具体的遍历文件夹的方法,然后去读用例,最后经人指点,加了__init __.py方法,把文件夹变成了包,瞬间就OK了。
getTestResult.py
# coding: utf-8from selenium import webdriverfrom time import sleepdef get_result(filename):
driver = webdriver.Firefox()
driver.maximize_window() # 得到测试报告路径
result_url = "file://%s" % filename
driver.get(result_url)
sleep(3)
res = driver.find_element_by_xpath("/html/body/div[1]/p[4]").text
result = res.split(':')
driver.quit() return result[-1]
这个方法是将生成的测试报告对应的测试运行结果拿出来,到时候作为发送邮件的标题发送。
sendEmail.py
# coding: utf-8import smtplibimport baseinfoimport timefrom email.mime.multipart import MIMEMultipartfrom email.header import Headerfrom email.mime.text import MIMETextdef send_Mail(file_new, result):
f = open(file_new, 'rb') # 读取测试报告正文
mail_body = f.read()
f.close() try:
smtp = smtplib.SMTP(baseinfo.Smtp_Server, 25)
sender = baseinfo.Smtp_Sender
password = baseinfo.Smtp_Sender_Password
receiver = baseinfo.Smtp_Receiver
smtp.login(sender, password)
msg = MIMEMultipart()
text = MIMEText(mail_body, 'html', 'utf-8')
text['Subject'] = Header('UI自动化测试报告', 'utf-8')
msg.attach(text) now = time.strftime("%Y-%m-%d")
msg['Subject'] = Header('[ 执行结果:' + result + ' ]'+ 'UI自动化测试报告' + now, 'utf-8')
msg_file = MIMEText(mail_body, 'html', 'utf-8')
msg_file['Content-Type'] = 'application/octet-stream'
msg_file["Content-Disposition"] = 'attachment; filename="TestReport.html"'
msg.attach(msg_file) msg['From'] = sender msg['To'] = ",".join(receiver)
tmp = smtp.sendmail(sender, receiver, msg.as_string()) print tmp
smtp.quit() return True
except smtplib.SMTPException as e:
print(str(e)) return False
发送邮件的方法,都是一个道理。
test_report
testReport_path.py
# coding: utf-8import os# 获取当前文件夹路径def report_path():
return os.path.split(os.path.realpath(__file__))[0]
testcase
login
testLogin1.py【测试用例1】
# coding: utf-8from selenium import webdriverimport timeimport unittestimport baseinfoimport sys
reload(sys)
sys.setdefaultencoding('utf8')class TestLogin(unittest.TestCase): print '1.这是testLogin1用例打印内容,文件夹login' @ classmethod
def setUpClass(self):
self.driver = webdriver.Firefox()
time.sleep(1)
self.driver.maximize_window() @ classmethod
def tearDownClass(self):
time.sleep(1)
self.driver.quit() def test_purchase(self):
print(u"因未找到对应元素,测试用例未正常执行!")
testLogin2【测试用例2】
# coding: utf-8import unittestclass testLogin2(unittest.TestCase): def setUp(self): print '2.这是testLogin2文件夹下面的setup方法' def test11(self):
return '3.return 方法返回' def testLogin(self):
print 222
testcase2
testBuy.py【测试用例3】
# coding: utf-8import unittestclass testBuy(unittest.TestCase): print '4.这是testBuy方法,来自testcase2文件夹' def testPrint(self):
print '5.这是test_1打印的内容,文件夹是testcase2'
testSell.py【测试用例4】
# coding: utf-8print '6.这里只有print--testSell.py文件'
与login和testcase2文件夹同级文件testcase_path.py
# coding: utf-8import os# 获取当前文件夹路径def dir_path():
return os.path.split(os.path.realpath(__file__))[0]
如果对软件测试、接口测试、自动化测试、面试经验交流感兴趣可以加软件测试交流:1085991341,会有不定期的发放免费的资料链接,还会有同行一起技术交流。
runtest.py
# coding: utf-8import timefrom module import *from testcase import testcase_pathfrom test_report import testReport_pathfrom HTMLTestRunner import HTMLTestRunnerif __name__ == '__main__': # 测试用例路径
test_dir = testcase_path.dir_path() # 测试报告存放路径
report_dir = testReport_path.report_path() # print report_dir now = time.strftime("%Y-%m-%d")
filename = report_dir + '\\report-' + now + '.html'
# print filename
fp = open(filename, 'wb')
runner = HTMLTestRunner(stream=fp, title='UI自动化测试报告', description='用例执行情况')
runner.run(getTestcases.testcaseDir(test_dir))
fp.close()
result = getTestResult.get_result(filename) print result
mail = sendEmail.send_Mail(filename, result) if mail:
print(u"邮件发送成功!") else:
print(u"邮件发送失败!")
用例执行这里只有一个方法,其他全是调用module文件夹下面的方法。
大家注意一下我的用例,运之后可以看到输出结果:
只有1、4、6打印出来了哦,其他的是不会打印的,也就是说你在用例里写的print是不会打印的,这是因为HTMLTestRunner.py规定的。试过自己修改过的可以打印用例里面的print了,但是会返回很多None,也就是说出里面会有好多红色的None。
以上内容希望对你有帮助,有被帮助到的朋友欢迎点赞,评论。
快速构建一个完整的Selenium框架的更多相关文章
- springboot:快速构建一个springboot项目
前言: springboot作为springcloud的基础,springboot的热度一直很高,所以就有了这个springboot系列,花些时间来了解和学习为自己做技术储备,以备不时之需[手动滑稽] ...
- 【jQuery插件】用jQuery Masonry快速构建一个pinterest网站布局(转)
[jQuery插件]用jQuery Masonry快速构建一个pinterest网站布局 时间:2011年03月21日作者:愚人码头查看次数:29,744 views评论次数:25条评论 前段时间领导 ...
- 转载自 BotVS 「 珍藏版 」如何搭建一个完整的交易框架
[img]http://dn-filebox.qbox.me/8c218c119046b2a25df2d9c7b00c1e0fa6899bdd.png[/img]NO:01 交易策略 ≠ 交易系统. ...
- 快速构建一个简单的单页vue应用
技术栈 vue-cli webpack vux,vux-loader less,less-loader vue-jsonp vue-scroller ES6 vue-cli:一个vue脚手架工具,利用 ...
- 快速构建一个 Springboot
快速构建一个 Springboot 官网:http://projects.spring.io/spring-boot/ Spring Boot可以轻松创建可以“运行”的独立的,生产级的基于Spring ...
- 快速构建一个vue项目
首先介绍一下命令行构建一个vue项目步骤: 1.下载安装node.js(直接运行安装包根据步骤安装完),打开命令行输入:node -v ,出现版本号即安装成功. 2.命令行界面输入:cnpm inst ...
- 快速构建一个使用axios的vue应用程序(转)
英文原文:https://www.sitepoint.com/fetching-data-third-party-api-vue-axios/ 译文:https://segmentfault.com/ ...
- 基于react+如何搭建一个完整的前端框架(1)
1.使用 create-react-app 快速构建 React 开发环境 create-react-app 是来自于 Facebook,通过该命令我们无需配置就能快速构建 React 开发环境. ...
- 快速构建一个springboot项目(一)
前言: springcloud是新一代的微服务框架而springboot作为springcloud的基础,很有必要对springboot深入学习一下. springboot能做什么? (1)spri ...
随机推荐
- PHP htmlspecialchars_decode() 函数
实例 把预定义的 HTML 实体 "<"(小于)和 ">"(大于)转换为字符:高佣联盟 www.cgewang.com <?php $str ...
- PHP getNamespaces() 函数
实例 返回 XML 文档中使用的命名空间: <?php$xml=<<<XML高佣联盟 www.cgewang.com<?xml version="1.0&quo ...
- Promise核心基础
基础 Promise 抽象表达:是js中进行异步编程的新的解决方案 具体解释:1.从语法上来说是一个构造函数 2.从功能上来说promise对象用来封装一个异步操作并可以获取其结果 状态改变:0.ne ...
- Python PIL方式打开的图片判断维度
1. PIL方式打开的图片判断维度 好久没更新啦,哈哈哈~~!今天跟宝宝们分享一篇如何判断灰度图像和彩色图像维度的方法.我们在读取灰度图像和彩色图像时,发现读取出来的图片维度不同,当我们要做后续 ...
- Python实现微信读书辅助工具
[TOC] ##项目来源 这个有意思的项目是我从GitHub上找来的,起因是在不久前微信读书突然就设置了非会员书架数目上限,我总想做点什么来表达我的不满,想到可否用爬虫来获取某一本书的内容, 但是我技 ...
- Maven知识记录(一)初识Maven私服
Maven知识记录(一)初识Maven私服 什么是maven私服 私服即私有的仓库.maven把存放文件的地方叫做仓库,我们可以理解成我门家中的储物间.而maven把存放文件的具体位置叫做坐标.我们项 ...
- 基于AspectCore打造属性注入
前言 源自于晓晨在成都.net社区群的一篇文章 <晓晨的ASP.NET Core 奇淫技巧之伪属性注入> 他的思路是 Ioc容器替换 ControllerActivator,因为只能在控制 ...
- Xcode11更改启动页设置方法
新开了个项目,发现之前的启动页怎么也调不好,后来发现配置里边少了一行,所以整理一下,我使用的xcode版本是11. 以前的时候是在这2个中间,还有一行,通过下边2项来配置,现在更改了,附上新的教程.如 ...
- 解决SpringBoot项目中Thymeleaf模板的中文乱码问题
1.使用IDEA创建SpringBoot项目 package com.example.demo; import org.springframework.boot.SpringApplication; ...
- 详解GaussDB(for MySQL)服务:复制策略与可用性分析
摘要:本文通过介绍GaussDB(for MySQL)读写路径,分析其可用性. 简介 数据持久性和服务可用性是数据库服务的关键特征. 在实践中,通常认为拥有 3 份数据副本,就足以保证持久性. 但是 ...