Example #1
0
def test_positive_end_to_end(session):
    """Perform end to end testing for location component

    :id: dba5d94d-0c18-4db0-a9e8-66599bffc5d9

    :expectedresults: All expected CRUD actions finished successfully

    :CaseLevel: Integration

    :CaseImportance: High
    """
    loc_parent = entities.Location().create()
    loc_child_name = gen_string('alpha')
    description = gen_string('alpha')
    updated_name = gen_string('alphanumeric')
    with session:
        session.location.create({
            'name': loc_child_name,
            'parent_location': loc_parent.name,
            'description': description
        })
        location_name = "{}/{}".format(loc_parent.name, loc_child_name)
        assert session.location.search(location_name)[0]['Name'] == location_name
        loc_values = session.location.read(location_name)
        assert loc_values['primary']['parent_location'] == loc_parent.name
        assert loc_values['primary']['name'] == loc_child_name
        assert loc_values['primary']['description'] == description
        session.location.update(location_name, {'primary.name': updated_name})
        location_name = "{}/{}".format(loc_parent.name, updated_name)
        assert session.location.search(location_name)[0]['Name'] == location_name
        session.location.delete(location_name)
        assert not session.location.search(location_name)
def test_positive_delete_with_user(session, module_org, module_loc):
    """Delete a Usergroup that contains a user

    :id: 2bda3db5-f54f-412f-831f-8e005631f271

    :expectedresults: Usergroup is deleted but added user is not

    :CaseLevel: Integration
    """
    user_name = gen_string('alpha')
    group_name = gen_utf8(smp=False)
    # Create a new user
    entities.User(
        login=user_name,
        password=gen_string('alpha'),
        organization=[module_org],
        location=[module_loc]
    ).create()

    with session:
        session.usergroup.create({
            'usergroup.name': group_name,
            'usergroup.users': {'assigned': [user_name]},
        })
        session.usergroup.delete(group_name)
        assert not session.usergroup.search(group_name)
        assert session.user.search(user_name) is not None
Example #3
0
    def test_positive_update_parameter(self):
        """Update a parameter associated with location

        :id: 7b61fa71-0203-4709-9abd-9bb51ce6c19f

        :expectedresults: Parameter is updated

        :CaseImportance: Critical
        """
        param_name = gen_string('alpha')
        param_new_value = gen_string('alpha')
        location = make_location()
        # Create parameter
        Location.set_parameter({
            'name': param_name,
            'value': gen_string('alpha'),
            'location': location['name'],
        })
        location = Location.info({'id': location['id']})
        self.assertEqual(len(location['parameters']), 1)
        Location.set_parameter({
            'name': param_name,
            'value': param_new_value,
            'location': location['name'],
        })
        location = Location.info({'id': location['id']})
        self.assertEqual(len(location['parameters']), 1)
        self.assertEqual(
            param_new_value, location['parameters'][param_name.lower()])
Example #4
0
    def test_positive_update_scap_content_with_newtitle(self):
        """Update scap content title

        :id: 2c32e94a-237d-40b9-8a3b-fca2ef26fe79

        :setup:

            1. Oscap should be enabled.
            2. Oscap-cli hammer plugin installed.

        :steps:

            1. Login to hammer shell.
            2. Execute "scap-content" command with "update" as sub-command.
            3. Pass valid parameters and newtitle parameter.

        :expectedresults: The scap-content is updated successfully.

        :CaseImportance: Critical
        """
        title = gen_string('alpha')
        new_title = gen_string('alpha')
        scap_content = make_scapcontent({
            'title': title,
            'scap-file': '/tmp/{0}'.format(self.file_name)})
        self.assertEqual(scap_content['title'], title)
        result = Scapcontent.update({
            'title': title,
            'new-title': new_title})
        if bz_bug_is_open(1496810):
            result = Scapcontent.info({'title': new_title})
        self.assertEqual(result['title'], new_title)
Example #5
0
    def test_positive_remove_parameter_by_loc_name(self):
        """Remove a parameter from location

        :id: 97fda466-1894-431e-bc76-3b1c7643522f

        :expectedresults: Parameter is removed from the location

        :CaseImportance: Critical
        """
        param_name = gen_string('alpha')
        location = make_location()
        Location.set_parameter({
            'name': param_name,
            'value': gen_string('alpha'),
            'location': location['name'],
        })
        location = Location.info({'id': location['id']})
        self.assertEqual(len(location['parameters']), 1)
        Location.delete_parameter({
            'name': param_name,
            'location': location['name'],
        })
        location = Location.info({'id': location['id']})
        self.assertEqual(len(location['parameters']), 0)
        self.assertNotIn(param_name.lower(), location['parameters'])
Example #6
0
    def test_positive_add_rh_custom_spin(self):
        """@Test: Associate Red Hat content in a view and filter it using rule

        @Feature: Content Views

        @Assert: Filtered RH content is available and can be seen in a
        view
        """
        content_view = entities.ContentView(organization=self.org).create()
        content_view.repository = [self.repo]
        content_view = content_view.update(['repository'])
        self.assertEqual(len(content_view.repository), 1)

        # content_view ← cv_filter
        cv_filter = entities.RPMContentViewFilter(
            content_view=content_view,
            inclusion='true',
            name=gen_string('alphanumeric'),
        ).create()
        self.assertEqual(content_view.id, cv_filter.content_view.id)

        # content_view ← cv_filter ← cv_filter_rule
        cv_filter_rule = entities.ContentViewFilterRule(
            content_view_filter=cv_filter,
            name=gen_string('alphanumeric'),
            version='1.0',
        ).create()
        self.assertEqual(cv_filter.id, cv_filter_rule.content_view_filter.id)
    def test_negative_update_with_same_name(self):
        """@Test: Try to update content view filter using name of already
        existing entity

        @Feature: Content View Filter

        @Assert: Content view filter is not updated

        """
        cvf_name = gen_string('utf8')
        ContentView.filter_create({
            'content-view-id': self.content_view['id'],
            'name': cvf_name,
            'type': 'rpm',
        })
        new_name = gen_string('alpha', 100)
        ContentView.filter_create({
            'content-view-id': self.content_view['id'],
            'name': new_name,
            'type': 'rpm',
        })
        with self.assertRaises(CLIReturnCodeError):
            ContentView.filter_update({
                'content-view-id': self.content_view['id'],
                'name': new_name,
                'new-name': cvf_name,
            })
Example #8
0
    def test_positive_remove_parameter_by_loc_id(self):
        """Remove a parameter from location

        :id: 13836073-3e39-4d3e-b4b4-e87619c28bae

        :expectedresults: Parameter is removed from the location

        :CaseImportance: Critical
        """
        param_name = gen_string('alpha')
        location = make_location()
        Location.set_parameter({
            'name': param_name,
            'value': gen_string('alpha'),
            'location-id': location['id'],
        })
        location = Location.info({'id': location['id']})
        self.assertEqual(len(location['parameters']), 1)
        Location.delete_parameter({
            'name': param_name,
            'location-id': location['id'],
        })
        location = Location.info({'id': location['id']})
        self.assertEqual(len(location['parameters']), 0)
        self.assertNotIn(param_name.lower(), location['parameters'])
