"""Tests for stats loading on login and session_start initialization.""" import time import pytest from mudlib.player import Player, accumulate_play_time from mudlib.store import init_db, load_player_stats, save_player @pytest.fixture def db(tmp_path): """Create a temporary test database.""" db_path = tmp_path / "test.db" init_db(db_path) return db_path def test_stats_load_and_apply_round_trip(db, mock_reader, mock_writer, test_zone): """Stats can be saved, loaded, and applied to a new player instance.""" # Create player with known stats p1 = Player(name="Ken", x=0, y=0, reader=mock_reader, writer=mock_writer) p1.location = test_zone p1.kills = 5 p1.deaths = 2 p1.mob_kills = {"goblin": 3} p1.play_time_seconds = 1000.0 p1.unlocked_moves = {"roundhouse"} # Save the player (which saves stats internally) save_player(p1) # Load stats from database stats = load_player_stats("Ken", db) # Create a new player instance and apply loaded stats p2 = Player(name="Ken", x=0, y=0, reader=mock_reader, writer=mock_writer) p2.location = test_zone p2.kills = stats["kills"] p2.deaths = stats["deaths"] p2.mob_kills = stats["mob_kills"] p2.play_time_seconds = stats["play_time_seconds"] p2.unlocked_moves = stats["unlocked_moves"] # Verify all stats match assert p2.kills == 5 assert p2.deaths == 2 assert p2.mob_kills == {"goblin": 3} assert p2.play_time_seconds == 1000.0 assert p2.unlocked_moves == {"roundhouse"} def test_session_start_set_after_login_setup(mock_reader, mock_writer, test_zone): """session_start is set to non-zero after login setup.""" # Simulate login setup p = Player(name="Ryu", x=0, y=0, reader=mock_reader, writer=mock_writer) p.location = test_zone # Set session_start (this is what server.py does) p.session_start = time.monotonic() # Verify it's non-zero assert p.session_start > 0 def test_accumulate_play_time_with_real_session_start( mock_reader, mock_writer, test_zone ): """accumulate_play_time works correctly with real session_start.""" p = Player(name="Chun", x=0, y=0, reader=mock_reader, writer=mock_writer) p.location = test_zone p.play_time_seconds = 100.0 # Set session_start to 60 seconds ago (simulating 60 seconds of play) p.session_start = time.monotonic() - 60.0 # Accumulate play time accumulate_play_time(p) # Play time should have increased by approximately 60 seconds assert p.play_time_seconds >= 159.0 assert p.play_time_seconds <= 161.0 # session_start should be reset to current time assert p.session_start > 0 assert time.monotonic() - p.session_start < 1.0