package main import ( "context" "encoding/json" "net/http" "net/http/httptest" "strings" "testing" "github.com/missionworkforce/missionmatch/internal/platform/inference" ) // TestOpenAIGuardRefusesEnabledWithoutSecret is GATE 0: with the openai backend enabled and no key in // the secret store, the guard returns an error so the gateway refuses to boot. An empty model is refused // the same way, because a backend with no model cannot serve. func TestOpenAIGuardRefusesEnabledWithoutSecret(t *testing.T) { if err := openaiGuard(true, "", "gpt-4o-mini"); err == nil { t.Fatal("openai enabled with an empty key must refuse to boot") } if err := openaiGuard(true, "sk-live-placeholder", ""); err == nil { t.Fatal("openai enabled with an empty model must refuse to boot") } } // TestOpenAIGuardAllowsEnabledWithSecretAndModel proves a correctly configured enable is allowed to boot. func TestOpenAIGuardAllowsEnabledWithSecretAndModel(t *testing.T) { if err := openaiGuard(true, "sk-live-placeholder", "gpt-4o-mini"); err != nil { t.Fatalf("openai enabled with a key and a model must boot: %v", err) } } // TestOpenAIGuardDisabledNeedsNoSecret proves the default off deployment needs no key present, so a // deployment that never turns on the external lane is not forced to hold an unused secret. func TestOpenAIGuardDisabledNeedsNoSecret(t *testing.T) { if err := openaiGuard(false, "", ""); err != nil { t.Fatalf("openai disabled must not require a key or a model: %v", err) } } // TestGenerateOpenAIParsesChatCompletionAndSendsBearer proves the openai backend speaks the chat // completions contract and presents the bearer credential from the secret store. func TestGenerateOpenAIParsesChatCompletionAndSendsBearer(t *testing.T) { var gotAuth string srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gotAuth = r.Header.Get("Authorization") _ = json.NewEncoder(w).Encode(map[string]any{ "choices": []map[string]any{{"message": map[string]string{"content": "A normalized public requirement."}}}, "usage": map[string]any{"completion_tokens": 7}, }) })) defer srv.Close() s := &server{cfg: config{openaiURL: srv.URL, openaiKey: "sk-test-abc", openaiModel: "gpt-4o-mini"}, ollama: &http.Client{}} text, tokens, model, err := s.generateOpenAI(context.Background(), "system", inference.GenerateRequest{Prompt: "normalize this public notice"}, 128) if err != nil { t.Fatalf("generateOpenAI failed: %v", err) } if text != "A normalized public requirement." { t.Errorf("unexpected text: %q", text) } if tokens != 7 { t.Errorf("expected 7 completion tokens, got %d", tokens) } if !strings.HasPrefix(model, "openai:") { t.Errorf("expected a model label prefixed openai:, got %q", model) } if gotAuth != "Bearer sk-test-abc" { t.Errorf("expected the bearer credential to be presented, got %q", gotAuth) } }