def test_edit_repository(self, appliance, repository, from_collection):
        """Tests editing repositories using REST API.

        Metadata:
            test_flag: rest

        Polarion:
            assignee: pvala
            casecomponent: Ansible
            caseimportance: medium
            initialEstimate: 1/4h
        """
        new_description = "Test Repository {}".format(fauxfactory.gen_alphanumeric(5))

        if from_collection:
            repository.reload()
            repository_data_edited = {
                "href": repository.href,
                "description": new_description,
            }
            appliance.rest_api.collections.configuration_script_sources.action.edit(
                repository_data_edited)
        else:
            repository.action.edit(description=new_description)

        assert_response(appliance)
        record, __ = wait_for(
            lambda: appliance.rest_api.collections.configuration_script_sources.find_by(
                description=new_description) or False,
            num_sec=180,
            delay=10,
        )
        repository.reload()
        assert repository.description == record[0].description
Ejemplo n.º 2
0
    def test_edit_tenants(self, appliance, tenants, multiple):
        """Tests editing tenants.

        Metadata:
            test_flag: rest
        """
        collection = appliance.rest_api.collections.tenants
        tenants_len = len(tenants)
        new = []
        for _ in range(tenants_len):
            new.append(
                {'name': 'test_tenants_{}'.format(fauxfactory.gen_alphanumeric().lower())})
        if multiple:
            for index in range(tenants_len):
                new[index].update(tenants[index]._ref_repr())
            edited = collection.action.edit(*new)
            assert_response(appliance)
        else:
            edited = []
            for index in range(tenants_len):
                edited.append(tenants[index].action.edit(**new[index]))
                assert_response(appliance)
        assert tenants_len == len(edited)
        for index, tenant in enumerate(tenants):
            record, _ = wait_for(
                lambda: collection.find_by(name=new[index]['name']) or False,
                num_sec=180,
                delay=10,
            )
            tenant.reload()
            assert record[0].id == edited[index].id == tenant.id
            assert record[0].name == edited[index].name == tenant.name
 def test_set_vm_owner(self, appliance, vm, from_detail):
     """Test whether set_owner action from the REST API works.
     Prerequisities:
         * A VM
     Steps:
         * Find a VM id using REST
         * Call either:
             * POST /api/vms/<id> (method ``set_owner``) <- {"owner": "owner username"}
             * POST /api/vms (method ``set_owner``) <- {"owner": "owner username",
                 "resources": [{"href": ...}]}
         * Query the VM again
         * Assert it has the attribute ``evm_owner`` as we set it.
     Metadata:
         test_flag: rest
     """
     rest_vm = appliance.rest_api.collections.vms.get(name=vm)
     if from_detail:
         responses = [rest_vm.action.set_owner(owner="admin")]
     else:
         responses = appliance.rest_api.collections.vms.action.set_owner(rest_vm, owner="admin")
     assert_response(appliance)
     for response in responses:
         assert response["success"] is True, "Could not set owner"
     rest_vm.reload()
     assert hasattr(rest_vm, "evm_owner_id")
     assert rest_vm.evm_owner.userid == "admin"
Ejemplo n.º 4
0
def test_set_ownership(appliance, template, from_detail):
    """Tests setting of template ownership.

    Metadata:
        test_flag: rest
    """
    if "set_ownership" not in appliance.rest_api.collections.templates.action.all:
        pytest.skip("set_ownership action for templates is not implemented in this version")
    group = appliance.rest_api.collections.groups.get(description='EvmGroup-super_administrator')
    user = appliance.rest_api.collections.users.get(userid='admin')
    data = {
        "owner": {"href": user.href},
        "group": {"href": group.href}
    }
    if from_detail:
        template.action.set_ownership(**data)
    else:
        data["href"] = template.href
        appliance.rest_api.collections.templates.action.set_ownership(**data)
    assert_response(appliance)
    template.reload()
    assert hasattr(template, "evm_owner_id")
    assert template.evm_owner_id == user.id
    assert hasattr(template, "miq_group_id")
    assert template.miq_group_id == group.id
Ejemplo n.º 5
0
    def test_mark_notifications(self, appliance, generate_notifications, from_detail):
        """Tests marking notifications as seen.

        Metadata:
            test_flag: rest

        Polarion:
            assignee: pvala
            casecomponent: Rest
            caseimportance: medium
            initialEstimate: 1/4h
        """
        unseen = appliance.rest_api.collections.notifications.find_by(seen=False)
        notifications = [unseen[-i] for i in range(1, 3)]

        if from_detail:
            for ent in notifications:
                ent.action.mark_as_seen()
                assert_response(appliance)
        else:
            appliance.rest_api.collections.notifications.action.mark_as_seen(*notifications)
            assert_response(appliance)

        for ent in notifications:
            ent.reload()
            assert ent.seen
Ejemplo n.º 6
0
def test_attributes_present(appliance, collection_name):
    """Tests that the expected attributes are present in all collections.

    Metadata:
        test_flag: rest

    Bugzilla:
        1510238
        1503852
        1547852

    Polarion:
        assignee: pvala
        casecomponent: Rest
        caseimportance: medium
        initialEstimate: 1/5h
    """
    attrs = 'href,id,href_slug'
    collection = getattr(appliance.rest_api.collections, collection_name)
    response = appliance.rest_api.get(
        '{0}{1}{2}'.format(collection._href, '?expand=resources&attributes=', attrs))
    assert_response(appliance)
    for resource in response.get('resources', []):
        assert 'id' in resource
        assert 'href' in resource
        assert resource['href'] == '{}/{}'.format(collection._href, resource['id'])
        assert 'href_slug' in resource
        assert resource['href_slug'] == '{}/{}'.format(collection.name, resource['id'])
Ejemplo n.º 7
0
 def create_picture(self, appliance):
     picture = appliance.rest_api.collections.pictures.action.create({
         "extension": "png",
         "content": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcS"
                    "JAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="})
     assert_response(appliance)
     return picture[0]
Ejemplo n.º 8
0
def test_rest_metric_rollups(appliance, interval, resource_type):
    """
    Polarion:
        assignee: pvala
        casecomponent: Rest
        caseimportance: medium
        initialEstimate: 1/10h
        testSteps:
            1. Send GET request:
            /api/metric_rollups?resource_type=:resource_type&capture_interval=:interval
            &start_date=:start_date&end_date=:end_date
        expectedResults:
            1. Successful 200 OK response.
    """
    end_date = datetime.now()
    start_date = end_date - timedelta(days=2)

    url = (
        "{entry_point}?resource_type={resource_type}&capture_interval={interval}"
        "&start_date={start_date}&end_date={end_date}&limit=30"
    ).format(
        entry_point=appliance.rest_api.collections.metric_rollups._href,
        resource_type=resource_type,
        interval=interval,
        start_date=start_date.isoformat(),
        end_date=end_date.isoformat(),
    )
    appliance.rest_api.get(url)
    assert_response(appliance)
