コード例 #1
0
ファイル: test_buttons.py プロジェクト: dajohnso/cfme_tests
def test_button_avp_displayed(dialog, request):
    """This test checks whether the Attribute/Values pairs are displayed in the dialog.
       automates 1229348
    Steps:
        * Open a dialog to create a button.
        * Locate the section with attribute/value pairs.
    """
    # This is optional, our nav tree does not have unassigned button
    buttongroup = ButtonGroup(
        text=fauxfactory.gen_alphanumeric(),
        hover="btn_desc_{}".format(fauxfactory.gen_alphanumeric()),
        type=ButtonGroup.VM_INSTANCE)
    request.addfinalizer(buttongroup.delete_if_exists)
    buttongroup.create()
    button = Button(group=buttongroup,
                    text=fauxfactory.gen_alphanumeric(),
                    hover="btn_hvr_{}".format(fauxfactory.gen_alphanumeric()),
                    dialog=dialog, system="Request", request="InspectMe")
    navigate_to(button, 'Add')
    section_loc = "//*[(self::h3 or self::p) and normalize-space(text())='Attribute/Value Pairs']"
    assert sel.is_displayed(section_loc),\
        "The Attribute/Value Pairs part of the form is not displayed"
    for i in range(1, 6):
        assert sel.is_displayed('#attribute_{}'.format(i))
        assert sel.is_displayed('#value_{}'.format(i))
コード例 #2
0
ファイル: vm.py プロジェクト: akrzos/cfme_tests
    def set_retirement_date(self, when, warn=None):
        """Sets the retirement date for this Vm object.

        It incorporates some magic to make it work reliably since the retirement form is not very
        pretty and it can't be just "done".

        Args:
            when: When to retire. :py:class:`str` in format mm/dd/yy of
                :py:class:`datetime.datetime` or :py:class:`utils.timeutil.parsetime`.
            warn: When to warn, fills the select in the form in case the ``when`` is specified.
        """
        self.load_details()
        lcl_btn("Set Retirement Date")
        if callable(self.retire_form.date_retire):
            # It is the old functiton
            sel.wait_for_element("#miq_date_1")
        else:
            sel.wait_for_element(self.retire_form.date_retire)
        if when is None:
            try:
                wait_for(lambda: sel.is_displayed(retire_remove_button), num_sec=5, delay=0.2)
                sel.click(retire_remove_button)
                wait_for(lambda: not sel.is_displayed(retire_remove_button), num_sec=10, delay=0.2)
                sel.click(form_buttons.save)
            except TimedOutError:
                pass
        else:
            if sel.is_displayed(retire_remove_button):
                sel.click(retire_remove_button)
                wait_for(lambda: not sel.is_displayed(retire_remove_button), num_sec=15, delay=0.2)
            fill(self.retire_form.date_retire, when)
            wait_for(lambda: sel.is_displayed(retire_remove_button), num_sec=15, delay=0.2)
            if warn is not None:
                fill(self.retire_form.warn, warn)
            sel.click(form_buttons.save)
コード例 #3
0
ファイル: accordion.py プロジェクト: anewmanRH/cfme_tests
def tree(name, *path):
    """Get underlying Tree() object. And eventually click path.

    If the accordion is not active, will be clicked.
    Attention! The object is 'live' so when it's obscured, it won't work!

    Usage:
        accordion.tree("Something").click_path("level 1", "level 2")
        accordion.tree("Something", "level 1", "level 2")  # is the same

    Args:
        *path: If specified, it will directly pass these parameters into click_path of Tree.
            Otherwise it returns the Tree object.
    """
    try:
        if not is_active(name):
            click(name)
    except AccordionItemNotFound:
        click(name)

    root_element = sel.element(locate(name))
    if sel.is_displayed(DYNATREE, root=root_element):
        # Dynatree detected
        tree = Tree(sel.element(DYNATREE, root=root_element))
    elif sel.is_displayed(TREEVIEW, root=root_element):
        # treeview detected
        el = sel.element(TREEVIEW, root=root_element)
        tree_id = sel.get_attribute(el, 'id')
        tree = BootstrapTreeview(tree_id)

    if path:
        return tree.click_path(*path)
    else:
        return tree
コード例 #4
0
ファイル: mixins.py プロジェクト: FilipB/cfme_tests
def left_half_size():
    if not sel.is_displayed(screen_splitter) or not sel.is_displayed(left_half):
        return None
    style = sel.get_attribute(left_half, "style")
    match = re.search(r"width:\s*(\d+)px", style)
    if match is None:
        return None
    return int(match.groups()[0])
コード例 #5
0
def fill_field(field=None, key=None, value=None):
    """ Fills the 'Field' type of form.

    Args:
        tag: Name of the field to compare (Host.VMs, ...).
        key: Operation to do (=, <, >=, IS NULL, ...).
        value: Value to check against.
    Returns: See :py:func:`cfme.web_ui.fill`.
    """
    field_norm = field.strip().lower()
    if "date updated" in field_norm or "date created" in field_norm or "boot time" in field_norm:
        no_date = None
    else:
        no_date = buttons.commit
    web_ui.fill(
        field_form,
        dict(
            type="Field",
            field=field,
            key=key,
            value=value if no_date else None
        ),
        action=no_date
    )
    if not no_date:
        # Flip the right part of form
        if isinstance(value, basestring) and not re.match(r"^[0-9]{2}/[0-9]{2}/[0-9]{4}$", value):
            if not sel.is_displayed(field_date_form.dropdown_select):
                sel.click(date_switch_buttons.to_relative)
            web_ui.fill(field_date_form, {"dropdown_select": value}, action=buttons.commit)
        else:
            # Specific selection
            if not sel.is_displayed(field_date_form.input_select_date):
                sel.click(date_switch_buttons.to_specific)
            if (isinstance(value, tuple) or isinstance(value, list)) and len(value) == 2:
                date, time = value
            elif isinstance(value, basestring):  # is in correct format mm/dd/yyyy
                # Date only (for now)
                date = value[:]
                time = None
            else:
                raise TypeError("fill_field expects a 2-tuple (date, time) or string with date")
            # TODO datetime.datetime support
            web_ui.fill(field_date_form.input_select_date, date)
            # Try waiting a little bit for time field
            # If we don't wait, committing the expression will glitch
            try:
                wait_for(lambda: sel.is_displayed(field_date_form.input_select_time), num_sec=6)
                # It appeared, so if the time is to be set, we will set it (passing None glitches)
                if time:
                    web_ui.fill(field_date_form.input_select_time, time)
            except TimedOutError:
                # Did not appear, ignore that
                pass
            finally:
                # And finally, commit the expression :)
                sel.click(buttons.commit)
