Beispiel #1
0
def exists(root, sub=None, and_is_not_greyed=False):
    """ Checks presence and usability of toolbar buttons.

    By default it checks whether the button is available, not caring whether it is greyed or not.
    You can optionally enable check for greyedness.

    Args:
        root: Button name.
        sub: Item name (optional)
        and_is_not_greyed: Check if the button is available to click.

    """
    sel.wait_for_ajax()
    if isinstance(root, dict):
        root = version.pick(root)
    if isinstance(sub, dict):
        sub = version.pick(sub)

    try:
        greyed = is_greyed(root, sub)
        if and_is_not_greyed:
            return not greyed
        else:
            return True
    except sel.NoSuchElementException:
        return False
    def update(self, updates, cancel=False, validate_credentials=False):
        """Updates the manager through UI

        args:
            updates (dict): Data to change.
            cancel (bool): Whether to cancel out of the update.  The cancel is done
                after all the new information has been filled in the UI.
            validate_credentials (bool): Whether to validate credentials - if True and the
                credentials are invalid, an error will be raised.

        Note:
            utils.update use is recommended over use of this method.
        """
        navigate_to(self, 'Edit')
        # Workaround - without this, update was failing on downstream appliance
        sel.wait_for_ajax()
        sel.wait_for_element(properties_form.name_text)

        fill(properties_form, self._form_mapping(**updates))
        fill(credential_form, updates.get('credentials', None), validate=validate_credentials)
        self._submit(cancel, edit_manager_btn)
        name = updates['name'] or self.name
        if not cancel:
            flash.assert_message_match('{} Provider "{}" was updated'.format(self.type, name))

        self.__dict__.update(**updates)
Beispiel #3
0
 def g(*args, **kwargs):
     sel.wait_for_ajax()  # Just in case
     error = sel.get_rails_error()
     if error is not None:
         raise CFMEExceptionOccured(
             "Flash message check failed because of following rails error:\n{}".format(error))
     return f(*args, **kwargs)
 def _custom_click_handler(self):
     """Handler called from pytest_selenium"""
     sel.wait_for_ajax()
     if self.is_dimmed and not self._force:
         logger.info("Not clicking {} because it is dimmed".format(repr(self)))
         return
     sel.wait_for_element(self, timeout=5)
     return sel.click(self, no_custom_handler=True)
Beispiel #5
0
    def f(_):
        # Can't do this currently because silly menu traps us
        # if is_page_active(toplevel, secondlevel):
        #     return
        if callable(toplevel):
            top_level = toplevel()
        else:
            top_level = toplevel

        if secondlevel is not None:
            if callable(secondlevel):
                second_level = secondlevel()
            else:
                second_level = secondlevel

            if secondlevel.startswith('/'):
                active_loc = (TOP_LEV_ACTIVE + SECOND_LEV_ACTIVE_HREF).format(
                    top_level, second_level)
                inactive_loc = (TOP_LEV_INACTIVE + SECOND_LEV_INACTIVE_HREF).format(
                    top_level, second_level)
            else:
                active_loc = (TOP_LEV_ACTIVE + SECOND_LEV_ACTIVE).format(top_level, second_level)
                inactive_loc = (TOP_LEV_INACTIVE + SECOND_LEV_INACTIVE).format(
                    top_level, second_level)
            el = "{} | {}".format(active_loc, inactive_loc)

            try:
                href = sel.get_attribute(el, 'href')
                sel.execute_script('document.location.href="{}"'.format(href))
            except NoSuchElementException:
                raise
        else:
            active_loc = TOP_LEV_ACTIVE.format(top_level)
            inactive_loc = TOP_LEV_INACTIVE.format(top_level)
            el = "{} | {}".format(active_loc, inactive_loc)

            try:
                href = sel.get_attribute(el, 'href')
                sel.execute_script('document.location.href="{}"'.format(href))
            except NoSuchElementException:
                raise
        sel.wait_for_ajax()
        if reset_action is not None:
            try:
                if callable(reset_action):
                    reset_action()
                else:
                    sel.click(reset_action)
            except NoSuchElementException:
                if _final:
                    # We have tried to renavigate but still some problem. Never mind and explode.
                    raise
                else:
                    # Work around the problem when the display selector disappears after returning
                    # from VM summary view. Can be fixed by renavigating, it then appears again.
                    nav_to_fn(toplevel, secondlevel, reset_action, _final=True)
        # todo move to element on the active tab to clear the menubox
        sel.wait_for_ajax()
