Beispiel #1
0
 def get_vm_details():
     power_state = InfoBlock.text("Power Management", "Power State")
     logger.debug("Service VM power state: {}".format(power_state))
     if power_state == "unknown":
         # The VM power state is unknown, check lifecycle instead of power
         retire_state = InfoBlock.text("Lifecycle", "Retirement state")
         return retire_state == "Retired"
     else:
         # VM power is a known state, use it
         return power_state == "off"
 def get_vm_details():
     power_state = InfoBlock.text('Power Management', 'Power State')
     logger.debug('Service VM power state: {}'.format(power_state))
     if power_state == 'unknown':
         # The VM power state is unknown, check lifecycle instead of power
         retire_state = InfoBlock.text('Lifecycle', 'Retirement state')
         return retire_state == 'Retired'
     else:
         # VM power is a known state, use it
         return power_state == 'off'
def test_disk_format_select(provisioner, disk_format, provider, prov_data):
    """ Tests disk format selection in provisioning dialog.

    Prerequisities:
        * A provider set up, supporting provisioning in CFME

    Steps:
        * Open the provisioning dialog.
        * Apart from the usual provisioning settings, set the disk format to be thick or thin.
        * Submit the provisioning request and wait for it to finish.
        * Visit the page of the provisioned VM.
        * The ``Thin Provisioning Used`` field should state true of false according to the selection

    Metadata:
        test_flag: provision
    """
    prov_data["vm_name"] = "test_prov_dlg_{}".format(fauxfactory.gen_alphanumeric())
    prov_data["disk_format"] = disk_format
    template_name = provider.data['provisioning']['template']

    vm = provisioner(template_name, prov_data)

    # Go to the VM info
    vm.load_details(refresh=True)
    thin = InfoBlock.text(
        "Datastore Allocation Summary", "Thin Provisioning Used").strip().lower() == "true"
    if disk_format == "thin":
        assert thin, "The disk format should be Thin"
    else:
        assert not thin, "The disk format should not be Thin"
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')
Beispiel #5
0
 def get_detail(self, *ident):
     """ Gets details from the details infoblock
     Args:
         *ident: Table name and Key name, e.g. "Relationships", "Images"
     Returns: A string representing the contents of the summary's value.
     """
     return InfoBlock.text(*ident)
    def wait_for_vm_retire(self):
        """ Waits for self.vm_name to go to the off state and returns state

        Args:
        Returns: A string representing the VM state
        """
        def get_vm_details():
            power_state = InfoBlock.text('Power Management', 'Power State')
            logger.debug('Service VM power state: {}'.format(power_state))
            if power_state == 'unknown':
                # The VM power state is unknown, check lifecycle instead of power
                retire_state = InfoBlock.text('Lifecycle', 'Retirement state')
                return retire_state == 'Retired'
            else:
                # VM power is a known state, use it
                return power_state == 'off'

        quadicon = Quadicon(self.vm_name, "vm")
        sel.click(quadicon)

        wait_for(
            get_vm_details,
            fail_func=tb.refresh,
            num_sec=120 * 60,
            delay=10,
            message="Service VM power off wait"
        )
        return InfoBlock.text('Power Management', 'Power State')
Beispiel #7
0
 def get_detail(self, *ident):
     """ Gets details from the details infoblock
     Args:
         *ident: Table name and Key name, e.g. "Relationships", "Images"
     Returns: A string representing the contents of the summary's value.
     """
     return InfoBlock.text(*ident)
def test_disk_format_select(provisioner, disk_format, provider, prov_data,
                            vm_name):
    """ Tests disk format selection in provisioning dialog.

    Prerequisities:
        * A provider set up, supporting provisioning in CFME

    Steps:
        * Open the provisioning dialog.
        * Apart from the usual provisioning settings, set the disk format to be thick or thin.
        * Submit the provisioning request and wait for it to finish.
        * Visit the page of the provisioned VM.
        * The ``Thin Provisioning Used`` field should state true of false according to the selection

    Metadata:
        test_flag: provision
    """
    prov_data["vm_name"] = vm_name
    prov_data["disk_format"] = disk_format
    template_name = provider.data['provisioning']['template']

    vm = provisioner(template_name, prov_data)

    # Go to the VM info
    vm.load_details(refresh=True)
    thin = InfoBlock.text("Datastore Allocation Summary",
                          "Thin Provisioning Used").strip().lower() == "true"
    if disk_format == "thin":
        assert thin, "The disk format should be Thin"
    else:
        assert not thin, "The disk format should not be Thin"
def test_services_rel(provider, rel):
    sel.force_navigate('containers_services')
    list_tbl_service = CheckboxTable(
        table_locator="//div[@id='list_grid']//table")
    ui_services = [r.name.text for r in list_tbl_service.rows()]
    mgmt_objs = provider.mgmt.list_service()  # run only if table is not empty

    if ui_services:
        # verify that mgmt pods exist in ui listed pods
        assert set(ui_services).issubset(
            [obj.name for obj in mgmt_objs]), 'Missing objects'

    for name in ui_services:
        obj = Service(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_service.rows()]) == val
        except ValueError:
            assert val == InfoBlock.text('Properties', 'Name')
Beispiel #10
0
 def get_detail(self, *args, **kwargs):
     # TODO: remove when bug 1389299 is fixed to use common.vm.get_detail()
     # Navigate to all first to force reload of details screen without using refresh
     navigate_to(self, 'All')
     self.load_details()
     if kwargs.get('icon_href', False):
         return InfoBlock.icon_href(*kwargs.get('properties'))
     else:
         return InfoBlock.text(*kwargs.get('properties'))
Beispiel #11
0
 def get_detail(self, *args, **kwargs):
     # TODO: remove when bug 1389299 is fixed to use common.vm.get_detail()
     # Navigate to all first to force reload of details screen without using refresh
     navigate_to(self, 'All')
     self.load_details()
     if kwargs.get('icon_href', False):
         return InfoBlock.icon_href(*kwargs.get('properties'))
     else:
         return InfoBlock.text(*kwargs.get('properties'))
Beispiel #12
0
def details_page_check(name, provider):
    title_match = match_page(summary='Instance "{}"'.format(name))
    if title_match:
        # Also check provider
        try:
            prov_match = InfoBlock.text('Relationships', 'Cloud Provider') == provider.name
            return title_match and prov_match
        except BlockTypeUnknown:
            # Default to false since we can't identify which provider the image belongs to
            return False
Beispiel #13
0
def details_page_check(name, provider):
    title_match = match_page(summary='Instance "{}"'.format(name))
    if title_match:
        # Also check provider
        try:
            prov_match = InfoBlock.text('Relationships',
                                        'Cloud Provider') == provider.name
            return title_match and prov_match
        except BlockTypeUnknown:
            # Default to false since we can't identify which provider the image belongs to
            return False
Beispiel #14
0
def test_host_event(gen_events, test_vm):
    """Tests host event on timelines

    Metadata:
        test_flag: timelines, provision
    """
    test_vm.load_details()
    host_name = InfoBlock.text('Relationships', 'Host')
    host = Host(name=host_name, provider=test_vm.provider)
    wait_for(count_events, [host, test_vm], timeout='10m', fail_condition=0,
             message="events to appear")