コード例 #6
0
ファイル: test_stack.py プロジェクト: rananda/cfme_tests
def test_resources_link(stack):
    try:
        navigate_to(stack, 'RelationshipResources')
    except CandidateNotFound:
        # Assert there is a non-clickable anchor
        assert sel.is_displayed(
            '//div[@id="stack_rel"]//a[@href="#" and normalize-space(.)="Resources (0)"]')
    else:
        assert sel.is_displayed('//h1[contains(text(), "{} (Resources)")]'.format(stack.name))
コード例 #7
0
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")
コード例 #8
0
ファイル: dashboard.py プロジェクト: FilipB/cfme_tests
 def can_zoom(self):
     """Can this Widget be zoomed?"""
     self.close_zoom()
     if not self.newer_version:
         return sel.is_displayed(self._zoom.format(self._div_id))
     else:
         self.open_dropdown_menu()
         zoomable = sel.is_displayed(self._menu_zoom.format(self._div_id))
         self.close_dropdown_menu()
         return zoomable
コード例 #9
0
ファイル: test_stack.py プロジェクト: rananda/cfme_tests
def test_security_group_link(stack):
    try:
        navigate_to(stack, 'RelationshipSecurityGroups')
    except CandidateNotFound:
        # Assert there is a non-clickable anchor
        assert sel.is_displayed(
            '//div[@id="stack_rel"]//a[@href="#" and normalize-space(.)="Security Groups (0)"]')
    else:
        # Navigation successful, stack had security groups
        assert sel.is_displayed(
            '//h1[contains(text(), "{} (All Security Groups)")]'.format(stack.name))
コード例 #10
0
ファイル: menu.py プロジェクト: richardfontana/cfme_tests
def any_box_displayed():
    """Checks whether any of the not-currently-selected toplevel items is hovered (active).

    First part of the condition is for the 5.3+ pop-up, second is for 5.2.
    """
    return version.pick(
        {
            version.LOWEST: lambda: sel.is_displayed("//a[contains(@class, 'maintab_active')]", _no_deeper=True),
            "5.3": lambda: any(map(lambda e: sel.is_displayed(e, _no_deeper=True), sel.elements(Loc.inactive_box_loc))),
            "5.4": lambda: sel.is_displayed(
                "//li[contains(@class, 'dropdown') and contains(@class, 'open')]", _no_deeper=True
            ),
        }
    )()
コード例 #11
0
ファイル: tasks.py プロジェクト: quarckster/cfme_tests
def _filter(
        zone=None,
        user=None,
        time_period=None,
        task_status_queued=None,
        task_status_running=None,
        task_status_ok=None,
        task_status_error=None,
        task_status_warn=None,
        task_state=None):
    """ Does filtering of the results in table. Needs to be on the correct page before called.

    If there was no change in the form and the apply button does not appear, nothing happens.

    Args:
        zone: Value for 'Zone' select
        user: Value for 'User' select
        time_period: Value for 'Time period' select.
        task_status_*: :py:class:`bool` values for checkboxes
        task_state: Value for 'Task State' select.
    """
    fill(filter_form, locals())
    try:
        wait_for(lambda: sel.is_displayed(buttons.apply), num_sec=5)
        sel.click(buttons.apply)
    except TimedOutError:
        pass
コード例 #12
0
ファイル: provider.py プロジェクト: rrasouli/cfme_tests
 def wait_for_delete(self):
     # TODO: replace with navigate_to() once implemented for all provider types
     sel.force_navigate('{}_providers'.format(self.page_name))
     quad = Quadicon(self.name, self.quad_name)
     logger.info('Waiting for a provider to delete...')
     wait_for(lambda prov: not sel.is_displayed(prov), func_args=[quad], fail_condition=False,
              message="Wait provider to disappear", num_sec=1000, fail_func=sel.refresh)
コード例 #13
0
def load_filter(saved_filter=None, report_filter=None, cancel=False):
    """Load saved filter

    Args:
        saved_filter: `Choose a saved XYZ filter`
        report_filter: `Choose a XYZ report filter`
        cancel: Whether to cancel the load dialog without loading
    """
    ensure_advanced_search_open()
    if sel.is_displayed(search_box.load_filter_disabled):
        raise DisabledButtonException('Load Filter button disabled, '
            'cannot load filter: {}'.format(saved_filter))
    assert saved_filter is not None or report_filter is not None, "At least 1 param required!"
    assert (saved_filter is not None) ^ (report_filter is not None), "You must provide just one!"

    sel.click(search_box.load_filter_button)
    # We apply it to the whole form but it will fill only one of the selects
    if saved_filter is not None:
        fill(search_box.saved_filter, saved_filter)
    else:   # No other check needed, covered by those two asserts
        fill(search_box.report_filter, report_filter)
    button = search_box.cancel_load_filter_dialog_button if cancel \
        else search_box.load_filter_dialog_button

    return sel.click(button)
