def setUp(self):
     """Create VMs, subscribe them to satellite-tools repo, install
     katello-ca and katello-agent packages, then create Host collection,
     associate it with previously created hosts.
     """
     super(HostCollectionPackageManagementTest, self).setUp()
     self.hosts = []
     for _ in range(self.hosts_number):
         client = VirtualMachine(distro=DISTRO_RHEL7)
         self.addCleanup(vm_cleanup, client)
         self.hosts.append(client)
         client.create()
         client.install_katello_ca()
         result = client.register_contenthost(
             self.session_org.label, self.activation_key.name)
         self.assertEqual(result.return_code, 0)
         client.enable_repo(REPOS['rhst7']['id'])
         client.install_katello_agent()
     host_ids = [
         entities.Host().search(query={
             'search': 'name={0}'.format(host.hostname)})[0].id
         for host in self.hosts
     ]
     self.host_collection = entities.HostCollection(
         host=host_ids,
         organization=self.session_org,
     ).create()
Example #2
0
    def test_destroy(self, ssh_command):
        """Check if destroy runs the required ssh commands"""
        self.configure_provisoning_server()
        image_dir = '/opt/robottelo/images'
        vm = VirtualMachine()

        with patch.multiple(
            vm,
            image_dir=image_dir,
            _created=True
        ):
            vm.destroy()

        self.assertEqual(ssh_command.call_count, 3)

        ssh_command_args_list = [
            call('virsh destroy {0}'.format(vm.hostname),
                 hostname=self.provisioning_server),
            call('virsh undefine {0}'.format(vm.hostname),
                 hostname=self.provisioning_server),
            call('rm {0}/{1}.img'.format(image_dir, vm.hostname),
                 hostname=self.provisioning_server),
        ]

        self.assertListEqual(ssh_command.call_args_list, ssh_command_args_list)
Example #3
0
def vm_content_hosts(request, module_loc, module_repos_collection):
    clients = []
    for _ in range(2):
        client = VirtualMachine(distro=module_repos_collection.distro)
        clients.append(client)
        request.addfinalizer(client.destroy)
        client.create()
        module_repos_collection.setup_virtual_machine(client)
        update_vm_host_location(client, module_loc.id)
    return clients
Example #4
0
    def test_dont_create_if_already_created(self, ssh_command, sleep):
        """Check if the creation steps does run more than one"""
        self.configure_provisoning_server()
        vm = VirtualMachine()

        with patch.multiple(vm, image_dir="/opt/robottelo/images", provisioning_server="provisioning.example.com"):
            vm.create()
            vm.create()
        self.assertEqual(vm.ip_addr, "192.168.0.1")
        self.assertEqual(ssh_command.call_count, 2)
        self.assertEqual(sleep.call_count, 1)
Example #5
0
    def _vm_cleanup(self, hostname=None):
        """ Cleanup the VM from provisioning server

        :param str hostname: The content host hostname
        """
        if hostname:
            vm = VirtualMachine(
                hostname=hostname,
                target_image=hostname,
                provisioning_server=self.libvirt_vm,
                distro=DISTRO_RHEL7,
                )
            vm._created = True
            vm.destroy()
Example #6
0
    def test_run(self, ssh_command):
        """Check if run calls ssh.command"""
        vm = VirtualMachine()

        def create_mock():
            """A mock for create method to set instance vars to run work"""
            vm._created = True
            vm.ip_addr = '192.168.0.1'

        with patch.object(vm, 'create', side_effect=create_mock):
            vm.create()

        vm.run('ls')
        ssh_command.assert_called_once_with('ls', hostname='192.168.0.1')
Example #7
0
    def test_run(self, ssh_command):
        """Check if run calls ssh.command"""
        self.configure_provisoning_server()
        vm = VirtualMachine()

        def create_mock():
            """A mock for create method to set instance vars to run work"""
            vm._created = True
            vm.ip_addr = "192.168.0.1"

        with patch.object(vm, "create", side_effect=create_mock):
            vm.create()

        vm.run("ls")
        ssh_command.assert_called_once_with("ls", hostname="192.168.0.1")
Example #8
0
    def register_client_to_rhai(self, activation_key, org, rhel_distro):
        self.vm = VirtualMachine(distro=rhel_distro)
        self.vm.create()
        # Download and Install ketello-ca rpm
        self.vm.install_katello_cert()
        self.vm.register_contenthost(activation_key, org)

        # Red Hat Access Insights requires RHEL 6/7 repo and it is not
        # possible to sync the repo during the tests, Adding repo file.
        if rhel_distro == 'rhel67':
            rhel_repo = conf.properties['clients.rhel6_repo']
        if rhel_distro == 'rhel71':
            rhel_repo = conf.properties['clients.rhel7_repo']
        try:
            if rhel_distro == 'rhel67':
                insights_repo = conf.properties['insights.insights_el6repo']
            if rhel_distro == 'rhel71':
                insights_repo = conf.properties['insights.insights_el7repo']
        except KeyError:
            pass

        self.logger.info('RHEL repo {0}'.format(rhel_repo))
        self.logger.info('Insights client repo {0}'.format(insights_repo))
        self.vm.configure_rhel_repo(rhel_repo)

        self.vm.run('wget -O /etc/yum.repos.d/insights.repo {0}'.
                    format(insights_repo))

        # Install redhat-access-insights package
        package_name = 'redhat-access-insights'
        result = self.vm.run('yum install -y {0}'.format(package_name))
        if result.return_code != 0:
            raise AccessInsightsError(
                'Unable to install redhat-access-insights rpm'
            )

        # Verify if package is installed by query it
        result = self.vm.run('rpm -qi {0}'.format(package_name))
        self.logger.info('Insights client rpm version: {0}'.format(
            result.stdout))

        if result.return_code != 0:
            raise AccessInsightsError(
                'Unable to install redhat-access-insights rpm'
            )

        # Register client with Red Hat Access Insights
        result = self.vm.run('redhat-access-insights --register')
        if result.return_code != 0:
            test_connection = self.vm.run(
                'redhat-access-insights --test-connection')
            if test_connection.return_code != 0:
                raise AccessInsightsError(
                    'Unable to register client, --test-connection not '
                    'successful')
            raise AccessInsightsError(
                'Unable to register client to Access Insights through '
                'Satellite')
Example #9
0
def cleanup_of_provisioned_server(hostname=None,
                                  provisioning_server=None,
                                  distro=None):
    """ Cleanup the VM from provisioning server

    :param: str hostname: The content host hostname
    :param: str provisioning_server: provision server name
    :param: str distro: distro type
    """
    if hostname:
        vm = VirtualMachine(
            hostname=hostname,
            target_image=hostname,
            provisioning_server=provisioning_server,
            distro=distro,
        )
        vm._created = True
        vm.destroy()
Example #10
0
    def test_positive_usage_limit(self):
        """Test that Usage limit actually limits usage

        :id: 00ded856-e939-4140-ac84-91b6a8643623

        :Steps:

            1. Create Activation key
            2. Update Usage Limit to a finite number
            3. Register Content hosts to match the Usage Limit
            4. Attempt to register an other Content host after reaching the
               Usage Limit

        :expectedresults: Content host Registration fails. Appropriate error
            shown

        :CaseLevel: System
        """
        env = make_lifecycle_environment({u'organization-id': self.org['id']})
        new_cv = make_content_view({u'organization-id': self.org['id']})
        ContentView.publish({u'id': new_cv['id']})
        cvv = ContentView.info({u'id': new_cv['id']})['versions'][0]
        ContentView.version_promote({
            u'id': cvv['id'],
            u'to-lifecycle-environment-id': env['id'],
        })
        new_ak = make_activation_key({
            u'lifecycle-environment-id': env['id'],
            u'content-view': new_cv['name'],
            u'organization-id': self.org['id'],
            u'max-hosts': '1',
        })
        with VirtualMachine(distro=DISTRO_RHEL6) as vm1:
            with VirtualMachine(distro=DISTRO_RHEL6) as vm2:
                vm1.install_katello_ca()
                result = vm1.register_contenthost(
                    self.org['label'], new_ak['name'])
                self.assertTrue(vm1.subscribed)
                vm2.install_katello_ca()
                result = vm2.register_contenthost(
                    self.org['label'], new_ak['name'])
                self.assertFalse(vm2.subscribed)
                self.assertEqual(result.return_code, 70)
                self.assertGreater(len(result.stderr), 0)
Example #11
0
def test_positive_run_job_template_multiple_hosts_by_ip(session, module_org, module_loc):
    """Run a job template against multiple hosts by ip

    :id: c4439ec0-bb80-47f6-bc31-fa7193bfbeeb

    :Setup: Create a working job template.

    :Steps:

        1. Set remote_execution_connect_by_ip on hosts to true
        2. Navigate to the hosts page and select at least two hosts
        3. Click the "Select Action"
        4. Select the job and appropriate template
        5. Run the job

    :expectedresults: Verify the job was successfully ran against the hosts

    :CaseLevel: System
    """
    with VirtualMachine(distro=DISTRO_DEFAULT) as client_1, VirtualMachine(
            distro=DISTRO_DEFAULT) as client_2:
        vm_clients = [client_1, client_2]
        host_names = [client.hostname for client in vm_clients]
        for client in vm_clients:
            _setup_vm_client_host(client, module_org.label)
            update_vm_host_location(client, location_id=module_loc.id)
        with session:
            hosts = session.host.search(
                ' or '.join(['name="{0}"'.format(hostname) for hostname in host_names]))
            assert set(host['Name'] for host in hosts) == set(host_names)
            job_status = session.host.schedule_remote_job(
                host_names,
                {
                    'job_category': 'Commands',
                    'job_template': 'Run Command - SSH Default',
                    'template_content.command': 'ls',
                    'schedule': 'Execute now',
                }
            )
            assert job_status['overview']['job_status'] == 'Success'
            assert (set(host_job['Host'] for host_job in job_status['overview']['hosts_table'])
                    == set(host_names))
            assert all(host_job['Status'] == 'success'
                       for host_job in job_status['overview']['hosts_table'])
Example #12
0
    def test_positive_chost_previous_env(self):
        """Check if the applicable errata are available from the content
        host's previous environment

        :id: 78110ba8-3942-46dd-8c14-bffa1dbd5195

        :Setup:

            1. Make sure multiple environments are present.
            2. Content host's previous environments have additional errata.

        :Steps: Go to Content Hosts -> Select content host -> Errata Tab ->
            Select Previous environments.

        :expectedresults: The errata from previous environments are displayed.

        :CaseLevel: System
        """
        with VirtualMachine(distro=DISTRO_RHEL7) as client:
            client.install_katello_ca()
            result = client.register_contenthost(
                self.session_org.label,
                self.activation_key.name,
            )
            self.assertEqual(result.return_code, 0)
            client.enable_repo(REPOS['rhst7']['id'])
            client.install_katello_agent()
            client.run('yum install -y {0}'.format(FAKE_1_CUSTOM_PACKAGE))
            last_env_id = max(lce.id for lce in entities.LifecycleEnvironment(
                organization=self.session_org).search())
            new_env = entities.LifecycleEnvironment(
                organization=self.session_org,
                prior=last_env_id,
            ).create()
            cvv = ContentView.info({'id':
                                    self.content_view.id})['versions'][-1]
            ContentView.version_promote({
                'id':
                cvv['id'],
                'organization-id':
                self.session_org.id,
                'to-lifecycle-environment-id':
                new_env.id,
            })
            Host.update({
                'name': client.hostname,
                'lifecycle-environment-id': new_env.id,
                'organization-id': self.session_org.id,
            })
            with Session(self.browser):
                self.assertIsNotNone(
                    self.contenthost.errata_search(
                        client.hostname,
                        CUSTOM_REPO_ERRATA_ID,
                        environment_name=self.env.name,
                    ))
def test_positive_virt_who_hypervisor_subscription_status(session):
    """Check that virt-who hypervisor shows the right subscription status
    without and with attached subscription.

    :id: 8b2cc5d6-ac85-463f-a973-f4818c55fb37

    :customerscenario: true

    :expectedresults:
        1. With subscription not attached, Subscription status is
           "Unsubscribed hypervisor" and represented by a yellow icon in
           content hosts list.
        2. With attached subscription, Subscription status is
           "Fully entitled" and represented by a green icon in content
           hosts list.

    :BZ: 1336924

    :CaseLevel: System
    """
    org = entities.Organization().create()
    lce = entities.LifecycleEnvironment(organization=org).create()
    provisioning_server = settings.compute_resources.libvirt_hostname
    # Create a new virt-who config
    virt_who_config = make_virt_who_config({
        'organization-id': org.id,
        'hypervisor-type': VIRT_WHO_HYPERVISOR_TYPES['libvirt'],
        'hypervisor-server': 'qemu+ssh://{0}/system'.format(provisioning_server),
        'hypervisor-username': '******',
    })
    # create a virtual machine to host virt-who service
    with VirtualMachine() as virt_who_vm:
        # configure virtual machine and setup virt-who service
        # do not supply subscription to attach to virt_who hypervisor
        virt_who_data = virt_who_hypervisor_config(
            virt_who_config['general-information']['id'],
            virt_who_vm,
            org_id=org.id,
            lce_id=lce.id,
            hypervisor_hostname=provisioning_server,
            configure_ssh=True,
        )
        virt_who_hypervisor_host = virt_who_data[
            'virt_who_hypervisor_host']
        with session:
            session.organization.select(org.name)
            assert session.contenthost.search(
                virt_who_hypervisor_host['name'])[0]['Subscription Status'] == 'yellow'
            chost = session.contenthost.read(virt_who_hypervisor_host['name'])
            assert chost['details']['subscription_status'] == 'Unsubscribed hypervisor'
            session.contenthost.add_subscription(
                virt_who_hypervisor_host['name'], VDC_SUBSCRIPTION_NAME)
            assert session.contenthost.search(
                virt_who_hypervisor_host['name'])[0]['Subscription Status'] == 'green'
            chost = session.contenthost.read(virt_who_hypervisor_host['name'])
            assert chost['details']['subscription_status'] == 'Fully entitled'
Example #14
0
def test_positive_view_vdc_subscription_products(session):
    """Ensure that Virtual Datacenters subscription provided products is
    not empty and that a consumed product exist in content products.

    :id: cc4593f0-66ab-4bf6-87d1-d4bd9c89eba5

    :customerscenario: true

    :steps:
        1. Upload a manifest with Virtual Datacenters subscription
        2. Enable a products provided by Virtual Datacenters subscription,
           and synchronize the auto created repository
        3. Create content view with the product repository, and publish it
        4. Create a lifecycle environment and promote the content view to
           it.
        5. Create an activation key with the content view and lifecycle
           environment
        6. Subscribe a host to the activation key
        7. Goto Hosts -> Content hosts and select the created content host
        8. Attach VDC subscription to content host
        9. Goto Content -> Red Hat Subscription
        10. Select Virtual Datacenters subscription

    :expectedresults:
        1. assert that the provided products is not empty
        2. assert that the enabled product is in subscription Product Content

    :BZ: 1366327

    :CaseLevel: System
    """
    org = entities.Organization().create()
    lce = entities.LifecycleEnvironment(organization=org).create()
    repos_collection = RepositoryCollection(
        distro=DISTRO_RHEL7, repositories=[RHELAnsibleEngineRepository(cdn=True)])
    product_name = repos_collection.rh_repos[0].data['product']
    repos_collection.setup_content(
        org.id, lce.id, upload_manifest=True, rh_subscriptions=[DEFAULT_SUBSCRIPTION_NAME])
    with VirtualMachine() as vm:
        setup_virtual_machine(
            vm,
            org.label,
            activation_key=repos_collection.setup_content_data['activation_key']['name'],
            install_katello_agent=False
        )
        with session:
            session.organization.select(org.name)
            session.contenthost.add_subscription(vm.hostname, VDC_SUBSCRIPTION_NAME)
            provided_products = session.subscription.provided_products(VDC_SUBSCRIPTION_NAME)
            # ensure that subscription provided products list is not empty and that the product is
            # in the provided products.
            assert provided_products and product_name in provided_products
            content_products = session.subscription.content_products(VDC_SUBSCRIPTION_NAME)
            # ensure that subscription enabled products list is not empty and that product is in
            # content products.
            assert content_products and product_name in content_products
