示例#1
0
def login(username, password, submit_method=_click_on_login):
    """
    Login to CFME with the given username and password.
    Optionally, submit_method can be press_enter_after_password
    to use the enter key to login, rather than clicking the button.

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

    Raises:
        RuntimeError: If the login fails, ie. if a flash message appears
    """
    # TODO: Should probably do the username check here, but there are pretty usernames to deal with
    # e.g. 'admin' shows up in the UI as 'Administrator'
    if not logged_in():
        # workaround for strange bug where we are logged out
        # as soon as we click something on the dashboard
        sel.sleep(1.0)

        logger.debug('Logging in as user %s' % username)
        fill(form, {'username': username, 'password': password})
        submit_method()
        flash.assert_no_errors()
    def _provisioner(template, provisioning_data, delayed=None):
        pytest.sel.force_navigate('infrastructure_provision_vms', context={
            'provider': provider,
            'template_name': template,
        })

        vm_name = provisioning_data["vm_name"]
        fill(provisioning_form, provisioning_data, action=provisioning_form.submit_button)
        flash.assert_no_errors()

        request.addfinalizer(lambda: cleanup_vm(vm_name, provider))
        if delayed is not None:
            total_seconds = (delayed - datetime.utcnow()).total_seconds()
            row_description = 'Provision from [{}] to [{}]'.format(template, vm_name)
            cells = {'Description': row_description}
            try:
                row, __ = wait_for(requests.wait_for_request, [cells],
                                   fail_func=requests.reload, num_sec=total_seconds, delay=5)
                pytest.fail("The provisioning was not postponed")
            except TimedOutError:
                pass
        logger.info('Waiting for vm %s to appear on provider %s', vm_name, provider.key)
        wait_for(provider.mgmt.does_vm_exist, [vm_name], handle_exception=True, num_sec=600)

        # nav to requests page happens on successful provision
        logger.info('Waiting for cfme provision request for vm %s', vm_name)
        row_description = 'Provision from [{}] to [{}]'.format(template, vm_name)
        cells = {'Description': row_description}
        row, __ = wait_for(requests.wait_for_request, [cells],
                           fail_func=requests.reload, num_sec=900, delay=20)
        assert row.last_message.text == 'Vm Provisioned Successfully'
        return VM.factory(vm_name, provider)
def test_broken_angular_select(request):
    """Test that checks the fancy selects do not break.

    Prerequisities:
        * A fresh downstream appliance

    Steps:
        1) Create a catalog.
        2) Create a catalog item, can be Generic and assign the catalog and OSE Installer dialog
            for testing purposes
        3) Try ordering the service, but instead of confirming the form, try changing some select.
    """
    # OSE Installer dialog, one dropdown from it
    the_select = AngularSelect("ose_size")
    cat = Catalog("Test_catalog_{}".format(fauxfactory.gen_alpha()))
    cat.create()
    request.addfinalizer(cat.delete)
    item = CatalogItem(
        item_type="Generic",
        name="Catitem_{}".format(fauxfactory.gen_alpha()),
        description=fauxfactory.gen_alpha(),
        display_in=True,
        catalog=cat.name,
        dialog="OSE Installer")
    item.create()
    request.addfinalizer(item.delete)

    # The check itself
    pytest.sel.force_navigate(
        "order_service_catalog",
        context={"catalog": cat.name, "catalog_item": item})
    fill(the_select, "Medium")
    assert not the_select.is_broken, "The select displayed itself next ot the angular select"
 def create(self):
     navigate_to(self, 'Add')
     fill(self.group_form, {'description_txt': self.description,
                            'role_select': self.role,
                            'group_tenant': self.tenant},
          action=form_buttons.add)
     flash.assert_success_message('Group "{}" was saved'.format(self.description))
示例#5
0
 def create(self):
     domain = "ManageIQ (Locked)"
     sel.force_navigate('catalog_item_new', context={'provider_type': self.item_type})
     sel.wait_for_element(basic_info_form.name_text)
     fill(basic_info_form, {'name_text': self.name,
                            'description_text': self.description,
                            'display_checkbox': self.display_in,
                            'select_catalog': self.catalog,
                            'select_dialog': self.dialog})
     if self.item_type != "Orchestration":
         sel.click(basic_info_form.field_entry_point)
         dynamic_tree.click_path("Datastore", domain, "Service", "Provisioning",
                                 "StateMachines", "ServiceProvision_Template", "default")
         sel.click(basic_info_form.apply_btn)
     tabstrip.select_tab("Request Info")
     # Address BZ1321631
     tabstrip.select_tab("Environment")
     tabstrip.select_tab("Catalog")
     template = template_select_form.template_table.find_row_by_cells({
         'Name': self.catalog_name,
         'Provider': self.provider
     })
     sel.click(template)
     web_ui.fill(request_form, {
         'instance_name': self.vm_name,
         'instance_type': self.instance_type,
         'guest_keypair': self.guest_keypair,
         'availability_zone': self.availability_zone,
         'cloud_tenant': self.cloud_tenant,
         'cloud_network': self.cloud_network,
         'security_groups': self.security_groups[0],  # not supporting multiselect now,
                                                      # just take first value
     })
     sel.click(template_select_form.add_button)
     flash.assert_success_message('Service Catalog Item "{}" was added'.format(self.name))
示例#6
0
def _filter(
        zone=None,
        user=None,
        time_period=None,
        task_status_queued=None,
        task_status_running=None,
        task_status_ok=None,
        task_status_error=None,
        task_status_warn=None,
        task_state=None):
    """ Does filtering of the results in table. Needs to be on the correct page before called.

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

    Args:
        zone: Value for 'Zone' select
        user: Value for 'User' select
        time_period: Value for 'Time period' select.
        task_status_*: :py:class:`bool` values for checkboxes
        task_state: Value for 'Task State' select.
    """
    fill(filter_form, locals())
    try:
        wait_for(lambda: sel.is_displayed(buttons.apply), num_sec=5)
        sel.click(buttons.apply)
    except TimedOutError:
        pass
