def _post_approval(smtp_test, provision_request, vm_type, requester, provider,
                   approved_vm_names):
    # requester includes the trailing space
    approved_subject = normalize_text(f"your {vm_type} request was approved")
    approved_from = normalize_text(
        f"{vm_type} request from {requester}was approved")

    wait_for_messages_with_subjects(smtp_test,
                                    {approved_subject, approved_from},
                                    num_sec=90)

    smtp_test.clear_database()

    # 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(approved_vm_names), provider.key)
    wait_for(lambda: all(map(provider.mgmt.does_vm_exist, approved_vm_names)),
             handle_exception=True,
             num_sec=600)

    provision_request.wait_for_request(method='ui')
    msg = f"Provisioning failed with the message {provision_request.row.last_message.text}."
    assert provision_request.is_succeeded(method='ui'), msg

    # account for multiple vms, specific names
    completed_subjects = {
        normalize_text(f"your {vm_type} request has completed vm name {name}")
        for name in approved_vm_names
    }
    wait_for_messages_with_subjects(smtp_test, completed_subjects, num_sec=90)
 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)
     )
Esempio n. 3
0
 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)
     )
 def _action_deny():
     provision_request = appliance.collections.requests.instantiate(
         cells=cells)
     provision_request.deny_request(method='ui', reason="You stink!")
     denied_subject = normalize_text(f"your {vm_type} request was denied")
     denied_from = normalize_text(
         f"{vm_type} request from {requester}was denied")
     wait_for_messages_with_subjects(smtp_test,
                                     [denied_subject, denied_from],
                                     num_sec=90)
Esempio n. 5
0
 def verify():
     subject = VersionPicker({
         LOWEST: "your virtual machine request has completed vm {}".format(
             normalize_text(vm_name)),
         "5.10": "your virtual machine request has completed vm name {}".format(
             normalize_text(vm_name))
     }).pick()
     return (
         len(filter(
             lambda mail: subject in normalize_text(mail["subject"]),
             smtp_test.get_emails())) == len(vm_names)
     )
Esempio n. 6
0
 def verify():
     subject = VersionPicker({
         LOWEST: "your virtual machine request has completed vm {}".format(
             normalize_text(vm_name)),
         "5.10": "your virtual machine request has completed vm name {}".format(
             normalize_text(vm_name))
     }).pick()
     return (
         len(filter(
             lambda mail: subject in normalize_text(mail["subject"]),
             smtp_test.get_emails())) == len(vm_names)
     )
Esempio n. 7
0
    def filedump(
        self,
        description,
        contents,
        slaveid=None,
        mode="w",
        contents_base64=False,
        display_type="primary",
        display_glyph=None,
        file_type=None,
        dont_write=False,
        os_filename=None,
        group_id=None,
        test_name=None,
        test_location=None,
    ):
        if not slaveid:
            slaveid = "Master"
        test_ident = "{}/{}".format(
            self.store[slaveid]["test_location"], self.store[slaveid]["test_name"]
        )
        artifacts = []
        if os_filename is None:
            safe_name = re.sub(r"\s+", "_", normalize_text(safe_string(description)))
            os_filename = self.ident + "-" + safe_name
            os_filename = os.path.join(self.store[slaveid]["artifact_path"], os_filename)
            if file_type is not None and "screenshot" in file_type:
                os_filename = os_filename + ".png"
            elif file_type is not None and (
                "_tb" in file_type or "traceback" in file_type or file_type == "log"
            ):
                os_filename = os_filename + ".log"
            elif file_type is not None and file_type == "html":
                os_filename = os_filename + ".html"
            elif file_type is not None and file_type == "video":
                os_filename = os_filename + ".ogv"
            else:
                os_filename = os_filename + ".txt"
        artifacts.append(
            {
                "file_type": file_type,
                "display_type": display_type,
                "display_glyph": display_glyph,
                "description": description,
                "os_filename": os_filename,
                "group_id": group_id,
            }
        )
        if not dont_write:
            if os.path.isfile(os_filename):
                os.remove(os_filename)
            with open(os_filename, mode) as f:
                if contents_base64:
                    contents = base64.b64decode(contents)
                f.write(contents)

        return None, {"artifacts": {test_ident: {"files": artifacts}}}
