diff --git a/mock/logschreiber.py b/mock/logschreiber.py
index 50d34d7..4646c13 100644
--- a/mock/logschreiber.py
+++ b/mock/logschreiber.py
@@ -5,7 +5,8 @@ Grundlage ist `vorlage/hand-beispiel.txt`, eine echte Hand. Beim Abspielen werde
nur Raum, Tischnummer, Sitznummern und Zeitstempel ersetzt; alles andere bleibt
Zeichen für Zeichen die Aufnahme. Am eigenen Zug (`game.user_turn` mit Zugoptionen)
hält der Lauf an, bis `aktion()` kommt, schreibt dann die eigene Aktionszeile
-(`game.seat`, Beschriftung aus dem Klick, Beträge aus der Aufnahme) und spielt weiter.
+(`game.user_action` wie im Archiv, dann `game.seat` mit der Beschriftung aus dem Klick
+und den Beträgen der Aufnahme) und spielt weiter.
from logschreiber import Logschreiber, Handlauf
"""
@@ -221,6 +222,9 @@ class Handlauf(threading.Thread):
else:
d["caption"] = "Raise"
d["newCaption"] = "Raise" if zug.get("roundMaxBet") else "Bet"
+ # Was der echte Client beim eigenen Klick sendet - Form aus dem Archiv
+ self.schreiber.schreiben("[Method] -> SendExtensionMessageToConnector - RoomName "
+ f"{self.raum} RequestId - game.user_action")
zeile = mit_bohne(vorbild, d)
if not STEMPEL.match(zeile):
zeile = "2000-01-01 00:00:00:000 [info] [UNITY] Stdout: " + zeile
diff --git a/mock/seiten/lobby.html b/mock/seiten/lobby.html
index df10b6f..966041c 100644
--- a/mock/seiten/lobby.html
+++ b/mock/seiten/lobby.html
@@ -29,6 +29,9 @@
.button { border: 0; border-radius: 6px; padding: 6px 14px; cursor: pointer; font: inherit; }
.button-module__primary___C1vVV { background: #1fae64; color: #fff; }
.quick-join-button { background: #2b3045; color: #fff; }
+ .table-seat-progress { display: inline-flex; gap: 3px; margin-left: 8px; vertical-align: middle; }
+ .table-seat-progress__seat { width: 6px; height: 6px; border-radius: 50%; background: #1fae64; }
+ .table-seat-progress__seat--empty { background: #3a3f52; }
.lobby-footer { display: flex; gap: 16px; padding: 8px 16px; color: #778; font-size: 12px; }
@@ -85,7 +88,7 @@ function zeile(t) {
r.className = "table-row";
r.dataset.tableId = t.id;
r.innerHTML = `
-
+
Join
`;
r.querySelector(".game-info").textContent = t.id;
r.querySelector("button").addEventListener("click", () => {
@@ -106,7 +109,10 @@ async function laden() {
let r = liste.querySelector(`[data-table-id="${CSS.escape(t.id)}"]`);
if (!r) { r = zeile(t); liste.appendChild(r); }
r.querySelector(".avg-stack").textContent = t.schnitt;
- r.querySelector(".players").textContent = `${t.spieler}/6`;
+ r.querySelector(".player-count").textContent = `${t.spieler}/6`;
+ const sitze = r.querySelector(".table-seat-progress");
+ sitze.innerHTML = Array.from({length: 6}, (_, i) =>
+ ` `).join("");
}
} catch (e) { /* Server weg - nichts zu tun */ }
}
diff --git a/mock/seiten/table.html b/mock/seiten/table.html
index 37a8359..33115a5 100644
--- a/mock/seiten/table.html
+++ b/mock/seiten/table.html
@@ -37,19 +37,21 @@
.betrag { position: absolute; transform: translate(-50%, -50%); width: 9vw; height: 4.4vh; text-align: center;
background: #0d0f15; color: #fff; border: 1px solid #333; border-radius: 6px; }
.dialog-backdrop { position: absolute; inset: 0; background: rgba(0,0,0,.55); display: none; }
- .sfs-buy-in-modal { position: absolute; left: 50%; top: 45%; transform: translate(-50%, -50%); width: 380px;
+ .sfs-buy-in-modal { position: absolute; width: 380px; box-sizing: border-box;
background: #1b1e29; border-radius: 12px; padding: 18px; display: none; }
.sfs-buy-in-header { display: flex; justify-content: space-between; align-items: center; }
- .sfs-buy-in-heading { font-size: 20px; font-weight: 700; }
+ .sfs-buy-in-heading { font-size: 20px; font-weight: 700; margin: 0; }
.sfs-buy-in-header-game-info { color: #99a; margin: 6px 0 14px; }
.sfs-buy-in-balance-container { display: flex; justify-content: space-between; margin-bottom: 12px; }
.sfs-buy-in-user-balance { color: #f5c542; font-weight: 700; }
.sfs-slider-range-value { width: 100%; box-sizing: border-box; padding: 8px; font-size: 18px; text-align: center;
background: #0d0f15; color: #fff; border: 1px solid #333; border-radius: 6px; }
.sfs-buy-in-body-range-buttons { display: flex; justify-content: space-between; margin: 10px 0 16px; }
- .sfs-buy-in-body-range-buttons [role=button], .sfs-buy-in-modal-button {
- background: #2b3045; border-radius: 6px; padding: 6px 16px; cursor: pointer; }
- .sfs-buy-in-modal-button { background: #1fae64; text-align: center; font-weight: 700; padding: 10px; }
+ .sfs-buy-in-body-range-buttons button, .sfs-buy-in-modal-button {
+ background: #2b3045; color: #fff; border: 0; border-radius: 6px; padding: 6px 16px; cursor: pointer;
+ font: inherit; }
+ .sfs-buy-in-modal-button-container { padding: 6px 40px; }
+ .sfs-buy-in-modal-button { background: #1fae64; font-weight: 700; padding: 10px; width: 100%; }
.sfs-buy-in-body-error { color: #ff6b6b; min-height: 1em; font-size: 12px; }
.common-dialog-cross-icon { cursor: pointer; font-size: 22px; }
@@ -67,7 +69,7 @@
diff --git a/mock/start.py b/mock/start.py
index 75114ce..60bc38a 100644
--- a/mock/start.py
+++ b/mock/start.py
@@ -68,6 +68,22 @@ def chrome_starten(pfad, cdp_port, url, headless):
raise SystemExit(f"Chrome antwortet nicht am Debug-Port {cdp_port}")
+def reste(profil):
+ """PIDs aller Prozesse, deren Befehlszeile den Profilordner nennt - Chrome samt Helfern.
+
+ Die eine PID reicht nicht: ein Chrome kann Helfer überleben lassen, und unter
+ Windows lässt sich ein Chrome-Prozess nicht zuverlässig nach seinem Zustand fragen.
+ """
+ if sys.platform == "win32":
+ befehl = ["powershell", "-NoProfile", "-Command",
+ "Get-CimInstance Win32_Process | Where-Object { $_.ProcessId -ne $PID -and "
+ f"$_.CommandLine -like '*{profil}*' }} | ForEach-Object {{ $_.ProcessId }}"]
+ else:
+ befehl = ["pgrep", "-f", "--", profil]
+ r = subprocess.run(befehl, capture_output=True, text=True)
+ return [int(p) for p in r.stdout.split() if p.isdigit() and int(p) != os.getpid()]
+
+
def chrome_beenden(proc, profil, cdp_port):
try:
with cdp.Verbindung(cdp.browser_ws(cdp_port), frist=3) as b:
@@ -79,6 +95,16 @@ def chrome_beenden(proc, profil, cdp_port):
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
+ for _ in range(10):
+ uebrig = reste(profil)
+ if not uebrig:
+ break
+ for pid in uebrig:
+ try:
+ os.kill(pid, signal.SIGTERM if sys.platform == "win32" else signal.SIGKILL)
+ except OSError:
+ pass
+ time.sleep(0.3)
for _ in range(50): # Windows gibt Dateien erst nach und nach frei
shutil.rmtree(profil, ignore_errors=True)
if not os.path.exists(profil):
diff --git a/tests/mock_spec.py b/tests/mock_spec.py
index c1d7e75..6e87f61 100644
--- a/tests/mock_spec.py
+++ b/tests/mock_spec.py
@@ -11,8 +11,15 @@ Werkzeuge es täten:
* eine Hand läuft und hält am eigenen Zug an
* ein Mausklick an der README-Stelle von `Call` wird geschrieben und von
hand/nachsehen.py belegt
+ * jedes bedienbare Element ist über seinen Text erreichbar (Auswahl wie
+ lobby/cdp.mjs --click) und trifft einen bzw. role="button"
* danach ist alles weg: Server, Chrome, Profilordner, Logdatei
+Kettentest (nur macOS, nur sichtbare Fenster) - ausschließlich unsere Werkzeuge:
+ lobby/cdp.mjs --click "Join" -> hand/fenster.py (COINPOKER_MOCK=1) findet das Fenster
+ -> hand/click.py klickt + und Buy-In -> betrieb/runner.py --live --act mit
+ COINPOKER_LOG auf die Klonlogdatei -> Aktion geschrieben und von nachsehen belegt.
+
python3 tests/mock_spec.py -v
MOCK_HEADLESS=1 python3 tests/mock_spec.py -v # ohne sichtbares Fenster
"""
@@ -41,9 +48,14 @@ for _u in ("hand", "lesen", "mcp", "mock"):
import cdp
import lobby_adapter
+import start
import nachsehen
START = os.path.join(WURZEL, "mock", "start.py")
+CDP_MJS = os.path.join(WURZEL, "lobby", "cdp.mjs")
+RUNNER = os.path.join(WURZEL, "betrieb", "runner.py")
+SHADOW = os.path.join(WURZEL, "betrieb", "scratch", "shadow.jsonl")
+STOPP = os.path.join(WURZEL, "hand", "scratch", "stop")
VORLAGE = os.path.join(WURZEL, "mock", "vorlage", "dom-lobby.json")
HELD = "mmintel"
@@ -52,7 +64,8 @@ VOLL = "Big Ben 123458" # 6/6
# Anteil des Fensterrahmens, aus mock/vorlage/README.md
STELLE = {"fold": (0.66, 0.94), "call": (0.80, 0.94), "raise": (0.93, 0.94),
- "plus": (0.14, 0.24)}
+ "plus": (0.14, 0.24),
+ "buyin": (0.50, 0.62)} # Buy-In im Dialog: festgelegt vom Klon (Bild fehlt)
ZEILEN_JS = """(() => {
const rows = [...document.querySelectorAll(".table-row")];
@@ -62,6 +75,23 @@ ZEILEN_JS = """(() => {
})));
})()"""
+# Wählt das Ziel genau wie lobby/cdp.mjs --click: kleinster sichtbarer Knoten mit
+# exakt dem Text, sonst mit dem Text am Anfang. Meldet, ob es ein Bedienelement trifft.
+TEXTZIEL_JS = """((text) => {
+ const wollen = text.trim().toLowerCase();
+ const flaeche = (n) => { const r = n.getBoundingClientRect(); return r.width * r.height; };
+ const alle = [...document.querySelectorAll('button, a, [role="button"], span, div, li')]
+ .filter((n) => n.offsetParent !== null && (n.innerText || "").trim().length > 0);
+ const genau = alle.filter((n) => (n.innerText || "").trim().toLowerCase() === wollen)
+ .sort((a, b) => flaeche(a) - flaeche(b));
+ const teil = alle.filter((n) => (n.innerText || "").trim().toLowerCase().startsWith(wollen))
+ .sort((a, b) => flaeche(a) - flaeche(b));
+ const ziel = genau[0] || teil[0];
+ if (!ziel) return "nichts";
+ const knopf = ziel.closest('button, [role="button"]');
+ return knopf ? "knopf:" + knopf.innerText.trim() : "kein knopf: " + ziel.tagName + "." + ziel.className;
+})(__TEXT__)"""
+
KLASSEN_JS = """(() => JSON.stringify([...new Set([...document.querySelectorAll('*')]
.flatMap(e => [...e.classList]))].sort()))()"""
@@ -78,26 +108,6 @@ def port_offen(port):
return s.connect_ex(("127.0.0.1", port)) == 0
-def prozess_lebt(pid):
- if sys.platform == "win32":
- import ctypes
- k = ctypes.windll.kernel32
- h = k.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
- if not h:
- return False
- code = ctypes.c_ulong()
- k.GetExitCodeProcess(h, ctypes.byref(code))
- k.CloseHandle(h)
- return code.value == 259 # STILL_ACTIVE
- try:
- os.kill(pid, 0)
- except ProcessLookupError:
- return False
- except PermissionError:
- return True
- return True
-
-
def warte(bedingung, frist, was):
ende = time.time() + frist
while time.time() < ende:
@@ -168,6 +178,9 @@ class Tischseite:
assert punkt, f"kein sichtbarer Knopf '{text}'"
self.klick(*punkt)
+ def textziel(self, text):
+ return self.js(TEXTZIEL_JS.replace("__TEXT__", json.dumps(text)))
+
def leiste(self):
return self.js("[...document.querySelectorAll('.aktionsleiste button')]"
".filter(n => n.offsetParent !== null).map(n => n.innerText.trim())"
@@ -250,6 +263,11 @@ class Klon(unittest.TestCase):
echte = set(json.load(h)["klassen"])
fremd = set(json.loads(lobby.js(KLASSEN_JS))) - echte
self.assertFalse(fremd, f"Klassen, die es in der echten Lobby nicht gibt: {fremd}")
+ aufbau = json.loads(lobby.js("""JSON.stringify([...document.querySelectorAll('.table-row')]
+ .map(r => [!!r.dataset.tableId, !!r.querySelector('.players'),
+ [...r.querySelectorAll('button')].filter(b => b.innerText.trim() === 'Join').length]))"""))
+ self.assertTrue(aufbau and all(a == [True, True, 1] for a in aufbau), aufbau)
+ self.assertEqual(lobby.textziel("Join"), "knopf:Join")
# 2. Join öffnet ein Fenster mit dem Tischtitel
vorher = {t["id"] for t in cdp.ziele(self.cdp_port)}
@@ -269,6 +287,8 @@ class Klon(unittest.TestCase):
voll = self.seite(self.ziel(lambda t: t["id"] not in vorher
and t.get("title") == "NLH 123458 - 1K/2K", "voller Tisch"))
warte(lambda: voll.leiste() == "Find Seat|Join Wait List", 10, "Leiste Find Seat")
+ for text in ("Find Seat", "Join Wait List"):
+ self.assertEqual(voll.textziel(text), "knopf:" + text)
self.assertEqual(voll.js("document.querySelectorAll('.platz-frei').length"), 0)
# 3. + an der README-Stelle -> Buy-in -> Platz
@@ -276,6 +296,7 @@ class Klon(unittest.TestCase):
"ein freier Platz")
x, y = tisch.punkt(*STELLE["plus"])
self.assertEqual(tisch.text_bei(x, y), "+")
+ self.assertEqual(tisch.textziel("+"), "knopf:+")
tisch.klick(x, y)
warte(lambda: tisch.js("!!document.querySelector('.sfs-buy-in-modal')?.offsetParent"),
5, "Buy-in-Dialog")
@@ -286,8 +307,12 @@ class Klon(unittest.TestCase):
"JSON.stringify([...document.querySelectorAll('.sfs-buy-in-modal, "
".sfs-buy-in-modal *')].flatMap(e => [...e.classList]))"))) - echte
self.assertFalse(fremd, f"Dialogklassen ohne Vorbild: {fremd}")
+ for text in ("Buy-In", "Min", "Max"):
+ self.assertEqual(tisch.textziel(text), "knopf:" + text, "Überschrift funkt dazwischen?")
tisch.klick_text("Max")
- tisch.klick_text("Buy-In")
+ bx, by = tisch.punkt(*STELLE["buyin"])
+ self.assertEqual(tisch.text_bei(bx, by), "Buy-In")
+ tisch.klick(bx, by)
def sitz():
for cmd, d in befehle(log_text(self.log), TISCH):
@@ -319,20 +344,117 @@ class Klon(unittest.TestCase):
px, py = tisch.punkt(*STELLE[name])
self.assertTrue(tisch.text_bei(px, py).lower().startswith(name),
f"{name} liegt nicht bei {STELLE[name]}: {tisch.text_bei(px, py)!r}")
+ self.assertTrue(tisch.textziel(name.capitalize()).startswith(
+ "knopf:" + name.capitalize()), tisch.textziel(name.capitalize()))
# 5. Klick auf Call -> Aktionszeile, belegt
ab = os.path.getsize(self.log)
tisch.klick(*tisch.punkt(*STELLE["call"]))
ok, beleg = nachsehen.bestaetigt(self.log, ab, TISCH, frist=5.0)
self.assertTrue(ok, beleg)
- with open(self.log, encoding="utf-8") as h:
- h.seek(ab)
- neu = h.read()
+
+ def ab_klick():
+ with open(self.log, encoding="utf-8") as h:
+ h.seek(ab)
+ return h.read()
+ neu = warte(lambda: "game.advance_player_action" in ab_klick() and ab_klick(), 10,
+ "Zugübergabe nach dem Klick")
eigene = [d for c, d in befehle(neu, TISCH) if c == "game.seat" and d["userName"] == HELD]
self.assertTrue(eigene, "keine eigene Aktionszeile nach dem Klick")
self.assertIn(eigene[0]["caption"], ("Call", "Check"))
+ self.assertIn(f"RoomName {TISCH} RequestId - game.user_action", neu)
+ self.assertIn("game.advance_player_action", neu)
warte(lambda: "Call Any" in tisch.leiste(), 10, "Leiste Call Any / X/F / Call")
+ def test_kette(self):
+ """Nur unsere Werkzeuge: cdp.mjs, fenster.py, click.py, runner.py, nachsehen."""
+ try:
+ self._kette()
+ finally:
+ self._aufraeumen()
+ self._nichts_uebrig()
+
+ def _kette(self):
+ if os.environ.get("MOCK_HEADLESS") == "1":
+ self.skipTest("Kettentest braucht sichtbare Fenster")
+ self.bereit()
+ umgebung = dict(os.environ, CDP_PORT=str(self.cdp_port))
+ r = subprocess.run(["node", CDP_MJS, "--click", "Join"], env=umgebung,
+ capture_output=True, text=True, encoding="utf-8", timeout=20)
+ self.assertIn("geklickt: Join", r.stdout, r.stdout + r.stderr)
+ self.ziel(lambda t: t.get("title") == "NLH 123456 - 1K/2K", "Tischfenster nach cdp.mjs")
+ if sys.platform != "darwin":
+ self.skipTest("hand/fenster.py und hand/click.py sind macOS-Werkzeuge "
+ "(osascript, CoreGraphics) - Kette ab hier nur auf dem Mac")
+ self.assertFalse(os.path.exists(STOPP), f"Not-Aus gesetzt: {STOPP}")
+
+ os.environ["COINPOKER_MOCK"] = "1"
+ import click
+ import fenster
+ f = warte(lambda: fenster.fenster_fuer(TISCH), 10, "fenster.py findet den Tisch am Titel")
+ self.assertEqual(f["tisch"], "123456")
+ self.assertTrue(f["tischfenster"])
+ x, y, w, h = f["rect"]
+
+ def klick(stelle):
+ fx, fy = STELLE[stelle]
+ click.click(round(x + w * fx), round(y + h * fy), pid=f["pid"])
+
+ def dialog_offen():
+ # nur lesen, nicht klicken
+ tisch = next(t for t in cdp.ziele(self.cdp_port) if t.get("title", "").startswith("NLH 123456"))
+ with cdp.Verbindung(tisch["webSocketDebuggerUrl"]) as v:
+ return cdp.auswerten(v, "!!document.querySelector('.sfs-buy-in-modal')?.offsetParent")
+
+ for _ in range(5): # das frische Fenster kann noch unterwegs sein
+ klick("plus")
+ try:
+ warte(dialog_offen, 1.5, "Buy-in-Dialog")
+ break
+ except AssertionError:
+ f = fenster.fenster_fuer(TISCH) or f
+ x, y, w, h = f["rect"]
+ else:
+ self.fail("+ per click.py öffnet den Buy-in nicht")
+
+ shadow_vorher = os.path.getsize(SHADOW) if os.path.exists(SHADOW) else None
+ runner = subprocess.Popen(
+ [sys.executable, RUNNER, "--live", "--act"], stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace",
+ env=dict(os.environ, COINPOKER_LOG=self.log, COINPOKER_MOCK="1", PYTHONUNBUFFERED="1"))
+ try:
+ klick("buyin")
+ warte(lambda: f'"Cmd":"game.seatInfo","RoomName":"{TISCH}"' in log_text(self.log),
+ 10, "Sitzzeile nach Buy-In per click.py")
+
+ def gebucht():
+ if not os.path.exists(SHADOW):
+ return None
+ with open(SHADOW, encoding="utf-8") as h:
+ h.seek(shadow_vorher or 0)
+ eintraege = [json.loads(z) for z in h.read().splitlines() if z.strip()]
+ return next((e for e in eintraege if e.get("geklickt")), None)
+ eintrag = warte(gebucht, 90, "runner.py klickt einen eigenen Zug")
+ finally:
+ runner.terminate()
+ ausgabe = runner.communicate(timeout=10)[0]
+ if shadow_vorher is None:
+ if os.path.exists(SHADOW):
+ os.remove(SHADOW)
+ else:
+ with open(SHADOW, "r+", encoding="utf-8") as h:
+ h.truncate(shadow_vorher)
+ self.assertTrue(eintrag["beleg"].startswith("Beleg"), (eintrag, ausgabe))
+ warte(lambda: "game.advance_player_action" in log_text(self.log).split(
+ "game.user_action", 1)[-1], 10, "Zugübergabe nach der Aktion")
+ text = log_text(self.log)
+ aktion = text.find(f"RoomName {TISCH} RequestId - game.user_action")
+ self.assertGreater(aktion, 0, "keine Aktionszeile im Klonlog")
+ nachher = befehle(text[aktion:], TISCH)
+ self.assertTrue(any(c == "game.seat" and d["userName"] == HELD for c, d in nachher))
+ self.assertIn("game.advance_player_action", [c for c, _ in nachher],
+ "keine Zugübergabezeile nach der Aktion")
+
def _aufraeumen(self):
for s in self.seiten:
try:
@@ -358,11 +480,12 @@ class Klon(unittest.TestCase):
self.assertEqual(self.proc.returncode, 0, "Klon nicht sauber beendet")
self.assertFalse(port_offen(self.port), "Server läuft noch")
self.assertFalse(port_offen(self.cdp_port), "Chrome-Debug-Port noch offen")
- pid = int(self.angaben.get("Chrome-PID", "0") or 0)
- self.assertTrue(pid, "Klon hat keine Chrome-PID genannt")
- warte(lambda: not prozess_lebt(pid), 10, "Chrome beendet")
+ self.assertTrue(self.angaben.get("Chrome-PID"), "Klon hat keine Chrome-PID genannt")
profil = self.angaben.get("Profil", "")
- self.assertTrue(profil and not os.path.exists(profil), f"Profilordner übrig: {profil}")
+ self.assertIn(start.PROFIL_PRAEFIX, profil)
+ warte(lambda: not start.reste(profil), 10, "kein Chrome-Prozess mit dem Klonprofil")
+ time.sleep(1.0) # ein überlebender Chrome legte den Ordner neu an
+ self.assertFalse(os.path.exists(profil), f"Profilordner übrig: {profil}")
self.assertFalse(os.path.exists(self.log), "Logdatei übrig")