Example #9
0
    def test_positive_update(self):
        """Update OpenScap content.

        :id: 9870555d-0b60-41ab-a481-81d4d3f78fec

        :Steps:

            1. Create an openscap content.
            2. Provide all the appropriate parameters.
            3. Update the openscap content, here the Org.

        :expectedresults: Whether creating  content for OpenScap is successful.

        :CaseLevel: Integration
        """
        org = entities.Organization(name=gen_string('alpha')).create()
        content_name = gen_string('alpha')
        with Session(self) as session:
            make_oscapcontent(
                session,
                name=content_name,
                content_path=self.content_path,
                content_org=self.org_name,
            )
            self.oscapcontent.update(content_name, content_org=org.name)
            session.nav.go_to_select_org(org.name)
            self.assertIsNotNone(
                self.oscapcontent.search(content_name))
Example #10
0
    def test_positive_create_default_value_with_list(self):
        """Create variable with matching list validator

        :id: 6bc2caa0-1300-4751-8239-34b96517465b

        :steps:

            1. Create variable with default value that matches the list
               validator of step 2
            2. Validate this value with list validator type and rule

        :expectedresults: Variable is created for matching value with list

        :CaseImportance: Critical
        """
        # Generate list of values
        values_list = [
            gen_string('alpha'),
            gen_string('alphanumeric'),
            gen_integer(min_value=100),
            choice(['true', 'false']),
        ]
        # Generate string from list for validator_rule
        values_list_str = ", ".join(str(x) for x in values_list)
        value = choice(values_list)
        smart_variable = entities.SmartVariable(
            puppetclass=self.puppet_class,
            default_value=value,
            validator_type='list',
            validator_rule=values_list_str,
        ).create()
        self.assertEqual(smart_variable.default_value, str(value))
        self.assertEqual(smart_variable.validator_type, 'list')
        self.assertEqual(smart_variable.validator_rule, values_list_str)
Example #11
0
def module_user(request, module_org, module_loc):
    """Creates admin user with default org set to module org and shares that
    user for all tests in the same test module. User's login contains test
    module name as a prefix.

    :rtype: :class:`nailgun.entities.Organization`
    """
    # take only "module" from "tests.ui.test_module"
    test_module_name = request.module.__name__.split('.')[-1].split('_', 1)[-1]
    login = '******'.format(test_module_name, gen_string('alphanumeric'))
    password = gen_string('alphanumeric')
    LOGGER.debug('Creating session user %r', login)
    user = nailgun.entities.User(
        admin=True,
        default_organization=module_org,
        default_location=module_loc,
        description='created automatically by airgun for module "{}"'.format(
            test_module_name),
        login=login,
        password=password,
    ).create()
    user.password = password
    yield user
    try:
        LOGGER.debug('Deleting session user %r', user.login)
        user.delete(synchronous=False)
    except HTTPError as err:
        LOGGER.warning('Unable to delete session user: %s', str(err))
Example #12
0
    def test_negative_create_matcher_value_with_regex(self):
        """Create matcher with non matching regexp validator

        :id: 8a0f9251-7992-4d1e-bace-7e32637bf56f

        :steps:
            1. Create a matcher with value that doesn't matches the regex of
               step 2
            2. Validate this value with regex validator type and rule

        :expectedresults: Matcher is not created for non matching value with
            regexp

        :CaseImportance: Critical
        """
        smart_variable = entities.SmartVariable(
            puppetclass=self.puppet_class,
            default_value=gen_string('numeric'),
            validator_type='regexp',
            validator_rule='[0-9]',
        ).create()
        with self.assertRaises(HTTPError) as context:
            entities.OverrideValue(
                smart_variable=smart_variable,
                match='domain=example.com',
                value=gen_string('alpha'),
            ).create()
        self.assertRegexpMatches(
            context.exception.response.text,
            "Validation failed: Value is invalid"
        )
        self.assertEqual(len(smart_variable.read().override_values), 0)
Example #13
0
    def test_positive_create_matcher_value_with_regex(self):
        """Create matcher with matching regex validator

        :id: 3ad09261-eb55-4758-b915-84006c9e527c

        :steps:
            1. Create a matcher with value that matches the regex of step 2
            2. Validate this value with regex validator type and rule

        :expectedresults: Matcher is created for matching value with regex

        :CaseImportance: Critical
        """
        value = gen_string('numeric')
        smart_variable = entities.SmartVariable(
            puppetclass=self.puppet_class,
            default_value=gen_string('numeric'),
            validator_type='regexp',
            validator_rule='[0-9]',
        ).create()
        entities.OverrideValue(
            smart_variable=smart_variable,
            match='domain=example.com',
            value=value,
        ).create()
        smart_variable = smart_variable.read()
        self.assertEqual(smart_variable.validator_type, 'regexp')
        self.assertEqual(smart_variable.validator_rule, '[0-9]')
        self.assertEqual(
            smart_variable.override_values[0]['match'], 'domain=example.com')
        self.assertEqual(
            smart_variable.override_values[0]['value'], value)
Example #14
0
    def test_negative_create_default_value_with_regex(self):
        """Create variable with non matching regex validator

        :id: 0c80bd58-26aa-4c2a-a087-ed3b88b226a7

        :steps:
            1. Create variable with default value that doesn't matches the
               regex of step 2
            2. Validate this value with regexp validator type and rule

        :expectedresults: Variable is not created for non matching value with
            regex

        :CaseImportance: Critical
        """
        value = gen_string('alpha')
        smart_variable = entities.SmartVariable(
            puppetclass=self.puppet_class,
            default_value=value,
        ).create()
        smart_variable.default_value = gen_string('alpha')
        smart_variable.validator_type = 'regexp'
        smart_variable.validator_rule = '[0-9]'
        with self.assertRaises(HTTPError) as context:
            smart_variable.update([
                'default_value', 'validator_type', 'validator_rule'
            ])
        self.assertRegexpMatches(
            context.exception.response.text,
            "Validation failed: Default value is invalid"
        )
        self.assertEqual(smart_variable.read().default_value, value)
Example #15
0
    def test_positive_create_default_value_with_regex(self):
        """Create variable with matching regex validator

        :id: aa9803b9-9a45-4ad8-b502-e0e32fc4b7d8

        :steps:
            1. Create variable with default value that matches the regex of
               step 2
            2. Validate this value with regex validator type and rule

        :expectedresults: Variable is created for matching value with regex

        :CaseImportance: Critical
        """
        value = gen_string('numeric')
        smart_variable = entities.SmartVariable(
            puppetclass=self.puppet_class,
            default_value=gen_string('alpha'),
        ).create()
        smart_variable.default_value = value
        smart_variable.validator_type = 'regexp'
        smart_variable.validator_rule = '[0-9]'
        smart_variable.update([
            'default_value', 'validator_type', 'validator_rule'
        ])
        smart_variable = smart_variable.read()
        self.assertEqual(smart_variable.default_value, value)
        self.assertEqual(smart_variable.validator_type, 'regexp')
        self.assertEqual(smart_variable.validator_rule, '[0-9]')
Example #16
0
def valid_trusted_puppetmaster_hosts():
    """Returns a list of valid trusted puppetmaster hosts"""
    return [
        '[ ' + gen_string('utf8') + ' ]',
        '[ ' + gen_string('alphanumeric') + ' ]',
        '[ ' + gen_string('numeric') + ' ]'
    ]
