from selenium import webdriverimport unittestimport time class Blog(unittest.TestCase): """登录博客园""" # 添加@classmethod装饰器,只打开浏览器一次 @classmethod def setUpClass(cls): """初始化""" cls.browser = webdriver.Chrome() cls.url = ‘https://passport.cnblogs.com/user/signin‘ cls.browser.get(cls.url) cls.browser.implicitly_wait(30) cls.browser.maximize_window() def login(self, username, password): """登录帐号密码参数化""" self.browser.find_element_by_id(‘input1‘).send_keys(username) self.browser.find_element_by_id(‘input2‘).send_keys(password) self.browser.find_element_by_id(‘signin‘).click() time.sleep(3) def is_login_sucess(self): """判断是否获取登录后账户名称""" time.sleep(2) try: text = self.browser.find_element_by_id(‘lnk_current_user‘).text print(text) return True except: return False def back_out(self): # 退出返回登录页面 time.sleep(2) self.browser.find_element_by_xpath(‘//*[@id="header_user_right"]/a[5]‘).click() time.sleep(2) # alert方法去掉退出弹框 s = self.browser.switch_to_alert() s.accept() time.sleep(2) self.browser.find_element_by_xpath(‘//*[@id="header_user_left"]/a[1]‘).click() time.sleep(2) def clear_box(self): """清空输入框""" self.browser.find_element_by_id(‘input1‘).clear() self.browser.find_element_by_id(‘input2‘).clear() time.sleep(1) def test_01(self): """调用login函数登录""" self.login(‘uesrname‘, ‘password‘) result = self.is_login_sucess() self.assertTrue(result) def test_02(self): """错误的示范""" self.back_out() self.clear_box() self.login(‘1‘, ‘2‘) result = self.is_login_sucess() self.assertTrue(result, msg=‘失败了呀,没有获取登录后的账户名称呢!‘) @classmethod def tearDownClass(cls): cls.browser.quit() if __name__ == ‘__main__‘: """生成html报告""" import HTMLTestRunner # now = time.s now = time.strftime(‘%Y-%m-%d %H-%M-%S‘) report_title = ‘博客园登录自动化测试‘ # report_path = r‘D:\PythonProject\com\report.html‘ report_path = ‘D:\\PythonProject\\com\\‘+ now + ‘report.html‘ explain = ‘博客园登录测试报告‘ test_suite = unittest.TestSuite() test_suite.addTest(Blog(‘test_01‘)) test_suite.addTest(Blog(‘test_02‘)) with open(report_path, ‘wb‘) as fp: runner = HTMLTestRunner.HTMLTestRunner(title=report_title, stream=fp, description=explain) runner.run(test_suite) fp.close()
时间: 2024-10-21 12:44:20