Ejemplo n.º 9
0
def test_query_simple_collections(appliance, collection_name):
    """This test tries to load each of the listed collections. 'Simple' collection means that they
    have no usable actions that we could try to run
    Metadata:
        test_flag: rest

    Polarion:
        assignee: pvala
        casecomponent: Rest
        caseimportance: high
        initialEstimate: 1/3h
        testSteps:
            1. Send a GET request: /api/<collection_name>
        expectedResults:
            1. Must receive a 200 OK response.
    """
    collection = getattr(appliance.rest_api.collections, collection_name)

    if collection_name in COLLECTIONS_OMITTED:
        # the "settings" and automate_workspaces collections are untypical
        # as they don't have "resources" and for this reason can't be reloaded (bug in api client)
        appliance.rest_api.get(collection._href)
        assert_response(appliance)
    else:
        assert_response(appliance)
        collection.reload()
        list(collection)
Ejemplo n.º 10
0
def test_create_pending_provision_requests(request, appliance, provider, small_template):
    """Tests creation and and auto-approval of pending provision request
    using /api/provision_requests.

    Metadata:
        test_flag: rest, provision
    """
    provision_data = get_provision_data(
        appliance.rest_api, provider, small_template.name, auto_approve=False)
    vm_name = provision_data['vm_fields']['vm_name']
    request.addfinalizer(lambda: clean_vm(appliance, provider, vm_name))
    prov_request, = appliance.rest_api.collections.provision_requests.action.create(
        **provision_data)
    assert_response(appliance)
    # check that the `approval_state` is pending_approval
    assert prov_request.options['auto_approve'] is False
    assert prov_request.approval_state == 'pending_approval'
    # The Automate approval process is running as part of the request workflow.
    # The request is within the specified parameters so it shall be auto-approved.
    prov_request.reload()
    wait_for(
        lambda: prov_request.approval_state == 'approved',
        fail_func=prov_request.reload,
        num_sec=300,
        delay=10)
    # Wait for provisioning to finish
    wait_for(
        lambda: prov_request.request_state == 'finished',
        fail_func=prov_request.reload,
        num_sec=600,
        delay=10)
Ejemplo n.º 11
0
def test_edit_vm(request, vm, appliance, from_detail):
    """Tests edit VMs using REST API.

    Testing BZ 1428250.

    Metadata:
        test_flag: rest

    Polarion:
        assignee: pvala
        casecomponent: Rest
        caseimportance: high
        initialEstimate: 1/4h
    """
    request.addfinalizer(vm.action.delete)
    new_description = 'Test REST VM {}'.format(fauxfactory.gen_alphanumeric(5))
    payload = {'description': new_description}
    if from_detail:
        edited = vm.action.edit(**payload)
        assert_response(appliance)
    else:
        payload.update(vm._ref_repr())
        edited = appliance.rest_api.collections.vms.action.edit(payload)
        assert_response(appliance)
        edited = edited[0]

    record, __ = wait_for(
        lambda: appliance.rest_api.collections.vms.find_by(
            description=new_description) or False,
        num_sec=100,
        delay=5,
    )
    vm.reload()
    assert vm.description == edited.description == record[0].description
Ejemplo n.º 12
0
def test_sorting_by_attributes(appliance):
    """Test that it's possible to sort resources by attributes.

    Metadata:
        test_flag: rest
    """
    url_string = '{}{}'.format(
        appliance.rest_api.collections.groups._href,
        '?expand=resources&attributes=id&sort_by=id&sort_order={}')
    response_asc = appliance.rest_api.get(url_string.format('asc'))
    assert_response(appliance)
    assert 'resources' in response_asc
    response_desc = appliance.rest_api.get(url_string.format('desc'))
    assert_response(appliance)
    assert 'resources' in response_desc
    assert response_asc['subcount'] == response_desc['subcount']

    id_last = 0
    for resource in response_asc['resources']:
        assert int(resource['id']) > int(id_last)
        id_last = int(resource['id'])
    id_last += 1
    for resource in response_desc['resources']:
        assert int(resource['id']) < int(id_last)
        id_last = int(resource['id'])
Ejemplo n.º 13
0
def test_provision_emails(request, provision_data, provider, appliance, smtp_test):
    """
    Test that redundant e-mails are not received when provisioning VM that has some
    attributes set to values that differ from template's default.

    Metadata:
        test_flag: rest, provision
    """
    def check_one_approval_mail_received():
        return len(smtp_test.get_emails(
            subject_like="%%Your Virtual Machine configuration was Approved%%")) == 1

    def check_one_completed_mail_received():
        return len(smtp_test.get_emails(
            subject_like="%%Your virtual machine request has Completed%%")) == 1

    request.addfinalizer(lambda: clean_vm(appliance, provider, vm_name))

    vm_name = provision_data["vm_fields"]["vm_name"]
    memory = int(provision_data["vm_fields"]["vm_memory"])
    provision_data["vm_fields"]["vm_memory"] = str(memory / 2)
    provision_data["vm_fields"]["number_of_cpus"] += 1

    appliance.rest_api.collections.provision_requests.action.create(**provision_data)
    assert_response(appliance)

    request = appliance.collections.requests.instantiate(description=vm_name, partial_check=True)
    request.wait_for_request()
    assert provider.mgmt.does_vm_exist(vm_name), "The VM {} does not exist!".format(vm_name)

    wait_for(check_one_approval_mail_received, num_sec=90, delay=5)
    wait_for(check_one_completed_mail_received, num_sec=90, delay=5)
Ejemplo n.º 14
0
def test_order_catalog_item_via_rest(
        request, appliance, provider, catalog_item, catalog):
    """Same as :py:func:`test_order_catalog_item`, but using REST.
    Metadata:
        test_flag: provision, rest
    """
    vm_name = catalog_item.prov_data['catalog']["vm_name"]
    request.addfinalizer(
        lambda: appliance.collections.infra_vms.instantiate(vm_name,
                                                            provider).cleanup_on_provider()
    )
    request.addfinalizer(catalog_item.delete)
    catalog = appliance.rest_api.collections.service_catalogs.find_by(name=catalog.name)
    assert len(catalog) == 1
    catalog, = catalog
    template = catalog.service_templates.find_by(name=catalog_item.name)
    assert len(template) == 1
    template, = template
    req = template.action.order()
    assert_response(appliance)

    @wait_for_decorator(timeout="15m", delay=5)
    def request_finished():
        req.reload()
        logger.info("Request status: {}, Request state: {}, Request message: {}".format(
            req.status, req.request_state, req.message))
        return req.status.lower() == "ok" and req.request_state.lower() == "finished"
Ejemplo n.º 15
0
def test_provider_refresh(provider_rest, appliance):
    """Test checking that refresh invoked from the REST API works.

    Metadata:
        test_flag: rest
    """
    # initiate refresh
    def _refresh_success():
        provider_rest.action.refresh()
        # the provider might not be ready yet, wait a bit
        if "failed last authentication check" in appliance.rest_api.response.json()["message"]:
            return False
        return True

    if not wait_for(_refresh_success, num_sec=30, delay=2, silent_failure=True):
        pytest.fail("Authentication failed, check credentials.")
    task_id = appliance.rest_api.response.json().get("task_id")
    assert_response(appliance, task_wait=0)

    # wait for an acceptable task state
    if task_id:
        task = appliance.rest_api.get_entity("tasks", task_id)
        wait_for(
            lambda: task.state.lower() in ("finished", "queued"),
            fail_func=task.reload,
            num_sec=30,
        )
        assert task.status.lower() == "ok", "Task failed with status '{}'".format(task.status)
