def get_web_element_inner_text(self, locator, wait_state=ElementWaitState.PRESENT, timeout=None):
        """
        Get the visible (i.e. not hidden by CSS) inner text of the web element without any leading
                or trailing whitespace.

        :param locator: The string pattern to find the element or the web element itself.
        :param wait_state: The wait state for retrial. Choose state from ElementWaitState class.
        :param timeout: wait time before throwing any exception.
                    If None, timeout is set to default timeout.
        :return: inner html
        """

        outer_html = None
        try:

            if isinstance(locator, WebElement):
                outer_html = locator.get_attribute('outerHTML')
                element_text = locator.text

            else:
                element = Locator(self.context).get_element(locator, wait_state, True, timeout)
                outer_html = element.get_attribute('outerHTML')
                element_text = element.text

            self.context.logger.info(f'Successfully performed get text on `{outer_html}` html.'
                                     f'Text obtained `{element_text}` ')
            return element_text
        except Exception as ex:
            self.context.logger.error(f'Unable to get the text on the element `{outer_html}`. '
                                      'Error: {ex}')
            self.context.logger.exception(ex)
            raise Exception(
                f'Unable to get the text on the element `{outer_html}`. Error:{ex}')
    def take_screenshot(self, file_path=None, locator=None, wait_state=ElementWaitState.PRESENT,
                        timeout=None):

        """
        Takes the screenshot of entire page or a given element.

        :param file_path: Path+filename.png,  where the screenshot should be saved.
                Default: None - To save screenshot to screenshots folder.

        :param locator:  Web element or a locator string whose screenshot need to be taken.
                Default: None - To take entire screenshot.

        :param wait_state: he wait state for retrial. Choose state from ElementWaitState class.
        :param timeout: wait time before throwing any exception. If None, timeout is set to default timeout.
        :return: Boolean True if successful. False if there is any IOError.
        """

        element_to_log = None
        if file_path is None:
            if not os.path.exists('../../screenshots/'):
                self.context.logger.info(f"Trying to create a Screenshots directory.")
                os.makedirs('../../screenshots/')
                self.context.logger.info(f"Screenshots directory created.")

            file_path = f'{os.path.abspath("screenshots")}/{datetime.now().strftime("%Y_%m_%d_%H_%M_%S_%f")}' \
                        f'_{"ele " if locator is not None else "full_screen"}.png'

        try:
            parent_dir = Path(file_path).parent
            if not parent_dir.exists():
                self.context.logger.error(f'The parent directory `{parent_dir}` does not exist, '
                                          'Please provide a valid path !!')
                raise FileNotFoundError(f'The parent directory `{parent_dir}` does not exist, '
                                        'Please provide a valid path !!')
            if isinstance(locator, WebElement):
                element, element_to_log = locator, locator.get_attribute('outerHTML')
            else:
                element, element_to_log = Locator(self.context).get_element(locator, wait_state, True, timeout) \
                                              if locator is not None else None, locator
            if element is None:
                status = self.context.driver.save_screenshot(file_path)
            else:
                status = element.screenshot(file_path)
            self.context.logger.info(f'Successfully captured the screenshot of the '
                                     f'{"element " + element_to_log if element_to_log is not None else "entire page"} '
                                     f'to the file {file_path}')
            return status

        except Exception as ex:
            self.context.logger.error(f'Unable to take screenshot of the element {element_to_log}.')
            self.context.logger.exception(ex)
            raise Exception(
                f'Unable to take screenshot of the element {element_to_log}. Error: {ex}')
    def clear_text(self, locator, wait_state=ElementWaitState.PRESENT, timeout=None):
        """
        Clears the text if it’s a text entry element.

        :param locator:  Web element or a locator string on which the action need to be performed.
        :param wait_state: he wait state for retrial. Choose state from ElementWaitState class.
        :param timeout: wait time before throwing any exception. If None, timeout is set to default timeout.
        :return: self
        """
        element_to_log = None
        try:
            if locator is None:
                raise ValueError('Please provide the string pattern or a web element to perform an action.')

            element, element_to_log = (locator, locator.get_attribute('outerHTML')) \
                if isinstance(locator, WebElement) \
                else (Locator(self.context).get_element(locator, wait_state, True, timeout), locator)
            element.clear()
            self.context.logger.info('Successfully cleared the text from the input field '
                                     f'`{element_to_log}`')
            return self
        except ValueError:
            self.context.logger.error(
                'String pattern is None.'
                ' Please provide a valid pattern to locate the element and to perform an action.')
            raise ValueError
        except Exception as ex:
            self.context.logger.error(f'Unable to clear the text from input field `{element_to_log}`.')
            self.context.logger.exception(ex)
            raise Exception(
                f'Unable to clear the text from input field `{element_to_log}`. Error: {ex}')
    def get_rectangle(self, locator, wait_state=ElementWaitState.PRESENT, timeout=None):
        """
        A dictionary with the size and location of the element.
        :param locator:  Web element or a locator string on which the action need to be performed.
        :param wait_state: he wait state for retrial. Choose state from ElementWaitState class.
        :param timeout: wait time before throwing any exception. If None, timeout is set to default timeout.
        :return:  A dictionary with the size and location of the element.
        """

        element_to_log = None
        try:
            if locator is None:
                raise ValueError('Please provide the string pattern or a web element to perform an action.')
            element, element_to_log = (locator, locator.get_attribute('outerHTML')) \
                if isinstance(locator, WebElement) \
                else (Locator(self.context).get_element(locator, wait_state, True, timeout), locator)
            size = element.rect
            self.context.logger.info(f'Successfully performed get rect call on the '
                                     f'element {element_to_log}. The value is `{size}`.')
            return size
        except ValueError as val_ex:
            self.context.logger.error(
                f'ValueError occurred.')
            self.context.logger.exception(val_ex)
            raise ValueError

        except Exception as ex:
            self.context.logger.error(f'Unable to perform get rect on the element {element_to_log}.')
            self.context.logger.exception(ex)
            raise Exception(
                f'Unable to perform get rect on the element {element_to_log}. Error: {ex}')
    def submit_form(self, locator, wait_state=ElementWaitState.PRESENT, timeout=None):
        """
        Submits a form.
        If the current element is a form or an element within a form, then this will be submitted.
        :param locator:  Web element or a locator string on which the action need to be performed.
        :param wait_state: he wait state for retrial. Choose state from ElementWaitState class.
        :param timeout: wait time before throwing any exception. If None, timeout is set to default timeout.
        :return: self
        """

        element_to_log = None
        try:
            if locator is None:
                raise ValueError('Please provide the string pattern or a web element to perform an action.')

            element, element_to_log = (locator, locator.get_attribute('outerHTML')) \
                if isinstance(locator, WebElement) \
                else (Locator(self.context).get_element(locator, wait_state, True, timeout), locator)
            element.submit()
            self.context.logger.info('Successfully performed a submit action on the element '
                                     f'{element_to_log}')
            return self
        except Exception as ex:
            self.context.logger.error(
                f'Unable to submit the form from. Submit action performed on the element `{element_to_log}`.')
            self.context.logger.exception(ex)
            raise Exception(
                f'Unable to submit the form from. Submit action performed on the element `{element_to_log}`. '
                f'Error: {ex}')
    def get_property(self, locator, name, wait_state=ElementWaitState.PRESENT, timeout=None):
        """
        Gets the given property of the element.

        :param locator:  Web element or a locator string on which the action need to be performed.
        :param name: Name of the property
        :param wait_state: he wait state for retrial. Choose state from ElementWaitState class.
        :param timeout: wait time before throwing any exception. If None, timeout is set to default timeout.
        :return: the given property of the element.
        """
        element_to_log = None
        try:
            if locator is None:
                raise ValueError('Please provide the string pattern or a web element to perform an action.')
            if name is None:
                raise ValueError('Please provide the valid property name to perform an action.')
            element, element_to_log = (locator, locator.get_attribute('outerHTML')) \
                if isinstance(locator, WebElement) \
                else (Locator(self.context).get_element(locator, wait_state, True, timeout), locator)
            value = element.get_property(name)
            self.context.logger.info(f'Successfully performed get property call for \'{name}\' '
                                     f'on the element {element_to_log}. The retrieved value is `{value}.')
            return value
        except ValueError as val_ex:
            self.context.logger.error(
                f'ValueError occurred.')
            self.context.logger.exception(val_ex)
            raise ValueError
        except Exception as ex:
            self.context.logger.error(f'Unable to get property value for \'{name}\' on'
                                      f' the element {element_to_log}.')
            self.context.logger.exception(ex)

            raise Exception(f'Unable to get property value for \'{name}\' on the element '
                            f'{element_to_log}. Error: {ex}')