Beispiel #15
0
def test_infra_host_event(gen_events, new_vm):
    """Tests host event on timelines

    Metadata:
        test_flag: timelines, provision
    """
    new_vm.load_details()
    host_name = InfoBlock.text('Relationships', 'Host')
    host = Host(name=host_name, provider=new_vm.provider)
    wait_for(count_events, [host, new_vm], timeout='10m', fail_condition=0,
             message="events to appear")
Beispiel #16
0
def details_page_check(name, provider):
    title_match = match_page(summary='Image "{}"'.format(name))
    if title_match:
        # Also check provider
        # Limits scope of testing to images that aren't orphaned or archived, but if we don't do
        # this and multiple providers are present we might have multiple images with the same name
        try:
            prov_match = InfoBlock.text('Relationships', 'Cloud Provider') == provider
            return title_match and prov_match
        except BlockTypeUnknown:
            # Default to false since we can't identify which provider the image belongs to
            return False
Beispiel #17
0
def details_page_check(name, provider):
    title_match = match_page(summary='Image "{}"'.format(name))
    if title_match:
        # Also check provider
        # Limits scope of testing to images that aren't orphaned or archived, but if we don't do
        # this and multiple providers are present we might have multiple images with the same name
        try:
            prov_match = InfoBlock.text('Relationships',
                                        'Cloud Provider') == provider
            return title_match and prov_match
        except BlockTypeUnknown:
            # Default to false since we can't identify which provider the image belongs to
            return False
Beispiel #18
0
    def get_detail(self, properties=None, icon_href=False):
        """ Gets details from the details infoblock

        Args:
            *properties: An InfoBlock title, followed by the Key name e.g. "Relationships", "Images"
            icon_href: Boolean indicating to return icon_href instead of text
        Returns: A string representing the contents of the InfoBlock's value.
        """
        navigate_to(self, 'Details')
        if icon_href:
            return InfoBlock.icon_href(*properties)
        else:
            return InfoBlock.text(*properties)
Beispiel #19
0
 def retire_on_date(self, retirement_date):
     navigate_to(self, "SetRetirement")
     fill(retirement_form, {"retirement_date": retirement_date}, action=form_buttons.save)
     navigate_to(self, "Details")
     wait_for(
         lambda: InfoBlock.text("Lifecycle", "Retirement State") == "Retiring",
         fail_func=tb.refresh,
         num_sec=5 * 60,
         delay=5,
         message="Service Retirement",
     )
     # wait for any vms to shutdown, this method leaves the page on the VM details
     vm_state = self.wait_for_vm_retire()
     assert vm_state in ["off", "unknown"]
Beispiel #20
0
 def retire_on_date(self, retirement_date):
     navigate_to(self, 'SetRetirement')
     fill(retirement_form, {'retirement_date': retirement_date},
          action=form_buttons.save)
     navigate_to(self, 'Details')
     wait_for(
         lambda: InfoBlock.text('Lifecycle', 'Retirement State') == 'Retiring',
         fail_func=tb.refresh,
         num_sec=5 * 60,
         delay=5,
         message='Service Retirement'
     )
     # wait for any vms to shutdown, this method leaves the page on the VM details
     vm_state = self.wait_for_vm_retire()
     assert vm_state in ['off', 'unknown']
Beispiel #21
0
    def get_detail(self, properties=None, icon_href=False):
        """Gets details from the details infoblock

        The function first ensures that we are on the detail page for the specific VM/Instance.

        Args:
            properties: An InfoBlock title, followed by the Key name, e.g. "Relationships", "Images"

        Returns:
            A string representing the contents of the InfoBlock's value.
        """
        self.load_details(refresh=True)
        if icon_href:
            return InfoBlock.icon_href(*properties)
        else:
            return InfoBlock.text(*properties)
Beispiel #22
0
    def get_detail(self, properties=None, icon_href=False):
        """Gets details from the details infoblock

        The function first ensures that we are on the detail page for the specific VM/Instance.

        Args:
            properties: An InfoBlock title, followed by the Key name, e.g. "Relationships", "Images"

        Returns:
            A string representing the contents of the InfoBlock's value.
        """
        self.load_details(refresh=True)
        if icon_href:
            return InfoBlock.icon_href(*properties)
        else:
            return InfoBlock.text(*properties)
Beispiel #23
0
def get_detail(properties):
    navigate_to(current_appliance().server, 'About')
    if current_version() < '5.7':
        return InfoBlock.text(*properties).encode(
            "utf-8").strip()
    else:
        locator = '//div[@class="product-versions-pf"]//li'
        sel.wait_for_element(locator)
        for element in sel.elements(locator):
            logger.debug('Checking for detail match for "{}" in  "{}"'.format(properties,
                                                                              element.text))
            match = re.match("{}\s(?P<value>.*)".format(properties), element.text)
            if match:
                return match.group('value')
        else:
            raise ElementOrBlockNotFound('Could not match about detail {}'.format(properties))
def test_images_rel(provider, rel):
    sel.force_navigate('containers_images')
    ui_images = [r.name.text for r in list_tbl.rows()]

    for name in ui_images:
        obj = Image(name, provider)

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

        try:
            val = int(val)
            assert len([r for r in list_tbl.rows()]) == val
        except ValueError:
            assert val == InfoBlock.text('Properties', 'Name')
Beispiel #25
0
def test_images_rel(provider, rel):
    sel.force_navigate('containers_images')
    ui_images = [r.name.text for r in list_tbl.rows()]

    for name in ui_images:
        obj = Image(name, provider)

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

        try:
            val = int(val)
            assert len([r for r in list_tbl.rows()]) == val
        except ValueError:
            assert val == InfoBlock.text('Properties', 'Name')
Beispiel #26
0
def get_detail(properties):
    navigate_to(current_appliance().server, 'About')
    if current_version() < '5.7':
        properties = ['Session Information', properties]
        return InfoBlock.text(*properties).encode("utf-8").strip()
    else:
        locator = '//div[@class="product-versions-pf"]//li'
        sel.wait_for_element(locator)
        for element in sel.elements(locator):
            logger.debug('Checking for detail match for "{}" in  "{}"'.format(
                properties, element.text))
            match = re.match("{}\s(?P<value>.*)".format(properties),
                             element.text)
            if match:
                return match.group('value')
        else:
            raise ElementOrBlockNotFound(
                'Could not match about detail {}'.format(properties))
Beispiel #27
0
def test_server_name():
    """Tests that changing the server name updates the about page"""
    form_infoblocks = InfoBlock('form')
    flash_msg = 'Configuration settings saved for CFME Server "{}'

    sel.force_navigate('cfg_settings_currentserver_server')
    old_server_name = sel.value(BasicInformation.basic_information.appliance_name)
    new_server_name = old_server_name + "-CFME"
    settings_pg = BasicInformation(appliance_name=new_server_name)
    settings_pg.update()
    flash.assert_message_contain(flash_msg.format(new_server_name))

    sel.force_navigate('about')
    assert new_server_name == form_infoblocks.text('Session Information', 'Server Name'),\
        "Server name in About section does not match the new name"

    settings_pg = BasicInformation(appliance_name=old_server_name)
    settings_pg.update()
    flash.assert_message_contain(flash_msg.format(old_server_name))
