Best Python code snippet using tempest_python
test_unified_limits.py
Source:test_unified_limits.py  
...50        except lib_exc.Forbidden:51            # If we fail to set limits, it means they are not52            # registered, and thus we will skip these tests once we53            # have our os_system_admin client and run54            # check_quotas_enabled().55            pass56    def setUp(self):57        super(ImageQuotaTest, self).setUp()58        self.created_images = []59    def create_image(self, data=None, **kwargs):60        """Wrapper that returns a test image."""61        if 'name' not in kwargs:62            name = data_utils.rand_name(self.__name__ + "-image")63            kwargs['name'] = name64        params = dict(kwargs)65        if data:66            # NOTE: On glance v1 API, the data should be passed on67            # a header. Then here handles the data separately.68            params['data'] = data69        image = self.image_client.create_image(**params)70        # Image objects returned by the v1 client have the image71        # data inside a dict that is keyed against 'image'.72        if 'image' in image:73            image = image['image']74        self.created_images.append(image['id'])75        self.addCleanup(76            self.image_client.wait_for_resource_deletion,77            image['id'])78        self.addCleanup(79            test_utils.call_and_ignore_notfound_exc,80            self.image_client.delete_image, image['id'])81        return image82    def check_quotas_enabled(self):83        # Check to see if we should even be running these tests. Use84        # the presence of a registered limit that we recognize as an85        # indication.  This will be set up by the operator (or86        # devstack) if glance is configured to use/honor the unified87        # limits. If one is set, they must all be set, because glance88        # has a single all-or-nothing flag for whether or not to use89        # keystone limits. If anything, checking only one helps to90        # assert the assumption that, if enabled, they must all be at91        # least registered for proper operation.92        registered_limits = self.os_system_admin.identity_limits_client.\93            get_registered_limits()['registered_limits']94        if 'image_count_total' not in [x['resource_name']95                                       for x in registered_limits]:96            raise self.skipException('Target system is not configured with '97                                     'glance unified limits')98    @classmethod99    def _create_limit(cls, name, value):100        return cls.os_system_admin.identity_limits_client.create_limit(101            CONF.identity.region, cls.glance_service_id,102            cls.image_client.tenant_id, name, value)['limits'][0]['id']103    def _update_limit(self, name, value):104        self.os_system_admin.identity_limits_client.update_limit(105            self.limit_ids[name], value)106    def _cleanup_images(self):107        while self.created_images:108            image_id = self.created_images.pop()109            try:110                self.image_client.delete_image(image_id)111            except lib_exc.NotFound:112                pass113    @decorators.idempotent_id('9b74fe24-183b-41e6-bf42-84c2958a7be8')114    @utils.services('image', 'identity')115    def test_image_count_quota(self):116        self.check_quotas_enabled()117        # Set a quota on the number of images for our tenant to one.118        self._update_limit('image_count_total', 1)119        # Create one image120        image = self.create_image(name='first',121                                  container_format='bare',122                                  disk_format='raw',123                                  visibility='private')124        # Second image would put us over quota, so expect failure.125        self.assertRaises(lib_exc.OverLimit,126                          self.create_image,127                          name='second',128                          container_format='bare',129                          disk_format='raw',130                          visibility='private')131        # Update our limit to two.132        self._update_limit('image_count_total', 2)133        # Now the same create should succeed.134        self.create_image(name='second',135                          container_format='bare',136                          disk_format='raw',137                          visibility='private')138        # Third image would put us over quota, so expect failure.139        self.assertRaises(lib_exc.OverLimit,140                          self.create_image,141                          name='third',142                          container_format='bare',143                          disk_format='raw',144                          visibility='private')145        # Delete the first image to put us under quota.146        self.image_client.delete_image(image['id'])147        # Now the same create should succeed.148        self.create_image(name='third',149                          container_format='bare',150                          disk_format='raw',151                          visibility='private')152        # Delete all the images we created before the next test runs,153        # so that it starts with full quota.154        self._cleanup_images()155    @decorators.idempotent_id('b103788b-5329-4aa9-8b0d-97f8733460db')156    @utils.services('image', 'identity')157    def test_image_count_uploading_quota(self):158        if not CONF.image_feature_enabled.import_image:159            skip_msg = (160                "%s skipped as image import is not available" % __name__)161            raise self.skipException(skip_msg)162        self.check_quotas_enabled()163        # Set a quota on the number of images we can have in uploading state.164        self._update_limit('image_stage_total', 10)165        self._update_limit('image_size_total', 10)166        self._update_limit('image_count_total', 10)167        self._update_limit('image_count_uploading', 1)168        file_content = data_utils.random_bytes(1 * units.Mi)169        # Create and stage an image170        image1 = self.create_image(name='first',171                                   container_format='bare',172                                   disk_format='raw',173                                   visibility='private')174        self.image_client.stage_image_file(image1['id'],175                                           io.BytesIO(file_content))176        # Check that we can not stage another177        image2 = self.create_image(name='second',178                                   container_format='bare',179                                   disk_format='raw',180                                   visibility='private')181        self.assertRaises(lib_exc.OverLimit,182                          self.image_client.stage_image_file,183                          image2['id'], io.BytesIO(file_content))184        # ... nor upload directly185        image3 = self.create_image(name='third',186                                   container_format='bare',187                                   disk_format='raw',188                                   visibility='private')189        self.assertRaises(lib_exc.OverLimit,190                          self.image_client.store_image_file,191                          image3['id'],192                          io.BytesIO(file_content))193        # Update our quota to make room194        self._update_limit('image_count_uploading', 2)195        # Now our upload should work196        self.image_client.store_image_file(image3['id'],197                                           io.BytesIO(file_content))198        # ...and because that is no longer in uploading state, we should be199        # able to stage our second image from above.200        self.image_client.stage_image_file(image2['id'],201                                           io.BytesIO(file_content))202        # Finish our import of image2203        self.image_client.image_import(image2['id'], method='glance-direct')204        waiters.wait_for_image_imported_to_stores(self.image_client,205                                                  image2['id'])206        # Set our quota back to one207        self._update_limit('image_count_uploading', 1)208        # Since image1 is still staged, we should not be able to upload209        # an image.210        image4 = self.create_image(name='fourth',211                                   container_format='bare',212                                   disk_format='raw',213                                   visibility='private')214        self.assertRaises(lib_exc.OverLimit,215                          self.image_client.store_image_file,216                          image4['id'],217                          io.BytesIO(file_content))218        # Finish our import of image1 to make space in our uploading quota.219        self.image_client.image_import(image1['id'], method='glance-direct')220        waiters.wait_for_image_imported_to_stores(self.image_client,221                                                  image1['id'])222        # Make sure that freed up the one upload quota to complete our upload223        self.image_client.store_image_file(image4['id'],224                                           io.BytesIO(file_content))225        # Delete all the images we created before the next test runs,226        # so that it starts with full quota.227        self._cleanup_images()228    @decorators.idempotent_id('05e8d064-c39a-4801-8c6a-465df375ec5b')229    @utils.services('image', 'identity')230    def test_image_size_quota(self):231        self.check_quotas_enabled()232        # Set a quota on the image size for our tenant to 1MiB, and allow ten233        # images.234        self._update_limit('image_size_total', 1)235        self._update_limit('image_count_total', 10)236        self._update_limit('image_count_uploading', 10)237        file_content = data_utils.random_bytes(1 * units.Mi)238        # Create and upload a 1MiB image.239        image1 = self.create_image(name='first',240                                   container_format='bare',241                                   disk_format='raw',242                                   visibility='private')243        self.image_client.store_image_file(image1['id'],244                                           io.BytesIO(file_content))245        # Create and upload a second 1MiB image. This succeeds, but246        # after completion, we are over quota. Despite us being at247        # quota above, the initial quota check for the second248        # operation has no idea what the image size will be, and thus249        # uses delta=0. This will succeed because we're not250        # technically over-quota and have not asked for any more (this251        # is oslo.limit behavior). After the second operation,252        # however, we will be over-quota regardless of the delta and253        # subsequent attempts will fail. Because glance goes not254        # require an image size to be declared before upload, this is255        # really the best it can do without an API change.256        image2 = self.create_image(name='second',257                                   container_format='bare',258                                   disk_format='raw',259                                   visibility='private')260        self.image_client.store_image_file(image2['id'],261                                           io.BytesIO(file_content))262        # Create and attempt to upload a third 1MiB image. This should fail to263        # upload (but not create) because we are over quota.264        image3 = self.create_image(name='third',265                                   container_format='bare',266                                   disk_format='raw',267                                   visibility='private')268        self.assertRaises(lib_exc.OverLimit,269                          self.image_client.store_image_file,270                          image3['id'], io.BytesIO(file_content))271        # Increase our size quota to 2MiB.272        self._update_limit('image_size_total', 2)273        # Now the upload of the already-created image is allowed, but274        # after completion, we are over quota again.275        self.image_client.store_image_file(image3['id'],276                                           io.BytesIO(file_content))277        # Create and attempt to upload a fourth 1MiB image. This should278        # fail to upload (but not create) because we are over quota.279        image4 = self.create_image(name='fourth',280                                   container_format='bare',281                                   disk_format='raw',282                                   visibility='private')283        self.assertRaises(lib_exc.OverLimit,284                          self.image_client.store_image_file,285                          image4['id'], io.BytesIO(file_content))286        # Delete our first image to make space in our existing 2MiB quota.287        self.image_client.delete_image(image1['id'])288        # Now the upload of the already-created image is allowed.289        self.image_client.store_image_file(image4['id'],290                                           io.BytesIO(file_content))291        # Delete all the images we created before the next test runs,292        # so that it starts with full quota.293        self._cleanup_images()294    @decorators.idempotent_id('fc76b8d9-aae5-46fb-9285-099e37f311f7')295    @utils.services('image', 'identity')296    def test_image_stage_quota(self):297        if not CONF.image_feature_enabled.import_image:298            skip_msg = (299                "%s skipped as image import is not available" % __name__)300            raise self.skipException(skip_msg)301        self.check_quotas_enabled()302        # Create a staging quota of 1MiB, allow 10MiB of active303        # images, and a total of ten images.304        self._update_limit('image_stage_total', 1)305        self._update_limit('image_size_total', 10)306        self._update_limit('image_count_total', 10)307        self._update_limit('image_count_uploading', 10)308        file_content = data_utils.random_bytes(1 * units.Mi)309        # Create and stage a 1MiB image.310        image1 = self.create_image(name='first',311                                   container_format='bare',312                                   disk_format='raw',313                                   visibility='private')314        self.image_client.stage_image_file(image1['id'],315                                           io.BytesIO(file_content))...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!!
