简体   繁体   English

在 Python unittest 中,有没有办法编写在断言失败时运行的代码?

[英]In Python unittest, is there any way to write code that is run in the event of an assertion failure?

I'm using the Python unittest library to write some tests with Selenium.我正在使用 Python unittest 库用 Selenium 编写一些测试。 One of these tests involves going forward from one page to the next, checking an assertion, and then returning to the previous page as so:其中一个测试涉及从一页前进到下一页,检查断言,然后返回上一页,如下所示:

def test_CheckNextPage(self):
     self.nextPageLink.click()
     self.assertEqual('The Next Page', self.driver.title)
     self.driver.back()

If in the event that the assertion fails, the self.driver.back() line is never reached and so all further tests are run on the wrong page, leading to them all being errors.如果断言失败,则永远不会到达self.driver.back()行,因此所有进一步的测试都在错误的页面上运行,导致它们全都是错误。

Is there any way to write a block of code to be run in the event of a failure after an assertion, so if it fails I can run some different code than if the assertion were to pass?有没有办法编写一段代码,以便在断言后发生故障时运行,所以如果它失败,我可以运行一些与断言通过时不同的代码? (this block of course including the self.driver.back() line). (这个块当然包括self.driver.back()行)。

You're probably looking for the tearDown method.您可能正在寻找 tearDown 方法。 A generic example is below.下面是一个通用示例。

import unittest

class SimpleWidgetTestCase(unittest.TestCase):
    def setUp(self):
        self.widget = Widget('The widget')

    def runTest(self):
        # your test

    def tearDown(self):
        self.widget.dispose()
        self.widget = None

If setUp() succeeded, the tearDown() method will be run whether runTest() succeeded or not.如果 setUp() 成功,则无论 runTest() 是否成功,都会运行 tearDown() 方法。

Look at the setUp and tearDown part of the documentation.查看文档的 setUp 和 tearDown 部分

For this case, I fixed the issue by using a try/except to effectively create two different execution paths.对于这种情况,我通过使用 try/except 来有效地创建两个不同的执行路径来解决该问题。 One path for in the event the assertion fails, and another for when it passes.断言失败时的一条路径,以及断言通过时的另一条路径。

def test_CheckNextPage(self):
     self.nextPageLink.click()
     try: self.assertEqual('The Next Page', self.driver.title)
     except: 
          self.driver.back()
          self.fail("Page title does not match expectation")

     self.driver.back()

In doing this, we get the full failure report from the assertion, and our manual failure message.在这样做时,我们从断言中获得完整的失败报告,以及我们的手动失败消息。 This way we can ensure that self.driver.back() is called no matter what so that the rest of the tests will run correctly.通过这种方式,我们可以确保self.driver.back()都会调用self.driver.back() ,以便其余的测试能够正确运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM