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()
Beispiel #2
0
 def test_qemu_ga_gets_ip(
     self, ssh_command, sleep, config_provisioning_server, host_os_version_patch
 ):
     """Verify that the IP is correctly parsed from the qemu-guest-agent output"""
     vm = VirtualMachine()
     vm.create()
     assert vm.ip_addr == '10.8.30.135'
    def test_pre_scenario_remoteexecution_satellite(self):
        """Run REX job on client registered with Satellite

        :id: preupgrade-3f338475-fa69-43ef-ac86-f00f4d324b33

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

        :expectedresults:
            1. It should create with pre-required details.
            2. REX job should run on it.
        """
        try:
            default_loc_id = entities.Location().search(
                query={'search': 'name="{}"'.format(DEFAULT_LOC)})[0].id
            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=1)],
            ).create()
            client = VirtualMachine(distro=DISTRO_RHEL7,
                                    provisioning_server=self.libvirt_vm,
                                    bridge=self.bridge)
            client.create()
            client.install_katello_ca()
            client.register_contenthost(org=self.org.label, lce='Library')
            add_remote_execution_ssh_key(hostname=client.ip_addr)
            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)
Beispiel #4
0
 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.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()
Beispiel #5
0
def vm_content_hosts(request, 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)
    return clients
Beispiel #6
0
 def test_subscription_manager_overall_status(
     self, ssh_command, sleep, config_provisioning_server, host_os_version_patch
 ):
     vm = VirtualMachine()
     vm.create()
     assert vm.subscription_manager_status().stdout == 'Overall Status: Current'
     assert (
         vm.subscription_manager_list_repos().stdout
         == 'This system has no repositories available through subscriptions.'
     )
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
Beispiel #8
0
class RHAI(Base):
    def view_registered_systems(self):
        """To view the number of registered systems"""
        result = self.wait_until_element(
            locators['insights.registered_systems']
        ).text
        return result

    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')
Beispiel #9
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)
Beispiel #10
0
    def test_dont_create_if_already_created(self, ssh_command, sleep):
        """Check if the creation steps are run more than once"""
        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, 3)
    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)
Beispiel #12
0
    def test_dont_create_if_already_created(
        self, ssh__mock, sleep, config_provisioning_server, host_os_version_patch
    ):
        """Check if the creation steps are run more than once"""
        vm = VirtualMachine()

        with patch.multiple(
            vm, image_dir='/opt/robottelo/images', provisioning_server=PROV_SERVER_DEFAULT
        ):
            vm.create()
            vm.create()
        assert vm.ip_addr == '192.168.0.1'
        assert ssh__mock.call_count == 4