Example #17
0
    def test_positive_create_content_environment_chain(self):
        """@Test: Create Content Environment in a chain

        @Feature: Content Environment - Positive Create

        @Assert: Environment is created

        """
        env1_name = gen_string('alpha')
        env2_name = gen_string('alpha')
        description = gen_string('alpha')
        with Session(self.browser) as session:
            make_lifecycle_environment(
                session,
                org=self.org_name,
                name=env1_name,
                description=description
            )
            self.assertIsNotNone(self.contentenv.search(env1_name))
            make_lifecycle_environment(
                session,
                org=self.org_name,
                name=env2_name,
                description=description,
                prior=env1_name,
            )
            self.assertIsNotNone(self.contentenv.search(env2_name))
Example #18
0
    def test_positive_update_hidden_value_in_variable(self):
        """Update the hidden default value of variable

        :id: 21b5586e-9434-45ea-ae85-12e24c549412

        :steps:
            1. Create variable with valid type and value
            2. Set 'Hidden Value' flag to true
            3. Now in hidden state, update the default value

        :expectedresults: 1. The variable default value is updated 2. The
            'hidden value' flag set to True

        :CaseImportance: Critical
        """
        value = gen_string('alpha')
        smart_variable = entities.SmartVariable(
            puppetclass=self.puppet_class,
            default_value=gen_string('alpha'),
            hidden_value=True,
        ).create()
        self.assertEqual(getattr(smart_variable, 'hidden_value?'), True)
        self.assertEqual(smart_variable.default_value, u'*****')
        smart_variable.default_value = value
        smart_variable.update(['default_value'])
        smart_variable = smart_variable.read(params={'show_hidden': 'true'})
        self.assertEqual(smart_variable.default_value, value)
        self.assertEqual(getattr(smart_variable, 'hidden_value?'), True)
    def test_positive_add_custom_product(self):
        """Test that custom product can be associated to Activation Keys

        @id: e66db2bf-517a-46ff-ba23-9f9744bef884

        @Assert: Custom products are successfully associated to Activation key

        @CaseLevel: Integration
        """
        name = gen_string('alpha')
        cv_name = gen_string('alpha')
        env_name = gen_string('alpha')
        product_name = gen_string('alpha')
        # Helper function to create and promote CV to next environment
        repo_id = self.create_sync_custom_repo(product_name=product_name)
        self.cv_publish_promote(cv_name, env_name, repo_id)
        with Session(self.browser) as session:
            make_activationkey(
                session,
                org=self.organization.name,
                name=name,
                env=env_name,
                content_view=cv_name,
            )
            self.assertIsNotNone(self.activationkey.search(name))
            self.activationkey.associate_product(name, [product_name])
            self.assertIsNotNone(self.activationkey.wait_until_element(
                common_locators['alert.success_sub_form']))
Example #20
0
def invalid_create_params():
    """Returns a list of invalid domain create parameters"""
    return [
        {u'description': gen_string(str_type='utf8', length=256)},
        {u'dns-id': '-1'},
        {u'name': gen_string(str_type='utf8', length=256)},
    ]
    def test_positive_delete_with_cv(self):
        """Create Activation key with content view and delete it

        @id: 7e40e1ed-8314-406b-9451-05f64806a6e6

        @Assert: Activation key is deleted

        @CaseLevel: Integration
        """
        name = gen_string('alpha')
        cv_name = gen_string('utf8')
        env_name = gen_string('alpha')
        # Helper function to create and promote CV to next environment
        repo_id = self.create_sync_custom_repo()
        self.cv_publish_promote(cv_name, env_name, repo_id)
        with Session(self.browser) as session:
            make_activationkey(
                session,
                org=self.organization.name,
                name=name,
                env=env_name,
                content_view=cv_name,
            )
            self.assertIsNotNone(self.activationkey.search(name))
            self.activationkey.delete(name)
    def test_positive_create_with_cv(self):
        """Create Activation key for all variations of Content Views

        @id: 2ad000f1-6c80-46aa-a61b-9ea62cefe91b

        @Assert: Activation key is created

        @CaseLevel: Integration
        """
        with Session(self.browser) as session:
            for cv_name in valid_data_list():
                with self.subTest(cv_name):
                    name = gen_string('alpha')
                    env_name = gen_string('alpha')
                    # Helper function to create and promote CV to next env
                    repo_id = self.create_sync_custom_repo()
                    self.cv_publish_promote(cv_name, env_name, repo_id)
                    make_activationkey(
                        session,
                        org=self.organization.name,
                        name=name,
                        env=env_name,
                        content_view=cv_name,
                    )
                    self.assertIsNotNone(self.activationkey.search(name))
    def test_positive_create_with_host_collection(self):
        """Create Activation key with Host Collection

        @id: 0e4ad2b4-47a7-4087-828f-2b0535a97b69

        @Assert: Activation key is created

        @CaseLevel: Integration
        """
        name = gen_string(str_type='alpha')
        # create Host Collection using API
        host_col = entities.HostCollection(
            organization=self.organization,
            name=gen_string(str_type='utf8'),
        ).create()

        with Session(self.browser) as session:
            make_activationkey(
                session,
                org=self.organization.name,
                name=name,
                env=ENVIRONMENT,
            )
            self.assertIsNotNone(self.activationkey.search(name))
            # add Host Collection
            self.activationkey.add_host_collection(name, host_col.name)
            self.assertIsNotNone(self.activationkey.find_element(
                common_locators['alert.success_sub_form']))

            # check added host collection is listed
            self.activationkey.click(tab_locators['ak.host_collections.list'])
            strategy, value = tab_locators['ak.host_collections.add.select']
            host_collection = self.activationkey.wait_until_element(
                (strategy, value % host_col.name))
            self.assertIsNotNone(host_collection)
