Best Python code snippet using tempest_python
test_access_rule.py
Source:test_access_rule.py  
1# Copyright 2020 SUSE LLC2#3# Licensed under the Apache License, Version 2.0 (the "License"); you may4# not use this file except in compliance with the License. You may obtain5# a copy of the License at6#7#      http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the12# License for the specific language governing permissions and limitations13# under the License.14import abc15from tempest.api.identity import base16from tempest import clients17from tempest.lib import auth18from tempest.lib.common.utils import data_utils19from tempest.lib import exceptions20from keystone_tempest_plugin.tests.rbac.v3 import base as rbac_base21class IdentityV3RbacAccessRuleTest(rbac_base.IdentityV3RbacBaseTests,22                                   metaclass=abc.ABCMeta):23    identity_version = 'v3'24    @classmethod25    def setup_clients(cls):26        super(IdentityV3RbacAccessRuleTest, cls).setup_clients()27        cls.persona = getattr(cls, 'os_%s' % cls.credentials[0])28        cls.client = cls.persona.access_rules_client29        cls.admin_client = cls.os_system_admin30    def user(self):31        user = {}32        name = data_utils.rand_name('user')33        user['name'] = name34        user['password'] = data_utils.rand_password()35        return user36    def app_cred(self):37        app_cred = {}38        app_cred['name'] = data_utils.rand_name('app_cred')39        app_cred['access_rules'] = [40            {41                'path': '/servers',42                'method': 'GET',43                'service': 'compute',44            }45        ]46        return app_cred47    @classmethod48    def setup_user_client(cls, domain_id=None):49        """Set up project user with its own client.50        This is to enable the project user to create its own app cred.51        Returns a client object and the user's ID.52        """53        user_dict = {54            'name': data_utils.rand_name('user'),55            'password': data_utils.rand_password(),56        }57        if domain_id:58            user_dict['domain_id'] = domain_id59        user_id = cls.admin_client.users_v3_client.create_user(60            **user_dict)['user']['id']61        def try_delete_user():62            # delete user if not deleted by domain deletion63            try:64                cls.admin_client.users_v3_client.delete_user(user_id)65            except exceptions.NotFound:66                pass67        cls.addClassResourceCleanup(try_delete_user)68        project_id = cls.admin_client.projects_client.create_project(69            data_utils.rand_name())['project']['id']70        cls.addClassResourceCleanup(71            cls.admin_client.projects_client.delete_project, project_id)72        member_role_id = cls.admin_client.roles_v3_client.list_roles(73            name='member')['roles'][0]['id']74        cls.admin_client.roles_v3_client.create_user_role_on_project(75            project_id, user_id, member_role_id)76        creds = auth.KeystoneV3Credentials(77            user_id=user_id,78            password=user_dict['password'],79            project_id=project_id)80        auth_provider = clients.get_auth_provider(creds)81        creds = auth_provider.fill_credentials()82        client = clients.Manager(credentials=creds)83        return client, user_id84    @abc.abstractmethod85    def test_identity_get_access_rule(self):86        """Test identity:get_access_rule policy87        This test must check:88          * whether the persona can retrieve an access rule they own89          * whether the persona can retrieve an access rule they do not own90          * whether the persona can retrieve an access rule that does not exist91          * whether the persona can retrieve an access rule for a user in their92            own domain (if applicable)93          * whether the persona can retrieve an access rule for a user in94            another domain (if applicable)95        """96        pass97    @abc.abstractmethod98    def test_identity_list_access_rules(self):99        """Test identity:list_access_rules policy100        This test must check:101          * whether the persona can list their own access rules102          * whether the persona can list the access rules for another user103          * whether the persona can list the access rules for a user in their104            own domain105          * whether the persona can list the access rules for a user in another106            domain107        """108        pass109    @abc.abstractmethod110    def test_identity_delete_access_rule(self):111        """Test identity:delete_access_rule policy.112        This test must check113          * whether the persona can delete an access rule they own114          * whether the persona can delete an access rule for an arbitrary user115          * whether the persona can delete an access rule that does not exist116          * whether the persona can delete an access rule for a user in another117            domain (if applicable)118          * whether the persona can delete an access rule for a user in their119            own domain (if applicable)120          * whether the persona can delete an access rule that does not exist121        """122        pass123class SystemAdminTests(IdentityV3RbacAccessRuleTest, base.BaseIdentityTest):124    credentials = ['system_admin']125    @classmethod126    def setup_clients(cls):127        super(SystemAdminTests, cls).setup_clients()128        cls.test_user_client, cls.test_user_id = cls.setup_user_client()129    def setUp(self):130        # create app cred for other user131        super(SystemAdminTests, self).setUp()132        app_cred_client = self.test_user_client.application_credentials_client133        app_cred = app_cred_client.create_application_credential(134            user_id=self.test_user_id, **self.app_cred()135        )['application_credential']136        self.app_cred_id = app_cred['id']137        self.access_rule_id = app_cred['access_rules'][0]['id']138        def try_delete_app_cred(id):139            app_cred_client = self.admin_client.application_credentials_client140            try:141                app_cred_client.delete_application_credential(142                    user_id=self.test_user_id,143                    application_credential_id=id)144            except exceptions.NotFound:145                pass146        def try_delete_access_rule(id):147            try:148                self.admin_client.access_rules_client.delete_access_rule(149                    user_id=self.test_user_id,150                    access_rule_id=id)151            except exceptions.NotFound:152                pass153        self.addCleanup(try_delete_access_rule, self.access_rule_id)154        self.addCleanup(try_delete_app_cred, self.app_cred_id)155    def test_identity_get_access_rule(self):156        # system admin cannot create app creds and therefore cannot create157        # access rules, so skip retrieval of own access rule158        # retrieve other user's access rules159        self.do_request(160            'show_access_rule',161            user_id=self.test_user_id, access_rule_id=self.access_rule_id)162        # retrieving a non-existent access rule should return a 404163        self.do_request(164            'show_access_rule', expected_status=exceptions.NotFound,165            user_id=self.test_user_id,166            access_rule_id=data_utils.rand_uuid_hex())167    def test_identity_list_access_rules(self):168        # system admin cannot create app creds and therefore cannot create169        # access rules, so skip listing of own access rule170        # list other user's access rules171        self.do_request('list_access_rules', user_id=self.test_user_id)172    def test_identity_delete_access_rule(self):173        # system admin cannot create app creds and therefore cannot create174        # access rules, so skip deletion of own access rule175        # delete other user's access rules176        app_cred_client = self.admin_client.application_credentials_client177        app_cred_client.delete_application_credential(178            user_id=self.test_user_id,179            application_credential_id=self.app_cred_id)180        self.do_request(181            'delete_access_rule', expected_status=204,182            user_id=self.test_user_id, access_rule_id=self.access_rule_id)183        # deleting a non-existent access rule should return a 404184        self.do_request(185            'delete_access_rule', expected_status=exceptions.NotFound,186            user_id=self.test_user_id,187            access_rule_id=data_utils.rand_uuid_hex())188class SystemMemberTests(SystemAdminTests):189    credentials = ['system_member', 'system_admin']190    def test_identity_delete_access_rule(self):191        app_cred_client = self.admin_client.application_credentials_client192        app_cred_client.delete_application_credential(193            user_id=self.test_user_id,194            application_credential_id=self.app_cred_id)195        self.do_request(196            'delete_access_rule', expected_status=exceptions.Forbidden,197            user_id=self.test_user_id, access_rule_id=self.access_rule_id)198        # retrieving a non-existent access rule should return a 404199        self.do_request(200            'show_access_rule', expected_status=exceptions.NotFound,201            user_id=self.test_user_id,202            access_rule_id=data_utils.rand_uuid_hex())203class SystemReaderTests(SystemMemberTests):204    credentials = ['system_reader', 'system_admin']205class DomainAdminTests(IdentityV3RbacAccessRuleTest, base.BaseIdentityTest):206    # Domain admins cannot create their own app creds (app creds can only be207    # scoped to projects) and domain admins have no special privileges over the208    # app creds own by users in their domains.209    credentials = ['domain_admin', 'system_admin']210    @classmethod211    def setup_clients(cls):212        super(DomainAdminTests, cls).setup_clients()213        own_domain_id = cls.persona.credentials.domain_id214        cls.test_client_1, cls.test_user_1 = cls.setup_user_client(215            domain_id=own_domain_id)216    def setUp(self):217        super(DomainAdminTests, self).setUp()218        self.other_domain_id = self.admin_client.domains_client.create_domain(219            name=data_utils.rand_name())['domain']['id']220        self.addCleanup(self.admin_client.domains_client.delete_domain,221                        self.other_domain_id)222        self.addCleanup(self.admin_client.domains_client.update_domain,223                        domain_id=self.other_domain_id, enabled=False)224        self.test_client_2, self.test_user_2 = self.setup_user_client(225            domain_id=self.other_domain_id)226        client = self.test_client_1.application_credentials_client227        app_cred_1 = client.create_application_credential(228            user_id=self.test_user_1, **self.app_cred()229        )['application_credential']230        self.access_rule_1 = app_cred_1['access_rules'][0]['id']231        self.addCleanup(232            self.test_client_1.access_rules_client.delete_access_rule,233            self.test_user_1,234            self.access_rule_1)235        self.addCleanup(236            client.delete_application_credential,237            self.test_user_1,238            app_cred_1['id'])239        client = self.test_client_2.application_credentials_client240        app_cred_2 = client.create_application_credential(241            user_id=self.test_user_2, **self.app_cred()242        )['application_credential']243        self.access_rule_2 = app_cred_2['access_rules'][0]['id']244        self.addCleanup(245            self.test_client_2.access_rules_client.delete_access_rule,246            self.test_user_2,247            self.access_rule_2)248        self.addCleanup(249            client.delete_application_credential,250            self.test_user_2,251            app_cred_2['id'])252    def test_identity_get_access_rule(self):253        # accessing access rules should be forbidden no matter whether the254        # owner is in the domain or outside of it255        # retrieve access rule from user in own domain256        self.do_request(257            'show_access_rule', expected_status=exceptions.Forbidden,258            user_id=self.test_user_1, access_rule_id=self.access_rule_1)259        # retrieve access rule from user in other domain260        self.do_request(261            'show_access_rule', expected_status=exceptions.Forbidden,262            user_id=self.test_user_2, access_rule_id=self.access_rule_2)263        # retrieving a non-existent access rule should return a 403264        self.do_request(265            'show_access_rule', expected_status=exceptions.Forbidden,266            user_id=self.test_user_1,267            access_rule_id=data_utils.rand_uuid_hex())268        self.do_request(269            'show_access_rule', expected_status=exceptions.Forbidden,270            user_id=self.test_user_2,271            access_rule_id=data_utils.rand_uuid_hex())272    def test_identity_list_access_rules(self):273        # listing access rules should be forbidden no matter whether the274        # owner is in the domain or outside of it275        self.do_request(276            'list_access_rules', expected_status=exceptions.Forbidden,277            user_id=self.test_user_1)278        self.do_request(279            'list_access_rules', expected_status=exceptions.Forbidden,280            user_id=self.test_user_2)281    def test_identity_delete_access_rule(self):282        # deleting access rules should be forbidden no matter whether the283        # owner is in the domain or outside of it284        # delete access rule from user in own domain285        self.do_request(286            'delete_access_rule', expected_status=exceptions.Forbidden,287            user_id=self.test_user_1, access_rule_id=self.access_rule_1)288        # delete access rule from user in other domain289        self.do_request(290            'delete_access_rule', expected_status=exceptions.Forbidden,291            user_id=self.test_user_2, access_rule_id=self.access_rule_2)292        # deleting a non-existent access rule should return a 403293        self.do_request(294            'delete_access_rule', expected_status=exceptions.Forbidden,295            user_id=self.test_user_1,296            access_rule_id=data_utils.rand_uuid_hex())297        self.do_request(298            'delete_access_rule', expected_status=exceptions.Forbidden,299            user_id=self.test_user_2,300            access_rule_id=data_utils.rand_uuid_hex())301class DomainMemberTests(DomainAdminTests):302    credentials = ['domain_member', 'system_admin']303class DomainReaderTests(DomainAdminTests):304    credentials = ['domain_reader', 'system_admin']305class ProjectAdminTests(IdentityV3RbacAccessRuleTest, base.BaseIdentityTest):306    credentials = ['project_admin', 'system_admin']307    @classmethod308    def setup_clients(cls):309        super(ProjectAdminTests, cls).setup_clients()310        cls.test_user_client, cls.test_user_id = cls.setup_user_client()311    def setUp(self):312        super(ProjectAdminTests, self).setUp()313        app_cred_client = self.persona.application_credentials_client314        user_id = self.persona.credentials.user_id315        self.app_cred_1 = app_cred_client.create_application_credential(316            user_id, **self.app_cred())['application_credential']317        self.access_rule_1 = self.app_cred_1['access_rules'][0]['id']318        def try_delete_own_app_cred(id):319            app_cred_client = self.persona.application_credentials_client320            try:321                app_cred_client.delete_application_credential(322                    self.persona.credentials.user_id, id)323            except exceptions.NotFound:324                pass325        def try_delete_own_access_rule(id):326            try:327                self.persona.access_rules_client.delete_access_rule(328                    self.persona.credentials.user_id, id)329            except exceptions.NotFound:330                pass331        self.addCleanup(try_delete_own_access_rule, self.access_rule_1)332        self.addCleanup(try_delete_own_app_cred, self.app_cred_1['id'])333        app_cred_client = self.test_user_client.application_credentials_client334        self.app_cred_2 = app_cred_client.create_application_credential(335            self.test_user_id, **self.app_cred())['application_credential']336        self.access_rule_2 = self.app_cred_2['access_rules'][0]['id']337        self.addCleanup(338            self.test_user_client.access_rules_client.delete_access_rule,339            self.test_user_id, self.access_rule_2)340        self.addCleanup(341            app_cred_client.delete_application_credential,342            self.test_user_id, self.app_cred_2['id'])343    def test_identity_get_access_rule(self):344        # should be able to access own credential345        self.do_request(346            'show_access_rule',347            user_id=self.persona.credentials.user_id,348            access_rule_id=self.access_rule_1)349        # retrieving non-existent access rule for self should return 404350        self.do_request(351            'show_access_rule', expected_status=exceptions.NotFound,352            user_id=self.persona.credentials.user_id,353            access_rule_id=data_utils.rand_uuid_hex())354        # should not be able to access another user's credential355        self.do_request(356            'show_access_rule', expected_status=exceptions.Forbidden,357            user_id=self.test_user_id, access_rule_id=self.access_rule_2)358        # retrieving non-existent access rule for other user should return 403359        self.do_request(360            'show_access_rule', expected_status=exceptions.Forbidden,361            user_id=self.test_user_id,362            access_rule_id=data_utils.rand_uuid_hex())363    def test_identity_list_access_rules(self):364        # should be able to list own credentials365        self.do_request(366            'list_access_rules', user_id=self.persona.credentials.user_id)367        # should not be able to list another user's credentials368        self.do_request(369            'list_access_rules', expected_status=exceptions.Forbidden,370            user_id=self.test_user_id)371    def test_identity_delete_access_rule(self):372        # should be able to delete own credential373        app_cred_client = self.persona.application_credentials_client374        app_cred_client.delete_application_credential(375            user_id=self.persona.credentials.user_id,376            application_credential_id=self.app_cred_1['id'])377        self.do_request(378            'delete_access_rule', expected_status=204,379            user_id=self.persona.credentials.user_id,380            access_rule_id=self.access_rule_1)381        # deleting non-existent access rule for self should return 404382        self.do_request(383            'delete_access_rule', expected_status=exceptions.NotFound,384            user_id=self.persona.credentials.user_id,385            access_rule_id=data_utils.rand_uuid_hex())386        # should not be able to delete another user's credential387        self.do_request(388            'delete_access_rule', expected_status=exceptions.Forbidden,389            user_id=self.test_user_id, access_rule_id=self.access_rule_2)390        # deleting non-existent access rule for other user should return 403391        self.do_request(392            'delete_access_rule', expected_status=exceptions.Forbidden,393            user_id=self.test_user_id,394            access_rule_id=data_utils.rand_uuid_hex())395class ProjectMemberTests(ProjectAdminTests):396    credentials = ['project_member', 'system_admin']397class ProjectReaderTests(ProjectAdminTests):...test_access_rules_client.py
Source:test_access_rules_client.py  
...51        super(TestAccessRulesClient, self).setUp()52        fake_auth = fake_auth_provider.FakeAuthProvider()53        self.client = access_rules_client.AccessRulesClient(54            fake_auth, 'identity', 'regionOne')55    def _test_show_access_rule(self, bytes_body=False):56        self.check_service_client_function(57            self.client.show_access_rule,58            'tempest.lib.common.rest_client.RestClient.get',59            self.FAKE_ACCESS_RULE_INFO,60            bytes_body,61            user_id="123456",62            access_rule_id="5499a186")63    def _test_list_access_rules(self, bytes_body=False):64        self.check_service_client_function(65            self.client.list_access_rules,66            'tempest.lib.common.rest_client.RestClient.get',67            self.FAKE_LIST_ACCESS_RULES,68            bytes_body,69            user_id="123456")70    def test_show_access_rule_with_str_body(self):71        self._test_show_access_rule()72    def test_show_access_rule_with_bytes_body(self):73        self._test_show_access_rule(bytes_body=True)74    def test_list_access_rule_with_str_body(self):75        self._test_list_access_rules()76    def test_list_access_rule_with_bytes_body(self):77        self._test_list_access_rules(bytes_body=True)78    def test_delete_access_rule(self):79        self.check_service_client_function(80            self.client.delete_access_rule,81            'tempest.lib.common.rest_client.RestClient.delete',82            {},83            user_id="123456",84            access_rule_id="5499a186",...access_rules_client.py
Source:access_rules_client.py  
...20from oslo_serialization import jsonutils as json21from tempest.lib.common import rest_client22class AccessRulesClient(rest_client.RestClient):23    api_version = "v3"24    def show_access_rule(self, user_id, access_rule_id):25        """Gets details of an access rule.26        For a full list of available parameters, please refer to the official27        API reference:28        https://docs.openstack.org/api-ref/identity/v3/index.html#show-access-rule-details29        """30        resp, body = self.get('users/%s/access_rules/%s' %31                              (user_id, access_rule_id))32        self.expected_success(200, resp.status)33        body = json.loads(body)34        return rest_client.ResponseBody(resp, body)35    def list_access_rules(self, user_id, **params):36        """Lists out all of a user's access rules.37        For a full list of available parameters, please refer to the official38        API reference:...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!!