コード例 #14
0
ファイル: requests.py プロジェクト: petrblaho/cfme_tests
def wait_for_request(cells, partial_check=False):
    """helper function checks if a request is complete

    After finding the request's row using the ``cells`` argument, this will wait for a request to
    reach the 'Finished' state and return it. In the event of an 'Error' state, it will raise an
    AssertionError, for use with ``pytest.raises``, if desired.

    Args:
        cells: A dict of cells use to identify the request row to inspect in the
            :py:attr:`request_list` Table. See :py:meth:`cfme.web_ui.Table.find_rows_by_cells`
            for more.

    Usage:

        # Filter on the "Description" column
        description = 'Provision from [%s] to [%s]' % (template_name, vm_name)
        cells = {'Description': description}

        # Filter on the "Request ID" column
        # Text must match exactly, you can use "{:,}".format(request_id) to add commas if needed.
        request_id = '{:,}'.format(1000000000001)  # Becomes '1,000,000,000,001', as in the table
        cells = {'Request ID': request_id}

        # However you construct the cells dict, pass it to wait_for_request
        # Provisioning requests often take more than 5 minutes but less than 10.
        wait_for(wait_for_request, [cells], num_sec=600)

    Raises:
        AssertionError: if the matched request has status 'Error'
        RequestException: if multiple matching requests were found

    Returns:
         The matching :py:class:`cfme.web_ui.Table.Row` if found, ``False`` otherwise.
    """
    for page in paginator.pages():
        if sel.elements(request_list._header_loc) and not sel.is_displayed(request_list):
            # The table exists but it is hidden - no cells
            return False
        results = request_list.find_rows_by_cells(cells, partial_check)
        if len(results) == 0:
            # row not on this page, assume it has yet to appear
            continue
        elif len(results) > 1:
            raise RequestException(
                'Multiple requests with matching content found - be more specific!'
            )
        else:
            # found the row!
            row = results[0]
            logger.debug(' Request Message: %s' % row.last_message.text)
            break
    else:
        # Request not found at all, can't continue
        return False

    assert row.status.text != 'Error'
    if row.request_state.text == 'Finished':
        return row
    else:
        return False
コード例 #15
0
 def can_be_clicked(self):
     """Whether the button is displayed, therefore clickable."""
     try:
         sel.move_to_element(self)
         return sel.is_displayed(self)
     except NoSuchElementException:
         return False
コード例 #16
0
ファイル: search.py プロジェクト: jkrocil/cfme_tests
def _process_user_filling(fill_callback, cancel_on_user_filling=False):
    """This function handles answering CFME's requests on user input.

    A `fill_callback` function is passed. If the box with user input appears, all requested
    inputs are gathered and iterated over. On each element the `fill_callback` function is called
    with 2 parameters: text which precedes the element itself to do matching, and the element.

    This function does not check return status after `fill_callback` call.

    Args:
        fill_callback: The function to be called on each user input.
    """
    if sel.is_displayed(search_box.quick_search_box):  # That is the one with user inputs
        if fill_callback is None:
            raise Exception("User should have provided a callback function!")
        if isinstance(fill_callback, dict):
            fill_callback = partial(_answering_function, fill_callback)
        for input in sel.elements(
                "//fieldset/*[contains(@id, 'value_')]",
                root=sel.element(search_box.quick_search_box)):
            fill_callback(  # Let the func fill it
                sel.text(input.find_element_by_xpath("..")),    # Parent element's text
                input  # The form element
            )
        if cancel_on_user_filling:
            sel.click(search_box.userinput_cancel_button)
        else:
            sel.click(search_box.userinput_apply_filter_button)
コード例 #17
0
ファイル: dashboard.py プロジェクト: dajohnso/cfme_tests
 def can_zoom(self):
     """Can this Widget be zoomed?"""
     self.close_zoom()
     self.open_dropdown_menu()
     zoomable = sel.is_displayed(self._menu_zoom.format(self._div_id))
     self.close_dropdown_menu()
     return zoomable
コード例 #18
0
def fill_count(count=None, key=None, value=None):
    """ Fills the 'Count of' type of form.

    If the value is unspecified and we are in the advanced search form (user input), the user_input
    checkbox will be checked if the value is None.

    Args:
        count: Name of the field to compare (Host.VMs, ...).
        key: Operation to do (=, <, >=, ...).
        value: Value to check against.
    Returns: See :py:func:`cfme.web_ui.fill`.
    """
    fill(
        count_form,
        dict(
            type="Count of",
            count=count,
            key=key,
            value=value,
        ),
    )
    # In case of advanced search box
    if sel.is_displayed(field_form.user_input):
        user_input = value is None
    else:
        user_input = None
    fill(field_form.user_input, user_input)
    sel.click(buttons.commit)
コード例 #19
0
ファイル: toolbar.py プロジェクト: MattLombana/cfme_tests
def refresh():
    """Refreshes page, attempts to use cfme refresh button otherwise falls back to browser refresh.
    """
    if sel.is_displayed("//div[@title='Reload current display']"):
        sel.click("//div[@title='Reload current display']")
    else:
        sel.refresh()
コード例 #20
0
ファイル: search.py プロジェクト: ManageIQ/integration_tests
def apply_filter():
    """Applies an existing filter"""
    ensure_advanced_search_open()
    if sel.is_displayed(search_box.apply_filter):
        return sel.click(search_box.apply_filter_button)
    else:
        return False