Esempio n. 8
0
    def filedump(
        self,
        description,
        contents,
        slaveid=None,
        mode="w",
        contents_base64=False,
        display_type="primary",
        display_glyph=None,
        file_type=None,
        dont_write=False,
        os_filename=None,
        group_id=None,
        test_name=None,
        test_location=None,
    ):
        if not slaveid:
            slaveid = "Master"
        test_ident = "{}/{}".format(self.store[slaveid]["test_location"],
                                    self.store[slaveid]["test_name"])
        artifacts = []
        if os_filename is None:
            safe_name = re.sub(r"\s+", "_",
                               normalize_text(safe_string(description)))
            os_filename = self.ident + "-" + safe_name
            os_filename = os.path.join(self.store[slaveid]["artifact_path"],
                                       os_filename)
            if file_type is not None and "screenshot" in file_type:
                os_filename = os_filename + ".png"
            elif file_type is not None and ("_tb" in file_type
                                            or "traceback" in file_type
                                            or file_type == "log"):
                os_filename = os_filename + ".log"
            elif file_type is not None and file_type == "html":
                os_filename = os_filename + ".html"
            elif file_type is not None and file_type == "video":
                os_filename = os_filename + ".ogv"
            else:
                os_filename = os_filename + ".txt"
        artifacts.append({
            "file_type": file_type,
            "display_type": display_type,
            "display_glyph": display_glyph,
            "description": description,
            "os_filename": os_filename,
            "group_id": group_id,
        })
        if not dont_write:
            if os.path.isfile(os_filename):
                os.remove(os_filename)
            with open(os_filename, mode) as f:
                if contents_base64:
                    contents = base64.b64decode(contents)
                f.write(contents)

        return None, {"artifacts": {test_ident: {"files": artifacts}}}
    def _check_subjects():
        subjects = {
            normalize_text(m["subject"])
            for m in smtp_test.get_emails()
        }
        found_subjects_substrings = set()
        # Looking for each expected subject in the list of received subjects with partial match
        for expected_substring in expected_subjects_substrings:
            for subject in subjects:
                if expected_substring in subject:
                    found_subjects_substrings.add(expected_substring)
                    break
            else:
                logger.info('No emails with subjects containing "%s" found.',
                            expected_substring)

        if expected_subjects_substrings - found_subjects_substrings:
            return False

        logger.info('Found all expected emails.')
        return True
Esempio n. 10
0
def test_provision_approval(appliance, 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: [
        appliance.collections.infra_vms.instantiate(name, provider).
        delete_from_provider() for name in vm_names
    ])

    provisioning_data = {
        'catalog': {
            'vm_name': vm_name,
            'num_vms': '2'
        },
        'environment': {
            'host_name': {
                'name': host
            },
            'datastore_name': {
                'name': datastore
            }
        },
        'network': {
            'vlan': partial_match(provisioning['vlan'])
        }
    }

    do_vm_provisioning(appliance,
                       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())) == 1,
             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())) == 1,
             num_sec=90,
             delay=5)
    smtp_test.clear_database()

    cells = {
        'Description':
        'Provision from [{}] to [{}###]'.format(template, vm_name)
    }
    provision_request = appliance.collections.requests.instantiate(cells=cells)
    navigate_to(provision_request, 'Details')
    if edit:
        # Automatic approval after editing the request to conform
        new_vm_name = vm_name + "-xx"
        modifications = {
            'catalog': {
                'num_vms': "1",
                'vm_name': new_vm_name
            },
            'Description':
            'Provision from [{}] to [{}]'.format(template, new_vm_name)
        }
        provision_request.edit_request(values=modifications)
        vm_names = [new_vm_name]  # Will be just one now
        request.addfinalizer(
            lambda: appliance.collections.infra_vms.instantiate(
                new_vm_name, provider).delete_from_provider())
    else:
        # Manual approval
        provision_request.approve_request(method='ui', reason="Approved")
        vm_names = [vm_name + "001", vm_name + "002"]  # There will be two VMs
        request.addfinalizer(lambda: [
            appliance.collections.infra_vms.instantiate(name, provider).
            delete_from_provider() for name 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())) == 1,
             num_sec=120,
             delay=5)
    smtp_test.clear_database()

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

    provision_request.wait_for_request(method='ui')
    msg = "Provisioning failed with the message {}".format(
        provision_request.row.last_message.text)
    assert provision_request.is_succeeded(method='ui'), msg

    # 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)
