Esempio n. 1
0
    def get_cookies(self, as_dict=False):
        """Returns all cookies of the current page.

        If ``as_dict`` argument evaluates as false, see `Boolean arguments` 
        for more details, then cookie information is returned as 
        a single string in format ``name1=value1; name2=value2; name3=value3``.
        When ``as_dict`` argument evaluates as true, cookie information
        is returned as Robot Framework dictionary format. The string format 
        can be used, for example, for logging purposes or in headers when
        sending HTTP requests. The dictionary format is helpful when
        the result can be passed to requests library's Create Session
        keyword's optional cookies parameter.

        The `` as_dict`` argument is new in SeleniumLibrary 3.3
        """
        if is_falsy(as_dict):
            pairs = []
            for cookie in self.driver.get_cookies():
                pairs.append(cookie['name'] + "=" + cookie['value'])
            return '; '.join(pairs)
        else:
            pairs = DotDict()
            for cookie in self.driver.get_cookies():
                pairs[cookie['name']] = cookie['value']
            return pairs
Esempio n. 2
0
 def _parse_capabilities(self, capabilities, browser=None):
     if is_falsy(capabilities):
         return {}
     if not isinstance(capabilities, dict):
         capabilities = self._string_to_dict(capabilities)
     browser = self.browser_names.get(browser, browser)
     if browser in ['ie', 'firefox', 'edge']:
         return {'capabilities': capabilities}
     return {'desired_capabilities': capabilities}
Esempio n. 3
0
 def register(self, strategy_name, strategy_keyword, persist=False):
     strategy = CustomLocator(self.ctx, strategy_name, strategy_keyword)
     if strategy.name in self._strategies:
         raise RuntimeError("The custom locator '%s' cannot be registered. "
                            "A locator of that name already exists." %
                            strategy.name)
     self._strategies[strategy.name] = strategy.find
     if is_falsy(persist):
         # Unregister after current scope ends
         events.on('scope_end', 'current', self.unregister, strategy.name)
Esempio n. 4
0
 def create(self, browser, options):
     if is_falsy(options):
         return None
     selenium_options = self._import_options(browser)
     if not is_string(options):
         return options
     options = self._parse(options)
     selenium_options = selenium_options()
     for option in options:
         for key in option:
             attr = getattr(selenium_options, key)
             if callable(attr):
                 attr(*option[key])
             else:
                 setattr(selenium_options, key, *option[key])
     return selenium_options
Esempio n. 5
0
    def set_window_size(self, width, height, inner=False):
        """Sets current windows size to given ``width`` and ``height``.

        Values can be given using strings containing numbers or by using
        actual numbers. See also `Get Window Size`.

        Browsers have a limit on their minimum size. Trying to set them
        smaller will cause the actual size to be bigger than the requested
        size.

        If ``inner`` parameter is set to True, keyword sets the necessary
        window width and height to have the desired HTML DOM _window.innerWidth_
        and _window.innerHeight_. See `Boolean arguments` for more details on how to set boolean
        arguments.

        The ``inner`` argument is new since SeleniumLibrary 4.0.

        This ``inner`` argument does not support Frames. If a frame is selected,
        switch to default before running this.

        Example:
        | `Set Window Size` | 800 | 600 |      |
        | `Set Window Size` | 800 | 600 | True |
        """
        width, height = int(width), int(height)
        if is_falsy(inner):
            return self.driver.set_window_size(width, height)
        self.driver.set_window_size(width, height)
        inner_width = int(
            self.driver.execute_script("return window.innerWidth;"))
        inner_height = int(
            self.driver.execute_script("return window.innerHeight;"))
        self.info('window.innerWidth is %s and window.innerHeight is %s' %
                  (inner_width, inner_height))
        width_offset = width - inner_width
        height_offset = height - inner_height
        window_width = width + width_offset
        window_height = height + height_offset
        self.info('Setting window size to %s %s' %
                  (window_width, window_height))
        self.driver.set_window_size(window_width, window_height)
        result_width = int(
            self.driver.execute_script("return window.innerWidth;"))
        result_height = int(
            self.driver.execute_script("return window.innerHeight;"))
        if result_width != width or result_height != height:
            raise AssertionError("Keyword failed setting correct window size.")
Esempio n. 6
0
    def click_link(self, locator, modifier=False):
        """Clicks a link identified by ``locator``.

        See the `Locating elements` section for details about the locator
        syntax. When using the default locator strategy, links are searched
        using ``id``, ``name``, ``href`` and the link text.

        See the `Click Element` keyword for details about the
        ``modifier`` argument.

        The ``modifier`` argument is new in SeleniumLibrary 3.3
        """
        if is_falsy(modifier):
            self.info("Clicking link '%s'." % locator)
            self.find_element(locator, tag='link').click()
        else:
            self._click_with_modifier(locator, ['link', 'link'], modifier)
Esempio n. 7
0
 def locator_should_match_x_times(self,
                                  locator,
                                  x,
                                  message=None,
                                  loglevel='TRACE'):
     """*DEPRECATED in SeleniumLibrary 4.0.*, use `Page Should Contain Element` with ``limit`` argument instead."""
     count = len(self.find_elements(locator))
     x = int(x)
     if count != x:
         if is_falsy(message):
             message = ("Locator '%s' should have matched %s time%s but "
                        "matched %s time%s." %
                        (locator, x, s(x), count, s(count)))
         self.ctx.log_source(loglevel)
         raise AssertionError(message)
     self.info("Current page contains %s elements matching '%s'." %
               (count, locator))