Ejemplo n.º 16
0
    def test_edit_groups(self, appliance, groups, multiple):
        """Tests editing groups.

        Metadata:
            test_flag: rest
        """
        collection = appliance.rest_api.collections.groups
        groups_len = len(groups)
        new = []
        for _ in range(groups_len):
            new.append(
                {'description': 'group_description_{}'.format(fauxfactory.gen_alphanumeric())})
        if multiple:
            for index in range(groups_len):
                new[index].update(groups[index]._ref_repr())
            edited = collection.action.edit(*new)
            assert_response(appliance)
        else:
            edited = []
            for index in range(groups_len):
                edited.append(groups[index].action.edit(**new[index]))
                assert_response(appliance)
        assert groups_len == len(edited)
        for index, group in enumerate(groups):
            record, _ = wait_for(
                lambda: collection.find_by(description=new[index]['description']) or False,
                num_sec=180,
                delay=10,
            )
            group.reload()
            assert record[0].id == edited[index].id == group.id
            assert record[0].description == edited[index].description == group.description
Ejemplo n.º 17
0
def update(self, updates):
    definition = self.appliance.rest_api.collections.generic_object_definitions.find_by(
        name=self.name)

    if not definition:
        self.rest_response = None
        return

    definition = definition[0]

    top = ['name', 'description']
    prop = ['attributes', 'associations', 'methods']

    body = {}
    properties = body['properties'] = {}

    for key in top:
        new = updates.get(key)
        body.update({} if new is None else {key: new})
    for key in prop:
        new = updates.get(key)
        properties.update({} if new is None else {key: new})

    definition.action.edit(**body)
    assert_response(self.appliance)
    self.rest_response = self.appliance.rest_api.response
Ejemplo n.º 18
0
    def test_assign_and_unassign_tag(self, appliance, tags_mod, provider, services_mod,
            service_templates, tenants, vm, collection_name):
        """Tests assigning and unassigning tags.

        Metadata:
            test_flag: rest

        Polarion:
            assignee: pvala
            casecomponent: Rest
            caseimportance: high
            initialEstimate: 1/5h
        """
        collection = getattr(appliance.rest_api.collections, collection_name)
        collection.reload()
        if not collection.all:
            pytest.skip("No available entity in {} to assign tag".format(collection_name))
        entity = collection[-1]
        tag = tags_mod[0]
        entity.tags.action.assign(tag)
        assert_response(appliance)
        entity.reload()
        assert tag.id in [t.id for t in entity.tags.all]
        entity.tags.action.unassign(tag)
        assert_response(appliance)
        entity.reload()
        assert tag.id not in [t.id for t in entity.tags.all]
Ejemplo n.º 19
0
    def test_cloud_networks_query(self, cloud_provider, appliance, from_detail):
        """Tests querying cloud providers and cloud_networks collection for network info.

        Metadata:
            test_flag: rest

        Polarion:
            assignee: pvala
            casecomponent: Cloud
            caseimportance: low
            initialEstimate: 1/3h
        """
        if from_detail:
            networks = appliance.rest_api.collections.providers.get(
                name=cloud_provider.name).cloud_networks
        else:
            networks = appliance.rest_api.collections.cloud_networks
        assert_response(appliance)
        assert networks
        assert len(networks) == networks.subcount

        enabled_networks = 0
        networks.reload(expand=True)
        for network in networks:
            assert 'CloudNetwork' in network.type
            if network.enabled is True:
                enabled_networks += 1
        assert enabled_networks >= 1
Ejemplo n.º 20
0
    def test_edit_categories(self, appliance, categories, multiple):
        """Tests editing categories.

        Metadata:
            test_flag: rest
        """
        collection = appliance.rest_api.collections.categories
        categories_len = len(categories)
        new = []
        for _ in range(categories_len):
            new.append(
                {'description': 'test_category_{}'.format(fauxfactory.gen_alphanumeric().lower())})
        if multiple:
            for index in range(categories_len):
                new[index].update(categories[index]._ref_repr())
            edited = collection.action.edit(*new)
            assert_response(appliance)
        else:
            edited = []
            for index in range(categories_len):
                edited.append(categories[index].action.edit(**new[index]))
                assert_response(appliance)
        assert categories_len == len(edited)
        for index in range(categories_len):
            record, _ = wait_for(
                lambda: collection.find_by(description=new[index]['description']) or False,
                num_sec=180,
                delay=10,
            )
            assert record[0].id == edited[index].id
            assert record[0].description == edited[index].description
    def test_edit(self, request, from_detail, collection_name, appliance, fixtures_db):
        """Test editing custom attributes using REST API.

        Metadata:
            test_flag: rest
        """
        attributes, resource = add_custom_attributes(request, fixtures_db[collection_name])
        response_len = len(attributes)
        body = []
        for __ in range(response_len):
            uid = fauxfactory.gen_alphanumeric(5)
            body.append({
                'name': 'ca_name_{}'.format(uid),
                'value': 'ca_value_{}'.format(uid),
                'section': 'metadata'
            })
        if from_detail:
            edited = []
            for i in range(response_len):
                edited.append(attributes[i].action.edit(**body[i]))
                assert_response(appliance)
        else:
            for i in range(response_len):
                body[i].update(attributes[i]._ref_repr())
            edited = resource.custom_attributes.action.edit(*body)
            assert_response(appliance)
        assert len(edited) == response_len
        for i in range(response_len):
            attributes[i].reload()
            assert edited[i].name == body[i]['name'] == attributes[i].name
            assert edited[i].value == body[i]['value'] == attributes[i].value
            assert edited[i].section == body[i]['section'] == attributes[i].section
Ejemplo n.º 22
0
def vm_snapshot(appliance, collection, vm_obj):
    """Creates VM/instance snapshot using REST API

    Returns:
        Tuple with VM and snapshot resources in REST API
    """
    uid = fauxfactory.gen_alphanumeric(8)
    snap_name = 'snpshot_{}'.format(uid)
    vm = collection.get(name=vm_obj.name)
    vm.snapshots.action.create(
        name=snap_name,
        description='snapshot {}'.format(uid),
        memory=False)
    assert_response(appliance)
    snap, __ = wait_for(
        lambda: vm.snapshots.find_by(name=snap_name) or False,
        num_sec=600, delay=5)
    snap = snap[0]

    yield vm, snap

    collection.reload()
    to_delete = vm.snapshots.find_by(name=snap_name)
    if to_delete:
        vm.snapshots.action.delete(to_delete[0])
    def test_authentications_edit_multiple(self, appliance, authentications):
        """Tests editing multiple authentications at once.

        Metadata:
            test_flag: rest

        Polarion:
            assignee: pvala
            casecomponent: Rest
            caseimportance: medium
            initialEstimate: 1/4h
        """
        new_names = []
        auths_data_edited = []
        for auth in authentications:
            new_name = 'test_edited_{}'.format(fauxfactory.gen_alphanumeric().lower())
            new_names.append(new_name)
            auth.reload()
            auths_data_edited.append({
                'href': auth.href,
                'name': new_name,
            })
        responses = appliance.rest_api.collections.authentications.action.edit(*auths_data_edited)
        assert_response(appliance)
        assert len(responses) == len(authentications)
        _check_edited_authentications(appliance, authentications, new_names)