Exemplo n.º 7
0
    def drag_and_drop_by_offset(self,
                                src_locator,
                                x_offset,
                                y_offset,
                                wait_state=ElementWaitState.PRESENT,
                                timeout=None):
        """
        Drag an object and drop it to an offset location. Holds down the left mouse button on the source element,
        then moves to the target offset and releases the mouse button.

        :param src_locator: The element to mouse down. (element to be moved). Can be a locator string or an web element
        :param x_offset: X offset to move to
        :param y_offset: Y offset to move to.
        :param wait_state: he wait state for retrial. Choose state from ElementWaitState class.
        :param timeout: wait time before throwing any exception.
                    If None, timeout defaults to 20 seconds.
        :return: self
        """

        element_to_log = None
        try:

            if src_locator is None:
                raise ValueError(
                    'Please provide the `source` string pattern or a web element to perform drag and drop.'
                )

            if isinstance(src_locator, WebElement):
                element, element_to_log = src_locator, src_locator.get_attribute(
                    'outerHTML')
            else:
                element, element_to_log = Locator(self.context).get_element(src_locator, wait_state, True, timeout), \
                                          src_locator
            (ActionChains(self.context.driver).drag_and_drop_by_offset(
                element, x_offset, y_offset).perform())
            self.context.logger.info(
                f'Successfully moved the source element {element_to_log} by an offset {x_offset, y_offset}'
            )
            return self
        except ValueError:
            self.context.logger.error(
                f'Locator pattern is None. Please provide a valid `source`'
                f' pattern to locate the element and perform a drag and drop operation.'
            )

            raise ValueError
        except Exception as ex:
            self.context.logger.error(
                f'Unable to move the source element {element_to_log} by an offset {x_offset, y_offset}.'
            )
            self.context.logger.exception(ex)
            raise Exception(
                f'Unable to move the source element {element_to_log} by an offset {x_offset, y_offset}. Error: {ex}'
            )
    def is_element_visible(self, locator, timeout=None):
        """
        Verify if the given web element is visible.

        Criteria for visibility of an element:
            1. The element has an opacity greater than  0.
            2. There are no other elements hiding it.
            3. The element has the visibility property set to visible.
            4. The element has the display property not set none.

        :param locator: The string pattern to find the element or a web element to perform an action.
        :param timeout: wait time before throwing any exception.
                    If None, timeout is set to default timeout.
        :return: True if the given web element is visible else False.
        """
        # Set initial visibility to false
        is_ele_visible = False
        is_web_element = isinstance(locator, WebElement)
        _ele_to_log = None
        try:
            _ele_to_log = locator.get_attribute(
                'outerHTML') if is_web_element else locator

            if is_web_element:
                # if the locator is web element
                is_ele_visible = locator.is_displayed()
                self.context.logger.info(
                    f'Successfully checked for the visibility of the element `{_ele_to_log}`.'
                )
            else:
                # if locator is a pattern string
                element = Locator(self.context).get_element(
                    locator, ElementWaitState.VISIBLE, False, timeout)
                # if we find the web element
                if isinstance(element, WebElement):
                    self.context.logger.info(
                        f'The element `{_ele_to_log}` is visible on the web page.'
                    )
                    is_ele_visible = True
                else:
                    self.context.logger.error(
                        f'The element `{_ele_to_log}` is not visible on the web page.'
                    )
            return is_ele_visible
        except Exception as ex:
            self.context.logger.error(
                f'Unable to perform the visibility check on the element `{_ele_to_log}`.'
            )
            self.context.logger.exception(ex)
            raise Exception(
                f'Unable to perform the visibility check on the element `{_ele_to_log}`. Error:{ex}.'
            )
