Best Python code snippet using toolium_python
config_driver.py
Source:config_driver.py  
...87        """88        driver_name = self.utils.get_driver_name()89        if driver_name in ('android', 'ios', 'iphone'):90            # Create local appium driver91            driver = self._setup_appium()92        else:93            driver_setup = {94                'firefox': self._setup_firefox,95                'chrome': self._setup_chrome,96                'safari': self._setup_safari,97                'opera': self._setup_opera,98                'iexplore': self._setup_explorer,99                'edge': self._setup_edge,100                'phantomjs': self._setup_phantomjs101            }102            try:103                driver_setup_method = driver_setup[driver_name]104            except KeyError:105                raise Exception('Unknown driver {0}'.format(driver_name))106            # Get driver capabilities107            capabilities = self._get_capabilities_from_driver_type(driver_name)108            self._add_capabilities_from_properties(capabilities, 'Capabilities')109            # Create local selenium driver110            driver = driver_setup_method(capabilities)111        return driver112    @staticmethod113    def _get_capabilities_from_driver_type(driver_name):114        """Create initial driver capabilities115        :params driver_name: name of selected driver116        :returns: capabilities dictionary117        """118        if driver_name == 'firefox':119            capabilities = DesiredCapabilities.FIREFOX.copy()120        elif driver_name == 'chrome':121            capabilities = DesiredCapabilities.CHROME.copy()122        elif driver_name == 'safari':123            capabilities = DesiredCapabilities.SAFARI.copy()124        elif driver_name == 'opera':125            capabilities = DesiredCapabilities.OPERA.copy()126        elif driver_name == 'iexplore':127            capabilities = DesiredCapabilities.INTERNETEXPLORER.copy()128        elif driver_name == 'edge':129            capabilities = DesiredCapabilities.EDGE.copy()130        elif driver_name == 'phantomjs':131            capabilities = DesiredCapabilities.PHANTOMJS.copy()132        elif driver_name in ('android', 'ios', 'iphone'):133            capabilities = {}134        else:135            raise Exception('Unknown driver {0}'.format(driver_name))136        return capabilities137    def _add_capabilities_from_driver_type(self, capabilities):138        """Extract version and platform from driver type and add them to capabilities139        :param capabilities: capabilities dict140        """141        driver_type = self.config.get('Driver', 'type')142        try:143            capabilities['version'] = driver_type.split('-')[1]144        except IndexError:145            pass146        try:147            platforms_list = {'xp': 'XP',148                              'windows_7': 'VISTA',149                              'windows_8': 'WIN8',150                              'windows_10': 'WIN10',151                              'linux': 'LINUX',152                              'android': 'ANDROID',153                              'mac': 'MAC'}154            capabilities['platform'] = platforms_list.get(driver_type.split('-')[3], driver_type.split('-')[3])155        except IndexError:156            pass157    def _add_capabilities_from_properties(self, capabilities, section):158        """Add capabilities from properties file159        :param capabilities: capabilities object160        :param section: properties section161        """162        cap_type = {'Capabilities': 'server', 'AppiumCapabilities': 'Appium server'}163        try:164            for cap, cap_value in dict(self.config.items(section)).items():165                self.logger.debug("Added %s capability: %s = %s", cap_type[section], cap, cap_value)166                cap_value = cap_value if cap == 'version' else self._convert_property_type(cap_value)167                self._update_dict(capabilities, {cap: cap_value}, initial_key=cap)168        except NoSectionError:169            pass170    def _setup_firefox(self, capabilities):171        """Setup Firefox webdriver172        :param capabilities: capabilities object173        :returns: a new local Firefox driver174        """175        if capabilities.get("marionette"):176            gecko_driver = self.config.get('Driver', 'gecko_driver_path')177            self.logger.debug("Gecko driver path given in properties: %s", gecko_driver)178        else:179            gecko_driver = None180        # Get Firefox binary181        firefox_binary = self.config.get_optional('Firefox', 'binary')182        firefox_options = FirefoxOptions()183        if self.config.getboolean_optional('Driver', 'headless'):184            self.logger.debug("Running Firefox in headless mode")185            firefox_options.add_argument('-headless')186        self._add_firefox_arguments(firefox_options)187        if firefox_binary:188            firefox_options.binary = firefox_binary189        log_path = os.path.join(DriverWrappersPool.output_directory, 'geckodriver.log')190        try:191            # Selenium 3192            return webdriver.Firefox(firefox_profile=self._create_firefox_profile(), capabilities=capabilities,193                                     executable_path=gecko_driver, firefox_options=firefox_options, log_path=log_path)194        except TypeError:195            # Selenium 2196            return webdriver.Firefox(firefox_profile=self._create_firefox_profile(), capabilities=capabilities,197                                     executable_path=gecko_driver, firefox_options=firefox_options)198    def _add_firefox_arguments(self, options):199        """Add Firefox arguments from properties file200        :param options: Firefox options object201        """202        try:203            for pref, pref_value in dict(self.config.items('FirefoxArguments')).items():204                pref_value = '={}'.format(pref_value) if pref_value else ''205                self.logger.debug("Added Firefox argument: %s%s", pref, pref_value)206                options.add_argument('{}{}'.format(pref, self._convert_property_type(pref_value)))207        except NoSectionError:208            pass209    def _create_firefox_profile(self):210        """Create and configure a firefox profile211        :returns: firefox profile212        """213        # Get Firefox profile214        profile_directory = self.config.get_optional('Firefox', 'profile')215        if profile_directory:216            self.logger.debug("Using firefox profile: %s", profile_directory)217        # Create Firefox profile218        profile = webdriver.FirefoxProfile(profile_directory=profile_directory)219        profile.native_events_enabled = True220        # Add Firefox preferences221        try:222            for pref, pref_value in dict(self.config.items('FirefoxPreferences')).items():223                self.logger.debug("Added firefox preference: %s = %s", pref, pref_value)224                profile.set_preference(pref, self._convert_property_type(pref_value))225            profile.update_preferences()226        except NoSectionError:227            pass228        # Add Firefox extensions229        try:230            for pref, pref_value in dict(self.config.items('FirefoxExtensions')).items():231                self.logger.debug("Added firefox extension: %s = %s", pref, pref_value)232                profile.add_extension(pref_value)233        except NoSectionError:234            pass235        return profile236    @staticmethod237    def _convert_property_type(value):238        """Converts the string value in a boolean, integer or string239        :param value: string value240        :returns: boolean, integer or string value241        """242        if value in ('true', 'True'):243            formatted_value = True244        elif value in ('false', 'False'):245            formatted_value = False246        elif ((str(value).startswith('{') and str(value).endswith('}'))247              or (str(value).startswith('[') and str(value).endswith(']'))):248            formatted_value = ast.literal_eval(value)249        else:250            try:251                formatted_value = int(value)252            except ValueError:253                formatted_value = value254        return formatted_value255    def _setup_chrome(self, capabilities):256        """Setup Chrome webdriver257        :param capabilities: capabilities object258        :returns: a new local Chrome driver259        """260        chrome_driver = self.config.get('Driver', 'chrome_driver_path')261        self.logger.debug("Chrome driver path given in properties: %s", chrome_driver)262        self._add_chrome_options_to_capabilities(capabilities)263        return webdriver.Chrome(chrome_driver, desired_capabilities=capabilities)264    def _create_chrome_options(self):265        """Create and configure a chrome options object266        :returns: chrome options object267        """268        # Get Chrome binary269        chrome_binary = self.config.get_optional('Chrome', 'binary')270        # Create Chrome options271        options = webdriver.ChromeOptions()272        if self.config.getboolean_optional('Driver', 'headless'):273            self.logger.debug("Running Chrome in headless mode")274            options.add_argument('--headless')275            if os.name == 'nt':  # Temporarily needed if running on Windows.276                options.add_argument('--disable-gpu')277        if chrome_binary is not None:278            options.binary_location = chrome_binary279        # Add Chrome preferences, mobile emulation options and chrome arguments280        self._add_chrome_options(options, 'prefs')281        self._add_chrome_options(options, 'mobileEmulation')282        self._add_chrome_arguments(options)283        return options284    def _add_chrome_options(self, options, option_name):285        """Add Chrome options from properties file286        :param options: chrome options object287        :param option_name: chrome option name288        """289        options_conf = {'prefs': {'section': 'ChromePreferences', 'message': 'preference'},290                        'mobileEmulation': {'section': 'ChromeMobileEmulation', 'message': 'mobile emulation option'}}291        option_value = dict()292        try:293            for key, value in dict(self.config.items(options_conf[option_name]['section'])).items():294                self.logger.debug("Added chrome %s: %s = %s", options_conf[option_name]['message'], key, value)295                option_value[key] = self._convert_property_type(value)296            if len(option_value) > 0:297                options.add_experimental_option(option_name, option_value)298        except NoSectionError:299            pass300    def _add_chrome_arguments(self, options):301        """Add Chrome arguments from properties file302        :param options: chrome options object303        """304        try:305            for pref, pref_value in dict(self.config.items('ChromeArguments')).items():306                pref_value = '={}'.format(pref_value) if pref_value else ''307                self.logger.debug("Added chrome argument: %s%s", pref, pref_value)308                options.add_argument('{}{}'.format(pref, self._convert_property_type(pref_value)))309        except NoSectionError:310            pass311    def _add_chrome_options_to_capabilities(self, capabilities):312        """Add Chrome options to capabilities313        :param capabilities: dictionary with driver capabilities314        """315        chrome_capabilities = self._create_chrome_options().to_capabilities()316        options_key = None317        if 'goog:chromeOptions' in chrome_capabilities:318            options_key = 'goog:chromeOptions'319        elif 'chromeOptions' in chrome_capabilities:320            # Selenium 3.5.3 and older321            options_key = 'chromeOptions'322        if options_key:323            self._update_dict(capabilities, chrome_capabilities, initial_key=options_key)324    def _update_dict(self, initial, update, initial_key=None):325        """ Update a initial dict with another dict values recursively326        :param initial: initial dict to be updated327        :param update: new dict328        :param initial_key: update only one key in initial dicts329        :return: merged dict330        """331        for key, value in update.items():332            if initial_key is None or key == initial_key:333                initial[key] = self._update_dict(initial.get(key, {}), value) if isinstance(value, dict) else value334        return initial335    def _setup_safari(self, capabilities):336        """Setup Safari webdriver337        :param capabilities: capabilities object338        :returns: a new local Safari driver339        """340        return webdriver.Safari(desired_capabilities=capabilities)341    def _setup_opera(self, capabilities):342        """Setup Opera webdriver343        :param capabilities: capabilities object344        :returns: a new local Opera driver345        """346        opera_driver = self.config.get('Driver', 'opera_driver_path')347        self.logger.debug("Opera driver path given in properties: %s", opera_driver)348        return webdriver.Opera(executable_path=opera_driver, desired_capabilities=capabilities)349    def _setup_explorer(self, capabilities):350        """Setup Internet Explorer webdriver351        :param capabilities: capabilities object352        :returns: a new local Internet Explorer driver353        """354        explorer_driver = self.config.get('Driver', 'explorer_driver_path')355        self.logger.debug("Explorer driver path given in properties: %s", explorer_driver)356        return webdriver.Ie(explorer_driver, capabilities=capabilities)357    def _setup_edge(self, capabilities):358        """Setup Edge webdriver359        :param capabilities: capabilities object360        :returns: a new local Edge driver361        """362        edge_driver = self.config.get('Driver', 'edge_driver_path')363        self.logger.debug("Edge driver path given in properties: %s", edge_driver)364        return webdriver.Edge(edge_driver, capabilities=capabilities)365    def _setup_phantomjs(self, capabilities):366        """Setup phantomjs webdriver367        :param capabilities: capabilities object368        :returns: a new local phantomjs driver369        """370        phantomjs_driver = self.config.get('Driver', 'phantomjs_driver_path')371        self.logger.debug("Phantom driver path given in properties: %s", phantomjs_driver)372        return webdriver.PhantomJS(executable_path=phantomjs_driver, desired_capabilities=capabilities)373    def _setup_appium(self):374        """Setup Appium webdriver375        :returns: a new remote Appium driver376        """377        self.config.set('Server', 'host', '127.0.0.1')378        self.config.set('Server', 'port', '4723')...driver_setup.py
Source:driver_setup.py  
...78    def _set_local_driver(self):79        driver_type = self.base_config.config.get('Driver', 'type')80        driver_name = driver_type.split('-')[0]81        if driver_name in (constants.ANDROID, constants.IOS, constants.IPHONE):82            driver = self._setup_appium()83        else:84            driver_setup = {85                'firefox': self.driver_types.firefox,86                'chrome': self.driver_types.chrome,87                'safari': self.driver_types.safari,88                'opera': self.driver_types.opera,89                'iexplore': self.driver_types.explorer,90                'edgeie': self.driver_types.edgeie,91                'edge': self.driver_types.edge,92                'phantomjs': self.driver_types.phantomjs93            }94            driver_setup_method = driver_setup.get(driver_name)95            if not driver_setup_method:96                raise Exception(f"Unknown driver {driver_name}")97            capabilities = get_driver_capabilities(driver_name)98            add_driver_capabilities(capabilities, 'Capabilities', self.base_config)99            try:100                if settings.PYTALOS_RUN['execution_proxy']['enabled']:101                    proxy = Proxy()102                    proxy.proxy_type = ProxyType.MANUAL103                    proxy.http_proxy = settings.PYTALOS_RUN['execution_proxy']['proxy']['http_proxy']104                    proxy.ssl_proxy = settings.PYTALOS_RUN['execution_proxy']['proxy']['https_proxy']105                    proxy.add_to_capabilities(capabilities)106            except (Exception,) as ex:107                print(ex)108            driver = driver_setup_method(capabilities)109        return driver110    def _setup_appium(self):111        self.base_config.config.set('Server', 'host', '127.0.0.1')112        self.base_config.config.set('Server', 'port', '4723')...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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
