def give_user_permission(self, perm_name):
        """Give ``self.user`` the ``perm_name`` permission.

        This method creates a role and filter to accomplish the above goal.
        When complete, the relevant relationhips look like this:

            user -> role <- filter -> permission

        :param str perm_name: The name of a permission. For example:
            'create_architectures'.
        :raises: ``AssertionError`` if more than one permission is found when
            searching for the permission with name ``perm_name``.
        :raises: ``requests.exceptions.HTTPError`` if an error occurs when
            updating ``self.user``'s roles.
        :rtype: None

        """
        role_id = entities.Role().create()['id']
        permission_ids = [
            permission['id']
            for permission
            in entities.Permission(name=perm_name).search()
        ]
        self.assertEqual(len(permission_ids), 1)
        entities.Filter(permission=permission_ids, role=role_id).create()
        # NOTE: An extra hash is used due to an API bug.
        client.put(
            self.user.path(),
            {u'user': {u'role_ids': [role_id]}},
            auth=get_server_credentials(),
            verify=False,
        ).raise_for_status()
    def test_update(self, entity):
        """@Test: Check whether the "edit_*" role has an effect.

        @Assert: A user cannot update an entity when missing the "edit_*" role,
        and they can update an entity when given the "edit_*" role.

        @Feature: Role

        NOTE: This method will only work if ``entity`` has a name.

        """
        entity_obj = entity(id=entity().create()['id'])
        with self.assertRaises(HTTPError):
            client.put(
                entity_obj.path(),
                {u'name': entity.name.get_value()},
                auth=self.auth,
                verify=False,
            ).raise_for_status()
        self.give_user_permission(_permission_name(entity, 'update'))
        client.put(
            entity_obj.path(),
            {u'name': entity.name.get_value()},
            auth=self.auth,
            verify=False,
        ).raise_for_status()
    def test_update_gpgkey(self):
        """@Test: Create a repository and update its GPGKey

        @Assert: The updated repository points to a new GPG key.

        @Feature: Repository

        """
        # Create a repo and make it point to a GPG key.
        key_1_id = entities.GPGKey(
            content=read_data_file(VALID_GPG_KEY_FILE),
            organization=self.org_id,
        ).create()['id']
        repo_id = entities.Repository(
            gpg_key=key_1_id,
            product=self.prod_id,
        ).create()['id']

        # Update the repo and make it point to a new GPG key.
        key_2_id = entities.GPGKey(
            content=read_data_file(VALID_GPG_KEY_BETA_FILE),
            organization=self.org_id,
        ).create()['id']
        client.put(
            entities.Repository(id=repo_id).path(),
            {u'gpg_key_id': key_2_id},
            auth=get_server_credentials(),
            verify=False,
        ).raise_for_status()

        # Verify the repository's attributes.
        attrs = entities.Repository(id=repo_id).read_json()
        self.assertEqual(attrs['gpg_key_id'], key_2_id)
Example #4
0
    def test_put_and_get(self):
        """@Test: Issue a PUT request and GET the updated system.

        @Assert: The updated system has the correct attributes.

        """
        path = System(uuid=System().create()['uuid']).path()

        # Generate some attributes and use them to update a system.
        gen_attrs = System().attributes()
        response = client.put(
            path,
            gen_attrs,
            auth=get_server_credentials(),
            verify=False,
        )
        self.assertEqual(response.status_code, httplib.OK, path)

        # Get the just-updated system and examine its attributes.
        real_attrs = client.get(
            path,
            auth=get_server_credentials(),
            verify=False,
        ).json()
        for key, value in gen_attrs.items():
            self.assertIn(key, real_attrs.keys(), path)
            self.assertEqual(
                value, real_attrs[key], '{0} {1}'.format(key, path)
            )
Example #5
0
    def test_put_and_get(self, entity):
        """@Test: Issue a PUT request and GET the updated entity.

        @Assert: The updated entity has the correct attributes.

        """
        if entity is entities.AuthSourceLDAP and bz_bug_is_open(1140313):
            self.skipTest("Bugzilla bug 1140313 is open.""")

        # Create an entity.
        entity_n = entity(id=entity().create()['id'])
        logger.info('test_put_and_get path: {0}'.format(entity_n.path()))

        # Generate some attributes and use them to update an entity.
        gen_attrs = entity().attributes()
        response = client.put(
            entity_n.path(),
            gen_attrs,
            auth=get_server_credentials(),
            verify=False,
        )
        response.raise_for_status()

        # Get the just-updated entity and examine its attributes.
        real_attrs = entity_n.read_json()
        for key, value in gen_attrs.items():
            self.assertIn(key, real_attrs.keys())
            self.assertEqual(value, real_attrs[key], key)
