diff --git a/pkg/providers/azureopenai/client_test.go b/pkg/providers/azureopenai/client_test.go index 3a6c796d..5f529c90 100644 --- a/pkg/providers/azureopenai/client_test.go +++ b/pkg/providers/azureopenai/client_test.go @@ -2,7 +2,12 @@ package azureopenai import ( "context" - "fmt" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" "testing" "glide/pkg/api/schemas" @@ -12,21 +17,73 @@ import ( "github.com/stretchr/testify/require" ) -func TestOpenAIClient_ChatRequest(t *testing.T) { +func TestAzureOpenAIClient_ChatRequest(t *testing.T) { + // AuzureOpenAI Chat API: https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#chat-completions + azureOpenAIMock := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + rawPayload, _ := io.ReadAll(r.Body) + + var data interface{} + // Parse the JSON body + err := json.Unmarshal(rawPayload, &data) + if err != nil { + t.Errorf("error decoding payload (%q): %v", string(rawPayload), err) + } + + chatResponse, err := os.ReadFile(filepath.Clean("./testdata/chat.success.json")) + if err != nil { + t.Errorf("error reading openai chat mock response: %v", err) + } + + w.Header().Set("Content-Type", "application/json") + _, err = w.Write(chatResponse) + + if err != nil { + t.Errorf("error on sending chat response: %v", err) + } + }) + + azureOpenAIServer := httptest.NewServer(azureOpenAIMock) + defer azureOpenAIServer.Close() + ctx := context.Background() cfg := DefaultConfig() + cfg.BaseURL = azureOpenAIServer.URL client, err := NewClient(cfg, telemetry.NewTelemetryMock()) require.NoError(t, err) request := schemas.UnifiedChatRequest{Message: schemas.ChatMessage{ - Role: "user", // TODO: limit to system,user,assistant,tool + Role: "user", Content: "What's the biggest animal?", }} response, err := client.Chat(ctx, &request) - fmt.Print(response) require.NoError(t, err) - require.Equal(t, "chatcmpl-123", response.ID) + require.Equal(t, "chatcmpl-8cdqrFT2lBQlHz0EDvvq6oQcRxNcZ", response.ID) +} + +func TestAzureOpenAIClient_ChatError(t *testing.T) { + azureOpenAIMock := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + }) + + azureOpenAIServer := httptest.NewServer(azureOpenAIMock) + defer azureOpenAIServer.Close() + + ctx := context.Background() + cfg := DefaultConfig() + cfg.BaseURL = azureOpenAIServer.URL + + client, err := NewClient(cfg, telemetry.NewTelemetryMock()) + require.NoError(t, err) + + request := schemas.UnifiedChatRequest{Message: schemas.ChatMessage{ + Role: "user", + Content: "What's the biggest animal?", + }} + + response, err := client.Chat(ctx, &request) + require.Error(t, err) + require.Nil(t, response) }