Added replay ability

This commit is contained in:
2026-10-10 23:00:04 -06:00
parent 13b1dcdd97
commit fbfa90edec
16 changed files with 700 additions and 39 deletions
+63
View File
@@ -93,6 +93,69 @@ def test_start_native_backend_reports_start_failure(monkeypatch):
assert backend_proxy._capture is None
def test_initialize_ok_with_replay(monkeypatch):
monkeypatch.setattr(
backend_proxy.environment, 'replay_path', lambda: '/tmp/x.jsonl')
assert backend_proxy.initialize() == backend_proxy.InitializationResult.Ok
def test_subscribe_starts_replay_backend(monkeypatch):
monkeypatch.setattr(
backend_proxy.environment, 'replay_path', lambda: '/tmp/x.jsonl')
started = []
monkeypatch.setattr(
backend_proxy, '_start_replay_backend',
lambda callback: started.append(callback) or True)
callback = lambda event: event
assert backend_proxy.subscribe(callback) is True
assert started == [callback]
def test_start_replay_backend_uses_pipeline(monkeypatch):
import src.net.replay as replay_mod
monkeypatch.setattr(backend_proxy, '_replay', None)
created = {}
class FakeReplay:
def __init__(self, on_udp):
created['on_udp'] = on_udp
def start(self):
created['started'] = True
return True
monkeypatch.setattr(replay_mod, 'ReplayEngine', FakeReplay)
assert backend_proxy._start_replay_backend(lambda event: event) is True
assert created['started'] is True
assert callable(created['on_udp'])
assert backend_proxy._replay is not None
backend_proxy._replay = None
def test_start_replay_backend_reports_start_failure(monkeypatch):
import src.net.replay as replay_mod
monkeypatch.setattr(backend_proxy, '_replay', None)
class FakeReplay:
def __init__(self, on_udp):
self.on_udp = on_udp
def start(self):
return False
monkeypatch.setattr(replay_mod, 'ReplayEngine', FakeReplay)
assert backend_proxy._start_replay_backend(lambda event: event) is False
assert backend_proxy._replay is None
def test_engine_initialize_reports_subscribe_failure(monkeypatch):
monkeypatch.setattr(
engine.backend_proxy, 'initialize',
+41 -11
View File
@@ -168,10 +168,10 @@ def test_fragment_reassembly():
(6, 'HealthUpdate'),
(29, 'NewCharacter'),
(32, 'ItemGained'),
(62, 'TakeSilver'),
(82, 'UpdateFame'),
(90, 'CharacterEquipmentChanged'),
(91, 'RegenerationHealthChanged'),
(153, 'SilverGained'),
(166, 'KnockedDown'),
(231, 'PartyJoined'),
(233, 'PartyPlayerJoined'),
@@ -315,6 +315,22 @@ def test_world_update_fame_delta_from_total():
assert events[0]['value']['value'] == pytest.approx(0.1)
def test_world_update_fame_applies_bonus_factor():
world = World()
world.transform(game('NewCharacter', {0: 10, 1: 'Alice'}))
events = world.transform(
game('UpdateFame', {0: 10, 1: 5000000, 2: 30000, 17: 0.25}))
assert events[0]['value']['value'] == pytest.approx(3.75)
def test_world_update_fame_applies_premium_and_satchel():
world = World()
world.transform(game('NewCharacter', {0: 10, 1: 'Alice'}))
events = world.transform(
game('UpdateFame', {0: 10, 1: 5000000, 2: 30000, 5: True, 10: 10000}))
assert events[0]['value']['value'] == pytest.approx(5.5)
def test_world_item_gained_emits_collected_item():
world = World()
world.transform(game('Join', {0: 63, 2: 'Alice'}))
@@ -356,22 +372,36 @@ def test_world_item_gained_uses_display_name_and_deduplicates():
assert duplicate == []
def test_world_silver_gained_tracks_known_sources():
def test_world_take_silver_tracks_main_player():
world = World()
world.transform(game('Join', {0: 63, 2: 'Alice'}))
looted = world.transform(game('SilverGained', {1: 54, 2: 45}))
other = world.transform(game('SilverGained', {1: 168, 2: 45}))
ignored = world.transform(game('SilverGained', {1: 126, 2: 81}))
events = world.transform(game('TakeSilver', {0: 63, 3: 648351}))
assert looted == [{'name': 'SilverGained', 'value': {
'value': 45.0, 'silver_type': 'looted'}}]
assert other == []
assert ignored == []
assert events[0]['name'] == 'SilverGained'
assert events[0]['value']['silver_type'] == 'looted'
assert events[0]['value']['value'] == pytest.approx(64.8351)
def test_world_silver_gained_waits_for_main_player_join():
def test_world_take_silver_subtracts_taxes():
world = World()
assert world.transform(game('SilverGained', {1: 54, 2: 45})) == []
world.transform(game('Join', {0: 63, 2: 'Alice'}))
events = world.transform(
game('TakeSilver', {0: 63, 3: 500000, 4: 20000, 5: 10000, 6: 5000}))
assert events[0]['value']['value'] == pytest.approx(46.5)
def test_world_take_silver_ignores_other_players():
world = World()
world.transform(game('Join', {0: 63, 2: 'Alice'}))
world.transform(game('NewCharacter', {0: 70, 1: 'Bob'}))
assert world.transform(game('TakeSilver', {0: 70, 3: 450000})) == []
def test_world_take_silver_waits_for_main_player_join():
world = World()
assert world.transform(game('TakeSilver', {0: 63, 3: 450000})) == []
def test_world_unconsumed_equipment_replayed_on_new_character():
+11
View File
@@ -13,6 +13,17 @@ def test_qt_args_removes_app_specific_options():
'aostats', '--log-path=/tmp/capture.jsonl']) == ['aostats']
def test_discovery_log_skips_replay_source(monkeypatch, tmp_path):
path = tmp_path / 'capture.jsonl'
monkeypatch.setattr(discovery, 'discovery_log_path', lambda: str(path))
monkeypatch.setattr(discovery, 'replay_path', lambda: str(path))
monkeypatch.setattr(discovery, '_initialized', False)
discovery.log('game_message', params={})
assert not path.exists()
def test_discovery_log_writes_jsonl_with_item_annotations(monkeypatch, tmp_path):
path = tmp_path / 'capture.jsonl'
monkeypatch.setattr(discovery, 'discovery_log_path', lambda: str(path))
+28
View File
@@ -14,3 +14,31 @@ def test_remember_last_party_flag_is_removed_from_qt_args(monkeypatch):
sys.argv = ['aostats']
importlib.reload(environment)
def test_replay_flags_are_parsed_and_removed_from_qt_args(monkeypatch):
monkeypatch.setattr(sys, 'argv', [
'aostats', '--replay', '/tmp/capture.jsonl',
'--replay-speed', '2', '--replay-headless'])
reloaded = importlib.reload(environment)
assert reloaded.replay_path() == '/tmp/capture.jsonl'
assert reloaded.replay_speed() == 2.0
assert reloaded.replay_headless() is True
assert reloaded.qt_args(sys.argv) == ['aostats']
sys.argv = ['aostats']
importlib.reload(environment)
def test_replay_equals_syntax_and_default_speed(monkeypatch):
monkeypatch.setattr(sys, 'argv', ['aostats', '--replay=/tmp/x.jsonl'])
reloaded = importlib.reload(environment)
assert reloaded.replay_path() == '/tmp/x.jsonl'
assert reloaded.replay_speed() == 0.0
assert reloaded.replay_headless() is False
assert reloaded.qt_args(['aostats', '--replay=/tmp/x.jsonl']) == ['aostats']
sys.argv = ['aostats']
importlib.reload(environment)
+146
View File
@@ -0,0 +1,146 @@
import json
import os
import re
import time
from collections import Counter
import pytest
from src.decode.pipeline import Pipeline
from src.net.replay import ReplayEngine, load_payloads
from src.replay_cli import summarize
RAW_LOG_PATH = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'aoaddons.log')
def _write_jsonl(path, payloads):
with open(path, 'w', encoding='utf-8') as out:
out.write(json.dumps({'type': 'session_start'}) + '\n')
for i, payload in enumerate(payloads):
out.write(json.dumps({
'type': 'udp_payload',
'timestamp': f'2026-10-10T00:00:{i:02d}.000+00:00',
'payload_hex': payload.hex(),
}) + '\n')
out.write(json.dumps({'type': 'game_message', 'name': 'UpdateFame'}) + '\n')
def test_load_payloads_reads_jsonl_and_ignores_other_records(tmp_path):
path = tmp_path / 'capture.jsonl'
_write_jsonl(str(path), [b'\x01\x02', b'\x03\x04\x05'])
assert load_payloads(str(path)) == [b'\x01\x02', b'\x03\x04\x05']
def test_load_payloads_supports_legacy_raw_format(tmp_path):
path = tmp_path / 'aoaddons.log'
path.write_text(
'some log line\n'
'Raw payload: [1, 2, 3]\n'
'unrelated\n'
'Raw payload: [4, 5]\n',
encoding='utf-8')
assert load_payloads(str(path)) == [b'\x01\x02\x03', b'\x04\x05']
def test_replay_engine_start_fails_for_missing_file():
engine = ReplayEngine(lambda payload: None, path='/does/not/exist.jsonl')
assert engine.start() is False
def test_replay_engine_feeds_payloads_in_order(tmp_path):
path = tmp_path / 'capture.jsonl'
_write_jsonl(str(path), [b'\xaa', b'\xbb', b'\xcc'])
received = []
engine = ReplayEngine(received.append, path=str(path), speed=0.0)
assert engine.start() is True
engine.wait(timeout=5)
assert received == [b'\xaa', b'\xbb', b'\xcc']
assert engine.packet_count == 3
def test_replay_engine_paces_with_timestamps(tmp_path):
path = tmp_path / 'capture.jsonl'
with open(path, 'w', encoding='utf-8') as out:
out.write(json.dumps({'type': 'session_start'}) + '\n')
for i in range(3):
out.write(json.dumps({
'type': 'udp_payload',
'timestamp': f'2026-10-10T00:00:00.{i * 100:03d}+00:00',
'payload_hex': 'aa',
}) + '\n')
started = time.monotonic()
engine = ReplayEngine(lambda payload: None, path=str(path), speed=1.0)
engine.start()
engine.wait(timeout=5)
elapsed = time.monotonic() - started
assert elapsed >= 0.15
def test_replay_engine_ignores_duplicate_start(tmp_path):
path = tmp_path / 'capture.jsonl'
_write_jsonl(str(path), [b'\xaa'])
engine = ReplayEngine(lambda payload: None, path=str(path))
assert engine.start() is True
assert engine.start() is True
engine.wait(timeout=5)
assert engine.packet_count == 1
def test_summarize_reports_fame_silver_and_player():
events = [
{'name': 'MainPlayerAppeared', 'value': {'id': 0, 'name': 'Alice'}},
{'name': 'ZoneChange'},
{'name': 'UpdateFame', 'value': {'value': 857.472}},
{'name': 'SilverGained', 'value': {
'value': 64.8351, 'silver_type': 'looted'}},
{'name': 'DamageDone', 'value': {'source': 1, 'value': 120.0}},
]
report = summarize(events, path='/tmp/capture.jsonl', packet_count=42)
assert 'Alice' in report
assert '857.47' in report
assert '64.84' in report
assert '120.00' in report
assert 'packets: 42' in report
pytestmark = pytest.mark.skipif(
not os.path.exists(RAW_LOG_PATH),
reason='aoaddons.log capture fixture is not available')
def _raw_payloads():
payloads = []
pattern = re.compile(r'Raw payload: \[([0-9, ]+)\]')
with open(RAW_LOG_PATH, encoding='utf-8', errors='replace') as log:
for line in log:
match = pattern.search(line)
if match:
payloads.append(
bytes(int(part) for part in match.group(1).split(',')))
return payloads
def test_replay_engine_integration_produces_events(tmp_path):
path = tmp_path / 'capture.jsonl'
_write_jsonl(str(path), _raw_payloads())
events = []
pipeline = Pipeline(events.append)
engine = ReplayEngine(pipeline.on_udp, path=str(path), speed=0.0)
assert engine.start() is True
engine.wait(timeout=10)
counts = Counter(event['name'] for event in events)
assert counts['MainPlayerAppeared'] >= 1
assert counts['PlayerAppeared'] == 2
assert counts['ZoneChange'] == 3