Skip to content

Commit

Permalink
#4: add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
mkrueger12 committed Jan 3, 2024
1 parent 2dd1ce4 commit a2447e8
Showing 1 changed file with 62 additions and 5 deletions.
67 changes: 62 additions & 5 deletions pkg/providers/azureopenai/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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)
}

0 comments on commit a2447e8

Please sign in to comment.