Exemplo n.º 9
0
    def move_cursor_to_element(self,
                               locator,
                               wait_state=ElementWaitState.PRESENT,
                               timeout=None):
        """
        Simulate users hovering a mouse over the given element.

        :param locator: Web element or a locator string on which the click action need to be performed
        :param wait_state: he wait state for retrial. Choose state from ElementWaitState class.
        :param timeout: wait time before throwing any exception.
                    If None, timeout defaults to 20 seconds.
        :return: self
        """
        element_to_log = None
        try:

            if locator is None:
                raise ValueError(
                    'Please provide the string pattern or a web element to perform an action.'
                )

            if isinstance(locator, WebElement):
                element, element_to_log = locator, locator.get_attribute(
                    'outerHTML')
            else:
                element, element_to_log = Locator(self.context).get_element(locator, wait_state, True, timeout) \
                                              if locator is not None else None, locator
            ActionChains(
                self.context.driver).move_to_element(element).perform()

            self.context.logger.info(
                f'Successfully moved the cursor on to the element {element_to_log}'
            )
            return self
        except ValueError:
            self.context.logger.error(
                'String pattern is None. Please provide a valid pattern to locate the element and perform an '
                'action.')
            raise ValueError

        except Exception as ex:
            self.context.logger.error(
                f'Unable to move the cursor to the element {element_to_log}.')
            self.context.logger.exception(ex)
            raise Exception(
                f'Unable to move to the element {element_to_log}. Error: {ex}')
    def get_all_dropdown_options(self,
                                 locator,
                                 wait_state=ElementWaitState.PRESENT,
                                 timeout=None):
        """
        Get a list of all options belonging to this select tag.

        :param locator:  Web element or a locator string on which the action need to be performed.
        :param wait_state: he wait state for retrial. Choose state from ElementWaitState class.
        :param timeout: wait time before throwing any exception. If None, timeout defaults to 20 seconds.
        :return: Returns a list of all options belonging to this select tag
        """
        element_to_log = None
        try:
            if locator is None:
                raise ValueError(
                    'Please provide the string pattern or a web element to perform an action'
                )

            element, element_to_log = (locator, locator.get_attribute('outerHTML')) \
                if isinstance(locator, WebElement) \
                else (Locator(self.context).get_element(locator, wait_state, True, timeout), locator)
            options = Select(element).options
            self.context.logger.info(
                f'Successfully retrieved {len(options)} options from the '
                f'dropdown element {element_to_log}')
            log_options = []
            for opt in options:
                log_options.append(opt.text)
            self.context.logger.info(
                f'The dropdown options are: { log_options}')
            return options
        except ValueError:
            self.context.logger.error(
                'String pattern is None.'
                ' Please provide a valid pattern to locate the element and to perform an action.'
            )
            raise ValueError

        except Exception as ex:
            self.context.logger.error(
                f'Unable to get all the options from the '
                f'dropdown element {element_to_log}, Error: {ex}')
            self.context.logger.exception(ex)
            raise Exception(f'Unable to get all the options from the '
                            f'dropdown element {element_to_log}, Error: {ex}')
    def get_dropdown_first_option(self,
                                  locator,
                                  wait_state=ElementWaitState.PRESENT,
                                  timeout=None):
        """
        Get the first dropdown option selected

        :param locator:  Web element or a locator string on which the action need to be performed.
        :param wait_state: he wait state for retrial. Choose state from ElementWaitState class.
        :param timeout: wait time before throwing any exception. If None, timeout defaults to 20 seconds.
        :return: Returns the first selected option in this select tag
         (or the currently selected option in a normal select)
        """

        element_to_log = None
        try:
            if locator is None:
                raise ValueError(
                    'Please provide the string pattern or a web element to perform an action'
                )

            element, element_to_log = (locator, locator.get_attribute('outerHTML')) \
                if isinstance(locator, WebElement) \
                else (Locator(self.context).get_element(locator, wait_state, True, timeout), locator)
            option_text = Select(element).first_selected_option.text
            self.context.logger.info(
                f'Successfully performed get first selected option call on the '
                f'dropdown element {element_to_log}. The selected option is `{option_text}`'
            )
            return option_text
        except ValueError:
            self.context.logger.error(
                'String pattern is None.'
                ' Please provide a valid pattern to locate the element and to perform an action.'
            )
            raise ValueError

        except Exception as ex:
            self.context.logger.error(
                f'Unable to get the first selected option from the '
                f'dropdown element {element_to_log}.')
            self.context.logger.exception(ex)
            raise Exception(
                f'Unable to get the first selected option from the '
                f'dropdown element {element_to_log}, Error: {ex}')
    def is_element_selected(self, locator, timeout=None):
        """
        Verify if the given web element is selected.

        :param locator: The string pattern to find the element.
        :param timeout: wait time before throwing any exception.
                    If None, timeout is set to default timeout.
        :return:True if the given web element is selected otherwise returns False.
        """

        is_selected = False
        is_web_element = isinstance(locator, WebElement)
        _ele_to_log = None
        if timeout is None:
            timeout = self.default_timeout
        try:
            _ele_to_log = locator.get_attribute(
                'outerHTML') if is_web_element else locator

            if is_web_element:
                is_selected = locator.is_selected()
                self.context.logger.info(
                    f'Successfully checked if the given element `{_ele_to_log}` is selected.'
                )
            else:
                try:
                    element = Locator(self.context).get_element(
                        locator, ElementWaitState.SELECTED, False, timeout)
                    if isinstance(element, WebElement):
                        self.context.logger.info(
                            f'The element {_ele_to_log} is already selected.')
                        is_selected = True
                except TimeoutException as t_ex:
                    self.context.logger.error(
                        f'The element {_ele_to_log} is not selected.')
            return is_selected
        except Exception as ex:
            self.context.logger.Error(
                f'Unable to verify if the given element {_ele_to_log} is selected.'
            )
            self.context.logger.exception(ex)
            raise Exception(
                f'Unable to verify if the given element {_ele_to_log} is selected. Error:{ex}'
            )
    def deselect_all_options_dropdown(self,
                                      locator,
                                      wait_state=ElementWaitState.PRESENT,
                                      timeout=None):
        """
        Deselect all options from multiselect.

        :param locator:  Web element or a locator string on which the action need to be performed.
        :param wait_state: he wait state for retrial. Choose state from ElementWaitState class.
        :param timeout: wait time before throwing any exception. If None, timeout defaults to 20 seconds.
        :return: self
        """
        element_to_log = None
        try:
            if locator is None:
                raise ValueError(
                    'Please provide the string pattern or a web element to perform an action'
                )

            element, element_to_log = (locator, locator.get_attribute('outerHTML')) \
                if isinstance(locator, WebElement) \
                else (Locator(self.context).get_element(locator, wait_state, True, timeout), locator)
            Select(element).deselect_all()
            self.context.logger.info(
                f'Successfully deselected all the options from the'
                f'multiselect dropdown element {element_to_log}')
            return self
        except ValueError:
            self.context.logger.error(
                'String pattern is None.'
                ' Please provide a valid pattern to locate the element and to perform an action.'
            )
            raise ValueError

        except Exception as ex:
            self.context.logger.error(
                f'Unable to deselect all options from the '
                f'multiselect dropdown element {element_to_log}.')
            self.context.logger.exception(ex)
            raise Exception(
                f'Unable to deselect all options from the '
                f'multiselect dropdown element {element_to_log}, Error: {ex}')
    def is_element_present(self, locator, timeout=None):
        """
        Verify if the given web element does present on DOM.
        :param locator: The string pattern to find the element.
        :param timeout: wait time before throwing any exception.
                    If None, timeout is set to default timeout.
        :return: True if the element is present on DOM else False.
        """

        is_ele_present = False
        element = Locator(self.context).get_element(locator,
                                                    ElementWaitState.PRESENT,
                                                    False, timeout)
        if isinstance(element, WebElement):
            self.context.logger.info(
                f'The given element {locator} does present on DOM.')
            is_ele_present = True
        else:
            self.context.logger.error(
                f'The given element `{locator}` does not present on DOM.')
        return is_ele_present
 def are_all_links_accessible(self):
     """
     Verify if all links (URLs) on the current page are accessible.
     :return: True if all links (URLs) on the current page are accessible else False
     """
     all_links_accessible = True
     broken_links = 0
     self.context.logger.info(
         'Trying to obtain all the links on the web page.')
     try:
         links = Locator(self.context).get_elements('<a>')
         self.context.logger.info(
             f'Successfully obtained {len(links)} links on the current web page.'
         )
         for link in links:
             link_text = link.get_attribute('href').strip()
             if link_text is not (None or ""):
                 r = requests.get(link_text)
                 self.context.logger.info(
                     f'URL:{link_text}, Status Code: {r.status_code}.')
                 if r.status_code != 200:
                     broken_links += 1
                     all_links_accessible = False
         if all_links_accessible:
             self.context.logger.info(
                 'Successfully verified if all links (URLs) on the current page are accessible '
                 'and all the links found to be accessible.')
         else:
             self.context.logger.error(
                 f'Successfully verified if all links (URLs) on the current page are accessible'
                 f' and found {broken_links} broken links.')
         return all_links_accessible
     except Exception as ex:
         self.context.logger.error(
             f'Unable to verify if all links (URLs) on the current page are accessible.'
         )
         self.context.logger.exception(ex)
         raise Exception(
             f'Unable to verify if all links (URLs) on the current page are accessible.'
         )
