61 lines
1.8 KiB
Python
61 lines
1.8 KiB
Python
import json
|
|
import unittest
|
|
from unittest.mock import patch
|
|
from urllib.error import URLError
|
|
|
|
from texas_holdem.agents import HttpAgent, normalise_http_agent_endpoint
|
|
|
|
|
|
class FakeResponse:
|
|
def __init__(self, payload: dict[str, object]) -> None:
|
|
self.payload = payload
|
|
|
|
def read(self) -> bytes:
|
|
return json.dumps(self.payload).encode("utf-8")
|
|
|
|
def __enter__(self) -> "FakeResponse":
|
|
return self
|
|
|
|
def __exit__(self, *args: object) -> None:
|
|
return None
|
|
|
|
|
|
class AgentTests(unittest.TestCase):
|
|
def test_normalise_http_agent_endpoint_accepts_action_or_game_paths(self) -> None:
|
|
self.assertEqual(
|
|
normalise_http_agent_endpoint("http://127.0.0.1:9101/act"),
|
|
"http://127.0.0.1:9101",
|
|
)
|
|
self.assertEqual(
|
|
normalise_http_agent_endpoint("http://127.0.0.1:9101/game/"),
|
|
"http://127.0.0.1:9101",
|
|
)
|
|
|
|
def test_http_agent_post_retries_and_sets_player_header(self) -> None:
|
|
calls = []
|
|
|
|
def fake_urlopen(request, timeout): # type: ignore[no-untyped-def]
|
|
calls.append((request, timeout))
|
|
if len(calls) == 1:
|
|
raise URLError("temporary")
|
|
return FakeResponse({"ok": True})
|
|
|
|
agent = HttpAgent(
|
|
"http://agent.test/act",
|
|
player_id="p1",
|
|
retries=1,
|
|
retry_backoff_seconds=0,
|
|
)
|
|
|
|
with patch("texas_holdem.agents.urlopen", fake_urlopen):
|
|
payload = agent._post_json("/game", {"game_id": "g1"}, timeout_seconds=2)
|
|
|
|
self.assertEqual(payload, {"ok": True})
|
|
self.assertEqual(len(calls), 2)
|
|
self.assertEqual(calls[1][0].headers["X-player-id"], "p1")
|
|
self.assertEqual(calls[1][1], 2)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|