python - 测试失败后自动关闭webdriver实例

标签 python testing selenium python-unittest

我的英语很差,但我会尽力描述我遇到的问题。

我使用 selenium webdriver 来测试一个网站,我用来编写脚本的语言是 python。因此,我使用了 Pyunit。

我知道如果我的测试套件没有异常,webdriver 实例将被正确关闭,(顺便说一下,我使用 chrome)但是,一旦抛出异常,脚本将被关闭,我必须关闭手动 Chrome 。

我想知道如何实现当 python 进程退出时,任何剩余的打开的 WebDriver 实例也将被关闭。

顺便说一下,我使用了页面对象设计模式,下面的代码是我脚本的一部分:

class personalcenter(unittest.TestCase):

    def setUp(self):

        self.driver = webdriver.Chrome()
        self.page = personalCenter(self.driver,"admin","123456")

    def testAddWorkExp(self):

        blahblahblah...

    def tearDown(self):

        self.page.quit()
        self.driver.quit()

if __name__ == "__main__":

    unittest.main()

这个问题的解决方案我找了很久,但是几乎所有的答案都依赖于java和junit或者testNG。我如何用Pyunit处理这个问题?

感谢您的每一个回答。

最佳答案

来自 tearDown() 文档:

Method called immediately after the test method has been called and the result recorded. This is called even if the test method raised an exception, so the implementation in subclasses may need to be particularly careful about checking internal state. Any exception raised by this method will be considered an error rather than a test failure. This method will only be called if the setUp() succeeds, regardless of the outcome of the test method. The default implementation does nothing.

因此,tearDown 不会被调用的唯一情况是 setUp 失败。 因此,我会简单地在 setUp 中捕获异常,关闭驱动程序,然后重新引发它:

def setUp(self):
    self.driver = webdriver.Chrome()
    try:
        self.page = personalCenter(self.driver,"admin","123456")
    except Exception:
        self.driver.quit()
        raise

关于python - 测试失败后自动关闭webdriver实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21109604/

相关文章:

testing - (错误)理解 Smalltalk 和 TDD

Python - 无法使用 selenium chromewebdriver 下载文件 - 'Failed - Download error'

java - 我应该使用什么工具从网站收集数据

node.js - 如何使用从 Controller 返回的值?在 NestJs 上测试 Controller

python - 如何在 vscode 中运行几行选定的代码?

python - 获取 scikit-learn tf-idf 矩阵中的文档名称

python - 寻找一种在 Django admin 中显示代码块的简单方法

c++ - 编写测试套件的指南

python - 我在使用 Selenium 时不断收到 "name"错误。我究竟做错了什么?

python - 查看Redis的版本