From 4753a98abcfc5401b6daedcd5b8fb6fefef22dc8 Mon Sep 17 00:00:00 2001 From: karanthashika Date: Mon, 16 Nov 2026 23:09:26 +0530 Subject: [PATCH] Fix NATS connection error showing port None when URL has no port --- priompt_sdk/client.py | 2 +- tests/test_client.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/priompt_sdk/client.py b/priompt_sdk/client.py index 086c58f..becd014 100644 --- a/priompt_sdk/client.py +++ b/priompt_sdk/client.py @@ -231,7 +231,7 @@ async def handler(msg): e = failed[0] u = urlparse(self._nats_url) # don't echo the token raise ConnectionError( - f"subscribe: cannot connect to NATS at {u.hostname}:{u.port}: " + f"subscribe: cannot connect to NATS at {u.hostname}:{u.port or 4222}: " f"{str(e) or type(e).__name__}" ) from e return t diff --git a/tests/test_client.py b/tests/test_client.py index 4d0c799..40e2c3f 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -337,3 +337,31 @@ def test_token_precedence(monkeypatch): monkeypatch.delenv("PRIOMPT_TOKEN") assert _bearer(PromptClient(url="priompt://urltok@localhost:1")) == "Bearer urltok" assert _bearer(PromptClient("localhost:1")) is None + + +def test_subscribe_nats_default_port(monkeypatch): + """NATS connection errors show port 4222 when URL has no port, and explicit port otherwise.""" + import sys + import types + + async def connect_no_port(url, error_cb=None, **kw): + err = Exception("TimeoutError") + if error_cb: + await error_cb(err) + raise err + + monkeypatch.setitem(sys.modules, "nats", types.SimpleNamespace(connect=connect_no_port)) + + # Case 1: No port in URL -> should default to 4222 + c1 = PromptClient("localhost:1", nats_url="nats://secret-token@127.0.0.1") + with pytest.raises(ConnectionError) as exc1: + c1.subscribe("priompt://x", lambda *_: None) + assert "127.0.0.1:4222" in str(exc1.value) + assert "secret-token" not in str(exc1.value) + + # Case 2: Explicit port in URL -> should preserve explicit port + c2 = PromptClient("localhost:1", nats_url="nats://secret-token@127.0.0.1:5222") + with pytest.raises(ConnectionError) as exc2: + c2.subscribe("priompt://x", lambda *_: None) + assert "127.0.0.1:5222" in str(exc2.value) + assert "secret-token" not in str(exc2.value) \ No newline at end of file