def test_containers_smartstate_analysis(provider, ssh_client):
    """Smart State analysis functionality check for single container image.
    Steps:
        1. Perform smart state analysis
            Expected: Green message showing: "...Analysis successfully Initiated"
        2. Waiting for analysis finish
            Expected: 'finished'
        3. check task succession in log
            Expected: LOG_VERIFICATION_TAGS are shown in the log
        4. verify that detail was added
            Expected: all RESULT_DETAIL_FIELDS are shown an pass the function"""
    delete_all_vm_tasks()
    # step 1
    navigate_to(Image, 'All')
    tb.select('List View')
    count = list_tbl.row_count()
    if not count:
        pytest.skip('Images table is empty! - cannot perform SSA test -> Skipping...')
    try:
        evm_tail = SSHTail('/var/www/miq/vmdb/log/evm.log')
    except:  # TODO: Should we add a specific exception?
        pytest.skip('Cannot continue test, probably due to containerized appliance\n'
                    'Traceback: \n{}'.format(format_exc()))
    evm_tail.set_initial_file_end()
    list_tbl.select_rows_by_indexes(choice(range(count)))
    tb.select('Configuration', 'Perform SmartState Analysis', invokes_alert=True)
    sel.handle_alert()
    flash.assert_message_contain('Analysis successfully initiated')
    # step 2
    ssa_timeout = '5M'
    try:
        tasks.wait_analysis_finished('Container image analysis',
                                     'vm', delay=5, timeout=ssa_timeout)
    except TimedOutError:
        pytest.fail('Timeout exceeded, Waited too much time for SSA to finish ({}).'
                    .format(ssa_timeout))
    # Step 3
    check_log(evm_tail.raw_string(), LOG_VERIFICATION_TAGS)
    # Step 4
    time_queued = tasks_table.rows_as_list()[0].updated.text
    tasks_table.click_cell('Updated', value=time_queued)
    for field, verify_func in RESULT_DETAIL_FIELDS.items():
        assert verify_func(InfoBlock.text('Configuration', field))
Beispiel #29
0
def test_server_name():
    """Tests that changing the server name updates the about page"""
    form_infoblocks = InfoBlock('form')
    flash_msg = 'Configuration settings saved for CFME Server "{}'

    sel.force_navigate('cfg_settings_currentserver_server')
    old_server_name = sel.value(
        BasicInformation.basic_information.appliance_name)
    new_server_name = old_server_name + "-CFME"
    settings_pg = BasicInformation(appliance_name=new_server_name)
    settings_pg.update()
    flash.assert_message_contain(flash_msg.format(new_server_name))

    sel.force_navigate('about')
    assert new_server_name == form_infoblocks.text('Session Information', 'Server Name'),\
        "Server name in About section does not match the new name"

    settings_pg = BasicInformation(appliance_name=old_server_name)
    settings_pg.update()
    flash.assert_message_contain(flash_msg.format(old_server_name))
def test_images_rel(provider, rel):
    """ https://bugzilla.redhat.com/show_bug.cgi?id=1365878
    """
    sel.force_navigate('containers_images')
    tb.select('List View')
    list_tbl_image = CheckboxTable(
        table_locator="//div[@id='list_grid']//table")
    ui_images = [r.name.text for r in list_tbl_image.rows()]

    for name in ui_images:
        obj = Image(name, provider)

        val = obj.get_detail('Relationships', rel)
        assert val != 'Unknown image source'
        obj.click_element('Relationships', rel)

        try:
            val = int(val)
            assert len([r for r in list_tbl_image.rows()]) == val
        except ValueError:
            assert val == InfoBlock.text('Properties', 'Name')
def test_images_rel(provider, rel, detailfield):
    """ https://bugzilla.redhat.com/show_bug.cgi?id=1365878
    """
    # Nav to provider first
    navigate_to(provider, 'Details')

    # Then to container images for that provider
    # Locate Relationships table in provider details
    images_key = ({
        version.LOWEST: 'Images',
        '5.7': 'Container Images'
    })
    sel.click(InfoBlock.element('Relationships', version.pick(images_key)))

    # Get the names of all the container images from the table
    list_tbl_image = CheckboxTable(
        table_locator="//div[@id='list_grid']//table")
    ui_images = [r.name.text for r in list_tbl_image.rows()]

    for name in ui_images:
        img = Image(name, provider)
        navigate_to(img, 'Details')

        val = img.get_detail('Relationships', rel)
        assert val != 'Unknown image source'

        sel.click(InfoBlock.element('Relationships', rel))

        # Containers Provider and Image Registry are string values
        # Other rows in the table show the number of the given items
        if rel in ['Containers Provider', 'Image Registry']:
            assert val == InfoBlock.text('Properties', detailfield)
        else:
            val = int(val)
            # There might be more than 1 page of items
            if paginator.page_controls_exist():
                paginator.results_per_page(1000)
            assert len([r for r in list_tbl_image.rows()]) == val
def test_projects_rel(provider, rel):
    sel.force_navigate('containers_projects')
    ui_projects = [r.name.text for r in list_tbl.rows()]
    mgmt_objs = provider.mgmt.list_project()  # run only if table is not empty

    if ui_projects:
        # verify that mgmt pods exist in ui listed pods
        assert set(ui_projects).issubset(
            [obj.name for obj in mgmt_objs]), 'Missing objects'

    for name in ui_projects:
        obj = Project(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.rows()]) == val
        except ValueError:
            assert val == InfoBlock.text('Properties', 'Name')
Beispiel #33
0
def test_services_rel(provider, rel):
    sel.force_navigate('containers_services')
    ui_services = [r.name.text for r in list_tbl.rows()]
    mgmt_objs = provider.mgmt.list_service()  # run only if table is not empty

    if ui_services:
        # verify that mgmt pods exist in ui listed pods
        assert set(ui_services).issubset([obj.name for obj in mgmt_objs
                                          ]), 'Missing objects'

    for name in ui_services:
        obj = Service(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.rows()]) == val
        except ValueError:
            assert val == InfoBlock.text('Properties', 'Name')
def test_nodes_rel(provider, rel):
    navigate_to(provider, 'Details')

    sel.click(InfoBlock.element('Relationships', 'Nodes'))

    list_tbl_node = CheckboxTable(
        table_locator="//div[@id='list_grid']//table")
    ui_nodes = [r.name.text for r in list_tbl_node.rows()]
    mgmt_objs = provider.mgmt.list_node()

    assert set(ui_nodes).issubset(
        [obj.name for obj in mgmt_objs]), 'Missing objects'

    for name in ui_nodes:
        node = Node(name, provider)

        val = node.get_detail('Relationships', rel)
        if val == '0':
            # the row can't be clicked when there are no items, and has class 'no-hover'
            logger.info('No items for node relationship: {}'.format(rel))
            continue
        # Should already be here, but just in case
        navigate_to(node, 'Details')
        sel.click(InfoBlock.element('Relationships', rel))

        try:
            val = int(val)
            # best effort to include all items from rel in one page
            if paginator.page_controls_exist():
                logger.info('Setting results per page to 1000 for {}'.format(rel))
                paginator.results_per_page(1000)
            else:
                logger.warning('Unable to increase results per page, '
                               'assertion against number of rows may fail.')
            assert len([r for r in list_tbl_node.rows()]) == val
        except ValueError:  # if the conversion to integer failed, its a non-scalar relationship
            assert val == InfoBlock.text('Properties', 'Name')
def test_projects_rel(provider, rel):
    sel.force_navigate('containers_projects')
    tb.select('List View')
    list_tbl_project = CheckboxTable(
        table_locator="//div[@id='list_grid']//table")
    ui_projects = [r.name.text for r in list_tbl_project.rows()]
    mgmt_objs = provider.mgmt.list_project()

    assert set(ui_projects).issubset(
        [obj.name for obj in mgmt_objs]), 'Missing objects'

    for name in ui_projects:
        obj = Project(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_project.rows()]) == val
        except ValueError:
            assert val == InfoBlock.text('Properties', 'Name')