Exemplo n.º 16
0
    def move_cursor_to_element_by_offset(self,
                                         locator,
                                         x_offset,
                                         y_offset,
                                         wait_state=ElementWaitState.PRESENT,
                                         timeout=None):
        """
        Simulate users hovering a mouse over the given element with the relative position (x, y)
        from the top-left corner of that element.

        :param locator: locator: Web element or a locator string on which the click action need to be performed
        :param x_offset: X offset to move to, as a positive or negative integer.
        :param y_offset: Y offset to move to, as a positive or negative integer.
        :param wait_state: he wait state for retrial. Choose state from ElementWaitState class.
        :param timeout: wait time before throwing any exception.
                    If None, timeout defaults to 20 seconds.
        :return: self
        """
        element_to_log = None
        try:

            element, element_to_log = (locator, locator.get_attribute('outerHTML')) \
                if isinstance(locator, WebElement) \
                else (Locator(self.context).get_element(locator, wait_state, True, timeout), locator)

            (ActionChains(self.context.driver).move_to_element_with_offset(
                element, x_offset, y_offset).perform())

            self.context.logger.info(
                f'Successfully moved mouse pointer by an offset {x_offset, y_offset} '
                f'on the element {element_to_log}')
            return self
        except Exception as ex:
            self.context.logger.error(
                f'Unable to move by an offset {x_offset, y_offset} '
                f'on the element {element_to_log}')
            self.context.logger.exception(ex)
            raise Exception(
                f'Unable to move by an offset {x_offset, y_offset} to the '
                f'element {element_to_log}. Error: {ex}')
    def is_attribute_present(self, locator, attribute, timeout=None):
        """
        Verify if the web element has an attribute with the specified name.
        :param locator: The string pattern or web element to find the element.
        :param attribute: attribute name
        :param timeout: wait time before throwing any exception.
                    If None, timeout is set to default timeout.
        :return: True if the web element has an attribute with the specified name otherwise False
        """
        is_attr_present = False
        web_element = locator if isinstance(locator, WebElement) \
            else Locator(self.context).get_element(locator, ElementWaitState.PRESENT, False, timeout)
        element_to_log = locator if not isinstance(
            locator, WebElement) else locator.get_attribute('outerHTML')

        try:
            attribute_value = web_element.get_attribute(attribute)
            self.context.logger.info(
                f'Successfully retrieved the attribute with the specified name `{attribute}`'
                f' on the element `{element_to_log}`.')
            if attribute_value is not None:
                is_attr_present = True
                self.context.logger.info(
                    f'The web element `{element_to_log}` has an attribute with the specified name `{attribute}`.'
                )
            else:
                self.context.logger.info(
                    f'The web element `{element_to_log}` NOT have an attribute with the specified name `{attribute}`.'
                )
            return is_attr_present

        except Exception as ex:
            self.context.logger.Error(
                f'Unable to verify if the given element {element_to_log} has an attribute with the specified '
                f'name `{attribute}`.')
            self.context.logger.exception(ex)
            raise Exception(
                f'Unable to verify if the given element {element_to_log} has an attribute with the specified '
                f'name `{attribute}`. Error:{ex}')
    def is_element_clickable(self, locator, timeout=None):
        """
        Verify if the given element is clickable.
        :param locator: The string pattern or web element to find the element.
        :param timeout: wait time before throwing any exception.
                    If None, timeout is set to default timeout.
        :return: True if the given element is clickable otherwise False.
        """
        is_enabled = False
        is_web_element = isinstance(locator, WebElement)
        _ele_to_log = None
        try:
            _ele_to_log = locator.get_attribute(
                'outerHTML') if is_web_element else locator

            if is_web_element:
                is_enabled = locator.is_enabled() and locator.is_displayed()
                self.context.logger.info(
                    f'Successfully checked if the given element `{_ele_to_log}` is clickable.'
                )
            else:
                element = Locator(self.context).get_element(
                    locator, ElementWaitState.CLICKABLE, False, timeout)
                if isinstance(element, WebElement):
                    self.context.logger.info(
                        f'The element {_ele_to_log} is clickable.')
                    is_enabled = True
                else:
                    self.context.logger.info(
                        f'The element {_ele_to_log} is not clickable.')
            return is_enabled
        except Exception as ex:
            self.context.logger.Error(
                f'Unable to verify if the given element {_ele_to_log} is clickable.'
            )
            self.context.logger.exception(ex)
            raise Exception(
                f'Unable to verify if the given element {_ele_to_log} is clickable. Error:{ex}'
            )
    def is_element_not_visible(self, locator, timeout=None):
        """
        Verify if given web element is NOT visible.
        :param locator: The string pattern to find the element.
        :param timeout: wait time before throwing any exception.
                    If None, timeout is set to default timeout.
        :return: True if given web element is NOT visible else False.
        """
        is_ele_not_invisible = True
        element = Locator(self.context).get_element(locator,
                                                    ElementWaitState.INVISIBLE,
                                                    False, timeout)
        if isinstance(element, WebElement) or None:
            self.context.logger.error(
                f'The given web element `{locator}` is visible on the web page.'
            )
            is_ele_not_invisible = False
        else:
            self.context.logger.info(
                f'The given web element `{locator}` is NOT visible on the web page'
            )

        return is_ele_not_invisible
 def set_text(self, locator, text, clear_text=True, wait_state=ElementWaitState.PRESENT, timeout=None):
     """
     Set the value of an input field, as though you type it in.
     It also clears the previous value of the input field if clear_text is set to true.
     :param locator:
     :param text:
     :param clear_text: boolean value to clear the previous value of the input field
         Defaults to True
     :param wait_state: he wait state for element retrial. Choose state from ElementWaitState class.
         Defaults to ElementWaitState.PRESENT.
     :param timeout: wait time before throwing any exception.
                 If None, timeout is set to default timeout.
     :return: self
     """
     field_name = None
     try:
         if isinstance(locator, WebElement):
             field_name = locator.get_attribute('name')
             if clear_text:
                 locator.clear()
                 self.context.logger.info(
                     f'Successfully cleared the text from input field `Input Field Name: {field_name}`.')
             locator.send_keys(text)
         else:
             element = Locator(self.context).get_element(locator, wait_state, True, timeout)
             field_name = element.get_attribute('name')
             if clear_text:
                 element.clear()
                 self.context.logger.info(
                     f'Successfully cleared the text from input field `Input Field Name: {field_name}`.')
             element.send_keys(text)
         self.context.logger.info(
             f'Successfully entered the text \'{text}\' in the input field `Input Field Name:{field_name}`')
         return self
     except Exception as ex:
         self.context.logger.error(f'Unable to set the text \'{text}\' n the input field '
                                   f'`Input Field Name:{field_name}`.')
         self.context.logger.exception(ex)
         raise Exception('Unable to set the text \'{text}\' n the input field '
                         f'`Input Field Name:{field_name}`. Error: {ex}')
    def key_press_and_release(self, modifier_value, key, locator=None,
                              wait_state=ElementWaitState.PRESENT, timeout=None):
        """
        Sends a key press and releasing it.
            Should only be used with modifier keys (Control, Alt and Shift).
        :param modifier_value: Should be modifier keys (Control, Alt and Shift).
        :param key: The key to send.
         :param locator: The element to send keys. If None, sends a key to current focused element..
        :param wait_state: he wait state for retrial. Choose state from ElementWaitState class.
        :param timeout: wait time before throwing any exception. If None, timeout is set to default timeout.
        :return: self

        USAGE: key_press_and_release(KeyCode.CONTROL,'c')
        """
        element_to_log = None
        try:

            element, element_to_log = (locator, locator.get_attribute('outerHTML')) \
                if isinstance(locator, WebElement) \
                else (Locator(self.context).get_element(locator, wait_state, True, timeout)
                      if locator is not None else None, locator)

            ActionChains(self.context.driver)\
                .key_down(modifier_value, element)\
                .send_keys(key)\
                .key_up(modifier_value, element)\
                .perform()

            self.context.logger.info(f'Successfully performed key press and release '
                                     f'{(modifier_value, key)} on element {element_to_log}')
            return self
        except Exception as ex:
            self.context.logger.error(f'Unable to perform key press and release '
                                      f'{(modifier_value, key)} on element {element_to_log}.')
            self.context.logger.exception(ex)
            raise Exception(f'Unable to perform key press and release {(modifier_value, key)} '
                            f'on element{element_to_log}. Error: {ex}')
    def get_attribute(self, locator, attribute, wait_state=ElementWaitState.PRESENT, timeout=None):
        """
        Gets the given attribute or property of the element.

        :param locator:  Web element or a locator string on which the action need to be performed.
        :param attribute: attribute/ property
        :param wait_state: he wait state for retrial. Choose state from ElementWaitState class.
        :param timeout: wait time before throwing any exception. If None, timeout is set to default timeout.
        :return: This method will first try to return the value of a property with the given name.
         If a property with that name doesn't exist, it returns the value of the attribute with the same name.
         If there’s no attribute with that name, None is returned.
        """
        element_to_log = None
        try:
            if locator is None:
                raise ValueError('Please provide the string pattern or a web element to perform an action.')
            if attribute is None:
                raise ValueError('Please provide the valid attribute  to perform an action.')
            element, element_to_log = (locator, locator.get_attribute('outerHTML')) \
                if isinstance(locator, WebElement) \
                else (Locator(self.context).get_element(locator, wait_state, True, timeout), locator)
            value = element.get_attribute(attribute)
            self.context.logger.info(f'Successfully performed get attribute call for \'{attribute}\' '
                                     f'on the element {element_to_log}. The value obtained is: `{value}`')
            return value
        except ValueError as val_ex:
            self.context.logger.error(
                f'ValueError occurred.')
            self.context.logger.exception(val_ex)
            raise ValueError
        except Exception as ex:
            self.context.logger.error(f'Unable to get attribute value for \'{attribute}\' on the'
                                      f' element {element_to_log}.')
            self.context.logger.error(ex)
            raise Exception(f'Unable to get attribute value for \'{attribute}\' on the element '
                            f'{element_to_log}. Error: {ex}')
    def get_element(self,
                    pattern,
                    wait_state=ElementWaitState.PRESENT,
                    throw_exception=True,
                    timeout=None):
        """
                Returns the web element based the specified locator pattern or 'None' if the element is not found.

                :param pattern: The string pattern used to find the element on a web page.
                :param wait_state: Choose state from ElementWaitState class. Defaults to ElementWaitState.PRESENT.
                 Allowed states are
                    ElementWaitState.PRESENT,
                    ElementWaitState.VISIBLE,
                    ElementWaitState.INVISIBLE,
                    ElementWaitState.CLICKABLE,
                    ElementWaitState.SELECTED,
                    ElementWaitState.FRAME_AVAILABLE_AND_SWITCH_TO
                :param throw_exception: The boolean to throw exception or not.
                        Defaulted to true.
                :param timeout: wait time before throwing expectation.
                :return:  Web element
        """
        return Locator(self.context).get_element(pattern, wait_state,
                                                 throw_exception, timeout)
    def get_elements(self,
                     pattern,
                     wait_state=ElementWaitState.PRESENT_OF_ALL,
                     throw_exception=True,
                     timeout=None):
        """
                Returns the web elements based the specified locator pattern or 'None' no elements are found.

                :param pattern: The string pattern used to find the element on a web page.
                :param wait_state: Choose state from ElementWaitState class.
                Defaults to ElementWaitState.PRESENT.

                 Allowed states are
                 ElementWaitState.PRESENT_OF_ALL,
                 ElementWaitState.VISIBLE_OF_ALL,
                 ElementWaitState.VISIBLE_OF_ANY

                :param throw_exception: The boolean to throw exception or not.
                        Defaulted to true.
                :param timeout: wait time before throwing expectation.
                :return:  Web elements
        """
        return Locator(self.context).get_elements(pattern, wait_state,
                                                  throw_exception, timeout)
    def select_checkbox(self,
                        locator,
                        is_select,
                        wait_state=ElementWaitState.PRESENT,
                        timeout=None):
        """
        Select or unselect the checkbox.

        :param locator: Web element or a locator string on which the click action need to be performed.
        :param is_select: The boolean to perform select/unselect
        :param wait_state: he wait state for retrial. Choose state from ElementWaitState class.
        :param timeout: wait time before throwing any exception.
                    If None, timeout defaults to 20 seconds.
        :return: self
        """
        if locator is None:
            raise ValueError(
                'Please provide the string pattern or a web element to perform an action'
            )

        element, log_element = (locator, locator.get_attribute('outerHTML')) \
            if isinstance(locator, WebElement) \
            else (Locator(self.context).get_element(locator, wait_state, True, timeout), locator)
        try:

            if not element.is_selected() and is_select:
                # if checkbox is not selected and is_select is true
                element.click()
                self.context.logger.info(
                    f'Successfully selected the element {log_element}')
            elif element.is_selected() and not is_select:
                # if checkbox is selected and is_select is false
                element.click()
                self.context.logger.info(
                    f'Successfully unselected the element {log_element}')
            elif not element.is_selected() and not is_select:
                # if checkbox is not selected and is_select is false
                # element.click()
                self.context.logger.info(
                    f'The element {log_element} is already in unselected state.'
                )
            elif element.is_selected() and is_select:
                # if checkbox is selected and is_select is true
                # element.click()
                self.context.logger.info(
                    f'The element {log_element} is already in selected state')
            return self
        except ValueError:
            self.context.logger.error(
                'String pattern is None.'
                ' Please provide a valid pattern to locate the element and to perform an action.'
            )
            raise ValueError

        except Exception as ex:
            self.context.logger.error(
                f'Unable to select/unselect the element {log_element}.')
            self.context.logger.exception(ex)
            raise Exception(
                f'Unable to select/unselect the element {log_element}. Error: {ex}'
            )
    def select_dropdown(self,
                        locator,
                        select_by,
                        is_select,
                        values=None,
                        wait_state=ElementWaitState.PRESENT,
                        timeout=None):
        """
        Select an option or list of options at the given index, value or visible text.

        :param locator: Web element or a locator string on which the action need to be performed.
        :param select_by: Method to select a dropdown value. Should be a instance of SelectMethod enum class
        :param is_select: is a boolean value True: To select , False: to deselect in case of multiselect dropdown.
        :param values: A list of single or multiple indices, values or visible texts
        :param wait_state: he wait state for retrial. Choose state from ElementWaitState class.
        :param timeout: wait time before throwing any exception. If None, timeout defaults to 20 seconds.
        :return: self

        USAGE:  select_dropdown('#dropdown', SelectMethod.VALUE, True, ['Option One'])\n
                select_dropdown('#dropdown', SelectMethod.VALUE, True, ['Option One', 'Option Two'])\n
                select_dropdown('#dropdown', SelectMethod.INDEX, True, [1, 2])
        """
        if values is None:
            values = []
        element_to_log = None
        try:
            if len(values) <= 0:
                raise ValueError(
                    'Please provide one or more dropdown values or indices to perform the action.'
                )
            if locator is None:
                raise ValueError(
                    'Please provide the `Locator`string pattern or a web element to perform an action.'
                )
            if not isinstance(select_by, SelectMethod):
                self.context.logger.error(
                    '{strategy} must be an instance of SelectStrategy'.format(
                        strategy=repr(select_by)))
                raise TypeError(
                    '{strategy} must be an instance of SelectStrategy'.format(
                        strategy=repr(select_by)))

            element, element_to_log = (locator, locator.get_attribute('outerHTML')) \
                if isinstance(locator, WebElement) \
                else (Locator(self.context).get_element(locator, wait_state, True, timeout), locator)
            select = Select(element)
            if select_by is SelectMethod.VISIBLE_TEXT:
                self._select_by_visible_text(select, is_select, *values)
            if select_by is SelectMethod.VALUE:
                self._select_by_value(select, is_select, *values)
            if select_by is SelectMethod.INDEX:
                self._select_by_index(select, is_select, *values)
            self.context.logger.info(
                f'Successfully selected/deselected the item {values} on '
                f'the dropdown element {element_to_log}')
            return self
        # Exception Handling
        except ValueError as val_ex:
            self.context.logger.error(f'ValueError  occurred.')
            self.context.logger.exception(val_ex)
        except TypeError as tpe_ex:
            self.context.logger.error(f'TypeError occurred.')
            self.context.logger.exception(tpe_ex)
            raise TypeError
        except Exception as ex:
            self.context.logger.error(
                f'Unable to select/deselect the item {values} on the '
                f'dropdown element {element_to_log}. Error: {ex}')
            raise Exception(f'Unable to select the item {values} on the '
                            f'dropdown element {element_to_log}. Error: {ex}')
