How to use desired_capabilities method in Selene

Best Python code snippet using selene_python

webdrivertools.py

Source:webdrivertools.py Github

copy

Full Screen

1# Copyright 2008-2011 Nokia Networks2# Copyright 2011-2016 Ryan Tomac, Ed Manlove and contributors3# Copyright 2016- Robot Framework Foundation4#5# Licensed under the Apache License, Version 2.0 (the "License");6# you may not use this file except in compliance with the License.7# You may obtain a copy of the License at8#9# http://www.apache.org/licenses/LICENSE-2.010#11# Unless required by applicable law or agreed to in writing, software12# distributed under the License is distributed on an "AS IS" BASIS,13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14# See the License for the specific language governing permissions and15# limitations under the License.16import os17import warnings18from robot.utils import ConnectionCache19from selenium import webdriver20from SeleniumLibrary.utils import is_falsy, is_truthy, SELENIUM_VERSION21class WebDriverCreator(object):22 browser_names = {23 'googlechrome': "chrome",24 'gc': "chrome",25 'chrome': "chrome",26 'headlesschrome': 'headless_chrome',27 'ff': 'firefox',28 'firefox': 'firefox',29 'headlessfirefox': 'headless_firefox',30 'ie': 'ie',31 'internetexplorer': 'ie',32 'edge': 'edge',33 'opera': 'opera',34 'safari': 'safari',35 'phantomjs': 'phantomjs',36 'htmlunit': 'htmlunit',37 'htmlunitwithjs': 'htmlunit_with_js',38 'android': 'android',39 'iphone': 'iphone'40 }41 def __init__(self, log_dir):42 self.log_dir = log_dir43 def create_driver(self, browser, desired_capabilities, remote_url,44 profile_dir=None):45 creation_method = self._get_creator_method(browser)46 desired_capabilities = self._parse_capabilities(desired_capabilities, browser)47 if (creation_method == self.create_firefox48 or creation_method == self.create_headless_firefox):49 return creation_method(desired_capabilities, remote_url,50 profile_dir)51 return creation_method(desired_capabilities, remote_url)52 def _get_creator_method(self, browser):53 browser = browser.lower().replace(' ', '')54 if browser in self.browser_names:55 return getattr(self, 'create_{}'.format(self.browser_names[browser]))56 raise ValueError('{} is not a supported browser.'.format(browser))57 def _parse_capabilities(self, capabilities, browser=None):58 if is_falsy(capabilities):59 return {}60 if not isinstance(capabilities, dict):61 capabilities = self._string_to_dict(capabilities)62 browser_alias = {'googlechrome': "chrome", 'gc': "chrome",63 'headlesschrome': 'chrome', 'ff': 'firefox',64 'headlessfirefox': 'firefox',65 'internetexplorer': 'ie'}66 browser = browser_alias.get(browser, browser)67 if browser in ['ie', 'firefox', 'edge']:68 return {'capabilities': capabilities}69 return {'desired_capabilities': capabilities}70 def _string_to_dict(self, capabilities):71 desired_capabilities = {}72 for part in capabilities.split(','):73 key, value = part.split(':')74 desired_capabilities[key.strip()] = value.strip()75 return desired_capabilities76 def create_chrome(self, desired_capabilities, remote_url, options=None):77 if is_truthy(remote_url):78 if not desired_capabilities:79 desired_capabilities = {'desired_capabilities': webdriver.DesiredCapabilities.CHROME.copy()}80 return self._remote(desired_capabilities, remote_url, options=options)81 if SELENIUM_VERSION.major >= 3 and SELENIUM_VERSION.minor >= 8:82 return webdriver.Chrome(options=options, **desired_capabilities)83 return webdriver.Chrome(**desired_capabilities)84 def create_headless_chrome(self, desired_capabilities, remote_url):85 if SELENIUM_VERSION.major >= 3 and SELENIUM_VERSION.minor >= 8:86 options = webdriver.ChromeOptions()87 options.set_headless()88 else:89 options = None90 return self.create_chrome(desired_capabilities, remote_url, options)91 def create_firefox(self, desired_capabilities, remote_url, ff_profile_dir,92 options=None):93 profile = self._get_ff_profile(ff_profile_dir)94 if is_truthy(remote_url):95 if not desired_capabilities:96 desired_capabilities = {'desired_capabilities': webdriver.DesiredCapabilities.FIREFOX.copy()}97 return self._remote(desired_capabilities, remote_url,98 profile, options)99 desired_capabilities.update(self._geckodriver_log)100 if SELENIUM_VERSION.major >= 3 and SELENIUM_VERSION.minor >= 8:101 return webdriver.Firefox(options=options, firefox_profile=profile,102 **desired_capabilities)103 return webdriver.Firefox(firefox_profile=profile,104 **desired_capabilities)105 def _get_ff_profile(self, ff_profile_dir):106 if is_falsy(ff_profile_dir):107 return webdriver.FirefoxProfile()108 return webdriver.FirefoxProfile(ff_profile_dir)109 @property110 def _geckodriver_log(self):111 if SELENIUM_VERSION.major >= 3:112 return {'log_path': os.path.join(self.log_dir, 'geckodriver.log')}113 return {}114 def create_headless_firefox(self, desired_capabilities, remote_url,115 ff_profile_dir):116 if SELENIUM_VERSION.major >= 3 and SELENIUM_VERSION.minor >= 8:117 options = webdriver.FirefoxOptions()118 options.set_headless()119 else:120 options = None121 return self.create_firefox(desired_capabilities, remote_url,122 ff_profile_dir, options)123 def create_ie(self, desired_capabilities, remote_url):124 if is_truthy(remote_url):125 if not desired_capabilities:126 ie = webdriver.DesiredCapabilities.INTERNETEXPLORER.copy()127 desired_capabilities = {'desired_capabilities': ie}128 return self._remote(desired_capabilities, remote_url)129 return webdriver.Ie(**desired_capabilities)130 def create_edge(self, desired_capabilities, remote_url):131 if is_truthy(remote_url):132 if not desired_capabilities:133 edge = webdriver.DesiredCapabilities.EDGE.copy()134 desired_capabilities = {'desired_capabilities': edge}135 return self._remote(desired_capabilities, remote_url)136 return webdriver.Edge(**desired_capabilities)137 def create_opera(self, desired_capabilities, remote_url):138 if is_truthy(remote_url):139 if not desired_capabilities:140 opera = webdriver.DesiredCapabilities.OPERA.copy()141 desired_capabilities = {'desired_capabilities': opera}142 return self._remote(desired_capabilities, remote_url)143 return webdriver.Opera(**desired_capabilities)144 def create_safari(self, desired_capabilities, remote_url):145 if is_truthy(remote_url):146 if not desired_capabilities:147 caps = webdriver.DesiredCapabilities.SAFARI.copy()148 desired_capabilities = {'desired_capabilities': caps}149 return self._remote(desired_capabilities, remote_url)150 return webdriver.Safari(**desired_capabilities)151 def create_phantomjs(self, desired_capabilities, remote_url):152 warnings.warn('SeleniumLibrary support for PhantomJS has been deprecated, '153 'please use headlesschrome or headlessfirefox instead.')154 if is_truthy(remote_url):155 if not desired_capabilities:156 caps = webdriver.DesiredCapabilities.PHANTOMJS.copy()157 desired_capabilities = {'desired_capabilities': caps}158 return self._remote(desired_capabilities, remote_url)159 return webdriver.PhantomJS(**desired_capabilities)160 def create_htmlunit(self, desired_capabilities, remote_url):161 if not desired_capabilities:162 desired_capabilities['desired_capabilities'] = webdriver.DesiredCapabilities.HTMLUNIT163 return self._remote(desired_capabilities, remote_url)164 def create_htmlunit_with_js(self, desired_capabilities, remote_url):165 if not desired_capabilities:166 desired_capabilities['desired_capabilities'] = webdriver.DesiredCapabilities.HTMLUNITWITHJS167 return self._remote(desired_capabilities, remote_url)168 def create_android(self, desired_capabilities, remote_url):169 if not desired_capabilities:170 desired_capabilities['desired_capabilities'] = webdriver.DesiredCapabilities.ANDROID171 return self._remote(desired_capabilities, remote_url)172 def create_iphone(self, desired_capabilities, remote_url):173 if not desired_capabilities:174 desired_capabilities['desired_capabilities'] = webdriver.DesiredCapabilities.IPHONE175 return self._remote(desired_capabilities, remote_url)176 def _remote(self, desired_capabilities, remote_url,177 profile_dir=None, options=None):178 remote_url = str(remote_url)179 if 'capabilities' in desired_capabilities:180 desired_capabilities['desired_capabilities'] = desired_capabilities.pop('capabilities')181 if SELENIUM_VERSION.major >= 3 and SELENIUM_VERSION.minor >= 8:182 return webdriver.Remote(command_executor=remote_url,183 browser_profile=profile_dir, options=options,184 **desired_capabilities)185 return webdriver.Remote(command_executor=remote_url,186 browser_profile=profile_dir,187 **desired_capabilities)188class WebDriverCache(ConnectionCache):189 def __init__(self):190 ConnectionCache.__init__(self, no_current_msg='No current browser')191 self._closed = set()192 @property193 def drivers(self):194 return self._connections195 @property196 def active_drivers(self):197 open_drivers = []198 for driver in self._connections:199 if driver not in self._closed:200 open_drivers.append(driver)201 return open_drivers202 def close(self):203 if self.current:204 driver = self.current205 driver.quit()206 self.current = self._no_current207 self._closed.add(driver)208 def close_all(self):209 for driver in self._connections:210 if driver not in self._closed:211 driver.quit()212 self.empty_cache()...

