Files
pipu-music/services/api/internal/search/meili_test.go
T
mrleo1nid f59d1e8d03
ci / db / db (push) Successful in 52s
ci / api / api (push) Successful in 42s
fix(search): skip deletion of missing temporary indexes
2026-10-28 23:56:46 +03:00

79 lines
2.8 KiB
Go

package search
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"reflect"
"testing"
)
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)
}
}