Best Python code snippet using tempest_python
accounts.py
Source:accounts.py  
...123                    names.append(fd.read())124        msg = ('Insufficient number of users provided. %s have allocated all '125               'the credentials for this allocation request' % ','.join(names))126        raise exceptions.InvalidConfiguration(msg)127    def _get_match_hash_list(self, roles=None):128        hashes = []129        if roles:130            # Loop over all the creds for each role in the subdict and generate131            # a list of cred lists for each role132            for role in roles:133                temp_hashes = self.hash_dict['roles'].get(role, None)134                if not temp_hashes:135                    raise exceptions.InvalidConfiguration(136                        "No credentials with role: %s specified in the "137                        "accounts ""file" % role)138                hashes.append(temp_hashes)139            # Take the list of lists and do a boolean and between each list to140            # find the creds which fall under all the specified roles141            temp_list = set(hashes[0])142            for hash_list in hashes[1:]:143                temp_list = temp_list & set(hash_list)144            hashes = temp_list145        else:146            hashes = self.hash_dict['creds'].keys()147        # NOTE(mtreinish): admin is a special case because of the increased148        # privlege set which could potentially cause issues on tests where that149        # is not expected. So unless the admin role isn't specified do not150        # allocate admin.151        admin_hashes = self.hash_dict['roles'].get(CONF.identity.admin_role,152                                                   None)153        if ((not roles or CONF.identity.admin_role not in roles) and154                admin_hashes):155            useable_hashes = [x for x in hashes if x not in admin_hashes]156        else:157            useable_hashes = hashes158        return useable_hashes159    def _get_creds(self, roles=None):160        if self.use_default_creds:161            raise exceptions.InvalidConfiguration(162                "Account file %s doesn't exist" % CONF.auth.test_accounts_file)163        useable_hashes = self._get_match_hash_list(roles)164        free_hash = self._get_free_hash(useable_hashes)165        return self.hash_dict['creds'][free_hash]166    @lockutils.synchronized('test_accounts_io', external=True)167    def remove_hash(self, hash_string):168        hash_path = os.path.join(self.accounts_dir, hash_string)169        if not os.path.isfile(hash_path):170            LOG.warning('Expected an account lock file %s to remove, but '171                        'one did not exist' % hash_path)172        else:173            os.remove(hash_path)174            if not os.listdir(self.accounts_dir):175                os.rmdir(self.accounts_dir)176    def get_hash(self, creds):177        for _hash in self.hash_dict['creds']:178            # Comparing on the attributes that are expected in the YAML179            if all([getattr(creds, k) == self.hash_dict['creds'][_hash][k] for180                   k in creds.get_init_attributes()]):181                return _hash182        raise AttributeError('Invalid credentials %s' % creds)183    def remove_credentials(self, creds):184        _hash = self.get_hash(creds)185        self.remove_hash(_hash)186    def get_primary_creds(self):187        if self.isolated_creds.get('primary'):188            return self.isolated_creds.get('primary')189        creds = self._get_creds()190        primary_credential = cred_provider.get_credentials(**creds)191        self.isolated_creds['primary'] = primary_credential192        return primary_credential193    def get_alt_creds(self):194        if self.isolated_creds.get('alt'):195            return self.isolated_creds.get('alt')196        creds = self._get_creds()197        alt_credential = cred_provider.get_credentials(**creds)198        self.isolated_creds['alt'] = alt_credential199        return alt_credential200    def get_creds_by_roles(self, roles, force_new=False):201        roles = list(set(roles))202        exist_creds = self.isolated_creds.get(str(roles), None)203        # The force kwarg is used to allocate an additional set of creds with204        # the same role list. The index used for the previously allocation205        # in the isolated_creds dict will be moved.206        if exist_creds and not force_new:207            return exist_creds208        elif exist_creds and force_new:209            new_index = str(roles) + '-' + str(len(self.isolated_creds))210            self.isolated_creds[new_index] = exist_creds211        creds = self._get_creds(roles=roles)212        role_credential = cred_provider.get_credentials(**creds)213        self.isolated_creds[str(roles)] = role_credential214        return role_credential215    def clear_isolated_creds(self):216        for creds in self.isolated_creds.values():217            self.remove_credentials(creds)218    def get_admin_creds(self):219        return self.get_creds_by_roles([CONF.identity.admin_role])220    def is_role_available(self, role):221        if self.use_default_creds:222            return False223        else:224            if self.hash_dict['roles'].get(role):225                return True226            return False227    def admin_available(self):228        return self.is_role_available(CONF.identity.admin_role)229class NotLockingAccounts(Accounts):230    """Credentials provider which always returns the first and second231    configured accounts as primary and alt users.232    This credential provider can be used in case of serial test execution233    to preserve the current behaviour of the serial tempest run.234    """235    def _unique_creds(self, cred_arg=None):236        """Verify that the configured credentials are valid and distinct """237        if self.use_default_creds:238            try:239                user = self.get_primary_creds()240                alt_user = self.get_alt_creds()241                return getattr(user, cred_arg) != getattr(alt_user, cred_arg)242            except exceptions.InvalidCredentials as ic:243                msg = "At least one of the configured credentials is " \244                      "not valid: %s" % ic.message245                raise exceptions.InvalidConfiguration(msg)246        else:247            # TODO(andreaf) Add a uniqueness check here248            return len(self.hash_dict['creds']) > 1249    def is_multi_user(self):250        return self._unique_creds('username')251    def is_multi_tenant(self):252        return self._unique_creds('tenant_id')253    def get_creds(self, id, roles=None):254        try:255            hashes = self._get_match_hash_list(roles)256            # No need to sort the dict as within the same python process257            # the HASH seed won't change, so subsequent calls to keys()258            # will return the same result259            _hash = hashes[id]260        except IndexError:261            msg = 'Insufficient number of users provided'262            raise exceptions.InvalidConfiguration(msg)263        return self.hash_dict['creds'][_hash]264    def get_primary_creds(self):265        if self.isolated_creds.get('primary'):266            return self.isolated_creds.get('primary')267        if not self.use_default_creds:268            creds = self.get_creds(0)269            primary_credential = cred_provider.get_credentials(**creds)...test_preprov_creds.py
Source:test_preprov_creds.py  
...15from tempest.lib import exceptions as lib_exc16from cinnamon_role import preprov_creds as ppc17from cinnamon_role.unit import base18class TestExactMatchingProvider(base.BaseTestCase):19    def test_get_match_hash_list(self):20        prov = self._get_provider()21        roles_wanted = ['role1', 'role2']22        # the role hashes are set up with the roles as keys, and the users23        # with that role in a list as the value24        # This dict is structured with the users/roles as follows:25        #   user1: ['role1', 'role2']26        #   user2: ['role1', 'role3']27        #   user3: ['role1', 'role2', role3']28        # We should only get user1, because that is the only user with29        # an exact match in roles30        role_hashes = {'role1': ['user1', 'user2', 'user3'],31                       'role2': ['user1', 'user3'],32                       'role3': ['user2', 'user3']}33        prov.hash_dict['roles'] = role_hashes34        expected_users = ['user1']35        with mock.patch('cinnamon_role.preprov_creds.super') as mock_sup:36            supers_users = ['user1', 'user3']37            mock_get = mock.Mock()38            mock_get.return_value = supers_users39            mock_sup.return_value._get_match_hash_list = mock_get40            actual_users = prov._get_match_hash_list(roles=roles_wanted)41        self.assertEqual(expected_users, actual_users)42    def test_get_match_hash_list_without_roles(self):43        prov = self._get_provider()44        hashes = mock.Mock()45        match_hash_list = mock.Mock()46        match_hash_list.return_value = hashes47        with mock.patch('cinnamon_role.preprov_creds.super') as mock_sup:48            mock_sup.return_value._get_match_hash_list = match_hash_list49            actual_hashes = prov._get_match_hash_list()50        self.assertEqual(hashes, actual_hashes)51        match_hash_list.assert_called_once_with(roles=None)52    def test_get_match_hash_list_no_users_available(self):53        prov = self._get_provider()54        roles_wanted = ['role1', 'role2']55        # user1: ['role1']56        # user2: ['role1', 'role3']57        # user3: ['role1', 'role2', 'role3']58        role_hashes = {'role1': ['user1', 'user2', 'user3'],59                       'role2': ['user3'],60                       'role3': ['user2', 'user3']}61        prov.hash_dict['roles'] = role_hashes62        with mock.patch('cinnamon_role.preprov_creds.super') as mock_sup:63            supers_users = ['user3']...preprov_creds.py
Source:preprov_creds.py  
...20    restrictiveness. The existing provider checks to see if the desired21    roles are a subset of any user. This provider changes that to be an22    exact match of roles on the user.23    """24    def _get_match_hash_list(self, roles=None):25        temp_hashes = super(26            ExactRoleMatchingPreProvisionedCredentialProvider,27            self)._get_match_hash_list(roles=roles)28        if roles:29            # search through the roles we don't want because if we find a user30            # in those roles, we don't want the user. We need to make an exact31            # match32            unwanted_roles = set(self.hash_dict['roles'].keys()) - set(roles)33            for role in unwanted_roles:34                unwanted_users = self.hash_dict['roles'].get(role)35                users_to_remove = set(temp_hashes) & set(unwanted_users)36                temp_hashes = list(set(temp_hashes) - set(users_to_remove))37            if not temp_hashes:38                raise lib_exc.InvalidCredentials(39                    "No credentials with exact roles %s specified in the "40                    "accounts file" % roles)41        return temp_hashes42    def are_roles_available(self, roles):43        try:44            hashes = self._get_match_hash_list(roles=roles)45        except lib_exc.InvalidCredentials:46            return False47        if hashes:48            return True49        else:...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
