Пример #1
0
def _file_exists(file_path=None):
    if not file_path:
        if isinstance(ACTIVE_FILE, File) is False:
            raise QWebInstanceDoesNotExistError('File has not been defined with UsePdf keyword')
        return True
    if isinstance(file_path, File) is False:
        raise QWebInstanceDoesNotExistError('Could not locate file {}'.format(file_path))
    return True
Пример #2
0
def get_table_row(locator, anchor="1", timeout=0, **kwargs):  # pylint: disable=unused-argument
    """Get row (index) from current table.

    Get table row by some visible text or value.

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

       ${row}       GetTableRow     //last          #returns table length(last row)
       ${row}       GetTableRow     Qentinel        #return first row which contain text Qentinel
       ${row}       GetTableRow     Qentinel    2     #second row with text Qentinel
       ${row}       GetTableRow     Qentinel    Sepi  #row contains texts Qentinel & Sepi
       ${row}       GetTableRow     Qentinel    skip_header=True  #start counting from first tc row

    Parameters
    ----------
    locator : str
      Text or value which is presented in wanted row or //last = last row of the table
    anchor : str
      If locator is not unique use anchor to tell which is correct. Anchor can be some text/value
      in same row than locator text or index. 1=first match etc. Default = 1
    timeout : str | int
       How long we search before failing. Default = Search Strategy default timeout (10s)

    Raises
    ------
    ValueError
       If the table is not defined by UseTable keyword
    """
    table = Table.ACTIVE_TABLE.update_table()
    if isinstance(ACTIVE_TABLE, Table) is False:
        raise QWebInstanceDoesNotExistError(
            'Table has not been defined with UseTable keyword')
    return table.get_row(locator, anchor, row_index=True, **kwargs)
Пример #3
0
def get_dd_elements_from_all_documents(locator, anchor, index, **kwargs):
    if int(index) > 0:
        index = int(index) - 1
    css_selector = CONFIG["CssSelectors"]
    if not css_selector or locator.startswith('xpath=') or locator.startswith(
            '//'):
        select = get_dropdown_element_by_locator(locator, anchor)
    elif Table.is_table_coordinates(locator):
        table = Table.ACTIVE_TABLE.update_table()
        if table is None:
            raise QWebInstanceDoesNotExistError(
                'Table has not been defined with UseTable keyword')
        locator = table.get_table_cell(locator, anchor)
        select = element.get_element_from_childnodes(
            locator, 'select', dom_traversing=False)[index]
    else:
        select = get_dropdown_element_by_css_selector(locator, anchor, index,
                                                      **kwargs)
    if not select:
        select = get_dropdown_element_by_locator(locator, anchor)
    if select:
        if CONFIG['SearchMode']:
            element.draw_borders(select)
        return Select(select)
    raise QWebElementNotFoundError('No matching elements found')
Пример #4
0
def get_cell_text(coordinates, anchor="1", timeout=0, **kwargs):
    r"""Get cell text to variable.

    Locates cell by coordinates from active table and return value

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

        ${value}    GetCellText  r2c3
        ${value}    GetCellText  r-2c5       #Row is second to last. Get value from cell c5
        ${value}    GetCellText  r?Robot/c5  #Row contains text Robot. Get value from cell c5
        ${value}    GetCellText  r?Robot/c-1  #Row contains text Robot. Get value from last cell

    Parameters
    ----------
    coordinates : str
      Row and column coordinates in table. R specifies row and c column.
      r1 = first row, r-1 = last row, r?Qentinel/ = row that contains word Qentinel
    anchor : str
      If row is located by text which is not unique, use anchor to point correct one.
      Anchor can be some other text in same row or index. Default = 1
    timeout : str | int
      How long we search before failing. Default = Search Strategy default timeout (10s)
    kwargs :
        |  Accepted kwargs:
        |       between : str/int - Start???End - Return all chars between texts Start and End.
        |       from_start : int - Return x amount of chars. Starting from first char
        |       from_end : int - Return x amount of chars. Starting from last char
        |       include_locator : True - Starting text is part of returned string
        |       exclude_post : False - Ending text is part of returned string
        |       int : True - Return integer instead of string
        |       float : int - Return float instead of string

    Raises
    ------
    QWebValueError
        If the table is not defined by UseTable keyword

    Related keywords
    ----------------
    \`ClickCell\`, \`GetTableRow\`, \`UseTable\`, \`VerifyTable\`
    """
    table = Table.ACTIVE_TABLE.update_table()
    if isinstance(ACTIVE_TABLE, Table) is False:
        raise QWebInstanceDoesNotExistError('Table has not been defined with UseTable keyword')
    table_cell = table.get_table_cell(coordinates, anchor)
    try:
        text = actions.get_element_text(table_cell, timeout=timeout)
        return util.get_substring(text, **kwargs)
    except QWebTimeoutError:
        return ""