Beispiel #36
0
def test_ssa_template(request, local_setup_provider, provider, soft_assert,
                      vm_analysis_data, appliance):
    """ Tests SSA can be performed on a template

    Metadata:
        test_flag: vm_analysis
    """

    template_name = vm_analysis_data['image']
    template = Template.factory(template_name, provider, template=True)

    # Set credentials to all hosts set for this datastore
    if provider.type in ['virtualcenter', 'rhevm']:
        datastore_name = vm_analysis_data['datastore']
        datastore_collection = appliance.collections.datastores
        test_datastore = datastore_collection.instantiate(name=datastore_name,
                                                          provider=provider)
        host_list = cfme_data.get('management_systems',
                                  {})[provider.key].get('hosts', [])
        host_names = [h.name for h in test_datastore.get_hosts()]
        for host_name in host_names:
            host_collection = appliance.collections.hosts
            test_host = host_collection.instantiate(name=host_name,
                                                    provider=provider)
            hosts_data = [x for x in host_list if x.name == host_name]
            if len(hosts_data) > 0:
                host_data = hosts_data[0]

                if not test_host.has_valid_credentials:
                    creds = host.get_credentials_from_config(
                        host_data['credentials'])
                    test_host.update(updates={'credentials': creds},
                                     validate_credentials=True)

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

    # Check release and quadricon
    quadicon_os_icon = template.find_quadicon().data['os']
    details_os_icon = template.get_detail(properties=('Properties',
                                                      'Operating System'),
                                          icon_href=True)
    logger.info("Icons: {}, {}".format(details_os_icon, quadicon_os_icon))

    # We shouldn't use get_detail anymore - it takes too much time
    c_users = InfoBlock.text('Security', 'Users')
    c_groups = InfoBlock.text('Security', 'Groups')
    c_packages = 0
    if vm_analysis_data['fs-type'] not in ['ntfs', 'fat32']:
        c_packages = InfoBlock.text('Configuration', 'Packages')

    logger.info("SSA shows {} users, {} groups and {} packages".format(
        c_users, c_groups, c_packages))

    if vm_analysis_data['fs-type'] not in ['ntfs', 'fat32']:
        soft_assert(c_users != '0', "users: '{}' != '0'".format(c_users))
        soft_assert(c_groups != '0', "groups: '{}' != '0'".format(c_groups))
        soft_assert(c_packages != '0',
                    "packages: '{}' != '0'".format(c_packages))
    else:
        # Make sure windows-specific data is not empty
        c_patches = InfoBlock.text('Security', 'Patches')
        c_applications = InfoBlock.text('Configuration', 'Applications')
        c_win32_services = InfoBlock.text('Configuration', 'Win32 Services')
        c_kernel_drivers = InfoBlock.text('Configuration', 'Kernel Drivers')
        c_fs_drivers = InfoBlock.text('Configuration', 'File System Drivers')

        soft_assert(c_patches != '0', "patches: '{}' != '0'".format(c_patches))
        soft_assert(c_applications != '0',
                    "applications: '{}' != '0'".format(c_applications))
        soft_assert(c_win32_services != '0',
                    "win32 services: '{}' != '0'".format(c_win32_services))
        soft_assert(c_kernel_drivers != '0',
                    "kernel drivers: '{}' != '0'".format(c_kernel_drivers))
        soft_assert(c_fs_drivers != '0',
                    "fs drivers: '{}' != '0'".format(c_fs_drivers))
def test_ssa_vm(provider, instance, soft_assert):
    """ Tests SSA can be performed and returns sane results

    Metadata:
        test_flag: vm_analysis
    """

    e_users = None
    e_groups = None
    e_packages = None
    e_services = None
    e_icon_part = instance.system_type['icon']

    if instance.system_type != WINDOWS:
        e_users = instance.ssh.run_command("cat /etc/passwd | wc -l").output.strip('\n')
        e_groups = instance.ssh.run_command("cat /etc/group | wc -l").output.strip('\n')
        e_packages = instance.ssh.run_command(
            instance.system_type['package-number']).output.strip('\n')
        e_services = instance.ssh.run_command(
            instance.system_type['services-number']).output.strip('\n')

    logger.info("Expecting to have {} users, {} groups, {} packages and {} services".format(
        e_users, e_groups, e_packages, e_services))

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

    # Check release and quadricon
    quadicon_os_icon = instance.find_quadicon().os
    details_os_icon = instance.get_detail(
        properties=('Properties', 'Operating System'), icon_href=True)
    logger.info("Icons: %s, %s", details_os_icon, quadicon_os_icon)

    # We shouldn't use get_detail anymore - it takes too much time
    c_lastanalyzed = InfoBlock.text('Lifecycle', 'Last Analyzed')
    c_users = InfoBlock.text('Security', 'Users')
    c_groups = InfoBlock.text('Security', 'Groups')
    c_packages = 0
    c_services = 0
    if instance.system_type != WINDOWS:
        c_packages = InfoBlock.text('Configuration', 'Packages')
        c_services = InfoBlock.text('Configuration', 'Init Processes')

    logger.info("SSA shows {} users, {} groups {} packages and {} services".format(
        c_users, c_groups, c_packages, c_services))

    soft_assert(c_lastanalyzed != 'Never', "Last Analyzed is set to Never")
    soft_assert(e_icon_part in details_os_icon,
                "details icon: '{}' not in '{}'".format(e_icon_part, details_os_icon))
    soft_assert(e_icon_part in quadicon_os_icon,
                "quad icon: '{}' not in '{}'".format(e_icon_part, details_os_icon))

    if instance.system_type != WINDOWS:
        soft_assert(c_users == e_users, "users: '{}' != '{}'".format(c_users, e_users))
        soft_assert(c_groups == e_groups, "groups: '{}' != '{}'".format(c_groups, e_groups))
        soft_assert(c_packages == e_packages,
            "packages: '{}' != '{}'".format(c_packages, e_packages))
        if not BZ("1312971").blocks:
            soft_assert(c_services == e_services,
                        "services: '{}' != '{}'".format(c_services, e_services))
    else:
        # Make sure windows-specific data is not empty
        c_patches = InfoBlock.text('Security', 'Patches')
        c_applications = InfoBlock.text('Configuration', 'Applications')
        c_win32_services = InfoBlock.text('Configuration', 'Win32 Services')
        c_kernel_drivers = InfoBlock.text('Configuration', 'Kernel Drivers')
        c_fs_drivers = InfoBlock.text('Configuration', 'File System Drivers')

        soft_assert(c_patches != '0', "patches: '{}' != '0'".format(c_patches))
        soft_assert(c_applications != '0', "applications: '{}' != '0'".format(c_applications))
        soft_assert(c_win32_services != '0', "win32 services: '{}' != '0'".format(c_win32_services))
        soft_assert(c_kernel_drivers != '0', "kernel drivers: '{}' != '0'".format(c_kernel_drivers))
        soft_assert(c_fs_drivers != '0', "fs drivers: '{}' != '0'".format(c_fs_drivers))

    image_label = 'Parent VM'
    if provider.type == 'openstack':
        image_label = 'VM Template'
    # 5.4 doesn't have Parent VM field
    if version.current_version() > "5.5" and provider.type != 'openstack':
        c_image = InfoBlock.text('Relationships', image_label)
        soft_assert(c_image == instance.image,
                    "image: '{}' != '{}'".format(c_image, instance.image))
