python+selenium+unittest+BeautifulReport自动化测试(2)
1、建立项目
我这里建立一个简单的项目
在电脑建立项目文件夹testproject
testproject文件夹里面在划分
1.1测试用例编写
以百度的网站的登陆作为测试
(1)打开pychram,文件打开我们刚才建立的文件夹
建立一个baidulogin文件
(2)打开百度网址
我们要做ui自动化测试首先要控制我们的浏览器,再进行浏览器的定位操作
控制浏览器要安装浏览器驱动,我是用谷歌浏览器,驱动器安装与对应表:https://blog.csdn.net/cz9025/article/details/70160273
浏览器驱动下载成功之后,将它放在Python3\Scripts文件夹下
接下来就可以打开浏览器了:
运行
(3)unittest单元测试框架运用
编写用例我们要使用unittest单元测试框架
创建一个baiduLogin类引用unittest,对上面代码做一些修整
上面通过继承TestCase类并且在测试类中为每一个测试添加测试方法来创建单个测试或者一组测试。
setUp():这个方法在每个测试开始前去执行一些初始化的任务,比如创建浏览器实例,访问URL,测试执行器在每次执行测试方法之前优先执行该方法
test开头方法:每个test开头的都作为一个用例,每个用例是从上面到下面执行的
tearDown():这个方法方法来清理所有的初始化值,关闭浏览器等
if __name__ == '__main__':相当于Python模拟的程序入口,运行我们上面的文件类方法
(4)元素定位
打开浏览器,按F12进行元素查找
然后进行selenium定位
Selenium提供了8种定位方式。
分别是id、name、class name、tag name、link text、partial link text、xpath、css selector
这8种定位方式在Python selenium中所对应的方法为:
find_element_by_id()
find_element_by_name()
find_element_by_class_name()
find_element_by_tag_name()
find_element_by_link_text()
find_element_by_partial_link_text()
find_element_by_xpath()
find_element_by_css_selector()
我们找到登陆按钮的元素
定位点击self.driver.find_element_by_class_name("lb").click()
元素赋值,接下来我们输入账号、密码
登陆:
(5)运行用例生成报告
创建test_suite.py文件用于运行用例生成报告
if __name__ == '__main__':
test_suite = unittest.defaultTestLoader.discover('./tests', pattern='test*.py')
result = BeautifulReport(test_suite)
result.report(filename='测试报告', description='测试deafult报告', report_dir='report', theme='theme_default')
说明
report (
filename -> 测试报告名称, 如果不指定默认文件名为report.html
description -> 测试报告用例名称展示
report_dir='.' -> 报告文件写入路径
theme='theme_default' -> 报告主题样式 theme_default theme_cyan theme_candy theme_memories
)
报告生成的