Best Python code snippet using tempest_python
test_config_tempest_user.py
Source:test_config_tempest_user.py  
1# -*- coding: utf-8 -*-2# Copyright 2017 Red Hat, Inc.3# All Rights Reserved.4#5# Licensed under the Apache License, Version 2.0 (the "License"); you may6# not use this file except in compliance with the License. You may obtain7# a copy of the License at8#9#      http://www.apache.org/licenses/LICENSE-2.010#11# Unless required by applicable law or agreed to in writing, software12# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the14# License for the specific language governing permissions and limitations15# under the License.16from config_tempest import config_tempest as tool17from config_tempest.tests.base import BaseConfigTempestTest18import mock19from tempest.lib import exceptions20class TestCreateTempestUser(BaseConfigTempestTest):21    def setUp(self):22        super(TestCreateTempestUser, self).setUp()23        self.conf = self._get_conf("v2.0", "v3")24        self.tenants_client = self._get_clients(self.conf).tenants25        self.users_client = self._get_clients(self.conf).users26        self.roles_client = self._get_clients(self.conf).roles27    @mock.patch('config_tempest.config_tempest.'28                'create_user_with_tenant')29    @mock.patch('config_tempest.config_tempest.give_role_to_user')30    def _test_create_tempest_user(self,31                                  mock_give_role_to_user,32                                  mock_create_user_with_tenant,33                                  services):34        alt_username = "my_user"35        alt_password = "my_pass"36        alt_tenant_name = "my_tenant"37        self.conf.set("identity", "alt_username", alt_username)38        self.conf.set("identity", "alt_password", alt_password)39        self.conf.set("identity", "alt_tenant_name", alt_tenant_name)40        tool.create_tempest_users(self.tenants_client,41                                  self.roles_client,42                                  self.users_client,43                                  self.conf,44                                  services=services)45        if 'orchestration' in services:46            self.assertEqual(mock_give_role_to_user.mock_calls, [47                mock.call(self.tenants_client,48                          self.roles_client,49                          self.users_client,50                          self.conf.get('identity',51                                        'admin_username'),52                          self.conf.get('identity',53                                        'tenant_name'),54                          role_name='admin'),55                mock.call(self.tenants_client,56                          self.roles_client,57                          self.users_client,58                          self.conf.get('identity',59                                        'username'),60                          self.conf.get('identity',61                                        'tenant_name'),62                          role_name='heat_stack_owner',63                          role_required=False),64            ])65        else:66            mock_give_role_to_user.assert_called_with(67                self.tenants_client, self.roles_client,68                self.users_client,69                self.conf.get('identity', 'admin_username'),70                self.conf.get('identity', 'tenant_name'),71                role_name='admin')72        self.assertEqual(mock_create_user_with_tenant.mock_calls, [73            mock.call(self.tenants_client,74                      self.users_client,75                      self.conf.get('identity', 'username'),76                      self.conf.get('identity', 'password'),77                      self.conf.get('identity', 'tenant_name')),78            mock.call(self.tenants_client,79                      self.users_client,80                      self.conf.get('identity', 'alt_username'),81                      self.conf.get('identity', 'alt_password'),82                      self.conf.get('identity', 'alt_tenant_name')),83        ])84    def test_create_tempest_user(self):85        services = ['compute', 'network']86        self._test_create_tempest_user(services=services)87    def test_create_tempest_user_with_orchestration(self):88        services = ['compute', 'network', 'orchestration']89        self._test_create_tempest_user(services=services)90class TestCreateUserWithTenant(BaseConfigTempestTest):91    def setUp(self):92        super(TestCreateUserWithTenant, self).setUp()93        self.conf = self._get_conf("v2.0", "v3")94        self.tenants_client = self._get_clients(self.conf).tenants95        self.users_client = self._get_clients(self.conf).users96        self.username = "test_user"97        self.password = "cryptic"98        self.tenant_name = "project"99        self.tenant_description = "Tenant for Tempest %s user" % self.username100        self.email = "%s@test.com" % self.username101    @mock.patch('tempest.common.identity.get_tenant_by_name')102    @mock.patch('tempest.lib.services.identity.v2.tenants_client.'103                'TenantsClient.create_tenant')104    @mock.patch('tempest.lib.services.identity.v2.users_client.'105                'UsersClient.create_user')106    def test_create_user_with_tenant(self,107                                     mock_create_user,108                                     mock_create_tenant,109                                     mock_get_tenant_by_name):110        mock_get_tenant_by_name.return_value = {'id': "fake-id"}111        tool.create_user_with_tenant(112            tenants_client=self.tenants_client,113            users_client=self.users_client,114            username=self.username,115            password=self.password,116            tenant_name=self.tenant_name)117        mock_create_tenant.assert_called_with(118            name=self.tenant_name, description=self.tenant_description)119        mock_create_user.assert_called_with(name=self.username,120                                            password=self.password,121                                            tenantId="fake-id",122                                            email=self.email)123    @mock.patch('tempest.common.identity.get_tenant_by_name')124    @mock.patch(125        'tempest.lib.services.identity.v2.'126        'tenants_client.TenantsClient.create_tenant')127    @mock.patch('tempest.lib.services.identity.v2'128                '.users_client.UsersClient.create_user')129    def test_create_user_with_tenant_tenant_exists(130            self,131            mock_create_user,132            mock_create_tenant,133            mock_get_tenant_by_name):134        mock_get_tenant_by_name.return_value = {'id': "fake-id"}135        exc = exceptions.Conflict136        mock_create_tenant.side_effect = exc137        tool.create_user_with_tenant(138            tenants_client=self.tenants_client,139            users_client=self.users_client,140            username=self.username,141            password=self.password,142            tenant_name=self.tenant_name)143        mock_create_tenant.assert_called_with(144            name=self.tenant_name, description=self.tenant_description)145        mock_create_user.assert_called_with(146            name=self.username,147            password=self.password,148            tenantId="fake-id",149            email=self.email)150    @mock.patch('tempest.lib.services.identity.v2.'151                'users_client.UsersClient.update_user_password')152    @mock.patch('tempest.common.identity.get_user_by_username')153    @mock.patch('tempest.common.identity.get_tenant_by_name')154    @mock.patch('tempest.lib.services.identity.v2.'155                'tenants_client.TenantsClient.create_tenant')156    @mock.patch('tempest.lib.services.identity.'157                'v2.users_client.UsersClient.create_user')158    def test_create_user_with_tenant_user_exists(159            self, mock_create_user, mock_create_tenant,160            mock_get_tenant_by_name,161            mock_get_user_by_username,162            mock_update_user_password):163        mock_get_tenant_by_name.return_value = {'id': "fake-id"}164        exc = exceptions.Conflict165        mock_create_user.side_effect = exc166        fake_user = {'id': "fake_user_id"}167        mock_get_user_by_username.return_value = fake_user168        tool.create_user_with_tenant(169            tenants_client=self.tenants_client,170            users_client=self.users_client,171            username=self.username, password=self.password,172            tenant_name=self.tenant_name)173        mock_create_tenant.assert_called_with(174            name=self.tenant_name, description=self.tenant_description)175        mock_create_user.assert_called_with(name=self.username,176                                            password=self.password,177                                            tenantId="fake-id",178                                            email=self.email)179        mock_update_user_password.assert_called_with(180            fake_user['id'], password=self.password)181    @mock.patch('tempest.lib.services.identity.v2.'182                'users_client.UsersClient.update_user_password')183    @mock.patch('tempest.common.identity.get_user_by_username')184    @mock.patch('tempest.common.identity.get_tenant_by_name')185    @mock.patch('tempest.lib.services.identity.v2.'186                'tenants_client.TenantsClient.create_tenant')187    @mock.patch('tempest.lib.services.identity.v2.'188                'users_client.UsersClient.create_user')189    def test_create_user_with_tenant_exists_user_exists(190            self, mock_create_user, mock_create_tenant,191            mock_get_tenant_by_name,192            mock_get_user_by_username,193            mock_update_user_password):194        mock_get_tenant_by_name.return_value = {'id': "fake-id"}195        exc = exceptions.Conflict196        mock_create_tenant.side_effects = exc197        mock_create_user.side_effect = exc198        fake_user = {'id': "fake_user_id"}199        mock_get_user_by_username.return_value = fake_user200        tool.create_user_with_tenant(tenants_client=self.tenants_client,201                                     users_client=self.users_client,202                                     username=self.username,203                                     password=self.password,204                                     tenant_name=self.tenant_name)205        mock_create_tenant.assert_called_with(206            name=self.tenant_name, description=self.tenant_description)207        mock_create_user.assert_called_with(name=self.username,208                                            password=self.password,209                                            tenantId="fake-id",210                                            email=self.email)211        mock_update_user_password.assert_called_with(212            fake_user['id'], password=self.password)213class TestGiveRoleToUser(BaseConfigTempestTest):214    def setUp(self):215        super(TestGiveRoleToUser, self).setUp()216        self.conf = self._get_conf("v2.0", "v3")217        self.tenants_client = self._get_clients(self.conf).tenants218        self.users_client = self._get_clients(self.conf).users219        self.roles_client = self._get_clients(self.conf).roles220        self.username = "test_user"221        self.tenant_name = "project"222        self.role_name = "fake_role"223        self.users = {'users':224                      [{'name': "test_user",225                        'id': "fake_user_id"},226                       {'name': "test_user2",227                        'id': "fake_user_id2"}]}228        self.roles = {'roles':229                      [{'name': "fake_role",230                        'id': "fake_role_id"},231                       {'name': "fake_role2",232                        'id': "fake_role_id2"}]}233    @mock.patch('tempest.common.identity.get_tenant_by_name')234    @mock.patch('tempest.lib.services.identity.v2.'235                'users_client.UsersClient.list_users')236    @mock.patch('tempest.lib.services.identity.v2.'237                'users_client.UsersClient.create_user')238    @mock.patch('tempest.lib.services.identity.v2.'239                'roles_client.RolesClient.list_roles')240    @mock.patch('tempest.lib.services.identity.v2.''roles_client.'241                'RolesClient.create_user_role_on_project')242    def test_give_role_to_user(self,243                               mock_create_user_role_on_project,244                               mock_list_roles,245                               mock_create_user,246                               mock_list_users,247                               mock_get_tenant_by_name):248        mock_get_tenant_by_name.return_value = \249            {'id': "fake_tenant_id"}250        mock_list_users.return_value = self.users251        mock_list_roles.return_value = self.roles252        tool.give_role_to_user(253            tenants_client=self.tenants_client,254            roles_client=self.roles_client,255            users_client=self.users_client,256            username=self.username,257            tenant_name=self.tenant_name,258            role_name=self.role_name)259        mock_create_user_role_on_project.assert_called_with(260            "fake_tenant_id", "fake_user_id", "fake_role_id")261    @mock.patch('tempest.common.identity.get_tenant_by_name')262    @mock.patch('tempest.lib.services.identity.'263                'v2.users_client.UsersClient.list_users')264    @mock.patch('tempest.lib.services.identity.v2.'265                'users_client.UsersClient.create_user')266    @mock.patch('tempest.lib.services.identity.v2.'267                'roles_client.RolesClient.list_roles')268    @mock.patch('tempest.lib.services.identity.v2.'269                'roles_client.RolesClient.create_user_role_on_project')270    def test_give_role_to_user_role_not_found(271            self,272            mock_create_user_role_on_project,273            mock_list_roles,274            mock_create_user,275            mock_list_users,276            mock_get_tenant_by_name):277        role_name = "fake_role_that_does_not_exist"278        mock_get_tenant_by_name.return_value = \279            {'id': "fake_tenant_id"}280        mock_list_users.return_value = self.users281        mock_list_roles.return_value = self.roles282        exc = Exception283        self.assertRaises(exc,284                          tool.give_role_to_user,285                          tenants_client=self.tenants_client,286                          roles_client=self.roles_client,287                          users_client=self.users_client,288                          username=self.username,289                          tenant_name=self.tenant_name,290                          role_name=role_name)291    @mock.patch('tempest.common.identity.get_tenant_by_name')292    @mock.patch('tempest.lib.services.identity.v2.'293                'users_client.UsersClient.list_users')294    @mock.patch('tempest.lib.services.identity.v2.'295                'users_client.UsersClient.create_user')296    @mock.patch('tempest.lib.services.identity.v2.'297                'roles_client.RolesClient.list_roles')298    @mock.patch('tempest.lib.services.identity.v2.roles_client'299                '.RolesClient.create_user_role_on_project')300    def test_give_role_to_user_role_not_found_not_req(301            self,302            mock_create_user_role_on_project,303            mock_list_roles,304            mock_create_user,305            mock_list_users,306            mock_get_tenant_by_name):307        mock_get_tenant_by_name.return_value = \308            {'id': "fake_tenant_id"}309        mock_list_users.return_value = self.users310        mock_list_roles.return_value = self.roles311        tool.give_role_to_user(312            tenants_client=self.tenants_client,313            roles_client=self.roles_client,314            users_client=self.users_client,315            username=self.username,316            tenant_name=self.tenant_name,317            role_name=self.role_name,318            role_required=False)319    @mock.patch('tempest.common.identity.get_tenant_by_name')320    @mock.patch('tempest.lib.services.identity.v2.'321                'users_client.UsersClient.list_users')322    @mock.patch('tempest.lib.services.identity.v2.'323                'users_client.UsersClient.create_user')324    @mock.patch('tempest.lib.services.identity.v2.'325                'roles_client.RolesClient.list_roles')326    @mock.patch('tempest.lib.services.identity.v2.roles_client.'327                'RolesClient.create_user_role_on_project')328    def test_give_role_to_user_role_already_given(329            self,330            mock_create_user_role_on_project,331            mock_list_roles,332            mock_create_user,333            mock_list_users,334            mock_get_tenant_by_name):335        exc = exceptions.Conflict336        mock_create_user_role_on_project.side_effect = exc337        mock_get_tenant_by_name.return_value = {'id': "fake_tenant_id"}338        mock_list_users.return_value = self.users339        mock_list_roles.return_value = self.roles340        tool.give_role_to_user(341            tenants_client=self.tenants_client,342            roles_client=self.roles_client,343            users_client=self.users_client,344            username=self.username,345            tenant_name=self.tenant_name,...openstack_grizzly_cloud.py
Source:openstack_grizzly_cloud.py  
...35        return user[0] if len(user) == 1 else None36    def get_role_by_name(self, name):37        role = [r for r in self.keystone.roles.list() if r.name == name]38        return role[0] if len(role) == 1 else None39    def get_tenant_by_name(self, name):40        tenant = [t for t in self.keystone.tenants.list() if t.name == name]41        return tenant[0] if len(tenant) == 1 else None42    def initialize_cloud_user(self):43        creds = self.credentials44        defaults = self.clouddefaults45        password = self.newpass()46        creds['OS_USERNAME'] = self.username47        creds['OS_PASSWORD'] = password48        defaults['project'] = self.defaultproject49        # Create user or reset password (we cannot retrieve existing password)50        user = self.get_user_by_name(self.username)51        if user is None:52            user = self.keystone.users.create(self.username, password, self.email)53        else:54            self.keystone.users.update_password(user, password)55        # Create membership role for user in each tenant56        member_role = self.get_role_by_name('_member_')57        os_tenants = []58        for tname in self.projects:59            tenant = self.get_tenant_by_name(tname)60            if tenant is None:61                tenant = self.keystone.tenants.create(tname)62            user_roles = self.keystone.roles.roles_for_user(user, tenant)63            if not filter(lambda r: r.id == member_role.id, user_roles):64                self.keystone.roles.add_user_role(user, member_role, tenant)65            os_tenants.append(tname)66        creds['FG_OS_TENANTS'] = ','.join(os_tenants)...tenant.py
Source:tenant.py  
...9async def check_free_tenant_name_and_domain(10    name: Optional[str] = None, domain: Optional[str] = None11):12    if name:13        tenant_by_name = await get_tenant_by_name(name)14        if tenant_by_name:15            raise HTTPException(16                status_code=HTTP_422_UNPROCESSABLE_ENTITY,17                detail="A tenant with this name already exists",18            )19    if domain:20        tenant_by_domain = await get_tenant_by_domain(domain)21        if tenant_by_domain:22            raise HTTPException(23                status_code=HTTP_422_UNPROCESSABLE_ENTITY,24                detail="A tenant with this domain already exists",25            )26async def get_tenant(query: dict = None) -> Optional[TenantInDB]:27    return await get_document(Tenant, TenantInDB, query)28async def get_tenants(29    query: Optional[dict] = None,30    page: Optional[int] = 1,31    limit: int = 10,32    sort: str = None,33    fetch_references: bool = False,34) -> Tuple[List[TenantInDB], int, bool]:35    return await get_document_list(36        Tenant, TenantInDB, query, page, limit, sort, fetch_references37    )38async def get_tenant_by_name(name: str) -> Optional[TenantInDB]:39    return await get_document(Tenant, TenantInDB, query={"name": name})40async def get_tenant_by_id(obj_id: str) -> Optional[TenantInDB]:41    return await get_document(Tenant, TenantInDB, query={"id": ObjectId(obj_id)})42async def get_tenant_by_domain(domain: str) -> Optional[TenantInDB]:43    return await get_document(Tenant, TenantInDB, query={"domain": domain})44async def create_tenant(tenant: TenantBase) -> TenantInDB:45    tenant_by_domain = await get_tenant_by_domain(tenant.domain)46    if tenant_by_domain:47        return tenant_by_domain48    db_tenant = TenantInDB(**tenant.dict())49    document = Tenant(**db_tenant.dict())50    await document.commit()51    return TenantInDB(**document.dump())52async def update_tenant(name: str, tenant: TenantInUpdate) -> TenantInDB:53    db_tenant = await get_tenant_by_name(name)54    db_tenant = db_tenant.copy(update=tenant.dict(skip_defaults=True))55    document = await Tenant.find_one({"name": name})56    document.dict_update(**db_tenant.dict())57    await document.commit()...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!!