Ejemplo n.º 24
0
    def test_query_by_multiple_tags(self, appliance, tags, services):
        """Tests support for multiple tag specification in query.

        Metadata:
            test_flag: rest

        Polarion:
            assignee: pvala
            casecomponent: Rest
            caseimportance: high
            initialEstimate: 1/30h
        """
        collection = appliance.rest_api.collections.services
        collection.reload()
        new_tags = [tag._ref_repr() for tag in tags]
        tagged_services = services[1:]

        # assign tags to selected services
        collection.action.assign_tags(*tagged_services, tags=new_tags)
        assert_response(appliance)

        # get only services that has all the tags assigned
        by_tag = ','.join([tag.name.replace('/managed', '') for tag in tags])
        query_results = collection.query_string(by_tag=by_tag)

        assert len(tagged_services) == len(query_results)
        result_ids = {item.id for item in query_results}
        tagged_ids = {item.id for item in tagged_services}
        assert result_ids == tagged_ids
    def test_edit_multiple_service_catalogs(self, appliance, service_catalogs):
        """Tests editing multiple service catalogs at time.
        Prerequisities:
            * An appliance with ``/api`` available.
        Steps:
            * POST /api/service_catalogs (method ``edit``)
                with the list of dictionaries used to edit
            * Check if the service_catalogs with ``new_name`` each exist
        Metadata:
            test_flag: rest
        """

        new_names = []
        scls_data_edited = []
        for scl in service_catalogs:
            new_name = fauxfactory.gen_alphanumeric()
            new_names.append(new_name)
            scls_data_edited.append({
                "href": scl.href,
                "name": new_name,
            })
        response = appliance.rest_api.collections.service_catalogs.action.edit(*scls_data_edited)
        assert_response(appliance)
        assert len(response) == len(new_names)
        for index, resource in enumerate(response):
            assert resource.name == new_names[index]
            scl = service_catalogs[index]
            scl.reload()
            assert scl.name == new_names[index]
Ejemplo n.º 26
0
    def test_edit_tag_from_detail(self, appliance, tags):
        """Tests tag editing from detail.

        Metadata:
            test_flag: rest

        Polarion:
            assignee: pvala
            casecomponent: Rest
            caseimportance: high
            initialEstimate: 1/30h
        """
        edited = []
        new_names = []
        for tag in tags:
            new_name = 'test_tag_{}'.format(fauxfactory.gen_alphanumeric())
            new_names.append(new_name)
            edited.append(tag.action.edit(name=new_name))
            assert_response(appliance)
        for index, name in enumerate(new_names):
            record, _ = wait_for(lambda:
                appliance.rest_api.collections.tags.find_by(name="%/{}".format(name)) or False,
                num_sec=180,
                delay=10)
            assert record[0].id == edited[index].id
            assert record[0].name == edited[index].name
Ejemplo n.º 27
0
    def test_assign_and_unassign_tag(self, appliance, tags_mod, provider, services_mod,
            service_templates, tenants, vm, collection_name):
        """Tests assigning and unassigning tags.

        Metadata:
            test_flag: rest

        Polarion:
            assignee: pvala
            casecomponent: Rest
            caseimportance: high
            initialEstimate: 1/5h
        """
        collection = getattr(appliance.rest_api.collections, collection_name)
        collection.reload()
        if not collection.all:
            pytest.skip("No available entity in {} to assign tag".format(collection_name))
        entity = collection[-1]
        tag = tags_mod[0]
        try:
            entity.tags.action.assign(tag)
        except AttributeError:
            msg = ('Missing tag attribute in parametrized REST collection {} for entity: {}'
                   .format(collection_name, entity))
            logger.exception(msg)
            pytest.fail(msg)
        assert_response(appliance)
        entity.reload()
        assert tag.id in [t.id for t in entity.tags.all]
        entity.tags.action.unassign(tag)
        assert_response(appliance)
        entity.reload()
        assert tag.id not in [t.id for t in entity.tags.all]
Ejemplo n.º 28
0
    def test_edit_tags_rest(self, appliance, tags):
        """Tests tags editing from collection.

        Metadata:
            test_flag: rest

        Polarion:
            assignee: pvala
            casecomponent: Rest
            caseimportance: high
            initialEstimate: 1/6h
        """
        collection = appliance.rest_api.collections.tags
        tags_len = len(tags)
        tags_data_edited = []
        for tag in tags:
            tags_data_edited.append({
                "href": tag.href,
                "name": "test_tag_{}".format(fauxfactory.gen_alphanumeric().lower()),
            })
        edited = collection.action.edit(*tags_data_edited)
        assert_response(appliance, results_num=tags_len)
        for index in range(tags_len):
            record, _ = wait_for(lambda:
                collection.find_by(name="%/{}".format(tags_data_edited[index]["name"])) or False,
                num_sec=180,
                delay=10)
            assert record[0].id == edited[index].id
            assert record[0].name == edited[index].name
Ejemplo n.º 29
0
    def test_bulk_assign_and_unassign_invalid_tag(self, appliance, services_mod, vm,
            collection_name):
        """Tests bulk assigning and unassigning invalid tags.

        Metadata:
            test_flag: rest
        """
        collection = getattr(appliance.rest_api.collections, collection_name)
        collection.reload()
        entities = collection.all[-2:]

        new_tags = ['invalid_tag1', 'invalid_tag2']
        tags_count = len(new_tags) * len(entities)
        tags_per_entities_count = []
        for entity in entities:
            entity.tags.reload()
            tags_per_entities_count.append(entity.tags.subcount)

        def _check_tags_counts():
            for index, entity in enumerate(entities):
                entity.tags.reload()
                assert entity.tags.subcount == tags_per_entities_count[index]

        collection.action.assign_tags(*entities, tags=new_tags)
        assert_response(appliance, success=False, results_num=tags_count)
        _check_tags_counts()

        collection.action.unassign_tags(*entities, tags=new_tags)
        assert_response(appliance, success=False, results_num=tags_count)
        _check_tags_counts()
Ejemplo n.º 30
0
def repository(appliance, ansible):
    collection = appliance.rest_api.collections.configuration_script_sources
    uniq = fauxfactory.gen_alphanumeric(5)
    repo_name = "test_repo_{}".format(uniq)
    data = {
        "name": repo_name,
        "description": "Test Repo {}".format(uniq),
        "manager_resource": {"href": ansible.href},
        "related": {},
        "scm_type": "git",
        "scm_url": "https://github.com/quarckster/ansible_playbooks",
        "scm_branch": "",
        "scm_clean": False,
        "scm_delete_on_update": False,
        "scm_update_on_launch": False
    }

    collection.action.create(data)
    assert_response(appliance)

    repo_rest, __ = wait_for(
        lambda: collection.find_by(name=repo_name) or False, num_sec=300, delay=5)
    repo_rest = repo_rest[0]

    yield repo_rest

    if repo_rest.exists:
        repo_rest.action.delete()
Ejemplo n.º 31
0
    def test_cloud_networks_query(self, cloud_provider, appliance,
                                  from_detail):
        """Tests querying cloud providers and cloud_networks collection for network info.

        Metadata:
            test_flag: rest
        """
        if from_detail:
            networks = appliance.rest_api.collections.providers.get(
                name=cloud_provider.name).cloud_networks
        else:
            networks = appliance.rest_api.collections.cloud_networks
        assert_response(appliance)
        assert networks
        assert len(networks) == networks.subcount

        enabled_networks = 0
        networks.reload(expand=True)
        for network in networks:
            assert 'CloudNetwork' in network.type
            if network.enabled is True:
                enabled_networks += 1
        assert enabled_networks >= 1
