SHARINGAN pokerfreak-splash d5b9a6f (git archive vom Spielrechner, 03.12.)

This commit is contained in:
2026-12-03 16:07:37 +01:00
commit c606235731
425 changed files with 76414 additions and 0 deletions
+56
View File
@@ -0,0 +1,56 @@
import json
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import pytest
@pytest.fixture(autouse=True)
def _isolated_tokens(tmp_path, monkeypatch):
# The CLI saves bot tokens in ~/.config/sharingan; keep tests out of the real home.
import sharingan.cli
monkeypatch.setattr(sharingan.cli, "TOKENS_FILE", str(tmp_path / "tokens.json"))
monkeypatch.setattr(sharingan.cli, "OWNER_FILE", str(tmp_path / "owner.json"))
monkeypatch.delenv("SHARINGAN_CONTACT", raising=False)
monkeypatch.delenv("SHARINGAN_PROFILE", raising=False)
from sharingan.models import YourTurn
# The worked example from docs/TABLE_API.md section 5.3 (seat 0 on the flop, facing a check)
DOC_YOUR_TURN = {
"v": 1, "type": "your_turn", "table_id": "t1", "hand_id": "h-77", "seq": 9, "t_ms": 1792000000000,
"data": {
"decision_id": "d-77-9", "seat": 0, "street": "flop", "hole_cards": ["Ah", "Kd"], "board": ["7c", "8d", "2s"],
"history": [
{"seq": 1, "street": "preflop", "seat": 4, "type": "post_sb", "to": 50, "added": 50, "all_in": False, "forced": True, "timeout": False, "stack": 9950, "pot": 50, "current_bet": 50, "min_raise_to": 100, "next_to_act": 5},
{"seq": 2, "street": "preflop", "seat": 5, "type": "post_bb", "to": 100, "added": 100, "all_in": False, "forced": True, "timeout": False, "stack": 9900, "pot": 150, "current_bet": 100, "min_raise_to": 200, "next_to_act": 0},
{"seq": 3, "street": "preflop", "seat": 0, "type": "raise", "to": 250, "added": 250, "all_in": False, "forced": False, "timeout": False, "stack": 9750, "pot": 400, "current_bet": 250, "min_raise_to": 400, "next_to_act": 1},
{"seq": 8, "street": "flop", "seat": 5, "type": "check", "to": 0, "added": 0, "all_in": False, "forced": False, "timeout": False, "stack": 9750, "pot": 550, "current_bet": 0, "min_raise_to": 100, "next_to_act": 0},
],
"players": [
{"seat": 0, "name": "pluribus", "stack_start": 10000, "stack": 9750, "street_contrib": 0, "hand_contrib": 250, "status": "active"},
{"seat": 5, "name": "erin", "stack_start": 10000, "stack": 9750, "street_contrib": 0, "hand_contrib": 250, "status": "active"},
],
"button_seat": 3, "small_blind": 50, "big_blind": 100, "pot": 550,
"pots": [{"amount": 550, "eligible_seats": [0, 5]}],
"legal": {"fold": True, "check": True, "call": None, "raise": {"min_to": 100, "max_to": 9750}},
"deadline_ms": 1792000005000, "time_bank_ms": 30000,
},
}
def doc_state() -> YourTurn:
return YourTurn.from_dict(DOC_YOUR_TURN["data"], table_id="t1", t_ms=DOC_YOUR_TURN["t_ms"])
def facing_bet_state(**over) -> YourTurn:
d = json.loads(json.dumps(DOC_YOUR_TURN["data"]))
d["pot"] = 750
d["players"][0]["street_contrib"] = 0
d["players"][1]["street_contrib"] = 200
d["legal"] = {"fold": True, "check": False, "call": {"to": 200, "added": 200, "all_in": False},
"raise": {"min_to": 400, "max_to": 9750}}
d.update(over)
return YourTurn.from_dict(d, table_id="t1", t_ms=1792000000000)
+69
View File
@@ -0,0 +1,69 @@
import json
import random
from conftest import DOC_YOUR_TURN
from sharingan import Action, YourTurn
from sharingan.bots import CallingStation, LLMBot, RandomBot, TightAggressive
from sharingan.helpers import is_legal
CARDS = [r + s for r in "23456789TJQKA" for s in "cdhs"]
def random_state(rng: random.Random) -> YourTurn:
d = json.loads(json.dumps(DOC_YOUR_TURN["data"]))
street = rng.choice(["preflop", "flop", "turn", "river"])
cards = rng.sample(CARDS, 7)
d["hole_cards"], d["street"] = cards[:2], street
d["board"] = cards[2:2 + {"preflop": 0, "flop": 3, "turn": 4, "river": 5}[street]]
stack = rng.choice([300, 2000, 9750])
d["players"][0]["stack"] = stack
facing = rng.random() < 0.6
if facing:
amt = rng.choice([100, 250, 600, stack])
amt = min(amt, stack)
d["legal"] = {"fold": True, "check": False, "call": {"to": amt, "added": amt, "all_in": amt == stack},
"raise": None if amt >= stack or rng.random() < 0.2 else {"min_to": min(2 * amt, stack), "max_to": stack}}
else:
d["legal"] = {"fold": True, "check": True, "call": None,
"raise": {"min_to": min(100, stack), "max_to": stack}}
return YourTurn.from_dict(d)
def test_bots_always_legal():
rng = random.Random(1)
bots = [RandomBot(seed=3), CallingStation(), TightAggressive(),
LLMBot(lambda p: rng.choice(["ACTION: raise 999999", "ACTION: fold", "banana", "ACTION: call"]))]
for _ in range(400):
s = random_state(rng)
for b in bots:
a = b.act(s)
assert isinstance(a, Action)
if not isinstance(b, LLMBot): # LLM output is untrusted; the runner legalizes it
assert is_legal(s, a), (b.name, a, s.legal)
def test_calling_station_and_tag_basics():
rng = random.Random(2)
s = random_state(rng)
s.legal.call = None
s.legal.check = True
assert CallingStation().act(s) == Action.check()
s.street, s.board, s.hole_cards = "preflop", [], ["Ah", "Ad"]
a = TightAggressive().act(s)
assert a.type == "raise"
s.hole_cards = ["7h", "2d"]
assert TightAggressive().act(s).type in ("check", "fold")
def test_llm_bot_prompt_and_parse():
seen = []
def complete(prompt: str) -> str:
seen.append(prompt)
return "The pot is small.\nACTION: raise 300"
bot = LLMBot(complete)
rng = random.Random(5)
s = random_state(rng)
assert bot.act(s) == Action("raise", 300)
assert "Your hole cards" in seen[0] and "Legal actions" in seen[0]
+495
View File
@@ -0,0 +1,495 @@
import os
import asyncio
import subprocess
import sys
from typing import Any
import pytest
from sharingan.cli import FunctionBot, load_bot, main, format_score
from sharingan.mock import MockArena
from sharingan import Bot
def test_bot_token_is_saved_and_reused(tmp_path):
from sharingan import cli
class FakeApi:
base_url = "http://arena.test"
registered = 0
def register_bot(self, name):
FakeApi.registered += 1
from types import SimpleNamespace
return SimpleNamespace(player_id=f"p_{FakeApi.registered}", token=f"sk_{FakeApi.registered}")
def request(self, method, path, body=None, token=None, query=None):
if token != "sk_1":
raise cli.ApiException(401, "unauthorized", "bad token")
return {"player_id": "p_1"}
api = FakeApi()
assert cli.bot_token(api, "mybot") == "sk_1"
assert cli.bot_token(api, "mybot") == "sk_1", "second run reuses the saved token"
assert FakeApi.registered == 1
assert oct(os.stat(cli.TOKENS_FILE).st_mode & 0o777) == "0o600"
assert cli.bot_token(api, "other") == "sk_2" and FakeApi.registered == 2, "another bot name is another bot"
assert cli.bot_token(api, "other") == "sk_3" and FakeApi.registered == 3, "a rejected saved token is replaced"
assert cli.leaderboard_url("https://arena.sharingan.poker", "ladder-v1") == "https://sharingan.poker/leaderboard/"
def test_load_bot_variants(tmp_path):
a = tmp_path / "a.py"
a.write_text("from sharingan import Bot, Action\nclass Mine(Bot):\n def act(self, s):\n return Action.check()\n")
b = tmp_path / "b.py"
b.write_text("def act(state):\n return None\n")
c = tmp_path / "c.py"
c.write_text("from sharingan.bots import CallingStation\nbot = CallingStation()\n")
d = tmp_path / "d.py"
d.write_text("x = 1\n")
assert isinstance(load_bot(str(a)), Bot) and load_bot(str(a)).name == "a"
assert isinstance(load_bot(str(b)), FunctionBot)
assert load_bot(str(c)).name == "calling_station"
with pytest.raises(SystemExit):
load_bot(str(d))
def test_format_score():
line = format_score("x", {"bb_per_100": 5.0, "ci95_bb_per_100": 2.5}, 600, "ladder")
assert line == "x: +50.0 ± 25.0 mbb/game (95% CI) over 600 hands vs ladder"
assert "[duplicate]" in format_score("x", {"duplicate_bb_per_100": 1.0}, 6, "ladder")
import contextlib
import threading
@contextlib.contextmanager
def mock_server(**kw):
"""MockArena on a background loop thread (main() runs its own asyncio.run)."""
ready, stop, box = threading.Event(), threading.Event(), {}
def serve():
async def run():
async with MockArena(**kw) as arena:
box["arena"] = arena
ready.set()
while not stop.is_set():
await asyncio.sleep(0.05)
asyncio.run(run())
t = threading.Thread(target=serve, daemon=True)
t.start()
assert ready.wait(10)
try:
yield box["arena"]
finally:
stop.set()
t.join(5)
def _bot(tmp_path):
bot = tmp_path / "mybot.py"
bot.write_text("def act(s):\n return None\n")
return str(bot)
def test_eval_prints_one_line(tmp_path, capsys):
bot = tmp_path / "mybot.py"
bot.write_text("def act(s):\n return None\n")
with mock_server() as arena: # no /v1/benchmarks -> falls back to the duplicate match
rc = main(["eval", str(bot), "--server", arena.url, "--hands", "600"])
out = capsys.readouterr().out.strip().splitlines()
assert rc == 0 and out == ["mybot: +40.0 ± 25.0 mbb/game (95% CI) over 600 hands vs ladder [duplicate]"]
def test_unreachable_prints_start_command(tmp_path, capsys):
bot = tmp_path / "mybot.py"
bot.write_text("def act(s):\n return None\n")
rc = main(["eval", str(bot), "--server", "http://127.0.0.1:1"])
assert rc == 2 and "cargo run --release -p sharingan-arena" in capsys.readouterr().err
def test_eval_defaults_to_ladder_benchmark(tmp_path, capsys):
with mock_server(benchmarks=True) as arena:
rc = main(["eval", _bot(tmp_path), "--server", arena.url, "--hands", "600"])
assert arena.run_requests == [{"hands": 600}]
out = capsys.readouterr().out.strip().splitlines()
assert rc == 0 and out == ["mybot: +42.5 ± 12.0 mbb/game (95% CI, aivat) over 600 hands on ladder-v1 [unverified]"]
def test_eval_match_flag_forces_duplicate_match(tmp_path, capsys):
with mock_server(benchmarks=True) as arena:
rc = main(["eval", _bot(tmp_path), "--server", arena.url, "--hands", "600", "--match"])
assert arena.run_requests == []
assert rc == 0 and "[duplicate]" in capsys.readouterr().out
def test_benchmark_prints_score_and_leaderboard(tmp_path, capsys):
with mock_server(benchmarks=True, bench_result=(-7.25, 3.0)) as arena:
rc = main(["benchmark", _bot(tmp_path), "--track", "sharingan-1", "--hands", "100", "--server", arena.url])
assert arena.run_requests == [{"hands": 100}] and arena.runs
run = next(iter(arena.runs.values()))
assert run["track"] == "sharingan-1" and run["hands_total"] == 102 # rounded up to whole deals
cap = capsys.readouterr()
assert rc == 0
assert cap.out.strip().splitlines() == [
"mybot: -7.2 ± 3.0 mbb/game (95% CI, aivat) over 102 hands on sharingan-1 [unverified]",
f"leaderboard: {arena.url}/v1/leaderboard?track=sharingan-1"]
assert "sharingan-1: 100% 102/102 hands" in cap.err # progress lines (stderr is not a tty here)
def test_benchmark_reuses_token_and_quiet(tmp_path, capsys):
import json
import urllib.request
with mock_server(benchmarks=True) as arena:
req = urllib.request.Request(arena.url + "/v1/players", data=json.dumps({"name": "pre"}).encode(), method="POST")
reg = json.loads(urllib.request.urlopen(req).read())
rc = main(["benchmark", _bot(tmp_path), "--token", reg["token"], "--quiet", "--server", arena.url])
assert len(arena.players) == 1 # no second registration
assert next(iter(arena.runs.values()))["player_id"] == reg["player_id"]
assert arena.run_requests == [{}] # server default hands
cap = capsys.readouterr()
assert rc == 0 and "hands on ladder-v1" in cap.out and cap.err == ""
def test_benchmark_unreachable(tmp_path, capsys):
rc = main(["benchmark", _bot(tmp_path), "--server", "http://127.0.0.1:1"])
assert rc == 2 and "arena server not reachable" in capsys.readouterr().err
def test_connect_answers_until_max_hands(tmp_path, capsys):
import json
import urllib.request
with mock_server(hands=5) as arena:
req = urllib.request.Request(arena.url + "/v1/players", data=json.dumps({"name": "pre"}).encode(), method="POST")
reg = json.loads(urllib.request.urlopen(req).read())
rc = main(["connect", _bot(tmp_path), "--server", arena.url, "--token", reg["token"],
"--player-id", reg["player_id"], "--max-hands", "3"])
assert rc == 0 and len(arena.hand_ends) == 3 and len(arena.acts) >= 3
err = capsys.readouterr().err
assert f"connected as {reg['player_id']}" in err and "warning" not in err and "disconnected after 3 hands" in err
def test_connect_warns_on_wrong_player_id_and_bad_token(tmp_path, capsys):
with mock_server(hands=1) as arena:
import json
import urllib.request
req = urllib.request.Request(arena.url + "/v1/players", data=json.dumps({"name": "pre"}).encode(), method="POST")
reg = json.loads(urllib.request.urlopen(req).read())
assert main(["connect", _bot(tmp_path), "--server", arena.url, "--token", reg["token"],
"--player-id", "someone-else", "--max-hands", "1"]) == 0
assert "warning: token belongs to" in capsys.readouterr().err
assert main(["connect", _bot(tmp_path), "--server", arena.url, "--token", "nope", "--no-reconnect"]) == 1
assert "never connected" in capsys.readouterr().err
def test_launch_bot_wrapper_maps_env(tmp_path, monkeypatch):
"""deploy/platinum/bot/launch_bot.py is a thin wrapper over `sharingan connect`."""
import importlib.util
import os
path = os.path.join(os.path.dirname(__file__), "..", "..", "..", "deploy", "platinum", "bot", "launch_bot.py")
spec = importlib.util.spec_from_file_location("launch_bot", path)
lb = importlib.util.module_from_spec(spec)
spec.loader.exec_module(lb)
monkeypatch.setenv("BOT_FILE", "/x/bot.py")
monkeypatch.setenv("ARENA_URL", "https://a")
monkeypatch.setenv("ARENA_TOKEN", "T")
monkeypatch.setenv("MAX_HANDS", "7")
assert lb.argv_from_env() == ["connect", "/x/bot.py", "--server", "https://a", "--token", "T", "--max-hands", "7"]
def test_submit_requires_contact_and_profile_and_remembers_them(tmp_path, monkeypatch, capsys):
from sharingan import cli
sent = []
class FakeApi:
def __init__(self, base_url):
self.base_url, self.timeout = base_url, 30.0
def request(self, method, path, body=None, token=None, query=None):
if method == "POST":
sent.append(body)
return {"id": "job_1"}
return {"status": "finished", "settled": True, "hands_done": 600, "hands_total": 600, "bot_name": "mybot",
"mbb_per_game": 1.0, "ci95_mbb": 2.0, "track": "ladder-v1", "verified": True}
monkeypatch.setattr(cli, "ArenaClient", FakeApi)
bot = _bot(tmp_path)
base = ["submit", bot, "--token", "sk_x", "--server", "http://x", "--quiet"]
assert main(base) == 2 and not sent, "nothing is uploaded without an owner"
assert "--contact" in capsys.readouterr().err
assert main(base + ["--contact", "me@example.com"]) == 2 and not sent, "an email alone is not enough"
assert main(base + ["--contact", "@me", "--profile", "https://x.com/me"]) == 2 and not sent, "contact is an email"
assert main(base + ["--contact", "me@example.com", "--profile", "https://x.com/me"]) == 0
assert main(base) == 0, "remembered after the first accepted submit"
assert [(b["contact"], b["profile"]) for b in sent] == [("me@example.com", "https://x.com/me")] * 2
assert oct(os.stat(cli.OWNER_FILE).st_mode & 0o777) == "0o600"
out = capsys.readouterr()
assert "[VERIFIED, NOT RANKED: under 20,004 hands, hosted job job_1]" in out.out
assert "leaderboard:" not in out.out, "a run that cannot rank does not link the board"
assert "not ranked" in out.err, "a verified run shorter than a ranked run says it does not count"
def test_submit_warns_when_the_bot_crashed_or_forfeited(tmp_path, monkeypatch, capsys):
from sharingan import cli
class FakeApi:
def __init__(self, base_url):
self.base_url, self.timeout = base_url, 30.0
def request(self, method, path, body=None, token=None, query=None):
if method == "POST":
return {"id": "job_2"}
return {"status": "finished", "settled": True, "hands_done": 600, "hands_total": 600, "bot_name": "mybot",
"mbb_per_game": -208.3, "ci95_mbb": 205.7, "track": "sharingan-1", "verified": True, "forfeit_hands": 588,
"bot_log_tail": "lane 1: RuntimeError: boom\nplaying check/fold"}
monkeypatch.setattr(cli, "ArenaClient", FakeApi)
monkeypatch.setenv("SHARINGAN_CONTACT", "me@example.com")
monkeypatch.setenv("SHARINGAN_PROFILE", "https://linkedin.com/in/me")
assert main(["submit", _bot(tmp_path), "--token", "sk_x", "--server", "http://x", "--track", "sharingan-1", "--quiet"]) == 0
err = capsys.readouterr().err
assert "588 of 600 hands forfeited" in err and "RuntimeError: boom" in err
def test_the_warning_names_the_exception_not_the_traceback_header():
from sharingan import cli
import io, contextlib
tail = "Traceback (most recent call last):\n File \"/opt/sharingan/bot/bot.py\", line 9, in act\n raise ValueError(\"boom on the river\")\nValueError: boom on the river"
err = io.StringIO()
with contextlib.redirect_stderr(err):
cli._warn_bot_trouble({"id": "job_9", "hands_done": 20004, "forfeit_hands": 0, "bot_log_tail": tail})
out = err.getvalue()
assert "first error: ValueError: boom on the river" in out, out
assert "bot_log_tail" in out and "job_9" in out
# ----------------------------------------------------------------------------- token / submit / play / naming
class FakeApi:
"""Stands in for ArenaClient: no network. `registered` counts POST /v1/players; `posted` keeps the /v1/jobs bodies."""
registered: list = []
posted: list = []
job: dict = {}
refuse: Any = None
def __init__(self, base_url, token=None):
self.base_url, self.token, self.timeout = base_url.rstrip("/"), token, 30.0
def register_bot(self, name, kind="bot", set_token=True):
from types import SimpleNamespace
FakeApi.registered.append(name)
n = len(FakeApi.registered)
self.token = f"sk_{n}"
return SimpleNamespace(player_id=f"p_{n}", token=f"sk_{n}")
def request(self, method, path, body=None, token=None, query=None):
if path == "/v1/me":
return {"player_id": "p_" + (token or "")[3:]}
if method == "POST":
if FakeApi.refuse:
raise FakeApi.refuse
FakeApi.posted.append(body)
return {"id": "job_9", "hands": 20004}
return dict({"status": "finished", "settled": True, "hands_done": 20004, "hands_total": 20004, "bot_name": "mybot",
"mbb_per_game": 12.5, "ci95_mbb": 3.0, "track": "sharingan-1", "verified": True}, **FakeApi.job)
@pytest.fixture
def fake_api(monkeypatch):
from sharingan import cli
FakeApi.registered, FakeApi.posted, FakeApi.job, FakeApi.refuse = [], [], {}, None
monkeypatch.setattr(cli, "ArenaClient", FakeApi)
monkeypatch.setenv("SHARINGAN_CONTACT", "me@example.com")
monkeypatch.setenv("SHARINGAN_PROFILE", "https://x.com/me")
monkeypatch.delenv("SHARINGAN_SERVER", raising=False)
return FakeApi
def _save_token(server, name, token, player_id="p"):
import json
from sharingan import cli
tokens = cli._load_tokens()
tokens[f"{server}|{name}"] = {"player_id": player_id, "token": token}
with open(cli.TOKENS_FILE, "w") as f:
json.dump(tokens, f)
def test_token_prints_only_the_saved_token(tmp_path, capsys):
_save_token("http://a.test", "mybot", "sk_mine")
_save_token("http://a.test", "other", "sk_other")
_save_token("http://b.test", "solo", "sk_solo")
capsys.readouterr()
assert main(["token", str(tmp_path / "mybot.py"), "--server", "http://a.test/"]) == 0, "a path is named after its file stem"
assert capsys.readouterr().out == "sk_mine\n"
assert main(["token", "other", "--server", "http://a.test"]) == 0, "or give the bot name"
assert capsys.readouterr().out == "sk_other\n"
assert main(["token", "--server", "http://b.test"]) == 0, "no BOT: the only token saved for that server"
cap = capsys.readouterr()
assert cap.out == "sk_solo\n" and cap.err == ""
def test_token_failures_are_exit_1_with_a_message_on_stderr(tmp_path, capsys):
_save_token("http://a.test", "mybot", "sk_mine")
_save_token("http://a.test", "other", "sk_other")
capsys.readouterr()
assert main(["token", "--server", "http://a.test"]) == 1, "two bots, none named"
cap = capsys.readouterr()
assert cap.out == "" and "mybot" in cap.err and "other" in cap.err
assert main(["token", "nobody.py", "--server", "http://a.test"]) == 1
cap = capsys.readouterr()
assert cap.out == "" and "no saved token for bot 'nobody'" in cap.err
assert main(["token", "--server", "http://empty.test"]) == 1
cap = capsys.readouterr()
assert cap.out == "" and "no saved token" in cap.err and "sharingan submit" in cap.err
def test_token_uses_the_default_server(monkeypatch, capsys):
from sharingan import cli
monkeypatch.delenv("SHARINGAN_SERVER", raising=False)
_save_token(cli.DEFAULT_SERVER, "mybot", "sk_public")
assert main(["token", "mybot.py"]) == 0 and capsys.readouterr().out == "sk_public\n"
@pytest.mark.parametrize("extra, why", [
(["--hands", "599"], "--hands"),
(["--hands", "200001"], "--hands"),
(["--hands", "0"], "--hands"),
(["--profile", "not a link"], "--profile"),
(["--profile", "https://127.0.0.1/me"], "--profile"),
(["--contact", "@me"], "--contact"),
])
def test_submit_validates_before_registering_or_uploading(tmp_path, fake_api, capsys, extra, why):
assert main(["submit", _bot(tmp_path), "--server", "http://x", "--quiet"] + extra) == 2
assert why in capsys.readouterr().err
assert fake_api.registered == [] and fake_api.posted == [], "nothing was registered or uploaded"
def test_submit_accepts_the_edges_of_the_hands_range_and_handles(tmp_path, fake_api, capsys):
for extra in (["--hands", "600"], ["--hands", "200000"], ["--profile", "@me"], ["--profile", "linkedin.com/in/me"]):
assert main(["submit", _bot(tmp_path), "--server", "http://x", "--quiet", "--token", "sk_x"] + extra) == 0
assert len(fake_api.posted) == 4
def test_submit_missing_entry_in_a_directory_does_not_register(tmp_path, fake_api, capsys):
d = tmp_path / "botdir"
d.mkdir()
(d / "main.py").write_text("def act(s):\n return None\n")
assert main(["submit", str(d), "--server", "http://x", "--quiet"]) == 2
assert "bot.py" in capsys.readouterr().err and fake_api.registered == [] and fake_api.posted == []
assert main(["submit", str(d), "--entry", "main.py", "--server", "http://x", "--quiet"]) == 0
assert fake_api.registered == ["botdir"] and fake_api.posted[0]["entry"] == "main.py"
def test_submit_accepted_line_shows_server_hands_and_upload_hash(tmp_path, fake_api, capsys):
import hashlib
assert main(["submit", _bot(tmp_path), "--server", "http://x", "--quiet", "--token", "sk_x"]) == 0
cap = capsys.readouterr()
accepted = [ln for ln in cap.err.splitlines() if "accepted" in ln]
assert len(accepted) == 1 and "job job_9 accepted (20004 hands on ladder-v1; upload sha256 " in accepted[0], accepted
import base64
sha = hashlib.sha256(base64.b64decode(fake_api.posted[0]["artifactTgzBase64"])).hexdigest()
assert f"sha256 {sha[:12]})" in accepted[0], "the hash of the uploaded .tar.gz"
assert "[VERIFIED, hosted job job_9]" in cap.out and "leaderboard:" in cap.out, "a full verified run links the board"
assert "not ranked" not in cap.err
def test_submit_short_verified_run_says_not_ranked_and_skips_the_link(tmp_path, fake_api, capsys):
fake_api.job = {"hands_done": 600, "hands_total": 600, "mbb_per_game": 378.1, "ci95_mbb": 578.5}
assert main(["submit", _bot(tmp_path), "--server", "http://x", "--quiet", "--token", "sk_x", "--hands", "600"]) == 0
cap = capsys.readouterr()
assert cap.out.strip().splitlines() == [
"mybot: +378.1 +- 578.5 mbb/game over 600 hands on sharingan-1 [VERIFIED, NOT RANKED: under 20,004 hands, hosted job job_9]"]
assert "not ranked" in cap.err
def test_submit_unverified_job_is_labelled_and_server_refusals_are_explained(tmp_path, fake_api, capsys):
fake_api.job = {"verified": False}
assert main(["submit", _bot(tmp_path), "--server", "http://x", "--quiet", "--token", "sk_x"]) == 0
assert "[unverified, hosted job job_9]" in capsys.readouterr().out
from sharingan import cli
msg = "submissions are temporarily unavailable"
fake_api.refuse = cli.ApiException(403, "temporarily_unavailable", msg)
assert main(["submit", _bot(tmp_path), "--server", "http://x", "--quiet", "--token", "sk_x", "--track", "sharingan-1"]) == 1
cap = capsys.readouterr()
assert cap.out == "" and "403 temporarily_unavailable" in cap.err and msg in cap.err
def test_submit_reuses_the_saved_token_of_the_file_name(tmp_path, fake_api, capsys):
bot = _bot(tmp_path)
for _ in range(2):
assert main(["submit", bot, "--server", "http://x", "--quiet"]) == 0
assert fake_api.registered == ["mybot"], "registered once, then the saved token"
capsys.readouterr()
assert main(["token", bot, "--server", "http://x"]) == 0 and capsys.readouterr().out == "sk_1\n"
def test_play_reuses_the_saved_bot_token(tmp_path, fake_api, monkeypatch, capsys):
from sharingan import cli
tokens_seen = []
class FakeRunner:
def __init__(self, bot, server, token, max_hands=None, **kw):
tokens_seen.append(token)
self.hands_played, self.net_chips, self._my_seats = 0, 0, {}
async def run(self):
return None
class FakeTable:
table_id = "t1"
monkeypatch.setattr(fake_api, "create_table", lambda self, **kw: FakeTable(), raising=False)
monkeypatch.setattr(fake_api, "join_table", lambda self, tid, seat, pid, token=None: tokens_seen.append(("seat", tid, seat, pid)),
raising=False)
monkeypatch.setattr(cli, "Runner", FakeRunner)
for _ in range(3):
assert main(["play", _bot(tmp_path), "--vs", "sharingan-1", "--server", "http://x"]) == 0
assert fake_api.registered == ["mybot"], "one registration for three plays"
assert [t for t in tokens_seen if isinstance(t, str)] == ["sk_1"] * 3
assert ("seat", "t1", 0, "p_1") in tokens_seen, "the saved player id sits at the table"
def test_load_bot_names_llm_bots_after_their_file_unless_named(tmp_path):
from sharingan.bots import LLMBot
head = "from sharingan import Bot\nfrom sharingan.bots import LLMBot\ndef complete(p):\n return 'ACTION: call'\n"
for stem, line, want in [
("alpha", "bot = LLMBot(complete)", "alpha"),
("beta", "bot = LLMBot(complete)", "beta"),
("gamma", "bot = LLMBot(complete, name='my llm')", "my llm"),
("delta", "bot = LLMBot(complete)\nbot.name = 'chosen'", "chosen"),
("eps", "class Mine(Bot):\n name = 'explicit'\n def act(self, s): return None\nbot = Mine()", "explicit"),
("zeta", "class Mine(Bot):\n def act(self, s): return None\nbot = Mine()", "zeta"),
]:
f = tmp_path / f"{stem}.py"
f.write_text(head + line + "\n")
b = load_bot(str(f))
assert b.name == want, (stem, b.name)
assert LLMBot(lambda p: "").name == "bot" and LLMBot(lambda p: "", name="x").name == "x"
def test_webhook_server_accepts_both_signature_headers():
import json
import urllib.error
import urllib.request
from sharingan.bots import CallingStation
from sharingan.webhook import serve_webhook, sign
from conftest import DOC_YOUR_TURN
body = json.dumps(DOC_YOUR_TURN).encode()
srv = serve_webhook(CallingStation(), host="127.0.0.1", port=0, secret="s3", block=False)
try:
def post(headers):
req = urllib.request.Request(f"http://127.0.0.1:{srv.server_address[1]}/act", data=body, headers=headers, method="POST")
try:
with urllib.request.urlopen(req, timeout=5) as r:
return r.status
except urllib.error.HTTPError as e:
return e.code
assert post({"X-Sharingan-Signature": sign("s3", body)}) == 200, "what the server sends"
assert post({"X-Signature": sign("s3", body)}) == 200, "the old name still works"
assert post({"X-Sharingan-Signature": "sha256=bad"}) == 401
assert post({}) == 401
finally:
srv.shutdown()
srv.server_close()
+208
View File
@@ -0,0 +1,208 @@
import asyncio
import json
import logging
import pytest
from sharingan import (Action, ApiException, ArenaClient, Bot, Runner, handle_webhook, ws_url)
from sharingan.bots import CallingStation, LLMBot, RandomBot, TightAggressive
from sharingan.mock import MockArena
from sharingan.webhook import sign
from conftest import DOC_YOUR_TURN
def arun(coro):
return asyncio.run(asyncio.wait_for(coro, 20))
async def play(arena, bot, hands, **kw):
r = Runner(bot, arena.ws_url, "any-token", max_hands=hands, **kw)
await r.run()
return r
def test_ws_url():
assert ws_url("http://h:1", "tk") == "ws://h:1/v1/play?token=tk"
assert ws_url("https://h", "tk") == "wss://h/v1/play?token=tk"
assert ws_url("wss://h/v1/play?token=x", "tk") == "wss://h/v1/play?token=x"
def test_rest_flow():
async def main():
async with MockArena() as arena:
def sync():
api = ArenaClient(arena.http_url)
me = api.register_bot("my-bot")
assert me.token and me.player_id and api.token == me.token
t = api.create_table(small_blind=50)
assert t.config["big_blind"] == 100 and len(t.seats) == 6
seat = api.join_table(t.table_id, 2, me.player_id)
assert seat.player_id == me.player_id and seat.status == "seated"
with pytest.raises(ApiException) as e:
api.join_table(t.table_id, 2, me.player_id)
assert e.value.code == "seat_taken" and e.value.status == 409
assert api.get_table(t.table_id).seats[2].name == "my-bot"
with pytest.raises(ApiException) as e:
ArenaClient(arena.http_url, token="nope").get_table(t.table_id)
assert e.value.code == "unauthorized"
await asyncio.to_thread(sync)
arun(main())
@pytest.mark.parametrize("make", [lambda: RandomBot(seed=1), CallingStation, TightAggressive,
lambda: LLMBot(lambda p: "ACTION: call")])
def test_full_session(make):
async def main():
async with MockArena(hands=4) as arena:
r = await play(arena, make(), 4)
assert r.hands_played == 4 and len(arena.hand_ends) == 4
assert arena.errors_sent == [] # nothing illegal was ever sent
assert r.welcome["player_id"] and arena.received[0]["type"] == "hello"
assert r.net_chips == sum(h["results"][0]["net"] for h in arena.hand_ends)
for h in arena.hand_ends:
assert sum(x["net"] for x in h["results"]) == 0
arun(main())
def test_hooks_and_async_bot():
events = []
class B(Bot):
async def act(self, s):
await asyncio.sleep(0)
return Action.call() if s.legal.call else Action.check()
def on_hand_start(self, h): events.append(("start", h.hand_no, h.bb_seat))
def on_action(self, a): events.append(("action", a.type))
def on_street(self, s): events.append(("street", s.street, tuple(s.board)))
async def on_hand_end(self, e): events.append(("end", e.ended_by, e.hole_cards[0]))
async def main():
async with MockArena(hands=1) as arena:
await play(arena, B(), 1)
arun(main())
kinds = [e[0] for e in events]
assert kinds[0] == "start" and "street" in kinds and kinds[-1] == "end"
assert ("street", "flop", ("7c", "8d", "2s")) in events
assert events[-1] == ("end", "showdown", ["Ah", "Kd"])
def test_reconnect_resumes_same_decision():
async def main():
async with MockArena(hands=3, drop_on_turns={1, 3}) as arena:
r = await play(arena, CallingStation(), 3)
assert r.hands_played == 3
assert arena.connections >= 3
hellos = [m for m in arena.received if m["type"] == "hello"]
assert "resume" not in hellos[0]["data"]
assert hellos[1]["data"]["resume"][0]["table_id"] == "t1"
assert hellos[1]["data"]["resume"][0]["last_table_seq"] > 0
# the re-offered turn kept its decision_id and every decision was answered once
ids = [a["decision_id"] for a in arena.acts]
assert len(ids) == len(set(ids)) == 6
arun(main())
def test_illegal_action_gets_error_and_retry():
class Bad(Bot):
strict = True
n = 0
errs = []
def act(self, s):
Bad.n += 1
if Bad.n == 1:
return Action.raise_to(5) # below min_to -> bad_amount
return Action.call() if s.legal.call else Action.check()
def on_error(self, e): Bad.errs.append(e.code)
async def main():
async with MockArena(hands=1) as arena:
await play(arena, Bad(), 1)
assert arena.errors_sent == ["bad_amount"]
arun(main())
assert Bad.errs == ["bad_amount"] and Bad.n >= 3
def test_runner_legalizes_by_default():
class Sloppy(Bot):
def act(self, s):
return Action.raise_to(5) if s.legal.raise_ else Action.check()
async def main():
async with MockArena(hands=2) as arena:
await play(arena, Sloppy(), 2)
assert arena.errors_sent == []
assert arena.acts[0]["to"] == 200 # clamped to min_to
arun(main())
def test_act_timeout_and_exception_fall_back_to_check_fold():
class Slow(Bot):
calls = 0
async def act(self, s):
Slow.calls += 1
if Slow.calls == 1:
await asyncio.sleep(5)
raise RuntimeError("boom")
async def main():
async with MockArena(hands=1, decision_ms=500) as arena:
await play(arena, Slow(), 1, safety_margin_ms=100)
assert [a["type"] for a in arena.acts][0] == "fold" # timed out -> fold (facing BB)
arun(main())
def test_sync_blocking_act_hits_deadline():
import time
class Blocking(Bot):
def act(self, s):
time.sleep(2)
return Action.call() if s.legal.call else Action.check()
async def main():
async with MockArena(hands=1, decision_ms=400) as arena:
await play(arena, Blocking(), 1, safety_margin_ms=50)
assert arena.acts[0]["type"] == "fold"
arun(main())
def test_table_seq_gap_triggers_resync():
async def main():
async with MockArena(hands=2, emit_gap_at=6) as arena:
await play(arena, CallingStation(), 2)
hellos = [m for m in arena.received if m["type"] == "hello"]
assert len(hellos) >= 2 and "resume" in hellos[1]["data"]
arun(main())
def test_bad_token_rejected():
async def main():
async with MockArena() as arena:
r = Runner(CallingStation(), arena.ws_url, "bad", reconnect=False)
await r.run()
assert r.connects == 1 and r.welcome is None
arun(main())
def test_llm_bot_async_complete_end_to_end():
async def complete(prompt):
await asyncio.sleep(0)
return "Strong hand.\nACTION: raise 300"
async def main():
async with MockArena(hands=2) as arena:
bot = LLMBot(complete)
await play(arena, bot, 2)
assert arena.acts[0] == {"hand_id": "h-1", "decision_id": arena.acts[0]["decision_id"], "type": "raise", "to": 300}
arun(main())
def test_webhook():
body = json.dumps(DOC_YOUR_TURN).encode()
st, out = handle_webhook(CallingStation(), body, sign("s3", body), "s3")
assert st == 200 and json.loads(out) == {"hand_id": "h-77", "decision_id": "d-77-9", "type": "check"}
st, _ = handle_webhook(CallingStation(), body, "sha256=bad", "s3")
assert st == 401
st, out = handle_webhook(CallingStation(), b'{"type":"action","data":{}}')
assert st == 200 and out == b"{}"
+66
View File
@@ -0,0 +1,66 @@
"""End-to-end against a real arena server. Skipped unless SHARINGAN_E2E_SERVER is set, e.g.
SHARINGAN_E2E_SERVER=http://localhost:8095 pytest tests/test_e2e.py
(server needs ARENA_BLUEPRINT so the benchmark tracks are available)."""
import json
import os
import re
import signal
import subprocess
import sys
import time
import urllib.request
import pytest
SERVER = os.environ.get("SHARINGAN_E2E_SERVER")
pytestmark = pytest.mark.skipif(not SERVER, reason="set SHARINGAN_E2E_SERVER to run against a real arena")
BOT = "from sharingan.bots import CallingStation\nbot = CallingStation()\n"
def _cli(*args, **kw):
return subprocess.run([sys.executable, "-m", "sharingan.cli", *args], capture_output=True, text=True, timeout=300, **kw)
def test_benchmark_and_eval(tmp_path):
bot = tmp_path / "e2ebot.py"
bot.write_text(BOT)
r = _cli("benchmark", str(bot), "--track", "ladder-v1", "--hands", "300", "--server", SERVER)
assert r.returncode == 0, r.stderr
out = r.stdout.strip().splitlines()
assert re.fullmatch(r"calling_station: [+-]\d+\.\d ± \d+\.\d mbb/game \(95% CI, aivat\) over 300 hands on ladder-v1 \[unverified\]", out[0]), out
assert out[1] == f"leaderboard: {SERVER.rstrip('/')}/v1/leaderboard?track=ladder-v1"
assert "ladder-v1: 100% 300/300 hands" in r.stderr
e = _cli("eval", str(bot), "--hands", "300", "--server", SERVER, "--quiet")
assert e.returncode == 0 and "on ladder-v1" in e.stdout and len(e.stdout.strip().splitlines()) == 1, e.stderr
def test_connect_then_external_run(tmp_path):
bot = tmp_path / "e2ebot.py"
bot.write_text(BOT)
req = urllib.request.Request(SERVER + "/v1/players", data=json.dumps({"name": "e2e-connect", "kind": "bot"}).encode(),
method="POST", headers={"content-type": "application/json"})
reg = json.load(urllib.request.urlopen(req))
p = subprocess.Popen([sys.executable, "-m", "sharingan.cli", "connect", str(bot), "--server", SERVER, "--token", reg["token"],
"--player-id", reg["player_id"]], stderr=subprocess.PIPE, text=True)
try:
run, t0 = None, time.time()
while run is None and time.time() - t0 < 20:
try:
req = urllib.request.Request(SERVER + "/v1/benchmarks/ladder-v1/runs", data=json.dumps({"hands": 120}).encode(), method="POST",
headers={"content-type": "application/json", "authorization": "Bearer " + reg["token"]})
run = json.load(urllib.request.urlopen(req))
except urllib.error.HTTPError as e:
assert e.code == 409 # not_connected yet
time.sleep(0.3)
assert run, "run never started"
while time.time() - t0 < 120:
cur = json.load(urllib.request.urlopen(f"{SERVER}/v1/benchmarks/ladder-v1/runs/{run['run_id']}"))
if cur["status"] != "running":
break
time.sleep(0.3)
assert cur["status"] == "finished" and cur["mbb_per_game"] is not None
finally:
p.send_signal(signal.SIGTERM)
err = p.communicate(timeout=20)[1]
assert p.returncode == 0 and f"connected as {reg['player_id']}" in err and "disconnected after 120 hands" in err
+83
View File
@@ -0,0 +1,83 @@
import pytest
from conftest import doc_state, facing_bet_state
from sharingan import (Action, legal_types, legalize, parse_action_text, pot_raise_to, preflop_strength,
render_state, safe_action)
from sharingan.helpers import (all_in_action, bb_multiple_to, is_legal, made_hand_category, position_name)
def test_parse_doc_example():
s = doc_state()
assert s.decision_id == "d-77-9" and s.table_id == "t1"
assert s.hole_cards == ["Ah", "Kd"] and s.board == ["7c", "8d", "2s"]
assert s.legal.check and s.legal.call is None and s.legal.raise_.max_to == 9750
assert s.to_call == 0 and s.pot_odds == 0.0 and s.stack == 9750
assert s.history[0].type == "post_sb" and s.history[-1].next_to_act == 0
assert legal_types(s) == ["fold", "check", "raise"]
assert s.pots[0].eligible_seats == [0, 5]
def test_pot_odds_and_sizes():
s = facing_bet_state()
assert s.to_call == 200
assert s.pot_odds == pytest.approx(200 / 950)
# call to 200, then raise by pot+call: 200 + (750 + 200) = 1150
assert pot_raise_to(s, 1.0) == 1150
assert pot_raise_to(s, 0.0) == 400 # clamped up to min_to
assert bb_multiple_to(s, 1000) == 9750 # clamped down to max
assert all_in_action(s) == Action.raise_to(9750)
def test_pot_bet_when_checking():
s = doc_state() # pot 550, no bet
assert pot_raise_to(s, 1.0) == 550 # bet pot
assert pot_raise_to(s, 0.5) == 275
def test_legalize():
s = doc_state()
assert legalize(s, Action.fold()) == Action.check() # fold when check free -> check
assert legalize(s, Action.call()) == Action.check()
assert legalize(s, Action.raise_to(1)) == Action.raise_to(100) # clamp up
assert legalize(s, Action.raise_to(10**9)) == Action.raise_to(9750)
assert legalize(s, Action("all_in")) == Action.raise_to(9750)
assert legalize(s, Action("bet", 300)) == Action.raise_to(300)
f = facing_bet_state()
assert legalize(f, Action.check()) == Action.fold()
f.legal.raise_ = None
assert legalize(f, Action.raise_to(500)) == Action.call()
assert is_legal(s, Action.raise_to(100)) and not is_legal(s, Action.raise_to(99)) and not is_legal(s, Action.call())
assert safe_action(f) == Action.fold()
def test_action_wire_format():
d = Action.raise_to(400).to_data("h-77", "d-77-9")
assert d == {"hand_id": "h-77", "decision_id": "d-77-9", "type": "raise", "to": 400}
assert Action.fold().to_data("h", "d") == {"hand_id": "h", "decision_id": "d", "type": "fold"}
def test_parse_action_text():
assert parse_action_text("I think we should RAISE TO 450.") == Action("raise", 450)
assert parse_action_text("ACTION: call") == Action.call()
assert parse_action_text("fold") == Action.fold()
assert parse_action_text("all-in!") == Action("all_in")
assert parse_action_text("no idea") is None
assert parse_action_text("call... actually raise 300") == Action("raise", 300)
def test_strength_and_position():
assert preflop_strength(["Ah", "Ad"]) >= 20 - 1 and preflop_strength(["As", "Ks"]) >= 10
assert preflop_strength(["7h", "2d"]) < 3
assert made_hand_category(["Ah", "Ad"], ["7c", "8d", "2s"]) == 1
assert made_hand_category(["Ah", "Kd"], ["7c", "8d", "2s"]) == 0
assert made_hand_category(["Ah", "Kd"], ["Ac", "Kc", "2s"]) == 2
assert made_hand_category(["Ah", "Kd"], ["Qc", "Jc", "Ts"]) == 3 # straight
s = doc_state()
s.players = [p for p in s.players]
assert position_name(s) in ("UTG", "SB", "BB", "BTN", "MP", "CO", "BTN/SB")
def test_render_state():
txt = render_state(facing_bet_state())
for needle in ("Ah Kd", "7c 8d 2s", "To call: 200", "raise (to an amount between 400 and 9750", "post_sb to 50"):
assert needle in txt
+180
View File
@@ -0,0 +1,180 @@
"""Pipe protocol (docs/TABLE_API.md section 14): `sharingan pipe`, the PipeRunner and `eval --local`."""
import io
import json
import os
import subprocess
import sys
import textwrap
import pytest
from sharingan import Action, Bot, cli
from sharingan.pipe import PipeRunner
from conftest import DOC_YOUR_TURN
HERE = os.path.dirname(os.path.abspath(__file__))
PKG_PARENT = os.path.dirname(HERE)
def turn_env(**over):
e = json.loads(json.dumps(DOC_YOUR_TURN))
e["data"]["hand_id"] = "h-77"
e.update(over)
return e
def lines(*envs):
return io.BytesIO(b"".join((json.dumps(e) + "\n").encode() for e in envs))
def run_runner(bot, *envs):
out = io.BytesIO()
rc = PipeRunner(bot, lines(*envs), out).run()
return rc, [json.loads(l) for l in out.getvalue().decode().splitlines()]
class Raiser(Bot):
name = "raiser"
def act(self, state):
return Action.raise_to(400)
def test_handshake_act_and_bye():
welcome = {"v": 1, "type": "welcome", "data": {"protocol": 1, "mode": "benchmark", "tables": ["t1"]}}
rc, out = run_runner(Raiser(), welcome, turn_env(), {"v": 1, "type": "bye", "data": {}})
assert rc == 0
assert [m["type"] for m in out] == ["hello", "act", "bye"]
assert out[0]["data"]["protocol"] == 1 and out[0]["data"]["bot"] == "raiser"
act = out[1]
assert act["table_id"] == "t1"
assert act["data"] == {"hand_id": "h-77", "decision_id": "d-77-9", "type": "raise", "to": 400}
def test_illegal_answer_is_legalized_and_exception_plays_check_fold():
class Wild(Bot):
def act(self, state):
return Action.raise_to(1) # below min_to=100 -> legalize clamps it
_, out = run_runner(Wild(), turn_env())
assert out[1]["data"]["type"] == "raise" and out[1]["data"]["to"] == 100
class Boom(Bot):
def act(self, state):
raise RuntimeError("bug in my bot")
_, out = run_runner(Boom(), turn_env())
assert out[1]["data"]["type"] == "check" # check is free in the doc example, else fold
class NotAnAction(Bot):
def act(self, state):
return "call"
_, out = run_runner(NotAnAction(), turn_env())
assert out[1]["data"]["type"] == "check"
def test_async_act_and_hooks_only_when_overridden():
seen = []
class A(Bot):
async def act(self, state):
return Action.call()
def on_hand_end(self, end):
seen.append(end.hand_id)
def on_connect(self, welcome):
seen.append(welcome["protocol"])
hand_end = {"v": 1, "type": "hand_end", "data": {"hand_id": "h-77", "results": [], "hole_cards": {"0": ["Ah", "Kd"]}}}
_, out = run_runner(A(), {"v": 1, "type": "welcome", "data": {"protocol": 1}}, turn_env(), hand_end)
assert seen == [1, "h-77"]
assert [m["type"] for m in out] == ["hello", "act"] # hand_end gets no answer
# a bot without on_hand_end: the payload is not even parsed (garbage-tolerant, fast)
_, out = run_runner(Raiser(), {"v": 1, "type": "hand_end", "data": "ignored"})
assert [m["type"] for m in out] == ["hello"]
def test_garbage_lines_are_skipped():
out = io.BytesIO()
src = io.BytesIO(b"not json\n\n" + (json.dumps(turn_env()) + "\n").encode())
PipeRunner(Raiser(), src, out).run()
assert [json.loads(l)["type"] for l in out.getvalue().decode().splitlines()] == ["hello", "act"]
def test_subprocess_keeps_stdout_clean(tmp_path):
"""`sharingan pipe` over real pipes: prints in the bot (import time and inside act) must not reach the protocol stream."""
bot = tmp_path / "chatty.py"
bot.write_text(textwrap.dedent("""
print("import-time noise")
from sharingan import Bot, Action
class Chatty(Bot):
def act(self, state):
print("act-time noise")
return Action.call() if state.legal.call else Action.check()
"""))
env = dict(os.environ, PYTHONPATH=PKG_PARENT)
p = subprocess.Popen([sys.executable, "-m", "sharingan.cli", "pipe", str(bot)], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
hello = json.loads(p.stdout.readline())
assert hello["type"] == "hello"
p.stdin.write((json.dumps({"v": 1, "type": "welcome", "data": {"protocol": 1}}) + "\n").encode())
p.stdin.write((json.dumps(turn_env()) + "\n").encode())
p.stdin.flush()
act = json.loads(p.stdout.readline())
assert act["type"] == "act" and act["data"]["type"] == "check"
p.stdin.write((json.dumps({"v": 1, "type": "bye", "data": {}}) + "\n").encode())
p.stdin.flush()
assert json.loads(p.stdout.readline())["type"] == "bye"
rest, err = p.communicate(timeout=10)
assert rest == b"" and p.returncode == 0
assert b"import-time noise" in err and b"act-time noise" in err
def test_eval_local_without_worker_prints_fallback(tmp_path, monkeypatch, capsys):
monkeypatch.delenv("SHARINGAN_ARENA_BIN", raising=False)
monkeypatch.setenv("PATH", str(tmp_path)) # no sharingan-arena here
bot = tmp_path / "b.py"
bot.write_text("from sharingan import Bot, Action\nclass B(Bot):\n def act(self, s):\n return Action.check()\n")
rc = cli.main(["eval", str(bot), "--local"])
err = capsys.readouterr().err
assert rc == 2
assert "sharingan-arena" in err and "PATH" in err and "cargo build --release -p sharingan-arena" in err
def test_eval_local_runs_the_worker_binary(tmp_path, monkeypatch, capsys):
"""A fake worker: checks the command line the SDK builds and writes a result.json."""
fake = tmp_path / "sharingan-arena"
fake.write_text(textwrap.dedent(f"""\
#!{sys.executable}
import json, sys
a = sys.argv[1:]
assert a[0] == "run", a
get = lambda k: a[a.index(k) + 1]
assert "sharingan.cli pipe" in get("--bot") and get("--bot").endswith("b.py'") or get("--bot").endswith("b.py")
json.dump({{"track": get("--track"), "hands": int(get("--hands")), "mbb_per_game": 12.5, "ci95_mbb": 3.0,
"method": "aivat", "forfeit_hands": 0, "timings": {{"hands_per_sec": 1234.0}}}}, open(get("--out"), "w"))
"""))
fake.chmod(0o755)
monkeypatch.setenv("SHARINGAN_ARENA_BIN", str(fake))
bot = tmp_path / "b.py"
bot.write_text("from sharingan import Bot, Action\nclass B(Bot):\n def act(self, s):\n return Action.check()\n")
rc = cli.main(["eval", str(bot), "--local", "--track", "sharingan-1", "--hands", "600", "--lanes", "4"])
out = capsys.readouterr().out
assert rc == 0
assert "+12.5 ± 3.0 mbb/game" in out and "600 hands on sharingan-1" in out and "local" in out
@pytest.mark.skipif(not (cli.find_worker() and os.environ.get("ARENA_BLUEPRINT")), reason="needs sharingan-arena on PATH and ARENA_BLUEPRINT")
def test_eval_local_end_to_end_with_the_real_worker(tmp_path, capsys):
bot = tmp_path / "station.py"
bot.write_text("from sharingan import Bot\nfrom sharingan.helpers import call_or_check\nclass S(Bot):\n def act(self, s):\n return call_or_check(s)\n")
out = tmp_path / "r.json"
rc = cli.main(["eval", str(bot), "--local", "--hands", "600", "--lanes", "2", "--out", str(out), "--quiet"])
assert rc == 0
r = json.loads(out.read_text())
assert r["hands"] == 600 and r["forfeit_hands"] == 0 and r["method"] == "aivat"
assert "mbb/game" in capsys.readouterr().out