Example #6
0
    def test_positive_update_3(self):
        """@Test: Create a repository and update its GPGKey

        @Feature: Repositories

        @Assert: Repository is updated with new GPGkey

        """
        key_1_content = read_data_file(VALID_GPG_KEY_FILE)
        key_2_content = read_data_file(VALID_GPG_KEY_BETA_FILE)

        # Create an organization and product
        org_attrs = entities.Organization().create()
        product_attrs = entities.Product(
            organization=org_attrs['id']
        ).create()

        gpgkey_1_attrs = entities.GPGKey(
            content=key_1_content,
            organization=org_attrs['id']
        ).create()

        gpgkey_2_attrs = entities.GPGKey(
            content=key_2_content,
            organization=org_attrs['id']
        ).create()

        # Creates new repository
        repository_attrs = entities.Repository(
            url=FAKE_1_YUM_REPO,
            product=product_attrs['id'],
            gpg_key=gpgkey_1_attrs['id'],
        ).create()

        path = entities.Repository(id=repository_attrs['id']).path()

        repository_copy = copy.deepcopy(repository_attrs)
        repository_copy['gpg_key_id'] = gpgkey_2_attrs['id']

        response = client.put(
            path,
            repository_copy,
            auth=get_server_credentials(),
            verify=False,
        )
        status_code = httplib.OK
        self.assertEqual(
            response.status_code,
            status_code,
            status_code_error(path, status_code, response),
        )
        # Fetch the updated repository
        updated_attrs = entities.Repository(
            id=repository_attrs['id']
        ).read_json()
        # Assert that key is updated
        self.assertEqual(
            updated_attrs['gpg_key_id'],
            gpgkey_2_attrs['id'],
        )
    def test_update_max_content_hosts(self):
        """@Test: Create an activation key with ``max_content_hosts == 1``,
        then update that field with a string value.

        @Feature: ActivationKey

        @Assert: The update fails with an HTTP 422 return code.

        """
        attrs = entities.ActivationKey(max_content_hosts=1).create()
        path = entities.ActivationKey(id=attrs['id']).path()
        new_attrs = attrs.copy()
        new_attrs['max_content_hosts'] = 'foo'
        response = client.put(
            path,
            new_attrs,
            auth=get_server_credentials(),
            verify=False,
        )
        self.assertEqual(
            response.status_code,
            httplib.UNPROCESSABLE_ENTITY,
            status_code_error(path, httplib.UNPROCESSABLE_ENTITY, response),
        )

        # Status code is OK. Was `max_content_hosts` changed, or is it still 1?
        response = entities.ActivationKey(id=attrs['id']).read_json()
        self.assertEqual(response['max_content_hosts'], 1)
Example #8
0
    def test_positive_update_1(self, name_generator):
        """@Test: Update a role with and give a name of ``name_generator()``.

        @Feature: Role

        @Assert: The role is updated with the given name.

        """
        if decorators.bz_bug_is_open(1112657) and (
                name_generator is gen_cjk or
                name_generator is gen_latin1 or
                name_generator is gen_utf8):
            self.skipTest('Bugzilla bug 1112657 is open.')
        try:
            role_id = entities.Role().create()['id']
        except HTTPError as err:
            self.fail(err)  # fail instead of error

        role = entities.Role(id=role_id)
        name = name_generator()
        response = client.put(
            role.path(),
            {u'name': name},
            auth=get_server_credentials(),
            verify=False,
        )
        response.raise_for_status()
        self.assertEqual(role.read_json()['name'], name)
