Skip to content

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

feat: add GET /_ministack/ses/messages endpoint for email inspection (#419)

Johannes Grumböcka99412c25dce
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 71d3efb0..7773a80b 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -130,6 +130,8 @@ def test_myservice_operation_one(mysvc):
assert resp["result"] == "ok"
```
+**Note:** If your service has operations that mutate global state or require isolation (like calling the reset endpoint), add them to the `_SERIAL_TESTS` set in `conftest.py`. This ensures they run sequentially after the parallel-safe tests.
+
---
## Running Tests Locally
diff --git a/ministack/app.py b/ministack/app.py
index b9a75d06..6b37e130 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -59,7 +59,7 @@ _NON_S3_VHOST_NAMES = frozenset({
from ministack.core.hypercorn_compat import install as _install_hypercorn_compat
from ministack.core.persistence import PERSIST_STATE, load_state, save_all
-from ministack.core.responses import set_request_account_id, set_request_region
+from ministack.core.responses import _12_DIGIT_RE, set_request_account_id, set_request_region
from ministack.core.router import detect_service, extract_access_key_id, extract_region
# Must run before hypercorn emits its first Expect: 100-continue reply.
@@ -452,6 +452,66 @@ async def _handle_admin_reset(path: str, method: str, query_params: dict):
return 200, {"Content-Type": "application/json"}, json.dumps({"reset": "ok"}).encode()
+async def _handle_ses_messages_request(method: str, path: str, headers: dict, query_params: dict):
+ """Handle SES messages inspection endpoint.
+
+ Supports filtering by account via the 'account' query parameter. When provided,
+ sets the request context to that account so emails are retrieved from the correct
+ AccountScopedDict._sent_emails_list.
+ """
+ if path != "/_ministack/ses/messages" or method != "GET":
+ return None
+
+ account_id = None
+ if "account" in query_params:
+ raw_account = query_params["account"]
+ account_id = raw_account[0] if isinstance(raw_account, (list, tuple)) else raw_account
+ if not _12_DIGIT_RE.match(account_id):
+ return 400, {"Content-Type": "application/json"}, json.dumps({
+ "__type": "InvalidAccountID",
+ "message": f"Account ID must be 12 digits, got: {account_id}",
+ }).encode()
+
+ try:
+ mod = _get_module("ses")
+ sent_emails_dict = {}
+ try:
+ all_data = mod._sent_emails.to_dict()
+ for (acct, key), val in all_data.items():
+ if key == "entries" and isinstance(val, list):
+ sent_emails_dict[acct] = val
+ except Exception:
+ # Fallback: empty dict on any unexpected shape
+ sent_emails_dict = {}
+
+ response = {
+ "messages": {
+ acct: [
+ {
+ "MessageId": rec["MessageId"],
+ "Source": rec["Source"],
+ "To": rec.get("To", []),
+ "CC": rec.get("CC", []),
+ "BCC": rec.get("BCC", []),
+ "Subject": rec.get("RenderedSubject") or rec.get("Subject", ""),
+ "BodyText": rec.get("RenderedBodyText") or rec.get("BodyText", ""),
+ "BodyHtml": rec.get("RenderedBodyHtml") or rec.get("BodyHtml"),
+ "Timestamp": rec["Timestamp"],
+ "Type": rec["Type"],
+ }
+ for rec in (recs if isinstance(recs, list) else [])
+ ]
+ for acct, recs in sent_emails_dict.items()
+ if account_id is None or acct == account_id
+ }
+ }
+ except Exception as e:
+ logger.exception("Error retrieving SES messages: %s", e)
+ return 500, {"Content-Type": "application/json"}, json.dumps({"message": str(e)}).encode()
+
+ return 200, {"Content-Type": "application/json"}, json.dumps(response).encode()
+
+
async def _handle_pre_body_request(method: str, path: str, headers: dict, query_params: dict, request_id: str):
"""Handle fast-path routes that do not require request body parsing."""
# OPTIONS on an execute-api host / path MUST flow through apigateway.handle_execute
@@ -472,6 +532,11 @@ async def _handle_pre_body_request(method: str, path: str, headers: dict, query_
response = await _handle_cognito_get_request(method, path, headers, query_params)
if response is not None:
return response
+
+ response = await _handle_ses_messages_request(method, path, headers, query_params)
+ if response is not None:
+ return response
+
return await _handle_admin_reset(path, method, query_params)
diff --git a/ministack/services/ses.py b/ministack/services/ses.py
index 2f4fd402..f87d8b81 100644
--- a/ministack/services/ses.py
+++ b/ministack/services/ses.py
@@ -192,11 +192,31 @@ def _send_raw_email(params):
parsed = _parse_raw_mime(raw_b64)
+ # Extract from body parts if available
+ subject = ""
+ body_text = ""
+ body_html = None
+ for part_info in parsed.get("BodyParts", []):
+ if isinstance(part_info, dict):
+ ct = part_info.get("ContentType", "")
+ data = part_info.get("Data", "")
+ if "text/plain" in ct:
+ body_text = data
+ elif "text/html" in ct:
+ body_html = data
+ elif isinstance(part_info, str):
+ # Already parsed as string (edge case)
+ pass
+
record = {
"MessageId": msg_id,
"Source": source or parsed.get("From", ""),
- "RawMessage": raw_b64,
- "Parsed": parsed,
+ "To": [e.strip() for e in parsed.get("To", "").split(",") if e.strip()] or [],
+ "CC": [e.strip() for e in parsed.get("Cc", "").split(",") if e.strip()] or [],
+ "BCC": [e.strip() for e in parsed.get("Bcc", "").split(",") if e.strip()] or [],
+ "Subject": subject or parsed.get("Subject", ""),
+ "BodyText": body_text,
+ "BodyHtml": body_html,
"Timestamp": time.time(),
"Type": "SendRawEmail",
}
@@ -206,7 +226,9 @@ def _send_raw_email(params):
actual_source = source or parsed.get("From", "")
raw_destinations = _collect_list(params, "Destinations.member")
to_from_parsed = [a.strip() for a in parsed.get("To", "").split(",") if a.strip()]
- relay_addrs = raw_destinations or to_from_parsed
+ cc_from_parsed = [a.strip() for a in parsed.get("Cc", "").split(",") if a.strip()]
+ bcc_from_parsed = [a.strip() for a in parsed.get("Bcc", "").split(",") if a.strip()]
+ relay_addrs = raw_destinations or (to_from_parsed + cc_from_parsed + bcc_from_parsed)
if actual_source and relay_addrs:
try:
raw_bytes = raw_b64.encode('utf-8') if isinstance(raw_b64, str) else raw_b64
diff --git a/ministack/services/ses_v2.py b/ministack/services/ses_v2.py
index 8bcbecc8..7bc6825d 100644
--- a/ministack/services/ses_v2.py
+++ b/ministack/services/ses_v2.py
@@ -13,10 +13,11 @@ import json
import logging
import os
import re
+import time
from ministack.core.persistence import PERSIST_STATE, load_state
from ministack.core.responses import AccountScopedDict, get_account_id, json_response, new_uuid, now_iso, get_region
-from ministack.services.ses import _build_mime_message, _smtp_relay
+from ministack.services.ses import _build_mime_message, _smtp_relay, _sent_emails_list, _parse_raw_mime
logger = logging.getLogger("ses-v2")
@@ -68,11 +69,14 @@ async def handle_request(method, path, headers, body, query_params):
# GET /v2/email/account
if sub == "/account" and method == "GET":
+ cutoff = time.time() - 86400
+ sent_list = _sent_emails_list()
+ sent_24h = sum(1 for e in sent_list if e["Timestamp"] >= cutoff)
return json_response({
"DedicatedIpAutoWarmupEnabled": False,
"EnforcementStatus": "HEALTHY",
"ProductionAccessEnabled": True,
- "SendQuota": {"Max24HourSend": 50000.0, "MaxSendRate": 14.0, "SentLast24Hours": 0.0},
+ "SendQuota": {"Max24HourSend": 50000.0, "MaxSendRate": 14.0, "SentLast24Hours": float(sent_24h)},
"SendingEnabled": True,
"SuppressionAttributes": {"SuppressedReasons": []},
})
@@ -88,34 +92,61 @@ async def handle_request(method, path, headers, body, query_params):
# POST /v2/email/outbound-emails (SendEmail)
if sub == "/outbound-emails" and method == "POST":
msg_id = f"ministack-{new_uuid()}"
- logger.info("SESv2 SendEmail: MessageId=%s", msg_id)
- # SMTP relay
source = data.get("FromEmailAddress", "")
dest = data.get("Destination", {})
to_addrs = dest.get("ToAddresses", [])
cc_addrs = dest.get("CcAddresses", [])
bcc_addrs = dest.get("BccAddresses", [])
+ content = data.get("Content", {})
+ simple = content.get("Simple", {})
+ raw = content.get("Raw", {})
+ subj = ""
+ body_text = ""
+ body_html = None
+ if simple:
+ subj = simple.get("Subject", {}).get("Data", "")
+ body_text = simple.get("Body", {}).get("Text", {}).get("Data", "")
+ body_html = simple.get("Body", {}).get("Html", {}).get("Data", "")
+ elif raw:
+ raw_data = raw.get("Data", "")
+ parsed = _parse_raw_mime(raw_data)
+ subj = parsed.get("Subject", "") or ""
+ for part_info in parsed.get("BodyParts", []):
+ if isinstance(part_info, dict):
+ ct = part_info.get("ContentType", "")
+ data = part_info.get("Data", "")
+ if "text/plain" in ct:
+ body_text = data
+ elif "text/html" in ct:
+ body_html = data
+ # Extract Cc/Bcc from raw MIME headers when not provided via Destination
+ if not cc_addrs:
+ cc_addrs = [e.strip() for e in parsed.get("Cc", "").split(",") if e.strip()]
+ if not bcc_addrs:
+ bcc_addrs = [e.strip() for e in parsed.get("Bcc", "").split(",") if e.strip()]
+
all_addrs = to_addrs + cc_addrs + bcc_addrs
if source and all_addrs:
- content = data.get("Content", {})
- simple = content.get("Simple", {})
- raw = content.get("Raw", {})
- if simple:
- subj = simple.get("Subject", {}).get("Data", "")
- body_text = simple.get("Body", {}).get("Text", {}).get("Data", "")
- body_html = simple.get("Body", {}).get("Html", {}).get("Data", "")
- mime_str = _build_mime_message(source, to_addrs, cc_addrs, bcc_addrs,
- subj, body_text, body_html, msg_id)
- _smtp_relay(source, all_addrs, mime_str)
- elif raw:
- import base64
- raw_data = raw.get("Data", "")
- try:
- decoded = base64.b64decode(raw_data).decode('utf-8', errors='replace')
- except Exception:
- decoded = raw_data
- raw_str = f'Message-ID: <{msg_id}>\r\n' + decoded
- _smtp_relay(source, all_addrs, raw_str)
+ mime_str = _build_mime_message(source, to_addrs, cc_addrs, bcc_addrs,
+ subj, body_text, body_html, msg_id)
+ _smtp_relay(source, all_addrs, mime_str)
+
+ # Append to shared sent_emails list for inspection endpoint visibility
+ record = {
+ "MessageId": msg_id,
+ "Source": source,
+ "To": to_addrs,
+ "CC": cc_addrs,
+ "BCC": bcc_addrs,
+ "Subject": subj,
+ "BodyText": body_text,
+ "BodyHtml": body_html,
+ "Timestamp": time.time(),
+ "Type": "v2.SendEmail",
+ }
+ _sent_emails_list().append(record)
+
+ logger.info("SESv2 SendEmail: MessageId=%s | %s -> %s", msg_id, source, to_addrs)
return json_response({"MessageId": msg_id})
# POST /v2/email/identities (CreateEmailIdentity)
diff --git a/tests/conftest.py b/tests/conftest.py
index c02e7490..29e91d41 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -31,15 +31,17 @@ def make_client(service):
_SERIAL_TESTS = {
"tests/test_athena.py::test_athena_engine_mock_via_config",
+ "tests/test_ec2.py::test_ec2_create_default_vpc",
+ "tests/test_eks.py::test_eks_cfn_cluster",
+ "tests/test_eks.py::test_eks_create_describe_delete_cluster",
"tests/test_lambda.py::test_lambda_reset_terminates_workers",
"tests/test_ministack.py::test_ministack_config_invalid_key_ignored",
+ "tests/test_ses.py::test_ses_messages_endpoint_reset",
+ "tests/test_ses.py::test_ses_messages_endpoint_account_filter",
"tests/test_sfn.py::test_sfn_mock_config_return",
"tests/test_sfn.py::test_sfn_mock_config_throw",
- "tests/test_ec2.py::test_ec2_create_default_vpc",
- "tests/test_sfn.py::test_sfn_wait_scale_zero_skips_wait",
"tests/test_sfn.py::test_sfn_wait_scale_zero_does_not_timeout_lambda_tasks",
- "tests/test_eks.py::test_eks_create_describe_delete_cluster",
- "tests/test_eks.py::test_eks_cfn_cluster",
+ "tests/test_sfn.py::test_sfn_wait_scale_zero_skips_wait",
}
diff --git a/tests/test_ses.py b/tests/test_ses.py
index c516d04b..5872ab8d 100644
--- a/tests/test_ses.py
+++ b/tests/test_ses.py
@@ -1,6 +1,7 @@
"""SES tests — API operations + SMTP relay integration."""
import io
+import base64
import json
import os
import pytest
@@ -9,9 +10,9 @@ import uuid as _uuid_mod
import zipfile
from botocore.exceptions import ClientError
from urllib.parse import urlparse
+from unittest.mock import MagicMock, patch
-# ========== from test_ses.py ==========
def test_ses_parse_smtp_host_not_set():
from ministack.services.ses import _parse_smtp_host
@@ -243,15 +244,6 @@ def test_ses_v2_get_account(sesv2):
assert resp["SendingEnabled"] is True
assert resp["ProductionAccessEnabled"] is True
-# ========== from test_ses_smtp_relay.py ==========
-
-"""Unit tests for SES SMTP relay functionality."""
-import os
-from unittest.mock import MagicMock, patch
-
-import pytest
-
-
@pytest.fixture(autouse=True)
def _clear_smtp_host():
"""Ensure SMTP_HOST is clean before/after each test."""
@@ -448,3 +440,248 @@ def test_ses_smtp_relay_send_templated_email(monkeypatch):
mock_smtp.sendmail.assert_called_once()
msg = _parse_mime(mock_smtp.sendmail.call_args[0][2])
assert 'Hello World' in msg['Subject']
+
+# ---------------------------------------------------------------------------
+# Endpoint tests for the new /_ministack/ses/messages endpoint
+# Verifies acceptance criteria from issue #415:
+# - v1 SES: SendEmail, SendRawEmail, SendTemplatedEmail, SendBulkTemplatedEmail
+# - v2 SES: SendEmail via sesv2 client
+# ---------------------------------------------------------------------------
+
+def test_ses_messages_endpoint_all_v1_send_types(ses):
+ """GET /_ministack/ses/messages shows all v1 send operations."""
+ import urllib.request
+
+ # Prepare template for SendTemplatedEmail and SendBulkTemplatedEmail
+ ses.create_template(Template={
+ "TemplateName": "test-template",
+ "SubjectPart": "Hello {{name}}",
+ "TextPart": "Hi {{name}}!",
+ })
+
+ # Test 1: Verify SendEmail appears
+ ses.verify_email_identity(EmailAddress="[email protected]")
+ ses.send_email(
+ Source="[email protected]",
+ Destination={"ToAddresses": ["[email protected]"]},
+ Message={
+ "Subject": {"Data": "Test v1 subject"},
+ "Body": {"Text": {"Data": "Hello from MiniStack SES v1"}},
+ },
+ )
+
+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+ url = f"{endpoint}/_ministack/ses/messages"
+ req = urllib.request.Request(url, method="GET")
+ with urllib.request.urlopen(req, timeout=5) as r:
+ data = json.loads(r.read().decode())
+
+ assert "messages" in data
+ send_emails = [m for m in data["messages"]["000000000000"] if m["Type"] == "SendEmail" and m["Source"] == "[email protected]"]
+ assert len(send_emails) >= 1, f"Expected SendEmail, got {[m['Type'] for m in data['messages']['000000000000']]}"
+
+ # Test 2: Verify SendRawEmail appears
+ ses.verify_email_identity(EmailAddress="[email protected]")
+ raw = (
+ "From: [email protected]\r\nTo: [email protected]\r\nSubject: Raw Test\r\n\r\nRaw body"
+ )
+ ses.send_raw_email(RawMessage={"Data": raw})
+
+ req = urllib.request.Request(url, method="GET")
+ with urllib.request.urlopen(req, timeout=5) as r:
+ data = json.loads(r.read().decode())
+
+ raw_emails = [m for m in data["messages"]["000000000000"] if m["Type"] == "SendRawEmail" and m["Source"] == "[email protected]"]
+ assert len(raw_emails) >= 1, f"Expected SendRawEmail, got {[m['Type'] for m in data['messages']['000000000000']]}"
+
+ # Test 3: Verify SendTemplatedEmail appears
+ resp = ses.send_templated_email(
+ Source="[email protected]",
+ Destination={"ToAddresses": ["[email protected]"]},
+ Template="test-template",
+ TemplateData=json.dumps({"name": "Alice"}),
+ )
+
+ req = urllib.request.Request(url, method="GET")
+ with urllib.request.urlopen(req, timeout=5) as r:
+ data = json.loads(r.read().decode())
+
+ templated_emails = [m for m in data["messages"]["000000000000"] if m["Type"] == "SendTemplatedEmail" and m["Source"] == "[email protected]"]
+ assert len(templated_emails) >= 1, f"Expected SendTemplatedEmail, got {[m['Type'] for m in data['messages']['000000000000']]}"
+
+ # Test 4: Verify SendBulkTemplatedEmail appears
+ resp = ses.send_bulk_templated_email(
+ Source="[email protected]",
+ Template="test-template",
+ DefaultTemplateData=json.dumps({"name": "Bob"}),
+ Destinations=[
+ {
+ "Destination": {"ToAddresses": ["[email protected]"]},
+ "ReplacementTemplateData": json.dumps({"name": "Bob"}),
+ },
+ {
+ "Destination": {"ToAddresses": ["[email protected]"]},
+ "ReplacementTemplateData": json.dumps({"name": "Carol"}),
+ },
+ ],
+ )
+
+ req = urllib.request.Request(url, method="GET")
+ with urllib.request.urlopen(req, timeout=5) as r:
+ data = json.loads(r.read().decode())
+
+ bulk_emails = [m for m in data["messages"]["000000000000"] if m["Type"] == "SendBulkTemplatedEmail" and m["Source"] == "[email protected]"]
+ assert len(bulk_emails) >= 2, f"Expected SendBulkTemplatedEmail (>=2), got {[m['Type'] for m in data['messages']['000000000000']]}"
+
+def test_ses_messages_endpoint_v2(sesv2):
+ """GET /_ministack/ses/messages shows v2 SendEmail via sesv2 client."""
+ import urllib.request
+
+ sesv2.send_email(
+ FromEmailAddress="[email protected]",
+ Destination={"ToAddresses": ["[email protected]"]},
+ Content={
+ "Simple": {
+ "Subject": {"Data": "Test v2 subject"},
+ "Body": {"Text": {"Data": "Hello from MiniStack SES v2"}},
+ }
+ },
+ )
+
+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+ url = f"{endpoint}/_ministack/ses/messages"
+ req = urllib.request.Request(url, method="GET")
+ with urllib.request.urlopen(req, timeout=5) as r:
+ data = json.loads(r.read().decode())
+
+ assert "messages" in data
+ v2_emails = [m for m in data["messages"]["000000000000"] if m["Type"] == "v2.SendEmail" and m["Source"] == "[email protected]"]
+ assert len(v2_emails) >= 1, f"Expected v2.SendEmail, got {[m['Type'] for m in data['messages']]}"
+ assert v2_emails[0]["Subject"] == "Test v2 subject"
+
+def test_ses_messages_endpoint_reset(ses):
+ """ Calling POST /_ministack/reset clears stored SES messages. """
+ ses.verify_email_identity(EmailAddress="[email protected]")
+ ses.send_email(
+ Source="[email protected]",
+ Destination={"ToAddresses": ["[email protected]"]},
+ Message={"Subject": {"Data": "Hi"}, "Body": {"Text": {"Data": "body"}}},
+ )
+ import urllib.request
+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+
+ urllib.request.urlopen(
+ urllib.request.Request(f"{endpoint}/_ministack/reset", method="POST")
+ )
+ with urllib.request.urlopen(f"{endpoint}/_ministack/ses/messages") as r:
+ data = json.loads(r.read())
+ assert data == {"messages": {}}
+
+# ---------------------------------------------------------------------------
+# Account filtering test for /_ministack/ses/messages endpoint
+#
+# Verifies that the ?account query parameter properly validates and filters emails.
+# Invalid non-12-digit accounts now return a 400 InvalidAccountID error.
+# ---------------------------------------------------------------------------
+def _client(service, access_key="test"):
+ """Create a boto3 client with a specific access key."""
+ import boto3
+ from botocore.config import Config
+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+ region = "us-east-1"
+ return boto3.client(
+ service,
+ endpoint_url=endpoint,
+ aws_access_key_id=access_key,
+ aws_secret_access_key="test",
+ region_name=region,
+ config=Config(region_name=region, retries={"max_attempts": 0}),
+ )
+
+def test_ses_messages_endpoint_account_filter():
+ """GET /_ministack/ses/messages?account=X filters by account ID."""
+ import urllib.request
+
+ # Clear any existing messages on the running server
+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+ urllib.request.urlopen(urllib.request.Request(f"{endpoint}/_ministack/reset", method="POST"))
+
+ # Account 1 and Account 2
+ ACCOUNT_1 = "011111111111"
+ ACCOUNT_2 = "987654321098"
+ ses_account_1 = _client("ses", access_key=ACCOUNT_1)
+ ses_account_2 = _client("ses", access_key=ACCOUNT_2)
+
+ # Send 2 emails to ACCOUNT_1
+ ses_account_1.verify_email_identity(EmailAddress=f"sender-{ACCOUNT_1}@example.com")
+ ses_account_1.send_email(
+ Source=f"sender-{ACCOUNT_1}@example.com",
+ Destination={"ToAddresses": [f"recipient-{ACCOUNT_1}@example.com"]},
+ Message={"Subject": {"Data": "Test email 1"}, "Body": {"Text": {"Data": "Body of test email 1"}}},
+ )
+ ses_account_1.send_email(
+ Source=f"sender-{ACCOUNT_1}@example.com",
+ Destination={"ToAddresses": [f"recipient-{ACCOUNT_1}@example.com"]},
+ Message={"Subject": {"Data": "Test email 2"}, "Body": {"Text": {"Data": "Body of test email 2"}}},
+ )
+
+ # Send 1 email to ACCOUNT_2
+ ses_account_2.verify_email_identity(EmailAddress=f"sender-{ACCOUNT_2}@example.com")
+ ses_account_2.send_email(
+ Source=f"sender-{ACCOUNT_2}@example.com",
+ Destination={"ToAddresses": [f"recipient-{ACCOUNT_2}@example.com"]},
+ Message={"Subject": {"Data": "Test email 3"}, "Body": {"Text": {"Data": "Body of test email 3"}}},
+ )
+
+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+
+ # Test 1: Without ?account: returns all emails
+ url = f"{endpoint}/_ministack/ses/messages"
+ req = urllib.request.Request(url, method="GET")
+ with urllib.request.urlopen(req, timeout=5) as r:
+ data = json.loads(r.read().decode())
+
+ assert "messages" in data
+ total = sum(len(messages) for messages in data["messages"].values())
+ assert total == 3, f"Expected 3 messages across all accounts, got {total}"
+
+ # Test 2: With invalid non-12-digit account should return error
+ url = f"{endpoint}/_ministack/ses/messages?account=notvalid"
+ req = urllib.request.Request(url, method="GET")
+ with pytest.raises(urllib.error.HTTPError) as exc_info:
+ urllib.request.urlopen(req, timeout=5)
+ assert exc_info.value.code == 400
+ import io
+ error_data = json.loads(io.BytesIO(exc_info.value.read()).read())
+ assert error_data["__type"] == "InvalidAccountID"
+ assert "got: notvalid" in error_data["message"]
+
+ # Test 3: With correct valid custom account (ACCOUNT_1)
+ url = f"{endpoint}/_ministack/ses/messages?account={ACCOUNT_1}"
+ req = urllib.request.Request(url, method="GET")
+ with urllib.request.urlopen(req, timeout=5) as r:
+ data = json.loads(r.read().decode())
+
+ assert "messages" in data
+ messages_for_a1 = data["messages"].get(ACCOUNT_1, [])
+ assert len(messages_for_a1) == 2, f"Expected 2 messages from ACCOUNT_1, got {len(messages_for_a1)}"
+
+ # Test 4: With correct valid custom account (ACCOUNT_2)
+ url = f"{endpoint}/_ministack/ses/messages?account={ACCOUNT_2}"
+ req = urllib.request.Request(url, method="GET")
+ with urllib.request.urlopen(req, timeout=5) as r:
+ data = json.loads(r.read().decode())
+
+ assert "messages" in data
+ messages_for_a2 = data["messages"].get(ACCOUNT_2, [])
+ assert len(messages_for_a2) == 1, f"Expected 1 message from ACCOUNT_2, got {len(messages_for_a2)}"
+
+ # Test 5: Empty messages for correct account with no emails sent
+ url = f"{endpoint}/_ministack/ses/messages?account=123456789012"
+ req = urllib.request.Request(url, method="GET")
+ with urllib.request.urlopen(req, timeout=5) as r:
+ data = json.loads(r.read().decode())
+ # Should return empty list (no emails for this account)
+ assert "messages" in data
+ assert data["messages"].get("123456789012", []) == [], "Expected 0 messages for account with no emails"
+
\ No newline at end of file