Migrating hosting from Codeberg to git.kmalloc.org. Renames the module path in go.mod, every internal import, and the OCI image source label in the Dockerfile. Build and full test suite verified green after the rename.
535 lines
20 KiB
Go
535 lines
20 KiB
Go
package spotifyimport
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"git.kmalloc.org/squid/sonda/internal/listening"
|
|
"git.kmalloc.org/squid/sonda/internal/playlists"
|
|
)
|
|
|
|
type fakeCatalog struct {
|
|
songs []Candidate
|
|
once sync.Once
|
|
entered chan struct{} // closed when Candidates is first called, when set
|
|
release chan struct{} // Candidates waits for it, when set
|
|
}
|
|
|
|
func (f *fakeCatalog) Candidates(context.Context) ([]Candidate, error) {
|
|
if f.entered != nil {
|
|
f.once.Do(func() { close(f.entered) })
|
|
}
|
|
if f.release != nil {
|
|
<-f.release
|
|
}
|
|
return f.songs, nil
|
|
}
|
|
|
|
type fakeListens struct {
|
|
seen map[string]bool
|
|
events []listening.Event
|
|
calls int
|
|
}
|
|
|
|
func (f *fakeListens) RecordMany(_ context.Context, userID int64, events []listening.Event) (int, error) {
|
|
f.calls++
|
|
if f.seen == nil {
|
|
f.seen = map[string]bool{}
|
|
}
|
|
created := 0
|
|
for _, e := range events {
|
|
k := fmt.Sprint(userID, e.IdempotencyKey)
|
|
if !f.seen[k] {
|
|
f.seen[k] = true
|
|
f.events = append(f.events, e)
|
|
created++
|
|
}
|
|
}
|
|
return created, nil
|
|
}
|
|
|
|
type fakePlaylists struct {
|
|
existing []string
|
|
made map[string][]int64
|
|
order []string
|
|
max int // playlists a user may have; 0 is no limit
|
|
nextID int64
|
|
names map[int64]string
|
|
}
|
|
|
|
func (f *fakePlaylists) List(_ context.Context, _ int64, p playlists.Page) (playlists.Listing, error) {
|
|
var all []playlists.Playlist
|
|
for _, n := range f.existing {
|
|
all = append(all, playlists.Playlist{Name: n})
|
|
}
|
|
end := min(p.Offset+p.Limit, len(all))
|
|
start := min(p.Offset, end)
|
|
return playlists.Listing{Items: all[start:end], Total: len(all), Limit: p.Limit, Offset: p.Offset}, nil
|
|
}
|
|
|
|
func (f *fakePlaylists) Create(_ context.Context, _ int64, name, _ string) (playlists.Playlist, error) {
|
|
if f.max > 0 && len(f.existing)+len(f.made) >= f.max {
|
|
return playlists.Playlist{}, playlists.ErrTooMany
|
|
}
|
|
if f.made == nil {
|
|
f.made, f.names = map[string][]int64{}, map[int64]string{}
|
|
}
|
|
f.nextID++
|
|
f.names[f.nextID] = name
|
|
f.made[name] = nil
|
|
f.order = append(f.order, name)
|
|
return playlists.Playlist{ID: f.nextID, Name: name}, nil
|
|
}
|
|
|
|
func (f *fakePlaylists) AddTracks(_ context.Context, _ int64, id int64, ids []int64, _ *int) (playlists.Playlist, error) {
|
|
if len(ids) > playlists.MaxAddAtOnce {
|
|
return playlists.Playlist{}, errors.New("too many at once")
|
|
}
|
|
f.made[f.names[id]] = append(f.made[f.names[id]], ids...)
|
|
return playlists.Playlist{ID: id}, nil
|
|
}
|
|
|
|
var songs = []Candidate{
|
|
{TrackID: 1, Title: "Karma Police", Album: "OK Computer", Artists: []string{"Radiohead"}, DurationMs: 260_000},
|
|
{TrackID: 2, Title: "Airbag", Album: "OK Computer", Artists: []string{"Radiohead"}, DurationMs: 284_000},
|
|
{TrackID: 3, Title: "Hyperballad", Album: "Post", Artists: []string{"Björk"}, DurationMs: 321_000},
|
|
}
|
|
|
|
// fakeRuns keeps the reports in memory, newest first when listed.
|
|
type fakeRuns struct {
|
|
saved []Run
|
|
fail error
|
|
}
|
|
|
|
func (f *fakeRuns) Save(_ context.Context, _ int64, at time.Time, r Report) (int64, error) {
|
|
if f.fail != nil {
|
|
return 0, f.fail
|
|
}
|
|
id := int64(len(f.saved) + 1)
|
|
f.saved = append(f.saved, Run{ID: id, At: at, Report: r})
|
|
return id, nil
|
|
}
|
|
|
|
func (f *fakeRuns) List(_ context.Context, _ int64, limit, offset int) ([]Run, int, error) {
|
|
var all []Run
|
|
for i := len(f.saved) - 1; i >= 0; i-- {
|
|
all = append(all, f.saved[i])
|
|
}
|
|
end := min(offset+limit, len(all))
|
|
start := min(offset, end)
|
|
return all[start:end], len(all), nil
|
|
}
|
|
|
|
// fakeOutside keeps the plays by key, as the database does.
|
|
type fakeOutside struct {
|
|
kept map[string]OutsidePlay
|
|
fail error
|
|
}
|
|
|
|
func (f *fakeOutside) RecordOutside(_ context.Context, _ int64, plays []OutsidePlay) (int, error) {
|
|
if f.fail != nil {
|
|
return 0, f.fail
|
|
}
|
|
if f.kept == nil {
|
|
f.kept = map[string]OutsidePlay{}
|
|
}
|
|
n := 0
|
|
for _, p := range plays {
|
|
if _, ok := f.kept[p.Key]; !ok {
|
|
f.kept[p.Key] = p
|
|
n++
|
|
}
|
|
}
|
|
return n, nil
|
|
}
|
|
|
|
type rig struct {
|
|
svc *Service
|
|
li *fakeListens
|
|
pl *fakePlaylists
|
|
runs *fakeRuns
|
|
out *fakeOutside
|
|
}
|
|
|
|
func newRig(cat *fakeCatalog) rig {
|
|
li, pl, runs, out := &fakeListens{}, &fakePlaylists{}, &fakeRuns{}, &fakeOutside{}
|
|
return rig{NewService(cat, li, pl, runs, out, key, 20*time.Second), li, pl, runs, out}
|
|
}
|
|
|
|
// report runs an import and gives the report of it.
|
|
func (r rig) report(userID int64, files []File) (Report, error) {
|
|
run, err := r.svc.Import(context.Background(), userID, files)
|
|
return run.Report, err
|
|
}
|
|
|
|
func upload(data string) File { return File{R: bytes.NewReader([]byte(data)), Size: int64(len(data))} }
|
|
|
|
func play(ts, artist, title, album string, ms int, extra string) string {
|
|
return fmt.Sprintf(`{"ts":%q,"ms_played":%d,"master_metadata_track_name":%q,"master_metadata_album_artist_name":%q,"master_metadata_album_album_name":%q%s}`,
|
|
ts, ms, title, artist, album, extra)
|
|
}
|
|
|
|
func history(plays ...string) string { return "[" + strings.Join(plays, ",") + "]" }
|
|
|
|
func TestImportRecordsTheListensThatMatchTheLibrary(t *testing.T) {
|
|
r := newRig(&fakeCatalog{songs: songs})
|
|
rep, err := r.report(7, []File{upload(history(
|
|
play("2023-05-01T10:00:00Z", "Radiohead", "Karma Police", "OK Computer", 260_000, `,"reason_end":"trackdone"`),
|
|
play("2023-05-01T10:05:00Z", "Radiohead", "Airbag", "OK Computer", 4_000, `,"reason_end":"fwdbtn","skipped":true`),
|
|
play("2023-05-01T10:06:00Z", "Radiohead", "Creep", "Pablo Honey", 200_000, ``),
|
|
play("2023-05-01T10:10:00Z", "Björk", "Hyperballad", "Post", 321_000, ``),
|
|
`{"ts":"2023-05-01T11:00:00Z","ms_played":999,"master_metadata_track_name":null,"episode_name":"A show"}`,
|
|
))})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
h := rep.History
|
|
if h.Entries != 4 || h.Matched != 3 || h.Imported != 3 || h.AlreadyThere != 0 || h.NotFound != 1 || h.Ignored != 1 {
|
|
t.Errorf("history = %+v", h)
|
|
}
|
|
if len(r.li.events) != 3 {
|
|
t.Fatalf("%d events recorded, want 3", len(r.li.events))
|
|
}
|
|
first := r.li.events[0]
|
|
if first.UserID != 7 || first.TrackID != 1 || first.Type != listening.Complete || first.DurationPlayedMs != 260_000 ||
|
|
!first.OccurredAt.Equal(time.Date(2023, 5, 1, 10, 0, 0, 0, time.UTC)) || !strings.HasPrefix(first.IdempotencyKey, "spotify:") {
|
|
t.Errorf("first event = %+v", first)
|
|
}
|
|
if r.li.events[1].Type != listening.Skip {
|
|
t.Errorf("a skip was recorded as %q", r.li.events[1].Type)
|
|
}
|
|
if len(rep.Missing) != 1 || rep.Missing[0] != (Missing{Artist: "Radiohead", Count: 1}) {
|
|
t.Errorf("missing = %+v", rep.Missing)
|
|
}
|
|
}
|
|
|
|
func TestTheKindOfAPlayComesFromHowItEndedOrHowMuchWasHeard(t *testing.T) {
|
|
r := newRig(&fakeCatalog{songs: songs})
|
|
_, err := r.report(1, []File{upload(history(
|
|
play("2023-01-01T10:00:00Z", "Radiohead", "Karma Police", "", 260_000, `,"reason_end":"trackdone"`), // ran to the end
|
|
play("2023-01-01T11:00:00Z", "Radiohead", "Karma Police", "", 250_000, `,"reason_end":"endplay"`), // 96 per cent, then stopped
|
|
play("2023-01-01T12:00:00Z", "Radiohead", "Karma Police", "", 90_000, `,"reason_end":"endplay"`), // a good part, then stopped
|
|
play("2023-01-01T13:00:00Z", "Radiohead", "Karma Police", "", 5_000, ``), // a few seconds, nothing said
|
|
play("2023-01-01T14:00:00Z", "Radiohead", "Karma Police", "", 90_000, `,"skipped":true`), // the file says skipped
|
|
play("2023-01-01T15:00:00Z", "Radiohead", "Karma Police", "", 9_999_999, `,"reason_end":"trackdone"`), // more than the song is long
|
|
))})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
want := []listening.EventType{listening.Complete, listening.Complete, listening.Play, listening.Skip, listening.Skip, listening.Complete}
|
|
for i, e := range r.li.events {
|
|
if e.Type != want[i] {
|
|
t.Errorf("play %d is %q, want %q", i, e.Type, want[i])
|
|
}
|
|
}
|
|
// A play longer than the song would be refused by the listening rules: it is brought to the length of the song.
|
|
if last := r.li.events[5]; last.DurationPlayedMs != 260_000 {
|
|
t.Errorf("duration = %d, want the length of the song", last.DurationPlayedMs)
|
|
}
|
|
}
|
|
|
|
func TestImportingTheSameFilesAgainAddsNothing(t *testing.T) {
|
|
r := newRig(&fakeCatalog{songs: songs})
|
|
data := history(
|
|
play("2023-05-01T10:00:00Z", "Radiohead", "Karma Police", "OK Computer", 260_000, ``),
|
|
play("2023-05-01T10:10:00Z", "Björk", "Hyperballad", "Post", 321_000, ``),
|
|
)
|
|
if _, err := r.report(1, []File{upload(data)}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
rep, err := r.report(1, []File{upload(data)})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if rep.History.Imported != 0 || rep.History.AlreadyThere != 2 || len(r.li.events) != 2 {
|
|
t.Errorf("second import: %+v, %d events", rep.History, len(r.li.events))
|
|
}
|
|
}
|
|
|
|
func TestTheSamePlayInTheTwoShapesOfFileIsCountedOnce(t *testing.T) {
|
|
r := newRig(&fakeCatalog{songs: songs})
|
|
extended := history(play("2022-01-02T08:30:41Z", "Björk", "Hyperballad", "Post", 321_000, `,"reason_end":"trackdone"`))
|
|
older := `[{"endTime":"2022-01-02 08:30","artistName":"Björk","trackName":"Hyperballad","msPlayed":321000}]`
|
|
rep, err := r.report(1, []File{upload(extended), upload(older)})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(r.li.events) != 1 || rep.History.Imported != 1 || rep.History.AlreadyThere != 1 {
|
|
t.Errorf("%d events, %+v: want the play once", len(r.li.events), rep.History)
|
|
}
|
|
}
|
|
|
|
func TestPlaylistsBecomePlaylistsWithTheSongsThatWereFound(t *testing.T) {
|
|
r := newRig(&fakeCatalog{songs: songs})
|
|
r.pl.existing = []string{"Mine already"}
|
|
rep, err := r.report(1, []File{upload(`{"playlists":[
|
|
{"name":"Road","items":[
|
|
{"track":{"trackName":"Hyperballad","artistName":"Björk","albumName":"Post"}},
|
|
{"track":{"trackName":"Creep","artistName":"Radiohead","albumName":"Pablo Honey"}},
|
|
{"track":{"trackName":"Karma Police","artistName":"Radiohead","albumName":"OK Computer"}},
|
|
{"track":null,"episode":{"name":"A show"}}]},
|
|
{"name":"mine ALREADY","items":[{"track":{"trackName":"Airbag","artistName":"Radiohead"}}]},
|
|
{"name":"Nothing here","items":[{"track":{"trackName":"Creep","artistName":"Radiohead"}}]},
|
|
{"name":"","items":[{"track":{"trackName":"Airbag","artistName":"Radiohead"}}]}
|
|
]}`)})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := r.pl.made["Road"]; len(got) != 2 || got[0] != 3 || got[1] != 1 {
|
|
t.Errorf("Road has %v, want the found songs in the order of the playlist: 3, 1", got)
|
|
}
|
|
if _, made := r.pl.made["mine ALREADY"]; made {
|
|
t.Error("a playlist whose name the person already has was made again")
|
|
}
|
|
if _, made := r.pl.made["Nothing here"]; made {
|
|
t.Error("a playlist with none of its songs found was made")
|
|
}
|
|
if got := r.pl.made["Spotify playlist"]; len(got) != 1 {
|
|
t.Errorf("a playlist with no name got %v under %v", got, r.pl.order)
|
|
}
|
|
want := []PlaylistResult{
|
|
{Name: "Road", Tracks: 4, Matched: 2, Status: "created"},
|
|
{Name: "mine ALREADY", Tracks: 1, Matched: 1, Status: "exists"},
|
|
{Name: "Nothing here", Tracks: 1, Matched: 0, Status: "empty"},
|
|
{Name: "Spotify playlist", Tracks: 1, Matched: 1, Status: "created"},
|
|
}
|
|
if fmt.Sprint(rep.Playlists) != fmt.Sprint(want) {
|
|
t.Errorf("playlists = %+v, want %+v", rep.Playlists, want)
|
|
}
|
|
if len(rep.Missing) != 1 || rep.Missing[0].Artist != "Radiohead" || rep.Missing[0].Count != 2 {
|
|
t.Errorf("missing = %+v, want Radiohead twice (Creep in two playlists)", rep.Missing)
|
|
}
|
|
}
|
|
|
|
func TestALongPlaylistIsAddedInPieces(t *testing.T) {
|
|
r := newRig(&fakeCatalog{songs: songs})
|
|
var items []string
|
|
for i := 0; i < 1234; i++ {
|
|
items = append(items, `{"track":{"trackName":"Airbag","artistName":"Radiohead"}}`)
|
|
}
|
|
rep, err := r.report(1, []File{upload(`{"playlists":[{"name":"Long","items":[` + strings.Join(items, ",") + `]}]}`)})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(r.pl.made["Long"]) != 1234 || rep.Playlists[0].Status != "created" {
|
|
t.Errorf("%d songs, %+v", len(r.pl.made["Long"]), rep.Playlists)
|
|
}
|
|
}
|
|
|
|
func TestWhenThePersonHasAsManyPlaylistsAsAllowedTheRestAreSaidSo(t *testing.T) {
|
|
r := newRig(&fakeCatalog{songs: songs})
|
|
r.pl.max = 1
|
|
item := `{"track":{"trackName":"Airbag","artistName":"Radiohead"}}`
|
|
rep, err := r.report(1, []File{upload(`{"playlists":[{"name":"A","items":[` + item + `]},{"name":"B","items":[` + item + `]},{"name":"C","items":[` + item + `]}]}`)})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
got := []string{rep.Playlists[0].Status, rep.Playlists[1].Status, rep.Playlists[2].Status}
|
|
if fmt.Sprint(got) != "[created limit limit]" {
|
|
t.Errorf("statuses = %v", got)
|
|
}
|
|
}
|
|
|
|
func TestTheArtistsThatAreMissingAreListedMostPlayedFirst(t *testing.T) {
|
|
r := newRig(&fakeCatalog{songs: songs})
|
|
var plays []string
|
|
for i := 0; i < 5; i++ {
|
|
plays = append(plays, play(fmt.Sprintf("2023-01-01T10:0%d:00Z", i), "Blur", "Song 2", "", 120_000, ``))
|
|
}
|
|
for i := 0; i < 3; i++ {
|
|
plays = append(plays, play(fmt.Sprintf("2023-01-02T10:0%d:00Z", i), "oasis", "Wonderwall", "", 120_000, ``))
|
|
plays = append(plays, play(fmt.Sprintf("2023-01-03T10:0%d:00Z", i), "Oasis", "Supersonic", "", 120_000, ``))
|
|
}
|
|
rep, err := r.report(1, []File{upload(history(plays...))})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(rep.Missing) != 2 || rep.Missing[0] != (Missing{"Oasis", 6}) && rep.Missing[0] != (Missing{"oasis", 6}) || rep.Missing[1] != (Missing{"Blur", 5}) {
|
|
t.Errorf("missing = %+v, want Oasis 6 (the spellings together) then Blur 5", rep.Missing)
|
|
}
|
|
}
|
|
|
|
func TestOnlyTheMostPlayedMissingArtistsAreListed(t *testing.T) {
|
|
r := newRig(&fakeCatalog{songs: songs})
|
|
var plays []string
|
|
for i := 0; i < MaxMissing+30; i++ {
|
|
plays = append(plays, play("2023-01-01T10:00:00Z", fmt.Sprintf("Artist %03d", i), "Song", "", 120_000, ``))
|
|
}
|
|
rep, err := r.report(1, []File{upload(history(plays...))})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(rep.Missing) != MaxMissing || rep.MissingTotal != MaxMissing+30 {
|
|
t.Errorf("%d listed of %d, want %d of %d", len(rep.Missing), rep.MissingTotal, MaxMissing, MaxMissing+30)
|
|
}
|
|
}
|
|
|
|
func TestFilesWithNothingOfSpotifyAreRefused(t *testing.T) {
|
|
r := newRig(&fakeCatalog{songs: songs})
|
|
_, err := r.report(1, []File{upload(`{"hello":"world"}`), upload("words")})
|
|
if !errors.Is(err, ErrNothingFound) {
|
|
t.Errorf("err = %v, want ErrNothingFound", err)
|
|
}
|
|
if len(r.li.events) != 0 {
|
|
t.Error("something was recorded")
|
|
}
|
|
}
|
|
|
|
func TestAnImportThatIsRunningBlocksAnotherOfTheSamePerson(t *testing.T) {
|
|
cat := &fakeCatalog{songs: songs, entered: make(chan struct{}), release: make(chan struct{})}
|
|
r := newRig(cat)
|
|
done := make(chan error, 1)
|
|
go func() {
|
|
_, err := r.report(5, []File{upload(history(play("2023-01-01T10:00:00Z", "Radiohead", "Airbag", "", 1000, ``)))})
|
|
done <- err
|
|
}()
|
|
<-cat.entered
|
|
if _, err := r.report(5, []File{upload(`[]`)}); !errors.Is(err, ErrBusy) {
|
|
t.Errorf("a second import of the same person: %v, want ErrBusy", err)
|
|
}
|
|
close(cat.release)
|
|
if err := <-done; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
// Once it is over, the person can import again, and somebody else could all along.
|
|
if _, err := r.report(5, []File{upload(`[]`)}); errors.Is(err, ErrBusy) {
|
|
t.Error("still busy after the import ended")
|
|
}
|
|
}
|
|
|
|
func TestManyListensAreRecordedInBatches(t *testing.T) {
|
|
r := newRig(&fakeCatalog{songs: songs})
|
|
var plays []string
|
|
for i := 0; i < 2500; i++ {
|
|
plays = append(plays, play(time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Duration(i)*time.Minute).Format(time.RFC3339), "Radiohead", "Airbag", "", 100_000, ``))
|
|
}
|
|
rep, err := r.report(1, []File{upload(history(plays...))})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if rep.History.Imported != 2500 || r.li.calls < 2 {
|
|
t.Errorf("imported %d in %d calls, want 2500 in several", rep.History.Imported, r.li.calls)
|
|
}
|
|
}
|
|
|
|
func TestAnImportIsKeptAndListedNewestFirst(t *testing.T) {
|
|
r := newRig(&fakeCatalog{songs: songs})
|
|
first, err := r.svc.Import(context.Background(), 1, []File{upload(history(play("2023-01-01T10:00:00Z", "Radiohead", "Airbag", "", 280_000, `,"reason_end":"trackdone"`)))})
|
|
if err != nil || first.ID != 1 || first.At.IsZero() || first.Report.History.Imported != 1 {
|
|
t.Fatalf("first import = %+v, %v, want it kept as 1 with one listen", first, err)
|
|
}
|
|
second, err := r.svc.Import(context.Background(), 1, []File{upload(history(play("2023-01-01T10:00:00Z", "Radiohead", "Airbag", "", 280_000, `,"reason_end":"trackdone"`)))})
|
|
if err != nil || second.ID != 2 || second.Report.History.AlreadyThere != 1 {
|
|
t.Fatalf("second import = %+v, %v, want 2 with the play already there", second, err)
|
|
}
|
|
page, err := r.svc.History(context.Background(), 1, 10, 0)
|
|
if err != nil || page.Total != 2 || len(page.Items) != 2 || page.Items[0].ID != 2 || page.Items[1].ID != 1 {
|
|
t.Fatalf("History = %+v, %v, want the two imports, newest first", page, err)
|
|
}
|
|
if page.Limit != 10 || page.Offset != 0 {
|
|
t.Errorf("page = %d/%d, want 10/0", page.Limit, page.Offset)
|
|
}
|
|
}
|
|
|
|
func TestAnImportThatFindsNothingIsNotKept(t *testing.T) {
|
|
r := newRig(&fakeCatalog{songs: songs})
|
|
if _, err := r.report(1, []File{upload(`{"hello":"world"}`)}); !errors.Is(err, ErrNothingFound) {
|
|
t.Fatalf("err = %v, want ErrNothingFound", err)
|
|
}
|
|
if len(r.runs.saved) != 0 {
|
|
t.Errorf("%d reports kept, want none", len(r.runs.saved))
|
|
}
|
|
}
|
|
|
|
func TestAReportThatCannotBeKeptStillComesBack(t *testing.T) {
|
|
r := newRig(&fakeCatalog{songs: songs})
|
|
r.runs.fail = errors.New("disk full")
|
|
run, err := r.svc.Import(context.Background(), 1, []File{upload(history(play("2023-01-01T10:00:00Z", "Radiohead", "Airbag", "", 280_000, `,"reason_end":"trackdone"`)))})
|
|
if !errors.Is(err, ErrNotKept) {
|
|
t.Fatalf("err = %v, want ErrNotKept", err)
|
|
}
|
|
if run.ID != 0 || run.Report.History.Imported != 1 || run.At.IsZero() {
|
|
t.Errorf("run = %+v, want the report with ID 0", run)
|
|
}
|
|
}
|
|
|
|
func TestHistoryPagesAreBounded(t *testing.T) {
|
|
r := newRig(&fakeCatalog{songs: songs})
|
|
for i := 0; i < 3; i++ {
|
|
r.runs.saved = append(r.runs.saved, Run{ID: int64(i + 1)})
|
|
}
|
|
page, err := r.svc.History(context.Background(), 1, 0, 0)
|
|
if err != nil || page.Limit != DefaultPage || len(page.Items) != 3 {
|
|
t.Errorf("no limit = %+v, %v, want the default page", page, err)
|
|
}
|
|
if page, _ := r.svc.History(context.Background(), 1, 100000, 0); page.Limit != MaxPage {
|
|
t.Errorf("a huge limit = %d, want %d", page.Limit, MaxPage)
|
|
}
|
|
if _, err := r.svc.History(context.Background(), 1, -1, 0); !errors.Is(err, ErrInvalidPage) {
|
|
t.Errorf("a negative limit: %v, want ErrInvalidPage", err)
|
|
}
|
|
if _, err := r.svc.History(context.Background(), 1, 10, -1); !errors.Is(err, ErrInvalidPage) {
|
|
t.Errorf("a negative offset: %v, want ErrInvalidPage", err)
|
|
}
|
|
}
|
|
|
|
func TestThePlaysOfArtistsNotInTheLibraryKeepOnlyTheArtistAndTheTime(t *testing.T) {
|
|
r := newRig(&fakeCatalog{songs: songs})
|
|
rep, err := r.report(1, []File{upload(history(
|
|
play("2023-01-01T10:00:00Z", "Radiohead", "Airbag", "", 280_000, `,"reason_end":"trackdone"`), // in the library
|
|
play("2023-01-01T10:05:00Z", "Blur", "Song 2", "Blur", 120_000, `,"reason_end":"trackdone"`), // not, and it counts
|
|
play("2023-01-01T10:10:00Z", "Blur", "Parklife", "Parklife", 5_000, `,"skipped":true`), // not, and a skip
|
|
play("2023-01-01T10:15:00Z", "Oasis", "Wonderwall", "", 3_000, ``), // not, shorter than a listen
|
|
play("2023-01-01T10:20:00Z", "Oasis", "Supersonic", "", 90_000, ``), // not, played enough
|
|
))})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if rep.History.NotFound != 4 || rep.History.KeptOutside != 2 {
|
|
t.Fatalf("history = %+v, want 4 not found and 2 kept", rep.History)
|
|
}
|
|
if len(r.out.kept) != 2 {
|
|
t.Fatalf("%d plays kept, want 2: %v", len(r.out.kept), r.out.kept)
|
|
}
|
|
got := map[string]time.Time{}
|
|
for k, p := range r.out.kept {
|
|
if !strings.HasPrefix(k, "spotify:") || p.Key != k {
|
|
t.Errorf("key %q of %+v", k, p)
|
|
}
|
|
got[p.Artist] = p.PlayedAt
|
|
}
|
|
if !got["Blur"].Equal(time.Date(2023, 1, 1, 10, 5, 0, 0, time.UTC)) || !got["Oasis"].Equal(time.Date(2023, 1, 1, 10, 20, 0, 0, time.UTC)) {
|
|
t.Errorf("kept = %v, want Blur at 10:05 and Oasis at 10:20", got)
|
|
}
|
|
}
|
|
|
|
func TestImportingAgainDoesNotKeepAPlayTwice(t *testing.T) {
|
|
r := newRig(&fakeCatalog{songs: songs})
|
|
files := func() []File {
|
|
return []File{upload(history(play("2023-01-01T10:05:00Z", "Blur", "Song 2", "Blur", 120_000, `,"reason_end":"trackdone"`)))}
|
|
}
|
|
if _, err := r.report(1, files()); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := r.report(1, files()); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(r.out.kept) != 1 {
|
|
t.Errorf("%d plays kept after two imports, want 1", len(r.out.kept))
|
|
}
|
|
}
|
|
|
|
func TestAnErrorWhileKeepingThePlaysFailsTheImport(t *testing.T) {
|
|
r := newRig(&fakeCatalog{songs: songs})
|
|
r.out.fail = errors.New("disk full")
|
|
_, err := r.report(1, []File{upload(history(play("2023-01-01T10:05:00Z", "Blur", "Song 2", "Blur", 120_000, `,"reason_end":"trackdone"`)))})
|
|
if err == nil || !strings.Contains(err.Error(), "disk full") {
|
|
t.Errorf("err = %v, want the disk error", err)
|
|
}
|
|
}
|