Example #1
0
 def download(self, extension):
     self.navigate()
     toolbar.select("Download")
     sel.click(
         "//table[contains(@class, 'buttons_cont')]"
         "//img[contains(@class, 'btn_sel_img') and contains(@src, '{}.png')]".format(extension)
     )
def test_summary_pages_links(provider, cls):

    navigate_to(cls.object, "All")
    all_url = sel.current_url()
    tb.select("List View")
    name = choice([r[2].text for r in list_tbl.rows()])
    obj = cls.object(name, provider)
    obj.summary  # <- reload summary

    breads = breadcrumbs()
    bread_names = map(sel.text_sane, breads)

    if cls.breadcrumb_member.startswith("Container") and cls.breadcrumb_member not in bread_names:
        breadcrumb_member = cls.breadcrumb_member.split(" ")[-1]
    else:
        breadcrumb_member = cls.breadcrumb_member

    assert breadcrumb_member in bread_names

    chosen_link = next(b for b in breads if sel.text_sane(b) == breadcrumb_member)

    sel.click(chosen_link)

    # TODO: replace with widgetastic view.is_displayed function when available
    assert sel.current_url().split("?")[0] == all_url.split("?")[0]
Example #3
0
    def validate(self, db=True):
        """ Validates that the detail page matches the Providers information.

        This method logs into the provider using the mgmt_system interface and collects
        a set of statistics to be matched against the UI. The details page is then refreshed
        continuously until the matching of all items is complete. A error will be raised
        if the match is not complete within a certain defined time period.
        """

        client = self.get_mgmt_system()

        # If we're not using db, make sure we are on the provider detail page
        if not db:
            sel.force_navigate('clouds_provider', context={'provider': self})

        # Initial bullet check
        if self._do_stats_match(client, self.STATS_TO_MATCH, db=db):
            client.disconnect()
            return
        else:
            # Set off a Refresh Relationships
            sel.force_navigate('clouds_provider', context={'provider': self})
            tb.select("Configuration", "Refresh Relationships and Power States", invokes_alert=True)
            sel.handle_alert()

            refresh_timer = RefreshTimer(time_for_refresh=300)
            wait_for(self._do_stats_match,
                     [client, self.STATS_TO_MATCH, refresh_timer],
                     {'db': db},
                     message="do_stats_match_db",
                     num_sec=1000,
                     delay=60)

        client.disconnect()
def test_tables_fields(provider, test_item, soft_assert):

    navigate_to(test_item.obj, 'All')
    tb.select('List View')
    # NOTE: We must re-instantiate here table
    # in order to prevent StaleElementException or UsingSharedTables
    # TODO: Switch to widgetastic
    paged_tbl = PagedTable(table_locator="//div[@id='list_grid']//table")
    for row in paged_tbl.rows():
        cell = row[2]  # We're using indexing since it could be either 'name' or 'host'
        if cell:
            name = cell.text
        else:
            logger.error('Could not find NAME header on {}s list...'
                         .format(test_item.obj.__name__))
            continue
        for field in test_item.fields_to_verify:

            try:
                value = getattr(row, field)
            except AttributeError:
                soft_assert(False, '{}\'s list table: field  not exist: {}'
                            .format(test_item.obj.__name__, field))
                continue

            soft_assert(value, '{}\'s list table: {} row - has empty field: {}'
                        .format(test_item.obj.__name__, name, field))
def test_relationships_tables(provider, cls):
    """This module verifies the integrity of the Relationships table.
    clicking on each field in the Relationships table takes the user
    to either Summary page where we verify that the field that appears
    in the Relationships table also appears in the Properties table,
    or to the page where the number of rows is equal to the number
    that is displayed in the Relationships table.
    """
    navigate_to(cls.object, 'All')
    tb.select('List View')
    list_tbl = CheckboxTable(table_locator="//div[@id='list_grid']//table")
    cls_instances = [r.name.text for r in list_tbl.rows()]
    cls_instances = sample(cls_instances, min(2, len(cls_instances)))
    for name in cls_instances:
        obj = cls.object(name, provider)
        obj.summary.reload()
        keys = sample(obj.summary.relationships.keys,
                      min(1, len(obj.summary.relationships.keys)))
        for key in keys:
            # reload summary to prevent StaleElementReferenceException:
            obj.summary.reload()
            element = getattr(obj.summary.relationships, key)
            if element.value in rel_values:
                continue
            sel.click(element)
            # TODO: find a better indication that we are in the right page:
            sel.is_displayed_text('{} (Summary)'.format(element.text_value))
 def delete_all(self, cancel=False):
     self._nav_to_snapshot_mgmt()
     toolbar.select('Delete Snapshots', 'Delete All Existing Snapshots', invokes_alert=True)
     sel.handle_alert(cancel=cancel)
     if not cancel:
         flash.assert_message_match('Remove All Snapshots initiated for 1 VM and '
                                    'Instance from the CFME Database')
Example #7
0
def test_cockpit_button_access(provider, soft_assert):
    """ The test verifies the existence of cockpit "Web Console"
        button on master node, then presses on the button and
        opens up the cockpit main page in a new window. Then
        we verify the title of the main cockpit page. The test
        will not work until the single sign-on bug is fixed

    """

    collection = NodeCollection()
    nodes = collection.all()
    node = [node for node in nodes if 'master' in node.name][0]
    navigate_to(node, 'Details')

    soft_assert(
        tb.exists(
            'Open a new browser window with Cockpit for this '
            'VM.  This requires that Cockpit is pre-configured on the VM.'),
        'No "Web Console" button found')
    tb.select('Open a new browser window with Cockpit for this '
              'VM.  This requires that Cockpit is pre-configured on the VM.')

    port_num = ':9090/system'
    url_cockpit = provider.hostname + port_num
    sel.get(url_cockpit)
    title_pg = sel.title()
    soft_assert(title_pg == 'Cockpit', 'Cockpit main page failed to open')