Example #24
0
    def setUpClass(cls):  # noqa
        super(ActiveDirectoryUserGroupTestCase, cls).setUpClass()
        cls.ldap_user_name = settings.ldap.username
        cls.ldap_user_passwd = settings.ldap.password
        cls.base_dn = settings.ldap.basedn
        cls.group_base_dn = settings.ldap.grpbasedn
        cls.ldap_hostname = settings.ldap.hostname
        cls.usergroup_name = gen_string('alpha')

        authsource_attrs = entities.AuthSourceLDAP(
            onthefly_register=True,
            account=cls.ldap_user_name,
            account_password=cls.ldap_user_passwd,
            base_dn=cls.base_dn,
            groups_base=cls.group_base_dn,
            attr_firstname=LDAP_ATTR['firstname'],
            attr_lastname=LDAP_ATTR['surname'],
            attr_login=LDAP_ATTR['login_ad'],
            server_type=LDAP_SERVER_TYPE['API']['ad'],
            attr_mail=LDAP_ATTR['mail'],
            name=gen_string('alpha'),
            host=cls.ldap_hostname,
            tls=False,
            port='389',
        ).create()
        cls.ldap_server_name = authsource_attrs.name
    def test_positive_create_with_envs(self):
        """Create Activation key for all variations of Environments

        @id: f75e994a-6da1-40a3-9685-f8387388b3f0

        @Assert: Activation key is created

        @CaseLevel: Integration
        """
        with Session(self.browser) as session:
            for env_name in valid_data_list():
                with self.subTest(env_name):
                    name = gen_string('alpha')
                    cv_name = gen_string('alpha')
                    # Helper function to create and sync custom repository
                    repo_id = self.create_sync_custom_repo()
                    # Helper function to create and promote CV to next env
                    self.cv_publish_promote(cv_name, env_name, repo_id)
                    make_activationkey(
                        session,
                        org=self.organization.name,
                        name=name,
                        env=env_name,
                        content_view=cv_name,
                    )
                    self.assertIsNotNone(self.activationkey.search(name))
    def test_positive_update_env(self):
        """Update Environment in an Activation key

        @id: 895cda6a-bb1e-4b94-a858-95f0be78a17b

        @Assert: Activation key is updated

        @CaseLevel: Integration
        """
        name = gen_string('alpha')
        cv_name = gen_string('alpha')
        env_name = gen_string('utf8')
        # Helper function to create and promote CV to next environment
        repo_id = self.create_sync_custom_repo()
        self.cv_publish_promote(cv_name, env_name, repo_id)
        with Session(self.browser) as session:
            make_activationkey(
                session,
                org=self.organization.name,
                name=name,
                env=ENVIRONMENT,
            )
            self.assertIsNotNone(self.activationkey.search(name))
            env_locator = locators['ak.selected_env']
            selected_env = self.activationkey.get_attribute(name, env_locator)
            self.assertEqual(ENVIRONMENT, selected_env)
            self.activationkey.update(name, content_view=cv_name, env=env_name)
            self.assertIsNotNone(self.activationkey.wait_until_element(
                common_locators['alert.success_sub_form']))
            selected_env = self.activationkey.get_attribute(name, env_locator)
            self.assertEqual(env_name, selected_env)
    def test_positive_create_non_default_for_location(self):
        """Create new partition table with disabled 'default' option. Check
        that newly created location does not contain that partition table.

        :id: 094d4583-763b-48d4-a89a-23b90741fd6f

        :expectedresults: New partition table is created and is not present in
            the list of selected partition tables for any new location

        :CaseLevel: Integration
        """
        name = gen_string('alpha')
        org_name = gen_string('alpha')
        with Session(self) as session:
            make_partitiontable(
                session,
                name=name,
                template_path=PARTITION_SCRIPT_DATA_FILE,
                default=False,
            )
            self.assertIsNotNone(self.partitiontable.search(name))
            entities.Location(name=org_name).create()
            self.location.search_and_click(org_name)
            session.nav.click(tab_locators['context.tab_ptable'])
            # Item is listed in 'All Items' list and not Selected Items' list.
            self.assertIsNotNone(
                session.nav.wait_until_element(
                    common_locators['entity_select'] % name)
            )
Example #28
0
def test_negative_set_parameter(session, valid_domain_name):
    """Set a parameter in a domain with 256 chars in name and value.

    :id: 1c647d66-6a3f-4d88-8e6b-60f2fc7fd603

    :expectedresults: Domain parameter is not updated. Error is raised

    :CaseLevel: Integration
    """
    update_values = {
        'parameters.params': [
            {
                'name': gen_string('alpha', 256),
                'value': gen_string('alpha', 256)
            }
        ]
    }
    with session:
        name = valid_domain_name
        session.domain.create({
            'domain.dns_domain': name,
            'domain.full_name': name,
        })
        with pytest.raises(AssertionError) as context:
            session.domain.update(name, update_values)
        assert 'Name is too long' in str(context.value)
    def test_positive_create_default_for_location(self):
        """Create new partition table with enabled 'default' option. Check
        that newly created location has that partition table assigned to it

        :id: 8dfaae7c-2f33-4f0d-93f6-1f78ea4d750d

        :expectedresults: New partition table is created and is present in the
            list of selected partition tables for any new location

        :CaseLevel: Integration
        """
        name = gen_string('alpha')
        loc_name = gen_string('alpha')
        with Session(self) as session:
            make_partitiontable(
                session,
                name=name,
                template_path=PARTITION_SCRIPT_DATA_FILE,
                default=True,
            )
            self.assertIsNotNone(self.partitiontable.search(name))
            entities.Location(name=loc_name).create()
            self.location.search_and_click(loc_name)
            session.nav.click(tab_locators['context.tab_ptable'])
            # Item is listed in 'Selected Items' list and not 'All Items' list.
            self.assertIsNotNone(
                session.nav.wait_until_element(
                    common_locators['entity_deselect'] % name)
            )
    def test_positive_delete_with_env(self):
        """Create Activation key with environment and delete it

        @id: b6019881-3d6e-4b75-89f5-1b62aff3b1ca

        @Assert: Activation key is deleted

        @CaseLevel: Integration
        """
        name = gen_string('alpha')
        cv_name = gen_string('alpha')
        env_name = gen_string('utf8')
        # Helper function to create and promote CV to next environment
        repo_id = self.create_sync_custom_repo()
        self.cv_publish_promote(cv_name, env_name, repo_id)
        with Session(self.browser) as session:
            make_activationkey(
                session,
                org=self.organization.name,
                name=name,
                env=env_name,
                content_view=cv_name,
            )
            self.assertIsNotNone(self.activationkey.search(name))
            self.activationkey.delete(name)
Example #31
0
def test_positive_update_name(session, module_org, module_loc,
                              module_host_group, discovered_host):
    """Update the discovered host name and provision it

    :id: 3770b007-5006-4815-ae03-fbd330aad304

    :Setup: Host should already be discovered

    :expectedresults: The hostname should be updated and host should be
        provisioned

    :BZ: 1728306, 1731112

    :CaseImportance: High
    """
    discovered_host_name = discovered_host['name']
    domain_name = module_host_group.domain.read().name
    new_name = gen_string('alpha').lower()
    new_host_name = f'{new_name}.{domain_name}'
    with session:
        discovered_host_values = session.discoveredhosts.wait_for_entity(
            discovered_host_name)
        assert discovered_host_values['Name'] == discovered_host_name
        session.discoveredhosts.provision(
            discovered_host_name,
            module_host_group.name,
            module_org.name,
            module_loc.name,
            quick=False,
            host_values={'host.name': new_name},
        )
        assert session.host.search(new_host_name)[0]['Name'] == new_host_name
        values = session.host.get_details(new_host_name)
        assert values['properties']['properties_table']['Status'] == 'OK'
        assert not session.discoveredhosts.search(
            f'name = {discovered_host_name}')
Example #32
0
    def test_positive_run_default_job_template_by_ip(self, fixture_vmsetup):
        """Run default template on host connected by ip and list task

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

        :expectedresults: Verify the job was successfully ran against the host
            and task can be listed by name and ID

        :BZ: 1647582

        :parametrized: yes
        """
        client = fixture_vmsetup
        command = "echo {}".format(gen_string('alpha'))
        invocation_command = make_job_invocation({
            'job-template':
            'Run Command - SSH Default',
            'inputs':
            f'command={command}',
            'search-query':
            f"name ~ {client.hostname}",
        })

        try:
            assert invocation_command['success'] == '1'
        except AssertionError:
            result = 'host output: {}'.format(' '.join(
                JobInvocation.get_output({
                    'id': invocation_command['id'],
                    'host': client.hostname
                })))
            raise AssertionError(result)

        task = Task.list_tasks({"search": command})[0]
        search = Task.list_tasks({"search": 'id={}'.format(task["id"])})
        assert search[0]["action"] == task["action"]