Example #9
0
    def create_cv(self, name, env_name):
        """Create product/repo and sync it and promote to given env"""

        repo_name = generate_string("alpha", 8)

        # Creates new product and repository via API's
        product_attrs = entities.Product(
            organization=self.org_id
        ).create()
        repo_attrs = entities.Repository(
            name=repo_name,
            url=FAKE_1_YUM_REPO,
            product=product_attrs['id'],
        ).create()

        # Sync repository
        response = entities.Repository(id=repo_attrs['id']).sync()
        task_status = entities.ForemanTask(id=response['id']).poll()
        self.assertEqual(
            task_status['result'],
            u'success',
            u"Sync for repository {0} failed.".format(repo_attrs['name']))

        # Create Life-Cycle content environment
        env_attrs = entities.LifecycleEnvironment(
            name=env_name,
            organization=self.org_id
        ).create()

        # Create content view(CV)
        content_view = entities.ContentView(
            name=name,
            organization=self.org_id
        ).create()
        # Associate YUM repo to created CV
        response = client.put(
            entities.ContentView(id=content_view['id']).path(),
            auth=get_server_credentials(),
            verify=False,
            data={u'repository_ids': [repo_attrs['id']]})

        # Publish content view
        task = entities.ContentView(id=content_view['id']).publish()
        task_status = entities.ForemanTask(id=task['id']).poll()
        self.assertEqual(
            task_status['result'],
            u'success',
            u"Publishing {0} failed.".format(content_view['name']))
        # Promote the Version 1 to selected environment
        content_view = entities.ContentView(id=content_view['id']).read_json()
        task = entities.ContentViewVersion(
            id=content_view['versions'][0]['id']).promote(env_attrs['id'])
        task_status = entities.ForemanTask(id=task['id']).poll()
        self.assertEqual(
            task_status['result'],
            u'success',
            u"Promoting {0} to {1} failed.".format(
                content_view['name'], env_attrs['name']))
        return product_attrs['name']
Example #10
0
    def test_positive_update_1(self, attrs):
        """@Test: Update a product with a new name or description.

        @Assert: The given attributes are used.

        @Feature: Product

        """
        client.put(
            self.product_n.path(),
            attrs,
            auth=get_server_credentials(),
            verify=False,
        ).raise_for_status()
        new_attrs = self.product_n.read_json()
        for name, value in attrs.items():
            self.assertIn(name, new_attrs.keys())
            self.assertEqual(value, new_attrs[name])
Example #11
0
    def test_negative_update_1(self, max_content_hosts):
        """@Test: Create activation key then update its limit to invalid value.

        @Assert:
        1. Activation key is created
        2. Update fails
        3. Record is not changed

        @Feature: ActivationKey

        """
        try:
            attrs = entities.ActivationKey().create()
        except FactoryError as err:
            self.fail(err)
        path = entities.ActivationKey(id=attrs['id']).path()

        # Make a copy of the activation key and update a few fields.
        ak_copy = attrs.copy()
        ak_copy['unlimited_content_hosts'] = False
        ak_copy['max_content_hosts'] = max_content_hosts

        # Update the activation key with semantically incorrect values.
        response = client.put(
            path,
            ak_copy,
            auth=get_server_credentials(),
            verify=False,
        )
        self.assertEqual(
            response.status_code,
            httplib.UNPROCESSABLE_ENTITY,
            status_code_error(path, httplib.UNPROCESSABLE_ENTITY, response),
        )

        # Fetch the activation key. Assert that values have not changed.
        real_attrs = entities.ActivationKey(id=attrs['id']).read_json()
        self.assertEqual(
            real_attrs['unlimited_content_hosts'],
            attrs['unlimited_content_hosts'],
            u"Unlimited content hosts values: {0} == {1}".format(
                real_attrs['unlimited_content_hosts'],
                attrs['unlimited_content_hosts'])
        )
        self.assertTrue(
            real_attrs['unlimited_content_hosts'],
            u"Unlimited content hosts is {0}".format(
                real_attrs['unlimited_content_hosts']
            )
        )
        self.assertEqual(
            real_attrs['max_content_hosts'],
            attrs['max_content_hosts'],
            u"Max content hosts values: {0} == {1}".format(
                real_attrs['max_content_hosts'],
                attrs['max_content_hosts'])
        )
    def test_update(self, attrs):
        """@Test: Create a repository and update its attributes.

        @Assert: The repository's attributes are updated.

        @Feature: Repository

        """
        client.put(
            self.repository.path(),
            attrs,
            auth=get_server_credentials(),
            verify=False,
        ).raise_for_status()
        real_attrs = self.repository.read_json()
        for name, value in attrs.items():
            self.assertIn(name, real_attrs.keys())
            self.assertEqual(value, real_attrs[name])
