Files
2026-11-17 21:11:30 +00:00

85 lines
2.4 KiB
Go

package k8s
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"git.site.latha.org/experiments/gitea-k3s-deployer/internal/config"
"git.site.latha.org/experiments/gitea-k3s-deployer/internal/manifest"
)
func TestResourcePath(t *testing.T) {
cases := []struct {
apiVersion string
kind string
ns string
name string
want string
}{
{"v1", "Namespace", "", "apps", "/api/v1/namespaces/apps"},
{"v1", "Service", "default", "web", "/api/v1/namespaces/default/services/web"},
{"apps/v1", "Deployment", "apps", "web", "/apis/apps/v1/namespaces/apps/deployments/web"},
{"networking.k8s.io/v1", "Ingress", "apps", "web", "/apis/networking.k8s.io/v1/namespaces/apps/ingresses/web"},
}
for _, tc := range cases {
got := ResourcePath(tc.apiVersion, tc.kind, tc.ns, tc.name)
if got != tc.want {
t.Errorf("ResourcePath(%q,%q,%q,%q) = %q, want %q", tc.apiVersion, tc.kind, tc.ns, tc.name, got, tc.want)
}
}
}
func TestExternalApplyServerSidePatch(t *testing.T) {
var gotMethod, gotPath, gotContentType, gotAuth, gotBody string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotMethod = r.Method
gotPath = r.URL.Path + "?" + r.URL.RawQuery
gotContentType = r.Header.Get("Content-Type")
gotAuth = r.Header.Get("Authorization")
b, _ := io.ReadAll(r.Body)
gotBody = string(b)
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"kind":"Service"}`))
}))
defer srv.Close()
client, err := NewClient(config.Config{
KubeMode: "external",
KubeAPIURL: srv.URL,
KubeToken: "test-token",
})
if err != nil {
t.Fatalf("NewClient error: %v", err)
}
err = client.Apply(context.Background(), manifest.K8sObject{
APIVersion: "v1",
Kind: "Service",
Namespace: "default",
Name: "demo",
RawYAML: []byte("apiVersion: v1\nkind: Service\n"),
})
if err != nil {
t.Fatalf("Apply error: %v", err)
}
if gotMethod != http.MethodPatch {
t.Errorf("method = %s, want PATCH", gotMethod)
}
if !strings.Contains(gotPath, "/api/v1/namespaces/default/services/demo?fieldManager=gitea-k3s-deployer&force=true") {
t.Errorf("unexpected path: %s", gotPath)
}
if gotContentType != "application/apply-patch+yaml" {
t.Errorf("Content-Type = %s", gotContentType)
}
if gotAuth != "Bearer test-token" {
t.Errorf("Authorization = %s", gotAuth)
}
if !strings.Contains(gotBody, "kind: Service") {
t.Errorf("unexpected body: %s", gotBody)
}
}