package prompts import ( "context" "encoding/json" "net/http" "net/http/httptest" "os" "path/filepath" "testing" ) func samplePrompts() []byte { data, err := json.Marshal([]map[string]any{ {"id": 1, "id_section": 1, "name": "behavioral", "prompt": "p1", "dt_create": "2026-01-01"}, {"id": 2, "id_section": 1, "name": "client_data", "prompt": "p2", "dt_create": "2026-01-01"}, {"id": 3, "id_section": 2, "name": "other", "prompt": "p3", "dt_create": "2026-01-01"}, }) if err != nil { panic(err) } return data } func TestLoadStatic(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "prompts.json") if err := os.WriteFile(path, samplePrompts(), 0o644); err != nil { t.Fatal(err) } l := New("static", path, "", "", 1) got, err := l.Load(context.Background()) if err != nil { t.Fatal(err) } if len(got) != 2 { t.Fatalf("want 2 prompts for section 1, got %d", len(got)) } if got[0].Name != "behavioral" || got[1].Name != "client_data" { t.Fatalf("unexpected names: %v, %v", got[0].Name, got[1].Name) } } func TestLoadStaticAllSections(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "prompts.json") if err := os.WriteFile(path, samplePrompts(), 0o644); err != nil { t.Fatal(err) } l := New("static", path, "", "", 0) got, err := l.Load(context.Background()) if err != nil { t.Fatal(err) } if len(got) != 3 { t.Fatalf("want 3 prompts without filter, got %d", len(got)) } } func TestLoadStaticMissingFile(t *testing.T) { l := New("static", filepath.Join(t.TempDir(), "missing.json"), "", "", 1) _, err := l.Load(context.Background()) if err == nil { t.Fatal("expected error for missing file") } } func TestLoadHTTP(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/metrics/" { t.Fatalf("path: got %s", r.URL.Path) } if r.URL.Query().Get("id_section") != "1" { t.Fatalf("id_section: got %s", r.URL.Query().Get("id_section")) } if auth := r.Header.Get("Authorization"); auth != "Bearer test-key" { t.Fatalf("auth: got %q", auth) } w.Header().Set("Content-Type", "application/json") _, _ = w.Write(samplePrompts()) })) defer srv.Close() l := New("http", "", srv.URL, "test-key", 1) got, err := l.Load(context.Background()) if err != nil { t.Fatal(err) } if len(got) != 2 { t.Fatalf("want 2 prompts, got %d", len(got)) } } func TestLoadHTTPErrorStatus(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusInternalServerError) _, _ = w.Write([]byte("boom")) })) defer srv.Close() l := New("http", "", srv.URL, "", 1) _, err := l.Load(context.Background()) if err == nil { t.Fatal("expected error on 500") } } func TestLoadHTTPMissingBaseURL(t *testing.T) { l := New("http", "", "", "", 1) _, err := l.Load(context.Background()) if err == nil { t.Fatal("expected error without base URL") } }