def get_driver(browser_name): ''' Spins up a new web browser and returns the driver. Tests that run with pytest spin up the browser from here. Can also be used to spin up additional browsers for the same test. ''' downloads_path = download_helper.get_downloads_folder() download_helper.reset_downloads_folder() if browser_name == constants.Browser.FIREFOX: try: profile = webdriver.FirefoxProfile() profile.set_preference("reader.parse-on-load.enabled", False) profile.set_preference("pdfjs.disabled", True) profile.set_preference( "security.mixed_content.block_active_content", False) profile.set_preference( "browser.download.manager.showAlertOnComplete", True) profile.set_preference("browser.download.panel.shown", True) profile.set_preference( "browser.download.animateNotifications", True) profile.set_preference("browser.download.dir", downloads_path) profile.set_preference("browser.download.folderList", 2) profile.set_preference( "browser.helperApps.neverAsk.saveToDisk", ("application/pdf, application/zip, application/octet-stream, " "text/csv, text/xml, application/xml, text/plain, " "text/octet-stream")) firefox_capabilities = DesiredCapabilities.FIREFOX try: # Use Geckodriver for Firefox if it's on the PATH firefox_capabilities['marionette'] = True firefox_driver = webdriver.Firefox( firefox_profile=profile, capabilities=firefox_capabilities) except WebDriverException: # Don't use Geckodriver: Only works for old versions of Firefox firefox_capabilities['marionette'] = False firefox_driver = webdriver.Firefox( firefox_profile=profile, capabilities=firefox_capabilities) return firefox_driver except: return webdriver.Firefox() if browser_name == constants.Browser.INTERNET_EXPLORER: return webdriver.Ie() if browser_name == constants.Browser.EDGE: return webdriver.Edge() if browser_name == constants.Browser.SAFARI: return webdriver.Safari() if browser_name == constants.Browser.PHANTOM_JS: return webdriver.PhantomJS() if browser_name == constants.Browser.GOOGLE_CHROME: try: chrome_options = webdriver.ChromeOptions() prefs = {"download.default_directory": downloads_path} chrome_options.add_experimental_option("prefs", prefs) chrome_options.add_argument("--allow-file-access-from-files") chrome_options.add_argument("--allow-running-insecure-content") return webdriver.Chrome(chrome_options=chrome_options) except Exception: return webdriver.Chrome()
def get_remote_driver(browser_name, headless, servername, port, proxy_string): downloads_path = download_helper.get_downloads_folder() download_helper.reset_downloads_folder() address = "http://%s:%s/wd/hub" % (servername, port) if browser_name == constants.Browser.GOOGLE_CHROME: chrome_options = _set_chrome_options(downloads_path, proxy_string) if headless: chrome_options.add_argument("--headless") capabilities = chrome_options.to_capabilities() return webdriver.Remote(command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.FIREFOX: try: # Use Geckodriver for Firefox if it's on the PATH profile = _create_firefox_profile(downloads_path, proxy_string) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = True if headless: firefox_capabilities['moz:firefoxOptions'] = ({ 'args': ['-headless'] }) capabilities = firefox_capabilities address = "http://%s:%s/wd/hub" % (servername, port) return webdriver.Remote(command_executor=address, desired_capabilities=capabilities, browser_profile=profile) except WebDriverException: # Don't use Geckodriver: Only works for old versions of Firefox profile = _create_firefox_profile(downloads_path, proxy_string) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = False if headless: firefox_capabilities['moz:firefoxOptions'] = ({ 'args': ['-headless'] }) capabilities = firefox_capabilities return webdriver.Remote(command_executor=address, desired_capabilities=capabilities, browser_profile=profile) elif browser_name == constants.Browser.INTERNET_EXPLORER: return webdriver.Remote( command_executor=address, desired_capabilities=( webdriver.DesiredCapabilities.INTERNETEXPLORER)) elif browser_name == constants.Browser.EDGE: return webdriver.Remote( command_executor=address, desired_capabilities=(webdriver.DesiredCapabilities.EDGE)) elif browser_name == constants.Browser.SAFARI: return webdriver.Remote( command_executor=address, desired_capabilities=(webdriver.DesiredCapabilities.SAFARI)) elif browser_name == constants.Browser.PHANTOM_JS: with warnings.catch_warnings(): # Ignore "PhantomJS has been deprecated" UserWarning warnings.simplefilter("ignore", category=UserWarning) return webdriver.Remote( command_executor=address, desired_capabilities=(webdriver.DesiredCapabilities.PHANTOMJS))
def get_local_driver(browser_name, headless, proxy_string): ''' Spins up a new web browser and returns the driver. Can also be used to spin up additional browsers for the same test. ''' downloads_path = download_helper.get_downloads_folder() download_helper.reset_downloads_folder() if browser_name == constants.Browser.FIREFOX: try: try: # Use Geckodriver for Firefox if it's on the PATH profile = _create_firefox_profile(downloads_path, proxy_string) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = True options = webdriver.FirefoxOptions() if headless: options.add_argument('-headless') firefox_driver = webdriver.Firefox( firefox_profile=profile, capabilities=firefox_capabilities, firefox_options=options) except WebDriverException: # Don't use Geckodriver: Only works for old versions of Firefox profile = _create_firefox_profile(downloads_path, proxy_string) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = False firefox_driver = webdriver.Firefox( firefox_profile=profile, capabilities=firefox_capabilities) return firefox_driver except Exception as e: if headless: raise Exception(e) return webdriver.Firefox() elif browser_name == constants.Browser.INTERNET_EXPLORER: return webdriver.Ie() elif browser_name == constants.Browser.EDGE: return webdriver.Edge() elif browser_name == constants.Browser.SAFARI: return webdriver.Safari() elif browser_name == constants.Browser.PHANTOM_JS: with warnings.catch_warnings(): # Ignore "PhantomJS has been deprecated" UserWarning warnings.simplefilter("ignore", category=UserWarning) return webdriver.PhantomJS() elif browser_name == constants.Browser.GOOGLE_CHROME: try: chrome_options = _set_chrome_options(downloads_path, proxy_string) if headless: chrome_options.add_argument("--headless") return webdriver.Chrome(options=chrome_options) except Exception as e: if headless: raise Exception(e) return webdriver.Chrome()
def get_driver(browser_name): ''' Spins up a new web browser and returns the driver. Tests that run with pytest spin up the browser from here. Can also be used to spin up additional browsers for the same test. ''' downloads_path = download_helper.get_downloads_folder() download_helper.reset_downloads_folder() if browser_name == constants.Browser.FIREFOX: try: try: # Use Geckodriver for Firefox if it's on the PATH profile = _create_firefox_profile(downloads_path) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = True firefox_driver = webdriver.Firefox( firefox_profile=profile, capabilities=firefox_capabilities) except WebDriverException: # Don't use Geckodriver: Only works for old versions of Firefox profile = _create_firefox_profile(downloads_path) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = False firefox_driver = webdriver.Firefox( firefox_profile=profile, capabilities=firefox_capabilities) return firefox_driver except: return webdriver.Firefox() if browser_name == constants.Browser.INTERNET_EXPLORER: return webdriver.Ie() if browser_name == constants.Browser.EDGE: return webdriver.Edge() if browser_name == constants.Browser.SAFARI: return webdriver.Safari() if browser_name == constants.Browser.PHANTOM_JS: return webdriver.PhantomJS() if browser_name == constants.Browser.GOOGLE_CHROME: try: chrome_options = webdriver.ChromeOptions() prefs = { "download.default_directory": downloads_path, "credentials_enable_service": False, "profile": { "password_manager_enabled": False } } chrome_options.add_experimental_option("prefs", prefs) chrome_options.add_argument("--allow-file-access-from-files") chrome_options.add_argument("--allow-running-insecure-content") return webdriver.Chrome(chrome_options=chrome_options) except Exception: return webdriver.Chrome()
def get_driver(browser_name): ''' Spins up a new web browser and returns the driver. Tests that run with pytest spin up the browser from here. Can also be used to spin up additional browsers for the same test. ''' downloads_path = download_helper.get_downloads_folder() download_helper.reset_downloads_folder() if browser_name == constants.Browser.FIREFOX: try: profile = webdriver.FirefoxProfile() profile.set_preference("reader.parse-on-load.enabled", False) profile.set_preference("pdfjs.disabled", True) profile.set_preference( "browser.download.manager.showAlertOnComplete", True) profile.set_preference("browser.download.panel.shown", True) profile.set_preference( "browser.download.animateNotifications", True) profile.set_preference("browser.download.dir", downloads_path) profile.set_preference("browser.download.folderList", 2) profile.set_preference( "browser.helperApps.neverAsk.saveToDisk", ("application/pdf, application/zip, application/octet-stream, " "text/csv, text/xml, application/xml, text/plain, " "text/octet-stream")) return webdriver.Firefox(profile) except: return webdriver.Firefox() if browser_name == constants.Browser.INTERNET_EXPLORER: return webdriver.Ie() if browser_name == constants.Browser.EDGE: return webdriver.Edge() if browser_name == constants.Browser.SAFARI: return webdriver.Safari() if browser_name == constants.Browser.PHANTOM_JS: return webdriver.PhantomJS() if browser_name == constants.Browser.GOOGLE_CHROME: try: chrome_options = webdriver.ChromeOptions() prefs = {"download.default_directory": downloads_path} chrome_options.add_experimental_option("prefs", prefs) chrome_options.add_argument("--allow-file-access-from-files") return webdriver.Chrome(chrome_options=chrome_options) except Exception: return webdriver.Chrome()
def get_driver(browser_name): ''' Spins up a new web browser and returns the driver. Tests that run with pytest spin up the browser from here. Can also be used to spin up additional browsers for the same test. ''' downloads_path = download_helper.get_downloads_folder() download_helper.reset_downloads_folder() if browser_name == constants.Browser.FIREFOX: try: try: # Use Geckodriver for Firefox if it's on the PATH profile = _create_firefox_profile(downloads_path) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = True firefox_driver = webdriver.Firefox( firefox_profile=profile, capabilities=firefox_capabilities) except WebDriverException: # Don't use Geckodriver: Only works for old versions of Firefox profile = _create_firefox_profile(downloads_path) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = False firefox_driver = webdriver.Firefox( firefox_profile=profile, capabilities=firefox_capabilities) return firefox_driver except: return webdriver.Firefox() if browser_name == constants.Browser.INTERNET_EXPLORER: return webdriver.Ie() if browser_name == constants.Browser.EDGE: return webdriver.Edge() if browser_name == constants.Browser.SAFARI: return webdriver.Safari() if browser_name == constants.Browser.PHANTOM_JS: return webdriver.PhantomJS() if browser_name == constants.Browser.GOOGLE_CHROME: try: chrome_options = webdriver.ChromeOptions() prefs = {"download.default_directory": downloads_path} chrome_options.add_experimental_option("prefs", prefs) chrome_options.add_argument("--allow-file-access-from-files") chrome_options.add_argument("--allow-running-insecure-content") return webdriver.Chrome(chrome_options=chrome_options) except Exception: return webdriver.Chrome()
def configure(self, options, conf): super(Base, self).configure(options, conf) self.enabled = True # Used if test class inherits BaseCase self.options = options self.report_on = options.report self.show_report = options.show_report self.successes = [] self.failures = [] self.start_time = float(0) self.duration = float(0) self.page_results_list = [] self.test_count = 0 self.import_error = False log_path = 'latest_logs/' archive_logs = options.archive_logs log_helper.log_folder_setup(log_path, archive_logs) download_helper.reset_downloads_folder() if self.report_on: report_helper.clear_out_old_report_logs(archive_past_runs=False)
def get_local_driver( browser_name, headless, locale_code, servername, proxy_string, proxy_auth, proxy_user, proxy_pass, user_agent, disable_csp, enable_ws, enable_sync, use_auto_ext, no_sandbox, disable_gpu, incognito, guest_mode, devtools, swiftshader, block_images, user_data_dir, extension_zip, extension_dir, mobile_emulator, device_width, device_height, device_pixel_ratio): ''' Spins up a new web browser and returns the driver. Can also be used to spin up additional browsers for the same test. ''' downloads_path = download_helper.get_downloads_folder() download_helper.reset_downloads_folder() if browser_name == constants.Browser.FIREFOX: try: try: # Use Geckodriver for Firefox if it's on the PATH profile = _create_firefox_profile( downloads_path, locale_code, proxy_string, user_agent, disable_csp) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = True options = webdriver.FirefoxOptions() if headless: options.add_argument('-headless') firefox_capabilities['moz:firefoxOptions'] = ( {'args': ['-headless']}) if LOCAL_GECKODRIVER and os.path.exists(LOCAL_GECKODRIVER): try: make_driver_executable_if_not(LOCAL_GECKODRIVER) except Exception as e: logging.debug("\nWarning: Could not make geckodriver" " executable: %s" % e) elif not is_geckodriver_on_path(): args = " ".join(sys.argv) if not ("-n" in sys.argv or "-n=" in args or args == "-c"): # (Not multithreaded) from seleniumbase.console_scripts import sb_install sys_args = sys.argv # Save a copy of current sys args print("\nWarning: geckodriver not found!" " Installing now:") try: sb_install.main(override="geckodriver") except Exception as e: print("\nWarning: Could not install geckodriver: " "%s" % e) sys.argv = sys_args # Put back the original sys args if "linux" in PLATFORM or not headless: firefox_driver = webdriver.Firefox( firefox_profile=profile, capabilities=firefox_capabilities) else: firefox_driver = webdriver.Firefox( firefox_profile=profile, capabilities=firefox_capabilities, options=options) except Exception: profile = _create_firefox_profile( downloads_path, locale_code, proxy_string, user_agent, disable_csp) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_driver = webdriver.Firefox( firefox_profile=profile, capabilities=firefox_capabilities) return firefox_driver except Exception as e: if headless: raise Exception(e) return webdriver.Firefox() elif browser_name == constants.Browser.INTERNET_EXPLORER: if not IS_WINDOWS: raise Exception( "IE Browser is for Windows-based operating systems only!") from selenium.webdriver.ie.options import Options ie_options = Options() ie_options.ignore_protected_mode_settings = False ie_options.ignore_zoom_level = True ie_options.require_window_focus = False ie_options.native_events = True ie_options.full_page_screenshot = True ie_options.persistent_hover = True ie_capabilities = ie_options.to_capabilities() if LOCAL_IEDRIVER and os.path.exists(LOCAL_IEDRIVER): try: make_driver_executable_if_not(LOCAL_IEDRIVER) except Exception as e: logging.debug("\nWarning: Could not make iedriver" " executable: %s" % e) return webdriver.Ie(capabilities=ie_capabilities) elif browser_name == constants.Browser.EDGE: try: chrome_options = _set_chrome_options( browser_name, downloads_path, headless, locale_code, proxy_string, proxy_auth, proxy_user, proxy_pass, user_agent, disable_csp, enable_ws, enable_sync, use_auto_ext, no_sandbox, disable_gpu, incognito, guest_mode, devtools, swiftshader, block_images, user_data_dir, extension_zip, extension_dir, servername, mobile_emulator, device_width, device_height, device_pixel_ratio) if LOCAL_EDGEDRIVER and os.path.exists(LOCAL_EDGEDRIVER): try: make_driver_executable_if_not(LOCAL_EDGEDRIVER) except Exception as e: logging.debug("\nWarning: Could not make edgedriver" " executable: %s" % e) elif not is_edgedriver_on_path(): args = " ".join(sys.argv) if not ("-n" in sys.argv or "-n=" in args or args == "-c"): # (Not multithreaded) from seleniumbase.console_scripts import sb_install sys_args = sys.argv # Save a copy of current sys args print("\nWarning: msedgedriver not found. Installing now:") sb_install.main(override="edgedriver") sys.argv = sys_args # Put back the original sys args # For Microsoft Edge (Chromium) version 79 or lower return webdriver.Chrome(executable_path=LOCAL_EDGEDRIVER, options=chrome_options) except Exception: # For Microsoft Edge (Chromium) version 80 or higher from msedge.selenium_tools import Edge, EdgeOptions if LOCAL_EDGEDRIVER and os.path.exists(LOCAL_EDGEDRIVER): try: make_driver_executable_if_not(LOCAL_EDGEDRIVER) except Exception as e: logging.debug("\nWarning: Could not make edgedriver" " executable: %s" % e) edge_options = EdgeOptions() edge_options.use_chromium = True prefs = { "download.default_directory": downloads_path, "local_discovery.notifications_enabled": False, "credentials_enable_service": False, "download.prompt_for_download": False, "download.directory_upgrade": True, "safebrowsing.enabled": False, "safebrowsing.disable_download_protection": True, "profile": { "password_manager_enabled": False, "default_content_setting_values.automatic_downloads": 1, "managed_default_content_settings.automatic_downloads": 1, "default_content_settings.popups": 0, "managed_default_content_settings.popups": 0 } } if locale_code: prefs["intl.accept_languages"] = locale_code if block_images: prefs["profile.managed_default_content_settings.images"] = 2 edge_options.add_experimental_option("prefs", prefs) edge_options.add_experimental_option("w3c", True) edge_options.add_experimental_option( "useAutomationExtension", False) edge_options.add_experimental_option( "excludeSwitches", ["enable-automation", "enable-logging"]) if guest_mode: edge_options.add_argument("--guest") if headless: edge_options.add_argument("--headless") if mobile_emulator: emulator_settings = {} device_metrics = {} if type(device_width) is int and ( type(device_height) is int and ( type(device_pixel_ratio) is int)): device_metrics["width"] = device_width device_metrics["height"] = device_height device_metrics["pixelRatio"] = device_pixel_ratio else: device_metrics["width"] = 411 device_metrics["height"] = 731 device_metrics["pixelRatio"] = 3 emulator_settings["deviceMetrics"] = device_metrics if user_agent: emulator_settings["userAgent"] = user_agent edge_options.add_experimental_option( "mobileEmulation", emulator_settings) edge_options.add_argument("--enable-sync") edge_options.add_argument("--disable-infobars") edge_options.add_argument("--disable-save-password-bubble") edge_options.add_argument("--disable-single-click-autofill") edge_options.add_argument( "--disable-autofill-keyboard-accessory-view[8]") edge_options.add_argument("--disable-translate") if not enable_ws: edge_options.add_argument("--disable-web-security") edge_options.add_argument("--homepage=about:blank") edge_options.add_argument("--dns-prefetch-disable") edge_options.add_argument("--dom-automation") edge_options.add_argument("--disable-hang-monitor") edge_options.add_argument("--disable-prompt-on-repost") if proxy_string: edge_options.add_argument('--proxy-server=%s' % proxy_string) edge_options.add_argument("--test-type") edge_options.add_argument("--log-level=3") edge_options.add_argument("--no-first-run") edge_options.add_argument("--ignore-certificate-errors") if devtools and not headless: edge_options.add_argument("--auto-open-devtools-for-tabs") edge_options.add_argument("--allow-file-access-from-files") edge_options.add_argument("--allow-insecure-localhost") edge_options.add_argument("--allow-running-insecure-content") if user_agent: edge_options.add_argument("--user-agent=%s" % user_agent) edge_options.add_argument("--no-sandbox") if swiftshader: edge_options.add_argument("--use-gl=swiftshader") else: edge_options.add_argument("--disable-gpu") if "linux" in PLATFORM: edge_options.add_argument("--disable-dev-shm-usage") capabilities = edge_options.to_capabilities() capabilities["platform"] = '' return Edge( executable_path=LOCAL_EDGEDRIVER, capabilities=capabilities) elif browser_name == constants.Browser.SAFARI: arg_join = " ".join(sys.argv) if ("-n" in sys.argv) or ("-n=" in arg_join) or (arg_join == "-c"): # Skip if multithreaded raise Exception("Can't run Safari tests in multi-threaded mode!") safari_capabilities = _set_safari_capabilities() return webdriver.Safari(desired_capabilities=safari_capabilities) elif browser_name == constants.Browser.OPERA: try: if LOCAL_OPERADRIVER and os.path.exists(LOCAL_OPERADRIVER): try: make_driver_executable_if_not(LOCAL_OPERADRIVER) except Exception as e: logging.debug("\nWarning: Could not make operadriver" " executable: %s" % e) opera_options = _set_chrome_options( browser_name, downloads_path, headless, locale_code, proxy_string, proxy_auth, proxy_user, proxy_pass, user_agent, disable_csp, enable_ws, enable_sync, use_auto_ext, no_sandbox, disable_gpu, incognito, guest_mode, devtools, swiftshader, block_images, user_data_dir, extension_zip, extension_dir, servername, mobile_emulator, device_width, device_height, device_pixel_ratio) opera_options.headless = False # No support for headless Opera return webdriver.Opera(options=opera_options) except Exception: return webdriver.Opera() elif browser_name == constants.Browser.PHANTOM_JS: with warnings.catch_warnings(): # Ignore "PhantomJS has been deprecated" UserWarning warnings.simplefilter("ignore", category=UserWarning) return webdriver.PhantomJS() elif browser_name == constants.Browser.GOOGLE_CHROME: try: chrome_options = _set_chrome_options( browser_name, downloads_path, headless, locale_code, proxy_string, proxy_auth, proxy_user, proxy_pass, user_agent, disable_csp, enable_ws, enable_sync, use_auto_ext, no_sandbox, disable_gpu, incognito, guest_mode, devtools, swiftshader, block_images, user_data_dir, extension_zip, extension_dir, servername, mobile_emulator, device_width, device_height, device_pixel_ratio) if LOCAL_CHROMEDRIVER and os.path.exists(LOCAL_CHROMEDRIVER): try: make_driver_executable_if_not(LOCAL_CHROMEDRIVER) except Exception as e: logging.debug("\nWarning: Could not make chromedriver" " executable: %s" % e) elif not is_chromedriver_on_path(): args = " ".join(sys.argv) if not ("-n" in sys.argv or "-n=" in args or args == "-c"): # (Not multithreaded) from seleniumbase.console_scripts import sb_install sys_args = sys.argv # Save a copy of current sys args print("\nWarning: chromedriver not found. Installing now:") sb_install.main(override="chromedriver") sys.argv = sys_args # Put back the original sys args if not headless or "linux" not in PLATFORM: return webdriver.Chrome(options=chrome_options) else: # Running headless on Linux try: return webdriver.Chrome(options=chrome_options) except Exception: # Use the virtual display on Linux during headless errors logging.debug("\nWarning: Chrome failed to launch in" " headless mode. Attempting to use the" " SeleniumBase virtual display on Linux...") chrome_options.headless = False return webdriver.Chrome(options=chrome_options) except Exception as e: if headless: raise Exception(e) if LOCAL_CHROMEDRIVER and os.path.exists(LOCAL_CHROMEDRIVER): try: make_driver_executable_if_not(LOCAL_CHROMEDRIVER) except Exception as e: logging.debug("\nWarning: Could not make chromedriver" " executable: %s" % e) return webdriver.Chrome() else: raise Exception( "%s is not a valid browser option for this system!" % browser_name)
def get_remote_driver( browser_name, headless, locale_code, servername, port, proxy_string, proxy_auth, proxy_user, proxy_pass, user_agent, cap_file, cap_string, disable_csp, enable_ws, enable_sync, use_auto_ext, no_sandbox, disable_gpu, incognito, guest_mode, devtools, swiftshader, block_images, user_data_dir, extension_zip, extension_dir, test_id, mobile_emulator, device_width, device_height, device_pixel_ratio): downloads_path = download_helper.get_downloads_folder() download_helper.reset_downloads_folder() address = "http://%s:%s/wd/hub" % (servername, port) desired_caps = {} extra_caps = {} if cap_file: from seleniumbase.core import capabilities_parser desired_caps = capabilities_parser.get_desired_capabilities(cap_file) if cap_string: try: extra_caps = json.loads(cap_string) except Exception as e: p1 = "Invalid input format for --cap-string:\n %s" % e p2 = "The --cap-string input was: %s" % cap_string p3 = "Enclose cap-string in SINGLE quotes; keys in DOUBLE quotes." p4 = ("""Here's an example of correct cap-string usage:\n """ """--cap-string='{"browserName":"chrome","name":"test1"}'""") raise Exception("%s\n%s\n%s\n%s" % (p1, p2, p3, p4)) for cap_key in extra_caps.keys(): desired_caps[cap_key] = extra_caps[cap_key] if cap_file or cap_string: if "name" in desired_caps.keys(): if desired_caps["name"] == "*": desired_caps["name"] = test_id if browser_name == constants.Browser.GOOGLE_CHROME: chrome_options = _set_chrome_options( browser_name, downloads_path, headless, locale_code, proxy_string, proxy_auth, proxy_user, proxy_pass, user_agent, disable_csp, enable_ws, enable_sync, use_auto_ext, no_sandbox, disable_gpu, incognito, guest_mode, devtools, swiftshader, block_images, user_data_dir, extension_zip, extension_dir, servername, mobile_emulator, device_width, device_height, device_pixel_ratio) capabilities = chrome_options.to_capabilities() for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote( command_executor=address, desired_capabilities=capabilities, keep_alive=True) elif browser_name == constants.Browser.FIREFOX: try: # Use Geckodriver for Firefox if it's on the PATH profile = _create_firefox_profile( downloads_path, locale_code, proxy_string, user_agent, disable_csp) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = True if headless: firefox_capabilities['moz:firefoxOptions'] = ( {'args': ['-headless']}) for key in desired_caps.keys(): firefox_capabilities[key] = desired_caps[key] capabilities = firefox_capabilities warnings.simplefilter("ignore", category=DeprecationWarning) return webdriver.Remote( command_executor=address, desired_capabilities=capabilities, browser_profile=profile, keep_alive=True) except WebDriverException: # Don't use Geckodriver: Only works for old versions of Firefox profile = _create_firefox_profile( downloads_path, locale_code, proxy_string, user_agent, disable_csp) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = False if headless: firefox_capabilities['moz:firefoxOptions'] = ( {'args': ['-headless']}) for key in desired_caps.keys(): firefox_capabilities[key] = desired_caps[key] capabilities = firefox_capabilities return webdriver.Remote( command_executor=address, desired_capabilities=capabilities, browser_profile=profile, keep_alive=True) elif browser_name == constants.Browser.INTERNET_EXPLORER: capabilities = webdriver.DesiredCapabilities.INTERNETEXPLORER for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote( command_executor=address, desired_capabilities=capabilities, keep_alive=True) elif browser_name == constants.Browser.EDGE: capabilities = webdriver.DesiredCapabilities.EDGE for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote( command_executor=address, desired_capabilities=capabilities, keep_alive=True) elif browser_name == constants.Browser.SAFARI: capabilities = webdriver.DesiredCapabilities.SAFARI for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote( command_executor=address, desired_capabilities=capabilities, keep_alive=True) elif browser_name == constants.Browser.OPERA: capabilities = webdriver.DesiredCapabilities.OPERA for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote( command_executor=address, desired_capabilities=capabilities, keep_alive=True) elif browser_name == constants.Browser.PHANTOM_JS: capabilities = webdriver.DesiredCapabilities.PHANTOMJS for key in desired_caps.keys(): capabilities[key] = desired_caps[key] with warnings.catch_warnings(): # Ignore "PhantomJS has been deprecated" UserWarning warnings.simplefilter("ignore", category=UserWarning) return webdriver.Remote( command_executor=address, desired_capabilities=capabilities, keep_alive=True) elif browser_name == constants.Browser.ANDROID: capabilities = webdriver.DesiredCapabilities.ANDROID for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote( command_executor=address, desired_capabilities=capabilities, keep_alive=True) elif browser_name == constants.Browser.IPHONE: capabilities = webdriver.DesiredCapabilities.IPHONE for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote( command_executor=address, desired_capabilities=capabilities, keep_alive=True) elif browser_name == constants.Browser.IPAD: capabilities = webdriver.DesiredCapabilities.IPAD for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote( command_executor=address, desired_capabilities=capabilities, keep_alive=True) elif browser_name == constants.Browser.REMOTE: return webdriver.Remote( command_executor=address, desired_capabilities=desired_caps, keep_alive=True)
def get_local_driver(browser_name, headless, proxy_string, proxy_auth, proxy_user, proxy_pass, user_agent, disable_csp, enable_sync, user_data_dir, extension_zip, extension_dir, mobile_emulator, device_width, device_height, device_pixel_ratio): ''' Spins up a new web browser and returns the driver. Can also be used to spin up additional browsers for the same test. ''' downloads_path = download_helper.get_downloads_folder() download_helper.reset_downloads_folder() if browser_name == constants.Browser.FIREFOX: try: try: # Use Geckodriver for Firefox if it's on the PATH profile = _create_firefox_profile(downloads_path, proxy_string, user_agent, disable_csp) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = True options = webdriver.FirefoxOptions() if headless: options.add_argument('-headless') if LOCAL_GECKODRIVER and os.path.exists(LOCAL_GECKODRIVER): make_driver_executable_if_not(LOCAL_GECKODRIVER) elif not is_geckodriver_on_path(): if not "".join(sys.argv) == "-c": # Skip if multithreaded from seleniumbase.console_scripts import sb_install sys_args = sys.argv # Save a copy of current sys args print("\nWarning: geckodriver not found." " Installing now:") sb_install.main(override="geckodriver") sys.argv = sys_args # Put back the original sys args firefox_driver = webdriver.Firefox( firefox_profile=profile, capabilities=firefox_capabilities, options=options) except WebDriverException: # Don't use Geckodriver: Only works for old versions of Firefox profile = _create_firefox_profile(downloads_path, proxy_string, user_agent, disable_csp) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = False firefox_driver = webdriver.Firefox( firefox_profile=profile, capabilities=firefox_capabilities) return firefox_driver except Exception as e: if headless: raise Exception(e) return webdriver.Firefox() elif browser_name == constants.Browser.INTERNET_EXPLORER: if not IS_WINDOWS: raise Exception( "IE Browser is for Windows-based operating systems only!") from selenium.webdriver.ie.options import Options ie_options = Options() ie_options.ignore_protected_mode_settings = False ie_options.ignore_zoom_level = True ie_options.require_window_focus = False ie_options.native_events = True ie_options.full_page_screenshot = True ie_options.persistent_hover = True ie_capabilities = ie_options.to_capabilities() if LOCAL_IEDRIVER and os.path.exists(LOCAL_IEDRIVER): make_driver_executable_if_not(LOCAL_IEDRIVER) return webdriver.Ie(capabilities=ie_capabilities) elif browser_name == constants.Browser.EDGE: if LOCAL_EDGEDRIVER and os.path.exists(LOCAL_EDGEDRIVER): make_driver_executable_if_not(LOCAL_EDGEDRIVER) # The new Microsoft Edge browser is based on Chromium chrome_options = _set_chrome_options( downloads_path, headless, proxy_string, proxy_auth, proxy_user, proxy_pass, user_agent, disable_csp, enable_sync, user_data_dir, extension_zip, extension_dir, mobile_emulator, device_width, device_height, device_pixel_ratio) return webdriver.Chrome(executable_path=LOCAL_EDGEDRIVER, options=chrome_options) else: return webdriver.Edge() elif browser_name == constants.Browser.SAFARI: if "".join(sys.argv) == "-c": # Skip if multithreaded raise Exception("Can't run Safari tests in multi-threaded mode!") return webdriver.Safari() elif browser_name == constants.Browser.OPERA: if LOCAL_OPERADRIVER and os.path.exists(LOCAL_OPERADRIVER): make_driver_executable_if_not(LOCAL_OPERADRIVER) return webdriver.Opera() elif browser_name == constants.Browser.PHANTOM_JS: with warnings.catch_warnings(): # Ignore "PhantomJS has been deprecated" UserWarning warnings.simplefilter("ignore", category=UserWarning) return webdriver.PhantomJS() elif browser_name == constants.Browser.GOOGLE_CHROME: try: chrome_options = _set_chrome_options( downloads_path, headless, proxy_string, proxy_auth, proxy_user, proxy_pass, user_agent, disable_csp, enable_sync, user_data_dir, extension_zip, extension_dir, mobile_emulator, device_width, device_height, device_pixel_ratio) if LOCAL_CHROMEDRIVER and os.path.exists(LOCAL_CHROMEDRIVER): make_driver_executable_if_not(LOCAL_CHROMEDRIVER) elif not is_chromedriver_on_path(): if not "".join(sys.argv) == "-c": # Skip if multithreaded from seleniumbase.console_scripts import sb_install sys_args = sys.argv # Save a copy of current sys args print("\nWarning: chromedriver not found. Installing now:") sb_install.main(override="chromedriver") sys.argv = sys_args # Put back the original sys args return webdriver.Chrome(options=chrome_options) except Exception as e: if headless: raise Exception(e) if LOCAL_CHROMEDRIVER and os.path.exists(LOCAL_CHROMEDRIVER): make_driver_executable_if_not(LOCAL_CHROMEDRIVER) return webdriver.Chrome() else: raise Exception("%s is not a valid browser option for this system!" % browser_name)
def get_remote_driver(browser_name, headless, servername, port, proxy_string, proxy_auth, proxy_user, proxy_pass, cap_file): downloads_path = download_helper.get_downloads_folder() download_helper.reset_downloads_folder() address = "http://%s:%s/wd/hub" % (servername, port) desired_caps = {} if cap_file: desired_caps = capabilities_parser.get_desired_capabilities(cap_file) if browser_name == constants.Browser.GOOGLE_CHROME: chrome_options = _set_chrome_options(downloads_path, proxy_string, proxy_auth, proxy_user, proxy_pass) if headless: if not proxy_auth: # Headless Chrome doesn't support extensions, which are # required when using a proxy server that has authentication. # Instead, base_case.py will use PyVirtualDisplay when not # using Chrome's built-in headless mode. See link for details: # https://bugs.chromium.org/p/chromium/issues/detail?id=706008 chrome_options.add_argument("--headless") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--no-sandbox") capabilities = chrome_options.to_capabilities() for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote(command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.FIREFOX: try: # Use Geckodriver for Firefox if it's on the PATH profile = _create_firefox_profile(downloads_path, proxy_string) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = True if headless: firefox_capabilities['moz:firefoxOptions'] = ({ 'args': ['-headless'] }) for key in desired_caps.keys(): firefox_capabilities[key] = desired_caps[key] capabilities = firefox_capabilities address = "http://%s:%s/wd/hub" % (servername, port) return webdriver.Remote(command_executor=address, desired_capabilities=capabilities, browser_profile=profile) except WebDriverException: # Don't use Geckodriver: Only works for old versions of Firefox profile = _create_firefox_profile(downloads_path, proxy_string) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = False if headless: firefox_capabilities['moz:firefoxOptions'] = ({ 'args': ['-headless'] }) for key in desired_caps.keys(): firefox_capabilities[key] = desired_caps[key] capabilities = firefox_capabilities return webdriver.Remote(command_executor=address, desired_capabilities=capabilities, browser_profile=profile) elif browser_name == constants.Browser.INTERNET_EXPLORER: capabilities = webdriver.DesiredCapabilities.INTERNETEXPLORER for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote(command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.EDGE: capabilities = webdriver.DesiredCapabilities.EDGE for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote(command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.SAFARI: capabilities = webdriver.DesiredCapabilities.SAFARI for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote(command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.OPERA: capabilities = webdriver.DesiredCapabilities.OPERA for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote(command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.PHANTOM_JS: capabilities = webdriver.DesiredCapabilities.PHANTOMJS for key in desired_caps.keys(): capabilities[key] = desired_caps[key] with warnings.catch_warnings(): # Ignore "PhantomJS has been deprecated" UserWarning warnings.simplefilter("ignore", category=UserWarning) return webdriver.Remote(command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.ANDROID: capabilities = webdriver.DesiredCapabilities.ANDROID for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote(command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.IPHONE: capabilities = webdriver.DesiredCapabilities.IPHONE for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote(command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.IPAD: capabilities = webdriver.DesiredCapabilities.IPAD for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote(command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.REMOTE: return webdriver.Remote(command_executor=address, desired_capabilities=desired_caps)
def get_remote_driver(browser_name, headless, servername, port, proxy_string): downloads_path = download_helper.get_downloads_folder() download_helper.reset_downloads_folder() address = "http://%s:%s/wd/hub" % (servername, port) if browser_name == constants.Browser.GOOGLE_CHROME: chrome_options = webdriver.ChromeOptions() prefs = { "download.default_directory": downloads_path, "credentials_enable_service": False, "profile": { "password_manager_enabled": False } } chrome_options.add_experimental_option("prefs", prefs) chrome_options.add_argument("--allow-file-access-from-files") chrome_options.add_argument("--allow-running-insecure-content") chrome_options.add_argument("--disable-infobars") if headless: chrome_options.add_argument("--headless") if proxy_string: chrome_options.add_argument('--proxy-server=%s' % proxy_string) if settings.START_CHROME_IN_FULL_SCREEN_MODE: # Run Chrome in full screen mode on WINDOWS chrome_options.add_argument("--start-maximized") # Run Chrome in full screen mode on MAC/Linux chrome_options.add_argument("--kiosk") capabilities = chrome_options.to_capabilities() return webdriver.Remote( command_executor=address, desired_capabilities=capabilities) if browser_name == constants.Browser.FIREFOX: try: # Use Geckodriver for Firefox if it's on the PATH profile = _create_firefox_profile(downloads_path, proxy_string) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = True if headless: firefox_capabilities['moz:firefoxOptions'] = ( {'args': ['-headless']}) capabilities = firefox_capabilities address = "http://%s:%s/wd/hub" % (servername, port) return webdriver.Remote( command_executor=address, desired_capabilities=capabilities, browser_profile=profile) except WebDriverException: # Don't use Geckodriver: Only works for old versions of Firefox profile = _create_firefox_profile(downloads_path, proxy_string) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = False if headless: firefox_capabilities['moz:firefoxOptions'] = ( {'args': ['-headless']}) capabilities = firefox_capabilities return webdriver.Remote( command_executor=address, desired_capabilities=capabilities, browser_profile=profile) if browser_name == constants.Browser.INTERNET_EXPLORER: return webdriver.Remote( command_executor=address, desired_capabilities=( webdriver.DesiredCapabilities.INTERNETEXPLORER)) if browser_name == constants.Browser.EDGE: return webdriver.Remote( command_executor=address, desired_capabilities=( webdriver.DesiredCapabilities.EDGE)) if browser_name == constants.Browser.SAFARI: return webdriver.Remote( command_executor=address, desired_capabilities=( webdriver.DesiredCapabilities.SAFARI)) if browser_name == constants.Browser.PHANTOM_JS: with warnings.catch_warnings(): # Ignore "PhantomJS has been deprecated" UserWarning warnings.simplefilter("ignore", category=UserWarning) return webdriver.Remote( command_executor=address, desired_capabilities=( webdriver.DesiredCapabilities.PHANTOMJS))
def get_local_driver(browser_name, headless, proxy_string): ''' Spins up a new web browser and returns the driver. Can also be used to spin up additional browsers for the same test. ''' downloads_path = download_helper.get_downloads_folder() download_helper.reset_downloads_folder() if browser_name == constants.Browser.FIREFOX: try: try: # Use Geckodriver for Firefox if it's on the PATH profile = _create_firefox_profile(downloads_path, proxy_string) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = True options = webdriver.FirefoxOptions() if headless: options.add_argument('-headless') firefox_driver = webdriver.Firefox( firefox_profile=profile, capabilities=firefox_capabilities, firefox_options=options) except WebDriverException: # Don't use Geckodriver: Only works for old versions of Firefox profile = _create_firefox_profile(downloads_path, proxy_string) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = False firefox_driver = webdriver.Firefox( firefox_profile=profile, capabilities=firefox_capabilities) return firefox_driver except Exception as e: if headless: raise Exception(e) return webdriver.Firefox() if browser_name == constants.Browser.INTERNET_EXPLORER: return webdriver.Ie() if browser_name == constants.Browser.EDGE: return webdriver.Edge() if browser_name == constants.Browser.SAFARI: return webdriver.Safari() if browser_name == constants.Browser.PHANTOM_JS: with warnings.catch_warnings(): # Ignore "PhantomJS has been deprecated" UserWarning warnings.simplefilter("ignore", category=UserWarning) return webdriver.PhantomJS() if browser_name == constants.Browser.GOOGLE_CHROME: try: chrome_options = webdriver.ChromeOptions() prefs = { "download.default_directory": downloads_path, "credentials_enable_service": False, "profile": { "password_manager_enabled": False } } chrome_options.add_experimental_option("prefs", prefs) chrome_options.add_argument("--allow-file-access-from-files") chrome_options.add_argument("--allow-running-insecure-content") chrome_options.add_argument("--disable-infobars") if headless: chrome_options.add_argument("--headless") if proxy_string: chrome_options.add_argument('--proxy-server=%s' % proxy_string) if settings.START_CHROME_IN_FULL_SCREEN_MODE: # Run Chrome in full screen mode on WINDOWS chrome_options.add_argument("--start-maximized") # Run Chrome in full screen mode on MAC/Linux chrome_options.add_argument("--kiosk") return webdriver.Chrome(options=chrome_options) except Exception as e: if headless: raise Exception(e) return webdriver.Chrome()
def get_configured_sb(context): if not sb_config.__base_class: from seleniumbase import BaseCase sb_config.__base_class = BaseCase sb_config.__base_class.test_method = {} sb = sb_config.__base_class("test_method") # Set default values sb.browser = "chrome" sb.is_behave = True sb.headless = False sb.headed = False sb.xvfb = False sb.start_page = None sb.locale_code = None sb.pdb_option = False sb.protocol = "http" sb.servername = "localhost" sb.port = 4444 sb.data = None sb.var1 = None sb.var2 = None sb.var3 = None sb.variables = {} sb.account = None sb.environment = "test" sb.user_agent = None sb.incognito = False sb.guest_mode = False sb.devtools = False sb.mobile_emulator = False sb.device_metrics = None sb.extension_zip = None sb.extension_dir = None sb.database_env = "test" sb.log_path = "latest_logs/" sb.archive_logs = False sb.disable_csp = False sb.disable_ws = False sb.enable_ws = False sb.enable_sync = False sb.use_auto_ext = False sb.no_sandbox = False sb.disable_gpu = False sb._multithreaded = False sb._reuse_session = False sb._crumbs = False sb.visual_baseline = False sb.window_size = None sb.maximize_option = False sb.save_screenshot_after_test = False sb.timeout_multiplier = None sb.pytest_html_report = None sb.with_db_reporting = False sb.with_s3_logging = False sb.js_checking_on = False sb.recorder_mode = False sb.recorder_ext = False sb.record_sleep = False sb.rec_behave = False sb.report_on = False sb.is_pytest = False sb.slow_mode = False sb.demo_mode = False sb.time_limit = None sb.demo_sleep = None sb.dashboard = False sb.dash_title = None sb._dash_initialized = False sb.message_duration = None sb.block_images = False sb.external_pdf = False sb.remote_debug = False sb.settings_file = None sb.user_data_dir = None sb.chromium_arg = None sb.firefox_arg = None sb.firefox_pref = None sb.proxy_string = None sb.proxy_bypass_list = None sb.swiftshader = False sb.ad_block_on = False sb.highlights = None sb.interval = None sb.cap_file = None sb.cap_string = None # Set a few sb_config vars early in case parsing args fails sb_config.dashboard = None sb_config._has_exception = None sb_config.save_screenshot = None browsers = set() # To error if selecting more than one valid_browsers = constants.ValidBrowsers.valid_browsers valid_envs = constants.ValidEnvs.valid_envs # Process command-line options userdata = context.config.userdata for key in userdata.keys(): # Convert --ARG to ARG, etc. if key.startswith("--"): key = key[2:] if key.startswith("-"): key = key[1:] low_key = key.lower() # Handle: -D browser=BROWSER if low_key == "browser": browser = userdata[key].lower() if browser in valid_browsers: sb.browser = browser browsers.add(browser) elif browser == "true": raise Exception( '\nThe "browser" argument requires a value!' "\nChoose from %s." '\nEg. -D browser="edge"' % valid_browsers ) else: raise Exception( '\n"%s" is not a valid "browser" selection!' "\nChoose from %s." '\nEg. -D browser="edge"' % (browser, valid_browsers) ) continue # Handle: -D BROWSER if low_key in valid_browsers: browser = low_key sb.browser = browser browsers.add(browser) continue # Handle: -D headless if low_key == "headless": sb.headless = True continue # Handle: -D headed / gui if low_key in ["headed", "gui"]: sb.headed = True continue # Handle: -D xvfb if low_key == "xvfb": sb.xvfb = True continue # Handle: -D start-page=URL / start_page=URL / url=URL if low_key in ["start-page", "start_page", "url"]: start_page = userdata[key] if start_page == "true": start_page = sb.start_page # revert to default sb.start_page = start_page continue # Handle: -D locale-code=CODE / locale_code=CODE / locale=CODE if low_key in ["locale-code", "locale_code", "locale"]: sb.start_page = userdata[key] continue # Handle: -D pdb / ipdb if low_key in ["pdb", "ipdb"]: sb.pdb_option = True continue # Handle: -D protocol=PROTOCOL if low_key == "protocol": protocol = userdata[key].lower() if protocol in ["http", "https"]: sb.protocol = protocol elif protocol == "true": raise Exception( '\nThe Selenium Grid "protocol" argument requires a value!' '\nChoose from ["http", "https"]' '\nEg. -D protocol="https"' ) else: raise Exception( '\n"%s" is not a valid Selenium Grid "protocol" selection!' '\nChoose from ["http", "https"]' '\nEg. -D protocol="https"' % protocol ) continue # Handle: -D servername=SERVERNAME if low_key == "servername": servername = userdata[key] if servername == "true": servername = sb.servername # revert to default sb.servername = servername continue # Handle: -D port=PORT if low_key == "port": port = int(userdata[key]) if port == "true": port = sb.port # revert to default sb.port = port continue # Handle: -D data=DATA if low_key == "data": sb.data = userdata[key] continue # Handle: -D var1=DATA if low_key == "var1": sb.var1 = userdata[key] continue # Handle: -D var2=DATA if low_key == "var2": sb.var2 = userdata[key] continue # Handle: -D var3=DATA if low_key == "var3": sb.var3 = userdata[key] continue # Handle: -D variables="{'KEY':'VALUE','KEY2':'VALUE2'}" if low_key == "variables": variables = userdata[key] if variables and type(variables) is str and len(variables) > 0: bad_input = False if ( not variables.startswith("{") or not variables.endswith("}") ): bad_input = True else: try: variables = ast.literal_eval(variables) if not type(variables) is dict: bad_input = True except Exception: bad_input = True if bad_input: raise Exception( '\nExpecting a Python dictionary for "variables"!' "\nEg. -D variables=\"{'KEY':'VALUE', 'KEY2':123}\"" ) else: variables = {} continue # Handle: -D account=ACCOUNT if low_key == "account": sb.account = userdata[key] continue # Handle: -D env=ENVIRONMENT if low_key == "environment": environment = userdata[key].lower() if environment in valid_envs: sb.environment = environment elif environment == "true": raise Exception( '\nThe "env" argument requires a value!' "\nChoose from %s." '\nEg. -D env="production"' % valid_envs ) else: raise Exception( '\n"%s" is not a valid "env" selection!' "\nChoose from %s." '\nEg. -D env="production"' % (environment, valid_envs) ) continue # Handle: -D user-agent=STRING / user_agent=STRING / agent=STRING if low_key in ["user-agent", "user_agent", "agent"]: user_agent = userdata[key] if user_agent == "true": user_agent = sb.user_agent # revert to default sb.user_agent = user_agent continue # Handle: -D incognito / incognito-mode / incognito_mode if low_key in ["incognito", "incognito-mode", "incognito_mode"]: sb.incognito = True continue # Handle: -D guest / guest-mode / guest_mode if low_key in ["guest", "guest-mode", "guest_mode"]: sb.guest_mode = True continue # Handle: -D devtools / open-devtools / open_devtools if low_key in ["devtools", "open-devtools", "open_devtools"]: sb.devtools = True continue # Handle: -D mobile / mobile-emulator / mobile_emulator if low_key in ["mobile", "mobile-emulator", "mobile_emulator"]: sb.mobile_emulator = True continue # Handle: -D metrics=STR / device-metrics=STR / device_metrics=STR if low_key in ["metrics", "device-metrics", "device_metrics"]: device_metrics = userdata[key] if device_metrics == "true": device_metrics = sb.device_metrics # revert to default sb.device_metrics = device_metrics continue # Handle: -D crx=ZIP / extension-zip=ZIP / extension_zip=ZIP if low_key in ["crx", "extension-zip", "extension_zip"]: extension_zip = userdata[key] if extension_zip == "true": extension_zip = sb.extension_zip # revert to default sb.extension_zip = extension_zip continue # Handle: -D extension-dir=DIR / extension_dir=DIR if low_key in ["extension-dir", "extension_dir"]: extension_dir = userdata[key] if extension_dir == "true": extension_dir = sb.extension_dir # revert to default sb.extension_dir = extension_dir continue # Handle: -D database-env=ENVIRONMENT / database_env=ENVIRONMENT if low_key in ["database-env", "database_env"]: database_env = userdata[key].lower() if database_env in valid_envs: sb.database_env = database_env elif database_env == "true": raise Exception( '\nThe "database-env" argument requires a value!' "\nChoose from %s." '\nEg. -D database-env="production"' % valid_envs ) else: raise Exception( '\n"%s" is not a valid "database-env" selection!' "\nChoose from %s." '\nEg. -D database-env="production"' % (environment, valid_envs) ) continue # Handle: -D archive-logs / archive_logs if low_key in ["archive-logs", "archive_logs"]: sb.archive_logs = True continue # Handle: -D disable-csp / disable_csp if low_key in ["disable-csp", "disable_csp"]: sb.disable_csp = True continue # Handle: -D disable-ws / disable_ws if low_key in ["disable-ws", "disable_ws"]: sb.disable_ws = True continue # Handle: -D enable-ws / enable_ws if low_key in ["enable-ws", "enable_ws"]: sb.enable_ws = True continue # Handle: -D enable-sync / enable_sync if low_key in ["enable-sync", "enable_sync"]: sb.enable_sync = True continue # Handle: -D use-auto-ext / use_auto_ext / auto-ext if low_key in ["use-auto-ext", "use_auto_ext", "auto-ext"]: sb.use_auto_ext = True continue # Handle: -D no-sandbox / no_sandbox if low_key in ["no-sandbox", "no_sandbox"]: sb.no_sandbox = True continue # Handle: -D disable-gpu / disable_gpu if low_key in ["disable-gpu", "disable_gpu"]: sb.disable_gpu = True continue # Handle: -D rs / reuse-session / reuse_session if low_key in ["rs", "reuse-session", "reuse_session"]: sb._reuse_session = True continue # Handle: -D crumbs if low_key == "crumbs": sb._crumbs = True continue # Handle: -D visual-baseline / visual_baseline if low_key in ["visual-baseline", "visual_baseline"]: sb.visual_baseline = True continue # Handle: -D window-size=Width,Height / window_size=Width,Height if low_key in ["window-size", "window_size"]: window_size = userdata[key] if window_size == "true": window_size = sb.window_size # revert to default sb.window_size = window_size continue # Handle: -D maximize / fullscreen / maximize-window if low_key in [ "maximize", "fullscreen", "maximize-window", "maximize_window" ]: sb.maximize_option = True continue # Handle: -D screenshot / save-screenshot / save_screenshot / ss if low_key in [ "screenshot", "save-screenshot", "save_screenshot", "ss" ]: sb.save_screenshot_after_test = True continue # Handle: -D timeout-multiplier=FLOAT / timeout_multiplier=FLOAT if low_key in ["timeout-multiplier", "timeout_multiplier"]: timeout_multiplier = userdata[key] if timeout_multiplier == "true": timeout_multiplier = sb.timeout_multiplier # revert to default sb.timeout_multiplier = timeout_multiplier continue # Handle: -D with-db-reporting / with-db_reporting if low_key in ["with-db-reporting", "with-db_reporting"]: sb.with_db_reporting = True continue # Handle: -D with-s3-logging / with-s3_logging if low_key in ["with-s3-logging", "with-s3_logging"]: sb.with_s3_logging = True continue # Handle: -D check-js / check_js if low_key in ["check-js", "check_js"]: sb.js_checking_on = True continue # Handle: -D recorder / record / rec / codegen if low_key in ["recorder", "record", "rec", "codegen"]: sb.recorder_mode = True sb.recorder_ext = True continue # Handle: -D rec-behave / rec-gherkin if low_key in ["rec-behave", "rec-gherkin"]: sb.rec_behave = True continue # Handle: -D record-sleep / record_sleep / rec-sleep / rec_sleep if low_key in ["record-sleep", "rec-sleep"]: sb.record_sleep = True continue # Handle: -D slow / slowmo / slow-mode / slow_mode if low_key in ["slow", "slowmo", "slow-mode", "slow_mode"]: sb.slow_mode = True continue # Handle: -D demo / demo-mode / demo_mode if low_key in ["demo", "demo-mode", "demo_mode"]: sb.demo_mode = True continue # Handle: -D time-limit / time_limit / timelimit if low_key in ["time-limit", "time_limit", "timelimit"]: time_limit = userdata[key] if time_limit == "true": time_limit = sb.time_limit # revert to default sb.time_limit = time_limit continue # Handle: -D demo-sleep / demo_sleep if low_key in ["demo-sleep", "demo_sleep"]: demo_sleep = userdata[key] if demo_sleep == "true": demo_sleep = sb.demo_sleep # revert to default sb.demo_sleep = demo_sleep continue # Handle: -D dashboard if low_key == "dashboard": sb.dashboard = True continue # Handle: -D dash-title=TITLE / dash_title=TITLE if low_key in ["dash-title", "dash_title"]: sb.dash_title = userdata[key] continue # Handle: -D message-duration / message_duration if low_key in ["message-duration", "message_duration"]: message_duration = userdata[key] if message_duration == "true": message_duration = sb.message_duration # revert to default sb.message_duration = message_duration continue # Handle: -D block-images / block_images if low_key in ["block-images", "block_images"]: sb.block_images = True continue # Handle: -D external-pdf / external_pdf if low_key in ["external-pdf", "external_pdf"]: sb.external_pdf = True continue # Handle: -D remote-debug / remote_debug if low_key in ["remote-debug", "remote_debug"]: sb.remote_debug = True continue # Handle: -D settings=FILE / settings-file=FILE / settings_file=FILE if low_key in ["settings", "settings-file", "settings_file"]: settings_file = userdata[key] if settings_file == "true": settings_file = sb.settings_file # revert to default sb.settings_file = settings_file continue # Handle: -D user-data-dir=DIR / user_data_dir=DIR if low_key in ["user-data-dir", "user_data_dir"]: user_data_dir = userdata[key] if user_data_dir == "true": user_data_dir = sb.user_data_dir # revert to default sb.user_data_dir = user_data_dir continue # Handle: -D chromium-arg="ARG=N,ARG2" / chromium_arg="ARG=N,ARG2" if low_key in ["chromium-arg", "chromium_arg"]: chromium_arg = userdata[key] if chromium_arg == "true": chromium_arg = sb.chromium_arg # revert to default sb.chromium_arg = chromium_arg continue # Handle: -D firefox-arg="ARG=N,ARG2" / firefox_arg="ARG=N,ARG2" if low_key in ["firefox-arg", "firefox_arg"]: firefox_arg = userdata[key] if firefox_arg == "true": firefox_arg = sb.firefox_arg # revert to default sb.firefox_arg = firefox_arg continue # Handle: -D firefox-pref="PREF:VAL" / firefox_pref="PREF:VAL" if low_key in ["firefox-pref", "firefox_pref"]: firefox_pref = userdata[key] if firefox_pref == "true": firefox_pref = sb.firefox_pref # revert to default sb.firefox_pref = firefox_pref continue # Handle: -D proxy=SERVER:PORT / proxy=USERNAME:PASSWORD@SERVER:PORT if low_key == "proxy": proxy_string = userdata[key] if proxy_string == "true": proxy_string = sb.proxy_string # revert to default sb.proxy_string = proxy_string continue # Handle: -D proxy-bypass-list="DOMAIN1;D2" / proxy_bypass_list="D1;D2" if low_key in ["proxy-bypass-list", "proxy_bypass_list"]: proxy_bypass_list = userdata[key] if proxy_bypass_list == "true": proxy_bypass_list = sb.proxy_bypass_list # revert to default sb.proxy_bypass_list = proxy_bypass_list continue # Handle: -D swiftshader if low_key == "swiftshader": sb.swiftshader = True continue # Handle: -D adblock / ad-block / ad_block / block-ads / block_ads if low_key in [ "adblock", "ad-block", "ad_block", "block-ads", "block_ads" ]: sb.ad_block_on = True continue # Handle: -D highlights=NUM if low_key == "highlights": highlights = userdata[key] if highlights == "true": highlights = sb.highlights # revert to default sb.highlights = highlights continue # Handle: -D interval=SECONDS if low_key == "interval": interval = userdata[key] if interval == "true": interval = sb.interval # revert to default sb.interval = interval continue # Handle: -D cap-file=FILE / cap_file=FILE if low_key in ["cap-file", "cap_file"]: cap_file = userdata[key] if cap_file == "true": cap_file = sb.cap_file # revert to default sb.cap_file = cap_file continue # Handle: -D cap-string=STRING / cap_string=STRING if low_key == "cap_string": cap_string = userdata[key] if cap_string == "true": cap_string = sb.cap_string # revert to default sb.cap_string = cap_string continue # Fail immediately if trying to set more than one default browser. if len(browsers) > 1: raise Exception( "\nOnly ONE default browser is allowed!\n" "%s browsers were selected: %s" % (len(browsers), browsers) ) # Recorder Mode does not support headless browser runs. # Chromium does not allow extensions in Headless Mode. if sb.recorder_ext and sb.headless: raise Exception( "\n\n Recorder Mode does NOT support Headless Mode!" '\n (DO NOT combine "-D rec" with "-D headless"!)\n' ) # Recorder Mode only supports Chromium browsers. if sb.recorder_ext and (sb.browser not in ["chrome", "edge"]): raise Exception( "\n\n Recorder Mode ONLY supports Chrome and Edge!" '\n (Your browser choice was: "%s")\n' % sb.browser ) # The Xvfb virtual display server is for Linux OS Only. if sb.xvfb and "linux" not in sys.platform: sb.xvfb = False if ( "linux" in sys.platform and not sb.headed and not sb.headless and not sb.xvfb ): print( '(Linux uses "-D headless" by default. ' 'To override, use "-D headed" / "-D gui". ' 'For Xvfb mode instead, use "-D xvfb". ' 'Or hide this info with "-D headless".)' ) sb.headless = True if not sb.headless: sb.headed = True if sb.servername != "localhost": # Using Selenium Grid # (Set -D server="127.0.0.1" for localhost Grid) # If the port is "443", the protocol is "https" if str(sb.port) == "443": sb.protocol = "https" if sb.window_size: window_size = sb.window_size if window_size.count(",") != 1: message = ( '\n\n window_size expects a "width,height" string!' '\n (Your input was: "%s")\n' % window_size ) raise Exception(message) window_size = window_size.replace(" ", "") width = None height = None try: width = int(window_size.split(",")[0]) height = int(window_size.split(",")[1]) except Exception: message = ( '\n\n Expecting integer values for "width,height"!' '\n (window_size input was: "%s")\n' % window_size ) raise Exception(message) settings.CHROME_START_WIDTH = width settings.CHROME_START_HEIGHT = height settings.HEADLESS_START_WIDTH = width settings.HEADLESS_START_HEIGHT = height # Set sb_config sb_config.browser = sb.browser sb_config.headless = sb.headless sb_config.headed = sb.headed sb_config.window_size = sb.window_size sb_config.maximize_option = sb.maximize_option sb_config.xvfb = sb.xvfb sb_config.save_screenshot = sb.save_screenshot_after_test sb_config._has_logs = False sb_config.variables = sb.variables sb_config.dashboard = sb.dashboard sb_config.dash_title = sb.dash_title sb_config.pdb_option = sb.pdb_option sb_config.rec_behave = sb.rec_behave sb_config.record_sleep = sb.record_sleep sb_config._is_timeout_changed = False sb_config._SMALL_TIMEOUT = settings.SMALL_TIMEOUT sb_config._LARGE_TIMEOUT = settings.LARGE_TIMEOUT sb_config._recorded_actions = {} sb_config._behave_recorded_actions = {} # Dashboard-specific variables sb_config._results = {} # SBase Dashboard test results sb_config._duration = {} # SBase Dashboard test duration sb_config._display_id = {} # SBase Dashboard display ID sb_config._d_t_log_path = {} # SBase Dashboard test log path sb_config._dash_html = None # SBase Dashboard HTML copy sb_config._test_id = None # SBase Dashboard test id sb_config._latest_display_id = None # The latest SBase display id sb_config._dashboard_initialized = False # Becomes True after init sb_config._has_exception = False # This becomes True if any test fails sb_config._multithreaded = False # This becomes True if multithreading sb_config._only_unittest = True # If any test uses BaseCase, becomes False sb_config._sbase_detected = False # Becomes True during SeleniumBase tests sb_config._extra_dash_entries = [] # Dashboard entries for non-SBase tests sb_config._using_html_report = False # Becomes True when using html report sb_config._dash_is_html_report = False # Dashboard becomes the html report sb_config._saved_dashboard_pie = None # Copy of pie chart for html report sb_config._dash_final_summary = None # Dash status to add to html report sb_config._html_report_name = None # The name of the pytest html report if sb_config.dash_title: constants.Dashboard.TITLE = sb_config.dash_title.replace("_", " ") log_helper.log_folder_setup(sb.log_path, sb.archive_logs) download_helper.reset_downloads_folder() proxy_helper.remove_proxy_zip_if_present() return sb
def get_remote_driver(browser_name, headless, servername, port, proxy_string, proxy_auth, proxy_user, proxy_pass, user_agent, cap_file, disable_csp, enable_sync, no_sandbox, disable_gpu, incognito, guest_mode, devtools, user_data_dir, extension_zip, extension_dir, mobile_emulator, device_width, device_height, device_pixel_ratio): downloads_path = download_helper.get_downloads_folder() download_helper.reset_downloads_folder() address = "http://%s:%s/wd/hub" % (servername, port) desired_caps = {} if cap_file: desired_caps = capabilities_parser.get_desired_capabilities(cap_file) if browser_name == constants.Browser.GOOGLE_CHROME: chrome_options = _set_chrome_options( downloads_path, headless, proxy_string, proxy_auth, proxy_user, proxy_pass, user_agent, disable_csp, enable_sync, no_sandbox, disable_gpu, incognito, guest_mode, devtools, user_data_dir, extension_zip, extension_dir, servername, mobile_emulator, device_width, device_height, device_pixel_ratio) capabilities = chrome_options.to_capabilities() for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote(command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.FIREFOX: try: # Use Geckodriver for Firefox if it's on the PATH profile = _create_firefox_profile(downloads_path, proxy_string, user_agent, disable_csp) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = True if headless: firefox_capabilities['moz:firefoxOptions'] = ({ 'args': ['-headless'] }) for key in desired_caps.keys(): firefox_capabilities[key] = desired_caps[key] capabilities = firefox_capabilities warnings.simplefilter("ignore", category=DeprecationWarning) return webdriver.Remote(command_executor=address, desired_capabilities=capabilities, browser_profile=profile) except WebDriverException: # Don't use Geckodriver: Only works for old versions of Firefox profile = _create_firefox_profile(downloads_path, proxy_string, user_agent, disable_csp) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = False if headless: firefox_capabilities['moz:firefoxOptions'] = ({ 'args': ['-headless'] }) for key in desired_caps.keys(): firefox_capabilities[key] = desired_caps[key] capabilities = firefox_capabilities return webdriver.Remote(command_executor=address, desired_capabilities=capabilities, browser_profile=profile) elif browser_name == constants.Browser.INTERNET_EXPLORER: capabilities = webdriver.DesiredCapabilities.INTERNETEXPLORER for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote(command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.EDGE: capabilities = webdriver.DesiredCapabilities.EDGE for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote(command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.SAFARI: capabilities = webdriver.DesiredCapabilities.SAFARI for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote(command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.OPERA: capabilities = webdriver.DesiredCapabilities.OPERA for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote(command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.PHANTOM_JS: capabilities = webdriver.DesiredCapabilities.PHANTOMJS for key in desired_caps.keys(): capabilities[key] = desired_caps[key] with warnings.catch_warnings(): # Ignore "PhantomJS has been deprecated" UserWarning warnings.simplefilter("ignore", category=UserWarning) return webdriver.Remote(command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.ANDROID: capabilities = webdriver.DesiredCapabilities.ANDROID for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote(command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.IPHONE: capabilities = webdriver.DesiredCapabilities.IPHONE for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote(command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.IPAD: capabilities = webdriver.DesiredCapabilities.IPAD for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote(command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.REMOTE: return webdriver.Remote(command_executor=address, desired_capabilities=desired_caps)
def get_local_driver(browser_name, headless, servername, proxy_string, proxy_auth, proxy_user, proxy_pass, user_agent, disable_csp, enable_sync, no_sandbox, disable_gpu, incognito, guest_mode, devtools, user_data_dir, extension_zip, extension_dir, mobile_emulator, device_width, device_height, device_pixel_ratio): ''' Spins up a new web browser and returns the driver. Can also be used to spin up additional browsers for the same test. ''' downloads_path = download_helper.get_downloads_folder() download_helper.reset_downloads_folder() if browser_name == constants.Browser.FIREFOX: try: try: # Use Geckodriver for Firefox if it's on the PATH profile = _create_firefox_profile(downloads_path, proxy_string, user_agent, disable_csp) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = True options = webdriver.FirefoxOptions() if headless: options.add_argument('-headless') firefox_capabilities['moz:firefoxOptions'] = ({ 'args': ['-headless'] }) if LOCAL_GECKODRIVER and os.path.exists(LOCAL_GECKODRIVER): try: make_driver_executable_if_not(LOCAL_GECKODRIVER) except Exception as e: logging.debug("\nWarning: Could not make geckodriver" " executable: %s" % e) elif not is_geckodriver_on_path(): args = " ".join(sys.argv) if not ("-n" in sys.argv or "-n=" in args or args == "-c"): # (Not multithreaded) from seleniumbase.console_scripts import sb_install sys_args = sys.argv # Save a copy of current sys args print("\nWarning: geckodriver not found!" " Installing now:") try: sb_install.main(override="geckodriver") except Exception as e: print("\nWarning: Could not install geckodriver: " "%s" % e) sys.argv = sys_args # Put back the original sys args if "linux" in PLATFORM or not headless: firefox_driver = webdriver.Firefox( firefox_profile=profile, capabilities=firefox_capabilities) else: firefox_driver = webdriver.Firefox( firefox_profile=profile, capabilities=firefox_capabilities, options=options) except Exception: profile = _create_firefox_profile(downloads_path, proxy_string, user_agent, disable_csp) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_driver = webdriver.Firefox( firefox_profile=profile, capabilities=firefox_capabilities) return firefox_driver except Exception as e: if headless: raise Exception(e) return webdriver.Firefox() elif browser_name == constants.Browser.INTERNET_EXPLORER: if not IS_WINDOWS: raise Exception( "IE Browser is for Windows-based operating systems only!") from selenium.webdriver.ie.options import Options ie_options = Options() ie_options.ignore_protected_mode_settings = False ie_options.ignore_zoom_level = True ie_options.require_window_focus = False ie_options.native_events = True ie_options.full_page_screenshot = True ie_options.persistent_hover = True ie_capabilities = ie_options.to_capabilities() if LOCAL_IEDRIVER and os.path.exists(LOCAL_IEDRIVER): try: make_driver_executable_if_not(LOCAL_IEDRIVER) except Exception as e: logging.debug("\nWarning: Could not make iedriver" " executable: %s" % e) return webdriver.Ie(capabilities=ie_capabilities) elif browser_name == constants.Browser.EDGE: try: chrome_options = _set_chrome_options( downloads_path, headless, proxy_string, proxy_auth, proxy_user, proxy_pass, user_agent, disable_csp, enable_sync, no_sandbox, disable_gpu, incognito, guest_mode, devtools, user_data_dir, extension_zip, extension_dir, servername, mobile_emulator, device_width, device_height, device_pixel_ratio) if LOCAL_EDGEDRIVER and os.path.exists(LOCAL_EDGEDRIVER): try: make_driver_executable_if_not(LOCAL_EDGEDRIVER) except Exception as e: logging.debug("\nWarning: Could not make edgedriver" " executable: %s" % e) elif not is_edgedriver_on_path(): args = " ".join(sys.argv) if not ("-n" in sys.argv or "-n=" in args or args == "-c"): # (Not multithreaded) from seleniumbase.console_scripts import sb_install sys_args = sys.argv # Save a copy of current sys args print("\nWarning: msedgedriver not found. Installing now:") sb_install.main(override="edgedriver") sys.argv = sys_args # Put back the original sys args return webdriver.Chrome(executable_path=LOCAL_EDGEDRIVER, options=chrome_options) except Exception as e: if headless: raise Exception(e) if LOCAL_EDGEDRIVER and os.path.exists(LOCAL_EDGEDRIVER): try: make_driver_executable_if_not(LOCAL_EDGEDRIVER) except Exception as e: logging.debug("\nWarning: Could not make edgedriver" " executable: %s" % e) return webdriver.Chrome(executable_path=LOCAL_EDGEDRIVER) elif browser_name == constants.Browser.SAFARI: arg_join = " ".join(sys.argv) if ("-n" in sys.argv) or ("-n=" in arg_join) or (arg_join == "-c"): # Skip if multithreaded raise Exception("Can't run Safari tests in multi-threaded mode!") return webdriver.Safari() elif browser_name == constants.Browser.OPERA: if LOCAL_OPERADRIVER and os.path.exists(LOCAL_OPERADRIVER): try: make_driver_executable_if_not(LOCAL_OPERADRIVER) except Exception as e: logging.debug("\nWarning: Could not make operadriver" " executable: %s" % e) return webdriver.Opera() elif browser_name == constants.Browser.PHANTOM_JS: with warnings.catch_warnings(): # Ignore "PhantomJS has been deprecated" UserWarning warnings.simplefilter("ignore", category=UserWarning) return webdriver.PhantomJS() elif browser_name == constants.Browser.GOOGLE_CHROME: try: chrome_options = _set_chrome_options( downloads_path, headless, proxy_string, proxy_auth, proxy_user, proxy_pass, user_agent, disable_csp, enable_sync, no_sandbox, disable_gpu, incognito, guest_mode, devtools, user_data_dir, extension_zip, extension_dir, servername, mobile_emulator, device_width, device_height, device_pixel_ratio) if LOCAL_CHROMEDRIVER and os.path.exists(LOCAL_CHROMEDRIVER): try: make_driver_executable_if_not(LOCAL_CHROMEDRIVER) except Exception as e: logging.debug("\nWarning: Could not make chromedriver" " executable: %s" % e) elif not is_chromedriver_on_path(): args = " ".join(sys.argv) if not ("-n" in sys.argv or "-n=" in args or args == "-c"): # (Not multithreaded) from seleniumbase.console_scripts import sb_install sys_args = sys.argv # Save a copy of current sys args print("\nWarning: chromedriver not found. Installing now:") sb_install.main(override="chromedriver") sys.argv = sys_args # Put back the original sys args return webdriver.Chrome(options=chrome_options) except Exception as e: if headless: raise Exception(e) if LOCAL_CHROMEDRIVER and os.path.exists(LOCAL_CHROMEDRIVER): try: make_driver_executable_if_not(LOCAL_CHROMEDRIVER) except Exception as e: logging.debug("\nWarning: Could not make chromedriver" " executable: %s" % e) return webdriver.Chrome() else: raise Exception("%s is not a valid browser option for this system!" % browser_name)
def get_remote_driver( browser_name, headless, servername, port, proxy_string, proxy_auth, proxy_user, proxy_pass, user_agent, cap_file, disable_csp): downloads_path = download_helper.get_downloads_folder() download_helper.reset_downloads_folder() address = "http://%s:%s/wd/hub" % (servername, port) desired_caps = {} if cap_file: desired_caps = capabilities_parser.get_desired_capabilities(cap_file) if browser_name == constants.Browser.GOOGLE_CHROME: chrome_options = _set_chrome_options( downloads_path, headless, proxy_string, proxy_auth, proxy_user, proxy_pass, user_agent, disable_csp) if headless: if not proxy_auth: # Headless Chrome doesn't support extensions, which are # required when using a proxy server that has authentication. # Instead, base_case.py will use PyVirtualDisplay when not # using Chrome's built-in headless mode. See link for details: # https://bugs.chromium.org/p/chromium/issues/detail?id=706008 chrome_options.add_argument("--headless") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--no-sandbox") capabilities = chrome_options.to_capabilities() for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote( command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.FIREFOX: try: # Use Geckodriver for Firefox if it's on the PATH profile = _create_firefox_profile( downloads_path, proxy_string, user_agent, disable_csp) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = True if headless: firefox_capabilities['moz:firefoxOptions'] = ( {'args': ['-headless']}) for key in desired_caps.keys(): firefox_capabilities[key] = desired_caps[key] capabilities = firefox_capabilities address = "http://%s:%s/wd/hub" % (servername, port) return webdriver.Remote( command_executor=address, desired_capabilities=capabilities, browser_profile=profile) except WebDriverException: # Don't use Geckodriver: Only works for old versions of Firefox profile = _create_firefox_profile( downloads_path, proxy_string, user_agent, disable_csp) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = False if headless: firefox_capabilities['moz:firefoxOptions'] = ( {'args': ['-headless']}) for key in desired_caps.keys(): firefox_capabilities[key] = desired_caps[key] capabilities = firefox_capabilities return webdriver.Remote( command_executor=address, desired_capabilities=capabilities, browser_profile=profile) elif browser_name == constants.Browser.INTERNET_EXPLORER: capabilities = webdriver.DesiredCapabilities.INTERNETEXPLORER for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote( command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.EDGE: capabilities = webdriver.DesiredCapabilities.EDGE for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote( command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.SAFARI: capabilities = webdriver.DesiredCapabilities.SAFARI for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote( command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.OPERA: capabilities = webdriver.DesiredCapabilities.OPERA for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote( command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.PHANTOM_JS: capabilities = webdriver.DesiredCapabilities.PHANTOMJS for key in desired_caps.keys(): capabilities[key] = desired_caps[key] with warnings.catch_warnings(): # Ignore "PhantomJS has been deprecated" UserWarning warnings.simplefilter("ignore", category=UserWarning) return webdriver.Remote( command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.ANDROID: capabilities = webdriver.DesiredCapabilities.ANDROID for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote( command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.IPHONE: capabilities = webdriver.DesiredCapabilities.IPHONE for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote( command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.IPAD: capabilities = webdriver.DesiredCapabilities.IPAD for key in desired_caps.keys(): capabilities[key] = desired_caps[key] return webdriver.Remote( command_executor=address, desired_capabilities=capabilities) elif browser_name == constants.Browser.REMOTE: return webdriver.Remote( command_executor=address, desired_capabilities=desired_caps)
def get_local_driver(browser_name, headless, proxy_string): ''' Spins up a new web browser and returns the driver. Can also be used to spin up additional browsers for the same test. ''' downloads_path = download_helper.get_downloads_folder() download_helper.reset_downloads_folder() if browser_name == constants.Browser.FIREFOX: try: try: # Use Geckodriver for Firefox if it's on the PATH profile = _create_firefox_profile(downloads_path, proxy_string) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = True options = webdriver.FirefoxOptions() if headless: options.add_argument('-headless') if LOCAL_GECKODRIVER and os.path.exists(LOCAL_GECKODRIVER): make_driver_executable_if_not(LOCAL_GECKODRIVER) firefox_driver = webdriver.Firefox( firefox_profile=profile, capabilities=firefox_capabilities, options=options, executable_path=LOCAL_GECKODRIVER) else: firefox_driver = webdriver.Firefox( firefox_profile=profile, capabilities=firefox_capabilities, options=options) except WebDriverException: # Don't use Geckodriver: Only works for old versions of Firefox profile = _create_firefox_profile(downloads_path, proxy_string) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = False firefox_driver = webdriver.Firefox( firefox_profile=profile, capabilities=firefox_capabilities) return firefox_driver except Exception as e: if headless: raise Exception(e) return webdriver.Firefox() elif browser_name == constants.Browser.INTERNET_EXPLORER: if not IS_WINDOWS: raise Exception( "IE Browser is for Windows-based operating systems only!") from selenium.webdriver.ie.options import Options ie_options = Options() ie_options.ignore_protected_mode_settings = False ie_options.ignore_zoom_level = True ie_options.require_window_focus = False ie_options.native_events = True ie_options.full_page_screenshot = True ie_options.persistent_hover = True ie_capabilities = ie_options.to_capabilities() if LOCAL_IEDRIVER and os.path.exists(LOCAL_IEDRIVER): make_driver_executable_if_not(LOCAL_IEDRIVER) return webdriver.Ie(capabilities=ie_capabilities, executable_path=LOCAL_IEDRIVER) else: return webdriver.Ie(capabilities=ie_capabilities) elif browser_name == constants.Browser.EDGE: if not IS_WINDOWS: raise Exception( "Edge Browser is for Windows-based operating systems only!") edge_capabilities = DesiredCapabilities.EDGE.copy() if LOCAL_EDGEDRIVER and os.path.exists(LOCAL_EDGEDRIVER): make_driver_executable_if_not(LOCAL_EDGEDRIVER) return webdriver.Edge(capabilities=edge_capabilities, executable_path=LOCAL_EDGEDRIVER) else: return webdriver.Edge(capabilities=edge_capabilities) elif browser_name == constants.Browser.SAFARI: return webdriver.Safari() elif browser_name == constants.Browser.OPERA: if LOCAL_OPERADRIVER and os.path.exists(LOCAL_OPERADRIVER): make_driver_executable_if_not(LOCAL_OPERADRIVER) return webdriver.Opera(executable_path=LOCAL_OPERADRIVER) else: return webdriver.Opera() elif browser_name == constants.Browser.PHANTOM_JS: with warnings.catch_warnings(): # Ignore "PhantomJS has been deprecated" UserWarning warnings.simplefilter("ignore", category=UserWarning) return webdriver.PhantomJS() elif browser_name == constants.Browser.GOOGLE_CHROME: try: chrome_options = _set_chrome_options(downloads_path, proxy_string) if headless: chrome_options.add_argument("--headless") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--no-sandbox") if LOCAL_CHROMEDRIVER and os.path.exists(LOCAL_CHROMEDRIVER): make_driver_executable_if_not(LOCAL_CHROMEDRIVER) return webdriver.Chrome(executable_path=LOCAL_CHROMEDRIVER, options=chrome_options) else: return webdriver.Chrome(options=chrome_options) except Exception as e: if headless: raise Exception(e) if LOCAL_CHROMEDRIVER and os.path.exists(LOCAL_CHROMEDRIVER): make_driver_executable_if_not(LOCAL_CHROMEDRIVER) return webdriver.Chrome(executable_path=LOCAL_CHROMEDRIVER) else: return webdriver.Chrome()
def get_local_driver( browser_name, headless, proxy_string, proxy_auth, proxy_user, proxy_pass, user_agent, disable_csp): ''' Spins up a new web browser and returns the driver. Can also be used to spin up additional browsers for the same test. ''' downloads_path = download_helper.get_downloads_folder() download_helper.reset_downloads_folder() if browser_name == constants.Browser.FIREFOX: try: try: # Use Geckodriver for Firefox if it's on the PATH profile = _create_firefox_profile( downloads_path, proxy_string, user_agent, disable_csp) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = True options = webdriver.FirefoxOptions() if headless: options.add_argument('-headless') if LOCAL_GECKODRIVER and os.path.exists(LOCAL_GECKODRIVER): make_driver_executable_if_not(LOCAL_GECKODRIVER) firefox_driver = webdriver.Firefox( firefox_profile=profile, capabilities=firefox_capabilities, options=options, executable_path=LOCAL_GECKODRIVER) else: firefox_driver = webdriver.Firefox( firefox_profile=profile, capabilities=firefox_capabilities, options=options) except WebDriverException: # Don't use Geckodriver: Only works for old versions of Firefox profile = _create_firefox_profile( downloads_path, proxy_string, user_agent, disable_csp) firefox_capabilities = DesiredCapabilities.FIREFOX.copy() firefox_capabilities['marionette'] = False firefox_driver = webdriver.Firefox( firefox_profile=profile, capabilities=firefox_capabilities) return firefox_driver except Exception as e: if headless: raise Exception(e) return webdriver.Firefox() elif browser_name == constants.Browser.INTERNET_EXPLORER: if not IS_WINDOWS: raise Exception( "IE Browser is for Windows-based operating systems only!") from selenium.webdriver.ie.options import Options ie_options = Options() ie_options.ignore_protected_mode_settings = False ie_options.ignore_zoom_level = True ie_options.require_window_focus = False ie_options.native_events = True ie_options.full_page_screenshot = True ie_options.persistent_hover = True ie_capabilities = ie_options.to_capabilities() if LOCAL_IEDRIVER and os.path.exists(LOCAL_IEDRIVER): make_driver_executable_if_not(LOCAL_IEDRIVER) return webdriver.Ie( capabilities=ie_capabilities, executable_path=LOCAL_IEDRIVER) else: return webdriver.Ie(capabilities=ie_capabilities) elif browser_name == constants.Browser.EDGE: if not IS_WINDOWS: raise Exception( "Edge Browser is for Windows-based operating systems only!") edge_capabilities = DesiredCapabilities.EDGE.copy() if LOCAL_EDGEDRIVER and os.path.exists(LOCAL_EDGEDRIVER): make_driver_executable_if_not(LOCAL_EDGEDRIVER) return webdriver.Edge( capabilities=edge_capabilities, executable_path=LOCAL_EDGEDRIVER) else: return webdriver.Edge(capabilities=edge_capabilities) elif browser_name == constants.Browser.SAFARI: return webdriver.Safari() elif browser_name == constants.Browser.OPERA: if LOCAL_OPERADRIVER and os.path.exists(LOCAL_OPERADRIVER): make_driver_executable_if_not(LOCAL_OPERADRIVER) return webdriver.Opera(executable_path=LOCAL_OPERADRIVER) else: return webdriver.Opera() elif browser_name == constants.Browser.PHANTOM_JS: with warnings.catch_warnings(): # Ignore "PhantomJS has been deprecated" UserWarning warnings.simplefilter("ignore", category=UserWarning) return webdriver.PhantomJS() elif browser_name == constants.Browser.GOOGLE_CHROME: try: chrome_options = _set_chrome_options( downloads_path, headless, proxy_string, proxy_auth, proxy_user, proxy_pass, user_agent, disable_csp) if headless: # Headless Chrome doesn't support extensions, which are # required when using a proxy server that has authentication. # Instead, base_case.py will use PyVirtualDisplay when not # using Chrome's built-in headless mode. See link for details: # https://bugs.chromium.org/p/chromium/issues/detail?id=706008 if not proxy_auth: chrome_options.add_argument("--headless") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--no-sandbox") if LOCAL_CHROMEDRIVER and os.path.exists(LOCAL_CHROMEDRIVER): make_driver_executable_if_not(LOCAL_CHROMEDRIVER) return webdriver.Chrome( executable_path=LOCAL_CHROMEDRIVER, options=chrome_options) else: return webdriver.Chrome(options=chrome_options) except Exception as e: if headless: raise Exception(e) if LOCAL_CHROMEDRIVER and os.path.exists(LOCAL_CHROMEDRIVER): make_driver_executable_if_not(LOCAL_CHROMEDRIVER) return webdriver.Chrome(executable_path=LOCAL_CHROMEDRIVER) else: return webdriver.Chrome() else: raise Exception( "%s is not a valid browser option for this system!" % browser_name)