Beispiel #1
0
def maximize_window():
    """Maximizes current browser window.

    Note: This keyword will not fail if maximizing is prevented for some reason.
          This can happen for example if window manager is not installed or setup correctly.

    Examples
    --------
     .. code-block:: robotframework

        MaximizeWindow


    Parameters
    ----------
    None
    """
    driver = browser.get_current_browser()
    if driver is None:
        raise QWebDriverError("No browser open. Use OpenBrowser keyword"
                              " to open browser first")

    if CONFIG.get_value('Headless') is True:
        logger.debug("Maximizing browser in headless mode")
        screen_width_js = driver.execute_script("return screen.width")
        screen_height_js = driver.execute_script("return screen.height")

        driver.set_window_size(screen_width_js, screen_height_js)

    else:
        driver.maximize_window()

    size = driver.get_window_size()
    logger.debug("Window size set to {}x{}".format(size["width"],
                                                   size["height"]))
Beispiel #2
0
def setup_xhr_monitor():
    """Inject jQuery if needed and check if page is ready.

    Setup_xhr_monitor injects jQuery to page if there isn't one
    already.

    """
    try:
        js = """
        function inject(){
            if (typeof(jQuery) === "undefined"){
               var head = document.querySelector('head');
               var script = document.createElement('script');
               script.type = "text/javascript";
               script.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"
               head.appendChild(script);
               if (typeof(jQuery) === "undefined"){
                    return false;
               }
            }
            return true;
        }
        return inject()"""

        return javascript.execute_javascript(js)

    except (WebDriverException, JavascriptException) as e:
        raise QWebDriverError(e)  # pylint: disable=W0707
Beispiel #3
0
def go_to(url, timeout=0):  # pylint: disable=unused-argument
    r"""Switch current page to given url.

    Examples
    --------
    .. code-block:: robotframework

        GoTo    http://google.com
        GoTo    file://resources/window.html

    Parameters
    ----------
    url : str
        URL of the website that will be opened.

    Raises
    ------
    UnexpectedAlertPresentException
        If the page opens with alert popup

    Related keywords
    ----------------
    \`CloseAllBrowsers\`, \`CloseBrowser\`, \`OpenBrowser\`, \`OpenWindow\`, \`SwitchWindow\`
    """
    driver = browser.get_current_browser()
    if driver is None:
        raise QWebDriverError("No browser open. Use OpenBrowser keyword"
                              " to open browser first")
    driver.get(url)
Beispiel #4
0
def close_alert(alert, action):  # pylint: disable=unused-argument
    if action.upper() == 'ACCEPT':
        alert.accept()
    elif action.upper() == 'DISMISS':
        alert.dismiss()
    elif action.upper() == 'NOTHING':
        return
    else:
        raise QWebDriverError(
            "Invalid alert action '{}'. Must be ACCEPT, DISMISS or LEAVE".
            format(action))
Beispiel #5
0
def switch_window(index, timeout=0):  # pylint: disable=unused-argument
    r"""Switch to another tab.

    Examples
    --------
    .. code-block:: robotframework

        SwitchWindow     1
        SwitchWindow     NEW    # Switches to latest opened tab

    Parameters
    ----------
    index : str
        Index of the tab starting from one and counting from left to right.
        OR
        Special keyword "NEW" which can be used to move to the latest opened tab.
    timeout : str | int
        How long we search before failing.

    Raises
    ------
    ValueError
         If the window index is out of reach

    Related keywords
    ----------------
    \`CloseBrowser\`, \`CloseWindow\`, \`CloseOthers\`, \`GoTo\`, \`OpenWindow\`
    """
    window_handles = window.get_window_handles()
    logger.info("Current browser contains {} tabs".format(len(window_handles)))
    if index.isdigit():
        if int(index) == 0:
            raise QWebValueError('SwitchWindow index starts at 1.')
        i = int(index) - 1
        if i < len(window_handles):
            correct_window_handle = window_handles[i]
            window.switch_to_window(correct_window_handle)
            return
        logger.debug('Tried to select tab with index {} but there'
                     ' are only {} tabs open'.format(index, len(window_handles)))
    elif index == "NEW":
        window.switch_to_window(window_handles[-1])
        return
    else:
        raise QWebValueError(
            'Given argument "{}" is not a digit or NEW'.format(index))
    raise QWebDriverError(
        'Tried to select tab with index {} but there are only {} tabs open'
        .format(index, len(window_handles)))