def test_provision_approval(appliance, 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: [VM.factory(name, provider).cleanup_on_provider() for name in vm_names])

    provisioning_data = {
        'catalog': {
            'vm_name': vm_name,
            'num_vms': '2'
        },
        'environment': {
            'host_name': {'name': host},
            'datastore_name': {'name': datastore}
        },
        'network': {
            'vlan': partial_match(provisioning['vlan'])
        }
    }

    do_vm_provisioning(appliance, 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())) == 1,
        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())) == 1,
        num_sec=90, delay=5)
    smtp_test.clear_database()

    cells = {'Description': 'Provision from [{}] to [{}###]'.format(template, vm_name)}
    provision_request = appliance.collections.requests.instantiate(cells=cells)
    navigate_to(provision_request, 'Details')
    if edit:
        # Automatic approval after editing the request to conform
        new_vm_name = vm_name + "-xx"
        modifications = {
            'catalog': {'num_vms': "1", 'vm_name': new_vm_name},
            'Description': 'Provision from [{}] to [{}]'.format(template, new_vm_name)}
        provision_request.edit_request(values=modifications)
        vm_names = [new_vm_name]  # Will be just one now
        request.addfinalizer(
            lambda: VM.factory(new_vm_name, provider).cleanup_on_provider()
        )
    else:
        # Manual approval
        provision_request.approve_request(method='ui', reason="Approved")
        vm_names = [vm_name + "001", vm_name + "002"]  # There will be two VMs
        request.addfinalizer(
            lambda: [VM.factory(name, provider).cleanup_on_provider() for name 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())) == 1,
        num_sec=120, delay=5)
    smtp_test.clear_database()

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

    provision_request.wait_for_request(method='ui')
    msg = "Provisioning failed with the message {}".format(provision_request.row.last_message.text)
    assert provision_request.is_succeeded(method='ui'), msg

    # 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)