Beispiel #6
0
 def update(self, updates):
     sel.force_navigate("cfg_tenant_project_edit", context={"tenant": self})
     # Workaround - without this, update was failing sometimes
     sel.wait_for_ajax()
     # Workaround - form is appearing after short delay
     sel.wait_for_element(self.tenant_form.description)
     fill(self.tenant_form, updates, action=self.save_changes)
     flash.assert_success_message(
         'Project "{}" was saved'.format(updates.get('name', self.name)))
def change_stored_password():
    if version.current_version() > '5.5':
        if sel.is_displayed(_stored_pw_script):
            sel.execute_script(
                sel.get_attribute(sel.element(_stored_pw_script), 'onClick'))
            sel.wait_for_ajax()  # To play safe
        elif sel.is_displayed(_stored_pw_angular):
            sel.click(_stored_pw_angular)
        else:
            logger.info("Probably no creds")
Beispiel #8
0
def delete(cancel=False):
    """Delete currently opened request

    Args:
        cancel: Whether to cancel the deletion.
    """
    sel.wait_for_element(buttons.delete)
    sel.click(buttons.delete, wait_ajax=False)
    sel.handle_alert(cancel)
    sel.wait_for_ajax()
    flash.assert_no_errors()
Beispiel #9
0
def login(user, submit_method=_js_auth_fn):
    """
    Login to CFME with the given username and password.
    Optionally, submit_method can be press_enter_after_password
    to use the enter key to login, rather than clicking the button.

    Args:
        user: The username to fill in the username field.
        password: The password to fill in the password field.
        submit_method: A function to call after the username and password have been input.

    Raises:
        RuntimeError: If the login fails, ie. if a flash message appears
    """

    if not user:
        username = conf.credentials['default']['username']
        password = conf.credentials['default']['password']
        cred = Credential(principal=username, secret=password)
        user = User(credential=cred)

    if not logged_in() or user.credential.principal is not current_username():
        if logged_in():
            logout()
        # workaround for strange bug where we are logged out
        # as soon as we click something on the dashboard
        sel.sleep(1.0)

        logger.debug('Logging in as user %s', user.credential.principal)
        try:
            fill(form, {'username': user.credential.principal, 'password': user.credential.secret})
        except sel.InvalidElementStateException as e:
            logger.warning("Got an error. Details follow.")
            msg = str(e).lower()
            if "element is read-only" in msg:
                logger.warning("Got a read-only login form, will reload the browser.")
                # Reload browser
                quit()
                ensure_browser_open()
                sel.sleep(1.0)
                sel.wait_for_ajax()
                # And try filling the form again
                fill(form, {'username': user.credential.principal,
                    'password': user.credential.secret})
            else:
                logger.warning("Unknown error, reraising.")
                logger.exception(e)
                raise
        with sel.ajax_timeout(90):
            submit_method()
        flash.assert_no_errors()
        user.full_name = _full_name()
        store.user = user
Beispiel #10
0
def old_select(root, sub=None, invokes_alert=False):
    """ Clicks on a button by calling the dhtmlx toolbar callEvent.

    Args:
        root: The root button's name as a string.
        sub: The sub button's name as a string. (optional)
        invokes_alert: If ``True``, then the behaviour is little bit different. After the last
            click, no ajax wait and no move away is done to be able to operate the alert that
            appears after click afterwards. Defaults to ``False``.
    Returns: ``True`` if everything went smoothly
    Raises: :py:class:`cfme.exceptions.ToolbarOptionGreyedOrUnavailable`
    """
    # wait for ajax on select to prevent pickup up a toolbar button in the middle of a page change
    sel.wait_for_ajax()
    if isinstance(root, dict):
        root = version.pick(root)
    if sub is not None and isinstance(sub, dict):
        sub = version.pick(sub)

    root_obj = version.pick({'5.4': 'miq_toolbars',
        '5.5.0.7': 'ManageIQ.toolbars'})

    if sub:
        search = sub_loc(sub)
    else:
        search = root_loc(root)

    eles = sel.elements(search)

    for ele in eles:
        idd = sel.get_attribute(ele, 'idd')
        if idd:
            break
    else:
        raise ToolbarOptionGreyedOrUnavailable(
            "Toolbar button {}/{} is greyed or unavailable!".format(root, sub))

    buttons = sel.execute_script('return {}'.format(root_obj))
    tb_name = None
    for tb_key, tb_obj in buttons.iteritems():
        for btn_key, btn_obj in tb_obj['buttons'].iteritems():
            if btn_obj['name'] == idd:
                tb_name = tb_key
    if not tb_name:
        raise ToolbarOptionGreyedOrUnavailable(
            "Toolbar button {}/{} is greyed or unavailable!".format(root, sub))

    sel.execute_script(
        "{}['{}']['obj'].callEvent('onClick', ['{}'])".format(root_obj, tb_name, idd))

    if not invokes_alert:
        sel.wait_for_ajax()
    return True
 def _set(self, op_interval=None, op_date=None, op_week=None, op_minute=None,
          force_by_text=False):
     self._object.load_chart_reference()
     if op_interval and op_interval != self.get_interval(force_visible_text=force_by_text):
         if force_by_text:
             self._interval.select_by_visible_text(op_interval)
         else:
             self._interval.select_by_value(op_interval)
         sel.wait_for_ajax()
     if op_date and op_date != self.get_date():
         web_ui.fill(self._date, op_date)
         sel.wait_for_ajax()
     if op_week and op_week != self.get_week(force_visible_text=force_by_text):
         if force_by_text:
             self._week.select_by_visible_text(op_week)
         else:
             self._week.select_by_value(op_week)
         sel.wait_for_ajax()
     if op_minute and op_minute != self.get_minute(force_visible_text=force_by_text):
         if force_by_text:
             self._minute.select_by_visible_text(op_minute)
         else:
             self._minute.select_by_value(op_minute)
         sel.wait_for_ajax()
     self._object.load_chart_reference(force_reload=True)