示例#7
0
 def create(self):
     sel.force_navigate('catalog_item_new',
                        context={'provider_type': self.item_type})
     sel.wait_for_element(basic_info_form.name_text)
     fill(basic_info_form, {'name_text': self.name,
                            'description_text': self.description,
                            'display_checkbox': self.display_in,
                            'select_catalog': self.catalog,
                            'select_dialog': self.dialog,
                            'select_orch_template': self.orch_template,
                            'select_provider': self.provider_type})
     if current_version() >= "5.4":
         sel.click(basic_info_form.field_entry_point)
         dynamic_tree.click_path("Datastore", self.domain, "Service", "Provisioning",
                                 "StateMachines", "ServiceProvision_Template", "default")
         sel.click(basic_info_form.apply_btn)
     if(self.catalog_name is not None):
         tabstrip.select_tab("Request Info")
         template = template_select_form.template_table.find_row_by_cells({
             'Name': self.catalog_name,
             'Provider': self.provider
         })
         sel.click(template)
         request_form.fill(self.provisioning_data)
     sel.click(template_select_form.add_button)
示例#8
0
 def edit_tags(self, tag, value):
     navigate_to(self, 'Details')
     policy_btn('Edit Tags', invokes_alert=True)
     fill(edit_tags_form, {'select_tag': tag,
                           'select_value': value},
          action=form_buttons.save)
     flash.assert_success_message('Tag edits were successfully saved')
def select_two_quads():
    count = 0
    for quad in Quadicon.all("infra_prov", this_page=True):
        count += 1
        if count > 2:
            break
        fill(quad.checkbox(), True)
示例#10
0
    def add_jdbc_driver(self, filename, driver_name, module_name, driver_class,
                        major_version=None, minor_version=None, cancel=False):
        """Clicks to "Add JDBC Driver" button, in opened window fills fields by provided parameters,
        and deploys.

        Args:
            filename: Full path to JDBC Driver to import.
            driver_name: Name of newly created JDBC Driver.
            module_name: Name on Module to register on server side.
            driver_class: JDBC Driver Class.
            major_version: Major version of JDBC driver, optional.
            minor_version: Minor version of JDBC driver, optional.
            cancel: Whether to click Cancel instead of commit.
        """
        self.load_details(refresh=True)
        jdbc_btn("Add JDBC Driver")
        fill(jdbc_driver_form,
            {
                "file_select": filename,
                "jdbc_driver_name": driver_name,
                "jdbc_module_name": module_name,
                "jdbc_driver_class": driver_class,
                "major_version": major_version,
                "minor_version": minor_version
            })
        sel.click(jdbc_driver_form.cancel_button if cancel else jdbc_driver_form.deploy_button)
        flash.assert_success_message('JDBC Driver "{}" has been installed on this server.'
                    .format(driver_name))
示例#11
0
 def update(self, updates):
     navigate_to(self, 'Edit')
     fill(basic_info_form, {'name_text': updates.get('name', None),
                            'description_text':
                            updates.get('description', None)},
          action=basic_info_form.edit_button)
     flash.assert_success_message('Service Catalog Item "{}" was saved'.format(self.name))
示例#12
0
def discover(rhevm=False, vmware=False, cancel=False, start_ip=None, end_ip=None):
    """
    Discover infrastructure providers. Note: only starts discovery, doesn't
    wait for it to finish.

    Args:
        rhvem: Whether to scan for RHEVM providers
        vmware: Whether to scan for VMware providers
        cancel:  Whether to cancel out of the discover UI.
    """
    sel.force_navigate('infrastructure_provider_discover')
    if cancel:  # normalize so that the form filler only clicks either start or cancel
        cancel = True
    else:
        cancel = None
    form_data = {'start_button': not cancel,
                 'cancel_button': cancel}
    if rhevm:
        form_data.update({'rhevm_chk': True})
    if vmware:
        form_data.update({'vmware_chk': True})

    if start_ip:
        for idx, octet in enumerate(start_ip.split('.')):
            key = 'from_%i' % idx
            form_data.update({key: octet})
    if end_ip:
        end_octet = end_ip.split('.')[-1]
        form_data.update({'to_3': end_octet})

    fill(discover_form, form_data)
示例#13
0
def fill_count(count=None, key=None, value=None):
    """ Fills the 'Count of' type of form.

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

    Args:
        count: Name of the field to compare (Host.VMs, ...).
        key: Operation to do (=, <, >=, ...).
        value: Value to check against.
    Returns: See :py:func:`cfme.web_ui.fill`.
    """
    fill(
        count_form,
        dict(
            type="Count of",
            count=count,
            key=key,
            value=value,
        ),
    )
    # In case of advanced search box
    if sel.is_displayed(field_form.user_input):
        user_input = value is None
    else:
        user_input = None
    fill(field_form.user_input, user_input)
    sel.click(buttons.commit)
示例#14
0
    def edit_schema(self, add_fields=None, remove_fields=None):
        sel.force_navigate("automate_explorer_schema_edit", context={'tree_item': self})
        for remove_field in remove_fields or []:
            f = remove_field.get_form()
            fill(f, {}, action=f.remove_entry_button, action_always=True)

        for add_field in add_fields or []:
            sel.click(self.schema_edit_page.add_field_btn)
            f = add_field.get_form(blank=True)
            fill(f, {'name_text': add_field.name,
                     'type_select': add_field.type_,
                     'data_type_select': add_field.data_type,
                     'default_value_text': add_field.default_value,
                     'description_text': add_field.description,
                     'sub_cb': add_field.sub,
                     'collect_text': add_field.collect,
                     'message_text': add_field.message,
                     'on_entry_text': add_field.on_entry,
                     'on_exit_text': add_field.on_exit,
                     'max_retries_text': add_field.max_retries,
                     'max_time_text': add_field.max_time},
                 action=f.add_entry_button)

        sel.click(form_buttons.save)
        flash.assert_success_message('Schema for Automate Class "{}" was saved'.format(self.name))
