diff --git a/.github/workflows/starter.yml b/.github/workflows/starter.yml index 6590c66..336727b 100644 --- a/.github/workflows/starter.yml +++ b/.github/workflows/starter.yml @@ -4,6 +4,8 @@ on: paths: - 'examples/odds_workspace.py' - 'examples/odds-migration/**' + - 'examples/websocket_stream.py' + - 'examples/websocket-replay/**' - 'examples/support-report/**' - 'examples/test_odds_workspace.py' - 'parlay_api/**' @@ -15,6 +17,8 @@ on: paths: - 'examples/odds_workspace.py' - 'examples/odds-migration/**' + - 'examples/websocket_stream.py' + - 'examples/websocket-replay/**' - 'examples/support-report/**' - 'parlay_api/**' - 'pyproject.toml' @@ -32,7 +36,7 @@ jobs: - uses: actions/setup-python@v5 with: python-version: ${{ matrix.python }} - - run: python -m pip install . pytest + - run: python -m pip install ".[ws]" pytest - name: Exercise the installed CLI outside the checkout working-directory: ${{ runner.temp }} run: | @@ -40,3 +44,5 @@ jobs: python -m pytest -q --import-mode=importlib "$GITHUB_WORKSPACE/tests/test_odds_coverage.py" "$GITHUB_WORKSPACE/tests/test_first_response.py" "$GITHUB_WORKSPACE/tests/test_migration_example.py" - name: Exercise the offline support report run: python -B -m unittest discover -s examples/support-report -p test_support_repro.py + - name: Replay fictional frames and exercise a loopback WebSocket + run: python -B tests/test_websocket_examples.py diff --git a/README.md b/README.md index 33a0d08..46069e8 100644 --- a/README.md +++ b/README.md @@ -189,7 +189,10 @@ runs without keys or API requests. After a successful SDK request, `client.last_quota` contains the returned usage headers. Header fields may be `None` when the service does not provide them. -Optional WebSocket examples require `python -m pip install 'parlay-api[ws]'`. +Practice a disconnect, duplicate update and reconnect using the [offline WebSocket replay](examples/websocket-replay). +It runs with Python alone and includes a fictional price trace. + +The optional live WebSocket example requires `python -m pip install 'parlay-api[ws]'`. WebSocket access is Business tier and up; see the current docs before connecting. ### Request delayed Pinnacle game lines diff --git a/examples/websocket-replay/README.md b/examples/websocket-replay/README.md new file mode 100644 index 0000000..a99dde8 --- /dev/null +++ b/examples/websocket-replay/README.md @@ -0,0 +1,31 @@ +# What happens to a price when a WebSocket reconnects? + +Follow one fictional NBA moneyline through two connections. You can run the exercise with Python 3.9 or later. It reads the included JSON trace and makes zero network requests. + +```sh +python3 examples/websocket-replay/replay.py +``` + +From the downloadable example bundle, run `python3 websocket-replay/replay.py` instead. + +| Trace step | What to look for | +| --- | --- | +| 2–4 | The partial initial state contains home −115 and away +105. A duplicate repeats the same price and row clock. The next update changes both. | +| 5 | A heartbeat leaves the row clock and prices untouched. | +| 6–8 | Disconnecting clears the displayed observation. A delayed callback from connection 1 cannot populate connection 2. | +| 9–10 | Connection 2 starts with an empty recent-row snapshot. Its first matching update supplies a price observed on this connection. | +| 11–12 | Cancel clears the observation. A later callback from that connection is ignored. | + +The outer `action` and `connection` fields belong to the local exercise. Inside `frame` are examples of odds-stream messages. The client matches the event, bookmaker, market, period and teams before using a two-sided price. A row's `last_update` is an epoch-millisecond clock. Print it separately from the time your client received the frame. + +An empty partial snapshot only describes the rows returned. A reconnect can miss intermediate changes. A later receipt can carry an older observation. For other markets, use the fields that identify that selection, including the player, side, period and line when applicable. The reducer covers the illustrated moneyline shapes. + +## Trying one live connection + +The sibling `websocket_stream.py` example opens one connection, sends the credential in the handshake header and stops after the chosen frame count. Install `parlay-api[ws]` and set `PARLAY_API_KEY` privately before using it. Use an eligible Business-or-higher account with an available streaming allowance. Each invocation makes a new connection attempt. + +```sh +python3 examples/websocket_stream.py basketball_nba --frames 3 +``` + +For a free browser exercise, try the [streaming guide and fictional event](https://parlay-api.com/live-odds-api?utm_source=github&utm_medium=developer_example&utm_campaign=sports_data_preview&utm_content=ws_replay). diff --git a/examples/websocket-replay/replay.py b/examples/websocket-replay/replay.py new file mode 100644 index 0000000..06bdc76 --- /dev/null +++ b/examples/websocket-replay/replay.py @@ -0,0 +1,96 @@ +"""Replay a fictional two-connection trace for one moneyline, entirely offline.""" +import json +from pathlib import Path + + +SPORT = "basketball_nba" +SELECTION = { + "event_id": "fictional-north-south", + "bookmaker": "example_book", + "kind": "game", + "market_key": "h2h", + "period_key": None, + "home_team": "North Owls", + "away_team": "South Foxes", +} + + +class SelectedMoneyline: + """A local observation on one connection. The connection number is client state.""" + + def __init__(self): + self.latest_connection = 0 + self.active_connection = None + self.quote = None + self.row_clock = 0 + + def observe(self, entry): + connection = entry["connection"] + action = entry["action"] + if action == "open" and connection > self.latest_connection: + self.latest_connection = self.active_connection = connection + self.quote = None + self.row_clock = 0 + return "Waiting for a matching observation" + if connection != self.active_connection or action == "open": + return "Ignored callback from inactive connection" + if action in ("disconnect", "cancel"): + self.active_connection = None + self.quote = None + return "Connection closed" + if action != "frame": + raise ValueError("Unrecognized local action") + frame = entry["frame"] + if frame.get("type") == "heartbeat": + return "Heartbeat" + if frame.get("type") not in ("initial_state", "odds_update"): + return "Ignored other frame" + if frame.get("sport_key") != SPORT or not isinstance(frame.get("data"), list): + return "Ignored out-of-scope or malformed frame" + changes = [] + for row in frame["data"]: + if not isinstance(row, dict) or row.get("sport_key", SPORT) != SPORT: + continue + if any(row.get(field) != value for field, value in SELECTION.items()): + continue + updated = row.get("last_update") + if type(updated) is not int or updated <= 0: + continue + if updated < self.row_clock: + changes.append("Ignored an older observation") + continue + if row.get("available") is False or row.get("action") == "remove": + self.row_clock = updated + self.quote = None + changes.append("Selection unavailable") + continue + home, away = row.get("home_ml"), row.get("away_ml") + if any(type(price) is not int or abs(price) < 100 for price in (home, away)): + continue + new_quote = (home, away, updated) + if new_quote == self.quote: + changes.append("Ignored duplicate") + elif updated == self.row_clock: + self.quote = None + changes.append("No unambiguous price at this timestamp") + else: + self.row_clock = updated + self.quote = new_quote + changes.append("Observed price") + return ", ".join(changes) or "No matching price observed in this frame" + + +def main(): + session = json.loads(Path(__file__).with_name("session.json").read_text()) + selection = SelectedMoneyline() + for index, entry in enumerate(session, 1): + result = selection.observe(entry) + shown = "no observation on this connection" + if selection.quote is not None: + home, away, updated = selection.quote + shown = f"home {home:+d}, away {away:+d}, row clock {updated} ms" + print(f"{index:2d}. {result} | {shown}") + + +if __name__ == "__main__": + main() diff --git a/examples/websocket-replay/session.json b/examples/websocket-replay/session.json new file mode 100644 index 0000000..4c32ed8 --- /dev/null +++ b/examples/websocket-replay/session.json @@ -0,0 +1,177 @@ +[ + { + "action": "open", + "connection": 1 + }, + { + "action": "frame", + "connection": 1, + "frame": { + "type": "initial_state", + "sport_key": "basketball_nba", + "snapshot_scope": "recent_rows", + "snapshot_complete": false, + "data": [ + { + "sport_key": "basketball_nba", + "event_id": "fictional-north-south", + "home_team": "North Owls", + "away_team": "South Foxes", + "bookmaker": "example_book", + "kind": "game", + "market_key": "h2h", + "period_key": null, + "home_ml": -115, + "away_ml": 105, + "last_update": 1806600000000 + } + ] + } + }, + { + "action": "frame", + "connection": 1, + "frame": { + "type": "odds_update", + "sport_key": "basketball_nba", + "data": [ + { + "sport_key": "basketball_nba", + "event_id": "fictional-north-south", + "home_team": "North Owls", + "away_team": "South Foxes", + "bookmaker": "example_book", + "kind": "game", + "market_key": "h2h", + "period_key": null, + "home_ml": -115, + "away_ml": 105, + "last_update": 1806600000000 + } + ] + } + }, + { + "action": "frame", + "connection": 1, + "frame": { + "type": "odds_update", + "sport_key": "basketball_nba", + "data": [ + { + "sport_key": "basketball_nba", + "event_id": "fictional-north-south", + "home_team": "North Owls", + "away_team": "South Foxes", + "bookmaker": "example_book", + "kind": "game", + "market_key": "h2h", + "period_key": null, + "home_ml": -120, + "away_ml": 110, + "last_update": 1806600006000 + } + ] + } + }, + { + "action": "frame", + "connection": 1, + "frame": { + "type": "heartbeat", + "timestamp": 1806600010 + } + }, + { + "action": "disconnect", + "connection": 1 + }, + { + "action": "open", + "connection": 2 + }, + { + "action": "frame", + "connection": 1, + "frame": { + "type": "odds_update", + "sport_key": "basketball_nba", + "data": [ + { + "sport_key": "basketball_nba", + "event_id": "fictional-north-south", + "home_team": "North Owls", + "away_team": "South Foxes", + "bookmaker": "example_book", + "kind": "game", + "market_key": "h2h", + "period_key": null, + "home_ml": -115, + "away_ml": 105, + "last_update": 1806600000000 + } + ] + } + }, + { + "action": "frame", + "connection": 2, + "frame": { + "type": "initial_state", + "sport_key": "basketball_nba", + "snapshot_scope": "recent_rows", + "snapshot_complete": false, + "data": [] + } + }, + { + "action": "frame", + "connection": 2, + "frame": { + "type": "odds_update", + "sport_key": "basketball_nba", + "data": [ + { + "sport_key": "basketball_nba", + "event_id": "fictional-north-south", + "home_team": "North Owls", + "away_team": "South Foxes", + "bookmaker": "example_book", + "kind": "game", + "market_key": "h2h", + "period_key": null, + "home_ml": -115, + "away_ml": 105, + "last_update": 1806600012000 + } + ] + } + }, + { + "action": "cancel", + "connection": 2 + }, + { + "action": "frame", + "connection": 2, + "frame": { + "type": "odds_update", + "sport_key": "basketball_nba", + "data": [ + { + "sport_key": "basketball_nba", + "event_id": "fictional-north-south", + "home_team": "North Owls", + "away_team": "South Foxes", + "bookmaker": "example_book", + "kind": "game", + "market_key": "h2h", + "period_key": null, + "home_ml": -115, + "away_ml": 105, + "last_update": 1806600000000 + } + ] + } + } +] diff --git a/examples/websocket_stream.py b/examples/websocket_stream.py index 48c6bed..ef56204 100644 --- a/examples/websocket_stream.py +++ b/examples/websocket_stream.py @@ -1,92 +1,87 @@ -"""Subscribe to live odds updates over WebSocket. +"""Read a bounded sample from the ParlayAPI odds WebSocket. -Streams every odds change for a given sport in real time. Useful for -+EV scanners that need to react faster than 60-second REST polling. - -Requires Business tier or above. - -Usage: - pip install websockets - export PARLAY_API_KEY=... - python websocket_stream.py basketball_nba +The live example opens one Business-or-higher odds connection using your own +account. Set PARLAY_API_KEY privately. For a keyless exercise, first run +python examples/websocket-replay/replay.py from the repository root. """ from __future__ import annotations import argparse -import asyncio import json import os +import re import sys -from datetime import datetime - -try: - import websockets -except ImportError: - print("install websockets: pip install websockets", file=sys.stderr) - raise - -sys.path.insert(0, "..") -from parlay_api import ParlayAPI - - -async def stream(api: ParlayAPI, sport: str, event_filter: str | None = None) -> None: - url = api.websocket_url(sport) - print(f"connecting to {url}") - async with websockets.connect(url, ping_interval=20) as ws: - if event_filter: - await ws.send(json.dumps({ - "type": "subscribe", - "event_id": event_filter, - })) - print(f"subscribed to event_id={event_filter}") - - seen_initial = False - while True: - raw = await ws.recv() - try: - msg = json.loads(raw) - except json.JSONDecodeError: - print(f"non-json frame: {raw[:80]}") - continue +from urllib.parse import urlencode - now = datetime.utcnow().strftime("%H:%M:%S") - mtype = msg.get("type", "?") - if mtype == "odds_update" and not seen_initial: - seen_initial = True - count = msg.get("count") or len(msg.get("data") or []) - print(f"[{now}] initial snapshot: {count} props") - continue - if mtype == "odds_update": - data = msg.get("data") or [] - # Show a couple of representative changes - for r in data[:3]: - print(f"[{now}] {r.get('bookmaker','?'):12} " - f"{r.get('player_name','?')[:24]:24} " - f"{r.get('market_key','?'):20} " - f"line={r.get('line','?')} " - f"O{r.get('over_price','?')} U{r.get('under_price','?')}") - else: - print(f"[{now}] {mtype}: {str(msg)[:140]}") - -def main() -> int: +def frame_summary(raw): + """Describe the received frame without printing URLs, keys or row contents.""" + try: + frame = json.loads(raw) + except (ValueError, TypeError): + return "Unreadable frame." + if not isinstance(frame, dict): + return "Unexpected frame shape." + kind = frame.get("type") + if kind in ("initial_state", "odds_update"): + rows = frame.get("data") + if not isinstance(rows, list): + return "Unexpected row collection." + if kind == "initial_state": + complete = frame.get("snapshot_complete") + scope = "completeness unspecified" + if complete is True: + scope = "declared complete" + elif complete is False: + scope = "declared partial" + return f"Initial state: {len(rows)} returned rows ({scope} for this request)." + return f"Odds update: {len(rows)} returned rows." + if kind == "heartbeat": + return "Heartbeat." + return "Other stream frame." + + +def stream(connect, sport, event_filter, key, frame_limit): + url = "wss://parlay-api.com/ws/odds/" + sport + if event_filter: + url += "?" + urlencode({"event_id": event_filter}) + print("Opening one odds connection.") + with connect(url, additional_headers={"X-API-Key": key}, + open_timeout=10, close_timeout=5) as socket: + for _ in range(frame_limit): + print(frame_summary(socket.recv(timeout=45))) + + +def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("sport") - parser.add_argument("--event", help="filter to one event_id") - parser.add_argument("--api-key", default=os.environ.get("PARLAY_API_KEY")) - args = parser.parse_args() - - if not args.api_key: - print("error: set PARLAY_API_KEY env var or pass --api-key", file=sys.stderr) + parser.add_argument("sport", help="catalogue sport key, such as basketball_nba") + parser.add_argument("--event", help="request the stream for one event ID") + parser.add_argument("--frames", type=int, default=3, help="stop after 1–50 frames (default 3)") + parser.add_argument("--api-key", help=argparse.SUPPRESS) + args = parser.parse_args(argv) + if not re.fullmatch(r"[a-z0-9_]{1,64}", args.sport): + parser.error("use one catalogue sport key") + if not 1 <= args.frames <= 50: + parser.error("--frames must be between 1 and 50") + key = args.api_key if args.api_key is not None else os.environ.get("PARLAY_API_KEY", "") + if not key or not key.isascii() or not all(33 <= ord(c) <= 126 for c in key): + print("Set a valid PARLAY_API_KEY privately before opening a connection.", file=sys.stderr) + return 2 + try: + from websockets.exceptions import WebSocketException + from websockets.sync.client import connect + except ImportError: + print("This live example requires websockets 11 or newer.", file=sys.stderr) return 2 - - api = ParlayAPI(api_key=args.api_key) try: - asyncio.run(stream(api, args.sport, args.event)) + stream(connect, args.sport, args.event, key, args.frames) + except (OSError, WebSocketException): + print("The connection ended before the sample finished. No reconnect was attempted.", file=sys.stderr) + return 1 except KeyboardInterrupt: - print("\nstopped") + print("Stopped.") return 0 if __name__ == "__main__": - sys.exit(main()) + raise SystemExit(main()) diff --git a/parlay_api/__init__.py b/parlay_api/__init__.py index 145f42c..815408d 100644 --- a/parlay_api/__init__.py +++ b/parlay_api/__init__.py @@ -636,25 +636,16 @@ def usage(self) -> dict: # ------------------------------------------------------------------ def websocket_url(self, sport_key: str) -> str: - """Build the WebSocket URL for a sport. + """Build a private WebSocket URL with the account key in its query. - Connect with any standard WS client. On connect, the server - sends ``{"type":"odds_update", ...}`` with the full current - snapshot, then push frames as prices change. Optional - subscribe filter: + Keep the returned string out of logs, issue reports and shared output. + Header-capable clients can send X-API-Key on the handshake instead. + See examples/websocket_stream.py for a bounded header-based example. - .. code-block:: python - - import asyncio, json, websockets - async def run(): - url = client.websocket_url("baseball_mlb") - async with websockets.connect(url) as ws: - while True: - msg = json.loads(await ws.recv()) - print(msg.get("type"), len(msg.get("data") or [])) - asyncio.run(run()) - - WebSocket access requires Business tier or above. + The initial_state frame describes the initial rows for the chosen + scope. Check the supplied scope and completeness fields before + interpreting an absence. Later odds_update frames carry changes. + Odds WebSocket access requires Business tier or above. """ scheme = "wss" if self.base_url.startswith("https") else "ws" host = self.base_url.split("://", 1)[1] diff --git a/tests/test_websocket_examples.py b/tests/test_websocket_examples.py new file mode 100644 index 0000000..72a3a5d --- /dev/null +++ b/tests/test_websocket_examples.py @@ -0,0 +1,194 @@ +"""Offline regressions for the live sample and the fictional reconnect trace.""" +import contextlib +import copy +import importlib.util +import io +import json +import os +import threading +import unittest +from pathlib import Path +from unittest.mock import patch +from urllib.parse import urlsplit + +try: + from websockets.exceptions import ConnectionClosedOK + from websockets.sync.client import connect + from websockets.sync.server import serve +except ImportError: + connect = None + + +EXAMPLES = Path(__file__).resolve().parents[1] / "examples" +LAB = EXAMPLES / "websocket-replay" + + +def load_example(name, path): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +live = load_example("websocket_stream", EXAMPLES / "websocket_stream.py") +replay = load_example("replay", LAB / "replay.py") +TRACE = json.loads((LAB / "session.json").read_text()) +ROW = TRACE[1]["frame"]["data"][0] +FIRST = ROW["last_update"] + + +class ReplayTests(unittest.TestCase): + def setUp(self): + self.selection = replay.SelectedMoneyline() + self.selection.observe(TRACE[0]) + + def rows(self, *rows): + return self.selection.observe({ + "connection": 1, "action": "frame", + "frame": {"type": "odds_update", "sport_key": replay.SPORT, "data": list(rows)}, + }) + + def test_each_fictional_step(self): + s = replay.SelectedMoneyline() + first = (-115, 105, FIRST) + second = (-120, 110, FIRST + 6000) + expected = [ + ("Waiting for a matching observation", None), ("Observed price", first), + ("Ignored duplicate", first), ("Observed price", second), + ("Heartbeat", second), ("Connection closed", None), + ("Waiting for a matching observation", None), + ("Ignored callback from inactive connection", None), + ("No matching price observed in this frame", None), + ("Observed price", (-115, 105, FIRST + 12000)), + ("Connection closed", None), ("Ignored callback from inactive connection", None), + ] + self.assertEqual(len(TRACE), len(expected)) + for index, (entry, pair) in enumerate(zip(TRACE, expected), 1): + with self.subTest(step=index): + result = s.observe(entry) + self.assertEqual((result, s.quote), pair) + + def test_unrelated_selections_and_bad_prices(self): + for changes in [ + {"bookmaker": "elsewhere"}, {"market_key": "spreads"}, {"period_key": "Q1"}, + {"sport_key": "icehockey_nhl"}, {"event_id": "other"}, {"kind": "prop"}, + {"home_team": "another"}, {"away_team": "other"}, {"home_ml": True}, + {"away_ml": None}, {"home_ml": 0}, {"last_update": None}, + ]: + with self.subTest(changes=changes): + self.rows(dict(ROW, **changes)) + self.assertIsNone(self.selection.quote) + + def test_empty_partial_does_not_withdraw_an_observation(self): + self.rows(ROW) + frame = copy.deepcopy(TRACE[8]["frame"]) + self.selection.observe({"connection": 1, "action": "frame", "frame": frame}) + self.assertEqual(self.selection.quote, (-115, 105, FIRST)) + + def test_older_price_does_not_overwrite_newer_or_revive_removal(self): + self.rows(ROW, dict(ROW, home_ml=-125, last_update=FIRST + 5), ROW) + self.assertEqual(self.selection.quote, (-125, 105, FIRST + 5)) + self.rows(dict(ROW, available=False, action="remove", last_update=FIRST + 10), ROW) + self.assertIsNone(self.selection.quote) + + def test_price_can_return_after_a_change(self): + self.rows(ROW, dict(ROW, home_ml=-125, last_update=FIRST + 5), + dict(ROW, last_update=FIRST + 10)) + self.assertEqual(self.selection.quote, (-115, 105, FIRST + 10)) + + def test_conflicting_row_clock_cannot_pick_a_winner(self): + self.rows(ROW, dict(ROW, home_ml=-135)) + self.assertIsNone(self.selection.quote) + self.rows(dict(ROW, last_update=FIRST + 1)) + self.assertEqual(self.selection.quote, (-115, 105, FIRST + 1)) + + def test_reopen_callback_does_not_reactivate_closed_connection(self): + self.selection.observe(TRACE[5]) + self.selection.observe(TRACE[0]) + self.selection.observe(TRACE[1]) + self.assertIsNone(self.selection.active_connection) + self.assertIsNone(self.selection.quote) + + +class LiveSampleTests(unittest.TestCase): + def test_distinct_frame_kinds_and_private_malformed_data(self): + cases = [ + ('{"type":"odds_update","data":[{}]}', "Odds update: 1 returned rows."), + ('{"type":"initial_state","data":[],"snapshot_complete":false}', "declared partial"), + ('{"type":"initial_state","data":[],"snapshot_complete":true}', "declared complete"), + ('{"type":"initial_state","data":[],"snapshot_complete":1}', "completeness unspecified"), + ('{"type":"heartbeat","note":"dummy-secret"}', "Heartbeat."), + ("dummy-secret", "Unreadable frame."), ("[]", "Unexpected frame shape."), + ('{"type":"odds_update","data":{}}', "Unexpected row collection."), + ('{"type":["dummy-secret"]}', "Other stream frame."), + ] + for raw, expected in cases: + with self.subTest(raw=raw): + result = live.frame_summary(raw) + self.assertIn(expected, result) + self.assertNotIn("dummy-secret", result) + + @unittest.skipIf(connect is None, "install the ws extra for transport tests") + def test_key_and_frame_limit_checked_before_connect(self): + with patch("websockets.sync.client.connect") as open_socket, contextlib.redirect_stderr(io.StringIO()): + for key in ("", " ", "dummy\nkey"): + with patch.dict(os.environ, {"PARLAY_API_KEY": key}): + self.assertEqual(live.main(["basketball_nba"]), 2) + for extra in (["--frames", "0"], ["--frames", "51"]): + with self.assertRaises(SystemExit): + live.main(["basketball_nba"] + extra) + open_socket.assert_not_called() + + @unittest.skipIf(connect is None, "install the ws extra for transport tests") + def test_connection_failure_is_redacted_and_single_attempt(self): + output = io.StringIO() + with patch.dict(os.environ, {"PARLAY_API_KEY": "private-test"}), \ + patch("websockets.sync.client.connect", side_effect=TimeoutError("private-test")) as dial, \ + contextlib.redirect_stdout(output), contextlib.redirect_stderr(output): + self.assertEqual(live.main(["basketball_nba"]), 1) + dial.assert_called_once() + self.assertNotIn("private-test", output.getvalue()) + + @unittest.skipIf(connect is None, "install the ws extra for transport tests") + def test_real_loopback_handshake_filter_and_graceful_close(self): + observed = [] + closed = threading.Event() + + def handler(ws): + observed.append((ws.request.path, ws.request.headers["X-API-Key"])) + for entry in TRACE[1:5]: + ws.send(json.dumps(entry["frame"])) + try: + ws.recv(timeout=5) + except ConnectionClosedOK: + closed.set() + + output = io.StringIO() + with serve(handler, "127.0.0.1", 0) as server: + worker = threading.Thread(target=server.serve_forever) + worker.start() + try: + def local_connect(url, **options): + dest = urlsplit(url) + self.assertEqual((dest.scheme, dest.netloc), ("wss", "parlay-api.com")) + self.assertNotIn("private-test", url) + port = server.socket.getsockname()[1] + return connect(f"ws://127.0.0.1:{port}{dest.path}?{dest.query}", **options) + + with contextlib.redirect_stdout(output): + live.stream(local_connect, "basketball_nba", "event / 5", "private-test", 4) + self.assertTrue(closed.wait(timeout=5)) + finally: + server.shutdown() + worker.join(timeout=5) + self.assertFalse(worker.is_alive()) + self.assertEqual(observed, [("/ws/odds/basketball_nba?event_id=event+%2F+5", "private-test")]) + rendered = output.getvalue() + self.assertIn("Initial state: 1", rendered) + self.assertEqual(rendered.count("Odds update:"), 2) + self.assertIn("Heartbeat.", rendered) + self.assertNotIn("private-test", rendered) + + +if __name__ == "__main__": + unittest.main()