Example #15
0
    def test_positive_run_custom_job_template(self):
        """Run a job template against a single host

        :id: 89b75feb-afff-44f2-a2bd-2ffe74b63ec7

        :Setup: Create a working job template.

        :Steps:

            1. Navigate to an individual host and click Run Job
            2. Select the job and appropriate template
            3. Run the job

        :expectedresults: Verify the job was successfully ran against the host

        :CaseLevel: System
        """
        jobs_template_name = gen_string('alpha')
        with VirtualMachine(distro=DISTRO_RHEL7) as client:
            client.install_katello_ca()
            client.register_contenthost(self.organization.label, lce='Library')
            self.assertTrue(client.subscribed)
            add_remote_execution_ssh_key(client.ip_addr)
            Host.update({
                u'name': client.hostname,
                u'subnet-id': self.new_sub['id'],
            })
            with Session(self.browser) as session:
                set_context(session, org=self.organization.name)
                make_job_template(
                    session,
                    name=jobs_template_name,
                    template_type='input',
                    template_content='<%= input("command") %>',
                    provider_type='SSH',
                )
                self.assertIsNotNone(
                    self.jobtemplate.search(jobs_template_name))
                self.jobtemplate.add_input(jobs_template_name,
                                           'command',
                                           required=True)
                self.hosts.click(self.hosts.search(client.hostname))
                status = self.job.run(job_category='Miscellaneous',
                                      job_template=jobs_template_name,
                                      options_list=[{
                                          'name': 'command',
                                          'value': 'ls'
                                      }])
                # get job invocation id from the current url
                invocation_id = self.browser.current_url.rsplit('/', 1)[-1]
                self.assertTrue(
                    status, 'host output: {0}'.format(' '.join(
                        JobInvocation.get_output({
                            'id': invocation_id,
                            'host': client.hostname
                        }))))
Example #16
0
    def test_negative_docker_host_setup_compresource(self):
        """Setup a docker host VM + compute resource

        :id: f3575972-13db-4a49-bc27-d1137172df41

        :expectedresults: Docker as compute resource is not setup successfully
        """
        docker_image = settings.docker.docker_image
        self.docker_host = VirtualMachine(source_image=docker_image,
                                          tag=u'docker')
        self.addCleanup(vm_cleanup, self.docker_host)
        self.docker_host.create()
        self.docker_host.install_katello_ca()
        with self.assertRaises(HTTPError):
            self.compute_resource = entities.DockerComputeResource(
                name=gen_string('alpha'),
                organization=[self.org],
                url='http://{0}:2375'.format(self.docker_host.ip_addr),
            ).create()
Example #17
0
    def test_negative_usage_limit(self):
        """Test that Usage limit actually limits usage

        @id: 9fe2d661-66f8-46a4-ae3f-0a9329494bdd

        @Steps:
        1. Create Activation key
        2. Update Usage Limit to a finite number
        3. Register Systems to match the Usage Limit
        4. Attempt to register an other system after reaching the Usage Limit

        @Assert: System Registration fails. Appropriate error shown

        @CaseLevel: System
        """
        name = gen_string('alpha')
        host_limit = '1'
        with Session(self.browser) as session:
            make_activationkey(
                session,
                org=self.organization.name,
                name=name,
                env=ENVIRONMENT,
            )
            self.assertIsNotNone(self.activationkey.search(name))
            self.activationkey.update(name, limit=host_limit)
            self.assertIsNotNone(
                self.activationkey.wait_until_element(
                    common_locators['alert.success_sub_form']))
            with VirtualMachine(distro=self.vm_distro) as vm1:
                with VirtualMachine(distro=self.vm_distro) as vm2:
                    vm1.install_katello_ca()
                    result = vm1.register_contenthost(self.organization.label,
                                                      name)
                    self.assertEqual(result.return_code, 0)
                    vm2.install_katello_ca()
                    result = vm2.register_contenthost(self.organization.label,
                                                      name)
                    self.assertNotEqual(result.return_code, 0)
                    self.assertGreater(len(result.stderr), 0)
                    self.assertIn(
                        'Max Hosts ({0}) reached for activation key'.format(
                            host_limit), result.stderr)
Example #18
0
    def test_positive_host_associations(self):
        """Register few hosts with different activation keys and ensure proper
        data is reflected under Associations > Content Hosts tab

        :id: 111aa2af-caf4-4940-8e4b-5b071d488876

        :expectedresults: Only hosts, registered by specific AK are shown under
            Associations > Content Hosts tab

        :BZ: 1344033, 1372826, 1394388

        :CaseLevel: System
        """
        org = entities.Organization().create()
        org_entities = setup_org_for_a_custom_repo({
            'url': FAKE_1_YUM_REPO,
            'organization-id': org.id,
        })
        ak1 = entities.ActivationKey(
            id=org_entities['activationkey-id']).read()
        ak2 = entities.ActivationKey(
            content_view=org_entities['content-view-id'],
            environment=org_entities['lifecycle-environment-id'],
            organization=org.id,
        ).create()
        with VirtualMachine(distro=DISTRO_RHEL7) as vm1, VirtualMachine(
                distro=DISTRO_RHEL7) as vm2:
            vm1.install_katello_ca()
            vm1.register_contenthost(org.label, ak1.name)
            self.assertTrue(vm1.subscribed)
            vm2.install_katello_ca()
            vm2.register_contenthost(org.label, ak2.name)
            self.assertTrue(vm2.subscribed)
            with Session(self) as session:
                set_context(session, org=org.name)
                ak1_hosts = self.activationkey.fetch_associated_content_hosts(
                    ak1.name)
                self.assertEqual(len(ak1_hosts), 1)
                self.assertIn(vm1.hostname, ak1_hosts)
                ak2_hosts = self.activationkey.fetch_associated_content_hosts(
                    ak2.name)
                self.assertEqual(len(ak2_hosts), 1)
                self.assertIn(vm2.hostname, ak2_hosts)
Example #19
0
 def test_name_limit(self):
     """Check whether exception is risen in case of too long host name (more
     than 59 chars)"""
     self.configure_provisioning_server()
     domain = self.provisioning_server.split('.', 1)[1]
     with self.assertRaises(VirtualMachineError):
         VirtualMachine(
             tag='test',
             target_image='a'*(59 - len(domain))
         )
Example #20
0
    def test_pre_scenario_remoteexecution_external_capsule(self):
        """Run REX job on client registered with external capsule

        :id: preupgrade-261dd2aa-be01-4c34-b877-54b8ee346561

        :steps:
            1. Create Subnet.
            2. Create Content host.
            3. Install katello-ca package and register to Satellite host.
            4. add rex ssh_key of external capsule on content host.
            5. run the REX job on client vm.

        :expectedresults:
            1. Content host should create with pre-required details.
            2. REX job should run on it.
        """
        try:
            sn = entities.Subnet(
                domain=self.vm_domain,
                gateway=self.gateway,
                ipam='DHCP',
                location=[DEFAULT_LOC_ID],
                mask=self.netmask,
                network=self.subnet,
                organization=[self.org.id],
                remote_execution_proxy=[entities.SmartProxy(id=2)],
            ).create()
            client = VirtualMachine(
                distro=DISTRO_RHEL7,
                provisioning_server=self.libvirt_vm,
                bridge=self.bridge)
            client.create()
            client.install_capsule_katello_ca(capsule=self.proxy_name)
            client.register_contenthost(org=self.org.label, lce='Library')
            add_remote_execution_ssh_key(hostname=client.ip_addr,
                                         proxy_hostname=self.proxy_name)
            host = entities.Host().search(
                query={'search': 'name="{}"'.format(client.hostname)})
            host[0].subnet = sn
            host[0].update(['subnet'])
            job = entities.JobInvocation().run(data={
                'job_template_id': 89, 'inputs': {'command': "ls"},
                'targeting_type': 'static_query', 'search_query': "name = {0}"
                .format(client.hostname)})
            self.assertEqual(job['output']['success_count'], 1)
            global_dict = {
                self.__class__.__name__: {'client_name': client.hostname}
            }
            create_dict(global_dict)
        except Exception as exp:
            if client._created:
                self._vm_cleanup(hostname=client.hostname)
            raise Exception(exp)
Example #21
0
    def setUp(self):
        """Create VM, subscribe it to satellite-tools repo, install katello-ca
        and katello-agent packages

        """
        super().setUp()
        # Create VM and register content host
        self.client = VirtualMachine(distro=DISTRO_RHEL7)
        self.client.create()
        self.addCleanup(vm_cleanup, self.client)
        self.client.install_katello_ca()
        # Register content host, install katello-agent
        self.client.register_contenthost(
            KatelloAgentTestCase.org['label'], KatelloAgentTestCase.activation_key['name']
        )
        assert self.client.subscribed
        self.host = Host.info({'name': self.client.hostname})
        self.client.enable_repo(REPOS['rhst7']['id'])
        self.client.install_katello_agent()
Example #22
0
def test_positive_host_associations(session):
    """Register few hosts with different activation keys and ensure proper
    data is reflected under Associations > Content Hosts tab

    :id: 111aa2af-caf4-4940-8e4b-5b071d488876

    :expectedresults: Only hosts, registered by specific AK are shown under
        Associations > Content Hosts tab

    :BZ: 1344033, 1372826, 1394388

    :CaseLevel: System
    """
    org = entities.Organization().create()
    org_entities = setup_org_for_a_custom_repo({
        'url': FAKE_1_YUM_REPO,
        'organization-id': org.id,
    })
    ak1 = entities.ActivationKey(
        id=org_entities['activationkey-id']).read()
    ak2 = entities.ActivationKey(
        content_view=org_entities['content-view-id'],
        environment=org_entities['lifecycle-environment-id'],
        organization=org.id,
    ).create()
    with VirtualMachine(distro=DISTRO_RHEL7) as vm1, VirtualMachine(
            distro=DISTRO_RHEL7) as vm2:
        vm1.install_katello_ca()
        vm1.register_contenthost(org.label, ak1.name)
        assert vm1.subscribed
        vm2.install_katello_ca()
        vm2.register_contenthost(org.label, ak2.name)
        assert vm2.subscribed
        with session:
            session.organization.select(org.name)
            ak1 = session.activationkey.read(ak1.name)
            assert len(ak1['content_hosts']['resources']) == 1
            assert ak1['content_hosts']['resources'][0]['Name'] == vm1.hostname
            # fixme: drop next line after airgun#63 is solved
            session.activationkey.search(ak2.name)
            ak2 = session.activationkey.read(ak2.name)
            assert len(ak2['content_hosts']['resources']) == 1
            assert ak2['content_hosts']['resources'][0]['Name'] == vm2.hostname
Example #23
0
def test_positive_candlepin_events_processed_by_STOMP(session):
    """Verify that Candlepin events are being read and processed by
       attaching subscriptions, validating host subscriptions status,
       and viewing processed and failed Candlepin events

    :id: 9510fd1c-2efb-4132-8665-9a72273cd1af

    :steps:

        1. Register Content Host without subscriptions attached
        2. Verify subscriptions status is red "invalid"
        3. Import a Manifest
        4. Attach subs to content host
        5. Verify subscription status is green "valid"
        6. Check for processed and failed Candlepin events

    :expectedresults: Candlepin events are being read and processed
                      correctly without any failures

    :BZ: #1826515

    :CaseImportance: High
    """
    org = entities.Organization().create()
    repo = entities.Repository(product=entities.Product(
        organization=org).create()).create()
    repo.sync()
    ak = entities.ActivationKey(
        content_view=org.default_content_view,
        max_hosts=100,
        organization=org,
        environment=entities.LifecycleEnvironment(id=org.library.id),
    ).create()
    with VirtualMachine(distro=DISTRO_RHEL7) as vm:
        vm.install_katello_ca()
        vm.register_contenthost(org.name, ak.name)
        with session:
            session.organization.select(org_name=org.name)
            host = session.contenthost.read(vm.hostname,
                                            widget_names='details')['details']
            sub_status = host['subscription_status']
            assert "Unentitled" in sub_status
            with manifests.clone() as manifest:
                upload_manifest(org.id, manifest.content)
            session.contenthost.add_subscription(vm.hostname,
                                                 DEFAULT_SUBSCRIPTION_NAME)
            session.browser.refresh()
            updated_sub_status = session.contenthost.read(
                vm.hostname,
                widget_names='details')['details']['subscription_status']
            assert "Fully entitled" in updated_sub_status
            response = entities.Ping().search_json(
            )["services"]["candlepin_events"]
            assert response["status"] == "ok"
            assert "0 Failed" in response["message"]
Example #24
0
    def setUp(self):
        """Create VM, subscribe it to satellite-tools repo, install katello-ca
        and katello-agent packages

        """
        super(TestCHKatelloAgent, self).setUp()

        # Create new org, environment, CV and activation key
        if TestCHKatelloAgent.org is None:
            TestCHKatelloAgent.org = make_org()
        if TestCHKatelloAgent.env is None:
            TestCHKatelloAgent.env = make_lifecycle_environment({
                u'organization-id': TestCHKatelloAgent.org['id'],
            })
        if TestCHKatelloAgent.cv is None:
            TestCHKatelloAgent.cv = make_content_view({
                u'organization-id': TestCHKatelloAgent.org['id'],
            })
        if TestCHKatelloAgent.activation_key is None:
            TestCHKatelloAgent.activation_key = make_activation_key({
                u'lifecycle-environment-id': TestCHKatelloAgent.env['id'],
                u'organization-id': TestCHKatelloAgent.org['id'],
            })
        # Add subscription to Satellite Tools repo to activation key
        if not TestCHKatelloAgent.org_is_set_up:
            setup_org_for_a_rh_repo({
                u'product': PRDS['rhel'],
                u'repository-set': REPOSET['rhst7'],
                u'repository': REPOS['rhst7']['name'],
                u'organization-id': TestCHKatelloAgent.org['id'],
                u'content-view-id': TestCHKatelloAgent.cv['id'],
                u'lifecycle-environment-id': TestCHKatelloAgent.env['id'],
                u'activationkey-id': TestCHKatelloAgent.activation_key['id'],
            })
            TestCHKatelloAgent.org_is_set_up = True

        # Create VM and register content host
        self.vm = VirtualMachine(distro='rhel71')
        self.vm.create()
        self.vm.install_katello_cert()
        # Create custom repo, add subscription to activation key
        setup_org_for_a_custom_repo({
            u'url': FAKE_0_YUM_REPO,
            u'organization-id': TestCHKatelloAgent.org['id'],
            u'content-view-id': TestCHKatelloAgent.cv['id'],
            u'lifecycle-environment-id': TestCHKatelloAgent.env['id'],
            u'activationkey-id': TestCHKatelloAgent.activation_key['id'],
        })
        # Register content host, install katello-agent
        self.vm.register_contenthost(
            TestCHKatelloAgent.activation_key['name'],
            TestCHKatelloAgent.org['label']
        )
        self.vm.enable_repo(REPOS['rhst7']['id'])
        self.vm.install_katello_agent()
Example #25
0
def test_negative_usage_limit(session, module_org):
    """Test that Usage limit actually limits usage

    :id: 9fe2d661-66f8-46a4-ae3f-0a9329494bdd

    :Steps:
        1. Create Activation key
        2. Update Usage Limit to a finite number
        3. Register Systems to match the Usage Limit
        4. Attempt to register an other system after reaching the Usage
            Limit

    :expectedresults: System Registration fails. Appropriate error shown

    :CaseLevel: System
    """
    name = gen_string('alpha')
    hosts_limit = '1'
    with session:
        session.activationkey.create({
            'name': name,
            'lce': {ENVIRONMENT: True},
        })
        assert session.activationkey.search(name) == name
        session.activationkey.update(
            name, {'details.hosts_limit': hosts_limit})
        ak = session.activationkey.read(name)
        assert ak['details']['hosts_limit'] == hosts_limit
    with VirtualMachine(distro=DISTRO_RHEL6) as vm1:
        with VirtualMachine(distro=DISTRO_RHEL6) as vm2:
            vm1.install_katello_ca()
            vm1.register_contenthost(module_org.label, name)
            assert vm1.subscribed
            vm2.install_katello_ca()
            result = vm2.register_contenthost(module_org.label, name)
            assert not vm2.subscribed
            assert len(result.stderr) > 0
            assert (
                'Max Hosts ({0}) reached for activation key'
                .format(hosts_limit)
                in result.stderr
            )