def test_provision_approval(appliance, provider, vm_name, smtp_test, request,
                            edit, soft_assert):
    """ 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 approval is pending
        * 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 with provisioning complete

    Metadata:
        test_flag: provision
        suite: infra_provisioning

    Polarion:
        assignee: jhenner
        caseimportance: high
        casecomponent: Provisioning
        initialEstimate: 1/8h
    """
    # generate_tests makes sure these have values
    # template, host, datastore = map(provisioning.get, ('template', 'host', 'datastore'))

    # It will provision two of them
    # All the subject checks are normalized, because of newlines and capitalization

    vm_names = [vm_name + "001", vm_name + "002"]
    if provider.one_of(CloudProvider):
        requester = ""
        vm_type = "instance"
    else:
        requester = "[email protected] "  # include trailing space for clean formatting
        vm_type = "virtual machine"
    collection = appliance.provider_based_collection(provider)
    inst_args = {'catalog': {'vm_name': vm_name, 'num_vms': '2'}}

    vm = collection.create(vm_name,
                           provider,
                           form_values=inst_args,
                           wait=False)
    try:
        wait_for(lambda: len(smtp_test.get_emails()) >= 2, num_sec=90, delay=3)
    except TimedOutError:
        pytest.fail(
            'Did not receive at least 2 emails from provisioning request, received: {}'
            .format(smtp_test.get_emails()))

    pending_subject = normalize_text(
        "your {} request is pending".format(vm_type))
    # requester includes the trailing space
    pending_from = normalize_text("{} request from {}pending approval".format(
        vm_type, requester))

    received_pending = [
        normalize_text(m["subject"]) for m in smtp_test.get_emails()
    ]
    # Looking for each expected subject in the list of received subjects with partial match
    for subject in [pending_subject, pending_from]:
        soft_assert(
            any(subject in r_sub for r_sub in received_pending),
            'Expected subject [{}], not matched in received subjects [{}]'.
            format(subject, received_pending))

    smtp_test.clear_database()

    cells = {
        'Description':
        'Provision from [{}] to [{}###]'.format(vm.template_name, vm.name)
    }
    provision_request = appliance.collections.requests.instantiate(cells=cells)
    if edit:
        # Automatic approval after editing the request to conform
        new_vm_name = '{}-xx'.format(vm_name)
        modifications = {
            'catalog': {
                'num_vms': "1",
                'vm_name': new_vm_name
            },
            'Description':
            'Provision from [{}] to [{}]'.format(vm.template_name, new_vm_name)
        }
        provision_request.edit_request(values=modifications)
        vm_names = [new_vm_name]  # Will be just one now
        request.addfinalizer(lambda: collection.instantiate(
            new_vm_name, provider).cleanup_on_provider())
    else:
        # Manual approval
        provision_request.approve_request(method='ui', reason="Approved")
        vm_names = [vm_name + "001", vm_name + "002"]  # There will be two VMs
        request.addfinalizer(lambda: [
            appliance.collections.infra_vms.instantiate(v_name, provider).
            cleanup_on_provider() for v_name in vm_names
        ])

    try:
        wait_for(lambda: len(smtp_test.get_emails()) >= 2, num_sec=90, delay=3)
    except TimedOutError:
        pytest.fail(
            'Did not receive at least 1 emails from provisioning request, received: {}'
            .format(smtp_test.get_emails()))
    # requester includes the trailing space
    approved_subject = normalize_text(
        "your {} request was approved".format(vm_type))
    approved_from = normalize_text("{} request from {}was approved".format(
        vm_type, requester))

    received_approved = [
        normalize_text(m["subject"]) for m in smtp_test.get_emails()
    ]
    # Looking for each expected subject in the list of received subjects with partial match
    for subject in [approved_subject, approved_from]:
        soft_assert(
            any(subject in r_sub for r_sub in received_approved),
            'Expected subject [{}], not matched in received subjects [{}]'.
            format(subject, received_approved))

    smtp_test.clear_database()

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

    provision_request.wait_for_request(method='ui')
    msg = "Provisioning failed with the message {}".format(
        provision_request.row.last_message.text)
    assert provision_request.is_succeeded(method='ui'), msg

    # account for multiple vms, specific names
    completed_subjects = [
        normalize_text("your {} request has completed vm name {}".format(
            vm_type, name)) for name in vm_names
    ]
    expected_subject_count = len(vm_names)
    # Wait for e-mails to appear
    try:
        wait_for(lambda: len(smtp_test.get_emails()) >= expected_subject_count,
                 message="provisioning request completed emails",
                 delay=5)
    except TimedOutError:
        pytest.fail(
            'Did not receive enough emails (> {}) from provisioning request, received: {}'
            .format(expected_subject_count, smtp_test.get_emails()))

    received_complete = [
        normalize_text(m['subject']) for m in smtp_test.get_emails()
    ]
    for expected_subject in completed_subjects:
        soft_assert(
            any(expected_subject in subject for subject in received_complete),
            'Expected subject [{}], not matched in received subjects [{}]'.
            format(subject, received_complete))
Esempio n. 13
0
 def verify():
     return (len(
         filter(
             lambda mail: normalize_text(subject) in normalize_text(mail[
                 "subject"]), smtp_test.get_emails())) == len(vm_names))
Esempio n. 14
0
 def _expected_email_arrived():
     emails = smtp.get_emails()
     messages = (_email_message_with_rcpttos_header(m) for m in emails
                 if subject in normalize_text(m['subject']))
     return all(eml_checker(m) for m in messages)
