Best Python code snippet using localstack_python
test_amis.py
Source:test_amis.py
...315 "groups": "all",316 }317 # Add 'all' group and confirm318 with pytest.raises(EC2ResponseError) as ex:319 conn.modify_image_attribute(**dict(ADD_GROUP_ARGS, **{"dry_run": True}))320 ex.value.error_code.should.equal("DryRunOperation")321 ex.value.status.should.equal(400)322 ex.value.message.should.equal(323 "An error occurred (DryRunOperation) when calling the ModifyImageAttribute operation: Request would have succeeded, but DryRun flag is set"324 )325 conn.modify_image_attribute(**ADD_GROUP_ARGS)326 attributes = conn.get_image_attribute(image.id, attribute="launchPermission")327 attributes.attrs["groups"].should.have.length_of(1)328 attributes.attrs["groups"].should.equal(["all"])329 image = conn.get_image(image_id)330 image.is_public.should.equal(True)331 # Add is idempotent332 conn.modify_image_attribute.when.called_with(**ADD_GROUP_ARGS).should_not.throw(333 EC2ResponseError334 )335 # Remove 'all' group and confirm336 conn.modify_image_attribute(**REMOVE_GROUP_ARGS)337 attributes = conn.get_image_attribute(image.id, attribute="launchPermission")338 attributes.attrs.should.have.length_of(0)339 image = conn.get_image(image_id)340 image.is_public.should.equal(False)341 # Remove is idempotent342 conn.modify_image_attribute.when.called_with(**REMOVE_GROUP_ARGS).should_not.throw(343 EC2ResponseError344 )345@mock_ec2_deprecated346def test_ami_attribute_user_permissions():347 conn = boto.connect_ec2("the_key", "the_secret")348 reservation = conn.run_instances(EXAMPLE_AMI_ID)349 instance = reservation.instances[0]350 image_id = conn.create_image(instance.id, "test-ami", "this is a test ami")351 image = conn.get_image(image_id)352 # Baseline353 attributes = conn.get_image_attribute(image.id, attribute="launchPermission")354 attributes.name.should.equal("launch_permission")355 attributes.attrs.should.have.length_of(0)356 # Both str and int values should work.357 USER1 = "123456789011"358 USER2 = 123456789022359 ADD_USERS_ARGS = {360 "image_id": image.id,361 "attribute": "launchPermission",362 "operation": "add",363 "user_ids": [USER1, USER2],364 }365 REMOVE_USERS_ARGS = {366 "image_id": image.id,367 "attribute": "launchPermission",368 "operation": "remove",369 "user_ids": [USER1, USER2],370 }371 REMOVE_SINGLE_USER_ARGS = {372 "image_id": image.id,373 "attribute": "launchPermission",374 "operation": "remove",375 "user_ids": [USER1],376 }377 # Add multiple users and confirm378 conn.modify_image_attribute(**ADD_USERS_ARGS)379 attributes = conn.get_image_attribute(image.id, attribute="launchPermission")380 attributes.attrs["user_ids"].should.have.length_of(2)381 set(attributes.attrs["user_ids"]).should.equal(set([str(USER1), str(USER2)]))382 image = conn.get_image(image_id)383 image.is_public.should.equal(False)384 # Add is idempotent385 conn.modify_image_attribute.when.called_with(**ADD_USERS_ARGS).should_not.throw(386 EC2ResponseError387 )388 # Remove single user and confirm389 conn.modify_image_attribute(**REMOVE_SINGLE_USER_ARGS)390 attributes = conn.get_image_attribute(image.id, attribute="launchPermission")391 attributes.attrs["user_ids"].should.have.length_of(1)392 set(attributes.attrs["user_ids"]).should.equal(set([str(USER2)]))393 image = conn.get_image(image_id)394 image.is_public.should.equal(False)395 # Remove multiple users and confirm396 conn.modify_image_attribute(**REMOVE_USERS_ARGS)397 attributes = conn.get_image_attribute(image.id, attribute="launchPermission")398 attributes.attrs.should.have.length_of(0)399 image = conn.get_image(image_id)400 image.is_public.should.equal(False)401 # Remove is idempotent402 conn.modify_image_attribute.when.called_with(**REMOVE_USERS_ARGS).should_not.throw(403 EC2ResponseError404 )405@mock_ec2406def test_ami_describe_executable_users():407 conn = boto3.client("ec2", region_name="us-east-1")408 ec2 = boto3.resource("ec2", "us-east-1")409 ec2.create_instances(ImageId=EXAMPLE_AMI_ID, MinCount=1, MaxCount=1)410 response = conn.describe_instances(411 Filters=[{"Name": "instance-state-name", "Values": ["running"]}]412 )413 instance_id = response["Reservations"][0]["Instances"][0]["InstanceId"]414 image_id = conn.create_image(InstanceId=instance_id, Name="TestImage")["ImageId"]415 USER1 = "123456789011"416 ADD_USER_ARGS = {417 "ImageId": image_id,418 "Attribute": "launchPermission",419 "OperationType": "add",420 "UserIds": [USER1],421 }422 # Add users and get no images423 conn.modify_image_attribute(**ADD_USER_ARGS)424 attributes = conn.describe_image_attribute(425 ImageId=image_id, Attribute="LaunchPermissions", DryRun=False426 )427 attributes["LaunchPermissions"].should.have.length_of(1)428 attributes["LaunchPermissions"][0]["UserId"].should.equal(USER1)429 images = conn.describe_images(ExecutableUsers=[USER1])["Images"]430 images.should.have.length_of(1)431 images[0]["ImageId"].should.equal(image_id)432@mock_ec2433def test_ami_describe_executable_users_negative():434 conn = boto3.client("ec2", region_name="us-east-1")435 ec2 = boto3.resource("ec2", "us-east-1")436 ec2.create_instances(ImageId=EXAMPLE_AMI_ID, MinCount=1, MaxCount=1)437 response = conn.describe_instances(438 Filters=[{"Name": "instance-state-name", "Values": ["running"]}]439 )440 instance_id = response["Reservations"][0]["Instances"][0]["InstanceId"]441 image_id = conn.create_image(InstanceId=instance_id, Name="TestImage")["ImageId"]442 USER1 = "123456789011"443 USER2 = "113355789012"444 ADD_USER_ARGS = {445 "ImageId": image_id,446 "Attribute": "launchPermission",447 "OperationType": "add",448 "UserIds": [USER1],449 }450 # Add users and get no images451 # Add users and get no images452 conn.modify_image_attribute(**ADD_USER_ARGS)453 attributes = conn.describe_image_attribute(454 ImageId=image_id, Attribute="LaunchPermissions", DryRun=False455 )456 attributes["LaunchPermissions"].should.have.length_of(1)457 attributes["LaunchPermissions"][0]["UserId"].should.equal(USER1)458 images = conn.describe_images(ExecutableUsers=[USER2])["Images"]459 images.should.have.length_of(0)460@mock_ec2461def test_ami_describe_executable_users_and_filter():462 conn = boto3.client("ec2", region_name="us-east-1")463 ec2 = boto3.resource("ec2", "us-east-1")464 ec2.create_instances(ImageId=EXAMPLE_AMI_ID, MinCount=1, MaxCount=1)465 response = conn.describe_instances(466 Filters=[{"Name": "instance-state-name", "Values": ["running"]}]467 )468 instance_id = response["Reservations"][0]["Instances"][0]["InstanceId"]469 image_id = conn.create_image(InstanceId=instance_id, Name="ImageToDelete")[470 "ImageId"471 ]472 USER1 = "123456789011"473 ADD_USER_ARGS = {474 "ImageId": image_id,475 "Attribute": "launchPermission",476 "OperationType": "add",477 "UserIds": [USER1],478 }479 # Add users and get no images480 conn.modify_image_attribute(**ADD_USER_ARGS)481 attributes = conn.describe_image_attribute(482 ImageId=image_id, Attribute="LaunchPermissions", DryRun=False483 )484 attributes["LaunchPermissions"].should.have.length_of(1)485 attributes["LaunchPermissions"][0]["UserId"].should.equal(USER1)486 images = conn.describe_images(487 ExecutableUsers=[USER1], Filters=[{"Name": "state", "Values": ["available"]}]488 )["Images"]489 images.should.have.length_of(1)490 images[0]["ImageId"].should.equal(image_id)491@mock_ec2_deprecated492def test_ami_attribute_user_and_group_permissions():493 """494 Boto supports adding/removing both users and groups at the same time.495 Just spot-check this -- input variations, idempotency, etc are validated496 via user-specific and group-specific tests above.497 """498 conn = boto.connect_ec2("the_key", "the_secret")499 reservation = conn.run_instances(EXAMPLE_AMI_ID)500 instance = reservation.instances[0]501 image_id = conn.create_image(instance.id, "test-ami", "this is a test ami")502 image = conn.get_image(image_id)503 # Baseline504 attributes = conn.get_image_attribute(image.id, attribute="launchPermission")505 attributes.name.should.equal("launch_permission")506 attributes.attrs.should.have.length_of(0)507 USER1 = "123456789011"508 USER2 = "123456789022"509 ADD_ARGS = {510 "image_id": image.id,511 "attribute": "launchPermission",512 "operation": "add",513 "groups": ["all"],514 "user_ids": [USER1, USER2],515 }516 REMOVE_ARGS = {517 "image_id": image.id,518 "attribute": "launchPermission",519 "operation": "remove",520 "groups": ["all"],521 "user_ids": [USER1, USER2],522 }523 # Add and confirm524 conn.modify_image_attribute(**ADD_ARGS)525 attributes = conn.get_image_attribute(image.id, attribute="launchPermission")526 attributes.attrs["user_ids"].should.have.length_of(2)527 set(attributes.attrs["user_ids"]).should.equal(set([USER1, USER2]))528 set(attributes.attrs["groups"]).should.equal(set(["all"]))529 image = conn.get_image(image_id)530 image.is_public.should.equal(True)531 # Remove and confirm532 conn.modify_image_attribute(**REMOVE_ARGS)533 attributes = conn.get_image_attribute(image.id, attribute="launchPermission")534 attributes.attrs.should.have.length_of(0)535 image = conn.get_image(image_id)536 image.is_public.should.equal(False)537@mock_ec2_deprecated538def test_ami_attribute_error_cases():539 conn = boto.connect_ec2("the_key", "the_secret")540 reservation = conn.run_instances(EXAMPLE_AMI_ID)541 instance = reservation.instances[0]542 image_id = conn.create_image(instance.id, "test-ami", "this is a test ami")543 image = conn.get_image(image_id)544 # Error: Add with group != 'all'545 with pytest.raises(EC2ResponseError) as cm:546 conn.modify_image_attribute(547 image.id, attribute="launchPermission", operation="add", groups="everyone"548 )549 cm.value.code.should.equal("InvalidAMIAttributeItemValue")550 cm.value.status.should.equal(400)551 cm.value.request_id.should_not.be.none552 # Error: Add with user ID that isn't an integer.553 with pytest.raises(EC2ResponseError) as cm:554 conn.modify_image_attribute(555 image.id,556 attribute="launchPermission",557 operation="add",558 user_ids="12345678901A",559 )560 cm.value.code.should.equal("InvalidAMIAttributeItemValue")561 cm.value.status.should.equal(400)562 cm.value.request_id.should_not.be.none563 # Error: Add with user ID that is > length 12.564 with pytest.raises(EC2ResponseError) as cm:565 conn.modify_image_attribute(566 image.id,567 attribute="launchPermission",568 operation="add",569 user_ids="1234567890123",570 )571 cm.value.code.should.equal("InvalidAMIAttributeItemValue")572 cm.value.status.should.equal(400)573 cm.value.request_id.should_not.be.none574 # Error: Add with user ID that is < length 12.575 with pytest.raises(EC2ResponseError) as cm:576 conn.modify_image_attribute(577 image.id,578 attribute="launchPermission",579 operation="add",580 user_ids="12345678901",581 )582 cm.value.code.should.equal("InvalidAMIAttributeItemValue")583 cm.value.status.should.equal(400)584 cm.value.request_id.should_not.be.none585 # Error: Add with one invalid user ID among other valid IDs, ensure no586 # partial changes.587 with pytest.raises(EC2ResponseError) as cm:588 conn.modify_image_attribute(589 image.id,590 attribute="launchPermission",591 operation="add",592 user_ids=["123456789011", "foo", "123456789022"],593 )594 cm.value.code.should.equal("InvalidAMIAttributeItemValue")595 cm.value.status.should.equal(400)596 cm.value.request_id.should_not.be.none597 attributes = conn.get_image_attribute(image.id, attribute="launchPermission")598 attributes.attrs.should.have.length_of(0)599 # Error: Add with invalid image ID600 with pytest.raises(EC2ResponseError) as cm:601 conn.modify_image_attribute(602 "ami-abcd1234", attribute="launchPermission", operation="add", groups="all"603 )604 cm.value.code.should.equal("InvalidAMIID.NotFound")605 cm.value.status.should.equal(400)606 cm.value.request_id.should_not.be.none607 # Error: Remove with invalid image ID608 with pytest.raises(EC2ResponseError) as cm:609 conn.modify_image_attribute(610 "ami-abcd1234",611 attribute="launchPermission",612 operation="remove",613 groups="all",614 )615 cm.value.code.should.equal("InvalidAMIID.NotFound")616 cm.value.status.should.equal(400)617 cm.value.request_id.should_not.be.none618@mock_ec2619def test_ami_describe_non_existent():620 ec2 = boto3.resource("ec2", region_name="us-west-1")621 # Valid pattern but non-existent id622 img = ec2.Image("ami-abcd1234")623 with pytest.raises(ClientError):...
test_images.py
Source:test_images.py
...180 self.assertIn('Description', data)181 self.assertIn('Value', data['Description'])182 self.assertEqual(desc, data['Description']['Value'])183 def _modify_description(**kwargs):184 self.client.modify_image_attribute(ImageId=image_id, **kwargs)185 data = self.client.describe_image_attribute(186 ImageId=image_id, Attribute='description')187 self.assertEqual(new_desc, data['Description']['Value'])188 new_desc = data_utils.rand_name('new desc')189 _modify_description(Attribute='description', Value=new_desc)190 _modify_description(Description={'Value': new_desc})191 data = self.client.deregister_image(ImageId=image_id)192 self.cancelResourceCleanUp(image_clean)193 @testtools.skipUnless(CONF.aws.ebs_image_id, "EBS image id is not defined")194 def test_check_bdm_in_image(self):195 image_id = CONF.aws.ebs_image_id196 data = self.client.describe_images(ImageIds=[image_id])197 root_device_name = data['Images'][0]['RootDeviceName']198 device_name_prefix = base.get_device_name_prefix(root_device_name)199 device_name = device_name_prefix + 'h'200 name = data_utils.rand_name('image')201 desc = data_utils.rand_name('description')202 image_id, image_clean = self._create_image(203 name, desc,204 extra_run_instance_args={205 'BlockDeviceMappings': [{'DeviceName': device_name,206 'Ebs': {'VolumeSize': 1}}]})207 data = self.client.describe_images(ImageIds=[image_id])208 image = data['Images'][0]209 for bdm in image['BlockDeviceMappings']:210 self.assertTrue('DeviceName', bdm)211 data = self.client.deregister_image(ImageId=image_id)212 self.cancelResourceCleanUp(image_clean)213 @testtools.skipUnless(CONF.aws.run_incompatible_tests,214 'By default glance is configured as "publicize_image": "role:admin"')215 @testtools.skipUnless(CONF.aws.run_incompatible_tests,216 'skip due to bug #1439819')217 @testtools.skipUnless(CONF.aws.ebs_image_id, "EBS image id is not defined")218 def test_check_launch_permission_attribute(self):219 name = data_utils.rand_name('image')220 desc = data_utils.rand_name('desc for image')221 image_id, image_clean = self._create_image(name, desc)222 # launch permission223 data = self.client.describe_image_attribute(224 ImageId=image_id, Attribute='launchPermission')225 self.assertIn('LaunchPermissions', data)226 self.assertEmpty(data['LaunchPermissions'])227 def _modify_launch_permission(**kwargs):228 self.client.modify_image_attribute(ImageId=image_id, **kwargs)229 data = self.client.describe_image_attribute(230 ImageId=image_id, Attribute='launchPermission')231 self.assertIn('LaunchPermissions', data)232 self.assertNotEmpty(data['LaunchPermissions'])233 self.assertIn('Group', data['LaunchPermissions'][0])234 self.assertEqual('all', data['LaunchPermissions'][0]['Group'])235 data = self.client.describe_images(ImageIds=[image_id])236 self.assertTrue(data['Images'][0]['Public'])237 self.client.reset_image_attribute(238 ImageId=image_id, Attribute='launchPermission')239 data = self.client.describe_image_attribute(240 ImageId=image_id, Attribute='launchPermission')241 self.assertEmpty(data['LaunchPermissions'])242 data = self.client.describe_images(ImageIds=[image_id])...
amiShareAllAccounts.py
Source:amiShareAllAccounts.py
...62 for account_id in accounts:63 print(account_id['Id'])64 if account_id['Id'] is None:65 break66 ec2_client.modify_image_attribute(67 ImageId=centos_ssm_parameter['Parameter']['Value'],68 Attribute='launchPermission',69 OperationType='add',70 UserIds = Convert(account_id['Id'])71 )72 ec2_client.modify_image_attribute(73 ImageId=centos_docker_ssm_parameter['Parameter']['Value'],74 Attribute='launchPermission',75 OperationType='add',76 UserIds = Convert(account_id['Id'])77 )78 ec2_client.modify_image_attribute(79 ImageId=rhel7_ssm_parameter['Parameter']['Value'],80 Attribute='launchPermission',81 OperationType='add',82 UserIds = Convert(account_id['Id'])83 )84 ec2_client.modify_image_attribute(85 ImageId=win2k12_ssm_parameter['Parameter']['Value'],86 Attribute='launchPermission',87 OperationType='add',88 UserIds = Convert(account_id['Id'])89 )90 ec2_client.modify_image_attribute(91 ImageId=win2k12AH_ssm_parameter['Parameter']['Value'],92 Attribute='launchPermission',93 OperationType='add',94 UserIds = Convert(account_id['Id'])95 )96 ec2_client.modify_image_attribute(97 ImageId=win2k16_ssm_parameter['Parameter']['Value'],98 Attribute='launchPermission',99 OperationType='add',100 UserIds = Convert(account_id['Id'])101 )102 ec2_client.modify_image_attribute(103 ImageId=win2k16AH_ssm_parameter['Parameter']['Value'],104 Attribute='launchPermission',105 OperationType='add',106 UserIds = Convert(account_id['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!!