mailcatchr 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Flahive Precision Engineering Pty. Ltd.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,43 @@
1
+ Metadata-Version: 2.4
2
+ Name: mailcatchr
3
+ Version: 1.0.0
4
+ Summary: Client for the mailcatchr API: catchall test inboxes for automated email testing.
5
+ Author-email: mailcatchr <support@mailcatchr.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://mailcatchr.com/
8
+ Project-URL: Documentation, https://docs.mailcatchr.com/
9
+ Project-URL: Source, https://github.com/mailcatchr/mailcatchr-sdk
10
+ Project-URL: Issues, https://github.com/mailcatchr/mailcatchr-sdk/issues
11
+ Keywords: email,testing,smtp,inbox,totp,playwright,pytest
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Software Development :: Testing
17
+ Requires-Python: >=3.9
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Dynamic: license-file
21
+
22
+ # mailcatchr (Python)
23
+
24
+ Client for the [mailcatchr](https://mailcatchr.com/) API. Standard library only; Python 3.9+.
25
+
26
+ ```bash
27
+ pip install mailcatchr
28
+ ```
29
+
30
+ ```python
31
+ from mailcatchr import Client
32
+
33
+ mc = Client(api_key=os.environ["MAILCATCHR_API_KEY"])
34
+
35
+ summary = mc.messages.wait_for(mailbox_id, to=address, subject="Reset your password", timeout_seconds=30)
36
+ assert summary is not None, "the reset email did not arrive"
37
+ message = mc.messages.get(mailbox_id, summary.id)
38
+ print(message.text_body)
39
+ ```
40
+
41
+ Errors raise `MailcatchrApiError` with `.status` and `.body`. `wait_for` returns `None` on timeout. See https://docs.mailcatchr.com/reference/sdks/.
42
+
43
+ Tests: `pip install pytest && pytest` from this directory.
@@ -0,0 +1,22 @@
1
+ # mailcatchr (Python)
2
+
3
+ Client for the [mailcatchr](https://mailcatchr.com/) API. Standard library only; Python 3.9+.
4
+
5
+ ```bash
6
+ pip install mailcatchr
7
+ ```
8
+
9
+ ```python
10
+ from mailcatchr import Client
11
+
12
+ mc = Client(api_key=os.environ["MAILCATCHR_API_KEY"])
13
+
14
+ summary = mc.messages.wait_for(mailbox_id, to=address, subject="Reset your password", timeout_seconds=30)
15
+ assert summary is not None, "the reset email did not arrive"
16
+ message = mc.messages.get(mailbox_id, summary.id)
17
+ print(message.text_body)
18
+ ```
19
+
20
+ Errors raise `MailcatchrApiError` with `.status` and `.body`. `wait_for` returns `None` on timeout. See https://docs.mailcatchr.com/reference/sdks/.
21
+
22
+ Tests: `pip install pytest && pytest` from this directory.
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "mailcatchr"
7
+ version = "1.0.0"
8
+ description = "Client for the mailcatchr API: catchall test inboxes for automated email testing."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "mailcatchr", email = "support@mailcatchr.com" }]
13
+ keywords = ["email", "testing", "smtp", "inbox", "totp", "playwright", "pytest"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Software Development :: Testing",
20
+ ]
21
+ dependencies = []
22
+
23
+ [project.urls]
24
+ Homepage = "https://mailcatchr.com/"
25
+ Documentation = "https://docs.mailcatchr.com/"
26
+ Source = "https://github.com/mailcatchr/mailcatchr-sdk"
27
+ Issues = "https://github.com/mailcatchr/mailcatchr-sdk/issues"
28
+
29
+ [tool.setuptools.packages.find]
30
+ where = ["src"]
31
+
32
+ [tool.pytest.ini_options]
33
+ pythonpath = ["src"]
34
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,29 @@
1
+ """Client for the mailcatchr API."""
2
+
3
+ from .client import (
4
+ Client,
5
+ CreateMailboxRequest,
6
+ Mailbox,
7
+ MailcatchrApiError,
8
+ MessageAttachment,
9
+ MessageDetail,
10
+ MessageSummary,
11
+ SendRequest,
12
+ SendResult,
13
+ TotpCode,
14
+ )
15
+
16
+ __all__ = [
17
+ "Client",
18
+ "CreateMailboxRequest",
19
+ "Mailbox",
20
+ "MailcatchrApiError",
21
+ "MessageAttachment",
22
+ "MessageDetail",
23
+ "MessageSummary",
24
+ "SendRequest",
25
+ "SendResult",
26
+ "TotpCode",
27
+ ]
28
+
29
+ __version__ = "1.0.0"
@@ -0,0 +1,342 @@
1
+ """Hand-written client over the mailcatchr v1 public API.
2
+
3
+ Mirrors the TypeScript SDK surface: mailboxes (list, create), messages
4
+ (list, get, wait_for), send, and TOTP codes. Standard library only so it
5
+ drops into any test suite without a dependency to negotiate.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import urllib.error
12
+ import urllib.parse
13
+ import urllib.request
14
+ from dataclasses import dataclass, field
15
+ from typing import Any, Callable, Dict, List, Optional
16
+
17
+ __all__ = [
18
+ "Client",
19
+ "CreateMailboxRequest",
20
+ "Mailbox",
21
+ "MailcatchrApiError",
22
+ "MessageAttachment",
23
+ "MessageDetail",
24
+ "MessageSummary",
25
+ "SendRequest",
26
+ "SendResult",
27
+ "TotpCode",
28
+ ]
29
+
30
+ DEFAULT_BASE_URL = "https://api.mailcatchr.com"
31
+ USER_AGENT = "mailcatchr-sdk-python/1.0.0"
32
+
33
+
34
+ class MailcatchrApiError(Exception):
35
+ """A non-2xx answer from the API. `status` is the HTTP code; `body` is the parsed JSON, raw text, or None."""
36
+
37
+ def __init__(self, status: int, body: Any) -> None:
38
+ super().__init__(f"mailcatchr API {status}")
39
+ self.status = status
40
+ self.body = body
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class Mailbox:
45
+ id: str
46
+ workspace_id: str
47
+ group_id: Optional[str]
48
+ name: str
49
+ subdomain: str
50
+ retention_days: int
51
+ outbound_enabled: bool
52
+ daily_inbound_used: int
53
+ created_at: str
54
+
55
+ @classmethod
56
+ def from_dict(cls, d: Dict[str, Any]) -> "Mailbox":
57
+ return cls(
58
+ id=d["id"],
59
+ workspace_id=d["workspaceId"],
60
+ group_id=d.get("groupId"),
61
+ name=d["name"],
62
+ subdomain=d["subdomain"],
63
+ retention_days=d["retentionDays"],
64
+ outbound_enabled=d["outboundEnabled"],
65
+ daily_inbound_used=d["dailyInboundUsed"],
66
+ created_at=d["createdAt"],
67
+ )
68
+
69
+
70
+ @dataclass(frozen=True)
71
+ class MessageSummary:
72
+ id: str
73
+ from_: str
74
+ to: str
75
+ subject: str
76
+ received_at: str
77
+ size_bytes: int
78
+ attachment_count: int
79
+
80
+ @classmethod
81
+ def from_dict(cls, d: Dict[str, Any]) -> "MessageSummary":
82
+ return cls(
83
+ id=d["id"],
84
+ from_=d["from"],
85
+ to=d["to"],
86
+ subject=d["subject"],
87
+ received_at=d["receivedAt"],
88
+ size_bytes=d["sizeBytes"],
89
+ attachment_count=d["attachmentCount"],
90
+ )
91
+
92
+
93
+ @dataclass(frozen=True)
94
+ class MessageAttachment:
95
+ id: str
96
+ filename: str
97
+ content_type: str
98
+ content_id: Optional[str]
99
+ is_inline: bool
100
+ size_bytes: int
101
+ virus_scan_status: str
102
+
103
+ @classmethod
104
+ def from_dict(cls, d: Dict[str, Any]) -> "MessageAttachment":
105
+ return cls(
106
+ id=d["id"],
107
+ filename=d["filename"],
108
+ content_type=d["contentType"],
109
+ content_id=d.get("contentId"),
110
+ is_inline=d["isInline"],
111
+ size_bytes=d["sizeBytes"],
112
+ virus_scan_status=str(d["virusScanStatus"]),
113
+ )
114
+
115
+
116
+ @dataclass(frozen=True)
117
+ class MessageDetail:
118
+ id: str
119
+ from_: str
120
+ to: str
121
+ cc: Optional[str]
122
+ bcc: Optional[str]
123
+ reply_to: Optional[str]
124
+ subject: str
125
+ text_body: Optional[str]
126
+ html_body: Optional[str]
127
+ headers_json: Optional[str]
128
+ spf_result: Optional[str]
129
+ envelope_from: Optional[str]
130
+ remote_ip: Optional[str]
131
+ received_at: str
132
+ size_bytes: int
133
+ attachments: List[MessageAttachment] = field(default_factory=list)
134
+
135
+ @classmethod
136
+ def from_dict(cls, d: Dict[str, Any]) -> "MessageDetail":
137
+ return cls(
138
+ id=d["id"],
139
+ from_=d["from"],
140
+ to=d["to"],
141
+ cc=d.get("cc"),
142
+ bcc=d.get("bcc"),
143
+ reply_to=d.get("replyTo"),
144
+ subject=d["subject"],
145
+ text_body=d.get("textBody"),
146
+ html_body=d.get("htmlBody"),
147
+ headers_json=d.get("headersJson"),
148
+ spf_result=d.get("spfResult"),
149
+ envelope_from=d.get("envelopeFrom"),
150
+ remote_ip=d.get("remoteIp"),
151
+ received_at=d["receivedAt"],
152
+ size_bytes=d["sizeBytes"],
153
+ attachments=[MessageAttachment.from_dict(a) for a in d.get("attachments") or []],
154
+ )
155
+
156
+
157
+ @dataclass(frozen=True)
158
+ class CreateMailboxRequest:
159
+ name: str
160
+ retention_days: Optional[int] = None
161
+ group_id: Optional[str] = None
162
+
163
+ def to_dict(self) -> Dict[str, Any]:
164
+ return {
165
+ "name": self.name,
166
+ "retentionDays": self.retention_days,
167
+ "groupId": self.group_id,
168
+ }
169
+
170
+
171
+ @dataclass(frozen=True)
172
+ class SendRequest:
173
+ from_: str
174
+ to: str
175
+ subject: str
176
+ text_body: Optional[str] = None
177
+ html_body: Optional[str] = None
178
+ cc: Optional[str] = None
179
+ bcc: Optional[str] = None
180
+ reply_to: Optional[str] = None
181
+
182
+ def to_dict(self) -> Dict[str, Any]:
183
+ return {
184
+ "from": self.from_,
185
+ "to": self.to,
186
+ "cc": self.cc,
187
+ "bcc": self.bcc,
188
+ "replyTo": self.reply_to,
189
+ "subject": self.subject,
190
+ "textBody": self.text_body,
191
+ "htmlBody": self.html_body,
192
+ }
193
+
194
+
195
+ @dataclass(frozen=True)
196
+ class SendResult:
197
+ outbound_send_id: str
198
+ message_id: str
199
+ status: str
200
+
201
+ @classmethod
202
+ def from_dict(cls, d: Dict[str, Any]) -> "SendResult":
203
+ return cls(outbound_send_id=d["outboundSendId"], message_id=d["messageId"], status=d["status"])
204
+
205
+
206
+ @dataclass(frozen=True)
207
+ class TotpCode:
208
+ code: str
209
+ expires_at: str
210
+ expires_in_seconds: int
211
+
212
+ @classmethod
213
+ def from_dict(cls, d: Dict[str, Any]) -> "TotpCode":
214
+ return cls(code=d["code"], expires_at=d["expiresAt"], expires_in_seconds=d["expiresInSeconds"])
215
+
216
+
217
+ Opener = Callable[[urllib.request.Request, float], Any]
218
+
219
+
220
+ def _default_opener(request: urllib.request.Request, timeout: float) -> Any:
221
+ return urllib.request.urlopen(request, timeout=timeout)
222
+
223
+
224
+ def build_query(params: Dict[str, Any]) -> str:
225
+ """Query string for the given params, dropping None and empty values. Returns "" when nothing remains."""
226
+ kept = {k: v for k, v in params.items() if v is not None and v != ""}
227
+ return f"?{urllib.parse.urlencode(kept)}" if kept else ""
228
+
229
+
230
+ def parse_error_body(raw: bytes) -> Any:
231
+ """JSON when it parses, the text otherwise, None when empty."""
232
+ if not raw:
233
+ return None
234
+ text = raw.decode("utf-8", errors="replace")
235
+ try:
236
+ return json.loads(text)
237
+ except ValueError:
238
+ return text
239
+
240
+
241
+ class _Transport:
242
+ def __init__(self, api_key: str, base_url: str, timeout: float, opener: Opener) -> None:
243
+ self._api_key = api_key
244
+ self._base_url = base_url.rstrip("/")
245
+ self._timeout = timeout
246
+ self._opener = opener
247
+
248
+ def request(self, method: str, path: str, body: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None) -> Any:
249
+ data = json.dumps(body).encode("utf-8") if body is not None else None
250
+ request = urllib.request.Request(
251
+ f"{self._base_url}{path}",
252
+ data=data,
253
+ method=method,
254
+ headers={
255
+ "Authorization": f"Bearer {self._api_key}",
256
+ "Content-Type": "application/json",
257
+ "Accept": "application/json",
258
+ "User-Agent": USER_AGENT,
259
+ },
260
+ )
261
+ try:
262
+ with self._opener(request, timeout or self._timeout) as response:
263
+ status = response.status
264
+ raw = response.read()
265
+ except urllib.error.HTTPError as err:
266
+ raise MailcatchrApiError(err.code, parse_error_body(err.read())) from None
267
+
268
+ if status == 204 or not raw:
269
+ return None
270
+ return json.loads(raw.decode("utf-8"))
271
+
272
+
273
+ class MailboxesApi:
274
+ def __init__(self, transport: _Transport) -> None:
275
+ self._t = transport
276
+
277
+ def list(self) -> List[Mailbox]:
278
+ """Every mailbox the key can read."""
279
+ return [Mailbox.from_dict(m) for m in self._t.request("GET", "/v1/mailboxes")]
280
+
281
+ def create(self, workspace_id: str, request: CreateMailboxRequest) -> Mailbox:
282
+ return Mailbox.from_dict(self._t.request("POST", f"/v1/workspaces/{workspace_id}/mailboxes/", request.to_dict()))
283
+
284
+
285
+ class MessagesApi:
286
+ def __init__(self, transport: _Transport) -> None:
287
+ self._t = transport
288
+
289
+ def list(self, mailbox_id: str, limit: Optional[int] = None, before: Optional[str] = None) -> List[MessageSummary]:
290
+ qs = build_query({"limit": limit, "before": before})
291
+ return [MessageSummary.from_dict(m) for m in self._t.request("GET", f"/v1/mailboxes/{mailbox_id}/messages{qs}")]
292
+
293
+ def get(self, mailbox_id: str, message_id: str) -> MessageDetail:
294
+ return MessageDetail.from_dict(self._t.request("GET", f"/v1/mailboxes/{mailbox_id}/messages/{message_id}"))
295
+
296
+ def wait_for(
297
+ self,
298
+ mailbox_id: str,
299
+ *,
300
+ to: Optional[str] = None,
301
+ subject: Optional[str] = None,
302
+ from_: Optional[str] = None,
303
+ since: Optional[str] = None,
304
+ timeout_seconds: int = 30,
305
+ ) -> Optional[MessageSummary]:
306
+ """Long-polls until a message matching every filter arrives. Returns None when the server's timeout fires first."""
307
+ qs = build_query({"subject": subject, "from": from_, "to": to, "since": since, "timeout": timeout_seconds})
308
+ # The server holds the connection for up to timeout_seconds; leave headroom for the round trip.
309
+ body = self._t.request("GET", f"/v1/mailboxes/{mailbox_id}/messages/await{qs}", timeout=timeout_seconds + 15)
310
+ return MessageSummary.from_dict(body) if body is not None else None
311
+
312
+
313
+ class TotpsApi:
314
+ def __init__(self, transport: _Transport) -> None:
315
+ self._t = transport
316
+
317
+ def code(self, totp_id: str) -> TotpCode:
318
+ """The current code for a stored authenticator."""
319
+ return TotpCode.from_dict(self._t.request("GET", f"/v1/totp/{totp_id}/code"))
320
+
321
+
322
+ class Client:
323
+ """Entry point. `opener` replaces urllib's opener in tests."""
324
+
325
+ def __init__(
326
+ self,
327
+ api_key: str,
328
+ base_url: str = DEFAULT_BASE_URL,
329
+ timeout: float = 30.0,
330
+ opener: Optional[Opener] = None,
331
+ ) -> None:
332
+ if not api_key:
333
+ raise ValueError("api_key is required")
334
+ transport = _Transport(api_key, base_url, timeout, opener or _default_opener)
335
+ self._t = transport
336
+ self.mailboxes = MailboxesApi(transport)
337
+ self.messages = MessagesApi(transport)
338
+ self.totps = TotpsApi(transport)
339
+
340
+ def send(self, mailbox_id: str, request: SendRequest) -> SendResult:
341
+ """Queues an outbound email from the mailbox."""
342
+ return SendResult.from_dict(self._t.request("POST", f"/v1/mailboxes/{mailbox_id}/send", request.to_dict()))
@@ -0,0 +1,43 @@
1
+ Metadata-Version: 2.4
2
+ Name: mailcatchr
3
+ Version: 1.0.0
4
+ Summary: Client for the mailcatchr API: catchall test inboxes for automated email testing.
5
+ Author-email: mailcatchr <support@mailcatchr.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://mailcatchr.com/
8
+ Project-URL: Documentation, https://docs.mailcatchr.com/
9
+ Project-URL: Source, https://github.com/mailcatchr/mailcatchr-sdk
10
+ Project-URL: Issues, https://github.com/mailcatchr/mailcatchr-sdk/issues
11
+ Keywords: email,testing,smtp,inbox,totp,playwright,pytest
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Software Development :: Testing
17
+ Requires-Python: >=3.9
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Dynamic: license-file
21
+
22
+ # mailcatchr (Python)
23
+
24
+ Client for the [mailcatchr](https://mailcatchr.com/) API. Standard library only; Python 3.9+.
25
+
26
+ ```bash
27
+ pip install mailcatchr
28
+ ```
29
+
30
+ ```python
31
+ from mailcatchr import Client
32
+
33
+ mc = Client(api_key=os.environ["MAILCATCHR_API_KEY"])
34
+
35
+ summary = mc.messages.wait_for(mailbox_id, to=address, subject="Reset your password", timeout_seconds=30)
36
+ assert summary is not None, "the reset email did not arrive"
37
+ message = mc.messages.get(mailbox_id, summary.id)
38
+ print(message.text_body)
39
+ ```
40
+
41
+ Errors raise `MailcatchrApiError` with `.status` and `.body`. `wait_for` returns `None` on timeout. See https://docs.mailcatchr.com/reference/sdks/.
42
+
43
+ Tests: `pip install pytest && pytest` from this directory.
@@ -0,0 +1,10 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/mailcatchr/__init__.py
5
+ src/mailcatchr/client.py
6
+ src/mailcatchr.egg-info/PKG-INFO
7
+ src/mailcatchr.egg-info/SOURCES.txt
8
+ src/mailcatchr.egg-info/dependency_links.txt
9
+ src/mailcatchr.egg-info/top_level.txt
10
+ tests/test_client.py
@@ -0,0 +1 @@
1
+ mailcatchr
@@ -0,0 +1,163 @@
1
+ import json
2
+ import threading
3
+ from http.server import BaseHTTPRequestHandler, HTTPServer
4
+
5
+ import pytest
6
+
7
+ from mailcatchr import Client, CreateMailboxRequest, MailcatchrApiError, SendRequest
8
+ from mailcatchr.client import build_query, parse_error_body
9
+
10
+
11
+ class Recorder(BaseHTTPRequestHandler):
12
+ """Serves canned responses keyed by method + path and records what it saw."""
13
+
14
+ routes = {}
15
+ seen = []
16
+
17
+ def _handle(self):
18
+ length = int(self.headers.get("Content-Length") or 0)
19
+ body = self.rfile.read(length) if length else b""
20
+ Recorder.seen.append({"method": self.command, "path": self.path, "headers": dict(self.headers), "body": body})
21
+ status, payload = Recorder.routes.get((self.command, self.path.split("?")[0]), (404, b""))
22
+ self.send_response(status)
23
+ if payload:
24
+ self.send_header("Content-Type", "application/json")
25
+ self.end_headers()
26
+ if payload:
27
+ self.wfile.write(payload)
28
+
29
+ do_GET = _handle
30
+ do_POST = _handle
31
+
32
+ def log_message(self, *_):
33
+ pass
34
+
35
+
36
+ @pytest.fixture
37
+ def server():
38
+ Recorder.routes = {}
39
+ Recorder.seen = []
40
+ httpd = HTTPServer(("127.0.0.1", 0), Recorder)
41
+ thread = threading.Thread(target=httpd.serve_forever, daemon=True)
42
+ thread.start()
43
+ yield httpd
44
+ httpd.shutdown()
45
+
46
+
47
+ @pytest.fixture
48
+ def client(server):
49
+ return Client(api_key="mc_live_test", base_url=f"http://127.0.0.1:{server.server_port}/")
50
+
51
+
52
+ def route(method, path, status, payload=None):
53
+ Recorder.routes[(method, path)] = (status, json.dumps(payload).encode() if payload is not None else b"")
54
+
55
+
56
+ def test_requires_an_api_key():
57
+ with pytest.raises(ValueError):
58
+ Client(api_key="")
59
+
60
+
61
+ def test_lists_mailboxes_with_bearer_and_user_agent(client):
62
+ route("GET", "/v1/mailboxes", 200, [
63
+ {"id": "m1", "workspaceId": "w1", "groupId": None, "name": "ci", "subdomain": "k7m2x9qd",
64
+ "retentionDays": 3, "outboundEnabled": False, "dailyInboundUsed": 2, "createdAt": "2026-09-20T00:00:00+00:00"},
65
+ ])
66
+
67
+ boxes = client.mailboxes.list()
68
+
69
+ assert [b.subdomain for b in boxes] == ["k7m2x9qd"]
70
+ headers = Recorder.seen[-1]["headers"]
71
+ assert headers["Authorization"] == "Bearer mc_live_test"
72
+ assert headers["User-Agent"].startswith("mailcatchr-sdk-python/")
73
+
74
+
75
+ def test_creates_a_mailbox_with_camel_case_body(client):
76
+ route("POST", "/v1/workspaces/w1/mailboxes/", 201, {
77
+ "id": "m2", "workspaceId": "w1", "groupId": None, "name": "pr-1842", "subdomain": "pr-1842",
78
+ "retentionDays": 7, "outboundEnabled": False, "dailyInboundUsed": 0, "createdAt": "2026-09-20T00:00:00+00:00"})
79
+
80
+ box = client.mailboxes.create("w1", CreateMailboxRequest(name="pr-1842", retention_days=7))
81
+
82
+ assert box.id == "m2"
83
+ assert json.loads(Recorder.seen[-1]["body"]) == {"name": "pr-1842", "retentionDays": 7, "groupId": None}
84
+
85
+
86
+ def test_wait_for_returns_summary_and_sends_filters(client):
87
+ route("GET", "/v1/mailboxes/m1/messages/await", 200, {
88
+ "id": "x1", "from": "noreply@acme.dev", "to": "alice@k7m2x9qd.mailcatchr.com", "subject": "Reset your password",
89
+ "receivedAt": "2026-09-20T00:00:01+00:00", "sizeBytes": 812, "attachmentCount": 0})
90
+
91
+ summary = client.messages.wait_for("m1", to="alice@k7m2x9qd.mailcatchr.com", subject="Reset", timeout_seconds=5)
92
+
93
+ assert summary is not None and summary.subject == "Reset your password"
94
+ assert summary.from_ == "noreply@acme.dev"
95
+ path = Recorder.seen[-1]["path"]
96
+ assert path.startswith("/v1/mailboxes/m1/messages/await?")
97
+ assert "to=alice%40k7m2x9qd.mailcatchr.com" in path and "subject=Reset" in path and "timeout=5" in path
98
+ assert "from=" not in path and "since=" not in path
99
+
100
+
101
+ def test_wait_for_returns_none_on_204(client):
102
+ route("GET", "/v1/mailboxes/m1/messages/await", 204)
103
+
104
+ assert client.messages.wait_for("m1", to="nobody@k7m2x9qd.mailcatchr.com", timeout_seconds=1) is None
105
+
106
+
107
+ def test_get_message_maps_detail_and_attachments(client):
108
+ route("GET", "/v1/mailboxes/m1/messages/x1", 200, {
109
+ "id": "x1", "from": "a@b", "to": "c@d", "cc": None, "bcc": None, "replyTo": None, "subject": "s",
110
+ "textBody": "hello", "htmlBody": None, "headersJson": "{}", "spfResult": "pass", "envelopeFrom": "a@b",
111
+ "remoteIp": "10.0.0.1", "receivedAt": "2026-09-20T00:00:00+00:00", "sizeBytes": 10,
112
+ "attachments": [{"id": "att", "filename": "f.pdf", "contentType": "application/pdf", "contentId": None,
113
+ "isInline": False, "sizeBytes": 5, "virusScanStatus": "Clean"}]})
114
+
115
+ message = client.messages.get("m1", "x1")
116
+
117
+ assert message.text_body == "hello"
118
+ assert message.attachments[0].filename == "f.pdf"
119
+
120
+
121
+ def test_send_posts_the_expected_body(client):
122
+ route("POST", "/v1/mailboxes/m1/send", 202, {"outboundSendId": "o1", "messageId": "x2", "status": "queued"})
123
+
124
+ result = client.send("m1", SendRequest(from_="noreply@k7m2x9qd.send.mailcatchr.com", to="qa@k7m2x9qd.mailcatchr.com", subject="Hi", text_body="Hello"))
125
+
126
+ assert result.status == "queued"
127
+ sent = json.loads(Recorder.seen[-1]["body"])
128
+ assert sent["from"] == "noreply@k7m2x9qd.send.mailcatchr.com" and sent["textBody"] == "Hello" and sent["htmlBody"] is None
129
+
130
+
131
+ def test_totp_code(client):
132
+ route("GET", "/v1/totp/t1/code", 200, {"code": "482910", "expiresAt": "2026-09-20T00:00:30+00:00", "expiresInSeconds": 18})
133
+
134
+ assert client.totps.code("t1").code == "482910"
135
+
136
+
137
+ def test_errors_carry_status_and_parsed_body(client):
138
+ route("POST", "/v1/workspaces/w1/mailboxes/", 409, {"error": "plan_max_mailboxes_reached", "limit": 1})
139
+
140
+ with pytest.raises(MailcatchrApiError) as err:
141
+ client.mailboxes.create("w1", CreateMailboxRequest(name="second"))
142
+
143
+ assert err.value.status == 409
144
+ assert err.value.body == {"error": "plan_max_mailboxes_reached", "limit": 1}
145
+
146
+
147
+ def test_a_bare_404_is_an_api_error_with_no_body(client):
148
+ with pytest.raises(MailcatchrApiError) as err:
149
+ client.totps.code("nope")
150
+
151
+ assert err.value.status == 404
152
+ assert err.value.body is None
153
+
154
+
155
+ def test_build_query_drops_empty_values():
156
+ assert build_query({"a": "x y", "b": None, "c": "", "d": 0}) == "?a=x+y&d=0"
157
+ assert build_query({"a": None}) == ""
158
+
159
+
160
+ def test_parse_error_body():
161
+ assert parse_error_body(b"") is None
162
+ assert parse_error_body(b'{"error":"x"}') == {"error": "x"}
163
+ assert parse_error_body(b"Bad gateway") == "Bad gateway"