コード例 #21
0
ファイル: providers.py プロジェクト: seandst/cfme_tests
def _setup_providers(cloud_or_infra, validate, check_existing):
    """Helper to set up all cloud or infra providers, and then validate them

    Args:
        cloud_or_infra: Like the name says: 'cloud' or 'infra' (a string)
        validate: see description in :py:func:`setup_provider`
        check_existing: see description in :py:func:`setup_provider`

    Returns:
        A list of provider objects that have been created.

    """
    # Pivot behavior on cloud_or_infra
    options_map = {
        'cloud': {
            'navigate': 'clouds_providers',
            'quad': 'cloud_prov',
            'list': list_cloud_providers
        },
        'infra': {
            'navigate': 'infrastructure_providers',
            'quad': 'infra_prov',
            'list': list_infra_providers
        }
    }
    # Check for existing providers all at once, to prevent reloading
    # the providers page for every provider in cfme_data
    if not options_map[cloud_or_infra]['list']():
        return []
    if check_existing:
        sel.force_navigate(options_map[cloud_or_infra]['navigate'])
        add_providers = []
        for provider_key in options_map[cloud_or_infra]['list']():
            provider_name = conf.cfme_data.get('management_systems', {})[provider_key]['name']
            quad = Quadicon(provider_name, options_map[cloud_or_infra]['quad'])
            for page in paginator.pages():
                if sel.is_displayed(quad):
                    logger.debug('Provider "%s" exists, skipping' % provider_key)
                    break
            else:
                add_providers.append(provider_key)
    else:
        # Add all cloud or infra providers unconditionally
        add_providers = options_map[cloud_or_infra]['list']()

    if add_providers:
        logger.info('Providers to be added: %s' % ', '.join(add_providers))

    # Save the provider objects for validation and return
    added_providers = []

    for provider_name in add_providers:
        # Don't validate in this step; add all providers, then go back and validate in order
        provider = setup_provider(provider_name, validate=False, check_existing=False)
        added_providers.append(provider)

    if validate:
        map(methodcaller('validate'), added_providers)

    return added_providers
コード例 #22
0
ファイル: instance.py プロジェクト: seandst/cfme_tests
    def on_details(self, force=False):
        """A function to determine if the browser is already on the proper instance details page.
        """
        locator = ("//div[@class='dhtmlxInfoBarLabel' and contains(. , 'Instance \"%s\"')]" %
            self.name)

        # If the locator isn't on the page, or if it _is_ on the page and contains
        # 'Timelines' we are on the wrong page and take the appropriate action
        if not sel.is_displayed(locator):
            wrong_page = True
        else:
            wrong_page = 'Timelines' in sel.text(locator)

        if wrong_page:
            if not force:
                return False
            else:
                self.load_details()
                return True

        text = sel.text(locator).encode("utf-8")
        pattern = r'("[A-Za-z0-9_\./\\-]*")'
        import re
        m = re.search(pattern, text)

        if not force:
            return self.name == m.group().replace('"', '')
        else:
            if self.name != m.group().replace('"', ''):
                self.load_details()
                return True
            else:
                return True
コード例 #23
0
    def _find_quadicon(self, is_vm=True, do_not_navigate=False, mark=False, refresh=True):
        """Find and return a quadicon belonging to a specific vm

        Returns: :py:class:`cfme.web_ui.Quadicon` instance
        Raises: VmNotFound
        """
        quadicon = Quadicon(self.name, "vm")
        if not do_not_navigate:
            if is_vm:
                self.provider_crud.load_all_provider_vms()
            else:
                self.provider_crud.load_all_provider_templates()
            toolbar.set_vms_grid_view()
        elif refresh:
            sel.refresh()
        if not paginator.page_controls_exist():
            if is_vm:
                raise VmNotFound("VM '{}' not found in UI!".format(self.name))
            else:
                raise TemplateNotFound("Template '{}' not found in UI!".format(self.name))

        paginator.results_per_page(1000)
        for page in paginator.pages():
            if sel.is_displayed(quadicon):
                if mark:
                    sel.check(quadicon.checkbox())
                return quadicon
        else:
            raise VmNotFound("VM '{}' not found in UI!".format(self.name))
コード例 #24
0
ファイル: toolbar.py プロジェクト: anewmanRH/cfme_tests
def refresh():
    """Refreshes page, attempts to use cfme refresh button otherwise falls back to browser refresh.
    """
    if sel.is_displayed(RELOAD_LOC):
        sel.click(RELOAD_LOC)
    else:
        sel.refresh()
コード例 #25
0
ファイル: instance.py プロジェクト: seandst/cfme_tests
    def find_quadicon(
            self, do_not_navigate=False, mark=False, refresh=True, from_any_provider=False):
        """Find and return a quadicon belonging to a specific instance

        Args:
            from_any_provider: Whether to look for it anywhere (root of the tree). Useful when
                looking up archived or orphaned VMs

        Returns: :py:class:`cfme.web_ui.Quadicon` instance
        Raises: InstanceNotFound
        """
        if not do_not_navigate:
            if from_any_provider:
                sel.force_navigate("clouds_instances")
            elif not self.provider_crud.load_all_provider_instances():
                raise InstanceNotFound("No instances for the provider!")
            toolbar.set_vms_grid_view()
        elif refresh:
            sel.refresh()
        if not paginator.page_controls_exist():
            raise InstanceNotFound("Instance '{}' not found in UI!".format(self.name))

        paginator.results_per_page(1000)
        for page in paginator.pages():
            quadicon = Quadicon(self.name, "instance")
            if sel.is_displayed(quadicon):
                if mark:
                    sel.check(quadicon.checkbox())
                return quadicon
        else:
            raise InstanceNotFound("Instance '{}' not found in UI!".format(self.name))
コード例 #26
0
 def _get_value(self, element, force_visible_text):
     self._object.load_chart_reference()
     if not sel.is_displayed(element):
         return None
     if force_visible_text:
         return element.first_selected_option_text
     return element.first_selected_option.value
コード例 #27
0
ファイル: __init__.py プロジェクト: jteehan/cfme_tests
 def load(self):
     self._keys = []
     key_values = []
     if sel.is_displayed(self.MULTIKEY_LOC, root=self._entry):
         # WE cannot process this kind of table yet.
         return
     for row in sel.elements(self.ROWS, root=self._entry):
         tds = sel.elements('./td', root=row)
         key = tds[0]
         klass = sel.get_attribute(key, 'class')
         if klass and 'label' in klass:
             # Ordinary field
             key_id = attributize_string(sel.text_sane(key))
             value = tuple(tds[1:])
             try:
                 rowspan = int(sel.get_attribute(key, 'rowspan'))
             except (ValueError, TypeError):
                 rowspan = None
             if rowspan:
                 key_values.append((key, key_id, [value]))
             else:
                 key_values.append((key, key_id, value))
         else:
             # value of last key_values should be extended
             key_values[-1][2].append(tuple(tds))
     for key, key_id, value in key_values:
         value_object = process_field(value)
         setattr(self, key_id, value_object)
         self._keys.append(key_id)
