diff --git a/src/newsdataapi/__init__.py b/src/newsdataapi/__init__.py index f856e98..33ac837 100644 --- a/src/newsdataapi/__init__.py +++ b/src/newsdataapi/__init__.py @@ -17,7 +17,7 @@ ) from .websocket import NewsDataApiWebSocket -__version__ = "0.4.2" +__version__ = "0.4.3" __all__ = [ "NewsDataApiClient", diff --git a/src/newsdataapi/websocket.py b/src/newsdataapi/websocket.py index cacff34..88a2c7b 100644 --- a/src/newsdataapi/websocket.py +++ b/src/newsdataapi/websocket.py @@ -15,6 +15,7 @@ import time from collections.abc import AsyncIterator, Iterator from typing import Any +from urllib.parse import quote, urlencode from . import constants from .client import NewsDataApiClient, _redact_url, _validate_params @@ -30,7 +31,12 @@ if _WEBSOCKET_SUPPORTED: from websockets.asyncio import client as _asyncio_client - from websockets.exceptions import ConnectionClosedError, InvalidMessage, InvalidStatus + from websockets.exceptions import ( + ConnectionClosedError, + InvalidMessage, + InvalidStatus, + InvalidURI, + ) from websockets.sync import client as _sync_client logger = logging.getLogger(__name__) @@ -275,10 +281,11 @@ def websocket_delete(self, registration_id: str) -> dict[str, Any]: # ---- streaming -------------------------------------------------------- def _url(self, registration_id: str) -> str: - return ( - f"{self._base_url}?apikey={self.api_client._apikey}" - f"®istration_id={registration_id}" + query = urlencode( + {"apikey": self.api_client._apikey, "registration_id": registration_id}, + quote_via=quote, ) + return f"{self._base_url}?{query}" def _connect_kwargs(self) -> dict[str, Any]: return { @@ -321,6 +328,11 @@ def stream(self, registration_id: str) -> Iterator[dict[str, Any]]: error_response, delay = response, refused_delay continue yield response + except InvalidURI as exc: + # never retried; str(exc) holds the full URL, API key included + raise NewsdataWebSocketError( + f"invalid WebSocket URL {self._base_url!r}: {exc.msg}" + ) from None except ( InvalidStatus, InvalidMessage, # connection lost during the handshake @@ -372,6 +384,11 @@ async def stream_async(self, registration_id: str) -> AsyncIterator[dict[str, An error_response, delay = response, refused_delay continue yield response + except InvalidURI as exc: + # never retried; str(exc) holds the full URL, API key included + raise NewsdataWebSocketError( + f"invalid WebSocket URL {self._base_url!r}: {exc.msg}" + ) from None except ( InvalidStatus, InvalidMessage, # connection lost during the handshake diff --git a/tests/test_websocket.py b/tests/test_websocket.py index 20ff5dd..23922c5 100644 --- a/tests/test_websocket.py +++ b/tests/test_websocket.py @@ -12,7 +12,12 @@ import pytest from websockets.datastructures import Headers -from websockets.exceptions import ConnectionClosedError, InvalidMessage, InvalidStatus +from websockets.exceptions import ( + ConnectionClosedError, + InvalidMessage, + InvalidStatus, + InvalidURI, +) from websockets.frames import Close from websockets.http11 import Response @@ -52,6 +57,17 @@ def _invalid_status(status: int) -> InvalidStatus: return InvalidStatus(Response(status, "x", Headers(), b"")) +def _invalid_uri_connect(urls: list[str]): + """A ``connect`` that rejects the URL like websockets does (``InvalidURI`` + carries the full URL, API key included), recording each attempt.""" + + def connect(url: str, **_kwargs: object) -> None: + urls.append(url) + raise InvalidURI(url, "scheme isn't ws or wss") + + return connect + + # Terminals the fakes raise from connect() itself (handshake / network # failures) rather than during iteration. _CONNECT_ERRORS = (InvalidStatus, InvalidMessage, OSError, asyncio.TimeoutError) @@ -150,6 +166,30 @@ def test_custom_base_url(monkeypatch: pytest.MonkeyPatch) -> None: assert fake.urls[0] == "wss://staging.example/ws?apikey=KEY®istration_id=REG" +def test_url_encodes_registration_id(monkeypatch: pytest.MonkeyPatch) -> None: + fake = _FakeConnect(([_news("A")], None)) + monkeypatch.setattr(CONNECT, fake) + list(_ws("KEY", reconnect=False).stream("a#b&c d")) + assert fake.urls[0] == ( + "wss://ws.newsdata.io/ws/event?apikey=KEY®istration_id=a%23b%26c%20d" + ) + + +def test_invalid_uri_raises_without_key(monkeypatch: pytest.MonkeyPatch) -> None: + urls: list[str] = [] + monkeypatch.setattr(CONNECT, _invalid_uri_connect(urls)) + ws = _ws("SECRETKEY", base_url="https://staging.example/ws") # reconnect on + with pytest.raises(NewsdataWebSocketError) as info: + list(ws.stream("REG")) + assert type(info.value) is NewsdataWebSocketError + assert len(urls) == 1 # never retried + assert "SECRETKEY" in urls[0] # the rejected URL did carry the key... + assert "SECRETKEY" not in str(info.value) # ...but the raised error does not + assert "https://staging.example/ws" in str(info.value) + assert info.value.__cause__ is None + assert info.value.__suppress_context__ + + def test_connect_params_passed_through(monkeypatch: pytest.MonkeyPatch) -> None: fake = _FakeConnect(([_news("A")], None)) monkeypatch.setattr(CONNECT, fake) @@ -625,6 +665,21 @@ def test_async_reconnects_on_transient_close(monkeypatch: pytest.MonkeyPatch) -> assert fake.calls == 2 +def test_async_invalid_uri_raises_without_key(monkeypatch: pytest.MonkeyPatch) -> None: + urls: list[str] = [] + monkeypatch.setattr(CONNECT_ASYNC, _invalid_uri_connect(urls)) + ws = _ws("SECRETKEY", base_url="https://staging.example/ws") # reconnect on + with pytest.raises(NewsdataWebSocketError) as info: + _atitles(ws, "REG") + assert type(info.value) is NewsdataWebSocketError + assert len(urls) == 1 # never retried + assert "SECRETKEY" in urls[0] + assert "SECRETKEY" not in str(info.value) + assert "https://staging.example/ws" in str(info.value) + assert info.value.__cause__ is None + assert info.value.__suppress_context__ + + def test_async_reconnects_on_network_error(monkeypatch: pytest.MonkeyPatch) -> None: fake = _FakeAsyncConnect( ([], OSError("connection refused")), # network failure -> reconnect