示例#15
0
 def create(self):
     sel.force_navigate('catalog_item_new', context={'provider_type': self.item_type})
     sel.wait_for_element(basic_info_form.name_text)
     fill(basic_info_form, {'name_text': self.name,
                            'description_text': self.description,
                            'display_checkbox': self.display_in,
                            'select_catalog': self.catalog,
                            'select_dialog': self.dialog})
     tabstrip.select_tab("Request Info")
     template = template_select_form.template_table.find_row_by_cells({
         'Name': self.catalog_name,
         'Provider': self.provider
     })
     sel.click(template)
     web_ui.fill(request_form, {
         'instance_name': self.vm_name,
         'instance_type': self.instance_type,
         'guest_keypair': self.guest_keypair,
         'availability_zone': self.availability_zone,
         'cloud_tenant': self.cloud_tenant,
         'cloud_network': self.cloud_network,
         'security_groups': self.security_groups[0],  # not supporting multiselect now,
                                                      # just take first value
     })
     sel.click(template_select_form.add_button)
     flash.assert_success_message('Service Catalog Item "%s" was added' % self.name)
示例#16
0
 def _set(self, op_interval=None, op_date=None, op_week=None, op_minute=None,
          force_by_text=False):
     self._object.load_chart_reference()
     if op_interval and op_interval != self.get_interval(force_visible_text=force_by_text):
         if force_by_text:
             self._interval.select_by_visible_text(op_interval)
         else:
             self._interval.select_by_value(op_interval)
         sel.wait_for_ajax()
     if op_date and op_date != self.get_date():
         web_ui.fill(self._date, op_date)
         sel.wait_for_ajax()
     if op_week and op_week != self.get_week(force_visible_text=force_by_text):
         if force_by_text:
             self._week.select_by_visible_text(op_week)
         else:
             self._week.select_by_value(op_week)
         sel.wait_for_ajax()
     if op_minute and op_minute != self.get_minute(force_visible_text=force_by_text):
         if force_by_text:
             self._minute.select_by_visible_text(op_minute)
         else:
             self._minute.select_by_value(op_minute)
         sel.wait_for_ajax()
     self._object.load_chart_reference(force_reload=True)
示例#17
0
 def update(self, updates):
     sel.force_navigate('catalog_item_edit',
         context={'catalog': self.catalog, 'catalog_item': self})
     fill(basic_info_form, {'name_text': updates.get('name', None),
                            'description_text': updates.get('description', None)},
         action=basic_info_form.edit_button)
     flash.assert_success_message('Service Catalog Item "%s" was saved' % self.name)
示例#18
0
文件: vm.py 项目: akrzos/cfme_tests
    def set_retirement_date(self, when, warn=None):
        """Sets the retirement date for this Vm object.

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

        Args:
            when: When to retire. :py:class:`str` in format mm/dd/yy of
                :py:class:`datetime.datetime` or :py:class:`utils.timeutil.parsetime`.
            warn: When to warn, fills the select in the form in case the ``when`` is specified.
        """
        self.load_details()
        lcl_btn("Set Retirement Date")
        if callable(self.retire_form.date_retire):
            # It is the old functiton
            sel.wait_for_element("#miq_date_1")
        else:
            sel.wait_for_element(self.retire_form.date_retire)
        if when is None:
            try:
                wait_for(lambda: sel.is_displayed(retire_remove_button), num_sec=5, delay=0.2)
                sel.click(retire_remove_button)
                wait_for(lambda: not sel.is_displayed(retire_remove_button), num_sec=10, delay=0.2)
                sel.click(form_buttons.save)
            except TimedOutError:
                pass
        else:
            if sel.is_displayed(retire_remove_button):
                sel.click(retire_remove_button)
                wait_for(lambda: not sel.is_displayed(retire_remove_button), num_sec=15, delay=0.2)
            fill(self.retire_form.date_retire, when)
            wait_for(lambda: sel.is_displayed(retire_remove_button), num_sec=15, delay=0.2)
            if warn is not None:
                fill(self.retire_form.warn, warn)
            sel.click(form_buttons.save)
示例#19
0
 def delete_all_attached_vms(self):
     self.load_details()
     sel.click(details_page.infoblock.element("Relationships", "Managed VMs"))
     for q in Quadicon.all('vm'):
         fill(q.checkbox(), True)
     cfg_btn("Remove selected items from the VMDB", invokes_alert=True)
     sel.handle_alert(cancel=False)
示例#20
0
 def set_ownership(self, owner, group):
     sel.force_navigate('service_set_ownership',
                        context={'service_name': self.service_name})
     fill(set_ownership_form, {'select_owner': owner,
                               'select_group': group},
          action=form_buttons.save)
     flash.assert_success_message('Ownership saved for selected Service')
示例#21
0
 def edit_tags(self, tag, value):
     sel.force_navigate('service_edit_tags',
                        context={'service_name': self.service_name})
     fill(edit_tags_form, {'select_tag': tag,
                           'select_value': value},
          action=form_buttons.save)
     flash.assert_success_message('Tag edits were successfully saved')
示例#22
0
def discover(credential, cancel=False, d_type="Amazon"):
    """
    Discover cloud providers. Note: only starts discovery, doesn't
    wait for it to finish.

    Args:
      credential (cfme.Credential):  Amazon discovery credentials.
      cancel (boolean):  Whether to cancel out of the discover UI.
    """
    sel.force_navigate("clouds_provider_discover")
    form_data = {"discover_select": d_type}
    if credential:
        form_data.update(
            {
                "username": credential.principal,
                "password": credential.secret,
                "password_verify": credential.verify_secret,
            }
        )
    fill(
        discover_form,
        form_data,
        action=form_buttons.cancel if cancel else discover_form.start_button,
        action_always=True,
    )