Beispiel #12
0
def select(root, sub=None, invokes_alert=False):
    """ Clicks on a button by calling the :py:meth:`click_n_move` method.

    Args:
        root: The root button's name as a string.
        sub: The sub button's name as a string. (optional)
        invokes_alert: If ``True``, then the behaviour is little bit different. After the last
            click, no ajax wait and no move away is done to be able to operate the alert that
            appears after click afterwards. Defaults to ``False``.
    Returns: ``True`` if everything went smoothly
    Raises: :py:class:`cfme.exceptions.ToolbarOptionGreyed`
    """
    # wait for ajax on select to prevent pickup up a toolbar button in the middle of a page change
    sel.wait_for_ajax()
    if isinstance(root, dict):
        root = version.pick(root)
    if sub is not None and isinstance(sub, dict):
        sub = version.pick(sub)
    if not is_greyed(root):
        try:
            if sub is None and invokes_alert:
                # We arrived into a place where alert will pop up so no moving and no ajax
                sel.click(root_loc(root), wait_ajax=False)
            else:
                select_n_move(root_loc(root))
        except sel.NoSuchElementException:
            raise ToolbarOptionUnavailable(
                "Toolbar button '{}' was not found.".format(root))
        except sel.StaleElementReferenceException:
            logger.debug('Stale toolbar button "{}", relocating'.format(root))
            select(root, sub, invokes_alert)
    else:
        raise ToolbarOptionGreyed("Toolbar button {} is greyed!".format(root))
    if sub:
        sel.wait_for_ajax()
        if not is_greyed(root, sub):
            try:
                if invokes_alert:
                    # We arrived into a place where alert will pop up so no moving and no ajax
                    sel.click(sub_loc(sub), wait_ajax=False)
                else:
                    select_n_move(sub_loc(sub))
            except sel.NoSuchElementException:
                raise ToolbarOptionUnavailable(
                    "Toolbar button '{}/{}' was not found.".format(root, sub))
        else:
            raise ToolbarOptionGreyed("Toolbar option {}/{} is greyed!".format(
                root, sub))
    return True
Beispiel #13
0
    def f(_):
        # Can't do this currently because silly menu traps us
        # if is_page_active(toplevel, secondlevel):
        #     return
        if callable(toplevel):
            top_level = toplevel()
        else:
            top_level = toplevel

        if secondlevel is not None:
            if callable(secondlevel):
                second_level = secondlevel()
            else:
                second_level = secondlevel

            if secondlevel.startswith('/'):
                active_loc = (TOP_LEV_ACTIVE + SECOND_LEV_ACTIVE_HREF).format(
                    top_level, second_level)
                inactive_loc = (TOP_LEV_INACTIVE + SECOND_LEV_INACTIVE_HREF).format(
                    top_level, second_level)
            else:
                active_loc = (TOP_LEV_ACTIVE + SECOND_LEV_ACTIVE).format(top_level, second_level)
                inactive_loc = (TOP_LEV_INACTIVE + SECOND_LEV_INACTIVE).format(
                    top_level, second_level)
            el = "{} | {}".format(active_loc, inactive_loc)

            try:
                href = sel.get_attribute(el, 'href')
                sel.execute_script('document.location.href="{}"'.format(href))
            except NoSuchElementException:
                raise
        else:
            active_loc = TOP_LEV_ACTIVE.format(top_level)
            inactive_loc = TOP_LEV_INACTIVE.format(top_level)
            el = "{} | {}".format(active_loc, inactive_loc)

            try:
                href = sel.get_attribute(el, 'href')
                sel.execute_script('document.location.href="{}"'.format(href))
            except NoSuchElementException:
                raise
        sel.wait_for_ajax()
        if reset_action is not None:
            if callable(reset_action):
                reset_action()
            else:
                sel.click(reset_action)
        # todo move to element on the active tab to clear the menubox
        sel.wait_for_ajax()