def edit_requests(collection, rest_api, requests_pending, from_detail):
    body = {'options': {'arbitrary_key_allowed': 'test_rest'}}

    if from_detail:
        # testing BZ 1418331
        for request in requests_pending:
            request.action.edit(**body)
            assert_response(rest_api)
    else:
        identifiers = []
        for i, resource in enumerate(requests_pending):
            loc = ({
                'id': resource.id
            }, {
                'href': '{}/{}'.format(collection._href, resource.id)
            })
            identifiers.append(loc[i % 2])
        collection.action.edit(*identifiers, **body)
        assert_response(rest_api)

    for request in requests_pending:
        request.reload()
        assert request.options['arbitrary_key_allowed'] == 'test_rest'
Ejemplo n.º 33
0
    def test_query_by_multiple_tags(self, appliance, tags, services):
        """Tests support for multiple tag specification in query.

        Metadata:
            test_flag: rest
        """
        collection = appliance.rest_api.collections.services
        collection.reload()
        new_tags = [tag._ref_repr() for tag in tags]
        tagged_services = services[1:]

        # assign tags to selected services
        collection.action.assign_tags(*tagged_services, tags=new_tags)
        assert_response(appliance)

        # get only services that has all the tags assigned
        by_tag = ','.join([tag.name.replace('/managed', '') for tag in tags])
        query_results = collection.query_string(by_tag=by_tag)

        assert len(tagged_services) == len(query_results)
        result_ids = {item.id for item in query_results}
        tagged_ids = {item.id for item in tagged_services}
        assert result_ids == tagged_ids
Ejemplo n.º 34
0
    def test_delete_authentications_from_detail_post(self, appliance,
                                                     authentications):
        """Tests deleting authentications from detail using POST method.

        Metadata:
            test_flag: rest

        Polarion:
            assignee: pvala
            casecomponent: Auth
            caseimportance: medium
            initialEstimate: 1/4h
        """
        for auth in authentications:
            auth.action.delete.POST()
            assert_response(appliance)
            auth.wait_not_exists(num_sec=180, delay=5)

            # BZ1476869
            with pytest.raises(Exception,
                               match='ActiveRecord::RecordNotFound'):
                auth.action.delete.POST()
            assert_response(appliance, http_status=404)
    def test_bad_section_edit(self, request, from_detail, collection_name, appliance, get_resource):
        """Test that editing custom attributes using REST API and adding invalid section fails.

        Metadata:
            test_flag: rest
        """
        resource = get_resource[collection_name]()
        attributes = add_custom_attributes(request, resource)
        response_len = len(attributes)
        body = []
        for __ in range(response_len):
            body.append({'section': 'bad_section'})
        if from_detail:
            for i in range(response_len):
                with pytest.raises(Exception, match='Api::BadRequestError'):
                    attributes[i].action.edit(**body[i])
                assert_response(appliance, http_status=400)
        else:
            for i in range(response_len):
                body[i].update(attributes[i]._ref_repr())
            with pytest.raises(Exception, match='Api::BadRequestError'):
                resource.custom_attributes.action.edit(*body)
            assert_response(appliance, http_status=400)
Ejemplo n.º 36
0
    def test_assign_and_unassign_tag(self, appliance, tags_mod, a_provider,
                                     services_mod, service_templates, tenants,
                                     vm, collection_name):
        """Tests assigning and unassigning tags.

        Metadata:
            test_flag: rest
        """
        collection = getattr(appliance.rest_api.collections, collection_name)
        collection.reload()
        if not collection.all:
            pytest.skip("No available entity in {} to assign tag".format(
                collection_name))
        entity = collection[-1]
        tag = tags_mod[0]
        entity.tags.action.assign(tag)
        assert_response(appliance)
        entity.reload()
        assert tag.id in [t.id for t in entity.tags.all]
        entity.tags.action.unassign(tag)
        assert_response(appliance)
        entity.reload()
        assert tag.id not in [t.id for t in entity.tags.all]
Ejemplo n.º 37
0
    def test_edit_groups(self, appliance, groups, multiple):
        """Tests editing groups.

        Metadata:
            test_flag: rest

        Polarion:
            assignee: pvala
            caseimportance: low
            initialEstimate: 1/3h
        """
        collection = appliance.rest_api.collections.groups
        groups_len = len(groups)
        new = []
        for _ in range(groups_len):
            new.append(
                {'description': 'group_description_{}'.format(fauxfactory.gen_alphanumeric())})
        if multiple:
            for index in range(groups_len):
                new[index].update(groups[index]._ref_repr())
            edited = collection.action.edit(*new)
            assert_response(appliance)
        else:
            edited = []
            for index in range(groups_len):
                edited.append(groups[index].action.edit(**new[index]))
                assert_response(appliance)
        assert groups_len == len(edited)
        for index, group in enumerate(groups):
            record, _ = wait_for(
                lambda: collection.find_by(description=new[index]['description']) or False,
                num_sec=180,
                delay=10,
            )
            group.reload()
            assert record[0].id == edited[index].id == group.id
            assert record[0].description == edited[index].description == group.description
Ejemplo n.º 38
0
    def test_edit_tenants(self, appliance, tenants, multiple):
        """Tests editing tenants.

        Metadata:
            test_flag: rest

        Polarion:
            assignee: pvala
            caseimportance: low
            initialEstimate: 1/3h
        """
        collection = appliance.rest_api.collections.tenants
        tenants_len = len(tenants)
        new = []
        for _ in range(tenants_len):
            new.append(
                {'name': 'test_tenants_{}'.format(fauxfactory.gen_alphanumeric().lower())})
        if multiple:
            for index in range(tenants_len):
                new[index].update(tenants[index]._ref_repr())
            edited = collection.action.edit(*new)
            assert_response(appliance)
        else:
            edited = []
            for index in range(tenants_len):
                edited.append(tenants[index].action.edit(**new[index]))
                assert_response(appliance)
        assert tenants_len == len(edited)
        for index, tenant in enumerate(tenants):
            record, _ = wait_for(
                lambda: collection.find_by(name=new[index]['name']) or False,
                num_sec=180,
                delay=10,
            )
            tenant.reload()
            assert record[0].id == edited[index].id == tenant.id
            assert record[0].name == edited[index].name == tenant.name
Ejemplo n.º 39
0
    def test_edit_user_name(self, appliance, users, multiple):
        """Tests editing user name.

        Metadata:
            test_flag: rest

        Polarion:
            assignee: pvala
            casecomponent: Configuration
            caseimportance: low
            initialEstimate: 1/3h
        """
        collection = appliance.rest_api.collections.users
        users_len = len(users)
        new = []
        for _ in range(users_len):
            new.append({"name": "user_name_{}".format(fauxfactory.gen_alphanumeric())})
        if multiple:
            for index in range(users_len):
                new[index].update(users[index]._ref_repr())
            edited = collection.action.edit(*new)
            assert_response(appliance)
        else:
            edited = []
            for index in range(users_len):
                edited.append(users[index].action.edit(**new[index]))
                assert_response(appliance)
        assert users_len == len(edited)
        for index, user in enumerate(users):
            record, _ = wait_for(
                lambda: collection.find_by(name=new[index]["name"]) or False,
                num_sec=180,
                delay=10,
            )
            user.reload()
            assert record[0].id == edited[index].id == user.id
            assert record[0].name == edited[index].name == user.name