コード例 #28
0
ファイル: tasks.py プロジェクト: ManageIQ/integration_tests
def _get_tasks(tab_destination, **filter_kwargs):
    """ Generic function to return contents of the tasks table

    Args:
        location: Location for :py:module:`ui_navigate` where to get the data.
        **filter_kwargs: See :py:meth:`_filter`
    Returns: List of dicts.
    """
    navigate_to(Tasks, tab_destination)
    if any([filter_kwargs[key] is not None for key in filter_kwargs.keys()]):
        _filter(**filter_kwargs)
    tasks = []

    if sel.is_displayed(tasks_table):
        for page in paginator.pages():
            for row in tasks_table.rows():
                tasks.append(
                    dict(
                        updated=parsetime.from_american_with_utc(
                            row.updated.text.encode('utf-8').strip()
                        ),
                        started=parsetime.from_american_with_utc(
                            row.started.text.encode('utf-8').strip()
                        ),
                        state=row.state.text.encode('utf-8').strip(),
                        message=row.message.text.encode('utf-8').strip(),
                        task_name=row.task_name.text.encode('utf-8').strip(),
                        user=row.user.text.encode('utf-8').strip()
                    )
                )
    else:
        logger.info('No Tasks collected on {}'.format(tab_destination))
    return tasks
コード例 #29
0
 def exists(self):
     navigate_to(self, 'All')
     for page in paginator.pages():
         if sel.is_displayed(Quadicon(self.name, 'host')):
             return True
     else:
         return False
コード例 #30
0
ファイル: provider.py プロジェクト: slouderm/cfme_tests
 def exists(self):
     sel.force_navigate('infrastructure_providers')
     for page in paginator.pages():
         if sel.is_displayed(Quadicon(self.name, 'infra_prov')):
             return True
     else:
         return False
コード例 #31
0
 def close_dropdown_menu(self):
     if not sel.is_displayed(self._menu_opener.format(self._div_id)):
         return  # Not a 5.5+
     if self.is_dropdown_menu_opened:
         sel.click(self._menu_opener.format(self._div_id))
         wait_for(
             lambda: not self.is_dropdown_menu_opened,
             num_sec=10, delay=0.2, message="widget dropdown menu closed")
コード例 #32
0
ファイル: stack.py プロジェクト: richardfontana/cfme_tests
 def wait_for_delete(self):
     sel.force_navigate("clouds_stacks")
     quad = Quadicon(self.name, 'stack')
     wait_for(lambda: not sel.is_displayed(quad),
              fail_condition=False,
              message="Wait stack to disappear",
              num_sec=500,
              fail_func=sel.refresh)
コード例 #33
0
def is_active(name):
    """ Checks if an accordion is currently open

    Args:
        name: The name of the accordion.
    Returns: ``True`` if the button is depressed, ``False`` if not.
    """
    return sel.is_displayed(_content_element(name))
コード例 #34
0
ファイル: resource_pool.py プロジェクト: vrutkovs/cfme_tests
 def exists(self):
     try:
         sel.force_navigate('infrastructure_resource_pool', context=self._get_context())
         quad = Quadicon(self.name, 'resource_pool')
         if sel.is_displayed(quad):
             return True
     except sel.NoSuchElementException:
         return False
コード例 #35
0
def reset_page():
    tb.select("Grid View")
    if sel.is_displayed(search_box.search_field):
        search.ensure_normal_search_empty()
    if paginator.page_controls_exist():
        # paginator.results_per_page(1000)
        sel.check(paginator.check_all())
        sel.uncheck(paginator.check_all())
コード例 #36
0
def is_advanced_search_opened():
    """Checks whether the advanced search box is currently opened"""
    # Covers advanced search sub-forms as well - user-input, load, and save
    return any(
        sel.is_displayed(loc) for loc in [
            search_box.advanced_search_box_visible, search_box.
            quick_search_box, search_box.saved_filter, search_box.save_name
        ])
コード例 #37
0
 def exists(self):
     try:
         navigate_to(self, 'Details')
         quad = Quadicon(self.name, self.quad_name)
         if sel.is_displayed(quad):
             return True
     except sel.NoSuchElementException:
         return False
コード例 #38
0
    def find_quadicon(self,
                      do_not_navigate=False,
                      mark=False,
                      refresh=True,
                      from_any_provider=False,
                      use_search=True):
        """Find and return a quadicon belonging to a specific vm

        Args:
            from_any_provider: Whether to look for it anywhere (root of the tree). Useful when
                looking up archived or orphaned VMs

        Returns: :py:class:`cfme.web_ui.Quadicon` instance
        Raises: VmOrInstanceNotFound
        """
        quadicon = Quadicon(self.name, self.quadicon_type)
        if not do_not_navigate:
            if from_any_provider:
                # TODO implement as navigate_to when cfme.infra.virtual_machines has destination
                navigate_to(self, 'All')
            elif self.is_vm:
                navigate_to(self, 'AllForProvider', use_resetter=False)
            else:
                navigate_to(self, 'AllForProvider', use_resetter=False)
            toolbar.select('Grid View')
        else:
            # Search requires navigation, we shouldn't use it then
            use_search = False
            if refresh:
                sel.refresh()
        if not paginator.page_controls_exist():
            if self.is_vm:
                raise VmOrInstanceNotFound("VM '{}' not found in UI!".format(
                    self.name))
            else:
                raise TemplateNotFound("Template '{}' not found in UI!".format(
                    self.name))

        paginator.results_per_page(1000)
        if use_search:
            try:
                if not search.has_quick_search_box():
                    # TODO rework search for archived/orphaned VMs
                    if self.is_vm:
                        navigate_to(self, 'AllForProvider', use_resetter=False)
                    else:
                        navigate_to(self, 'AllForProvider', use_resetter=False)
                search.normal_search(self.name)
            except Exception as e:
                logger.warning("Failed to use search: %s", str(e))
        for page in paginator.pages():
            if sel.is_displayed(quadicon, move_to=True):
                if mark:
                    sel.check(quadicon.checkbox())
                return quadicon
        else:
            raise VmOrInstanceNotFound("VM '{}' not found in UI!".format(
                self.name))