Beispiel #14
0
def select_security_group(sg):
    '''Workaround for select box that is immediately replaced by the same
       select box no matter what selenium clicks on (but works fine
       manually).  For now only selects one item even though it's a
       multiselect.

    '''
    val = sel.get_attribute("//select[@id='environment__security_groups']/option[.='%s']" %
                            sg, 'value')
    sel.browser().execute_script(
        "$j('#environment__security_groups').val('%s');"
        "$j.ajax({type: 'POST', url: '/miq_request/prov_field_changed/new',"
        " data: {'environment__security_groups':'%s'}})" % (val, val))
    sel.wait_for_ajax()
    sel.sleep(1)
Beispiel #15
0
def test_password_mismatch_validation(soft_assert):
    """ Tests password mismatch check """
    prov = HawkularProvider()
    cred = prov.Credential(
        principal='bad',
        secret=fauxfactory.gen_alphanumeric(5),
        verify_secret=fauxfactory.gen_alphanumeric(6)
    )
    navigate_to(prov, 'Add')
    fill(prov.properties_form, {"type_select": "Hawkular", "hostname_text": "test",
                                "name_text": "test", "port_text": "8080"})
    fill(cred.form, cred)
    sel.wait_for_ajax()
    soft_assert(not form_buttons.validate.can_be_clicked)
    soft_assert(not prov.add_provider_button.can_be_clicked)
    soft_assert(cred.form.default_verify_secret.angular_help_block == "Passwords do not match")
def select_security_group(sg):
    '''Workaround for select box that is immediately replaced by the same
       select box no matter what selenium clicks on (but works fine
       manually).  For now only selects one item even though it's a
       multiselect.

    '''
    val = sel.get_attribute(
        "//select[@id='environment__security_groups']/option[.='%s']" % sg,
        'value')
    sel.browser().execute_script(
        "$j('#environment__security_groups').val('%s');"
        "$j.ajax({type: 'POST', url: '/miq_request/prov_field_changed/new',"
        " data: {'environment__security_groups':'%s'}})" % (val, val))
    sel.wait_for_ajax()
    sel.sleep(1)
Beispiel #17
0
def pf_select(root, sub=None, invokes_alert=False):
    """ Clicks on a button by calling the click event with the jquery trigger.

    Args:
        root: The root button's name as a string.
        sub: The sub button's name as a string. (optional)
        invokes_alert: If ``True``, then the behaviour is little bit different. After the last
            click, no ajax wait and no move away is done to be able to operate the alert that
            appears after click afterwards. Defaults to ``False``.
    Returns: ``True`` if everything went smoothly
    Raises: :py:class:`cfme.exceptions.ToolbarOptionGreyedOrUnavailable`
    """

    sel.wait_for_ajax()
    if isinstance(root, dict):
        root = version.pick(root)
    if isinstance(sub, dict):
        sub = version.pick(sub)

    if sub:
        q_sub = xpath_quote(sub).replace("'", "\\'")
        sel.execute_script(
            "return $('a:contains({})').trigger('click')".format(q_sub))
    else:
        q_root = xpath_quote(root).replace("'", "\\'")
        try:
            sel.element("//button[@data-original-title = {0}] | "
                        "//a[@data-original-title = {0}]".format(q_root))
            sel.execute_script(
                "return $('*[data-original-title={}]').trigger('click')".format(q_root))
        except sel.NoSuchElementException:
            try:
                sel.element("//button[@title={}]".format(q_root))
                sel.execute_script(
                    "return $('button[title={}]').trigger('click')".format(q_root))
            except sel.NoSuchElementException:
                try:
                    sel.element("//button[contains(@title, {})]".format(q_root))
                    sel.execute_script(
                        "return $('button:contains({})').trigger('click')".format(q_root))
                except sel.NoSuchElementException:
                    # The view selection buttons?
                    sel.click("//li/a[@title={}]/*[self::i or self::img]/../..".format(q_root))

    if not invokes_alert:
        sel.wait_for_ajax()
    return True