Ejemplo n.º 40
0
def test_edit_region(temp_appliance_preconfig_funcscope, from_detail):
    """
    Bugzilla:
        1805844

    Polarion:
        assignee: pvala
        casecomponent: Configuration
        caseimportance: medium
        initialEstimate: 1/10h
    """
    appliance = temp_appliance_preconfig_funcscope
    ui_region = appliance.server.zone.region
    view = navigate_to(ui_region, "Details")
    payload = {
        "description":
        fauxfactory.gen_alpha(start=f"Edited {ui_region.region_string} ",
                              length=20)
    }
    expected_title = f'CFME Region "{payload["description"]} [{ui_region.number}]"'
    currently_selected = f'CFME Region: {payload["description"]} [{ui_region.number}]'

    region = ui_region.rest_api_entity
    if from_detail:
        region.action.edit(**payload)
    else:
        payload.update(region._ref_repr())
        appliance.rest_api.collections.regions.action.edit(payload)

    assert_response(appliance)
    wait_for(lambda: region.description == payload["description"],
             fail_func=region.reload,
             timeout=30)
    wait_for(lambda: view.title.text == expected_title,
             fail_func=view.browser.refresh,
             timeout=800)
    assert currently_selected in view.accordions.settings.tree.currently_selected
Ejemplo n.º 41
0
    def create_rest(self):
        """Create the config manager in CFME using REST"""
        include_ssl = False
        if self.type == "ansible_tower":
            config_type = "AnsibleTower"
        else:
            config_type = "Foreman"
            include_ssl = True

        payload = {
            "type": f"ManageIQ::Providers::{config_type}::Provider",
            "url": self.url,
            "name": self.name,
            "credentials": {
                "userid": self.credentials.view_value_mapping["username"],
                "password": self.credentials.view_value_mapping["password"],
            },
        }

        if include_ssl:
            payload["verify_ssl"] = self.ssl

        try:
            self.appliance.rest_api.post(
                api_endpoint_url=self.appliance.url_path(
                    "/api/providers/?provider_class=provider"),
                **payload)
        except APIException as err:
            raise AssertionError(f"Provider wasn't added: {err}")

        response = self.appliance.rest_api.response
        if not response:
            raise AssertionError(
                f"Provider wasn't added, status code {response.status_code}")

        assert_response(self.appliance)
        return True
Ejemplo n.º 42
0
def test_associate_unassigned_buttons_rest(appliance, group_rest,
                                           buttons_rest):
    """Test associate unassigned button with group

    Bugzilla:
        1737449
        1745198

    Polarion:
        assignee: ndhandre
        initialEstimate: 1/4h
        caseimportance: medium
        startsin: 5.10
        casecomponent: CustomButton
        tags: custom_button
    """

    # Add associate unassigned buttons to group with rest
    set_data = group_rest.set_data
    set_data["button_order"] = [int(b.id) for b in buttons_rest]
    data = {"set_data": set_data}
    group_rest.action.edit(**data)
    assert_response(appliance)

    # Check association with UI
    group_collection = appliance.collections.button_groups
    gp = group_collection.ENTITY.from_id(group_collection, group_rest.id)

    # Point to new object type so that teardown button(removed with rest) and new buttons, group
    # (created with rest) reflect on UI without any selenium exception.
    view = navigate_to(gp, "ObjectType")
    view.browser.refresh()

    view = navigate_to(gp, "Details")
    ui_assinged_btns = {btn["Text"].text for btn in view.assigned_buttons}

    assert ui_assinged_btns == {btn.name for btn in buttons_rest}
    def test_edit_multiple_service_catalogs(self, appliance, service_catalogs):
        """Tests editing multiple service catalogs at time.
        Prerequisities:
            * An appliance with ``/api`` available.
        Steps:
            * POST /api/service_catalogs (method ``edit``)
                with the list of dictionaries used to edit
            * Check if the service_catalogs with ``new_name`` each exist
        Metadata:
            test_flag: rest

        Polarion:
            assignee: nansari
            caseimportance: low
            initialEstimate: 1/3h
            casecomponent: Services
            tags: service
        """

        new_names = []
        scls_data_edited = []
        for scl in service_catalogs:
            new_name = fauxfactory.gen_alphanumeric()
            new_names.append(new_name)
            scls_data_edited.append({
                "href": scl.href,
                "name": new_name,
            })
        response = appliance.rest_api.collections.service_catalogs.action.edit(
            *scls_data_edited)
        assert_response(appliance)
        assert len(response) == len(new_names)
        for index, resource in enumerate(response):
            assert resource.name == new_names[index]
            scl = service_catalogs[index]
            scl.reload()
            assert scl.name == new_names[index]
Ejemplo n.º 44
0
    def test_edit_conditions(self, conditions, appliance, from_detail):
        """Tests edit conditions.

        Metadata:
            test_flag: rest

        Polarion:
            assignee: pvala
            casecomponent: Control
            caseimportance: low
            initialEstimate: 1/4h
        """
        num_conditions = len(conditions)
        uniq = [fauxfactory.gen_alphanumeric(5) for _ in range(num_conditions)]
        new = [{'description': f'Edited Test Condition {u}'} for u in uniq]
        if from_detail:
            edited = []
            for index in range(num_conditions):
                edited.append(conditions[index].action.edit(**new[index]))
                assert_response(appliance)
        else:
            for index in range(num_conditions):
                new[index].update(conditions[index]._ref_repr())
            edited = appliance.rest_api.collections.conditions.action.edit(
                *new)
            assert_response(appliance)
        assert len(edited) == num_conditions
        for index, condition in enumerate(conditions):
            record, __ = wait_for(
                lambda: appliance.rest_api.collections.conditions.find_by(
                    description=new[index]['description']) or False,
                num_sec=100,
                delay=5,
                message="Find a test condition")
            condition.reload()
            assert condition.description == edited[
                index].description == record[0].description
Ejemplo n.º 45
0
    def test_edit_policies(self, policies, appliance, from_detail):
        """Tests edit policies.

        Testing BZ 1435777

        Metadata:
            test_flag: rest

        Polarion:
            assignee: pvala
            caseimportance: low
            initialEstimate: 1/4h
        """
        num_policies = len(policies)
        uniq = [fauxfactory.gen_alphanumeric(5) for _ in range(num_policies)]
        new = [{'description': 'Edited Test Policy {}'.format(u)} for u in uniq]
        if from_detail:
            edited = []
            for index in range(num_policies):
                edited.append(policies[index].action.edit(**new[index]))
                assert_response(appliance)
        else:
            for index in range(num_policies):
                new[index].update(policies[index]._ref_repr())
            edited = appliance.rest_api.collections.policies.action.edit(*new)
            assert_response(appliance)
        assert len(edited) == num_policies
        for index, policy in enumerate(policies):
            record, __ = wait_for(
                lambda: appliance.rest_api.collections.policies.find_by(
                    description=new[index]['description']) or False,
                num_sec=100,
                delay=5,
                message="Find a policy"
            )
            policy.reload()
            assert policy.description == edited[index].description == record[0].description
