Best Python code snippet using localstack_python
test_s3_lifecycle.py
Source:test_s3_lifecycle.py
...41 }42 client.put_bucket_lifecycle_configuration(43 Bucket="bucket", LifecycleConfiguration=lfc44 )45 result = client.get_bucket_lifecycle_configuration(Bucket="bucket")46 assert len(result["Rules"]) == 147 assert result["Rules"][0]["Filter"]["Prefix"] == ""48 assert not result["Rules"][0]["Filter"].get("And")49 assert not result["Rules"][0]["Filter"].get("Tag")50 with assert_raises(KeyError):51 assert result["Rules"][0]["Prefix"]52 # Without any prefixes and an empty filter (this is by default a prefix for the whole bucket):53 lfc = {54 "Rules": [55 {56 "Expiration": {"Days": 7},57 "ID": "wholebucket",58 "Filter": {},59 "Status": "Enabled",60 }61 ]62 }63 client.put_bucket_lifecycle_configuration(64 Bucket="bucket", LifecycleConfiguration=lfc65 )66 result = client.get_bucket_lifecycle_configuration(Bucket="bucket")67 assert len(result["Rules"]) == 168 with assert_raises(KeyError):69 assert result["Rules"][0]["Prefix"]70 # If we remove the filter -- and don't specify a Prefix, then this is bad:71 lfc["Rules"][0].pop("Filter")72 with assert_raises(ClientError) as err:73 client.put_bucket_lifecycle_configuration(74 Bucket="bucket", LifecycleConfiguration=lfc75 )76 assert err.exception.response["Error"]["Code"] == "MalformedXML"77 # With a tag:78 lfc["Rules"][0]["Filter"] = {"Tag": {"Key": "mytag", "Value": "mytagvalue"}}79 client.put_bucket_lifecycle_configuration(80 Bucket="bucket", LifecycleConfiguration=lfc81 )82 result = client.get_bucket_lifecycle_configuration(Bucket="bucket")83 assert len(result["Rules"]) == 184 with assert_raises(KeyError):85 assert result["Rules"][0]["Filter"]["Prefix"]86 assert not result["Rules"][0]["Filter"].get("And")87 assert result["Rules"][0]["Filter"]["Tag"]["Key"] == "mytag"88 assert result["Rules"][0]["Filter"]["Tag"]["Value"] == "mytagvalue"89 with assert_raises(KeyError):90 assert result["Rules"][0]["Prefix"]91 # With And (single tag):92 lfc["Rules"][0]["Filter"] = {93 "And": {94 "Prefix": "some/prefix",95 "Tags": [{"Key": "mytag", "Value": "mytagvalue"}],96 }97 }98 client.put_bucket_lifecycle_configuration(99 Bucket="bucket", LifecycleConfiguration=lfc100 )101 result = client.get_bucket_lifecycle_configuration(Bucket="bucket")102 assert len(result["Rules"]) == 1103 assert not result["Rules"][0]["Filter"].get("Prefix")104 assert result["Rules"][0]["Filter"]["And"]["Prefix"] == "some/prefix"105 assert len(result["Rules"][0]["Filter"]["And"]["Tags"]) == 1106 assert result["Rules"][0]["Filter"]["And"]["Tags"][0]["Key"] == "mytag"107 assert result["Rules"][0]["Filter"]["And"]["Tags"][0]["Value"] == "mytagvalue"108 with assert_raises(KeyError):109 assert result["Rules"][0]["Prefix"]110 # With multiple And tags:111 lfc["Rules"][0]["Filter"]["And"] = {112 "Prefix": "some/prefix",113 "Tags": [114 {"Key": "mytag", "Value": "mytagvalue"},115 {"Key": "mytag2", "Value": "mytagvalue2"},116 ],117 }118 client.put_bucket_lifecycle_configuration(119 Bucket="bucket", LifecycleConfiguration=lfc120 )121 result = client.get_bucket_lifecycle_configuration(Bucket="bucket")122 assert len(result["Rules"]) == 1123 assert not result["Rules"][0]["Filter"].get("Prefix")124 assert result["Rules"][0]["Filter"]["And"]["Prefix"] == "some/prefix"125 assert len(result["Rules"][0]["Filter"]["And"]["Tags"]) == 2126 assert result["Rules"][0]["Filter"]["And"]["Tags"][0]["Key"] == "mytag"127 assert result["Rules"][0]["Filter"]["And"]["Tags"][0]["Value"] == "mytagvalue"128 assert result["Rules"][0]["Filter"]["And"]["Tags"][1]["Key"] == "mytag2"129 assert result["Rules"][0]["Filter"]["And"]["Tags"][1]["Value"] == "mytagvalue2"130 with assert_raises(KeyError):131 assert result["Rules"][0]["Prefix"]132 # And filter without Prefix but multiple Tags:133 lfc["Rules"][0]["Filter"]["And"] = {134 "Tags": [135 {"Key": "mytag", "Value": "mytagvalue"},136 {"Key": "mytag2", "Value": "mytagvalue2"},137 ]138 }139 client.put_bucket_lifecycle_configuration(140 Bucket="bucket", LifecycleConfiguration=lfc141 )142 result = client.get_bucket_lifecycle_configuration(Bucket="bucket")143 assert len(result["Rules"]) == 1144 with assert_raises(KeyError):145 assert result["Rules"][0]["Filter"]["And"]["Prefix"]146 assert len(result["Rules"][0]["Filter"]["And"]["Tags"]) == 2147 assert result["Rules"][0]["Filter"]["And"]["Tags"][0]["Key"] == "mytag"148 assert result["Rules"][0]["Filter"]["And"]["Tags"][0]["Value"] == "mytagvalue"149 assert result["Rules"][0]["Filter"]["And"]["Tags"][1]["Key"] == "mytag2"150 assert result["Rules"][0]["Filter"]["And"]["Tags"][1]["Value"] == "mytagvalue2"151 with assert_raises(KeyError):152 assert result["Rules"][0]["Prefix"]153 # Can't have both filter and prefix:154 lfc["Rules"][0]["Prefix"] = ""155 with assert_raises(ClientError) as err:156 client.put_bucket_lifecycle_configuration(157 Bucket="bucket", LifecycleConfiguration=lfc158 )159 assert err.exception.response["Error"]["Code"] == "MalformedXML"160 lfc["Rules"][0]["Prefix"] = "some/path"161 with assert_raises(ClientError) as err:162 client.put_bucket_lifecycle_configuration(163 Bucket="bucket", LifecycleConfiguration=lfc164 )165 assert err.exception.response["Error"]["Code"] == "MalformedXML"166 # No filters -- just a prefix:167 del lfc["Rules"][0]["Filter"]168 client.put_bucket_lifecycle_configuration(169 Bucket="bucket", LifecycleConfiguration=lfc170 )171 result = client.get_bucket_lifecycle_configuration(Bucket="bucket")172 assert not result["Rules"][0].get("Filter")173 assert result["Rules"][0]["Prefix"] == "some/path"174 # Can't have Tag, Prefix, and And in a filter:175 del lfc["Rules"][0]["Prefix"]176 lfc["Rules"][0]["Filter"] = {177 "Prefix": "some/prefix",178 "Tag": {"Key": "mytag", "Value": "mytagvalue"},179 }180 with assert_raises(ClientError) as err:181 client.put_bucket_lifecycle_configuration(182 Bucket="bucket", LifecycleConfiguration=lfc183 )184 assert err.exception.response["Error"]["Code"] == "MalformedXML"185 lfc["Rules"][0]["Filter"] = {186 "Tag": {"Key": "mytag", "Value": "mytagvalue"},187 "And": {188 "Prefix": "some/prefix",189 "Tags": [190 {"Key": "mytag", "Value": "mytagvalue"},191 {"Key": "mytag2", "Value": "mytagvalue2"},192 ],193 },194 }195 with assert_raises(ClientError) as err:196 client.put_bucket_lifecycle_configuration(197 Bucket="bucket", LifecycleConfiguration=lfc198 )199 assert err.exception.response["Error"]["Code"] == "MalformedXML"200 # Make sure multiple rules work:201 lfc = {202 "Rules": [203 {204 "Expiration": {"Days": 7},205 "ID": "wholebucket",206 "Filter": {"Prefix": ""},207 "Status": "Enabled",208 },209 {210 "Expiration": {"Days": 10},211 "ID": "Tags",212 "Filter": {"Tag": {"Key": "somekey", "Value": "somevalue"}},213 "Status": "Enabled",214 },215 ]216 }217 client.put_bucket_lifecycle_configuration(218 Bucket="bucket", LifecycleConfiguration=lfc219 )220 result = client.get_bucket_lifecycle_configuration(Bucket="bucket")["Rules"]221 assert len(result) == 2222 assert result[0]["ID"] == "wholebucket"223 assert result[1]["ID"] == "Tags"224@mock_s3225def test_lifecycle_with_eodm():226 client = boto3.client("s3")227 client.create_bucket(228 Bucket="bucket", CreateBucketConfiguration={"LocationConstraint": "us-west-1"}229 )230 lfc = {231 "Rules": [232 {233 "Expiration": {"ExpiredObjectDeleteMarker": True},234 "ID": "wholebucket",235 "Filter": {"Prefix": ""},236 "Status": "Enabled",237 }238 ]239 }240 client.put_bucket_lifecycle_configuration(241 Bucket="bucket", LifecycleConfiguration=lfc242 )243 result = client.get_bucket_lifecycle_configuration(Bucket="bucket")244 assert len(result["Rules"]) == 1245 assert result["Rules"][0]["Expiration"]["ExpiredObjectDeleteMarker"]246 # Set to False:247 lfc["Rules"][0]["Expiration"]["ExpiredObjectDeleteMarker"] = False248 client.put_bucket_lifecycle_configuration(249 Bucket="bucket", LifecycleConfiguration=lfc250 )251 result = client.get_bucket_lifecycle_configuration(Bucket="bucket")252 assert len(result["Rules"]) == 1253 assert not result["Rules"][0]["Expiration"]["ExpiredObjectDeleteMarker"]254 # With failure:255 lfc["Rules"][0]["Expiration"]["Days"] = 7256 with assert_raises(ClientError) as err:257 client.put_bucket_lifecycle_configuration(258 Bucket="bucket", LifecycleConfiguration=lfc259 )260 assert err.exception.response["Error"]["Code"] == "MalformedXML"261 del lfc["Rules"][0]["Expiration"]["Days"]262 lfc["Rules"][0]["Expiration"]["Date"] = datetime(2015, 1, 1)263 with assert_raises(ClientError) as err:264 client.put_bucket_lifecycle_configuration(265 Bucket="bucket", LifecycleConfiguration=lfc266 )267 assert err.exception.response["Error"]["Code"] == "MalformedXML"268@mock_s3269def test_lifecycle_with_nve():270 client = boto3.client("s3")271 client.create_bucket(272 Bucket="bucket", CreateBucketConfiguration={"LocationConstraint": "us-west-1"}273 )274 lfc = {275 "Rules": [276 {277 "NoncurrentVersionExpiration": {"NoncurrentDays": 30},278 "ID": "wholebucket",279 "Filter": {"Prefix": ""},280 "Status": "Enabled",281 }282 ]283 }284 client.put_bucket_lifecycle_configuration(285 Bucket="bucket", LifecycleConfiguration=lfc286 )287 result = client.get_bucket_lifecycle_configuration(Bucket="bucket")288 assert len(result["Rules"]) == 1289 assert result["Rules"][0]["NoncurrentVersionExpiration"]["NoncurrentDays"] == 30290 # Change NoncurrentDays:291 lfc["Rules"][0]["NoncurrentVersionExpiration"]["NoncurrentDays"] = 10292 client.put_bucket_lifecycle_configuration(293 Bucket="bucket", LifecycleConfiguration=lfc294 )295 result = client.get_bucket_lifecycle_configuration(Bucket="bucket")296 assert len(result["Rules"]) == 1297 assert result["Rules"][0]["NoncurrentVersionExpiration"]["NoncurrentDays"] == 10298 # TODO: Add test for failures due to missing children299@mock_s3300def test_lifecycle_with_nvt():301 client = boto3.client("s3")302 client.create_bucket(303 Bucket="bucket", CreateBucketConfiguration={"LocationConstraint": "us-west-1"}304 )305 lfc = {306 "Rules": [307 {308 "NoncurrentVersionTransitions": [309 {"NoncurrentDays": 30, "StorageClass": "ONEZONE_IA"}310 ],311 "ID": "wholebucket",312 "Filter": {"Prefix": ""},313 "Status": "Enabled",314 }315 ]316 }317 client.put_bucket_lifecycle_configuration(318 Bucket="bucket", LifecycleConfiguration=lfc319 )320 result = client.get_bucket_lifecycle_configuration(Bucket="bucket")321 assert len(result["Rules"]) == 1322 assert result["Rules"][0]["NoncurrentVersionTransitions"][0]["NoncurrentDays"] == 30323 assert (324 result["Rules"][0]["NoncurrentVersionTransitions"][0]["StorageClass"]325 == "ONEZONE_IA"326 )327 # Change NoncurrentDays:328 lfc["Rules"][0]["NoncurrentVersionTransitions"][0]["NoncurrentDays"] = 10329 client.put_bucket_lifecycle_configuration(330 Bucket="bucket", LifecycleConfiguration=lfc331 )332 result = client.get_bucket_lifecycle_configuration(Bucket="bucket")333 assert len(result["Rules"]) == 1334 assert result["Rules"][0]["NoncurrentVersionTransitions"][0]["NoncurrentDays"] == 10335 # Change StorageClass:336 lfc["Rules"][0]["NoncurrentVersionTransitions"][0]["StorageClass"] = "GLACIER"337 client.put_bucket_lifecycle_configuration(338 Bucket="bucket", LifecycleConfiguration=lfc339 )340 result = client.get_bucket_lifecycle_configuration(Bucket="bucket")341 assert len(result["Rules"]) == 1342 assert (343 result["Rules"][0]["NoncurrentVersionTransitions"][0]["StorageClass"]344 == "GLACIER"345 )346 # With failures for missing children:347 del lfc["Rules"][0]["NoncurrentVersionTransitions"][0]["NoncurrentDays"]348 with assert_raises(ClientError) as err:349 client.put_bucket_lifecycle_configuration(350 Bucket="bucket", LifecycleConfiguration=lfc351 )352 assert err.exception.response["Error"]["Code"] == "MalformedXML"353 lfc["Rules"][0]["NoncurrentVersionTransitions"][0]["NoncurrentDays"] = 30354 del lfc["Rules"][0]["NoncurrentVersionTransitions"][0]["StorageClass"]355 with assert_raises(ClientError) as err:356 client.put_bucket_lifecycle_configuration(357 Bucket="bucket", LifecycleConfiguration=lfc358 )359 assert err.exception.response["Error"]["Code"] == "MalformedXML"360@mock_s3361def test_lifecycle_with_aimu():362 client = boto3.client("s3")363 client.create_bucket(364 Bucket="bucket", CreateBucketConfiguration={"LocationConstraint": "us-west-1"}365 )366 lfc = {367 "Rules": [368 {369 "AbortIncompleteMultipartUpload": {"DaysAfterInitiation": 7},370 "ID": "wholebucket",371 "Filter": {"Prefix": ""},372 "Status": "Enabled",373 }374 ]375 }376 client.put_bucket_lifecycle_configuration(377 Bucket="bucket", LifecycleConfiguration=lfc378 )379 result = client.get_bucket_lifecycle_configuration(Bucket="bucket")380 assert len(result["Rules"]) == 1381 assert (382 result["Rules"][0]["AbortIncompleteMultipartUpload"]["DaysAfterInitiation"] == 7383 )384 # Change DaysAfterInitiation:385 lfc["Rules"][0]["AbortIncompleteMultipartUpload"]["DaysAfterInitiation"] = 30386 client.put_bucket_lifecycle_configuration(387 Bucket="bucket", LifecycleConfiguration=lfc388 )389 result = client.get_bucket_lifecycle_configuration(Bucket="bucket")390 assert len(result["Rules"]) == 1391 assert (392 result["Rules"][0]["AbortIncompleteMultipartUpload"]["DaysAfterInitiation"]393 == 30394 )395 # TODO: Add test for failures due to missing children396@mock_s3_deprecated397def test_lifecycle_with_glacier_transition():398 conn = boto.s3.connect_to_region("us-west-1")399 bucket = conn.create_bucket("foobar", location="us-west-1")400 lifecycle = Lifecycle()401 transition = Transition(days=30, storage_class="GLACIER")402 rule = Rule(403 "myid", prefix="", status="Enabled", expiration=None, transition=transition...
get_bucket_lifecycle_configuration.py
Source:get_bucket_lifecycle_configuration.py
...20# language governing permissions and limitations under the License.21import logging22import boto323from botocore.exceptions import ClientError24def get_bucket_lifecycle_configuration(bucket_name):25 """Retrieve the lifecycle configuration of an Amazon S3 bucket26 :param bucket_name: string27 :return: List of lifecycle configuration rules. If no configuration is28 defined, the list is empty. If error, returns None.29 """30 # Retrieve the configuration31 s3 = boto3.client('s3')32 try:33 response = s3.get_bucket_lifecycle_configuration(Bucket=bucket_name)34 except ClientError as e:35 if e.response['Error']['Code'] == 'NoSuchLifecycleConfiguration':36 return []37 else:38 # e.response['Error']['Code'] == 'NoSuchBucket', etc.39 logging.error(e)40 return None41 return response['Rules']42def main():43 """Exercise get_bucket_lifecycle_configuration()"""44 # Assign this value before running the program45 test_bucket_name = 'BUCKET_NAME'46 # Set up logging47 logging.basicConfig(level=logging.DEBUG,48 format='%(levelname)s: %(asctime)s: %(message)s')49 # Retrieve the lifecycle configuration50 lifecycle_config = get_bucket_lifecycle_configuration(test_bucket_name)51 if lifecycle_config is not None:52 if not lifecycle_config:53 logging.info(f'{test_bucket_name} does not have a lifecycle configuration.')54 else:55 for rule in lifecycle_config:56 logging.info(f'Rule: {rule["ID"]}, Status: {rule["Status"]}')57 for transition in rule['Transitions']:58 logging.info(f'--After {transition["Days"]:3d} days, '59 f'transition to storage class '60 f'{transition["StorageClass"]}')61if __name__ == '__main__':...
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!!