Beispiel #13
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')
Beispiel #14
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')
Beispiel #15
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")
Beispiel #16
0
    def test_run(self, config_provisioning_server, host_os_version_patch):
        """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()

        with patch('robottelo.ssh.command') as ssh_mock:
            vm.run('ls')
            ssh_mock.assert_called_once_with('ls', hostname='192.168.0.1', timeout=None)
def fixture_vmsetup(request, fixture_org):
    """Create Org, Lifecycle Environment, Content View, Activation key,
    VM, install katello-ca, register it, add remote execution key
    """
    # Create VM and register content host
    client = VirtualMachine(distro=request.param)
    try:
        client.create()
        if request.param in [DISTRO_SLES11, DISTRO_SLES12]:
            # SLES hostname in subscription-manager facts doesn't include domain
            client._hostname = client.hostname.split(".")[0]
        client.install_katello_ca()
        # Register content host
        client.register_contenthost(org=fixture_org.label, lce='Library')
        assert client.subscribed
        add_remote_execution_ssh_key(client.ip_addr)
        yield client
    finally:
        client._hostname = None
        client.destroy()
def fixture_vmsetup(request, fixture_org):
    """Create Org, Lifecycle Environment, Content View, Activation key,
    VM, install katello-ca, register it, add remote execution key
    """
    # Create VM and register content host
    client = VirtualMachine(distro=request.param)
    try:
        client.create()
        if request.param in [DISTRO_SLES11, DISTRO_SLES12]:
            # SLES hostname in subscription-manager facts doesn't include domain
            client._hostname = client.hostname.split(".")[0]
        client.install_katello_ca()
        # Register content host
        client.register_contenthost(
            org=fixture_org.label,
            lce='Library'
        )
        assert client.subscribed
        add_remote_execution_ssh_key(client.ip_addr)
        yield client
    finally:
        client._hostname = None
        client.destroy()
Beispiel #19
0
class DockerContainerTestCase(APITestCase):
    """Tests specific to using ``Containers`` in an external Docker
    Compute Resource

    :CaseComponent: ContainerManagement-Content

    :CaseLevel: Integration

    :CaseImportance: Low
    """
    @classmethod
    @skip_if_not_set('docker')
    def setUpClass(cls):
        """Create an organization and product which can be re-used in tests."""
        super(DockerContainerTestCase, cls).setUpClass()
        cls.org = entities.Organization().create()

    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()
Beispiel #20
0
class TestCHKatelloAgent(CLITestCase):
    """Content-host tests, which require VM with installed katello-agent."""

    org = None
    env = None
    cv = None
    activation_key = None
    org_is_set_up = False

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

    def tearDown(self):
        self.vm.destroy()
        super(TestCHKatelloAgent, self).tearDown()

    def test_contenthost_get_errata_info(self):
        """@Test: Get errata info

        @Feature: Content Host - Errata

        @Assert: Errata info was displayed

        """
        self.vm.download_install_rpm(FAKE_0_YUM_REPO, FAKE_0_CUSTOM_PACKAGE)
        result = ContentHost.errata_info({
            u'organization-id': TestCHKatelloAgent.org['id'],
            u'content-host': self.vm.hostname,
            u'id': FAKE_0_ERRATA_ID,
        })
        self.assertEqual(result.return_code, 0)
        self.assertEqual(result.stdout[0]['errata-id'], FAKE_0_ERRATA_ID)
        self.assertEqual(result.stdout[0]['packages'], FAKE_0_CUSTOM_PACKAGE)

    def test_contenthost_apply_errata(self):
        """@Test: Apply errata to content host

        @Feature: Content Host - Errata

        @Assert: Errata is scheduled for installation

        """
        self.vm.download_install_rpm(FAKE_0_YUM_REPO, FAKE_0_CUSTOM_PACKAGE)
        result = ContentHost.errata_apply({
            u'organization-id': TestCHKatelloAgent.org['id'],
            u'content-host': self.vm.hostname,
            u'errata-ids': FAKE_0_ERRATA_ID,
        })
        self.assertEqual(result.return_code, 0)

    def test_contenthost_package_install(self):
        """@Test: Install package to content host remotely

        @Feature: Content Host - Package

        @Assert: Package was successfully installed

        """
        result = ContentHost.package_install({
            u'organization-id': TestCHKatelloAgent.org['id'],
            u'content-host': self.vm.hostname,
            u'packages': FAKE_0_CUSTOM_PACKAGE_NAME,
        })
        self.assertEqual(result.return_code, 0)
        result = self.vm.run('rpm -q {}'.format(FAKE_0_CUSTOM_PACKAGE_NAME))
        self.assertEqual(result.return_code, 0)

    def test_contenthost_package_remove(self):
        """@Test: Remove package from content host remotely

        @Feature: Content Host - Package

        @Assert: Package was successfully removed

        """
        self.vm.download_install_rpm(FAKE_0_YUM_REPO, FAKE_0_CUSTOM_PACKAGE)
        result = ContentHost.package_remove({
            u'organization-id': TestCHKatelloAgent.org['id'],
            u'content-host': self.vm.hostname,
            u'packages': FAKE_0_CUSTOM_PACKAGE_NAME,
        })
        self.assertEqual(result.return_code, 0)
        result = self.vm.run('rpm -q {}'.format(FAKE_0_CUSTOM_PACKAGE_NAME))
        self.assertNotEqual(result.return_code, 0)

    def test_contenthost_package_upgrade(self):
        """@Test: Upgrade content host package remotely

        @Feature: Content Host - Package

        @Assert: Package was successfully upgraded

        """
        self.vm.run('yum install -y {}'.format(FAKE_1_CUSTOM_PACKAGE))
        result = ContentHost.package_upgrade({
            u'organization-id': TestCHKatelloAgent.org['id'],
            u'content-host': self.vm.hostname,
            u'packages': FAKE_1_CUSTOM_PACKAGE_NAME,
        })
        self.assertEqual(result.return_code, 0)
        result = self.vm.run('rpm -q {}'.format(FAKE_2_CUSTOM_PACKAGE))
        self.assertEqual(result.return_code, 0)

    def test_contenthost_package_upgrade_all(self):
        """@Test: Upgrade all the content host packages remotely

        @Feature: Content Host - Package

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

        """
        self.vm.run('yum install -y {}'.format(FAKE_1_CUSTOM_PACKAGE))
        result = ContentHost.package_upgrade_all({
            u'organization-id': TestCHKatelloAgent.org['id'],
            u'content-host': self.vm.hostname,
        })
        self.assertEqual(result.return_code, 0)
        result = self.vm.run('rpm -q {}'.format(FAKE_2_CUSTOM_PACKAGE))
        self.assertEqual(result.return_code, 0)

    def test_contenthost_package_group_install(self):
        """@Test: Install package group to content host remotely

        @Feature: Content Host - Package group

        @Assert: Package group was successfully installed

        """
        result = ContentHost.package_group_install({
            u'organization-id': TestCHKatelloAgent.org['id'],
            u'content-host': self.vm.hostname,
            u'groups': FAKE_0_CUSTOM_PACKAGE_GROUP_NAME,
        })
        self.assertEqual(result.return_code, 0)
        for package in FAKE_0_CUSTOM_PACKAGE_GROUP:
            result = self.vm.run('rpm -q {}'.format(package))
            self.assertEqual(result.return_code, 0)

    def test_contenthost_package_group_remove(self):
        """@Test: Remove package group from content host remotely

        @Feature: Content Host - Package group

        @Assert: Package group was successfully removed

        """
        hammer_args = {
            u'organization-id': TestCHKatelloAgent.org['id'],
            u'content-host': self.vm.hostname,
            u'groups': FAKE_0_CUSTOM_PACKAGE_GROUP_NAME,
        }
        result = ContentHost.package_group_install(hammer_args)
        self.assertEqual(result.return_code, 0)
        result = ContentHost.package_group_remove(hammer_args)
        self.assertEqual(result.return_code, 0)
        for package in FAKE_0_CUSTOM_PACKAGE_GROUP:
            result = self.vm.run('rpm -q {}'.format(package))
            self.assertNotEqual(result.return_code, 0)
Beispiel #21
0
    def test_positive_generate_hostpkgcompare(self):
        """Generate 'Host - compare content hosts packages' report

        :id: 572fb387-86f2-40e2-b2df-e8ec26433610


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

        :steps:
            1. hammer report-template generate --name 'Host - compare content hosts package' ...

        :expectedresults: report is scheduled and generated containing all the expected information
                          regarding host packages

        :CaseImportance: Medium

        :BZ: 1860430
        """
        # Add subscription to Satellite Tools repo to activation key
        setup_org_for_a_rh_repo(
            {
                'product': PRDS['rhel'],
                'repository-set': REPOSET['rhst7'],
                'repository': REPOS['rhst7']['name'],
                'organization-id': self.setup_org['id'],
                'content-view-id': self.setup_content_view['id'],
                'lifecycle-environment-id': self.setup_env['id'],
                'activationkey-id': self.setup_new_ak['id'],
            }
        )

        hosts = []
        for i in [0, 1]:
            # Create VM and register content host
            client = VirtualMachine(distro=DISTRO_RHEL7)
            client.create()
            self.addCleanup(vm_cleanup, client)
            client.install_katello_ca()
            # Register content host, install katello-agent
            client.register_contenthost(self.setup_org['label'], self.setup_new_ak['name'])
            self.assertTrue(client.subscribed)
            hosts.append(Host.info({'name': client.hostname}))
            client.enable_repo(REPOS['rhst7']['id'])
            client.install_katello_agent()
        hosts.sort(key=lambda host: host['name'])

        host1, host2 = hosts
        Host.package_install({'host-id': host1['id'], 'packages': FAKE_0_CUSTOM_PACKAGE_NAME})
        Host.package_install({'host-id': host1['id'], 'packages': FAKE_1_CUSTOM_PACKAGE})
        Host.package_install({'host-id': host2['id'], 'packages': FAKE_2_CUSTOM_PACKAGE})

        result = ReportTemplate.generate(
            {
                'name': 'Host - compare content hosts packages',
                'inputs': f"Host 1 = {host1['name']}, " f"Host 2 = {host2['name']}",
            }
        )
        result.remove('')

        self.assertGreater(len(result), 1)
        headers = f'Package,{host1["name"]},{host2["name"]},Architecture,Status'
        self.assertEqual(headers, result[0])
        items = [item.split(',') for item in result[1:]]
        self.assertGreater(len(items), 0)
        for item in items:
            self.assertEqual(len(item), 5)
            name, host1version, host2version, arch, status = item
            self.assertGreater(len(name), 0)
            assert (
                (host1version == '-' and name in host2version)
                or (name in host1version and host2version == '-')
                or (name in host1version and name in host2version)
            )
            self.assertIn(arch, ['x86_64', 'i686', 's390x', 'ppc64', 'ppc64le', 'noarch'])
            assert status in (
                'same version',
                f'{host1["name"]} only',
                f'{host2["name"]} only',
                f'lower in {host1["name"]}',
                f'greater in {host1["name"]}',
            )
            # test for specific installed packages
            if name == FAKE_0_CUSTOM_PACKAGE_NAME:
                assert status == f'{host1["name"]} only'
            if name == FAKE_1_CUSTOM_PACKAGE_NAME:
                assert (
                    status == f'lower in {host1["name"]}'
                    or status == f'greater in {host2["name"]}'
                )
Beispiel #22
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_1_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

        :customerscenario: true

        :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()
                # In case we have a lot of unregistered hosts
                # fixme: Should be replaced with loop across all pages
                self.contenthost.assign_value(
                    common_locators['table_per_page'], '100')
                # 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')
                checked_in_dates = [
                    date for date in dates if date != 'Never checked in'
                ]
                self.assertGreater(checked_in_dates[1], checked_in_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

        :customerscenario: true

        :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

        :customerscenario: true

        :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

        :customerscenario: true

        :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

        :customerscenario: true

        :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

        :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(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')
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))
Beispiel #24
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'
                )
Beispiel #25
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=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', 1478090)
    @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, 1478090

        :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_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_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
    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
    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_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', 1377676)
    @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
    @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
class RemoteExecutionTestCase(CLITestCase):
    """Implements job execution tests in CLI."""

    @classmethod
    @skip_if_not_set('clients', 'fake_manifest')
    def setUpClass(cls):
        """Create Org, Lifecycle Environment, Content View, Activation key
        """
        super(RemoteExecutionTestCase, cls).setUpClass()
        cls.org = make_org()
        ssh.command(
            '''echo 'getenforce' > {0}'''.format(TEMPLATE_FILE)
        )
        cls.env = make_lifecycle_environment({
            u'organization-id': cls.org['id'],
        })
        cls.content_view = make_content_view({
            u'organization-id': cls.org['id'],
        })
        cls.activation_key = make_activation_key({
            u'lifecycle-environment-id': cls.env['id'],
            u'organization-id': cls.org['id'],
        })
        if settings.cdn:
            # 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': cls.org['id'],
                u'content-view-id': cls.content_view['id'],
                u'lifecycle-environment-id': cls.env['id'],
                u'activationkey-id': cls.activation_key['id'],
            })
        else:
            # Create custom internal Tools repo, add to activation key
            setup_org_for_a_custom_repo({
                u'url': settings.sattools_repo,
                u'organization-id': cls.org['id'],
                u'content-view-id': cls.content_view['id'],
                u'lifecycle-environment-id': cls.env['id'],
                u'activationkey-id': cls.activation_key['id'],
            })

    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)

    @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),
        })
        self.assertEqual(
                invocation_command['success'],
                u'1',
                'host output: {0}'.format(
                    ' '.join(JobInvocation.get_output({
                        'id': invocation_command[u'id'],
                        'host': self.client.hostname})
                    )
                )
            )

    @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.org[u'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),
        })
        self.assertEqual(
                invocation_command['success'],
                u'1',
                'host output: {0}'.format(
                    ' '.join(JobInvocation.get_output({
                        'id': invocation_command[u'id'],
                        'host': self.client.hostname})
                    )
                )
            )

    @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 unitl 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']})
        self.assertEqual(
                invocation_info['success'],
                u'1',
                'host output: {0}'.format(
                    ' '.join(JobInvocation.get_output({
                        'id': invocation_command[u'id'],
                        'host': self.client.hostname})
                    )
                )
            )
Beispiel #27
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.org['label'],
            KatelloAgentTestCase.activation_key['name'],
        )
        self.host = Host.info({'name': self.client.hostname})
        self.client.enable_repo(REPOS['rhst7']['id'])
        self.client.install_katello_agent()

    def tearDown(self):
        """Destroy the VM"""
        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)
class KatelloAgentTestCase(CLITestCase):
    """Content-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.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

        @Feature: Content Host - Errata

        @Assert: Errata info was displayed

        """
        self.client.download_install_rpm(FAKE_0_YUM_REPO, FAKE_0_CUSTOM_PACKAGE)
        result = ContentHost.errata_info(
            {
                u"content-host": self.client.hostname,
                u"id": FAKE_0_ERRATA_ID,
                u"organization-id": KatelloAgentTestCase.org["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 content host

        @Feature: Content Host - Errata

        @Assert: Errata is scheduled for installation

        """
        self.client.download_install_rpm(FAKE_0_YUM_REPO, FAKE_0_CUSTOM_PACKAGE)
        ContentHost.errata_apply(
            {
                u"content-host": self.client.hostname,
                u"errata-ids": FAKE_0_ERRATA_ID,
                u"organization-id": KatelloAgentTestCase.org["id"],
            }
        )

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

        @Feature: Content Host - Package

        @Assert: Package was successfully installed

        """
        ContentHost.package_install(
            {
                u"content-host": self.client.hostname,
                u"organization-id": KatelloAgentTestCase.org["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 package from content host remotely

        @Feature: Content Host - Package

        @Assert: Package was successfully removed

        """
        self.client.download_install_rpm(FAKE_0_YUM_REPO, FAKE_0_CUSTOM_PACKAGE)
        ContentHost.package_remove(
            {
                u"content-host": self.client.hostname,
                u"organization-id": KatelloAgentTestCase.org["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 content host package remotely

        @Feature: Content Host - Package

        @Assert: Package was successfully upgraded

        """
        self.client.run("yum install -y {0}".format(FAKE_1_CUSTOM_PACKAGE))
        ContentHost.package_upgrade(
            {
                u"content-host": self.client.hostname,
                u"organization-id": KatelloAgentTestCase.org["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 content host packages remotely

        @Feature: Content Host - Package

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

        """
        self.client.run("yum install -y {0}".format(FAKE_1_CUSTOM_PACKAGE))
        ContentHost.package_upgrade_all(
            {u"content-host": self.client.hostname, u"organization-id": KatelloAgentTestCase.org["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 package group to content host remotely

        @Feature: Content Host - Package group

        @Assert: Package group was successfully installed

        """
        ContentHost.package_group_install(
            {
                u"content-host": self.client.hostname,
                u"groups": FAKE_0_CUSTOM_PACKAGE_GROUP_NAME,
                u"organization-id": KatelloAgentTestCase.org["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 package group from content host remotely

        @Feature: Content Host - Package group

        @Assert: Package group was successfully removed

        """
        hammer_args = {
            u"content-host": self.client.hostname,
            u"groups": FAKE_0_CUSTOM_PACKAGE_GROUP_NAME,
            u"organization-id": KatelloAgentTestCase.org["id"],
        }
        ContentHost.package_group_install(hammer_args)
        ContentHost.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 Content host has been
        unregistered from Satellite

        @feature: Content host

        @assert: Content host can no longer retrieve content from satellite
        """
        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)
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)
class RemoteExecutionTestCase(CLITestCase):
    """Implements job execution tests in CLI."""

    @classmethod
    @skip_if_not_set('clients', 'fake_manifest')
    def setUpClass(cls):
        """Create Org, Lifecycle Environment, Content View, Activation key
        """
        super(RemoteExecutionTestCase, cls).setUpClass()
        cls.org = make_org()
        ssh.command(
            '''echo 'getenforce' > {0}'''.format(TEMPLATE_FILE)
        )
        cls.env = make_lifecycle_environment({
            u'organization-id': cls.org['id'],
        })
        cls.content_view = make_content_view({
            u'organization-id': cls.org['id'],
        })
        cls.activation_key = make_activation_key({
            u'lifecycle-environment-id': cls.env['id'],
            u'organization-id': cls.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': cls.org['id'],
            u'content-view-id': cls.content_view['id'],
            u'lifecycle-environment-id': cls.env['id'],
            u'activationkey-id': cls.activation_key['id'],
        })

    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'],
        })

    @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),
        })
        self.assertEqual(
                invocation_command['success'],
                u'1',
                'host output: {0}'.format(
                    ' '.join(JobInvocation.get_output({
                        'id': invocation_command[u'id'],
                        'host': self.client.hostname})
                    )
                )
            )

    @tier2
    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),
        })
        self.assertEqual(
                make_user_job[u'success'],
                u'1',
                'host output: {0}'.format(
                    ' '.join(JobInvocation.get_output({
                        'id': make_user_job[u'id'],
                        'host': self.client.hostname})
                    )
                )
            )
        # 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),
        })
        self.assertEqual(
                invocation_command['success'],
                u'1',
                'host output: {0}'.format(
                    ' '.join(JobInvocation.get_output({
                        'id': invocation_command[u'id'],
                        'host': self.client.hostname})
                    )
                )
            )
        # 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])

    @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.org[u'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),
        })
        self.assertEqual(
                invocation_command['success'],
                u'1',
                'host output: {0}'.format(
                    ' '.join(JobInvocation.get_output({
                        'id': invocation_command[u'id'],
                        'host': self.client.hostname})
                    )
                )
            )

    @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']})
        self.assertEqual(
                invocation_info['success'],
                u'1',
                'host output: {0}'.format(
                    ' '.join(JobInvocation.get_output({
                        'id': invocation_command[u'id'],
                        'host': self.client.hostname})
                    )
                )
            )

    @tier3
    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) 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'1', output_msgs)

    @tier3
    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
        setup_org_for_a_custom_repo({
            u'url': FAKE_0_YUM_REPO,
            u'organization-id': self.org['id'],
            u'content-view-id': self.content_view['id'],
            u'lifecycle-environment-id': self.env['id'],
            u'activationkey-id': self.activation_key['id'],
        })
        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),
        })
        self.assertEqual(
                invocation_command['success'],
                u'1',
                'host output: {0}'.format(
                    ' '.join(JobInvocation.get_output({
                        'id': invocation_command[u'id'],
                        'host': self.client.hostname})
                    )
                )
            )
        result = ssh.command(
                "rpm -q {0}".format(" ".join(packages)),
                hostname=self.client.hostname
                )
        self.assertEqual(result.return_code, 0)

    @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
            })
            self.assertEqual(
                    invocation_command['status'],
                    u'queued',
                    'host output: {0}'.format(
                        ' '.join(JobInvocation.get_output({
                            'id': invocation_command[u'id'],
                            'host': self.client.hostname})
                        )
                    )
                )
        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
    def test_positive_run_job_multiple_hosts_concurrency(self):
        """Run job against multiple hosts with concurrency-level
Beispiel #31
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=DISTRO_RHEL7)
        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: b69b9797-3c0c-42cd-94ed-3f751bb9b24c

        @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))
Beispiel #32
0
 def test_qemu_ga_gets_ip(self, ssh_command, sleep):
     """Verify that the IP is correctly parsed from the qemu-guest-agent output"""
     self.configure_provisioning_server()
     vm = VirtualMachine()
     vm.create()
     self.assertEqual(vm.ip_addr, '10.8.30.135')
Beispiel #33
0
class RHAI(Base):
    def view_registered_systems(self):
        """To view the number of registered systems"""
        result = self.wait_until_element(
            locators['insights.registered_systems']
        ).text
        return result

    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')
Beispiel #34
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=DISTRO_RHEL7)
        self.addCleanup(vm_cleanup, self.client)
        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()

    @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.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

        :expectedresults: 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

        :expectedresults: 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

        :expectedresults: 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

        :expectedresults: 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: 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.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))

    @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.browser):
            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', 1377676)
    @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.browser):
            # 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)