Ejemplo n.º 46
0
    def test_bulk_assign_and_unassign_invalid_tag(self, appliance,
                                                  services_mod, vm,
                                                  collection_name, users):
        """Tests bulk assigning and unassigning invalid tags.

        Metadata:
            test_flag: rest

        Polarion:
            assignee: pvala
            casecomponent: Configuration
            caseimportance: high
            initialEstimate: 1/5h
        """
        collection = getattr(appliance.rest_api.collections, collection_name)
        collection.reload()
        entities = collection.all[-2:]

        new_tags = ['invalid_tag1', 'invalid_tag2']
        tags_count = len(new_tags) * len(entities)
        tags_per_entities_count = []
        for entity in entities:
            entity.tags.reload()
            tags_per_entities_count.append(entity.tags.subcount)

        def _check_tags_counts():
            for index, entity in enumerate(entities):
                entity.tags.reload()
                assert entity.tags.subcount == tags_per_entities_count[index]

        collection.action.assign_tags(*entities, tags=new_tags)
        assert_response(appliance, success=False, results_num=tags_count)
        _check_tags_counts()

        collection.action.unassign_tags(*entities, tags=new_tags)
        assert_response(appliance, success=False, results_num=tags_count)
        _check_tags_counts()
    def test_soft_reboot(self, provider, testing_instance, soft_assert,
                         ensure_vm_running, appliance, from_detail):
        """ Tests instance soft reboot

        Metadata:
            test_flag: power_control, provision, rest

        Polarion:
            assignee: pvala
            casecomponent: Cloud
            caseimportance: high
            initialEstimate: 1/4h
        """
        testing_instance.wait_for_power_state_change_rest(
            desired_state=testing_instance.STATE_ON)
        vm = testing_instance.rest_api_entity
        state_change_time = vm.state_changed_on
        if from_detail:
            vm.action.reboot_guest()
        else:
            appliance.rest_api.collections.instances.action.reboot_guest(vm)
        assert_response(appliance.rest_api)

        # On some providers the VM never actually shuts off, on others it might
        # We may also miss a quick reboot during the wait_for.
        # Just check for when the state last changed
        wait_for_power_state_refresh(testing_instance, state_change_time)
        state_change_time = testing_instance.rest_api_entity.state_changed_on
        # If the VM is not on after this state change, wait for another
        if vm.power_state != testing_instance.STATE_ON:
            wait_for_power_state_refresh(testing_instance, state_change_time)

        # assert and wait until the power state change is reflected in REST
        assert testing_instance.wait_for_power_state_change_rest(
            desired_state=testing_instance.STATE_ON)
        # check if the power state change is reflected on UI and provider
        wait_for_instance_state(soft_assert, testing_instance, state="started")
Ejemplo n.º 48
0
def test_provision(request, appliance, provider, provision_data):
    """Tests provision via REST API.
    Prerequisities:
        * Have a provider set up with templates suitable for provisioning.
    Steps:
        * POST /api/provision_requests (method ``create``) the JSON with provisioning data. The
            request is returned.
        * Query the request by its id until the state turns to ``finished`` or ``provisioned``.
    Metadata:
        test_flag: rest, provision
    """
    vm_name = provision_data['vm_fields']['vm_name']
    request.addfinalizer(lambda: clean_vm(appliance, provider, vm_name))
    appliance.rest_api.collections.provision_requests.action.create(
        **provision_data)
    assert_response(appliance)
    provision_request = appliance.collections.requests.instantiate(
        description=vm_name, partial_check=True)
    provision_request.wait_for_request()
    msg = "Provisioning failed with the message {}".format(
        provision_request.rest.message)
    assert provision_request.is_succeeded(), msg
    found_vms = appliance.rest_api.collections.vms.find_by(name=vm_name)
    assert found_vms, 'VM `{}` not found'.format(vm_name)
Ejemplo n.º 49
0
def vm_snapshot(appliance, collection, vm_obj):
    """Creates VM/instance snapshot using REST API

    Returns:
        Tuple with VM and snapshot resources in REST API
    """
    uid = fauxfactory.gen_alphanumeric(8)
    snap_name = 'snpshot_{}'.format(uid)
    vm = collection.get(name=vm_obj.name)
    vm.snapshots.action.create(name=snap_name,
                               description='snapshot {}'.format(uid),
                               memory=False)
    assert_response(appliance)
    snap, __ = wait_for(lambda: vm.snapshots.find_by(name=snap_name) or False,
                        num_sec=600,
                        delay=5)
    snap = snap[0]

    yield vm, snap

    collection.reload()
    to_delete = vm.snapshots.find_by(name=snap_name)
    if to_delete:
        vm.snapshots.action.delete(to_delete[0])
def test_container_provider_crud_rest(appliance, has_no_providers, provider):
    """
    Test
    Polarion:
        assignee: pvala
        caseimportance: critical
        casecomponent: Containers
        initialEstimate: 1/6h
    """
    provider.create_rest()
    provider_rest = appliance.rest_api.collections.providers.get(
        name=provider.name)
    assert provider_rest.type == "ManageIQ::Providers::Openshift::ContainerManager"

    new_name = fauxfactory.gen_alphanumeric()
    edited = provider_rest.action.edit(name=new_name)
    assert_response(appliance)
    provider_rest.reload()
    assert provider_rest.name == new_name == edited.name

    provider_rest.action.delete()
    provider_rest.wait_not_exists()

    assert not provider_rest.exists
Ejemplo n.º 51
0
    def test_edit_repository(self, appliance, repository, from_collection):
        """Tests editing repositories using REST API.

        Metadata:
            test_flag: rest

        Polarion:
            assignee: pvala
            casecomponent: Ansible
            caseimportance: medium
            initialEstimate: 1/4h
            endsin: 5.10
        """
        new_description = "Test Repository {}".format(
            fauxfactory.gen_alphanumeric(5))

        if from_collection:
            repository.reload()
            repository_data_edited = {
                "href": repository.href,
                "description": new_description,
            }
            appliance.rest_api.collections.configuration_script_sources.action.edit(
                repository_data_edited)
        else:
            repository.action.edit(description=new_description)

        assert_response(appliance)
        record, __ = wait_for(
            lambda: appliance.rest_api.collections.configuration_script_sources
            .find_by(description=new_description) or False,
            num_sec=180,
            delay=10,
        )
        repository.reload()
        assert repository.description == record[0].description
Ejemplo n.º 52
0
    def test_edit_arbitration_settings(self, appliance, arbitration_settings, from_detail):
        """Tests edit arbitration settings.

        Metadata:
            test_flag: rest
        """
        num_settings = len(arbitration_settings)
        uniq = [fauxfactory.gen_alphanumeric(5) for _ in range(num_settings)]
        new = [{'name': 'test_edit{}'.format(u), 'display_name': 'Test Edit{}'.format(u)}
               for u in uniq]
        if from_detail:
            edited = []
            for i in range(num_settings):
                edited.append(arbitration_settings[i].action.edit(**new[i]))
                assert_response(appliance)
        else:
            for i in range(num_settings):
                new[i].update(arbitration_settings[i]._ref_repr())
            edited = appliance.rest_api.collections.arbitration_settings.action.edit(*new)
            assert_response(appliance)
        assert len(edited) == num_settings
        for i in range(num_settings):
            assert (edited[i].name == new[i]['name'] and
                    edited[i].display_name == new[i]['display_name'])