Beispiel #18
0
def pf_select(root, sub=None, invokes_alert=False):
    """ Clicks on a button by calling the click event with the jquery trigger.

    Args:
        root: The root button's name as a string.
        sub: The sub button's name as a string. (optional)
        invokes_alert: If ``True``, then the behaviour is little bit different. After the last
            click, no ajax wait and no move away is done to be able to operate the alert that
            appears after click afterwards. Defaults to ``False``.
    Returns: ``True`` if everything went smoothly
    Raises: :py:class:`cfme.exceptions.ToolbarOptionGreyedOrUnavailable`
    """

    sel.wait_for_ajax()
    if isinstance(root, dict):
        root = version.pick(root)
    if isinstance(sub, dict):
        sub = version.pick(sub)

    if sub:
        q_sub = quoteattr(sub).replace("'", "\\'")
        sel.execute_script(
            "return $('a:contains({})').trigger('click')".format(q_sub))
    else:
        q_root = quoteattr(root).replace("'", "\\'")
        try:
            sel.element("//button[@data-original-title = {0}] | "
                        "//a[@data-original-title = {0}]".format(q_root))
            sel.execute_script(
                "return $('*[data-original-title={}]').trigger('click')".format(q_root))
        except sel.NoSuchElementException:
            try:
                sel.element("//button[@title={}]".format(q_root))
                sel.execute_script(
                    "return $('button[title={}]').trigger('click')".format(q_root))
            except sel.NoSuchElementException:
                try:
                    sel.element("//button[contains(@title, {})]".format(q_root))
                    sel.execute_script(
                        "return $('button:contains({})').trigger('click')".format(q_root))
                except sel.NoSuchElementException:
                    # The view selection buttons?
                    sel.click("//li/a[@title={}]/*[self::i or self::img]/../..".format(q_root))

    if not invokes_alert:
        sel.wait_for_ajax()
    return True
Beispiel #19
0
def login(username, password, submit_method=_js_auth_fn):
    """
    Login to CFME with the given username and password.
    Optionally, submit_method can be press_enter_after_password
    to use the enter key to login, rather than clicking the button.

    Args:
        user: The username to fill in the username field.
        password: The password to fill in the password field.
        submit_method: A function to call after the username and password have been input.

    Raises:
        RuntimeError: If the login fails, ie. if a flash message appears
    """
    if not logged_in() or username is not current_username():
        if logged_in():
            logout()
        # workaround for strange bug where we are logged out
        # as soon as we click something on the dashboard
        sel.sleep(1.0)

        logger.debug('Logging in as user %s' % username)
        try:
            fill(form, {'username': username, 'password': password})
        except sel.InvalidElementStateException as e:
            logger.warning("Got an error. Details follow.")
            msg = str(e).lower()
            if "element is read-only" in msg:
                logger.warning(
                    "Got a read-only login form, will reload the browser.")
                # Reload browser
                quit()
                ensure_browser_open()
                sel.sleep(1.0)
                sel.wait_for_ajax()
                # And try filling the form again
                fill(form, {'username': username, 'password': password})
            else:
                logger.warning("Unknown error, reraising.")
                logger.exception(e)
                raise
        with sel.ajax_timeout(90):
            submit_method()
        flash.assert_no_errors()
        thread_locals.current_user = User(username, password, _full_name())
Beispiel #20
0
        def f(_):
            # Can't do this currently because silly menu traps us
            # if is_page_active(toplevel, secondlevel):
            #     return
            if callable(toplevel):
                top_level = toplevel()
            else:
                top_level = toplevel

            if secondlevel is not None:
                if callable(secondlevel):
                    second_level = secondlevel()
                else:
                    second_level = secondlevel

                if secondlevel.startswith('/'):
                    active_loc = (cls.TOP_LEV_ACTIVE +
                                  cls.SECOND_LEV_ACTIVE_HREF).format(
                                      top_level, second_level)
                    inactive_loc = (cls.TOP_LEV_INACTIVE +
                                    cls.SECOND_LEV_INACTIVE_HREF).format(
                                        top_level, second_level)
                else:
                    active_loc = (cls.TOP_LEV_ACTIVE +
                                  cls.SECOND_LEV_ACTIVE).format(
                                      top_level, second_level)
                    inactive_loc = (cls.TOP_LEV_INACTIVE +
                                    cls.SECOND_LEV_INACTIVE).format(
                                        top_level, second_level)
                el = "{} | {}".format(active_loc, inactive_loc)
                cls._try_nav(el)

            else:
                active_loc = cls.TOP_LEV_ACTIVE.format(top_level)
                inactive_loc = cls.TOP_LEV_INACTIVE.format(top_level)
                el = "{} | {}".format(active_loc, inactive_loc)
                cls._try_nav(el)

            nav_fn = lambda: cls._nav_to_fn(
                toplevel, secondlevel, reset_action, _final=True)
            cls._try_reset_action(reset_action, _final, nav_fn)
            # todo move to element on the active tab to clear the menubox
            sel.wait_for_ajax()
