我试图通过使用setUpClass()
和tearDownClass()
方法并使用@classmethod
装饰器在方法之间共享单个 Chrome / Firefox 实例。它可以在Chrome上正常运行,但在Firefox中失败。这是环境:
这两种测试方法的预期结果分别为3和1.使用Chrome运行的测试符合预期,但不适用于Firefox。
import unittest
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
caps = DesiredCapabilities.FIREFOX
caps["marionette"] = True
class SearchTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
# create a new Firefox session
cls.driver = webdriver.Firefox(capabilities=caps, executable_path="my\geckodriver\path")
cls.driver.implicitly_wait(30)
cls.driver.maximize_window()
# create a new Chrome session
# cls.driver = webdriver.Chrome("my\chromedriver\path")
# cls.driver.implicitly_wait(30)
# cls.driver.maximize_window()
# navigate to the application home page
cls.driver.get("http://demo-store.seleniumacademy.com/")
def test_search_by_category(self):
# get the search textbox
self.search_field = self.driver.find_element_by_name("q")
self.search_field.clear()
# enter search keyword and submit
self.search_field.send_keys("phone")
self.search_field.submit()
# get all the anchor elements which have product names displayed
# currently on result page using find_elements_by_xpath method
products = self.driver.find_elements_by_xpath("//h2[@class='product-name']")
self.assertEqual(3, len(products))
def test_search_by_name(self):
# get the search textbox
self.search_field = self.driver.find_element_by_name("q")
self.search_field.clear()
# enter search keyword and submit
self.search_field.send_keys("salt shaker")
self.search_field.submit()
# get all the anchor elements which have product names displayed
# currently on result page using find_elements_by_xpath method
products = self.driver.find_elements_by_xpath("//h2[@class='product-name']")
self.assertEqual(1, len(products))
@classmethod
def tearDownClass(cls):
# close the browser window
cls.driver.quit()
if __name__ == '__main__':
unittest.main(verbosity=2)
期望是这样的(用Chrome完成):
test_search_by_category (main.SearchTests) ... ok
test_search_by_name (main.SearchTests) ... ok
----------------------------------------------------------------------
Ran 2 tests in 14.172s
OK
但是使用Firefox,它始终显示:
test_search_by_category (main.SearchTests) ... ok
test_search_by_name (main.SearchTests) ... FAIL
FAIL: test_search_by_name (main.SearchTests)
Traceback (most recent call last):
File "G:\Thunder\PycharmProject\setests\searchtests.py", line 54, in test_search_by_name
self.assertEqual(1, len(products))
AssertionError: 1 != 3
----------------------------------------------------------------------
Ran 2 tests in 13.568s
FAILED (failures=1)
我猜是因为在firefox下运行的硒无法启动第二种测试方法,因此它使用先前的len(products)
值与期望值“ 1”进行比较。
答案 0 :(得分:0)
问题是firefox驱动程序在检查元素数之前不等待页面重新加载。检查此问题
https://github.com/SeleniumHQ/selenium/issues/4570
一个可能的解决方案是在每次测试运行之前导航到您的主页。
为此,您可以在测试中添加一个graph_renderer.node_renderer.data_source.data['code1'] = # your data here
方法,然后将获取页面代码和重置输入框代码移动到该setup
方法中。这是它的样子:
setup
否则,您需要编写代码以确保重新加载页面。