Example #33
0
    def test_positive_create_with_compresource(self):
        """Add compute resource during organization creation

        :id: de9f755a-cf06-4ee0-a2f7-f1bfb1015b36

        :expectedresults: compute resource is added.

        :CaseLevel: Integration
        """
        with Session(self.browser):
            for resource_name in generate_strings_list():
                with self.subTest(resource_name):
                    url = (LIBVIRT_RESOURCE_URL %
                           settings.compute_resources.libvirt_hostname)
                    # Create compute resource using nailgun
                    resource = entities.LibvirtComputeResource(
                        name=resource_name,
                        url=url,
                    ).create()
                    self.assertEqual(resource.name, resource_name)
                    self.assertIsNotNone(
                        self.org.create_with_entity(gen_string('alpha'),
                                                    'resources',
                                                    resource_name))
Example #34
0
    def test_negative_rename_sat_no_credentials(self):
        """change hostname without credentials on Satellite server

        :id: ed4f7611-33c9-455f-8557-507cc59ede92

        :BZ: 1485884

        :expectedresults: script terminates with a message, hostname
            is not changed

        :CaseAutomation: automated
        """
        with get_connection() as connection:
            original_name = connection.run('hostname').stdout[0]
            hostname = gen_string('alpha')
            result = connection.run(
                'satellite-change-hostname -y {0}'.format(hostname),
                output_format='plain')
            assert result.return_code == 1
            assert NO_CREDS_MSG in result.stdout
            # assert no changes were made
            result = connection.run('hostname')
            assert original_name == result.stdout[
                0], "Invalid hostame assigned"
Example #35
0
    def test_positive_update_ptable(self):
        """Remove partition table.

        :id: 75662a83-0921-45fd-a4b5-012c48bb003a

        :expectedresults: Partition table is added and then removed.

        :CaseLevel: Integration
        """
        with Session(self.browser) as session:
            org_name = gen_string('alpha')
            make_org(session, org_name=org_name)
            for ptable_name in generate_strings_list():
                with self.subTest(ptable_name):
                    # Create partition table using nailgun
                    ptable = entities.PartitionTable(name=ptable_name).create()
                    self.assertEqual(ptable.name, ptable_name)
                    kwargs = {
                        'org_name': org_name,
                        'entity_type': 'ptables',
                        'entity_name': ptable_name
                    }
                    self.assertIsNotNone(self.org.add_entity(**kwargs))
                    self.assertIsNotNone(self.org.remove_entity(**kwargs))
Example #36
0
    def test_positive_get_info_of_tailoring_file(self, tailoring_file_path):
        """Get information of tailoring file

        :id: bc201194-e8c8-4385-a577-09f3455f5a4d

        :setup: tailoring file

        :steps:

            1. Create tailoring file with valid parameters
            2. Execute "tailoring-file" command with "info" as sub-command
               with valid parameter

        :expectedresults: Tailoring file information should be displayed

        :CaseImportance: Critical
        """
        name = gen_string('alphanumeric')
        make_tailoringfile({
            'name': name,
            'scap-file': tailoring_file_path['satellite']
        })
        result = TailoringFiles.info({'name': name})
        assert result['name'] == name
Example #37
0
    def test_negative_info_scap_content(self):
        """View info of scap content with invalid ID as parameter

        :id: 86f44fb1-2e2b-4004-83c1-4a62162ebea9

        :setup:

            1. Oscap should be enabled.
            2. Default content should already be populated.
            3. Oscap-cli hammer plugin installed.

        :steps:

            1. Login to hammer shell as admin.
            2. Execute the "scap-content" command with info as sub-command.
            3. Pass invalid "ID" of scap-content as argument.

        :expectedresults: The info of the scap-content is not listed.

        :CaseImportance: Critical
        """
        invalid_scap_id = gen_string('alpha')
        with self.assertRaises(CLIReturnCodeError):
            Scapcontent.info({'id': invalid_scap_id})
Example #38
0
def test_positive_add_docker_repo_cv(session, module_org):
    """Add docker repository to a non-composite content view and
    publish it. Then create an activation key and associate it with the
    Docker content view.

    :id: e4935729-c5bc-46be-a23a-93ebde6b3506

    :expectedresults: Content view with docker repo can be added to
        activation key

    :CaseLevel: Integration
    """
    lce = entities.LifecycleEnvironment(organization=module_org).create()
    repo = entities.Repository(
        content_type=REPO_TYPE['docker'],
        product=entities.Product(organization=module_org).create(),
        url=DOCKER_REGISTRY_HUB,
    ).create()
    content_view = entities.ContentView(composite=False,
                                        organization=module_org,
                                        repository=[repo]).create()
    content_view.publish()
    cvv = content_view.read().version[0].read()
    promote(cvv, lce.id)
    ak_name = gen_string('alphanumeric')
    with session:
        session.activationkey.create({
            'name': ak_name,
            'lce': {
                lce.name: True
            },
            'content_view': content_view.name
        })
        ak = session.activationkey.read(ak_name, 'details')
        assert ak['details']['content_view'] == content_view.name
        assert ak['details']['lce'][lce.name][lce.name]
Example #39
0
    def test_negative_create_with_same_name(self):
        """Create OpenScap content with same name

        :id: f5c6491d-b83c-4ca2-afdf-4bb93e6dd92b

        :Steps:

            1. Create an openscap content.
            2. Provide all the appropriate parameters.
            3. Create openscap content with same name

        :expectedresults: Creating content for OpenScap is not successful.

        :BZ: 1474172

        :CaseImportance: Critical
        """
        content_name = gen_string('alpha')
        with Session(self) as session:
            make_oscapcontent(
                session,
                name=content_name,
                content_path=self.content_path,
                content_org=self.org_name,
            )
            self.assertIsNotNone(self.oscapcontent.search(content_name))
            make_oscapcontent(
                session,
                name=content_name,
                content_path=self.content_path,
                content_org=self.org_name,
            )
            self.assertIsNotNone(
                self.oscapcontent.wait_until_element(
                    common_locators['name_haserror'])
            )
Example #40
0
    def test_positive_list_job_template_with_saved_org_and_loc(self):
        """List available job templates with saved default organization and
        location in config

        :id: 4fd05dd7-53e3-41ba-ba90-6181a7190ad8

        :expectedresults: The Job Template can be listed without errors

        :BZ: 1368173

        :CaseImportance: Critical
        """
        template_name = gen_string('alpha')
        location = make_location()
        make_job_template({
            u'organizations': self.organization['name'],
            u'name': template_name,
            u'file': TEMPLATE_FILE,
        })
        templates = JobTemplate.list(
            {'organization-id': self.organization['id']})
        self.assertGreaterEqual(len(templates), 1)
        Defaults.add({
            u'param-name': 'organization_id',
            u'param-value': self.organization['id'],
        })
        Defaults.add({
            u'param-name': 'location_id',
            u'param-value': location['id'],
        })
        try:
            templates = JobTemplate.list()
            self.assertGreaterEqual(len(templates), 1)
        finally:
            Defaults.delete({u'param-name': 'organization_id'})
            Defaults.delete({u'param-name': 'location_id'})
