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
Fix add multi behaviour (#1042)
Nahuel Nucera7062525286a7
diff --git a/README.md b/README.mdindex c5c2ce4d..b7544887 100644--- a/README.md+++ b/README.md@@ -4,7 +4,7 @@<h1 align="center">MiniStack</h1><p align="center"><strong>Free, open-source local AWS emulator. Free forever.</strong></p>-<p align="center">56+ AWS services on a single port · Terraform compatible · Real databases · MIT licensed</p>+<p align="center">60+ AWS services on a single port · Terraform compatible · Real databases · MIT licensed</p><p align="center"><a href="https://github.com/ministackorg/ministack/releases"><img src="https://img.shields.io/github/v/release/ministackorg/ministack" alt="GitHub release"></a>@@ -25,7 +25,7 @@LocalStack recently moved its core services behind a paid plan. If you relied on LocalStack Community for local development and CI/CD pipelines, MiniStack is your free alternative.-- **56+ AWS services** emulated on a single port (4566)+- **60+ AWS services** emulated on a single port (4566)- **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 (full image only), ECS runs real Docker containers- **Tiny footprint** — ~270MB image, ~30MB RAM at idle vs LocalStack's ~1GB image and ~500MB RAMdiff --git a/ministack/app.py b/ministack/app.pyindex 8aafba6a..125678ae 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -1802,6 +1802,12 @@ async def _handle_lifespan(scope, receive, send):_eb_mod.start_scheduler()except Exception as e:logger.warning("EventBridge scheduler startup failed: %s", e)+ # EventBridge Scheduler standalone schedules also need a firing loop (#958).+ try:+ from ministack.services import scheduler as _sched_mod+ _sched_mod.start_scheduler()+ except Exception as e:+ logger.warning("Scheduler startup failed: %s", e)await send({"type": "lifespan.startup.complete"})logger.info("Ready — %d services available on port %s.", len(SERVICE_HANDLERS), port)# Per-service "init completed" lines are logged at DEBUG only — atdiff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.pyindex c13e6ebe..d975aa54 100644--- a/ministack/services/apigateway.py+++ b/ministack/services/apigateway.py@@ -1008,7 +1008,14 @@ async def _invoke_lambda_proxy(# Build API Gateway v2 proxy event (payload format 2.0)# AWS API Gateway v2 joins multi-value query params with commasqs = {k: ",".join(v) for k, v in query_params.items()} if query_params else None- raw_qs = "&".join(f"{k}={val}" for k, vals in query_params.items() for val in vals)+ # rawQueryString must stay percent-encoded like real AWS. query_params here are+ # already URL-decoded, so re-encode each key/value: a raw space breaks lambda_http+ # (http::Uri rejects it -> 502), and a decoded '='/'&' inside a value would corrupt+ # the query structure. safe="" encodes everything except RFC-3986 unreserved (#1035).+ raw_qs = "&".join(+ f"{urllib.parse.quote(k, safe='')}={urllib.parse.quote(val, safe='')}"+ for k, vals in query_params.items() for val in vals+ )# Binary request bodies are base64-encoded with isBase64Encoded=true; only# the text content types AWS recognizes are passed through as UTF-8 strings.if body:diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 7db8dbf3..899eb22e 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -1907,8 +1907,23 @@ def _lambda_esm_create(logical_id, props, stack_name):"Enabled": props.get("Enabled", True),"FunctionResponseTypes": props.get("FunctionResponseTypes", []),}- if props.get("FilterCriteria"):- esm["FilterCriteria"] = props["FilterCriteria"]+ # Preserve every optional ESM property the API create/update path round-trips,+ # so a CloudFormation-created mapping reads back without drift. Previously only+ # FilterCriteria was kept; DestinationConfig, ParallelizationFactor, the retry/age+ # knobs, and ScalingConfig were silently dropped -> perpetual Terraform/CDK diffs.+ # `is not None` (not truthiness) so explicit falsy values round-trip: 0 retries,+ # BisectBatchOnFunctionError=false; absent props stay absent (no spurious attrs).+ for _opt in (+ "FilterCriteria",+ "DestinationConfig",+ "ParallelizationFactor",+ "MaximumRetryAttempts",+ "MaximumRecordAgeInSeconds",+ "BisectBatchOnFunctionError",+ "ScalingConfig",+ ):+ if props.get(_opt) is not None:+ esm[_opt] = props[_opt]_lambda_svc._esms[esm_id] = esm# Anchor a DynamoDB-stream ESM's LATEST position at create time, matching the# API CreateEventSourceMapping path; no-op for SQS/Kinesis sources (#936).@@ -1921,6 +1936,46 @@ def _lambda_esm_delete(physical_id, props):_lambda_svc._esms.pop(physical_id, None)+def _lambda_esm_update(physical_id, old_props, new_props, stack_name):+ # Mutate the existing mapping in place, same as the API UpdateEventSourceMapping+ # path (_update_esm): keep the same UUID and copy the changed mutable props.+ # An immutable prop (EventSourceArn / StartingPosition[Timestamp]) forces a+ # CloudFormation replacement: create the new mapping, delete the old one.+ esm = _lambda_svc._esms.get(physical_id)+ if esm is None:+ return _lambda_esm_create(physical_id, new_props, stack_name)+ for immutable in ("EventSourceArn", "StartingPosition", "StartingPositionTimestamp"):+ if new_props.get(immutable) != old_props.get(immutable):+ new_id, attrs = _lambda_esm_create(physical_id, new_props, stack_name)+ _lambda_svc._esms.pop(physical_id, None)+ return new_id, attrs+ for key in (+ "BatchSize",+ "MaximumBatchingWindowInSeconds",+ "FunctionResponseTypes",+ "MaximumRetryAttempts",+ "MaximumRecordAgeInSeconds",+ "BisectBatchOnFunctionError",+ "ParallelizationFactor",+ "DestinationConfig",+ "FilterCriteria",+ "ScalingConfig",+ ):+ if key in new_props:+ esm[key] = new_props[key]+ if "Enabled" in new_props:+ esm["Enabled"] = new_props["Enabled"]+ esm["State"] = "Enabled" if new_props["Enabled"] else "Disabled"+ if "FunctionName" in new_props:+ func_name, qualifier = _lambda_svc._resolve_name_and_qualifier(new_props["FunctionName"])+ func = _lambda_svc._functions.get(func_name)+ func_arn = func["config"]["FunctionArn"] if func else f"arn:aws:lambda:{get_region()}:{get_account_id()}:function:{func_name}"+ esm["FunctionName"] = func_name+ esm["FunctionArn"] = func_arn + (f":{qualifier}" if qualifier else "")+ esm["LastModified"] = int(time.time())+ return physical_id, {"UUID": physical_id}++# --- EventBridge Pipes (minimal: DynamoDB Streams -> SNS) ---def _pipes_pipe_create(logical_id, props, stack_name):@@ -4232,7 +4287,7 @@ _RESOURCE_HANDLERS = {"AWS::ApiGateway::Deployment": {"create": _apigw_deployment_create, "delete": _apigw_deployment_delete},"AWS::ApiGateway::Stage": {"create": _apigw_stage_create, "delete": _apigw_stage_delete},"AWS::ApiGateway::Account": {"create": _apigw_account_create, "delete": _apigw_account_delete},- "AWS::Lambda::EventSourceMapping": {"create": _lambda_esm_create, "delete": _lambda_esm_delete},+ "AWS::Lambda::EventSourceMapping": {"create": _lambda_esm_create, "update": _lambda_esm_update, "delete": _lambda_esm_delete},"AWS::Pipes::Pipe": {"create": _pipes_pipe_create, "delete": _pipes_pipe_delete},"AWS::Lambda::Alias": {"create": _lambda_alias_create, "delete": _lambda_alias_delete},"AWS::SQS::QueuePolicy": {"create": _sqs_queue_policy_create, "delete": _sqs_queue_policy_delete},diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex 30fd93ea..d8ec8191 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -4544,13 +4544,29 @@ def _esm_response(esm: dict) -> dict:return {k: v for k, v in esm.items() if k not in ("FunctionName", "Enabled")}-def _validate_scaling_config(data: dict):+def _validate_scaling_config(data: dict, source_arn: str = ""):scaling = data.get("ScalingConfig")if not scaling:return Nonemax_conc = scaling.get("MaximumConcurrency")if max_conc is None:return None+ # ScalingConfig (MaximumConcurrency) is Amazon SQS-only per the AWS API.+ if ":sqs:" not in source_arn:+ return error_response_json(+ "InvalidParameterValueException",+ "ScalingConfig is only supported for Amazon SQS event sources.",+ 400,+ )+ # MaximumConcurrency is an integer; a non-int would otherwise raise on the+ # comparisons below and surface as a 500 instead of a validation error.+ if isinstance(max_conc, bool) or not isinstance(max_conc, int):+ return error_response_json(+ "ValidationException",+ f"1 validation error detected: Value '{max_conc}' at 'scalingConfig.maximumConcurrency' "+ "failed to satisfy constraint: Member must be an integer",+ 400,+ )if max_conc < 2:return error_response_json("ValidationException",@@ -4569,7 +4585,7 @@ def _validate_scaling_config(data: dict):def _create_esm(data: dict):- err = _validate_scaling_config(data)+ err = _validate_scaling_config(data, data.get("EventSourceArn", ""))if err:return erresm_id = new_uuid()@@ -4658,7 +4674,7 @@ def _update_esm(esm_id: str, data: dict):f"Event source mapping not found: {esm_id}",404,)- err = _validate_scaling_config(data)+ err = _validate_scaling_config(data, esm.get("EventSourceArn", ""))if err:return errfor key in (diff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex 48cfdd85..b6ab9178 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -2362,6 +2362,13 @@ def _apply_object_lock_from_headers(bucket_name: str, key: str, headers: dict):_object_legal_hold[(bucket_name, key)] = lock_legal+def _object_tagging_count_header(bucket_name: str, key: str, version_id) -> dict:+ """GetObject returns ``x-amz-tagging-count`` (boto3 surfaces it as ``TagCount``)+ only when the object carries at least one tag; AWS omits the header at zero (#1026)."""+ n = len(_object_tags.get((bucket_name, key, version_id), {}))+ return {"x-amz-tagging-count": str(n)} if n else {}++def _get_object(bucket_name: str, key: str, headers: dict, query_params: dict = None):query_params = query_params or {}bucket = _ensure_bucket(bucket_name)@@ -2398,6 +2405,7 @@ def _get_object(bucket_name: str, key: str, headers: dict, query_params: dict =resp_headers[f"x-amz-checksum-{alg.lower()}"] = valif stored:resp_headers["x-amz-checksum-type"] = "FULL_OBJECT"+ resp_headers.update(_object_tagging_count_header(bucket_name, key, version_id))return 200, resp_headers, v["data"]return _error("NoSuchVersion", "The specified version does not exist.", 404, f"/{bucket_name}/{key}")@@ -2419,6 +2427,7 @@ def _get_object(bucket_name: str, key: str, headers: dict, query_params: dict =include_checksums = checksum_mode_on and not range_headerresp_headers = _object_response_headers(obj, bucket_name, key,include_checksums=include_checksums)+ resp_headers.update(_object_tagging_count_header(bucket_name, key, obj.get("version_id")))body = _read_body(bucket_name, key, obj)if range_header:diff --git a/ministack/services/scheduler.py b/ministack/services/scheduler.pyindex dcccb371..22236857 100644--- a/ministack/services/scheduler.py+++ b/ministack/services/scheduler.py@@ -15,10 +15,18 @@ import jsonimport loggingimport osimport re+import threadingimport time+from datetime import datetime, timezonefrom ministack.core.persistence import load_state-from ministack.core.responses import AccountScopedDict, get_account_id, get_region+from ministack.core.responses import (+ AccountScopedDict,+ get_account_id,+ get_region,+ new_uuid,+ set_request_account_id,+)logger = logging.getLogger("scheduler")@@ -426,4 +434,149 @@ async def handle_request(method, path, headers, body_bytes, query_params):if method == "DELETE":return _untag_resource(arn, query)++# ---------------------------------------------------------------------------+# Schedule firing (issue #958)+# ---------------------------------------------------------------------------+# A background sweep over ``_schedules`` that fires each due schedule's target,+# mirroring ``eventbridge._tick_scheduled_rules`` but over the Scheduler store+# and its single-``Target`` shape. Rate/cron parsing and target dispatch are+# reused from EventBridge so behavior matches the rules path exactly; the extras+# unique to Scheduler are handled here: ``at()`` one-time expressions,+# ``ActionAfterCompletion`` one-shot delete, ``State`` and ``StartDate``/``EndDate``.++_SCHEDULE_TICK_INTERVAL = 10 # seconds between sweeps+_schedule_last_fired: dict = {} # (account_id, (group, name)) -> epoch; not persisted+_ticker_thread: "threading.Thread | None" = None+++def _to_epoch(value):+ """StartDate/EndDate arrive as rest-json unix timestamps (numbers); tolerate+ ISO-8601 strings too. Returns a float epoch, or None."""+ if value is None:+ return None+ if isinstance(value, (int, float)):+ return float(value)+ try:+ return datetime.fromisoformat(str(value).replace("Z", "+00:00")).timestamp()+ except ValueError:+ return None+++def _at_time_epoch(expr: str):+ """Parse an ``at(yyyy-mm-ddThh:mm:ss)`` one-time expression to a UTC epoch,+ or None when the expression is not an ``at()`` form."""+ m = re.match(r"^\s*at\((.+)\)\s*$", expr)+ if not m:+ return None+ try:+ dt = datetime.fromisoformat(m.group(1).strip())+ except ValueError:+ return None+ if dt.tzinfo is None:+ dt = dt.replace(tzinfo=timezone.utc)+ return dt.timestamp()+++def _tick_schedules():+ """Fire every ENABLED schedule that is due, honoring State, Start/EndDate,+ at()/rate()/cron() expressions and ActionAfterCompletion one-shot delete."""+ from ministack.services import eventbridge as _eb++ now = time.time()+ now_dt = datetime.fromtimestamp(now, tz=timezone.utc)+ for state_key, sched in list(_schedules._data.items()):+ account_id, key = state_key+ if sched.get("State") != "ENABLED":+ continue+ end = _to_epoch(sched.get("EndDate"))+ if end is not None and now > end:+ # A recurring schedule past its EndDate has "completed".+ if sched.get("ActionAfterCompletion") == "DELETE":+ _schedules._data.pop(state_key, None)+ _schedule_last_fired.pop(state_key, None)+ continue+ start = _to_epoch(sched.get("StartDate"))+ if start is not None and now < start:+ continue++ expr = sched.get("ScheduleExpression", "")+ one_shot = False++ at_epoch = _at_time_epoch(expr)+ if at_epoch is not None:+ # One-time at(): fire once when the moment has passed.+ if now < at_epoch or state_key in _schedule_last_fired:+ continue+ one_shot = True+ else:+ interval = _eb._parse_rate_seconds(expr)+ if interval is not None:+ # rate(): countdown anchored to creation, then every interval.+ if state_key not in _schedule_last_fired:+ _schedule_last_fired[state_key] = sched.get("CreationDate", now)+ if now - _schedule_last_fired[state_key] < interval:+ continue+ else:+ fields = _eb._parse_cron_fields(expr)+ if fields is None:+ continue # unsupported / unparseable expression+ # cron(): fire once per scheduled occurrence.+ if state_key not in _schedule_last_fired:+ _schedule_last_fired[state_key] = now+ continue+ last_dt = datetime.fromtimestamp(_schedule_last_fired[state_key], tz=timezone.utc)+ next_fire = _eb._cron_next_fire(fields, last_dt)+ if next_fire is None or now_dt < next_fire:+ continue++ _schedule_last_fired[state_key] = now+ target = sched.get("Target") or {}+ if not target.get("Arn"):+ continue+ # Fire under the schedule's own tenant so ARN-building / dispatch scope right.+ set_request_account_id(account_id)+ event = {+ "EventId": new_uuid(),+ "Source": "aws.scheduler",+ "DetailType": "Scheduled Event",+ "Detail": "{}",+ "Time": now,+ "Resources": [sched.get("Arn", "")],+ "Account": account_id,+ "Region": get_region(),+ }+ try:+ _eb._invoke_target(target, event, sched)+ except Exception:+ logger.exception("Scheduler dispatch error for %s (account %s)", key, account_id)++ # ActionAfterCompletion=DELETE on a one-time at() schedule: remove after+ # firing. Recurring DELETE schedules "complete" at EndDate (handled above);+ # at() with NONE stays but never refires (guarded by _schedule_last_fired).+ if one_shot and sched.get("ActionAfterCompletion") == "DELETE":+ _schedules._data.pop(state_key, None)+ _schedule_last_fired.pop(state_key, None)+++def _ticker_loop():+ while True:+ time.sleep(_SCHEDULE_TICK_INTERVAL)+ try:+ _tick_schedules()+ except Exception:+ logger.exception("Scheduler ticker error")+++def start_scheduler() -> None:+ """Start the schedule-firing daemon (idempotent). Wired from the gateway+ lifespan.startup, mirroring ``eventbridge.start_scheduler``."""+ global _ticker_thread+ if _ticker_thread is not None and _ticker_thread.is_alive():+ return+ _ticker_thread = threading.Thread(+ target=_ticker_loop, daemon=True, name="evb-scheduler-ticker"+ )+ _ticker_thread.start()+return _error(400, "ValidationException", f"No route for {method} {path}")diff --git a/tests/test_apigatewayv2.py b/tests/test_apigatewayv2.pyindex 18830348..825b5d11 100644--- a/tests/test_apigatewayv2.py+++ b/tests/test_apigatewayv2.py@@ -922,6 +922,43 @@ def test_apigw_query_params_and_headers_in_event(apigw, lam):lam.delete_function(FunctionName=fname)+def test_apigw_raw_query_string_percent_encoded(apigw, lam):+ """rawQueryString must stay percent-encoded like AWS: a space in a value comes+ back as %20, not a literal space (which breaks lambda_http / http::Uri) — #1035."""+ import urllib.request as _urlreq+ import uuid as _uuid++ fname = f"intg-rawqs-{_uuid.uuid4().hex[:8]}"+ code = (+ "import json\n"+ "def handler(event, context):\n"+ " return {'statusCode': 200, 'body': json.dumps({'rawQs': event.get('rawQueryString')})}\n"+ )+ lam.create_function(+ FunctionName=fname, Runtime="python3.12", Role=_LAMBDA_ROLE,+ Handler="index.handler", Code={"ZipFile": _make_zip(code)},+ )+ api_id = apigw.create_api(Name=f"rawqs-api-{fname}", ProtocolType="HTTP")["ApiId"]+ int_id = apigw.create_integration(+ ApiId=api_id, IntegrationType="AWS_PROXY",+ IntegrationUri=f"arn:aws:lambda:us-east-1:000000000000:function:{fname}",+ PayloadFormatVersion="2.0",+ )["IntegrationId"]+ apigw.create_route(ApiId=api_id, RouteKey="GET /authorize", Target=f"integrations/{int_id}")+ apigw.create_stage(ApiId=api_id, StageName="$default")+ try:+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/$default/authorize?scope=openid%20profile"+ req = _urlreq.Request(url, method="GET")+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")+ resp = _urlreq.urlopen(req)+ body = json.loads(resp.read())+ assert "openid%20profile" in body["rawQs"]+ assert "openid profile" not in body["rawQs"] # no literal space+ finally:+ apigw.delete_api(ApiId=api_id)+ lam.delete_function(FunctionName=fname)++def test_apigw_multiple_path_parameters(apigw, lam):"""Multiple path parameters in one route should all be extracted."""import urllib.request as _urlreqdiff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 764e326d..07522896 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -1177,6 +1177,75 @@ def test_cfn_esm_filter_criteria_round_trips(cfn, lam, ddb):ddb.delete_table(TableName="cfn-esm-fc-table")lam.delete_function(FunctionName="cfn-esm-fc-fn")++def test_cfn_esm_extra_props_round_trip_and_in_place_update(cfn, lam, ddb):+ """CFN-created EventSourceMappings must round-trip every optional prop (not just+ FilterCriteria), and a stack update must mutate the mapping in place (same UUID),+ never duplicate it — #1034 follow-up."""+ code = "def handler(e,c): return {'ok': True}"+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("index.py", code)+ lam.create_function(+ FunctionName="cfn-esm-xp-fn", Runtime="python3.11",+ Role="arn:aws:iam::000000000000:role/r", Handler="index.handler",+ Code={"ZipFile": buf.getvalue()},+ )+ table = ddb.create_table(+ TableName="cfn-esm-xp-table",+ KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ StreamSpecification={"StreamEnabled": True, "StreamViewType": "NEW_IMAGE"},+ )+ stream_arn = table["TableDescription"]["LatestStreamArn"]+ dlq = "arn:aws:sqs:us-east-1:000000000000:cfn-esm-xp-dlq"++ def template(batch):+ return {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {"Mapping": {+ "Type": "AWS::Lambda::EventSourceMapping",+ "Properties": {+ "FunctionName": "cfn-esm-xp-fn",+ "EventSourceArn": stream_arn,+ "StartingPosition": "LATEST",+ "BatchSize": batch,+ "MaximumRetryAttempts": 3,+ "BisectBatchOnFunctionError": True,+ "ParallelizationFactor": 4,+ "DestinationConfig": {"OnFailure": {"Destination": dlq}},+ },+ }},+ }++ cfn.create_stack(StackName="cfn-esm-xp", TemplateBody=json.dumps(template(5)))+ stack = _wait_stack(cfn, "cfn-esm-xp")+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")++ maps = lam.list_event_source_mappings(FunctionName="cfn-esm-xp-fn")["EventSourceMappings"]+ assert len(maps) == 1+ m = maps[0]+ uuid_before = m["UUID"]+ assert m["BatchSize"] == 5+ assert m["MaximumRetryAttempts"] == 3+ assert m["BisectBatchOnFunctionError"] is True+ assert m["ParallelizationFactor"] == 4+ assert m["DestinationConfig"]["OnFailure"]["Destination"] == dlq++ # Stack update changing BatchSize must update in place: same UUID, still one mapping.+ cfn.update_stack(StackName="cfn-esm-xp", TemplateBody=json.dumps(template(9)))+ _wait_stack(cfn, "cfn-esm-xp")+ maps2 = lam.list_event_source_mappings(FunctionName="cfn-esm-xp-fn")["EventSourceMappings"]+ assert len(maps2) == 1, "stack update must not duplicate the mapping"+ assert maps2[0]["UUID"] == uuid_before, "update must mutate in place (same UUID)"+ assert maps2[0]["BatchSize"] == 9++ cfn.delete_stack(StackName="cfn-esm-xp")+ _wait_stack(cfn, "cfn-esm-xp")+ ddb.delete_table(TableName="cfn-esm-xp-table")+ lam.delete_function(FunctionName="cfn-esm-xp-fn")+def test_cfn_wait_condition(cfn):"""AWS::CloudFormation::WaitCondition and WaitConditionHandle are no-ops."""template = {diff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex 9ed8c66e..fe608da0 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -526,6 +526,33 @@ def test_lambda_esm_scaling_config_out_of_range_rejected(lam, sqs, bad_value):body = json.loads(e.read())assert body.get("__type") == "ValidationException", body+def test_lambda_esm_scaling_config_rejected_on_non_sqs(lam, kin):+ """ScalingConfig is Amazon SQS-only; setting it on a Kinesis (or any non-SQS)+ event source must be rejected, not silently accepted — #1029."""+ fname = "esm-scaling-nonsqs-func"+ stream = "esm-scaling-nonsqs-stream"+ try:+ lam.delete_function(FunctionName=fname)+ except ClientError:+ pass+ try:+ kin.delete_stream(StreamName=stream, EnforceConsumerDeletion=True)+ except ClientError:+ pass+ lam.create_function(+ FunctionName=fname, Runtime="python3.12", Role=_LAMBDA_ROLE,+ Handler="index.handler", Code={"ZipFile": _make_zip(_LAMBDA_CODE)},+ )+ kin.create_stream(StreamName=stream, ShardCount=1)+ stream_arn = kin.describe_stream(StreamName=stream)["StreamDescription"]["StreamARN"]+ with pytest.raises(ClientError) as exc:+ lam.create_event_source_mapping(+ EventSourceArn=stream_arn, FunctionName=fname,+ StartingPosition="LATEST",+ ScalingConfig={"MaximumConcurrency": 10},+ )+ assert exc.value.response["Error"]["Code"] == "InvalidParameterValueException"+def test_lambda_esm_filter_criteria_stored_on_create(lam, sqs):"""FilterCriteria specified at CreateEventSourceMapping must be echoedback by GetEventSourceMapping — it was silently dropped before this fix."""diff --git a/tests/test_s3.py b/tests/test_s3.pyindex bb1701a8..eebdcb98 100644--- a/tests/test_s3.py+++ b/tests/test_s3.py@@ -820,6 +820,24 @@ def test_s3_object_tagging(s3):assert tags["priority"] == "high"+def test_s3_get_object_returns_tag_count(s3):+ """GetObject must surface x-amz-tagging-count as TagCount when the object has+ tags, and omit it when it has none (matches AWS / boto3 behavior) — #1026."""+ bkt = "intg-s3-tagcount"+ s3.create_bucket(Bucket=bkt)+ s3.put_object(+ Bucket=bkt, Key="tagged.txt", Body=b"hi",+ Tagging="environment=dev&owner=test&project=p&version=1.0®ion=eu",+ )+ resp = s3.get_object(Bucket=bkt, Key="tagged.txt")+ assert resp["TagCount"] == 5++ # An object with no tags: AWS omits the header, so boto3 has no TagCount key.+ s3.put_object(Bucket=bkt, Key="untagged.txt", Body=b"hi")+ resp2 = s3.get_object(Bucket=bkt, Key="untagged.txt")+ assert "TagCount" not in resp2++def test_s3_object_tagging_per_version(s3):"""Tags must be stored per object version, not collapsed onto the key.diff --git a/tests/test_scheduler.py b/tests/test_scheduler.pyindex 6f0e6312..c90d2394 100644--- a/tests/test_scheduler.py+++ b/tests/test_scheduler.py@@ -456,3 +456,41 @@ def test_scheduler_cfn_creates_schedule(cfn, scheduler):# Delete stackcfn.delete_stack(StackName=stack_name)time.sleep(1)+++def test_scheduler_fires_at_expression_to_sqs(scheduler):+ """A standalone schedule must actually fire: an at() schedule in the near past+ delivers to its SQS target within one tick of the daemon — #958."""+ import datetime as _dt++ sqs = boto3.client("sqs", endpoint_url=ENDPOINT, aws_access_key_id="test",+ aws_secret_access_key="test", region_name=REGION)+ name = f"fire-{_uid()}"+ q_url = sqs.create_queue(QueueName=f"sched-target-{_uid()}")["QueueUrl"]+ q_arn = sqs.get_queue_attributes(+ QueueUrl=q_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]+ past = (_dt.datetime.now(_dt.timezone.utc) - _dt.timedelta(seconds=2)).strftime("%Y-%m-%dT%H:%M:%S")+ scheduler.create_schedule(+ Name=name,+ ScheduleExpression=f"at({past})",+ FlexibleTimeWindow={"Mode": "OFF"},+ Target={"Arn": q_arn, "RoleArn": "arn:aws:iam::000000000000:role/r",+ "Input": "hello-from-schedule"},+ )+ try:+ deadline = time.time() + 20+ body = None+ while time.time() < deadline:+ msgs = sqs.receive_message(+ QueueUrl=q_url, WaitTimeSeconds=1, MaxNumberOfMessages=1+ ).get("Messages", [])+ if msgs:+ body = msgs[0]["Body"]+ break+ assert body == "hello-from-schedule", f"schedule did not fire (body={body!r})"+ finally:+ try:+ scheduler.delete_schedule(Name=name)+ except ClientError:+ pass+ sqs.delete_queue(QueueUrl=q_url)