Initialize local project and fix ranch growth synchronization
This commit is contained in:
@@ -0,0 +1,259 @@
|
||||
import copy
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import json
|
||||
from pathlib import Path
|
||||
from contextlib import contextmanager
|
||||
import shutil
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
import uuid
|
||||
from unittest.mock import patch
|
||||
|
||||
import requests
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
from ranch_assistant.api import ApiError, Client, DEFAULT_KEY, Session, decode, encode
|
||||
from ranch_assistant.engine import Engine, demo_snapshot
|
||||
from ranch_assistant.farming import FarmBudget, FarmConfig, FarmRunner, matches
|
||||
from ranch_assistant.model import Catalog, Planner, Policy, Snapshot
|
||||
|
||||
|
||||
@contextmanager
|
||||
def workspace_temp():
|
||||
root = Path(__file__).resolve().parents[2] / "test-artifacts"
|
||||
folder = root / uuid.uuid4().hex
|
||||
folder.mkdir(parents=True)
|
||||
try:
|
||||
yield folder
|
||||
finally:
|
||||
target = folder.resolve()
|
||||
if target.parent != root.resolve():
|
||||
raise RuntimeError("Unexpected test cleanup path")
|
||||
shutil.rmtree(target)
|
||||
|
||||
|
||||
class CoreTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.catalog = Catalog()
|
||||
|
||||
def snapshot(self):
|
||||
return demo_snapshot(self.catalog)
|
||||
|
||||
def test_catalog_and_quality_boundaries(self):
|
||||
self.assertEqual(len(self.catalog.monsters), 749)
|
||||
mon = self.snapshot().raw["monsters"][0]
|
||||
row = self.catalog.monster(mon["typeId"])
|
||||
for fraction, expected in ((0, 1), (.25, 2), (.5, 3), (.75, 4), (1, 4)):
|
||||
for stat in ("atk", "def", "hp", "dex"):
|
||||
mon["g" + stat.capitalize()] = row[stat + "_grow_min"] + fraction * (row[stat + "_grow_max"] - row[stat + "_grow_min"])
|
||||
# The client rounds growth values to three decimals first.
|
||||
self.assertEqual(self.catalog.quality(mon), [expected] * 4)
|
||||
mon.pop("gAtk")
|
||||
self.assertIsNone(self.catalog.quality(mon)[0])
|
||||
|
||||
def test_locked_team_and_existing_monsters_are_preserved(self):
|
||||
snapshot = self.snapshot()
|
||||
planner = Planner(self.catalog)
|
||||
policy = Policy(strategy="gold", protect_star=6, protect_quality=5, fill=False)
|
||||
snapshot.raw["monsters"][0]["lock"] = 1
|
||||
snapshot.raw["teams"][0]["monsters"].append(snapshot.raw["monsters"][1]["id"])
|
||||
plans = planner.plan(snapshot, policy)
|
||||
self.assertFalse(any(a.kind in ("feed", "sell") for a in plans))
|
||||
self.assertNotIn(900, planner.managed)
|
||||
|
||||
def test_collection_then_feed_with_target_cap(self):
|
||||
snapshot = self.snapshot()
|
||||
planner = Planner(self.catalog)
|
||||
policy = Policy(strategy="experience", protect_star=6, protect_quality=5, feed_target=900, fill=False)
|
||||
first = planner.plan(snapshot, policy)[0]
|
||||
self.assertEqual(first.kind, "collect")
|
||||
mon = snapshot.raw["monsters"][0]
|
||||
mon.update(process=3, roomId=1)
|
||||
snapshot.raw["stacks"][0]["monsterId"] = 0
|
||||
plans = planner.plan(snapshot, policy)
|
||||
self.assertEqual(plans[0].kind, "feed")
|
||||
self.assertEqual(plans[0].payload, {"targetId": 900, "foods": [mon["id"]]})
|
||||
snapshot.monsters[900]["level"] = policy.target_level
|
||||
self.assertFalse(any(a.kind == "feed" for a in planner.plan(snapshot, policy)))
|
||||
|
||||
def test_unknown_quality_never_sold(self):
|
||||
snapshot = self.snapshot()
|
||||
for mon in snapshot.raw["monsters"]:
|
||||
mon.pop("gHp", None)
|
||||
plans = Planner(self.catalog).plan(snapshot, Policy(strategy="gold", protect_star=6, protect_quality=5, fill=False))
|
||||
self.assertTrue(all(a.kind != "sell" for a in plans))
|
||||
|
||||
def test_reserved_eggs_and_vip_slot(self):
|
||||
snapshot = self.snapshot()
|
||||
for slot in snapshot.raw["stacks"]:
|
||||
slot["monsterId"] = 0
|
||||
snapshot.raw["monsters"] = []
|
||||
egg = snapshot.raw["items"][0]
|
||||
snapshot.raw["items"] = [egg]
|
||||
egg["num"] = 2
|
||||
policy = Policy(reserved_eggs={str(egg["typeId"]): 1})
|
||||
plans = Planner(self.catalog).plan(snapshot, policy)
|
||||
self.assertEqual(len(plans), 1)
|
||||
self.assertNotEqual(plans[0].payload["eggs"][0]["stackId"], 4)
|
||||
egg["num"] = 10
|
||||
plans = Planner(self.catalog).plan(snapshot, Policy())
|
||||
self.assertEqual(len(plans), 5)
|
||||
self.assertNotIn(4, [p.payload["eggs"][0]["stackId"] for p in plans])
|
||||
|
||||
def test_room_full_blocks_collecting(self):
|
||||
snapshot = self.snapshot()
|
||||
snapshot.raw["rooms"] = []
|
||||
plans = Planner(self.catalog).plan(snapshot, Policy(strategy="keep", fill=False))
|
||||
self.assertEqual(plans, [])
|
||||
|
||||
def test_null_vip_info_does_not_block_snapshot_preview(self):
|
||||
snapshot = self.snapshot()
|
||||
snapshot.raw["activityHistory"]["vipInfo"] = None
|
||||
for slot in snapshot.raw["stacks"]:
|
||||
slot["monsterId"] = 0
|
||||
snapshot.raw["monsters"] = []
|
||||
self.assertTrue(Planner(self.catalog).plan(snapshot, Policy()))
|
||||
|
||||
def test_policy_error_returns_fetched_data_and_stops_actions(self):
|
||||
engine = Engine(self.catalog)
|
||||
engine.snapshot = self.snapshot()
|
||||
engine.auto = True
|
||||
with patch.object(engine, "plans", side_effect=ValueError("invalid policy")):
|
||||
snapshot, plans, message = engine.poll()
|
||||
self.assertIs(snapshot, engine.snapshot)
|
||||
self.assertEqual(plans, [])
|
||||
self.assertFalse(engine.auto)
|
||||
self.assertIn("策略暂不可用", message)
|
||||
|
||||
def test_codec_and_har_resume(self):
|
||||
payload = {"token": "local-test", "reqid": 42, "reqsid": 43, "text": "魔物"}
|
||||
self.assertEqual(decode(encode(payload, DEFAULT_KEY), DEFAULT_KEY), payload)
|
||||
har = {"log": {"entries": [{"request": {"url": "http://127.0.0.1/game/masterService/masterQueryDetail", "postData": {"text": encode(payload, DEFAULT_KEY).decode()}}}]}}
|
||||
session = Session.imported(har)
|
||||
self.assertEqual(session.reqid, 43)
|
||||
self.assertEqual(session.reqsid, 44)
|
||||
self.assertEqual(session.server_url, "http://127.0.0.1/game/")
|
||||
|
||||
def test_writes_not_retried_or_secrets_logged(self):
|
||||
client = Client(Session("http://127.0.0.1/", "private-token"))
|
||||
with patch.object(client.http, "post", side_effect=requests.Timeout("private-token")) as post:
|
||||
with self.assertRaises(ApiError) as raised:
|
||||
client.call("monsterService/monsterSell", {"monsterIds": [1]})
|
||||
self.assertEqual(post.call_count, 1)
|
||||
self.assertNotIn("private-token", str(raised.exception))
|
||||
|
||||
def test_budget_stamina_tickets_stale_and_persistent_daily_limit(self):
|
||||
snapshot = self.snapshot()
|
||||
config = FarmConfig(daily_limit=1)
|
||||
with workspace_temp() as folder:
|
||||
budget = FarmBudget(Path(folder) / "runs.json")
|
||||
self.assertTrue(budget.check(snapshot, config, self.catalog)[0])
|
||||
snapshot.raw["master"]["ti"] = 5
|
||||
self.assertFalse(budget.check(snapshot, config, self.catalog)[0])
|
||||
snapshot.raw["master"]["ti"] = 100
|
||||
snapshot.raw["items"] = []
|
||||
self.assertFalse(budget.check(snapshot, config, self.catalog)[0])
|
||||
snapshot = self.snapshot()
|
||||
snapshot.received_at -= 60
|
||||
self.assertFalse(budget.check(snapshot, config, self.catalog)[0])
|
||||
snapshot.received_at = time.time()
|
||||
budget.reserve(snapshot, config)
|
||||
restarted = FarmBudget(Path(folder) / "runs.json")
|
||||
self.assertFalse(restarted.check(snapshot, config, self.catalog)[0])
|
||||
|
||||
def test_farm_screen_gate_and_real_tap_sequence(self):
|
||||
with workspace_temp() as folder:
|
||||
folder = Path(folder)
|
||||
blank = Image.new("RGB", (200, 400), "black")
|
||||
ready, victory = blank.copy(), blank.copy()
|
||||
draw = ImageDraw.Draw(ready)
|
||||
draw.rectangle((10, 10, 99, 39), fill="green")
|
||||
draw.rectangle((20, 300, 99, 349), fill="red")
|
||||
ImageDraw.Draw(victory).rectangle((100, 200, 179, 249), fill="blue")
|
||||
boxes = {"stage": (10, 10, 100, 40), "entry": (20, 300, 100, 350), "victory": (100, 200, 180, 250)}
|
||||
templates = {}
|
||||
for name, box in boxes.items():
|
||||
(victory if name == "victory" else ready).crop(box).save(folder / f"{name}.png")
|
||||
templates[name] = {"screen": [200, 400], "box": box, "file": name + ".png", "stage_id": "bd00"}
|
||||
class FakeAdb:
|
||||
image = ready
|
||||
taps = []
|
||||
def foreground(self): return True
|
||||
def screenshot(self): return self.image
|
||||
def tap(self, x, y): self.taps.append((x, y))
|
||||
adb = FakeAdb()
|
||||
runner = FarmRunner(adb, self.catalog, folder)
|
||||
runner.config = FarmConfig(templates=templates)
|
||||
runner.start()
|
||||
bad = ready.copy()
|
||||
ImageDraw.Draw(bad).rectangle(boxes["stage"], fill="black")
|
||||
adb.image = bad
|
||||
runner.tick(self.snapshot())
|
||||
self.assertEqual(adb.taps, [])
|
||||
adb.image = ready
|
||||
with patch("ranch_assistant.farming.time.monotonic", return_value=10): runner.tick(self.snapshot())
|
||||
self.assertEqual(len(adb.taps), 1)
|
||||
adb.image = victory
|
||||
with patch("ranch_assistant.farming.time.monotonic", return_value=13): runner.tick(self.snapshot())
|
||||
adb.image = ready
|
||||
with patch("ranch_assistant.farming.time.monotonic", return_value=16): runner.tick(self.snapshot())
|
||||
self.assertEqual(runner.completed, 1)
|
||||
self.assertEqual(len(adb.taps), 2)
|
||||
|
||||
|
||||
class WireIntegrationTests(unittest.TestCase):
|
||||
def test_encrypted_http_read_mature_settle_sell_refresh(self):
|
||||
catalog = Catalog()
|
||||
state = demo_snapshot(catalog).raw
|
||||
for mon in state["monsters"]:
|
||||
if mon.get("process") == 2:
|
||||
mon["mode"] = 0
|
||||
mon["timeStart"] = 1
|
||||
calls = []
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *args): pass
|
||||
def do_POST(self):
|
||||
body = decode(self.rfile.read(int(self.headers["Content-Length"])), DEFAULT_KEY)
|
||||
calls.append((self.path, body))
|
||||
if self.path.endswith("stackCheckProcess"):
|
||||
for mon in state["monsters"]:
|
||||
if mon.get("process") == 2: mon["mode"] = 2
|
||||
response = {"resCode": 0}
|
||||
elif self.path.endswith("monsterSell"):
|
||||
mid = body["monsterId"][0]
|
||||
state["monsters"] = [m for m in state["monsters"] if m["id"] != mid]
|
||||
for slot in state["stacks"]:
|
||||
if slot["monsterId"] == mid: slot["monsterId"] = 0
|
||||
response = {"resCode": 0, "money": 150}
|
||||
else:
|
||||
response = state | {"resCode": 0}
|
||||
raw = encode(response, DEFAULT_KEY)
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Length", str(len(raw)))
|
||||
self.end_headers()
|
||||
self.wfile.write(raw)
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
client = Client(Session(f"http://127.0.0.1:{server.server_port}/", "synthetic-test-token"))
|
||||
try:
|
||||
engine = Engine(catalog, client)
|
||||
engine.policy = Policy(strategy="gold", protect_star=6, protect_quality=5, fill=False)
|
||||
engine.poll()
|
||||
self.assertFalse(any(p.endswith("stackCheckProcess") or p.endswith("monsterSell") for p, _ in calls))
|
||||
engine.auto = True
|
||||
snapshot, _, _ = engine.poll()
|
||||
self.assertEqual(sum(p.endswith("monsterSell") for p, _ in calls), 1)
|
||||
self.assertEqual(sum(m.get("process") == 2 for m in snapshot.raw["monsters"]), 3)
|
||||
self.assertEqual([v["reqid"] for _, v in calls], list(range(len(calls))))
|
||||
finally:
|
||||
client.close()
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join(2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user