Example #26
0
    def test_positive_generate_entitlements_report_multiple_formats(self):
        """Generate an report using the Entitlements template in html, yaml, and csv format.

        :id: f2b74916-1298-4d20-9c24-a2c2b3a3e9a9

        :setup: Installed Satellite with Organization, Activation key,
                Content View, Content Host, and Subscriptions.

        :steps:
            1. hammer report-template generate --organization '' --id '' --report-format ''

        :expectedresults: report is generated containing all the expected information
                          regarding Entitlements.

        :CaseImportance: High
        """
        with VirtualMachine(distro=DISTRO_RHEL7) as vm:
            vm.install_katello_ca()
            vm.register_contenthost(self.setup_org['label'],
                                    self.setup_new_ak['name'])
            assert vm.subscribed
            result_html = ReportTemplate.generate({
                'organization':
                self.setup_org['name'],
                'name':
                'Entitlements',
                'report-format':
                'html',
            })
            assert vm.hostname in result_html[2]
            assert self.setup_subs_id[0]['name'] in result_html[2]
            result_yaml = ReportTemplate.generate({
                'organization':
                self.setup_org['name'],
                'name':
                'Entitlements',
                'report-format':
                'yaml',
            })
            for entry in result_yaml:
                if '-Name:' in entry:
                    assert vm.hostname in entry
                elif 'Subscription Name:' in entry:
                    assert self.setup_subs_id[0]['name'] in entry
            result_csv = ReportTemplate.generate({
                'organization':
                self.setup_org['name'],
                'name':
                'Entitlements',
                'report-format':
                'csv',
            })
            assert vm.hostname in result_csv[1]
            assert self.setup_subs_id[0]['name'] in result_csv[1]
Example #27
0
    def test_positive_run_default_job_template_multiple_hosts_by_ip(
        self, fixture_vmsetup, fixture_org
    ):
        """Run default job template against multiple hosts by ip

        :id: 694a21d3-243b-4296-8bd0-4bad9663af15

        :expectedresults: Verify the job was successfully ran against all hosts

        :parametrized: yes
        """
        self.org = fixture_org
        self.client = fixture_vmsetup
        Host.set_parameter(
            {
                'host': self.client.hostname,
                'name': 'remote_execution_connect_by_ip',
                'value': 'True',
            }
        )
        with VirtualMachine(distro=DISTRO_RHEL7) as client2:
            client2.install_katello_ca()
            client2.register_contenthost(self.org.label, lce='Library')
            add_remote_execution_ssh_key(client2.ip_addr)
            Host.set_parameter(
                {
                    'host': client2.hostname,
                    'name': 'remote_execution_connect_by_ip',
                    'value': 'True',
                }
            )
            invocation_command = make_job_invocation(
                {
                    'job-template': 'Run Command - SSH Default',
                    'inputs': 'command="ls"',
                    'search-query': "name ~ {} or name ~ {}".format(
                        self.client.hostname, client2.hostname
                    ),
                }
            )
            # collect output messages from clients
            output_msgs = []
            for vm in self.client, client2:
                output_msgs.append(
                    'host output from {}: {}'.format(
                        vm.hostname,
                        ' '.join(
                            JobInvocation.get_output(
                                {'id': invocation_command['id'], 'host': vm.hostname}
                            )
                        ),
                    )
                )
            assert invocation_command['success'] == '2', output_msgs
Example #28
0
 def setUpClass(cls):  # noqa
     super(InstallerTestCase, cls).setUpClass()
     cls.vm = VirtualMachine(cls.vm_cpu, cls.vm_ram, cls.vm_os)
     cls.vm.create()
     key_filename = conf.properties.get('main.server.ssh.key_private')
     with settings(key_filename=key_filename, user='******', warn_only=True):
         execute(
             product_install,
             'upstream',
             host=cls.vm.ip_addr
         )
Example #29
0
    def test_positive_install_in_hc(self):
        """Install errata in a host-collection

        @id: 6f0242df-6511-4c0f-95fc-3fa32c63a064

        @Setup: Errata synced on satellite server.

        @Steps:

        1. PUT /api/v2/hosts/bulk/update_content

        @Assert: errata is installed in the host-collection.

        @CaseLevel: System
        """
        with VirtualMachine(distro=DISTRO_RHEL7) as client1, VirtualMachine(
                distro=DISTRO_RHEL7) as client2:
            clients = [client1, client2]
            for client in clients:
                client.install_katello_ca()
                result = client.register_contenthost(self.org.label,
                                                     self.activation_key.name)
                self.assertEqual(result.return_code, 0)
                client.enable_repo(REPOS['rhst7']['id'])
                client.install_katello_agent()
            host_ids = [
                entities.Host().search(
                    query={'search': 'name={0}'.format(client.hostname)})[0].id
                for client in clients
            ]
            self._install_package(clients, host_ids, FAKE_1_CUSTOM_PACKAGE)
            entities.Host().install_content(
                data={
                    'organization_id': self.org.id,
                    'included': {
                        'ids': host_ids
                    },
                    'content_type': 'errata',
                    'content': [CUSTOM_REPO_ERRATA_ID],
                })
            self._validate_package_installed(clients, FAKE_2_CUSTOM_PACKAGE)
Example #30
0
    def test_destroy(self, ssh_command):
        """Check if destroy runs the required ssh commands"""
        self.configure_provisoning_server()
        image_dir = '/opt/robottelo/images'
        vm = VirtualMachine()

        with patch.multiple(vm, image_dir=image_dir, _created=True):
            vm.destroy()

        self.assertEqual(ssh_command.call_count, 3)

        ssh_command_args_list = [
            call('virsh destroy {0}'.format(vm.hostname),
                 hostname=self.provisioning_server),
            call('virsh undefine {0}'.format(vm.hostname),
                 hostname=self.provisioning_server),
            call('rm {0}/{1}.img'.format(image_dir, vm.hostname),
                 hostname=self.provisioning_server),
        ]

        self.assertListEqual(ssh_command.call_args_list, ssh_command_args_list)
Example #31
0
 def setUp(self):
     """Create a VM, subscribe it to satellite-tools repo, install
     katello-ca and katello-agent packages"""
     super(ContentHostTestCase, self).setUp()
     self.client = VirtualMachine(distro='rhel71')
     self.client.create()
     self.client.install_katello_ca()
     result = self.client.register_contenthost(
         self.session_org.label, self.activation_key.name)
     self.assertEqual(result.return_code, 0)
     self.client.enable_repo(REPOS['rhst7']['id'])
     self.client.install_katello_agent()
 def setUp(self):
     """Create VM, install katello-ca, register it, add remote execution key
     """
     super(RemoteExecutionTestCase, self).setUp()
     # Create VM and register content host
     self.client = VirtualMachine(
         distro=DISTRO_RHEL7,
         provisioning_server=settings.compute_resources.libvirt_hostname,
         bridge=settings.vlan_networking.bridge)
     self.addCleanup(vm_cleanup, self.client)
     self.client.create()
     self.client.install_katello_ca()
     # Register content host
     self.client.register_contenthost(org=self.org.label, lce='Library')
     self.assertTrue(self.client.subscribed)
     add_remote_execution_ssh_key(self.client.ip_addr)
     # add host to subnet
     Host.update({
         'name': self.client.hostname,
         'subnet-id': self.sn.id,
     })
    def test_positive_usage_limit(self):
        """Test that Usage limit actually limits usage

        @Feature: Activation key - Usage limit

        @Steps:

        1. Create Activation key
        2. Update Usage Limit to a finite number
        3. Register Content hosts to match the Usage Limit
        4. Attempt to register an other Content host after reaching the Usage
           Limit

        @Assert: Content host Registration fails. Appropriate error shown
        """
        env = make_lifecycle_environment({u'organization-id': self.org['id']})
        new_cv = make_content_view({u'organization-id': self.org['id']})
        ContentView.publish({u'id': new_cv['id']})
        cvv = ContentView.info({u'id': new_cv['id']})['versions'][0]
        ContentView.version_promote({
            u'id': cvv['id'],
            u'to-lifecycle-environment-id': env['id'],
        })
        new_ak = make_activation_key({
            u'lifecycle-environment-id': env['id'],
            u'content-view': new_cv['name'],
            u'organization-id': self.org['id'],
            u'max-content-hosts': '1',
        })
        with VirtualMachine(distro='rhel65') as vm1:
            with VirtualMachine(distro='rhel65') as vm2:
                vm1.install_katello_ca()
                result = vm1.register_contenthost(
                    new_ak['name'], self.org['label'])
                self.assertEqual(result.return_code, 0)
                vm2.install_katello_ca()
                result = vm2.register_contenthost(
                    new_ak['name'], self.org['label'])
                self.assertEqual(result.return_code, 255)
                self.assertGreater(len(result.stderr), 0)
Example #34
0
    def test_positive_apply_for_all_hosts(self):
        """Apply an erratum for all content hosts

        :id: d70a1bee-67f4-4883-a0b9-2ccc08a91738

        :Setup: Errata synced on satellite server.

        :Steps:

            1. Go to Content -> Errata. Select an erratum -> Content Hosts tab.
            2. Select all Content Hosts and apply the erratum.

        :expectedresults: Check that the erratum is applied in all the content
            hosts.

        :CaseLevel: System
        """
        with VirtualMachine(distro=DISTRO_RHEL7) as client1, VirtualMachine(
                distro=DISTRO_RHEL7) as client2:
            clients = [client1, client2]
            for client in clients:
                client.install_katello_ca()
                result = client.register_contenthost(
                    self.session_org.label,
                    self.activation_key.name,
                )
                self.assertEqual(result.return_code, 0)
                client.enable_repo(REPOS['rhst7']['id'])
                client.install_katello_agent()
                client.run('yum install -y {0}'.format(FAKE_1_CUSTOM_PACKAGE))
            with Session(self.browser):
                result = self.errata.install(
                    CUSTOM_REPO_ERRATA_ID,
                    [client.hostname for client in clients],
                )
                self.assertEqual(result, 'success')
                for client in clients:
                    self.assertIsNotNone(
                        self.contenthost.package_search(
                            client.hostname, FAKE_2_CUSTOM_PACKAGE))
Example #35
0
 def setUp(self):
     """Create a VM, subscribe it to satellite-tools repo, install
     katello-ca and katello-agent packages"""
     super(ContentHostTestCase, self).setUp()
     self.client = VirtualMachine(distro=DISTRO_RHEL7)
     self.addCleanup(vm_cleanup, self.client)
     self.client.create()
     self.client.install_katello_ca()
     self.client.register_contenthost(
         self.session_org.label, self.activation_key.name)
     self.assertTrue(self.client.subscribed)
     self.client.enable_repo(REPOS['rhst7']['id'])
     self.client.install_katello_agent()
 def setUpClass(cls):
     """Create an organization which can be re-used in tests."""
     super(RemoteExecutionTestCase, cls).setUpClass()
     cls.organization = make_org()
     ssh.command('''echo 'getenforce' > {0}'''.format(TEMPLATE_FILE))
     cls.client = VirtualMachine(distro=DISTRO_RHEL7)
     cls.client.create()
     cls.client.install_katello_ca()
     cls.client.register_contenthost(cls.organization['label'],
                                     lce='Library')
     cls.client.enable_repo(REPOS['rhst7']['id'])
     cls.client.install_katello_agent()
     add_remote_execution_ssh_key(cls.client.hostname)
Example #37
0
    def test_positive_register_host_ak_with_host_collection(self):
        """Attempt to register a host using activation key with host collection

        :id: 7daf4e40-3fa6-42af-b3f7-1ca1a5c9bfeb

        :BZ: 1385814

        :expectedresults: Host successfully registered and listed in host
            collection

        :CaseLevel: System
        """
        # create a new activation key
        activation_key = make_activation_key({
            'lifecycle-environment-id':
            self.env['id'],
            'organization-id':
            self.org['id'],
            'content-view-id':
            self.content_view['id'],
        })
        hc = make_host_collection({'organization-id': self.org['id']})
        ActivationKey.add_host_collection({
            'id': activation_key['id'],
            'organization-id': self.org['id'],
            'host-collection-id': hc['id'],
        })
        # add the registered instance host to collection
        HostCollection.add_host({
            'id': hc['id'],
            'organization-id': self.org['id'],
            'host-ids': self.host['id']
        })
        with VirtualMachine() as client:
            client.create()
            client.install_katello_ca()
            # register the client host with the current activation key
            client.register_contenthost(self.org['name'],
                                        activation_key=activation_key['name'])
            assert client.subscribed
            # note: when registering the host, it should be automatically added
            # to the host collection
            client_host = Host.info({'name': client.hostname})
            hosts = HostCollection.hosts({
                'id': hc['id'],
                'organization-id': self.org['id']
            })
            assert len(hosts) == 2
            expected_hosts_ids = {self.host['id'], client_host['id']}
            hosts_ids = {host['id'] for host in hosts}
            assert hosts_ids == expected_hosts_ids
    def test_positive_run_job_template_multiple_hosts(self):
        """Run a job template against multiple hosts

        @id: 7f1981cb-afcc-49b7-a565-7fef9aa8ddde

        @Setup: Create a working job template.

        @Steps:

        1. Navigate to the hosts page and select at least two hosts
        2. Click the "Select Action"
        3. Select the job and appropriate template
        4. Run the job

        @Assert: Verify the job was successfully ran against the hosts

        @CaseLevel: System
        """
        with VirtualMachine(distro='rhel71') as client:
            with VirtualMachine(distro='rhel71') as client2:
                for vm in client, client2:
                    vm.install_katello_ca()
                    vm.register_contenthost(self.organization.label,
                                            lce='Library')
                    add_remote_execution_ssh_key(vm.ip_addr)
                with Session(self.browser) as session:
                    set_context(session, org=self.organization.name)
                    self.hosts.navigate_to_entity()
                    self.hosts.update_host_bulkactions(
                        [client.hostname, client2.hostname],
                        action='Run Job',
                        parameters_list=[{
                            'command': 'ls'
                        }],
                    )
                    strategy, value = locators['job_invocation.status']
                    self.job.wait_until_element(
                        (strategy, value % 'succeeded'), 240)
 def setUp(self):
     """Create VM, subscribe it to satellite-tools repo, install katello-ca
         and katello-agent packages, add remote execution key
     """
     super(RemoteExecutionTestCase, self).setUp()
     # Create VM and register content host
     self.client = VirtualMachine(distro=DISTRO_RHEL7)
     self.addCleanup(vm_cleanup, self.client)
     self.client.create()
     self.client.install_katello_ca()
     # Register content host, install katello-agent
     self.client.register_contenthost(
         self.org['label'],
         self.activation_key['name'],
     )
     self.assertTrue(self.client.subscribed)
     self.client.enable_repo(REPOS['rhst7']['id'])
     self.client.install_katello_agent()
     add_remote_execution_ssh_key(self.client.ip_addr)
     # create subnet for current org, default loc and domain
     subnet_options = {
         u'domain-ids': 1,
         u'organization-ids': self.org["id"],
         u'location-ids': 2
        }
     if not bz_bug_is_open(1328322):
         subnet_options[u'remote-execution-proxy-id'] = 1
     new_sub = make_subnet(subnet_options)
     # add rex proxy to subnet, default is internal proxy (id 1)
     if bz_bug_is_open(1328322):
         subnet = entities.Subnet(id=new_sub["id"])
         subnet.remote_execution_proxy_ids = [1]
         subnet.update(["remote_execution_proxy_ids"])
     # add host to subnet
     Host.update({
         'name': self.client.hostname,
         'subnet-id': new_sub['id'],
     })
Example #40
0
    def test_positive_run_default_job_template(self):
        """Run a job template against a single host

        :id: 7f0cdd1a-c87c-4324-ae9c-dbc30abad217

        :Setup: Use pre-defined job template.

        :Steps:

            1. Navigate to an individual host and click Run Job
            2. Select the job and appropriate template
            3. Run the job

        :expectedresults: Verify the job was successfully ran against the host

        :CaseLevel: Integration
        """
        with VirtualMachine(
                distro=DISTRO_RHEL7,
                bridge=settings.vlan_networking.bridge,
                provisioning_server=settings.compute_resources.libvirt_hostname
                ) as client:
            client.install_katello_ca()
            client.register_contenthost(self.organization.label, lce='Library')
            self.assertTrue(client.subscribed)
            add_remote_execution_ssh_key(client.ip_addr)
            Host.update({
                u'name': client.hostname,
                u'subnet-id': self.new_sub.id,
            })
            with Session(self) as session:
                set_context(session, org=self.organization.name)
                self.hosts.click(self.hosts.search(client.hostname))
                status = self.job.run(
                    job_category='Commands',
                    job_template='Run Command - SSH Default',
                    options_list=[{'name': 'command', 'value': 'ls'}]
                )
                # get job invocation id from the current url
                invocation_id = self.browser.current_url.rsplit('/', 1)[-1]
                try:
                    self.assertTrue(status)
                except AssertionError:
                    result = 'host output: {0}'.format(
                            ' '.join(JobInvocation.get_output({
                                'id': invocation_id,
                                'host': client.hostname})
                            )
                        )
                    raise AssertionError(result)