def test_provision_approval(appliance, provider, vm_name, smtp_test, request,
                            action, soft_assert):
    """ 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 approval is pending
        * Depending on whether you want to do:
            * approve: manually approve the request in UI
            * edit: Edit the request in UI so it conforms the rules for auto-approval.
            * deny: Deny the request in UI.
        * Wait for an e-mail with approval
        * Wait until the request finishes
        * Wait until an email with provisioning complete

    Metadata:
        test_flag: provision
        suite: infra_provisioning

    Polarion:
        assignee: jhenner
        caseimportance: high
        casecomponent: Provisioning
        initialEstimate: 1/8h

    Bugzilla:
        1472844
        1676910
        1380197
        1818172
    """

    # generate_tests makes sure these have values
    # template, host, datastore = map(provisioning.get, ('template', 'host', 'datastore'))

    # It will provision two of them
    # All the subject checks are normalized, because of newlines and capitalization

    vm_names = [vm_name + "001", vm_name + "002"]
    requester = "[email protected] "  # include trailing space for clean formatting
    if provider.one_of(CloudProvider):
        requester = "" if BZ(1818172).blocks else requester
        vm_type = "instance"
    else:
        vm_type = "virtual machine"
    collection = appliance.provider_based_collection(provider)
    inst_args = {'catalog': {'vm_name': vm_name, 'num_vms': '2'}}

    vm = collection.create(vm_name,
                           provider,
                           form_values=inst_args,
                           wait=False)
    pending_subject = normalize_text(f"your {vm_type} request is pending")
    # requester includes the trailing space
    pending_from = normalize_text(
        f"{vm_type} request from {requester}pending approval")

    wait_for_messages_with_subjects(smtp_test, {pending_subject, pending_from},
                                    num_sec=90)

    smtp_test.clear_database()

    cells = {
        'Description': f'Provision from [{vm.template_name}] to [{vm.name}###]'
    }

    def _action_edit():
        # Automatic approval after editing the request to conform
        new_vm_name = f'{vm_name}-xx'
        modifications = {
            'catalog': {
                'num_vms': "1",
                'vm_name': new_vm_name
            },
            'Description':
            f'Provision from [{vm.template_name}] to [{new_vm_name}]'
        }
        provision_request = appliance.collections.requests.instantiate(
            cells=cells)
        provision_request.edit_request(values=modifications)
        vm_names = [new_vm_name]  # Will be just one now
        request.addfinalizer(lambda: collection.instantiate(
            new_vm_name, provider).cleanup_on_provider())
        _post_approval(smtp_test, provision_request, vm_type, requester,
                       provider, vm_names)

    def _action_approve():
        # Manual approval
        provision_request = appliance.collections.requests.instantiate(
            cells=cells)
        provision_request.approve_request(method='ui', reason="Approved")
        for v_name in vm_names:
            request.addfinalizer(lambda:
                                 (appliance.collections.infra_vms.instantiate(
                                     v_name, provider).cleanup_on_provider()))
        _post_approval(smtp_test, provision_request, vm_type, requester,
                       provider, vm_names)

    def _action_deny():
        provision_request = appliance.collections.requests.instantiate(
            cells=cells)
        provision_request.deny_request(method='ui', reason="You stink!")
        denied_subject = normalize_text(f"your {vm_type} request was denied")
        denied_from = normalize_text(
            f"{vm_type} request from {requester}was denied")
        wait_for_messages_with_subjects(smtp_test,
                                        [denied_subject, denied_from],
                                        num_sec=90)

    # Call function doing what is necessary -- Variation of Strategy design pattern.
    action_callable = locals().get(f'_action_{action}')
    if not action_callable:
        raise NotImplementedError(
            f'Action {action} is not known to this test.')
    action_callable()