Beispiel #21
0
def select(root, sub=None, invokes_alert=False):
    """ Clicks on a button by calling the :py:meth:`click_n_move` method.

    Args:
        root: The root button's name as a string.
        sub: The sub button's name as a string. (optional)
        invokes_alert: If ``True``, then the behaviour is little bit different. After the last
            click, no ajax wait and no move away is done to be able to operate the alert that
            appears after click afterwards. Defaults to ``False``.
    Returns: ``True`` if everything went smoothly
    Raises: :py:class:`cfme.exceptions.ToolbarOptionGreyed`
    """
    # wait for ajax on select to prevent pickup up a toolbar button in the middle of a page change
    sel.wait_for_ajax()
    if not is_greyed(root):
        try:
            if sub is None and invokes_alert:
                # We arrived into a place where alert will pop up so no moving and no ajax
                sel.click(root_loc(root), wait_ajax=False)
            else:
                select_n_move(root_loc(root))
        except sel.NoSuchElementException:
            raise ToolbarOptionUnavailable("Toolbar button '{}' was not found.".format(root))
        except sel.StaleElementReferenceException:
            logger.debug('Stale toolbar button "{}", relocating'.format(root))
            select(root, sub, invokes_alert)
    else:
        raise ToolbarOptionGreyed("Toolbar button {} is greyed!".format(root))
    if sub:
        sel.wait_for_ajax()
        if not is_greyed(root, sub):
            try:
                if invokes_alert:
                    # We arrived into a place where alert will pop up so no moving and no ajax
                    sel.click(sub_loc(sub), wait_ajax=False)
                else:
                    select_n_move(sub_loc(sub))
            except sel.NoSuchElementException:
                raise ToolbarOptionUnavailable("Toolbar button '{}/{}' was not found.".format(
                    root, sub))
        else:
            raise ToolbarOptionGreyed("Toolbar option {}/{} is greyed!".format(root, sub))
    return True
Beispiel #22
0
    def _try_nav(el, toplevel, secondlevel, thirdlevel=None):
        try:
            href = sel.get_attribute(el, 'href')
        except NoSuchElementException as e:
            # Make our own exception
            if thirdlevel is None:
                item = '{} / {}'.format(toplevel, secondlevel)
            else:
                item = '{} / {} / {}'.format(toplevel, secondlevel, thirdlevel)

            message = '\n'.join([
                'An error happened during selecting of the menu item: {}'.format(item),
                str(e).rstrip(),  # An extra newline at the end.
            ])

            raise MenuItemNotFound(message)

        sel.execute_script('document.location.href = arguments[0];', href)
        sel.wait_for_ajax()
        def set_relationship(self, server_name, server_id, click_cancel=False):
            self.navigate()
            option = "{} ({})".format(server_name, server_id)

            if click_cancel:
                fill(self.relationship_form, {'server_select': option},
                     action=self.relationship_form.cancel_button)
            else:
                fill(self.relationship_form, {'server_select': option},
                     action=self.relationship_form.save_button)
                # something weird going on where changing the select doesn't POST to undim save
                sel.wait_for_ajax()
                if self.relationship_form.save_button.is_dimmed:
                    logger.warning("Worked around dimmed save button")
                    sel.browser().execute_script(
                        "$j.ajax({type: 'POST', url: '/vm_infra/evm_relationship_field_changed',"
                        " data: {'server_id':'%s'}})" % (server_id))
                    sel.click(form_buttons.FormButton(
                        "Save Changes", dimmed_alt="Save", force_click=True))
                flash.assert_success_message("Management Engine Relationship saved")
def test_password_mismatch_validation(soft_assert):
    """ Tests password mismatch check """
    prov = HawkularProvider()
    cred = Credential(principal='bad',
                      secret=fauxfactory.gen_alphanumeric(5),
                      verify_secret=fauxfactory.gen_alphanumeric(6))
    navigate_to(prov, 'Add')
    fill(
        prov.properties_form, {
            "type_select": "Hawkular",
            "hostname_text": "test",
            "name_text": "test",
            "port_text": "8080"
        })
    fill(cred.form, cred)
    sel.wait_for_ajax()
    soft_assert(not form_buttons.validate.can_be_clicked)
    soft_assert(not prov.add_provider_button.can_be_clicked)
    soft_assert(cred.form.default_verify_secret.angular_help_block ==
                "Passwords do not match")
