def test_robot_env_overrides_var_file(self, mock_get_variables): os.environ["PO_AUTHOR"] = "Twain" os.environ["PO_VAR_FILE"] = self.path_to_var_file try: handler = OptionHandler(MockPage()) self.assertEquals(handler.get("author"), "Twain") except Exception, e: raise e
def test_robot_cmd_line_var_overrides_env_var(self, mock_get_variables): os.environ["PO_BROWSER"] = "firefox" mock_get_variables.return_value = {"${browser}": "chrome"} try: handler = OptionHandler() self.assertEquals(handler.get("browser"), "chrome") except Exception, e: raise e
def test_robot_env_overrides_var_file(self, mock_get_variables): os.environ["PO_AUTHOR"] = "Twain" os.environ["PO_VAR_FILE"] = self.path_to_var_file try: handler = OptionHandler() self.assertEquals(handler.get("author"), "Twain") except Exception, e: raise e
def test_is_singleton(self): ids = [] for i in range(3): ids.append(id(OptionHandler())) self.assertTrue( all(x == ids[0] for x in ids), "All OptionHandler instances should refer to the same instance")
def __init__(self, *args, **kwargs): """ Initializes the options used by the actions defined in this class. """ #_ComponentsManager.__init__(self, *args, **kwargs) #_SelectorsManager.__init__(self, *args, **kwargs) super(_BaseActions, self).__init__(*args, **kwargs) self._option_handler = OptionHandler(self) self._is_robot = Context.in_robot() self.selenium_speed = self._option_handler.get("selenium_speed") or 0 self.set_selenium_speed(self.selenium_speed) siw_opt = self._option_handler.get("selenium_implicit_wait") self.selenium_implicit_wait = siw_opt if siw_opt is not None else 10 self.set_selenium_implicit_wait(self.selenium_implicit_wait) self.set_selenium_timeout(self.selenium_implicit_wait) self.baseurl = self._option_handler.get("baseurl")
def test_no_robot_var_file(self): os.environ["PO_VAR_FILE"] = self.path_to_var_file handler = OptionHandler(MockPage()) self.assertEquals(handler.get("author"), "Dickens") self.assertEquals(handler.get("dynamic"), "Python")
def test_var_file_import_exception(self): os.environ["PO_VAR_FILE"] = "foo/bar/asdfsadf/asdf" handler = OptionHandler(MockPage()) handler.get("PO_VAR_FILE")
def test_no_robot_ignore_lowercase_env_vars(self): os.environ["PO_BROWSEr"] = "firefox" handler = OptionHandler(MockPage()) self.assertIsNone(handler.get("browser"), "Mixed case environment variables should not be set")
def test_no_robot_env_not_set_is_none(self): handler = OptionHandler(MockPage()) self.assertIsNone(handler.get("fasdfasdfasdfsadf"))
def test_no_robot_get_env_var(self): os.environ["PO_FOO"] = "bar" handler = OptionHandler(MockPage()) self.assertEquals(handler.get("foo"), "bar")
def test_get_options_from_page_object(self): p = MockPage() p.options = {'author': 'Twain'} handler = OptionHandler(p) self.assertEquals(handler.get("author"), "Twain")
class _BaseActions(_S2LWrapper): """ Helper class that defines actions for PageObjectLibrary. """ _abstracted_logger = Logger() def __init__(self, *args, **kwargs): """ Initializes the options used by the actions defined in this class. """ #_ComponentsManager.__init__(self, *args, **kwargs) #_SelectorsManager.__init__(self, *args, **kwargs) super(_BaseActions, self).__init__(*args, **kwargs) self._option_handler = OptionHandler(self) self._is_robot = Context.in_robot() self.selenium_speed = self._option_handler.get("selenium_speed") or 0 self.set_selenium_speed(self.selenium_speed) siw_opt = self._option_handler.get("selenium_implicit_wait") self.selenium_implicit_wait = siw_opt if siw_opt is not None else 10 self.set_selenium_implicit_wait(self.selenium_implicit_wait) self.set_selenium_timeout(self.selenium_implicit_wait) self.baseurl = self._option_handler.get("baseurl") def log(self, msg, level="INFO", is_console=True): """ Logs either to Robot log file or to a file called po_log.txt at the current directory. :param msg: The message to log :param level: The level to log at :type level: String corresponding to Robot or Python logging levels. See http://robot-framework.readthedocs.org/en/2.8.4/autodoc/robot.api.html?#log-levels for Robot log levels and http://docs.python.org/2/library/logging.html#levels for Python logging levels outside Robot. :param is_console: Whether or not to log to stdout :type is_console: Boolean Possible Robot levels are: - "WARN" - "INFO" - "DEBUG" - "TRACE" In Robot, you set the logging threshold using the --loglevel, or -L option to filter out logging chatter. For example, by default the logging level is set to "INFO" so if you logged "DEBUG" messages, the messages would not get reported. Robot logging messages get logged to stdout and to log.html. Outside of Robot, possible logging levels are: - "CRITICAL" - "ERROR" - "WARNING" - "INFO" - "DEBUG" - "NOSET" ...and you set the logging threshold level using the PO_LOG_LEVEL environment variable or log_level variable in a variable file. The Python logging module provides more logging levels than Robot provides; therefore, logging levels passed as strings to boththe log() method and the threshold level, are mapped to the closest supported Robot logging level and vice versa. The default threshold for both Robot and Python is "INFO". """ return self._log(msg, self.name, level, is_console) def _log(self, msg, page_name, level="INFO", is_console=True): """ See :func:`log`.""" self._abstracted_logger.log(msg, page_name, level, is_console) return self def wait_until_alert_is_present(self, timeout=None): alert_present = False self.wait_for(lambda: EC.alert_is_present(), timeout=timeout, message="No alert was present after %s" % self._format_timeout(timeout or self.selenium_implicit_wait)) def wait_until_element_is_not_visible(self, locator, timeout=None, error=None): """Waits until element specified with `locator` is not visible. Fails if `timeout` expires before the element is not visible. See `introduction` for more information about `timeout` and its default value. `error` can be used to override the default error message. """ def check_visibility(): visible = self._is_visible(locator) if not visible: return elif visible is None: return else: return error or "Element locator '%s' was still matched after %s" % (locator, self._format_timeout(timeout)) self._wait_until_no_error(timeout, check_visibility) def wait_for(self, condition, timeout=None, message=''): """ Waits for a condition defined by the passed function to become True. :param condition: The condition to wait for :type condition: callable :param timeout: How long to wait for the condition, defaults to the selenium implicit wait :type condition: number :param message: Message to show if the wait times out :type condition: string :returns: None """ wait = WebDriverWait(self.get_current_browser(), timeout or self.selenium_implicit_wait) def wait_fnc(driver): try: ret = condition() except AssertionError as e: return False else: return ret wait.until(wait_fnc, message) return self @robot_alias("get_hash_on__name__") def get_hash(self): """ Get the current location hash. :return: the current hash """ url = self.get_location() parts = url.split("#") if len(parts) > 0: return "#".join(parts[1:]) else: return "" @robot_alias("hash_on__name__should_be") def hash_should_be(self, expected_value): hash = self.get_hash() asserts.assert_equal(hash, expected_value) return self def is_visible(self, selector): """ Get the visibility of an element by selector or locator :param selector: The selector or locator :type selector: str :return: whether the element is visible """ return self._is_visible(selector) def _element_find(self, locator, *args, **kwargs): """ Override built-in _element_find() method and intelligently determine the locator for a passed-in selector name. Try to use _element_find with the locator as is, then if a selector exists, try that. ``locator`` can also be a WebElement if an element has been identified already and it is desired to perform actions on that element :param locator: The Selenium2Library-style locator, or IFT selector or WebElement (if the element has already been identified). :type locator: str or WebElement :returns: WebElement or list """ if isinstance(locator, WebElement): return locator our_wait = self.selenium_implicit_wait if kwargs.get("wait") is None else kwargs["wait"] # If wait is set, don't pass it along to the super classe's implementation, since it has none. if "wait" in kwargs: del kwargs["wait"] self.driver.implicitly_wait(our_wait) if locator in self.selectors: locator = self.resolve_selector(locator) try: return super(_BaseActions, self)._element_find(locator, *args, **kwargs) except ValueError: if not self._is_locator_format(locator): # Not found, doesn't look like a locator, not in selectors dict raise exceptions.SelectorError( "\"%s\" is not a valid locator. If this is a selector name, make sure it is spelled correctly." % locator) else: raise finally: self.driver.implicitly_wait(self.selenium_implicit_wait) @not_keyword def find_element(self, locator, required=True, wait=None, **kwargs): """ Wraps Selenium2Library's protected _element_find() method to find single elements. TODO: Incorporate selectors API into this. :param locator: The Selenium2Library-style locator to use :type locator: str :param required: Optional parameter indicating whether an exception should be raised if no matches are found. Defaults to True. :type required: boolean :param wait: Maximum Time in seconds to wait until the element exists. By default the implicit wait is 10 seconds for any element finding method, including Se2lib methods. Passing a wait to find_element overrides this. :returns: WebElement instance """ ret = self._element_find(locator, first_only=False, required=required, wait=wait, **kwargs) if len(ret) > 1: raise exceptions.SelectorError( "\"%s\" found more than one element. If this is expected, use \"find_elements\" instead" % locator) return ret[0] @not_keyword def find_elements(self, locator, required=True, wait=None, **kwargs): """ Wraps Selenium2Library's protected _element_find() method to find multiple elements. TODO: Incorporate selectors API into this. :param locator: The Selenium2Library-style locator to use :type locator: str :param required: Optional parameter indicating whether an exception should be raised if no matches are found. Defaults to True. :type required: boolean :param wait: Maximum Time in seconds to wait until the element exists. By default the implicit wait is 10 seconds for any element finding method, including Se2lib methods. Passing a wait to find_element overrides this. :returns: WebElement instance """ return self._element_find(locator, first_only=False, required=required, wait=wait, **kwargs) @not_keyword def get_subclass_from_po_module(self, module_name, super_class, fallback_to_super=True): """Given `module_name`, try to import it and find in it a subclass of `super_class`. This is for dynamically resolving what page object to use for, say, a search that can bring up multiple types of search result page. :param module_name: The name of the module to look for. :type module_name: str :param super_class: The class to look for subclasses of. :type super_class: type :param fallback_to_super: Whether to default to returning `super_class` if module `module_name` cannot be imported. :returns: type """ try: po_mod = importlib.import_module(module_name) except ImportError: if fallback_to_super: return super_class else: for name, obj in inspect.getmembers(po_mod): if inspect.isclass(obj) and issubclass(obj, super_class) and obj != super_class: return obj raise exceptions.PageSelectionError("You need to have the %s package installed to go to a %s page," "and the package needs to have a subclass of %s." % (module_name, module_name, super_class)) def _is_locator_format(self, locator): """ Ask Selenium2Library's ElementFinder if the locator uses one of its supported prefixes. :param locator: The locator to look up :type locator: str """ finder = self._element_finder prefix = finder._parse_locator(locator)[0] return prefix is not None or locator.startswith("//") def location_should_be(self, expected_url): """ Wrapper for Selenium2Library's location_should_be() method. Allows matching against the baseurl if a partial url is given. :param url: Either complete url or partial url to be validated against :type url: str :returns: True or False """ if re.match("^(\w+:)?//", expected_url): # Simply compares with the expected url as it starts with http return super(_BaseActions, self).location_should_be(expected_url), self else: # This condition is for partial url, # as the regular expression fails it is considered as partial url # and hence it is appended to the baseurl return super(_BaseActions, self).location_should_be(self.baseurl+ expected_url), self
def test_robot(self, mock_get_variables): mock_get_variables.return_value = {"${browser}": "foobar"} handler = OptionHandler(MockPage()) self.assertEquals(handler.get("browser"), "foobar")
def get_threshold_level_as_str(): ret = OptionHandler(object()).get("log_level") or "INFO" return ret.upper()
def test_robot(self, mock_get_variables): mock_get_variables.return_value = {"${browser}": "foobar"} handler = OptionHandler() self.assertEquals(handler.get("browser"), "foobar")
def test_var_file_import_exception(self): os.environ["PO_VAR_FILE"] = "foo/bar/asdfsadf/asdf" handler = OptionHandler() handler.get("PO_VAR_FILE")
def test_no_robot_var_file(self): os.environ["PO_VAR_FILE"] = self.path_to_var_file handler = OptionHandler() self.assertEquals(handler.get("author"), "Dickens") self.assertEquals(handler.get("dynamic"), "Python")
def test_no_robot_env_not_set_is_none(self): handler = OptionHandler() self.assertIsNone(handler.get("fasdfasdfasdfsadf"))
def test_no_robot_ignore_lowercase_env_vars(self): os.environ["PO_BROWSEr"] = "firefox" handler = OptionHandler() self.assertIsNone(handler.get("browser"), "Mixed case environment variables should not be set")
def test_no_robot_get_env_var(self): os.environ["PO_FOO"] = "bar" handler = OptionHandler() self.assertEquals(handler.get("foo"), "bar")
def test_robot_can_get_vars_from_env(self, mock_get_variables): os.environ["PO_BROWSER"] = "opera" try: handler = OptionHandler() self.assertEquals(handler.get("browser"), "opera") except Exception, e: raise e
def test_robot_can_get_vars_from_env(self, mock_get_variables): os.environ["PO_BROWSER"] = "opera" try: handler = OptionHandler(MockPage()) self.assertEquals(handler.get("browser"), "opera") except Exception, e: raise e
def test_robot_cmd_line_var_overrides_var_file(self, mock_get_variables): mock_get_variables.return_value = {"${author}": "Twain"} os.environ["PO_VAR_FILE"] = self.path_to_var_file try: handler = OptionHandler() self.assertEquals(handler.get("author"), "Twain") except Exception, e: raise e
def test_robot_cmd_line_var_overrides_env_var(self, mock_get_variables): os.environ["PO_BROWSER"] = "firefox" mock_get_variables.return_value = {"${browser}": "chrome"} try: handler = OptionHandler(MockPage()) self.assertEquals(handler.get("browser"), "chrome") except Exception, e: raise e
def test_robot_cmd_line_var_overrides_var_file(self, mock_get_variables): mock_get_variables.return_value = {"${author}": "Twain"} os.environ["PO_VAR_FILE"] = self.path_to_var_file try: handler = OptionHandler(MockPage()) self.assertEquals(handler.get("author"), "Twain") except Exception, e: raise e