Esempio n. 16
0
def test_provision_approval(appliance, provider, vm_name, smtp_test, request,
                            edit):
    """ 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

    Polarion:
        assignee: jhenner
        caseimportance: high
        casecomponent: Provisioning
        initialEstimate: 1/8h
    """
    # 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"]
    if BZ(1628240).blocks and provider.one_of(CloudProvider):
        requester = ""
    else:
        requester = "[email protected] "
    collection = appliance.provider_based_collection(provider)
    inst_args = {'catalog': {
        'vm_name': vm_name,
        'num_vms': '2'
    }}

    vm = collection.create(vm_name, provider, form_values=inst_args, wait=False)
    try:
        if provider.one_of(CloudProvider):
            vm_type = "instance"
        else:
            vm_type = "virtual machine"

        subject = VersionPicker({
            LOWEST: "your request for a new vms was not autoapproved",
            "5.10": "your {} request is pending".format(vm_type)
        }).pick()
        wait_for(
            lambda:
            len(filter(
                lambda mail:
                normalize_text(subject) in normalize_text(mail["subject"]),
                smtp_test.get_emails())) == 1,
            num_sec=90, delay=5)
        subject = VersionPicker({
            LOWEST: "virtual machine request was not approved",
            "5.10": "{} request from {}pending approval".format(vm_type, requester)
        }).pick()

        wait_for(
            lambda:
            len(filter(
                lambda mail:
                normalize_text(subject) in normalize_text(mail["subject"]),
                smtp_test.get_emails())) == 1,
            num_sec=90, delay=5)
    except TimedOutError:
        subjects = ",".join([normalize_text(m["subject"]) for m in smtp_test.get_emails()])
        logger.error("expected: %s, got emails: %s", subject, subjects)
        raise

    smtp_test.clear_database()

    cells = {'Description': 'Provision from [{}] to [{}###]'.format(vm.template_name, vm.name)}
    provision_request = appliance.collections.requests.instantiate(cells=cells)
    navigate_to(provision_request, 'Details')
    if edit:
        # Automatic approval after editing the request to conform
        new_vm_name = '{}-xx'.format(vm_name)
        modifications = {
            'catalog': {'num_vms': "1", 'vm_name': new_vm_name},
            'Description': 'Provision from [{}] to [{}]'.format(vm.template_name, new_vm_name)}
        provision_request.edit_request(values=modifications)
        vm_names = [new_vm_name]  # Will be just one now
        request.addfinalizer(
            lambda: collection.instantiate(new_vm_name, provider).cleanup_on_provider()
        )
    else:
        # Manual approval
        provision_request.approve_request(method='ui', reason="Approved")
        vm_names = [vm_name + "001", vm_name + "002"]  # There will be two VMs
        request.addfinalizer(
            lambda: [appliance.collections.infra_vms.instantiate(name,
                                                                 provider).cleanup_on_provider()
                     for name in vm_names]
        )
    subject = VersionPicker({
        LOWEST: "your virtual machine configuration was approved",
        "5.10": "your {} request was approved".format(vm_type)
    }).pick()
    try:
        wait_for(
            lambda:
            len(filter(
                lambda mail:
                normalize_text(subject) in normalize_text(mail["subject"]),
                smtp_test.get_emails())) == 1,
            num_sec=120, delay=5)
    except TimedOutError:
        subjects = ",".join([normalize_text(m["subject"]) for m in smtp_test.get_emails()])
        logger.error("expected: %s, got emails: %s", subject, subjects)
        raise

    smtp_test.clear_database()

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

    provision_request.wait_for_request(method='ui')
    msg = "Provisioning failed with the message {}".format(provision_request.row.last_message.text)
    assert provision_request.is_succeeded(method='ui'), msg

    subject = VersionPicker({
        LOWEST: "your virtual machine request has completed vm {}".format(vm_name),
        "5.10": "your {} request has completed vm name {}".format(vm_type, vm_name)
    }).pick()

    # Wait for e-mails to appear
    def verify():
        return (
            len(filter(
                lambda mail: normalize_text(subject) in normalize_text(mail["subject"]),
                smtp_test.get_emails())) == len(vm_names)
        )
    try:
        wait_for(verify, message="email receive check", delay=5)
    except TimedOutError:
        subjects = ",".join([normalize_text(m["subject"]) for m in smtp_test.get_emails()])
        logger.error("expected: %s, got emails: %s", subject, subjects)
        raise
Esempio n. 17
0
 def verify():
     return (
         len(filter(
             lambda mail: normalize_text(subject) in normalize_text(mail["subject"]),
             smtp_test.get_emails())) == len(vm_names)
     )