Beispiel #35
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)
Beispiel #36
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
        # add rex proxy to subnet, default is internal proxy (id 1)
        # 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],
            remote_execution_proxy=[entities.SmartProxy(id=1)],
        ).create()

    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_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()
Beispiel #38
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

        @Feature: Host - Errata

        @Assert: Errata info was displayed

        """
        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

        @Feature: Host - Errata

        @Assert: Errata is scheduled for installation

        """
        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

        @Feature: Host - Package

        @Assert: Package was successfully installed

        """
        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

        @Feature: Host - Package

        @Assert: Package was successfully removed

        """
        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

        @Feature: Host - Package

        @Assert: Package was successfully upgraded

        """
        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

        @Feature: Host - Package

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

        """
        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

        @Feature: Host - Package group

        @Assert: Package group was successfully installed

        """
        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

        @Feature: Host - Package group

        @Assert: Package group was successfully removed

        """
        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

        @feature: Host

        @assert: Host can no longer retrieve content from satellite
        """
        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)
    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()
    def test_pre_scenario_containers_support_removal(self):
        """Pre-upgrade scenario test to verify containers created and run
        before upgrade

        :id: preupgrade-f6de07ae-14c7-4452-9cb1-cafe2aa648ae

        :steps:

            1. Create docker host
            2. Create and run container from dockerhub
            3. Create and run container from external registry

        :expectedresults:

            1. Docker host is created
            2. Container from dockerhub is created and running
            3. Container from external registry is created and running

        """
        rh_registry_available = not bz_bug_is_open(1703397)
        repo_name = 'rhel'
        compute_resource_name = gen_string('alpha')
        registry_url = settings.docker.external_registry_1

        org = entities.Organization().create()

        docker_host = VirtualMachine(source_image=settings.docker.docker_image,
                                     tag=u'docker')
        docker_host.create()
        try:
            docker_host.install_katello_ca()

            compute_resource = entities.DockerComputeResource(
                name=compute_resource_name,
                organization=[org],
                url='http://{0}:2375'.format(docker_host.ip_addr),
            ).create()

            # Only one registry with given URL can exist on Satellite,
            # so search for it first and create it only if necessary
            try:
                registry = entities.Registry().search(
                    filters={'url': registry_url})[0]
            except IndexError:
                registry = entities.Registry(
                    url=registry_url,
                    organization=[org],
                ).create()

            # container from dockerhub
            dockerhub_container = entities.DockerHubContainer(
                command='sleep inf',
                compute_resource=compute_resource,
                organization=[org],
            ).create()
            self.assertEqual(dockerhub_container.compute_resource.id,
                             compute_resource.id)

            # container from external registry
            if rh_registry_available:
                external_container = entities.DockerRegistryContainer(
                    command='sleep inf',
                    compute_resource=compute_resource,
                    organization=[org],
                    registry=registry,
                    repository_name=repo_name,
                ).create()
                self.assertEqual(external_container.compute_resource.id,
                                 compute_resource.id)
                self.assertEqual(external_container.registry.id, registry.id)
                self.assertEqual(external_container.repository_name, repo_name)

            running_containers = docker_host.run('docker ps')
            self.assertEqual(running_containers.return_code, 0)

            self.assertTrue(
                any(dockerhub_container.name in line
                    for line in running_containers.stdout))
            if rh_registry_available:
                self.assertTrue(
                    any(external_container.name in line
                        for line in running_containers.stdout))

            ext_container_name = external_container.name if rh_registry_available else ''

            scenario_dict = {
                self.__class__.__name__: {
                    'rh_registry_available': rh_registry_available,
                    'docker_host': docker_host.hostname,
                    'dockerhub_container': dockerhub_container.name,
                    'external_container': ext_container_name,
                }
            }
            create_dict(scenario_dict)
        except Exception as exp:
            self._vm_cleanup(hostname=docker_host.hostname)
            raise Exception(exp)
    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()
Beispiel #42
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()
Beispiel #43
0
class KatelloAgentTestCase(CLITestCase):
    """Content-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.client.enable_repo(REPOS['rhst7']['id'])
        self.client.install_katello_agent()

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

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

        @Feature: Content Host - Errata

        @Assert: Errata info was displayed

        """
        self.client.download_install_rpm(
            FAKE_0_YUM_REPO,
            FAKE_0_CUSTOM_PACKAGE
        )
        result = ContentHost.errata_info({
            u'content-host': self.client.hostname,
            u'id': FAKE_0_ERRATA_ID,
            u'organization-id': KatelloAgentTestCase.org['id'],
        })
        self.assertEqual(result[0]['errata-id'], FAKE_0_ERRATA_ID)
        self.assertEqual(result[0]['packages'], FAKE_0_CUSTOM_PACKAGE)

    @tier2
    @run_only_on('sat')
    def test_positive_apply_errata(self):
        """@Test: Apply errata to content host

        @Feature: Content Host - Errata

        @Assert: Errata is scheduled for installation

        """
        self.client.download_install_rpm(
            FAKE_0_YUM_REPO,
            FAKE_0_CUSTOM_PACKAGE
        )
        ContentHost.errata_apply({
            u'content-host': self.client.hostname,
            u'errata-ids': FAKE_0_ERRATA_ID,
            u'organization-id': KatelloAgentTestCase.org['id'],
        })

    @tier2
    @run_only_on('sat')
    def test_positive_install_package(self):
        """@Test: Install package to content host remotely

        @Feature: Content Host - Package

        @Assert: Package was successfully installed

        """
        ContentHost.package_install({
            u'content-host': self.client.hostname,
            u'organization-id': KatelloAgentTestCase.org['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)

    @tier2
    @run_only_on('sat')
    def test_positive_remove_package(self):
        """@Test: Remove package from content host remotely

        @Feature: Content Host - Package

        @Assert: Package was successfully removed

        """
        self.client.download_install_rpm(
            FAKE_0_YUM_REPO,
            FAKE_0_CUSTOM_PACKAGE
        )
        ContentHost.package_remove({
            u'content-host': self.client.hostname,
            u'organization-id': KatelloAgentTestCase.org['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)

    @tier2
    @run_only_on('sat')
    def test_positive_upgrade_package(self):
        """@Test: Upgrade content host package remotely

        @Feature: Content Host - Package

        @Assert: Package was successfully upgraded

        """
        self.client.run('yum install -y {0}'.format(FAKE_1_CUSTOM_PACKAGE))
        ContentHost.package_upgrade({
            u'content-host': self.client.hostname,
            u'organization-id': KatelloAgentTestCase.org['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)

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

        @Feature: Content Host - Package

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

        """
        self.client.run('yum install -y {0}'.format(FAKE_1_CUSTOM_PACKAGE))
        ContentHost.package_upgrade_all({
            u'content-host': self.client.hostname,
            u'organization-id': KatelloAgentTestCase.org['id'],
        })
        result = self.client.run('rpm -q {0}'.format(FAKE_2_CUSTOM_PACKAGE))
        self.assertEqual(result.return_code, 0)

    @tier2
    @run_only_on('sat')
    def test_positive_install_package_group(self):
        """@Test: Install package group to content host remotely

        @Feature: Content Host - Package group

        @Assert: Package group was successfully installed

        """
        ContentHost.package_group_install({
            u'content-host': self.client.hostname,
            u'groups': FAKE_0_CUSTOM_PACKAGE_GROUP_NAME,
            u'organization-id': KatelloAgentTestCase.org['id'],
        })
        for package in FAKE_0_CUSTOM_PACKAGE_GROUP:
            result = self.client.run('rpm -q {0}'.format(package))
            self.assertEqual(result.return_code, 0)

    @tier2
    @run_only_on('sat')
    def test_positive_remove_package_group(self):
        """@Test: Remove package group from content host remotely

        @Feature: Content Host - Package group

        @Assert: Package group was successfully removed

        """
        hammer_args = {
            u'content-host': self.client.hostname,
            u'groups': FAKE_0_CUSTOM_PACKAGE_GROUP_NAME,
            u'organization-id': KatelloAgentTestCase.org['id'],
        }
        ContentHost.package_group_install(hammer_args)
        ContentHost.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)