Ejemplo n.º 53
0
    def test_vm_set_ownership(self, appliance, vm):
        """Tests set_ownership action from detail.

        Metadata:
            test_flag: rest

        Polarion:
            assignee: pvala
            casecomponent: Rest
            caseimportance: high
            initialEstimate: 1/3h
        """
        if "set_ownership" not in appliance.rest_api.collections.services.action.all:
            pytest.skip(
                "Set owner action for service is not implemented in this version"
            )
        rest_vm = appliance.rest_api.collections.vms.get(name=vm)
        user = appliance.rest_api.collections.users.get(userid='admin')
        data = {"owner": {"href": user.href}}
        rest_vm.action.set_ownership(**data)
        assert_response(appliance)
        rest_vm.reload()
        assert hasattr(rest_vm, "evm_owner_id")
        assert rest_vm.evm_owner_id == user.id
Ejemplo n.º 54
0
    def test_assign_and_unassign_tag(self, appliance, tags_mod, provider,
                                     services_mod, service_templates, tenants,
                                     vm, collection_name, users):
        """Tests assigning and unassigning tags.

        Metadata:
            test_flag: rest

        Polarion:
            assignee: pvala
            casecomponent: Configuration
            caseimportance: high
            initialEstimate: 1/5h
        """
        collection = getattr(appliance.rest_api.collections, collection_name)
        collection.reload()
        if not collection.all:
            pytest.skip(
                f"No available entity in {collection_name} to assign tag")
        entity = collection[-1]
        tag = tags_mod[0]
        try:
            entity.tags.action.assign(tag)
        except AttributeError:
            msg = (
                'Missing tag attribute in parametrized REST collection {} for entity: {}'
                .format(collection_name, entity))
            logger.exception(msg)
            pytest.fail(msg)
        assert_response(appliance)
        entity.reload()
        assert tag.id in [t.id for t in entity.tags.all]
        entity.tags.action.unassign(tag)
        assert_response(appliance)
        entity.reload()
        assert tag.id not in [t.id for t in entity.tags.all]
Ejemplo n.º 55
0
def vm_snapshot(request, appliance, collection, vm):
    """Creates VM/instance snapshot using REST API.

    Returns:
        Tuple with VM and snapshot resources in REST API
    """
    uid = fauxfactory.gen_alphanumeric(8)
    snap_desc = 'snapshot {}'.format(uid)
    request.addfinalizer(lambda: _delete_snapshot(vm, snap_desc))
    vm.snapshots.action.create(
        name='test_snapshot_{}'.format(uid),
        description=snap_desc,
        memory=False,
    )
    assert_response(appliance)
    snap, __ = wait_for(
        lambda: vm.snapshots.find_by(description=snap_desc) or False,
        num_sec=800,
        delay=5,
        message='snapshot creation',
    )
    snap = snap[0]

    return vm, snap
Ejemplo n.º 56
0
    def test_bad_section_add(self, request, collection_name, appliance,
                             get_resource):
        """Test adding custom attributes with invalid section to resource using REST API.

        Metadata:
            test_flag: rest

        Polarion:
            assignee: pvala
            casecomponent: Rest
            caseimportance: medium
            initialEstimate: 1/4h
        """
        resource = get_resource[collection_name]()
        add_custom_attributes(request, resource)
        uid = fauxfactory.gen_alphanumeric(5)
        body = {
            'name': f'ca_name_{uid}',
            'value': f'ca_value_{uid}',
            'section': 'bad_section'
        }
        with pytest.raises(Exception, match='Api::BadRequestError'):
            resource.custom_attributes.action.add(body)
        assert_response(appliance, http_status=400)
Ejemplo n.º 57
0
def test_vm_scan(appliance, vm, from_detail):
    """Tests running VM scan using REST API.

    Metadata:
        test_flag: rest

    Polarion:
        assignee: pvala
        casecomponent: Rest
        caseimportance: high
        initialEstimate: 1/3h
    """
    if from_detail:
        response = vm.action.scan()
    else:
        response, = appliance.rest_api.collections.vms.action.scan(vm)
    assert_response(appliance)

    @wait_for_decorator(timeout='5m', delay=5, message='REST running VM scan finishes')
    def _finished():
        response.task.reload()
        if 'error' in response.task.status.lower():
            pytest.fail('Error when running scan vm method: `{}`'.format(response.task.message))
        return response.task.state.lower() == 'finished'
    def test_edit_service_catalog(self, appliance, service_catalogs):
        """Tests editing a service catalog via rest.
        Prerequisities:
            * An appliance with ``/api`` available.
        Steps:
            * POST /api/service_catalogs/<id>/ (method ``edit``) with the ``name``
            * Check if the service_catalog with ``new_name`` exists
        Metadata:
            test_flag: rest

        Polarion:
            assignee: nansari
            caseimportance: low
            casecomponent: Services
            initialEstimate: 1/3h
            tags: service
        """
        for ctl in service_catalogs:
            new_name = fauxfactory.gen_alphanumeric()
            response = ctl.action.edit(name=new_name)
            assert_response(appliance)
            assert response.name == new_name
            ctl.reload()
            assert ctl.name == new_name
Ejemplo n.º 59
0
def test_edit_provider_request_task(appliance, request, provider,
                                    request_task):
    """
    Polarion:
        assignee: pvala
        caseimportance: medium
        initialEstimate: 1/4h
        casecomponent: Rest
        setup:
            1. Create a provision request.
        testSteps:
            1. Edit the provision request task:
                POST /api/provision_requests/:id/request_tasks/:request_task_id
                {
                "action" : "edit",
                "resource" : {
                    "options" : {
                    "request_param_a" : "value_a",
                    "request_param_b" : "value_b"
                    }
                }
                }
        expectedResults:
            1. Task must be edited successfully.
    """
    # edit the request_task by adding new elements
    request_task.action.edit(options={
        "request_param_a": "value_a",
        "request_param_b": "value_b"
    })
    assert_response(appliance)

    # assert the presence of newly added elements
    request_task.reload()
    assert request_task.options["request_param_a"] == "value_a"
    assert request_task.options["request_param_b"] == "value_b"
Ejemplo n.º 60
0
def add_custom_attributes(request, resource):
    body = []
    attrs_num = 2
    for __ in range(attrs_num):
        uid = fauxfactory.gen_alphanumeric(5)
        body.append({
            'name': 'ca_name_{}'.format(uid),
            'value': 'ca_value_{}'.format(uid)
        })
    attrs = resource.custom_attributes.action.add(*body)

    @request.addfinalizer
    def _delete():
        resource.custom_attributes.reload()
        ids = [attr.id for attr in attrs]
        delete_attrs = [
            attr for attr in resource.custom_attributes if attr.id in ids
        ]
        if delete_attrs:
            resource.custom_attributes.action.delete(*delete_attrs)

    assert_response(resource.collection._api)
    assert len(attrs) == attrs_num
    return attrs