【selenium】selenium+python+unittest实现生成测试报告
以慕课网https://www.imooc.com/为例
1,loginSuccess.py
# testLogin 2022-05-17 by Pearl # coding:utf-8 import unittest from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.keys import Keys import time import sys reload(sys) sys.setdefaultencoding('utf8') class LoginSuccessTestCase(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() #需要提前下载chromedriver.exe,存放路径:python/Scripts或Chrome(‘这里写出另外存放的路径’) self.driver.maximize_window() self.driver.get("https://www.imooc.com/") self.driver.implicitly_wait(15) self.expect_result = u'我的课程' # 登录前的cookie cookie1 = self.driver.get_cookies() print('cookie11', cookie1) def test_login(self): self.driver.find_element_by_id('js-signin-btn').click() time.sleep(10) uName_tag = self.driver.find_element_by_name("email") uPwd_tag = self.driver.find_element_by_name("password") uName_tag.click() uName_tag.send_keys('your username') time.sleep(5) uPwd_tag.click() uPwd_tag.send_keys('your password') time.sleep(5) self.driver.find_element_by_class_name('xa-login').click() time.sleep(10) # 获取登录后的cookie 方便跳过验证码 cookie2 = self.driver.get_cookies() print('cookie2', cookie2) result = self.driver.find_element_by_xpath("//div[@id='login-area']/ul/li[4]/a/span").text # 断言 self.assertEqual(result, self.expect_result) def tearDown(self): self.driver.close() if __name__ == '__main__': unittest.main()
2,runner.py,HTMLTestRunner下载地址:http://tungwaiyip.info/software/HTMLTestRunner.html
# coding:utf-8 import unittest import HTMLTestRunner #导入HTMLTestRunner,存放路径:python/Scripts from time import strftime, localtime, time from loginSuccess import * from loginFail import * import sys reload(sys) sys.setdefaultencoding('utf8') # suite = unittest.TestSuite() suite1 = unittest.TestLoader().loadTestsFromTestCase(LoginSuccessTestCase) suite2 = unittest.TestLoader().loadTestsFromTestCase(LoginFailTestCase) suite = unittest.TestSuite([suite1, suite2]) # 把测试用例添加到测试容器中 now = strftime("%Y-%m-%M-%H_%M_%S", localtime()) # 获取当前时间 filename = now + "test.html" # 文件名 fp = file(filename, 'wb') runner = HTMLTestRunner.HTMLTestRunner( stream=fp, verbosity=2, title="测试报告", description="测试报告的详情") runner.run(suite)