Esempio n. 18
0
def test_provision_approval(appliance, provider, vm_name, smtp_test, request,
                            edit):
    """ 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

    Polarion:
        assignee: jhenner
        caseimportance: high
        initialEstimate: 1/8h
    """
    # 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"]
    if BZ(1628240).blocks and provider.one_of(CloudProvider):
        requester = ""
    else:
        requester = "[email protected] "
    collection = appliance.provider_based_collection(provider)
    inst_args = {'catalog': {'vm_name': vm_name, 'num_vms': '2'}}

    vm = collection.create(vm_name,
                           provider,
                           form_values=inst_args,
                           wait=False)
    try:
        if provider.one_of(CloudProvider):
            vm_type = "instance"
        else:
            vm_type = "virtual machine"

        subject = VersionPicker({
            LOWEST:
            "your request for a new vms was not autoapproved",
            "5.10":
            "your {} request is pending".format(vm_type)
        }).pick()
        wait_for(lambda: len(
            filter(
                lambda mail: normalize_text(subject) in normalize_text(mail[
                    "subject"]), smtp_test.get_emails())) == 1,
                 num_sec=90,
                 delay=5)
        subject = VersionPicker({
            LOWEST:
            "virtual machine request was not approved",
            "5.10":
            "{} request from {}pending approval".format(vm_type, requester)
        }).pick()

        wait_for(lambda: len(
            filter(
                lambda mail: normalize_text(subject) in normalize_text(mail[
                    "subject"]), smtp_test.get_emails())) == 1,
                 num_sec=90,
                 delay=5)
    except TimedOutError:
        subjects = ",".join(
            [normalize_text(m["subject"]) for m in smtp_test.get_emails()])
        logger.error("expected: %s, got emails: %s", subject, subjects)
        raise

    smtp_test.clear_database()

    cells = {
        'Description':
        'Provision from [{}] to [{}###]'.format(vm.template_name, vm.name)
    }
    provision_request = appliance.collections.requests.instantiate(cells=cells)
    navigate_to(provision_request, 'Details')
    if edit:
        # Automatic approval after editing the request to conform
        new_vm_name = '{}-xx'.format(vm_name)
        modifications = {
            'catalog': {
                'num_vms': "1",
                'vm_name': new_vm_name
            },
            'Description':
            'Provision from [{}] to [{}]'.format(vm.template_name, new_vm_name)
        }
        provision_request.edit_request(values=modifications)
        vm_names = [new_vm_name]  # Will be just one now
        request.addfinalizer(lambda: collection.instantiate(
            new_vm_name, provider).cleanup_on_provider())
    else:
        # Manual approval
        provision_request.approve_request(method='ui', reason="Approved")
        vm_names = [vm_name + "001", vm_name + "002"]  # There will be two VMs
        request.addfinalizer(lambda: [
            appliance.collections.infra_vms.instantiate(name, provider).
            cleanup_on_provider() for name in vm_names
        ])
    subject = VersionPicker({
        LOWEST:
        "your virtual machine configuration was approved",
        "5.10":
        "your {} request was approved".format(vm_type)
    }).pick()
    try:
        wait_for(lambda: len(
            filter(
                lambda mail: normalize_text(subject) in normalize_text(mail[
                    "subject"]), smtp_test.get_emails())) == 1,
                 num_sec=120,
                 delay=5)
    except TimedOutError:
        subjects = ",".join(
            [normalize_text(m["subject"]) for m in smtp_test.get_emails()])
        logger.error("expected: %s, got emails: %s", subject, subjects)
        raise

    smtp_test.clear_database()

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

    provision_request.wait_for_request(method='ui')
    msg = "Provisioning failed with the message {}".format(
        provision_request.row.last_message.text)
    assert provision_request.is_succeeded(method='ui'), msg

    subject = VersionPicker({
        LOWEST:
        "your virtual machine request has completed vm {}".format(vm_name),
        "5.10":
        "your {} request has completed vm name {}".format(vm_type, vm_name)
    }).pick()

    # Wait for e-mails to appear
    def verify():
        return (len(
            filter(
                lambda mail: normalize_text(subject) in normalize_text(mail[
                    "subject"]), smtp_test.get_emails())) == len(vm_names))

    try:
        wait_for(verify, message="email receive check", delay=5)
    except TimedOutError:
        subjects = ",".join(
            [normalize_text(m["subject"]) for m in smtp_test.get_emails()])
        logger.error("expected: %s, got emails: %s", subject, subjects)
        raise