Пример #5
0
def get_dropdown_element_by_css_selector(locator, anchor, index, **kwargs):
    """Get Dropdown element using css selectors.
       Parameters
       ----------
       locator : str
           Label text or attribute that points to the dropdown.
           Looking for placeholder and commonly used tooltip-attributes first.
           If locator is label text, finds input element by it's for attribute.
           if for attribute is not available, then finds element by doing some
           DOM traversing.
       anchor : str
           Using if locator is not an XPath.
       index : int
           If multiple elements use index to pick correct one.
       Returns
       -------
       WebElement
   """
    dropdown_elements = []
    partial_matches = []
    css = 'select'
    if 'qweb_old' not in kwargs:
        full_matches, partial_matches = element.get_elements_by_css(
            locator, css, **kwargs)
        if full_matches:
            if index != 0:
                try:
                    return full_matches[index]
                except IndexError as e:
                    raise QWebInstanceDoesNotExistError(
                        f'Found {len(full_matches)} elements. Given index was {index}'
                    ) from e
            correct_element = text.get_element_using_anchor(
                full_matches, anchor)
            return correct_element
    try:
        locator_element = text.get_text_using_anchor(locator, anchor)
        # if this is option, return parent select immediately
        if locator_element.tag_name.lower() == "option":
            return javascript.execute_javascript(
                "return arguments[0].parentNode;", locator_element)
        dropdown_elements = list(
            dict.fromkeys(
                element.get_element_from_childnodes(locator_element, css, **
                                                    kwargs) + partial_matches))
    except QWebElementNotFoundError:
        logger.trace(
            'Element not found by visible text. Trying with partial match')
        dropdown_elements = partial_matches
    if dropdown_elements:
        return dropdown_elements[index]
    return None
Пример #6
0
def get_element_using_anchor(elements, anchor, **kwargs):
    """Determine correct element from list of elements using anchor.

    Parameters
    ----------
    elements : :obj:`list` of :obj:`WebElement`
    anchor

    Returns
    -------
    WebElement
    """
    if anchor is None:
        # Element was not unique and anchor was not used.
        raise QWebValueError(
            'Found {} elements. Use anchor to determine which is wanted'.
            format(len(elements)))
    # Select by index unless anchor type is text
    if anchor.isdigit() and kwargs.get("anchor_type",
                                       "auto").lower() != "text":
        anchor = int(anchor) - 1
        if anchor < len(elements):
            return elements[anchor]
        raise QWebInstanceDoesNotExistError(
            'Found {} elements. Given anchor was {}'.format(
                len(elements), anchor + 1))
    if isinstance(anchor, str):  # Get closest element to anchor
        kwargs['stay_in_current_frame'] = True
        anchor_element = None
        if CONFIG['MultipleAnchors']:
            anchor_elements = []
            logger.debug(
                'Multiple anchors enabled, trying to find first exact match')
            try:
                anchor_elements = _get_exact_text_element(anchor, **kwargs)
            except NoSuchFrameException:
                logger.debug('Got no such frame from get exact text')
            if len(anchor_elements) > 0:
                # Using first exact match as anchor
                anchor_element = anchor_elements[0]
            else:
                # No exact matches found, trying to find partial
                anchor_elements = get_text_elements(anchor, **kwargs)
                if len(anchor_elements) > 0:
                    logger.debug(
                        'No exact match found, using first partial match')
                    anchor_element = anchor_elements[0]
        else:
            anchor_element = get_unique_text_element(anchor, **kwargs)
        return element.get_closest_element(anchor_element, elements)
    raise TypeError("Unknown argument type {}".format(type(anchor)))