Full Screen

Full Screen

browser.py

Source:browser.py Github

copy

Full Screen

...34 base64string = encodestring('{}:{}'.format(config['username'], config['access-key']))[:-1]35 headers = {"Authorization": "Basic {}".format(base64string)}36 result = requests.put(url, data=body_content, headers=headers)37 return result.status_code == 20038def make_saucelabs_desired_capabilities():39 """40 Returns a DesiredCapabilities object corresponding to the environment sauce parameters41 """42 desired_capabilities = settings.SAUCE.get('BROWSER', DesiredCapabilities.CHROME)43 desired_capabilities['platform'] = settings.SAUCE.get('PLATFORM')44 desired_capabilities['version'] = settings.SAUCE.get('VERSION')45 desired_capabilities['device-type'] = settings.SAUCE.get('DEVICE')46 desired_capabilities['name'] = settings.SAUCE.get('SESSION')47 desired_capabilities['build'] = settings.SAUCE.get('BUILD')48 desired_capabilities['video-upload-on-pass'] = False49 desired_capabilities['sauce-advisor'] = False50 desired_capabilities['capture-html'] = True51 desired_capabilities['record-screenshots'] = True52 desired_capabilities['selenium-version'] = "2.34.0"53 desired_capabilities['max-duration'] = 360054 desired_capabilities['public'] = 'public restricted'55 return desired_capabilities56@before.harvest57def initial_setup(server):58 """59 Launch the browser once before executing the tests.60 """61 world.absorb(settings.LETTUCE_SELENIUM_CLIENT, 'LETTUCE_SELENIUM_CLIENT')62 if world.LETTUCE_SELENIUM_CLIENT == 'local':63 browser_driver = getattr(settings, 'LETTUCE_BROWSER', 'chrome')64 if browser_driver == 'chrome':65 desired_capabilities = DesiredCapabilities.CHROME66 desired_capabilities['loggingPrefs'] = {67 'browser': 'ALL',68 }69 else:70 desired_capabilities = {}71 # There is an issue with ChromeDriver2 r195627 on Ubuntu72 # in which we sometimes get an invalid browser session.73 # This is a work-around to ensure that we get a valid session.74 success = False75 num_attempts = 076 while (not success) and num_attempts < MAX_VALID_BROWSER_ATTEMPTS:77 # Load the browser and try to visit the main page78 # If the browser couldn't be reached or79 # the browser session is invalid, this will80 # raise a WebDriverException81 try:82 if browser_driver == 'firefox':83 # Lettuce initializes differently for firefox, and sending84 # desired_capabilities will not work. So initialize without85 # sending desired_capabilities.86 world.browser = Browser(browser_driver)87 else:88 world.browser = Browser(browser_driver, desired_capabilities=desired_capabilities)89 world.browser.driver.set_script_timeout(GLOBAL_SCRIPT_TIMEOUT)90 world.visit('/')91 except WebDriverException:92 LOGGER.warn("Error acquiring %s browser, retrying", browser_driver, exc_info=True)93 if hasattr(world, 'browser'):94 world.browser.quit()95 num_attempts += 196 else:97 success = True98 # If we were unable to get a valid session within the limit of attempts,99 # then we cannot run the tests.100 if not success:101 raise IOError("Could not acquire valid {driver} browser session.".format(driver=browser_driver))102 world.absorb(0, 'IMPLICIT_WAIT')103 world.browser.driver.set_window_size(1280, 1024)104 elif world.LETTUCE_SELENIUM_CLIENT == 'saucelabs':105 config = get_saucelabs_username_and_key()106 world.browser = Browser(107 'remote',108 url="http://{}:{}@ondemand.saucelabs.com:80/wd/hub".format(config['username'], config['access-key']),109 **make_saucelabs_desired_capabilities()110 )111 world.absorb(30, 'IMPLICIT_WAIT')112 world.browser.set_script_timeout(GLOBAL_SCRIPT_TIMEOUT)113 elif world.LETTUCE_SELENIUM_CLIENT == 'grid':114 world.browser = Browser(115 'remote',116 url=settings.SELENIUM_GRID.get('URL'),117 browser=settings.SELENIUM_GRID.get('BROWSER'),118 )119 world.absorb(30, 'IMPLICIT_WAIT')120 world.browser.driver.set_script_timeout(GLOBAL_SCRIPT_TIMEOUT)121 else:122 raise Exception("Unknown selenium client '{}'".format(world.LETTUCE_SELENIUM_CLIENT))123 world.browser.driver.implicitly_wait(world.IMPLICIT_WAIT)...

Full Screen

Full Screen

capabilities_parser.py

Source:capabilities_parser.py Github

copy

Full Screen

1import re2def get_desired_capabilities(cap_file):3 if not cap_file.endswith('.py'):4 raise Exception("\n\n`%s` is not a Python file!\n\n" % cap_file)5 f = open(cap_file, 'r')6 all_code = f.read()7 f.close()8 desired_capabilities = {}9 num_capabilities = 010 code_lines = all_code.split('\n')11 for line in code_lines:12 if "desired_cap = {" in line:13 line = line.split("desired_cap = {")[1]14 # 'KEY' : 'VALUE'15 data = re.match(r"^\s*'([\S\s]+)'\s*:\s*'([\S\s]+)'\s*[,}]?\s*$", line)16 if data:...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Selene automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful