Best Python code snippet using tempest_python
test_auth.py
Source:test_auth.py  
...242        creds = self.auth_provider.credentials243        for attr in ['user_id', 'tenant_id']:244            self.assertEqual(self._get_from_fake_identity(attr),245                             getattr(creds, attr))246    def _test_base_url_helper(self, expected_url, filters,247                              auth_data=None):248        url = self.auth_provider.base_url(filters, auth_data)249        self.assertEqual(url, expected_url)250    def test_base_url(self):251        self.filters = {252            'service': 'compute',253            'endpoint_type': 'publicURL',254            'region': 'FakeRegion'255        }256        expected = self._get_result_url_from_endpoint(257            self._endpoints[0]['endpoints'][1])258        self._test_base_url_helper(expected, self.filters)259    def test_base_url_to_get_admin_endpoint(self):260        self.filters = {261            'service': 'compute',262            'endpoint_type': 'adminURL',263            'region': 'FakeRegion'264        }265        expected = self._get_result_url_from_endpoint(266            self._endpoints[0]['endpoints'][1], endpoint_type='adminURL')267        self._test_base_url_helper(expected, self.filters)268    def test_base_url_unknown_region(self):269        """If the region is unknown, the first endpoint is returned."""270        self.filters = {271            'service': 'compute',272            'endpoint_type': 'publicURL',273            'region': 'AintNoBodyKnowThisRegion'274        }275        expected = self._get_result_url_from_endpoint(276            self._endpoints[0]['endpoints'][0])277        self._test_base_url_helper(expected, self.filters)278    def test_base_url_with_non_existent_service(self):279        self.filters = {280            'service': 'BAD_SERVICE',281            'endpoint_type': 'publicURL',282            'region': 'FakeRegion'283        }284        self.assertRaises(exceptions.EndpointNotFound,285                          self._test_base_url_helper, None, self.filters)286    def test_base_url_without_service(self):287        self.filters = {288            'endpoint_type': 'publicURL',289            'region': 'FakeRegion'290        }291        self.assertRaises(exceptions.EndpointNotFound,292                          self._test_base_url_helper, None, self.filters)293    def test_base_url_with_known_name(self):294        """If name and service is known, return the endpoint."""295        self.filters = {296            'service': 'compute',297            'endpoint_type': 'publicURL',298            'region': 'FakeRegion',299            'name': 'nova'300        }301        expected = self._get_result_url_from_endpoint(302            self._endpoints[0]['endpoints'][1])303        self._test_base_url_helper(expected, self.filters)304    def test_base_url_with_known_name_and_unknown_servce(self):305        """Test with Known Name and Unknown service306        If the name is known but the service is unknown, raise an exception.307        """308        self.filters = {309            'service': 'AintNoBodyKnowThatService',310            'endpoint_type': 'publicURL',311            'region': 'FakeRegion',312            'name': 'AintNoBodyKnowThatName'313        }314        self.assertRaises(exceptions.EndpointNotFound,315                          self._test_base_url_helper, None, self.filters)316    def test_base_url_with_unknown_name_and_known_service(self):317        """Test with Unknown Name and Known Service318        If the name is unknown, raise an exception.  Note that filtering by319        name is only successful service exists.320        """321        self.filters = {322            'service': 'compute',323            'endpoint_type': 'publicURL',324            'region': 'FakeRegion',325            'name': 'AintNoBodyKnowThatName'326        }327        self.assertRaises(exceptions.EndpointNotFound,328                          self._test_base_url_helper, None, self.filters)329    def test_base_url_without_name(self):330        self.filters = {331            'service': 'compute',332            'endpoint_type': 'publicURL',333            'region': 'FakeRegion',334        }335        expected = self._get_result_url_from_endpoint(336            self._endpoints[0]['endpoints'][1])337        self._test_base_url_helper(expected, self.filters)338    def test_base_url_with_api_version_filter(self):339        self.filters = {340            'service': 'compute',341            'endpoint_type': 'publicURL',342            'region': 'FakeRegion',343            'api_version': 'v12'344        }345        expected = self._get_result_url_from_endpoint(346            self._endpoints[0]['endpoints'][1], replacement='v12')347        self._test_base_url_helper(expected, self.filters)348    def test_base_url_with_skip_path_filter(self):349        self.filters = {350            'service': 'compute',351            'endpoint_type': 'publicURL',352            'region': 'FakeRegion',353            'skip_path': True354        }355        expected = 'http://fake_url/'356        self._test_base_url_helper(expected, self.filters)357    def test_base_url_with_unversioned_endpoint(self):358        auth_data = {359            'serviceCatalog': [360                {361                    'type': 'identity',362                    'endpoints': [363                        {364                            'region': 'FakeRegion',365                            'publicURL': 'http://fake_url'366                        }367                    ]368                }369            ]370        }371        filters = {372            'service': 'identity',373            'endpoint_type': 'publicURL',374            'region': 'FakeRegion',375            'api_version': 'v2.0'376        }377        expected = 'http://fake_url/v2.0'378        self._test_base_url_helper(expected, filters, ('token', auth_data))379    def test_base_url_with_extra_path_endpoint(self):380        auth_data = {381            'serviceCatalog': [382                {383                    'type': 'compute',384                    'endpoints': [385                        {386                            'region': 'FakeRegion',387                            'publicURL': 'http://fake_url/some_path/v2.0'388                        }389                    ]390                }391            ]392        }393        filters = {394            'service': 'compute',395            'endpoint_type': 'publicURL',396            'region': 'FakeRegion',397            'api_version': 'v2.0'398        }399        expected = 'http://fake_url/some_path/v2.0'400        self._test_base_url_helper(expected, filters, ('token', auth_data))401    def test_base_url_with_unversioned_extra_path_endpoint(self):402        auth_data = {403            'serviceCatalog': [404                {405                    'type': 'compute',406                    'endpoints': [407                        {408                            'region': 'FakeRegion',409                            'publicURL': 'http://fake_url/some_path'410                        }411                    ]412                }413            ]414        }415        filters = {416            'service': 'compute',417            'endpoint_type': 'publicURL',418            'region': 'FakeRegion',419            'api_version': 'v2.0'420        }421        expected = 'http://fake_url/some_path/v2.0'422        self._test_base_url_helper(expected, filters, ('token', auth_data))423    def test_token_not_expired(self):424        expiry_data = datetime.datetime.utcnow() + datetime.timedelta(days=1)425        self._verify_expiry(expiry_data=expiry_data, should_be_expired=False)426    def test_token_expired(self):427        expiry_data = datetime.datetime.utcnow() - datetime.timedelta(hours=1)428        self._verify_expiry(expiry_data=expiry_data, should_be_expired=True)429    def test_token_not_expired_to_be_renewed(self):430        expiry_data = (datetime.datetime.utcnow() +431                       self.auth_provider.token_expiry_threshold / 2)432        self._verify_expiry(expiry_data=expiry_data, should_be_expired=True)433    def _verify_expiry(self, expiry_data, should_be_expired):434        for expiry_format in self.auth_provider.EXPIRY_DATE_FORMATS:435            auth_data = self._auth_data_with_expiry(436                expiry_data.strftime(expiry_format))437            self.assertEqual(self.auth_provider.is_expired(auth_data),438                             should_be_expired)439    def test_set_scope_all_valid(self):440        for scope in self.auth_provider.SCOPES:441            self.auth_provider.scope = scope442            self.assertEqual(scope, self.auth_provider.scope)443    def test_set_scope_invalid(self):444        with testtools.ExpectedException(exceptions.InvalidScope,445                                         '.* invalid_scope .*'):446            self.auth_provider.scope = 'invalid_scope'447class TestKeystoneV3AuthProvider(TestKeystoneV2AuthProvider):448    _endpoints = fake_identity.IDENTITY_V3_RESPONSE['token']['catalog']449    _auth_provider_class = auth.KeystoneV3AuthProvider450    credentials = fake_credentials.FakeKeystoneV3Credentials()451    def setUp(self):452        super(TestKeystoneV3AuthProvider, self).setUp()453        self.patchobject(v3_client.V3TokenClient, 'raw_request',454                         fake_identity._fake_v3_response)455    def _get_fake_identity(self):456        return fake_identity.IDENTITY_V3_RESPONSE['token']457    def _get_fake_alt_identity(self):458        return fake_identity.ALT_IDENTITY_V3['token']459    def _get_result_url_from_endpoint(self, ep, replacement=None):460        if replacement:461            return ep['url'].replace('v3', replacement)462        return ep['url']463    def _auth_data_with_expiry(self, date_as_string):464        token, access = self.auth_provider.auth_data465        access['expires_at'] = date_as_string466        return token, access467    def _get_from_fake_identity(self, attr):468        token = fake_identity.IDENTITY_V3_RESPONSE['token']469        if attr == 'user_id':470            return token['user']['id']471        elif attr == 'project_id':472            return token['project']['id']473        elif attr == 'user_domain_id':474            return token['user']['domain']['id']475        elif attr == 'project_domain_id':476            return token['project']['domain']['id']477    def test_check_credentials_missing_attribute(self):478        # reset credentials to fresh ones479        self.credentials.reset()480        for attr in ['username', 'password', 'user_domain_name',481                     'project_domain_name']:482            cred = copy.copy(self.credentials)483            del cred[attr]484            self.assertFalse(self.auth_provider.check_credentials(cred),485                             "Credentials should be invalid without %s" % attr)486    def test_check_domain_credentials_missing_attribute(self):487        # reset credentials to fresh ones488        self.credentials.reset()489        domain_creds = fake_credentials.FakeKeystoneV3DomainCredentials()490        for attr in ['username', 'password', 'user_domain_name']:491            cred = copy.copy(domain_creds)492            del cred[attr]493            self.assertFalse(self.auth_provider.check_credentials(cred),494                             "Credentials should be invalid without %s" % attr)495    def test_fill_credentials(self):496        self.auth_provider.fill_credentials()497        creds = self.auth_provider.credentials498        for attr in ['user_id', 'project_id', 'user_domain_id',499                     'project_domain_id']:500            self.assertEqual(self._get_from_fake_identity(attr),501                             getattr(creds, attr))502    # Overwrites v2 test503    def test_base_url_to_get_admin_endpoint(self):504        self.filters = {505            'service': 'compute',506            'endpoint_type': 'admin',507            'region': 'MiddleEarthRegion'508        }509        expected = self._get_result_url_from_endpoint(510            self._endpoints[0]['endpoints'][2])511        self._test_base_url_helper(expected, self.filters)512    # Overwrites v2 test513    def test_base_url_with_unversioned_endpoint(self):514        auth_data = {515            'catalog': [516                {517                    'type': 'identity',518                    'endpoints': [519                        {520                            'region': 'FakeRegion',521                            'url': 'http://fake_url',522                            'interface': 'public'523                        }524                    ]525                }526            ]527        }528        filters = {529            'service': 'identity',530            'endpoint_type': 'publicURL',531            'region': 'FakeRegion',532            'api_version': 'v3'533        }534        expected = 'http://fake_url/v3'535        self._test_base_url_helper(expected, filters, ('token', auth_data))536    def test_base_url_with_extra_path_endpoint(self):537        auth_data = {538            'catalog': [539                {540                    'type': 'compute',541                    'endpoints': [542                        {543                            'region': 'FakeRegion',544                            'url': 'http://fake_url/some_path/v2.0',545                            'interface': 'public'546                        }547                    ]548                }549            ]550        }551        filters = {552            'service': 'compute',553            'endpoint_type': 'publicURL',554            'region': 'FakeRegion',555            'api_version': 'v2.0'556        }557        expected = 'http://fake_url/some_path/v2.0'558        self._test_base_url_helper(expected, filters, ('token', auth_data))559    def test_base_url_with_unversioned_extra_path_endpoint(self):560        auth_data = {561            'catalog': [562                {563                    'type': 'compute',564                    'endpoints': [565                        {566                            'region': 'FakeRegion',567                            'url': 'http://fake_url/some_path',568                            'interface': 'public'569                        }570                    ]571                }572            ]573        }574        filters = {575            'service': 'compute',576            'endpoint_type': 'publicURL',577            'region': 'FakeRegion',578            'api_version': 'v2.0'579        }580        expected = 'http://fake_url/some_path/v2.0'581        self._test_base_url_helper(expected, filters, ('token', auth_data))582    # Base URL test with scope only for V3583    def test_base_url_scope_project(self):584        self.auth_provider.scope = 'project'585        self.filters = {586            'service': 'compute',587            'endpoint_type': 'publicURL',588            'region': 'FakeRegion'589        }590        expected = self._get_result_url_from_endpoint(591            self._endpoints[0]['endpoints'][1])592        self._test_base_url_helper(expected, self.filters)593    # Base URL test with scope only for V3594    def test_base_url_unscoped_identity(self):595        self.auth_provider.scope = 'unscoped'596        self.patchobject(v3_client.V3TokenClient, 'raw_request',597                         fake_identity._fake_v3_response_no_scope)598        self.filters = {599            'service': 'identity',600            'endpoint_type': 'publicURL',601            'region': 'FakeRegion'602        }603        expected = fake_identity.FAKE_AUTH_URL604        self._test_base_url_helper(expected, self.filters)605    # Base URL test with scope only for V3606    def test_base_url_unscoped_other(self):607        self.auth_provider.scope = 'unscoped'608        self.patchobject(v3_client.V3TokenClient, 'raw_request',609                         fake_identity._fake_v3_response_no_scope)610        self.filters = {611            'service': 'compute',612            'endpoint_type': 'publicURL',613            'region': 'FakeRegion'614        }615        self.assertRaises(exceptions.EndpointNotFound,616                          self.auth_provider.base_url,617                          auth_data=self.auth_provider.auth_data,618                          filters=self.filters)...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!!