def test_ssa_template(request, local_setup_provider, provider, soft_assert, vm_analysis_data):
    """ Tests SSA can be performed on a template

    Metadata:
        test_flag: vm_analysis
    """

    template_name = vm_analysis_data['image']
    template = Template.factory(template_name, provider, template=True)

    # Set credentials to all hosts set for this datastore
    if provider.type != 'openstack':
        datastore_name = vm_analysis_data['datastore']
        test_datastore = datastore.Datastore(datastore_name, provider.key)
        host_list = cfme_data.get('management_systems', {})[provider.key].get('hosts', [])
        host_names = test_datastore.get_hosts()
        for host_name in host_names:
            test_host = host.Host(name=host_name)
            hosts_data = [x for x in host_list if x.name == host_name]
            if len(hosts_data) > 0:
                host_data = hosts_data[0]

                if not test_host.has_valid_credentials:
                    creds = host.get_credentials_from_config(host_data['credentials'])
                    test_host.update(
                        updates={'credentials': creds},
                        validate_credentials=True
                    )

    template.smartstate_scan()
    wait_for(lambda: is_vm_analysis_finished(template_name),
             delay=15, timeout="10m", fail_func=lambda: toolbar.select('Reload'))

    # Check release and quadricon
    quadicon_os_icon = template.find_quadicon().os
    details_os_icon = template.get_detail(
        properties=('Properties', 'Operating System'), icon_href=True)
    logger.info("Icons: {}, {}".format(details_os_icon, quadicon_os_icon))

    # We shouldn't use get_detail anymore - it takes too much time
    c_users = InfoBlock.text('Security', 'Users')
    c_groups = InfoBlock.text('Security', 'Groups')
    c_packages = 0
    if vm_analysis_data['fs-type'] not in ['ntfs', 'fat32']:
        c_packages = InfoBlock.text('Configuration', 'Packages')

    logger.info("SSA shows {} users, {} groups and {} packages".format(
        c_users, c_groups, c_packages))

    if vm_analysis_data['fs-type'] not in ['ntfs', 'fat32']:
        soft_assert(c_users != '0', "users: '{}' != '0'".format(c_users))
        soft_assert(c_groups != '0', "groups: '{}' != '0'".format(c_groups))
        soft_assert(c_packages != '0', "packages: '{}' != '0'".format(c_packages))
    else:
        # Make sure windows-specific data is not empty
        c_patches = InfoBlock.text('Security', 'Patches')
        c_applications = InfoBlock.text('Configuration', 'Applications')
        c_win32_services = InfoBlock.text('Configuration', 'Win32 Services')
        c_kernel_drivers = InfoBlock.text('Configuration', 'Kernel Drivers')
        c_fs_drivers = InfoBlock.text('Configuration', 'File System Drivers')

        soft_assert(c_patches != '0', "patches: '{}' != '0'".format(c_patches))
        soft_assert(c_applications != '0', "applications: '{}' != '0'".format(c_applications))
        soft_assert(c_win32_services != '0', "win32 services: '{}' != '0'".format(c_win32_services))
        soft_assert(c_kernel_drivers != '0', "kernel drivers: '{}' != '0'".format(c_kernel_drivers))
        soft_assert(c_fs_drivers != '0', "fs drivers: '{}' != '0'".format(c_fs_drivers))
def test_run_host_analysis(request, setup_provider, provider, host_type, host_name, register_event,
                           soft_assert, bug):
    """ Run host SmartState analysis

    Metadata:
        test_flag: host_analysis
    """
    # Add credentials to host
    host_data = get_host_data_by_name(provider.key, host_name)
    test_host = host.Host(name=host_name, provider=provider)

    wait_for(lambda: test_host.exists, delay=10, num_sec=120)

    if not test_host.has_valid_credentials:
        with update(test_host):
            test_host.credentials = host.get_credentials_from_config(host_data['credentials'])

        wait_for(lambda: test_host.has_valid_credentials, delay=10, num_sec=120)

        # Remove creds after test
        @request.addfinalizer
        def _host_remove_creds():
            with update(test_host):
                test_host.credentials = host.Host.Credential(
                    principal="", secret="", verify_secret="")

    builder = EventBuilder(get_or_create_current_appliance())
    base_evt = partial(builder.new_event, target_type='Host', target_name=host_name)

    register_event(base_evt(event_type='request_host_scan'),
                   base_evt(event_type='host_scan_complete'))

    # Initiate analysis
    test_host.run_smartstate_analysis()

    wait_for(lambda: is_host_analysis_finished(host_name),
             delay=15, timeout="10m", fail_func=lambda: toolbar.select('Reload'))

    # Check results of the analysis
    drift_history = test_host.get_detail('Relationships', 'Drift History')
    soft_assert(drift_history != '0', 'No drift history change found')

    if provider.type == "rhevm":
        soft_assert(test_host.get_detail('Configuration', 'Services') != '0',
            'No services found in host detail')

    if host_type in ('rhel', 'rhev'):
        soft_assert(InfoBlock.text('Security', 'Users') != '0',
            'No users found in host detail')
        soft_assert(InfoBlock.text('Security', 'Groups') != '0',
            'No groups found in host detail')
        soft_assert(InfoBlock.text('Security', 'SSH Root') != '',
            'No packages found in host detail')
        soft_assert(InfoBlock.text('Configuration', 'Packages') != '0',
            'No packages found in host detail')
        soft_assert(InfoBlock.text('Configuration', 'Files') != '0',
            'No files found in host detail')
        soft_assert(InfoBlock.text('Security', 'Firewall Rules') != '0',
            'No firewall rules found in host detail')

    elif host_type in ('esx', 'esxi'):
        soft_assert(InfoBlock.text('Configuration', 'Advanced Settings') != '0',
            'No advanced settings found in host detail')

        if not(provider.type == "virtualcenter" and provider.version < "5"):
            # If the Firewall Rules are 0, the element can't be found (it's not a link)
            try:
                # This fails for vsphere4...  https://bugzilla.redhat.com/show_bug.cgi?id=1055657
                list_acc.select('Security', 'Show the firewall rules on this Host')
            except ListAccordionLinkNotFound:
                # py.test's .fail would wipe the soft_assert data
                soft_assert(False, "No firewall rules found in host detail accordion")