示例#23
0
def discover(rhevm=False, vmware=False, scvmm=False, cancel=False, start_ip=None, end_ip=None):
    """
    Discover infrastructure providers. Note: only starts discovery, doesn't
    wait for it to finish.

    Args:
        rhvem: Whether to scan for RHEVM providers
        vmware: Whether to scan for VMware providers
        scvmm: Whether to scan for SCVMM providers
        cancel:  Whether to cancel out of the discover UI.
    """
    sel.force_navigate('infrastructure_provider_discover')
    form_data = {}
    if rhevm:
        form_data.update({'rhevm_chk': True})
    if vmware:
        form_data.update({'vmware_chk': True})
    if scvmm:
        form_data.update({'scvmm_chk': True})

    if start_ip:
        for idx, octet in enumerate(start_ip.split('.')):
            key = 'from_%i' % idx
            form_data.update({key: octet})
    if end_ip:
        end_octet = end_ip.split('.')[-1]
        form_data.update({'to_3': end_octet})

    fill(discover_form, form_data,
         action=form_buttons.cancel if cancel else discover_form.start_button,
         action_always=True)
 def update(self, updates):
     navigate_to(self, 'Edit')
     # Workaround - form is appearing after short delay
     sel.wait_for_element(self.tenant_form.description)
     fill(self.tenant_form, updates, action=self.save_changes)
     flash.assert_success_message(
         'Project "{}" was saved'.format(updates.get('name', self.name)))
示例#25
0
文件: vm.py 项目: rananda/cfme_tests
 def set_ownership(self, user=None, group=None, click_cancel=False, click_reset=False):
     """Set ownership of the VM/Instance or Template/Image"""
     sel.click(self.find_quadicon(False, False, False, use_search=False))
     cfg_btn('Set Ownership')
     if click_reset:
         action = form_buttons.reset
         msg_assert = partial(
             flash.assert_message_match,
             'All changes have been reset'
         )
     elif click_cancel:
         action = form_buttons.cancel
         msg_assert = partial(
             flash.assert_success_message,
             'Set Ownership was cancelled by the user'
         )
     else:
         action = form_buttons.save
         msg_assert = partial(
             flash.assert_success_message,
             'Ownership saved for selected {}'.format(self.VM_TYPE)
         )
     fill(set_ownership_form, {'user_name': user, 'group_name': group},
          action=action)
     msg_assert()
 def create(self):
     navigate_to(self, 'Add')
     fill(self.form, {'name_txt': self.name,
                      'vm_restriction_select': self.vm_restriction,
                      'product_features_tree': self.product_features},
          action=form_buttons.add)
     flash.assert_success_message('Role "{}" was saved'.format(self.name))
 def update(self, updates):
     navigate_to(self, 'Edit')
     fill(self.form, {'name_txt': updates.get('name'),
                      'vm_restriction_select': updates.get('vm_restriction'),
                      'product_features_tree': updates.get('product_features')},
          action=form_buttons.save)
     flash.assert_success_message('Role "{}" was saved'.format(updates.get('name', self.name)))
示例#28
0
def _fill_credential(form, cred, validate=None):
    """How to fill in a credential (either candu or default).  Validates the
    credential if that option is passed in.
    """
    if cred.candu:
        fill(
            credential_form,
            {
                "candu_button": True,
                "candu_principal": cred.principal,
                "candu_secret": cred.secret,
                "candu_verify_secret": cred.verify_secret,
                "validate_btn": validate,
            },
        )
    else:
        fill(
            credential_form,
            {
                "default_principal": cred.principal,
                "default_secret": cred.secret,
                "default_verify_secret": cred.verify_secret,
                "validate_btn": validate,
            },
        )
    if validate:
        flash.assert_no_errors()
 def _retrieve_ext_auth_user_groups(self):
     navigate_to(self, 'Add')
     fill(self.group_form, {'lookup_ldap_groups_chk': True,
                            'user_to_look_up': self.user_to_lookup,
                            },)
     sel.wait_for_element(form_buttons.retrieve)
     sel.click(form_buttons.retrieve)
    def publish_to_template(self, template_name, email=None, first_name=None, last_name=None):
        self.load_details()
        lcl_btn("Publish this VM to a Template")
        first_name = first_name or fauxfactory.gen_alphanumeric()
        last_name = last_name or fauxfactory.gen_alphanumeric()
        email = email or "{}@{}.test".format(first_name, last_name)
        try:
            prov_data = cfme_data["management_systems"][self.provider.key]["provisioning"]
        except (KeyError, IndexError):
            raise ValueError("You have to specify the correct options in cfme_data.yaml")

        provisioning_data = {
            "first_name": first_name,
            "last_name": last_name,
            "email": email,
            "vm_name": template_name,
            "host_name": {"name": prov_data.get("host")},
            "datastore_name": {"name": prov_data.get("datastore")},
        }
        from cfme.provisioning import provisioning_form
        fill(provisioning_form, provisioning_data, action=provisioning_form.submit_button)
        cells = {'Description': 'Publish from [{}] to [{}]'.format(self.name, template_name)}
        row, __ = wait_for(
            requests.wait_for_request, [cells], fail_func=requests.reload, num_sec=900, delay=20)
        return Template(template_name, self.provider)
示例#31
0
 def update(self, updates):
     sel.force_navigate("report_custom_edit", context={"report": self})
     fill(report_form, updates, action=form_buttons.save)
     flash.assert_no_errors()
示例#32
0
 def update(self, updates):
     sel.force_navigate("reports_widgets_chart_edit",
                        context={"widget": self})
     fill(self.form, updates, action=form_buttons.save)
     flash.assert_no_errors()
示例#33
0
 def create(self, cancel=False):
     sel.force_navigate("reports_widgets_chart_add")
     fill(self.form,
          self.__dict__,
          action=form_buttons.cancel if cancel else form_buttons.add)
     flash.assert_no_errors()