コード例 #39
0
 def is_dimmed(self):
     locator = (
         "({TAG_TYPES})[{ALT_EXPR} and {DIMMED} and {TYPE_CONDITION} and {IS_DISPLAYED} "
         "and {ON_CURRENT_TAB}]"
         "|"  # A bit different type of a button
         "({TAG_TYPES})[normalize-space(.)={DIMMED_ALT} and {IS_DISPLAYED} and "
         "(@disabled='true' or contains(@class, 'btn-disabled')) and {ON_CURRENT_TAB}]"
         .format(**self._format_generator(dimmed=True, include_dimmed_alt=True)))
     return sel.is_displayed(locator)
コード例 #40
0
 def opened_boxes_ids(self):
     """Return ids of all opened boxes."""
     return [
         # it's like 's_3'
         int(sel.get_attribute(el, "id").rsplit("_", 1)[-1])
         for el in sel.elements(
             "//div[@title='Drag this Shortcut to a new location']")
         if sel.is_displayed(el)
     ]
コード例 #41
0
ファイル: host.py プロジェクト: jdemon519/cfme_tests
def wait_for_host_delete(host):
    navigate_to(Host, 'All')
    quad = Quadicon(host.name, 'host')
    logger.info('Waiting for a host to delete...')
    wait_for(lambda: not sel.is_displayed(quad),
             fail_condition=False,
             message="Wait host to disappear",
             num_sec=500,
             fail_func=sel.refresh)
コード例 #42
0
 def close_dropdown_menu(self):
     if not sel.is_displayed(self._menu_opener.format(self._div_id)):
         return  # Not a 5.5+
     if self.is_dropdown_menu_opened:
         sel.click("//a[contains(@class, 'navbar-brand')]/img")
         wait_for(lambda: not self.is_dropdown_menu_opened,
                  num_sec=10,
                  delay=0.2,
                  message="widget dropdown menu closed")
コード例 #43
0
 def is_dimmed(self):
     return sel.is_displayed("//img[@alt='{}' and contains(@class, 'dimmed')"
         " and (contains(@class, 'button') or contains(@src, 'button'))"
         " and not(ancestor::*[contains(@style, 'display:none')"
         " or contains(@style, 'display: none')])]|//button[.='{}' and @disabled='true'"
         " and not(ancestor::*[contains(@style, 'display:none')"
         " or contains(@style, 'display: none')])]|".format(
             self._dimmed_alt or self._alt, self._dimmed_alt or self._alt
         ))
コード例 #44
0
def _setup_providers(prov_class, validate, check_existing):
    """Helper to set up all cloud, infra or container providers, and then validate them

    Args:
        prov_class: Provider class - 'cloud, 'infra', 'container' or 'middleware' (a string)
        validate: see description in :py:func:`setup_provider`
        check_existing: see description in :py:func:`setup_provider`

    Returns:
        A list of provider objects that have been created.

    """

    # Check for existing providers all at once, to prevent reloading
    # the providers page for every provider in cfme_data
    if not list_providers(BaseProvider.type_mapping[prov_class]):
        return []
    if check_existing:
        navigate = "{}_providers".format(
            BaseProvider.type_mapping[prov_class].values()[0].page_name)
        sel.force_navigate(navigate)
        add_providers = []
        for provider_key in list_providers(
                BaseProvider.type_mapping[prov_class].keys()):
            provider_name = conf.cfme_data.get('management_systems',
                                               {})[provider_key]['name']
            quad_name = BaseProvider.type_mapping[prov_class].values(
            )[0].quad_name
            quad = Quadicon(provider_name, quad_name)
            for page in paginator.pages():
                if sel.is_displayed(quad):
                    logger.debug('Provider %s exists, skipping', provider_key)
                    break
            else:
                add_providers.append(provider_key)
    else:
        # Add all cloud, infra or container providers unconditionally
        add_providers = list_providers(
            BaseProvider.type_mapping[prov_class].keys())

    if add_providers:
        logger.info('Providers to be added: %s', ', '.join(add_providers))

    # Save the provider objects for validation and return
    added_providers = []

    for provider_name in add_providers:
        # Don't validate in this step; add all providers, then go back and validate in order
        provider = setup_provider(provider_name,
                                  validate=False,
                                  check_existing=False)
        added_providers.append(provider)

    if validate:
        map(methodcaller('validate'), added_providers)

    return added_providers
コード例 #45
0
def get_all_messages():
    """Returns a list of all flash messages, (including ones hidden behind
    the currently showing one, if any).  All flash messages will be
    dismissed."""
    all_messages = []
    while sel.is_displayed(area.message):
        all_messages = all_messages + get_messages()
        dismiss()
    return all_messages
コード例 #46
0
ファイル: search.py プロジェクト: jkrocil/integration_tests
def delete_filter(cancel=False):
    """If possible, deletes the currently loaded filter."""
    ensure_advanced_search_open()
    if sel.is_displayed(search_box.delete_filter_button):
        sel.click(search_box.delete_filter_button, wait_ajax=False)
        sel.handle_alert(cancel)
        return True
    else:
        return False
