Best Python code snippet using robotframework-pageobjects_python
page.py
Source:page.py
...122 "sauce_screenresolution",123 ]124 for sauce_opt in self._sauce_options:125 setattr(self, sauce_opt, self._option_handler.get(sauce_opt))126 self._attempt_sauce = self._validate_sauce_options()127 # There's only a session ID when using a remote webdriver (Sauce, for example)128 self.session_id = None129 # If a name is not explicitly set with the name attribute,130 # get it from the class name.131 try:132 self.name133 except AttributeError:134 self.name = self._titleize(self.__class__.__name__)135 # Allow setting of uri_template or uri, but make them the same internally136 if hasattr(self, 'uri_template'):137 self.uri = self.uri_template138 # Set a default uri in case one is not set in the Page139 elif not hasattr(self, 'uri'):140 self.uri = '/'141 @staticmethod142 @not_keyword143 def _titleize(str):144 """145 Converts camel case to title case146 :param str: camel case string147 :return: title case string148 """149 return re.sub('([a-z0-9])([A-Z])', r'\1 \2', re.sub(r"(.)([A-Z][a-z]+)", r'\1 \2', str))150 @staticmethod151 @not_keyword152 def _underscore(str):153 return re.sub(r"\s+", "_", str)154 @not_keyword155 def get_keyword_names(self):156 """157 RF Dynamic API hook implementation that provides a list of all keywords defined by158 the implementing class. NB that this will not expose Selenium2Library's keywords.159 That is done (in Robot) by programmatically importing Selenium2Library. See __init__160 in _S2LWrapper.161 This method uses the _Keywords class to handle exclusions and aliases.162 :returns: list163 """164 # Return all method names on the class to expose keywords to Robot Framework165 keywords = []166 #members = inspect.getmembers(self, inspect.ismethod)167 # Look through our methods and identify which ones are Selenium2Library's168 # (by checking it and its base classes).169 for name in dir(self):170 is_keyword = _Keywords.is_obj_keyword_by_name(name, self)171 if is_keyword:172 obj = getattr(self, name)173 in_s2l_base = False174 try:175 func = obj.__func__ # Get the unbound function for the method176 except AttributeError:177 # ignore static methods included in libraries178 continue179 # Check if that function is defined in Selenium2Library180 if func not in self.__class__.__dict__.values():181 if name in Selenium2Library.__dict__.keys():182 in_s2l_base = True183 else:184 # Check if the function is defined in any of Selenium2Library's direct base classes.185 # Note that this will not check those classes' ancestors.186 # TODO: Check all S2L's ancestors. DCLT-187 for base in Selenium2Library.__bases__:188 if name in base.__dict__.keys():189 in_s2l_base = True190 # Don't add methods belonging to S2L to the exposed keywords.191 if in_s2l_base and (in_ld or _Keywords.has_registered_s2l_keywords):192 continue193 elif inspect.ismethod(obj) and not name.startswith("_") and not _Keywords.is_method_excluded(name):194 # Add all methods that don't start with an underscore and were not marked with the195 # @not_keyword decorator.196 if not in_ld:197 keywords += _Keywords.get_robot_aliases(name, self._underscore(self.name))198 else:199 keywords.append(name)200 _Keywords.has_registered_s2l_keywords = True201 return keywords202 def _attempt_screenshot(self):203 try:204 self.capture_page_screenshot()205 except Exception, e:206 if e.message.find("No browser is open") != -1:207 pass208 @not_keyword209 def run_keyword(self, alias, args, kwargs):210 """211 RF Dynamic API hook implementation that maps method aliases to their actual functions.212 :param alias: The alias to look up213 :type alias: str214 :param args: The arguments for the keyword215 :type args: list216 :returns: callable217 """218 # Translate back from Robot Framework alias to actual method219 meth = getattr(self, _Keywords.get_funcname_from_robot_alias(alias, self._underscore(self.name)))220 try:221 ret = meth(*args, **kwargs)222 except:223 # Pass up the stack, so we see complete stack trace in Robot trace logs224 raise225 if isinstance(ret, Page):226 # DCLT-829227 # In Context, we keep track of the currently executing page.228 # That way, when a keyword is run, Robot (specifically, our monkeypatch229 # of Robot's Namespace class - see context.py) will know which library230 # to run a keyword on when there is a conflict.231 # All page object methods should return an instance of Page.232 # Look at the class name of that instance and use it to identify233 # which page object to set Context's pointer to.234 # Get the names of all currently imported libraries235 libnames = Context.get_libraries()236 classname = ret.__class__.__name__237 for name in libnames:238 # If we find a match for the class name, set the pointer in Context.239 if name.split(".")[-1:][0] == classname:240 Context.set_current_page(name)241 # The case of raising an exception if a page object method returns None is handled242 # by Page's meta class, because we need to raise this exception for Robot and243 # outside Robot.244 # If nothing was returned and the method was defined in Selenium2Library,245 # just return self. That way, we exempt Selenium2Library from the "must_return"246 # requirement, but still know what page we're on. (For Selenium2Library keywords247 # that go to another page, we'll just assume we're using the same PO.)248 if ret is None:249 func = meth.__func__250 if meth in Selenium2Library.__dict__.values():251 ret = self252 else:253 for base in Selenium2Library.__bases__:254 if meth.__func__ in base.__dict__.values():255 ret = self256 break257 return ret258 @not_keyword259 def get_keyword_documentation(self, kwname):260 """261 RF Dynamic API hook implementation that exposes keyword documentation to the libdoc tool262 :param kwname: a keyword name263 :return: a documentation string for kwname264 """265 if kwname == '__intro__':266 docstring = self.__doc__ if self.__doc__ else ''267 s2l_link = """\n268 All keywords listed in the Selenium2Library documentation are also available in this Page Object.269 See http://rtomac.github.io/robotframework-selenium2library/doc/Selenium2Library.html270 """271 return docstring + s2l_link272 kw = getattr(self, kwname, None)273 alias = ''274 if kwname in _Keywords._aliases:275 alias = '*Alias: %s*\n\n' % _Keywords.get_robot_aliases(kwname, self._underscore(self.name))[0].replace('_', ' ').title()276 docstring = kw.__doc__ if kw.__doc__ else ''277 docstring = re.sub(r'(wrapper)', r'*\1*', docstring, flags=re.I)278 return alias + docstring279 @not_keyword280 def get_keyword_arguments(self, kwname):281 """282 RF Dynamic API hook implementation that exposes keyword argspecs to the libdoc tool283 :param kwname: a keyword name284 :return: a list of strings describing the argspec285 """286 kw = getattr(self, kwname, None)287 if kw:288 args, varargs, keywords, defaults = inspect.getargspec(kw)289 defaults = dict(zip(args[-len(defaults):], defaults)) if defaults else {}290 arglist = []291 for arg in args:292 if arg != 'self':293 argstring = arg294 if arg in defaults:295 argstring += '=%s' % defaults[arg]296 arglist.append(argstring)297 if varargs:298 arglist.append('*args')299 if keywords:300 arglist.append('**keywords')301 return arglist302 else:303 return ['*args']304 def _parse_service_args(self, service_args):305 return [arg.strip() for arg in service_args.split(" ") if arg.strip() != ""]306 def _validate_sauce_options(self):307 """308 Check if user wants to use sauce and make sure all required options are given309 :return: bool (does user want to use sauce?)310 """311 trigger_opts = {'platform': None, 'browserversion': None, 'device_orientation': None}312 for trigger_opt in trigger_opts.keys():313 trigger_opts[trigger_opt] = getattr(self, 'sauce_' + trigger_opt)314 sauce_desired = any(trigger_opts.values())315 if sauce_desired:316 required_opts = {'username': None, 'apikey': None, 'platform': None}317 for required_opt in required_opts.keys():318 required_opts[required_opt] = getattr(self, 'sauce_' + required_opt)319 have_all_required = all(required_opts.values())320 if not have_all_required:...
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!!