Search code examples
pythonseleniumsingletonpython-behave

Singleton realization in Selenium [Python]


i'm trying to use a Singleton pattern for project with Selenium and Behave, but it doesn't work correctly - object is always created second time under @then decorator. I guess i've made some mistake in new method, but can't really see where.

class WebDriver:
    singleton_instance = None
    driver = None

    def __init__(self):
       self.driver = webdriver.Chrome("C:\webdriver\chromedriver.exe")



    def __new__(cls):
        if not hasattr(cls, 'instance'):
            cls.singleton_instance = super(WebDriver, cls).__new__(cls)
        return cls.singleton_instance

@given ("website '{url}'")
def website_opener(context,url):
    driver = WebDriver()
    print(driver.singleton_instance)

@then("push button with text '{text}'")
def button_pusher(context,text):
   driver = WebDriver() #another object of WebDriver() is created
   print(driver.singleton_instance)

   WebDriverWait(driver,120).until(
     EC.element_to_be_clickable((By.XPATH,'//*[contains(text(), "%s")]' % text))
   )

context.browser.quit()

Solution

  • You don't nee to use __new__

    class WebDriver:
    
        class __WebDriver:
            def __init__(self):
                self.driver = webdriver.Chrome(r'C:\webdriver\chromedriver.exe')
    
        driver = None
    
        def __init__(self):
            if not self.driver:
                WebDriver.driver = WebDriver.__WebDriver().driver
    
    
    @given ("website '{url}'")
    def website_opener(context,url):
        driver = WebDriver().driver
        driver.get('https://google.com')