Search code examples
pythonbashseleniumbddpython-behave

How to create a bash script to execute non-headless automation in python-behave


I asked this few days back but it was assumed and erroneously linked to a previous question. This is the question.


Solution

  • The solution is actually simple.

    I found a workaround by using export headless=0; behave in the non-headless bash script and it worked.

    The caveat to this method is that I have to use os.getenv('headless') which refers to the value set in my .env file. that was headless=1.

    The final webconfig.py looks like this.

    import dotenv
    
    import os
    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    dotenv.load_dotenv()
    
    headless = bool(int(os.getenv('headless')))
    
    
    class Driver:
        def __init__(self, driver):
            self.driver = driver
    
            if driver == "chrome":
                if headless:
                    chrome_options = Options()
                    chrome_options.add_argument("--headless")
                    chrome_options.add_argument("--no-sandbox")
                    chrome_options.add_argument("--disable-gpu")
                    chrome_options.add_argument("--start-maximized")
                    chrome_options.add_argument("--window-size=1920,1200")
                    chrome_options.add_argument("--disable-dev-shm-usage")
    
                    self.driver = webdriver.Chrome(chrome_options=chrome_options)
                else:
                    self.driver = webdriver.Chrome()
            elif driver == "firefox":
                self.driver = webdriver.Firefox()
            else:
                print(f"{driver} is not defined.")