Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing the webdriver instance automatically after the test failed

My English is very poor but I'll try my best to describe the problem I encountered.

I used selenium webdriver to test a web site and the language that I used to write my script is python.Because of this,I used Pyunit.

I know that if my test suite have no exceptions,the webdriver instance will be closed correctly,(by the way, I used chrome) however,once a exception was threw,the script will be shut down and I have to close chrome manually.

I wonder that how can I achieved that when a python process quits , any remaining open WebDriver instances will also be closed.

By the way, I used Page Object Design Pattern,and the code below is a part of my script:

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()

I haved searched the solution of this problem for a long time ,but almost every answer is depended on java and junit or testNG.How can I deal with this issue with Pyunit?

Thanks for every answer.

like image 576
justuno Avatar asked May 09 '26 22:05

justuno


1 Answers

From the tearDown() documentation:

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.

So, the only case where tearDown will not be called is when setUp fails. Therefore I would simply catch the exception inside setUp, close the driver, and re-raise it:

def setUp(self):
    self.driver = webdriver.Chrome()
    try:
        self.page = personalCenter(self.driver,"admin","123456")
    except Exception:
        self.driver.quit()
        raise
like image 102
E.Z. Avatar answered May 11 '26 12:05

E.Z.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!