Beispiel #25
0
 def load_chart_reference(self, force_reload=False):
     """Takes current page to chart detailed page"""
     if self.is_on_chart_page and not force_reload:
         return
     if not self.is_on_chart_page:
         self._utz_object.reload()
     self._c_object = None
     if not self.is_on_chart_page:
         root_objs = sel.elements(CHARTS)
         for root_obj in root_objs:
             if sel.text_sane(
                     root_obj.find_element_by_tag_name('h2')) == self.name:
                 root_obj.find_element_by_tag_name("a").click()
                 sel.wait_for_ajax()
                 self._c_object = sel.element(CHARTS)
                 break
     else:
         self._c_object = sel.element(CHARTS)
     if self._c_object is None:
         raise RuntimeError("Unable to get detail page of '{}'".format(
             self.name))
     # remove old legends and load new legends
     for legend_id in self._legends:
         try:
             delattr(self, legend_id)
         except AttributeError:
             pass
     self._legends = []
     # load available legends
     for legend in sel.elements(self.LEGENDS):
         legend_text = sel.text_sane(legend)
         # changing legend name to full name with pre defined map
         legend_id = self._get_ui_key(
             attributize_string(legend_text.strip()))
         legend_object = Legend(name=legend_text, legend_object=legend)
         setattr(self, legend_id, legend_object)
         self._legends.append(legend_id)
     self._c_lines = self._c_object\
         .find_elements_by_xpath("//*[name()='g']//*[contains(@class, 'c3-target') "
                                 "and contains(@class, 'c3-chart-line')]")
Beispiel #26
0
        def f(_):
            # Can't do this currently because silly menu traps us
            # if is_page_active(toplevel, secondlevel):
            #     return
            if callable(toplevel):
                top_level = toplevel()
            else:
                top_level = toplevel

            if secondlevel is not None:
                if callable(secondlevel):
                    second_level = secondlevel()
                else:
                    second_level = secondlevel

                if secondlevel.startswith('/'):
                    active_loc = (cls.TOP_LEV_ACTIVE + cls.SECOND_LEV_ACTIVE_HREF).format(
                        top_level, second_level)
                    inactive_loc = (cls.TOP_LEV_INACTIVE + cls.SECOND_LEV_INACTIVE_HREF).format(
                        top_level, second_level)
                else:
                    active_loc = (cls.TOP_LEV_ACTIVE + cls.SECOND_LEV_ACTIVE).format(
                        top_level, second_level)
                    inactive_loc = (cls.TOP_LEV_INACTIVE + cls.SECOND_LEV_INACTIVE).format(
                        top_level, second_level)
                el = "{} | {}".format(active_loc, inactive_loc)
                cls._try_nav(el, toplevel, secondlevel)

            else:
                active_loc = cls.TOP_LEV_ACTIVE.format(top_level)
                inactive_loc = cls.TOP_LEV_INACTIVE.format(top_level)
                el = "{} | {}".format(active_loc, inactive_loc)
                cls._try_nav(el, toplevel, secondlevel)

            def nav_fn():
                return cls._nav_to_fn(toplevel, secondlevel, reset_action, _final=True)
            cls._try_reset_action(reset_action, _final, nav_fn)
            # todo move to element on the active tab to clear the menubox
            sel.wait_for_ajax()
        def set_relationship(self, server_name, server_id, click_cancel=False):
            self.navigate()
            option = "{} ({})".format(server_name, server_id)

            if click_cancel:
                fill(self.relationship_form, {'server_select': option},
                     action=self.relationship_form.cancel_button)
            else:
                fill(self.relationship_form, {'server_select': option},
                     action=self.relationship_form.save_button)
                # something weird going on where changing the select doesn't POST to undim save
                sel.wait_for_ajax()
                if self.relationship_form.save_button.is_dimmed:
                    logger.warning("Worked around dimmed save button")
                    sel.browser().execute_script(
                        "$j.ajax({type: 'POST', url: '/vm_infra/evm_relationship_field_changed',"
                        " data: {'server_id':'%s'}})" % (server_id))
                    sel.click(
                        form_buttons.FormButton("Save Changes",
                                                dimmed_alt="Save",
                                                force_click=True))
                flash.assert_success_message(
                    "Management Engine Relationship saved")
 def load_chart_reference(self, force_reload=False):
     """Takes current page to chart detailed page"""
     if self.is_on_chart_page and not force_reload:
         return
     if not self.is_on_chart_page:
         self._utz_object.reload()
     self._c_object = None
     if not self.is_on_chart_page:
         root_objs = sel.elements(CHARTS)
         for root_obj in root_objs:
             if sel.text_sane(root_obj.find_element_by_tag_name('h2')) == self.name:
                 root_obj.find_element_by_tag_name("a").click()
                 sel.wait_for_ajax()
                 self._c_object = sel.element(CHARTS)
                 break
     else:
         self._c_object = sel.element(CHARTS)
     if self._c_object is None:
         raise RuntimeError("Unable to get detail page of '{}'".format(self.name))
     # remove old legends and load new legends
     for legend_id in self._legends:
         try:
             delattr(self, legend_id)
         except AttributeError:
             pass
     self._legends = []
     # load available legends
     for legend in sel.elements(self.LEGENDS):
         legend_text = sel.text_sane(legend)
         # changing legend name to full name with pre defined map
         legend_id = self._get_ui_key(attributize_string(legend_text.strip()))
         legend_object = Legend(name=legend_text, legend_object=legend)
         setattr(self, legend_id, legend_object)
         self._legends.append(legend_id)
     self._c_lines = self._c_object\
         .find_elements_by_xpath("//*[name()='g']//*[contains(@class, 'c3-target') "
                                 "and contains(@class, 'c3-chart-line')]")