Exemplo n.º 27
0
    def drag_and_drop_to_object(self,
                                source,
                                target,
                                wait_state=ElementWaitState.PRESENT,
                                timeout=None):
        """
        Drag an object and drop it onto another object. Holds down the left mouse button on the source element,
        then moves to the target element and releases the mouse button.

        :param source: The element to mouse down. (element to be moved). Can be a locator string or an web element.
        :param target: The element to mouse up. (destination location). Can be locator string or an web element
        :param wait_state: he wait state for retrial. Choose state from ElementWaitState class.
        :param timeout: wait time before throwing any exception.
                    If None, timeout defaults to 20 seconds.
        :return: self
        """
        trg_element = None
        trg_element_to_log = None
        src_element_to_log = None
        try:
            if source is None:
                raise ValueError(
                    'Please provide the `source` string pattern or a web element to perform drag and drop.'
                )
            if target is None:
                raise ValueError(
                    'Please provide the `target` string pattern or a web element to perform a drag and drop.'
                )
            if isinstance(source, WebElement):
                src_element, src_element_to_log = source, source.get_attribute(
                    'outerHTML')
            else:
                src_element, src_element_to_log = Locator(
                    self.context).get_element(source, wait_state, True,
                                              timeout), source
            if isinstance(target, WebElement):
                src_element, trg_element_to_log = target, target.get_attribute(
                    'outerHTML')
            else:
                trg_element, trg_element_to_log = Locator(
                    self.context).get_element(target, wait_state, True,
                                              timeout), target

            (ActionChains(self.context.driver).drag_and_drop(
                src_element, trg_element).perform())
            self.context.logger.info(
                f'Successfully dragged from the source element '
                f'{src_element_to_log} and dropped onto target element {trg_element_to_log}'
            )
            return self
        except ValueError:
            self.context.logger.error(
                f'Locator pattern is None. Please provide a valid {"`source`" if source is None else "`target`"}'
                f' pattern to locate the element and perform a drag and drop operation.'
            )

            raise ValueError

        except Exception as ex:
            self.context.logger.error(
                f'Unable to drag and drop on elements {src_element_to_log} '
                f'and {trg_element_to_log}.')
            self.context.logger.exception(ex)
            raise Exception(
                f'Unable to drag and drop on elements {src_element_to_log} '
                f'and {trg_element_to_log}. Error: {ex}')
