Best Python code snippet using tempest_python
test_auth.py
Source:test_auth.py  
...93        super(TestKeystoneV2AuthProvider, self).setUp()94        self.stubs.Set(v2_client.TokenClient, 'raw_request',95                       fake_identity._fake_v2_response)96        self.target_url = 'test_api'97    def _get_fake_identity(self):98        return fake_identity.IDENTITY_V2_RESPONSE['access']99    def _get_fake_alt_identity(self):100        return fake_identity.ALT_IDENTITY_V2_RESPONSE['access']101    def _get_result_url_from_endpoint(self, ep, endpoint_type='publicURL',102                                      replacement=None):103        if replacement:104            return ep[endpoint_type].replace('v2', replacement)105        return ep[endpoint_type]106    def _get_token_from_fake_identity(self):107        return fake_identity.TOKEN108    def _get_from_fake_identity(self, attr):109        access = fake_identity.IDENTITY_V2_RESPONSE['access']110        if attr == 'user_id':111            return access['user']['id']112        elif attr == 'tenant_id':113            return access['token']['tenant']['id']114    def _test_request_helper(self, filters, expected):115        url, headers, body = self.auth_provider.auth_request('GET',116                                                             self.target_url,117                                                             filters=filters)118        self.assertEqual(expected['url'], url)119        self.assertEqual(expected['token'], headers['X-Auth-Token'])120        self.assertEqual(expected['body'], body)121    def _auth_data_with_expiry(self, date_as_string):122        token, access = self.auth_provider.auth_data123        access['token']['expires'] = date_as_string124        return token, access125    def test_request(self):126        filters = {127            'service': 'compute',128            'endpoint_type': 'publicURL',129            'region': 'FakeRegion'130        }131        url = self._get_result_url_from_endpoint(132            self._endpoints[0]['endpoints'][1]) + '/' + self.target_url133        expected = {134            'body': None,135            'url': url,136            'token': self._get_token_from_fake_identity(),137        }138        self._test_request_helper(filters, expected)139    def test_request_with_alt_auth_cleans_alt(self):140        """Test alternate auth data for headers141        Assert that when the alt data is provided for headers, after an142        auth_request the data alt_data is cleaned-up.143        """144        self.auth_provider.set_alt_auth_data(145            'headers',146            (fake_identity.ALT_TOKEN, self._get_fake_alt_identity()))147        filters = {148            'service': 'compute',149            'endpoint_type': 'publicURL',150            'region': 'fakeRegion'151        }152        self.auth_provider.auth_request('GET', self.target_url,153                                        filters=filters)154        # Assert alt auth data is clear after it155        self.assertIsNone(self.auth_provider.alt_part)156        self.assertIsNone(self.auth_provider.alt_auth_data)157    def _test_request_with_identical_alt_auth(self, part):158        """Test alternate but identical auth data for headers159        Assert that when the alt data is provided, but it's actually160        identical, an exception is raised.161        """162        self.auth_provider.set_alt_auth_data(163            part,164            (fake_identity.TOKEN, self._get_fake_identity()))165        filters = {166            'service': 'compute',167            'endpoint_type': 'publicURL',168            'region': 'fakeRegion'169        }170        self.assertRaises(exceptions.BadAltAuth,171                          self.auth_provider.auth_request,172                          'GET', self.target_url, filters=filters)173    def test_request_with_identical_alt_auth_headers(self):174        self._test_request_with_identical_alt_auth('headers')175    def test_request_with_identical_alt_auth_url(self):176        self._test_request_with_identical_alt_auth('url')177    def test_request_with_identical_alt_auth_body(self):178        self._test_request_with_identical_alt_auth('body')179    def test_request_with_alt_part_without_alt_data(self):180        """Test empty alternate auth data181        Assert that when alt_part is defined, the corresponding original182        request element is kept the same.183        """184        filters = {185            'service': 'compute',186            'endpoint_type': 'publicURL',187            'region': 'fakeRegion'188        }189        self.auth_provider.set_alt_auth_data('headers', None)190        url, headers, body = self.auth_provider.auth_request('GET',191                                                             self.target_url,192                                                             filters=filters)193        # The original headers where empty194        self.assertNotEqual(url, self.target_url)195        self.assertIsNone(headers)196        self.assertEqual(body, None)197    def _test_request_with_alt_part_without_alt_data_no_change(self, body):198        """Test empty alternate auth data with no effect199        Assert that when alt_part is defined, no auth_data is provided,200        and the the corresponding original request element was not going to201        be changed anyways, and exception is raised202        """203        filters = {204            'service': 'compute',205            'endpoint_type': 'publicURL',206            'region': 'fakeRegion'207        }208        self.auth_provider.set_alt_auth_data('body', None)209        self.assertRaises(exceptions.BadAltAuth,210                          self.auth_provider.auth_request,211                          'GET', self.target_url, filters=filters)212    def test_request_with_alt_part_without_alt_data_no_change_headers(self):213        self._test_request_with_alt_part_without_alt_data_no_change('headers')214    def test_request_with_alt_part_without_alt_data_no_change_url(self):215        self._test_request_with_alt_part_without_alt_data_no_change('url')216    def test_request_with_alt_part_without_alt_data_no_change_body(self):217        self._test_request_with_alt_part_without_alt_data_no_change('body')218    def test_request_with_bad_service(self):219        filters = {220            'service': 'BAD_SERVICE',221            'endpoint_type': 'publicURL',222            'region': 'fakeRegion'223        }224        self.assertRaises(exceptions.EndpointNotFound,225                          self.auth_provider.auth_request, 'GET',226                          self.target_url, filters=filters)227    def test_request_without_service(self):228        filters = {229            'service': None,230            'endpoint_type': 'publicURL',231            'region': 'fakeRegion'232        }233        self.assertRaises(exceptions.EndpointNotFound,234                          self.auth_provider.auth_request, 'GET',235                          self.target_url, filters=filters)236    def test_check_credentials_missing_attribute(self):237        for attr in ['username', 'password']:238            cred = copy.copy(self.credentials)239            del cred[attr]240            self.assertFalse(self.auth_provider.check_credentials(cred))241    def test_fill_credentials(self):242        self.auth_provider.fill_credentials()243        creds = self.auth_provider.credentials244        for attr in ['user_id', 'tenant_id']:245            self.assertEqual(self._get_from_fake_identity(attr),246                             getattr(creds, attr))247    def _test_base_url_helper(self, expected_url, filters,248                              auth_data=None):249        url = self.auth_provider.base_url(filters, auth_data)250        self.assertEqual(url, expected_url)251    def test_base_url(self):252        self.filters = {253            'service': 'compute',254            'endpoint_type': 'publicURL',255            'region': 'FakeRegion'256        }257        expected = self._get_result_url_from_endpoint(258            self._endpoints[0]['endpoints'][1])259        self._test_base_url_helper(expected, self.filters)260    def test_base_url_to_get_admin_endpoint(self):261        self.filters = {262            'service': 'compute',263            'endpoint_type': 'adminURL',264            'region': 'FakeRegion'265        }266        expected = self._get_result_url_from_endpoint(267            self._endpoints[0]['endpoints'][1], endpoint_type='adminURL')268        self._test_base_url_helper(expected, self.filters)269    def test_base_url_unknown_region(self):270        """If the region is unknown, the first endpoint is returned."""271        self.filters = {272            'service': 'compute',273            'endpoint_type': 'publicURL',274            'region': 'AintNoBodyKnowThisRegion'275        }276        expected = self._get_result_url_from_endpoint(277            self._endpoints[0]['endpoints'][0])278        self._test_base_url_helper(expected, self.filters)279    def test_base_url_with_non_existent_service(self):280        self.filters = {281            'service': 'BAD_SERVICE',282            'endpoint_type': 'publicURL',283            'region': 'FakeRegion'284        }285        self.assertRaises(exceptions.EndpointNotFound,286                          self._test_base_url_helper, None, self.filters)287    def test_base_url_without_service(self):288        self.filters = {289            'endpoint_type': 'publicURL',290            'region': 'FakeRegion'291        }292        self.assertRaises(exceptions.EndpointNotFound,293                          self._test_base_url_helper, None, self.filters)294    def test_base_url_with_api_version_filter(self):295        self.filters = {296            'service': 'compute',297            'endpoint_type': 'publicURL',298            'region': 'FakeRegion',299            'api_version': 'v12'300        }301        expected = self._get_result_url_from_endpoint(302            self._endpoints[0]['endpoints'][1], replacement='v12')303        self._test_base_url_helper(expected, self.filters)304    def test_base_url_with_skip_path_filter(self):305        self.filters = {306            'service': 'compute',307            'endpoint_type': 'publicURL',308            'region': 'FakeRegion',309            'skip_path': True310        }311        expected = 'http://fake_url/'312        self._test_base_url_helper(expected, self.filters)313    def test_token_not_expired(self):314        expiry_data = datetime.datetime.utcnow() + datetime.timedelta(days=1)315        self._verify_expiry(expiry_data=expiry_data, should_be_expired=False)316    def test_token_expired(self):317        expiry_data = datetime.datetime.utcnow() - datetime.timedelta(hours=1)318        self._verify_expiry(expiry_data=expiry_data, should_be_expired=True)319    def test_token_not_expired_to_be_renewed(self):320        expiry_data = (datetime.datetime.utcnow() +321                       self.auth_provider.token_expiry_threshold / 2)322        self._verify_expiry(expiry_data=expiry_data, should_be_expired=True)323    def _verify_expiry(self, expiry_data, should_be_expired):324        for expiry_format in self.auth_provider.EXPIRY_DATE_FORMATS:325            auth_data = self._auth_data_with_expiry(326                expiry_data.strftime(expiry_format))327            self.assertEqual(self.auth_provider.is_expired(auth_data),328                             should_be_expired)329class TestKeystoneV3AuthProvider(TestKeystoneV2AuthProvider):330    _endpoints = fake_identity.IDENTITY_V3_RESPONSE['token']['catalog']331    _auth_provider_class = auth.KeystoneV3AuthProvider332    credentials = fake_credentials.FakeKeystoneV3Credentials()333    def setUp(self):334        super(TestKeystoneV3AuthProvider, self).setUp()335        self.stubs.Set(v3_client.V3TokenClient, 'raw_request',336                       fake_identity._fake_v3_response)337    def _get_fake_identity(self):338        return fake_identity.IDENTITY_V3_RESPONSE['token']339    def _get_fake_alt_identity(self):340        return fake_identity.ALT_IDENTITY_V3['token']341    def _get_result_url_from_endpoint(self, ep, replacement=None):342        if replacement:343            return ep['url'].replace('v3', replacement)344        return ep['url']345    def _auth_data_with_expiry(self, date_as_string):346        token, access = self.auth_provider.auth_data347        access['expires_at'] = date_as_string348        return token, access349    def _get_from_fake_identity(self, attr):350        token = fake_identity.IDENTITY_V3_RESPONSE['token']351        if attr == 'user_id':...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!!