def fill_field(field=None, key=None, value=None):
    """ Fills the 'Field' type of form.

    Args:
        tag: Name of the field to compare (Host.VMs, ...).
        key: Operation to do (=, <, >=, IS NULL, ...).
        value: Value to check against.
    Returns: See :py:func:`cfme.web_ui.fill`.
    """
    field_norm = field.strip().lower()
    if "date updated" in field_norm or "date created" in field_norm or "boot time" in field_norm:
        no_date = False
    else:
        no_date = True
    web_ui.fill(
        field_form,
        dict(
            type="Field",
            field=field,
            key=key,
            value=value if no_date else None,
        ),
    )
    # In case of advanced search box
    if sel.is_displayed(field_form.user_input):
        user_input = value is None
    else:
        user_input = None
    web_ui.fill(field_form.user_input, user_input)
    if not no_date:
        # Flip the right part of form
        if isinstance(value, basestring) and not re.match(
                r"^[0-9]{2}/[0-9]{2}/[0-9]{4}$", value):
            if not sel.is_displayed(field_date_form.dropdown_select):
                sel.click(date_switch_buttons.to_relative)
            web_ui.fill(field_date_form, {"dropdown_select": value},
                        action=buttons.commit)
        else:
            # Specific selection
            if not sel.is_displayed(field_date_form.input_select_date):
                sel.click(date_switch_buttons.to_specific)
            if (isinstance(value, tuple)
                    or isinstance(value, list)) and len(value) == 2:
                date, time = value
            elif isinstance(value,
                            basestring):  # is in correct format mm/dd/yyyy
                # Date only (for now)
                date = value[:]
                time = None
            else:
                raise TypeError(
                    "fill_field expects a 2-tuple (date, time) or string with date"
                )
            # TODO datetime.datetime support
            web_ui.fill(field_date_form.input_select_date, date)
            # Try waiting a little bit for time field
            # If we don't wait, committing the expression will glitch
            try:
                wait_for(lambda: sel.is_displayed(field_date_form.
                                                  input_select_time),
                         num_sec=6)
                # It appeared, so if the time is to be set, we will set it (passing None glitches)
                if time:
                    web_ui.fill(field_date_form.input_select_time, time)
            except TimedOutError:
                # Did not appear, ignore that
                pass
            finally:
                # And finally, commit the expression :)
                sel.click(buttons.commit)
    else:
        sel.click(buttons.commit)
示例#35
0
def test_provision_approval(setup_provider, provider, vm_name, smtp_test,
                            request, edit, provisioning):
    """ Tests provisioning approval. Tests couple of things.

    * Approve manually
    * Approve by editing the request to conform

    Prerequisities:
        * A provider that can provision.
        * Automate role enabled
        * User with e-mail set so you can receive and view them

    Steps:
        * Create a provisioning request that does not get automatically approved (eg. ``num_vms``
            bigger than 1)
        * Wait for an e-mail to come, informing you that the auto-approval was unsuccessful.
        * Depending on whether you want to do manual approval or edit approval, do:
            * MANUAL: manually approve the request in UI
            * EDIT: Edit the request in UI so it conforms the rules for auto-approval.
        * Wait for an e-mail with approval
        * Wait until the request finishes
        * Wait until an email, informing about finished provisioning, comes.

    Metadata:
        test_flag: provision
        suite: infra_provisioning
    """
    # generate_tests makes sure these have values
    template, host, datastore = map(provisioning.get,
                                    ('template', 'host', 'datastore'))

    # It will provision two of them
    vm_names = [vm_name + "001", vm_name + "002"]
    request.addfinalizer(
        lambda: [cleanup_vm(vmname, provider) for vmname in vm_names])

    provisioning_data = {
        'vm_name': vm_name,
        'host_name': {
            'name': [host]
        },
        'datastore_name': {
            'name': [datastore]
        },
        'num_vms': "2",
    }

    # Same thing, different names. :\
    if provider.type == 'rhevm':
        provisioning_data['provision_type'] = 'Native Clone'
    elif provider.type == 'virtualcenter':
        provisioning_data['provision_type'] = 'VMware'

    try:
        provisioning_data['vlan'] = provisioning['vlan']
    except KeyError:
        # provisioning['vlan'] is required for rhevm provisioning
        if provider.type == 'rhevm':
            raise pytest.fail(
                'rhevm requires a vlan value in provisioning info')

    do_vm_provisioning(template,
                       provider,
                       vm_name,
                       provisioning_data,
                       request,
                       smtp_test,
                       wait=False)
    wait_for(lambda: len(
        filter(
            lambda mail: "your request for a new vms was not autoapproved" in
            normalize_text(mail["subject"]), smtp_test.get_emails())) > 0,
             num_sec=90,
             delay=5)
    wait_for(lambda: len(
        filter(
            lambda mail: "virtual machine request was not approved" in
            normalize_text(mail["subject"]), smtp_test.get_emails())) > 0,
             num_sec=90,
             delay=5)

    cells = {
        'Description':
        'Provision from [{}] to [{}###]'.format(template, vm_name)
    }
    wait_for(lambda: requests.go_to_request(cells), num_sec=80, delay=5)
    if edit:
        # Automatic approval after editing the request to conform
        with requests.edit_request(cells) as form:
            fill(form.num_vms, "1")
            new_vm_name = vm_name + "-xx"
            fill(form.vm_name, new_vm_name)
        vm_names = [new_vm_name]  # Will be just one now
        cells = {
            'Description':
            'Provision from [{}] to [{}]'.format(template, new_vm_name)
        }
        request.addfinalizer(lambda: cleanup_vm(new_vm_name, provider))
    else:
        # Manual approval
        requests.approve_request(cells, "Approved")
        vm_names = [vm_name + "001", vm_name + "002"]  # There will be two VMs
        request.addfinalizer(
            lambda: [cleanup_vm(vmname, provider) for vmname in vm_names])
    wait_for(lambda: len(
        filter(
            lambda mail: "your virtual machine configuration was approved" in
            normalize_text(mail["subject"]), smtp_test.get_emails())) > 0,
             num_sec=120,
             delay=5)

    # Wait for the VM to appear on the provider backend before proceeding to ensure proper cleanup
    logger.info('Waiting for vms %s to appear on provider %s',
                ", ".join(vm_names), provider.key)
    wait_for(lambda: all(map(provider.mgmt.does_vm_exist, vm_names)),
             handle_exception=True,
             num_sec=600)

    row, __ = wait_for(requests.wait_for_request, [cells],
                       fail_func=requests.reload,
                       num_sec=1500,
                       delay=20)
    assert normalize_text(row.status.text) == 'ok' \
        and normalize_text(row.request_state.text) == 'finished'

    # Wait for e-mails to appear
    def verify():
        return (len(
            filter(
                lambda mail: "your virtual machine request has completed vm {}"
                .format(normalize_text(vm_name)) in normalize_text(mail[
                    "subject"]), smtp_test.get_emails())) == len(vm_names))

    wait_for(verify, message="email receive check", delay=5)