コード例 #47
0
ファイル: vm.py プロジェクト: dgur/integration_tests
    def set_retirement_date(self, when, warn=None):
        """Sets the retirement date for this Vm object.

        It incorporates some magic to make it work reliably since the retirement form is not very
        pretty and it can't be just "done".

        Args:
            when: When to retire. :py:class:`str` in format mm/dd/yyyy of
                :py:class:`datetime.datetime` or :py:class:`utils.timeutil.parsetime`.
            warn: When to warn, fills the select in the form in case the ``when`` is specified.
        """
        # TODO: refactor for retirement nav destinations and widget form fill when child classes
        self.load_details()
        lcl_btn("Set Retirement Date")
        if callable(self.retire_form.date_retire):
            # It is the old functiton
            sel.wait_for_element("#miq_date_1")
        else:
            sel.wait_for_element(self.retire_form.date_retire)
        if when is None:
            try:
                wait_for(lambda: sel.is_displayed(retire_remove_button),
                         num_sec=5,
                         delay=0.2)
                sel.click(retire_remove_button)
                wait_for(lambda: not sel.is_displayed(retire_remove_button),
                         num_sec=10,
                         delay=0.2)
                sel.click(form_buttons.save)
            except TimedOutError:
                pass
        else:
            if sel.is_displayed(retire_remove_button):
                sel.click(retire_remove_button)
                wait_for(lambda: not sel.is_displayed(retire_remove_button),
                         num_sec=15,
                         delay=0.2)
            fill(self.retire_form.date_retire, when)
            wait_for(lambda: sel.is_displayed(retire_remove_button),
                     num_sec=15,
                     delay=0.2)
            if warn is not None:
                fill(self.retire_form.warn, warn)
            sel.click(form_buttons.save)
コード例 #48
0
 def is_datastore_analysis_finished():
     """ Check if analysis is finished - if not, reload page
     """
     if not sel.is_displayed(tasks.tasks_table) or not tabs.is_tab_selected('All Other Tasks'):
         sel.force_navigate('tasks_all_other')
     host_analysis_finished = tasks.tasks_table.find_row_by_cells({
         'task_name': "SmartState Analysis for [{}]".format(datastore_name),
         'state': 'Finished'
     })
     return host_analysis_finished is not None
コード例 #49
0
ファイル: host.py プロジェクト: jkrocil/integration_tests
def wait_for_host_delete(host):
    sel.force_navigate('infrastructure_hosts')
    quad = Quadicon(host.name, 'host')
    logger.info('Waiting for a host to delete...')
    wait_for(lambda prov: not sel.is_displayed(prov),
             func_args=[quad],
             fail_condition=False,
             message="Wait host to disappear",
             num_sec=1000,
             fail_func=sel.refresh)
コード例 #50
0
 def exists(self):
     sel.force_navigate('infrastructure_repositories')
     try:
         if current_version() >= '5.4':
             quadicon = Quadicon(self.name, "repository")
             return sel.is_displayed(quadicon.locate())
         else:
             return bool(_repo_row(self.name))
     except:  # exception?
         return False
コード例 #51
0
ファイル: __init__.py プロジェクト: jdemon519/cfme_tests
    def step(self):
        self.prerequisite_view.navigation.select('Compute', 'Clouds',
                                                 'Instances')

        # use accordion
        # If a filter was applied, it will persist through navigation and needs to be cleared
        if sel.is_displayed(search_box.clear_advanced_search):
            logger.debug('Clearing advanced search filter')
            sel.click(search_box.clear_advanced_search)
        accordion.tree('Instances', 'All Instances')
コード例 #52
0
 def wait_for_delete(self):
     navigate_to(self, 'All')
     quad = Quadicon(self.name, self.quad_name)
     logger.info('Waiting for a provider to delete...')
     wait_for(lambda prov: not sel.is_displayed(prov),
              func_args=[quad],
              fail_condition=False,
              message="Wait provider to disappear",
              num_sec=1000,
              fail_func=sel.refresh)
コード例 #53
0
ファイル: login.py プロジェクト: vprusa/cfme_tests
def logout():
    """
    Logs out of CFME.
    """
    if logged_in():
        if not sel.is_displayed(page.logout):
            sel.click(dashboard.page.user_dropdown)
        sel.click(page.logout, wait_ajax=False)
        sel.handle_alert(wait=False)
        store.user = None
コード例 #54
0
 def datasources(cls, provider=None, server=None):
     datasources = []
     _get_datasources_page(provider=provider, server=server)
     if sel.is_displayed(list_tbl):
         for _ in paginator.pages():
             for row in list_tbl.rows():
                 _server = MiddlewareServer(provider=provider, name=row.server.text)
                 datasources.append(MiddlewareDatasource(provider=provider, server=_server,
                                                         name=row.datasource_name.text))
     return datasources
コード例 #55
0
    def equal_drift_results(self, row_text, section, *indexes):
        """ Compares drift analysis results of a row specified by it's title text

        Args:
            row_text: Title text of the row to compare
            section: Accordion section where the change happened; this section must be activated
            indexes: Indexes of results to compare starting with 0 for first row (latest result).
                     Compares all available drifts, if left empty (default).

        Note:
            There have to be at least 2 drift results available for this to work.

        Returns:
            ``True`` if equal, ``False`` otherwise.
        """
        # mark by indexes or mark all
        sel.force_navigate('infrastructure_host', context={'host': self})
        list_acc.select('Relationships',
            version.pick({
                version.LOWEST: 'Show host drift history',
                '5.4': 'Show Host drift history'}))
        if indexes:
            drift_table.select_rows_by_indexes(*indexes)
        else:
            # We can't compare more than 10 drift results at once
            # so when selecting all, we have to limit it to the latest 10
            if len(list(drift_table.rows())) > 10:
                drift_table.select_rows_by_indexes(*range(0, 10))
            else:
                drift_table.select_all()
        tb.select("Select up to 10 timestamps for Drift Analysis")

        # Make sure the section we need is active/open
        sec_loc_map = {
            'Properties': 'Properties',
            'Security': 'Security',
            'Configuration': 'Configuration',
            'My Company Tags': 'Categories'}
        active_sec_loc = "//div[@id='all_sections_treebox']//li[contains(@id, 'group_{}')]"\
            "/span[contains(@class, 'dynatree-selected')]".format(sec_loc_map[section])
        sec_checkbox_loc = "//div[@id='all_sections_treebox']//li[contains(@id, 'group_{}')]"\
            "//span[contains(@class, 'dynatree-checkbox')]".format(sec_loc_map[section])
        sec_apply_btn = "//div[@id='accordion']/a[contains(normalize-space(text()), 'Apply')]"

        # If the section is not active yet, activate it
        if not sel.is_displayed(active_sec_loc):
            sel.click(sec_checkbox_loc)
            sel.click(sec_apply_btn)

        if not tb.is_active("All attributes"):
            tb.select("All attributes")
        d_grid = DriftGrid()
        if any(d_grid.cell_indicates_change(row_text, i) for i in range(0, len(indexes))):
            return False
        return True