Beispiel #6
0
 def perform(*args, **kwargs):
     params = signature(fn).parameters
     args, kwargs = _args_to_kwargs(params, args, kwargs)
     timeout = get_timeout(**kwargs)
     err = None
     msg = None
     performed = False
     logger.debug('time to run {}'.format(timeout))
     start = time.time()
     while time.time() < timeout + start:
         try:
             return fn(*args, **kwargs)
         except QWebValueMismatchError as mismatch:
             if 'text_appearance' not in str(
                     fn) and 'get_or_compare_text' not in str(fn):
                 err = QWebValueError
                 msg = mismatch
             logger.trace('Value mismatch: {}'.format(mismatch))
             continue
         except (QWebElementNotFoundError, UnexpectedAlertPresentException):
             logger.debug('Not found')
             time.sleep(SHORT_DELAY)
         except QWebValueError as ve:
             if performed:
                 break
             raise ve
         except (QWebStalingElementError,
                 StaleElementReferenceException) as S:
             if 'execute_click' in str(fn) or 'text_appearance' in str(fn):
                 logger.info('Got staling element err from retry click.'
                             'Action is probably triggered.')
                 raise QWebUnexpectedConditionError(S)
             raise QWebStalingElementError('Staling element')
         except (WebDriverException, QWebDriverError) as wde:
             if 'alert' in str(fn):
                 time.sleep(LONG_DELAY)
                 logger.info(
                     "Got webdriver exception..{}. Retrying..".format(wde))
                 err = QWebDriverError
                 msg = wde
             else:
                 raise QWebDriverError(wde)
     if msg:
         raise err(msg)
     raise QWebTimeoutError('Timeout exceeded')
Beispiel #7
0
def swipe(direction, times='1', start=None):
    """
    Internal swipe function used by the swipe keywords. Uses the arrow keys to "swipe",
    unless a starting point is given. If a starting point is given, drag and drop is used.
    Functionality isn't 100% same as in QMobile, but this should work in most cases.
    """
    logger.info('Even though the keyword is called swipe, '
                'it actually uses arrow keys or drag and drop to "swipe".')
    directions = {
        'down': (Keys.ARROW_DOWN, 0, 500),
        'up': (Keys.ARROW_UP, 0, -500),
        'left': (Keys.ARROW_LEFT, -500, 0),
        'right': (Keys.ARROW_RIGHT, 500, 0)
    }
    driver = browser.get_current_browser()
    if driver is None:
        raise QWebDriverError("No browser open. Use OpenBrowser keyword"
                              " to open browser first")
    action_chains = ActionChains(driver)
    try:
        times = int(times)
    except ValueError as e:
        raise ValueError(
            'Amount of times swiped needs to be an integer.') from e
    if not start:
        default_swipe_length = 20
        times = default_swipe_length * times
        for _ in range(times):
            action_chains.send_keys(directions[direction][0])
            action_chains.pause(0.05)
        action_chains.perform()
        time.sleep(.5)
    else:
        start_element = text.get_unique_text_element(start)
        action_chains.click(start_element)
        action_chains.pause(.5)
        action_chains.drag_and_drop_by_offset(start_element,
                                              directions[direction][1] * times,
                                              directions[direction][2] * times)
        action_chains.perform()
        time.sleep(.5)
Beispiel #8
0
def set_current_browser(index):
    # pylint: disable=global-statement
    global _current_browser

    if index.isdigit():
        if int(index) == 0:
            raise QWebValueError('SwitchBrowser index starts at 1.')

        i = int(index) - 1

        if i < len(_open_browsers):
            _current_browser = _open_browsers[i]
        else:
            raise QWebDriverError(
                f'Tried to select browser with index {index} but there are \
                                  {len(_open_browsers)} browsers open')
    elif index == "NEW":
        _current_browser = _open_browsers[-1]
    else:
        raise QWebValueError(
            'Given argument "{}" is not a digit or NEW'.format(index))
