homingpigeondev 0.1.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 Soft Sync Solutions LLC
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,72 @@
1
+ Metadata-Version: 2.4
2
+ Name: homingpigeondev
3
+ Version: 0.1.0
4
+ Summary: Homing Pigeon (homingpigeon.dev) sends text-message alerts from your code or your coding agent to one phone: yours. No carrier registration, no app, no browser signup. Free to start.
5
+ License: MIT
6
+ Project-URL: Homepage, https://homingpigeon.dev
7
+ Project-URL: Documentation, https://homingpigeon.dev/llms.txt
8
+ Project-URL: Source, https://github.com/homingpigeondev/homingpigeondev/tree/main/python
9
+ Keywords: sms,text message,alerts,notifications,trading bot,cron,coding agent,mcp
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Topic :: Communications :: Telephony
14
+ Classifier: Topic :: System :: Monitoring
15
+ Requires-Python: >=3.8
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # Homing Pigeon for Python
21
+
22
+ Homing Pigeon (homingpigeon.dev) sends text-message alerts from your code or your coding agent to one phone: yours. No carrier registration, no app, no browser signup. Free to start.
23
+
24
+ ```sh
25
+ pip install homingpigeondev
26
+ ```
27
+
28
+ ```python
29
+ import homingpigeondev
30
+
31
+ homingpigeondev.send("Backup failed on db-1.")
32
+ ```
33
+
34
+ No dependencies. Python 3.8 and up.
35
+
36
+ ## Verify your phone once
37
+
38
+ Texts go only to the US mobile number you verify as your own. There is no "to" field.
39
+
40
+ ```sh
41
+ python -m homingpigeondev verify +15551234567 # texts you a six-digit code
42
+ python -m homingpigeondev verify +15551234567 123456 # saves the key on this machine
43
+ ```
44
+
45
+ Or from Python, with `homingpigeondev.verify(phone)` and then `homingpigeondev.verify(phone, code)`.
46
+
47
+ If you already verified through Claude Code, Codex, Cursor or the npm CLI, skip this: the key is already saved and `send()` finds it.
48
+
49
+ ## Where the key comes from
50
+
51
+ In order: the `api_key` argument, the `HOMINGPIGEON_API_KEY` environment variable, then `~/.config/homingpigeon/config.json`. On a server, set the environment variable and keep the key out of git.
52
+
53
+ ## Sending
54
+
55
+ ```python
56
+ homingpigeondev.send(f"Bought {fill.qty} {fill.symbol} at {fill.price}", idempotency_key=fill.id)
57
+ ```
58
+
59
+ - Messages are up to 480 characters and count as one text.
60
+ - `idempotency_key` means a retry never texts you twice for the same event.
61
+ - Failures raise `homingpigeondev.HomingPigeonError`, with `code` and `next_step`. If an alert must never stop your program, wrap the call in `try`.
62
+ - `homingpigeondev.status()` returns messages left this month and what happened to the last send.
63
+
64
+ You get 50 free texts a month. After that, it is $19 a month for 1,000.
65
+
66
+ ## With a coding agent
67
+
68
+ Tell your agent:
69
+
70
+ > Use Homing Pigeon to text me when this finishes.
71
+
72
+ It asks for your number, you read back the code, and it does the rest. The MCP server, hooks and API are in the [main README](https://github.com/homingpigeondev/homingpigeondev#readme). Terms: https://homingpigeon.dev/terms
@@ -0,0 +1,53 @@
1
+ # Homing Pigeon for Python
2
+
3
+ Homing Pigeon (homingpigeon.dev) sends text-message alerts from your code or your coding agent to one phone: yours. No carrier registration, no app, no browser signup. Free to start.
4
+
5
+ ```sh
6
+ pip install homingpigeondev
7
+ ```
8
+
9
+ ```python
10
+ import homingpigeondev
11
+
12
+ homingpigeondev.send("Backup failed on db-1.")
13
+ ```
14
+
15
+ No dependencies. Python 3.8 and up.
16
+
17
+ ## Verify your phone once
18
+
19
+ Texts go only to the US mobile number you verify as your own. There is no "to" field.
20
+
21
+ ```sh
22
+ python -m homingpigeondev verify +15551234567 # texts you a six-digit code
23
+ python -m homingpigeondev verify +15551234567 123456 # saves the key on this machine
24
+ ```
25
+
26
+ Or from Python, with `homingpigeondev.verify(phone)` and then `homingpigeondev.verify(phone, code)`.
27
+
28
+ If you already verified through Claude Code, Codex, Cursor or the npm CLI, skip this: the key is already saved and `send()` finds it.
29
+
30
+ ## Where the key comes from
31
+
32
+ In order: the `api_key` argument, the `HOMINGPIGEON_API_KEY` environment variable, then `~/.config/homingpigeon/config.json`. On a server, set the environment variable and keep the key out of git.
33
+
34
+ ## Sending
35
+
36
+ ```python
37
+ homingpigeondev.send(f"Bought {fill.qty} {fill.symbol} at {fill.price}", idempotency_key=fill.id)
38
+ ```
39
+
40
+ - Messages are up to 480 characters and count as one text.
41
+ - `idempotency_key` means a retry never texts you twice for the same event.
42
+ - Failures raise `homingpigeondev.HomingPigeonError`, with `code` and `next_step`. If an alert must never stop your program, wrap the call in `try`.
43
+ - `homingpigeondev.status()` returns messages left this month and what happened to the last send.
44
+
45
+ You get 50 free texts a month. After that, it is $19 a month for 1,000.
46
+
47
+ ## With a coding agent
48
+
49
+ Tell your agent:
50
+
51
+ > Use Homing Pigeon to text me when this finishes.
52
+
53
+ It asks for your number, you read back the code, and it does the rest. The MCP server, hooks and API are in the [main README](https://github.com/homingpigeondev/homingpigeondev#readme). Terms: https://homingpigeon.dev/terms
@@ -0,0 +1,28 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "homingpigeondev"
7
+ version = "0.1.0"
8
+ description = "Homing Pigeon (homingpigeon.dev) sends text-message alerts from your code or your coding agent to one phone: yours. No carrier registration, no app, no browser signup. Free to start."
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ requires-python = ">=3.8"
12
+ dependencies = []
13
+ keywords = ["sms", "text message", "alerts", "notifications", "trading bot", "cron", "coding agent", "mcp"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Operating System :: OS Independent",
18
+ "Topic :: Communications :: Telephony",
19
+ "Topic :: System :: Monitoring",
20
+ ]
21
+
22
+ [project.urls]
23
+ Homepage = "https://homingpigeon.dev"
24
+ Documentation = "https://homingpigeon.dev/llms.txt"
25
+ Source = "https://github.com/homingpigeondev/homingpigeondev/tree/main/python"
26
+
27
+ [tool.setuptools.packages.find]
28
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,157 @@
1
+ """Homing Pigeon (homingpigeon.dev) sends text-message alerts from your code or your coding
2
+ agent to one phone: yours. No carrier registration, no app, no browser signup. Free to start.
3
+
4
+ import homingpigeondev
5
+ homingpigeondev.send("Backup failed on db-1.")
6
+
7
+ The key comes from HOMINGPIGEON_API_KEY, or from the file that verify() and the npm CLI save
8
+ (~/.config/homingpigeon/config.json), so a phone verified once works everywhere on the machine.
9
+ """
10
+
11
+ import json
12
+ import os
13
+ import tempfile
14
+ import urllib.error
15
+ import urllib.request
16
+
17
+ __version__ = "0.1.0"
18
+ __all__ = ["send", "status", "verify", "HomingPigeonError"]
19
+
20
+ DEFAULT_API_URL = "https://homingpigeon.dev"
21
+
22
+
23
+ class HomingPigeonError(Exception):
24
+ """An API error. ``code`` is stable, ``next_step`` says what to do about it."""
25
+
26
+ def __init__(self, code, message, next_step=None, status=None):
27
+ super().__init__(message)
28
+ self.code = code
29
+ self.message = message
30
+ self.next_step = next_step
31
+ self.status = status
32
+
33
+ def __str__(self):
34
+ return f"{self.message} {self.next_step}" if self.next_step else self.message
35
+
36
+
37
+ def _config_dir():
38
+ if os.environ.get("HOMINGPIGEON_CONFIG_DIR"):
39
+ return os.environ["HOMINGPIGEON_CONFIG_DIR"]
40
+ base = os.environ.get("XDG_CONFIG_HOME") or os.path.join(os.path.expanduser("~"), ".config")
41
+ return os.path.join(base, "homingpigeon")
42
+
43
+
44
+ def _config_file():
45
+ return os.path.join(_config_dir(), "config.json")
46
+
47
+
48
+ def _read_config():
49
+ try:
50
+ with open(_config_file(), encoding="utf-8") as f:
51
+ data = json.load(f)
52
+ return data if isinstance(data, dict) else {}
53
+ except (OSError, ValueError):
54
+ return {}
55
+
56
+
57
+ def _write_config(patch):
58
+ data = {**_read_config(), **patch}
59
+ os.makedirs(_config_dir(), mode=0o700, exist_ok=True)
60
+ fd, tmp = tempfile.mkstemp(dir=_config_dir(), suffix=".tmp")
61
+ try:
62
+ os.chmod(tmp, 0o600)
63
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
64
+ json.dump(data, f, indent=2)
65
+ f.write("\n")
66
+ os.replace(tmp, _config_file())
67
+ except BaseException:
68
+ try:
69
+ os.unlink(tmp)
70
+ except OSError:
71
+ pass
72
+ raise
73
+
74
+
75
+ def _api_key(api_key=None):
76
+ return api_key or os.environ.get("HOMINGPIGEON_API_KEY") or _read_config().get("apiKey")
77
+
78
+
79
+ def _api_url():
80
+ return (os.environ.get("HOMINGPIGEON_API_URL") or DEFAULT_API_URL).rstrip("/")
81
+
82
+
83
+ def _request(method, route, body=None, api_key=None, auth=False, timeout=20):
84
+ headers = {"User-Agent": f"homingpigeondev/{__version__} (python)", "Accept": "application/json"}
85
+ if auth:
86
+ key = _api_key(api_key)
87
+ if not key:
88
+ raise HomingPigeonError(
89
+ "key_not_verified",
90
+ "No Homing Pigeon key was found on this machine.",
91
+ "Verify your own phone first: homingpigeondev.verify(\"+15551234567\"), "
92
+ "then again with the six-digit code you receive.",
93
+ )
94
+ headers["Authorization"] = f"Bearer {key}"
95
+ data = None
96
+ if body is not None:
97
+ headers["Content-Type"] = "application/json"
98
+ data = json.dumps(body).encode("utf-8")
99
+
100
+ req = urllib.request.Request(_api_url() + route, data=data, headers=headers, method=method)
101
+ try:
102
+ with urllib.request.urlopen(req, timeout=timeout) as res:
103
+ status, raw = res.status, res.read()
104
+ except urllib.error.HTTPError as err:
105
+ status, raw = err.code, err.read()
106
+ except (urllib.error.URLError, OSError) as err:
107
+ raise HomingPigeonError("network_error", "Could not reach Homing Pigeon.", "Check the connection and try again.") from err
108
+
109
+ try:
110
+ payload = json.loads(raw.decode("utf-8"))
111
+ except ValueError:
112
+ payload = None
113
+ if 200 <= status < 300 and isinstance(payload, dict):
114
+ return payload
115
+ error = payload.get("error") if isinstance(payload, dict) else None
116
+ error = error if isinstance(error, dict) else {}
117
+ raise HomingPigeonError(
118
+ error.get("code") or "unexpected_response",
119
+ error.get("message") or f"Homing Pigeon returned HTTP {status}.",
120
+ error.get("next_step") or "Try again in a minute. If it keeps failing, tell the user.",
121
+ status,
122
+ )
123
+
124
+
125
+ def send(message, idempotency_key=None, api_key=None, timeout=20):
126
+ """Text ``message`` to your verified phone. Up to 480 characters.
127
+
128
+ Pass ``idempotency_key`` (such as a fill or job ID) so a retry never texts you twice.
129
+ Raises HomingPigeonError on failure, so wrap it if an alert must never stop your code.
130
+ """
131
+ body = {"message": message}
132
+ if idempotency_key is not None:
133
+ body["idempotency_key"] = str(idempotency_key)
134
+ return _request("POST", "/v1/send", body, api_key=api_key, auth=True, timeout=timeout)
135
+
136
+
137
+ def status(api_key=None, timeout=20):
138
+ """Messages left this month, whether the number is paused, and what happened to the last send."""
139
+ return _request("GET", "/v1/status", api_key=api_key, auth=True, timeout=timeout)
140
+
141
+
142
+ def verify(phone, code=None, project=None, save=True, timeout=20):
143
+ """Verify your own US mobile number.
144
+
145
+ Call it with the phone alone to get a six-digit code by text, then again with the code.
146
+ The second call returns ``api_key`` and, unless ``save=False``, saves it where send() and the
147
+ npm CLI find it. ``project`` is a short name shown in front of each text.
148
+ """
149
+ body = {"phone": phone}
150
+ if code is not None:
151
+ body["code"] = str(code)
152
+ if project:
153
+ body["project"] = project
154
+ result = _request("POST", "/v1/verify", body, timeout=timeout)
155
+ if save and result.get("api_key"):
156
+ _write_config({"apiKey": result["api_key"]})
157
+ return result
@@ -0,0 +1,39 @@
1
+ """python -m homingpigeondev send "Backup failed." | status | verify +15551234567 [code]"""
2
+
3
+ import json
4
+ import sys
5
+
6
+ from . import HomingPigeonError, send, status, verify
7
+
8
+ USAGE = """usage:
9
+ python -m homingpigeondev verify +15551234567 text a six-digit code to your own phone
10
+ python -m homingpigeondev verify +15551234567 123456 finish, and save the key on this machine
11
+ python -m homingpigeondev send "Backup failed." text yourself
12
+ python -m homingpigeondev status messages left and the last send"""
13
+
14
+
15
+ def main(argv=None):
16
+ args = list(sys.argv[1:] if argv is None else argv)
17
+ try:
18
+ if len(args) >= 2 and args[0] == "send":
19
+ send(" ".join(args[1:]))
20
+ print("Sent.")
21
+ elif args == ["status"]:
22
+ print(json.dumps(status(), indent=2))
23
+ elif len(args) in (2, 3) and args[0] == "verify":
24
+ result = verify(*args[1:])
25
+ if result.get("api_key"):
26
+ print(f"Verified {result.get('phone', '')}. The key is saved, so send() works on this machine.")
27
+ else:
28
+ print(f"Code sent to {result.get('phone', 'your phone')}. Run verify again with the number and the code.")
29
+ else:
30
+ print(USAGE, file=sys.stderr)
31
+ return 2
32
+ except HomingPigeonError as err:
33
+ print(f"Error ({err.code}): {err}", file=sys.stderr)
34
+ return 1
35
+ return 0
36
+
37
+
38
+ if __name__ == "__main__":
39
+ sys.exit(main())
@@ -0,0 +1,72 @@
1
+ Metadata-Version: 2.4
2
+ Name: homingpigeondev
3
+ Version: 0.1.0
4
+ Summary: Homing Pigeon (homingpigeon.dev) sends text-message alerts from your code or your coding agent to one phone: yours. No carrier registration, no app, no browser signup. Free to start.
5
+ License: MIT
6
+ Project-URL: Homepage, https://homingpigeon.dev
7
+ Project-URL: Documentation, https://homingpigeon.dev/llms.txt
8
+ Project-URL: Source, https://github.com/homingpigeondev/homingpigeondev/tree/main/python
9
+ Keywords: sms,text message,alerts,notifications,trading bot,cron,coding agent,mcp
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Topic :: Communications :: Telephony
14
+ Classifier: Topic :: System :: Monitoring
15
+ Requires-Python: >=3.8
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # Homing Pigeon for Python
21
+
22
+ Homing Pigeon (homingpigeon.dev) sends text-message alerts from your code or your coding agent to one phone: yours. No carrier registration, no app, no browser signup. Free to start.
23
+
24
+ ```sh
25
+ pip install homingpigeondev
26
+ ```
27
+
28
+ ```python
29
+ import homingpigeondev
30
+
31
+ homingpigeondev.send("Backup failed on db-1.")
32
+ ```
33
+
34
+ No dependencies. Python 3.8 and up.
35
+
36
+ ## Verify your phone once
37
+
38
+ Texts go only to the US mobile number you verify as your own. There is no "to" field.
39
+
40
+ ```sh
41
+ python -m homingpigeondev verify +15551234567 # texts you a six-digit code
42
+ python -m homingpigeondev verify +15551234567 123456 # saves the key on this machine
43
+ ```
44
+
45
+ Or from Python, with `homingpigeondev.verify(phone)` and then `homingpigeondev.verify(phone, code)`.
46
+
47
+ If you already verified through Claude Code, Codex, Cursor or the npm CLI, skip this: the key is already saved and `send()` finds it.
48
+
49
+ ## Where the key comes from
50
+
51
+ In order: the `api_key` argument, the `HOMINGPIGEON_API_KEY` environment variable, then `~/.config/homingpigeon/config.json`. On a server, set the environment variable and keep the key out of git.
52
+
53
+ ## Sending
54
+
55
+ ```python
56
+ homingpigeondev.send(f"Bought {fill.qty} {fill.symbol} at {fill.price}", idempotency_key=fill.id)
57
+ ```
58
+
59
+ - Messages are up to 480 characters and count as one text.
60
+ - `idempotency_key` means a retry never texts you twice for the same event.
61
+ - Failures raise `homingpigeondev.HomingPigeonError`, with `code` and `next_step`. If an alert must never stop your program, wrap the call in `try`.
62
+ - `homingpigeondev.status()` returns messages left this month and what happened to the last send.
63
+
64
+ You get 50 free texts a month. After that, it is $19 a month for 1,000.
65
+
66
+ ## With a coding agent
67
+
68
+ Tell your agent:
69
+
70
+ > Use Homing Pigeon to text me when this finishes.
71
+
72
+ It asks for your number, you read back the code, and it does the rest. The MCP server, hooks and API are in the [main README](https://github.com/homingpigeondev/homingpigeondev#readme). Terms: https://homingpigeon.dev/terms
@@ -0,0 +1,10 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/homingpigeondev/__init__.py
5
+ src/homingpigeondev/__main__.py
6
+ src/homingpigeondev.egg-info/PKG-INFO
7
+ src/homingpigeondev.egg-info/SOURCES.txt
8
+ src/homingpigeondev.egg-info/dependency_links.txt
9
+ src/homingpigeondev.egg-info/top_level.txt
10
+ tests/test_homingpigeondev.py
@@ -0,0 +1 @@
1
+ homingpigeondev
@@ -0,0 +1,187 @@
1
+ """Runs against a local mock of the API. Never sends a real text. python -m unittest discover -s tests"""
2
+
3
+ import contextlib
4
+ import io
5
+ import json
6
+ import os
7
+ import stat
8
+ import sys
9
+ import tempfile
10
+ import threading
11
+ import unittest
12
+ from http.server import BaseHTTPRequestHandler, HTTPServer
13
+
14
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
15
+ import homingpigeondev # noqa: E402
16
+ from homingpigeondev.__main__ import main # noqa: E402
17
+
18
+
19
+ class Mock(BaseHTTPRequestHandler):
20
+ requests = []
21
+ reply = None # (status, body) to force, else the default for the route
22
+
23
+ def _handle(self):
24
+ length = int(self.headers.get("Content-Length") or 0)
25
+ body = json.loads(self.rfile.read(length)) if length else None
26
+ Mock.requests.append({"method": self.command, "path": self.path, "headers": dict(self.headers), "body": body})
27
+ if Mock.reply:
28
+ code, payload = Mock.reply
29
+ elif self.path == "/v1/verify" and body and body.get("code"):
30
+ code, payload = 200, {"verified": True, "api_key": "hp_test_from_verify", "phone": "+1 •••-•••-4567"}
31
+ elif self.path == "/v1/verify":
32
+ code, payload = 202, {"status": "code_sent", "phone": "+1 •••-•••-4567"}
33
+ elif self.path == "/v1/send":
34
+ code, payload = 200, {"sent": True, "messages_remaining": 49}
35
+ else:
36
+ code, payload = 200, {"paused": False, "messages_remaining": 49}
37
+ raw = payload if isinstance(payload, bytes) else json.dumps(payload).encode()
38
+ self.send_response(code)
39
+ self.send_header("Content-Type", "application/json")
40
+ self.send_header("Content-Length", str(len(raw)))
41
+ self.end_headers()
42
+ self.wfile.write(raw)
43
+
44
+ do_GET = do_POST = _handle
45
+
46
+ def log_message(self, *args):
47
+ pass
48
+
49
+
50
+ class Base(unittest.TestCase):
51
+ @classmethod
52
+ def setUpClass(cls):
53
+ cls.server = HTTPServer(("127.0.0.1", 0), Mock)
54
+ threading.Thread(target=cls.server.serve_forever, daemon=True).start()
55
+ cls.url = f"http://127.0.0.1:{cls.server.server_port}"
56
+
57
+ @classmethod
58
+ def tearDownClass(cls):
59
+ cls.server.shutdown()
60
+
61
+ def setUp(self):
62
+ Mock.requests.clear()
63
+ Mock.reply = None
64
+ self.dir = tempfile.TemporaryDirectory()
65
+ self.env = {"HOMINGPIGEON_API_URL": self.url, "HOMINGPIGEON_CONFIG_DIR": self.dir.name}
66
+ self.saved = {k: os.environ.pop(k, None) for k in ("HOMINGPIGEON_API_URL", "HOMINGPIGEON_CONFIG_DIR", "HOMINGPIGEON_API_KEY")}
67
+ os.environ.update(self.env)
68
+
69
+ def tearDown(self):
70
+ for k in ("HOMINGPIGEON_API_URL", "HOMINGPIGEON_CONFIG_DIR", "HOMINGPIGEON_API_KEY"):
71
+ os.environ.pop(k, None)
72
+ if self.saved[k] is not None:
73
+ os.environ[k] = self.saved[k]
74
+ self.dir.cleanup()
75
+
76
+ def config(self):
77
+ with open(os.path.join(self.dir.name, "config.json")) as f:
78
+ return json.load(f)
79
+
80
+
81
+ class SendTest(Base):
82
+ def test_send_uses_env_key_and_sends_only_the_message(self):
83
+ os.environ["HOMINGPIGEON_API_KEY"] = "hp_env"
84
+ result = homingpigeondev.send("Backup failed.", idempotency_key=42)
85
+ self.assertEqual(result["messages_remaining"], 49)
86
+ req = Mock.requests[-1]
87
+ self.assertEqual((req["method"], req["path"]), ("POST", "/v1/send"))
88
+ self.assertEqual(req["headers"]["Authorization"], "Bearer hp_env")
89
+ self.assertRegex(req["headers"]["User-Agent"], r"^homingpigeondev/[\d.]+ \(python\)$")
90
+ self.assertEqual(req["body"], {"message": "Backup failed.", "idempotency_key": "42"})
91
+
92
+ def test_send_reads_the_key_the_npm_cli_saved(self):
93
+ with open(os.path.join(self.dir.name, "config.json"), "w") as f:
94
+ json.dump({"apiKey": "hp_from_npm", "hookMinMinutes": 5}, f)
95
+ homingpigeondev.send("Hi")
96
+ self.assertEqual(Mock.requests[-1]["headers"]["Authorization"], "Bearer hp_from_npm")
97
+
98
+ def test_argument_beats_env(self):
99
+ os.environ["HOMINGPIGEON_API_KEY"] = "hp_env"
100
+ homingpigeondev.send("Hi", api_key="hp_arg")
101
+ self.assertEqual(Mock.requests[-1]["headers"]["Authorization"], "Bearer hp_arg")
102
+
103
+ def test_no_key_raises_before_any_request(self):
104
+ with self.assertRaises(homingpigeondev.HomingPigeonError) as ctx:
105
+ homingpigeondev.send("Hi")
106
+ self.assertEqual(ctx.exception.code, "key_not_verified")
107
+ self.assertIn("verify", ctx.exception.next_step)
108
+ self.assertEqual(Mock.requests, [])
109
+
110
+ def test_api_errors_carry_code_and_next_step(self):
111
+ os.environ["HOMINGPIGEON_API_KEY"] = "hp_env"
112
+ Mock.reply = (402, {"error": {"code": "limit_reached", "message": "No texts left.", "next_step": "Upgrade."}})
113
+ with self.assertRaises(homingpigeondev.HomingPigeonError) as ctx:
114
+ homingpigeondev.send("Hi")
115
+ err = ctx.exception
116
+ self.assertEqual((err.code, err.status, err.next_step), ("limit_reached", 402, "Upgrade."))
117
+ self.assertEqual(str(err), "No texts left. Upgrade.")
118
+
119
+ def test_non_json_error(self):
120
+ os.environ["HOMINGPIGEON_API_KEY"] = "hp_env"
121
+ Mock.reply = (502, b"<html>bad gateway</html>")
122
+ with self.assertRaises(homingpigeondev.HomingPigeonError) as ctx:
123
+ homingpigeondev.send("Hi")
124
+ self.assertEqual((ctx.exception.code, ctx.exception.status), ("unexpected_response", 502))
125
+
126
+ def test_network_error(self):
127
+ os.environ["HOMINGPIGEON_API_KEY"] = "hp_env"
128
+ os.environ["HOMINGPIGEON_API_URL"] = "http://127.0.0.1:9"
129
+ with self.assertRaises(homingpigeondev.HomingPigeonError) as ctx:
130
+ homingpigeondev.send("Hi", timeout=3)
131
+ self.assertEqual(ctx.exception.code, "network_error")
132
+
133
+ def test_status(self):
134
+ os.environ["HOMINGPIGEON_API_KEY"] = "hp_env"
135
+ self.assertEqual(homingpigeondev.status()["messages_remaining"], 49)
136
+ self.assertEqual((Mock.requests[-1]["method"], Mock.requests[-1]["path"]), ("GET", "/v1/status"))
137
+
138
+
139
+ class VerifyTest(Base):
140
+ def test_verify_then_send_with_the_saved_key(self):
141
+ first = homingpigeondev.verify("+15551234567", project="my-bot")
142
+ self.assertEqual(first["status"], "code_sent")
143
+ self.assertEqual(Mock.requests[-1]["body"], {"phone": "+15551234567", "project": "my-bot"})
144
+ self.assertFalse(os.path.exists(os.path.join(self.dir.name, "config.json")))
145
+
146
+ with open(os.path.join(self.dir.name, "config.json"), "w") as f:
147
+ json.dump({"hookMinMinutes": 10}, f)
148
+ second = homingpigeondev.verify("+15551234567", 123456)
149
+ self.assertEqual(second["api_key"], "hp_test_from_verify")
150
+ self.assertEqual(Mock.requests[-1]["body"], {"phone": "+15551234567", "code": "123456"})
151
+ self.assertEqual(self.config(), {"hookMinMinutes": 10, "apiKey": "hp_test_from_verify"})
152
+ mode = stat.S_IMODE(os.stat(os.path.join(self.dir.name, "config.json")).st_mode)
153
+ self.assertEqual(mode, 0o600)
154
+
155
+ homingpigeondev.send("Hi")
156
+ self.assertEqual(Mock.requests[-1]["headers"]["Authorization"], "Bearer hp_test_from_verify")
157
+
158
+ def test_verify_save_false(self):
159
+ homingpigeondev.verify("+15551234567", "123456", save=False)
160
+ self.assertFalse(os.path.exists(os.path.join(self.dir.name, "config.json")))
161
+
162
+
163
+ class CliTest(Base):
164
+ def run_cli(self, *args):
165
+ out, err = io.StringIO(), io.StringIO()
166
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
167
+ code = main(list(args))
168
+ return code, out.getvalue(), err.getvalue()
169
+
170
+ def test_cli_flow(self):
171
+ self.assertEqual(self.run_cli("verify", "+15551234567")[0], 0)
172
+ code, out, _ = self.run_cli("verify", "+15551234567", "123456")
173
+ self.assertEqual(code, 0)
174
+ self.assertIn("Verified", out)
175
+ code, out, _ = self.run_cli("send", "Backup", "finished.")
176
+ self.assertEqual((code, out.strip()), (0, "Sent."))
177
+ self.assertEqual(Mock.requests[-1]["body"], {"message": "Backup finished."})
178
+
179
+ def test_cli_errors_and_usage(self):
180
+ code, _, err = self.run_cli("send", "Hi")
181
+ self.assertEqual(code, 1)
182
+ self.assertIn("key_not_verified", err)
183
+ self.assertEqual(self.run_cli()[0], 2)
184
+
185
+
186
+ if __name__ == "__main__":
187
+ unittest.main()