Example #41
0
    def setUp(self):
        """Create VM, subscribe it to satellite-tools repo, install katello-ca
        and katello-agent packages

        """
        super(KatelloAgentTestCase, self).setUp()
        # Create VM and register content host
        self.client = VirtualMachine(distro="rhel71")
        self.client.create()
        self.client.install_katello_ca()
        # Register content host, install katello-agent
        self.client.register_contenthost(KatelloAgentTestCase.activation_key["name"], KatelloAgentTestCase.org["label"])
        self.client.enable_repo(REPOS["rhst7"]["id"])
        self.client.install_katello_agent()
Example #42
0
def test_positive_add_multiple_aks_to_system(session, module_org):
    """Check if multiple Activation keys can be attached to a system

    :id: 4d6b6b69-9d63-4180-af2e-a5d908f8adb7

    :expectedresults: Multiple Activation keys are attached to a system

    :CaseLevel: System
    """
    key_1_name = gen_string('alpha')
    key_2_name = gen_string('alpha')
    cv_1_name = gen_string('alpha')
    cv_2_name = gen_string('alpha')
    env_1_name = gen_string('alpha')
    env_2_name = gen_string('alpha')
    product_1_name = gen_string('alpha')
    product_2_name = gen_string('alpha')
    repo_1_id = create_sync_custom_repo(org_id=module_org.id, product_name=product_1_name)
    cv_publish_promote(cv_1_name, env_1_name, repo_1_id, module_org.id)
    repo_2_id = create_sync_custom_repo(
        org_id=module_org.id, product_name=product_2_name, repo_url=FAKE_2_YUM_REPO
    )
    cv_publish_promote(cv_2_name, env_2_name, repo_2_id, module_org.id)
    with session:
        # Create 2 activation keys
        for key_name, env_name, cv_name, product_name in (
            (key_1_name, env_1_name, cv_1_name, product_1_name),
            (key_2_name, env_2_name, cv_2_name, product_2_name),
        ):
            session.activationkey.create(
                {'name': key_name, 'lce': {env_name: True}, 'content_view': cv_name}
            )
            assert session.activationkey.search(key_name)[0]['Name'] == key_name
            session.activationkey.add_subscription(key_name, product_name)
            ak = session.activationkey.read(key_name, widget_names='subscriptions')
            subscriptions = [
                subscription['Repository Name']
                for subscription in ak['subscriptions']['resources']['assigned']
            ]
            assert product_name in subscriptions
        # Create VM
        with VirtualMachine(distro=DISTRO_RHEL6) as vm:
            vm.install_katello_ca()
            vm.register_contenthost(module_org.label, '{0},{1}'.format(key_1_name, key_2_name))
            assert vm.subscribed
            # Assert the content-host association with activation keys
            for key_name in [key_1_name, key_2_name]:
                ak = session.activationkey.read(key_name, widget_names='content_hosts')
                assert len(ak['content_hosts']['table']) == 1
                assert ak['content_hosts']['table'][0]['Name'] == vm.hostname
Example #43
0
    def register_client_to_rhai(self, activation_key, org):
        self.vm = VirtualMachine(distro='rhel67')
        self.vm.create()
        # Download and Install ketello-ca rpm
        self.vm.install_katello_cert()
        self.vm.register_contenthost(activation_key, org)

        # Red Hat Access Insights requires RHEL 6/7 repo and it not
        # possible to sync the repo during the tests,
        # adding a file in /etc/yum.repos.d/rhel6/7.repo

        rhel6_repo = conf.properties['insights.rhel6_repo']

        repo_file = (
            '[rhel6-rpms]\n'
            'name=RHEL6\n'
            'baseurl={0}\n'
            'enabled=1\n'
            .format(rhel6_repo)
        )

        self.vm.run(
            'echo "{0}" >> /etc/yum.repos.d/rhel6.repo'
            .format(repo_file)
        )

        # Install redhat-access-insights package
        package_name = 'redhat-access-insights'
        result = self.vm.run('yum install -y {0}'.format(package_name))
        if result.return_code != 0:
            raise AccessInsightsError(
                'Unable to install redhat-access-insights rpm'
            )

        # Verify if package is installed by query it
        result = self.vm.run('rpm -q {0}'.format(package_name))
        if result.return_code != 0:
            raise AccessInsightsError(
                'Unable to install redhat-access-insights rpm'
            )

        # Register client with Red Hat Access Insights
        result = self.vm.run('redhat-access-insights --register')
        if result.return_code != 0:
            raise AccessInsightsError(
                'Unable to register client to Access Insights through '
                'Satellite')
Example #44
0
    def setUp(self):
        """Create VM, subscribe it to satellite-tools repo, install katello-ca
        and katello-agent packages

        """
        super(KatelloAgentTestCase, self).setUp()
        # Create VM and register content host
        self.client = VirtualMachine(distro='rhel71')
        self.client.create()
        self.client.install_katello_ca()
        # Register content host, install katello-agent
        self.client.register_contenthost(
            KatelloAgentTestCase.activation_key['name'],
            KatelloAgentTestCase.org['label']
        )
        self.host = Host.info({'name': self.client.hostname})
        self.client.enable_repo(REPOS['rhst7']['id'])
        self.client.install_katello_agent()
Example #45
0
 def setUp(self):
     """Create VM, subscribe it to satellite-tools repo, install katello-ca
     and katello-agent packages, add remote execution key
     """
     super(RemoteExecutionTestCase, self).setUp()
     # Create VM and register content host
     self.client = VirtualMachine(distro=DISTRO_RHEL7)
     self.addCleanup(vm_cleanup, self.client)
     self.client.create()
     self.client.install_katello_ca()
     # Register content host, install katello-agent
     self.client.register_contenthost(
         self.org['label'],
         self.activation_key['name'],
     )
     if settings.cdn:
         self.client.enable_repo(REPOS['rhst7']['id'])
     self.client.install_katello_agent()
     add_remote_execution_ssh_key(self.client.ip_addr)
 def setUp(self):
     """Create VM, subscribe it to satellite-tools repo, install katello-ca
         and katello-agent packages, add remote execution key
     """
     super(RemoteExecutionTestCase, self).setUp()
     # Create VM and register content host
     self.client = VirtualMachine(
         distro=DISTRO_RHEL7,
         provisioning_server=settings.compute_resources.libvirt_hostname,
         bridge=settings.vlan_networking.bridge)
     self.addCleanup(vm_cleanup, self.client)
     self.client.create()
     self.client.install_katello_ca()
     # Register content host, install katello-agent
     self.client.register_contenthost(
         self.org['label'],
         self.activation_key['name'],
     )
     self.assertTrue(self.client.subscribed)
     self.client.enable_repo(REPOS['rhst7']['id'])
     self.client.install_katello_agent()
     add_remote_execution_ssh_key(self.client.ip_addr)
     # create subnet for current org, default loc and domain
     subnet_options = {
         u'domain-ids': 1,
         u'organization-ids': self.org["id"],
         u'location-ids': 2
        }
     if not bz_bug_is_open(1328322):
         subnet_options[u'remote-execution-proxy-id'] = 1
     new_sub = make_subnet(subnet_options)
     # add rex proxy to subnet, default is internal proxy (id 1)
     if bz_bug_is_open(1328322):
         subnet = entities.Subnet(id=new_sub["id"])
         subnet.remote_execution_proxy_ids = [1]
         subnet.update(["remote_execution_proxy_ids"])
     # add host to subnet
     Host.update({
         'name': self.client.hostname,
         'subnet-id': new_sub['id'],
     })
Example #47
0
 def setUp(self):
     """Create VM, install katello-ca, register it, add remote execution key
     """
     super(RemoteExecutionTestCase, self).setUp()
     # Create VM and register content host
     self.client = VirtualMachine(
         distro=DISTRO_RHEL7,
         provisioning_server=settings.compute_resources.libvirt_hostname,
         bridge=settings.vlan_networking.bridge)
     self.addCleanup(vm_cleanup, self.client)
     self.client.create()
     self.client.install_katello_ca()
     # Register content host
     self.client.register_contenthost(
         org=self.org.label,
         lce='Library'
     )
     self.assertTrue(self.client.subscribed)
     add_remote_execution_ssh_key(self.client.ip_addr)
     # add host to subnet
     Host.update({
         'name': self.client.hostname,
         'subnet-id': self.sn.id,
     })
