def driver(request, logger, proxy): browser = request.config.getoption('--browser') if browser == 'chrome': options = ChromeOptions() options.add_argument('--headless') options.add_argument('--start-fullscreen') options.add_argument(f'--proxy-server={proxy.proxy}') options.add_experimental_option('w3c', False) caps = DesiredCapabilities.CHROME.copy() caps['timeouts'] = { 'implicit': 20000, 'pageLoad': 20000, 'script': 20000 } caps['loggingPrefs'] = {'browser': 'ALL'} wd = EventFiringWebDriver( webdriver.Chrome(options=options, desired_capabilities=caps), ChromeListener(logger)) else: raise ValueError('Unsupported browser.') yield wd wd.quit()
def openChrome(self): opts = webdriver.ChromeOptions() if not self.show_flash: opts.add_argument("--disable-bundled-ppapi-flash") prefs = { # 'download.default_directory': os.getcwd(), # 'download.prompt_for_download': False, # 'profile.default_content_setting_values.notifications' : 2, #prevent notification } if not self.show_image: prefs['profile.managed_default_content_settings.images'] = 2 opts.add_experimental_option("prefs", prefs) if not self.proxy == '': opts.add_argument('--proxy-server=%s' % self.proxy) opts.add_argument('--disable-impl-side-painting') opts.add_argument('--no-sandbox') if self.is_mobile_view: w = 375 h = 667 mobile_emulation = { "deviceMetrics": { "width": w, "height": h, "pixelRatio": 3.0 }, "userAgent": CHROME_IPHONE_UA } opts.add_experimental_option("mobileEmulation", mobile_emulation) opts.add_argument("window-size=" + str(w) + "," + str(h)) print("USED MOBILE VIEW") else: if self.user_agent == '': self.user_agent = CHROME_MAC_UA opts.add_argument("user-agent=" + self.user_agent) opts.add_argument("window-size=" + str(self.driver_w) + "," + str(self.driver_h)) if self.use_user_data: if not os.path.exists(self.user_data_path): os.makedirs(self.user_data_path) opts.add_argument("user-data-dir=" + self.user_data_path) # else: # opts.add_argument("incognito") self.driver = webdriver.Remote( command_executor=SELENIUM_HUB, desired_capabilities=opts.to_capabilities()) self.driver.implicitly_wait(IMPLICITY_WAIT) # 暗黙の待機(秒) self.driver.set_page_load_timeout(CLIENT_TIMEOUT) # ページの読み込み待ち時間(秒) if self.is_mobile_view: pass else: self.driver.maximize_window() # 最大化 # 独自イベントハンドラーを追加 self.driver = EventFiringWebDriver(self.driver, MyListener()) self.wait = WebDriverWait(self.driver, CLIENT_TIMEOUT) self.wait_10s = WebDriverWait(self.driver, 10)
def driver(request, driver_class, driver_kwargs): """Returns a WebDriver instance based on options and capabilities""" retries = int(request.config.getini("max_driver_init_attempts")) for retry in Retrying(stop=stop_after_attempt(retries), wait=wait_exponential(), reraise=True): with retry: LOGGER.info( f"Driver init, attempt {retry.retry_state.attempt_number}/{retries}" ) driver = driver_class(**driver_kwargs) event_listener = request.config.getoption("event_listener") if event_listener is not None: # Import the specified event listener and wrap the driver instance mod_name, class_name = event_listener.rsplit(".", 1) mod = __import__(mod_name, fromlist=[class_name]) event_listener = getattr(mod, class_name) if not isinstance(driver, EventFiringWebDriver): driver = EventFiringWebDriver(driver, event_listener()) request.node._driver = driver yield driver driver.quit()
def driver(request, driver_class, driver_kwargs): """ Returns a WebDriver instance based on options and capabilities This is copied from pytest-selenium 1.11.4, but modified to retry getting the driver up to 3 times to cope with intermittent connection resets in TravisCI. We ripped the original ``driver = driver_class(**driver_kwargs)`` out and replaced it with the ``get_driver_for_class()`` function, which is wrapped in the retrying package's ``@retry`` decorator. """ kwargs = driver_kwargs if driver_class == ChromeWD: kwargs['desired_capabilities']['loggingPrefs'] = {'browser': 'ALL'} driver = get_driver_for_class(driver_class, kwargs) event_listener = request.config.getoption('event_listener') if event_listener is not None: # Import the specified event listener and wrap the driver instance mod_name, class_name = event_listener.rsplit('.', 1) mod = __import__(mod_name, fromlist=[class_name]) event_listener = getattr(mod, class_name) if not isinstance(driver, EventFiringWebDriver): driver = EventFiringWebDriver(driver, event_listener()) request.node._driver = driver yield driver driver.quit()
def __init__(self, browser='chrome', *args, **kwargs): """ Creates a nerodia.browser.Browser instance :param browser: firefox, ie, chrome, remote or Selenium WebDriver instance :type browser: selenium.webdriver.remote.webdriver.WebDriver or str :param args: args passed to the underlying driver :param kwargs: kwargs passed to the underlying driver """ if isinstance(browser, six.string_types[0]): module = import_module('selenium.webdriver.{}.webdriver'.format( browser.lower())) caps = Capabilities(browser, **kwargs) self.driver = module.WebDriver(**caps.kwargs) elif isinstance(browser, WebDriver): self.driver = browser else: raise TypeError( 'A browser name or WebDriver instance must be supplied, ' 'got {}'.format(type(browser))) if 'listener' in kwargs: self.driver = EventFiringWebDriver(self.driver, kwargs.get('listener')) self.after_hooks = AfterHooks(self) self.current_frame = None self.closed = False self.default_context = True self._original_window = None
def get_driver(browser, headless_mode=False) -> EventFiringWebDriver: if browser == "chrome": options = webdriver.ChromeOptions() options.add_argument("start-maximized") if headless_mode is True: options.add_argument("--headless") driver = EventFiringWebDriver( webdriver.Chrome(ChromeDriverManager().install(), options=options), WebDriverListener()) return driver elif browser == "firefox": options = webdriver.FirefoxOptions() if headless_mode is True: options.headless = True driver = EventFiringWebDriver( webdriver.Firefox( executable_path=GeckoDriverManager().install(), options=options), WebDriverListener()) return driver elif browser == "edge": options = EdgeOptions() options.use_chromium = True if headless_mode is True: options.headless = True driver_path = EdgeChromiumDriverManager().install() driver = EventFiringWebDriver( Edge(executable_path=driver_path, options=options), WebDriverListener()) return driver raise Exception("Provide valid driver name")
def browser(logger, request): selected_browser = request.config.getoption('--browser') if selected_browser not in ('firefox', 'chrome'): raise ValueError( f'--browser option can only be "firefox" or "chrome", received "{selected_browser}"' ) executor = request.config.getoption('--executor') browser_logger = logging.getLogger('Browser') logger.info(f'Starting {selected_browser.capitalize()}') browser = EventFiringWebDriver( webdriver.Remote( command_executor=f'http://{executor}:4444/wd/hub', desired_capabilities={ 'browserName': selected_browser, 'loggingPrefs': { 'browser': 'ALL' }, 'acceptInsecureCerts': True, }, ), EventListener(browser_logger), ) browser.implicitly_wait(request.config.getoption('--time')) browser.get(request.config.getoption('--url')) # Ожидание на случай первоначальной установки WebDriverWait(browser, 100).until(EC.visibility_of_element_located(HEADER)) failed = request.session.testsfailed yield browser if request.session.testsfailed > failed: browser.save_screenshot( f'screenshots/{datetime.now().strftime("%d-%m-%Y %H-%M-%S")}.png') browser.quit()
def setUp(self): self.base_url = 'https://autodemo.testoneo.com/en/' driver = webdriver.Chrome( executable_path=r"C:\TestFiles\chromedriver.exe") self.ef_driver = EventFiringWebDriver(driver, ScreenshotListener()) self.ef_driver.maximize_window() time.sleep(2)
def setUpClass(self): self.base_url = 'https://autodemo.testoneo.com/en/' self.login_url = self.base_url + 'login' self.clothes_product_url = self.base_url + '3-clothes' self.accessories_product_url = self.base_url + '6-accessories' self.art_product_url = self.base_url + '9-art' driver = webdriver.Chrome(executable_path=r"C:\Personal_Belongings\Python\Chromedriver\chromedriver.exe") self.ef_driver = EventFiringWebDriver(driver, ScreenshotListener())
def setUp(self): self.base_url = 'https://autodemo.testoneo.com/en/' self.login_url = self.base_url + 'login' self.sample_product_url = self.base_url + 'men/1-1-hummingbird-printed-t-shirt.html' self.subpage_art_url = self.base_url + '9-art' driver = webdriver.Chrome( executable_path=r"C:\Users\Dominika\Downloads\chromedriver_win32(" r"1)\chromedriver.exe") self.ef_driver = EventFiringWebDriver(driver, ScreenshotListener())
def setUp(request): W_driver = wdf.get_driver() driver = EventFiringWebDriver(W_driver, MyListeners()) if request.node is not None: request.node.driver = driver yield if request.node.rep_call.failed: allure.attach(driver.get_screenshot_as_png(), name=request.function.__name__, attachment_type=allure.attachment_type.PNG) driver.quit()
def get_chrome_driver(): chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--start-maximized") capabilities = chrome_options.to_capabilities() capabilities['loggingPrefs'] = {'performance': 'INFO'} driver = webdriver.Chrome(executable_path=chrome_path_url, desired_capabilities=capabilities) listener = WebEventListener() driver = EventFiringWebDriver(driver, listener) driver.implicitly_wait(3) return driver
def setUp(self): options = webdriver.ChromeOptions() options.add_argument('headless') options.add_argument("--no-sandbox") options.add_argument("--disable-dev-shm-usage") self.driver = EventFiringWebDriver( webdriver.Chrome(chrome_options=options), ScreenshotListener()) self.driver.set_page_load_timeout(10) self.driver.set_script_timeout(10) self.driver.maximize_window() self.driver.get(self.get_host()) self.wait_content_is_ready()
def setUp(self): self.base_url = 'https://autodemo.testoneo.com/en/' self.login_url = self.base_url + 'login' self.product_url = self.base_url + 'art/12-mountain-fox-vector-graphics.html' self.sample_product_url = self.base_url + 'men/1-1-hummingbird-printed-t-shirt.html' self.clothes_product_url = self.base_url + '3-clothes' self.accessories_product_url = self.base_url + '6-accessories' self.art_product_url = self.base_url + '9-art' driver = webdriver.Chrome( executable_path= r"C:\Personal_Belongings\Python\Chromedriver\chromedriver.exe") self.ef_driver = EventFiringWebDriver(driver, ScreenshotListener())
def get_browser(self): if self.remote and self.host is None: self.host = "127.0.0.1" if self.remote and self.port is None: self.port = "4444" if self.browser == "chrome": desired_capabilities = DesiredCapabilities.CHROME.copy() options = webdriver.ChromeOptions() options.add_argument("--start-maximized") options.add_argument("--ignore-certificate-errors") if self.remote: try: driver = webdriver.Remote(desired_capabilities=desired_capabilities, options=options, command_executor="http://" + self.host + ":" + self.port + "/wd/hub") except Exception: logging.exception("WebDriver Host is not available") raise ConnectionError("WebDriver Host is not available") else: driver = webdriver.Chrome(executable_path=ChromeDriverManager().install(), options=options) elif self.browser == "firefox": desired_capabilities = DesiredCapabilities.FIREFOX.copy() options = webdriver.FirefoxOptions() if self.remote: try: driver = webdriver.Remote(desired_capabilities=desired_capabilities, options=options, command_executor="http://" + self.host + ":" + self.port + "/wd/hub") except Exception: logging.exception("WebDriver Host is not available") raise ConnectionError("WebDriver Host is not available") else: driver = webdriver.Firefox(executable_path=GeckoDriverManager().install(), options=options) else: raise Exception("Provide valid browser name") driver.maximize_window() try: urlopen(self.base_url) except Exception: driver.quit() raise Exception("Target host is not available") w_driver = EventFiringWebDriver(driver, WebDriverListener()) w_driver.get(self.base_url) return w_driver
def configuration(request): web_driver = None url = excel.get_cell_value(constants.EXCEL_PATH, "BrowserSetting", 0, "URL") if request.param == "Chrome": web_driver = create_driver("Chrome", url) elif request.param == "Chrome": web_driver = create_driver("Chrome", url) driver = EventFiringWebDriver(web_driver, WebDriverListeners()) request.node.driver = driver yield if request.node.rep_call.failed: attach_screen_shot(driver, request.function.__name__) driver.close()
def setup_teardown_shop(request): global driver simple_driver = webdriver.Chrome(ChromeDriverManager().install()) driver = EventFiringWebDriver(simple_driver, MyListener()) request.cls.driver = driver yield simple_driver.quit()
def driver(request, driver_class, driver_kwargs): """Returns a WebDriver instance based on options and capabilities""" driver = driver_class(**driver_kwargs) event_listener = request.config.getoption('event_listener') if event_listener is not None: # Import the specified event listener and wrap the driver instance mod_name, class_name = event_listener.rsplit('.', 1) mod = __import__(mod_name, fromlist=[class_name]) event_listener = getattr(mod, class_name) if not isinstance(driver, EventFiringWebDriver): driver = EventFiringWebDriver(driver, event_listener()) request.node._driver = driver yield driver driver.quit()
def get_driver(path, headless=False): system = platform.system() if system == "Windows": if not path.endswith(".exe"): path += ".exe" if not os.path.exists(path): Driver.__download_driver(path, system) options = webdriver.ChromeOptions() options.add_argument("--disable-extensions") options.add_argument("--window-size=1280,1024") options.add_argument("--log-level=3") options.add_experimental_option("prefs", {"profile.default_content_setting_values.geolocation" : 1}) # geolocation permission, 0=Ask, 1=Allow, 2=Deny options.add_argument("user-agent=" + Driver.__WEB_USER_AGENT) if headless: #for this program, headless should only be used for testing or to set-up all the db-fiddles before hand options.add_argument("--headless") driver_dl_index = 1 while True: try: driver = webdriver.Chrome(path, options=options) break #driver not up to date with Chrome browser, try different ver except: Driver.__download_driver(path, system, driver_dl_index) driver_dl_index += 1 if driver_dl_index > 2: print(f'Tried downloading the {driver_dl_index} most recent chrome drivers. None match current Chrome browser version') break return EventFiringWebDriver(driver, EventListener())
def get_driver(path, device, headless): system = platform.system() if system == "Windows": if not path.endswith(".exe"): path += ".exe" if not os.path.exists(path): Driver.__download_driver(path, system) options = webdriver.ChromeOptions() options.add_argument("--disable-extensions") # options.add_argument("--no-sandbox") options.add_argument("--disable-geolocation") options.add_argument("--disable-notifications") options.add_argument("--dns-prefetch-disable") options.add_argument("--window-size=1280,1024") options.add_argument("--log-level=3") options.add_experimental_option( "prefs", {"profile.default_content_setting_values.geolocation": 2 }) # geolocation permission, 0=Ask, 1=Allow, 2=Deny if headless: options.add_argument("--headless") #else: # options.add_argument("--window-position=-2000,0") # doesnt move off screen if device == Driver.WEB_DEVICE: options.add_argument("user-agent=" + Driver.__WEB_USER_AGENT) else: options.add_argument("user-agent=" + Driver.__MOBILE_USER_AGENT) driver = webdriver.Chrome(path, chrome_options=options) driver.set_page_load_timeout(60) #if not headless: # driver.set_window_position(-2000, 0) return EventFiringWebDriver(driver, EventListener()) return driver
def driver(request, driver_class, driver_kwargs): """Returns a WebDriver instance based on options and capabilities""" driver = driver_class(**driver_kwargs) event_listener = request.config.getoption("event_listener") if event_listener is not None: # Import the specified event listener and wrap the driver instance mod_name, class_name = event_listener.rsplit(".", 1) mod = __import__(mod_name, fromlist=[class_name]) event_listener = getattr(mod, class_name) if not isinstance(driver, EventFiringWebDriver): driver = EventFiringWebDriver(driver, event_listener()) request.node._driver = driver yield driver driver.quit()
def start_browser(): if "redhat" in platform.platform(): display = Display(visible=0, size=(1920, 1080)) display.start() chrome_options = Options() chrome_options.add_argument('--disable-gpu') chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('lang=ru') chrome_options.add_argument('--window-size=1920,1080') chrome_options.add_argument('--disable-dev-shm-usage') driver = webdriver.Chrome(executable_path=CHROME_DRIVER_DICT[sys.platform], options=chrome_options) listener = LoggedListener() tests_data.shared_variables.DRIVER = EventFiringWebDriver( driver=driver, event_listener=listener) yield if sys.exc_info(): driver = tests_data.shared_variables.DRIVER allure.attach(body=driver.get_screenshot_as_png(), name='screenshot', attachment_type=AttachmentType.PNG) tests_data.shared_variables.DRIVER.quit()
def setUp(self): self.log.debug("Properties initialization") self.prop = Property() try: self.dic_prop = self.prop.load_property_files("/Users/user/PycharmProjects/BGETest/config/config.properties") self.log.debug("Properties successfully loaded.") self.log.debug(self.dic_prop) except FileNotFoundError as err: self.log.error("config.properties file not found!!!") raise ValueError("There is no config.properties file in the project directory" + str(err)) browserName = self.dic_prop.get("browser", "chrome") if browserName.lower() == "firefox": self.driver = webdriver.Firefox() self.log.debug("Object for firefox is created - " + str(self.driver)) elif browserName.lower() == "chrome": self.driver = webdriver.Chrome() self.log.debug("Object for chrome is created - " + str(self.driver)) elif browserName.lower() == "safari": self.driver = webdriver.Safari() self.log.debug("Object for safari is created - " + str(self.driver)) else: raise ValueError("Unknown browser, please check the config.properties file") self.eventListener = WebEventListener() self.driver = EventFiringWebDriver(self.driver, self.eventListener) self.driver.maximize_window() self.driver.delete_all_cookies() self.log.debug("Cookies are successfully deleted") self.driver.set_page_load_timeout(self.PAGE_LOAD_TIME) self.driver.implicitly_wait(self.IMPLICITLY_WAIT) self.driver.get(self.dic_prop.get("url")) self.longMessage = False self.log.debug(self.id()) self.screenshot = ScreenShot(self.driver) try: self.screenshotName = "./results/{}.png".format(str(self.id()).split('.')[3]) except IndexError: self.screenshotName = "./results/{}.png".format(str(self.id()).split('.')[2])
def set_up_test(request): url = helpers.get_url() web_driver = webdriver_manager.create_driver(request.param, url) driver = EventFiringWebDriver(web_driver, Listen()) request.node.driver = driver yield if request.node.rep_call.failed: helpers.attach_screen_shot(driver, request.function.__name__) web_driver.close()
class MainTest(unittest.TestCase): @classmethod def setUpClass(self): driver = Config().browser() print("Run started at:" + str(datetime.datetime.utcnow())) self.ef_driver = EventFiringWebDriver(driver, ScreenshotListener()) self.ef_driver.maximize_window() def assert_element_text(self, xpath, expected_text): """ Compare expected text with observed value from web element :param xpath: xpath to element with text to be observed :param expected_text: text what we expecting to be found :return: None """ element = self.ef_driver.find_element_by_xpath(xpath) return self.assertEqual( element.text, expected_text, f'Expected message differ from {expected_text}') def assert_element_contains_innerText(self, selector, expected_text): """ Compare expected text with observed value from web elements :param selector: css_selector to list with elements to be observed :param expected_text: text what we expecting to be found in element from the list :return: assertions for every element """ elements = self.ef_driver.find_elements_by_css_selector(selector) for element in elements: return self.assertIn( element.get_attribute('innerText'), expected_text, f'Expected message differ from {expected_text}') def assert_title(self, url, expected_text): self.ef_driver.get(url) actual_title = self.ef_driver.title self.assertEqual( expected_text, actual_title, f'Expected {expected_text} differ from actual driver,') def go_driver_give_that_page(self, driver, url, page_object): tested_page = page_object(driver) driver.get(url) return tested_page @classmethod def tearDownClass(self): self.ef_driver.close() if (self.ef_driver != None): print("Test environment destroyed.") print("Run completed at: " + str(datetime.datetime.utcnow())) """
def _get_instance(): """Return WebDriver instance based on given options. """ web_driver = driver_factory.get_instance() if event_listener and not isinstance(web_driver, EventFiringWebDriver): web_driver = EventFiringWebDriver(web_driver, event_listener()) request.node._driver = web_driver request.addfinalizer(web_driver.quit) return web_driver
def browser(logger, request): selected_browser = request.config.getoption('--browser') browser = EventFiringWebDriver( webdriver.Remote( command_executor=f'http://{env.str("SELENOID_HOST")}:4444/wd/hub', desired_capabilities={ 'browserName': selected_browser, 'acceptInsecureCerts': True }, ), EventListener(logging.getLogger('Browser')), ) request.addfinalizer(browser.quit) browser.get(f'http://{env.str("PRESTASHOP_HOST")}') # Ожидание на случай первоначальной установки WebDriverWait(browser, 100).until(EC.visibility_of_element_located(HEADER)) return browser
def get_driver(cls, device, headless, cookies) -> EventFiringWebDriver: # raspberry pi: assumes driver already installed via `sudo apt-get install chromium-chromedriver` if platform.machine() in ["armv7l","aarch64"]: driver_path = "/usr/lib/chromium-browser/chromedriver" # all others else: if not os.path.exists(cls.DRIVERS_DIR): os.mkdir(cls.DRIVERS_DIR) driver_path = os.path.join(cls.DRIVERS_DIR, cls.driver_name) if not os.path.exists(driver_path): cls.__download_driver() # we start at dl_try_count = 1 b/c we already downloaded the most recent version dl_try_count = 1 MAX_TRIES = 3 is_dl_success = False options = cls.add_driver_options(device, headless, cookies) while not is_dl_success: try: driver = cls.WebDriverCls(driver_path, options=options) is_dl_success = True except SessionNotCreatedException as se: error_msg = str(se).lower() if cls.VERSION_MISMATCH_STR not in error_msg: raise SessionNotCreatedException(error_msg) # driver not up to date with Chrome browser, try different version if dl_try_count == MAX_TRIES: raise SessionNotCreatedException( f'Tried downloading the {dl_try_count} most recent drivers. None match your browser version. Aborting now, please update your browser.') cls.__download_driver(dl_try_count) dl_try_count += 1 # WebDriverException is Selenium generic exception except WebDriverException as wde: error_msg = str(wde) # handle cookie error if "DevToolsActivePort file doesn't exist" in error_msg: #print('Driver error using cookies option. Trying without cookies.') options = cls.add_driver_options(device, headless, cookies=False) # elif 'x' in error_msg: else: raise WebDriverException(error_msg) # if not headless: # driver.set_window_position(-2000, 0) return EventFiringWebDriver(driver, EventListener())
def start_browser(): configs = Properties() configs.load(open(os.path.join(PROJECT_ROOT, 'app.properties'), 'rb')) browser_name = configs.get("browser").data options = webdriver.ChromeOptions() options.add_argument('--no-sandbox') options.add_argument('--disable-gpu') options.add_argument('--window-size=1920,1080') options.add_argument('lang=ru') if browser_name == "chrome": driver = webdriver.Chrome( executable_path=CHROME_DRIVER_DICT[sys.platform], options=options) elif browser_name == "opera": driver = webdriver.Opera( executable_path=OPERA_DRIVER_DICT[sys.platform], options=options) driver.maximize_window() elif browser_name == "yandex": driver = webdriver.Opera( executable_path=YANDEX_DRIVER_DICT[sys.platform], options=options) driver.maximize_window() else: driver = webdriver.Chrome( executable_path=CHROME_DRIVER_DICT[sys.platform], options=options) listener = LoggedListener() driver = EventFiringWebDriver(driver=driver, event_listener=listener) yield driver if sys.exc_info(): allure.attach(body=driver.get_screenshot_as_png(), name='screenshot', attachment_type=AttachmentType.PNG) driver.quit()
def start_browser(browser_name, url): web_driver = None if browser_name == "chrome": web_driver = webdriver.Chrome( executable_path=".\\resources\\drivers\\chromedriver") elif browser_name == "firefox": web_driver = webdriver.Firefox( executable_path=".\\resources\\drivers\\geckodriver") driver = EventFiringWebDriver(web_driver, MyListener()) driver.implicitly_wait(properties.get_implicit_wait()) driver.maximize_window() driver.get(url) return driver
def __init__(self, driver): super().__init__(EventFiringWebDriver(driver, LogEventListener())) # 支付方式列表 self.payment_method = { 1: 'Bank card', 2: 'Alipay', 3: 'WeChat', 4: 'PayPal', 5: 'FPS', 6: 'PayMe', 7: 'Faspay', 8: 'Line Pay', 9: 'Cash' }
def start_webdriver_client(self): capabilities = {} for c in self.capabilities: name, value = c.split(':') # handle integer capabilities if value.isdigit(): value = int(value) # handle boolean capabilities elif value.lower() in ['true', 'false']: value = value.lower() == 'true' capabilities.update({name: value}) if self.proxy_host and self.proxy_port: proxy = Proxy() proxy.http_proxy = '%s:%s' % (self.proxy_host, self.proxy_port) proxy.ssl_proxy = proxy.http_proxy proxy.add_to_capabilities(capabilities) profile = None if self.driver.upper() == 'REMOTE': capabilities.update(getattr(webdriver.DesiredCapabilities, self.browser_name.upper())) if json.loads(self.chrome_options) or self.extension_paths: capabilities = self.create_chrome_options( self.chrome_options, self.extension_paths).to_capabilities() if self.browser_name.upper() == 'FIREFOX': profile = self.create_firefox_profile( self.firefox_preferences, self.profile_path, self.extension_paths) if self.browser_version: capabilities['version'] = self.browser_version capabilities['platform'] = self.platform.upper() executor = 'http://%s:%s/wd/hub' % (self.host, self.port) try: self.selenium = webdriver.Remote(command_executor=executor, desired_capabilities=capabilities or None, browser_profile=profile) except AttributeError: valid_browsers = [attr for attr in dir(webdriver.DesiredCapabilities) if not attr.startswith('__')] raise AttributeError("Invalid browser name: '%s'. Valid options are: %s" % (self.browser_name, ', '.join(valid_browsers))) elif self.driver.upper() == 'CHROME': options = None if self.chrome_options or self.extension_paths: options = self.create_chrome_options( self.chrome_options, self.extension_paths) if self.chrome_path: self.selenium = webdriver.Chrome(executable_path=self.chrome_path, chrome_options=options, desired_capabilities=capabilities or None) else: self.selenium = webdriver.Chrome(chrome_options=options, desired_capabilities=capabilities or None) elif self.driver.upper() == 'FIREFOX': binary = self.firefox_path and FirefoxBinary(self.firefox_path) or None profile = self.create_firefox_profile( self.firefox_preferences, self.profile_path, self.extension_paths) self.selenium = webdriver.Firefox( firefox_binary=binary, firefox_profile=profile, capabilities=capabilities or None) elif self.driver.upper() == 'IE': self.selenium = webdriver.Ie() elif self.driver.upper() == 'OPERA': capabilities.update(webdriver.DesiredCapabilities.OPERA) self.selenium = webdriver.Opera(executable_path=self.opera_path, desired_capabilities=capabilities) else: self.selenium = getattr(webdriver, self.driver)() if self.event_listener is not None and not isinstance(self.selenium, EventFiringWebDriver): self.selenium = EventFiringWebDriver(self.selenium, self.event_listener())
class Client(object): def __init__(self, test_id, options): self.test_id = test_id self.host = options.host self.port = options.port self.base_url = options.base_url self.api = options.api.upper() self.webdriver = self.api == 'WEBDRIVER' self.rc = self.api == 'RC' if self.webdriver: self.driver = options.driver self.capabilities = options.capabilities or [] self.chrome_path = options.chrome_path self.chrome_options = options.chrome_options or '{}' self.firefox_path = options.firefox_path self.firefox_preferences = options.firefox_preferences or [] self.profile_path = options.profile_path self.extension_paths = options.extension_paths or [] self.opera_path = options.opera_path self.timeout = options.webqatimeout if self.driver.upper() == 'REMOTE': self.browser_name = options.browser_name self.browser_version = options.browser_version self.platform = options.platform if options.event_listener: mod_name, class_name = options.event_listener.rsplit('.', 1) mod = __import__(mod_name, fromlist=[class_name]) self.event_listener = getattr(mod, class_name) else: self.event_listener = None if self.rc: self.browser = options.environment or options.browser self.timeout = options.webqatimeout * 1000 self.capture_network = options.capture_network self.default_implicit_wait = 10 self.sauce_labs_credentials = options.sauce_labs_credentials_file self.assume_untrusted = options.assume_untrusted self.proxy_host = options.proxy_host self.proxy_port = options.proxy_port def check_usage(self): self.check_basic_usage() if self.webdriver: self.check_webdriver_usage() else: self.check_rc_usage() def check_basic_usage(self): if not self.base_url: raise pytest.UsageError('--baseurl must be specified.') def check_webdriver_usage(self): if self.driver.upper() == 'REMOTE': if not self.browser_name: raise pytest.UsageError("--browsername must be specified when using the 'webdriver' api.") if not self.platform: raise pytest.UsageError("--platform must be specified when using the 'webdriver' api.") def check_rc_usage(self): if not self.browser: raise pytest.UsageError("--browser or --environment must be specified when using the 'rc' api.") def start(self): self.check_usage() if self.webdriver: self.start_webdriver_client() self.selenium.implicitly_wait(self.default_implicit_wait) else: self.start_rc_client() self.selenium.set_timeout(self.timeout) self.selenium.set_context(self.test_id) def start_webdriver_client(self): capabilities = {} for c in self.capabilities: name, value = c.split(':') # handle integer capabilities if value.isdigit(): value = int(value) # handle boolean capabilities elif value.lower() in ['true', 'false']: value = value.lower() == 'true' capabilities.update({name: value}) if self.proxy_host and self.proxy_port: proxy = Proxy() proxy.http_proxy = '%s:%s' % (self.proxy_host, self.proxy_port) proxy.ssl_proxy = proxy.http_proxy proxy.add_to_capabilities(capabilities) profile = None if self.driver.upper() == 'REMOTE': capabilities.update(getattr(webdriver.DesiredCapabilities, self.browser_name.upper())) if json.loads(self.chrome_options) or self.extension_paths: capabilities = self.create_chrome_options( self.chrome_options, self.extension_paths).to_capabilities() if self.browser_name.upper() == 'FIREFOX': profile = self.create_firefox_profile( self.firefox_preferences, self.profile_path, self.extension_paths) if self.browser_version: capabilities['version'] = self.browser_version capabilities['platform'] = self.platform.upper() executor = 'http://%s:%s/wd/hub' % (self.host, self.port) try: self.selenium = webdriver.Remote(command_executor=executor, desired_capabilities=capabilities or None, browser_profile=profile) except AttributeError: valid_browsers = [attr for attr in dir(webdriver.DesiredCapabilities) if not attr.startswith('__')] raise AttributeError("Invalid browser name: '%s'. Valid options are: %s" % (self.browser_name, ', '.join(valid_browsers))) elif self.driver.upper() == 'CHROME': options = None if self.chrome_options or self.extension_paths: options = self.create_chrome_options( self.chrome_options, self.extension_paths) if self.chrome_path: self.selenium = webdriver.Chrome(executable_path=self.chrome_path, chrome_options=options, desired_capabilities=capabilities or None) else: self.selenium = webdriver.Chrome(chrome_options=options, desired_capabilities=capabilities or None) elif self.driver.upper() == 'FIREFOX': binary = self.firefox_path and FirefoxBinary(self.firefox_path) or None profile = self.create_firefox_profile( self.firefox_preferences, self.profile_path, self.extension_paths) self.selenium = webdriver.Firefox( firefox_binary=binary, firefox_profile=profile, capabilities=capabilities or None) elif self.driver.upper() == 'IE': self.selenium = webdriver.Ie() elif self.driver.upper() == 'OPERA': capabilities.update(webdriver.DesiredCapabilities.OPERA) self.selenium = webdriver.Opera(executable_path=self.opera_path, desired_capabilities=capabilities) else: self.selenium = getattr(webdriver, self.driver)() if self.event_listener is not None and not isinstance(self.selenium, EventFiringWebDriver): self.selenium = EventFiringWebDriver(self.selenium, self.event_listener()) def start_rc_client(self): self.selenium = selenium(self.host, str(self.port), self.browser, self.base_url) if self.capture_network: self.selenium.start('captureNetworkTraffic=true') else: self.selenium.start() @property def session_id(self): if self.webdriver: return self.selenium.session_id else: return self.selenium.get_eval('selenium.sessionId') def create_firefox_profile(self, preferences, profile_path, extensions): profile = webdriver.FirefoxProfile(profile_path) for p in preferences: name, value = p.split(':') # handle integer preferences if value.isdigit(): value = int(value) # handle boolean preferences elif value.lower() in ['true', 'false']: value = value.lower() == 'true' profile.set_preference(name, value) profile.assume_untrusted_cert_issuer = self.assume_untrusted profile.update_preferences() for extension in extensions: profile.add_extension(extension) return profile def create_chrome_options(self, preferences, extensions): options = webdriver.ChromeOptions() options_from_json = json.loads(preferences) if 'arguments' in options_from_json: for args_ in options_from_json['arguments']: options.add_argument(args_) if 'binary_location' in options_from_json: options.binary_location = options_from_json['binary_location'] for extension in extensions: options.add_extension(extension) return options @property def screenshot(self): try: if self.webdriver: screenshot = self.selenium.get_screenshot_as_base64() else: screenshot = self.selenium.capture_entire_page_screenshot_to_string('') return screenshot except: return None @property def html(self): try: if self.webdriver: html = self.selenium.page_source else: html = self.selenium.get_html_source() return html.encode('utf-8') except: return None @property def log(self): try: if self.rc: return self.selenium.get_log().encode('utf-8') except: return None @property def network_traffic(self): try: if self.rc and self.capture_network: return self.selenium.captureNetworkTraffic('json') except: return None @property def url(self): try: if self.webdriver: url = self.selenium.current_url else: url = self.selenium.get_location() return url except: return None def stop(self): try: if self.webdriver: self.selenium.quit() else: self.selenium.stop() except: pass