コード例 #56
0
    def copy_to(self, domain=None):
        self._open_copy_dialog()
        if isinstance(domain, Domain):
            domain_name = domain.name
        else:
            domain_name = str(domain)
        if sel.is_displayed(self.copy_form.domain):
            fill(self.copy_form, {"domain": domain_name, "override": True})
        else:
            # If there is only one domain, therefore the select is not present, only text
            domain_selected = sel.text(self.copy_form.domain_text_only).strip()
            if domain_selected != domain_name:
                raise ValueError(
                    "There is only one domain to select and that is {}".format(
                        domain_selected))
            fill(self.copy_form, {"override": True})
        sel.click(self.copy_button)
        flash.assert_message_match(
            "Copy selected Automate {} was saved".format(self.class_name))

        # Bunch'o functions that copy the chain to the domain and change domain's name
        def _change_path_in_namespace(o, new_domain_name):
            if isinstance(o, Domain):
                if isinstance(new_domain_name, Domain):
                    return new_domain_name
                new_domain = copy(o)
                new_domain.name = new_domain_name
                return new_domain
            else:
                new_obj = copy(o)
                if new_obj.parent is None:
                    # This should happen in the domain part of this func so Error here
                    raise Exception(
                        "It is not expected that {} has no parent!".format(
                            type(new_obj).__name__))
                new_obj.parent = _change_path_in_namespace(
                    new_obj.parent, new_domain_name)
                return new_obj

        def _change_parent_path_until_namespace(obj, new_domain_name):
            if isinstance(obj, Namespace):
                return _change_path_in_namespace(obj, new_domain_name)
            else:
                new_obj = copy(obj)
                if new_obj.parent is None:
                    # This should happen in the namespace func so Error here
                    raise Exception(
                        "It is not expected that {} has no parent!".format(
                            type(new_obj).__name__))
                new_obj.parent = _change_parent_path_until_namespace(
                    new_obj.parent, new_domain_name)
                return new_obj

        return _change_parent_path_until_namespace(self, domain)
コード例 #57
0
def test_delete_stack(setup_provider, provider, provisioning, request):
    """ Tests delete stack

    Metadata:
        test_flag: delete_object
    """
    stack = Stack(provisioning['stack'], provider=provider)
    refresh_and_wait(provider, stack)
    stack.delete()
    navigate_to(stack, 'All')
    assert lambda: not sel.is_displayed(Quadicon(stack.name, stack.quad_name))
コード例 #58
0
 def deployments(cls, provider=None, server=None):
     deployments = []
     _get_deployments_page(provider=provider, server=server)
     if sel.is_displayed(list_tbl):
         _provider = provider  # In deployment UI, we cannot get provider name on list all page
         for _ in paginator.pages():
             for row in list_tbl.rows():
                 _server = MiddlewareServer(provider=provider, name=row.server.text)
                 deployments.append(MiddlewareDeployment(provider=_provider, server=_server,
                                                         name=row.deployment_name.text))
     return deployments
コード例 #59
0
ファイル: pxe.py プロジェクト: richardfontana/cfme_tests
def remove_all_pxe_servers():
    """
    Convenience function to remove all PXE servers
    """
    logger.debug('Removing all PXE servers')
    sel.force_navigate('infrastructure_pxe_servers')
    sel.force_navigate('infrastructure_pxe_servers')  # Yes we really do this twice.
    if sel.is_displayed(pxe_server_table_exist):
        sel.click(pg.check_all())
        cfg_btn('Remove PXE Servers from the VMDB', invokes_alert=True)
        sel.handle_alert(cancel=False)
コード例 #60
0
ファイル: vm.py プロジェクト: pavelzag/cfme_tests
    def find_quadicon(
            self, do_not_navigate=False, mark=False, refresh=True, from_any_provider=False,
            use_search=True):
        """Find and return a quadicon belonging to a specific vm

        Args:
            from_any_provider: Whether to look for it anywhere (root of the tree). Useful when
                looking up archived or orphaned VMs

        Returns: :py:class:`cfme.web_ui.Quadicon` instance
        Raises: VmOrInstanceNotFound
        """
        quadicon = Quadicon(self.name, self.quadicon_type)
        if not do_not_navigate:
            if from_any_provider:
                sel.force_navigate(self.ALL_LIST_LOCATION)
            elif self.is_vm:
                self.provider.load_all_provider_vms()
            else:
                self.provider.load_all_provider_templates()
            toolbar.select('Grid View')
        else:
            # Search requires navigation, we shouldn't use it then
            use_search = False
            if refresh:
                sel.refresh()
        if not paginator.page_controls_exist():
            if self.is_vm:
                raise VmOrInstanceNotFound("VM '{}' not found in UI!".format(self.name))
            else:
                raise TemplateNotFound("Template '{}' not found in UI!".format(self.name))

        # this is causing some issues in 5.5.0.9, commenting out for a bit
        # paginator.results_per_page(1000)
        if use_search:
            try:
                if not search.has_quick_search_box():
                    # We don't use provider-specific page (vm_templates_provider_branch) here
                    # as those don't list archived/orphaned VMs
                    if self.is_vm:
                        sel.force_navigate(self.provider.instances_page_name)
                    else:
                        sel.force_navigate(self.provider.templates_page_name)
                search.normal_search(self.name)
            except Exception as e:
                logger.warning("Failed to use search: %s", str(e))

        for page in paginator.pages():
            if sel.is_displayed(quadicon, move_to=True):
                if mark:
                    sel.check(quadicon.checkbox())
                return quadicon
        else:
            raise VmOrInstanceNotFound("VM '{}' not found in UI!".format(self.name))