Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/newsdataapi/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
)
from .websocket import NewsDataApiWebSocket

__version__ = "0.4.2"
__version__ = "0.4.3"

__all__ = [
"NewsDataApiClient",
Expand Down
25 changes: 21 additions & 4 deletions src/newsdataapi/websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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__)
Expand Down Expand Up @@ -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"&registration_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 {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
57 changes: 56 additions & 1 deletion tests/test_websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -150,6 +166,30 @@ def test_custom_base_url(monkeypatch: pytest.MonkeyPatch) -> None:
assert fake.urls[0] == "wss://staging.example/ws?apikey=KEY&registration_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&registration_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)
Expand Down Expand Up @@ -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
Expand Down
Loading