Files
pipu-music/services/api/internal/search/meili_test.go
T
mrleo1nid 82f3eed9a0
ci / api / api (push) Successful in 56s
ci / db / db (push) Successful in 1m13s
Improve search relevance and artist transliteration
2026-10-30 12:09:24 +03:00

115 lines
4.5 KiB
Go

package search
import (
"context"
"encoding/json"
"errors"
"log/slog"
"net/http"
"net/http/httptest"
"reflect"
"testing"
"github.com/stretchr/testify/require"
)
func TestQueryRequiresAllWordsAndProtectsExactArtist(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var body struct {
Queries []MultiQuery `json:"queries"`
}
require.NoError(t, json.NewDecoder(r.Body).Decode(&body))
require.Len(t, body.Queries, 3)
for _, q := range body.Queries {
require.Equal(t, "all", q.MatchingStrategy)
}
require.Contains(t, body.Queries[0].AttributesToRetrieve, "name_translit")
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"results":[{"hits":[{"id":"collab","name":"Boulevard Depo X 161"},{"id":"exact","name":"BOULEVARD DEPO","name_translit":["боулевард депо","бульвар депо"]}],"estimatedTotalHits":2},{"hits":[]},{"hits":[]}]}`))
}))
defer srv.Close()
h := &Handler{meili: NewMeili(srv.URL, ""), log: slog.Default()}
f, err := h.query(context.Background(), "бульвар депо", limits{artists: 3, albums: 3, tracks: 5})
require.NoError(t, err)
require.Equal(t, []string{"exact"}, f.exactArtists)
f = h.personal(context.Background(), f, limits{artists: 1})
require.Equal(t, []string{"exact"}, f.artists)
}
func TestExactArtistName(t *testing.T) {
require.True(t, exactArtistName("boulevard depo", "BOULEVARD DEPO", nil))
require.True(t, exactArtistName("БУЛЬВАР ДЕПО", "BOULEVARD DEPO", []any{"бульвар депо"}))
require.True(t, exactArtistName("кино", "Kino", "кино"))
require.False(t, exactArtistName("boulevard depo", "Depo Boulevard", nil))
require.False(t, exactArtistName("boulevard depo", "Boulevard Depo X 161", nil))
require.False(t, exactArtistName("!", "", nil))
}
func TestDeleteIndexIfExists(t *testing.T) {
for _, tc := range []struct {
name string
lookupCode int
task string
wantErr bool
}{
{name: "missing index", lookupCode: http.StatusNotFound},
{name: "existing index", lookupCode: http.StatusOK, task: `{"status":"succeeded"}`},
{name: "lookup failure", lookupCode: http.StatusServiceUnavailable, wantErr: true},
{name: "delete failure", lookupCode: http.StatusOK, task: `{"status":"failed","error":{"code":"internal","message":"disk error"}}`, wantErr: true},
{name: "concurrent deletion", lookupCode: http.StatusOK, task: `{"status":"failed","error":{"code":"index_not_found","message":"Index disappeared"}}`},
} {
t.Run(tc.name, func(t *testing.T) {
var requests []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests = append(requests, r.Method+" "+r.URL.Path)
w.Header().Set("Content-Type", "application/json")
switch r.Method + " " + r.URL.Path {
case "GET /indexes/tracks_next":
w.WriteHeader(tc.lookupCode)
_, _ = w.Write([]byte(`{}`))
case "DELETE /indexes/tracks_next":
w.WriteHeader(http.StatusAccepted)
_, _ = w.Write([]byte(`{"taskUid":1}`))
case "GET /tasks/1":
_, _ = w.Write([]byte(tc.task))
default:
t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
w.WriteHeader(http.StatusBadRequest)
}
}))
defer srv.Close()
err := NewMeili(srv.URL, "").deleteIndexIfExists(context.Background(), "tracks_next")
if (err != nil) != tc.wantErr {
t.Fatalf("err = %v, wantErr = %v", err, tc.wantErr)
}
wantRequests := []string{"GET /indexes/tracks_next"}
if tc.lookupCode == http.StatusOK {
wantRequests = append(wantRequests, "DELETE /indexes/tracks_next", "GET /tasks/1")
}
if !reflect.DeepEqual(requests, wantRequests) {
t.Fatalf("requests = %v, want %v", requests, wantRequests)
}
})
}
}
// На чистом Meilisearch удаление несуществующего индекса падает в задаче, а не ответом 404.
func TestCallMapsFailedIndexTaskToNotFound(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.Method == http.MethodDelete {
w.WriteHeader(http.StatusAccepted)
_, _ = w.Write([]byte(`{"taskUid":0}`))
return
}
_, _ = w.Write([]byte(`{"status":"failed","error":{"code":"index_not_found","message":"Index ` + "`x`" + ` not found."}}`))
}))
defer srv.Close()
err := NewMeili(srv.URL, "").call(context.Background(), http.MethodDelete, "/indexes/x", nil)
if !errors.Is(err, ErrMeiliNotFound) {
t.Fatalf("err = %v, want ErrMeiliNotFound", err)
}
}