Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

feat(lambda-core): network connectors, EC2 fleet tags, lint (#1685)

Nahuel Nucera9d9069c0a09e
diff --git a/ministack/app.py b/ministack/app.py
index 2f3daab3..5afb07c3 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -375,6 +375,7 @@ SERVICE_REGISTRY = {
"kinesis": {"module": "kinesis"},
"kms": {"module": "kms"},
"lambda": {"module": "lambda_svc"},
+ "lambda-core": {"module": "lambda_core"},
"lambda-microvms": {"module": "lambda_microvms"},
"location": {"module": "location"},
"logs": {"module": "cloudwatch_logs", "aliases": ("cloudwatch-logs",)},
@@ -450,6 +451,7 @@ _state_map = {
"cloudwatch": "cloudwatch",
"s3": "s3",
"lambda": "lambda_svc",
+ "lambda_core": "lambda_core",
"lambda_microvms": "lambda_microvms",
"rds": "rds",
"ecs": "ecs",
diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.py
index 6a2cb651..d27769b9 100644
--- a/ministack/core/iam_actions.py
+++ b/ministack/core/iam_actions.py
@@ -78,6 +78,7 @@ SERVICE_TO_IAM_NAMESPACE: dict[str, str] = {
"kinesis": "kinesis",
"kms": "kms",
"lambda": "lambda",
+ "lambda-core": "lambda",
"lambda-microvms": "lambda",
"location": "geo",
"logs": "logs",
diff --git a/ministack/core/responses.py b/ministack/core/responses.py
index 7ee62071..076c8eb8 100644
--- a/ministack/core/responses.py
+++ b/ministack/core/responses.py
@@ -439,10 +439,23 @@ def _dict_to_xml(parent: Element, data):
parent.text = data
-def json_response(data: dict, status: int = 200) -> tuple:
- """Build an AWS-style JSON response."""
+# Response/error body content types. The json protocol (awsJson1.0/1.1) answers
+# `application/x-amz-json-1.0`; a rest-json service answers `application/json`.
+JSON_1_0_CONTENT_TYPE = "application/x-amz-json-1.0"
+REST_JSON_CONTENT_TYPE = "application/json"
+
+
+def json_response(data: dict, status: int = 200, *,
+ content_type: str = JSON_1_0_CONTENT_TYPE) -> tuple:
+ """Build an AWS-style JSON response.
+
+ `content_type` follows the service's protocol: the json protocol answers
+ `application/x-amz-json-1.0` (the default here), while a rest-json service
+ answers `application/json`. SDKs pick their parser from the service model
+ rather than this header, so it is about matching the wire.
+ """
body = json.dumps(data, ensure_ascii=False).encode("utf-8")
- return status, {"Content-Type": "application/x-amz-json-1.0"}, body
+ return status, {"Content-Type": content_type}, body
def error_response_xml(code: str, message: str, status: int, namespace: str = "http://s3.amazonaws.com/doc/2006-03-01/") -> tuple:
@@ -462,12 +475,6 @@ def error_response_xml(code: str, message: str, status: int, namespace: str = "h
return status, {"Content-Type": "application/xml"}, body
-# Error-body content types. The json protocol (awsJson1.0/1.1) answers
-# `application/x-amz-json-1.0`; a rest-json service answers `application/json`.
-JSON_1_0_CONTENT_TYPE = "application/x-amz-json-1.0"
-REST_JSON_CONTENT_TYPE = "application/json"
-
-
def error_response_json(code: str, message: str, status: int = 400, extra: dict | None = None,
*, message_key: str = "message",
content_type: str = JSON_1_0_CONTENT_TYPE) -> tuple:
diff --git a/ministack/core/router.py b/ministack/core/router.py
index 3dabc203..58bfae20 100644
--- a/ministack/core/router.py
+++ b/ministack/core/router.py
@@ -32,6 +32,11 @@ _LAMBDA_PATH_RE = re.compile(
r"durable-executions|durable-execution-callbacks)(?:/|$)"
)
+# Lambda Core (botocore `lambda-core`, apiVersion 2026-04-30) network
+# connectors. The request URIs ship under 2026-04-04, not the model's
+# apiVersion — `/2026-04-04/network-connectors[/{Identifier}]`.
+_LAMBDA_CORE_PATH_RE = re.compile(r"^/2026-04-04/network-connectors(?:/|$)")
+
# ECS Task Metadata V4 paths: /v4/<token>[/task|/stats|...]. Token is
# url-safe base64, generated per-container in services/ecs.py.
_ECS_METADATA_PATH_RE = re.compile(r"^/v4/[A-Za-z0-9_-]{8,}(?:/.*)?$")
@@ -68,6 +73,12 @@ SERVICE_PATTERNS = {
"target_prefixes": ["DynamoDB_20120810"],
"host_patterns": [r"dynamodb\."],
},
+ # Lambda Core (2026-04-04 URIs) shares Lambda's host and credential scope,
+ # so only the path distinguishes it. Listed before `lambda`; the patterns
+ # are disjoint, and the signed case is handled earlier in detect_service.
+ "lambda-core": {
+ "path_patterns": [r"^/2026-04-04/network-connectors"],
+ },
# Lambda MicroVMs (2025-09-09) sign with credential scope `lambda-microvms`
# and use host `lambda-microvms.{region}.amazonaws.com` — distinct from
# Lambda's `lambda.` host, so this must be its own entry. Listed before
@@ -712,6 +723,15 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->
or path.startswith("/async-invoke")):
return "bedrock-runtime"
return "bedrock"
+ # Lambda Core signs as `lambda`: its endpointPrefix AND signingName
+ # are both `lambda` (botocore lambda-core/2026-04-30), unlike
+ # lambda-microvms which has its own scope. So the credential scope
+ # cannot tell the two apart and the path has to. This must sit
+ # before the SERVICE_PATTERNS early-return below, or `lambda`
+ # matches there and the request reaches the function router, which
+ # reads `/2026-04-04/network-connectors` as a function name.
+ if svc_name == "lambda" and _LAMBDA_CORE_PATH_RE.match(path):
+ return "lambda-core"
if svc_name in SERVICE_PATTERNS:
return svc_name
# Map common credential scope names
@@ -1183,6 +1203,10 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->
or path_lower.startswith("/domainnames")
):
return "apigateway"
+ # Before the Lambda path check: both live on the Lambda endpoint, and an
+ # unsigned caller (curl) has no credential scope to disambiguate with.
+ if _LAMBDA_CORE_PATH_RE.match(path_lower):
+ return "lambda-core"
if _LAMBDA_PATH_RE.match(path_lower):
return "lambda"
if path_lower.startswith(("/oauth2/", "/login", "/logout")):
diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.py
index cee04756..69ff8cf5 100644
--- a/ministack/services/cloudformation/handlers.py
+++ b/ministack/services/cloudformation/handlers.py
@@ -554,7 +554,6 @@ def _resource_metadata_xml(stack, logical_id):
def _describe_stack_resource(params):
- from ministack.services.cloudformation import _stacks
stack_name = _p(params, "StackName")
logical_id = _p(params, "LogicalResourceId")
@@ -591,7 +590,6 @@ def _describe_stack_resource(params):
# --- DescribeStackResources ---
def _describe_stack_resources(params):
- from ministack.services.cloudformation import _stacks
stack_name = _p(params, "StackName")
logical_resource_id = _p(params, "LogicalResourceId")
@@ -818,7 +816,6 @@ def _stack_has_no_updates(stack, template, param_values, tags,
def _update_stack(params):
- from ministack.services.cloudformation import _stacks
from .helpers import _resolve_document
stack_name = _p(params, "StackName")
@@ -1037,7 +1034,6 @@ def _list_exports(params):
# --- GetTemplateSummary ---
def _get_template_summary(params):
- from ministack.services.cloudformation import _stacks
template_body, resolve_err = _resolve_template(params)
if resolve_err:
return resolve_err
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index 478d987b..bf7576ec 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -6965,9 +6965,17 @@ def _create_fleet(p):
for slot, launched in zip(slots, slot_buckets):
if not launched:
continue
- if instance_tags:
+ # The slot's launch template contributes its own instance tags; the
+ # request's TagSpecifications (instant fleets only, per the model)
+ # are layered on top. On a duplicate key the request wins — that
+ # precedence is MiniStack's choice, not a measured AWS behaviour.
+ merged = {t["Key"]: t["Value"] for t in slot.get("instance_tags") or []}
+ merged.update({t["Key"]: t["Value"] for t in instance_tags})
+ if merged:
for inst in launched:
- _tags[inst["InstanceId"]] = instance_tags[:]
+ _tags[inst["InstanceId"]] = [
+ {"Key": k, "Value": v} for k, v in merged.items()
+ ]
instance_items.append({
"InstanceIds": [inst["InstanceId"] for inst in launched],
"InstanceType": slot["instance_type"],
@@ -7028,6 +7036,19 @@ def _slot_from_lt_data(spec, lt_data):
"user_data": (lt_data or {}).get("UserData") or "",
"sg_ids": (lt_data or {}).get("SecurityGroupIds") or None,
"iam_profile": iam_profile,
+ # RequestLaunchTemplateData.TagSpecifications is "the tags to apply to
+ # the resources that are created during instance launch", and
+ # CreateFleetRequest.TagSpecifications points at the launch template as
+ # THE way to tag instances of a maintain/request fleet. Only the
+ # `instance` specs belong on the instance; a `volume` spec is for the
+ # volume.
+ "instance_tags": [
+ dict(tag)
+ for spec in ((lt_data or {}).get("TagSpecifications") or [])
+ if spec.get("ResourceType") == "instance"
+ for tag in (spec.get("Tags") or [])
+ if tag.get("Key")
+ ],
}
diff --git a/ministack/services/lambda_core.py b/ministack/services/lambda_core.py
new file mode 100644
index 00000000..c62a59be
--- /dev/null
+++ b/ministack/services/lambda_core.py
@@ -0,0 +1,488 @@
+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT
+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).
+"""AWS Lambda Core network connectors (REST-JSON, ``lambda-core`` 2026-04-30).
+
+Control-plane emulation of the network-connector family: ``CreateNetworkConnector``,
+``GetNetworkConnector``, ``UpdateNetworkConnector``, ``DeleteNetworkConnector``
+and ``ListNetworkConnectors``. Shapes, status codes, enums and member casing are
+taken from botocore ``lambda-core/2026-04-30/service-2.json``.
+
+Two things about this service are easy to get wrong and are worth stating here.
+
+*It is not its own endpoint.* ``endpointPrefix`` and ``signingName`` are both
+``lambda`` — unlike ``lambda-microvms``, which signs under its own name. A
+client therefore signs a network-connector call exactly like a Lambda call, so
+the router cannot tell them apart by credential scope and must look at the path
+(``/2026-04-04/network-connectors``). Note the request URIs carry ``2026-04-04``
+while the model's own ``apiVersion`` is ``2026-04-30``; the URI is what ships.
+
+*The error envelope is not uniform.* Every exception carries a ``Type`` member,
+but the message member's casing differs per shape: ``ResourceNotFoundException``
+and ``ServiceException`` model ``Message``, while ``InvalidParameterValueException``,
+``ResourceConflictException``, ``NetworkConnectorLimitExceededException`` and
+``TooManyRequestsException`` model ``message``. ``_error`` below keys off the
+code so each one goes out the way its shape declares.
+
+There is no real VPC attachment behind a connector. ``CreateNetworkConnector``
+returns ``PENDING``, matching the modelled 202, and the connector reaches
+``ACTIVE`` on the next read, which is what a client polling ``GetNetworkConnector``
+needs in order to proceed. Nothing validates that the subnets or security groups
+exist in EC2.
+"""
+
+import copy
+import json
+import logging
+import re
+from datetime import datetime, timezone
+from urllib.parse import unquote
+
+from ministack.core.persistence import load_state
+from ministack.core.responses import (
+ REST_JSON_CONTENT_TYPE,
+ AccountRegionScopedDict,
+ error_response_json,
+ get_account_id,
+ get_region,
+ json_response,
+ new_uuid,
+)
+
+logger = logging.getLogger("lambda_core")
+
+# The URI prefix the operations ship under. Deliberately not the model's
+# apiVersion (2026-04-30) — every requestUri in the model says 2026-04-04.
+API_PREFIX = "2026-04-04"
+
+# NetworkConnectorState, verbatim from the model enum.
+_STATE_PENDING = "PENDING"
+_STATE_ACTIVE = "ACTIVE"
+_STATES = ("PENDING", "ACTIVE", "INACTIVE", "FAILED", "DELETING", "DELETE_FAILED")
+
+# NetworkConnectorType — the model declares exactly one value today.
+_TYPE_VPC_EGRESS = "VPC_EGRESS"
+
+# NetworkProtocol enum.
+_NETWORK_PROTOCOLS = ("IPv4", "DualStack")
+# ComputeResourceType enum, and AssociatedComputeResourceTypesList min/max 1.
+_COMPUTE_RESOURCE_TYPES = ("MicroVm",)
+
+# NetworkConnectorName: an ARN, or a bare name of 1..64 name characters.
+_NAME_RE = re.compile(r"[a-zA-Z0-9_-]{1,64}")
+# NetworkConnectorSubnetIds max 16; NetworkConnectorSecurityGroupIds max 5.
+_MAX_SUBNETS = 16
+_MAX_SECURITY_GROUPS = 5
+_SUBNET_RE = re.compile(r"subnet-[0-9a-z]*")
+_SECURITY_GROUP_RE = re.compile(r"sg-[0-9a-zA-Z]*")
+# MaxHundredListItems.
+_MAX_ITEMS_MIN, _MAX_ITEMS_MAX = 1, 100
+
+# Exceptions whose message member the model declares capitalised. Every other
+# modelled exception uses lowercase `message`.
+_CAPITALISED_MESSAGE_CODES = frozenset(
+ {"ResourceNotFoundException", "ServiceException"}
+)
+
+# ---------------------------------------------------------------------------
+# State (account + region scoped)
+# ---------------------------------------------------------------------------
+
+_connectors = AccountRegionScopedDict() # Name -> record
+_client_tokens = AccountRegionScopedDict() # ClientToken -> first response
+
+
+def get_state():
+ return copy.deepcopy({"connectors": _connectors, "client_tokens": _client_tokens})
+
+
+def restore_state(data):
+ if not data:
+ return
+ _connectors.clear()
+ _client_tokens.clear()
+ _connectors.update(data.get("connectors", {}))
+ _client_tokens.update(data.get("client_tokens", {}))
+
+
+try:
+ _persisted = load_state("lambda_core")
+ if _persisted:
+ restore_state(_persisted)
+except Exception: # pragma: no cover - best-effort restore
+ logger.exception("Failed to restore persisted lambda_core state; continuing fresh")
+
+
+def reset():
+ _connectors.clear()
+ _client_tokens.clear()
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _now_iso() -> str:
+ """CoreTimestamp is `timestampFormat: iso8601` in the model, so LastModified
+ is an ISO-8601 string rather than the epoch number a json-protocol
+ timestamp would carry."""
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
+
+
+def _connector_arn(name: str) -> str:
+ return (
+ f"arn:aws:lambda:{get_region()}:{get_account_id()}:network-connector:{name}"
+ )
+
+
+def _error(code: str, message: str, status: int, extra: dict | None = None):
+ """A lambda-core error body.
+
+ The protocol is rest-json, so the body is `application/json`. Every
+ modelled exception carries a `Type` member alongside the message, and the
+ message member's casing is per-shape (see the module docstring).
+ """
+ body = dict(extra or {})
+ body["Type"] = "User" if status < 500 else "Service"
+ key = "Message" if code in _CAPITALISED_MESSAGE_CODES else "message"
+ return error_response_json(
+ code, message, status, body,
+ message_key=key,
+ content_type=REST_JSON_CONTENT_TYPE,
+ )
+
+
+def _invalid(message: str):
+ return _error("InvalidParameterValueException", message, 400)
+
+
+def _not_found(identifier: str):
+ return _error(
+ "ResourceNotFoundException",
+ f"Network connector not found: {identifier}",
+ 404,
+ )
+
+
+def _parse_body(body):
+ if not body:
+ return {}, None
+ try:
+ parsed = json.loads(body)
+ except ValueError:
+ return None, _invalid("Could not parse request body as JSON")
+ if not isinstance(parsed, dict):
+ return None, _invalid("Request body must be a JSON object")
+ return parsed, None
+
+
+def _name_from_identifier(identifier: str) -> str:
+ """`Identifier` accepts the name or the ARN; connectors are keyed by name."""
+ if identifier.startswith("arn:"):
+ return identifier.rsplit(":", 1)[-1]
+ return identifier
+
+
+def _validate_configuration(config):
+ """`Configuration.VpcEgressConfiguration` and its members, to the model's
+ own constraints. Wordings are MiniStack's own — the live service was not
+ measured and no message string is documented."""
+ if config is None:
+ return None
+ if not isinstance(config, dict):
+ return _invalid("Configuration must be a structure")
+ vpc = config.get("VpcEgressConfiguration")
+ if vpc is None:
+ return None
+ if not isinstance(vpc, dict):
+ return _invalid("Configuration.VpcEgressConfiguration must be a structure")
+
+ subnets = vpc.get("SubnetIds")
+ if subnets is not None:
+ if not isinstance(subnets, list) or not 1 <= len(subnets) <= _MAX_SUBNETS:
+ return _invalid(
+ "Configuration.VpcEgressConfiguration.SubnetIds must have 1 to "
+ f"{_MAX_SUBNETS} entries"
+ )
+ for subnet in subnets:
+ if not isinstance(subnet, str) or not _SUBNET_RE.fullmatch(subnet):
+ return _invalid(f"Invalid subnet id: {subnet!r}")
+
+ groups = vpc.get("SecurityGroupIds")
+ if groups is not None:
+ if not isinstance(groups, list) or len(groups) > _MAX_SECURITY_GROUPS:
+ return _invalid(
+ "Configuration.VpcEgressConfiguration.SecurityGroupIds must have "
+ f"at most {_MAX_SECURITY_GROUPS} entries"
+ )
+ for group in groups:
+ if not isinstance(group, str) or not _SECURITY_GROUP_RE.fullmatch(group):
+ return _invalid(f"Invalid security group id: {group!r}")
+
+ protocol = vpc.get("NetworkProtocol")
+ if protocol is not None and protocol not in _NETWORK_PROTOCOLS:
+ return _invalid(
+ f"NetworkProtocol must be one of {', '.join(_NETWORK_PROTOCOLS)}"
+ )
+
+ compute = vpc.get("AssociatedComputeResourceTypes")
+ if compute is not None:
+ # AssociatedComputeResourceTypesList is min 1, max 1.
+ if not isinstance(compute, list) or len(compute) != 1:
+ return _invalid(
+ "AssociatedComputeResourceTypes must have exactly 1 entry"
+ )
+ if compute[0] not in _COMPUTE_RESOURCE_TYPES:
+ return _invalid(
+ "AssociatedComputeResourceTypes entries must be one of "
+ f"{', '.join(_COMPUTE_RESOURCE_TYPES)}"
+ )
+ return None
+
+
+def _summary(record: dict) -> dict:
+ """NetworkConnectorSummary: the members ListNetworkConnectors returns."""
+ return {
+ "Arn": record["Arn"],
+ "Name": record["Name"],
+ "Id": record["Id"],
+ "Type": record["Type"],
+ "State": record["State"],
+ "LastModified": record["LastModified"],
+ }
+
+
+def _settle(record: dict) -> dict:
+ """A connector created a moment ago reads back ACTIVE.
+
+ There is no VPC attachment to wait on here, and a client that polls
+ GetNetworkConnector after a 202 needs to see the connector leave PENDING or
+ it never proceeds.
+ """
+ if record.get("State") == _STATE_PENDING:
+ record["State"] = _STATE_ACTIVE
+ return record
+
+
+def _view(record: dict, members: tuple) -> dict:
+ return {k: record[k] for k in members if record.get(k) is not None}
+
+
+# CreateNetworkConnectorResponse members, in model order.
+_CREATE_MEMBERS = ("Arn", "Name", "Id", "Configuration", "OperatorRole", "State")
+# GetNetworkConnectorResponse members, in model order.
+_GET_MEMBERS = (
+ "Arn", "Name", "Id", "Version", "Configuration", "OperatorRole", "State",
+ "StateReason", "StateReasonCode", "LastUpdateStatus", "LastUpdateStatusReason",
+ "LastUpdateStatusReasonCode", "LastModified",
+)
+# UpdateNetworkConnectorResponse members, in model order.
+_UPDATE_MEMBERS = (
+ "Arn", "Name", "Id", "OperatorRole", "Configuration", "State",
+ "LastUpdateStatus", "LastUpdateStatusReason", "LastModified",
+)
+# DeleteNetworkConnectorResponse members, in model order.
+_DELETE_MEMBERS = ("Arn", "Name", "Id", "Configuration", "OperatorRole", "State")
+
+
+# ---------------------------------------------------------------------------
+# Operations
+# ---------------------------------------------------------------------------
+
+
+def _create_network_connector(body):
+ data, err = _parse_body(body)
+ if err:
+ return err
+
+ name = data.get("Name")
+ if not isinstance(name, str) or not name:
+ return _invalid("Name is required")
+ if not _NAME_RE.fullmatch(name):
+ return _invalid(
+ "Name must be 1 to 64 characters of [a-zA-Z0-9_-], or a network "
+ "connector ARN"
+ )
+
+ config = data.get("Configuration")
+ if config is None:
+ return _invalid("Configuration is required")
+ cfg_err = _validate_configuration(config)
+ if cfg_err:
+ return cfg_err
+
+ token = data.get("ClientToken")
+ if token is not None and (not isinstance(token, str) or not 1 <= len(token) <= 64):
+ return _invalid("ClientToken must be 1 to 64 characters")
+ if token:
+ replay = _client_tokens.get(token)
+ if replay is not None:
+ # "All calls after the first that use this token return the same
+ # response as the first call" — the idempotency contract the
+ # ClientToken member exists for.
+ return json_response(dict(replay), content_type=REST_JSON_CONTENT_TYPE)
+
+ if name in _connectors:
+ return _error(
+ "ResourceConflictException",
+ f"Network connector already exists: {name}",
+ 409,
+ )
+
+ record = {
+ "Arn": _connector_arn(name),
+ "Name": name,
+ "Id": new_uuid(),
+ "Type": _TYPE_VPC_EGRESS,
+ "Version": 1,
+ "Configuration": copy.deepcopy(config),
+ "OperatorRole": data.get("OperatorRole"),
+ "State": _STATE_PENDING,
+ "LastUpdateStatus": "Successful",
+ "LastModified": _now_iso(),
+ "Tags": dict(data.get("Tags") or {}),
+ }
+ _connectors[name] = record
+ logger.info("CreateNetworkConnector name=%s id=%s", name, record["Id"])
+
+ response = _view(record, _CREATE_MEMBERS)
+ if token:
+ _client_tokens[token] = dict(response)
+ # The model gives CreateNetworkConnector a 202.
+ return json_response(response, status=202, content_type=REST_JSON_CONTENT_TYPE)
+
+
+def _get_network_connector(identifier):
+ record = _connectors.get(_name_from_identifier(identifier))
+ if record is None:
+ return _not_found(identifier)
+ return json_response(
+ _view(_settle(record), _GET_MEMBERS), content_type=REST_JSON_CONTENT_TYPE
+ )
+
+
+def _update_network_connector(identifier, body):
+ record = _connectors.get(_name_from_identifier(identifier))
+ if record is None:
+ return _not_found(identifier)
+
+ data, err = _parse_body(body)
+ if err:
+ return err
+
+ token = data.get("ClientToken")
+ if token is not None and (not isinstance(token, str) or not 1 <= len(token) <= 64):
+ return _invalid("ClientToken must be 1 to 64 characters")
+
+ if "Configuration" in data:
+ cfg_err = _validate_configuration(data["Configuration"])
+ if cfg_err:
+ return cfg_err
+ record["Configuration"] = copy.deepcopy(data["Configuration"])
+ if "OperatorRole" in data:
+ record["OperatorRole"] = data["OperatorRole"]
+
+ _settle(record)
+ record["Version"] = (record.get("Version") or 0) + 1
+ record["LastUpdateStatus"] = "Successful"
+ record["LastModified"] = _now_iso()
+ logger.info("UpdateNetworkConnector name=%s", record["Name"])
+ # The model gives UpdateNetworkConnector a 202.
+ return json_response(
+ _view(record, _UPDATE_MEMBERS), status=202,
+ content_type=REST_JSON_CONTENT_TYPE,
+ )
+
+
+def _delete_network_connector(identifier):
+ name = _name_from_identifier(identifier)
+ record = _connectors.get(name)
+ if record is None:
+ return _not_found(identifier)
+ # The response reports the connector as it goes away, so the state it
+ # carries is DELETING rather than whatever it was reading before.
+ record = dict(record)
+ record["State"] = "DELETING"
+ del _connectors[name]
+ logger.info("DeleteNetworkConnector name=%s", name)
+ # The model gives DeleteNetworkConnector a 202.
+ return json_response(
+ _view(record, _DELETE_MEMBERS), status=202,
+ content_type=REST_JSON_CONTENT_TYPE,
+ )
+
+
+def _qp(query_params, key, default=None):
+ value = query_params.get(key, default)
+ if isinstance(value, list):
+ return value[0] if value else default
+ return value
+
+
+def _list_network_connectors(query_params):
+ state = _qp(query_params, "State")
+ if state is not None and state not in _STATES:
+ return _invalid(f"State must be one of {', '.join(_STATES)}")
+
+ raw_max = _qp(query_params, "MaxItems")
+ max_items = None
+ if raw_max is not None:
+ try:
+ max_items = int(raw_max)
+ except (TypeError, ValueError):
+ return _invalid("MaxItems must be an integer")
+ if not _MAX_ITEMS_MIN <= max_items <= _MAX_ITEMS_MAX:
+ return _invalid(
+ f"MaxItems must be between {_MAX_ITEMS_MIN} and {_MAX_ITEMS_MAX}"
+ )
+
+ records = [_settle(r) for r in _connectors.values()]
+ if state is not None:
+ records = [r for r in records if r["State"] == state]
+ # Marker carries the name of the last item returned, so a connector created
+ # between pages cannot make the walk repeat an entry the way an offset would.
+ records.sort(key=lambda r: r["Name"])
+
+ marker = _qp(query_params, "Marker")
+ if marker:
+ records = [r for r in records if r["Name"] > marker]
+
+ body = {}
+ if max_items is not None and len(records) > max_items:
+ page = records[:max_items]
+ body["NextMarker"] = page[-1]["Name"]
+ else:
+ page = records
+ body["NetworkConnectors"] = [_summary(r) for r in page]
+ if "NextMarker" in body:
+ body = {"NetworkConnectors": body["NetworkConnectors"],
+ "NextMarker": body["NextMarker"]}
+ return json_response(body, content_type=REST_JSON_CONTENT_TYPE)
+
+
+# ---------------------------------------------------------------------------
+# Dispatcher
+# ---------------------------------------------------------------------------
+
+
+async def handle_request(method, path, headers, body, query_params):
+ parts = [p for p in path.strip("/").split("/") if p]
+ if len(parts) < 2 or parts[0] != API_PREFIX or parts[1] != "network-connectors":
+ return _invalid(f"Unsupported Lambda Core path: {path}")
+
+ segments = parts[2:]
+ if not segments:
+ if method == "POST":
+ return _create_network_connector(body)
+ if method == "GET":
+ return _list_network_connectors(query_params)
+ elif len(segments) == 1:
+ identifier = unquote(segments[0])
+ if method == "GET":
+ return _get_network_connector(identifier)
+ if method == "PUT":
+ return _update_network_connector(identifier, body)
+ if method == "DELETE":
+ return _delete_network_connector(identifier)
+
+ return _invalid(f"Unsupported Lambda Core request: {method} {path}")
diff --git a/pyproject.toml b/pyproject.toml
index a0bfce51..d57fec11 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -114,7 +114,6 @@ select = ["E", "F", "I"]
ignore = [
"E501", # line too long — XML templates and service tables make this impractical
"E402", # module import not at top — intentional lazy imports in service files
- "F401", # unused import — needs manual review; some are re-exports
"F811", # redefined while unused — needs manual review
"F841", # unused variable — needs manual review
"E741", # ambiguous variable name — too noisy for emulator code
diff --git a/tests/test_ec2.py b/tests/test_ec2.py
index 04529919..66860125 100644
--- a/tests/test_ec2.py
+++ b/tests/test_ec2.py
@@ -3514,6 +3514,94 @@ def test_create_fleet_distributes_across_configs_and_overrides(ec2):
assert len(total_ids) == 4
+def test_create_fleet_applies_launch_template_instance_tags(ec2):
+ """A launch template's instance TagSpecifications reach the instances the
+ fleet creates.
+
+ The EC2 model is explicit that this is the mechanism:
+ ``RequestLaunchTemplateData.TagSpecifications`` is "the tags to apply to the
+ resources that are created during instance launch", and
+ ``CreateFleetRequest.TagSpecifications`` says that for a ``maintain`` or
+ ``request`` fleet "you cannot specify a resource type of instance. To tag
+ instances at launch, specify the tags in a launch template."
+ """
+ uid = _uuid_mod.uuid4().hex[:8]
+ lt = ec2.create_launch_template(
+ LaunchTemplateName=f"lt-tags-{uid}",
+ LaunchTemplateData={
+ "ImageId": "ami-12345678",
+ "InstanceType": "t3.micro",
+ "TagSpecifications": [
+ {"ResourceType": "instance",
+ "Tags": [{"Key": "ProbeTag", "Value": "from-launch-template"},
+ {"Key": "EnvironmentTag", "Value": "probe-environment"}]},
+ # A non-instance spec must not leak onto the instance.
+ {"ResourceType": "volume",
+ "Tags": [{"Key": "VolumeOnly", "Value": "yes"}]},
+ ],
+ },
+ )
+ lt_id = lt["LaunchTemplate"]["LaunchTemplateId"]
+ resp = ec2.create_fleet(
+ LaunchTemplateConfigs=[{
+ "LaunchTemplateSpecification": {"LaunchTemplateId": lt_id, "Version": "1"},
+ }],
+ TargetCapacitySpecification={
+ "TotalTargetCapacity": 1,
+ "DefaultTargetCapacityType": "on-demand",
+ },
+ Type="instant",
+ )
+ instance_id = resp["Instances"][0]["InstanceIds"][0]
+ inst = ec2.describe_instances(InstanceIds=[instance_id])[
+ "Reservations"][0]["Instances"][0]
+ tags = {t["Key"]: t["Value"] for t in inst.get("Tags", [])}
+ assert tags.get("ProbeTag") == "from-launch-template"
+ assert tags.get("EnvironmentTag") == "probe-environment"
+ assert "VolumeOnly" not in tags
+
+
+def test_create_fleet_merges_request_and_launch_template_instance_tags(ec2):
+ """An instant fleet may also carry its own instance TagSpecifications. Both
+ sets reach the instance; on a duplicate key the request wins (the merge
+ precedence is MiniStack's choice, not a measured AWS behaviour)."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ lt = ec2.create_launch_template(
+ LaunchTemplateName=f"lt-merge-{uid}",
+ LaunchTemplateData={
+ "ImageId": "ami-12345678",
+ "InstanceType": "t3.micro",
+ "TagSpecifications": [
+ {"ResourceType": "instance",
+ "Tags": [{"Key": "FromTemplate", "Value": "yes"},
+ {"Key": "Shared", "Value": "template"}]},
+ ],
+ },
+ )
+ resp = ec2.create_fleet(
+ LaunchTemplateConfigs=[{
+ "LaunchTemplateSpecification": {
+ "LaunchTemplateId": lt["LaunchTemplate"]["LaunchTemplateId"],
+ "Version": "1"},
+ }],
+ TargetCapacitySpecification={
+ "TotalTargetCapacity": 1,
+ "DefaultTargetCapacityType": "on-demand",
+ },
+ Type="instant",
+ TagSpecifications=[{"ResourceType": "instance",
+ "Tags": [{"Key": "FromRequest", "Value": "yes"},
+ {"Key": "Shared", "Value": "request"}]}],
+ )
+ instance_id = resp["Instances"][0]["InstanceIds"][0]
+ inst = ec2.describe_instances(InstanceIds=[instance_id])[
+ "Reservations"][0]["Instances"][0]
+ tags = {t["Key"]: t["Value"] for t in inst.get("Tags", [])}
+ assert tags.get("FromTemplate") == "yes"
+ assert tags.get("FromRequest") == "yes"
+ assert tags.get("Shared") == "request"
+
+
def test_create_fleet_maintain_returns_fleetid_only(ec2):
"""For Type=maintain (and request), AWS does not launch synchronously —
response carries FleetId only; no Instances / no Errors."""
diff --git a/tests/test_ecs.py b/tests/test_ecs.py
index 44a34c2a..20074495 100644
--- a/tests/test_ecs.py
+++ b/tests/test_ecs.py
@@ -436,7 +436,7 @@ def test_ecs_register_task_def_v2(ecs):
resp2 = ecs.register_task_definition(
family="ecs-td-v2",
- containerDefinitions=[{"name": "web", "image": "nginx:latest", "cpu": 256, "memory": 512}],
+ containerDefinitions=[{"name": "web", "image": "nginx:alpine", "cpu": 256, "memory": 512}],
)
assert resp2["taskDefinition"]["revision"] == 2
diff --git a/tests/test_lambda_core.py b/tests/test_lambda_core.py
new file mode 100644
index 00000000..6c43eace
--- /dev/null
+++ b/tests/test_lambda_core.py
@@ -0,0 +1,212 @@
+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT
+"""AWS Lambda Core network connectors (botocore ``lambda-core`` 2026-04-30).
+
+Driven through a real boto3 ``lambda-core`` client, so every case also covers
+the routing the issue reported: the service signs with credential scope
+``lambda``, so a request that is not disambiguated by path reaches the function
+router and comes back as "Function not found: /2026-04-04/network-connectors".
+"""
+
+import uuid as _uuid_mod
+
+import pytest
+from botocore.exceptions import ClientError
+from conftest import make_client
+
+
[email protected](scope="module")
+def lambda_core():
+ return make_client("lambda-core")
+
+
+def _name(prefix="nc"):
+ return f"{prefix}-{_uuid_mod.uuid4().hex[:8]}"
+
+
+def _config(subnets=("subnet-0123456789abcdef0",), groups=("sg-0123456789abcdef0",),
+ protocol="IPv4"):
+ return {
+ "VpcEgressConfiguration": {
+ "SubnetIds": list(subnets),
+ "SecurityGroupIds": list(groups),
+ "NetworkProtocol": protocol,
+ "AssociatedComputeResourceTypes": ["MicroVm"],
+ }
+ }
+
+
+def test_lambda_core_create_returns_the_modelled_shape(lambda_core):
+ """CreateNetworkConnector answers Arn/Name/Id, the three members the model
+ marks required on the response, plus the echoed Configuration."""
+ name = _name()
+ resp = lambda_core.create_network_connector(Name=name, Configuration=_config())
+ assert resp["Name"] == name
+ assert resp["Id"]
+ assert resp["Arn"].endswith(f":network-connector:{name}")
+ assert resp["Arn"].startswith("arn:aws:lambda:")
+ # NetworkConnectorState enum.
+ assert resp["State"] in ("PENDING", "ACTIVE")
+ vpc = resp["Configuration"]["VpcEgressConfiguration"]
+ assert vpc["SubnetIds"] == ["subnet-0123456789abcdef0"]
+ assert vpc["NetworkProtocol"] == "IPv4"
+ assert vpc["AssociatedComputeResourceTypes"] == ["MicroVm"]
+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 202
+
+
+def test_lambda_core_get_reports_active_and_iso_last_modified(lambda_core):
+ """A connector a client polls after the 202 must leave PENDING, and
+ CoreTimestamp is `timestampFormat: iso8601`, so boto3 parses LastModified
+ into a datetime rather than handing back a number."""
+ import datetime as _dt
+
+ name = _name()
+ lambda_core.create_network_connector(Name=name, Configuration=_config())
+ got = lambda_core.get_network_connector(Identifier=name)
+ assert got["State"] == "ACTIVE"
+ assert got["Name"] == name
+ assert isinstance(got["LastModified"], _dt.datetime)
+
+
+def test_lambda_core_get_accepts_the_arn_as_identifier(lambda_core):
+ """`Identifier` is documented as the name or the ARN."""
+ name = _name()
+ created = lambda_core.create_network_connector(Name=name, Configuration=_config())
+ got = lambda_core.get_network_connector(Identifier=created["Arn"])
+ assert got["Name"] == name
+
+
+def test_lambda_core_update_changes_config_and_keeps_identity(lambda_core):
+ """UpdateNetworkConnector is a 202 and keeps Arn/Name/Id."""
+ name = _name()
+ created = lambda_core.create_network_connector(Name=name, Configuration=_config())
+ updated = lambda_core.update_network_connector(
+ Identifier=name,
+ Configuration=_config(subnets=["subnet-aaaaaaaaaaaaaaaaa"], protocol="DualStack"),
+ )
+ assert updated["ResponseMetadata"]["HTTPStatusCode"] == 202
+ assert updated["Arn"] == created["Arn"]
+ assert updated["Id"] == created["Id"]
+ vpc = updated["Configuration"]["VpcEgressConfiguration"]
+ assert vpc["SubnetIds"] == ["subnet-aaaaaaaaaaaaaaaaa"]
+ assert vpc["NetworkProtocol"] == "DualStack"
+ assert lambda_core.get_network_connector(
+ Identifier=name)["Configuration"]["VpcEgressConfiguration"][
+ "NetworkProtocol"] == "DualStack"
+
+
+def test_lambda_core_delete_removes_it(lambda_core):
+ name = _name()
+ lambda_core.create_network_connector(Name=name, Configuration=_config())
+ deleted = lambda_core.delete_network_connector(Identifier=name)
+ assert deleted["ResponseMetadata"]["HTTPStatusCode"] == 202
+ assert deleted["Name"] == name
+ with pytest.raises(ClientError) as excinfo:
+ lambda_core.get_network_connector(Identifier=name)
+ assert excinfo.value.response["Error"]["Code"] == "ResourceNotFoundException"
+ assert excinfo.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+
+
+def test_lambda_core_list_filters_by_state_and_pages(lambda_core):
+ """ListNetworkConnectors takes State/Marker/MaxItems on the query string and
+ answers NetworkConnectors + NextMarker."""
+ prefix = _name("page")
+ made = sorted(f"{prefix}-{i}" for i in range(3))
+ for n in made:
+ lambda_core.create_network_connector(Name=n, Configuration=_config())
+
+ seen, marker = [], None
+ while True:
+ kwargs = {"MaxItems": 1}
+ if marker:
+ kwargs["Marker"] = marker
+ page = lambda_core.list_network_connectors(**kwargs)
+ seen.extend(c["Name"] for c in page["NetworkConnectors"]
+ if c["Name"].startswith(prefix))
+ marker = page.get("NextMarker")
+ if not marker:
+ break
+ assert seen == made
+
+ summary = [c for c in lambda_core.list_network_connectors(
+ State="ACTIVE")["NetworkConnectors"] if c["Name"] == made[0]][0]
+ # NetworkConnectorSummary.Type is required, and VPC_EGRESS is the one value
+ # the model's NetworkConnectorType enum carries.
+ assert summary["Type"] == "VPC_EGRESS"
+ assert summary["State"] == "ACTIVE"
+
+
+def test_lambda_core_client_token_replays_the_first_response(lambda_core):
+ """ClientToken is an idempotency token: the second call answers the first
+ call's response and creates nothing new."""
+ token = _uuid_mod.uuid4().hex
+ first = lambda_core.create_network_connector(
+ Name=_name(), Configuration=_config(), ClientToken=token)
+ second = lambda_core.create_network_connector(
+ Name=_name(), Configuration=_config(), ClientToken=token)
+ assert second["Id"] == first["Id"]
+ assert second["Name"] == first["Name"]
+
+
+def test_lambda_core_duplicate_name_conflicts(lambda_core):
+ name = _name()
+ lambda_core.create_network_connector(Name=name, Configuration=_config())
+ with pytest.raises(ClientError) as excinfo:
+ lambda_core.create_network_connector(Name=name, Configuration=_config())
+ assert excinfo.value.response["Error"]["Code"] == "ResourceConflictException"
+ assert excinfo.value.response["ResponseMetadata"]["HTTPStatusCode"] == 409
+
+
+def test_lambda_core_unknown_identifier_is_not_found(lambda_core):
+ for call in ("get_network_connector", "delete_network_connector"):
+ with pytest.raises(ClientError) as excinfo:
+ getattr(lambda_core, call)(Identifier="no-such-connector")
+ assert excinfo.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
[email protected]("config,reason", [
+ ({"VpcEgressConfiguration": {"SubnetIds": ["not-a-subnet"]}}, "subnet id"),
+ ({"VpcEgressConfiguration": {"SecurityGroupIds": ["nope"]}}, "security group"),
+ ({"VpcEgressConfiguration": {"NetworkProtocol": "IPv6"}}, "NetworkProtocol enum"),
+ ({"VpcEgressConfiguration": {"AssociatedComputeResourceTypes": ["Nope"]}},
+ "ComputeResourceType enum"),
+])
+def test_lambda_core_configuration_constraints_are_enforced(lambda_core, config, reason):
+ """The model's own constraints: subnet/sg id patterns, the NetworkProtocol
+ and ComputeResourceType enums, and AssociatedComputeResourceTypesList min 1.
+
+ Only the error code is asserted. No message string is documented for this
+ service, so the wordings are MiniStack's own and pinning one here would
+ read as if it had been measured."""
+ with pytest.raises(ClientError) as excinfo:
+ lambda_core.create_network_connector(Name=_name(), Configuration=config)
+ err = excinfo.value.response
+ assert err["Error"]["Code"] == "InvalidParameterValueException", reason
+ assert err["ResponseMetadata"]["HTTPStatusCode"] == 400
+
+
+def test_lambda_core_empty_compute_resource_types_is_refused_on_the_wire():
+ """AssociatedComputeResourceTypesList is min 1, so botocore refuses an
+ empty list client-side and it never reaches the server. Send it raw to
+ prove the service refuses it too, rather than accepting a shape the model
+ forbids."""
+ raw = make_client("lambda-core", {"parameter_validation": False})
+ with pytest.raises(ClientError) as excinfo:
+ raw.create_network_connector(
+ Name=_name(),
+ Configuration={"VpcEgressConfiguration":
+ {"AssociatedComputeResourceTypes": []}},
+ )
+ err = excinfo.value.response
+ assert err["Error"]["Code"] == "InvalidParameterValueException"
+ assert err["ResponseMetadata"]["HTTPStatusCode"] == 400
+
+
+def test_lambda_core_does_not_shadow_the_lambda_function_api(lambda_core):
+ """The whole point of the routing fix: lambda-core signs with credential
+ scope `lambda`, so adding it must not divert the function API."""
+ lam = make_client("lambda")
+ with pytest.raises(ClientError) as excinfo:
+ lam.get_function(FunctionName="definitely-not-a-function")
+ assert excinfo.value.response["Error"]["Code"] == "ResourceNotFoundException"
+ # And the connector surface still answers on the same endpoint.
+ assert "NetworkConnectors" in lambda_core.list_network_connectors()
diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.py
index 5755e1d2..b5afefac 100644
--- a/tests/test_stepfunctions.py
+++ b/tests/test_stepfunctions.py
@@ -3773,7 +3773,11 @@ def test_sfn_integration_ecs_run_task_output_contains_status(sfn, ecs):
containerDefinitions=[
{
"name": "app",
- "image": "nginx:latest",
+ # alpine variant: this one really is launched (ecs:runTask),
+ # so the tag is a ~200MB pull rather than task-definition
+ # metadata. lastStatus RUNNING holds either way — both images
+ # are long-running servers.
+ "image": "nginx:alpine",
"memory": 256,
}
],
@@ -8128,3 +8132,117 @@ def test_sfn_choice_numeric_path_dynamic_batch_loop(sfn):
assert output["index"] == 3
finally:
sfn.delete_state_machine(stateMachineArn=arn)
+
+
+# ---------------------------------------------------------------------------
+# Numeric ``*Path`` Choice operators, exercised against the ASL rule evaluator
+# directly rather than through a running execution. The integration cover is
+# ``test_sfn_choice_numeric_path_dynamic_batch_loop`` above.
+# ---------------------------------------------------------------------------
+
+
+def test_numeric_path_operators_relate_variable_to_resolved_path():
+ """NumericLessThanPath/GreaterThanPath/LessThanEqualsPath/GreaterThanEqualsPath
+ compare the Variable-resolved LHS against the path-resolved RHS."""
+ from ministack.services.stepfunctions import _evaluate_rule
+
+ data = {"value": 5, "limit": 3, "floor": 5, "ceil": 10}
+ assert _evaluate_rule({"Variable": "$.value", "NumericLessThanPath": "$.ceil"}, data)
+ assert _evaluate_rule({"Variable": "$.value", "NumericGreaterThanPath": "$.limit"}, data)
+ assert _evaluate_rule({"Variable": "$.value", "NumericLessThanEqualsPath": "$.floor"}, data)
+ assert _evaluate_rule({"Variable": "$.value", "NumericGreaterThanEqualsPath": "$.floor"}, data)
+ # Inverse comparisons must not match.
+ assert not _evaluate_rule({"Variable": "$.value", "NumericLessThanPath": "$.limit"}, data)
+ assert not _evaluate_rule({"Variable": "$.value", "NumericGreaterThanPath": "$.ceil"}, data)
+ assert not _evaluate_rule({"Variable": "$.value", "NumericLessThanEqualsPath": "$.limit"}, data)
+ assert not _evaluate_rule({"Variable": "$.value", "NumericGreaterThanEqualsPath": "$.ceil"}, data)
+
+
+def test_numeric_path_operators_reject_bool_operand():
+ """Booleans are not numeric operands: ``_is_num`` excludes ``bool`` even though
+ ``bool`` is an ``int`` subclass in Python."""
+ from ministack.services.stepfunctions import _evaluate_rule
+
+ data = {"flag": True, "limit": 0}
+ for op in (
+ "NumericEqualsPath",
+ "NumericLessThanPath",
+ "NumericGreaterThanPath",
+ "NumericLessThanEqualsPath",
+ "NumericGreaterThanEqualsPath",
+ ):
+ assert not _evaluate_rule({"Variable": "$.flag", op: "$.limit"}, data), op
+
+
+def test_numeric_path_operators_reject_non_numeric_operand():
+ """Strings and missing values are not numeric operands."""
+ from ministack.services.stepfunctions import _evaluate_rule
+
+ data = {"text": "5", "limit": 3}
+ for op in (
+ "NumericLessThanPath",
+ "NumericGreaterThanPath",
+ "NumericLessThanEqualsPath",
+ "NumericGreaterThanEqualsPath",
+ ):
+ assert not _evaluate_rule({"Variable": "$.text", op: "$.limit"}, data), op
+ assert not _evaluate_rule({"Variable": "$.missing", op: "$.limit"}, data), op
+
+
+def test_numeric_path_operators_float_operands():
+ """Float LHS and RHS values compare correctly."""
+ from ministack.services.stepfunctions import _evaluate_rule
+
+ data = {"value": 0.5, "limit": 0.25}
+ assert _evaluate_rule({"Variable": "$.value", "NumericGreaterThanPath": "$.limit"}, data)
+ assert _evaluate_rule({"Variable": "$.value", "NumericGreaterThanEqualsPath": "$.limit"}, data)
+ assert not _evaluate_rule({"Variable": "$.value", "NumericLessThanPath": "$.limit"}, data)
+
+
+def test_numeric_path_operators_reject_non_numeric_rhs():
+ """A non-numeric RHS (missing, string, null, or bool) must make the rule False:
+ no TypeError from comparing a number to a string and no bool coerced to int
+ (e.g. ``1 >= True`` must not match)."""
+ from ministack.services.stepfunctions import _evaluate_rule
+
+ cases = [
+ ("missing", {}),
+ ("text", {"text": "3"}),
+ ("null", {"null": None}),
+ ("flag", {"flag": True}),
+ ]
+ for op in (
+ "NumericLessThanPath",
+ "NumericGreaterThanPath",
+ "NumericLessThanEqualsPath",
+ "NumericGreaterThanEqualsPath",
+ ):
+ for rhs_key, data in cases:
+ data = {**data, "value": 1}
+ # "1 >= True" is True under raw Python int coercion; the guarded
+ # comparison must return False instead.
+ assert not _evaluate_rule({"Variable": "$.value", op: f"$.{rhs_key}"}, data), (
+ op,
+ rhs_key,
+ )
+
+
+def test_numeric_path_operators_accept_int_float_rhs_mix():
+ """int LHS vs float RHS (and vice versa) still compares numerically."""
+ from ministack.services.stepfunctions import _evaluate_rule
+
+ assert _evaluate_rule(
+ {"Variable": "$.value", "NumericLessThanPath": "$.limit"}, {"value": 1, "limit": 1.5}
+ )
+ assert _evaluate_rule(
+ {"Variable": "$.value", "NumericGreaterThanEqualsPath": "$.limit"}, {"value": 2.0, "limit": 2}
+ )
+
+
+def test_numeric_equals_path_still_works():
+ """Regression guard for the pre-existing NumericEqualsPath operator."""
+ from ministack.services.stepfunctions import _evaluate_rule
+
+ data = {"value": 7, "expected": 7}
+ assert _evaluate_rule({"Variable": "$.value", "NumericEqualsPath": "$.expected"}, data)
+ assert not _evaluate_rule({"Variable": "$.value", "NumericEqualsPath": "$.other"}, {"value": 7, "other": 8})
diff --git a/tests/test_stepfunctions_choice_numeric_paths.py b/tests/test_stepfunctions_choice_numeric_paths.py
deleted file mode 100644
index 6d466663..00000000
--- a/tests/test_stepfunctions_choice_numeric_paths.py
+++ /dev/null
@@ -1,101 +0,0 @@
-# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT
-"""Unit tests for numeric ``*Path`` Choice operators in the Step Functions engine.
-
-Unlike the integration tests in ``test_stepfunctions.py`` these exercise the
-ASL rule evaluator directly, so no running emulator is required.
-"""
-
-from ministack.services.stepfunctions import _evaluate_rule
-
-
-def test_numeric_path_operators_relate_variable_to_resolved_path():
- """NumericLessThanPath/GreaterThanPath/LessThanEqualsPath/GreaterThanEqualsPath
- compare the Variable-resolved LHS against the path-resolved RHS."""
- data = {"value": 5, "limit": 3, "floor": 5, "ceil": 10}
- assert _evaluate_rule({"Variable": "$.value", "NumericLessThanPath": "$.ceil"}, data)
- assert _evaluate_rule({"Variable": "$.value", "NumericGreaterThanPath": "$.limit"}, data)
- assert _evaluate_rule({"Variable": "$.value", "NumericLessThanEqualsPath": "$.floor"}, data)
- assert _evaluate_rule({"Variable": "$.value", "NumericGreaterThanEqualsPath": "$.floor"}, data)
- # Inverse comparisons must not match.
- assert not _evaluate_rule({"Variable": "$.value", "NumericLessThanPath": "$.limit"}, data)
- assert not _evaluate_rule({"Variable": "$.value", "NumericGreaterThanPath": "$.ceil"}, data)
- assert not _evaluate_rule({"Variable": "$.value", "NumericLessThanEqualsPath": "$.limit"}, data)
- assert not _evaluate_rule({"Variable": "$.value", "NumericGreaterThanEqualsPath": "$.ceil"}, data)
-
-
-def test_numeric_path_operators_reject_bool_operand():
- """Booleans are not numeric operands: ``_is_num`` excludes ``bool`` even though
- ``bool`` is an ``int`` subclass in Python."""
- data = {"flag": True, "limit": 0}
- for op in (
- "NumericEqualsPath",
- "NumericLessThanPath",
- "NumericGreaterThanPath",
- "NumericLessThanEqualsPath",
- "NumericGreaterThanEqualsPath",
- ):
- assert not _evaluate_rule({"Variable": "$.flag", op: "$.limit"}, data), op
-
-
-def test_numeric_path_operators_reject_non_numeric_operand():
- """Strings and missing values are not numeric operands."""
- data = {"text": "5", "limit": 3}
- for op in (
- "NumericLessThanPath",
- "NumericGreaterThanPath",
- "NumericLessThanEqualsPath",
- "NumericGreaterThanEqualsPath",
- ):
- assert not _evaluate_rule({"Variable": "$.text", op: "$.limit"}, data), op
- assert not _evaluate_rule({"Variable": "$.missing", op: "$.limit"}, data), op
-
-
-def test_numeric_path_operators_float_operands():
- """Float LHS and RHS values compare correctly."""
- data = {"value": 0.5, "limit": 0.25}
- assert _evaluate_rule({"Variable": "$.value", "NumericGreaterThanPath": "$.limit"}, data)
- assert _evaluate_rule({"Variable": "$.value", "NumericGreaterThanEqualsPath": "$.limit"}, data)
- assert not _evaluate_rule({"Variable": "$.value", "NumericLessThanPath": "$.limit"}, data)
-
-
-def test_numeric_path_operators_reject_non_numeric_rhs():
- """A non-numeric RHS (missing, string, null, or bool) must make the rule False:
- no TypeError from comparing a number to a string and no bool coerced to int
- (e.g. ``1 >= True`` must not match)."""
- cases = [
- ("missing", {}),
- ("text", {"text": "3"}),
- ("null", {"null": None}),
- ("flag", {"flag": True}),
- ]
- for op in (
- "NumericLessThanPath",
- "NumericGreaterThanPath",
- "NumericLessThanEqualsPath",
- "NumericGreaterThanEqualsPath",
- ):
- for rhs_key, data in cases:
- data = {**data, "value": 1}
- # "1 >= True" is True under raw Python int coercion; the guarded
- # comparison must return False instead.
- assert not _evaluate_rule({"Variable": "$.value", op: f"$.{rhs_key}"}, data), (
- op,
- rhs_key,
- )
-
-
-def test_numeric_path_operators_accept_int_float_rhs_mix():
- """int LHS vs float RHS (and vice versa) still compares numerically."""
- assert _evaluate_rule(
- {"Variable": "$.value", "NumericLessThanPath": "$.limit"}, {"value": 1, "limit": 1.5}
- )
- assert _evaluate_rule(
- {"Variable": "$.value", "NumericGreaterThanEqualsPath": "$.limit"}, {"value": 2.0, "limit": 2}
- )
-
-
-def test_numeric_equals_path_still_works():
- """Regression guard for the pre-existing NumericEqualsPath operator."""
- data = {"value": 7, "expected": 7}
- assert _evaluate_rule({"Variable": "$.value", "NumericEqualsPath": "$.expected"}, data)
- assert not _evaluate_rule({"Variable": "$.value", "NumericEqualsPath": "$.other"}, {"value": 7, "other": 8})