Best Python code snippet using tempest_python
test_implied_role.py
Source:test_implied_role.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.lib.common.utils import data_utils17from tempest.lib import exceptions18from keystone_tempest_plugin.tests.rbac.v3 import base as rbac_base19class IdentityV3RbacImpliedRoleTest(rbac_base.IdentityV3RbacBaseTests,20                                    metaclass=abc.ABCMeta):21    @classmethod22    def setup_clients(cls):23        super(IdentityV3RbacImpliedRoleTest, cls).setup_clients()24        cls.persona = getattr(cls, 'os_%s' % cls.credentials[0])25        cls.client = cls.persona.roles_v3_client26        cls.admin_client = cls.os_system_admin27        cls.admin_roles_client = cls.admin_client.roles_v3_client28    @classmethod29    def resource_setup(cls):30        super(IdentityV3RbacImpliedRoleTest, cls).resource_setup()31        cls.prior_role = cls.admin_roles_client.create_role(32            name=data_utils.rand_name('prior_role'))['role']['id']33        cls.addClassResourceCleanup(34            cls.admin_roles_client.delete_role, cls.prior_role)35        cls.implied_role = cls.admin_roles_client.create_role(36            name=data_utils.rand_name('implied_role'))['role']['id']37        cls.addClassResourceCleanup(38            cls.admin_roles_client.delete_role, cls.implied_role)39    @abc.abstractmethod40    def test_identity_create_implied_role(self):41        """Test identity:create_implied_role policy.42        This test must check:43          * whether the persona can create an implied role44        """45        pass46    @abc.abstractmethod47    def test_identity_get_implied_role(self):48        """Test identity:get_implied_role policy.49        This test must check:50          * whether the persona can get an implied role51        """52        pass53    @abc.abstractmethod54    def test_identity_list_implied_roles(self):55        """Test identity:list_implied_roles policy.56        This test must check:57          * whether the persona can list implied roles58        """59        pass60    @abc.abstractmethod61    def test_identity_list_role_inference_rules(self):62        """Test identity:list_role_inference_rules policy.63        This test must check:64          * whether the persona can list role inference rules65        """66        pass67    @abc.abstractmethod68    def test_identity_delete_implied_role(self):69        """Test identity:delete_implied_role policy.70        This test must check71          * whether the persona can delete an implied role72        """73        pass74    @abc.abstractmethod75    def test_identity_check_implied_role(self):76        """Test identity:check_implied_role policy.77        This test must check:78          * whether the persona can check an association between two roles79        """80        pass81class SystemAdminTests(IdentityV3RbacImpliedRoleTest, base.BaseIdentityTest):82    credentials = ['system_admin']83    def test_identity_create_implied_role(self):84        self.do_request('create_role_inference_rule',85                        expected_status=201,86                        prior_role=self.prior_role,87                        implies_role=self.implied_role)88        self.addCleanup(self.admin_roles_client.delete_role_inference_rule,89                        prior_role=self.prior_role,90                        implies_role=self.implied_role)91    def test_identity_get_implied_role(self):92        self.admin_roles_client.create_role_inference_rule(93            prior_role=self.prior_role, implies_role=self.implied_role)94        self.addCleanup(self.admin_roles_client.delete_role_inference_rule,95                        prior_role=self.prior_role,96                        implies_role=self.implied_role)97        self.do_request('show_role_inference_rule',98                        prior_role=self.prior_role,99                        implies_role=self.implied_role)100    def test_identity_list_implied_roles(self):101        self.admin_roles_client.create_role_inference_rule(102            prior_role=self.prior_role, implies_role=self.implied_role)103        self.addCleanup(self.admin_roles_client.delete_role_inference_rule,104                        prior_role=self.prior_role,105                        implies_role=self.implied_role)106        self.do_request('list_role_inferences_rules',107                        prior_role=self.prior_role)108    def test_identity_list_role_inference_rules(self):109        self.admin_roles_client.create_role_inference_rule(110            prior_role=self.prior_role, implies_role=self.implied_role)111        self.addCleanup(self.admin_roles_client.delete_role_inference_rule,112                        prior_role=self.prior_role,113                        implies_role=self.implied_role)114        self.do_request('list_all_role_inference_rules')115    def test_identity_delete_implied_role(self):116        self.admin_roles_client.create_role_inference_rule(117            prior_role=self.prior_role, implies_role=self.implied_role)118        self.do_request('delete_role_inference_rule',119                        expected_status=204,120                        prior_role=self.prior_role,121                        implies_role=self.implied_role)122    def test_identity_check_implied_role(self):123        self.admin_roles_client.create_role_inference_rule(124            prior_role=self.prior_role, implies_role=self.implied_role)125        self.addCleanup(self.admin_roles_client.delete_role_inference_rule,126                        prior_role=self.prior_role,127                        implies_role=self.implied_role)128        self.do_request('check_role_inference_rule',129                        expected_status=204,130                        prior_role=self.prior_role,131                        implies_role=self.implied_role)132class SystemMemberTests(SystemAdminTests):133    credentials = ['system_member', 'system_admin']134    def test_identity_create_implied_role(self):135        self.do_request('create_role_inference_rule',136                        expected_status=exceptions.Forbidden,137                        prior_role=self.prior_role,138                        implies_role=self.implied_role)139    def test_identity_delete_implied_role(self):140        self.admin_roles_client.create_role_inference_rule(141            prior_role=self.prior_role, implies_role=self.implied_role)142        self.addCleanup(self.admin_roles_client.delete_role_inference_rule,143                        prior_role=self.prior_role,144                        implies_role=self.implied_role)145        self.do_request('delete_role_inference_rule',146                        expected_status=exceptions.Forbidden,147                        prior_role=self.prior_role,148                        implies_role=self.implied_role)149class SystemReaderTests(SystemMemberTests):150    credentials = ['system_reader', 'system_admin']151class DomainAdminTests(SystemReaderTests):152    credentials = ['domain_admin', 'system_admin']153    def test_identity_get_implied_role(self):154        self.admin_roles_client.create_role_inference_rule(155            prior_role=self.prior_role, implies_role=self.implied_role)156        self.addCleanup(self.admin_roles_client.delete_role_inference_rule,157                        prior_role=self.prior_role,158                        implies_role=self.implied_role)159        self.do_request('show_role_inference_rule',160                        expected_status=exceptions.Forbidden,161                        prior_role=self.prior_role,162                        implies_role=self.implied_role)163    def test_identity_list_implied_roles(self):164        self.admin_roles_client.create_role_inference_rule(165            prior_role=self.prior_role, implies_role=self.implied_role)166        self.addCleanup(self.admin_roles_client.delete_role_inference_rule,167                        prior_role=self.prior_role,168                        implies_role=self.implied_role)169        self.do_request('list_role_inferences_rules',170                        expected_status=exceptions.Forbidden,171                        prior_role=self.prior_role)172    def test_identity_list_role_inference_rules(self):173        self.admin_roles_client.create_role_inference_rule(174            prior_role=self.prior_role, implies_role=self.implied_role)175        self.addCleanup(self.admin_roles_client.delete_role_inference_rule,176                        prior_role=self.prior_role,177                        implies_role=self.implied_role)178        self.do_request('list_all_role_inference_rules',179                        expected_status=exceptions.Forbidden)180    def test_identity_check_implied_role(self):181        self.admin_roles_client.create_role_inference_rule(182            prior_role=self.prior_role, implies_role=self.implied_role)183        self.addCleanup(self.admin_roles_client.delete_role_inference_rule,184                        prior_role=self.prior_role,185                        implies_role=self.implied_role)186        self.do_request('check_role_inference_rule',187                        expected_status=exceptions.Forbidden,188                        prior_role=self.prior_role,189                        implies_role=self.implied_role)190class DomainMemberTests(DomainAdminTests):191    credentials = ['domain_member', 'system_admin']192class DomainReaderTests(DomainMemberTests):193    credentials = ['domain_reader', 'system_admin']194class ProjectAdminTests(DomainReaderTests):195    credentials = ['project_admin', 'system_admin']196class ProjectMemberTests(ProjectAdminTests):197    credentials = ['project_member', 'system_admin']198class ProjectReaderTests(ProjectAdminTests):...fixtures.py
Source:fixtures.py  
1# Copyright 2017 AT&T Corporation.2# All Rights Reserved.3#4#    Licensed under the Apache License, Version 2.0 (the "License"); you may5#    not use this file except in compliance with the License. You may obtain6#    a copy of the License at7#8#         http://www.apache.org/licenses/LICENSE-2.09#10#    Unless required by applicable law or agreed to in writing, software11#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT12#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the13#    License for the specific language governing permissions and limitations14#    under the License.15"""Fixtures for Patrole tests."""16from unittest import mock17import fixtures18import time19from tempest import config20from tempest import test21from patrole_tempest_plugin import rbac_utils22CONF = config.CONF23class ConfPatcher(fixtures.Fixture):24    """Fixture to patch and restore global CONF. Adopted from Nova.25    This also resets overrides for everything that is patched during26    its teardown.27    """28    def __init__(self, **kwargs):29        """Constructor30        :params group: if specified all config options apply to that group.31        :params **kwargs: the rest of the kwargs are processed as a32            set of key/value pairs to be set as configuration override.33        """34        super(ConfPatcher, self).__init__()35        self.group = kwargs.pop('group', None)36        self.args = kwargs37    def setUp(self):38        super(ConfPatcher, self).setUp()39        for k, v in self.args.items():40            self.addCleanup(CONF.clear_override, k, self.group)41            CONF.set_override(k, v, self.group)42class FakeBaseRbacTest(rbac_utils.RbacUtilsMixin, test.BaseTestCase):43    credentials = []44    os_primary = None45    def runTest(self):46        pass47class RbacUtilsMixinFixture(fixtures.Fixture):48    """Fixture for `RbacUtils` class."""49    USER_ID = mock.sentinel.user_id50    PROJECT_ID = mock.sentinel.project_id51    def __init__(self, do_reset_mocks=True, rbac_test_roles=None):52        self._do_reset_mocks = do_reset_mocks53        self._rbac_test_roles = rbac_test_roles or ['member']54    def patchobject(self, target, attribute, *args, **kwargs):55        p = mock.patch.object(target, attribute, *args, **kwargs)56        m = p.start()57        self.addCleanup(p.stop)58        return m59    def setUp(self):60        super(RbacUtilsMixinFixture, self).setUp()61        self.useFixture(ConfPatcher(rbac_test_roles=self._rbac_test_roles,62                                    group='patrole'))63        self.useFixture(ConfPatcher(64            admin_role='admin', auth_version='v3', group='identity'))65        self.useFixture(ConfPatcher(66            api_v3=True, group='identity-feature-enabled'))67        # Mock out functionality that can't be used by unit tests. Mocking out68        # time.sleep is a test optimization.69        self.mock_time = self.patchobject(rbac_utils, 'time',70                                          __name__='mock_time', spec=time)71        test_obj_kwargs = {72            'credentials.user_id': self.USER_ID,73            'credentials.tenant_id': self.PROJECT_ID,74            'credentials.project_id': self.PROJECT_ID,75        }76        class FakeRbacTest(FakeBaseRbacTest):77            os_primary = mock.Mock()78            os_admin = mock.Mock()79        FakeRbacTest.os_primary.configure_mock(**test_obj_kwargs)80        self.admin_roles_client = FakeRbacTest.os_admin.roles_v3_client81        self.admin_roles_client.list_all_role_inference_rules.return_value = {82            "role_inferences": [83                {84                    "implies": [{"id": "reader_id", "name": "reader"}],85                    "prior_role": {"id": "member_id", "name": "member"}86                },87                {88                    "implies": [{"id": "member_id", "name": "member"}],89                    "prior_role": {"id": "admin_id", "name": "admin"}90                }91            ]92        }93        default_roles = {'admin', 'member', 'reader'}.union(94            set(self._rbac_test_roles))95        self.set_roles(list(default_roles), [])96        FakeRbacTest.setUpClass()97        self.test_obj = FakeRbacTest()98        if self._do_reset_mocks:99            self.admin_roles_client.reset_mock()100            self.test_obj.os_primary.reset_mock()101            self.test_obj.os_admin.reset_mock()102            self.mock_time.reset_mock()103    def set_roles(self, roles, roles_on_project=None):104        """Set the list of available roles in the system.105        :param roles: List of roles returned by ``list_roles``.106        :param roles_on_project: List of roles returned by107            ``list_user_roles_on_project``.108        :returns: None.109        """110        if not roles_on_project:111            roles_on_project = []112        if not isinstance(roles, list):113            roles = [roles]114        if not isinstance(roles_on_project, list):115            roles_on_project = [roles_on_project]116        available_roles = {117            'roles': [{'name': role, 'id': '%s_id' % role} for role in roles]118        }119        available_project_roles = {120            'roles': [{'name': role, 'id': '%s_id' % role}121                      for role in roles_on_project]122        }123        self.admin_roles_client.list_roles.return_value = available_roles124        self.admin_roles_client.list_user_roles_on_project.return_value = (...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!!