Example #48
0
class RemoteExecutionTestCase(CLITestCase):
    """Implements job execution tests in CLI."""

    @classmethod
    @skip_if_not_set('clients', 'fake_manifest', 'vlan_networking')
    def setUpClass(cls):
        """Create Org, Lifecycle Environment, Content View, Activation key
        """
        super(RemoteExecutionTestCase, cls).setUpClass()
        cls.org = entities.Organization().create()
        ssh.command(
            '''echo 'getenforce' > {0}'''.format(TEMPLATE_FILE)
        )
        # create subnet for current org, default loc and domain
        # using API due BZ#1370460
        cls.sn = entities.Subnet(
            domain=[1],
            gateway=settings.vlan_networking.gateway,
            ipam='DHCP',
            location=[DEFAULT_LOC_ID],
            mask=settings.vlan_networking.netmask,
            network=settings.vlan_networking.subnet,
            organization=[cls.org.id]
        ).create()
        # add rex proxy to subnet, default is internal proxy (id 1)
        if bz_bug_is_open(1328322):
            cls.sn.remote_execution_proxy_ids = [1]
            cls.sn.update(["remote_execution_proxy_ids"])
        else:
            cls.sn.remote_execution_proxy_id = 1
            cls.sn.update(["remote_execution_proxy_id"])

    def setUp(self):
        """Create VM, install katello-ca, register it, add remote execution key
        """
        super(RemoteExecutionTestCase, self).setUp()
        # Create VM and register content host
        self.client = VirtualMachine(
            distro=DISTRO_RHEL7,
            provisioning_server=settings.compute_resources.libvirt_hostname,
            bridge=settings.vlan_networking.bridge)
        self.addCleanup(vm_cleanup, self.client)
        self.client.create()
        self.client.install_katello_ca()
        # Register content host
        self.client.register_contenthost(
            org=self.org.label,
            lce='Library'
        )
        self.assertTrue(self.client.subscribed)
        add_remote_execution_ssh_key(self.client.ip_addr)
        # add host to subnet
        Host.update({
            'name': self.client.hostname,
            'subnet-id': self.sn.id,
        })

    @stubbed()
    @tier2
    def test_positive_run_default_job_template(self):
        """Run default job template against a single host

        :id: f4470ed4-f971-4a3c-a2f1-150d45755e48

        :expectedresults: Verify the job was successfully ran against the host
        """
        invocation_command = make_job_invocation({
            'job-template': 'Run Command - SSH Default',
            'inputs': 'command="ls"',
            'search-query': "name ~ {0}".format(self.client.hostname),
        })
        try:
            self.assertEqual(invocation_command['success'], u'1')
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)

    @stubbed()
    @tier2
    @skip_if_bug_open('bugzilla', 1451675)
    def test_positive_run_job_effective_user(self):
        """Run default job template as effective user against a single host

        :id: ecd3f24f-26df-4a2c-9112-6af33b68b601

        :expectedresults: Verify the job was successfully run under the
            effective user identity on host
        """
        # create a user on client via remote job
        username = gen_string('alpha')
        filename = gen_string('alpha')
        make_user_job = make_job_invocation({
            'job-template': 'Run Command - SSH Default',
            'inputs': "command='useradd {0}'".format(username),
            'search-query': "name ~ {0}".format(self.client.hostname),
        })
        try:
            self.assertEqual(make_user_job[u'success'], u'1')
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': make_user_job[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)
        # create a file as new user
        invocation_command = make_job_invocation({
            'job-template': 'Run Command - SSH Default',
            'inputs': "command='touch /home/{0}/{1}'".format(
                username, filename),
            'search-query': "name ~ {0}".format(self.client.hostname),
            'effective-user': '******'.format(username),
        })
        try:
            self.assertEqual(invocation_command['success'], u'1')
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)
        # check the file owner
        result = ssh.command(
            '''stat -c '%U' /home/{0}/{1}'''.format(username, filename),
            hostname=self.client.hostname
        )
        # assert the file is owned by the effective user
        self.assertEqual(username, result.stdout[0])

    @stubbed()
    @tier2
    def test_positive_run_custom_job_template(self):
        """Run custom job template against a single host

        :id: 71928f36-61b4-46e6-842c-a051cfd9a68e

        :expectedresults: Verify the job was successfully ran against the host
        """
        template_name = gen_string('alpha', 7)
        make_job_template({
            u'organizations': self.name,
            u'name': template_name,
            u'file': TEMPLATE_FILE
        })
        invocation_command = make_job_invocation({
            'job-template': template_name,
            'search-query': "name ~ {0}".format(self.client.hostname),
        })
        try:
            self.assertEqual(invocation_command['success'], u'1')
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)

    @stubbed()
    @tier3
    def test_positive_run_scheduled_job_template(self):
        """Schedule a job to be ran against a host

        :id: 1953517b-6908-40aa-858b-747629d2f374

        :expectedresults: Verify the job was successfully ran after the
            designated time
        """
        system_current_time = ssh.command('date +"%b %d %Y %I:%M%p"').stdout[0]
        current_time_object = datetime.strptime(
            system_current_time, '%b %d %Y %I:%M%p')
        plan_time = (current_time_object + timedelta(seconds=30)).strftime(
            "%Y-%m-%d %H:%M")
        invocation_command = make_job_invocation({
            'job-template': 'Run Command - SSH Default',
            'inputs': 'command="ls"',
            'start-at': plan_time,
            'search-query': "name ~ {0}".format(self.client.hostname),
        })
        # Wait until the job runs
        pending_state = u'1'
        while pending_state != u'0':
            invocation_info = JobInvocation.info({
                'id': invocation_command[u'id']})
            pending_state = invocation_info[u'pending']
            sleep(30)
        invocation_info = JobInvocation.info({
            'id': invocation_command[u'id']})
        try:
            self.assertEqual(invocation_info['success'], u'1')
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)

    @stubbed()
    @tier3
    @upgrade
    def test_positive_run_default_job_template_multiple_hosts(self):
        """Run default job template against multiple hosts

        :id: 415c0156-be77-4676-918b-c0d4be810b0e

        :expectedresults: Verify the job was successfully ran against all hosts
        """
        with VirtualMachine(
            distro=DISTRO_RHEL7,
            provisioning_server=settings.compute_resources.libvirt_hostname,
            bridge=settings.vlan_networking.bridge,
        ) as client2:
            client2.install_katello_ca()
            client2.register_contenthost(
                self.org.label, lce='Library')
            add_remote_execution_ssh_key(client2.ip_addr)
            invocation_command = make_job_invocation({
                'job-template': 'Run Command - SSH Default',
                'inputs': 'command="ls"',
                'search-query': "name ~ {0} or name ~ {1}".format(
                    self.client.hostname, client2.hostname),
            })
            # collect output messages from clients
            output_msgs = []
            for vm in self.client, client2:
                output_msgs.append(
                    'host output from {0}: {1}'.format(
                        vm.hostname,
                        ' '.join(JobInvocation.get_output({
                            'id': invocation_command[u'id'],
                            'host': vm.hostname})
                        )
                    )
                )
            self.assertEqual(invocation_command['success'], u'2', output_msgs)

    @stubbed()
    @tier3
    @upgrade
    def test_positive_install_multiple_packages_with_a_job(self):
        """Run job to install several packages on host

        :id: 1cf2709e-e6cd-46c9-a7b7-c2e542c0e943

        :expectedresults: Verify the packages were successfully installed
            on host
        """
        packages = ["cow", "dog", "lion"]
        # Create a custom repo
        repo = entities.Repository(
            content_type='yum',
            product=entities.Product(organization=self.org).create(),
            url=FAKE_0_YUM_REPO,
        ).create()
        repo.sync()
        prod = repo.product.read()
        subs = entities.Subscription().search(
            query={'search': 'name={0}'.format(prod.name)}
        )
        self.assertGreater(
            len(subs), 0, 'No subscriptions matching the product returned'
        )

        ak = entities.ActivationKey(
            organization=self.org,
            content_view=self.org.default_content_view,
            environment=self.org.library
        ).create()
        ak.add_subscriptions(data={'subscriptions': [{'id': subs[0].id}]})
        self.client.register_contenthost(
            org=self.org.label, activation_key=ak.name
        )

        invocation_command = make_job_invocation({
            'job-template': 'Install Package - Katello SSH Default',
            'inputs': 'package={0} {1} {2}'.format(*packages),
            'search-query': "name ~ {0}".format(self.client.hostname),
        })
        try:
            self.assertEqual(invocation_command['success'], u'1')
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)
        result = ssh.command(
            "rpm -q {0}".format(" ".join(packages)),
            hostname=self.client.hostname
        )
        self.assertEqual(result.return_code, 0)

    @stubbed()
    @tier3
    def test_positive_run_recurring_job_with_max_iterations(self):
        """Run default job template multiple times with max iteration

        :id: 37fb7d77-dbb1-45ae-8bd7-c70be7f6d949

        :expectedresults: Verify the job was run not more than the specified
            number of times.
        """
        invocation_command = make_job_invocation({
            'job-template': 'Run Command - SSH Default',
            'inputs': 'command="ls"',
            'search-query': "name ~ {0}".format(self.client.hostname),
            'cron-line': '* * * * *',  # every minute
            'max-iteration': 2,  # just two runs
        })
        if not bz_bug_is_open(1431190):
            JobInvocation.get_output({
                'id': invocation_command[u'id'],
                'host': self.client.hostname
            })
            try:
                self.assertEqual(invocation_command['status'], u'queued')
            except AssertionError:
                result = 'host output: {0}'.format(
                    ' '.join(JobInvocation.get_output({
                        'id': invocation_command[u'id'],
                        'host': self.client.hostname})
                        )
                    )
                raise AssertionError(result)
        sleep(150)
        rec_logic = RecurringLogic.info({
            'id': invocation_command['recurring-logic-id']})
        self.assertEqual(rec_logic['state'], u'finished')
        self.assertEqual(rec_logic['iteration'], u'2')

    @stubbed()
    @tier3
    def test_positive_run_job_multiple_hosts_time_span(self):
        """Run job against multiple hosts with time span setting

        :id: 82d69069-0592-4083-8992-8969235cc8c9

        :expectedresults: Verify the jobs were successfully distributed
            across the specified time sequence
        """
        # currently it is not possible to get subtasks from
        # a task other than via UI

    @stubbed()
    @tier3
    @upgrade
    def test_positive_run_job_multiple_hosts_concurrency(self):
        """Run job against multiple hosts with concurrency-level

        :id: 15639753-fe50-4e33-848a-04fe464947a6

        :expectedresults: Verify the number of running jobs does comply
            with the concurrency-level setting
        """
        # currently it is not possible to get subtasks from
        # a task other than via UI

    @tier2
    def test_positive_run_default_job_template_by_ip(self):
        """Run default template on host connected by ip

        :id: 811c7747-bec6-4a2d-8e5c-b5045d3fbc0d

        :expectedresults: Verify the job was successfully ran against the host
        """
        # set connecting to host via ip
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        invocation_command = make_job_invocation({
            'job-template': 'Run Command - SSH Default',
            'inputs': 'command="ls"',
            'search-query': "name ~ {0}".format(self.client.hostname),
        })
        try:
            self.assertEqual(invocation_command['success'], u'1')
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)

    @tier2
    @skip_if_bug_open('bugzilla', 1451675)
    def test_positive_run_job_effective_user_by_ip(self):
        """Run default job template as effective user on a host by ip

        :id: 0cd75cab-f699-47e6-94d3-4477d2a94bb7

        :expectedresults: Verify the job was successfully run under the
            effective user identity on host
        """
        # set connecting to host via ip
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        # create a user on client via remote job
        username = gen_string('alpha')
        filename = gen_string('alpha')
        make_user_job = make_job_invocation({
            'job-template': 'Run Command - SSH Default',
            'inputs': "command='useradd {0}'".format(username),
            'search-query': "name ~ {0}".format(self.client.hostname),
        })
        try:
            self.assertEqual(make_user_job[u'success'], u'1')
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': make_user_job[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)
        # create a file as new user
        invocation_command = make_job_invocation({
            'job-template': 'Run Command - SSH Default',
            'inputs': "command='touch /home/{0}/{1}'".format(
                username, filename),
            'search-query': "name ~ {0}".format(self.client.hostname),
            'effective-user': '******'.format(username),
        })
        try:
            self.assertEqual(invocation_command['success'], u'1')
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)
        # check the file owner
        result = ssh.command(
            '''stat -c '%U' /home/{0}/{1}'''.format(username, filename),
            hostname=self.client.ip_addr
        )
        # assert the file is owned by the effective user
        self.assertEqual(username, result.stdout[0])

    @tier2
    def test_positive_run_custom_job_template_by_ip(self):
        """Run custom template on host connected by ip

        :id: 9740eb1d-59f5-42b2-b3ab-659ca0202c74

        :expectedresults: Verify the job was successfully ran against the host
        """
        # set connecting to host via ip
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        template_name = gen_string('alpha', 7)
        make_job_template({
            u'organizations': self.org.name,
            u'name': template_name,
            u'file': TEMPLATE_FILE
        })
        invocation_command = make_job_invocation({
            'job-template': template_name,
            'search-query': "name ~ {0}".format(self.client.hostname),
        })
        try:
            self.assertEqual(invocation_command['success'], u'1')
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)

    @tier3
    @upgrade
    def test_positive_run_default_job_template_multiple_hosts_by_ip(self):
        """Run default job template against multiple hosts by ip

        :id: 694a21d3-243b-4296-8bd0-4bad9663af15

        :expectedresults: Verify the job was successfully ran against all hosts
        """
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        with VirtualMachine(
            distro=DISTRO_RHEL7,
            provisioning_server=settings.compute_resources.libvirt_hostname,
            bridge=settings.vlan_networking.bridge,
        ) as client2:
            client2.install_katello_ca()
            client2.register_contenthost(
                self.org.label, lce='Library')
            add_remote_execution_ssh_key(client2.ip_addr)
            Host.set_parameter({
                'host': client2.hostname,
                'name': 'remote_execution_connect_by_ip',
                'value': 'True',
            })
            invocation_command = make_job_invocation({
                'job-template': 'Run Command - SSH Default',
                'inputs': 'command="ls"',
                'search-query': "name ~ {0} or name ~ {1}".format(
                    self.client.hostname, client2.hostname),
            })
            # collect output messages from clients
            output_msgs = []
            for vm in self.client, client2:
                output_msgs.append('host output from {0}: {1}'.format(
                    vm.hostname,
                    ' '.join(JobInvocation.get_output({
                        'id': invocation_command[u'id'],
                        'host': vm.hostname})
                    )
                )
                )
            self.assertEqual(invocation_command['success'], u'2', output_msgs)

    @tier3
    def test_positive_install_multiple_packages_with_a_job_by_ip(self):
        """Run job to install several packages on host by ip

        :id: 8b73033f-83c9-4024-83c3-5e442a79d320

        :expectedresults: Verify the packages were successfully installed
            on host
        """
        # set connecting to host by ip
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        packages = ["cow", "dog", "lion"]
        # Create a custom repo
        repo = entities.Repository(
            content_type='yum',
            product=entities.Product(organization=self.org).create(),
            url=FAKE_0_YUM_REPO,
        ).create()
        repo.sync()
        prod = repo.product.read()
        subs = entities.Subscription().search(
            query={'search': 'name={0}'.format(prod.name)}
        )
        self.assertGreater(
            len(subs), 0, 'No subscriptions matching the product returned'
        )

        ak = entities.ActivationKey(
            organization=self.org,
            content_view=self.org.default_content_view,
            environment=self.org.library
        ).create()
        ak.add_subscriptions(data={'subscriptions': [{'id': subs[0].id}]})
        self.client.register_contenthost(
            org=self.org.label, activation_key=ak.name
        )

        invocation_command = make_job_invocation({
            'job-template': 'Install Package - Katello SSH Default',
            'inputs': 'package={0} {1} {2}'.format(*packages),
            'search-query': "name ~ {0}".format(self.client.hostname),
        })
        try:
            self.assertEqual(invocation_command['success'], u'1')
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)
        result = ssh.command(
            "rpm -q {0}".format(" ".join(packages)),
            hostname=self.client.ip_addr
        )
        self.assertEqual(result.return_code, 0)

    @tier3
    @upgrade
    def test_positive_run_recurring_job_with_max_iterations_by_ip(self):
        """Run default job template multiple times with max iteration by ip

        :id: 0a3d1627-95d9-42ab-9478-a908f2a7c509

        :expectedresults: Verify the job was run not more than the specified
            number of times.
        """
        # set connecting to host by ip
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        invocation_command = make_job_invocation({
            'job-template': 'Run Command - SSH Default',
            'inputs': 'command="ls"',
            'search-query': "name ~ {0}".format(self.client.hostname),
            'cron-line': '* * * * *',  # every minute
            'max-iteration': 2,  # just two runs
        })
        if not bz_bug_is_open(1431190):
            JobInvocation.get_output({
                'id': invocation_command[u'id'],
                'host': self.client.hostname
            })
            try:
                self.assertEqual(invocation_command['status'], u'queued')
            except AssertionError:
                result = 'host output: {0}'.format(
                    ' '.join(JobInvocation.get_output({
                        'id': invocation_command[u'id'],
                        'host': self.client.hostname})
                        )
                    )
                raise AssertionError(result)
        sleep(150)
        rec_logic = RecurringLogic.info({
            'id': invocation_command['recurring-logic-id']})
        self.assertEqual(rec_logic['state'], u'finished')
        self.assertEqual(rec_logic['iteration'], u'2')

    @tier3
    def test_positive_run_scheduled_job_template_by_ip(self):
        """Schedule a job to be ran against a host

        :id: 0407e3de-ef59-4706-ae0d-b81172b81e5c

        :expectedresults: Verify the job was successfully ran after the
            designated time
        """
        system_current_time = ssh.command('date +"%b %d %Y %I:%M%p"').stdout[0]
        current_time_object = datetime.strptime(
            system_current_time, '%b %d %Y %I:%M%p')
        plan_time = (current_time_object + timedelta(seconds=30)).strftime(
            "%Y-%m-%d %H:%M")
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        invocation_command = make_job_invocation({
            'job-template': 'Run Command - SSH Default',
            'inputs': 'command="ls"',
            'start-at': plan_time,
            'search-query': "name ~ {0}".format(self.client.hostname),
        })
        # Wait until the job runs
        pending_state = u'1'
        while pending_state != u'0':
            invocation_info = JobInvocation.info({
                'id': invocation_command[u'id']})
            pending_state = invocation_info[u'pending']
            sleep(30)
        invocation_info = JobInvocation.info({
            'id': invocation_command[u'id']})
        try:
            self.assertEqual(invocation_info['success'], u'1')
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)
    def test_positive_delete_activation_key_5(self):
        """@Test: Delete an Activation key which has registered systems

        @Feature: Activation key - Positive Delete

        @Steps:
        1. Create an Activation key
        2. Register systems to it
        3. Delete the Activation key

        @Assert: Activation key is deleted

        """
        name = gen_string("alpha", 8)
        cv_name = gen_string("alpha", 8)
        env_name = gen_string("alpha", 8)
        product_name = gen_string("alpha", 8)
        # Helper function to create and promote CV to next environment
        self.create_cv(cv_name, env_name, product_name)
        with Session(self.browser) as session:
            make_activationkey(
                session, org=self.org_name, name=name, env=env_name,
                description=gen_string("alpha", 16),
                content_view=cv_name
            )
            self.assertIsNotNone(self.activationkey.search_key(name))
            self.activationkey.associate_product(name, [product_name])
            self.assertIsNotNone(self.activationkey.wait_until_element
                                 (common_locators["alert.success"]))
            # Create VM
            vm = VirtualMachine(distro='rhel65')
            vm.create()
            # Download and Install rpm
            result = vm.run(
                "wget -nd -r -l1 --no-parent -A '*.noarch.rpm' http://{0}/pub/"
                .format(self.server_name)
            )
            self.assertEqual(
                result.return_code, 0,
                "failed to fetch katello-ca rpm: {0}, return code: {1}"
                .format(result.stderr, result.return_code)
            )
            result = vm.run(
                'rpm -i katello-ca-consumer*.noarch.rpm'
            )
            self.assertEqual(
                result.return_code, 0,
                "failed to install katello-ca rpm: {0}, return code: {1}"
                .format(result.stderr, result.return_code)
            )
            # Register client with foreman server using activation-key
            result = vm.run(
                'subscription-manager register --activationkey {0} '
                '--org {1} --force'
                .format(name, self.org_label)
            )
            self.assertEqual(
                result.return_code, 0,
                "failed to register client:: {0} and return code: {1}"
                .format(result.stderr, result.return_code)
            )
            # Delete the activation key
            self.activationkey.delete(name, True)
            self.assertIsNone(self.activationkey.search_key(name))
            # Delete the virtual machine
            vm.destroy()
Example #50
0
 def test_run_raises_exception(self):
     """Check if run raises an exception if the vm is not created"""
     self.configure_provisoning_server()
     vm = VirtualMachine()
     with self.assertRaises(VirtualMachineError):
         vm.run('ls')