def test_pods_rel(provider, rel):
    """   This module verifies the integrity of the Relationships table
          We also verify that clicking on the Relationships table field
          takes the user to the correct page, and the number of rows
          that appears on that page is equal to the number in the
          Relationships table
    """
    sel.force_navigate('containers_pods')
    tb.select('List View')
    list_tbl_pod = CheckboxTable(table_locator="//div[@id='list_grid']//table")
    ui_pods = [r.name.text for r in list_tbl_pod.rows()]
    ui_pods_revised = filter(
        lambda ch: 'nginx' not in ch and not ch.startswith('metrics'),
        ui_pods)

    for name in ui_pods_revised:
        obj = Pod(name, provider)

        val = obj.get_detail('Relationships', rel)
        if val == '0':
            continue
        obj.click_element('Relationships', rel)

        try:
            val = int(val)
            assert len([r for r in list_tbl_pod.rows()]) == val
        except ValueError:
            assert val == InfoBlock.text('Properties', 'Name')
Example #9
0
    def equal_drift_results(self, row_text, *indexes):
        """ Compares drift analysis results of a row specified by it's title text

        Args:
            row_text: Title text of the row to compare
            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', '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")

        d_grid = DriftGrid()
        if not tb.is_active("All attributes"):
            tb.select("All attributes")
        if any(d_grid.cell_indicates_change(row_text, i) for i in range(0, len(indexes))):
            return False
        return True
Example #10
0
    def queue_canned_report(cls, path):
        """Queue report from selection of pre-prepared reports.

        Args:
            *path: Path in tree after All Reports
        Returns: Value of Run At in the table so the run can be then checked.
        """
        cls.path = path
        navigate_to(cls, "Info")
        toolbar.select("Queue")
        flash.assert_no_errors()
        tabstrip.select_tab("Saved Reports")
        queued_at = sel.text(list(records_table.rows())[0].queued_at)

        def _get_state():
            navigate_to(cls, 'Saved')
            row = records_table.find_row("queued_at", queued_at)
            status = sel.text(row.status).strip().lower()
            assert status != "error", sel.text(row)
            return status == version.pick({"5.6": "finished",
                                           "5.7": "complete"})

        wait_for(
            _get_state,
            delay=3,
            message="wait for report generation finished",
            fail_func=toolbar.refresh()
        )
        return sel.text(list(records_table.rows())[0].run_at).encode("utf-8")
def test_tag_item_through_selecting(request, location, tag):
    """Add a tag to an item with going through the details page.

    Prerequisities:
        * Have a tag category and tag created.
        * Be on the page you want to test.

    Steps:
        * Select any quadicon.
        * Select ``Policy/Edit Tags`` and assign the tag to it.
        * Click on the quadicon and verify the tag is assigned. (TODO)
        * Go back to the quadicon view and select ``Policy/Edit Tags`` and remove the tag.
        * Click on the quadicon and verify the tag is not present. (TODO)
    """
    pytest.sel.force_navigate(location)
    tb.select('Grid View')
    if not Quadicon.any_present():
        pytest.skip("No Quadicon present, cannot test.")
    Quadicon.select_first_quad()

    def _delete():
        pytest.sel.force_navigate(location)
        tb.select('Grid View')
        Quadicon.select_first_quad()
        mixins.remove_tag(tag)
    request.addfinalizer(lambda: diaper(_delete))
    mixins.add_tag(tag)
    _delete()
Example #12
0
 def resetter(self):
     # Reset view and selection
     tb.select("Grid View")
     from cfme.web_ui import paginator
     if paginator.page_controls_exist():
         paginator.check_all()
         paginator.uncheck_all()
Example #13
0
 def generate(self, wait=True):
     self.go_to_detail()
     toolbar.select("Configuration", "Generate Widget content now", invokes_alert=True)
     sel.handle_alert()
     flash.assert_no_errors()
     if wait:
         wait_for(lambda: self.check_status() == "Complete")
Example #14
0
def test_table_views():
    for obj in objects_mapping.keys():
        navigate_to(obj, 'All')
        view = choice(VIEWS)
        tb.select(view)
        if not tb.is_active(view):
            raise Exception("Failed to set view \"{}\" For {}".format(view, obj.__name__))
Example #15
0
def navigate_and_get_rows(provider, obj, count, table_class=CheckboxTable,
                          silent_failure=False):
    """Get <count> random rows from the obj list table,
    if <count> is greater that the number of rows, return number of rows.

    Args:
        provider: containers provider
        obj: the containers object
        table: the object's Table object
        count: number of random rows to return
        silent_failure: If True and no records found for obj, it'll
                        return None instead of raise exception

    return: list of rows"""

    navigate_to(obj, 'All')
    tb.select('List View')
    if sel.is_displayed_text("No Records Found.") and silent_failure:
        return []
    from cfme.web_ui import paginator
    paginator.results_per_page(1000)
    table = table_class(table_locator="//div[@id='list_grid']//table")
    rows = table.rows_as_list()
    if not rows:
        return []

    return sample(rows, min(count, len(rows)))
Example #16
0
def queue_canned_report(*path):
    """Queue report from selection of pre-prepared reports.

    Args:
        *path: Path in tree after All Reports
    Returns: Value of Run At in the table so the run can be then checked.
    """
    sel.force_navigate("report_canned_info", context={"path": path})
    toolbar.select("Queue")
    flash.assert_no_errors()
    tabstrip.select_tab("Saved Reports")

    def _get_state():
        try:
            first_row = list(records_table.rows())[0]
        except IndexError:
            return False
        return sel.text(first_row.status).strip().lower() == "finished"

    wait_for(
        _get_state,
        delay=1,
        message="wait for report generation finished",
        fail_func=reload_view
    )
    return sel.text(list(records_table.rows())[0].run_at).encode("utf-8")
Example #17
0
 def terminate(self, cancel=False):
     sel.force_navigate('clouds_instance', context={'instance': self})
     toolbar.select("Power", "Terminate", invokes_alert=True)
     sel.handle_alert(cancel)
     if not cancel:
         wait_for(self.provider_mgmt.is_vm_state,
                  [self.name, self.provider_mgmt.states['deleted']])
def test_no_template_power_control(provider, setup_provider_funcscope, soft_assert):
    """ Ensures that no power button is displayed for templates.

    Prerequisities:
        * An infra provider that has some templates.

    Steps:
        * Open the view of all templates of the provider
        * Verify the Power toolbar button is not visible
        * Select some template using the checkbox
        * Verify the Power toolbar button is not visible
        * Click on some template to get into the details page
        * Verify the Power toolbar button is not visible
    """
    provider.load_all_provider_templates()
    toolbar.select('Grid View')
    soft_assert(not toolbar.exists("Power"), "Power displayed in template grid view!")

    # Ensure selecting a template doesn't cause power menu to appear
    templates = list(get_all_vms(True))
    template_name = random.choice(templates)
    selected_template = VM.factory(template_name, provider, template=True)

    # Check the power button with checking the quadicon
    quadicon = selected_template.find_quadicon(do_not_navigate=True, mark=True, refresh=False)
    soft_assert(not toolbar.exists("Power"), "Power displayed when template quadicon checked!")

    # Ensure there isn't a power button on the details page
    pytest.sel.click(quadicon)
    soft_assert(not toolbar.exists("Power"), "Power displayed in template details!")
Example #19
0
 def power(self, on=True, cancel=False):
     sel.force_navigate('clouds_instance', context={'instance': self})
     toolbar.select("Power", "Start" if on else "Stop", invokes_alert=True)
     sel.handle_alert(cancel)
     if not cancel:
         wait_for(self.provider_mgmt.is_vm_state,
              [self.name, self.provider_mgmt.states['running' if on else 'stopped']])
Example #20
0
 def resetter(self):
     # Default list view
     tb.select('List View')
     if paginator.page_controls_exist():
         # Make sure nothing is selected
         sel.check(paginator.check_all())
         sel.uncheck(paginator.check_all())
Example #21
0
 def resetter(self):
     tb.refresh()
     tb.select('List View')
     # Ensure no rows are checked
     if paginator.page_controls_exist():
         sel.check(paginator.check_all())
         sel.uncheck(paginator.check_all())
Example #22
0
 def config_profiles(self):
     """Returns 'ConfigProfile' configuration profiles (hostgroups) available on this manager"""
     navigate_to(self, 'Details')
     tb.select('List View')
     wait_for(self._does_profile_exist, num_sec=300, delay=20, fail_func=sel.refresh)
     return [ConfigProfile(row['name'].text, self) for row in
             page.list_table_config_profiles.rows()]
 def revert_to(self, cancel=False):
     self._nav_to_snapshot_mgmt()
     self.snapshot_tree.click_path(*self.snapshot_tree.find_path_to(re.compile(self.name)))
     toolbar.select('Revert to selected snapshot', invokes_alert=True)
     sel.handle_alert(cancel=cancel)
     flash.assert_message_match('Revert To Snapshot initiated for 1 VM and Instance from '
                                'the CFME Database')
Example #24
0
    def validate(self):
        """ Validates that the detail page matches the Providers information.

        This method logs into the provider using the mgmt_system interface and collects
        a set of statistics to be matched against the UI. The details page is then refreshed
        continuously until the matching of all items is complete. A error will be raised
        if the match is not complete within a certain defined time period.
        """

        if not self._on_detail_page():
            sel.force_navigate('infrastructure_provider', context={'provider': self})

        stats_to_match = ['num_template', 'num_vm', 'num_datastore', 'num_host', 'num_cluster']
        client = self.get_mgmt_system()

        # Bail out here if the stats match.
        if self._do_stats_match(client, stats_to_match):
            client.disconnect()
            return

        refresh_timer = RefreshTimer()

        # Otherwise refresh relationships and hand off to wait_for
        tb.select("Configuration", "Refresh Relationships and Power States", invokes_alert=True)
        sel.handle_alert()

        ec, tc = wait_for(self._do_stats_match,
                          [client, stats_to_match, refresh_timer],
                          message="do_stats_match",
                          fail_func=sel.refresh,
                          num_sec=1000,
                          delay=10)
        client.disconnect()
Example #25
0
def test_vmware_vimapi_hotadd_disk(
        request, testing_group, provider, testing_vm, domain, cls):
    """ Tests hot adding a disk to vmware vm.

    This test exercises the ``VMware_HotAdd_Disk`` method, located in ``/Integration/VMware/VimApi``

    Steps:
        * It creates an instance in ``System/Request`` that can be accessible from eg. a button.
        * Then it creates a button, that refers to the ``VMware_HotAdd_Disk`` in ``Request``. The
            button shall belong in the VM and instance button group.
        * After the button is created, it goes to a VM's summary page, clicks the button.
        * The test waits until the capacity of disks is raised.

    Metadata:
        test_flag: hotdisk, provision
    """
    meth = cls.methods.create(
        name='load_value_{}'.format(fauxfactory.gen_alpha()),
        script=dedent('''\
            # Sets the capacity of the new disk.

            $evm.root['size'] = 1  # GB
            exit MIQ_OK
            '''))

    request.addfinalizer(meth.delete_if_exists)

    # Instance that calls the method and is accessible from the button
    instance = cls.instances.create(
        name="VMware_HotAdd_Disk_{}".format(fauxfactory.gen_alpha()),
        fields={
            "meth4": {'value': meth.name},  # To get the value
            "rel5": {'value': "/Integration/VMware/VimApi/VMware_HotAdd_Disk"},
        },
    )

    request.addfinalizer(instance.delete_if_exists)

    # Button that will invoke the dialog and action
    button_name = fauxfactory.gen_alphanumeric()
    button = Button(group=testing_group,
                    text=button_name,
                    hover=button_name, system="Request", request=instance.name)
    request.addfinalizer(button.delete_if_exists)
    button.create()

    def _get_disk_capacity():
        testing_vm.summary.reload()
        return testing_vm.summary.datastore_allocation_summary.total_allocation.value

    original_disk_capacity = _get_disk_capacity()
    logger.info('Initial disk allocation: %s', original_disk_capacity)
    toolbar.select(testing_group.text, button.text)
    flash.assert_no_errors()
    try:
        wait_for(
            lambda: _get_disk_capacity() > original_disk_capacity, num_sec=180, delay=5)
    finally:
        logger.info('End disk capacity: %s', _get_disk_capacity())
def test_edit_default_group():
    flash_msg = 'Read Only EVM Group "{}" can not be edited'
    group = ac.Group(description='EvmGroup-approver')
    sel.force_navigate("cfg_accesscontrol_groups")
    row = group_table.find_row_by_cells({'Name': group.description})
    sel.check(sel.element(".//input[@type='checkbox']", root=row[0]))
    tb.select('Configuration', 'Edit the selected Group')
    flash.assert_message_match(flash_msg.format(group.description))
def set_and_test_view(group_name, view):
    default_view = get_default_view(group_name)
    set_view(group_name, view)
    sel.force_navigate('infrastructure_virtual_machines')
    select_two_quads()
    tb.select('Configuration', 'Compare Selected items')
    assert tb.is_active(view), "{} setting failed".format(view)
    reset_default_view(group_name, default_view)
Example #28
0
 def step(self):
     # Use list view to match name and provider
     tb.select('List View')
     cell = {'Name': self.obj.name, 'Provider': self.obj.provider.name}
     try:
         sel.click(list_table.find_row_by_cell_on_all_pages(cell))
     except NoSuchElementException:
         raise ImageNotFound('Could not find image matching {}'.format(cell))
 def tag(self, tag):
     """Tags the system by given tag"""
     self.navigate()
     # Workaround for BZ#1241867
     tb.select('Policy', 'Edit Tags')
     fill(mixins.tag_form, {'category': 'Cost Center *', 'tag': 'Cost Center 001'})
     # ---
     mixins.add_tag(tag, navigate=False)
Example #30
0
 def generate(self, wait=True, **kwargs):
     navigate_to(self, 'Details')
     toolbar.select("Configuration", "Generate Widget content now", invokes_alert=True)
     sel.handle_alert()
     flash.assert_message_match("Content generation for this Widget has been initiated")
     flash.assert_no_errors()
     if wait:
         self.wait_generated(**kwargs)
 def create(self):
     self._nav_to_snapshot_mgmt()
     toolbar.select('Create a new snapshot for this VM')
     if self.name is not None:
         fill(snapshot_form, {
             'name': self.name,
             'description': self.description,
             'snapshot_memory': self.memory
         },
              action=snapshot_form.create_button)
     else:
         fill(snapshot_form, {
             'description': self.description,
             'snapshot_memory': self.memory
         },
              action=snapshot_form.create_button)
     wait_for(self.does_snapshot_exist,
              num_sec=300,
              delay=20,
              fail_func=sel.refresh,
              handle_exception=True)
Example #32
0
    def wait_candu_data_available(self, timeout=600):
        """Waits until C&U data are available for this VM/Instance

        Args:
            timeout: Timeout passed to :py:func:`utils.wait.wait_for`
        """
        self.load_details(refresh=True)
        wait_for(lambda: not toolbar.is_greyed('Monitoring', 'Utilization'),
                 delay=10,
                 handle_exception=True,
                 num_sec=timeout,
                 fail_func=lambda: toolbar.select("Reload"))
Example #33
0
    def queue(self, wait_for_finish=False):
        sel.force_navigate("report_custom_info", context={"report": self})
        toolbar.select("Queue")
        flash.assert_no_errors()
        if wait_for_finish:
            # Get the queued_at value to always target the correct row
            queued_at = sel.text(list(records_table.rows())[0].queued_at)

            def _get_state():
                row = records_table.find_row("queued_at", queued_at)
                status = sel.text(row.status).strip().lower()
                assert status != "error", sel.text(row)
                return status == "finished"

            wait_for(
                _get_state,
                delay=1,
                message="wait for report generation finished",
                fail_func=reload_view,
                num_sec=300,
            )
    def compare(self, *objects, **kwargs):
        """Compares two or more objects in the genealogy.

        Args:
            *objects: :py:class:`Vm` or :py:class:`Template` or :py:class:`str` with name.

        Keywords:
            sections: Which sections to compare.
            attributes: `all`, `different` or `same`. Default: `all`.
            mode: `exists` or `details`. Default: `exists`."""
        sections = kwargs.get("sections")
        attributes = kwargs.get("attributes", "all").lower()
        mode = kwargs.get("mode", "exists").lower()
        assert len(objects) >= 2, "You must specify at least two objects"
        objects = map(lambda o: o.name
                      if isinstance(o, (Vm, Template)) else o, objects)
        self.navigate()
        for obj in objects:
            if not isinstance(obj, list):
                path = self.genealogy_tree.find_path_to(obj)
            self.genealogy_tree.check_node(*path)
        toolbar.select("Compare selected VMs")
        # COMPARE PAGE
        flash.assert_no_errors()
        if sections is not None:
            map(lambda path: self.section_comparison_tree.check_node(*path),
                sections)
            sel.click(self.apply_button)
            flash.assert_no_errors()
        # Set requested attributes sets
        toolbar.select(self.attr_mapping[attributes])
        # Set the requested mode
        toolbar.select(self.mode_mapping[mode])
Example #35
0
def test_tag_item_through_details(request, location, tag):
    """Add a tag to an item with going through the details page.

    Prerequisities:
        * Have a tag category and tag created.
        * Be on the page you want to test.

    Steps:
        * Click any quadicon.
        * On the details page, select ``Policy/Edit Tags`` and assign the tag to it.
        * Verify the tag is assigned. (TODO)
        * Select ``Policy/Edit Tags`` and remove the tag.
        * Verify the tag is not present. (TODO)
    """
    pytest.sel.force_navigate(location)
    tb.select('Grid View')
    if not Quadicon.any_present():
        pytest.skip("No Quadicon present, cannot test.")
    pytest.sel.click(Quadicon.first())
    request.addfinalizer(lambda: diaper(lambda: mixins.remove_tag(tag)))
    mixins.add_tag(tag)
    mixins.remove_tag(tag)
Example #36
0
    def check_compliance_wrapper(self, timeout=240):
        """This wrapper takes care of waiting for the compliance status to change

        Args:
            timeout: Wait timeout in seconds.
        """
        self.load_details(refresh=True)
        original_state = self.compliance_status
        yield
        wait_for(
            lambda: self.compliance_status != original_state,
            num_sec=timeout, delay=5, message="compliance of {} checked".format(self.name),
            fail_func=lambda: toolbar.select("Reload"))
Example #37
0
def test_multiple_host_bad_creds(setup_provider, provider):
    """    Tests multiple host credentialing with bad credentials """

    sel.force_navigate('infrastructure_provider', context={'provider': provider})
    sel.click(details_page.infoblock.element("Relationships", "Hosts"))

    quads = Quadicon.all("host", this_page=True)
    for quad in quads:
            sel.check(quad.checkbox())
    tb.select("Configuration", config_option())

    cfme_host = random.choice(provider.data["hosts"])
    creds = conf.credentials['bad_credentials']
    fill(credential_form, {'default_principal': creds['username'],
                           'default_secret': creds['password'],
                           'default_verify_secret': creds['password'],
                           'validate_host': cfme_host["name"]})

    sel.click(credential_form.validate_multi_host)
    flash.assert_message_match('Cannot complete login due to an incorrect user name or password.')

    sel.click(credential_form.cancel_changes)
def set_random_tag(instance):
    logger.debug("Setting random tag")
    navigate_to(instance, 'Details')
    toolbar.select('Policy', 'Edit Tags')

    # select random tag category
    cat_selector = AngularSelect("tag_cat")
    random_cat = random.choice(cat_selector.all_options)
    logger.debug("Selected category {cat}".format(cat=random_cat))
    cat_selector.select_by_value(random_cat.value)

    # select random tag tag
    tag_selector = AngularSelect("tag_add")
    random_tag = random.choice(
        [op for op in tag_selector.all_options if op.value != "select"])
    logger.debug("Selected value {tag}".format(tag=random_tag))
    tag_selector.select_by_value(random_tag.value)

    # Save tag conig
    form_buttons.save()
    logger.debug("Tag configuration was saved")
    return Tag(display_name=random_tag.text, category=random_cat.text)
Example #39
0
def test_images_views():
    sel.force_navigate('containers_images')
    tb.select('Grid View')
    assert tb.is_active('Grid View'), "Images grid view setting failed"
    tb.select('Tile View')
    assert tb.is_active('Tile View'), "Images tile view setting failed"
    tb.select('List View')
    assert tb.is_active('List View'), "Images list view setting failed"
Example #40
0
def test_replicators_views():
    sel.force_navigate('containers_replicators')
    tb.select('Grid View')
    assert tb.is_active('Grid View'), "Replicators grid view setting failed"
    tb.select('Tile View')
    assert tb.is_active('Tile View'), "Replicators tile view setting failed"
    tb.select('List View')
    assert tb.is_active('List View'), "Replicators list view setting failed"
def test_ssa_packages(provider, instance, soft_assert):
    """ Tests SSA fetches correct results for packages

    Metadata:
        test_flag: vm_analysis
    """

    if instance.system_type == WINDOWS:
        pytest.skip("Windows has no packages")

    expected = None
    if 'package' not in instance.system_type.keys():
        pytest.skip("Don't know how to update packages for {}".format(
            instance.system_type))

    package_name = instance.system_type['package']
    package_command = instance.system_type['install-command']
    package_number_command = instance.system_type['package-number']

    cmd = package_command.format(package_name)
    output = instance.ssh.run_command(cmd.format(package_name)).output
    logger.info("{0} output:\n{1}".format(cmd, output))

    expected = instance.ssh.run_command(package_number_command).output.strip(
        '\n')

    instance.smartstate_scan()
    wait_for(lambda: is_vm_analysis_finished(instance.name),
             delay=15,
             timeout="10m",
             fail_func=lambda: tb.select('Reload'))

    # Check that all data has been fetched
    current = instance.get_detail(properties=('Configuration', 'Packages'))
    assert current == expected

    # Make sure new package is listed
    sel.click(InfoBlock("Configuration", "Packages"))
    template = '//div[@id="list_grid"]/div[@class="{}"]/table/tbody'
    packages = version.pick({
        version.LOWEST:
        SplitTable(header_data=(template.format("xhdr"), 1),
                   body_data=(template.format("objbox"), 0)),
        "5.5":
        Table('//table'),
    })

    for page in paginator.pages():
        if packages.find_row('Name', package_name):
            return
    pytest.fail("Package {0} was not found".format(package_name))
Example #42
0
    def f(context):
        # Here it also can have long spinners
        with sel.ajax_timeout(90):
            toolbar.select('Lifecycle', tb_item)
        provider = context['provider']
        template_name = context['template_name']
        template_select_form.template_table._update_cache()
        template = template_select_form.template_table.find_row_by_cells({
            'Name': template_name,
            'Provider': provider if isinstance(provider, basestring) else provider.name
        })
        if template:
            sel.click(template)
            # In order to mitigate the sometimes very long spinner timeout, raise the timeout
            with sel.ajax_timeout(90):
                if current_version() < "5.4":
                    sel.click(submit_button)
                else:
                    sel.click(form_buttons.FormButton("Continue", force_click=True))

        else:
            raise TemplateNotFound('Unable to find template "{}" for provider "{}"'.format(
                template_name, provider.key))
Example #43
0
 def is_host_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(host_name),
         'state':
         'Finished'
     })
     if host_analysis_finished:
         # Delete the task
         tasks.tasks_table.select_row_by_cells({
             'task_name':
             "SmartState Analysis for '{}'".format(host_name),
             'state':
             'Finished'
         })
         tb.select('Delete Tasks', 'Delete', invokes_alert=True)
         sel.handle_alert()
     return host_analysis_finished is not None
def test_drift_analysis(request, provider, instance, soft_assert):
    """ Tests drift analysis is correct

    Metadata:
        test_flag: vm_analysis
    """

    instance.load_details()
    drift_num_orig = 0
    drift_orig = InfoBlock("Relationships", "Drift History").text
    if drift_orig != 'None':
        drift_num_orig = int(drift_orig)
    instance.smartstate_scan()
    wait_for(lambda: is_vm_analysis_finished(instance.name),
             delay=15, timeout="35m", fail_func=lambda: toolbar.select('Reload'))
    instance.load_details()
    wait_for(
        lambda: int(InfoBlock("Relationships", "Drift History").text) == drift_num_orig + 1,
        delay=20,
        num_sec=120,
        message="Waiting for Drift History count to increase",
        fail_func=sel.refresh
    )
    drift_new = int(InfoBlock("Relationships", "Drift History").text)

    # add a tag and a finalizer to remove it
    tag = ('Department', 'Accounting')
    instance.add_tag(tag, single_value=False)
    request.addfinalizer(lambda: instance.remove_tag(tag))

    instance.smartstate_scan()
    wait_for(lambda: is_vm_analysis_finished(instance.name),
             delay=15, timeout="35m", fail_func=lambda: toolbar.select('Reload'))
    instance.load_details()
    wait_for(
        lambda: int(InfoBlock("Relationships", "Drift History").text) == drift_new + 1,
        delay=20,
        num_sec=120,
        message="Waiting for Drift History count to increase",
        fail_func=sel.refresh
    )

    # check drift difference
    soft_assert(not instance.equal_drift_results('Department (1)', 'My Company Tags', 0, 1),
                "Drift analysis results are equal when they shouldn't be")

    # Test UI features that modify the drift grid
    d_grid = DriftGrid()

    # Accounting tag should not be displayed, because it was changed to True
    toolbar.select("Attributes with same values")
    with error.expected(sel.NoSuchElementException):
        d_grid.get_cell('Accounting', 0)

    # Accounting tag should be displayed now
    toolbar.select("Attributes with different values")
    d_grid.get_cell('Accounting', 0)
Example #45
0
def get_workers_list(do_not_navigate=False, refresh=True):
    """Retrieves all workers.

    Returns a dictionary where keys are names of the workers and values are lists (because worker
    can have multiple instances) which contain dictionaries with some columns.
    """
    if do_not_navigate:
        if refresh:
            tb.select("Reload current workers display")
    else:
        navigate_to(current_appliance.server, 'Workers')
    workers = {}
    for row in records_table.rows():
        name = sel.text_sane(row.name)
        if name not in workers:
            workers[name] = []
        worker = {
            "status":
            sel.text_sane(row.status),
            "pid":
            int(sel.text_sane(row.pid))
            if len(sel.text_sane(row.pid)) > 0 else None,
            "spid":
            int(sel.text_sane(row.spid))
            if len(sel.text_sane(row.spid)) > 0 else None,
            "started":
            parsetime.from_american_with_utc(sel.text_sane(row.started)),
            "last_heartbeat":
            None,
        }
        try:
            workers["last_heartbeat"] = parsetime.from_american_with_utc(
                sel.text_sane(row.last_heartbeat))
        except ValueError:
            pass
        workers[name].append(worker)
    return workers
Example #46
0
    def validate(self, db=True):
        """ Validates that the detail page matches the Providers information.

        This method logs into the provider using the mgmt_system interface and collects
        a set of statistics to be matched against the UI. The details page is then refreshed
        continuously until the matching of all items is complete. A error will be raised
        if the match is not complete within a certain defined time period.
        """

        client = self.get_mgmt_system()

        # If we're not using db, make sure we are on the provider detail page
        if not db:
            sel.force_navigate('{}_provider'.format(self.page_name),
                               context={'provider': self})

        # Initial bullet check
        if self._do_stats_match(client, self.STATS_TO_MATCH, db=db):
            client.disconnect()
            return
        else:
            # Set off a Refresh Relationships
            sel.force_navigate('{}_provider'.format(self.page_name),
                               context={'provider': self})
            tb.select("Configuration",
                      "Refresh Relationships and Power States",
                      invokes_alert=True)
            sel.handle_alert()

            refresh_timer = RefreshTimer(time_for_refresh=300)
            wait_for(self._do_stats_match,
                     [client, self.STATS_TO_MATCH, refresh_timer], {'db': db},
                     message="do_stats_match_db",
                     num_sec=1000,
                     delay=60)

        client.disconnect()
def test_multiple_host_good_creds(setup_provider, provider):
    """  Tests multiple host credentialing  with good credentials """

    details_view = navigate_to(provider, 'Details')
    details_view.contents.relationships.click_at('Hosts')

    quads = Quadicon.all("host", this_page=True)
    for quad in quads:
            sel.check(quad.checkbox())
    tb.select("Configuration", config_option())

    cfme_host = random.choice(provider.data["hosts"])
    cred = cfme_host['credentials']
    creds = conf.credentials[cred]
    fill(credential_form, {'default_principal': creds['username'],
                           'default_secret': creds['password'],
                           'default_verify_secret': creds['password'],
                           'validate_host': cfme_host["name"]})

    sel.click(credential_form.validate_multi_host)
    flash.assert_message_match('Credential validation was successful')

    sel.click(credential_form.save_btn)
    flash.assert_message_match('Credentials/Settings saved successfully')
Example #48
0
def test_no_template_power_control(provider, setup_provider_funcscope,
                                   soft_assert):
    """ Ensures that no power button is displayed for templates.

    Prerequisities:
        * An infra provider that has some templates.

    Steps:
        * Open the view of all templates of the provider
        * Verify the Power toolbar button is not visible
        * Select some template using the checkbox
        * Verify the Power toolbar button is not visible
        * Click on some template to get into the details page
        * Verify the Power toolbar button is not visible
    """
    provider.load_all_provider_templates()
    toolbar.select('Grid View')
    soft_assert(not toolbar.exists("Power"),
                "Power displayed in template grid view!")

    # Ensure selecting a template doesn't cause power menu to appear
    templates = list(get_all_vms(True))
    template_name = random.choice(templates)
    selected_template = VM.factory(template_name, provider, template=True)

    # Check the power button with checking the quadicon
    quadicon = selected_template.find_quadicon(do_not_navigate=True,
                                               mark=True,
                                               refresh=False)
    soft_assert(not toolbar.exists("Power"),
                "Power displayed when template quadicon checked!")

    # Ensure there isn't a power button on the details page
    pytest.sel.click(quadicon)
    soft_assert(not toolbar.exists("Power"),
                "Power displayed in template details!")
Example #49
0
def test_multiple_host_good_creds(setup_provider, provider):
    """  Tests multiple host credentialing  with good credentials """

    sel.force_navigate('infrastructure_provider', context={'provider': provider})
    sel.click(details_page.infoblock.element("Relationships", "Hosts"))

    quads = Quadicon.all("host", this_page=True)
    for quad in quads:
            sel.check(quad.checkbox())
    tb.select("Configuration", config_option())

    cfme_host = random.choice(provider.data["hosts"])
    cred = cfme_host['credentials']
    creds = conf.credentials[cred]
    fill(credential_form, {'default_principal': creds['username'],
                           'default_secret': creds['password'],
                           'default_verify_secret': creds['password'],
                           'validate_host': cfme_host["name"]})

    sel.click(credential_form.validate_multi_host)
    flash.assert_message_match('Credential validation was successful')

    sel.click(credential_form.save_btn)
    flash.assert_message_match('Credentials/Settings saved successfully')
Example #50
0
def test_widgets_on_dashboard(request, dashboard, default_widgets,
                              custom_widgets, soft_assert):
    with update(dashboard):
        dashboard.widgets = map(lambda w: w.title, custom_widgets)

    def _finalize():
        with update(dashboard):
            dashboard.widgets = default_widgets

    request.addfinalizer(_finalize)
    sel.force_navigate("dashboard")
    toolbar.select("Reset Dashboard Widgets to the defaults",
                   invokes_alert=True)
    sel.handle_alert(False)
    soft_assert(
        len(Widget.all()) == len(custom_widgets),
        "Count of the widgets differ")
    for custom_w in custom_widgets:
        try:
            Widget.by_name(custom_w.title)
        except NameError:
            soft_assert(
                False,
                "Widget {} not found on dashboard".format(custom_w.title))
Example #51
0
def queue_canned_report(*path):
    """Queue report from selection of pre-prepared reports.

    Args:
        *path: Path in tree after All Reports
    Returns: Value of Run At in the table so the run can be then checked.
    """
    sel.force_navigate("report_canned_info", context={"path": path})
    toolbar.select("Queue")
    flash.assert_no_errors()
    tabstrip.select_tab("Saved Reports")

    def _get_state():
        try:
            first_row = list(records_table.rows())[0]
        except IndexError:
            return False
        return sel.text(first_row.status).strip().lower() == "finished"

    wait_for(_get_state,
             delay=1,
             message="wait for report generation finished",
             fail_func=reload_view)
    return sel.text(list(records_table.rows())[0].run_at).encode("utf-8")
Example #52
0
    def step(self):
        # Use list view to match name and provider
        tb.select('List View')
        # Instance may be in a state where the provider is not displayed in the table
        # Try first to match name and provider, fall back to just name
        # Matching only on name has the potential to select the wrong instance
        try:
            return sel.click(
                list_table.find_row_by_cell_on_all_pages({
                    'Name':
                    self.obj.name,
                    'Provider':
                    self.obj.provider.name
                }))
        except (NameError, TypeError):
            logger.warning(
                'Exception caught, could not match instance with name and provider'
            )

        # If name and provider weren't matched, look for just name
        logger.warning('Matching instance only using name only: {}'.format(
            self.obj.name))
        sel.click(
            list_table.find_row_by_cell_on_all_pages({'Name': self.obj.name}))
Example #53
0
def test_tables_sort(test_item):

    pytest.skip(
        'This test is currently skipped due to an issue in the testing framework:'
        ' https://github.com/ManageIQ/integration_tests/issues/4052')

    navigate_to(test_item, 'All')
    toolbar.select('List View')
    # NOTE: We must re-instantiate here table
    # in order to prevent StaleElementException or UsingSharedTables
    sort_tbl = SortTable(table_locator="//div[@id='list_grid']//table")
    header_texts = [header.text for header in sort_tbl.headers]
    for col, header_text in enumerate(header_texts):

        if not header_text:
            continue

        # Checking both orders
        sort_tbl.sort_by(header_text, 'ascending')
        rows_ascending = [r[col].text for r in sort_tbl.rows()]
        sort_tbl.sort_by(header_text, 'descending')
        rows_descending = [r[col].text for r in sort_tbl.rows()]

        assert rows_ascending[::-1] == rows_descending
Example #54
0
    def queue(self, wait_for_finish=False):
        navigate_to(self, 'Details')
        toolbar.select("Queue")
        flash.assert_no_errors()
        tabstrip.select_tab("Saved Reports")
        if wait_for_finish:
            # Get the queued_at value to always target the correct row
            queued_at = sel.text(list(records_table.rows())[0].queued_at)

            def _get_state():
                navigate_to(self, 'Saved')
                row = records_table.find_row("queued_at", queued_at)
                status = sel.text(row.status).strip().lower()
                assert status != "error", sel.text(row)
                return status == version.pick({"5.6": "finished",
                                               "5.7": "complete"})

            wait_for(
                _get_state,
                delay=1,
                message="wait for report generation finished",
                fail_func=toolbar.refresh(),
                num_sec=300,
            )
def test_ssa_files(provider, instance, policy_profile, soft_assert):
    """Tests that instances can be scanned for specific file."""

    if instance.system_type == WINDOWS:
        pytest.skip("We cannot verify Windows files yet")

    instance.smartstate_scan()
    wait_for(lambda: is_vm_analysis_finished(instance.name),
             delay=15, timeout="35m", fail_func=lambda: toolbar.select('Reload'))

    # Check that all data has been fetched
    current = instance.get_detail(properties=('Configuration', 'Files'))
    assert current != '0', "No files were scanned"

    instance.open_details(("Configuration", "Files"))
    if not instance.paged_table.find_row_on_all_pages('Name', ssa_expect_file):
        pytest.fail("File {0} was not found".format(ssa_expect_file))
Example #56
0
def retire_extend_button(request):
    grp_name = "grp_{}".format(fauxfactory.gen_alphanumeric())
    grp = ButtonGroup(text=grp_name,
                      hover=grp_name,
                      type=ButtonGroup.VM_INSTANCE)
    request.addfinalizer(lambda: grp.delete_if_exists())
    grp.create()
    btn_name = "btn_{}".format(fauxfactory.gen_alphanumeric())
    button = Button(group=grp,
                    text=btn_name,
                    hover=btn_name,
                    system="Request",
                    request="vm_retire_extend")
    request.addfinalizer(lambda: button.delete_if_exists())
    button.create()

    return lambda: toolbar.select(grp.text, button.text)
def test_ssa_users(provider, instance, soft_assert):
    """ Tests SSA fetches correct results for users list

    Metadata:
        test_flag: vm_analysis
    """
    username = fauxfactory.gen_alphanumeric()
    expected = None

    # In windows case we can't add new users (yet)
    # So we simply check that user list doesn't cause any Rails errors
    if instance.system_type != WINDOWS:
        # Add a new user
        instance.ssh.run_command("userdel {0} || useradd {0}".format(username))
        expected = instance.ssh.run_command(
            "cat /etc/passwd | wc -l").output.strip('\n')

    instance.smartstate_scan()
    wait_for(lambda: is_vm_analysis_finished(instance.name),
             delay=15,
             timeout="10m",
             fail_func=lambda: tb.select('Reload'))

    # Check that all data has been fetched
    current = instance.get_detail(properties=('Security', 'Users'))
    if instance.system_type != WINDOWS:
        assert current == expected

    # Make sure created user is in the list
    sel.click(InfoBlock("Security", "Users"))
    template = '//div[@id="list_grid"]/div[@class="{}"]/table/tbody'
    users = version.pick({
        version.LOWEST:
        SplitTable(header_data=(template.format("xhdr"), 1),
                   body_data=(template.format("objbox"), 0)),
        "5.5":
        Table('//table'),
    })

    for page in paginator.pages():
        sel.wait_for_element(users)
        if users.find_row('Name', username):
            return
    if instance.system_type != WINDOWS:
        pytest.fail("User {0} was not found".format(username))
Example #58
0
    def queue(self, wait_for_finish=False):
        """Queue this schedule.

        Args:
            wait_for_finish: If True, then this function blocks until the action is finished.
        """
        if not self.exists:
            self.create()
        sel.force_navigate("schedule", context={"schedule": self})
        last_run = sel.text(self.table_item("Last Run Time")).strip()
        cfg_btn("Queue up this Schedule to run now")
        flash.assert_no_errors()
        if wait_for_finish:
            wait_for(
                lambda: sel.text(self.table_item("Last Run Time")).strip() != last_run,
                delay=2,
                fail_func=lambda: toolbar.select("Reload current display"),
                message="wait for report queue finish"
            )
def test_ssa_groups(provider, instance, soft_assert):
    """ Tests SSA fetches correct results for groups

    Metadata:
        test_flag: vm_analysis
    """
    group = fauxfactory.gen_alphanumeric()
    expected = None

    if instance.system_type != WINDOWS:
        # Add a new group
        instance.ssh.run_command("groupdel {0} || groupadd {0}".format(group))
        expected = instance.ssh.run_command(
            "cat /etc/group | wc -l").output.strip('\n')

    instance.smartstate_scan()
    wait_for(lambda: is_vm_analysis_finished(instance.name),
             delay=15,
             timeout="10m",
             fail_func=lambda: tb.select('Reload'))

    # Check that all data has been fetched
    current = instance.get_detail(properties=('Security', 'Groups'))
    if instance.system_type != WINDOWS:
        assert current == expected

    # Make sure created group is in the list
    sel.click(InfoBlock("Security", "Groups"))
    template = '//div[@id="list_grid"]/div[@class="{}"]/table/tbody'
    groups = version.pick({
        version.LOWEST:
        SplitTable(header_data=(template.format("xhdr"), 1),
                   body_data=(template.format("objbox"), 0)),
        "5.5":
        Table('//table'),
    })

    for page in paginator.pages():
        sel.wait_for_element(groups)
        if groups.find_row('Name', group):
            return
    if instance.system_type != WINDOWS:
        pytest.fail("Group {0} was not found".format(group))
    def queue(self, wait_for_finish=False):
        """Queue this schedule.

        Args:
            wait_for_finish: If True, then this function blocks until the action is finished.
        """
        if not self.exists:
            self.create()
        navigate_to(self, 'Details')
        last_run = sel.text(self.table_item("Last Run Time")).strip()
        navigate_to(self, 'Queue')
        flash.assert_no_errors()
        if wait_for_finish:
            wait_for(
                lambda: sel.text(self.table_item("Last Run Time")).strip() != last_run,
                delay=2,
                fail_func=lambda: toolbar.select("Reload current display"),
                message="wait for report queue finish"
            )