Beispiel #44
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().setUpClass()
        # Create new org, environment, CV and activation key
        KatelloAgentTestCase.org = make_org()
        KatelloAgentTestCase.env = make_lifecycle_environment(
            {'organization-id': KatelloAgentTestCase.org['id']}
        )
        KatelloAgentTestCase.content_view = make_content_view(
            {'organization-id': KatelloAgentTestCase.org['id']}
        )
        KatelloAgentTestCase.activation_key = make_activation_key(
            {
                'lifecycle-environment-id': KatelloAgentTestCase.env['id'],
                'organization-id': KatelloAgentTestCase.org['id'],
            }
        )
        # Add subscription to Satellite Tools repo to activation key
        setup_org_for_a_rh_repo(
            {
                'product': PRDS['rhel'],
                'repository-set': REPOSET['rhst7'],
                'repository': REPOS['rhst7']['name'],
                'organization-id': KatelloAgentTestCase.org['id'],
                'content-view-id': KatelloAgentTestCase.content_view['id'],
                'lifecycle-environment-id': KatelloAgentTestCase.env['id'],
                'activationkey-id': KatelloAgentTestCase.activation_key['id'],
            }
        )
        # Create custom repo, add subscription to activation key
        setup_org_for_a_custom_repo(
            {
                'url': FAKE_1_YUM_REPO,
                'organization-id': KatelloAgentTestCase.org['id'],
                'content-view-id': KatelloAgentTestCase.content_view['id'],
                'lifecycle-environment-id': KatelloAgentTestCase.env['id'],
                '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().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()

    @pytest.mark.tier3
    def test_positive_get_errata_info(self):
        """Get errata info

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

        :expectedresults: Errata info was displayed

        :CaseLevel: System
        """
        self.client.run(f'yum install -y {FAKE_1_CUSTOM_PACKAGE}')
        result = Host.errata_info({'host-id': self.host['id'], 'id': FAKE_1_ERRATA_ID})
        assert result[0]['errata-id'] == FAKE_1_ERRATA_ID
        assert FAKE_2_CUSTOM_PACKAGE in result[0]['packages']

    @pytest.mark.tier3
    @pytest.mark.upgrade
    def test_positive_apply_errata(self):
        """Apply errata to a host

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

        :expectedresults: Errata is scheduled for installation

        :CaseLevel: System
        """
        self.client.run(f'yum install -y {FAKE_1_CUSTOM_PACKAGE}')
        Host.errata_apply({'errata-ids': FAKE_1_ERRATA_ID, 'host-id': self.host['id']})

    @pytest.mark.tier3
    def test_positive_apply_security_erratum(self):
        """Apply security erratum to a host

        :id: 4d1095c8-d354-42ac-af44-adf6dbb46deb

        :expectedresults: erratum is recognized by the
            `yum update --security` command on client

        :CaseLevel: System

        :BZ: 1420671, 1740790
        """
        self.client.download_install_rpm(FAKE_1_YUM_REPO, FAKE_2_CUSTOM_PACKAGE)
        # Check the system is up to date
        result = self.client.run('yum update --security | grep "No packages needed for security"')
        assert result.return_code == 0
        before_downgrade = int(time.time())
        # Downgrade walrus package
        self.client.run(f'yum downgrade -y {FAKE_2_CUSTOM_PACKAGE_NAME}')
        # Wait for errata applicability cache is counted
        wait_for_errata_applicability_task(int(self.host['id']), before_downgrade)
        # Check that host has applicable errata
        host_errata = Host.errata_list({'host-id': self.host['id']})
        assert host_errata[0]['erratum-id'] == FAKE_1_ERRATA_ID
        assert host_errata[0]['installable'] == 'true'
        # Check the erratum becomes available
        result = self.client.run(
            'yum update --assumeno --security | grep "No packages needed for security"'
        )
        assert result.return_code == 1

    @pytest.mark.tier3
    @pytest.mark.upgrade
    def test_positive_install_package(self):
        """Install a package to a host remotely

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

        :expectedresults: Package was successfully installed

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

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

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

        :expectedresults: Package was successfully removed

        :CaseLevel: System
        """
        self.client.run(f'yum install -y {FAKE_1_CUSTOM_PACKAGE}')
        Host.package_remove({'host-id': self.host['id'], 'packages': FAKE_1_CUSTOM_PACKAGE_NAME})
        result = self.client.run(f'rpm -q {FAKE_1_CUSTOM_PACKAGE_NAME}')
        assert result.return_code != 0

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

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

        :expectedresults: Package was successfully upgraded

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

    @pytest.mark.tier3
    def test_positive_upgrade_packages_all(self):
        """Upgrade all the host packages remotely

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

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

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

    @pytest.mark.tier3
    @pytest.mark.upgrade
    def test_positive_install_and_remove_package_group(self):
        """Install and remove a package group to a host remotely

        :id: ded20a89-cfd9-48d5-8829-739b1a4d4042

        :expectedresults: Package group was successfully installed
            and removed

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

    @pytest.mark.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

        :expectedresults: Host can no longer retrieve content from satellite

        :CaseLevel: System
        """
        result = self.client.run('subscription-manager unregister')
        assert result.return_code == 0
        result = self.client.run(f'yum install -y {FAKE_1_CUSTOM_PACKAGE}')
        assert result.return_code != 0

    @pytest.mark.tier3
    @pytest.mark.upgrade
    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
Beispiel #45
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_1_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()

    @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

        :customerscenario: true

        :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()
                # In case we have a lot of unregistered hosts
                # fixme: Should be replaced with loop across all pages
                self.contenthost.assign_value(
                    common_locators['table_per_page'], '100')
                # 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')
                checked_in_dates = [date for date in dates
                                    if date != 'Never checked in']
                self.assertGreater(checked_in_dates[1], checked_in_dates[0])
                dates = self.contenthost.sort_table_by_column('Last Checkin')
                self.assertGreater(dates[0], dates[1])

    @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
    @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
Beispiel #46
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:
            default_loc_id = (entities.Location().search(
                query={'search': f'name="{DEFAULT_LOC}"'})[0].id)
            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': f'name="{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': f"name = {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:
                cleanup_of_provisioned_server(
                    hostname=client.hostname,
                    provisioning_server=self.libvirt_vm,
                    distro=DISTRO_RHEL7,
                )
            raise Exception(exp)
Beispiel #47
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()