Example #51
0
class KatelloAgentTestCase(CLITestCase):
    """Host tests, which require VM with installed katello-agent."""

    org = None
    env = None
    content_view = None
    activation_key = None

    @classmethod
    @skip_if_not_set('clients', 'fake_manifest')
    def setUpClass(cls):
        """Create Org, Lifecycle Environment, Content View, Activation key

        """
        super(KatelloAgentTestCase, cls).setUpClass()
        # Create new org, environment, CV and activation key
        KatelloAgentTestCase.org = make_org()
        KatelloAgentTestCase.env = make_lifecycle_environment({
            u'organization-id': KatelloAgentTestCase.org['id'],
        })
        KatelloAgentTestCase.content_view = make_content_view({
            u'organization-id': KatelloAgentTestCase.org['id'],
        })
        KatelloAgentTestCase.activation_key = make_activation_key({
            u'lifecycle-environment-id': KatelloAgentTestCase.env['id'],
            u'organization-id': KatelloAgentTestCase.org['id'],
        })
        # Add subscription to Satellite Tools repo to activation key
        setup_org_for_a_rh_repo({
            u'product': PRDS['rhel'],
            u'repository-set': REPOSET['rhst7'],
            u'repository': REPOS['rhst7']['name'],
            u'organization-id': KatelloAgentTestCase.org['id'],
            u'content-view-id': KatelloAgentTestCase.content_view['id'],
            u'lifecycle-environment-id': KatelloAgentTestCase.env['id'],
            u'activationkey-id': KatelloAgentTestCase.activation_key['id'],
        })
        # Create custom repo, add subscription to activation key
        setup_org_for_a_custom_repo({
            u'url': FAKE_0_YUM_REPO,
            u'organization-id': KatelloAgentTestCase.org['id'],
            u'content-view-id': KatelloAgentTestCase.content_view['id'],
            u'lifecycle-environment-id': KatelloAgentTestCase.env['id'],
            u'activationkey-id': KatelloAgentTestCase.activation_key['id'],
        })

    def setUp(self):
        """Create VM, subscribe it to satellite-tools repo, install katello-ca
        and katello-agent packages

        """
        super(KatelloAgentTestCase, self).setUp()
        # Create VM and register content host
        self.client = VirtualMachine(distro='rhel71')
        self.client.create()
        self.client.install_katello_ca()
        # Register content host, install katello-agent
        self.client.register_contenthost(
            KatelloAgentTestCase.activation_key['name'],
            KatelloAgentTestCase.org['label']
        )
        self.host = Host.info({'name': self.client.hostname})
        self.client.enable_repo(REPOS['rhst7']['id'])
        self.client.install_katello_agent()

    def tearDown(self):
        self.client.destroy()
        super(KatelloAgentTestCase, self).tearDown()

    @tier3
    @run_only_on('sat')
    def test_positive_get_errata_info(self):
        """Get errata info

        @id: afb5ab34-1703-49dc-8ddc-5e032c1b86d7

        @Assert: Errata info was displayed


        @CaseLevel: System
        """
        self.client.download_install_rpm(
            FAKE_0_YUM_REPO,
            FAKE_0_CUSTOM_PACKAGE
        )
        result = Host.errata_info({
            u'host-id': self.host['id'],
            u'id': FAKE_0_ERRATA_ID,
        })
        self.assertEqual(result[0]['errata-id'], FAKE_0_ERRATA_ID)
        self.assertEqual(result[0]['packages'], FAKE_0_CUSTOM_PACKAGE)

    @tier3
    @run_only_on('sat')
    def test_positive_apply_errata(self):
        """Apply errata to a host

        @id: 8d0e5c93-f9fd-4ec0-9a61-aa93082a30c5

        @Assert: Errata is scheduled for installation


        @CaseLevel: System
        """
        self.client.download_install_rpm(
            FAKE_0_YUM_REPO,
            FAKE_0_CUSTOM_PACKAGE
        )
        Host.errata_apply({
            u'errata-ids': FAKE_0_ERRATA_ID,
            u'host-id': self.host['id'],
        })

    @tier3
    @run_only_on('sat')
    def test_positive_install_package(self):
        """Install a package to a host remotely

        @id: b1009bba-0c7e-4b00-8ac4-256e5cfe4a78

        @Assert: Package was successfully installed


        @CaseLevel: System
        """
        Host.package_install({
            u'host-id': self.host['id'],
            u'packages': FAKE_0_CUSTOM_PACKAGE_NAME,
        })
        result = self.client.run(
            'rpm -q {0}'.format(FAKE_0_CUSTOM_PACKAGE_NAME)
        )
        self.assertEqual(result.return_code, 0)

    @tier3
    @run_only_on('sat')
    def test_positive_remove_package(self):
        """Remove a package from a host remotely

        @id: 573dec11-8f14-411f-9e41-84426b0f23b5

        @Assert: Package was successfully removed


        @CaseLevel: System
        """
        self.client.download_install_rpm(
            FAKE_0_YUM_REPO,
            FAKE_0_CUSTOM_PACKAGE
        )
        Host.package_remove({
            u'host-id': self.host['id'],
            u'packages': FAKE_0_CUSTOM_PACKAGE_NAME,
        })
        result = self.client.run(
            'rpm -q {0}'.format(FAKE_0_CUSTOM_PACKAGE_NAME)
        )
        self.assertNotEqual(result.return_code, 0)

    @tier3
    @run_only_on('sat')
    def test_positive_upgrade_package(self):
        """Upgrade a host package remotely

        @id: ad751c63-7175-40ae-8bc4-800462cd9c29

        @Assert: Package was successfully upgraded


        @CaseLevel: System
        """
        self.client.run('yum install -y {0}'.format(FAKE_1_CUSTOM_PACKAGE))
        Host.package_upgrade({
            u'host-id': self.host['id'],
            u'packages': FAKE_1_CUSTOM_PACKAGE_NAME,
        })
        result = self.client.run('rpm -q {0}'.format(FAKE_2_CUSTOM_PACKAGE))
        self.assertEqual(result.return_code, 0)

    @tier3
    @run_only_on('sat')
    def test_positive_upgrade_packages_all(self):
        """Upgrade all the host packages remotely

        @id: 003101c7-bb95-4e51-a598-57977b2858a9

        @Assert: Packages (at least 1 with newer version available) were
        successfully upgraded


        @CaseLevel: System
        """
        self.client.run('yum install -y {0}'.format(FAKE_1_CUSTOM_PACKAGE))
        Host.package_upgrade_all({'host-id': self.host['id']})
        result = self.client.run('rpm -q {0}'.format(FAKE_2_CUSTOM_PACKAGE))
        self.assertEqual(result.return_code, 0)

    @tier3
    @run_only_on('sat')
    def test_positive_install_package_group(self):
        """Install a package group to a host remotely

        @id: 8c28c188-2903-44d1-ab1e-b74f6d6affcf

        @Assert: Package group was successfully installed


        @CaseLevel: System
        """
        Host.package_group_install({
            u'groups': FAKE_0_CUSTOM_PACKAGE_GROUP_NAME,
            u'host-id': self.host['id'],
        })
        for package in FAKE_0_CUSTOM_PACKAGE_GROUP:
            result = self.client.run('rpm -q {0}'.format(package))
            self.assertEqual(result.return_code, 0)

    @tier3
    @run_only_on('sat')
    def test_positive_remove_package_group(self):
        """Remove a package group from a host remotely

        @id: c80dbeff-93b4-4cd4-8fae-6a4d1bfc94f0

        @Assert: Package group was successfully removed


        @CaseLevel: System
        """
        hammer_args = {
            u'groups': FAKE_0_CUSTOM_PACKAGE_GROUP_NAME,
            u'host-id': self.host['id'],
        }
        Host.package_group_install(hammer_args)
        Host.package_group_remove(hammer_args)
        for package in FAKE_0_CUSTOM_PACKAGE_GROUP:
            result = self.client.run('rpm -q {0}'.format(package))
            self.assertNotEqual(result.return_code, 0)

    @tier3
    def test_negative_unregister_and_pull_content(self):
        """Attempt to retrieve content after host has been unregistered from
        Satellite

        @id: de0d0d91-b1e1-4f0e-8a41-c27df4d6b6fd

        @assert: Host can no longer retrieve content from satellite

        @CaseLevel: System
        """
        result = self.client.run('subscription-manager unregister')
        self.assertEqual(result.return_code, 0)
        result = self.client.run(
            'yum install -y {0}'.format(FAKE_1_CUSTOM_PACKAGE))
        self.assertNotEqual(result.return_code, 0)
Example #52
0
 def test_run_raises_exception(self):
     """Check if run raises an exception if the vm is not created"""
     vm = VirtualMachine()
     with self.assertRaises(VirtualMachineError):
         vm.run('ls')
    def test_usage_limit(self):
        """@Test: Test that Usage limit actually limits usage

        @Feature: Activation key - Usage limit

        @Steps:
        1. Create Activation key
        2. Update Usage Limit to a finite number
        3. Register Systems to match the Usage Limit
        4. Attempt to register an other system after reaching the Usage Limit

        @Assert: System Registration fails. Appropriate error shown

        """
        name = gen_string("alpha", 10)
        host_limit = "1"
        with Session(self.browser) as session:
            make_activationkey(session, org=self.org_name,
                               name=name, env=ENVIRONMENT)
            self.assertIsNotNone(self.activationkey.search_key(name))
            self.activationkey.update(name, limit=host_limit)
            self.assertIsNotNone(self.activationkey.wait_until_element
                                 (common_locators["alert.success"]))
            # Create VM1
            vm1 = VirtualMachine(distro='rhel65')
            vm1.create()
            # Download and Install rpm
            result = vm1.run(
                "wget -nd -r -l1 --no-parent -A '*.noarch.rpm' http://{0}/pub/"
                .format(self.server_name)
            )
            self.assertEqual(
                result.return_code, 0,
                "failed to fetch katello-ca rpm: {0}, return code: {1}"
                .format(result.stderr, result.return_code)
            )
            result = vm1.run(
                'rpm -i katello-ca-consumer*.noarch.rpm'
            )
            self.assertEqual(
                result.return_code, 0,
                "failed to install katello-ca rpm: {0}, return code: {1}"
                .format(result.stderr, result.return_code)
            )
            # Register client1 with foreman server using activation-key
            result = vm1.run(
                'subscription-manager register --activationkey {0} '
                '--org {1} --force'
                .format(name, self.org_label)
            )
            self.assertEqual(
                result.return_code, 0,
                "failed to register client:: {0} and return code: {1}"
                .format(result.stderr, result.return_code)
            )
            # Create VM2
            vm2 = VirtualMachine(distro='rhel65')
            vm2.create()
            # Download and Install rpm
            result = vm2.run(
                "wget -nd -r -l1 --no-parent -A '*.noarch.rpm' http://{0}/pub/"
                .format(self.server_name)
            )
            self.assertEqual(
                result.return_code, 0,
                "failed to fetch katello-ca rpm: {0}, return code: {1}"
                .format(result.stderr, result.return_code)
            )
            result = vm2.run(
                'rpm -i katello-ca-consumer*.noarch.rpm'
            )
            self.assertEqual(
                result.return_code, 0,
                "failed to install katello-ca rpm: {0}, return code: {1}"
                .format(result.stderr, result.return_code)
            )
            # Register client2 with foreman server using activation-key
            result = vm2.run(
                'subscription-manager register --activationkey {0} '
                '--org {1} --force'
                .format(name, self.org_label)
            )
            # Assert system registration fails for client2 and
            # appropriate error raised
            self.assertNotEqual(result.return_code, 0)
            self.assertGreater(len(result.stderr), 0,
                               "There should be an exception here.")
            self.assertIn('Max Content Hosts ({0}) reached for activation key'
                          .format(host_limit), result.stderr)
            # Destroy both VM's
            vm1.destroy()
            vm2.destroy()
Example #54
0
 def test_provisioning_server_not_configured(self):
     """Check if an exception is raised if missing provisioning_server"""
     vm = VirtualMachine()
     with patch.object(vm, 'provisioning_server', None):
         with self.assertRaises(VirtualMachineError):
             vm.create()
Example #55
0
class ContentHostTestCase(UITestCase):
    """Implements Content Host tests in UI"""

    @classmethod
    def set_session_org(cls):
        """Create an organization for tests, which will be selected
        automatically"""
        cls.session_org = entities.Organization().create()

    @classmethod
    @skip_if_not_set('clients', 'fake_manifest')
    def setUpClass(cls):
        """Create Lifecycle Environment, Content View and Activation key
        """
        super(ContentHostTestCase, cls).setUpClass()
        cls.env = entities.LifecycleEnvironment(
            organization=cls.session_org).create()
        cls.content_view = entities.ContentView(
            organization=cls.session_org).create()
        cls.activation_key = entities.ActivationKey(
            environment=cls.env,
            organization=cls.session_org,
        ).create()
        setup_org_for_a_rh_repo({
            'product': PRDS['rhel'],
            'repository-set': REPOSET['rhst7'],
            'repository': REPOS['rhst7']['name'],
            'organization-id': cls.session_org.id,
            'content-view-id': cls.content_view.id,
            'lifecycle-environment-id': cls.env.id,
            'activationkey-id': cls.activation_key.id,
        })
        setup_org_for_a_custom_repo({
            'url': FAKE_6_YUM_REPO,
            'organization-id': cls.session_org.id,
            'content-view-id': cls.content_view.id,
            'lifecycle-environment-id': cls.env.id,
            'activationkey-id': cls.activation_key.id,
        })

    def setUp(self):
        """Create a VM, subscribe it to satellite-tools repo, install
        katello-ca and katello-agent packages"""
        super(ContentHostTestCase, self).setUp()
        self.client = VirtualMachine(distro='rhel71')
        self.client.create()
        self.client.install_katello_ca()
        result = self.client.register_contenthost(
            self.session_org.label, self.activation_key.name)
        self.assertEqual(result.return_code, 0)
        self.client.enable_repo(REPOS['rhst7']['id'])
        self.client.install_katello_agent()

    def tearDown(self):
        """Destroy the VM"""
        self.client.destroy()
        super(ContentHostTestCase, self).tearDown()

    @tier3
    def test_positive_install_package(self):
        """Install a package to a host remotely

        @id: 13b9422d-4b7a-4068-9a57-a94602cd6410

        @assert: Package was successfully installed

        @CaseLevel: System
        """
        with Session(self.browser):
            result = self.contenthost.execute_package_action(
                self.client.hostname,
                'Package Install',
                FAKE_0_CUSTOM_PACKAGE_NAME,
            )
            self.assertEqual(result, 'success')
            self.assertIsNotNone(self.contenthost.package_search(
                self.client.hostname, FAKE_0_CUSTOM_PACKAGE_NAME))

    @tier3
    def test_positive_remove_package(self):
        """Remove a package from a host remotely

        @id: 86d8896b-06d9-4c99-937e-f3aa07b4eb69

        @Assert: Package was successfully removed

        @CaseLevel: System
        """
        self.client.download_install_rpm(
            FAKE_6_YUM_REPO,
            FAKE_0_CUSTOM_PACKAGE
        )
        with Session(self.browser):
            result = self.contenthost.execute_package_action(
                self.client.hostname,
                'Package Remove',
                FAKE_0_CUSTOM_PACKAGE_NAME,
            )
            self.assertEqual(result, 'success')
            self.assertIsNone(self.contenthost.package_search(
                self.client.hostname, FAKE_0_CUSTOM_PACKAGE_NAME))

    @tier3
    def test_positive_upgrade_package(self):
        """Upgrade a host package remotely

        @id: 1969db93-e7af-4f5f-973d-23c222224db6

        @Assert: Package was successfully upgraded

        @CaseLevel: System
        """
        self.client.run('yum install -y {0}'.format(FAKE_1_CUSTOM_PACKAGE))
        with Session(self.browser):
            result = self.contenthost.execute_package_action(
                self.client.hostname,
                'Package Update',
                FAKE_1_CUSTOM_PACKAGE_NAME,
            )
            self.assertEqual(result, 'success')
            self.assertIsNotNone(self.contenthost.package_search(
                self.client.hostname, FAKE_2_CUSTOM_PACKAGE))

    @tier3
    def test_positive_install_package_group(self):
        """Install a package group to a host remotely

        @id: a43fb21b-5f6a-4f14-8cd6-114ec287540c

        @Assert: Package group was successfully installed

        @CaseLevel: System
        """
        with Session(self.browser):
            result = self.contenthost.execute_package_action(
                self.client.hostname,
                'Group Install',
                FAKE_0_CUSTOM_PACKAGE_GROUP_NAME,
            )
            self.assertEqual(result, 'success')
            for package in FAKE_0_CUSTOM_PACKAGE_GROUP:
                self.assertIsNotNone(self.contenthost.package_search(
                    self.client.hostname, package))

    @tier3
    def test_positive_remove_package_group(self):
        """Remove a package group from a host remotely

        @id: dbeea1f2-adf4-4ad8-a989-efad8ce21b98

        @Assert: Package group was successfully removed

        @CaseLevel: System
        """
        with Session(self.browser):
            result = self.contenthost.execute_package_action(
                self.client.hostname,
                'Group Install',
                FAKE_0_CUSTOM_PACKAGE_GROUP_NAME,
            )
            self.assertEqual(result, 'success')
            result = self.contenthost.execute_package_action(
                self.client.hostname,
                'Group Remove',
                FAKE_0_CUSTOM_PACKAGE_GROUP_NAME,
            )
            self.assertEqual(result, 'success')
            for package in FAKE_0_CUSTOM_PACKAGE_GROUP:
                self.assertIsNone(self.contenthost.package_search(
                    self.client.hostname, package))

    @tier3
    def test_positive_install_errata(self):
        """Install a errata to a host remotely

        @id: 13b9422d-4b7a-4068-9a57-a94602cd6410

        @assert: Errata was successfully installed

        @CaseLevel: System
        """
        self.client.run('yum install -y {0}'.format(FAKE_1_CUSTOM_PACKAGE))
        with Session(self.browser):
            result = self.contenthost.install_errata(
                self.client.hostname,
                FAKE_2_ERRATA_ID,
            )
            self.assertEqual(result, 'success')
            self.assertIsNotNone(self.contenthost.package_search(
                self.client.hostname, FAKE_2_CUSTOM_PACKAGE))
