feat: rainyun http client — adapter pattern with auth injection
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
package rainyun
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestClientAuthHeader(t *testing.T) {
|
||||
var gotKey string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotKey = r.Header.Get("X-Api-Key")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte(`{"code":0,"data":{"id":1,"name":"test"}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := newClient(srv.URL, "sk-test")
|
||||
var result struct {
|
||||
Code int `json:"code"`
|
||||
Data struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := c.get(context.Background(), "/test", &result); err != nil {
|
||||
t.Fatalf("get() error: %v", err)
|
||||
}
|
||||
if gotKey != "sk-test" {
|
||||
t.Errorf("X-Api-Key = %q, want %q", gotKey, "sk-test")
|
||||
}
|
||||
if result.Data.Name != "test" {
|
||||
t.Errorf("Data.Name = %q, want %q", result.Data.Name, "test")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientAPIError(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(404)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte(`{"code":1002,"msg":"not found"}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := newClient(srv.URL, "sk-test")
|
||||
var result any
|
||||
err := c.get(context.Background(), "/error", &result)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for 404")
|
||||
}
|
||||
apiErr, ok := err.(*APIError)
|
||||
if !ok {
|
||||
t.Fatalf("expected *APIError, got %T", err)
|
||||
}
|
||||
if apiErr.StatusCode != 404 {
|
||||
t.Errorf("error code = %d, want 404", apiErr.StatusCode)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user