124 lines
2.6 KiB
Go
124 lines
2.6 KiB
Go
package client
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"testing"
|
|
|
|
"git.threesix.ai/jordan/sp4-verify-1770325799/pkg/auth"
|
|
)
|
|
|
|
func TestAuthClient_ValidateToken(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
response ValidateResponse
|
|
statusCode int
|
|
wantErr bool
|
|
wantUserID string
|
|
}{
|
|
{
|
|
name: "valid token",
|
|
response: ValidateResponse{
|
|
Data: struct {
|
|
Valid bool `json:"valid"`
|
|
User *auth.User `json:"user,omitempty"`
|
|
Error string `json:"error,omitempty"`
|
|
}{
|
|
Valid: true,
|
|
User: &auth.User{
|
|
ID: "user-123",
|
|
Email: "test@example.com",
|
|
},
|
|
},
|
|
},
|
|
statusCode: http.StatusOK,
|
|
wantErr: false,
|
|
wantUserID: "user-123",
|
|
},
|
|
{
|
|
name: "invalid token",
|
|
response: ValidateResponse{
|
|
Data: struct {
|
|
Valid bool `json:"valid"`
|
|
User *auth.User `json:"user,omitempty"`
|
|
Error string `json:"error,omitempty"`
|
|
}{
|
|
Valid: false,
|
|
Error: "token expired",
|
|
},
|
|
},
|
|
statusCode: http.StatusOK,
|
|
wantErr: true,
|
|
},
|
|
{
|
|
name: "server error",
|
|
statusCode: http.StatusInternalServerError,
|
|
wantErr: true,
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
// Create test server
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
// Verify path
|
|
if r.URL.Path != "/api/auth-svc/validate" {
|
|
t.Errorf("unexpected path: %s", r.URL.Path)
|
|
}
|
|
|
|
// Verify auth header is present
|
|
if r.Header.Get("Authorization") == "" {
|
|
t.Error("missing Authorization header")
|
|
}
|
|
|
|
w.WriteHeader(tt.statusCode)
|
|
if tt.statusCode == http.StatusOK {
|
|
_ = json.NewEncoder(w).Encode(tt.response)
|
|
}
|
|
}))
|
|
defer server.Close()
|
|
|
|
// Set the env var for service discovery
|
|
os.Setenv("AUTH_SVC_URL", server.URL)
|
|
defer os.Unsetenv("AUTH_SVC_URL")
|
|
|
|
// Create client
|
|
client, err := NewAuthClient()
|
|
if err != nil {
|
|
t.Fatalf("failed to create client: %v", err)
|
|
}
|
|
|
|
// Call validate
|
|
user, err := client.ValidateToken(context.Background(), "test-token")
|
|
|
|
if tt.wantErr {
|
|
if err == nil {
|
|
t.Error("expected error, got nil")
|
|
}
|
|
return
|
|
}
|
|
|
|
if err != nil {
|
|
t.Fatalf("unexpected error: %v", err)
|
|
}
|
|
|
|
if user.ID != tt.wantUserID {
|
|
t.Errorf("user ID = %s, want %s", user.ID, tt.wantUserID)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestNewAuthClient_MissingURL(t *testing.T) {
|
|
// Ensure env var is not set
|
|
os.Unsetenv("AUTH_SVC_URL")
|
|
|
|
_, err := NewAuthClient()
|
|
if err == nil {
|
|
t.Error("expected error when AUTH_SVC_URL is not set")
|
|
}
|
|
}
|