Example #56
0
class IncrementalUpdateTestCase(TestCase):
    """Tests for the Incremental Update feature"""

    @classmethod
    @skip_if_not_set('clients')
    def setUpClass(cls):
        """Creates the pre-requisites for the Incremental updates that used in
        all test"""
        super(IncrementalUpdateTestCase, cls).setUpClass()
        # Create a new Organization
        cls.org = Organization(name=gen_alpha()).create()

        # Create two lifecycle environments - DEV, QE
        cls.dev_lce = LifecycleEnvironment(
            name='DEV',
            organization=cls.org
        ).create()
        cls.qe_lce = LifecycleEnvironment(
            name='QE',
            prior=cls.dev_lce,
            organization=cls.org
        ).create()

        # Upload manifest
        with manifests.clone() as manifest:
            upload_manifest(cls.org.id, manifest.content)

        # Enable repositories - RHE Virtualization Agents and rhel6 sat6tools
        rhva_6_repo_id = enable_rhrepo_and_fetchid(
            basearch=DEFAULT_ARCHITECTURE,
            org_id=cls.org.id,
            product=PRDS['rhel'],
            repo=REPOS['rhva6']['name'],
            reposet=REPOSET['rhva6'],
            releasever=DEFAULT_RELEASE_VERSION,
        )
        rhel6_sat6tools_repo_id = enable_rhrepo_and_fetchid(
            basearch=DEFAULT_ARCHITECTURE,
            org_id=cls.org.id,
            product=PRDS['rhel'],
            repo=REPOS['rhst6']['name'],
            reposet=REPOSET['rhst6'],
            releasever=None,
        )

        # Read the repositories
        cls.rhva_6_repo = Repository(id=rhva_6_repo_id).read()
        cls.rhel6_sat6tools_repo = Repository(
            id=rhel6_sat6tools_repo_id
        ).read()

        # Sync the enabled repositories
        try:
            cls.old_task_timeout = entity_mixins.TASK_TIMEOUT
            # Update timeout to 15 minutes to finish sync
            entity_mixins.TASK_TIMEOUT = 900
            for repo in [cls.rhva_6_repo, cls.rhel6_sat6tools_repo]:
                assert Repository(id=repo.id).sync()['result'] == u'success'
        finally:
            entity_mixins.TASK_TIMEOUT = cls.old_task_timeout

    def setUp(self):
        """Creates the pre-requisites for the Incremental updates that used per
        each test"""
        super(IncrementalUpdateTestCase, self).setUp()
        # Create content view that will be used filtered erratas
        self.rhel_6_partial_cv = ContentView(
            organization=self.org,
            name=gen_alpha(),
            repository=[self.rhva_6_repo, self.rhel6_sat6tools_repo]
        ).create()

        # Create a content view filter to filter out errata
        rhel_6_partial_cvf = ErratumContentViewFilter(
            content_view=self.rhel_6_partial_cv,
            type='erratum',
            name='rhel_6_partial_cv_filter',
            repository=[self.rhva_6_repo]
        ).create()

        # Create a content view filter rule - filtering out errata in the last
        # 365 days
        start_date = (date.today() - timedelta(days=365)).strftime('%Y-%m-%d')
        ContentViewFilterRule(
            content_view_filter=rhel_6_partial_cvf,
            types=['security', 'enhancement', 'bugfix'],
            start_date=start_date,
            end_date=date.today().strftime('%Y-%m-%d')
        ).create()

        # Publish content view and re-read it

        self.rhel_6_partial_cv.publish()
        self.rhel_6_partial_cv = self.rhel_6_partial_cv.read()

        # Promote content view to 'DEV' and 'QE'
        assert len(self.rhel_6_partial_cv.version) == 1
        for env in (self.dev_lce, self.qe_lce):
            promote(self.rhel_6_partial_cv.version[0], env.id)

        # Create host collection
        self.rhel_6_partial_hc = HostCollection(
            organization=self.org, name=gen_alpha(), max_hosts=5).create()

        # Create activation key for content view
        kwargs = {'organization': self.org, 'environment': self.qe_lce.id}
        rhel_6_partial_ak = ActivationKey(
            name=gen_alpha(),
            content_view=self.rhel_6_partial_cv,
            host_collection=[self.rhel_6_partial_hc],
            **kwargs
        ).create()

        # Assign subscription to activation key. Fetch available subscriptions
        subs = Subscription(organization=self.org).search()
        assert len(subs) > 0

        # Add subscription to activation key
        sub_found = False
        for sub in subs:
            if sub.read_json()['product_name'] == DEFAULT_SUBSCRIPTION_NAME:
                rhel_6_partial_ak.add_subscriptions(data={
                    u'subscription_id': sub.id
                })
                sub_found = True
        assert sub_found

        # Enable product content in activation key
        rhel_6_partial_ak.content_override(data={'content_override': {
            u'content_label': REPOS['rhst6']['id'],
            u'value': u'1'
        }})

        # Create client machine and register it to satellite with
        # rhel_6_partial_ak
        self.vm = VirtualMachine(distro=DISTRO_RHEL6, tag='incupdate')
        self.addCleanup(vm_cleanup, self.vm)
        self.setup_vm(self.vm, rhel_6_partial_ak.name, self.org.label)
        self.vm.enable_repo(REPOS['rhva6']['id'])
        self.vm.run('yum install -y {0}'.format(REAL_0_RH_PACKAGE))

        # Find the content hosts and save them
        hosts = Host(organization=str(self.org.id)).search()
        self.partial_hosts = []
        for host in hosts:
            self.partial_hosts.append(host)

    @staticmethod
    def setup_vm(client, act_key, org_name):
        """Creates the vm and registers it to the satellite"""
        client.create()
        client.install_katello_ca()

        # Register content host, install katello-agent
        client.register_contenthost(
            org_name,
            act_key,
            releasever=DEFAULT_RELEASE_VERSION
        )
        assert client.subscribed
        client.install_katello_agent()
        client.run('katello-package-upload')

    @staticmethod
    def get_applicable_errata(repo):
        """Retrieves applicable errata for the given repo"""
        return Errata(repository=repo).search(
            query={'errata_restrict_applicable': True}
        )

    @run_only_on('sat')
    @tier4
    def test_positive_noapply_api(self):
        """Check if api incremental update can be done without
        actually applying it

        :id: 481c5ff2-801f-4eff-b1e0-95ea5bb37f95

        :Setup:  The prerequisites are already covered in the setUpClass() but
            for easy debug, get the content view id, Repository id and
            Lifecycle environment id using hammer and plug these statements on
            the top of the test. For example::

                self.rhel_6_partial_cv = ContentView(id=38).read()
                self.rhva_6_repo = Repository(id=164).read()
                self.qe_lce = LifecycleEnvironment(id=46).read()

        :expectedresults: Incremental update completed with no errors and
            Content view has a newer version

        :CaseLevel: System
        """
        # Get the content view versions and use the recent one.  API always
        # returns the versions in ascending order so it is safe to assume the
        # last one in the list is the recent
        cv_versions = self.rhel_6_partial_cv.version

        # Get the applicable errata
        errata_list = self.get_applicable_errata(self.rhva_6_repo)
        self.assertGreater(len(errata_list), 0)

        # Apply incremental update using the first applicable errata
        ContentViewVersion().incremental_update(data={
            'content_view_version_environments': [{
                'content_view_version_id': cv_versions[-1].id,
                'environment_ids': [self.qe_lce.id]
            }],
            'add_content': {
                'errata_ids': [errata_list[0].id]
            }
        })

        # Re-read the content view to get the latest versions
        self.rhel_6_partial_cv = self.rhel_6_partial_cv.read()
        self.assertGreater(
            len(self.rhel_6_partial_cv.version),
            len(cv_versions)
        )

    @run_only_on('sat')
    @tier4
    def test_positive_noapply_cli(self):
        """Check if cli incremental update can be done without
        actually applying it

        :id: f25b0919-74cb-4e2c-829e-482558990b3c

        :expectedresults: Incremental update completed with no errors and
            Content view has a newer version

        :CaseLevel: System
        """
        # Get the content view versions and use the recent one.  API always
        # returns the versions in ascending order so it is safe to assume the
        # last one in the list is the recent

        cv_versions = self.rhel_6_partial_cv.version

        # Get the applicable errata
        errata_list = self.get_applicable_errata(self.rhva_6_repo)
        self.assertGreater(len(errata_list), 0)

        # Apply incremental update using the first applicable errata
        ContentViewCLI.version_incremental_update({
            u'content-view-version-id': cv_versions[-1].id,
            u'lifecycle-environment-ids': self.qe_lce.id,
            u'errata-ids': errata_list[0].id,
        })

        # Re-read the content view to get the latest versions
        self.rhel_6_partial_cv = self.rhel_6_partial_cv.read()
        self.assertGreater(
            len(self.rhel_6_partial_cv.version),
            len(cv_versions)
        )
Example #57
0
    def setUp(self):
        """Creates the pre-requisites for the Incremental updates that used per
        each test"""
        super(IncrementalUpdateTestCase, self).setUp()
        # Create content view that will be used filtered erratas
        self.rhel_6_partial_cv = ContentView(
            organization=self.org,
            name=gen_alpha(),
            repository=[self.rhva_6_repo, self.rhel6_sat6tools_repo]
        ).create()

        # Create a content view filter to filter out errata
        rhel_6_partial_cvf = ErratumContentViewFilter(
            content_view=self.rhel_6_partial_cv,
            type='erratum',
            name='rhel_6_partial_cv_filter',
            repository=[self.rhva_6_repo]
        ).create()

        # Create a content view filter rule - filtering out errata in the last
        # 365 days
        start_date = (date.today() - timedelta(days=365)).strftime('%Y-%m-%d')
        ContentViewFilterRule(
            content_view_filter=rhel_6_partial_cvf,
            types=['security', 'enhancement', 'bugfix'],
            start_date=start_date,
            end_date=date.today().strftime('%Y-%m-%d')
        ).create()

        # Publish content view and re-read it

        self.rhel_6_partial_cv.publish()
        self.rhel_6_partial_cv = self.rhel_6_partial_cv.read()

        # Promote content view to 'DEV' and 'QE'
        assert len(self.rhel_6_partial_cv.version) == 1
        for env in (self.dev_lce, self.qe_lce):
            promote(self.rhel_6_partial_cv.version[0], env.id)

        # Create host collection
        self.rhel_6_partial_hc = HostCollection(
            organization=self.org, name=gen_alpha(), max_hosts=5).create()

        # Create activation key for content view
        kwargs = {'organization': self.org, 'environment': self.qe_lce.id}
        rhel_6_partial_ak = ActivationKey(
            name=gen_alpha(),
            content_view=self.rhel_6_partial_cv,
            host_collection=[self.rhel_6_partial_hc],
            **kwargs
        ).create()

        # Assign subscription to activation key. Fetch available subscriptions
        subs = Subscription(organization=self.org).search()
        assert len(subs) > 0

        # Add subscription to activation key
        sub_found = False
        for sub in subs:
            if sub.read_json()['product_name'] == DEFAULT_SUBSCRIPTION_NAME:
                rhel_6_partial_ak.add_subscriptions(data={
                    u'subscription_id': sub.id
                })
                sub_found = True
        assert sub_found

        # Enable product content in activation key
        rhel_6_partial_ak.content_override(data={'content_override': {
            u'content_label': REPOS['rhst6']['id'],
            u'value': u'1'
        }})

        # Create client machine and register it to satellite with
        # rhel_6_partial_ak
        self.vm = VirtualMachine(distro=DISTRO_RHEL6, tag='incupdate')
        self.addCleanup(vm_cleanup, self.vm)
        self.setup_vm(self.vm, rhel_6_partial_ak.name, self.org.label)
        self.vm.enable_repo(REPOS['rhva6']['id'])
        self.vm.run('yum install -y {0}'.format(REAL_0_RH_PACKAGE))

        # Find the content hosts and save them
        hosts = Host(organization=str(self.org.id)).search()
        self.partial_hosts = []
        for host in hosts:
            self.partial_hosts.append(host)
