最近在学习unittest单元测试框架,之前调试好的测试脚本,发现放在这个框架中,无法正常switch_to.window,总是报错无法定位到元素,个人感觉是因为窗口梅正常切换过去,新人求指教,谢谢,代码如下:
main.py
import time
import unittest
import auto_test
suite = unittest.TestSuite()
suite.addTest(auto_test.Python_autotest('get_browser'))
suite.addTest(auto_test.Python_autotest('search'))
suite.addTest(auto_test.Python_autotest('user_login'))
suite.addTest(auto_test.Python_autotest('user_logout'))
if __name__ == '__main__':
runner = unittest.TextTestRunner()
runner.run(suite)
auto_test.py
from selenium import webdriver
import time
import unittest
class Python_autotest(unittest.TestCase):
def setUp(self,driver = webdriver.Firefox()):
print('Test is start')
self.driver = driver
def get_browser(self):
self.driver.get("https://www.baidu.com/")
def search(self):
try:
self.driver.find_element_by_xpath('//*[@id="kw"]').send_keys('segmentfault')
self.driver.find_element_by_xpath('//*[@id="su"]').click()
except Exception:
print('No found everything, sorry!')
else:
time.sleep(1)
self.driver.find_element_by_xpath("/html/body/div[1]/div[5]/div[1]/div[3]/div[1]/h3/a").click()
def user_login(self):
self.driver.switch_to.window(self.driver.window_handles[-1])
time.sleep(3)
self.driver.find_element_by_xpath('/html/body/div[4]/div/div/div[1]/div[2]/a[1]').click()#点击页面中的前端菜单栏
def user_logout(self):
self.driver.quit()
def tearDown(self):
print('Test is finish')
if __name__ == '__main__':
unittest.main()