def test_db_backup_schedule(request, db_backup_data):
    """ Test scheduled one-type backup on given machines using smb/nfs
    """

    # ---- Create new db backup schedule set to run in the next 6 min
    dt = get_schedulable_datetime()
    # the dash is there to make strftime not use a leading zero
    hour = dt.strftime('%-H')
    minute = dt.strftime('%-M')

    sched_args = {
        'name': db_backup_data.schedule_name,
        'description': db_backup_data.schedule_description,
        'active': True,
        'run_type': "Once",
        'run_every': None,
        'time_zone': "UTC",
        'start_date': dt,
        'start_hour': hour,
        'start_min': minute
    }

    if db_backup_data.protocol_type == 'smb':
        sched_args.update({
            'protocol':
            'Samba',
            'uri':
            db_backup_data.hostname,
            'username':
            db_backup_data.credentials['username'],
            'password':
            db_backup_data.credentials['password'],
            'password_verify':
            db_backup_data.credentials['password']
        })
    else:
        sched_args.update({
            'protocol': 'Network File System',
            'uri': db_backup_data.hostname,
        })

    if db_backup_data.protocol_type == 'nfs':
        path_on_host = urlparse('nfs://' + db_backup_data.hostname).path
    else:
        path_on_host = db_backup_data.path_on_host
    full_path = get_full_path_to_file(path_on_host,
                                      db_backup_data.schedule_name)

    sched = DatabaseBackupSchedule(**sched_args)
    # Fails on upstream - BZ1099341
    sched.create()
    flash.assert_message_contain('Schedule "{}" was saved'.format(
        db_backup_data.schedule_name))

    # ----

    # ---- Add cleanup finalizer
    def delete_sched_and_files():
        with get_ssh_client(db_backup_data.hostname,
                            db_backup_data.credentials) as ssh:
            ssh.run_command('rm -rf {}'.format(full_path))
        sched.delete()
        flash.assert_message_contain('Schedule "{}": Delete successful'.format(
            db_backup_data.schedule_description))

    request.addfinalizer(delete_sched_and_files)
    # ----

    # ---- Wait for schedule to run
    sel.force_navigate('cfg_settings_schedule',
                       context={'schedule_name': db_backup_data.schedule_name})
    form_infoblocks = InfoBlock('form')
    wait_for(
        lambda: form_infoblocks.text('Schedule Info', 'Last Run Time') != '',
        num_sec=600,
        delay=30,
        fail_func=sel.refresh,
        message='Schedule failed to run in 10mins from being set up')
    # ----

    # ---- Check if the db backup file exists
    with get_ssh_client(db_backup_data.hostname,
                        db_backup_data.credentials) as ssh:

        assert ssh.run_command('cd "{}"'.format(path_on_host))[0] == 0,\
            "Could not cd into '{}' over ssh".format(path_on_host)
        # Find files no more than 5 minutes old, count them and remove newline
        file_check_cmd = "find {}/* -cmin -5 | wc -l | tr -d '\n' ".format(
            full_path)

        wait_for(lambda: ssh.run_command(file_check_cmd)[1] == '1',
                 delay=5,
                 num_sec=60,
                 message="File '{}' not found on share".format(full_path))
def test_ssa_vm(provider, instance, soft_assert):
    """ Tests SSA can be performed and returns sane results

    Metadata:
        test_flag: vm_analysis
    """

    e_users = None
    e_groups = None
    e_packages = None
    e_icon_part = instance.system_type['icon']

    if instance.system_type != WINDOWS:
        e_users = instance.ssh.run_command(
            "cat /etc/passwd | wc -l").output.strip('\n')
        e_groups = instance.ssh.run_command(
            "cat /etc/group | wc -l").output.strip('\n')
        e_packages = instance.ssh.run_command(
            instance.system_type['package-number']).output.strip('\n')

    logger.info("Expecting to have {} users, {} groups and {} packages".format(
        e_users, e_groups, e_packages))

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

    # Check release and quadricon
    quadicon_os_icon = instance.find_quadicon().os
    details_os_icon = instance.get_detail(properties=('Properties',
                                                      'Operating System'),
                                          icon_href=True)
    logger.info("Icons: {}, {}".format(details_os_icon, quadicon_os_icon))

    # We shouldn't use get_detail anymore - it takes too much time
    c_users = InfoBlock.text('Security', 'Users')
    c_groups = InfoBlock.text('Security', 'Groups')
    c_packages = 0
    if instance.system_type != WINDOWS:
        c_packages = InfoBlock.text('Configuration', 'Packages')

    logger.info("SSA shows {} users, {} groups and {} packages".format(
        c_users, c_groups, c_packages))

    soft_assert(
        e_icon_part in details_os_icon,
        "details icon: '{}' not in '{}'".format(e_icon_part, details_os_icon))
    soft_assert(
        e_icon_part in quadicon_os_icon,
        "quad icon: '{}' not in '{}'".format(e_icon_part, details_os_icon))

    if instance.system_type != WINDOWS:
        soft_assert(c_users == e_users,
                    "users: '{}' != '{}'".format(c_users, e_users))
        soft_assert(c_groups == e_groups,
                    "groups: '{}' != '{}'".format(c_groups, e_groups))
        soft_assert(c_packages == e_packages,
                    "groups: '{}' != '{}'".format(c_groups, e_groups))
    else:
        # Make sure windows-specific data is not empty
        c_patches = InfoBlock.text('Security', 'Patches')
        c_applications = InfoBlock.text('Configuration', 'Applications')
        c_win32_services = InfoBlock.text('Configuration', 'Win32 Services')
        c_kernel_drivers = InfoBlock.text('Configuration', 'Kernel Drivers')
        c_fs_drivers = InfoBlock.text('Configuration', 'File System Drivers')

        soft_assert(c_patches != '0', "patches: '{}' != '0'".format(c_patches))
        soft_assert(c_applications != '0',
                    "applications: '{}' != '0'".format(c_applications))
        soft_assert(c_win32_services != '0',
                    "win32 services: '{}' != '0'".format(c_win32_services))
        soft_assert(c_kernel_drivers != '0',
                    "kernel drivers: '{}' != '0'".format(c_kernel_drivers))
        soft_assert(c_fs_drivers != '0',
                    "fs drivers: '{}' != '0'".format(c_fs_drivers))

    image_label = 'Parent VM'
    if provider.type == 'openstack':
        image_label = 'VM Template'
    # 5.4 doesn't have Parent VM field
    if version.current_version() > "5.5" and provider.type != 'openstack':
        c_image = InfoBlock.text('Relationships', image_label)
        soft_assert(c_image == instance.image,
                    "image: '{}' != '{}'".format(c_image, instance.image))
def test_run_host_analysis(request, setup_provider, provider, host_type, host_name, register_event,
                           soft_assert, bug):
    """ Run host SmartState analysis

    Metadata:
        test_flag: host_analysis
    """
    # Add credentials to host
    host_data = get_host_data_by_name(provider.key, host_name)
    test_host = host.Host(name=host_name)

    wait_for(lambda: test_host.exists, delay=10, num_sec=120)

    if not test_host.has_valid_credentials:
        with update(test_host):
            test_host.credentials = host.get_credentials_from_config(host_data['credentials'])

        wait_for(lambda: test_host.has_valid_credentials, delay=10, num_sec=120)

        # Remove creds after test
        @request.addfinalizer
        def _host_remove_creds():
            with update(test_host):
                test_host.credentials = host.Host.Credential(
                    principal="", secret="", verify_secret="")

    register_event(None, "host", host_name, ["host_analysis_request", "host_analysis_complete"])

    # Initiate analysis
    test_host.run_smartstate_analysis()

    # Wait for the task to finish
    @pytest.wait_for(delay=15, timeout="8m", fail_func=lambda: tb.select('Reload'))
    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'
        })
        return host_analysis_finished is not None

    # 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()

    # Check results of the analysis
    drift_history = test_host.get_detail('Relationships', 'Drift History')
    soft_assert(drift_history != '0', 'No drift history change found')

    # This is done on purpose; we cannot use the "bug" fixture here as
    # the bug doesnt block streams other than 5.3
    services_bug = BZ(1156028, forced_streams=["5.3", "5.4", "5.5", "upstream"])
    if provider.type == "rhevm" and (not services_bug.blocks):
        soft_assert(test_host.get_detail('Configuration', 'Services') != '0',
            'No services found in host detail')

    if host_type in ('rhel', 'rhev'):
        soft_assert(InfoBlock.text('Security', 'Users') != '0',
            'No users found in host detail')
        soft_assert(InfoBlock.text('Security', 'Groups') != '0',
            'No groups found in host detail')
        soft_assert(InfoBlock.text('Security', 'SSH Root') != '',
            'No packages found in host detail')
        soft_assert(InfoBlock.text('Configuration', 'Packages') != '0',
            'No packages found in host detail')
        soft_assert(InfoBlock.text('Configuration', 'Files') != '0',
            'No files found in host detail')

        if not BZ(1055657, forced_streams=["5.4", "5.5", "upstream"]).blocks:
            soft_assert(InfoBlock.text('Security', 'Firewall Rules') != '0',
                        'No firewall rules found in host detail')

    elif host_type in ('esx', 'esxi'):
        soft_assert(InfoBlock.text('Configuration', 'Advanced Settings') != '0',
            'No advanced settings found in host detail')

        fw_bug = bug(1055657)
        if not (fw_bug is not None and provider.type == "virtualcenter" and provider.version < "5"):
            # If the Firewall Rules are 0, the element can't be found (it's not a link)
            try:
                # This fails for vsphere4...  https://bugzilla.redhat.com/show_bug.cgi?id=1055657
                list_acc.select('Security', 'Show the firewall rules on this Host')
            except ListAccordionLinkNotFound:
                # py.test's .fail would wipe the soft_assert data
                soft_assert(False, "No firewall rules found in host detail accordion")