Example #13
0
    def test_positive_update(self, attrs):
        """@Test: Update an organization's attributes with valid values.

        @Assert: The organization's attributes are updated.

        @Feature: Organization

        """
        client.put(
            self.organization.path(),
            attrs,
            verify=False,
            auth=get_server_credentials(),
        ).raise_for_status()

        # Read the organization and validate its attributes.
        new_attrs = self.organization.read_json()
        for name, value in attrs.items():
            self.assertIn(name, new_attrs.keys())
            self.assertEqual(new_attrs[name], value)
    def test_positive_update(self, attrs):
        """@Test: Update a content view and provide valid attributes.

        @Assert: The update succeeds.

        @Feature: ContentView

        """
        client.put(
            self.content_view.path(),
            attrs,
            auth=get_server_credentials(),
            verify=False,
        ).raise_for_status()

        # Read the content view and validate its attributes.
        new_attrs = self.content_view.read_json()
        for name, value in attrs.items():
            self.assertIn(name, new_attrs.keys())
            self.assertEqual(new_attrs[name], value)
Example #15
0
    def test_positive_update_1(self, name):
        """@Test: Create a product and update its name

        @Feature: Products

        @Assert: Product name has been updated

        """
        # Create a product and update its name.
        prod_id = entities.Product().create()['id']
        client.put(
            entities.Product(id=prod_id).path(),
            {u'name': name},
            auth=get_server_credentials(),
            verify=False,
        ).raise_for_status()

        # Fetch the updated product and assert that name has been updated.
        prod_attrs = entities.Product(id=prod_id).read_json()
        self.assertEqual(prod_attrs['name'], name)
    def test_put_and_get(self, entity_cls):
        """@Test: Issue a PUT request and GET the updated entity.

        @Assert: The updated entity has the correct attributes.

        """
        logger.debug('test_put_and_get arg: {0}'.format(entity_cls))
        skip_if_sam(self, entity_cls)
        if entity_cls in BZ_1154156_ENTITIES and bz_bug_is_open(1154156):
            self.skipTest("Bugzilla bug 1154156 is open.")

        # Create an entity.
        entity = entity_cls(id=entity_cls().create_json()['id'])

        # Update that entity.
        entity.create_missing()
        payload = entity.create_payload()  # FIXME: use entity.update_payload()
        response = client.put(
            entity.path(),
            payload,
            auth=get_server_credentials(),
            verify=False,
        )
        response.raise_for_status()

        # Drop the extra outer dict and sensitive params from `payload`.
        if len(payload.keys()) == 1 and isinstance(payload.values()[0], dict):
            payload = payload.values()[0]
        if isinstance(entity, entities.Host):
            del payload['root_pass']
            del payload['name']  # FIXME: "Foo" in, "foo.example.com" out.
        if issubclass(_get_partial_func(entity_cls), entities.User):
            del payload['password']

        # It is impossible to easily verify foreign keys.
        if bz_bug_is_open(1151240):
            for key in payload.keys():
                if key.endswith('_id') or key.endswith('_ids'):
                    del payload[key]
            if issubclass(
                    _get_partial_func(entity_cls),
                    entities.LifecycleEnvironment):
                del payload['prior']  # this foreign key is oddly named

        # Compare a trimmed-down `payload` against what the server has.
        attrs = entity.read_json()
        for key, value in payload.items():
            self.assertIn(key, attrs.keys())
            self.assertEqual(value, attrs[key], key)
Example #17
0
    def test_negative_update(self, attrs):
        """@Test: Update a content view and provide an invalid attribute.

        @Assert: The content view's attributes are not updated.

        @Feature: ContentView

        """
        response = client.put(
            self.content_view.path(),
            attrs,
            auth=get_server_credentials(),
            verify=False,
        )
        with self.assertRaises(HTTPError):
            response.raise_for_status()
Example #18
0
    def test_negative_update(self, attrs):
        """@Test: Update an organization's attributes with invalid values.

        @Assert: The organization's attributes are not updated.

        @Feature: Organization

        """
        response = client.put(
            self.organization.path(),
            attrs,
            verify=False,
            auth=get_server_credentials(),
        )
        with self.assertRaises(HTTPError):
            response.raise_for_status()
Example #19
0
    def test_put_status_code(self):
        """@Test Issue a PUT request and check the returned status code.

        @Assert: HTTP 200 is returned with an ``application/json`` content-type

        """
        system = System(uuid=System().create_json()['uuid'])
        logger.debug('system uuid: {0}'.format(system.uuid))
        system.create_missing()
        response = client.put(
            system.path(),
            system.create_payload(),
            auth=get_server_credentials(),
            verify=False,
        )
        self.assertEqual(httplib.OK, response.status_code)
        self.assertIn('application/json', response.headers['content-type'])
