|
1 | 1 | """Tests for WebSocket functionality.""" |
2 | 2 |
|
| 3 | +import asyncio |
| 4 | +import base64 |
| 5 | +from typing import Literal |
| 6 | + |
3 | 7 | import pytest |
| 8 | +from nacl.signing import SigningKey |
| 9 | +from websockets.asyncio.server import ServerConnection, serve |
| 10 | +from websockets.http11 import Request |
4 | 11 |
|
5 | 12 | from polymarket_us import AuthenticationError, PolymarketUS |
6 | 13 | from polymarket_us.websocket import MarketsWebSocket, PrivateWebSocket |
7 | 14 |
|
8 | 15 | TEST_SECRET_KEY = "nWGxne/9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A=" |
9 | 16 |
|
10 | 17 |
|
| 18 | +@pytest.mark.parametrize("stream", ["markets", "private"]) |
| 19 | +async def test_connect_sends_auth_headers(stream: Literal["markets", "private"]) -> None: |
| 20 | + requests: asyncio.Queue[Request] = asyncio.Queue() |
| 21 | + |
| 22 | + async def handler(connection: ServerConnection) -> None: |
| 23 | + assert connection.request is not None |
| 24 | + await requests.put(connection.request) |
| 25 | + await connection.send('{"heartbeat": {}}') |
| 26 | + await connection.wait_closed() |
| 27 | + |
| 28 | + async with serve(handler, "127.0.0.1", 0, close_timeout=1) as server: |
| 29 | + port = server.sockets[0].getsockname()[1] |
| 30 | + with PolymarketUS( |
| 31 | + key_id="test-key", |
| 32 | + secret_key=TEST_SECRET_KEY, |
| 33 | + api_base_url=f"http://127.0.0.1:{port}", |
| 34 | + ) as client: |
| 35 | + ws = client.ws.markets() if stream == "markets" else client.ws.private() |
| 36 | + heartbeat = asyncio.Event() |
| 37 | + ws.on("heartbeat", heartbeat.set) |
| 38 | + try: |
| 39 | + await asyncio.wait_for(ws.connect(), timeout=5) |
| 40 | + request = await asyncio.wait_for(requests.get(), timeout=5) |
| 41 | + assert request.path == f"/v1/ws/{stream}" |
| 42 | + assert request.headers["X-PM-Access-Key"] == "test-key" |
| 43 | + timestamp = request.headers["X-PM-Timestamp"] |
| 44 | + assert timestamp.isdigit() |
| 45 | + signature = base64.b64decode(request.headers["X-PM-Signature"]) |
| 46 | + signing_key = SigningKey(base64.b64decode(TEST_SECRET_KEY)) |
| 47 | + signing_key.verify_key.verify( |
| 48 | + (timestamp + "GET" + request.path).encode(), signature |
| 49 | + ) |
| 50 | + await asyncio.wait_for(heartbeat.wait(), timeout=5) |
| 51 | + assert ws.is_connected |
| 52 | + finally: |
| 53 | + await asyncio.wait_for(ws.close(), timeout=5) |
| 54 | + assert not ws.is_connected |
| 55 | + |
| 56 | + |
11 | 57 | class TestWebSocketFactory: |
12 | 58 | """Tests for WebSocket factory.""" |
13 | 59 |
|
|
0 commit comments