Skip to content

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

feat: AmazonMQ support (#875)

Lucas Giacomazzie8fa1bf0898b
diff --git a/README.md b/README.md
index 7f32f362..d4e3f414 100644
--- a/README.md
+++ b/README.md
@@ -389,6 +389,8 @@ subnet = ec2.create_subnet(
| **Resource Groups** | CreateGroup, GetGroup, DeleteGroup, UpdateGroup, ListGroups, GetGroupQuery, UpdateGroupQuery, GetGroupConfiguration, PutGroupConfiguration, GroupResources, UngroupResources, ListGroupResources, ListGroupingStatuses, SearchResources, Tag, Untag, GetTags, GetAccountSettings, UpdateAccountSettings | 19 of 23 spec ops; tag-sync ops omitted (not exposed by AWS CLI / Terraform); `Group` accepts bare name or full ARN |
| **Cost & Usage Reports** | DeleteReportDefinition, DescribeReportDefinitions, ListTagsForResource, ModifyReportDefinition, PutReportDefinition, TagResource, UntagResource | 7 of 7 spec ops |
| **Inspector2** | Enable, Disable, ListFindings, BatchGetFindingDetails, ListCoverage, ListCoverageStatistics, ListFindingAggregations, SearchVulnerabilities, TagResource, UntagResource, ListTagsForResource, CreateFilter, ListFilters, DeleteFilter | 14 operations; deterministic stub vulnerability findings for ECR images, Lambda functions, and EC2 instances; filtering, sorting, pagination |
+| **AmazonMQ** | CreateBroker, ListBrokers, DescribeBrokers, DeleteBrokers, UpdateBroker, RebootBroker, DescribeBrokerEngineTypes, DescribeBrokerInstanceOptions, CreateTags, ListTags, DeleteTags, CreateUser, DeleteUser, ListUsers, UpdateUser, DescribeUser | 16 of 24 spec ops; No real container support |
+
### CloudFormation
diff --git a/ministack/app.py b/ministack/app.py
index f4c6a9e4..05bad538 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -311,6 +311,7 @@ SERVICE_REGISTRY = {
"cloudtrail": {"module": "cloudtrail"},
"cur": {"module": "cur"},
"inspector2": {"module": "inspector2"},
+ "mq": {"module": "mq"},
"s3tables": {"module": "s3tables"},
}
@@ -348,6 +349,7 @@ _state_map = {
"resource_groups": "resource_groups",
"cloudtrail": "cloudtrail", "iot": "iot",
"inspector2": "inspector2",
+ "mq": "mq",
"s3tables": "s3tables",
"lambda_durable": "lambda_durable",
}
diff --git a/ministack/core/router.py b/ministack/core/router.py
index 5bf2db0c..076f27d0 100644
--- a/ministack/core/router.py
+++ b/ministack/core/router.py
@@ -249,6 +249,15 @@ SERVICE_PATTERNS = {
"path_prefixes": ["/v1/"],
"credential_scope": "batch",
},
+ "mq": {
+ "host_patterns": [r"mq\."],
+ "path_patterns": [
+ r"^/v1/brokers",
+ r"^/v1/broker-engine-types",
+ r"^/v1/broker-instance-options",
+ r"^/v1/tags"
+ ],
+ },
"cloudformation": {
"host_patterns": [r"cloudformation\."],
},
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 55dcc314..1ea45ddf 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -1312,13 +1312,18 @@ def _cfn_nested_stack_deploy(logical_id, props, parent_stack_name, *,
sub-attribute form CDK and console-built templates emit.
"""
import copy
+
from ministack.core.responses import get_account_id, get_region, new_uuid
from ministack.services.cloudformation import (
- _stack_events, _stacks,
+ _stack_events,
+ _stacks,
)
from ministack.services.cloudformation.engine import (
- _evaluate_conditions, _parse_template, _resolve_parameters,
- _resolve_refs, _topological_sort,
+ _evaluate_conditions,
+ _parse_template,
+ _resolve_parameters,
+ _resolve_refs,
+ _topological_sort,
)
from ministack.services.cloudformation.helpers import _resolve_template
from ministack.services.cloudformation.stacks import _add_event
diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.py
index c1f2a2b1..348beac0 100644
--- a/ministack/services/dynamodb.py
+++ b/ministack/services/dynamodb.py
@@ -249,7 +249,7 @@ def _validate_attribute_value(attr_name: str, value: dict) -> tuple | None:
if vtype == "S":
if not isinstance(vval, str):
return error_response_json("ValidationException",
- f"Supplied AttributeValue is empty, must contain exactly one of the supported datatypes", 400)
+ "Supplied AttributeValue is empty, must contain exactly one of the supported datatypes", 400)
elif vtype == "N":
canon = _ddb_canonicalize_number(vval)
if canon is None:
@@ -332,7 +332,7 @@ def _validate_attribute_value(attr_name: str, value: dict) -> tuple | None:
return err
else:
return error_response_json("ValidationException",
- f"Supplied AttributeValue is empty, must contain exactly one of the supported datatypes", 400)
+ "Supplied AttributeValue is empty, must contain exactly one of the supported datatypes", 400)
return None
@@ -429,7 +429,7 @@ def _validate_item(item: dict, pk_name: str | None = None, sk_name: str | None =
size = _item_size_bytes(item)
if size > _DDB_ITEM_MAX_BYTES:
return error_response_json("ValidationException",
- f"Item size has exceeded the maximum allowed size", 400)
+ "Item size has exceeded the maximum allowed size", 400)
return None
# DynamoDB Streams: table_name -> list of stream records
@@ -1701,7 +1701,7 @@ def _query(data):
# Limit must be >= 1 when supplied.
if limit is not None and int(limit) <= 0:
return error_response_json("ValidationException",
- f"1 validation error detected: Value at 'Limit' failed to satisfy constraint: Member must have value greater than or equal to 1", 400)
+ "1 validation error detected: Value at 'Limit' failed to satisfy constraint: Member must have value greater than or equal to 1", 400)
# Select validation per AWS: ALL_PROJECTED_ATTRIBUTES is only valid on an
# index; SPECIFIC_ATTRIBUTES requires a ProjectionExpression / AttributesToGet.
if select == "ALL_PROJECTED_ATTRIBUTES" and not index_name:
@@ -1715,7 +1715,7 @@ def _query(data):
# ConsistentRead on a GSI is invalid (only LSIs support strongly-consistent reads).
if data.get("ConsistentRead") and is_gsi:
return error_response_json("ValidationException",
- f"Consistent reads are not supported on global secondary indexes", 400)
+ "Consistent reads are not supported on global secondary indexes", 400)
# ExclusiveStartKey must contain the base table's key attributes; when
# querying an index, it must also contain the index's key attributes.
@@ -1923,7 +1923,7 @@ def _scan(data):
seg = int(segment); ts = int(total_segments)
if ts < 1 or ts > 1_000_000:
return error_response_json("ValidationException",
- f"TotalSegments must be between 1 and 1000000", 400)
+ "TotalSegments must be between 1 and 1000000", 400)
# Negative segment uses the standard "1 validation error detected"
# envelope with the lowercase 'segment' slot and "greater than or
# equal to 0" floor — distinct from the segment>=totalSegments error.
diff --git a/ministack/services/elasticache.py b/ministack/services/elasticache.py
index 8784fe8f..169cb2a3 100644
--- a/ministack/services/elasticache.py
+++ b/ministack/services/elasticache.py
@@ -113,6 +113,7 @@ _pending_rg_respawn: set = set()
# Serialize lazy respawn so two concurrent first-requests after restart
# don't both spawn a container for the same cluster.
import threading as _threading
+
_respawn_lock = _threading.Lock()
diff --git a/ministack/services/lambda_durable.py b/ministack/services/lambda_durable.py
index 8fbc1a5e..5853001a 100644
--- a/ministack/services/lambda_durable.py
+++ b/ministack/services/lambda_durable.py
@@ -26,6 +26,7 @@ import time
import uuid
from urllib.parse import unquote
+from ministack.core.persistence import load_state
from ministack.core.responses import (
AccountScopedDict,
error_response_json,
@@ -33,8 +34,6 @@ from ministack.core.responses import (
get_region,
json_response,
)
-from ministack.core.persistence import load_state
-
# ---------------------------------------------------------------------------
# State
@@ -400,6 +399,7 @@ def _fire_chained_invoke(parent_rec: dict, op_id: str, ci_opts: dict,
its result back onto the parent's ChainedInvoke operation when the child
completes."""
import threading
+
from ministack.services import lambda_svc
target = ci_opts.get("FunctionName")
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index 32d1d306..ed9aa0ca 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -28,13 +28,13 @@ import asyncio
import base64
import copy
import hashlib
-import secrets
import importlib
import io
import json
import logging
import os
import re
+import secrets
import socket
import subprocess
import tempfile
diff --git a/ministack/services/mq.py b/ministack/services/mq.py
new file mode 100644
index 00000000..91b62b72
--- /dev/null
+++ b/ministack/services/mq.py
@@ -0,0 +1,953 @@
+"""AmazonMQ Service Emulator.
+
+This module provides a mock implementation of AWS MQ (Message Broker) service,
+supporting both RabbitMQ and ActiveMQ engines with configurable deployment modes,
+host instance types, and storage backends.
+
+Key Components:
+- Broker lifecycle management (create, describe, update, delete, reboot)
+- User management for ActiveMQ brokers
+- Tag management for brokers
+- Broker metadata and configuration queries
+- Persistence of broker state across service restarts
+
+State Management:
+- _brokers: Maps broker_id → broker configuration dict
+- _name_index: Maps broker_name → broker_id (prevents duplicate names)
+- _tags: Maps broker_arn → tags dict
+- _users: Maps broker_id → {username → user_config} (ActiveMQ only)
+
+All state is persisted to disk via ministack.core.persistence.
+"""
+
+import copy
+import json
+import logging
+import re
+import time
+from urllib.parse import unquote
+
+from ministack.core.persistence import load_state
+from ministack.core.responses import AccountScopedDict, get_account_id, get_region, new_uuid
+
+logger = logging.getLogger("mq")
+
+
+# ============================================================================
+# Module State
+# ============================================================================
+# These module-level dicts are scoped per AWS account/region via AccountScopedDict.
+# Invariants to maintain:
+# - _name_index[name] must exist iff _brokers[id].brokerName == name
+# - _tags[arn] exists iff _brokers[id] with matching arn exists
+# - _users[id] exists iff _brokers[id].engineType == "ACTIVEMQ"
+
+_brokers: AccountScopedDict = AccountScopedDict()
+_name_index: AccountScopedDict = AccountScopedDict()
+_tags: AccountScopedDict = AccountScopedDict()
+_users: AccountScopedDict = AccountScopedDict()
+
+
+# ============================================================================
+# Configuration & Supported Engines
+# ============================================================================
+
+SUPPORTED_ENGINES = {
+ "RABBITMQ": {
+ "storage_types": ["EBS"],
+ "deployment_modes": ["SINGLE_INSTANCE", "CLUSTER_MULTI_AZ"],
+ "versions": ["4.2", "3.13"],
+ # output of
+ # aws mq describe-broker-instance-options \
+ # --engine-type RABBITMQ \
+ # --query 'BrokerInstanceOptions[].HostInstanceType' \
+ # --output json
+ "host_instance_types": [
+ "mq.m5.2xlarge", "mq.m5.4xlarge", "mq.m5.large", "mq.m5.xlarge",
+ "mq.m7g.12xlarge", "mq.m7g.16xlarge", "mq.m7g.2xlarge", "mq.m7g.4xlarge",
+ "mq.m7g.8xlarge", "mq.m7g.large", "mq.m7g.medium", "mq.m7g.xlarge",
+ ],
+ },
+ "ACTIVEMQ": {
+ "storage_types": ["EBS", "EFS"],
+ "deployment_modes": ["SINGLE_INSTANCE", "ACTIVE_STANDBY_MULTI_AZ"],
+ "versions": ["5.19", "5.18"],
+ # output of
+ # aws mq describe-broker-instance-options \
+ # --engine-type ACTIVEMQ \
+ # --query 'BrokerInstanceOptions[].HostInstanceType' \
+ # --output json
+ "host_instance_types": [
+ "mq.m5.2xlarge", "mq.m5.4xlarge", "mq.m5.large", "mq.m5.xlarge", "mq.t3.micro"
+ ],
+ },
+}
+
+
+# ============================================================================
+# HTTP & Error Constants
+# ============================================================================
+
+HTTP_STATUS_TO_EXCEPTION = {
+ 400: "BadRequestException",
+ 403: "ForbiddenException",
+ 404: "NotFoundException",
+ 409: "ConflictException",
+ 500: "InternalServerErrorException",
+}
+
+HTTP_JSON_HEADERS = {"Content-Type": "application/json"}
+
+
+# ============================================================================
+# Error Messages
+# ============================================================================
+# Centralized error messages to prevent duplication and improve consistency.
+
+ERROR_MESSAGES = {
+ # Broker name validation
+ "BROKER_NAME_REQUIRED": "brokerName is required.",
+ "BROKER_NAME_INVALID": "brokerName is invalid.",
+ "BROKER_NAME_EXISTS": "A broker with the name '{}' already exists.",
+ "BROKER_NOT_FOUND": "Broker '{}' does not exist.",
+
+ # Engine configuration
+ "ENGINE_TYPE_UNSUPPORTED": "Unsupported engine type '{}'.",
+ "ENGINE_VERSION_INVALID": "Engine version is invalid.",
+ "DEPLOYMENT_MODE_INVALID": "Deployment mode is invalid.",
+
+ # Instance & storage types
+ "HOST_INSTANCE_TYPE_INVALID": "Host instance type is invalid.",
+ "STORAGE_TYPE_INVALID": "Invalid storage type: '{}'.",
+
+ # User management
+ "USER_ALREADY_EXISTS": "User '{}' already exists.",
+ "USER_NOT_FOUND": "User '{}' does not exist.",
+ "PASSWORD_INVALID": "Password must be at least 4 characters and cannot contain ',', ':' or '='.",
+ "ACTIVEMQ_ONLY_OP": "This operation is supported only for ActiveMQ brokers.",
+
+ # Broker state
+ "BROKER_NOT_RUNNING": "You can reboot only a broker with RUNNING status.",
+
+ # Tagging
+ "RESOURCE_NOT_FOUND": "Resource '{}' does not exist.",
+ "TAG_KEYS_REQUIRED": "tagKeys is required.",
+
+ # Pagination
+ "MAX_RESULTS_INVALID": "maxResults must be an integer from 5 to 100.",
+ "NEXT_TOKEN_INVALID": "nextToken is invalid.",
+
+ # Request parsing
+ "JSON_INVALID": "Invalid JSON in request body.",
+ "TAGS_INVALID": "tags must be an object.",
+
+ # Generic
+ "ACTION_UNKNOWN": "Unknown action: {} {}",
+}
+
+
+# ============================================================================
+# Validation Patterns (Regex)
+# ============================================================================
+# All regex patterns with documentation for their purpose.
+
+# Broker name: 1-50 alphanumeric characters, hyphens, underscores
+BROKER_NAME_PATTERN = re.compile(r"^[A-Za-z0-9_-]{1,50}$")
+
+# Broker ID extraction from path: /v1/brokers/{id}
+BROKER_ID_PATH_PATTERN = re.compile(r"^/v1/brokers/([^/]+)$")
+
+# Broker reboot from path: /v1/brokers/{id}/reboot
+BROKER_REBOOT_PATH_PATTERN = re.compile(r"^/v1/brokers/([^/]+)/reboot$")
+
+# Users list from path: /v1/brokers/{id}/users
+BROKER_USERS_PATH_PATTERN = re.compile(r"^/v1/brokers/([^/]+)/users$")
+
+# User operations from path: /v1/brokers/{id}/users/{username}
+BROKER_USER_PATH_PATTERN = re.compile(r"^/v1/brokers/([^/]+)/users/([^/]+)$")
+
+# Tag operations from path: /v1/tags/{arn}
+TAGS_PATH_PATTERN = re.compile(r"^/v1/tags/(.+)$")
+
+# Password: cannot contain comma, colon, or equals (AWS MQ limitation)
+INVALID_PASSWORD_CHARS_PATTERN = re.compile(r"[,:=]")
+
+
+# ============================================================================
+# Service Implementation
+# ============================================================================
+
+# ============================================================================
+# Validation Helpers
+# ============================================================================
+# Centralized validation functions to reduce code duplication and improve
+# testability. All validation functions return None on success or an error
+# tuple (status, headers, body) on failure.
+
+
+def _validate_broker_config(body: dict) -> tuple | None:
+ """Validate all required broker configuration fields.
+
+ Returns None if valid, or error tuple if invalid.
+ """
+ engine_type = str(body.get("engineType", "")).strip().upper()
+ if engine_type not in SUPPORTED_ENGINES:
+ return _err(400, "EngineType", ERROR_MESSAGES["ENGINE_TYPE_UNSUPPORTED"].format(engine_type))
+
+ broker_name = str(body.get("brokerName", "")).strip()
+ if not broker_name:
+ return _err(400, "BrokerName", ERROR_MESSAGES["BROKER_NAME_REQUIRED"])
+ if not BROKER_NAME_PATTERN.fullmatch(broker_name):
+ return _err(400, "BrokerName", ERROR_MESSAGES["BROKER_NAME_INVALID"])
+ if broker_name in _name_index:
+ return _err(409, "BrokerName", ERROR_MESSAGES["BROKER_NAME_EXISTS"].format(broker_name))
+
+ engine_versions = SUPPORTED_ENGINES[engine_type]["versions"]
+ engine_version = body.get("engineVersion") or engine_versions[0]
+ if engine_version not in engine_versions:
+ return _err(400, "EngineVersion", ERROR_MESSAGES["ENGINE_VERSION_INVALID"])
+
+ deployment_mode = str(body.get("deploymentMode", "SINGLE_INSTANCE")).upper()
+ if deployment_mode not in SUPPORTED_ENGINES[engine_type]["deployment_modes"]:
+ return _err(400, "DeploymentMode", ERROR_MESSAGES["DEPLOYMENT_MODE_INVALID"])
+
+ host_instance_type = body.get("hostInstanceType", "mq.m5.large")
+ if host_instance_type not in _valid_host_instance_types(engine_type):
+ return _err(400, "HostInstanceType", ERROR_MESSAGES["HOST_INSTANCE_TYPE_INVALID"])
+
+ storage_type = body.get("storageType", "EBS")
+ if storage_type and storage_type not in _valid_storage_types(engine_type):
+ return _err(400, "StorageType", ERROR_MESSAGES["STORAGE_TYPE_INVALID"].format(storage_type))
+
+ return None
+
+
+def _validate_broker_update_fields(broker: dict, body: dict) -> tuple | None:
+ """Validate broker update fields.
+
+ Returns None if valid, or error tuple if invalid.
+ Only validates fields that are actually being updated.
+ """
+ engine_type = broker["engineType"]
+
+ if "engineVersion" in body:
+ engine_versions = SUPPORTED_ENGINES[engine_type]["versions"]
+ if body["engineVersion"] not in engine_versions:
+ return _err(400, "EngineVersion", ERROR_MESSAGES["ENGINE_VERSION_INVALID"])
+
+ if "hostInstanceType" in body:
+ if body["hostInstanceType"] not in _valid_host_instance_types(engine_type):
+ return _err(400, "HostInstanceType", ERROR_MESSAGES["HOST_INSTANCE_TYPE_INVALID"])
+
+ return None
+
+
+def _validate_query_parameter_filter(
+ engine_type: str | None,
+ host_instance_type: str | None,
+ storage_type: str | None,
+) -> tuple | None:
+ """Validate query parameters for broker instance options filtering.
+
+ Returns None if valid, or error tuple if invalid.
+ """
+ if engine_type and engine_type not in SUPPORTED_ENGINES:
+ return _err(400, "EngineType", ERROR_MESSAGES["ENGINE_TYPE_UNSUPPORTED"].format(engine_type))
+
+ if host_instance_type and host_instance_type not in _valid_host_instance_types(engine_type):
+ return _err(400, "HostInstanceType", ERROR_MESSAGES["HOST_INSTANCE_TYPE_INVALID"])
+
+ if storage_type and storage_type not in _valid_storage_types(engine_type):
+ return _err(400, "StorageType", ERROR_MESSAGES["STORAGE_TYPE_INVALID"].format(storage_type))
+
+ return None
+
+
+# ============================================================================
+# State & Persistence
+# ============================================================================
+
+
+def get_state() -> dict:
+ """Retrieve current broker state (used for persistence)."""
+ return {
+ "brokers": copy.deepcopy(_brokers),
+ "name_index": copy.deepcopy(_name_index),
+ "tags": copy.deepcopy(_tags),
+ "users": copy.deepcopy(_users),
+ }
+
+
+def restore_state(data: dict) -> None:
+ if not data:
+ return
+ _brokers.update(data.get("brokers", {}))
+ _name_index.update(data.get("name_index", {}))
+ _tags.update(data.get("tags", {}))
+ _users.update(data.get("users", {}))
+
+
+try:
+ _restored = load_state("mq")
+ if _restored:
+ restore_state(_restored)
+except Exception:
+ logger.exception("Failed to restore mq state; starting fresh")
+
+
+# ============================================================================
+# Response Builders
+# ============================================================================
+
+
+def _ok(data: dict) -> tuple:
+ """Return 200 OK with JSON-encoded response body."""
+ return 200, dict(HTTP_JSON_HEADERS), json.dumps(data, ensure_ascii=False).encode("utf-8")
+
+
+def _no_content() -> tuple:
+ """Return 204 No Content."""
+ return 204, {}, b""
+
+
+def _err(http_status: int, error_attribute: str, message: str) -> tuple:
+ """Return error response with appropriate HTTP status and AWS error format."""
+ exc_type = HTTP_STATUS_TO_EXCEPTION.get(http_status, "BadRequestException")
+ body = json.dumps(
+ {"errorAttribute": error_attribute, "message": message, "__type": exc_type},
+ ensure_ascii=False,
+ ).encode("utf-8")
+ return http_status, {**HTTP_JSON_HEADERS, "x-amzn-errortype": exc_type}, body
+
+
+# ============================================================================
+# Broker Metadata & Utilities
+# ============================================================================
+
+
+def _make_broker_arn(broker_id: str) -> str:
+ """Construct an ARN for a broker given its ID."""
+ return f"arn:aws:mq:{get_region()}:{get_account_id()}:broker:{broker_id}"
+
+
+def _valid_host_instance_types(engine_type: str | None) -> set[str]:
+ """Get set of valid host instance types for an engine type."""
+ if engine_type:
+ return set(SUPPORTED_ENGINES.get(engine_type, {}).get("host_instance_types", []))
+ out = set()
+ for cfg in SUPPORTED_ENGINES.values():
+ out.update(cfg["host_instance_types"])
+ return out
+
+def _valid_storage_types(engine_type: str | None) -> set[str]:
+ """Get set of valid storage types for an engine type."""
+ if engine_type:
+ return set(SUPPORTED_ENGINES.get(engine_type, {}).get("storage_types", []))
+ out = set()
+ for cfg in SUPPORTED_ENGINES.values():
+ out.update(cfg["storage_types"])
+ return out
+
+
+def _parse_max_results(query_params: dict, *, default: int = 20):
+ """Parse and validate maxResults pagination parameter."""
+ raw = query_params.get("maxResults")
+ if not raw:
+ return default, None
+ if isinstance(raw, list):
+ raw = raw[-1] if raw else None
+ try:
+ value = int(raw)
+ except (TypeError, ValueError):
+ return None, _err(400, "MaxResults", ERROR_MESSAGES["MAX_RESULTS_INVALID"])
+ if value < 5 or value > 100:
+ return None, _err(400, "MaxResults", ERROR_MESSAGES["MAX_RESULTS_INVALID"])
+ return value, None
+
+# ============================================================================
+# Pagination & Query Parsing
+# ============================================================================
+
+
+def _parse_next_token(query_params: dict):
+ """Parse and validate nextToken pagination parameter."""
+ raw = query_params.get("nextToken")
+ if not raw:
+ return 0, None
+ if isinstance(raw, list):
+ raw = raw[-1] if raw else None
+ try:
+ offset = int(raw)
+ except (TypeError, ValueError):
+ return 0, _err(400, "NextToken", ERROR_MESSAGES["NEXT_TOKEN_INVALID"])
+ if offset < 0:
+ return 0, _err(400, "NextToken", ERROR_MESSAGES["NEXT_TOKEN_INVALID"])
+ return offset, None
+
+
+def _paginate(items: list, offset: int, max_results: int):
+ """Paginate a list of items returning page and optional nextToken."""
+ page = items[offset : offset + max_results]
+ next_token = str(offset + max_results) if (offset + max_results) < len(items) else None
+ return page, next_token
+
+
+# ============================================================================
+# Broker Lookup & Guards
+# ============================================================================
+
+
+def _resource_exists(resource_arn: str) -> bool:
+ """Check if a broker with given ARN exists."""
+ return any(b.get("brokerArn") == resource_arn for b in _brokers.values())
+
+
+def _get_broker_or_404(broker_id: str):
+ """Retrieve broker or return 404 error tuple."""
+ broker = _brokers.get(broker_id)
+ if not broker:
+ return None, _err(404, "BrokerId", ERROR_MESSAGES["BROKER_NOT_FOUND"].format(broker_id))
+ return broker, None
+
+
+# ============================================================================
+# Broker Guard Functions
+# ============================================================================
+
+
+def _ensure_activemq_broker(broker: dict):
+ """Verify broker is ActiveMQ engine type; return error if not."""
+ if broker.get("engineType") != "ACTIVEMQ":
+ return _err(400, "BrokerId", ERROR_MESSAGES["ACTIVEMQ_ONLY_OP"])
+ return None
+
+def _validate_password(password: str):
+ """Validate password meets AWS MQ requirements."""
+ if len(password) < 4 or INVALID_PASSWORD_CHARS_PATTERN.search(password):
+ return _err(400, "Password", ERROR_MESSAGES["PASSWORD_INVALID"])
+ return None
+
+
+# ============================================================================
+# Broker CRUD Operations
+# ============================================================================
+
+
+def _create_broker(body: dict) -> tuple:
+ """Create a new MQ broker with specified configuration."""
+ # Validate all configuration first
+ config_err = _validate_broker_config(body)
+ if config_err:
+ return config_err
+
+ # Extract validated configuration
+ engine_type = str(body.get("engineType", "")).strip().upper()
+ broker_name = str(body.get("brokerName", "")).strip()
+ engine_versions = SUPPORTED_ENGINES[engine_type]["versions"]
+ engine_version = body.get("engineVersion") or engine_versions[0]
+ deployment_mode = str(body.get("deploymentMode", "SINGLE_INSTANCE")).upper()
+ host_instance_type = body.get("hostInstanceType", "mq.m5.large")
+ storage_type = body.get("storageType", "EBS")
+
+ # Create broker in state
+ broker_id = new_uuid()
+ broker_arn = _make_broker_arn(broker_id)
+ created = time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime())
+
+ _brokers[broker_id] = {
+ "brokerId": broker_id,
+ "brokerName": broker_name,
+ "brokerArn": broker_arn,
+ "brokerState": "RUNNING",
+ "engineType": engine_type,
+ "engineVersion": engine_version,
+ "deploymentMode": deployment_mode,
+ "hostInstanceType": host_instance_type,
+ "publiclyAccessible": bool(body.get("publiclyAccessible", False)),
+ "autoMinorVersionUpgrade": bool(body.get("autoMinorVersionUpgrade", True)),
+ "created": created,
+ "_createdAt": time.time_ns(),
+ "brokerInstances": [{"consoleURL": "https://localhost:15671", "endpoints": ["amqps://localhost:5671"], "ipAddress": "127.0.0.1"}],
+ }
+ _name_index[broker_name] = broker_id
+ _tags[broker_arn] = dict(body.get("tags") or {})
+ _users[broker_id] = {}
+
+ return _ok({"brokerId": broker_id, "brokerArn": broker_arn})
+
+
+def _list_brokers(query_params: dict) -> tuple:
+ """List all brokers with pagination support."""
+ max_results, max_err = _parse_max_results(query_params)
+ if max_err:
+ return max_err
+ offset, token_err = _parse_next_token(query_params)
+ if token_err:
+ return token_err
+
+ brokers_list = sorted(
+ [
+ {
+ "brokerId": b["brokerId"],
+ "brokerName": b["brokerName"],
+ "brokerArn": b["brokerArn"],
+ "brokerState": b["brokerState"],
+ "deploymentMode": b["deploymentMode"],
+ "engineType": b["engineType"],
+ "engineVersion": b["engineVersion"],
+ "hostInstanceType": b["hostInstanceType"],
+ "created": b["created"],
+ "_createdAt": b.get("_createdAt", 0),
+ }
+ for b in _brokers.values()
+ ],
+ key=lambda x: x["_createdAt"],
+ reverse=True,
+ )
+ for row in brokers_list:
+ row.pop("_createdAt", None)
+
+ page, next_token = _paginate(brokers_list, offset, max_results)
+ out = {"brokerSummaries": page}
+ if next_token:
+ out["nextToken"] = next_token
+ return _ok(out)
+
+
+def _describe_broker(broker_id: str) -> tuple:
+ """Describe a specific broker in detail."""
+ broker, err = _get_broker_or_404(broker_id)
+ if err:
+ return err
+ out = copy.deepcopy(broker)
+ out.pop("_createdAt", None)
+ out["tags"] = dict(_tags.get(broker["brokerArn"], {}))
+ return _ok(out)
+
+
+def _delete_broker(broker_id: str) -> tuple:
+ """Delete a broker and all associated data."""
+ broker, err = _get_broker_or_404(broker_id)
+ if err:
+ return err
+ del _brokers[broker_id]
+ _name_index.pop(broker["brokerName"], None)
+ _tags.pop(broker["brokerArn"], None)
+ _users.pop(broker_id, None)
+ return _ok({"brokerId": broker_id})
+
+
+def _update_broker(broker_id: str, body: dict) -> tuple:
+ """Update broker configuration fields."""
+ broker, err = _get_broker_or_404(broker_id)
+ if err:
+ return err
+
+ # Validate update fields
+ validation_err = _validate_broker_update_fields(broker, body)
+ if validation_err:
+ return validation_err
+
+ # Apply updates
+ field_map = {
+ "authenticationStrategy": "authenticationStrategy",
+ "autoMinorVersionUpgrade": "autoMinorVersionUpgrade",
+ "configuration": "configuration",
+ "engineVersion": "engineVersion",
+ "hostInstanceType": "hostInstanceType",
+ "ldapServerMetadata": "ldapServerMetadata",
+ "logs": "logs",
+ "maintenanceWindowStartTime": "maintenanceWindowStartTime",
+ "securityGroups": "securityGroups",
+ "dataReplicationMode": "pendingDataReplicationMode",
+ }
+
+ out = {"brokerId": broker_id}
+ for src, dst in field_map.items():
+ if src in body:
+ broker[dst] = copy.deepcopy(body[src])
+ out[dst] = copy.deepcopy(body[src])
+
+ return _ok(out)
+
+
+def _reboot_broker(broker_id: str) -> tuple:
+ """Reboot a broker (soft restart)."""
+ broker, err = _get_broker_or_404(broker_id)
+ if err:
+ return err
+ if broker.get("brokerState") != "RUNNING":
+ return _err(400, "BrokerState", ERROR_MESSAGES["BROKER_NOT_RUNNING"])
+ return _ok({})
+
+# ============================================================================
+# Broker Metadata & Configuration Queries
+# ============================================================================
+
+
+def _list_broker_engine_types(query_params: dict) -> tuple:
+ """List supported MQ broker engine types and versions."""
+ # Parse engine type parameter
+ engine_type = query_params.get("engineType")
+ if isinstance(engine_type, list):
+ engine_type = engine_type[-1] if engine_type else None
+ if engine_type:
+ engine_type = str(engine_type).upper()
+ if engine_type not in SUPPORTED_ENGINES:
+ return _err(400, "EngineType", ERROR_MESSAGES["ENGINE_TYPE_UNSUPPORTED"].format(engine_type))
+
+ # Parse pagination parameters
+ max_results, max_err = _parse_max_results(query_params)
+ if max_err:
+ return max_err
+ offset, token_err = _parse_next_token(query_params)
+ if token_err:
+ return token_err
+
+ # Build filtered engine list
+ items = []
+ for eng, cfg in SUPPORTED_ENGINES.items():
+ if engine_type and eng != engine_type:
+ continue
+ items.append({"engineType": eng, "engineVersions": [{"name": v} for v in cfg["versions"]]})
+
+ # Paginate and return
+ page, next_token = _paginate(items, offset, max_results)
+ out = {"brokerEngineTypes": page, "maxResults": max_results}
+ if next_token:
+ out["nextToken"] = next_token
+ return _ok(out)
+
+def _list_broker_instance_options(query_params: dict) -> tuple:
+ """List supported instance and storage type combinations."""
+ max_results, max_err = _parse_max_results(query_params)
+ if max_err:
+ return max_err
+ offset, token_err = _parse_next_token(query_params)
+ if token_err:
+ return token_err
+
+ # Parse and normalize filter parameters
+ engine_type = query_params.get("engineType")
+ if isinstance(engine_type, list):
+ engine_type = engine_type[-1] if engine_type else None
+ engine_type = str(engine_type).upper() if engine_type else None
+
+ host_instance_type = query_params.get("hostInstanceType")
+ if isinstance(host_instance_type, list):
+ host_instance_type = host_instance_type[-1] if host_instance_type else None
+
+ storage_type = query_params.get("storageType")
+ if isinstance(storage_type, list):
+ storage_type = storage_type[-1] if storage_type else None
+ storage_type = str(storage_type).upper() if storage_type else None
+
+ # Validate filters
+ validation_err = _validate_query_parameter_filter(engine_type, host_instance_type, storage_type)
+ if validation_err:
+ return validation_err
+
+ # Build filtered options list
+ filtered = []
+ for eng, cfg in SUPPORTED_ENGINES.items():
+ if engine_type and eng != engine_type:
+ continue
+ for host in cfg["host_instance_types"]:
+ if host_instance_type and host != host_instance_type:
+ continue
+ for stor in cfg["storage_types"]:
+ if storage_type and stor != storage_type:
+ continue
+ filtered.append(
+ {
+ "availabilityZones": [{"name": "us-east-1a"}, {"name": "us-east-1b"}],
+ "engineType": eng,
+ "hostInstanceType": host,
+ "storageType": stor,
+ "supportedEngineVersions": [{"name": v} for v in cfg["versions"]],
+ "supportedDeploymentModes": list(cfg["deployment_modes"]),
+ }
+ )
+
+ page, next_token = _paginate(filtered, offset, max_results)
+ out = {"brokerInstanceOptions": page, "maxResults": max_results}
+ if next_token:
+ out["nextToken"] = next_token
+ return _ok(out)
+
+# ============================================================================
+# Tag Management
+# ============================================================================
+
+
+def _list_tags(resource_arn: str) -> tuple:
+ """List all tags for a broker resource."""
+ if not _resource_exists(resource_arn):
+ return _err(404, "ResourceArn", ERROR_MESSAGES["RESOURCE_NOT_FOUND"].format(resource_arn))
+ return _ok({"tags": dict(_tags.get(resource_arn, {}))})
+
+
+def _create_tags(resource_arn: str, body: dict) -> tuple:
+ """Add or update tags on a broker resource."""
+ if not _resource_exists(resource_arn):
+ return _err(404, "ResourceArn", ERROR_MESSAGES["RESOURCE_NOT_FOUND"].format(resource_arn))
+ tags = body.get("tags") if isinstance(body, dict) else None
+ if not isinstance(tags, dict):
+ return _err(400, "Tags", ERROR_MESSAGES["TAGS_INVALID"])
+ _tags.setdefault(resource_arn, {}).update({str(k): str(v) for k, v in tags.items()})
+ return _no_content()
+
+
+def _delete_tags(resource_arn: str, query_params: dict) -> tuple:
+ """Delete specific tags from a broker resource."""
+ if not _resource_exists(resource_arn):
+ return _err(404, "ResourceArn", ERROR_MESSAGES["RESOURCE_NOT_FOUND"].format(resource_arn))
+ tag_keys = query_params.get("tagKeys")
+ if not tag_keys:
+ return _err(400, "TagKeys", ERROR_MESSAGES["TAG_KEYS_REQUIRED"])
+ if isinstance(tag_keys, str):
+ tag_keys = [tag_keys]
+ tags = _tags.setdefault(resource_arn, {})
+ for key in tag_keys:
+ tags.pop(str(key), None)
+ return _no_content()
+
+# ============================================================================
+# User Management (ActiveMQ only)
+# ============================================================================
+
+
+def _create_user(broker_id: str, username: str, body: dict) -> tuple:
+ """Create a user account on an ActiveMQ broker."""
+ broker, err = _get_broker_or_404(broker_id)
+ if err:
+ return err
+ engine_err = _ensure_activemq_broker(broker)
+ if engine_err:
+ return engine_err
+
+ users_map = _users.setdefault(broker_id, {})
+ if username in users_map:
+ return _err(409, "Username", ERROR_MESSAGES["USER_ALREADY_EXISTS"].format(username))
+
+ password = str(body.get("password", ""))
+ pw_err = _validate_password(password)
+ if pw_err:
+ return pw_err
+
+ users_map[username] = {
+ "username": username,
+ "password": password,
+ "consoleAccess": bool(body.get("consoleAccess", False)),
+ "groups": list(body.get("groups") or []),
+ "replicationUser": bool(body.get("replicationUser", False)),
+ "_createdAt": time.time_ns(),
+ }
+ return _ok({})
+
+
+def _delete_user(broker_id: str, username: str) -> tuple:
+ """Delete a user account from an ActiveMQ broker."""
+ broker, err = _get_broker_or_404(broker_id)
+ if err:
+ return err
+ engine_err = _ensure_activemq_broker(broker)
+ if engine_err:
+ return engine_err
+
+ users_map = _users.setdefault(broker_id, {})
+ if username not in users_map:
+ return _err(404, "Username", ERROR_MESSAGES["USER_NOT_FOUND"].format(username))
+
+ del users_map[username]
+ return _ok({})
+
+
+def _list_users(broker_id: str, query_params: dict) -> tuple:
+ """List all users for an ActiveMQ broker."""
+ broker, err = _get_broker_or_404(broker_id)
+ if err:
+ return err
+ engine_err = _ensure_activemq_broker(broker)
+ if engine_err:
+ return engine_err
+
+ max_results, max_err = _parse_max_results(query_params)
+ if max_err:
+ return max_err
+ offset, token_err = _parse_next_token(query_params)
+ if token_err:
+ return token_err
+
+ users_map = _users.setdefault(broker_id, {})
+ users_list = sorted(
+ [
+ {
+ "username": u["username"],
+ "consoleAccess": bool(u.get("consoleAccess", False)),
+ "groups": list(u.get("groups", [])),
+ "replicationUser": bool(u.get("replicationUser", False)),
+ "_createdAt": u.get("_createdAt", 0),
+ }
+ for u in users_map.values()
+ ],
+ key=lambda x: x["_createdAt"],
+ reverse=True,
+ )
+ for row in users_list:
+ row.pop("_createdAt", None)
+
+ page, next_token = _paginate(users_list, offset, max_results)
+ out = {"brokerId": broker_id, "maxResults": max_results, "users": page}
+ if next_token:
+ out["nextToken"] = next_token
+ return _ok(out)
+
+
+def _update_user(broker_id: str, username: str, body: dict) -> tuple:
+ """Update a user account on an ActiveMQ broker."""
+ broker, err = _get_broker_or_404(broker_id)
+ if err:
+ return err
+ engine_err = _ensure_activemq_broker(broker)
+ if engine_err:
+ return engine_err
+
+ users_map = _users.setdefault(broker_id, {})
+ user = users_map.get(username)
+ if not user:
+ return _err(404, "Username", ERROR_MESSAGES["USER_NOT_FOUND"].format(username))
+
+ if "password" in body:
+ pw_err = _validate_password(str(body.get("password", "")))
+ if pw_err:
+ return pw_err
+ user["password"] = str(body["password"])
+
+ if "consoleAccess" in body:
+ user["consoleAccess"] = bool(body["consoleAccess"])
+ if "groups" in body:
+ user["groups"] = list(body.get("groups") or [])
+ if "replicationUser" in body:
+ user["replicationUser"] = bool(body["replicationUser"])
+
+ return _ok({})
+
+def _describe_user(broker_id: str, username: str) -> tuple:
+ """Describe a specific user account on an ActiveMQ broker."""
+ broker, err = _get_broker_or_404(broker_id)
+ if err:
+ return err
+
+ engine_err = _ensure_activemq_broker(broker)
+ if engine_err:
+ return engine_err
+
+ users_map = _users.setdefault(broker_id, {})
+ user = users_map.get(username)
+ if not user:
+ return _err(404, "Username", ERROR_MESSAGES["USER_NOT_FOUND"].format(username))
+
+ out = {
+ "brokerId": broker_id,
+ "consoleAccess": bool(user.get("consoleAccess", False)),
+ "groups": list(user.get("groups", [])),
+ "pending": {},
+ "username": user["username"],
+ "replicationUser": bool(user.get("replicationUser", False)),
+ }
+ return _ok(out)
+
+
+
+
+# ============================================================================
+# Request Routing & Handlers
+# ============================================================================
+
+
+async def handle_request(method: str, path: str, headers: dict, body: bytes, query_params: dict) -> tuple:
+ """Main request handler that routes to appropriate API endpoint handler."""
+ method = method.upper()
+
+ if path == "/v1/broker-instance-options" and method == "GET":
+ return _list_broker_instance_options(query_params)
+
+ if path == "/v1/broker-engine-types" and method == "GET":
+ return _list_broker_engine_types(query_params)
+
+ m = TAGS_PATH_PATTERN.match(path)
+ if m:
+ resource_arn = unquote(m.group(1))
+ if method == "GET":
+ return _list_tags(resource_arn)
+ if method == "POST":
+ try:
+ payload = json.loads(body) if body else {}
+ except json.JSONDecodeError:
+ return _err(400, "RequestBody", ERROR_MESSAGES["JSON_INVALID"])
+ return _create_tags(resource_arn, payload)
+ if method == "DELETE":
+ return _delete_tags(resource_arn, query_params)
+
+ m = BROKER_USERS_PATH_PATTERN.match(path)
+ if m and method == "GET":
+ return _list_users(m.group(1), query_params)
+
+ m = BROKER_USER_PATH_PATTERN.match(path)
+ if m:
+ broker_id, username = m.group(1), unquote(m.group(2))
+ if method == "POST":
+ try:
+ payload = json.loads(body) if body else {}
+ except json.JSONDecodeError:
+ return _err(400, "RequestBody", ERROR_MESSAGES["JSON_INVALID"])
+ return _create_user(broker_id, username, payload)
+ if method == "DELETE":
+ return _delete_user(broker_id, username)
+ if method == "PUT":
+ try:
+ payload = json.loads(body) if body else {}
+ except json.JSONDecodeError:
+ return _err(400, "RequestBody", ERROR_MESSAGES["JSON_INVALID"])
+ return _update_user(broker_id, username, payload)
+ if method == "GET":
+ return _describe_user(broker_id, username)
+
+ if method == "POST" and path == "/v1/brokers":
+ try:
+ payload = json.loads(body) if body else {}
+ except json.JSONDecodeError:
+ return _err(400, "RequestBody", ERROR_MESSAGES["JSON_INVALID"])
+ return _create_broker(payload)
+
+ if method == "GET" and path == "/v1/brokers":
+ return _list_brokers(query_params)
+
+ m = BROKER_REBOOT_PATH_PATTERN.match(path)
+ if m and method == "POST":
+ return _reboot_broker(m.group(1))
+
+ m = BROKER_ID_PATH_PATTERN.match(path)
+ if m:
+ broker_id = m.group(1)
+ if method == "GET":
+ return _describe_broker(broker_id)
+ if method == "PUT":
+ try:
+ payload = json.loads(body) if body else {}
+ except json.JSONDecodeError:
+ return _err(400, "RequestBody", ERROR_MESSAGES["JSON_INVALID"])
+ return _update_broker(broker_id, payload)
+ if method == "DELETE":
+ return _delete_broker(broker_id)
+
+ return _err(400, "Action", ERROR_MESSAGES["ACTION_UNKNOWN"].format(method, path))
+
+
+def reset() -> None:
+ """Clear all MQ service state (used for testing)."""
+ _brokers.clear()
+ _name_index.clear()
+ _tags.clear()
+ _users.clear()
diff --git a/ministack/services/rds.py b/ministack/services/rds.py
index 0b8d49b1..16d97f3f 100644
--- a/ministack/services/rds.py
+++ b/ministack/services/rds.py
@@ -30,9 +30,9 @@ clients can call DescribeDBInstances and other operations without ``Action=`` qu
parameters.
"""
+import contextvars
import copy
import datetime
-import contextvars
import json
import logging
import os
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index e190f4be..8002c18f 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -30,8 +30,8 @@ import json
import logging
import os
import re
-import struct
import shutil
+import struct
import threading
import time
import zlib
diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.py
index a9a65fe0..6b985acb 100644
--- a/ministack/services/stepfunctions.py
+++ b/ministack/services/stepfunctions.py
@@ -2882,7 +2882,7 @@ def _jsonata_now(*args):
# With picture: XPath-3.1 date/time picture (subset — see
# `_format_datetime_picture`). With timezone: "+HH:MM" / "-HH:MM" offset
# applied before formatting.
- from datetime import datetime, timezone, timedelta
+ from datetime import datetime, timedelta, timezone
if len(args) > 2:
raise ValueError("$now expects 0, 1, or 2 arguments")
now = datetime.now(timezone.utc)
diff --git a/tests/conftest.py b/tests/conftest.py
index 38b3e855..e816e56f 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -521,3 +521,8 @@ def cur():
@pytest.fixture(scope="session")
def inspector2():
return make_client("inspector2")
+
+
[email protected](scope="session")
+def mq():
+ return make_client("mq")
diff --git a/tests/test_mq.py b/tests/test_mq.py
new file mode 100644
index 00000000..725ecbbc
--- /dev/null
+++ b/tests/test_mq.py
@@ -0,0 +1,1210 @@
+"""
+Integration tests for the AmazonMQ service (RabbitMQ CRUD).
+"""
+
+import uuid
+
+import pytest
+from botocore.exceptions import ClientError
+
+# ###########################################################################
+# Helpers
+# ###########################################################################
+
+def _name(suffix: str = "") -> str:
+ """Generate a unique broker name for a test run."""
+ return f"intg-mq-{suffix}-{uuid.uuid4().hex[:8]}"
+
+
+def _create(mq, **kwargs) -> dict:
+ params = dict(
+ BrokerName=_name("base"),
+ EngineType="RABBITMQ",
+ EngineVersion="3.13",
+ HostInstanceType="mq.m5.large",
+ PubliclyAccessible=False,
+ DeploymentMode="SINGLE_INSTANCE",
+ )
+ params.update(kwargs)
+ return mq.create_broker(**params)
+
+
+############################################################################
+# CreateBroker
+############################################################################
+
+def test_mq_create_broker_with_required_options(mq):
+ name = _name("create")
+ resp = mq.create_broker(
+ BrokerName=name,
+ EngineType="RABBITMQ",
+ EngineVersion="3.13",
+ HostInstanceType="mq.m5.large",
+ PubliclyAccessible=False,
+ DeploymentMode="SINGLE_INSTANCE",
+ )
+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200
+ assert "BrokerId" in resp
+ assert "BrokerArn" in resp
+ assert resp["BrokerArn"].startswith("arn:aws:mq:")
+
+def test_mq_create_broker_with_duplicated_name(mq):
+ name = _name("dup")
+ _create(mq, BrokerName=name)
+
+ with pytest.raises(ClientError) as exc:
+ _create(mq, BrokerName=name)
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 409
+ assert exc.value.response["Error"]["Code"] == "ConflictException"
+
+ "create_params",
+ [
+ {"BrokerName": _name("invalid-engine"), "EngineType": "INVALID_ENGINE", "EngineVersion": "1.0", "HostInstanceType": "mq.m5.large", "DeploymentMode": "SINGLE_INSTANCE", "PubliclyAccessible": False},
+ {"BrokerName": _name("invalid-engine-version"), "EngineType": "RABBITMQ", "EngineVersion": "INVALID_VERSION", "HostInstanceType": "mq.m5.large", "DeploymentMode": "SINGLE_INSTANCE", "PubliclyAccessible": False},
+ {"BrokerName": _name("invalid-deployment-mode"), "EngineType": "RABBITMQ", "EngineVersion": "3.13", "HostInstanceType": "mq.m5.large", "DeploymentMode": "INVALID_MODE", "PubliclyAccessible": False},
+ {"BrokerName": _name("invalid-instance-type"), "EngineType": "RABBITMQ", "EngineVersion": "3.13", "HostInstanceType": "INVALID_INSTANCE", "DeploymentMode": "SINGLE_INSTANCE", "PubliclyAccessible": False},
+ {"BrokerName": _name("invalid-storage-type"), "EngineType": "RABBITMQ", "EngineVersion": "3.13", "HostInstanceType": "mq.m5.large", "DeploymentMode": "SINGLE_INSTANCE", "StorageType": "INVALID_STORAGE", "PubliclyAccessible": False}
+ ],
+)
+def test_mq_create_broker_with_invalid_parameters(
+ mq, create_params
+):
+ """Test that invalid parameters return BadRequestException."""
+ with pytest.raises(ClientError) as exc:
+ mq.create_broker(**create_params)
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ assert exc.value.response["Error"]["Code"] == "BadRequestException"
+
+def test_mq_create_broker_initializes_empty_tags(mq):
+ """Test that _tags[broker_arn] = {} when no tags provided (Line 222)."""
+ name = _name("tags-init-empty")
+ resp = mq.create_broker(
+ BrokerName=name,
+ EngineType="RABBITMQ",
+ EngineVersion="3.13",
+ HostInstanceType="mq.m5.large",
+ PubliclyAccessible=False,
+ DeploymentMode="SINGLE_INSTANCE",
+ )
+ broker_arn = resp["BrokerArn"]
+
+ # Verify tags dict is initialized and empty
+ list_resp = mq.list_tags(ResourceArn=broker_arn)
+ assert list_resp["Tags"] == {}
+
+def test_mq_create_broker_initializes_empty_users(mq):
+ """Test that _users[broker_id] = {} on creation (Line 223)."""
+ broker_id = _create(mq, BrokerName=_name("users-init"), EngineType="ACTIVEMQ", EngineVersion="5.19")["BrokerId"]
+
+ # Verify users dict is initialized and empty
+ list_resp = mq.list_users(BrokerId=broker_id)
+ assert list_resp.get("Users", []) == []
+ assert list_resp["MaxResults"] == 20
+
+def test_mq_create_broker_with_tags_initializes_tags(mq):
+ """Test that _tags[broker_arn] stores provided tags (Line 222)."""
+ name = _name("tags-init-with")
+ resp = mq.create_broker(
+ BrokerName=name,
+ EngineType="RABBITMQ",
+ EngineVersion="3.13",
+ HostInstanceType="mq.m5.large",
+ PubliclyAccessible=False,
+ DeploymentMode="SINGLE_INSTANCE",
+ Tags={"environment": "test", "team": "platform"},
+ )
+ broker_arn = resp["BrokerArn"]
+
+ # Verify tags are persisted
+ list_resp = mq.list_tags(ResourceArn=broker_arn)
+ assert list_resp["Tags"]["environment"] == "test"
+ assert list_resp["Tags"]["team"] == "platform"
+
+def test_mq_create_broker_with_empty_tags_dict(mq):
+ """Test that empty tags dict is handled correctly (Line 222)."""
+ name = _name("tags-init-empty-dict")
+ resp = mq.create_broker(
+ BrokerName=name,
+ EngineType="RABBITMQ",
+ EngineVersion="3.13",
+ HostInstanceType="mq.m5.large",
+ PubliclyAccessible=False,
+ DeploymentMode="SINGLE_INSTANCE",
+ Tags={},
+ )
+ broker_arn = resp["BrokerArn"]
+
+ list_resp = mq.list_tags(ResourceArn=broker_arn)
+ assert list_resp["Tags"] == {}
+
+############################################################################
+# ListBrokers
+############################################################################
+
+def test_mq_list_brokers(mq):
+ names = [_name("list") for _ in range(2)]
+ ids = set()
+ for n in names:
+ r = mq.create_broker(
+ BrokerName=n,
+ EngineType="RABBITMQ",
+ EngineVersion="3.13",
+ HostInstanceType="mq.m5.large",
+ PubliclyAccessible=False,
+ DeploymentMode="SINGLE_INSTANCE",
+ )
+ ids.add(r["BrokerId"])
+
+ resp = mq.list_brokers()
+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200
+ listed_ids = {b["BrokerId"] for b in resp.get("BrokerSummaries", [])}
+ assert ids.issubset(listed_ids), f"Expected {ids} in {listed_ids}"
+
+def test_mq_list_brokers_with_max_results(mq):
+ # Create 10 brokers to ensure we have more than 5 to list
+ for _ in range(10):
+ _create(mq, BrokerName=_name("list-max"))
+
+ resp = mq.list_brokers(MaxResults=5)
+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200
+ assert len(resp.get("BrokerSummaries", [])) <= 5
+
[email protected]("invalid_max", [4, 101])
+def test_mq_list_brokers_with_invalid_max_results(mq, invalid_max):
+ with pytest.raises(ClientError) as exc:
+ mq.list_brokers(MaxResults=invalid_max)
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ assert exc.value.response["Error"]["Code"] == "BadRequestException"
+
+def test_mq_list_brokers_pagination(mq):
+ # Create 10 brokers to ensure we have more than 5 to list
+ created_ids = []
+ for _ in range(10):
+ resp = _create(mq, BrokerName=_name("list-page"))
+ created_ids.append(resp["BrokerId"])
+
+ # Paginate with a stable page size and gather IDs until we find all new brokers.
+ listed_ids = set()
+ token = None
+ pages = 0
+ while True:
+ pages += 1
+ kwargs = {"MaxResults": 5}
+ if token:
+ kwargs["NextToken"] = token
+
+ resp = mq.list_brokers(**kwargs)
+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200
+ assert len(resp.get("BrokerSummaries", [])) <= 5
+
+ listed_ids.update({b["BrokerId"] for b in resp.get("BrokerSummaries", [])})
+ if set(created_ids).issubset(listed_ids):
+ break
+
+ token = resp.get("NextToken")
+ if not token:
+ break
+
+ # Safety guard in case pagination regresses.
+ assert pages <= 100
+
+ assert set(created_ids).issubset(listed_ids), f"Expected {created_ids} in {listed_ids}"
+
+############################################################################
+# DescribeBrokers
+############################################################################
+
+def test_mq_describe_broker(mq):
+ name = _name("describe")
+ create_resp = _create(mq, BrokerName=name)
+ broker_id = create_resp["BrokerId"]
+
+ desc = mq.describe_broker(BrokerId=broker_id)
+ assert desc["ResponseMetadata"]["HTTPStatusCode"] == 200
+ assert desc["BrokerId"] == broker_id
+ assert desc["BrokerName"] == name
+ assert desc["EngineType"] == "RABBITMQ"
+ assert desc["BrokerState"] == "RUNNING"
+ assert "BrokerInstances" in desc
+
+def test_mq_describe_broker_with_non_existent_id(mq):
+ with pytest.raises(ClientError) as exc:
+ mq.describe_broker(BrokerId="invalid-id")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ assert exc.value.response["Error"]["Code"] == "NotFoundException"
+
+def test_mq_describe_broker_includes_tags(mq):
+ """Test that DescribeBroker returns tags from _tags dict (Line 271)."""
+ name = _name("describe-tags")
+ create_resp = mq.create_broker(
+ BrokerName=name,
+ EngineType="RABBITMQ",
+ EngineVersion="3.13",
+ HostInstanceType="mq.m5.large",
+ PubliclyAccessible=False,
+ DeploymentMode="SINGLE_INSTANCE",
+ Tags={"env": "staging", "owner": "devops"},
+ )
+ broker_id = create_resp["BrokerId"]
+
+ desc = mq.describe_broker(BrokerId=broker_id)
+ assert desc["ResponseMetadata"]["HTTPStatusCode"] == 200
+ assert "Tags" in desc
+ assert desc["Tags"]["env"] == "staging"
+ assert desc["Tags"]["owner"] == "devops"
+
+def test_mq_describe_broker_includes_empty_tags(mq):
+ """Test that DescribeBroker returns empty tags object when none exist (Line 271)."""
+ name = _name("describe-tags-empty")
+ create_resp = mq.create_broker(
+ BrokerName=name,
+ EngineType="RABBITMQ",
+ EngineVersion="3.13",
+ HostInstanceType="mq.m5.large",
+ PubliclyAccessible=False,
+ DeploymentMode="SINGLE_INSTANCE",
+ )
+ broker_id = create_resp["BrokerId"]
+
+ desc = mq.describe_broker(BrokerId=broker_id)
+ assert "Tags" in desc
+ assert desc["Tags"] == {}
+ assert isinstance(desc["Tags"], dict)
+
+def test_mq_describe_broker_tags_reflect_create_tags_additions(mq):
+ """Test that DescribeBroker reflects tags added via CreateTags (Line 271)."""
+ name = _name("describe-tags-added")
+ create_resp = _create(mq, BrokerName=name)
+ broker_id = create_resp["BrokerId"]
+ arn = create_resp["BrokerArn"]
+
+ # Initially no tags
+ desc1 = mq.describe_broker(BrokerId=broker_id)
+ assert desc1["Tags"] == {}
+
+ # Add tags
+ mq.create_tags(ResourceArn=arn, Tags={"added": "after"})
+
+ # Verify DescribeBroker now shows the tags
+ desc2 = mq.describe_broker(BrokerId=broker_id)
+ assert desc2["Tags"]["added"] == "after"
+
+############################################################################
+# DeleteBrokers
+############################################################################
+
+def test_mq_delete_broker(mq):
+ name = _name("delete")
+ broker_id = _create(mq, BrokerName=name)["BrokerId"]
+
+ del_resp = mq.delete_broker(BrokerId=broker_id)
+ assert del_resp["ResponseMetadata"]["HTTPStatusCode"] == 200
+ assert del_resp["BrokerId"] == broker_id
+
+def test_mq_delete_broker_with_non_existent_id(mq):
+ with pytest.raises(ClientError) as exc:
+ mq.delete_broker(BrokerId="invalid-id")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ assert exc.value.response["Error"]["Code"] == "NotFoundException"
+
+def test_mq_delete_broker_removes_tags(mq):
+ """Test that DeleteBroker removes entry from _tags dict (Line 281)."""
+ name = _name("delete-tags-cleanup")
+ create_resp = mq.create_broker(
+ BrokerName=name,
+ EngineType="RABBITMQ",
+ EngineVersion="3.13",
+ HostInstanceType="mq.m5.large",
+ PubliclyAccessible=False,
+ DeploymentMode="SINGLE_INSTANCE",
+ Tags={"cleanup": "test"},
+ )
+ broker_id = create_resp["BrokerId"]
+ broker_arn = create_resp["BrokerArn"]
+
+ # Verify tags exist before delete
+ list_resp = mq.list_tags(ResourceArn=broker_arn)
+ assert list_resp["Tags"]["cleanup"] == "test"
+
+ # Delete broker
+ mq.delete_broker(BrokerId=broker_id)
+
+ # Verify tags are cleaned up - ListTags should fail with 404
+ with pytest.raises(ClientError) as exc:
+ mq.list_tags(ResourceArn=broker_arn)
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+
+def test_mq_delete_broker_removes_users(mq):
+ """Test that DeleteBroker removes entry from _users dict (Line 282)."""
+ broker_id = _create(mq, BrokerName=_name("delete-users-cleanup"), EngineType="ACTIVEMQ", EngineVersion="5.19")["BrokerId"]
+
+ # Create a user
+ mq.create_user(
+ BrokerId=broker_id,
+ Username="cleanup_user",
+ Password="CleanupPassw0rd!",
+ ConsoleAccess=False,
+ )
+
+ # Verify user exists
+ list_resp = mq.list_users(BrokerId=broker_id)
+ usernames = {u["Username"] for u in list_resp.get("Users", [])}
+ assert "cleanup_user" in usernames
+
+ # Delete broker
+ mq.delete_broker(BrokerId=broker_id)
+
+ # Verify users are cleaned up - ListUsers should fail with 404
+ with pytest.raises(ClientError) as exc:
+ mq.list_users(BrokerId=broker_id)
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+
+def test_mq_delete_broker_clears_name_index(mq):
+ """Test that DeleteBroker cleans up _name_index secondary index."""
+ name = _name("delete-name-index")
+ broker_id = _create(mq, BrokerName=name)["BrokerId"]
+
+ # Delete broker
+ mq.delete_broker(BrokerId=broker_id)
+
+ # Verify name index is cleared - creating broker with same name should succeed
+ resp = mq.create_broker(
+ BrokerName=name,
+ EngineType="RABBITMQ",
+ EngineVersion="3.13",
+ HostInstanceType="mq.m5.large",
+ PubliclyAccessible=False,
+ DeploymentMode="SINGLE_INSTANCE",
+ )
+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200
+ assert resp["BrokerId"] != broker_id
+
+############################################################################
+# UpdateBroker
+############################################################################
+
+def test_mq_update_broker_with_required_options(mq):
+ broker_id = _create(mq, BrokerName=_name("update"))["BrokerId"]
+
+ resp = mq.update_broker(
+ BrokerId=broker_id,
+ HostInstanceType="mq.m5.xlarge",
+ AutoMinorVersionUpgrade=True,
+ )
+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200
+ assert resp["BrokerId"] == broker_id
+ assert resp["HostInstanceType"] == "mq.m5.xlarge"
+
+def test_mq_update_broker_with_non_existent_id(mq):
+ with pytest.raises(ClientError) as exc:
+ mq.update_broker(
+ BrokerId="invalid-id",
+ HostInstanceType="mq.m5.xlarge",
+ AutoMinorVersionUpgrade=True,
+ )
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ assert exc.value.response["Error"]["Code"] == "NotFoundException"
+
[email protected]("update_params", [
+ {"HostInstanceType": "INVALID_INSTANCE", "AutoMinorVersionUpgrade": True},
+ {"EngineVersion": "INVALID_VERSION", "AutoMinorVersionUpgrade": True},
+])
+def test_mq_update_broker_with_invalid_options(mq, update_params):
+ broker_id = _create(mq, BrokerName=_name("update-invalid"))["BrokerId"]
+
+ with pytest.raises(ClientError) as exc:
+ mq.update_broker(BrokerId=broker_id, **update_params)
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ assert exc.value.response["Error"]["Code"] == "BadRequestException"
+
+############################################################################
+# RebootBroker
+############################################################################
+
+def test_mq_reboot_broker(mq):
+ broker_id = _create(mq, BrokerName=_name("reboot"))["BrokerId"]
+
+ resp = mq.reboot_broker(BrokerId=broker_id)
+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200
+
+def test_mq_reboot_broker_with_non_existent_id(mq):
+ with pytest.raises(ClientError) as exc:
+ mq.reboot_broker(BrokerId="invalid-id")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ assert exc.value.response["Error"]["Code"] == "NotFoundException"
+
+############################################################################
+# DescribeBrokerEngineTypes
+############################################################################
+
+def test_mq_describe_broker_engine_types_with_no_params(mq):
+ resp = mq.describe_broker_engine_types()
+ assert len(resp["BrokerEngineTypes"]) > 0
+ assert resp["MaxResults"] == 20
+
+def test_mq_describe_broker_engine_types_with_engine_type(mq):
+ resp = mq.describe_broker_engine_types(EngineType="RABBITMQ")
+ assert len(resp["BrokerEngineTypes"]) > 0
+ assert all(e["EngineType"] == "RABBITMQ" for e in resp["BrokerEngineTypes"])
+
+def test_mq_describe_broker_engine_types_with_invalid_engine_type(mq):
+ with pytest.raises(ClientError) as exc:
+ mq.describe_broker_engine_types(EngineType="INVALID_ENGINE")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ assert exc.value.response["Error"]["Code"] == "BadRequestException"
+
[email protected]("invalid_max", [4, 101])
+def test_mq_describe_broker_engine_types_with_invalid_max_results(mq, invalid_max):
+ with pytest.raises(ClientError) as exc:
+ mq.describe_broker_engine_types(MaxResults=invalid_max)
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ assert exc.value.response["Error"]["Code"] == "BadRequestException"
+
+########################################################################
+# DescribeBrokerInstanceOptions
+########################################################################
+
+def test_mq_describe_broker_instance_options(mq):
+ resp = mq.describe_broker_instance_options()
+
+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200
+ assert len(resp.get("BrokerInstanceOptions", [])) > 0
+ for option in resp["BrokerInstanceOptions"]:
+ assert "AvailabilityZones" in option
+ assert "EngineType" in option
+ assert "HostInstanceType" in option
+ assert "StorageType" in option
+ assert "SupportedEngineVersions" in option
+ assert "SupportedDeploymentModes" in option
+
+ "kwargs,assertions",
+ [
+ (
+ {"EngineType": "RABBITMQ"},
+ lambda o: o["EngineType"] == "RABBITMQ",
+ ),
+ (
+ {"HostInstanceType": "mq.m5.large"},
+ lambda o: o["HostInstanceType"] == "mq.m5.large",
+ ),
+ (
+ {"StorageType": "EBS"},
+ lambda o: o["StorageType"] == "EBS",
+ ),
+ (
+ {"EngineType": "RABBITMQ", "HostInstanceType": "mq.m5.large"},
+ lambda o: (
+ o["EngineType"] == "RABBITMQ"
+ and o["HostInstanceType"] == "mq.m5.large"
+ ),
+ ),
+ (
+ {"EngineType": "RABBITMQ", "StorageType": "EBS"},
+ lambda o: (
+ o["EngineType"] == "RABBITMQ"
+ and o["StorageType"] == "EBS"
+ ),
+ ),
+ (
+ {"HostInstanceType": "mq.m5.large", "StorageType": "EBS"},
+ lambda o: (
+ o["HostInstanceType"] == "mq.m5.large"
+ and o["StorageType"] == "EBS"
+ ),
+ ),
+ (
+ {
+ "EngineType": "RABBITMQ",
+ "HostInstanceType": "mq.m5.large",
+ "StorageType": "EBS",
+ },
+ lambda o: (
+ o["EngineType"] == "RABBITMQ"
+ and o["HostInstanceType"] == "mq.m5.large"
+ and o["StorageType"] == "EBS"
+ ),
+ ),
+ ],
+)
+def test_mq_broker_instance_options_filtered(mq, kwargs, assertions):
+ resp = mq.describe_broker_instance_options(**kwargs)
+
+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200
+ assert len(resp.get("BrokerInstanceOptions", [])) > 0
+ assert all(assertions(o) for o in resp["BrokerInstanceOptions"])
+
+ "kwargs",
+ [
+ {"EngineType": "INVALID_ENGINE"},
+ {"HostInstanceType": "INVALID_INSTANCE"},
+ {"StorageType": "INVALID_STORAGE"},
+ ],
+)
+def test_mq_describe_broker_instance_options_with_invalid_parameters(mq, kwargs):
+ with pytest.raises(ClientError) as exc:
+ mq.describe_broker_instance_options(**kwargs)
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ assert exc.value.response["Error"]["Code"] == "BadRequestException"
+
+def test_mq_describe_broker_instance_options_with_max_results(mq):
+ resp = mq.describe_broker_instance_options(MaxResults=5)
+
+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200
+ assert resp["MaxResults"] == 5
+ assert len(resp.get("BrokerInstanceOptions", [])) == 5
+
[email protected]("invalid_max", [4, 101])
+def test_mq_describe_broker_instance_options_with_invalid_max_results(mq, invalid_max):
+ with pytest.raises(ClientError) as exc:
+ mq.describe_broker_instance_options(MaxResults=invalid_max)
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ assert exc.value.response["Error"]["Code"] == "BadRequestException"
+
+def test_mq_describe_broker_instance_options_pagination(mq):
+ # Walk all pages with a stable page size and verify pagination progress.
+ seen = set()
+ token = None
+ pages = 0
+ while True:
+ pages += 1
+ kwargs = {"MaxResults": 5}
+ if token:
+ kwargs["NextToken"] = token
+
+ resp = mq.describe_broker_instance_options(**kwargs)
+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200
+ assert resp["MaxResults"] == 5
+
+ items = resp.get("BrokerInstanceOptions", [])
+ assert len(items) <= 5
+
+ page_keys = {
+ (o["EngineType"], o["HostInstanceType"], o["StorageType"])
+ for o in items
+ }
+ assert page_keys.isdisjoint(seen)
+ seen.update(page_keys)
+
+ token = resp.get("NextToken")
+ if not token:
+ break
+
+ # Safety guard in case pagination regresses.
+ assert pages <= 100
+
+ # Ensure pagination actually covered more than one page worth of results.
+ assert len(seen) > 5
+
+#########################################################################
+# CreateTags
+#########################################################################
+
+def test_mq_create_tags(mq):
+ broker = _create(mq, BrokerName=_name("tags"))
+ arn = broker["BrokerArn"]
+
+ create_resp = mq.create_tags(ResourceArn=arn, Tags={"env": "dev", "team": "core"})
+ assert create_resp["ResponseMetadata"]["HTTPStatusCode"] == 204
+
+def test_mq_create_tags_with_non_existent_arn(mq):
+ with pytest.raises(ClientError) as exc:
+ mq.create_tags(ResourceArn="arn:aws:mq:invalid-arn", Tags={"env": "dev"})
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ assert exc.value.response["Error"]["Code"] == "NotFoundException"
+
+##########################################################################
+# ListTags
+##########################################################################
+
+def test_mq_list_tags(mq):
+ broker = _create(mq, BrokerName=_name("tags"))
+ arn = broker["BrokerArn"]
+
+ mq.create_tags(ResourceArn=arn, Tags={"env": "dev", "team": "core"})
+
+ list_resp = mq.list_tags(ResourceArn=arn)
+ assert list_resp["ResponseMetadata"]["HTTPStatusCode"] == 200
+ assert list_resp["Tags"]["env"] == "dev"
+ assert list_resp["Tags"]["team"] == "core"
+
+def test_mq_list_tags_with_no_tags(mq):
+ broker = _create(mq, BrokerName=_name("tags"))
+ arn = broker["BrokerArn"]
+
+ list_resp = mq.list_tags(ResourceArn=arn)
+ assert list_resp["ResponseMetadata"]["HTTPStatusCode"] == 200
+ assert list_resp["Tags"] == {}
+
+def test_mq_list_tags_with_non_existent_arn(mq):
+ with pytest.raises(ClientError) as exc:
+ mq.list_tags(ResourceArn="arn:aws:mq:invalid-arn")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ assert exc.value.response["Error"]["Code"] == "NotFoundException"
+
+def test_mq_list_tags_multiple_times_consistent(mq):
+ """Test that ListTags returns consistent results across multiple calls."""
+ broker = _create(mq, BrokerName=_name("tags-consistency"))
+ arn = broker["BrokerArn"]
+
+ mq.create_tags(ResourceArn=arn, Tags={"a": "1", "b": "2", "c": "3"})
+
+ # Call ListTags multiple times and verify consistency
+ resp1 = mq.list_tags(ResourceArn=arn)
+ resp2 = mq.list_tags(ResourceArn=arn)
+ resp3 = mq.list_tags(ResourceArn=arn)
+
+ assert resp1["Tags"] == resp2["Tags"] == resp3["Tags"]
+ assert len(resp1["Tags"]) == 3
+
+###########################################################################
+# DeleteTags
+###########################################################################
+
+def test_mq_delete_tags(mq):
+ broker = _create(mq, BrokerName=_name("tags"))
+ arn = broker["BrokerArn"]
+
+ mq.create_tags(ResourceArn=arn, Tags={"env": "dev", "team": "core"})
+
+ del_resp = mq.delete_tags(ResourceArn=arn, TagKeys=["env"])
+ assert del_resp["ResponseMetadata"]["HTTPStatusCode"] == 204
+
+ list_resp = mq.list_tags(ResourceArn=arn)
+ assert "env" not in list_resp["Tags"]
+ assert list_resp["Tags"]["team"] == "core"
+
+def test_mq_delete_tags_with_non_existent_arn(mq):
+ with pytest.raises(ClientError) as exc:
+ mq.delete_tags(ResourceArn="arn:aws:mq:invalid-arn", TagKeys=["env"])
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ assert exc.value.response["Error"]["Code"] == "NotFoundException"
+
+def test_mq_delete_tags_idempotent(mq):
+ """Test that DeleteTags is idempotent (deleting non-existent key succeeds)."""
+ broker = _create(mq, BrokerName=_name("tags-idempotent"))
+ arn = broker["BrokerArn"]
+
+ mq.create_tags(ResourceArn=arn, Tags={"key1": "value1"})
+
+ # Delete non-existent key - should succeed
+ del_resp = mq.delete_tags(ResourceArn=arn, TagKeys=["nonexistent"])
+ assert del_resp["ResponseMetadata"]["HTTPStatusCode"] == 204
+
+ # Verify original tag still exists
+ list_resp = mq.list_tags(ResourceArn=arn)
+ assert list_resp["Tags"]["key1"] == "value1"
+
+############################################################################
+# CreateUser
+############################################################################
+
+def test_mq_create_user_with_required_options(mq):
+ broker_id = _create(mq, BrokerName=_name("user"), EngineType="ACTIVEMQ", EngineVersion="5.19")["BrokerId"]
+
+ resp = mq.create_user(
+ BrokerId=broker_id,
+ Username="testuser",
+ Password="TestPassw0rd!",
+ ConsoleAccess=False,
+ )
+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200
+
+def test_mq_create_user_with_duplicated_username(mq):
+ broker_id = _create(mq, BrokerName=_name("user"), EngineType="ACTIVEMQ", EngineVersion="5.19")["BrokerId"]
+
+ mq.create_user(
+ BrokerId=broker_id,
+ Username="testuser",
+ Password="TestPassw0rd!",
+ ConsoleAccess=False,
+ )
+
+ with pytest.raises(ClientError) as exc:
+ mq.create_user(
+ BrokerId=broker_id,
+ Username="testuser",
+ Password="AnotherPassw0rd!",
+ ConsoleAccess=False,
+ )
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 409
+ assert exc.value.response["Error"]["Code"] == "ConflictException"
+
[email protected]("invalid_password", [
+ "pas", # less than 4 characters
+ "password,", # with commas
+ "password:", # with colons
+ "password=" # with equals sign
+])
+def test_mq_create_user_with_invalid_password(mq, invalid_password):
+ broker_id = _create(mq, BrokerName=_name("user"), EngineType="ACTIVEMQ", EngineVersion="5.19")["BrokerId"]
+ with pytest.raises(ClientError) as exc:
+ mq.create_user(
+ BrokerId=broker_id,
+ Username="testuser",
+ Password=invalid_password,
+ ConsoleAccess=False,
+ )
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ assert exc.value.response["Error"]["Code"] == "BadRequestException"
+
+def test_mq_create_user_with_non_existent_broker_id(mq):
+ with pytest.raises(ClientError) as exc:
+ mq.create_user(
+ BrokerId="invalid-id",
+ Username="testuser",
+ Password="TestPassw0rd!",
+ ConsoleAccess=False,
+ )
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ assert exc.value.response["Error"]["Code"] == "NotFoundException"
+
+def test_mq_create_user_with_not_supported_engine_type(mq):
+ broker_id = _create(mq, BrokerName=_name("user-invalid"), EngineType="RABBITMQ", EngineVersion="4.2")["BrokerId"]
+
+ with pytest.raises(ClientError) as exc:
+ mq.create_user(
+ BrokerId=broker_id,
+ Username="testuser",
+ Password="TestPassw0rd!",
+ ConsoleAccess=False,
+ )
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ assert exc.value.response["Error"]["Code"] == "BadRequestException"
+
+##########################################################################
+# DeleteUser
+##########################################################################
+
+def test_mq_delete_user(mq):
+ broker_id = _create(mq, BrokerName=_name("user"), EngineType="ACTIVEMQ", EngineVersion="5.19")["BrokerId"]
+
+ mq.create_user(
+ BrokerId=broker_id,
+ Username="testuser",
+ Password="TestPassw0rd!",
+ ConsoleAccess=False,
+ )
+
+ del_resp = mq.delete_user(BrokerId=broker_id, Username="testuser")
+ assert del_resp["ResponseMetadata"]["HTTPStatusCode"] == 200
+
+def test_mq_delete_user_with_non_existent_username(mq):
+ broker_id = _create(mq, BrokerName=_name("user"), EngineType="ACTIVEMQ", EngineVersion="5.19")["BrokerId"]
+
+ with pytest.raises(ClientError) as exc:
+ mq.delete_user(BrokerId=broker_id, Username="nonexistentuser")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ assert exc.value.response["Error"]["Code"] == "NotFoundException"
+
+def test_mq_delete_user_with_non_existent_broker_id(mq):
+ with pytest.raises(ClientError) as exc:
+ mq.delete_user(BrokerId="invalid-id", Username="testuser")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ assert exc.value.response["Error"]["Code"] == "NotFoundException"
+
+def test_mq_delete_user_with_not_supported_engine_type(mq):
+ broker_id = _create(mq, BrokerName=_name("user-invalid"), EngineType="RABBITMQ", EngineVersion="4.2")["BrokerId"]
+
+ with pytest.raises(ClientError) as exc:
+ mq.delete_user(BrokerId=broker_id, Username="testuser")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ assert exc.value.response["Error"]["Code"] == "BadRequestException"
+
+###########################################################################
+# ListUsers
+###########################################################################
+
+def test_mq_list_users(mq):
+ broker_id = _create(mq, BrokerName=_name("user"), EngineType="ACTIVEMQ", EngineVersion="5.19")["BrokerId"]
+
+ mq.create_user(
+ BrokerId=broker_id,
+ Username="testuser1",
+ Password="TestPassw0rd!",
+ ConsoleAccess=False,
+ )
+
+ list_resp = mq.list_users(BrokerId=broker_id)
+ assert list_resp["ResponseMetadata"]["HTTPStatusCode"] == 200
+ assert list_resp["MaxResults"] == 20
+ usernames = {u["Username"] for u in list_resp.get("Users", [])}
+ assert "testuser1" in usernames
+
+def test_mq_list_users_with_no_users(mq):
+ broker_id = _create(mq, BrokerName=_name("user"), EngineType="ACTIVEMQ", EngineVersion="5.19")["BrokerId"]
+
+ list_resp = mq.list_users(BrokerId=broker_id)
+ assert list_resp["ResponseMetadata"]["HTTPStatusCode"] == 200
+ assert list_resp.get("Users", []) == []
+ assert isinstance(list_resp.get("Users", []), list)
+
+def test_mq_list_users_with_non_existent_broker_id(mq):
+ with pytest.raises(ClientError) as exc:
+ mq.list_users(BrokerId="invalid-id")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ assert exc.value.response["Error"]["Code"] == "NotFoundException"
+
+def test_mq_list_users_with_not_supported_engine_type(mq):
+ broker_id = _create(mq, BrokerName=_name("user-invalid"), EngineType="RABBITMQ")["BrokerId"]
+
+ with pytest.raises(ClientError) as exc:
+ mq.list_users(BrokerId=broker_id)
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ assert exc.value.response["Error"]["Code"] == "BadRequestException"
+
+def test_mq_list_users_with_pagination(mq):
+ broker_id = _create(mq, BrokerName=_name("user-page"), EngineType="ACTIVEMQ", EngineVersion="5.19")["BrokerId"]
+
+ # Create enough users to require multiple pages.
+ expected_usernames = set()
+ for i in range(9):
+ username = f"testuser{i}"
+ expected_usernames.add(username)
+ mq.create_user(
+ BrokerId=broker_id,
+ Username=username,
+ Password="TestPassw0rd!",
+ ConsoleAccess=False,
+ )
+
+ # Paginate with stable MaxResults and gather until all created users are observed.
+ listed_usernames = set()
+ token = None
+ pages = 0
+ while True:
+ pages += 1
+ kwargs = {"BrokerId": broker_id, "MaxResults": 5}
+ if token:
+ kwargs["NextToken"] = token
+
+ resp = mq.list_users(**kwargs)
+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200
+ assert resp["MaxResults"] == 5
+ assert len(resp.get("Users", [])) <= 5
+
+ listed_usernames.update({u["Username"] for u in resp.get("Users", [])})
+ if expected_usernames.issubset(listed_usernames):
+ break
+
+ token = resp.get("NextToken")
+ if not token:
+ break
+
+ # Safety guard in case pagination regresses.
+ assert pages <= 100
+
+ assert expected_usernames.issubset(listed_usernames), f"Expected {expected_usernames} in {listed_usernames}"
+
[email protected]("invalid_max", [4, 101])
+def test_mq_list_users_with_invalid_max_results(mq, invalid_max):
+ broker_id = _create(mq, BrokerName=_name("user-invalid-max"), EngineType="ACTIVEMQ", EngineVersion="5.19")["BrokerId"]
+
+ with pytest.raises(ClientError) as exc:
+ mq.list_users(BrokerId=broker_id, MaxResults=invalid_max)
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ assert exc.value.response["Error"]["Code"] == "BadRequestException"
+
+############################################################################
+# UpdateUser
+############################################################################
+
+def test_mq_update_user(mq):
+ broker_id = _create(mq, BrokerName=_name("user"), EngineType="ACTIVEMQ", EngineVersion="5.19")["BrokerId"]
+
+ mq.create_user(
+ BrokerId=broker_id,
+ Username="full_update_user",
+ Password="InitialPassw0rd!",
+ ConsoleAccess=False,
+ Groups=["users"],
+ ReplicationUser=False,
+ )
+
+ # Update all fields
+ mq.update_user(
+ BrokerId=broker_id,
+ Username="full_update_user",
+ Password="UpdatedPassw0rd!",
+ ConsoleAccess=True,
+ Groups=["admins", "ops"],
+ ReplicationUser=True,
+ )
+
+ # Verify updates
+ user = mq.describe_user(BrokerId=broker_id, Username="full_update_user")
+ assert user["ConsoleAccess"] == True
+ assert set(user["Groups"]) == {"admins", "ops"}
+ assert user["ReplicationUser"] == True
+
+def test_mq_update_user_with_non_existent_username(mq):
+ broker_id = _create(mq, BrokerName=_name("user"), EngineType="ACTIVEMQ", EngineVersion="5.19")["BrokerId"]
+
+ with pytest.raises(ClientError) as exc:
+ mq.update_user(
+ BrokerId=broker_id,
+ Username="nonexistentuser",
+ Password="NewPassw0rd!",
+ ConsoleAccess=True,
+ )
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ assert exc.value.response["Error"]["Code"] == "NotFoundException"
+
+def test_mq_update_user_with_non_existent_broker_id(mq):
+ with pytest.raises(ClientError) as exc:
+ mq.update_user(
+ BrokerId="invalid-id",
+ Username="testuser",
+ Password="NewPassw0rd!",
+ ConsoleAccess=True,
+ )
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ assert exc.value.response["Error"]["Code"] == "NotFoundException"
+
+def test_mq_update_user_with_not_supported_engine_type(mq):
+ broker_id = _create(mq, BrokerName=_name("user-invalid-update"), EngineType="RABBITMQ")["BrokerId"]
+
+ with pytest.raises(ClientError) as exc:
+ mq.update_user(
+ BrokerId=broker_id,
+ Username="testuser",
+ Password="NewPassw0rd!",
+ ConsoleAccess=True,
+ )
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ assert exc.value.response["Error"]["Code"] == "BadRequestException"
+
[email protected]("invalid_password", [
+ "pas", # less than 4 characters
+ "password,", # with commas
+ "password:", # with colons
+ "password=" # with equals sign
+])
+def test_mq_update_user_with_invalid_password(mq, invalid_password):
+ broker_id = _create(mq, BrokerName=_name("user-invalid-update"), EngineType="ACTIVEMQ", EngineVersion="5.19")["BrokerId"]
+
+ mq.create_user(
+ BrokerId=broker_id,
+ Username="testuser",
+ Password="TestPassw0rd!",
+ ConsoleAccess=False,
+ )
+
+ with pytest.raises(ClientError) as exc:
+ mq.update_user(
+ BrokerId=broker_id,
+ Username="testuser",
+ Password=invalid_password,
+ )
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ assert exc.value.response["Error"]["Code"] == "BadRequestException"
+
+############################################################################
+# DescribeUser
+############################################################################
+
+def test_mq_describe_user(mq):
+ broker_id = _create(mq, BrokerName=_name("user"), EngineType="ACTIVEMQ", EngineVersion="5.19")["BrokerId"]
+
+ mq.create_user(
+ BrokerId=broker_id,
+ Username="testuser",
+ Password="TestPassw0rd!",
+ ConsoleAccess=False,
+ Groups=["group1", "group2"],
+ ReplicationUser = True
+ )
+
+ desc_resp = mq.describe_user(BrokerId=broker_id, Username="testuser")
+ assert desc_resp["ResponseMetadata"]["HTTPStatusCode"] == 200
+ assert desc_resp["Username"] == "testuser"
+ assert desc_resp["ConsoleAccess"] is False
+ assert set(desc_resp["Groups"]) == {"group1", "group2"}
+ assert desc_resp["ReplicationUser"] is True
+
+def test_mq_describe_user_with_non_existent_username(mq):
+ broker_id = _create(mq, BrokerName=_name("user"), EngineType="ACTIVEMQ", EngineVersion="5.19")["BrokerId"]
+
+ with pytest.raises(ClientError) as exc:
+ mq.describe_user(BrokerId=broker_id, Username="nonexistentuser")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ assert exc.value.response["Error"]["Code"] == "NotFoundException"
+
+def test_mq_describe_user_with_non_existent_broker_id(mq):
+ with pytest.raises(ClientError) as exc:
+ mq.describe_user(BrokerId="invalid-id", Username="testuser")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ assert exc.value.response["Error"]["Code"] == "NotFoundException"
+
+def test_mq_describe_user_with_not_supported_engine_type(mq):
+ broker_id = _create(mq, BrokerName=_name("user-invalid-describe"), EngineType="RABBITMQ")["BrokerId"]
+
+ with pytest.raises(ClientError) as exc:
+ mq.describe_user(BrokerId=broker_id, Username="testuser")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ assert exc.value.response["Error"]["Code"] == "BadRequestException"
+
+
+############################################################################
+# Lifecycle tests
+############################################################################
+
+def test_mq_create_describe_delete_broker_tags_lifecycle(mq):
+ """Test full lifecycle: create with tags -> describe shows tags -> delete removes tags."""
+ name = _name("lifecycle-tags")
+
+ # 1. Create broker with tags
+ create_resp = mq.create_broker(
+ BrokerName=name,
+ EngineType="RABBITMQ",
+ EngineVersion="3.13",
+ HostInstanceType="mq.m5.large",
+ PubliclyAccessible=False,
+ DeploymentMode="SINGLE_INSTANCE",
+ Tags={"lifecycle": "test", "phase": "all"},
+ )
+ broker_id = create_resp["BrokerId"]
+ broker_arn = create_resp["BrokerArn"]
+
+ # 2. Describe broker and verify tags included
+ desc = mq.describe_broker(BrokerId=broker_id)
+ assert desc["Tags"]["lifecycle"] == "test"
+ assert desc["Tags"]["phase"] == "all"
+
+ # 3. Add more tags
+ mq.create_tags(ResourceArn=broker_arn, Tags={"added": "later"})
+
+ # 4. Verify describe shows all tags
+ desc2 = mq.describe_broker(BrokerId=broker_id)
+ assert desc2["Tags"]["lifecycle"] == "test"
+ assert desc2["Tags"]["phase"] == "all"
+ assert desc2["Tags"]["added"] == "later"
+
+ # 5. Delete broker
+ mq.delete_broker(BrokerId=broker_id)
+
+ # 6. Verify tags are cleaned up
+ with pytest.raises(ClientError) as exc:
+ mq.list_tags(ResourceArn=broker_arn)
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+
+
+def test_mq_multiple_brokers_isolated_tags(mq):
+ """Test that tags from different brokers don't interfere with each other."""
+ # Create two brokers with different tags
+ name1 = _name("isolated-1")
+ resp1 = mq.create_broker(
+ BrokerName=name1,
+ EngineType="RABBITMQ",
+ EngineVersion="3.13",
+ HostInstanceType="mq.m5.large",
+ PubliclyAccessible=False,
+ DeploymentMode="SINGLE_INSTANCE",
+ Tags={"broker": "first", "env": "prod"},
+ )
+ arn1 = resp1["BrokerArn"]
+
+ name2 = _name("isolated-2")
+ resp2 = mq.create_broker(
+ BrokerName=name2,
+ EngineType="RABBITMQ",
+ EngineVersion="3.13",
+ HostInstanceType="mq.m5.large",
+ PubliclyAccessible=False,
+ DeploymentMode="SINGLE_INSTANCE",
+ Tags={"broker": "second", "env": "dev"},
+ )
+ arn2 = resp2["BrokerArn"]
+
+ # Verify each broker has its own isolated tags
+ tags1 = mq.list_tags(ResourceArn=arn1)["Tags"]
+ tags2 = mq.list_tags(ResourceArn=arn2)["Tags"]
+
+ assert tags1["broker"] == "first"
+ assert tags1["env"] == "prod"
+ assert tags2["broker"] == "second"
+ assert tags2["env"] == "dev"
+
+
+def test_mq_multiple_brokers_isolated_users(mq):
+ """Test that users from different brokers don't interfere with each other."""
+ # Create two ActiveMQ brokers
+ broker_id1 = _create(mq, BrokerName=_name("users-isolated-1"), EngineType="ACTIVEMQ", EngineVersion="5.19")["BrokerId"]
+ broker_id2 = _create(mq, BrokerName=_name("users-isolated-2"), EngineType="ACTIVEMQ", EngineVersion="5.19")["BrokerId"]
+
+ # Create users with same username in different brokers
+ mq.create_user(
+ BrokerId=broker_id1,
+ Username="shared_name",
+ Password="Broker1Passw0rd!",
+ ConsoleAccess=True,
+ )
+
+ mq.create_user(
+ BrokerId=broker_id2,
+ Username="shared_name",
+ Password="Broker2Passw0rd!",
+ ConsoleAccess=False,
+ )
+
+ # Verify users are isolated
+ user1 = mq.describe_user(BrokerId=broker_id1, Username="shared_name")
+ user2 = mq.describe_user(BrokerId=broker_id2, Username="shared_name")
+
+ assert user1 is not None
+ assert user2 is not None
+ assert user1["ConsoleAccess"] == True
+ assert user2["ConsoleAccess"] == False
+
+
+def test_mq_recreate_broker_after_delete_has_fresh_tags_and_users(mq):
+ """Test that recreating a broker after deletion starts with fresh tag/user dicts."""
+ name = _name("recreate-fresh")
+
+ # Create, add tags/users, and delete
+ resp1 = mq.create_broker(
+ BrokerName=name,
+ EngineType="ACTIVEMQ",
+ EngineVersion="5.19",
+ HostInstanceType="mq.m5.large",
+ PubliclyAccessible=False,
+ DeploymentMode="SINGLE_INSTANCE",
+ Tags={"first": "creation"},
+ )
+ broker_id1 = resp1["BrokerId"]
+ broker_arn1 = resp1["BrokerArn"]
+
+ # Add a user
+ mq.create_user(
+ BrokerId=broker_id1,
+ Username="first_user",
+ Password="FirstPassw0rd!",
+ ConsoleAccess=True,
+ )
+
+ # Delete the broker
+ mq.delete_broker(BrokerId=broker_id1)
+
+ # Recreate broker with same name
+ resp2 = mq.create_broker(
+ BrokerName=name,
+ EngineType="ACTIVEMQ",
+ EngineVersion="5.19",
+ HostInstanceType="mq.m5.large",
+ PubliclyAccessible=False,
+ DeploymentMode="SINGLE_INSTANCE",
+ )
+ broker_id2 = resp2["BrokerId"]
+ broker_arn2 = resp2["BrokerArn"]
+
+ # Verify fresh state
+ tags = mq.list_tags(ResourceArn=broker_arn2)["Tags"]
+ users = mq.list_users(BrokerId=broker_id2)["Users"]
+
+ assert tags == {}
+ assert users == []
+
+ # Verify old ARN is different from new ARN
+ assert broker_arn1 != broker_arn2