Pytest Setup and Teardown for Selenium Testing

Instead of relying on pytest’s built-in setup methods, you can manage resources within the test class using __init__ and __del__.

import pytest
from selenium import webdriver

class TestClass:

    def __init__(self):
        # Initialize browser for each test instance
        self.browser = webdriver.Chrome()

    def test_buttons(self):
        # Use self.browser here to interact with the browser
        self.browser.get('http://example.com')
        assert self.browser.title == 'Example Domain'

    def test_buttons2(self):
        # Another test using the same browser instance
        self.browser.get('http://anotherexample.com')
        assert self.browser.title == 'Another Example'

    def __del__(self):
        # Cleanup browser instance when the test object is deleted
        if hasattr(self, 'browser'):
            self.browser.quit()

:white_check_mark: Why this works?

  • A clean, object-oriented approach to managing resources.
  • The browser instance exists as long as the test object is alive.
  • Automatic cleanup when the object is deleted.

:warning: Potential Issue:

  • __del__ is not always called immediately (Python’s garbage collection is unpredictable).
  • Less explicit than pytest’s built-in setup/teardown methods.