Python+Unittest+HTMLTestRunner测试报告—百度个人中心实例
环境配置:https://blog.csdn.net/sevensolo/article/details/100125704
Unittest用法:https://blog.csdn.net/sevensolo/article/details/98202271
# -*- coding = utf-8 -*-
import unittest
import time
from selenium import webdriver
from HTMLTestRunner import HTMLTestRunner
url = "https://www.baidu.com"
class test_Baidu(unittest.TestCase):
def setUp(self):
self.broswer= webdriver.Chrome() # 启动浏览器。Unittest方法,执行之前调用
def tearDown(self): # 关闭浏览器。Unittest方法,用例执行完毕之后调用
self.broswer.quit()
def test_open(self):
"""打开浏览器"""
self.broswer.get(url)
time.sleep(1)
self.assertEqual("百度一下,你就知道", self.browser.title)
if __name__ == "__main__":
unittest.main()
· 这里我们使用了setUp
()和Teardown()
方法,这两个方法介绍,大家可以去看看
· 启动浏览器,输入百度网址,并设置使用断言assertEqual()
,检查百度首页打开是否成功
运行结果
检查hao123首页城市名是否为杭州
· 百度首页寻找hao123并点击,打开F12查看hao123元素属性是超链接,所以这里的hao123定位方法使用by link_text
· hao123页面寻找元素,打开F12查看hao123查看杭州元素属性是class,所以这里定位方法用by class_name
· hao123页面寻找城市是否为杭州,并设置断言预期和结果是否相等
按F12,点击查看器旁边得按钮,选择hao123,查看元素属性
同样的方法查看城市杭州元素属性
# -*- coding = utf-8 -*-
import unittest
import time
import os
from selenium import webdriver
from HTMLTestRunner import HTMLTestRunner
"""参数设置"""
url = "https://www.baidu.com" # 地址
time = time.strftime("%Y%m%d%H%M%S") # 时间,用来命名测试报告
path = os.path.dirname(os.path.realpath(__file__)) # 测试报告输出目录,当前目录
class test_Baidu(unittest.TestCase):
def setUp(self):
self.broswer= webdriver.Chrome()
def tearDown(self):
self.broswer.quit()
def test_checkCity(self):
"""打开浏览器"""
self.broswer.get(url)
time.sleep(1)
"""定位hao123元素并点击"""
self.broswer.find_element_by_link_text("hao123").click()
time.sleep(1)
"""地址位置返回正确"""
city = self.broswer.find_element_by_class_name("weather2-item")
self.assertTrue("杭州", city.get_attribute("weather2-item")) # 设置断言检查城市信息是否正确
if __name__ == "__main__":
Result = unittest.TestSuite()
Result.addTest(test_Baidu("test_checkCity"))
"""
报告时间为当前时间,并给出输出格式
测试路径为当前工程路径
文件命名为路径+\\+当前时间+test_result.html
"""
filename = path + '\\' + time + 'Test_Result.html'
fp = open(filename, "wb")
runner = HTMLTestRunner(stream=fp, title=u"MathTest测试报告", description=u"用例执行情况")
runner.run(Result)
fp.close()
执行结果,OK
工程目录查看测试报告,打开后,可以查看测试用例执行的详细情况