Example #58
0
class ContentHostTestCase(UITestCase):
    """Implements Content Host tests in UI"""

    @classmethod
    def set_session_org(cls):
        """Create an organization for tests, which will be selected
        automatically"""
        cls.session_org = entities.Organization().create()

    @classmethod
    @skip_if_not_set('clients', 'fake_manifest')
    def setUpClass(cls):
        """Create Lifecycle Environment, Content View and Activation key
        """
        super(ContentHostTestCase, cls).setUpClass()
        cls.env = entities.LifecycleEnvironment(
            organization=cls.session_org).create()
        cls.content_view = entities.ContentView(
            organization=cls.session_org).create()
        cls.activation_key = entities.ActivationKey(
            environment=cls.env,
            organization=cls.session_org,
        ).create()
        setup_org_for_a_rh_repo({
            'product': PRDS['rhel'],
            'repository-set': REPOSET['rhst7'],
            'repository': REPOS['rhst7']['name'],
            'organization-id': cls.session_org.id,
            'content-view-id': cls.content_view.id,
            'lifecycle-environment-id': cls.env.id,
            'activationkey-id': cls.activation_key.id,
        }, force_manifest_upload=True)
        setup_org_for_a_custom_repo({
            'url': FAKE_0_YUM_REPO,
            'organization-id': cls.session_org.id,
            'content-view-id': cls.content_view.id,
            'lifecycle-environment-id': cls.env.id,
            'activationkey-id': cls.activation_key.id,
        })
        setup_org_for_a_custom_repo({
            'url': FAKE_6_YUM_REPO,
            'organization-id': cls.session_org.id,
            'content-view-id': cls.content_view.id,
            'lifecycle-environment-id': cls.env.id,
            'activationkey-id': cls.activation_key.id,
        })

    def setUp(self):
        """Create a VM, subscribe it to satellite-tools repo, install
        katello-ca and katello-agent packages"""
        super(ContentHostTestCase, self).setUp()
        self.client = VirtualMachine(distro=DISTRO_RHEL7)
        self.addCleanup(vm_cleanup, self.client)
        self.client.create()
        self.client.install_katello_ca()
        self.client.register_contenthost(
            self.session_org.label, self.activation_key.name)
        self.assertTrue(self.client.subscribed)
        self.client.enable_repo(REPOS['rhst7']['id'])
        self.client.install_katello_agent()

    @skip_if_bug_open('bugzilla', 1495271)
    @tier3
    def test_positive_search_by_subscription_status(self):
        """Register host into the system and search for it afterwards by
        subscription status

        :id: b4d24ee7-51b9-43e4-b0c9-7866b6340ce1

        :expectedresults: Validate that host can be found for valid
            subscription status and that host is not present in the list for
            invalid status

        :BZ: 1406855, 1498827

        :CaseLevel: System
        """
        with Session(self):
            self.assertIsNotNone(self.contenthost.search(self.client.hostname))
            self.assertIsNotNone(
                self.contenthost.search(
                    self.client.hostname,
                    _raw_query='subscription_status = valid',
                )
            )
            self.assertIsNone(
                self.contenthost.search(
                    self.client.hostname,
                    _raw_query='subscription_status != valid',
                )
            )

    @tier3
    def test_positive_sort_by_last_checkin(self):
        """Register two content hosts and then sort them by last checkin date

        :id: c42c1347-8b3a-4ba7-95d1-609e2e9ec40e

        :expectedresults: Validate that content hosts are sorted properly

        :BZ: 1281251

        :CaseLevel: System
        """
        with VirtualMachine(distro=DISTRO_RHEL7) as vm:
            vm.install_katello_ca()
            vm.register_contenthost(
                self.session_org.label, self.activation_key.name)
            self.assertTrue(vm.subscribed)
            vm.enable_repo(REPOS['rhst7']['id'])
            vm.install_katello_agent()
            with Session(self):
                self.assertIsNotNone(
                    self.contenthost.search(self.client.hostname))
                if bz_bug_is_open(1495271):
                    self.dashboard.navigate_to_entity()
                self.assertIsNotNone(self.contenthost.search(vm.hostname))
                self.contenthost.click(common_locators['kt_clear_search'])
                if bz_bug_is_open(1495271):
                    self.dashboard.navigate_to_entity()
                    self.contenthost.navigate_to_entity()
                # prevent any issues in case some default sorting was set
                self.contenthost.sort_table_by_column('Name')
                dates = self.contenthost.sort_table_by_column('Last Checkin')
                self.assertGreater(dates[1], dates[0])
                dates = self.contenthost.sort_table_by_column('Last Checkin')
                self.assertGreater(dates[0], dates[1])

    @tier3
    def test_positive_install_package(self):
        """Install a package to a host remotely

        :id: 13b9422d-4b7a-4068-9a57-a94602cd6410

        :expectedresults: Package was successfully installed

        :CaseLevel: System
        """
        with Session(self):
            result = self.contenthost.execute_package_action(
                self.client.hostname,
                'Package Install',
                FAKE_0_CUSTOM_PACKAGE_NAME,
            )
            self.assertEqual(result, 'success')
            self.assertIsNotNone(self.contenthost.package_search(
                self.client.hostname, FAKE_0_CUSTOM_PACKAGE_NAME))

    @tier3
    def test_negative_install_package(self):
        """Attempt to install non-existent package to a host remotely

        :id: d60b70f9-c43f-49c0-ae9f-187ffa45ac97

        :BZ: 1262940

        :expectedresults: Task finished with warning

        :CaseLevel: System
        """
        with Session(self):
            result = self.contenthost.execute_package_action(
                self.client.hostname,
                'Package Install',
                gen_string('alphanumeric'),
            )
            self.assertEqual(result, 'warning')

    @tier3
    def test_positive_remove_package(self):
        """Remove a package from a host remotely

        :id: 86d8896b-06d9-4c99-937e-f3aa07b4eb69

        :expectedresults: Package was successfully removed

        :CaseLevel: System
        """
        self.client.download_install_rpm(
            FAKE_6_YUM_REPO,
            FAKE_0_CUSTOM_PACKAGE
        )
        with Session(self):
            result = self.contenthost.execute_package_action(
                self.client.hostname,
                'Package Remove',
                FAKE_0_CUSTOM_PACKAGE_NAME,
            )
            self.assertEqual(result, 'success')
            self.assertIsNone(self.contenthost.package_search(
                self.client.hostname, FAKE_0_CUSTOM_PACKAGE_NAME))

    @tier3
    def test_positive_upgrade_package(self):
        """Upgrade a host package remotely

        :id: 1969db93-e7af-4f5f-973d-23c222224db6

        :expectedresults: Package was successfully upgraded

        :CaseLevel: System
        """
        self.client.run('yum install -y {0}'.format(FAKE_1_CUSTOM_PACKAGE))
        with Session(self):
            result = self.contenthost.execute_package_action(
                self.client.hostname,
                'Package Update',
                FAKE_1_CUSTOM_PACKAGE_NAME,
            )
            self.assertEqual(result, 'success')
            self.assertIsNotNone(self.contenthost.package_search(
                self.client.hostname, FAKE_2_CUSTOM_PACKAGE))

    @tier3
    @upgrade
    def test_positive_install_package_group(self):
        """Install a package group to a host remotely

        :id: a43fb21b-5f6a-4f14-8cd6-114ec287540c

        :expectedresults: Package group was successfully installed

        :CaseLevel: System
        """
        with Session(self):
            result = self.contenthost.execute_package_action(
                self.client.hostname,
                'Group Install',
                FAKE_0_CUSTOM_PACKAGE_GROUP_NAME,
            )
            self.assertEqual(result, 'success')
            for package in FAKE_0_CUSTOM_PACKAGE_GROUP:
                self.assertIsNotNone(self.contenthost.package_search(
                    self.client.hostname, package))

    @tier3
    def test_positive_remove_package_group(self):
        """Remove a package group from a host remotely

        :id: dbeea1f2-adf4-4ad8-a989-efad8ce21b98

        :expectedresults: Package group was successfully removed

        :CaseLevel: System
        """
        with Session(self):
            result = self.contenthost.execute_package_action(
                self.client.hostname,
                'Group Install',
                FAKE_0_CUSTOM_PACKAGE_GROUP_NAME,
            )
            self.assertEqual(result, 'success')
            result = self.contenthost.execute_package_action(
                self.client.hostname,
                'Group Remove',
                FAKE_0_CUSTOM_PACKAGE_GROUP_NAME,
            )
            self.assertEqual(result, 'success')
            for package in FAKE_0_CUSTOM_PACKAGE_GROUP:
                self.assertIsNone(self.contenthost.package_search(
                    self.client.hostname, package))

    @tier3
    @upgrade
    def test_positive_install_errata(self):
        """Install a errata to a host remotely

        :id: b69b9797-3c0c-42cd-94ed-3f751bb9b24c

        :expectedresults: Errata was successfully installed

        :CaseLevel: System
        """
        self.client.run('yum install -y {0}'.format(FAKE_1_CUSTOM_PACKAGE))
        with Session(self):
            result = self.contenthost.install_errata(
                self.client.hostname,
                FAKE_2_ERRATA_ID,
            )
            self.assertEqual(result, 'success')
            self.assertIsNotNone(self.contenthost.package_search(
                self.client.hostname, FAKE_2_CUSTOM_PACKAGE))

    @tier3
    def test_positive_search_errata_non_admin(self):
        """Search for host's errata by non-admin user with enough permissions

        :id: 5b8887d2-987f-4bce-86a1-8f65ca7e1195

        :BZ: 1255515

        :expectedresults: User can access errata page and proper errata is
            listed

        :CaseLevel: System
        """
        self.client.run('yum install -y {0}'.format(FAKE_1_CUSTOM_PACKAGE))
        user_login = gen_string('alpha')
        user_password = gen_string('alpha')
        default_loc = entities.Location().search(
            query={'search': 'name="{0}"'.format(DEFAULT_LOC)})[0]
        role = entities.Role().create()
        for permission_name in (
                'view_hosts', 'view_lifecycle_environments',
                'view_content_views', 'view_organizations'):
            entities.Filter(
                permission=entities.Permission(name=permission_name).search(),
                role=role,
            ).create()
        entities.User(
            role=[role],
            admin=False,
            login=user_login,
            password=user_password,
            organization=[self.session_org],
            location=[default_loc],
            default_organization=self.session_org,
        ).create()
        with Session(self, user=user_login, password=user_password):
            result = self.contenthost.errata_search(
                self.client.hostname, FAKE_2_ERRATA_ID)
            self.assertIsNotNone(result)

    @tier3
    def test_positive_fetch_registered_by(self):
        """Register a host with activation key and fetch host's 'Registered by'
        field value.

        :id: 5c6dbb5d-bd26-4439-ab04-536a6ad012b9

        :expectedresults: 'Registered By' field on content host page points to
            activation key which was used to register the host

        :BZ: 1380117

        :CaseLevel: System
        """
        with Session(self):
            result = self.contenthost.fetch_parameters(
                self.client.hostname,
                [['Details', 'Registered By']],
            )
            self.assertEqual(
                result['Registered By'], self.activation_key.name)

    @skip_if_bug_open('bugzilla', 1351464)
    @skip_if_bug_open('bugzilla', 1387892)
    @tier3
    def test_positive_provisioning_host_link(self):
        """Check that the host link in provisioning tab of content host page
        point to the host details page.

        :id: 28f5fb0e-007b-4ee6-876e-9693fb7f5841

        :expectedresults: The Provisioning host details name link at
            content_hosts/provisioning point to host detail page eg:
            hosts/hostname

        :BZ: 1387892

        :CaseLevel: System
        """
        with Session(self):
            # open the content host
            self.contenthost.search_and_click(self.client.hostname)
            # open the provisioning tab of the content host
            self.contenthost.click(
                tab_locators['contenthost.tab_provisioning_details'])
            # click the name field value that contain the hostname
            self.contenthost.click(
                tab_locators['contenthost.tab_provisioning_details_host_link'])
            # assert that the current url is equal to:
            # server_host_url/hosts/hostname
            host_url = urljoin(settings.server.get_url(),
                               'hosts/{0}'.format(self.client.hostname))
            self.assertEqual(self.browser.current_url, host_url)

    @tier3
    @upgrade
    def test_positive_ensure_errata_applicability_with_host_reregistered(self):
        """Ensure that errata remain available to install when content host is
        re-registered

        :id: 30b1e512-45e5-481e-845f-5344ed81450d

        :steps:
            1. Prepare an activation key with content view that contain a
                repository with a package that has errata
            2. Register the host to activation key
            3. Install the package that has errata
            4. Refresh content host subscription running:
                "subscription-manager refresh  && yum repolist"
            5. Ensure errata is available for installation
            6. Refresh content host subscription running:
                "subscription-manager refresh  && yum repolist"

        :expectedresults: errata is available in installable errata list

        :BZ: 1463818

        :CaseLevel: System
        """
        self.client.run('yum install -y {0}'.format(FAKE_1_CUSTOM_PACKAGE))
        result = self.client.run('rpm -q {0}'.format(FAKE_1_CUSTOM_PACKAGE))
        self.assertEqual(result.return_code, 0)
        result = self.client.run(
            'subscription-manager refresh  && yum repolist')
        self.assertEqual(result.return_code, 0)
        with Session(self):
            self.assertIsNotNone(
                self.contenthost.errata_search(
                    self.client.hostname, FAKE_2_ERRATA_ID)
            )
            result = self.client.run(
                'subscription-manager refresh  && yum repolist')
            self.assertEqual(result.return_code, 0)
            self.assertIsNotNone(
                self.contenthost.errata_search(
                    self.client.hostname, FAKE_2_ERRATA_ID)
            )

    @tier3
    @upgrade
    def test_positive_check_ignore_facts_os_setting(self):
        """Verify that 'Ignore facts for operating system' setting works
        properly

        :steps:

            1. Create a new host entry using content host self registration
               procedure
            2. Check that there is a new setting added "Ignore facts for
               operating system", and set it to true.
            3. Upload the facts that were read from initial host, but with a
               change in all the operating system fields to a different OS or
               version.
            4. Verify that the host OS isn't updated.
            5. Set the setting in step 2 to false.
            6. Upload same modified facts from step 3.
            7. Verify that the host OS is updated.
            8. Verify that new OS is created

        :id: 71bed439-105c-4e87-baae-738379d055fb

        :expectedresults: Host facts impact its own values properly according
            to the setting values

        :BZ: 1155704

        :CaseLevel: System
        """
        ignore_setting = entities.Setting().search(
            query={'search': 'name="ignore_facts_for_operatingsystem"'})[0]
        default_ignore_setting = str(ignore_setting.value)
        major = str(gen_integer(15, 99))
        minor = str(gen_integer(1, 9))
        expected_os = "RedHat {}.{}".format(major, minor)
        with Session(self):
            host = entities.Host().search(query={
                'search': 'name={0} and organization_id={1}'.format(
                    self.client.hostname, self.session_org.id)
            })[0].read()
            # Get host current operating system value
            os = self.hosts.get_host_properties(
                self.client.hostname, ['Operating System'])['Operating System']
            # Change necessary setting to true
            ignore_setting.value = 'True'
            ignore_setting.update({'value'})
            # Add cleanup function to roll back setting to default value
            self.addCleanup(
                setting_cleanup,
                'ignore_facts_for_operatingsystem',
                default_ignore_setting
            )
            # Read all facts for corresponding host
            facts = host.get_facts(
                data={u'per_page': 10000})['results'][self.client.hostname]
            # Modify OS facts to another values and upload them to the server
            # back
            facts['operatingsystem'] = 'RedHat'
            facts['osfamily'] = 'RedHat'
            facts['operatingsystemmajrelease'] = major
            facts['operatingsystemrelease'] = "{}.{}".format(major, minor)
            host.upload_facts(
                data={
                    u'name': self.client.hostname,
                    u'facts': facts,
                }
            )
            updated_os = self.hosts.get_host_properties(
                self.client.hostname, ['Operating System'])['Operating System']
            # Check that host OS was not changed due setting was set to true
            self.assertEqual(os, updated_os)
            # Put it to false and re-run the process
            ignore_setting.value = 'False'
            ignore_setting.update({'value'})
            host.upload_facts(
                data={
                    u'name': self.client.hostname,
                    u'facts': facts,
                }
            )
            updated_os = self.hosts.get_host_properties(
                self.client.hostname, ['Operating System'])['Operating System']
            # Check that host OS was changed to new value
            self.assertNotEqual(os, updated_os)
            self.assertEqual(updated_os, expected_os)
            # Check that new OS was created
            self.assertIsNotNone(self.operatingsys.search(
                expected_os, _raw_query=expected_os))

    @tier3
    @upgrade
    @stubbed()
    def test_positive_bulk_add_subscriptions(self):
        """Add a subscription to more than one content host, using bulk actions.

        :id: a427c77f-100d-4af5-9248-6f806db364ef

        :steps:

            1. Upload a manifest with, or use an existing, subscription
            2. Register multiple hosts to the current organization
            3. Select all of those hosts
            4. Navigate to the bulk subscriptions page
            5. Select and add a subscription to the hosts

        :expectedresults: The subscriptions are successfully attached to the
            hosts

        :CaseLevel: System
        """

    @tier3
    @stubbed()
    def test_positive_bulk_remove_subscriptions(self):
        """Remove a subscription to more than one content host, using bulk
        actions.

        :id: f74b829e-d888-4caf-a25e-ca64b073a3fc

        :steps:

            1. Upload a manifest with, or use an existing, subscription
            2. Register multiple hosts to the current organization
            3. Select all of those hosts
            4. Navigate to the bulk subscriptions page
            5. Select and add a subscription to the hosts
            6. Verify that the subscriptions were added
            7. Reselect all the hosts from step 3
            8. Navigate to the bulk subscriptions page
            9. Select the subscription added in step 5 and remove it

        :expectedresults: The subscriptions are successfully removed from the
            hosts

        :CaseLevel: System
        """

    @skip_if_not_set('clients', 'fake_manifest', 'compute_resources')
    @tier3
    @upgrade
    def test_positive_virt_who_hypervisor_subscription_status(self):
        """Check that virt-who hypervisor shows the right subscription status
        without and with attached subscription.

        :id: 8b2cc5d6-ac85-463f-a973-f4818c55fb37

        :expectedresults:
            1. With subscription not attached, Subscription status is
               "Unsubscribed hypervisor" and represented by a yellow icon in
               content hosts list.
            2. With attached subscription, Subscription status is
               "Fully entitled" and represented by a green icon in content
               hosts list.

        :BZ: 1336924

        :CaseLevel: System
        """
        org = entities.Organization().create()
        lce = entities.LifecycleEnvironment(organization=org).create()
        provisioning_server = settings.compute_resources.libvirt_hostname
        # Create a new virt-who config
        virt_who_config = make_virt_who_config({
            'organization-id': org.id,
            'hypervisor-type': VIRT_WHO_HYPERVISOR_TYPES['libvirt'],
            'hypervisor-server': 'qemu+ssh://{0}/system'.format(
                provisioning_server),
            'hypervisor-username': '******',
        })
        # create a virtual machine to host virt-who service
        with VirtualMachine() as virt_who_vm:
            # configure virtual machine and setup virt-who service
            # do not supply subscription to attach to virt_who hypervisor
            virt_who_data = virt_who_hypervisor_config(
                virt_who_config['general-information']['id'],
                virt_who_vm,
                org_id=org.id,
                lce_id=lce.id,
                hypervisor_hostname=provisioning_server,
                configure_ssh=True,
                exec_one_shot=True,
            )
            virt_who_hypervisor_host = virt_who_data[
                'virt_who_hypervisor_host']
            with Session(self) as session:
                set_context(session, org=org.name, force_context=True)
                self.assertEqual(
                    session.contenthost.get_subscription_status_color(
                        virt_who_hypervisor_host['name']),
                    'yellow'
                )
                self.assertEqual(
                    session.contenthost.get_subscription_status_text(
                        virt_who_hypervisor_host['name']),
                    'Unsubscribed hypervisor'
                )
                session.contenthost.update(
                    virt_who_hypervisor_host['name'],
                    add_subscriptions=[VDC_SUBSCRIPTION_NAME]
                )
                self.assertEqual(
                    session.contenthost.get_subscription_status_color(
                        virt_who_hypervisor_host['name']),
                    'green'
                )
                self.assertEqual(
                    session.contenthost.get_subscription_status_text(
                        virt_who_hypervisor_host['name']),
                    'Fully entitled'
                )
    def test_multiple_activation_keys_to_system(self):
        """@Test: Check if multiple Activation keys can be attached to a system

        @Feature: Activation key - System

        @Steps:
        1. Create multiple Activation keys
        2. Attach all the created Activation keys to a System

        @Assert: Multiple Activation keys are attached to a system

        """
        key_1_name = gen_string("alpha", 8)
        key_2_name = gen_string("alpha", 8)
        cv_1_name = gen_string("alpha", 8)
        cv_2_name = gen_string("alpha", 8)
        env_1_name = gen_string("alpha", 8)
        env_2_name = gen_string("alpha", 8)
        product_1_name = gen_string("alpha", 8)
        product_2_name = gen_string("alpha", 8)
        # Helper function to create and promote CV to next environment
        self.create_cv(cv_1_name, env_1_name, product_1_name)
        self.create_cv(cv_2_name, env_2_name, product_2_name,
                       repo_url=FAKE_2_YUM_REPO)
        with Session(self.browser) as session:
            # Create activation_key_1
            make_activationkey(
                session, org=self.org_name, name=key_1_name, env=env_1_name,
                description=gen_string("alpha", 16),
                content_view=cv_1_name
            )
            self.assertIsNotNone(self.activationkey.search_key(key_1_name))
            self.activationkey.associate_product(key_1_name, [product_1_name])
            self.assertIsNotNone(self.activationkey.wait_until_element
                                 (common_locators["alert.success"]))
            # Create activation_key_2
            make_activationkey(
                session, org=self.org_name, name=key_2_name, env=env_2_name,
                description=gen_string("alpha", 16),
                content_view=cv_2_name
            )
            self.assertIsNotNone(self.activationkey.search_key(key_2_name))
            self.activationkey.associate_product(key_2_name, [product_2_name])
            self.assertIsNotNone(self.activationkey.wait_until_element
                                 (common_locators["alert.success"]))
            # Create VM
            vm = VirtualMachine(distro='rhel65')
            vm.create()
            vm_name = vm.run('hostname')
            # Download and Install rpm
            result = vm.run(
                "wget -nd -r -l1 --no-parent -A '*.noarch.rpm' http://{0}/pub/"
                .format(self.server_name)
            )
            self.assertEqual(
                result.return_code, 0,
                "failed to fetch katello-ca rpm: {0}, return code: {1}"
                .format(result.stderr, result.return_code)
            )
            result = vm.run(
                'rpm -i katello-ca-consumer*.noarch.rpm'
            )
            self.assertEqual(
                result.return_code, 0,
                "failed to install katello-ca rpm: {0}, return code: {1}"
                .format(result.stderr, result.return_code)
            )
            # Register client with foreman server using activation-key
            result = vm.run(
                'subscription-manager register --activationkey {0},{1} '
                '--org {2} --force'
                .format(key_1_name, key_2_name, self.org_label)
            )
            self.assertEqual(
                result.return_code, 0,
                "failed to register client:: {0} and return code: {1}"
                .format(result.stderr, result.return_code)
            )
            # Assert the content-host association with activation-key
            for key_name in [key_1_name, key_2_name]:
                host_name = self.activationkey.fetch_associated_content_host(
                    key_name)
                self.assertEqual(vm_name.stdout[0], host_name)
            # Delete the virtual machine
            vm.destroy()