97 lines
2.6 KiB
Go
97 lines
2.6 KiB
Go
package globals
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func TestGostClientCreateServiceUsesBasicAuthAndPathPrefix(t *testing.T) {
|
|
var (
|
|
gotPath string
|
|
gotAuth string
|
|
gotBody GostServiceConfig
|
|
)
|
|
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
gotPath = r.URL.Path
|
|
gotAuth = r.Header.Get("Authorization")
|
|
if err := json.NewDecoder(r.Body).Decode(&gotBody); err != nil {
|
|
t.Fatalf("Decode failed: %v", err)
|
|
}
|
|
w.WriteHeader(http.StatusOK)
|
|
}))
|
|
defer server.Close()
|
|
|
|
client := NewGost(server.URL, 0, "/api", "user", "pass")
|
|
err := client.CreateService(&GostServiceConfig{
|
|
Name: "svc-1",
|
|
Addr: ":10000",
|
|
Handler: GostHandlerConfig{
|
|
Type: "auto",
|
|
Chain: "chain-a",
|
|
Auther: "auther-a",
|
|
},
|
|
Listener: GostListenerConfig{Type: "tcp"},
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("CreateService returned error: %v", err)
|
|
}
|
|
|
|
if gotPath != "/api/config/services" {
|
|
t.Fatalf("unexpected path: %s", gotPath)
|
|
}
|
|
if gotAuth != "Basic "+base64.StdEncoding.EncodeToString([]byte("user:pass")) {
|
|
t.Fatalf("unexpected auth header: %s", gotAuth)
|
|
}
|
|
if gotBody.Name != "svc-1" || gotBody.Handler.Type != "auto" || gotBody.Handler.Chain != "chain-a" {
|
|
t.Fatalf("unexpected request body: %+v", gotBody)
|
|
}
|
|
}
|
|
|
|
func TestGostClientDeleteServiceTreats404AsIdempotent(t *testing.T) {
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
http.NotFound(w, r)
|
|
}))
|
|
defer server.Close()
|
|
|
|
client := NewGost(server.URL, 0, "", "user", "pass")
|
|
if err := client.DeleteService("svc-1"); !IsGostNotFound(err) {
|
|
t.Fatalf("expected gost not found error, got: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestGostClientGetChainReadsTopLevelName(t *testing.T) {
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path != "/config/chains/chain-a" {
|
|
t.Fatalf("unexpected path: %s", r.URL.Path)
|
|
}
|
|
_, _ = w.Write([]byte(`{"name":"chain-a"}`))
|
|
}))
|
|
defer server.Close()
|
|
|
|
client := NewGost(server.URL, 0, "", "user", "pass")
|
|
chain, err := client.GetChain("chain-a")
|
|
if err != nil {
|
|
t.Fatalf("GetChain returned error: %v", err)
|
|
}
|
|
if chain.Name != "chain-a" {
|
|
t.Fatalf("unexpected chain: %+v", chain)
|
|
}
|
|
}
|
|
|
|
func TestNormalizeGostPathPrefix(t *testing.T) {
|
|
if got := normalizeGostPathPrefix("api/"); got != "/api" {
|
|
t.Fatalf("unexpected prefix: %s", got)
|
|
}
|
|
if got := normalizeGostPathPrefix(""); got != "" {
|
|
t.Fatalf("unexpected empty prefix: %s", got)
|
|
}
|
|
if !strings.HasPrefix(normalizeGostPathPrefix("/v1"), "/") {
|
|
t.Fatal("expected normalized prefix to start with slash")
|
|
}
|
|
}
|