package handlers import ( "bytes" "context" "encoding/json" "io" "mime/multipart" "net/http/httptest" "os" "path/filepath" "strings" "sync" "testing" "time" "github.com/gin-gonic/gin" "adam-french.co.uk/usaco-site/internal/audiostore" "adam-french.co.uk/usaco-site/internal/claude" "adam-french.co.uk/usaco-site/internal/explain" "adam-french.co.uk/usaco-site/internal/index" "adam-french.co.uk/usaco-site/internal/review" "adam-french.co.uk/usaco-site/internal/transcribe" ) // fakeReviewer answers every review with one verdict, or fails. type fakeReviewer struct { user string fail bool } func (f *fakeReviewer) Model() string { return "fake-model" } func (f *fakeReviewer) JSON(_ context.Context, req claude.Request, out any) error { f.user = req.User if f.fail { return &claude.Failure{Msg: "Claude declined to answer"} } *out.(*review.Result) = review.Result{Verdict: "correct", Summary: "Union-find over the edges."} return nil } type fakeTranscriber struct { file string audio []byte err error } func (f *fakeTranscriber) Model() string { return "fake-whisper" } func (f *fakeTranscriber) Transcribe(_ context.Context, filename string, audio []byte) (*transcribe.Transcript, error) { f.file, f.audio = filename, audio if f.err != nil { return nil, f.err } return &transcribe.Transcript{ Text: "Um, I'd union the cows.", Duration: 60, Segments: []transcribe.Segment{{Start: 0, End: 4, Text: " Um, I'd union the cows."}}, }, nil } // fakeStore is a bucket in a map. type fakeStore struct { mu sync.Mutex objs map[string]string typ map[string]string } func newFakeStore() *fakeStore { return &fakeStore{objs: map[string]string{}, typ: map[string]string{}} } func (f *fakeStore) Put(_ context.Context, key, contentType string, b []byte) error { f.mu.Lock() defer f.mu.Unlock() f.objs[key], f.typ[key] = string(b), contentType return nil } func (f *fakeStore) Get(_ context.Context, key string) (*audiostore.Object, error) { f.mu.Lock() defer f.mu.Unlock() b, ok := f.objs[key] if !ok { return nil, audiostore.ErrNotFound } return &audiostore.Object{Body: io.NopCloser(strings.NewReader(b)), ContentType: f.typ[key], Size: int64(len(b))}, nil } func (f *fakeStore) Delete(_ context.Context, key string) error { f.mu.Lock() defer f.mu.Unlock() delete(f.objs, key) return nil } func (f *fakeStore) keys() []string { f.mu.Lock() defer f.mu.Unlock() var ks []string for k := range f.objs { ks = append(ks, k) } return ks } // upload posts a recording form; size pads the audio to that many bytes. func upload(r *gin.Engine, name, filename string, size int, fields ...string) *httptest.ResponseRecorder { var body bytes.Buffer w := multipart.NewWriter(&body) for i := 0; i+1 < len(fields); i += 2 { w.WriteField(fields[i], fields[i+1]) } if filename != "" { part, _ := w.CreateFormFile("audio", filename) part.Write([]byte("ID3")) if size > 3 { part.Write(make([]byte, size-3)) } } w.Close() return do(r, "POST", "/usaco/api/problems/"+name+"/review", body.String(), true, "Content-Type", w.FormDataContentType()) } func waitReview(t *testing.T, r *gin.Engine, name string) explain.Status { t.Helper() for range 400 { var s explain.Status json.Unmarshal(do(r, "GET", "/usaco/api/problems/"+name+"/review", "", true).Body.Bytes(), &s) if s.State != explain.Running { return s } time.Sleep(5 * time.Millisecond) } t.Fatal("review still running") return explain.Status{} } func withStatement(t *testing.T, r *gin.Engine) { t.Helper() if rec := do(r, "PUT", "/usaco/api/problems/moocast/meta", `{"statement":"# Moocast\nwalkie-talkies"}`, true); rec.Code != 200 { t.Fatalf("saving a statement = %d: %s", rec.Code, rec.Body) } } func TestReviewNeedsConfigAndAValidRecording(t *testing.T) { r, repo, _ := setup(t) if rec := upload(r, "moocast", "a.mp3", 10); rec.Code != 503 { t.Fatalf("no Claude = %d, want 503", rec.Code) } repo.srv.Claude = &fakeReviewer{} if rec := upload(r, "moocast", "a.mp3", 10); rec.Code != 503 || !strings.Contains(rec.Body.String(), "TRANSCRIBE_API_KEY") { t.Fatalf("no transcriber = %d %s, want 503", rec.Code, rec.Body) } repo.srv.Transcriber = &fakeTranscriber{} if rec := do(r, "POST", "/usaco/api/problems/moocast/review", "", false); rec.Code != 401 { t.Fatalf("public upload = %d, want 401", rec.Code) } for _, c := range []struct { file string size int want int }{ {"", 0, 400}, {"notes.txt", 10, 400}, {"a.mp3", transcribe.MaxBytes + 1, 413}, {"a.mp3", 10, 400}, // no statement or link yet } { if rec := upload(r, "moocast", c.file, c.size); rec.Code != c.want { t.Errorf("%q (%d bytes) = %d %s, want %d", c.file, c.size, rec.Code, rec.Body, c.want) } } if rec := upload(r, "moocast", "a.mp3", 10, "note", strings.Repeat("x", maxNote+1)); rec.Code != 400 { t.Errorf("long note = %d, want 400", rec.Code) } } func TestReviewWritesAndCommits(t *testing.T) { r, repo, _ := setup(t) fr, ft := &fakeReviewer{}, &fakeTranscriber{} repo.srv.Claude, repo.srv.Transcriber = fr, ft withStatement(t, r) if rec := upload(r, "moocast", "Take 1.M4A", 10, "note", "mock interview", "includeCode", "true"); rec.Code != 202 { t.Fatalf("start = %d: %s", rec.Code, rec.Body) } if s := waitReview(t, r, "moocast"); s.State != explain.Done { t.Fatalf("job = %+v, want done", s) } if !strings.HasSuffix(ft.file, ".m4a") || string(ft.audio[:3]) != "ID3" { t.Errorf("transcriber got %q, %q", ft.file, ft.audio) } for _, want := range []string{"walkie-talkies", "\nmock interview", "", "[00:00] Um, I'd union the cows."} { if !strings.Contains(fr.user, want) { t.Errorf("prompt is missing %q:\n%s", want, fr.user) } } if last := repo.msg[len(repo.msg)-1]; last != "Review moocast" { t.Errorf("commit subject = %q", last) } files, _ := filepath.Glob(filepath.Join(repo.dir, "solved/moocast/reviews/*.md")) if len(files) != 1 { t.Fatalf("reviews = %v", files) } b, _ := os.ReadFile(files[0]) if md := string(b); !strings.HasPrefix(md, "\n_Reviewed by fake-model") || !strings.Contains(md, "transcribed by fake-whisper") { t.Errorf("review = %s", md) } var adm index.Problem json.Unmarshal(do(r, "GET", "/usaco/api/problems/moocast", "", true).Body.Bytes(), &adm) if len(adm.Reviews) != 1 || adm.Reviews[0].Verdict != "correct" || adm.Reviews[0].HasAudio || adm.ReviewCount != 1 { t.Fatalf("admin reviews = %+v", adm.Reviews) } id := adm.Reviews[0].ID if rec := do(r, "GET", "/usaco/api/problems/moocast/reviews/"+id+"/audio", "", true); rec.Code != 404 { t.Errorf("audio with no store = %d, want 404", rec.Code) } // Reviews are the admin's alone, even on a solved problem. var pub struct { Reviews []index.Review ReviewCount int } json.Unmarshal(do(r, "GET", "/usaco/api/problems/moocast", "", false).Body.Bytes(), &pub) if len(pub.Reviews) != 0 || pub.ReviewCount != 0 { t.Errorf("public view = %+v", pub) } if body := do(r, "GET", "/usaco/api/problems", "", false).Body.String(); strings.Contains(body, `"reviewCount":1`) { t.Errorf("public list shows the review count: %s", body) } if rec := do(r, "DELETE", "/usaco/api/problems/moocast/reviews/"+id, "", false); rec.Code != 401 { t.Errorf("public delete = %d, want 401", rec.Code) } } func TestReviewKeepsAndRemovesTheRecording(t *testing.T) { r, repo, _ := setup(t) store := newFakeStore() repo.srv.Claude, repo.srv.Transcriber, repo.srv.Audio = &fakeReviewer{}, &fakeTranscriber{}, store withStatement(t, r) upload(r, "moocast", "take.mp3", 100) if s := waitReview(t, r, "moocast"); s.State != explain.Done { t.Fatalf("job = %+v, want done", s) } var p index.Problem json.Unmarshal(do(r, "GET", "/usaco/api/problems/moocast", "", true).Body.Bytes(), &p) if len(p.Reviews) != 1 || !p.Reviews[0].HasAudio { t.Fatalf("reviews = %+v", p.Reviews) } id := p.Reviews[0].ID if keys := store.keys(); len(keys) != 1 || keys[0] != "moocast/"+id+".mp3" { t.Fatalf("stored = %v", keys) } rec := do(r, "GET", "/usaco/api/problems/moocast/reviews/"+id+"/audio", "", true, "Range", "bytes=0-2") if rec.Code != 206 || rec.Body.String() != "ID3" || rec.Header().Get("Content-Type") != "audio/mpeg" { t.Errorf("ranged audio = %d %q %q", rec.Code, rec.Body, rec.Header().Get("Content-Type")) } for _, bad := range []string{"..", "2026-01-01-000000", "notes"} { if rec := do(r, "GET", "/usaco/api/problems/moocast/reviews/"+bad+"/audio", "", true); rec.Code != 404 { t.Errorf("audio for %q = %d, want 404", bad, rec.Code) } } if rec := do(r, "DELETE", "/usaco/api/problems/moocast/reviews/"+id, "", true); rec.Code != 200 { t.Fatalf("delete = %d: %s", rec.Code, rec.Body) } if last := repo.msg[len(repo.msg)-1]; last != "Remove review moocast" { t.Errorf("commit subject = %q", last) } if _, err := os.Stat(filepath.Join(repo.dir, "solved/moocast/reviews")); !os.IsNotExist(err) { t.Error("the empty reviews dir should be gone") } if keys := store.keys(); len(keys) != 0 { t.Errorf("recording not removed: %v", keys) } } func TestReviewFailures(t *testing.T) { r, repo, _ := setup(t) store := newFakeStore() ft := &fakeTranscriber{err: &transcribe.Failure{Msg: "no speech was found in the recording"}} fr := &fakeReviewer{} repo.srv.Claude, repo.srv.Transcriber, repo.srv.Audio = fr, ft, store withStatement(t, r) commits := len(repo.msg) upload(r, "moocast", "a.mp3", 10) if s := waitReview(t, r, "moocast"); s.State != explain.Failed || s.Error != "no speech was found in the recording" { t.Fatalf("transcription failure: job = %+v", s) } // The recording is stored before Claude runs, and must not be left // behind when the review fails. ft.err, fr.fail = nil, true upload(r, "moocast", "a.mp3", 10) if s := waitReview(t, r, "moocast"); s.State != explain.Failed || s.Error != "Claude declined to answer" { t.Fatalf("Claude failure: job = %+v", s) } if len(repo.msg) != commits || len(store.keys()) != 0 { t.Errorf("a failed review left commits %v or recordings %v", repo.msg[commits:], store.keys()) } }