Пример #7
0
def click_cell(coordinates, anchor="1", timeout=0, index=1, **kwargs):  # pylint: disable=unused-argument
    r"""Click table cell.

    Locates cell by coordinates or text from active table and clicks it

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

       ClickCell    r2c3
       ClickCell    r-1c-1                  #Last row, last cell
       ClickCell    r?SomeText/c3           #Click cell 3 in row that contains text SomeText
       ClickCell    r?Robot/c3      Hello   #Click cell 3 in row with words Robot and Hello in it
       ClickCell    r1c1            tag=a   #Clicks first child element with a tag
       ClickCell    r?Robot/c3      index=2  tag=input  #Clicks the second child element of cell 3

    Parameters
    ----------
    coordinates : str
      Row and column coordinates in table or some text that locates in preferred row.
      R specifies row and c column.
      r1 = first row, r-1 = last row, r?Qentinel/ = row that contains word Qentinel
    anchor : str
      If row is located by text which is not unique, use anchor to point correct one.
      Anchor can be some other text in same row or index. Default = 1
    timeout : str | int
       How long we search before failing. Default = Search Strategy default timeout (10s)
    index : int
       Use index when table cell contains more than one clickable element and preferred one
       is not the first one. Requires the use of tag and value should be > 0, default = 1.

    Raises
    ------
    QWebValueError
       If the table is not defined by UseTable keyword

    Related keywords
    ----------------
    \`GetCellText\`, \`GetTableRow\`, \`UseTable\`, \`VerifyTable\`
    """
    table = Table.ACTIVE_TABLE.update_table()
    if isinstance(ACTIVE_TABLE, Table) is False:
        raise QWebInstanceDoesNotExistError('Table has not been defined with UseTable keyword')
    table_cell = table.get_clickable_cell(coordinates, anchor, index, **kwargs)
    actions.execute_click_and_verify_condition(table_cell, **kwargs)
Пример #8
0
def verify_table(coordinates, expected, anchor="1", timeout=0):
    r"""Verify text in table coordinates.

    Reads cell value from coordinates in active table and verifies it
    against expected value.

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

         VerifyTable            r2c3    Qentinel


    Parameters
    ----------
    coordinates : str
        Row and column coordinates in table. R specifies row and c column.
        Order does not matter.
    expected : str
        Expected value that needs to be found in table.
    anchor : str
        Index number or text near the input field's locator element.
        If the page contains many places where the locator is then anchor is used
        to select the wanted item. Index number selects the item from the list
        of matching entries starting with 1. Text selects the entry with the closest
        distance.
    timeout : str | int
        How long we search before failing. Default = Search Strategy default timeout (10s)

    Raises
    ------
    QWebValueMismatchErr
        If the table is not defined by UseTable keyword

    Related keywords
    ----------------
    \`ClickCell\`, \`GetCellText\`, \`GetTableRow\`, \`UseTable\`
    """
    table = Table.ACTIVE_TABLE.update_table()
    if isinstance(ACTIVE_TABLE, Table) is False:
        raise QWebInstanceDoesNotExistError('Table has not been defined with UseTable keyword')
    table_cell = table.ACTIVE_TABLE.get_table_cell(coordinates, anchor)
    actions.get_element_text(table_cell, expected=expected, timeout=timeout)
