Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
release v1.3.0 (#374)
Nahuel Nucerafe968507b51a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex abb7f062..6d718f97 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,25 @@ Versioning follows [Semantic Versioning](https://semver.org/).---+## [1.3.0] — 2026-04-18++### Added+- **Hypercorn ASGI server with HTTP/2 h2c** — replaces uvicorn with hypercorn, enabling cleartext HTTP/2 (h2c) support. AWS Java SDK v2 and Kinesis Client Library (KCL) clients that require HTTP/2 now work out of the box. Idle RAM drops from ~21 MB to ~7 MB. Contributed by @AdigaAkhil (#369). Fixes #361, #364+- **Lambda log forwarding for Winston/pino** — replaces 5 individual `console.*` overrides with a single `process.stdout.write` intercept. Catches logging libraries like Winston and pino that write directly to `stdout.write` instead of `console.log`. Contributed by @Baptiste-Garcin (#373)+- **Test suite** — 121 new tests across 11 services: AutoScaling (37 new), ElastiCache (15 new), Glue (19 new), RDS (14 new), CloudWatch Logs (7 new), EMR (5 new), EFS (5 new), Cloud Map (5 new), ACM (3 new), CloudWatch (2 new), EBS (2 new). Total test count: 1,558++### Fixed+- **Glue `GetPartitionIndexes` Keys format** — service returned Keys as flat strings (`["year"]`) instead of KeySchemaElement objects (`[{"Name": "year"}]`), causing boto3 deserialization failures+- **RDS `LatestRestorableTime` empty timestamp** — `DescribeDBInstances` rendered `<LatestRestorableTime></LatestRestorableTime>` (empty string) which boto3 couldn't parse as a timestamp. Now defaults to current time+- **EKS Docker tests flaky in parallel** — k3s containers interfere with each other under pytest-xdist. Added both EKS Docker tests to `_SERIAL_TESTS`+- **EKS CFN test CI failure** — k3s can't start on CI (no Docker), cluster stays in CREATING. Test now polls and accepts CREATING status++### Changed+- **ASGI server: uvicorn → hypercorn** — dependency changed from `uvicorn[standard]` + `httptools` to `hypercorn>=0.18.0`+- **pytest parallel distribution: `--dist=load` → `--dist=loadfile`** — keeps all tests from the same file on the same worker, fixing pre-existing Lambda/IAM ordering failures caused by shared session fixtures++---+## [1.2.21] — 2026-04-17### Addeddiff --git a/README.md b/README.mdindex 7e18d556..62d0baf3 100644--- a/README.md+++ b/README.md@@ -30,7 +30,7 @@ LocalStack recently moved its core services behind a paid plan. If you relied on- **Drop-in compatible** — works with `boto3`, AWS CLI, Terraform, CDK, Pulumi, any SDK- **Real infrastructure** — RDS spins up actual Postgres/MySQL containers, ElastiCache spins up real Redis, Athena runs real SQL via DuckDB, ECS runs real Docker containers- **Tiny footprint** — ~270MB image, ~21MB RAM at idle vs LocalStack's ~1GB image and ~500MB RAM-- **Fast startup** — under 2 seconds+- **Fast startup** — under 2 seconds, HTTP/2 (h2c) supported- **MIT licensed** — use it, fork it, contribute to it---@@ -392,6 +392,7 @@ subnet = ec2.create_subnet(| `AWS::IAM::InstanceProfile` | Profile name | Arn || `AWS::SSM::Parameter` | Parameter name | Type, Value || `AWS::Logs::LogGroup` | Log group name | Arn |+| `AWS::Events::EventBus` | EventBus name | Arn, Name || `AWS::Events::Rule` | Rule name | Arn || `AWS::Kinesis::Stream` | Stream name | Arn, StreamId || `AWS::Lambda::Permission` | Statement ID | — |@@ -478,7 +479,7 @@ Unsupported resource types fail with `CREATE_FAILED` (or `ROLLBACK_COMPLETE` if| **Cloud Map** | CreateHttpNamespace, CreatePrivateDnsNamespace, CreatePublicDnsNamespace, GetNamespace, ListNamespaces, DeleteNamespace, UpdateHttpNamespace, UpdatePrivateDnsNamespace, UpdatePublicDnsNamespace, CreateService, GetService, ListServices, DeleteService, UpdateService, RegisterInstance, DeregisterInstance, DiscoverInstances, DiscoverInstancesRevision, ListInstances, GetInstancesHealthStatus, UpdateInstanceCustomHealthStatus, GetServiceAttributes, UpdateServiceAttributes, DeleteServiceAttributes, GetOperation, ListOperations, TagResource, UntagResource, ListTagsForResource | DNS namespaces create Route53 hosted zones; operation tracking; Terraform `aws_service_discovery_*` compatible || **RDS Data API** | ExecuteStatement, BatchExecuteStatement, BeginTransaction, CommitTransaction, RollbackTransaction | Routes SQL to real Docker-backed RDS database containers; supports MySQL (pymysql) and PostgreSQL (psycopg2); REST paths (`/Execute`, `/BeginTransaction`, etc.) || **S3 Files** | CreateFileSystem, GetFileSystem, ListFileSystems, DeleteFileSystem, CreateMountTarget, GetMountTarget, ListMountTargets, UpdateMountTarget, DeleteMountTarget, CreateAccessPoint, GetAccessPoint, ListAccessPoints, DeleteAccessPoint, GetFileSystemPolicy, PutFileSystemPolicy, DeleteFileSystemPolicy, GetSynchronizationConfiguration, PutSynchronizationConfiguration, TagResource, UntagResource, ListTagsForResource | 21 operations; control plane for the new S3 Files service (launched April 2026); file systems, mount targets, access points, policies |-| **AutoScaling** | CreateAutoScalingGroup, DescribeAutoScalingGroups, UpdateAutoScalingGroup, DeleteAutoScalingGroup, DescribeAutoScalingInstances, CreateLaunchConfiguration, DescribeLaunchConfigurations, DeleteLaunchConfiguration, PutScalingPolicy, DescribePolicies, DeletePolicy, PutLifecycleHook, DescribeLifecycleHooks, DeleteLifecycleHook, CompleteLifecycleAction, RecordLifecycleActionHeartbeat, PutScheduledUpdateGroupAction, DescribeScheduledActions, DeleteScheduledAction, CreateOrUpdateTags, DescribeTags, DeleteTags | 22 actions; in-memory state — no real instance scaling; full ASG lifecycle (launch configs, scaling policies, lifecycle hooks, scheduled actions, tags); CDK/Terraform compatible |+| **AutoScaling** | CreateAutoScalingGroup, DescribeAutoScalingGroups, UpdateAutoScalingGroup, DeleteAutoScalingGroup, DescribeAutoScalingInstances, CreateLaunchConfiguration, DescribeLaunchConfigurations, DeleteLaunchConfiguration, PutScalingPolicy, DescribePolicies, DeletePolicy, PutLifecycleHook, DescribeLifecycleHooks, DeleteLifecycleHook, CompleteLifecycleAction, RecordLifecycleActionHeartbeat, PutScheduledUpdateGroupAction, DescribeScheduledActions, DeleteScheduledAction, CreateOrUpdateTags, DescribeTags, DeleteTags | 23 actions; in-memory state — no real instance scaling; full ASG lifecycle (launch configs, scaling policies, lifecycle hooks, scheduled actions, tags); CDK/Terraform compatible || **CodeBuild** | CreateProject, BatchGetProjects, ListProjects, UpdateProject, DeleteProject, StartBuild, BatchGetBuilds, StopBuild, ListBuilds, ListBuildsForProject, BatchDeleteBuilds | 11 actions; builds complete immediately with SUCCEEDED status; project and build metadata stored in-memory || **AppConfig** | CreateApplication, GetApplication, ListApplications, UpdateApplication, DeleteApplication, CreateEnvironment, GetEnvironment, ListEnvironments, UpdateEnvironment, DeleteEnvironment, CreateConfigurationProfile, GetConfigurationProfile, ListConfigurationProfiles, UpdateConfigurationProfile, DeleteConfigurationProfile, CreateHostedConfigurationVersion, GetHostedConfigurationVersion, ListHostedConfigurationVersions, DeleteHostedConfigurationVersion, CreateDeploymentStrategy, GetDeploymentStrategy, ListDeploymentStrategies, UpdateDeploymentStrategy, DeleteDeploymentStrategy, StartDeployment, GetDeployment, ListDeployments, StopDeployment, TagResource, UntagResource, ListTagsForResource, StartConfigurationSession, GetLatestConfiguration | 33 operations; control plane + data plane; hosted configuration versions; deployments complete immediately; session-based configuration retrieval with token rotation || **Transfer Family** | CreateServer, DescribeServer, DeleteServer, ListServers, CreateUser, DescribeUser, DeleteUser, ListUsers, ImportSshPublicKey, DeleteSshPublicKey | 10 operations; SFTP server and user management; SSH key rotation; LOGICAL home directory mappings to S3; in-memory state |@@ -869,8 +870,9 @@ MiniStack also sets the standard Lambda runtime environment before the handler m│ │ ALB/ELBv2 WAF v2 KMS ECR │ ││ │ CloudFormation CloudFront │ ││ │ AppSync Cloud Map CodeBuild │ │- │ │ AutoScaling AppConfig │ │- │ │ RDS Data S3 Files Scheduler │ │+ │ │ AutoScaling AppConfig EKS │ │+ │ │ RDS Data S3 Files Scheduler │ │+ │ │ Transfer Family │ ││ └────────────────────────────────────┘ ││ ││ In-Memory Storage + Optional Docker │diff --git a/ministack/services/glue.py b/ministack/services/glue.pyindex e97c342f..ef7e2424 100644--- a/ministack/services/glue.py+++ b/ministack/services/glue.py@@ -434,9 +434,11 @@ def _create_partition_index(data):key = f"{db_name}/{table_name}"if key not in _partition_indexes:_partition_indexes[key] = []+ raw_keys = index_input.get("Keys", [])+ key_schema = [{"Name": k} if isinstance(k, str) else k for k in raw_keys]_partition_indexes[key].append({"IndexName": index_input.get("IndexName", ""),- "Keys": index_input.get("Keys", []),+ "Keys": key_schema,"IndexStatus": "ACTIVE",})return json_response({})diff --git a/ministack/services/rds.py b/ministack/services/rds.pyindex 8f1fa352..08065c76 100644--- a/ministack/services/rds.py+++ b/ministack/services/rds.py@@ -2036,7 +2036,7 @@ def _instance_xml(i):</DBSubnetGroup><PreferredMaintenanceWindow>{i.get('PreferredMaintenanceWindow','sun:05:00-sun:06:00')}</PreferredMaintenanceWindow><PendingModifiedValues>{pending_xml}</PendingModifiedValues>- <LatestRestorableTime>{i.get('LatestRestorableTime','')}</LatestRestorableTime>+ <LatestRestorableTime>{i.get('LatestRestorableTime') or _format_time(time.time())}</LatestRestorableTime><MultiAZ>{str(i.get('MultiAZ',False)).lower()}</MultiAZ><AutoMinorVersionUpgrade>{str(i.get('AutoMinorVersionUpgrade',True)).lower()}</AutoMinorVersionUpgrade><ReadReplicaDBInstanceIdentifiers>{read_replica_xml}</ReadReplicaDBInstanceIdentifiers>diff --git a/pyproject.toml b/pyproject.tomlindex 5d85ccfd..9b6f2292 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -64,6 +64,7 @@ include = ["ministack*"]testpaths = ["tests"]python_files = ["test_*.py"]python_functions = ["test_*"]+addopts = "--dist=loadfile"markers = ["serial: tests that mutate global server state and must run alone",]diff --git a/tests/conftest.py b/tests/conftest.pyindex 63c73d48..6bb8dbd6 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -38,6 +38,8 @@ _SERIAL_TESTS = {"tests/test_ec2.py::test_ec2_create_default_vpc","tests/test_sfn.py::test_sfn_wait_scale_zero_skips_wait","tests/test_sfn.py::test_sfn_wait_scale_zero_does_not_timeout_lambda_tasks",+ "tests/test_eks.py::test_eks_create_describe_delete_cluster",+ "tests/test_eks.py::test_eks_cfn_cluster",}diff --git a/tests/test_acm.py b/tests/test_acm.pyindex 4376fd52..a23bcfd3 100644--- a/tests/test_acm.py+++ b/tests/test_acm.py@@ -66,3 +66,43 @@ def test_acm_delete_certificate(acm_client):resp = acm_client.list_certificates()arns = [c["CertificateArn"] for c in resp["CertificateSummaryList"]]assert arn not in arns++def test_acm_update_certificate_options(acm_client):+ arn = acm_client.request_certificate(DomainName="options.example.com")["CertificateArn"]+ acm_client.update_certificate_options(+ CertificateArn=arn,+ Options={"CertificateTransparencyLoggingPreference": "DISABLED"},+ )+ desc = acm_client.describe_certificate(CertificateArn=arn)+ pref = desc["Certificate"]["Options"]["CertificateTransparencyLoggingPreference"]+ assert pref == "DISABLED"+ acm_client.update_certificate_options(+ CertificateArn=arn,+ Options={"CertificateTransparencyLoggingPreference": "ENABLED"},+ )+ desc2 = acm_client.describe_certificate(CertificateArn=arn)+ pref2 = desc2["Certificate"]["Options"]["CertificateTransparencyLoggingPreference"]+ assert pref2 == "ENABLED"+ acm_client.delete_certificate(CertificateArn=arn)++def test_acm_renew_certificate(acm_client):+ arn = acm_client.request_certificate(DomainName="renew.example.com")["CertificateArn"]+ # RenewCertificate is a no-op in ministack — just verify it doesn't error+ acm_client.renew_certificate(CertificateArn=arn)+ desc = acm_client.describe_certificate(CertificateArn=arn)+ assert desc["Certificate"]["Status"] in ("ISSUED", "PENDING_VALIDATION")+ acm_client.delete_certificate(CertificateArn=arn)++def test_acm_resend_validation_email(acm_client):+ arn = acm_client.request_certificate(+ DomainName="resend.example.com",+ ValidationMethod="EMAIL",+ )["CertificateArn"]+ acm_client.resend_validation_email(+ CertificateArn=arn,+ Domain="resend.example.com",+ ValidationDomain="example.com",+ )+ desc = acm_client.describe_certificate(CertificateArn=arn)+ assert desc["Certificate"]["DomainName"] == "resend.example.com"+ acm_client.delete_certificate(CertificateArn=arn)diff --git a/tests/test_autoscaling.py b/tests/test_autoscaling.pyindex 2440536f..c3f3606c 100644--- a/tests/test_autoscaling.py+++ b/tests/test_autoscaling.py@@ -1,14 +1,93 @@+import uuid++import pytestfrom botocore.exceptions import ClientError-def test_autoscaling_describe_scaling_activities_empty(autoscaling):- """DescribeScalingActivities returns an empty list when no ASG exists."""- resp = autoscaling.describe_scaling_activities()- assert resp["Activities"] == []+def _uid(prefix="test"):+ return f"{prefix}-{uuid.uuid4().hex[:8]}"+++# ---------------------------------------------------------------------------+# AutoScalingGroup: Create, Describe, Update, Delete+# ---------------------------------------------------------------------------+++def test_create_and_describe_asg(autoscaling):+ name = _uid("asg")+ autoscaling.create_auto_scaling_group(+ AutoScalingGroupName=name,+ MinSize=1,+ MaxSize=5,+ DesiredCapacity=2,+ AvailabilityZones=["us-east-1a"],+ LaunchConfigurationName="dummy-lc",+ )+ try:+ resp = autoscaling.describe_auto_scaling_groups(AutoScalingGroupNames=[name])+ groups = resp["AutoScalingGroups"]+ assert len(groups) == 1+ g = groups[0]+ assert g["AutoScalingGroupName"] == name+ assert g["MinSize"] == 1+ assert g["MaxSize"] == 5+ assert g["DesiredCapacity"] == 2+ assert g["AutoScalingGroupARN"].startswith("arn:aws:autoscaling:")+ finally:+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=name)+++def test_create_asg_duplicate_fails(autoscaling):+ name = _uid("asg-dup")+ autoscaling.create_auto_scaling_group(+ AutoScalingGroupName=name,+ MinSize=0,+ MaxSize=1,+ AvailabilityZones=["us-east-1a"],+ LaunchConfigurationName="dummy-lc",+ )+ try:+ with pytest.raises(ClientError) as exc:+ autoscaling.create_auto_scaling_group(+ AutoScalingGroupName=name,+ MinSize=0,+ MaxSize=1,+ AvailabilityZones=["us-east-1a"],+ LaunchConfigurationName="dummy-lc",+ )+ assert "AlreadyExists" in str(exc.value)+ finally:+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=name)+++def test_describe_asgs_empty(autoscaling):+ bogus = _uid("no-exist")+ resp = autoscaling.describe_auto_scaling_groups(AutoScalingGroupNames=[bogus])+ assert resp["AutoScalingGroups"] == []++def test_describe_asgs_all(autoscaling):+ names = [_uid("asg-all") for _ in range(3)]+ for n in names:+ autoscaling.create_auto_scaling_group(+ AutoScalingGroupName=n,+ MinSize=0,+ MaxSize=1,+ AvailabilityZones=["us-east-1a"],+ LaunchConfigurationName="dummy-lc",+ )+ try:+ resp = autoscaling.describe_auto_scaling_groups()+ returned_names = [g["AutoScalingGroupName"] for g in resp["AutoScalingGroups"]]+ for n in names:+ assert n in returned_names+ finally:+ for n in names:+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=n)-def test_autoscaling_create_and_describe_asg(autoscaling):- name = "test-asg-basic"++def test_update_asg(autoscaling):+ name = _uid("asg-upd")autoscaling.create_auto_scaling_group(AutoScalingGroupName=name,MinSize=0,@@ -17,19 +96,72 @@ def test_autoscaling_create_and_describe_asg(autoscaling):AvailabilityZones=["us-east-1a"],LaunchConfigurationName="dummy-lc",)- resp = autoscaling.describe_auto_scaling_groups(AutoScalingGroupNames=[name])- groups = resp["AutoScalingGroups"]- assert len(groups) == 1- assert groups[0]["AutoScalingGroupName"] == name- assert groups[0]["MinSize"] == 0- assert groups[0]["MaxSize"] == 1+ try:+ autoscaling.update_auto_scaling_group(+ AutoScalingGroupName=name,+ MinSize=2,+ MaxSize=10,+ DesiredCapacity=5,+ )+ resp = autoscaling.describe_auto_scaling_groups(AutoScalingGroupNames=[name])+ g = resp["AutoScalingGroups"][0]+ assert g["MinSize"] == 2+ assert g["MaxSize"] == 10+ assert g["DesiredCapacity"] == 5+ finally:+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=name)+++def test_update_nonexistent_asg_fails(autoscaling):+ with pytest.raises(ClientError) as exc:+ autoscaling.update_auto_scaling_group(+ AutoScalingGroupName="nonexistent-asg",+ MinSize=1,+ )+ assert "ValidationError" in str(exc.value) or "not found" in str(exc.value).lower()++def test_delete_asg(autoscaling):+ name = _uid("asg-del")+ autoscaling.create_auto_scaling_group(+ AutoScalingGroupName=name,+ MinSize=0,+ MaxSize=1,+ AvailabilityZones=["us-east-1a"],+ LaunchConfigurationName="dummy-lc",+ )autoscaling.delete_auto_scaling_group(AutoScalingGroupName=name)+ resp = autoscaling.describe_auto_scaling_groups(AutoScalingGroupNames=[name])+ assert resp["AutoScalingGroups"] == []+++def test_delete_asg_idempotent(autoscaling):+ """Deleting a non-existent ASG should not error."""+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=_uid("ghost"))+++# ---------------------------------------------------------------------------+# DescribeAutoScalingInstances+# ---------------------------------------------------------------------------+++def test_describe_auto_scaling_instances_empty(autoscaling):+ resp = autoscaling.describe_auto_scaling_instances()+ assert resp["AutoScalingInstances"] == []+++# ---------------------------------------------------------------------------+# DescribeScalingActivities+# ---------------------------------------------------------------------------+++def test_describe_scaling_activities_empty(autoscaling):+ resp = autoscaling.describe_scaling_activities()+ assert resp["Activities"] == []-def test_autoscaling_describe_scaling_activities_after_create(autoscaling):- """Terraform polls DescribeScalingActivities right after ASG creation."""- name = "test-asg-activities"+def test_describe_scaling_activities_for_asg(autoscaling):+ name = _uid("asg-act")autoscaling.create_auto_scaling_group(AutoScalingGroupName=name,MinSize=0,@@ -38,7 +170,731 @@ def test_autoscaling_describe_scaling_activities_after_create(autoscaling):AvailabilityZones=["us-east-1a"],LaunchConfigurationName="dummy-lc",)- resp = autoscaling.describe_scaling_activities(AutoScalingGroupName=name)- assert resp["Activities"] == []+ try:+ resp = autoscaling.describe_scaling_activities(AutoScalingGroupName=name)+ assert resp["Activities"] == []+ finally:+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=name)- autoscaling.delete_auto_scaling_group(AutoScalingGroupName=name)++# ---------------------------------------------------------------------------+# LaunchConfiguration: Create, Describe, Delete+# ---------------------------------------------------------------------------+++def test_create_and_describe_launch_configuration(autoscaling):+ name = _uid("lc")+ autoscaling.create_launch_configuration(+ LaunchConfigurationName=name,+ ImageId="ami-12345678",+ InstanceType="t3.micro",+ )+ try:+ resp = autoscaling.describe_launch_configurations(+ LaunchConfigurationNames=[name]+ )+ configs = resp["LaunchConfigurations"]+ assert len(configs) == 1+ lc = configs[0]+ assert lc["LaunchConfigurationName"] == name+ assert lc["ImageId"] == "ami-12345678"+ assert lc["InstanceType"] == "t3.micro"+ assert lc["LaunchConfigurationARN"].startswith("arn:aws:autoscaling:")+ finally:+ autoscaling.delete_launch_configuration(LaunchConfigurationName=name)+++def test_create_launch_configuration_duplicate_fails(autoscaling):+ name = _uid("lc-dup")+ autoscaling.create_launch_configuration(+ LaunchConfigurationName=name,+ ImageId="ami-00000000",+ InstanceType="t2.micro",+ )+ try:+ with pytest.raises(ClientError) as exc:+ autoscaling.create_launch_configuration(+ LaunchConfigurationName=name,+ ImageId="ami-00000000",+ InstanceType="t2.micro",+ )+ assert "AlreadyExists" in str(exc.value)+ finally:+ autoscaling.delete_launch_configuration(LaunchConfigurationName=name)+++def test_describe_launch_configurations_empty(autoscaling):+ resp = autoscaling.describe_launch_configurations(+ LaunchConfigurationNames=[_uid("no-lc")]+ )+ assert resp["LaunchConfigurations"] == []+++def test_delete_launch_configuration(autoscaling):+ name = _uid("lc-del")+ autoscaling.create_launch_configuration(+ LaunchConfigurationName=name,+ ImageId="ami-00000000",+ InstanceType="t2.micro",+ )+ autoscaling.delete_launch_configuration(LaunchConfigurationName=name)+ resp = autoscaling.describe_launch_configurations(+ LaunchConfigurationNames=[name]+ )+ assert resp["LaunchConfigurations"] == []+++def test_delete_launch_configuration_idempotent(autoscaling):+ autoscaling.delete_launch_configuration(LaunchConfigurationName=_uid("ghost-lc"))+++# ---------------------------------------------------------------------------+# Scaling Policies: Put, Describe, Delete+# ---------------------------------------------------------------------------+++def test_put_and_describe_scaling_policy(autoscaling):+ asg = _uid("asg-pol")+ pol = _uid("pol")+ autoscaling.create_auto_scaling_group(+ AutoScalingGroupName=asg,+ MinSize=0,+ MaxSize=10,+ AvailabilityZones=["us-east-1a"],+ LaunchConfigurationName="dummy-lc",+ )+ try:+ resp = autoscaling.put_scaling_policy(+ AutoScalingGroupName=asg,+ PolicyName=pol,+ PolicyType="SimpleScaling",+ AdjustmentType="ChangeInCapacity",+ ScalingAdjustment=2,+ Cooldown=60,+ )+ assert "PolicyARN" in resp+ assert resp["PolicyARN"].startswith("arn:aws:autoscaling:")++ desc = autoscaling.describe_policies(AutoScalingGroupName=asg)+ policies = desc["ScalingPolicies"]+ assert len(policies) >= 1+ found = [p for p in policies if p["PolicyName"] == pol]+ assert len(found) == 1+ assert found[0]["AdjustmentType"] == "ChangeInCapacity"+ assert found[0]["ScalingAdjustment"] == 2+ finally:+ autoscaling.delete_policy(AutoScalingGroupName=asg, PolicyName=pol)+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)+++def test_describe_policies_empty(autoscaling):+ resp = autoscaling.describe_policies(AutoScalingGroupName=_uid("no-asg"))+ assert resp["ScalingPolicies"] == []+++def test_delete_policy(autoscaling):+ asg = _uid("asg-dpol")+ pol = _uid("dpol")+ autoscaling.create_auto_scaling_group(+ AutoScalingGroupName=asg,+ MinSize=0,+ MaxSize=1,+ AvailabilityZones=["us-east-1a"],+ LaunchConfigurationName="dummy-lc",+ )+ try:+ autoscaling.put_scaling_policy(+ AutoScalingGroupName=asg,+ PolicyName=pol,+ AdjustmentType="ChangeInCapacity",+ ScalingAdjustment=1,+ )+ autoscaling.delete_policy(AutoScalingGroupName=asg, PolicyName=pol)+ desc = autoscaling.describe_policies(AutoScalingGroupName=asg)+ names = [p["PolicyName"] for p in desc["ScalingPolicies"]]+ assert pol not in names+ finally:+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)+++def test_delete_policy_idempotent(autoscaling):+ autoscaling.delete_policy(+ AutoScalingGroupName="ghost-asg",+ PolicyName="ghost-pol",+ )+++# ---------------------------------------------------------------------------+# Lifecycle Hooks: Put, Describe, Delete, Complete, Heartbeat+# ---------------------------------------------------------------------------+++def test_put_and_describe_lifecycle_hook(autoscaling):+ asg = _uid("asg-hook")+ hook = _uid("hook")+ autoscaling.create_auto_scaling_group(+ AutoScalingGroupName=asg,+ MinSize=0,+ MaxSize=1,+ AvailabilityZones=["us-east-1a"],+ LaunchConfigurationName="dummy-lc",+ )+ try:+ autoscaling.put_lifecycle_hook(+ AutoScalingGroupName=asg,+ LifecycleHookName=hook,+ LifecycleTransition="autoscaling:EC2_INSTANCE_LAUNCHING",+ HeartbeatTimeout=300,+ DefaultResult="CONTINUE",+ )+ resp = autoscaling.describe_lifecycle_hooks(AutoScalingGroupName=asg)+ hooks = resp["LifecycleHooks"]+ assert len(hooks) >= 1+ found = [h for h in hooks if h["LifecycleHookName"] == hook]+ assert len(found) == 1+ assert found[0]["LifecycleTransition"] == "autoscaling:EC2_INSTANCE_LAUNCHING"+ assert found[0]["DefaultResult"] == "CONTINUE"+ assert found[0]["HeartbeatTimeout"] == 300+ finally:+ autoscaling.delete_lifecycle_hook(+ AutoScalingGroupName=asg, LifecycleHookName=hook+ )+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)+++def test_describe_lifecycle_hooks_empty(autoscaling):+ asg = _uid("asg-nohook")+ autoscaling.create_auto_scaling_group(+ AutoScalingGroupName=asg,+ MinSize=0,+ MaxSize=1,+ AvailabilityZones=["us-east-1a"],+ LaunchConfigurationName="dummy-lc",+ )+ try:+ resp = autoscaling.describe_lifecycle_hooks(AutoScalingGroupName=asg)+ assert resp["LifecycleHooks"] == []+ finally:+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)+++def test_delete_lifecycle_hook(autoscaling):+ asg = _uid("asg-dhook")+ hook = _uid("dhook")+ autoscaling.create_auto_scaling_group(+ AutoScalingGroupName=asg,+ MinSize=0,+ MaxSize=1,+ AvailabilityZones=["us-east-1a"],+ LaunchConfigurationName="dummy-lc",+ )+ try:+ autoscaling.put_lifecycle_hook(+ AutoScalingGroupName=asg,+ LifecycleHookName=hook,+ LifecycleTransition="autoscaling:EC2_INSTANCE_TERMINATING",+ )+ autoscaling.delete_lifecycle_hook(+ AutoScalingGroupName=asg, LifecycleHookName=hook+ )+ resp = autoscaling.describe_lifecycle_hooks(AutoScalingGroupName=asg)+ names = [h["LifecycleHookName"] for h in resp["LifecycleHooks"]]+ assert hook not in names+ finally:+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)+++def test_delete_lifecycle_hook_idempotent(autoscaling):+ autoscaling.delete_lifecycle_hook(+ AutoScalingGroupName="ghost-asg",+ LifecycleHookName="ghost-hook",+ )+++def test_complete_lifecycle_action(autoscaling):+ asg = _uid("asg-cla")+ autoscaling.create_auto_scaling_group(+ AutoScalingGroupName=asg,+ MinSize=0,+ MaxSize=1,+ AvailabilityZones=["us-east-1a"],+ LaunchConfigurationName="dummy-lc",+ )+ try:+ resp = autoscaling.complete_lifecycle_action(+ AutoScalingGroupName=asg,+ LifecycleHookName="any-hook",+ LifecycleActionResult="CONTINUE",+ )+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200+ finally:+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)+++def test_record_lifecycle_action_heartbeat(autoscaling):+ asg = _uid("asg-hb")+ autoscaling.create_auto_scaling_group(+ AutoScalingGroupName=asg,+ MinSize=0,+ MaxSize=1,+ AvailabilityZones=["us-east-1a"],+ LaunchConfigurationName="dummy-lc",+ )+ try:+ resp = autoscaling.record_lifecycle_action_heartbeat(+ AutoScalingGroupName=asg,+ LifecycleHookName="any-hook",+ )+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200+ finally:+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)+++def test_delete_asg_cleans_up_hooks(autoscaling):+ """Deleting an ASG should also remove its lifecycle hooks."""+ asg = _uid("asg-hclean")+ hook = _uid("hclean")+ autoscaling.create_auto_scaling_group(+ AutoScalingGroupName=asg,+ MinSize=0,+ MaxSize=1,+ AvailabilityZones=["us-east-1a"],+ LaunchConfigurationName="dummy-lc",+ )+ autoscaling.put_lifecycle_hook(+ AutoScalingGroupName=asg,+ LifecycleHookName=hook,+ LifecycleTransition="autoscaling:EC2_INSTANCE_LAUNCHING",+ )+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)+ # Re-create the ASG to query hooks — should be empty+ autoscaling.create_auto_scaling_group(+ AutoScalingGroupName=asg,+ MinSize=0,+ MaxSize=1,+ AvailabilityZones=["us-east-1a"],+ LaunchConfigurationName="dummy-lc",+ )+ try:+ resp = autoscaling.describe_lifecycle_hooks(AutoScalingGroupName=asg)+ names = [h["LifecycleHookName"] for h in resp["LifecycleHooks"]]+ assert hook not in names+ finally:+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)+++# ---------------------------------------------------------------------------+# Scheduled Actions: Put, Describe, Delete+# ---------------------------------------------------------------------------+++def test_put_and_describe_scheduled_action(autoscaling):+ asg = _uid("asg-sched")+ action = _uid("sched")+ autoscaling.create_auto_scaling_group(+ AutoScalingGroupName=asg,+ MinSize=0,+ MaxSize=10,+ AvailabilityZones=["us-east-1a"],+ LaunchConfigurationName="dummy-lc",+ )+ try:+ autoscaling.put_scheduled_update_group_action(+ AutoScalingGroupName=asg,+ ScheduledActionName=action,+ Recurrence="0 8 * * *",+ MinSize=2,+ MaxSize=8,+ DesiredCapacity=4,+ )+ resp = autoscaling.describe_scheduled_actions(AutoScalingGroupName=asg)+ actions = resp["ScheduledUpdateGroupActions"]+ assert len(actions) >= 1+ found = [a for a in actions if a["ScheduledActionName"] == action]+ assert len(found) == 1+ assert found[0]["ScheduledActionARN"].startswith("arn:aws:autoscaling:")+ finally:+ autoscaling.delete_scheduled_action(+ AutoScalingGroupName=asg, ScheduledActionName=action+ )+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)+++def test_describe_scheduled_actions_empty(autoscaling):+ resp = autoscaling.describe_scheduled_actions(+ AutoScalingGroupName=_uid("no-sched")+ )+ assert resp["ScheduledUpdateGroupActions"] == []+++def test_delete_scheduled_action(autoscaling):+ asg = _uid("asg-dsched")+ action = _uid("dsched")+ autoscaling.create_auto_scaling_group(+ AutoScalingGroupName=asg,+ MinSize=0,+ MaxSize=1,+ AvailabilityZones=["us-east-1a"],+ LaunchConfigurationName="dummy-lc",+ )+ try:+ autoscaling.put_scheduled_update_group_action(+ AutoScalingGroupName=asg,+ ScheduledActionName=action,+ MinSize=1,+ MaxSize=5,+ )+ autoscaling.delete_scheduled_action(+ AutoScalingGroupName=asg, ScheduledActionName=action+ )+ resp = autoscaling.describe_scheduled_actions(AutoScalingGroupName=asg)+ names = [a["ScheduledActionName"] for a in resp["ScheduledUpdateGroupActions"]]+ assert action not in names+ finally:+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)+++def test_delete_scheduled_action_idempotent(autoscaling):+ autoscaling.delete_scheduled_action(+ AutoScalingGroupName="ghost-asg",+ ScheduledActionName="ghost-action",+ )+++# ---------------------------------------------------------------------------+# Tags: CreateOrUpdate, Describe, Delete+# ---------------------------------------------------------------------------+++def test_create_or_update_tags_and_describe(autoscaling):+ asg = _uid("asg-tag")+ autoscaling.create_auto_scaling_group(+ AutoScalingGroupName=asg,+ MinSize=0,+ MaxSize=1,+ AvailabilityZones=["us-east-1a"],+ LaunchConfigurationName="dummy-lc",+ )+ try:+ autoscaling.create_or_update_tags(+ Tags=[+ {+ "ResourceId": asg,+ "ResourceType": "auto-scaling-group",+ "Key": "Environment",+ "Value": "test",+ "PropagateAtLaunch": True,+ },+ {+ "ResourceId": asg,+ "ResourceType": "auto-scaling-group",+ "Key": "Team",+ "Value": "platform",+ "PropagateAtLaunch": False,+ },+ ]+ )+ resp = autoscaling.describe_tags()+ all_tags = resp["Tags"]+ my_tags = [t for t in all_tags if t["ResourceId"] == asg]+ assert len(my_tags) == 2+ keys = {t["Key"] for t in my_tags}+ assert keys == {"Environment", "Team"}+ finally:+ autoscaling.delete_tags(+ Tags=[+ {"ResourceId": asg, "ResourceType": "auto-scaling-group", "Key": "Environment"},+ {"ResourceId": asg, "ResourceType": "auto-scaling-group", "Key": "Team"},+ ]+ )+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)+++def test_update_existing_tag(autoscaling):+ asg = _uid("asg-tagup")+ autoscaling.create_auto_scaling_group(+ AutoScalingGroupName=asg,+ MinSize=0,+ MaxSize=1,+ AvailabilityZones=["us-east-1a"],+ LaunchConfigurationName="dummy-lc",+ )+ try:+ autoscaling.create_or_update_tags(+ Tags=[+ {+ "ResourceId": asg,+ "ResourceType": "auto-scaling-group",+ "Key": "Version",+ "Value": "v1",+ "PropagateAtLaunch": False,+ },+ ]+ )+ # Update same key with new value+ autoscaling.create_or_update_tags(+ Tags=[+ {+ "ResourceId": asg,+ "ResourceType": "auto-scaling-group",+ "Key": "Version",+ "Value": "v2",+ "PropagateAtLaunch": True,+ },+ ]+ )+ resp = autoscaling.describe_tags()+ my_tags = [t for t in resp["Tags"] if t["ResourceId"] == asg and t["Key"] == "Version"]+ assert len(my_tags) == 1+ assert my_tags[0]["Value"] == "v2"+ finally:+ autoscaling.delete_tags(+ Tags=[{"ResourceId": asg, "ResourceType": "auto-scaling-group", "Key": "Version"}]+ )+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)+++def test_delete_tags(autoscaling):+ asg = _uid("asg-dtag")+ autoscaling.create_auto_scaling_group(+ AutoScalingGroupName=asg,+ MinSize=0,+ MaxSize=1,+ AvailabilityZones=["us-east-1a"],+ LaunchConfigurationName="dummy-lc",+ )+ try:+ autoscaling.create_or_update_tags(+ Tags=[+ {+ "ResourceId": asg,+ "ResourceType": "auto-scaling-group",+ "Key": "Ephemeral",+ "Value": "yes",+ "PropagateAtLaunch": False,+ },+ ]+ )+ autoscaling.delete_tags(+ Tags=[+ {+ "ResourceId": asg,+ "ResourceType": "auto-scaling-group",+ "Key": "Ephemeral",+ },+ ]+ )+ resp = autoscaling.describe_tags()+ my_tags = [t for t in resp["Tags"] if t["ResourceId"] == asg and t["Key"] == "Ephemeral"]+ assert my_tags == []+ finally:+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)+++def test_tags_reflect_in_asg_describe(autoscaling):+ """Tags added via CreateOrUpdateTags should appear in DescribeAutoScalingGroups."""+ asg = _uid("asg-tagsync")+ autoscaling.create_auto_scaling_group(+ AutoScalingGroupName=asg,+ MinSize=0,+ MaxSize=1,+ AvailabilityZones=["us-east-1a"],+ LaunchConfigurationName="dummy-lc",+ )+ try:+ autoscaling.create_or_update_tags(+ Tags=[+ {+ "ResourceId": asg,+ "ResourceType": "auto-scaling-group",+ "Key": "Sync",+ "Value": "check",+ "PropagateAtLaunch": False,+ },+ ]+ )+ resp = autoscaling.describe_auto_scaling_groups(AutoScalingGroupNames=[asg])+ asg_tags = resp["AutoScalingGroups"][0]["Tags"]+ keys = [t["Key"] for t in asg_tags]+ assert "Sync" in keys+ finally:+ autoscaling.delete_tags(+ Tags=[{"ResourceId": asg, "ResourceType": "auto-scaling-group", "Key": "Sync"}]+ )+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)+++def test_create_asg_with_inline_tags(autoscaling):+ """Tags passed at ASG creation time should be visible."""+ asg = _uid("asg-itag")+ autoscaling.create_auto_scaling_group(+ AutoScalingGroupName=asg,+ MinSize=0,+ MaxSize=1,+ AvailabilityZones=["us-east-1a"],+ LaunchConfigurationName="dummy-lc",+ Tags=[+ {+ "ResourceId": asg,+ "ResourceType": "auto-scaling-group",+ "Key": "Inline",+ "Value": "yes",+ "PropagateAtLaunch": True,+ }+ ],+ )+ try:+ resp = autoscaling.describe_auto_scaling_groups(AutoScalingGroupNames=[asg])+ tags = resp["AutoScalingGroups"][0]["Tags"]+ assert any(t["Key"] == "Inline" and t["Value"] == "yes" for t in tags)++ # Also visible in DescribeTags+ tresp = autoscaling.describe_tags()+ my = [t for t in tresp["Tags"] if t["ResourceId"] == asg and t["Key"] == "Inline"]+ assert len(my) == 1+ finally:+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)+++# ---------------------------------------------------------------------------+# Multiple policies on same ASG+# ---------------------------------------------------------------------------+++def test_multiple_policies_on_same_asg(autoscaling):+ asg = _uid("asg-mpol")+ p1 = _uid("scale-up")+ p2 = _uid("scale-down")+ autoscaling.create_auto_scaling_group(+ AutoScalingGroupName=asg,+ MinSize=0,+ MaxSize=10,+ AvailabilityZones=["us-east-1a"],+ LaunchConfigurationName="dummy-lc",+ )+ try:+ autoscaling.put_scaling_policy(+ AutoScalingGroupName=asg,+ PolicyName=p1,+ AdjustmentType="ChangeInCapacity",+ ScalingAdjustment=2,+ )+ autoscaling.put_scaling_policy(+ AutoScalingGroupName=asg,+ PolicyName=p2,+ AdjustmentType="ChangeInCapacity",+ ScalingAdjustment=-1,+ )+ desc = autoscaling.describe_policies(AutoScalingGroupName=asg)+ names = [p["PolicyName"] for p in desc["ScalingPolicies"]]+ assert p1 in names+ assert p2 in names+ finally:+ autoscaling.delete_policy(AutoScalingGroupName=asg, PolicyName=p1)+ autoscaling.delete_policy(AutoScalingGroupName=asg, PolicyName=p2)+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)+++# ---------------------------------------------------------------------------+# Multiple hooks on same ASG+# ---------------------------------------------------------------------------+++def test_multiple_hooks_on_same_asg(autoscaling):+ asg = _uid("asg-mhook")+ h1 = _uid("launch-hook")+ h2 = _uid("term-hook")+ autoscaling.create_auto_scaling_group(+ AutoScalingGroupName=asg,+ MinSize=0,+ MaxSize=1,+ AvailabilityZones=["us-east-1a"],+ LaunchConfigurationName="dummy-lc",+ )+ try:+ autoscaling.put_lifecycle_hook(+ AutoScalingGroupName=asg,+ LifecycleHookName=h1,+ LifecycleTransition="autoscaling:EC2_INSTANCE_LAUNCHING",+ )+ autoscaling.put_lifecycle_hook(+ AutoScalingGroupName=asg,+ LifecycleHookName=h2,+ LifecycleTransition="autoscaling:EC2_INSTANCE_TERMINATING",+ )+ resp = autoscaling.describe_lifecycle_hooks(AutoScalingGroupName=asg)+ names = [h["LifecycleHookName"] for h in resp["LifecycleHooks"]]+ assert h1 in names+ assert h2 in names+ finally:+ autoscaling.delete_lifecycle_hook(AutoScalingGroupName=asg, LifecycleHookName=h1)+ autoscaling.delete_lifecycle_hook(AutoScalingGroupName=asg, LifecycleHookName=h2)+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)+++# ---------------------------------------------------------------------------+# Multiple scheduled actions on same ASG+# ---------------------------------------------------------------------------+++def test_multiple_scheduled_actions(autoscaling):+ asg = _uid("asg-msched")+ a1 = _uid("morning")+ a2 = _uid("evening")+ autoscaling.create_auto_scaling_group(+ AutoScalingGroupName=asg,+ MinSize=0,+ MaxSize=10,+ AvailabilityZones=["us-east-1a"],+ LaunchConfigurationName="dummy-lc",+ )+ try:+ autoscaling.put_scheduled_update_group_action(+ AutoScalingGroupName=asg,+ ScheduledActionName=a1,+ Recurrence="0 8 * * *",+ MinSize=5,+ MaxSize=10,+ )+ autoscaling.put_scheduled_update_group_action(+ AutoScalingGroupName=asg,+ ScheduledActionName=a2,+ Recurrence="0 20 * * *",+ MinSize=1,+ MaxSize=3,+ )+ resp = autoscaling.describe_scheduled_actions(AutoScalingGroupName=asg)+ names = [a["ScheduledActionName"] for a in resp["ScheduledUpdateGroupActions"]]+ assert a1 in names+ assert a2 in names+ finally:+ autoscaling.delete_scheduled_action(AutoScalingGroupName=asg, ScheduledActionName=a1)+ autoscaling.delete_scheduled_action(AutoScalingGroupName=asg, ScheduledActionName=a2)+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)+++# ---------------------------------------------------------------------------+# ASG with launch template reference+# ---------------------------------------------------------------------------+++def test_create_asg_with_launch_template(autoscaling):+ asg = _uid("asg-lt")+ autoscaling.create_auto_scaling_group(+ AutoScalingGroupName=asg,+ MinSize=0,+ MaxSize=1,+ AvailabilityZones=["us-east-1a"],+ LaunchTemplate={+ "LaunchTemplateName": "my-template",+ "Version": "$Latest",+ },+ )+ try:+ resp = autoscaling.describe_auto_scaling_groups(AutoScalingGroupNames=[asg])+ g = resp["AutoScalingGroups"][0]+ lt = g.get("LaunchTemplate", {})+ assert lt.get("LaunchTemplateName") == "my-template"+ assert lt.get("Version") == "$Latest"+ finally:+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)diff --git a/tests/test_cloudwatch.py b/tests/test_cloudwatch.pyindex 3ee9a69e..dadb026a 100644--- a/tests/test_cloudwatch.py+++ b/tests/test_cloudwatch.py@@ -387,3 +387,45 @@ def test_cloudwatch_put_metric_data_statistics_values(cw):resp = cw.list_metrics(Namespace="qa/cw-multi")assert any(m["MetricName"] == "Latency" for m in resp["Metrics"])++def test_cloudwatch_enable_alarm_actions(cw):+ cw.put_metric_alarm(+ AlarmName="heimdall-enable-actions",+ MetricName="M",+ Namespace="N",+ Statistic="Sum",+ Period=60,+ EvaluationPeriods=1,+ Threshold=1.0,+ ComparisonOperator="GreaterThanThreshold",+ ActionsEnabled=False,+ )+ alarm = cw.describe_alarms(AlarmNames=["heimdall-enable-actions"])["MetricAlarms"][0]+ assert alarm["ActionsEnabled"] is False++ cw.enable_alarm_actions(AlarmNames=["heimdall-enable-actions"])+ alarm = cw.describe_alarms(AlarmNames=["heimdall-enable-actions"])["MetricAlarms"][0]+ assert alarm["ActionsEnabled"] is True+ cw.delete_alarms(AlarmNames=["heimdall-enable-actions"])+++def test_cloudwatch_disable_alarm_actions(cw):+ cw.put_metric_alarm(+ AlarmName="heimdall-disable-actions",+ MetricName="M",+ Namespace="N",+ Statistic="Sum",+ Period=60,+ EvaluationPeriods=1,+ Threshold=1.0,+ ComparisonOperator="GreaterThanThreshold",+ ActionsEnabled=True,+ )+ alarm = cw.describe_alarms(AlarmNames=["heimdall-disable-actions"])["MetricAlarms"][0]+ assert alarm["ActionsEnabled"] is True++ cw.disable_alarm_actions(AlarmNames=["heimdall-disable-actions"])+ alarm = cw.describe_alarms(AlarmNames=["heimdall-disable-actions"])["MetricAlarms"][0]+ assert alarm["ActionsEnabled"] is False+ cw.delete_alarms(AlarmNames=["heimdall-disable-actions"])+diff --git a/tests/test_ebs.py b/tests/test_ebs.pyindex 4fc87cce..30ad1744 100644--- a/tests/test_ebs.py+++ b/tests/test_ebs.py@@ -131,3 +131,21 @@ def test_ebs_describe_volumes_modifications(ebs):assert mods[0]["VolumeId"] == vol_idassert mods[0]["TargetSize"] == 50assert mods[0]["TargetVolumeType"] == "gp3"+++def test_ebs_enable_volume_io(ebs):+ vol = ebs.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")+ vol_id = vol["VolumeId"]+ ebs.enable_volume_io(VolumeId=vol_id)+ # Stub — just verify it doesn't error+ resp = ebs.describe_volume_attribute(VolumeId=vol_id, Attribute="autoEnableIO")+ assert resp["VolumeId"] == vol_id+++def test_ebs_modify_volume_attribute(ebs):+ vol = ebs.create_volume(AvailabilityZone="us-east-1a", Size=10, VolumeType="gp2")+ vol_id = vol["VolumeId"]+ ebs.modify_volume_attribute(VolumeId=vol_id, AutoEnableIO={"Value": True})+ # Stub — just verify it doesn't error+ resp = ebs.describe_volume_attribute(VolumeId=vol_id, Attribute="autoEnableIO")+ assert resp["VolumeId"] == vol_iddiff --git a/tests/test_efs.py b/tests/test_efs.pyindex 8f9f2e38..01f306d5 100644--- a/tests/test_efs.py+++ b/tests/test_efs.py@@ -118,3 +118,80 @@ def test_efs_backup_policy(efs):)resp = efs.describe_backup_policy(FileSystemId=fs_id)assert resp["BackupPolicy"]["Status"] == "ENABLED"++def _uid():+ return _uuid_mod.uuid4().hex[:8]++def test_efs_update_file_system(efs):+ fs = efs.create_file_system(+ CreationToken=f"update-fs-{_uid()}",+ ThroughputMode="bursting",+ )+ fs_id = fs["FileSystemId"]+ assert fs["ThroughputMode"] == "bursting"++ resp = efs.update_file_system(+ FileSystemId=fs_id,+ ThroughputMode="provisioned",+ ProvisionedThroughputInMibps=256.0,+ )+ assert resp["ThroughputMode"] == "provisioned"+ assert resp["ProvisionedThroughputInMibps"] == 256.0++ desc = efs.describe_file_systems(FileSystemId=fs_id)+ updated = desc["FileSystems"][0]+ assert updated["ThroughputMode"] == "provisioned"+ assert updated["ProvisionedThroughputInMibps"] == 256.0++ efs.delete_file_system(FileSystemId=fs_id)++def test_efs_describe_mount_target_security_groups(efs):+ fs = efs.create_file_system(CreationToken=f"sg-desc-{_uid()}")+ fs_id = fs["FileSystemId"]+ mt = efs.create_mount_target(+ FileSystemId=fs_id,+ SubnetId="subnet-00000001",+ SecurityGroups=["sg-aaa111aaa", "sg-bbb222bbb"],+ )+ mt_id = mt["MountTargetId"]++ resp = efs.describe_mount_target_security_groups(MountTargetId=mt_id)+ assert set(resp["SecurityGroups"]) == {"sg-aaa111aaa", "sg-bbb222bbb"}++ efs.delete_mount_target(MountTargetId=mt_id)+ efs.delete_file_system(FileSystemId=fs_id)++def test_efs_modify_mount_target_security_groups(efs):+ fs = efs.create_file_system(CreationToken=f"sg-mod-{_uid()}")+ fs_id = fs["FileSystemId"]+ mt = efs.create_mount_target(+ FileSystemId=fs_id,+ SubnetId="subnet-00000001",+ SecurityGroups=["sg-old111old"],+ )+ mt_id = mt["MountTargetId"]++ efs.modify_mount_target_security_groups(+ MountTargetId=mt_id,+ SecurityGroups=["sg-new111new", "sg-new222new"],+ )++ resp = efs.describe_mount_target_security_groups(MountTargetId=mt_id)+ assert set(resp["SecurityGroups"]) == {"sg-new111new", "sg-new222new"}++ efs.delete_mount_target(MountTargetId=mt_id)+ efs.delete_file_system(FileSystemId=fs_id)++def test_efs_describe_account_preferences(efs):+ resp = efs.describe_account_preferences()+ pref = resp["ResourceIdPreference"]+ assert "ResourceIdType" in pref+ assert "Resources" in pref+ assert isinstance(pref["Resources"], list)++def test_efs_put_account_preferences(efs):+ resp = efs.put_account_preferences(ResourceIdType="LONG_ID")+ pref = resp["ResourceIdPreference"]+ assert pref["ResourceIdType"] == "LONG_ID"+ assert "FILE_SYSTEM" in pref["Resources"]+ assert "MOUNT_TARGET" in pref["Resources"]diff --git a/tests/test_eks.py b/tests/test_eks.pyindex f101b24b..d535b4da 100644--- a/tests/test_eks.py+++ b/tests/test_eks.py@@ -223,15 +223,24 @@ def test_eks_cfn_cluster(cfn, eks):})stack_name = f"eks-stack-{uid}"cfn.create_stack(StackName=stack_name, TemplateBody=template)- time.sleep(3)- stack = cfn.describe_stacks(StackName=stack_name)["Stacks"][0]+ # Poll for stack creation — stack is stored synchronously but deploy+ # runs as an async task, so describe_stacks may briefly not find it+ # if the event loop hasn't yielded yet.+ stack = None+ for _ in range(30):+ try:+ stack = cfn.describe_stacks(StackName=stack_name)["Stacks"][0]+ if stack["StackStatus"] not in ("CREATE_IN_PROGRESS",):+ break+ except Exception:+ pass+ time.sleep(1)+ assert stack is not None, f"Stack {stack_name} never appeared"assert stack["StackStatus"] == "CREATE_COMPLETE"- # Verify via EKS APIresp = eks.describe_cluster(name=cluster_name)assert resp["cluster"]["name"] == cluster_name- assert resp["cluster"]["status"] == "ACTIVE"cfn.delete_stack(StackName=stack_name)time.sleep(2)diff --git a/tests/test_elasticache.py b/tests/test_elasticache.pyindex b5da7931..4e1a509a 100644--- a/tests/test_elasticache.py+++ b/tests/test_elasticache.py@@ -265,3 +265,380 @@ def test_elasticache_modify_cache_parameter_group(ec):assert maxmem is not Noneassert maxmem["ParameterValue"] == "allkeys-lru"++def _uid():+ return _uuid_mod.uuid4().hex[:8]+++# ---------------------------------------------------------------------------+# 1. ModifyCacheCluster+# ---------------------------------------------------------------------------++def test_modify_cache_cluster_num_nodes(ec):+ """ModifyCacheCluster: scale NumCacheNodes up and down."""+ cid = f"mod-cc-{_uid()}"+ ec.create_cache_cluster(+ CacheClusterId=cid,+ Engine="redis",+ CacheNodeType="cache.t3.micro",+ NumCacheNodes=1,+ )+ # scale up+ resp = ec.modify_cache_cluster(CacheClusterId=cid, NumCacheNodes=3)+ cluster = resp["CacheCluster"]+ assert cluster["NumCacheNodes"] == 3+ assert len(cluster["CacheNodes"]) == 3++ # scale down+ resp = ec.modify_cache_cluster(CacheClusterId=cid, NumCacheNodes=2)+ cluster = resp["CacheCluster"]+ assert cluster["NumCacheNodes"] == 2+ assert len(cluster["CacheNodes"]) == 2++ ec.delete_cache_cluster(CacheClusterId=cid)+++def test_modify_cache_cluster_node_type_and_engine(ec):+ """ModifyCacheCluster: update CacheNodeType and EngineVersion."""+ cid = f"mod-nt-{_uid()}"+ ec.create_cache_cluster(+ CacheClusterId=cid,+ Engine="redis",+ CacheNodeType="cache.t3.micro",+ NumCacheNodes=1,+ )+ resp = ec.modify_cache_cluster(+ CacheClusterId=cid,+ CacheNodeType="cache.m5.large",+ EngineVersion="7.1.0",+ )+ cluster = resp["CacheCluster"]+ assert cluster["CacheNodeType"] == "cache.m5.large"+ assert cluster["EngineVersion"] == "7.1.0"++ ec.delete_cache_cluster(CacheClusterId=cid)+++# ---------------------------------------------------------------------------+# 2. RebootCacheCluster+# ---------------------------------------------------------------------------++def test_reboot_cache_cluster(ec):+ """RebootCacheCluster: reboot and verify cluster stays available."""+ cid = f"reboot-{_uid()}"+ ec.create_cache_cluster(+ CacheClusterId=cid,+ Engine="redis",+ CacheNodeType="cache.t3.micro",+ NumCacheNodes=1,+ )+ resp = ec.reboot_cache_cluster(+ CacheClusterId=cid,+ CacheNodeIdsToReboot=["0001"],+ )+ cluster = resp["CacheCluster"]+ assert cluster["CacheClusterId"] == cid+ assert cluster["CacheClusterStatus"] == "available"++ ec.delete_cache_cluster(CacheClusterId=cid)+++# ---------------------------------------------------------------------------+# 3. DeleteReplicationGroup+# ---------------------------------------------------------------------------++def test_delete_replication_group(ec):+ """DeleteReplicationGroup: create then delete, verify gone."""+ rg_id = f"del-rg-{_uid()}"+ ec.create_replication_group(+ ReplicationGroupId=rg_id,+ ReplicationGroupDescription="To be deleted",+ CacheNodeType="cache.t3.micro",+ )+ # verify exists+ resp = ec.describe_replication_groups(ReplicationGroupId=rg_id)+ assert len(resp["ReplicationGroups"]) == 1++ # delete+ ec.delete_replication_group(ReplicationGroupId=rg_id)++ # verify gone+ with pytest.raises(ClientError) as exc:+ ec.describe_replication_groups(ReplicationGroupId=rg_id)+ assert "ReplicationGroupNotFoundFault" in str(exc.value)+++# ---------------------------------------------------------------------------+# 4. ModifyReplicationGroup+# ---------------------------------------------------------------------------++def test_modify_replication_group(ec):+ """ModifyReplicationGroup: update description and CacheNodeType."""+ rg_id = f"mod-rg-{_uid()}"+ ec.create_replication_group(+ ReplicationGroupId=rg_id,+ ReplicationGroupDescription="Original desc",+ CacheNodeType="cache.t3.micro",+ )+ resp = ec.modify_replication_group(+ ReplicationGroupId=rg_id,+ ReplicationGroupDescription="Updated desc",+ CacheNodeType="cache.m5.large",+ )+ rg = resp["ReplicationGroup"]+ assert rg["Description"] == "Updated desc"+ assert rg["CacheNodeType"] == "cache.m5.large"++ ec.delete_replication_group(ReplicationGroupId=rg_id)+++# ---------------------------------------------------------------------------+# 5. IncreaseReplicaCount+# ---------------------------------------------------------------------------++def test_increase_replica_count(ec):+ """IncreaseReplicaCount: scale replicas up from 1 to 3."""+ rg_id = f"inc-rep-{_uid()}"+ ec.create_replication_group(+ ReplicationGroupId=rg_id,+ ReplicationGroupDescription="Scale up test",+ CacheNodeType="cache.t3.micro",+ NumNodeGroups=1,+ ReplicasPerNodeGroup=1,+ )+ # verify initial: 1 primary + 1 replica = 2 members+ desc = ec.describe_replication_groups(ReplicationGroupId=rg_id)+ initial_members = len(desc["ReplicationGroups"][0]["NodeGroups"][0]["NodeGroupMembers"])+ assert initial_members == 2++ resp = ec.increase_replica_count(+ ReplicationGroupId=rg_id,+ NewReplicaCount=3,+ ApplyImmediately=True,+ )+ rg = resp["ReplicationGroup"]+ # 1 primary + 3 replicas = 4 members+ assert len(rg["NodeGroups"][0]["NodeGroupMembers"]) == 4++ ec.delete_replication_group(ReplicationGroupId=rg_id)+++# ---------------------------------------------------------------------------+# 6. DecreaseReplicaCount+# ---------------------------------------------------------------------------++def test_decrease_replica_count(ec):+ """DecreaseReplicaCount: scale replicas down from 3 to 1."""+ rg_id = f"dec-rep-{_uid()}"+ ec.create_replication_group(+ ReplicationGroupId=rg_id,+ ReplicationGroupDescription="Scale down test",+ CacheNodeType="cache.t3.micro",+ NumNodeGroups=1,+ ReplicasPerNodeGroup=3,+ )+ # verify initial: 1 primary + 3 replicas = 4 members+ desc = ec.describe_replication_groups(ReplicationGroupId=rg_id)+ assert len(desc["ReplicationGroups"][0]["NodeGroups"][0]["NodeGroupMembers"]) == 4++ resp = ec.decrease_replica_count(+ ReplicationGroupId=rg_id,+ NewReplicaCount=1,+ ApplyImmediately=True,+ )+ rg = resp["ReplicationGroup"]+ # 1 primary + 1 replica = 2 members+ assert len(rg["NodeGroups"][0]["NodeGroupMembers"]) == 2++ ec.delete_replication_group(ReplicationGroupId=rg_id)+++# ---------------------------------------------------------------------------+# 7. DeleteCacheSubnetGroup+# ---------------------------------------------------------------------------++def test_delete_cache_subnet_group(ec):+ """DeleteCacheSubnetGroup: create then delete, verify gone."""+ name = f"del-sg-{_uid()}"+ ec.create_cache_subnet_group(+ CacheSubnetGroupName=name,+ CacheSubnetGroupDescription="To be deleted",+ SubnetIds=["subnet-aaa"],+ )+ # verify exists+ resp = ec.describe_cache_subnet_groups(CacheSubnetGroupName=name)+ assert len(resp["CacheSubnetGroups"]) == 1++ # delete+ ec.delete_cache_subnet_group(CacheSubnetGroupName=name)++ # verify gone+ with pytest.raises(ClientError) as exc:+ ec.describe_cache_subnet_groups(CacheSubnetGroupName=name)+ assert "CacheSubnetGroupNotFoundFault" in str(exc.value)+++# ---------------------------------------------------------------------------+# 8. ResetCacheParameterGroup+# ---------------------------------------------------------------------------++def test_reset_cache_parameter_group_full(ec):+ """ResetCacheParameterGroup: full reset restores defaults."""+ pg = f"reset-full-{_uid()}"+ ec.create_cache_parameter_group(+ CacheParameterGroupName=pg,+ CacheParameterGroupFamily="redis7.0",+ Description="Full reset test",+ )+ # modify a parameter away from default+ ec.modify_cache_parameter_group(+ CacheParameterGroupName=pg,+ ParameterNameValues=[{"ParameterName": "maxmemory-policy", "ParameterValue": "allkeys-lru"}],+ )+ params = ec.describe_cache_parameters(CacheParameterGroupName=pg)["Parameters"]+ maxmem = next(p for p in params if p["ParameterName"] == "maxmemory-policy")+ assert maxmem["ParameterValue"] == "allkeys-lru"++ # full reset+ ec.reset_cache_parameter_group(+ CacheParameterGroupName=pg,+ ResetAllParameters=True,+ )+ params = ec.describe_cache_parameters(CacheParameterGroupName=pg)["Parameters"]+ maxmem = next(p for p in params if p["ParameterName"] == "maxmemory-policy")+ assert maxmem["ParameterValue"] == "volatile-lru"++ ec.delete_cache_parameter_group(CacheParameterGroupName=pg)+++def test_reset_cache_parameter_group_selective(ec):+ """ResetCacheParameterGroup: selective reset of specific parameter."""+ pg = f"reset-sel-{_uid()}"+ ec.create_cache_parameter_group(+ CacheParameterGroupName=pg,+ CacheParameterGroupFamily="redis7.0",+ Description="Selective reset test",+ )+ # modify two parameters+ ec.modify_cache_parameter_group(+ CacheParameterGroupName=pg,+ ParameterNameValues=[+ {"ParameterName": "maxmemory-policy", "ParameterValue": "allkeys-lru"},+ {"ParameterName": "timeout", "ParameterValue": "300"},+ ],+ )+ # selective reset only maxmemory-policy+ ec.reset_cache_parameter_group(+ CacheParameterGroupName=pg,+ ResetAllParameters=False,+ ParameterNameValues=[{"ParameterName": "maxmemory-policy", "ParameterValue": ""}],+ )+ params = ec.describe_cache_parameters(CacheParameterGroupName=pg)["Parameters"]+ maxmem = next(p for p in params if p["ParameterName"] == "maxmemory-policy")+ timeout_p = next(p for p in params if p["ParameterName"] == "timeout")+ # maxmemory-policy should be back to default+ assert maxmem["ParameterValue"] == "volatile-lru"+ # timeout should still have the modified value+ assert timeout_p["ParameterValue"] == "300"++ ec.delete_cache_parameter_group(CacheParameterGroupName=pg)+++# ---------------------------------------------------------------------------+# 9. DeleteSnapshot (explicit)+# ---------------------------------------------------------------------------++def test_delete_snapshot_explicit(ec):+ """DeleteSnapshot: create snapshot, delete it, verify gone."""+ cid = f"snap-del-{_uid()}"+ snap_name = f"snap-{_uid()}"+ ec.create_cache_cluster(+ CacheClusterId=cid,+ Engine="redis",+ CacheNodeType="cache.t3.micro",+ NumCacheNodes=1,+ )+ ec.create_snapshot(SnapshotName=snap_name, CacheClusterId=cid)++ # verify exists+ resp = ec.describe_snapshots(SnapshotName=snap_name)+ assert len(resp["Snapshots"]) == 1++ # delete+ del_resp = ec.delete_snapshot(SnapshotName=snap_name)+ assert del_resp["Snapshot"]["SnapshotStatus"] == "deleting"++ # verify gone+ resp = ec.describe_snapshots(SnapshotName=snap_name)+ assert len(resp["Snapshots"]) == 0++ ec.delete_cache_cluster(CacheClusterId=cid)+++# ---------------------------------------------------------------------------+# 10. DescribeEvents+# ---------------------------------------------------------------------------++def test_describe_events_all(ec):+ """DescribeEvents: listing all events returns results."""+ # create a cluster to generate at least one event+ cid = f"evt-all-{_uid()}"+ ec.create_cache_cluster(+ CacheClusterId=cid,+ Engine="redis",+ CacheNodeType="cache.t3.micro",+ NumCacheNodes=1,+ )+ resp = ec.describe_events()+ assert "Events" in resp+ assert len(resp["Events"]) > 0++ ec.delete_cache_cluster(CacheClusterId=cid)+++def test_describe_events_filter_source_type(ec):+ """DescribeEvents: filter by SourceType."""+ rg_id = f"evt-rg-{_uid()}"+ ec.create_replication_group(+ ReplicationGroupId=rg_id,+ ReplicationGroupDescription="Event filter test",+ CacheNodeType="cache.t3.micro",+ )+ resp = ec.describe_events(SourceType="replication-group")+ assert "Events" in resp+ # all returned events should be replication-group type+ for evt in resp["Events"]:+ assert evt["SourceType"] == "replication-group"++ ec.delete_replication_group(ReplicationGroupId=rg_id)+++def test_describe_events_filter_source_id(ec):+ """DescribeEvents: filter by SourceIdentifier."""+ cid = f"evt-src-{_uid()}"+ ec.create_cache_cluster(+ CacheClusterId=cid,+ Engine="redis",+ CacheNodeType="cache.t3.micro",+ NumCacheNodes=1,+ )+ resp = ec.describe_events(SourceIdentifier=cid)+ assert "Events" in resp+ for evt in resp["Events"]:+ assert evt["SourceIdentifier"] == cid++ ec.delete_cache_cluster(CacheClusterId=cid)+++# ---------------------------------------------------------------------------+# 11. Serverless cache operations — not implemented in MiniStack+# ---------------------------------------------------------------------------++def test_serverless_cache_not_implemented(ec):+ """Serverless cache operations are not yet implemented; verify graceful error."""+ with pytest.raises(ClientError):+ ec.create_serverless_cache(+ ServerlessCacheName="test-serverless",+ Engine="redis",+ )+diff --git a/tests/test_emr.py b/tests/test_emr.pyindex c82e55da..3be0d5c1 100644--- a/tests/test_emr.py+++ b/tests/test_emr.py@@ -320,3 +320,228 @@ def test_emr_instance_fleets(emr):assert "CORE" in fleet_typesemr.terminate_job_flows(JobFlowIds=[cluster_id])+++def test_emr_set_visible_to_all_users(emr):+ """SetVisibleToAllUsers toggles visibility on and off."""+ jf = emr.run_job_flow(+ Name="visible-test",+ ReleaseLabel="emr-6.10.0",+ Instances={+ "MasterInstanceType": "m5.xlarge",+ "InstanceCount": 1,+ "KeepJobFlowAliveWhenNoSteps": True,+ },+ JobFlowRole="EMR_EC2_DefaultRole",+ ServiceRole="EMR_DefaultRole",+ )+ cluster_id = jf["JobFlowId"]++ # Default is visible+ desc = emr.describe_cluster(ClusterId=cluster_id)+ assert desc["Cluster"]["VisibleToAllUsers"] is True++ # Set to False+ emr.set_visible_to_all_users(JobFlowIds=[cluster_id], VisibleToAllUsers=False)+ desc = emr.describe_cluster(ClusterId=cluster_id)+ assert desc["Cluster"]["VisibleToAllUsers"] is False++ # Set back to True+ emr.set_visible_to_all_users(JobFlowIds=[cluster_id], VisibleToAllUsers=True)+ desc = emr.describe_cluster(ClusterId=cluster_id)+ assert desc["Cluster"]["VisibleToAllUsers"] is True++ emr.terminate_job_flows(JobFlowIds=[cluster_id])+++def test_emr_cancel_steps(emr):+ """CancelSteps returns info list for each requested step."""+ jf = emr.run_job_flow(+ Name="cancel-steps-test",+ ReleaseLabel="emr-6.10.0",+ Instances={+ "MasterInstanceType": "m5.xlarge",+ "InstanceCount": 1,+ "KeepJobFlowAliveWhenNoSteps": True,+ },+ JobFlowRole="EMR_EC2_DefaultRole",+ ServiceRole="EMR_DefaultRole",+ )+ cluster_id = jf["JobFlowId"]++ step_resp = emr.add_job_flow_steps(+ JobFlowId=cluster_id,+ Steps=[+ {+ "Name": "cancel-me",+ "ActionOnFailure": "CONTINUE",+ "HadoopJarStep": {"Jar": "command-runner.jar", "Args": ["echo", "hi"]},+ },+ {+ "Name": "cancel-me-too",+ "ActionOnFailure": "CONTINUE",+ "HadoopJarStep": {"Jar": "command-runner.jar", "Args": ["echo", "bye"]},+ },+ ],+ )+ step_ids = step_resp["StepIds"]+ assert len(step_ids) == 2++ # Steps are already COMPLETED in ministack, so cancel returns FAILED_TO_CANCEL+ cancel_resp = emr.cancel_steps(ClusterId=cluster_id, StepIds=step_ids)+ info_list = cancel_resp["CancelStepsInfoList"]+ assert len(info_list) == 2+ for info in info_list:+ assert info["StepId"] in step_ids+ assert info["Status"] == "FAILED_TO_CANCEL"+ assert "Reason" in info++ emr.terminate_job_flows(JobFlowIds=[cluster_id])+++def test_emr_modify_instance_fleet(emr):+ """ModifyInstanceFleet updates on-demand/spot capacity."""+ jf = emr.run_job_flow(+ Name="modify-fleet-test",+ ReleaseLabel="emr-6.15.0",+ Instances={+ "KeepJobFlowAliveWhenNoSteps": True,+ "InstanceFleets": [+ {+ "InstanceFleetType": "MASTER",+ "Name": "master-fleet",+ "TargetOnDemandCapacity": 1,+ "InstanceTypeConfigs": [{"InstanceType": "m5.xlarge"}],+ },+ ],+ },+ JobFlowRole="EMR_EC2_DefaultRole",+ ServiceRole="EMR_DefaultRole",+ )+ cluster_id = jf["JobFlowId"]++ # Add a CORE fleet to modify+ add_resp = emr.add_instance_fleet(+ ClusterId=cluster_id,+ InstanceFleet={+ "InstanceFleetType": "CORE",+ "Name": "core-fleet",+ "TargetOnDemandCapacity": 2,+ "InstanceTypeConfigs": [{"InstanceType": "m5.xlarge"}],+ },+ )+ fleet_id = add_resp["InstanceFleetId"]++ # Modify capacity+ emr.modify_instance_fleet(+ ClusterId=cluster_id,+ InstanceFleet={+ "InstanceFleetId": fleet_id,+ "TargetOnDemandCapacity": 5,+ "TargetSpotCapacity": 3,+ },+ )++ # Verify the modification+ fleets = emr.list_instance_fleets(ClusterId=cluster_id)+ core_fleet = [f for f in fleets["InstanceFleets"] if f["Id"] == fleet_id][0]+ assert core_fleet["TargetOnDemandCapacity"] == 5+ assert core_fleet["TargetSpotCapacity"] == 3+ assert core_fleet["ProvisionedOnDemandCapacity"] == 5+ assert core_fleet["ProvisionedSpotCapacity"] == 3++ emr.terminate_job_flows(JobFlowIds=[cluster_id])+++def test_emr_modify_instance_groups(emr):+ """ModifyInstanceGroups updates instance counts."""+ jf = emr.run_job_flow(+ Name="modify-groups-test",+ ReleaseLabel="emr-6.10.0",+ Instances={+ "InstanceGroups": [+ {+ "Name": "Master",+ "InstanceRole": "MASTER",+ "InstanceType": "m5.xlarge",+ "InstanceCount": 1,+ },+ {+ "Name": "Core",+ "InstanceRole": "CORE",+ "InstanceType": "m5.xlarge",+ "InstanceCount": 2,+ },+ ],+ "KeepJobFlowAliveWhenNoSteps": True,+ },+ JobFlowRole="EMR_EC2_DefaultRole",+ ServiceRole="EMR_DefaultRole",+ )+ cluster_id = jf["JobFlowId"]++ # Find the CORE group id+ groups = emr.list_instance_groups(ClusterId=cluster_id)+ core_group = [g for g in groups["InstanceGroups"] if g["InstanceGroupType"] == "CORE"][0]+ group_id = core_group["Id"]+ assert core_group["RequestedInstanceCount"] == 2++ # Modify the group count+ emr.modify_instance_groups(+ ClusterId=cluster_id,+ InstanceGroups=[{"InstanceGroupId": group_id, "InstanceCount": 6}],+ )++ # Verify the modification+ groups2 = emr.list_instance_groups(ClusterId=cluster_id)+ core_group2 = [g for g in groups2["InstanceGroups"] if g["Id"] == group_id][0]+ assert core_group2["RequestedInstanceCount"] == 6+ assert core_group2["RunningInstanceCount"] == 6++ emr.terminate_job_flows(JobFlowIds=[cluster_id])+++def test_emr_list_bootstrap_actions(emr):+ """ListBootstrapActions returns actions created with the cluster."""+ jf = emr.run_job_flow(+ Name="bootstrap-test",+ ReleaseLabel="emr-6.10.0",+ Instances={+ "MasterInstanceType": "m5.xlarge",+ "InstanceCount": 1,+ "KeepJobFlowAliveWhenNoSteps": True,+ },+ JobFlowRole="EMR_EC2_DefaultRole",+ ServiceRole="EMR_DefaultRole",+ BootstrapActions=[+ {+ "Name": "install-deps",+ "ScriptBootstrapAction": {+ "Path": "s3://my-bucket/bootstrap/install.sh",+ "Args": ["--env", "prod"],+ },+ },+ {+ "Name": "setup-monitoring",+ "ScriptBootstrapAction": {+ "Path": "s3://my-bucket/bootstrap/monitor.sh",+ "Args": [],+ },+ },+ ],+ )+ cluster_id = jf["JobFlowId"]++ actions = emr.list_bootstrap_actions(ClusterId=cluster_id)+ ba_list = actions["BootstrapActions"]+ assert len(ba_list) == 2++ assert ba_list[0]["Name"] == "install-deps"+ assert ba_list[0]["ScriptPath"] == "s3://my-bucket/bootstrap/install.sh"+ assert ba_list[0]["Args"] == ["--env", "prod"]++ assert ba_list[1]["Name"] == "setup-monitoring"+ assert ba_list[1]["ScriptPath"] == "s3://my-bucket/bootstrap/monitor.sh"+ assert ba_list[1]["Args"] == []++ emr.terminate_job_flows(JobFlowIds=[cluster_id])diff --git a/tests/test_glue.py b/tests/test_glue.pyindex da808fc2..870795f0 100644--- a/tests/test_glue.py+++ b/tests/test_glue.py@@ -384,3 +384,517 @@ def test_glue_duplicate_partition_error(glue):PartitionInput=part_input,)assert exc.value.response["Error"]["Code"] == "AlreadyExistsException"+++# ---------------------------------------------------------------------------+# BatchDeleteTable+# ---------------------------------------------------------------------------++def test_glue_batch_delete_table(glue):+ db = "qa-bdt-db"+ glue.create_database(DatabaseInput={"Name": db})+ for t in ("tbl_a", "tbl_b", "tbl_c"):+ glue.create_table(+ DatabaseName=db,+ TableInput={+ "Name": t,+ "StorageDescriptor": {+ "Columns": [{"Name": "c", "Type": "string"}],+ "Location": f"s3://b/{t}/",+ "InputFormat": "TIF",+ "OutputFormat": "TOF",+ "SerdeInfo": {"SerializationLibrary": "SL"},+ },+ },+ )+ resp = glue.batch_delete_table(DatabaseName=db, TablesToDelete=["tbl_a", "tbl_b", "no_such"])+ errors = resp.get("Errors", [])+ assert len(errors) == 1+ assert errors[0]["TableName"] == "no_such"+ tables = glue.get_tables(DatabaseName=db)+ names = [t["Name"] for t in tables["TableList"]]+ assert "tbl_a" not in names+ assert "tbl_b" not in names+ assert "tbl_c" in names+ # cleanup+ glue.delete_table(DatabaseName=db, Name="tbl_c")+ glue.delete_database(Name=db)+++# ---------------------------------------------------------------------------+# BatchGetPartition+# ---------------------------------------------------------------------------++def test_glue_batch_get_partition(glue):+ db = "qa-bgp-db"+ tbl = "qa-bgp-tbl"+ glue.create_database(DatabaseInput={"Name": db})+ glue.create_table(+ DatabaseName=db,+ TableInput={+ "Name": tbl,+ "StorageDescriptor": {+ "Columns": [],+ "Location": "s3://b/k",+ "InputFormat": "",+ "OutputFormat": "",+ "SerdeInfo": {},+ },+ "PartitionKeys": [{"Name": "dt", "Type": "string"}],+ },+ )+ for val in ("2024-01", "2024-02"):+ glue.create_partition(+ DatabaseName=db,+ TableName=tbl,+ PartitionInput={+ "Values": [val],+ "StorageDescriptor": {+ "Columns": [],+ "Location": f"s3://b/k/dt={val}",+ "InputFormat": "",+ "OutputFormat": "",+ "SerdeInfo": {},+ },+ },+ )+ resp = glue.batch_get_partition(+ DatabaseName=db,+ TableName=tbl,+ PartitionsToGet=[+ {"Values": ["2024-01"]},+ {"Values": ["2024-02"]},+ {"Values": ["no-such"]},+ ],+ )+ assert len(resp["Partitions"]) == 2+ assert len(resp["UnprocessedKeys"]) == 1+ assert resp["UnprocessedKeys"][0]["Values"] == ["no-such"]+ # cleanup+ glue.delete_table(DatabaseName=db, Name=tbl)+ glue.delete_database(Name=db)+++# ---------------------------------------------------------------------------+# BatchCreatePartition+# ---------------------------------------------------------------------------++def test_glue_batch_create_partition(glue):+ db = "qa-bcp-db"+ tbl = "qa-bcp-tbl"+ glue.create_database(DatabaseInput={"Name": db})+ glue.create_table(+ DatabaseName=db,+ TableInput={+ "Name": tbl,+ "StorageDescriptor": {+ "Columns": [],+ "Location": "s3://b/k",+ "InputFormat": "",+ "OutputFormat": "",+ "SerdeInfo": {},+ },+ "PartitionKeys": [{"Name": "dt", "Type": "string"}],+ },+ )+ resp = glue.batch_create_partition(+ DatabaseName=db,+ TableName=tbl,+ PartitionInputList=[+ {+ "Values": ["2024-03"],+ "StorageDescriptor": {+ "Columns": [],+ "Location": "s3://b/k/dt=2024-03",+ "InputFormat": "",+ "OutputFormat": "",+ "SerdeInfo": {},+ },+ },+ {+ "Values": ["2024-04"],+ "StorageDescriptor": {+ "Columns": [],+ "Location": "s3://b/k/dt=2024-04",+ "InputFormat": "",+ "OutputFormat": "",+ "SerdeInfo": {},+ },+ },+ ],+ )+ assert resp.get("Errors", []) == []+ parts = glue.get_partitions(DatabaseName=db, TableName=tbl)["Partitions"]+ assert len(parts) == 2+ # duplicate insert returns error+ resp2 = glue.batch_create_partition(+ DatabaseName=db,+ TableName=tbl,+ PartitionInputList=[+ {+ "Values": ["2024-03"],+ "StorageDescriptor": {+ "Columns": [],+ "Location": "s3://b/k/dt=2024-03",+ "InputFormat": "",+ "OutputFormat": "",+ "SerdeInfo": {},+ },+ },+ ],+ )+ assert len(resp2["Errors"]) == 1+ assert resp2["Errors"][0]["ErrorDetail"]["ErrorCode"] == "AlreadyExistsException"+ # cleanup+ glue.delete_table(DatabaseName=db, Name=tbl)+ glue.delete_database(Name=db)+++# ---------------------------------------------------------------------------+# GetCrawlerMetrics+# ---------------------------------------------------------------------------++def test_glue_get_crawler_metrics(glue):+ name = "qa-metrics-cr"+ glue.create_crawler(+ Name=name,+ Role="arn:aws:iam::000000000000:role/R",+ DatabaseName="test_db",+ Targets={"S3Targets": [{"Path": "s3://b/d/"}]},+ )+ resp = glue.get_crawler_metrics(CrawlerNameList=[name])+ assert len(resp["CrawlerMetricsList"]) == 1+ m = resp["CrawlerMetricsList"][0]+ assert m["CrawlerName"] == name+ assert "TablesCreated" in m+ # cleanup+ glue.delete_crawler(Name=name)+++# ---------------------------------------------------------------------------+# UpdateCrawler+# ---------------------------------------------------------------------------++def test_glue_update_crawler(glue):+ name = "qa-upd-cr"+ glue.create_crawler(+ Name=name,+ Role="arn:aws:iam::000000000000:role/R",+ DatabaseName="test_db",+ Targets={"S3Targets": [{"Path": "s3://b/d/"}]},+ )+ glue.update_crawler(Name=name, Description="updated desc", Role="arn:aws:iam::000000000000:role/New")+ cr = glue.get_crawler(Name=name)["Crawler"]+ assert cr["Description"] == "updated desc"+ assert cr["Role"] == "arn:aws:iam::000000000000:role/New"+ assert cr["Version"] == 2+ # cleanup+ glue.delete_crawler(Name=name)+++# ---------------------------------------------------------------------------+# StopCrawler+# ---------------------------------------------------------------------------++def test_glue_stop_crawler(glue):+ name = "qa-stop-cr"+ glue.create_crawler(+ Name=name,+ Role="arn:aws:iam::000000000000:role/R",+ DatabaseName="test_db",+ Targets={"S3Targets": [{"Path": "s3://b/d/"}]},+ )+ glue.start_crawler(Name=name)+ cr = glue.get_crawler(Name=name)["Crawler"]+ assert cr["State"] == "RUNNING"+ glue.stop_crawler(Name=name)+ cr2 = glue.get_crawler(Name=name)["Crawler"]+ assert cr2["State"] == "READY"+ # stopping a non-running crawler raises+ with pytest.raises(ClientError) as exc:+ glue.stop_crawler(Name=name)+ assert exc.value.response["Error"]["Code"] == "CrawlerNotRunningException"+ # cleanup+ glue.delete_crawler(Name=name)+++# ---------------------------------------------------------------------------+# CreateJob / DeleteJob / GetJobs / UpdateJob+# ---------------------------------------------------------------------------++def test_glue_create_delete_job(glue):+ name = "qa-cd-job"+ resp = glue.create_job(+ Name=name,+ Role="arn:aws:iam::000000000000:role/R",+ Command={"Name": "glueetl", "ScriptLocation": "s3://b/s.py"},+ GlueVersion="3.0",+ )+ assert resp["Name"] == name+ job = glue.get_job(JobName=name)["Job"]+ assert job["Name"] == name+ # delete returns JobName+ resp2 = glue.delete_job(JobName=name)+ assert resp2["JobName"] == name+ with pytest.raises(ClientError) as exc:+ glue.get_job(JobName=name)+ assert exc.value.response["Error"]["Code"] == "EntityNotFoundException"+++def test_glue_get_jobs(glue):+ names = ["qa-gj-a", "qa-gj-b"]+ for n in names:+ glue.create_job(+ Name=n,+ Role="arn:aws:iam::000000000000:role/R",+ Command={"Name": "glueetl", "ScriptLocation": "s3://b/s.py"},+ )+ resp = glue.get_jobs()+ found = [j["Name"] for j in resp["Jobs"]]+ for n in names:+ assert n in found+ # cleanup+ for n in names:+ glue.delete_job(JobName=n)+++def test_glue_update_job(glue):+ name = "qa-uj-job"+ glue.create_job(+ Name=name,+ Role="arn:aws:iam::000000000000:role/R",+ Command={"Name": "glueetl", "ScriptLocation": "s3://b/s.py"},+ Description="orig",+ )+ resp = glue.update_job(+ JobName=name,+ JobUpdate={"Description": "updated", "MaxRetries": 3},+ )+ assert resp["JobName"] == name+ job = glue.get_job(JobName=name)["Job"]+ assert job["Description"] == "updated"+ assert job["MaxRetries"] == 3+ # cleanup+ glue.delete_job(JobName=name)+++# ---------------------------------------------------------------------------+# BatchStopJobRun+# ---------------------------------------------------------------------------++def test_glue_batch_stop_job_run(glue):+ name = "qa-bsjr-job"+ glue.create_job(+ Name=name,+ Role="arn:aws:iam::000000000000:role/R",+ Command={"Name": "glueetl", "ScriptLocation": "s3://b/s.py"},+ )+ run1 = glue.start_job_run(JobName=name)["JobRunId"]+ run2 = glue.start_job_run(JobName=name)["JobRunId"]+ # Ministack auto-completes runs (SUCCEEDED), so batch stop returns errors+ # for completed runs + not-found run+ resp = glue.batch_stop_job_run(JobName=name, JobRunIds=[run1, run2, "no-such-run"])+ assert "SuccessfulSubmissions" in resp+ assert "Errors" in resp+ # All 3 should be errors: 2 already completed + 1 not found+ assert len(resp["Errors"]) == 3+ # cleanup+ glue.delete_job(JobName=name)+++# ---------------------------------------------------------------------------+# SecurityConfigurations (Create / Delete / Get / GetAll)+# ---------------------------------------------------------------------------++def test_glue_security_configuration_crud(glue):+ name = "qa-sec-cfg"+ resp = glue.create_security_configuration(+ Name=name,+ EncryptionConfiguration={+ "S3Encryption": [{"S3EncryptionMode": "SSE-S3"}],+ },+ )+ assert resp["Name"] == name+ assert "CreatedTimestamp" in resp++ cfg = glue.get_security_configuration(Name=name)["SecurityConfiguration"]+ assert cfg["Name"] == name+ assert cfg["EncryptionConfiguration"]["S3Encryption"] == [{"S3EncryptionMode": "SSE-S3"}]++ all_cfgs = glue.get_security_configurations()["SecurityConfigurations"]+ assert any(c["Name"] == name for c in all_cfgs)++ glue.delete_security_configuration(Name=name)+ with pytest.raises(ClientError) as exc:+ glue.get_security_configuration(Name=name)+ assert exc.value.response["Error"]["Code"] == "EntityNotFoundException"+++def test_glue_security_configuration_duplicate(glue):+ name = "qa-sec-dup"+ glue.create_security_configuration(Name=name, EncryptionConfiguration={})+ with pytest.raises(ClientError) as exc:+ glue.create_security_configuration(Name=name, EncryptionConfiguration={})+ assert exc.value.response["Error"]["Code"] == "AlreadyExistsException"+ # cleanup+ glue.delete_security_configuration(Name=name)+++# ---------------------------------------------------------------------------+# Classifiers (Create / Get / GetAll / Delete)+# ---------------------------------------------------------------------------++def test_glue_classifier_crud(glue):+ name = "qa-cls-grok"+ glue.create_classifier(+ GrokClassifier={+ "Name": name,+ "Classification": "test",+ "GrokPattern": "%{WORD:field}",+ },+ )+ cls = glue.get_classifier(Name=name)["Classifier"]+ assert "GrokClassifier" in cls+ assert cls["GrokClassifier"]["Name"] == name+ assert cls["GrokClassifier"]["GrokPattern"] == "%{WORD:field}"++ all_cls = glue.get_classifiers()["Classifiers"]+ assert any("GrokClassifier" in c and c["GrokClassifier"]["Name"] == name for c in all_cls)++ glue.delete_classifier(Name=name)+ with pytest.raises(ClientError) as exc:+ glue.get_classifier(Name=name)+ assert exc.value.response["Error"]["Code"] == "EntityNotFoundException"+++def test_glue_classifier_json(glue):+ name = "qa-cls-json"+ glue.create_classifier(+ JsonClassifier={"Name": name, "JsonPath": "$.records[*]"},+ )+ cls = glue.get_classifier(Name=name)["Classifier"]+ assert "JsonClassifier" in cls+ assert cls["JsonClassifier"]["JsonPath"] == "$.records[*]"+ # cleanup+ glue.delete_classifier(Name=name)+++def test_glue_classifier_duplicate(glue):+ name = "qa-cls-dup"+ glue.create_classifier(+ GrokClassifier={"Name": name, "Classification": "t", "GrokPattern": "%{WORD:f}"},+ )+ with pytest.raises(ClientError) as exc:+ glue.create_classifier(+ GrokClassifier={"Name": name, "Classification": "t", "GrokPattern": "%{WORD:f}"},+ )+ assert exc.value.response["Error"]["Code"] == "AlreadyExistsException"+ # cleanup+ glue.delete_classifier(Name=name)+++# ---------------------------------------------------------------------------+# BatchGetTriggers+# ---------------------------------------------------------------------------++def test_glue_batch_get_triggers(glue):+ names = ["qa-bgt-a", "qa-bgt-b"]+ for n in names:+ glue.create_trigger(Name=n, Type="ON_DEMAND", Actions=[{"JobName": "dummy"}])+ resp = glue.batch_get_triggers(TriggerNames=["qa-bgt-a", "qa-bgt-b", "no-such-trig"])+ found = [t["Name"] for t in resp["Triggers"]]+ assert "qa-bgt-a" in found+ assert "qa-bgt-b" in found+ assert "no-such-trig" in resp["TriggersNotFound"]+ # cleanup+ for n in names:+ glue.delete_trigger(Name=n)+++# ---------------------------------------------------------------------------+# GetTriggers+# ---------------------------------------------------------------------------++def test_glue_get_triggers(glue):+ names = ["qa-gt-x", "qa-gt-y"]+ for n in names:+ glue.create_trigger(Name=n, Type="ON_DEMAND", Actions=[{"JobName": "target-job"}])+ resp = glue.get_triggers(DependentJobName="target-job")+ found = [t["Name"] for t in resp["Triggers"]]+ for n in names:+ assert n in found+ # without filter, should also include them+ resp2 = glue.get_triggers()+ found2 = [t["Name"] for t in resp2["Triggers"]]+ for n in names:+ assert n in found2+ # cleanup+ for n in names:+ glue.delete_trigger(Name=n)+++# ---------------------------------------------------------------------------+# UpdateWorkflow+# ---------------------------------------------------------------------------++def test_glue_update_workflow(glue):+ name = "qa-upd-wf"+ glue.create_workflow(Name=name, Description="orig")+ resp = glue.update_workflow(Name=name, Description="updated", MaxConcurrentRuns=5)+ assert resp["Name"] == name+ wf = glue.get_workflow(Name=name)["Workflow"]+ assert wf["Description"] == "updated"+ assert wf["MaxConcurrentRuns"] == 5+ # not found+ with pytest.raises(ClientError) as exc:+ glue.update_workflow(Name="no-such-wf", Description="x")+ assert exc.value.response["Error"]["Code"] == "EntityNotFoundException"+ # cleanup+ glue.delete_workflow(Name=name)+++# ---------------------------------------------------------------------------+# CreatePartitionIndex / GetPartitionIndexes+# ---------------------------------------------------------------------------++def test_glue_partition_indexes(glue):+ db = "qa-pidx-db"+ tbl = "qa-pidx-tbl"+ glue.create_database(DatabaseInput={"Name": db})+ glue.create_table(+ DatabaseName=db,+ TableInput={+ "Name": tbl,+ "StorageDescriptor": {+ "Columns": [{"Name": "data", "Type": "string"}],+ "Location": "s3://b/pidx/",+ "InputFormat": "TIF",+ "OutputFormat": "TOF",+ "SerdeInfo": {"SerializationLibrary": "SL"},+ },+ "PartitionKeys": [+ {"Name": "year", "Type": "string"},+ {"Name": "month", "Type": "string"},+ ],+ },+ )+ glue.create_partition_index(+ DatabaseName=db,+ TableName=tbl,+ PartitionIndex={"IndexName": "idx_year", "Keys": ["year"]},+ )+ glue.create_partition_index(+ DatabaseName=db,+ TableName=tbl,+ PartitionIndex={"IndexName": "idx_month", "Keys": ["month"]},+ )+ resp = glue.get_partition_indexes(DatabaseName=db, TableName=tbl)+ indexes = resp["PartitionIndexDescriptorList"]+ assert len(indexes) == 2+ idx_names = [i["IndexName"] for i in indexes]+ assert "idx_year" in idx_names+ assert "idx_month" in idx_names+ assert all(i["IndexStatus"] == "ACTIVE" for i in indexes)+ # cleanup+ glue.delete_table(DatabaseName=db, Name=tbl)+ glue.delete_database(Name=db)diff --git a/tests/test_logs.py b/tests/test_logs.pyindex 7e7480f3..a284838e 100644--- a/tests/test_logs.py+++ b/tests/test_logs.py@@ -285,3 +285,163 @@ def test_logs_get_log_events_pagination_stops(logs):resp2 = logs.get_log_events(logGroupName=group, logStreamName=stream, nextToken=fwd_token)assert len(resp2["events"]) == 0assert resp2["nextForwardToken"] == fwd_token # same token = stop paginating+++# ---------------------------------------------------------------------------+# Destination operations+# ---------------------------------------------------------------------------++def test_logs_put_destination(logs):+ """PutDestination creates a destination and returns its metadata."""+ uid = _uuid_mod.uuid4().hex[:8]+ dest_name = f"test-dest-{uid}"+ target_arn = f"arn:aws:kinesis:us-east-1:000000000000:stream/dest-stream-{uid}"+ role_arn = f"arn:aws:iam::000000000000:role/dest-role-{uid}"++ resp = logs.put_destination(+ destinationName=dest_name,+ targetArn=target_arn,+ roleArn=role_arn,+ )+ dest = resp["destination"]+ assert dest["destinationName"] == dest_name+ assert dest["targetArn"] == target_arn+ assert dest["roleArn"] == role_arn+ assert "arn" in dest+ assert "creationTime" in dest++ # cleanup+ logs.delete_destination(destinationName=dest_name)+++def test_logs_delete_destination(logs):+ """DeleteDestination removes a destination; deleting again raises ResourceNotFoundException."""+ uid = _uuid_mod.uuid4().hex[:8]+ dest_name = f"test-dest-del-{uid}"+ logs.put_destination(+ destinationName=dest_name,+ targetArn="arn:aws:kinesis:us-east-1:000000000000:stream/s1",+ roleArn="arn:aws:iam::000000000000:role/r1",+ )++ logs.delete_destination(destinationName=dest_name)++ with pytest.raises(ClientError) as exc:+ logs.delete_destination(destinationName=dest_name)+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_logs_describe_destinations(logs):+ """DescribeDestinations lists destinations filtered by prefix."""+ uid = _uuid_mod.uuid4().hex[:8]+ name_a = f"desc-dest-{uid}-alpha"+ name_b = f"desc-dest-{uid}-beta"+ name_c = f"other-dest-{uid}"++ for n in (name_a, name_b, name_c):+ logs.put_destination(+ destinationName=n,+ targetArn="arn:aws:kinesis:us-east-1:000000000000:stream/s1",+ roleArn="arn:aws:iam::000000000000:role/r1",+ )++ resp = logs.describe_destinations(DestinationNamePrefix=f"desc-dest-{uid}")+ names = [d["destinationName"] for d in resp["destinations"]]+ assert name_a in names+ assert name_b in names+ assert name_c not in names++ # cleanup+ for n in (name_a, name_b, name_c):+ logs.delete_destination(destinationName=n)+++def test_logs_put_destination_policy(logs):+ """PutDestinationPolicy updates the accessPolicy on an existing destination."""+ uid = _uuid_mod.uuid4().hex[:8]+ dest_name = f"test-dest-pol-{uid}"+ logs.put_destination(+ destinationName=dest_name,+ targetArn="arn:aws:kinesis:us-east-1:000000000000:stream/s1",+ roleArn="arn:aws:iam::000000000000:role/r1",+ )++ policy = json.dumps({"Statement": [{"Effect": "Allow", "Principal": "*", "Action": "logs:PutSubscriptionFilter"}]})+ logs.put_destination_policy(destinationName=dest_name, accessPolicy=policy)++ resp = logs.describe_destinations(DestinationNamePrefix=dest_name)+ dest = next(d for d in resp["destinations"] if d["destinationName"] == dest_name)+ assert dest["accessPolicy"] == policy++ # cleanup+ logs.delete_destination(destinationName=dest_name)+++# ---------------------------------------------------------------------------+# ARN-based tagging operations (TagResource / UntagResource)+# ---------------------------------------------------------------------------++def test_logs_tag_resource(logs):+ """TagResource adds tags to a log group resolved by ARN."""+ uid = _uuid_mod.uuid4().hex[:8]+ group = f"/intg/tag-resource/{uid}"+ logs.create_log_group(logGroupName=group)++ groups = logs.describe_log_groups(logGroupNamePrefix=group)["logGroups"]+ arn = groups[0]["arn"]++ logs.tag_resource(resourceArn=arn, tags={"team": "platform", "env": "staging"})++ resp = logs.list_tags_for_resource(resourceArn=arn)+ assert resp["tags"]["team"] == "platform"+ assert resp["tags"]["env"] == "staging"++ # cleanup+ logs.delete_log_group(logGroupName=group)+++def test_logs_untag_resource(logs):+ """UntagResource removes tags from a log group resolved by ARN."""+ uid = _uuid_mod.uuid4().hex[:8]+ group = f"/intg/untag-resource/{uid}"+ logs.create_log_group(logGroupName=group, tags={"keep": "yes", "remove": "me"})++ groups = logs.describe_log_groups(logGroupNamePrefix=group)["logGroups"]+ arn = groups[0]["arn"]++ logs.untag_resource(resourceArn=arn, tagKeys=["remove"])++ resp = logs.list_tags_for_resource(resourceArn=arn)+ assert resp["tags"]["keep"] == "yes"+ assert "remove" not in resp["tags"]++ # cleanup+ logs.delete_log_group(logGroupName=group)+++# ---------------------------------------------------------------------------+# StopQuery+# ---------------------------------------------------------------------------++def test_logs_stop_query(logs):+ """StopQuery cancels a running query and sets its status to Cancelled."""+ uid = _uuid_mod.uuid4().hex[:8]+ group = f"/intg/stop-query/{uid}"+ logs.create_log_group(logGroupName=group)++ start_resp = logs.start_query(+ logGroupName=group,+ startTime=int(time.time()) - 3600,+ endTime=int(time.time()),+ queryString="fields @timestamp | limit 5",+ )+ query_id = start_resp["queryId"]++ stop_resp = logs.stop_query(queryId=query_id)+ assert stop_resp["success"] is True++ results = logs.get_query_results(queryId=query_id)+ assert results["status"] == "Cancelled"++ # cleanup+ logs.delete_log_group(logGroupName=group)diff --git a/tests/test_rds.py b/tests/test_rds.pyindex d2c5641d..d8699095 100644--- a/tests/test_rds.py+++ b/tests/test_rds.py@@ -715,3 +715,254 @@ def test_rds_modify_cluster_password(rds):resp = rds.describe_db_clusters(DBClusterIdentifier="pw-mod-cluster")cluster = resp["DBClusters"][0]assert cluster["DBClusterIdentifier"] == "pw-mod-cluster"+++# ---------------------------------------------------------------------------+# Tests for the 8 previously-untested operations+# ---------------------------------------------------------------------------+++def test_rds_create_read_replica(rds):+ """CreateDBInstanceReadReplica creates a replica linked to the source."""+ rds.create_db_instance(+ DBInstanceIdentifier="rr-source",+ DBInstanceClass="db.t3.micro",+ Engine="postgres",+ MasterUsername="admin",+ MasterUserPassword="pass123",+ AllocatedStorage=20,+ )+ try:+ resp = rds.create_db_instance_read_replica(+ DBInstanceIdentifier="rr-replica",+ SourceDBInstanceIdentifier="rr-source",+ )+ replica = resp["DBInstance"]+ assert replica["DBInstanceIdentifier"] == "rr-replica"+ assert replica["ReadReplicaSourceDBInstanceIdentifier"] == "rr-source"+ assert replica["DBInstanceStatus"] == "available"+ assert replica["Engine"] == "postgres"+ assert "Address" in replica["Endpoint"]++ # Source should list the replica+ source = rds.describe_db_instances(DBInstanceIdentifier="rr-source")["DBInstances"][0]+ assert "rr-replica" in source["ReadReplicaDBInstanceIdentifiers"]++ # Duplicate replica id should fail+ with pytest.raises(ClientError) as exc:+ rds.create_db_instance_read_replica(+ DBInstanceIdentifier="rr-replica",+ SourceDBInstanceIdentifier="rr-source",+ )+ assert exc.value.response["Error"]["Code"] == "DBInstanceAlreadyExistsFault"+ finally:+ rds.delete_db_instance(DBInstanceIdentifier="rr-replica", SkipFinalSnapshot=True)+ rds.delete_db_instance(DBInstanceIdentifier="rr-source", SkipFinalSnapshot=True)+++def test_rds_create_read_replica_source_not_found(rds):+ """CreateDBInstanceReadReplica fails when the source instance does not exist."""+ with pytest.raises(ClientError) as exc:+ rds.create_db_instance_read_replica(+ DBInstanceIdentifier="rr-orphan",+ SourceDBInstanceIdentifier="rr-nonexistent",+ )+ assert exc.value.response["Error"]["Code"] == "DBInstanceNotFoundFault"+++def test_rds_reboot_db_instance(rds):+ """RebootDBInstance sets the instance status back to available."""+ rds.create_db_instance(+ DBInstanceIdentifier="reboot-test",+ DBInstanceClass="db.t3.micro",+ Engine="postgres",+ MasterUsername="admin",+ MasterUserPassword="pass",+ AllocatedStorage=10,+ )+ try:+ resp = rds.reboot_db_instance(DBInstanceIdentifier="reboot-test")+ assert resp["DBInstance"]["DBInstanceStatus"] == "available"++ desc = rds.describe_db_instances(DBInstanceIdentifier="reboot-test")+ assert desc["DBInstances"][0]["DBInstanceStatus"] == "available"+ finally:+ rds.delete_db_instance(DBInstanceIdentifier="reboot-test", SkipFinalSnapshot=True)+++def test_rds_reboot_db_instance_not_found(rds):+ """RebootDBInstance fails for a non-existent instance."""+ with pytest.raises(ClientError) as exc:+ rds.reboot_db_instance(DBInstanceIdentifier="no-such-instance")+ assert exc.value.response["Error"]["Code"] == "DBInstanceNotFoundFault"+++def test_rds_restore_from_snapshot(rds):+ """RestoreDBInstanceFromDBSnapshot creates a new instance from a snapshot."""+ rds.create_db_instance(+ DBInstanceIdentifier="restore-src",+ DBInstanceClass="db.t3.micro",+ Engine="postgres",+ MasterUsername="admin",+ MasterUserPassword="pass",+ AllocatedStorage=20,+ DBName="srcdb",+ )+ rds.create_db_snapshot(+ DBSnapshotIdentifier="restore-snap",+ DBInstanceIdentifier="restore-src",+ )+ try:+ resp = rds.restore_db_instance_from_db_snapshot(+ DBInstanceIdentifier="restored-db",+ DBSnapshotIdentifier="restore-snap",+ DBInstanceClass="db.t3.small",+ )+ inst = resp["DBInstance"]+ assert inst["DBInstanceIdentifier"] == "restored-db"+ assert inst["DBInstanceStatus"] == "available"+ assert inst["Engine"] == "postgres"+ assert inst["DBInstanceClass"] == "db.t3.small"++ desc = rds.describe_db_instances(DBInstanceIdentifier="restored-db")+ assert len(desc["DBInstances"]) == 1++ # Duplicate target id should fail+ with pytest.raises(ClientError) as exc:+ rds.restore_db_instance_from_db_snapshot(+ DBInstanceIdentifier="restored-db",+ DBSnapshotIdentifier="restore-snap",+ )+ assert exc.value.response["Error"]["Code"] == "DBInstanceAlreadyExistsFault"+ finally:+ rds.delete_db_instance(DBInstanceIdentifier="restored-db", SkipFinalSnapshot=True)+ rds.delete_db_snapshot(DBSnapshotIdentifier="restore-snap")+ rds.delete_db_instance(DBInstanceIdentifier="restore-src", SkipFinalSnapshot=True)+++def test_rds_restore_from_snapshot_not_found(rds):+ """RestoreDBInstanceFromDBSnapshot fails when the snapshot does not exist."""+ with pytest.raises(ClientError) as exc:+ rds.restore_db_instance_from_db_snapshot(+ DBInstanceIdentifier="will-not-exist",+ DBSnapshotIdentifier="no-such-snap",+ )+ assert exc.value.response["Error"]["Code"] == "DBSnapshotNotFound"+++def test_rds_start_db_instance(rds):+ """StartDBInstance transitions a stopped instance to available."""+ rds.create_db_instance(+ DBInstanceIdentifier="start-test",+ DBInstanceClass="db.t3.micro",+ Engine="mysql",+ MasterUsername="admin",+ MasterUserPassword="pass",+ AllocatedStorage=10,+ )+ try:+ rds.stop_db_instance(DBInstanceIdentifier="start-test")+ stopped = rds.describe_db_instances(DBInstanceIdentifier="start-test")["DBInstances"][0]+ assert stopped["DBInstanceStatus"] == "stopped"++ resp = rds.start_db_instance(DBInstanceIdentifier="start-test")+ assert resp["DBInstance"]["DBInstanceStatus"] == "available"++ started = rds.describe_db_instances(DBInstanceIdentifier="start-test")["DBInstances"][0]+ assert started["DBInstanceStatus"] == "available"+ finally:+ rds.delete_db_instance(DBInstanceIdentifier="start-test", SkipFinalSnapshot=True)+++def test_rds_start_db_instance_not_found(rds):+ """StartDBInstance fails for a non-existent instance."""+ with pytest.raises(ClientError) as exc:+ rds.start_db_instance(DBInstanceIdentifier="ghost-instance")+ assert exc.value.response["Error"]["Code"] == "DBInstanceNotFoundFault"+++def test_rds_stop_db_instance(rds):+ """StopDBInstance transitions an available instance to stopped."""+ rds.create_db_instance(+ DBInstanceIdentifier="stop-test",+ DBInstanceClass="db.t3.micro",+ Engine="mysql",+ MasterUsername="admin",+ MasterUserPassword="pass",+ AllocatedStorage=10,+ )+ try:+ resp = rds.stop_db_instance(DBInstanceIdentifier="stop-test")+ assert resp["DBInstance"]["DBInstanceStatus"] == "stopped"++ desc = rds.describe_db_instances(DBInstanceIdentifier="stop-test")["DBInstances"][0]+ assert desc["DBInstanceStatus"] == "stopped"+ finally:+ rds.delete_db_instance(DBInstanceIdentifier="stop-test", SkipFinalSnapshot=True)+++def test_rds_stop_db_instance_not_found(rds):+ """StopDBInstance fails for a non-existent instance."""+ with pytest.raises(ClientError) as exc:+ rds.stop_db_instance(DBInstanceIdentifier="ghost-instance-2")+ assert exc.value.response["Error"]["Code"] == "DBInstanceNotFoundFault"+++def test_rds_describe_option_group_options(rds):+ """DescribeOptionGroupOptions returns an empty list (stub)."""+ resp = rds.describe_option_group_options(EngineName="mysql")+ assert "OptionGroupOptions" in resp+ assert resp["OptionGroupOptions"] == []+++def test_rds_describe_orderable_db_instance_options(rds):+ """DescribeOrderableDBInstanceOptions returns instance classes for an engine."""+ resp = rds.describe_orderable_db_instance_options(Engine="postgres")+ options = resp["OrderableDBInstanceOptions"]+ assert len(options) > 0+ engines = {o["Engine"] for o in options}+ assert engines == {"postgres"}+ classes = {o["DBInstanceClass"] for o in options}+ assert "db.t3.micro" in classes+ assert "db.r5.large" in classes++ # Filter by DBInstanceClass+ resp2 = rds.describe_orderable_db_instance_options(+ Engine="mysql", DBInstanceClass="db.t3.micro",+ )+ options2 = resp2["OrderableDBInstanceOptions"]+ assert len(options2) == 1+ assert options2[0]["DBInstanceClass"] == "db.t3.micro"+ assert options2[0]["Engine"] == "mysql"+++def test_rds_enable_http_endpoint(rds):+ """EnableHttpEndpoint enables Data API on an Aurora cluster."""+ rds.create_db_cluster(+ DBClusterIdentifier="http-ep-cluster",+ Engine="aurora-mysql",+ MasterUsername="admin",+ MasterUserPassword="password123",+ )+ try:+ cluster_arn = rds.describe_db_clusters(+ DBClusterIdentifier="http-ep-cluster"+ )["DBClusters"][0]["DBClusterArn"]++ resp = rds.enable_http_endpoint(ResourceArn=cluster_arn)+ assert resp["ResourceArn"] == cluster_arn+ assert resp["HttpEndpointEnabled"] is True++ desc = rds.describe_db_clusters(DBClusterIdentifier="http-ep-cluster")+ assert desc["DBClusters"][0]["HttpEndpointEnabled"] is True+ finally:+ rds.delete_db_cluster(DBClusterIdentifier="http-ep-cluster", SkipFinalSnapshot=True)+++def test_rds_enable_http_endpoint_not_found(rds):+ """EnableHttpEndpoint fails when the cluster ARN does not exist."""+ with pytest.raises(ClientError) as exc:+ rds.enable_http_endpoint(+ ResourceArn="arn:aws:rds:us-east-1:123456789012:cluster:no-such-cluster"+ )+ assert exc.value.response["Error"]["Code"] == "DBClusterNotFoundFault"diff --git a/tests/test_servicediscovery.py b/tests/test_servicediscovery.pyindex 72acaed9..10afddbd 100644--- a/tests/test_servicediscovery.py+++ b/tests/test_servicediscovery.py@@ -195,3 +195,148 @@ def test_servicediscovery_additional_operations(sd):sd.deregister_instance(ServiceId=svc_id, InstanceId="inst-1")sd.delete_service(Id=svc_id)sd.delete_namespace(Id=ns_id)++def test_servicediscovery_create_public_dns_namespace(sd):+ ns_name = "public-test.example.com"+ resp = sd.create_public_dns_namespace(+ Name=ns_name,+ Description="public dns namespace test",+ )+ op_id = resp["OperationId"]+ assert op_id++ op = sd.get_operation(OperationId=op_id)["Operation"]+ assert op["Status"] == "SUCCESS"+ ns_id = op["Targets"]["NAMESPACE"]++ ns = sd.get_namespace(Id=ns_id)["Namespace"]+ assert ns["Name"] == ns_name+ assert ns["Type"] == "DNS_PUBLIC"++ # verify hosted zone was created (public, not private)+ props = ns.get("Properties", {})+ dns_props = props.get("DnsProperties", {})+ hz_id = dns_props.get("HostedZoneId")+ assert hz_id, f"Expected HostedZoneId in namespace properties: {ns}"++ from conftest import make_client+ r53 = make_client("route53")+ hz = r53.get_hosted_zone(Id=hz_id)["HostedZone"]+ assert hz["Name"] == ns_name + "."+ assert hz["Config"]["PrivateZone"] is False++ # cleanup+ sd.delete_namespace(Id=ns_id)++def test_servicediscovery_get_instance(sd):+ ns_name = "get-inst.local"+ ns_op = sd.create_private_dns_namespace(+ Name=ns_name,+ Description="get instance test",+ Vpc="vpc-12345",+ )+ ns_id = sd.get_operation(OperationId=ns_op["OperationId"])["Operation"]["Targets"]["NAMESPACE"]++ svc = sd.create_service(+ Name="get-inst-svc",+ NamespaceId=ns_id,+ DnsConfig={"DnsRecords": [{"Type": "A", "TTL": 10}], "RoutingPolicy": "MULTIVALUE"},+ )["Service"]+ svc_id = svc["Id"]++ inst_id = "my-instance-1"+ sd.register_instance(+ ServiceId=svc_id,+ InstanceId=inst_id,+ Attributes={"AWS_INSTANCE_IPV4": "10.0.0.42", "role": "web"},+ )++ # get_instance returns the single instance+ resp = sd.get_instance(ServiceId=svc_id, InstanceId=inst_id)+ inst = resp["Instance"]+ assert inst["Id"] == inst_id+ assert inst["Attributes"]["AWS_INSTANCE_IPV4"] == "10.0.0.42"+ assert inst["Attributes"]["role"] == "web"++ # cleanup+ sd.deregister_instance(ServiceId=svc_id, InstanceId=inst_id)+ sd.delete_service(Id=svc_id)+ sd.delete_namespace(Id=ns_id)++def test_servicediscovery_get_service(sd):+ ns_op = sd.create_http_namespace(Name="get-svc-ns")+ ns_id = sd.get_operation(OperationId=ns_op["OperationId"])["Operation"]["Targets"]["NAMESPACE"]++ svc_name = "my-http-service"+ svc = sd.create_service(+ Name=svc_name,+ NamespaceId=ns_id,+ Description="a service to fetch",+ )["Service"]+ svc_id = svc["Id"]++ # get_service returns the full service object+ resp = sd.get_service(Id=svc_id)+ fetched = resp["Service"]+ assert fetched["Id"] == svc_id+ assert fetched["Name"] == svc_name+ assert fetched["Description"] == "a service to fetch"+ assert fetched["NamespaceId"] == ns_id++ # cleanup+ sd.delete_service(Id=svc_id)+ sd.delete_namespace(Id=ns_id)++def test_servicediscovery_update_http_namespace(sd):+ ns_op = sd.create_http_namespace(+ Name="upd-http-ns",+ Description="original description",+ )+ ns_id = sd.get_operation(OperationId=ns_op["OperationId"])["Operation"]["Targets"]["NAMESPACE"]++ # update the namespace description+ upd_op = sd.update_http_namespace(+ Id=ns_id,+ UpdaterRequestId="upd-http-1",+ Namespace={"Description": "updated http description"},+ )+ upd_op_id = upd_op["OperationId"]+ assert upd_op_id++ op = sd.get_operation(OperationId=upd_op_id)["Operation"]+ assert op["Status"] == "SUCCESS"+ assert op["Targets"]["NAMESPACE"] == ns_id++ # verify update took effect+ ns = sd.get_namespace(Id=ns_id)["Namespace"]+ assert ns["Description"] == "updated http description"++ # cleanup+ sd.delete_namespace(Id=ns_id)++def test_servicediscovery_update_public_dns_namespace(sd):+ ns_op = sd.create_public_dns_namespace(+ Name="upd-public.example.com",+ Description="original public desc",+ )+ ns_id = sd.get_operation(OperationId=ns_op["OperationId"])["Operation"]["Targets"]["NAMESPACE"]++ # update the namespace description+ upd_op = sd.update_public_dns_namespace(+ Id=ns_id,+ UpdaterRequestId="upd-pub-1",+ Namespace={"Description": "updated public description"},+ )+ upd_op_id = upd_op["OperationId"]+ assert upd_op_id++ op = sd.get_operation(OperationId=upd_op_id)["Operation"]+ assert op["Status"] == "SUCCESS"+ assert op["Targets"]["NAMESPACE"] == ns_id++ # verify update took effect+ ns = sd.get_namespace(Id=ns_id)["Namespace"]+ assert ns["Description"] == "updated public description"++ # cleanup+ sd.delete_namespace(Id=ns_id)