示例#36
0
def copy_request(cells, modifications):
    with requests.copy_request(cells):
        fill(provisioning_form, modifications)
示例#37
0
 def update(self, updates):
     navigate_to(self, 'Edit')
     fill(self.form, updates, action=form_buttons.save)
     flash.assert_no_errors()
示例#38
0
 def create(self, cancel=False):
     navigate_to(self, 'New')
     fill(report_form,
          self,
          action=form_buttons.cancel if cancel else form_buttons.add)
     flash.assert_no_errors()
示例#39
0
def fill_snmp_trap_field_trap(field, val):
    return fill(field, val.as_tuple)
def test_iso_provision_from_template(provider_key, provider_crud,
                                     provider_type, provider_mgmt,
                                     provisioning, vm_name, smtp_test,
                                     request):

    # generate_tests makes sure these have values
    iso_template, host, datastore, iso_file, iso_kickstart,\
        iso_root_password, iso_image_type, vlan = map(provisioning.get, ('pxe_template', 'host',
                                'datastore', 'iso_file', 'iso_kickstart',
                                'iso_root_password', 'iso_image_type', 'vlan'))
    pytest.sel.force_navigate('infrastructure_provision_vms',
                              context={
                                  'provider': provider_crud,
                                  'template_name': iso_template,
                              })

    note = ('template %s to vm %s on provider %s' %
            (iso_template, vm_name, provider_crud.key))
    provisioning_data = {
        'email': '*****@*****.**',
        'first_name': 'Template',
        'last_name': 'Provisioner',
        'notes': note,
        'vm_name': vm_name,
        'host_name': {
            'name': [host]
        },
        'datastore_name': {
            'name': [datastore]
        },
        'provision_type': 'ISO',
        'iso_file': {
            'name': [iso_file]
        },
        'custom_template': {
            'name': [iso_kickstart]
        },
        'root_password': iso_root_password,
        'vlan': vlan,
    }

    fill(provisioning_form,
         provisioning_data,
         action=provisioning_form.submit_button)
    flash.assert_no_errors()

    request.addfinalizer(
        lambda: cleanup_vm(vm_name, provider_key, provider_mgmt))

    # Wait for the VM to appear on the provider backend before proceeding to ensure proper cleanup
    logger.info('Waiting for vm %s to appear on provider %s', vm_name,
                provider_crud.key)
    wait_for(provider_mgmt.does_vm_exist, [vm_name],
             handle_exception=True,
             num_sec=600)

    # nav to requests page happens on successful provision
    logger.info('Waiting for cfme provision request for vm %s' % vm_name)
    row_description = 'Provision from [%s] to [%s]' % (iso_template, vm_name)
    cells = {'Description': row_description}
    row, __ = wait_for(requests.wait_for_request, [cells],
                       fail_func=requests.reload,
                       num_sec=1800,
                       delay=20)
    assert row.last_message.text == 'VM Provisioned Successfully'

    # Wait for e-mails to appear
    def verify():
        return (
            len(
                smtp_test.get_emails(
                    text_like="%%Your Virtual Machine Request was approved%%"))
            > 0 and len(
                smtp_test.get_emails(
                    subject_like=
                    "Your virtual machine request has Completed - VM:%%%s" %
                    vm_name)) > 0)

    wait_for(verify, message="email receive check", delay=5)
示例#41
0
 def type(self, value):
     return fill(self.type_loc, value)
示例#42
0
def fill_snmp_trap_field_dict(field, val):
    return fill(field, (val["oid"], val["type"], val.get("value", None)))
示例#43
0
def fill_snmp_form(form, values, action):
    """I wanted to use dict but that is overrided in web_ui that it disassembles dict to list
    of tuples :("""
    return fill(form.fields, values)
示例#44
0
 def value(self, value):
     return fill(self.value_loc, value)
示例#45
0
def fill_snmp_hosts_field_list(field, values):
    fields = field.host_fields
    if len(values) > len(fields):
        raise ValueError("You cannot specify more hosts than the form allows!")
    for i, value in enumerate(values):
        fill(fields[i], value)
示例#46
0
 def oid(self, value):
     return fill(self.oid_loc, value)
示例#47
0
def fill_snmp_traps_field_list(field, values):
    assert len(values) <= len(
        field.traps), "You cannot specify more traps than fields"
    for i, value in enumerate(values):
        fill(field.traps[i], value)
示例#48
0
def fill_snmp_hosts_field_basestr(field, value):
    fill(field, [value])