Beispiel #9
0
def wait_page_loaded():
    """Wait for webpage to be loaded.

    Examples
    --------
    .. code-block:: robotframework

        WaitPageLoaded

    Each keyword should have this in the beginning since it is crucial that
    page has been loaded fully.

    Monkeypatch this method to have different wait.
    """
    if CONFIG["DefaultDocument"]:
        driver = browser.get_current_browser()
        if driver is None:
            raise QWebDriverError("No browser open. Use OpenBrowser keyword"
                                  " to open browser first")
        try:
            driver.switch_to.default_content()
        except InvalidSessionIdException as ie:
            CONFIG.set_value("OSScreenshots", True)
            raise QWebBrowserError(
                "Browser session lost. Did browser crash?") from ie
        except (NoSuchWindowException, WebDriverException) as e:
            logger.warn(
                'Cannot switch to default context, maybe window is closed. Err: {}'
                .format(e))
            if any(s in str(e) for s in FATAL_MESSAGES):
                CONFIG.set_value("OSScreenshots", True)
                raise QWebBrowserError(e) from e
            driver.switch_to.default_content()
    timeout = CONFIG['XHRTimeout']
    if timeout.lower() == "none":
        return
    try:
        xhr.wait_xhr(timestr_to_secs(timeout))
    except (WebDriverException, QWebDriverError) as e:
        logger.info('Unable to check AJAX requests due error: {}'.format(e))
Beispiel #10
0
def verify_title(title, timeout=0):  # pylint: disable=unused-argument
    r"""Verifies that current page's title matches expected title.


    Examples
    --------
     .. code-block:: robotframework

        VerifyTitle      Google
        VerifyTitle      Google     timeout=3


    Parameters
    ----------
    title : str
        The expected title
    timeout : str | int
        How long we wait for title to change before failing.

    Raises
    ------
    QWebValueError
        If the expected title differs from actual page title

    Related keywords
    ----------------
    \`GetTitle\`, \`GetUrl\`, \`VerifyUrl\`
    """
    driver = browser.get_current_browser()
    if driver is None:
        raise QWebDriverError("No browser open. Use OpenBrowser keyword"
                              " to open browser first")
    actual = driver.title

    if actual != title:
        raise QWebValueError(f"Page title '{actual}'' does not match expected '{title}'")
Beispiel #11
0
def get_title():
    r"""Gets the title of current page/window.


    Examples
    --------
     .. code-block:: robotframework

        ${title}=   GetTitle


    Parameters
    ----------
    None

    Related keywords
    ----------------
    \`GetUrl\`, \`VerifyTitle\`, \`VerifyUrl\`
    """
    driver = browser.get_current_browser()
    if driver is None:
        raise QWebDriverError("No browser open. Use OpenBrowser keyword"
                              " to open browser first")
    return driver.title
Beispiel #12
0
def verify_url(url, timeout=0):  # pylint: disable=unused-argument
    r"""Verifies that current page url/location matches expected url.


    Examples
    --------
     .. code-block:: robotframework

        VerifyUrl      https://www.google.com
        VerifyUrl      https://www.google.com     timeout=5


    Parameters
    ----------
    url : str
        The expected url
    timeout : str | int
        How long we wait for url to change before failing.

    Raises
    ------
    QWebValueError
        If the expected url differs from current url

    Related keywords
    ----------------
    \`GetTitle\`, \`GetUrl\`, \`VerifyTitle\`
    """
    driver = browser.get_current_browser()
    if driver is None:
        raise QWebDriverError("No browser open. Use OpenBrowser keyword"
                              " to open browser first")
    current = driver.current_url

    if current.lower() != url.lower():
        raise QWebValueError(f"Current url '{current}'' does not match expected url '{url}'")
Beispiel #13
0
def get_url():
    r"""Gets current url/location.


    Examples
    --------
     .. code-block:: robotframework

        ${url}=   GetUrl


    Parameters
    ----------
    None

    Related keywords
    ----------------
    \`GetTitle\`,\`VerifyTitle\`, \`VerifyUrl\`
    """
    driver = browser.get_current_browser()
    if driver is None:
        raise QWebDriverError("No browser open. Use OpenBrowser keyword"
                              " to open browser first")
    return driver.current_url
Beispiel #14
0
def switch_to_window(handle):
    driver = browser.get_current_browser()
    if driver is None:
        raise QWebDriverError("No browser open. Use OpenBrowser keyword"
                              " to open browser first")
    driver.switch_to.window(handle)
Beispiel #15
0
def get_url():
    driver = browser.get_current_browser()
    if driver is None:
        raise QWebDriverError("No browser open. Use OpenBrowser keyword"
                              " to open browser first")
    return driver.current_url