Example #20
0
    def test_positive_update_2(self):
        """@Test: Create a repository and update its URL

        @Feature: Repositories

        @Assert: Repository URL is updated

        """

        # Creates new repository
        repository_attrs = entities.Repository(
            url=FAKE_1_YUM_REPO,
        ).create()

        path = entities.Repository(id=repository_attrs['id']).path()

        repository_copy = copy.deepcopy(repository_attrs)
        repository_copy['url'] = FAKE_2_YUM_REPO

        response = client.put(
            path,
            repository_copy,
            auth=get_server_credentials(),
            verify=False,
        )
        status_code = httplib.OK
        self.assertEqual(
            response.status_code,
            status_code,
            status_code_error(path, status_code, response),
        )
        # Fetch the updated repository
        updated_attrs = entities.Repository(
            id=repository_attrs['id']
        ).read_json()
        # Assert that URL is updated
        self.assertNotEqual(
            updated_attrs['url'],
            repository_attrs['url'],
        )
        self.assertEqual(
            updated_attrs['url'],
            FAKE_2_YUM_REPO,
        )
    def test_negative_update_1(self, max_content_hosts):
        """@Test: Create activation key then update its limit to invalid value.

        @Assert:
        1. Activation key is created
        2. Update fails
        3. Record is not changed

        @Feature: ActivationKey

        """
        try:
            attrs = entities.ActivationKey().create()
        except HTTPError as err:
            self.fail(err)
        activationkey = entities.ActivationKey(id=attrs['id'])

        # Update the activation key with semantically incorrect values.
        response = client.put(
            activationkey.path(),
            {
                u'unlimited_content_hosts': False,
                u'max_content_hosts': max_content_hosts
            },
            auth=get_server_credentials(),
            verify=False,
        )
        self.assertEqual(
            response.status_code,
            httplib.UNPROCESSABLE_ENTITY,
            status_code_error(
                activationkey.path(),
                httplib.UNPROCESSABLE_ENTITY,
                response
            ),
        )

        # Make sure no attributes have changed.
        new_attrs = activationkey.read_json()
        for attr in ('unlimited_content_hosts', 'max_content_hosts'):
            self.assertEqual(attrs[attr], new_attrs[attr])
        self.assertTrue(new_attrs['unlimited_content_hosts'])
Example #22
0
    def test_put_status_code(self, entity):
        """@Test Issue a PUT request and check the returned status code.

        @Assert: HTTP 200 is returned with an ``application/json`` content-type

        """
        path = entity(id=entity().create()['id']).path()
        response = client.put(
            path,
            entity().attributes(),
            auth=get_server_credentials(),
            verify=False,
        )
        status_code = httplib.OK
        self.assertEqual(
            status_code,
            response.status_code,
            status_code_error(path, status_code, response),
        )
        self.assertIn('application/json', response.headers['content-type'])
    def test_negative_update_1(self, attrs):
        """@Test: Update a content view and provide an invalid attribute.

        @Assert: The content view's attributes are not updated.

        @Feature: ContentView

        """
        bug_id = attrs.pop('bz-bug', None)
        if bug_id is not None and bz_bug_is_open(bug_id):
            self.skipTest('Bugzilla bug {0} is open.'.format(bug_id))

        response = client.put(
            self.content_view.path(),
            attrs,
            auth=get_server_credentials(),
            verify=False,
        )
        with self.assertRaises(HTTPError):
            response.raise_for_status()
Example #24
0
    def test_positive_update_1(self, test_data):
        """@Test: Create a role and update its name

        @Feature: Role

        @Assert: Role name should be updated

        """
        try:
            role_attrs = entities.Role(name=test_data['name']).create()
        except factory.FactoryError as err:
            self.fail(err)  # fail instead of error

        path = entities.Role(id=role_attrs['id']).path()

        role_copy = role_attrs.copy()
        role_copy['name'] = test_data['new_name']

        response = client.put(
            path,
            role_copy,
            auth=get_server_credentials(),
            verify=False,
        )
        status_code = httplib.OK
        self.assertEqual(
            response.status_code,
            status_code,
            status_code_error(path, status_code, response),
        )
        # Fetch the updated role
        updated_attrs = client.get(
            path,
            auth=get_server_credentials(),
            verify=False,
        ).json()
        # Assert that values have changed
        self.assertNotEqual(
            updated_attrs['name'],
            role_attrs['name'],
        )
