package scores import ( "fmt" "path/filepath" "sync" "testing" "thermal-snake/internal/game" ) func TestRunHistoryAndRankingAcrossReopen(t *testing.T) { path := filepath.Join(t.TempDir(), "scores.db") store, err := Open(path) if err != nil { t.Fatal(err) } defer func() { if store != nil { _ = store.Close() } }() alice, err := store.Register("key-A") if err != nil { t.Fatal(err) } bob, err := store.Register("key-B") if err != nil { t.Fatal(err) } if alice.Callsign == bob.Callsign { t.Fatal("distinct keys share a callsign") } record := func(key, id string, score int, wantBest bool) { t.Helper() _, best, err := store.Record(key, Run{ID: id, Score: score, Outcome: game.Wall}) if err != nil || best != wantBest { t.Fatalf("record %s got best=%v, err=%v", id, best, err) } } record("key-B", "bob-first", 100, true) record("key-A", "alice-first", 100, true) record("key-A", "alice-low", 0, false) record("key-A", "alice-equal", 100, false) record("key-A", "alice-low", 0, false) // Retry with the same ID. if err := store.Close(); err != nil { t.Fatal(err) } store, err = Open(path) if err != nil { t.Fatal(err) } again, err := store.Register("key-A") if err != nil || again.Callsign != alice.Callsign || again.Total != 3 || again.Best == nil || again.Best.ID != "alice-first" { t.Fatalf("reopened profile: %+v, %v", again, err) } standings, err := store.Leaderboard() if err != nil || len(standings) != 2 { t.Fatalf("reopened standings: %+v, %v", standings, err) } if standings[0].Callsign != bob.Callsign || standings[0].Rank != 1 || standings[1].Callsign != alice.Callsign || standings[1].Rank != 2 { t.Fatalf("equal scores ranked out of recording order: %+v", standings) } history, total, err := store.History("key-A", 1, 1) if err != nil || total != 3 || len(history) != 1 || history[0].ID != "alice-low" || history[0].Score != 0 { t.Fatalf("reopened history: %+v, total %d, %v", history, total, err) } record("key-A", "alice-high", 200, true) standings, err = store.Leaderboard() if err != nil || len(standings) != 2 || standings[0].Callsign != alice.Callsign { t.Fatalf("new best should take first place: %+v, %v", standings, err) } } func TestConcurrentSessionsShareAProfile(t *testing.T) { store, err := Open(filepath.Join(t.TempDir(), "scores.db")) if err != nil { t.Fatal(err) } defer store.Close() const sessions = 18 var wg sync.WaitGroup for i := range sessions { wg.Go(func() { if _, err := store.Register("same-key"); err != nil { t.Errorf("register: %v", err) return } if _, _, err := store.Record("same-key", Run{ID: fmt.Sprint(i), Score: i * 100}); err != nil { t.Errorf("record: %v", err) } }) } wg.Wait() runs, total, err := store.History("same-key", 0, sessions) if err != nil || len(runs) != sessions || total != sessions { t.Fatalf("history has %d of %d runs: %v", len(runs), total, err) } pilot, err := store.Profile("same-key") if err != nil || pilot.Best == nil || pilot.Best.Score != (sessions-1)*100 { t.Fatalf("unexpected personal best: %+v, %v", pilot, err) } }