Files

73 lines
2.0 KiB
Go

package app_test
import (
"context"
"testing"
"git.jokresner.de/johannes/meilisearch-showcase/internal/app"
"git.jokresner.de/johannes/meilisearch-showcase/internal/domain/catalog"
)
// fakeIndex is an in-memory MovieIndex: the port makes the use cases testable
// without Meilisearch running.
type fakeIndex struct {
movies map[catalog.MovieID]*catalog.Movie
schema bool
}
func newFake() *fakeIndex { return &fakeIndex{movies: map[catalog.MovieID]*catalog.Movie{}} }
func (f *fakeIndex) EnsureSchema(context.Context) error { f.schema = true; return nil }
func (f *fakeIndex) Index(_ context.Context, ms []*catalog.Movie) error {
for _, m := range ms {
f.movies[m.ID()] = m
}
return nil
}
func (f *fakeIndex) Get(_ context.Context, id catalog.MovieID) (*catalog.Movie, error) {
m, ok := f.movies[id]
if !ok {
return nil, catalog.ErrNotFound
}
return m, nil
}
func (f *fakeIndex) Delete(_ context.Context, id catalog.MovieID) error {
delete(f.movies, id)
return nil
}
func (f *fakeIndex) Search(_ context.Context, q catalog.Query) (catalog.Results, error) {
var r catalog.Results
for _, m := range f.movies {
r.Hits = append(r.Hits, catalog.Hit{Movie: m})
}
r.EstimatedTotal = int64(len(r.Hits))
return r, nil
}
func TestImportRejectsInvalidRecord(t *testing.T) {
svc := app.NewCatalogService(newFake())
_, err := svc.ImportMovies(context.Background(), []app.MovieInput{
{ID: "1", Title: "Alien", Year: 1979, Rating: 8.5},
{ID: "2", Title: "", Year: 1999, Rating: 7},
})
if err == nil {
t.Fatal("want validation error for record 1")
}
}
func TestImportThenGet(t *testing.T) {
f := newFake()
svc := app.NewCatalogService(f)
n, err := svc.ImportMovies(context.Background(), []app.MovieInput{{ID: "1", Title: "Alien", Year: 1979, Rating: 8.5}})
if err != nil || n != 1 {
t.Fatalf("import: n=%d err=%v", n, err)
}
m, err := svc.Get(context.Background(), "1")
if err != nil || m.Title() != "Alien" {
t.Fatalf("get: %v %v", m, err)
}
if _, err := svc.Get(context.Background(), " "); err == nil {
t.Fatal("want invalid id error")
}
}