Beispiel #43
0
def test_ssa_vm(provider, instance, soft_assert):
    """ Tests SSA can be performed and returns sane results

    Metadata:
        test_flag: vm_analysis
    """

    # TODO: check if previously scanned?
    #       delete the vm itself if it did have a scan already
    #       delete all previous scan tasks

    e_users = None
    e_groups = None
    e_packages = None
    e_services = None
    e_icon_part = instance.system_type['icon']

    if instance.system_type != WINDOWS:
        e_users = instance.ssh.run_command(
            "cat /etc/passwd | wc -l").output.strip('\n')
        e_groups = instance.ssh.run_command(
            "cat /etc/group | wc -l").output.strip('\n')
        e_packages = instance.ssh.run_command(
            instance.system_type['package-number']).output.strip('\n')
        e_services = instance.ssh.run_command(
            instance.system_type['services-number']).output.strip('\n')

    logger.info(
        "Expecting to have {} users, {} groups, {} packages and {} services".
        format(e_users, e_groups, e_packages, e_services))

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

    # Check release and quadricon
    quadicon_os_icon = instance.find_quadicon().data['os']
    details_os_icon = instance.get_detail(properties=('Properties',
                                                      'Operating System'),
                                          icon_href=True)
    logger.info("Icons: %s, %s", details_os_icon, quadicon_os_icon)

    # We shouldn't use get_detail anymore - it takes too much time
    c_lastanalyzed = InfoBlock.text('Lifecycle', 'Last Analyzed')
    c_users = InfoBlock.text('Security', 'Users')
    c_groups = InfoBlock.text('Security', 'Groups')
    c_packages = 0
    c_services = 0
    if instance.system_type != WINDOWS:
        c_packages = InfoBlock.text('Configuration', 'Packages')
        c_services = InfoBlock.text('Configuration', 'Init Processes')

    logger.info(
        "SSA shows {} users, {} groups {} packages and {} services".format(
            c_users, c_groups, c_packages, c_services))

    soft_assert(c_lastanalyzed != 'Never', "Last Analyzed is set to Never")
    soft_assert(
        e_icon_part in details_os_icon,
        "details icon: '{}' not in '{}'".format(e_icon_part, details_os_icon))
    soft_assert(
        e_icon_part in quadicon_os_icon,
        "quad icon: '{}' not in '{}'".format(e_icon_part, details_os_icon))

    if instance.system_type != WINDOWS:
        soft_assert(c_users == e_users,
                    "users: '{}' != '{}'".format(c_users, e_users))
        soft_assert(c_groups == e_groups,
                    "groups: '{}' != '{}'".format(c_groups, e_groups))
        soft_assert(c_packages == e_packages,
                    "packages: '{}' != '{}'".format(c_packages, e_packages))
        soft_assert(c_services == e_services,
                    "services: '{}' != '{}'".format(c_services, e_services))
    else:
        # Make sure windows-specific data is not empty
        c_patches = InfoBlock.text('Security', 'Patches')
        c_applications = InfoBlock.text('Configuration', 'Applications')
        c_win32_services = InfoBlock.text('Configuration', 'Win32 Services')
        c_kernel_drivers = InfoBlock.text('Configuration', 'Kernel Drivers')
        c_fs_drivers = InfoBlock.text('Configuration', 'File System Drivers')

        soft_assert(c_patches != '0', "patches: '{}' != '0'".format(c_patches))
        soft_assert(c_applications != '0',
                    "applications: '{}' != '0'".format(c_applications))
        soft_assert(c_win32_services != '0',
                    "win32 services: '{}' != '0'".format(c_win32_services))
        soft_assert(c_kernel_drivers != '0',
                    "kernel drivers: '{}' != '0'".format(c_kernel_drivers))
        soft_assert(c_fs_drivers != '0',
                    "fs drivers: '{}' != '0'".format(c_fs_drivers))
def test_run_host_analysis(request, setup_provider, provider, host_type,
                           host_name, register_event, soft_assert, bug):
    """ Run host SmartState analysis

    Metadata:
        test_flag: host_analysis
    """
    # Add credentials to host
    host_data = get_host_data_by_name(provider.key, host_name)
    test_host = host.Host(name=host_name)

    wait_for(lambda: test_host.exists, delay=10, num_sec=120)

    if not test_host.has_valid_credentials:
        with update(test_host):
            test_host.credentials = host.get_credentials_from_config(
                host_data['credentials'])

        wait_for(lambda: test_host.has_valid_credentials,
                 delay=10,
                 num_sec=120)

        # Remove creds after test
        @request.addfinalizer
        def _host_remove_creds():
            with update(test_host):
                test_host.credentials = host.Host.Credential(principal="",
                                                             secret="",
                                                             verify_secret="")

    register_event(None, "host", host_name,
                   ["host_analysis_request", "host_analysis_complete"])

    # Initiate analysis
    test_host.run_smartstate_analysis()

    # Wait for the task to finish
    @pytest.wait_for(delay=15,
                     timeout="8m",
                     fail_func=lambda: tb.select('Reload'))
    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'
        })
        return host_analysis_finished is not None

    # 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()

    # Check results of the analysis
    drift_history = test_host.get_detail('Relationships', 'Drift History')
    soft_assert(drift_history != '0', 'No drift history change found')

    # This is done on purpose; we cannot use the "bug" fixture here as
    # the bug doesnt block streams other than 5.3
    services_bug = BZ(1156028,
                      forced_streams=["5.3", "5.4", "5.5", "upstream"])
    if provider.type == "rhevm" and (not services_bug.blocks):
        soft_assert(
            test_host.get_detail('Configuration', 'Services') != '0',
            'No services found in host detail')

    if host_type in ('rhel', 'rhev'):
        soft_assert(
            InfoBlock.text('Security', 'Users') != '0',
            'No users found in host detail')
        soft_assert(
            InfoBlock.text('Security', 'Groups') != '0',
            'No groups found in host detail')
        soft_assert(
            InfoBlock.text('Security', 'SSH Root') != '',
            'No packages found in host detail')
        soft_assert(
            InfoBlock.text('Configuration', 'Packages') != '0',
            'No packages found in host detail')
        soft_assert(
            InfoBlock.text('Configuration', 'Files') != '0',
            'No files found in host detail')

        if not BZ(1055657, forced_streams=["5.4", "5.5", "upstream"]).blocks:
            soft_assert(
                InfoBlock.text('Security', 'Firewall Rules') != '0',
                'No firewall rules found in host detail')

    elif host_type in ('esx', 'esxi'):
        soft_assert(
            InfoBlock.text('Configuration', 'Advanced Settings') != '0',
            'No advanced settings found in host detail')

        fw_bug = bug(1055657)
        if not (fw_bug is not None and provider.type == "virtualcenter"
                and provider.version < "5"):
            # If the Firewall Rules are 0, the element can't be found (it's not a link)
            try:
                # This fails for vsphere4...  https://bugzilla.redhat.com/show_bug.cgi?id=1055657
                list_acc.select('Security',
                                'Show the firewall rules on this Host')
            except ListAccordionLinkNotFound:
                # py.test's .fail would wipe the soft_assert data
                soft_assert(
                    False, "No firewall rules found in host detail accordion")