示例#49
0
    def add_datasource(self, ds_type, ds_name, jndi_name, ds_url,
               xa_ds=False, driver_name=None,
               existing_driver=None, driver_module_name=None, driver_class=None,
               username=None, password=None, sec_domain=None, cancel=False):
        """Clicks to "Add Datasource" button,
        in opened window fills fields by provided parameter by clicking 'Next',
        and submits the form by clicking 'Finish'.

        Args:
            ds_type: Type of database.
            ds_name: Name of newly created Datasource.
            jndi_name: JNDI Name of Datasource.
            driver_name: JDBC Driver name in Datasource.
            driver_module_name: Module name of JDBC Driver used in datasource.
            driver_class: JDBC Driver Class.
            ds_url: Database connection URL in jdbc format.
            username: Database username.
            password: Databasae password, optional.
            sec_domain: Security Domain, optional.
            cancel: Whether to click Cancel instead of commit.
        """
        self.load_details(refresh=True)
        datasources_btn("Add Datasource", invokes_alert=True)
        if self.appliance.version >= '5.8':
            fill(datasource_form,
                {
                    "xa_ds": xa_ds
                })
        fill(datasource_form,
            {
                "ds_type": ds_type,
            })
        sel.click(datasource_form.cancel_button if cancel else datasource_form.next0_button)
        fill(datasource_form,
            {
                "ds_name": ds_name,
                "jndi_name": jndi_name
            })
        sel.click(datasource_form.cancel_button if cancel else datasource_form.next1_button)
        if existing_driver and self.appliance.version >= '5.8':
            tabstrip.select_tab("Existing Driver")
            fill(datasource_form,
                {
                    "existing_driver": existing_driver
                })
        else:
            fill(datasource_form,
                {
                    "driver_name": driver_name,
                    "driver_module_name": driver_module_name,
                    "driver_class": driver_class
                })
        sel.click(datasource_form.cancel_button if cancel else datasource_form.next2_button)
        fill(datasource_form,
            {
                "ds_url": ds_url,
                "username": username,
                "password": password,
                "sec_domain": sec_domain
            })
        sel.click(datasource_form.cancel_button if cancel else datasource_form.finish_button)
        flash.assert_no_errors()
示例#50
0
def fill_snmp_traps_field_single_trap(field, value):
    fill(field.traps[0], value)
示例#51
0
def _fill_tabstrip(tabstrip_field, value):
    logger.debug(' Navigating to tabstrip %s', tabstrip_field.ident_string)
    web_ui.fill(tabstrip_field.locate(), value)
示例#52
0
    def create(self,
               email=None,
               first_name=None,
               last_name=None,
               availability_zone=None,
               security_groups=None,
               instance_type=None,
               guest_keypair=None,
               cancel=False,
               **prov_fill_kwargs):
        """Provisions an EC2 instance with the given properties through CFME

        Args:
            email: Email of the requester
            first_name: Name of the requester
            last_name: Surname of the requester
            availability_zone: Name of the zone the instance should belong to
            security_groups: List of security groups the instance should belong to
                             (currently, only the first one will be used)
            instance_type: Type of the instance
            guest_keypair: Name of the key pair used to access the instance
            cancel: Clicks the cancel button if `True`, otherwise clicks the submit button
                    (Defaults to `False`)
        Note:
            For more optional keyword arguments, see
            :py:data:`cfme.cloud.provisioning.provisioning_form`
        """
        from cfme.provisioning import provisioning_form
        sel.force_navigate('clouds_provision_instances',
                           context={
                               'provider': self.provider,
                               'template_name': self.template_name,
                           })

        fill(
            provisioning_form,
            dict(
                email=email,
                first_name=first_name,
                last_name=last_name,
                instance_name=self.name,
                availability_zone=availability_zone,
                # not supporting multiselect now, just take first value
                security_groups=security_groups[0],
                instance_type=instance_type,
                guest_keypair=guest_keypair,
                **prov_fill_kwargs))

        if cancel:
            sel.click(provisioning_form.cancel_button)
            flash.assert_success_message(
                "Add of new VM Provision Request was cancelled by the user")
        else:
            sel.click(provisioning_form.submit_button)
            flash.assert_success_message(
                "VM Provision Request was Submitted, you will be notified when your VMs are ready"
            )

        row_description = 'Provision from [{}] to [{}]'.format(
            self.template_name, self.name)
        cells = {'Description': row_description}
        row, __ = wait_for(requests.wait_for_request, [cells],
                           fail_func=requests.reload,
                           num_sec=900,
                           delay=20)
        assert row.last_message.text == 'Vm Provisioned Successfully'
示例#53
0
 def create(self):
     sel.force_navigate('cfg_accesscontrol_group_add')
     fill(self.group_form, {'description_txt': self.description,
                            'role_select': self.role},
          action=form_buttons.add)
     flash.assert_success_message('Group "%s" was saved' % self.description)
示例#54
0
def generated_request(appliance, infra_provider, provider_data, provisioning,
                      template_name, vm_name):
    """Creates a provision request, that is not automatically approved, and returns the search data.

    After finishing the test, request should be automatically deleted.

    Slightly modified code from :py:module:`cfme.tests.infrastructure.test_provisioning`
    """
    first_name = fauxfactory.gen_alphanumeric()
    last_name = fauxfactory.gen_alphanumeric()
    notes = fauxfactory.gen_alphanumeric()
    e_mail = "{}@{}.test".format(first_name, last_name)
    host, datastore = map(provisioning.get, ('host', 'datastore'))
    vm = Vm(name=vm_name, provider=infra_provider, template_name=template_name)
    navigate_to(vm, 'Provision')

    provisioning_data = {
        'email': e_mail,
        'first_name': first_name,
        'last_name': last_name,
        'notes': notes,
        'vm_name': vm_name,
        'host_name': {
            'name': [host]
        },
        'datastore_name': {
            'name': [datastore]
        },
        'num_vms': "10",  # so it won't get auto-approved
    }

    # Same thing, different names. :\
    if provider_data["type"] == 'rhevm':
        provisioning_data['provision_type'] = 'Native Clone'
    elif provider_data["type"] == 'virtualcenter':
        provisioning_data['provision_type'] = 'VMware'

    try:
        provisioning_data['vlan'] = provisioning['vlan']
    except KeyError:
        # provisioning['vlan'] is required for rhevm provisioning
        if provider_data["type"] == 'rhevm':
            raise pytest.fail(
                'rhevm requires a vlan value in provisioning info')

    fill(provisioning_form,
         provisioning_data,
         action=provisioning_form.submit_button)
    flash.assert_no_errors()
    request_cells = {
        "Description":
        "Provision from [{}] to [{}###]".format(template_name, vm_name),
    }
    provision_request = RequestCollection(appliance).instantiate(
        cells=request_cells)
    yield provision_request

    browser().get(store.base_url)
    appliance.server.login_admin()

    provision_request.remove_request()
    flash.assert_no_errors()