Example #41
0
    def _create_container(self):
        """Create a docker container running a ``standalone-firefox`` selenium.

        Make sure to have the image ``selenium/standalone-firefox`` already
        pulled.
        """
        if self.container:
            return
        self.container = self._client.create_container(
            detach=True,
            environment={
                'SCREEN_WIDTH': '1920',
                'SCREEN_HEIGHT': '1080',
            },
            host_config=self._client.create_host_config(
                publish_all_ports=True),
            image='selenium/standalone-firefox',
            name=self._name.split('.')[-1] +
            '_{0}'.format(gen_string('alphanumeric', 3)),
            ports=[4444],
        )
        LOGGER.debug('Starting container with ID "%s"', self.container['Id'])
        self._client.start(self.container['Id'])
        self.container.update(self._client.port(self.container['Id'], 4444)[0])
Example #42
0
    def test_positive_delete_scap_policy_with_name(self):
        """Delete the scap policy with name as parameter

        :id: 6c167e7b-cbdd-4059-808c-04c686ba9fe8

        :setup:

            1. Oscap should be enabled.
            2. Oscap-cli hammer plugin installed.
            3. Atleast 1 policy.

        :steps:

            1. Login to hammer shell.
            2. Execute "policy" command with "delete" as sub-command.
            3. Pass name as parameter.

        :expectedresults: The scap policy is deleted successfully.
        """
        name = gen_string('alphanumeric')
        scap_policy = make_scap_policy({
            'name':
            name,
            'scap-content-id':
            self.scap_id_rhel6,
            'scap-content-profile-id':
            self.scap_profile_id_rhel6,
            'period':
            OSCAP_PERIOD['weekly'].lower(),
            'weekday':
            OSCAP_WEEKDAY['friday'].lower(),
        })
        self.assertEqual(scap_policy['name'], name)
        Scappolicy.delete({'name': name})
        with self.assertRaises(CLIReturnCodeError):
            Scapcontent.info({'name': scap_policy['name']})
Example #43
0
def test_positive_search_lce_via_UTF8(module_org):
    """Search lifecycle environment via its name containing UTF-8
    chars

    :id: d15001ed-5bbf-43cf-bdd3-1e129dff14ec

    :expectedresults: Can get info for lifecycle by its name

    :BZ: 1077333

    :CaseImportance: High
    """
    test_data = {
        'name': gen_string('utf8', 15),
        'organization-id': module_org.id
    }
    # Can we find the new object
    result = LifecycleEnvironment.info({
        'name':
        make_lifecycle_environment(test_data)['name'],
        'organization-id':
        module_org.id
    })
    assert result['name'] == test_data['name']
Example #44
0
    def test_negative_delete(self):
        """[UI ONLY] Attempt to delete an Activation Key and cancel it

        :id: 07a17b98-b756-405c-b0c2-516f2a16aff1

        :Steps:
            1. Create an Activation key
            2. Attempt to remove an Activation Key
            3. Click Cancel in the confirmation dialog box

        :expectedresults: Activation key is not deleted

        :CaseImportance: Critical
        """
        name = gen_string('alpha')
        with Session(self) as session:
            make_activationkey(
                session,
                org=self.organization.name,
                name=name,
                env=ENVIRONMENT,
            )
            self.assertIsNotNone(self.activationkey.search(name))
            self.activationkey.delete(name, really=False)
Example #45
0
    def test_negative_create_external_with_same_name(self):
        """Attempt to create two User Groups with same External AD User Group
        name

        :id: 8f2cde96-644a-4729-880a-65a22c7e7262

        :Steps:

            1. Create an UserGroup.
            2. Assign External AD UserGroup as per the UserGroup name in AD.
            3. Repeat steps 1) and 2), but provide the same external UserGroup
               name

        :expectedresults: Creation of User Group should not be possible with
            same External AD User Group name.

        :CaseImportance: Critical
        """
        new_usergroup_name = gen_string('alpha')
        with Session(self.browser) as session:
            make_usergroup(
                session,
                name=self.usergroup_name,
                roles=['admin'],
                ext_usergrp='foobargroup',
                ext_authsourceid='LDAP-' + self.ldap_server_name,
            )
            self.assertIsNotNone(self.usergroup.search(self.usergroup_name))
            make_usergroup(
                session,
                name=new_usergroup_name,
                roles=['admin'],
                ext_usergrp='foobargroup',
                ext_authsourceid='LDAP-' + self.ldap_server_name,
            )
            self.assertIsNone(self.usergroup.search(new_usergroup_name))
Example #46
0
    def test_positive_update_inclusion(self, module_org, content_view):
        """Create new content view filter and assign it to existing content
        view by id. Try to update that filter and assign opposite inclusion
        value for it

        :id: 76b3c66d-8200-4cf0-8cd0-b57de4ff12b0

        :expectedresults: Content view filter updated successfully and has
            correct and expected value for inclusion parameter

        :CaseLevel: Integration
        """
        cvf_name = gen_string('utf8')
        ContentView.filter.create(
            {
                'content-view-id': content_view['id'],
                'inclusion': 'true',
                'name': cvf_name,
                'organization-id': module_org.id,
                'type': 'rpm',
            }, )
        cvf = ContentView.filter.info({
            'content-view-id': content_view['id'],
            'name': cvf_name
        })
        assert cvf['inclusion'] == 'true'
        ContentView.filter.update({
            'content-view-id': content_view['id'],
            'name': cvf_name,
            'inclusion': 'false',
        })
        cvf = ContentView.filter.info({
            'content-view-id': content_view['id'],
            'name': cvf_name
        })
        assert cvf['inclusion'] == 'false'
Example #47
0
def test_create_with_config_group(session, module_org, module_loc):
    """Create new host group with assigned config group to it

    :id: 05a64d6b-113b-4652-86bf-19bc65b70131

    :expectedresults: Host group created and contains proper config group
    """
    name = gen_string('alpha')
    environment = entities.Environment(organization=[module_org], location=[module_loc]).create()
    config_group = entities.ConfigGroup().create()
    with session:
        # Create host group with config group
        session.hostgroup.create(
            {
                'host_group.name': name,
                'host_group.puppet_environment': environment.name,
                'puppet_classes.config_groups.assigned': [config_group.name],
            }
        )
        hostgroup_values = session.hostgroup.read(name, widget_names='puppet_classes')
        assert len(hostgroup_values['puppet_classes']['config_groups']['assigned']) == 1
        assert (
            hostgroup_values['puppet_classes']['config_groups']['assigned'][0] == config_group.name
        )
Example #48
0
    def test_positive_end_to_end_with_open_ldap(self, open_ldap_data, server_name):
        """CRUD LDAP Operations with OpenLDAP

        :id: f84db334-0189-11eb-846c-d46d6dd3b5b2

        :parametrized: yes

        :expectedresults: Whether creating/updating/deleting LDAP Auth with OpenLDAP is successful.

        :CaseImportance: High
        """
        auth = make_ldap_auth_source(
            {
                'name': server_name,
                'onthefly-register': 'true',
                'host': open_ldap_data['ldap_hostname'],
                'server-type': LDAP_SERVER_TYPE['CLI']['posix'],
                'attr-login': LDAP_ATTR['login_ad'],
                'attr-firstname': LDAP_ATTR['firstname'],
                'attr-lastname': LDAP_ATTR['surname'],
                'attr-mail': LDAP_ATTR['mail'],
                'account': open_ldap_data['ldap_user_name'],
                'account-password': open_ldap_data['ldap_user_passwd'],
                'base-dn': open_ldap_data['base_dn'],
            }
        )
        assert auth['server']['name'] == server_name
        assert auth['server']['server'] == open_ldap_data['ldap_hostname']
        assert auth['server']['server-type'] == LDAP_SERVER_TYPE['CLI']['posix']
        new_name = gen_string('alpha')
        LDAPAuthSource.update({'name': server_name, 'new-name': new_name})
        updated_auth = LDAPAuthSource.info({'id': auth['server']['id']})
        assert updated_auth['server']['name'] == new_name
        LDAPAuthSource.delete({'name': new_name})
        with pytest.raises(CLIReturnCodeError):
            LDAPAuthSource.info({'name': new_name})