Example #25
0
    def test_positive_update_4(self):
        """@Test: Create a repository and update to publish it via HTTP

        @Feature: Repositories

        @Assert: Repository is updated with unprotected flag 'True'

        """

        repository_attrs = entities.Repository(
            url=FAKE_1_YUM_REPO,
        ).create()

        path = entities.Repository(id=repository_attrs['id']).path()

        repository_copy = copy.deepcopy(repository_attrs)
        repository_copy['unprotected'] = True

        response = client.put(
            path,
            repository_copy,
            auth=get_server_credentials(),
            verify=False,
        )
        status_code = httplib.OK
        self.assertEqual(
            response.status_code,
            status_code,
            status_code_error(path, status_code, response),
        )
        # Fetch the updated repository
        updated_attrs = entities.Repository(
            id=repository_attrs['id']
        ).read_json()

        # Assert that unprotected flag is updated
        self.assertEqual(
            updated_attrs['unprotected'],
            True,
        )
    def test_positive_update_1(self, max_content_hosts):
        """@Test: Create activation key then update it to limited content
        hosts.

        @Assert: Activation key is created, updated to limited content host

        @Feature: ActivationKey

        """
        # Create an activation key.
        try:
            activation_key = entities.ActivationKey(
                id=entities.ActivationKey().create()['id']
            )
        except HTTPError as err:
            self.fail(err)

        # Update the activation key.
        description = entities.ActivationKey.description.get_value()
        response = client.put(
            activation_key.path(),
            {
                'description': description,
                'max_content_hosts': max_content_hosts,
                'unlimited_content_hosts': False,
            },
            auth=get_server_credentials(),
            verify=False,
        )
        response.raise_for_status()

        # Fetch the activation key. Assert that values have been updated.
        real_attrs = activation_key.read_json()
        self.assertEqual(real_attrs['description'], description)
        self.assertEqual(real_attrs['max_content_hosts'], max_content_hosts)
        self.assertFalse(real_attrs['unlimited_content_hosts'])
    def test_put_status_code(self, entity_cls):
        """@Test Issue a PUT request and check the returned status code.

        @Assert: HTTP 200 is returned with an ``application/json`` content-type

        """
        logger.debug('test_put_status_code arg: {0}'.format(entity_cls))
        skip_if_sam(self, entity_cls)
        if entity_cls in BZ_1154156_ENTITIES and bz_bug_is_open(1154156):
            self.skipTest("Bugzilla bug 1154156 is open.")

        # Create an entity
        entity = entity_cls(id=entity_cls().create_json()['id'])

        # Update that entity.
        entity.create_missing()
        response = client.put(
            entity.path(),
            entity.create_payload(),  # FIXME: use entity.update_payload()
            auth=get_server_credentials(),
            verify=False,
        )
        self.assertEqual(httplib.OK, response.status_code)
        self.assertIn('application/json', response.headers['content-type'])