Esempio n. 8
0
 def _get_ff_profile(self, ff_profile_dir):
     if isinstance(ff_profile_dir, FirefoxProfile):
         return ff_profile_dir
     if is_falsy(ff_profile_dir):
         return webdriver.FirefoxProfile()
     try:
         return webdriver.FirefoxProfile(ff_profile_dir)
     except (OSError, FileNotFoundError):
         ff_options = self.selenium_options._parse(ff_profile_dir)
         ff_profile = webdriver.FirefoxProfile()
         for option in ff_options:
             for key in option:
                 attr = getattr(ff_profile, key)
                 if callable(attr):
                     attr(*option[key])
                 else:
                     setattr(ff_profile, key, *option[key])
         return ff_profile
Esempio n. 9
0
    def click_button(self, locator, modifier=False):
        """Clicks the button identified by ``locator``.

        See the `Locating elements` section for details about the locator
        syntax. When using the default locator strategy, buttons are
        searched using ``id``, ``name``, and ``value``.

        See the `Click Element` keyword for details about the
        ``modifier`` argument.

        The ``modifier`` argument is new in SeleniumLibrary 3.3
        """
        if is_falsy(modifier):
            self.info("Clicking button '%s'." % locator)
            element = self.find_element(locator, tag='input', required=False)
            if not element:
                element = self.find_element(locator, tag='button')
            element.click()
        else:
            self._click_with_modifier(locator, ['button', 'input'], modifier)
Esempio n. 10
0
    def click_image(self, locator, modifier=False):
        """Clicks an image identified by ``locator``.

        See the `Locating elements` section for details about the locator
        syntax. When using the default locator strategy, images are searched
        using ``id``, ``name``, ``src`` and ``alt``.

        See the `Click Element` keyword for details about the
        ``modifier`` argument.

        The ``modifier`` argument is new in SeleniumLibrary 3.3
        """
        if is_falsy(modifier):
            self.info("Clicking image '%s'." % locator)
            element = self.find_element(locator, tag='image', required=False)
            if not element:
                # A form may have an image as it's submit trigger.
                element = self.find_element(locator, tag='input')
            element.click()
        else:
            self._click_with_modifier(locator, ['image', 'input'], modifier)
Esempio n. 11
0
    def switch_window(self, locator='MAIN', timeout=None, browser='CURRENT'):
        """Switches to browser window matching ``locator``.

        If the window is found, all subsequent commands use the selected
        window, until this keyword is used again. If the window is not
        found, this keyword fails. The previous windows handle is returned
        and can be used to switch back to it later.

        Notice that alerts should be handled with
        `Handle Alert` or other alert related keywords.

        The ``locator`` can be specified using different strategies somewhat
        similarly as when `locating elements` on pages.

        - By default, the ``locator`` is matched against window handle, name,
          title, and URL. Matching is done in that order and the first
          matching window is selected.

        - The ``locator`` can specify an explicit strategy by using the format
          ``strategy:value`` (recommended) or ``strategy=value``. Supported
          strategies are ``name``, ``title``, and ``url``. These matches windows
          using their name, title, or URL, respectively. Additionally, ``default``
          can be used to explicitly use the default strategy explained above.

        - If the ``locator`` is ``NEW`` (case-insensitive), the latest
          opened window is selected. It is an error if this is the same
          as the current window.

        - If the ``locator`` is ``MAIN`` (default, case-insensitive),
          the main window is selected.

        - If the ``locator`` is ``CURRENT`` (case-insensitive), nothing is
          done. This effectively just returns the current window handle.

        - If the ``locator`` is not a string, it is expected to be a list
          of window handles _to exclude_. Such a list of excluded windows
          can be got from `Get Window Handles` before doing an action that
          opens a new window.

        The ``timeout`` is used to specify how long keyword will poll to select
        the new window. The ``timeout`` is new in SeleniumLibrary 3.2.

        Example:
        | `Click Link`      | popup1      |      | # Open new window |
        | `Switch Window`   | example     |      | # Select window using default strategy |
        | `Title Should Be` | Pop-up 1    |      |
        | `Click Button`    | popup2      |      | # Open another window |
        | ${handle} = | `Switch Window`   | NEW  | # Select latest opened window |
        | `Title Should Be` | Pop-up 2    |      |
        | `Switch Window`   | ${handle}   |      | # Select window using handle |
        | `Title Should Be` | Pop-up 1    |      |
        | `Switch Window`   | MAIN        |      | # Select the main window |
        | `Title Should Be` | Main        |      |
        | ${excludes} = | `Get Window Handles` | | # Get list of current windows |
        | `Click Link`      | popup3      |      | # Open one more window |
        | `Switch Window`   | ${excludes} |      | # Select window using excludes |
        | `Title Should Be` | Pop-up 3    |      |

        The ``browser`` argument allows with ``index_or_alias`` to implicitly switch to
        a specific browser when switching to a window. See `Switch Browser`

        - If the ``browser`` is ``CURRENT`` (case-insensitive), no other browser is
          selected.

        *NOTE:*

        - The ``strategy:value`` syntax is only supported by SeleniumLibrary
          3.0 and newer.
        - Prior to SeleniumLibrary 3.0 matching windows by name, title
          and URL was case-insensitive.
        - Earlier versions supported aliases ``None``, ``null`` and the
          empty string for selecting the main window, and alias ``self``
          for selecting the current window. Support for these aliases was
          removed in SeleniumLibrary 3.2.
        """
        epoch = time.time()
        timeout = epoch if is_falsy(
            timeout) else timestr_to_secs(timeout) + epoch
        try:
            return self.driver.current_window_handle
        except NoSuchWindowException:
            pass
        finally:
            if not is_string(browser) or not browser.upper() == 'CURRENT':
                self.drivers.switch(browser)
            self._window_manager.select(locator, timeout)