python - 第一次测试后 Selenium 测试失败

标签 python django selenium

我正在尝试使用 xvfb 在 Debian 服务器上运行我为 Django 项目编写的 selenium 测试。

我尝试运行 3 个测试,在第一个测试之后,它们失败并出现以下错误: NoSuchElementException:消息:u'无法定位元素:{"method":"xpath","selector":"//a[@href=\\"#detail\\"]"}'

我已经运行了 export DISPLAY=:99 并使用 Django LiveServerTestCase 和 django-selenium。 SELENIUM_DISPLAY = ':99' 在我的 settings.py 中设置。

这是我的测试运行程序:

class BaseLiveTest(LiveServerTestCase):
    @classmethod
    def setUpClass(cls):
        cls.selenium = WebDriver()
        super(BaseLiveTest, cls).setUpClass()

    @classmethod
    def tearDownClass(cls):
        super(BaseLiveTest, cls).tearDownClass()
        cls.selenium.quit()

    def login(self, user):
        #helper function, to log in users
        #go to login page
        self.selenium.get("%s%s" % (self.live_server_url, reverse('userena_signin')))
        #wait for page to display
        WebDriverWait(self.selenium, 10).until(
            lambda x: self.selenium.find_element_by_id('id_identification'),
        )
        #fill in form and submit
        identifictation_input = self.selenium.find_element_by_id('id_identification')
        identifictation_input.send_keys(user.email)
        password_input = self.selenium.find_element_by_id("id_password")
        password_input.send_keys('password')
        self.selenium.find_element_by_xpath('//form/descendant::button[@type="submit"]').click()

        #wait for dashboard to load
        WebDriverWait(self.selenium, 10).until(
            lambda x: self.selenium.find_element_by_id('container'),
        )

当我单独运行每个测试时,它们都会通过,但如果我尝试依次运行它们,最后两个测试就会失败。有什么想法吗?

最佳答案

您需要使用setUp()tearDown(),而不是setUpClass()tearDownClass() >。类版本针对整个固定装置全局运行,因此所有 3 个测试都使用相同的 WebDriver 实例,因此浏览器不会处于您对第二个和第三个测试所期望的状态。

关于python - 第一次测试后 Selenium 测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12012323/

相关文章:

selenium - 如何在Selenium Webdriver(Python)中使用变量名存储包含特定文本的元素来存储字符串?

python - 为什么 requests.get() 不能在 for 循环中工作?

database - Django model.save() 不写入数据库

python - __init__() 获得参数 'crescator' 的多个值

python - Neomodel 是否支持模型形式?如果是这样,为什么不选择默认元属性/如何设置它们?

selenium - Selenium 的最小 perl 脚本是什么?

java - 如何使用 Selenium JavascriptExecutor 将 <script> 添加到 Head 中

python - 通过名称引用列表元素

python - 混合 C++ 和 Python 的项目的目录结构

python - 将 Numpy 数组拆分为等长的子数组