203 lines
8.8 KiB
Python
203 lines
8.8 KiB
Python
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 ranch_assistant.api import ApiError, Client, DEFAULT_KEY, Session, decode, encode
|
|
from ranch_assistant.engine import Engine, demo_snapshot
|
|
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)
|
|
feeding = next(a for a in plans if a.kind == "feed")
|
|
self.assertEqual(feeding.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))
|
|
|
|
|
|
|
|
|
|
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["monsterIds"][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.assertTrue(any(p.endswith("stackCheckProcess") for p, _ in calls))
|
|
self.assertFalse(any(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()
|