sonda/internal/mastodon/mastodon_test.go
tgiachi a7a258464b feat(mastodon): say in Settings when the instance no longer accepts the token
When the instance refuses the token on a post (it was revoked or expired), the account now remembers it: GET /me/mastodon says problem: token_refused and nothing is posted until I connect again with a new token.

- migration 0027 adds mastodon_accounts.problem (SQLite and PostgreSQL).
- Only a refused token marks the account; an instance that is down does not.
- Saving the account again clears the problem.
- Settings shows the warning and the form with the instance already filled in, next to Disconnect.
- English and Italian.
2026-11-14 10:04:07 +01:00

360 lines
11 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package mastodon
import (
"context"
"errors"
"strings"
"sync"
"testing"
"time"
"go.uber.org/zap"
)
func TestNormalizeTakesTheAddressOfAnInstanceInTheWaysPeopleWriteIt(t *testing.T) {
for in, want := range map[string]string{
"mastodon.social": "https://mastodon.social",
" Mastodon.Social ": "https://mastodon.social",
"https://mastodon.social": "https://mastodon.social",
"https://mastodon.social/": "https://mastodon.social",
"https://mastodon.uno:8443": "https://mastodon.uno:8443",
"social.example.org/": "https://social.example.org",
"https://social.example.org//": "https://social.example.org",
} {
got, err := Normalize(in)
if err != nil || got != want {
t.Errorf("Normalize(%q) = %q, %v; want %q", in, got, err, want)
}
}
}
func TestNormalizeRefusesWhatIsNotTheAddressOfAPublicInstance(t *testing.T) {
long := strings.Repeat("a", 250) + ".org"
for _, in := range []string{
"", " ", "http://mastodon.social", "ftp://mastodon.social", "localhost", "intranet", "127.0.0.1", "https://10.0.0.5",
"https://[::1]", "https://user:pass@mastodon.social", "https://mastodon.social/path", "https://mastodon.social/?x=1",
"https://mastodon.social#top", "mastodon social", "https://", long, "@squid@mastodon.social",
} {
if got, err := Normalize(in); !errors.Is(err, ErrBadInstance) {
t.Errorf("Normalize(%q) = %q, %v; want ErrBadInstance", in, got, err)
}
}
}
func TestComposeSaysWhatWasHeardAndNothingMore(t *testing.T) {
got := Compose(Track{Title: "Sonar", Artists: []string{"Nora Valdés", "Teo"}, Album: "Luce Sommersa"})
want := "🎵 Sonar – Nora Valdés, Teo (Luce Sommersa) #NowPlaying"
if got != want {
t.Errorf("Compose = %q, want %q", got, want)
}
if got := Compose(Track{Title: "Sonar"}); got != "🎵 Sonar #NowPlaying" {
t.Errorf("a track with no artist and no album: %q", got)
}
if got := Compose(Track{Title: "Sonar", Artists: []string{"Nora"}}); got != "🎵 Sonar – Nora #NowPlaying" {
t.Errorf("a track with no album: %q", got)
}
}
func TestComposeNeverPassesTheLimitOfAPost(t *testing.T) {
got := Compose(Track{Title: strings.Repeat("é", 800), Artists: []string{"Nora"}, Album: "x"})
if n := len([]rune(got)); n > maxPost {
t.Errorf("%d characters, the limit is %d", n, maxPost)
}
if !strings.HasSuffix(got, " #NowPlaying") || !strings.Contains(got, "…") {
t.Errorf("it is cut with a mark and keeps the tag: %q", got[len(got)-30:])
}
}
type fakeStore struct {
mu sync.Mutex
creds map[int64]Credentials
tracks map[int64]Track
}
func newFakeStore() *fakeStore {
return &fakeStore{creds: map[int64]Credentials{}, tracks: map[int64]Track{7: {Title: "Sonar", Artists: []string{"Nora"}, Album: "Luce"}}}
}
func (f *fakeStore) Get(_ context.Context, id int64) (Credentials, bool, error) {
f.mu.Lock()
defer f.mu.Unlock()
c, ok := f.creds[id]
return c, ok, nil
}
func (f *fakeStore) Save(_ context.Context, id int64, c Credentials) error {
f.mu.Lock()
defer f.mu.Unlock()
f.creds[id] = c
return nil
}
func (f *fakeStore) SetProblem(_ context.Context, id int64, problem string) error {
f.mu.Lock()
defer f.mu.Unlock()
c, ok := f.creds[id]
if !ok {
return nil
}
c.Problem = problem
f.creds[id] = c
return nil
}
func (f *fakeStore) Delete(_ context.Context, id int64) error {
f.mu.Lock()
defer f.mu.Unlock()
delete(f.creds, id)
return nil
}
func (f *fakeStore) Track(_ context.Context, id int64) (Track, bool, error) {
t, ok := f.tracks[id]
return t, ok, nil
}
type post struct{ instance, token, status, key string }
type fakeRemote struct {
mu sync.Mutex
handle string
verify error
postErr error
posts []post
posted chan post
}
func (f *fakeRemote) Verify(_ context.Context, instance, token string) (string, error) {
if f.verify != nil {
return "", f.verify
}
return f.handle, nil
}
func (f *fakeRemote) Post(_ context.Context, instance, token, status, key string) error {
f.mu.Lock()
p := post{instance, token, status, key}
f.posts = append(f.posts, p)
err := f.postErr
f.mu.Unlock()
if f.posted != nil {
f.posted <- p
}
return err
}
func (f *fakeRemote) count() int {
f.mu.Lock()
defer f.mu.Unlock()
return len(f.posts)
}
func newService(t *testing.T) (*Service, *fakeStore, *fakeRemote) {
t.Helper()
st, rm := newFakeStore(), &fakeRemote{handle: "@squid@mastodon.social"}
return NewService(st, rm, zap.NewNop()), st, rm
}
func TestNothingIsConnectedUntilTheUserConnectsAnAccount(t *testing.T) {
s, _, _ := newService(t)
if _, connected, err := s.Status(context.Background(), 1); err != nil || connected {
t.Fatalf("Status = connected %v, %v", connected, err)
}
}
func TestConnectChecksTheTokenAndKeepsTheAccountWithoutShowingTheToken(t *testing.T) {
s, st, _ := newService(t)
acc, err := s.Connect(context.Background(), 1, "Mastodon.Social/", "secret-token")
if err != nil {
t.Fatal(err)
}
if acc.Instance != "https://mastodon.social" || acc.Handle != "@squid@mastodon.social" {
t.Errorf("account = %+v", acc)
}
if got := st.creds[1]; got.Token != "secret-token" || got.Instance != "https://mastodon.social" {
t.Errorf("kept = %+v", got)
}
got, connected, _ := s.Status(context.Background(), 1)
if !connected || got != acc {
t.Errorf("Status = %+v, %v", got, connected)
}
}
func TestConnectKeepsNothingWhenTheTokenIsRefusedOrTheInstanceIsNotThere(t *testing.T) {
for _, bad := range []error{ErrRefused, ErrUnreachable} {
s, st, rm := newService(t)
rm.verify = bad
if _, err := s.Connect(context.Background(), 1, "mastodon.social", "tok"); !errors.Is(err, bad) {
t.Errorf("err = %v, want %v", err, bad)
}
if len(st.creds) != 0 {
t.Errorf("%v: something was kept: %+v", bad, st.creds)
}
}
s, _, _ := newService(t)
if _, err := s.Connect(context.Background(), 1, "http://mastodon.social", "tok"); !errors.Is(err, ErrBadInstance) {
t.Errorf("a plain http address: %v", err)
}
if _, err := s.Connect(context.Background(), 1, "mastodon.social", " "); !errors.Is(err, ErrBadToken) {
t.Errorf("an empty token: %v", err)
}
if _, err := s.Connect(context.Background(), 1, "mastodon.social", strings.Repeat("x", 600)); !errors.Is(err, ErrBadToken) {
t.Errorf("a token that is far too long: %v", err)
}
}
func TestDisconnectForgetsTheToken(t *testing.T) {
s, st, _ := newService(t)
_, _ = s.Connect(context.Background(), 1, "mastodon.social", "tok")
if err := s.Disconnect(context.Background(), 1); err != nil {
t.Fatal(err)
}
if len(st.creds) != 0 {
t.Errorf("still kept: %+v", st.creds)
}
if err := s.Disconnect(context.Background(), 1); err != nil {
t.Errorf("disconnecting twice is not an error: %v", err)
}
}
func TestAnAnnouncementIsAnUnlistedPostOfTheTrackToTheAccountOfWhoListened(t *testing.T) {
s, st, rm := newService(t)
_ = st.Save(context.Background(), 1, Credentials{Instance: "https://mastodon.social", Token: "tok", Handle: "@squid@mastodon.social"})
if err := s.announce(context.Background(), 1, 7); err != nil {
t.Fatal(err)
}
if rm.count() != 1 {
t.Fatalf("%d posts", rm.count())
}
p := rm.posts[0]
if p.instance != "https://mastodon.social" || p.token != "tok" || p.status != "🎵 Sonar – Nora (Luce) #NowPlaying" || p.key == "" {
t.Errorf("post = %+v", p)
}
}
func TestNothingIsPostedForWhoDidNotConnectAnAccountOrForATrackThatIsGone(t *testing.T) {
s, st, rm := newService(t)
if err := s.announce(context.Background(), 1, 7); err != nil || rm.count() != 0 {
t.Errorf("not connected: %v, %d posts", err, rm.count())
}
_ = st.Save(context.Background(), 1, Credentials{Instance: "https://mastodon.social", Token: "tok"})
if err := s.announce(context.Background(), 1, 999); err != nil || rm.count() != 0 {
t.Errorf("unknown track: %v, %d posts", err, rm.count())
}
}
func TestAtMostOnePostAMinuteForEachPerson(t *testing.T) {
s, st, rm := newService(t)
now := time.Date(2026, 11, 14, 10, 0, 0, 0, time.UTC)
s.now = func() time.Time { return now }
for _, id := range []int64{1, 2} {
_ = st.Save(context.Background(), id, Credentials{Instance: "https://mastodon.social", Token: "tok"})
}
_ = s.announce(context.Background(), 1, 7)
now = now.Add(30 * time.Second)
_ = s.announce(context.Background(), 1, 7)
_ = s.announce(context.Background(), 2, 7) // somebody else is not held back by the first
if rm.count() != 2 {
t.Fatalf("%d posts, want 2", rm.count())
}
now = now.Add(31 * time.Second)
_ = s.announce(context.Background(), 1, 7)
if rm.count() != 3 {
t.Errorf("a minute later it posts again: %d posts", rm.count())
}
}
func TestAFailedPostIsNotRetriedAndDoesNotCountAgainstTheMinute(t *testing.T) {
s, st, rm := newService(t)
_ = st.Save(context.Background(), 1, Credentials{Instance: "https://mastodon.social", Token: "tok"})
rm.postErr = ErrUnreachable
if err := s.announce(context.Background(), 1, 7); !errors.Is(err, ErrUnreachable) {
t.Errorf("err = %v", err)
}
rm.postErr = nil
_ = s.announce(context.Background(), 1, 7)
if rm.count() != 2 {
t.Errorf("%d posts: the failed one must not hold back the next", rm.count())
}
}
func TestARefusedTokenIsRememberedAndNothingIsPostedUntilTheAccountIsConnectedAgain(t *testing.T) {
s, st, rm := newService(t)
ctx := context.Background()
_ = st.Save(ctx, 1, Credentials{Instance: "https://mastodon.social", Token: "tok", Handle: "@a@x"})
rm.postErr = ErrRefused
if err := s.announce(ctx, 1, 7); !errors.Is(err, ErrRefused) {
t.Fatalf("err = %v", err)
}
acc, _, _ := s.Status(ctx, 1)
if acc.Problem != ProblemTokenRefused {
t.Errorf("problem = %q, want %q", acc.Problem, ProblemTokenRefused)
}
// While the token is refused no post is tried: the instance would say no again.
rm.postErr = nil
before := rm.count()
if err := s.announce(ctx, 1, 7); err != nil {
t.Errorf("a paused account is not an error: %v", err)
}
if rm.count() != before {
t.Errorf("a post was tried with a refused token")
}
// Connecting again with a new token clears it and posts go out again.
if _, err := s.Connect(ctx, 1, "mastodon.social", "new-token"); err != nil {
t.Fatal(err)
}
if acc, _, _ := s.Status(ctx, 1); acc.Problem != "" {
t.Errorf("problem after connecting again = %q", acc.Problem)
}
_ = s.announce(ctx, 1, 7)
if rm.count() != before+1 {
t.Errorf("%d posts: connecting again must let posts go out", rm.count())
}
}
func TestAPostThatFailsForAnyOtherReasonIsNotAProblemOfTheAccount(t *testing.T) {
s, st, rm := newService(t)
ctx := context.Background()
_ = st.Save(ctx, 1, Credentials{Instance: "https://mastodon.social", Token: "tok", Handle: "@a@x"})
rm.postErr = ErrUnreachable
_ = s.announce(ctx, 1, 7)
if acc, _, _ := s.Status(ctx, 1); acc.Problem != "" {
t.Errorf("an instance that is down marked the account: %q", acc.Problem)
}
}
func TestAnnounceReturnsAtOnceAndTheWorkerPostsInTheBackground(t *testing.T) {
s, st, rm := newService(t)
rm.posted = make(chan post, 1)
_ = st.Save(context.Background(), 1, Credentials{Instance: "https://mastodon.social", Token: "tok"})
ctx, stop := context.WithCancel(context.Background())
done := make(chan struct{})
go func() { s.Run(ctx); close(done) }()
s.Announce(1, 7)
select {
case p := <-rm.posted:
if p.status == "" {
t.Error("empty post")
}
case <-time.After(3 * time.Second):
t.Fatal("nothing was posted")
}
stop()
<-done
}
func TestAnnounceNeverBlocksEvenWhenNobodyIsWorking(t *testing.T) {
s, _, _ := newService(t)
finished := make(chan struct{})
go func() {
for i := 0; i < 500; i++ {
s.Announce(1, 7)
}
close(finished)
}()
select {
case <-finished:
case <-time.After(3 * time.Second):
t.Fatal("Announce blocked")
}
}