Best Python code snippet using tempest_python
test_unified_limits.py
Source:test_unified_limits.py  
...99    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))316        # Create and stage a second 1MiB image. This succeeds, but317        # after completion, we are over quota.318        image2 = self.create_image(name='second',319                                   container_format='bare',320                                   disk_format='raw',321                                   visibility='private')322        self.image_client.stage_image_file(image2['id'],323                                           io.BytesIO(file_content))324        # Create and attempt to stage a third 1MiB image. This should fail to325        # stage (but not create) because we are over quota.326        image3 = self.create_image(name='third',327                                   container_format='bare',328                                   disk_format='raw',329                                   visibility='private')330        self.assertRaises(lib_exc.OverLimit,331                          self.image_client.stage_image_file,332                          image3['id'], io.BytesIO(file_content))333        # Make sure that even though we are over our stage quota, we334        # can still create and upload an image the regular way.335        image_upload = self.create_image(name='uploaded',336                                         container_format='bare',337                                         disk_format='raw',338                                         visibility='private')339        self.image_client.store_image_file(image_upload['id'],340                                           io.BytesIO(file_content))341        # Increase our stage quota to two MiB.342        self._update_limit('image_stage_total', 2)343        # Now the upload of the already-created image is allowed, but344        # after completion, we are over quota again.345        self.image_client.stage_image_file(image3['id'],346                                           io.BytesIO(file_content))347        # Create and attempt to stage a fourth 1MiB image. This should348        # fail to stage (but not create) because we are over quota.349        image4 = self.create_image(name='fourth',350                                   container_format='bare',351                                   disk_format='raw',352                                   visibility='private')353        self.assertRaises(lib_exc.OverLimit,354                          self.image_client.stage_image_file,355                          image4['id'], io.BytesIO(file_content))356        # Finish our import of image1 to make space in our stage quota....coin_market.py
Source:coin_market.py  
...135                self.url = self.reset_url = self.reset_url + self.convert136                break137        # create '(?|&)limit'138        if self.limit:139            self._update_limit(None)140        # thresholds141        percents = {x: "percent_change_" + x for x in ["1h", "24h", "7d"]}142        self.thresholds_init = {143            "percents": percents,144            "format_coin": self.py3.get_color_names_list(self.format_coin),145            "plus": [x for x in placeholders if x in percents.values()],146        }147    def _get_coin_data(self, reset=False):148        if reset:149            self.url = self.reset_url150        try:151            data = self.py3.request(self.url).json()152        except self.py3.RequestException:153            data = {}154        return data155    def _update_limit(self, data):156        # we use limit if it exists. otherwise, we stretch the limit157        # large enough to obtain (all) self.markets + some padding158        self.url = self.url + ("&" if self.convert else "?")159        if self.limit:160            limit = self.limit161        else:162            limit = 0163            for market_id in self.markets:164                index = next(165                    (i for (i, d) in enumerate(data) if d["symbol"] == market_id), -1166                )167                if index >= limit:168                    limit = index169                    limit += 5  # padding170        self.url += "limit=%s" % limit171    def _strip_data(self, data):172        # if self.limit, we don't strip. otherwise, we strip 1000+ coins173        # down to %s coins by removing everything not in self.markets.174        new_data = []175        if self.limit:176            new_data = data177        else:178            for symbol in self.markets:179                for market in data:180                    if symbol == market["symbol"]:181                        new_data.append(market)182                        break183        return new_data184    def _organize_data(self, data):185        # compare len(stripped(1000+ coins) with len(self.markets)186        new_data = self._strip_data(data)187        is_equal = len(new_data) == len(self.markets)188        # first_use bad? the user entered bad markets. stop here (error).189        # otherwise, make a limit for first time on 1000+ coins.190        if self.first_use:191            self.first_use = False192            if not is_equal:193                self.py3.error("bad markets")194            else:195                self._update_limit(data)196        elif not is_equal:197            # post first_use bad? the markets fell out of the limit + padding.198            # reset the url to get 1000+ coins again to strip, compare, make199            # new limit and padding for the next one, but we'll use this one.200            # otherwise, we would have kept going with the first one.201            new_data = self._get_coin_data(reset=True)202            new_data = self._strip_data(new_data)203            self._update_limit(new_data)204        return new_data205    def _manipulate_data(self, data):206        new_data = []207        for market in data:208            # datetimes209            for k in self.init_datetimes:210                if k in market:211                    market[k] = self.py3.safe_format(212                        datetime.strftime(213                            datetime.fromtimestamp(float(market[k])),214                            self.format_datetime[k],215                        )216                    )217            # thresholds...test_compute_unified_limits.py
Source:test_compute_unified_limits.py  
...51    def _create_limit(cls, name, value):52        return cls.os_system_admin.identity_limits_client.create_limit(53            CONF.identity.region, cls.nova_service_id,54            cls.servers_client.tenant_id, name, value)['limits'][0]['id']55    def _update_limit(self, name, value):56        self.os_system_admin.identity_limits_client.update_limit(57            self.limit_ids[name], value)58class ServersQuotaTest(ComputeProjectQuotaTest):59    @classmethod60    def resource_setup(cls):61        super(ServersQuotaTest, cls).resource_setup()62        try:63            cls.limit_ids['servers'] = cls._create_limit(64                'servers', 5)65            cls.limit_ids['class:VCPU'] = cls._create_limit(66                'class:VCPU', 10)67            cls.limit_ids['class:MEMORY_MB'] = cls._create_limit(68                'class:MEMORY_MB', 25 * 1024)69            cls.limit_ids['class:DISK_GB'] = cls._create_limit(70                'class:DISK_GB', 10)71        except lib_exc.Forbidden:72            raise cls.skipException('Target system is not configured with '73                                    'compute unified limits')74    @decorators.idempotent_id('555d8bbf-d2ed-4e39-858c-4235899402d9')75    @utils.services('compute')76    def test_server_count_vcpu_memory_disk_quota(self):77        # Set a quota on the number of servers for our tenant to one.78        self._update_limit('servers', 1)79        # Create one server.80        first = self.create_server(name='first')81        # Second server would put us over quota, so expect failure.82        # NOTE: In nova, quota exceeded raises 403 Forbidden.83        self.assertRaises(lib_exc.Forbidden,84                          self.create_server,85                          name='second')86        # Update our limit to two.87        self._update_limit('servers', 2)88        # Now the same create should succeed.89        second = self.create_server(name='second')90        # Third server would put us over quota, so expect failure.91        self.assertRaises(lib_exc.Forbidden,92                          self.create_server,93                          name='third')94        # Delete the first server to put us under quota.95        self.servers_client.delete_server(first['id'])96        waiters.wait_for_server_termination(self.servers_client, first['id'])97        # Now the same create should succeed.98        third = self.create_server(name='third')99        # Set the servers limit back to 10 to test other resources.100        self._update_limit('servers', 10)101        # Default flavor has: VCPU=1, MEMORY_MB=512, DISK_GB=1102        # We are currently using 2 VCPU, set the limit to 2.103        self._update_limit('class:VCPU', 2)104        # Server create should fail as it would go over quota.105        self.assertRaises(lib_exc.Forbidden,106                          self.create_server,107                          name='fourth')108        # Delete the second server to put us under quota.109        self.servers_client.delete_server(second['id'])110        waiters.wait_for_server_termination(self.servers_client, second['id'])111        # Same create should now succeed.112        fourth = self.create_server(name='fourth')113        # We are currently using 2 DISK_GB. Set limit to 1.114        self._update_limit('class:DISK_GB', 1)115        # Server create should fail because we're already over (new) quota.116        self.assertRaises(lib_exc.Forbidden,117                          self.create_server,118                          name='fifth')119        # Delete the third server.120        self.servers_client.delete_server(third['id'])121        waiters.wait_for_server_termination(self.servers_client, third['id'])122        # Server create should fail again because it would still put us over123        # quota.124        self.assertRaises(lib_exc.Forbidden,125                          self.create_server,126                          name='fifth')127        # Delete the fourth server.128        self.servers_client.delete_server(fourth['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!!
