package httpapi import ( "bytes" "context" "mime/multipart" "net/http" "net/http/httptest" "testing" "speech-learning-api/internal/domain" "speech-learning-api/internal/store" ) type exerciseLookupStore struct { DataStore exerciseID string userID string } func (s *exerciseLookupStore) GetExercise(_ context.Context, exerciseID, userID string) (domain.Exercise, error) { s.exerciseID = exerciseID s.userID = userID return domain.Exercise{}, store.ErrNotFound } func TestCreateAttemptScopesExerciseLookupToCurrentUser(t *testing.T) { var body bytes.Buffer form := multipart.NewWriter(&body) if err := form.WriteField("exercise_id", "ex_other_user"); err != nil { t.Fatal(err) } if err := form.Close(); err != nil { t.Fatal(err) } req := httptest.NewRequest(http.MethodPost, "/practice/attempts", &body) req.Header.Set("Content-Type", form.FormDataContentType()) req = req.WithContext(context.WithValue(req.Context(), userIDKey, "usr_current")) recorder := httptest.NewRecorder() lookup := &exerciseLookupStore{} server := &Server{store: lookup} server.createAttempt(recorder, req) if recorder.Code != http.StatusNotFound { t.Fatalf("status = %d, want 404", recorder.Code) } if lookup.exerciseID != "ex_other_user" || lookup.userID != "usr_current" { t.Fatalf("lookup used exercise %q and user %q", lookup.exerciseID, lookup.userID) } } func TestNextLessonScopesPreviousExerciseToCurrentUser(t *testing.T) { req := httptest.NewRequest(http.MethodPost, "/lessons/next", bytes.NewBufferString(`{"previous_exercise_id":"ex_other_user"}`)) req = req.WithContext(context.WithValue(req.Context(), userIDKey, "usr_current")) recorder := httptest.NewRecorder() lookup := &exerciseLookupStore{} server := &Server{store: lookup} server.nextLesson(recorder, req) if recorder.Code != http.StatusNotFound { t.Fatalf("status = %d, want 404", recorder.Code) } if lookup.exerciseID != "ex_other_user" || lookup.userID != "usr_current" { t.Fatalf("lookup used exercise %q and user %q", lookup.exerciseID, lookup.userID) } }