Exemplo n.º 28
0
    def click_web_element(self,
                          locator=None,
                          click_method=ClickMethod.API_CLICK,
                          wait_state=ElementWaitState.PRESENT,
                          timeout=None):
        """
        Simulates user clicking on an element with different click methods available.

        :param locator: Web element or a locator string on which the click action need to be performed
        :param click_method: Method to perform click and  by default  click_method=ClickMethod.API_CLICK
        Available methods are:
            API_CLICK
            JAVA_SCRIPT_CLICK
            ACTION_CHAIN_CLICK
        :param wait_state: he wait state for retrial. Choose state from ElementWaitState class.
        :param timeout: wait time before throwing any exception.
                    If None, timeout defaults to 20 seconds.
        :return: self
        """
        element_to_log = None
        try:
            if not isinstance(click_method, ClickMethod):
                raise TypeError(
                    f'`{click_method}` must be an instance of ClickMethod.')

            if locator is None:
                raise ValueError(
                    'Please provide the string pattern or a web element to perform a click'
                )

            if isinstance(locator, WebElement):
                element, element_to_log = locator, locator.get_attribute(
                    'outerHTML')
            else:
                element, element_to_log = Locator(self.context).get_element(
                    locator, wait_state, True, timeout), locator
            if click_method is ClickMethod.API_CLICK:
                element.click()
                self.context.logger.info(
                    f'Successfully clicked on the element {element_to_log}')
            if click_method is ClickMethod.JAVA_SCRIPT_CLICK:
                js_executor.execute_javascript('arguments[0].click();',
                                               element)
                self.context.logger.info(
                    f'Successfully clicked on the element {element_to_log}')
            if click_method is ClickMethod.ACTION_CHAIN_CLICK:
                ActionChains(self.context.driver).click(element).perform()
                self.context.logger.info(
                    f'Successfully clicked on the element {element_to_log}')
            return self
        except TypeError:
            self.context.logger.error(
                f'`{click_method}` must be an instance of ClickMethod')
            raise TypeError
        except ValueError:
            self.context.logger.error(
                'String pattern is None. Please provide a valid pattern to locate the element.'
            )
            raise ValueError
        except Exception as ex:
            self.context.logger.error(
                f'Unable to click on the element `{element_to_log}`.')
            self.context.logger.exception(ex)
            raise Exception(
                f'Unable to click on the element `{element_to_log}`. Error: {ex}'
            )