Example #28
0
    def test_put_and_get(self):
        """@Test: Issue a PUT request and GET the updated system.

        @Assert: The updated system has the correct attributes.

        """
        system = System(uuid=System().create_json()['uuid'])
        logger.debug('system uuid: {0}'.format(system.uuid))

        # Generate some attributes and use them to update `system`.
        system.create_missing()
        response = client.put(
            system.path(),
            system.create_payload(),
            auth=get_server_credentials(),
            verify=False,
        )
        self.assertEqual(response.status_code, httplib.OK)

        # Get the just-updated system and examine its attributes.
        attrs = system.read_json()
        for key, value in system.create_payload().items():
            self.assertIn(key, attrs.keys())
            self.assertEqual(value, attrs[key])
    def test_set_host_collection(self):
        """@Test: Associate an activation key with several host collections.

        @Assert:
        1. By default, an activation key is associated with no host
        collections.
        2. After associating an activation key with some set of host
        collections and reading that activation key, the correct host
        collections are listed.

        @Feature: ActivationKey

        """
        # Let's create an organization and re-use it in several places. Doing
        # so will speed up this test.
        org = entities.Organization().create()

        # By default, an activation key should have no host collections.
        act_key = entities.ActivationKey(organization=org['id']).create()
        self.assertEqual(act_key['host_collections'], [])

        # Associate our activation key with one host collection.
        host_coll_1 = entities.HostCollection(organization=org['id']).create()
        client.put(
            entities.ActivationKey(id=act_key['id']).path(),
            verify=False,
            auth=get_server_credentials(),
            data={u'host_collection_ids': [host_coll_1['id']]},
        )

        # Verify that the association succeeded.
        act_key = entities.ActivationKey(id=act_key['id']).read_json()
        self.assertEqual(len(act_key['host_collections']), 1)
        self.assertEqual(
            act_key['host_collections'][0]['id'],
            host_coll_1['id'],
        )

        # Associate our activation key with two host collections.
        host_coll_2 = entities.HostCollection(organization=org['id']).create()
        client.put(
            entities.ActivationKey(id=act_key['id']).path(),
            verify=False,
            auth=get_server_credentials(),
            data={
                u'host_collection_ids': [host_coll_1['id'], host_coll_2['id']]
            },
        )

        # Verify that the association succeeded.
        act_key = entities.ActivationKey(id=act_key['id']).read_json()
        self.assertEqual(len(act_key['host_collections']), 2)
        for host_coll in act_key['host_collections']:
            self.assertIn(
                host_coll['id'],
                (host_coll_1['id'], host_coll_2['id'])
            )

        # Finally, associate our activation key with zero host collections.
        client.put(
            entities.ActivationKey(id=act_key['id']).path(),
            verify=False,
            auth=get_server_credentials(),
            data={u'host_collection_ids': []},
        )

        # Verify that the association succeeded.
        act_key = entities.ActivationKey(id=act_key['id']).read_json()
        self.assertEqual(act_key['host_collections'], [])
    def create_cv(self, name, env_name, product_name=None, repo_name=None,
                  repo_url=None, repo_type=None, rh_repo=None):
        """Create product/repo and sync it and promote to given env"""
        if not rh_repo:
            product_name = product_name or gen_string("alpha", 8)
            repo_name = repo_name or gen_string("alpha", 8)
            # Creates new product and repository via API's
            product_attrs = entities.Product(
                name=product_name,
                organization=self.org_id
            ).create()
            repo_attrs = entities.Repository(
                name=repo_name,
                url=repo_url or FAKE_1_YUM_REPO,
                content_type=repo_type or REPO_TYPE['yum'],
                product=product_attrs['id'],
            ).create()
            repo_id = repo_attrs['id']
        else:
            # Upload manifest
            manifest_path = manifests.clone()
            task_result = entities.Organization(
                id=self.org_id
            ).upload_manifest(path=manifest_path)['result']
            self.assertEqual(u'success', task_result)
            # Enable RH repo and fetch repository_id
            repo_id = utils.enable_rhrepo_and_fetchid(
                rh_repo['basearch'],
                self.org_id,
                rh_repo['product'],
                rh_repo['name'],
                rh_repo['reposet'],
                rh_repo['releasever'])
            repo_name = rh_repo['name']
        # Sync repository
        task_result = entities.Repository(id=repo_id).sync()['result']
        self.assertEqual(
            task_result,
            u'success',
            u"Sync for repository {0} failed.".format(repo_name))

        # Create Life-Cycle content environment
        env_attrs = entities.LifecycleEnvironment(
            name=env_name,
            organization=self.org_id
        ).create()

        # Create content view(CV)
        content_view = entities.ContentView(
            name=name,
            organization=self.org_id
        )
        content_view.id = content_view.create()['id']

        # Associate YUM repo to created CV
        response = client.put(
            entities.ContentView(id=content_view.id).path(),
            auth=get_server_credentials(),
            verify=False,
            data={u'repository_ids': [repo_id]})
        response.raise_for_status()

        # Publish content view
        self.assertEqual(u'success', content_view.publish()['result'])

        # Get the content view version's ID.
        response = client.get(
            entities.ContentViewVersion().path(),
            auth=get_server_credentials(),
            data={u'content_view_id': content_view.id},
            verify=False,
        )
        response.raise_for_status()
        results = response.json()['results']
        self.assertEqual(len(results), 1)
        cv_version = entities.ContentViewVersion(id=results[0]['id'])

        # Promote the content view version.
        self.assertEqual(
            'success',
            cv_version.promote(environment_id=env_attrs['id'])['result']
        )