Beispiel #29
0
    def update(self, updates, cancel=False, validate_credentials=False):
        """Updates the manager through UI

        args:
            updates (dict): Data to change.
            cancel (bool): Whether to cancel out of the update.  The cancel is done
                after all the new information has been filled in the UI.
            validate_credentials (bool): Whether to validate credentials - if True and the
                credentials are invalid, an error will be raised.

        Note:
            utils.update use is recommended over use of this method.
        """
        sel.force_navigate('infrastructure_config_manager_edit', context={'manager': self})
        # Workaround - without this, update was failing on downstream appliance
        sel.wait_for_ajax()
        sel.wait_for_element(properties_form.name_text)

        fill(properties_form, self._form_mapping(**updates))
        fill(credential_form, updates.get('credentials', None), validate=validate_credentials)
        self._submit(cancel, edit_manager_btn)
        name = updates['name'] or self.name
        if not cancel:
            flash.assert_message_match('{} Provider "{}" was updated'.format(self.type, name))
Beispiel #30
0
def get_messages():
    """Return a list of flash messages"""
    sel.wait_for_ajax()
    return map(message, sel.elements(area.message))
Beispiel #31
0
def logged_in():
    ensure_browser_open()
    with sel.ajax_timeout(90):
        sel.wait_for_ajax()  # This is called almost everywhere, protects from spinner
    return sel.is_displayed(dashboard.page.user_dropdown)
Beispiel #32
0
def select_security_group(sg):
    """TODO: Not even sure this is needed any more, but removal of it is not part of this PR"""
    sel.wait_for_ajax()
    sel.sleep(1)
Beispiel #33
0
 def _try_nav(el):
     href = sel.get_attribute(el, 'href')
     sel.execute_script('document.location.href = arguments[0];', href)
     sel.wait_for_ajax()
Beispiel #34
0
 def select(self, *items):
     sel.wait_for_ajax()
     for item in items:
         self._select.select_by_visible_text(item)
Beispiel #35
0
def logged_in():
    ensure_browser_open()
    with sel.ajax_timeout(90):
        sel.wait_for_ajax(
        )  # This is called almost everywhere, protects from spinner
    return sel.is_displayed(dashboard.page.user_dropdown)
Beispiel #36
0
 def cfg_tenant_project_edit(_):
     tb_select("Edit this item")
     sel.wait_for_ajax()
Beispiel #37
0
 def cfg_tenant_project_edit(_):
     tb_select("Edit this item")
     sel.wait_for_ajax()
Beispiel #38
0
 def _try_nav(el):
     href = sel.get_attribute(el, 'href')
     sel.execute_script('document.location.href = arguments[0];', href)
     sel.wait_for_ajax()
Beispiel #39
0
def get_messages():
    """Return a list of visible flash messages"""
    sel.wait_for_ajax()
    return map(message, [e for e in sel.elements(area.message) if sel.is_displayed(e)])
Beispiel #40
0
def get_messages():
    """Return a list of flash messages"""
    sel.wait_for_ajax()
    return map(message, sel.elements(area.message))
Beispiel #41
0
 def select(self, *items):
     sel.wait_for_ajax()
     for item in items:
         self._select.select_by_visible_text(item)
Beispiel #42
0
def select_security_group(sg):
    """TODO: Not even sure this is needed any more, but removal of it is not part of this PR"""
    sel.wait_for_ajax()
    sel.sleep(1)
Beispiel #43
0
def get_messages():
    """Return a list of visible flash messages"""
    sel.wait_for_ajax()
    return map(message,
               [e for e in sel.elements(area.message) if sel.is_displayed(e)])