Beispiel #45
0
def test_run_host_analysis(request, setup_provider, provider, host_type,
                           host_name, register_event, soft_assert, bug):
    """ Run host SmartState analysis

    Metadata:
        test_flag: host_analysis
    """
    # Add credentials to host
    host_data = get_host_data_by_name(provider.key, host_name)
    test_host = host.Host(name=host_name)

    wait_for(lambda: test_host.exists, delay=10, num_sec=120)

    if not test_host.has_valid_credentials:
        with update(test_host):
            test_host.credentials = host.get_credentials_from_config(
                host_data['credentials'])

        wait_for(lambda: test_host.has_valid_credentials,
                 delay=10,
                 num_sec=120)

        # Remove creds after test
        @request.addfinalizer
        def _host_remove_creds():
            with update(test_host):
                test_host.credentials = host.Host.Credential(principal="",
                                                             secret="",
                                                             verify_secret="")

    register_event(None, "host", host_name,
                   ["host_analysis_request", "host_analysis_complete"])

    # Initiate analysis
    test_host.run_smartstate_analysis()

    wait_for(lambda: is_host_analysis_finished(host_name),
             delay=15,
             timeout="10m",
             fail_func=lambda: toolbar.select('Reload'))

    # Check results of the analysis
    drift_history = test_host.get_detail('Relationships', 'Drift History')
    soft_assert(drift_history != '0', 'No drift history change found')

    if provider.type == "rhevm":
        soft_assert(
            test_host.get_detail('Configuration', 'Services') != '0',
            'No services found in host detail')

    if host_type in ('rhel', 'rhev'):
        soft_assert(
            InfoBlock.text('Security', 'Users') != '0',
            'No users found in host detail')
        soft_assert(
            InfoBlock.text('Security', 'Groups') != '0',
            'No groups found in host detail')
        soft_assert(
            InfoBlock.text('Security', 'SSH Root') != '',
            'No packages found in host detail')
        soft_assert(
            InfoBlock.text('Configuration', 'Packages') != '0',
            'No packages found in host detail')
        soft_assert(
            InfoBlock.text('Configuration', 'Files') != '0',
            'No files found in host detail')
        soft_assert(
            InfoBlock.text('Security', 'Firewall Rules') != '0',
            'No firewall rules found in host detail')

    elif host_type in ('esx', 'esxi'):
        soft_assert(
            InfoBlock.text('Configuration', 'Advanced Settings') != '0',
            'No advanced settings found in host detail')

        if not (provider.type == "virtualcenter" and provider.version < "5"):
            # If the Firewall Rules are 0, the element can't be found (it's not a link)
            try:
                # This fails for vsphere4...  https://bugzilla.redhat.com/show_bug.cgi?id=1055657
                list_acc.select('Security',
                                'Show the firewall rules on this Host')
            except ListAccordionLinkNotFound:
                # py.test's .fail would wipe the soft_assert data
                soft_assert(
                    False, "No firewall rules found in host detail accordion")
def test_db_backup_schedule(request, db_backup_data):
    """ Test scheduled one-type backup on given machines using smb/nfs
    """

    # ---- Create new db backup schedule set to run in the next 6 min
    dt = get_schedulable_datetime()
    # the dash is there to make strftime not use a leading zero
    hour = dt.strftime('%-H')
    minute = dt.strftime('%-M')

    sched_args = {
        'name': db_backup_data.schedule_name,
        'description': db_backup_data.schedule_description,
        'active': True,
        'run_type': "Once",
        'run_every': None,
        'time_zone': "UTC",
        'start_date': dt,
        'start_hour': hour,
        'start_min': minute
    }

    if db_backup_data.protocol_type == 'smb':
        sched_args.update({
            'protocol': 'Samba',
            'uri': db_backup_data.hostname,
            'username': db_backup_data.credentials['username'],
            'password': db_backup_data.credentials['password'],
            'password_verify': db_backup_data.credentials['password']
        })
    else:
        sched_args.update({
            'protocol': 'Network File System',
            'uri': db_backup_data.hostname,
        })

    if db_backup_data.protocol_type == 'nfs':
        path_on_host = urlparse('nfs://' + db_backup_data.hostname).path
    else:
        path_on_host = db_backup_data.path_on_host
    full_path = get_full_path_to_file(path_on_host, db_backup_data.schedule_name)

    sched = DatabaseBackupSchedule(**sched_args)
    # Fails on upstream - BZ1099341
    sched.create()
    flash.assert_message_contain('Schedule "{}" was saved'.format(db_backup_data.schedule_name))
    # ----

    # ---- Add cleanup finalizer
    def delete_sched_and_files():
        with get_ssh_client(db_backup_data.hostname, db_backup_data.credentials) as ssh:
            ssh.run_command('rm -rf {}'.format(full_path))
        sched.delete()
        flash.assert_message_contain(
            'Schedule "{}": Delete successful'.format(db_backup_data.schedule_description)
        )
    request.addfinalizer(delete_sched_and_files)
    # ----

    # ---- Wait for schedule to run
    sel.force_navigate('cfg_settings_schedule',
                       context={'schedule_name': db_backup_data.schedule_name})
    form_infoblocks = InfoBlock('form')
    wait_for(
        lambda: form_infoblocks.text('Schedule Info', 'Last Run Time') != '',
        num_sec=600,
        delay=30,
        fail_func=sel.refresh,
        message='Schedule failed to run in 10mins from being set up'
    )
    # ----

    # ---- Check if the db backup file exists
    with get_ssh_client(db_backup_data.hostname, db_backup_data.credentials) as ssh:

        assert ssh.run_command('cd "{}"'.format(path_on_host))[0] == 0,\
            "Could not cd into '{}' over ssh".format(path_on_host)
        # Find files no more than 5 minutes old, count them and remove newline
        file_check_cmd = "find {}/* -cmin -5 | wc -l | tr -d '\n' ".format(full_path)

        wait_for(
            lambda: ssh.run_command(file_check_cmd)[1] == '1',
            delay=5,
            num_sec=60,
            message="File '{}' not found on share".format(full_path)
        )