Пример #9
0
def get_checkbox_elements_from_all_documents(locator, anchor, index, **kwargs):
    """Function for finding checkbox elements.
    Parameters
    ----------
    locator : str
        Label text or attribute that points to the checkbox.
    anchor : str
        in case there is duplicates.
    index : int
        If multiple matches. Use index to pick correct one.
    Returns
    -------
    WebElement
    """
    index = int(index) - 1
    css_selector = CONFIG["CssSelectors"]
    css = '[type="checkbox"], [role="checkbox"]'
    if Table.is_table_coordinates(locator):
        table = Table.ACTIVE_TABLE.update_table()
        if table is None:
            raise QWebInstanceDoesNotExistError(
                'Table has not been defined with UseTable keyword')
        locator_element = table.get_table_cell(locator, anchor)
        checkbox_element = element.get_element_from_childnodes(
            locator_element, css, dom_traversing=False, **kwargs)
        if checkbox_element:
            return checkbox_element[index], locator_element
        raise QWebElementNotFoundError('No matching checkbox found')
    if not css_selector or locator.startswith('xpath=') or locator.startswith(
            '//'):
        checkbox_element, locator_element = get_checkbox_by_locator(
            locator, anchor=anchor)
    else:
        checkbox_element, locator_element = get_checkbox_by_css_selector(
            locator, anchor=anchor, index=index, **kwargs)
        if not checkbox_element:
            checkbox_element, locator_element = get_checkbox_by_locator(
                locator, anchor)
    if checkbox_element:
        return checkbox_element, locator_element
    raise QWebElementNotFoundError('No matching element found')
Пример #10
0
def get_input_elements_from_all_documents(locator,
                                          anchor,
                                          timeout,
                                          index=1,
                                          enable_check=False,
                                          **kwargs):  # pylint: disable=unused-argument
    """Function for finding input elements.
    Parameters
    ----------
    locator : str
       Label text or attribute that points to the checkbox.
    anchor : str
       in case there is duplicates.
    timeout : str
       How long we are finding before fail.
       Default = Search Strategy global default = 10 sec)
    index : int
       If table cell contains more than one input elements or if there is some kind of
       nested structure inside of given input index may needed. Default = 1 (first)
    enable_check : bool
        When CSS Selectors are used, we are not return disabled input element
        always by default. Element is needed with verify input status kw
        so if enable_check= True, disabled input_element is returned
    kwargs:
        limit_traverse : bool
            If set to false. We are heading up to fifth parent element if needed when
            finding relative input element for some label text.
    Returns
    -------
    WebElement
    """
    index = int(index) - 1
    css = 'input:not([type="hidden"]):not([type="submit"]):not([type="button"])' \
          ':not([type="reset"]):not([type="checkbox"]):not([type="radio"])' \
          ':not([aria-hidden="true"]),' \
          'textarea:not([type="hidden"]),[contenteditable="true"]'
    kwargs['css'] = kwargs.get('css', css)
    if Table.is_table_coordinates(locator):
        table = Table.ACTIVE_TABLE.update_table()
        if table is None:
            raise QWebInstanceDoesNotExistError(
                'Table has not been defined with UseTable keyword')
        locator_element = table.get_table_cell(locator, anchor)
        input_element = element.get_element_from_childnodes(
            locator_element, kwargs['css'], dom_traversing=False)
        if input_element:
            return input_element[index]
        raise QWebElementNotFoundError('No matching table input found')
    css_selector = CONFIG["CssSelectors"]
    if not css_selector or locator.startswith('xpath=') or locator.startswith(
            '//'):
        input_element = get_input_element_by_locator(locator, anchor, **kwargs)
    else:
        logger.debug('Uses CSS-selectors to locate element')
        input_element = get_input_element_by_css_selector(
            locator, anchor, index, enable_check, **kwargs)
        if not input_element:
            input_element = get_input_element_by_locator(
                locator, anchor, **kwargs)
    if input_element:
        if CONFIG['SearchMode']:
            element.draw_borders(input_element)
        return input_element
    raise QWebElementNotFoundError('No matching input elements found')
Пример #11
0
def _list_exists():
    if isinstance(ACTIVE_LIST, List) is False:
        raise QWebInstanceDoesNotExistError(
            'List has not been defined with UseList keyword')
    return True