今天用unittest+selenium+HTMLTestRunner做一个简单的项目实战,以自己的博客为例:
test_zx.py
import unittest
import time
from HTMLTestRunner import HTMLTestRunner
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class T(unittest.TestCase):
def setUp(self):
self.url = 'https://blog.csdn.net/zzrs_xssh'
self.driver = webdriver.Chrome()
self.driver.implicitly_wait(10)
self.handlers = []
self.driver.maximize_window()
def test_zx(self):
"""zx test case"""
driver = self.driver
driver.get(self.url)
WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CLASS_NAME, 'title-blog')))
print(driver.title)
self._handler_list()
# 操作滚动条将页面拉到最下边
js = 'var q=document.documentElement.scrollTop=10000'
driver.execute_script(js)
# 找到对应的元素点击
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="mainBox"]/main/div[2]/div[39]/h4/a')))
elem = driver.find_element_by_xpath('//*[@id="mainBox"]/main/div[2]/div[39]/h4/a')
elem.click()
self._handler_list()
print(f"所有窗口的handler是{self.handlers}")
self._switch_to_window(1)
print(driver.title)
elem_title = driver.find_element_by_xpath('//*[@id="mainBox"]/main/div[1]/div/div/div[1]/h1')
self.assertEqual(elem_title.text, u"python基础——sorted函数和sort函数")
time.sleep(5)
def _switch_to_window(self, window_num):
"""根据下标切换到对应的窗口"""
return self.driver.switch_to.window(self.handlers[window_num])
def _handler_list(self):
"""把当前所有的窗口handler加到列表中"""
for handler in self.driver.window_handles:
if handler not in self.handlers:
self.handlers.append(handler)
def tearDown(self):
self.handlers = []
self.driver.quit()
if __name__ == '__main__':
suit = unittest.TestSuite()
suit.addTest(T("test_zx"))
with open("res.html", "w", encoding="utf-8") as f:
runner = HTMLTestRunner.HTMLTestRunner(stream=f,
title=u"zx测试报告",
description=u"zx迭代1测试报告")
runner.run(suit)
以上代码执行完以后应该会在test_zx.py的同级目录下生成一个res.html的文件,但是事实并非如此,并没有生成res.html文件,解决办法:将if name == 'main’改为if name == ‘test_zx’,即可解决