Example #49
0
def test_positive_update_medium(session):
    """Add/Remove medium from/to location

    :id: 738c5ff1-ef09-466f-aaac-64f194cac78d

    :expectedresults: medium is added and removed from the location

    :CaseLevel: Integration
    """
    media = entities.Media(
        path_=INSTALL_MEDIUM_URL % gen_string('alpha', 6),
        os_family='Redhat',
    ).create()
    loc = entities.Location().create()
    with session:
        session.location.update(
            loc.name, {'media.resources.assigned': [media.name]})
        loc_values = session.location.read(loc.name)
        assert loc_values['media']['resources']['assigned'][0] == media.name
        session.location.update(
            loc.name, {'media.resources.unassigned': [media.name]})
        loc_values = session.location.read(loc.name)
        assert len(loc_values['media']['resources']['assigned']) == 0
        assert media.name in loc_values['media']['resources']['unassigned']
Example #50
0
    def test_positive_update_interval(self):
        """Update Sync plan's interval

        @id: 35820efd-099e-45dd-8298-77d5f35c26db

        @Assert: Sync Plan's interval is updated
        """
        name = gen_string('alpha')
        entities.SyncPlan(
            name=name,
            interval=SYNC_INTERVAL['day'],
            organization=self.organization,
            enabled=True,
        ).create()
        with Session(self.browser) as session:
            session.nav.go_to_select_org(self.organization.name)
            for new_interval in valid_sync_intervals():
                with self.subTest(new_interval):
                    self.syncplan.update(name, new_sync_interval=new_interval)
                    self.syncplan.search(name).click()
                    # Assert updated sync interval
                    interval_text = self.syncplan.wait_until_element(
                        locators['sp.fetch_interval']).text
                    self.assertEqual(interval_text, new_interval)
Example #51
0
    def test_positive_update_interval_custom_cron(self):
        """Create a sync plan and update its interval to custom cron.

        :id: 26c58319-cae0-4b0c-b388-2a1fe3f22344

        :expectedresults: A sync plan is created and its interval can be
            updated to custom cron.

        :CaseImportance: Critical
        """
        for interval in valid_sync_interval():
            if interval != SYNC_INTERVAL['custom']:
                sync_plan = entities.SyncPlan(
                    description=gen_string('alpha'),
                    organization=self.org,
                    interval=interval
                ).create()

                sync_plan.interval = SYNC_INTERVAL['custom']
                sync_plan.cron_expression = gen_choice(valid_cron_expressions())
                self.assertEqual(
                    sync_plan.update(['interval', 'cron_expression']).interval,
                    SYNC_INTERVAL['custom']
                )
Example #52
0
def make_smart_variable(
        session, org=None, loc=None, force_context=True, **kwargs):
    """Creates Smart Variable"""
    create_args = {
        u'name': gen_string('alpha'),
        u'puppet_class': None,
        u'description': None,
        u'key_type': None,
        u'default_value': None,
        u'hidden_value': False,
        u'validator_type': None,
        u'validator_rule': None,
        u'matcher': None,
        u'matcher_priority': None,
        u'matcher_merge_overrides': None,
        u'matcher_merge_default': None,
        u'matcher_merge_avoid': None,
    }
    page = session.nav.go_to_puppet_classes
    core_factory(create_args, kwargs, session, page,
                 org=org, loc=loc, force_context=force_context)
    PuppetClasses(session.browser).click(
        PuppetClasses(session.browser).search(kwargs['puppet_class']))
    SmartVariable(session.browser).create(**create_args)
Example #53
0
def test_negative_create_with_same_name(module_org):
    """Create gpg key with valid name and valid gpg key via file
    import then try to create new one with same name

    :id: 8751745c-5cf6-42f7-8fbd-6c23119da486

    :expectedresults: gpg key is not created

    :CaseImportance: Critical
    """
    name = gen_string('alphanumeric')
    gpg_key = make_content_credential({
        'name': name,
        'organization-id': module_org.id
    })
    # Can we find the new object?
    result = ContentCredential.exists({'organization-id': module_org.id},
                                      (search_key, gpg_key[search_key]))
    assert gpg_key[search_key] == result[search_key]
    with pytest.raises(CLIFactoryError):
        make_content_credential({
            'name': name,
            'organization-id': module_org.id
        })
Example #54
0
def test_negative_create_empty_query(controller):
    """Create a bookmark with empty query

    :id: 674d569f-6f86-43ba-b9cc-f43e05e8ab1c

    :parametrized: yes

    :Steps:

        1. Attempt to create a bookmark with a random name, valid controller, and empty query.
        2. List the bookmarks.

    :expectedresults:

        1. Error returned.
        2. Bookmark is not listed.

    :CaseImportance: Critical
    """
    name = gen_string('alpha')
    with pytest.raises(HTTPError):
        entities.Bookmark(controller=controller, name=name, query='').create()
    result = entities.Bookmark().search(query={'search': f'name="{name}"'})
    assert len(result) == 0
Example #55
0
    def test_positive_multibyte_latin1_org_names(self):
        """Hammer Multibyte and Latin-1 Org names break list pagination

        :id: 4fa0afe7-6d0a-4c3e-a0fc-4ecb95c50fc9

        :BZ: 1418412

        :expectedresults: Multibyte and latin1 names need to be
            displayed with consistent spacing
        """
        org_names = [
            gen_string('alpha', random.randint(1, 30)),
            gen_string('latin1', random.randint(1, 30)),
            u'大傻瓜-{0}'.format(gen_string('alpha', 5)),
            u'你好你-{0}'.format(gen_string('alpha', 5)),
            u'jalapeño-{0}'.format(gen_string('alpha', 5)),
            u'организация-{0}'.format(gen_string('alpha', 5)),
        ]
        for org in org_names:
            make_org({'name': org})
        org_list_lines = [
            line.strip() for line in Org.list(output_format='table') if line]
        self.assertGreaterEqual(len(org_list_lines), len(org_names))
        org_names_lines = [
            line
            for line in org_list_lines
            if any(name in line for name in org_names)
        ]
        self.assertEqual(len(org_names_lines), len(org_names))
        for org_str in org_names_lines:
            width = sum(
                1 if unicodedata.east_asian_width(char)
                in ["Na", "N", "A", "H"]
                else 2 for char in org_str
            )
            self.assertEqual(len(org_names_lines[0]), width)