示例#55
0
def _fill_ifr_map(ifr, d):
    logger.info("   Filling row with data {}".format(str(d)))
    return fill(ifr.form,
                dict(zip(ifr.columns, (d.get(x, None) for x in ifr.columns))))
def test_host_provisioning(setup_provider, cfme_data, host_provisioning, provider, smtp_test,
                           request):
    """Tests host provisioning

    Metadata:
        test_flag: host_provision
    """

    # Add host before provisioning
    test_host = host.get_from_config('esx')
    test_host.create()

    # Populate provisioning_data before submitting host provisioning form
    pxe_server, pxe_image, pxe_image_type, pxe_kickstart, datacenter, cluster, datastores,\
        prov_host_name, root_password, ip_addr, subnet_mask, gateway, dns = map(
            host_provisioning.get,
            ('pxe_server', 'pxe_image', 'pxe_image_type', 'pxe_kickstart', 'datacenter', 'cluster',
             'datastores', 'hostname', 'root_password', 'ip_addr', 'subnet_mask', 'gateway', 'dns'))

    def cleanup_host():
        try:
            logger.info('Cleaning up host %s on provider %s', prov_host_name, provider.key)
            mgmt_system = provider.mgmt
            host_list = mgmt_system.list_host()
            if host_provisioning['ip_addr'] in host_list:
                wait_for(mgmt_system.is_host_connected, [host_provisioning['ip_addr']])
                mgmt_system.remove_host_from_cluster(host_provisioning['ip_addr'])

            ipmi = test_host.get_ipmi()
            ipmi.power_off()

            # During host provisioning,the host name gets changed from what's specified at creation
            # time.If host provisioning succeeds,the original name is reverted to,otherwise the
            # changed names are retained upon failure
            renamed_host_name1 = "{} ({})".format('IPMI', host_provisioning['ipmi_address'])
            renamed_host_name2 = "{} ({})".format('VMware ESXi', host_provisioning['ip_addr'])

            host_list_ui = host.get_all_hosts()
            if host_provisioning['hostname'] in host_list_ui:
                test_host.delete(cancel=False)
                host.wait_for_host_delete(test_host)
            elif renamed_host_name1 in host_list_ui:
                host_renamed_obj1 = host.Host(name=renamed_host_name1, provider=provider)
                host_renamed_obj1.delete(cancel=False)
                host.wait_for_host_delete(host_renamed_obj1)
            elif renamed_host_name2 in host_list_ui:
                host_renamed_obj2 = host.Host(name=renamed_host_name2, provider=provider)
                host_renamed_obj2.delete(cancel=False)
                host.wait_for_host_delete(host_renamed_obj2)
        except:
            # The mgmt_sys classes raise Exception :\
            logger.warning('Failed to clean up host %s on provider %s',
                prov_host_name, provider.key)

    request.addfinalizer(cleanup_host)

    navigate_to(test_host, 'Provision')

    note = ('Provisioning host {} on provider {}'.format(prov_host_name, provider.key))
    provisioning_data = {
        'email': '*****@*****.**',
        'first_name': 'Template',
        'last_name': 'Provisioner',
        'notes': note,
        'pxe_server': pxe_server,
        'pxe_image': {'name': [pxe_image]},
        'provider_name': provider.name,
        'cluster': "{} / {}".format(datacenter, cluster),
        'datastore_name': {'name': datastores},
        'root_password': root_password,
        'prov_host_name': prov_host_name,
        'ip_address': ip_addr,
        'subnet_mask': subnet_mask,
        'gateway': gateway,
        'dns_servers': dns,
        'custom_template': {'name': [pxe_kickstart]},
    }

    fill(provisioning_form, provisioning_data, action=provisioning_form.host_submit_button)
    flash.assert_success_message(
        "Host Request was Submitted, you will be notified when your Hosts are ready")

    row_description = 'PXE install on [{}] from image [{}]'.format(prov_host_name, pxe_image)
    cells = {'Description': row_description}

    row, __ = wait_for(requests.wait_for_request, [cells],
                       fail_func=requests.reload, num_sec=1500, delay=20)
    assert row.last_message.text == 'Host Provisioned Successfully'
    assert row.status.text != 'Error'

    # Navigate to host details page and verify Provider and cluster names
    assert test_host.get_detail('Relationships', 'Infrastructure Provider') ==\
        provider.name, 'Provider name does not match'

    assert test_host.get_detail('Relationships', 'Cluster') ==\
        host_provisioning['cluster'], 'Cluster does not match'

    # Navigate to host datastore page and verify that the requested datastore has been assigned
    # to the host
    requested_ds = host_provisioning['datastores']
    datastores = test_host.get_datastores()
    assert set(requested_ds).issubset(datastores), 'Datastores are missing some members'

    # Wait for e-mails to appear
    def verify():
        return len(
            smtp_test.get_emails(
                subject_like="Your host provisioning request has Completed - Host:%%".format(
                    prov_host_name))
        ) > 0

    wait_for(verify, message="email receive check", delay=5)
示例#57
0
 def update(self, updates):
     sel.force_navigate("automate_explorer_domain_edit",
                        context={"tree_item": self})
     fill(self.form, updates, action=form_buttons.save)
     flash.assert_no_errors()
示例#58
0
def _fill_ifr_str(ifr, s):
    """You don't have to specify full dict when filling just value ..."""
    logger.info("   Filling row with value {}".format(s))
    return fill(ifr, {"value": s})
示例#59
0
 def update(self, updates, expect_success=True):
     sel.force_navigate("my_settings_default_filters", context=self)
     fill(self.filter_form, {'filter_tree': updates.get('filters')},
          action=form_buttons.save)
     if expect_success:
         flash.assert_success_message('Default Filters saved successfully')
示例#60
0
def _fill_ifields_obj(ifields, d):
    logger.info("   Delegating the filling of the fields to the form.")
    return fill(ifields.form, d)