package bot import ( "context" "encoding/json" "io" "net/http" "regexp" "sort" "strconv" "strings" "sync" "testing" "velox-bot/internal/beta" "velox-bot/internal/commands" "github.com/bwmarrin/discordgo" ) const ( appID = "100" betaServer = "700000000000000001" optedIn = "222" leftServer = "333" ) // fakeDiscord answers the application-command calls the beta sync makes, from // memory, and records what it was asked to change. var registerOnce sync.Once type fakeDiscord struct { mu sync.Mutex cmds map[string][]*discordgo.ApplicationCommand // guild -> commands failures map[string]int // guild -> status for every call nextID int created []string // "guild/name" deleted []string // "guild/name" } var cmdPath = regexp.MustCompile(`/applications/` + appID + `/guilds/(\d+)/commands(?:/(\d+))?$`) func (f *fakeDiscord) RoundTrip(r *http.Request) (*http.Response, error) { f.mu.Lock() defer f.mu.Unlock() reply := func(code int, v any) (*http.Response, error) { b, _ := json.Marshal(v) return &http.Response{StatusCode: code, Body: io.NopCloser(strings.NewReader(string(b))), Header: http.Header{"Content-Type": {"application/json"}}, Request: r}, nil } m := cmdPath.FindStringSubmatch(r.URL.Path) if m == nil { return reply(404, map[string]any{"message": "unknown route"}) } guild, id := m[1], m[2] if code := f.failures[guild]; code != 0 { return reply(code, map[string]any{"message": "failure", "code": 0}) } switch r.Method { case http.MethodGet: return reply(200, f.cmds[guild]) case http.MethodPost: var c discordgo.ApplicationCommand _ = json.NewDecoder(r.Body).Decode(&c) f.nextID++ c.ID = strconv.Itoa(1000 + f.nextID) f.cmds[guild] = append(f.cmds[guild], &c) f.created = append(f.created, guild+"/"+c.Name) return reply(200, c) case http.MethodDelete: kept := f.cmds[guild][:0] for _, c := range f.cmds[guild] { if c.ID == id { f.deleted = append(f.deleted, guild+"/"+c.Name) continue } kept = append(kept, c) } f.cmds[guild] = kept return reply(204, nil) } return reply(405, nil) } func (f *fakeDiscord) names(guild string) []string { f.mu.Lock() defer f.mu.Unlock() var out []string for _, c := range f.cmds[guild] { out = append(out, c.Name) } sort.Strings(out) return out } type fakeStore struct { registered map[string]bool servers []string failWrite bool } func (s *fakeStore) GetBetaSettings(context.Context) (string, string, error) { return betaServer, "555", nil } func (s *fakeStore) ListBetaGuilds(context.Context) ([]string, error) { return s.servers, nil } func (s *fakeStore) ListBetaRegistered(context.Context) ([]string, error) { var out []string for id := range s.registered { out = append(out, id) } return out, nil } func (s *fakeStore) SetBetaRegistered(_ context.Context, id string, on bool) error { if s.failWrite { return io.ErrUnexpectedEOF } if on { s.registered[id] = true } else { delete(s.registered, id) } return nil } func newTestBot(t *testing.T, d *fakeDiscord) *Bot { t.Helper() sess, err := discordgo.New("Bot x") if err != nil { t.Fatal(err) } sess.Client = &http.Client{Transport: d} sess.MaxRestRetries = 0 return &Bot{ Session: sess, AppID: appID, betaRegistered: map[string]bool{}, betaKnown: map[string]bool{}, } } func contains(list []string, v string) bool { for _, x := range list { if x == v { return true } } return false } func TestBetaCommandsFollowTheServers(t *testing.T) { registerOnce.Do(func() { commands.RegisterBeta(&discordgo.ApplicationCommand{Name: "betatest", Description: "test"}, func(*discordgo.Session, *discordgo.InteractionCreate) {}) }) d := &fakeDiscord{cmds: map[string][]*discordgo.ApplicationCommand{ // A server that opted out while the bot was offline still has them, // next to a command that isn't a beta one. leftServer: {{ID: "1", Name: "betatest"}, {ID: "2", Name: "ping"}}, // A stale command in the beta server, which the bot cleans up. betaServer: {{ID: "3", Name: "oldthing"}}, }, failures: map[string]int{}} store := &fakeStore{registered: map[string]bool{leftServer: true}, servers: []string{optedIn}} b := newTestBot(t, d) ctx := context.Background() beta.Configure(betaServer, "555", store.servers) b.syncBetaCommands(ctx, store) if got := d.names(leftServer); len(got) != 1 || got[0] != "ping" { t.Errorf("the beta command is removed from the server that left, nothing else: %v", got) } if got := d.names(optedIn); len(got) != 1 || got[0] != "betatest" { t.Errorf("an opted-in server gets the beta commands but not /beta: %v", got) } got := d.names(betaServer) if !contains(got, "beta") || !contains(got, "betatest") || contains(got, "oldthing") { t.Errorf("the beta server gets /beta and the beta commands, and loses stale ones: %v", got) } if store.registered[leftServer] || !store.registered[optedIn] || !store.registered[betaServer] { t.Errorf("the database remembers where the commands are now: %v", store.registered) } // The server opts out. store.servers = nil beta.Configure(betaServer, "555", store.servers) b.syncBetaCommands(ctx, store) if got := d.names(optedIn); len(got) != 0 { t.Errorf("an opted-out server loses them within one round: %v", got) } if store.registered[optedIn] || !store.registered[betaServer] { t.Errorf("only the beta server stays remembered: %v", store.registered) } } func TestBetaCleanupIsRetriedAndGivesUpWhenTheBotIsGone(t *testing.T) { d := &fakeDiscord{cmds: map[string][]*discordgo.ApplicationCommand{ leftServer: {{ID: "1", Name: "betatest"}}, }, failures: map[string]int{leftServer: 500}} store := &fakeStore{registered: map[string]bool{leftServer: true}} b := newTestBot(t, d) ctx := context.Background() beta.Configure(betaServer, "555", nil) b.syncBetaCommands(ctx, store) if !store.registered[leftServer] { t.Fatal("a failed cleanup is remembered so it is tried again") } d.failures[leftServer] = 0 b.syncBetaCommands(ctx, store) if store.registered[leftServer] || len(d.names(leftServer)) != 0 { t.Errorf("the retry cleans up: %v, %v", store.registered, d.names(leftServer)) } // The bot was removed from a server: nothing to clean, don't try forever. store.registered["444"] = true b.betaKnown["444"] = true d.failures["444"] = 403 b.syncBetaCommands(ctx, store) if store.registered["444"] { t.Error("a server the bot can't reach any more is forgotten") } } // Close used to loop over a list that started with empty entries and read // their IDs, so shutting down crashed. It must just disconnect, and must not // touch the registered commands. func TestCloseDoesNotTouchCommands(t *testing.T) { d := &fakeDiscord{cmds: map[string][]*discordgo.ApplicationCommand{ "1": {{ID: "7", Name: "ping"}}, }, failures: map[string]int{}} b := newTestBot(t, d) b.GuildID = "1" b.Commands = []*discordgo.ApplicationCommand{{Name: "ping"}} if err := b.Close(); err != nil { t.Fatalf("Close on a bot that never connected: %v", err) } if len(d.deleted) != 0 { t.Errorf("Close must not delete commands: %v", d.deleted) } }