pythonunit-testingselenium-webdriverselenium-chromedriverpython-unittest

Python Unittest: How to initialize selenium in a class and avoid having the browser opening twice?


Consider the example below, since I'm initializing the driver in setUp method and using it in test_login, the browser will open twice, the first time during setUp and then it will be closed and the tests will begin.

If I remove the logic from setUp and put it in test_login, the driver will be undefined in test_profile and tearDown

What's the correct way to initialize the driver and use it throughout the class while not causing the browser to open twice?

from selenium import webdriver
import unittest
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager


class Test(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome(
            service=Service(ChromeDriverManager().install()))
        self.driver.get('https://example.com/login')
        self.current_url = self.driver.current_url
        self.dashboard_url = 'https://example.com/dashboard'

    def test_login(self):
        self.assertEqual(self.dashboard_url, self.current_url)
    
    def test_profile(self):
        self.driver.get('https://example.com/profile')
    
    def tearDown(self):
        self.driver.close()

Solution

  • You need to use setUpClass / tearDownClass:

    import unittest
    
    
    class Test(unittest.TestCase):
        @classmethod
        def setUpClass(cls) -> None:
            print('setUpClass')
    
        @classmethod
        def tearDownClass(cls) -> None:
            print('tearDownClass')
    
        def setUp(self):
            print('setUp')
    
        def test_login(self):
            print('login')
    
        def test_profile(self):
            print('profile')
    
        def tearDown(self):
            print('tearDown')