Example #56
0
def valid_name_desc_data():
    """Random data for valid name and description"""
    return (
        {
            u'name': gen_string('numeric'),
            u'description': gen_string('numeric')
        },
        {
            u'name': gen_string('alphanumeric', 255),
            u'description': gen_string('alphanumeric')
        },
        {
            u'name': gen_string('alphanumeric'),
            u'description': gen_string('alphanumeric', 255)
        },
        {
            u'name': gen_string('utf8'),
            u'description': gen_string('utf8')
        },
        {
            u'name': u'<html>{0}</html>'.format(gen_string('alpha')),
            u'description': u'<html>{0}</html>'.format(gen_string('alpha'))
        },
        {
            u'name':
            u"{0}[]@#$%^&*(),./?\\\"{{}}><|''".format(gen_string('utf8')),
            u'description':
            u"{0}[]@#$%^&*(),./?\\\"{{}}><|''".format(gen_string('alpha'))
        },
    )
Example #57
0
:TestType: Functional

:CaseImportance: High

:Upstream: No
"""
import random

import pytest
from fauxfactory import gen_string
from nailgun import entities

from robottelo.config import settings
from robottelo.constants import VALID_GCE_ZONES

clouduser = gen_string('alpha')
finishuser = gen_string('alpha')


@pytest.fixture(scope='module')
def module_gce_cloudimg(default_architecture, module_gce_compute, default_os,
                        gce_custom_cloudinit_uuid):
    """Creates cloudinit image on GCE Compute Resource"""
    cloud_image = entities.Image(
        architecture=default_architecture,
        compute_resource=module_gce_compute,
        name=gen_string('alpha'),
        operatingsystem=default_os,
        username=clouduser,
        uuid=gce_custom_cloudinit_uuid,
        user_data=True,
    def test_positive_run_job_effective_user_by_ip(self, fixture_vmsetup,
                                                   fixture_org):
        """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
        """
        self.org = fixture_org
        self.client = fixture_vmsetup
        # 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 -m {0}'".format(username),
            'search-query':
            "name ~ {0}".format(self.client.hostname),
        })
        try:
            assert 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:
            assert 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
        assert username == result.stdout[0]
    def test_positive_run_effective_user_job(self, fixture_vmsetup,
                                             fixture_org):
        """Tests Ansible REX job having effective user runs successfully

        :id: a5fa20d8-c2bd-4bbf-a6dc-bf307b59dd8c

        :Steps:

            0. Create a VM and register to SAT and prepare for REX (ssh key)

            1. Run Ansible Command job for the host to create a user

            2. Run Ansible Command job using effective user

            3. Check the job result at the host is done under that user

        :expectedresults: multiple asserts along the code

        :CaseAutomation: automated

        :CaseLevel: System
        """
        self.org = fixture_org
        self.client = fixture_vmsetup
        # 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 - Ansible Default',
            'inputs':
            "command='useradd -m {0}'".format(username),
            'search-query':
            "name ~ {0}".format(self.client.hostname),
        })
        try:
            assert 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 - Ansible Default',
            'inputs':
            "command='touch /home/{0}/{1}'".format(username, filename),
            'search-query':
            "name ~ {0}".format(self.client.hostname),
            'effective-user':
            '******'.format(username),
        })
        try:
            assert 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
        assert username == result.stdout[0], "file ownership mismatch"
Example #60
0
    def test_positive_rename_satellite(self):
        """run katello-change-hostname on Satellite server

        :id: 9944bfb1-1440-4820-ada8-2e219f09c0be

        :setup: Satellite server with synchronized rh and custom
            repos and with a registered host

        :steps:

            1. Rename Satellite using katello-change-hostname
            2. Do basic checks for hostname change (hostnamctl)
            3. Run some existence tests, as in backup testing
            4. Verify certificates were properly recreated, check
                for instances of old hostname
                in etc/foreman-installer/scenarios.d/
            5. Check for updated repo urls, installation media paths,
                updated internal capsule
            6. Check usability of entities created before rename: refresh
                manifest, resync repos, republish CVs and re-register hosts
            7. Create new entities (run end-to-end test from robottelo)

        :BZ: 1469466

        :expectedresults: Satellite hostname is successfully updated
            and the server functions correctly

        :CaseAutomation: automated
        """
        with original_manifest() as manifest:
            upload_manifest(self.org.id, manifest.content)
        with get_connection() as connection:
            old_hostname = connection.run('hostname').stdout[0]
            new_hostname = 'new-{0}'.format(old_hostname)
            # create installation medium with hostname in path
            medium_path = 'http://{0}/testpath-{1}/os/'.format(
                old_hostname, gen_string('alpha'))
            medium = entities.Media(organization=[self.org],
                                    path_=medium_path).create()
            repo = entities.Repository(product=self.product,
                                       name='testrepo').create()
            result = connection.run(
                'satellite-change-hostname {0} -y -u {1} -p {2}'.format(
                    new_hostname, self.username, self.password),
                timeout=1200,
            )
            self.assertEqual(result.return_code, 0, 'unsuccessful rename')
            self.assertIn(BCK_MSG, result.stdout)
            # services running after rename?
            result = connection.run('hammer ping')
            self.assertEqual(result.return_code, 0,
                             'services did not start properly')
            # basic hostname check
            result = connection.run('hostname')
            self.assertEqual(result.return_code, 0)
            self.assertIn(new_hostname, result.stdout,
                          'hostname left unchanged')
            # check default capsule
            result = connection.run(
                'hammer -u {1} -p {2} --output json capsule \
                        info --name {0}'.format(new_hostname, self.username,
                                                self.password),
                output_format='json',
            )
            self.assertEqual(result.return_code, 0,
                             'internal capsule not renamed correctly')
            self.assertEqual(result.stdout['url'],
                             "https://{}:9090".format(new_hostname))
            # check old consumer certs were deleted
            result = connection.run('rpm -qa | grep ^{}'.format(old_hostname))
            self.assertEqual(result.return_code, 1,
                             'old consumer certificates not removed')
            # check new consumer certs were created
            result = connection.run('rpm -qa | grep ^{}'.format(new_hostname))
            self.assertEqual(result.return_code, 0,
                             'new consumer certificates not created')
            # check if installation media paths were updated
            result = connection.run(
                'hammer -u {1} -p {2} --output json \
                        medium info --id {0}'.format(medium.id, self.username,
                                                     self.password),
                output_format='json',
            )
            self.assertEqual(result.return_code, 0)
            self.assertIn(new_hostname, result.stdout['path'],
                          'medium path not updated correctly')
            # check answer file for instances of old hostname
            ans_f = '/etc/foreman-installer/scenarios.d/satellite-answers.yaml'
            result = connection.run('grep " {0}" {1}'.format(
                old_hostname, ans_f))
            self.assertEqual(
                result.return_code,
                1,
                'old hostname was not correctly replaced \
                                     in answers.yml',
            )
            # check repository published at path
            result = connection.run(
                'hammer -u {1} -p {2} --output json \
                        repository info --id {0}'.format(
                    repo.id, self.username, self.password),
                output_format='json',
            )
            self.assertEqual(result.return_code, 0)
            self.assertIn(
                new_hostname,
                result.stdout['published-at'],
                'repository published path not updated correctly',
            )

        # refresh manifest
        sub = entities.Subscription(organization=self.org)
        sub.refresh_manifest(data={'organization_id': self.org.id})
        # sync and publish the previously created repo
        repo.sync()
        cv = entities.ContentView(organization=self.org).create()
        cv.repository = [repo]
        cv.update(['repository'])
        cv.publish()