| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
package kubernetes_test |
| 18 |
|
| 19 |
import ( |
| 20 |
"context" |
| 21 |
"net/http" |
| 22 |
"net/http/httptest" |
| 23 |
"testing" |
| 24 |
|
| 25 |
v1 "k8s.io/api/core/v1" |
| 26 |
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 27 |
"k8s.io/client-go/kubernetes" |
| 28 |
"k8s.io/client-go/kubernetes/scheme" |
| 29 |
"k8s.io/client-go/rest" |
| 30 |
) |
| 31 |
|
| 32 |
func TestClientUserAgent(t *testing.T) { |
| 33 |
tests := []struct { |
| 34 |
name string |
| 35 |
userAgent string |
| 36 |
expect string |
| 37 |
}{ |
| 38 |
{ |
| 39 |
name: "empty", |
| 40 |
expect: rest.DefaultKubernetesUserAgent(), |
| 41 |
}, |
| 42 |
{ |
| 43 |
name: "custom", |
| 44 |
userAgent: "test-agent", |
| 45 |
expect: "test-agent", |
| 46 |
}, |
| 47 |
} |
| 48 |
|
| 49 |
for _, tc := range tests { |
| 50 |
t.Run(tc.name, func(t *testing.T) { |
| 51 |
ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 52 |
userAgent := r.Header.Get("User-Agent") |
| 53 |
if userAgent != tc.expect { |
| 54 |
t.Errorf("User Agent expected: %s got: %s", tc.expect, userAgent) |
| 55 |
http.Error(w, "Unexpected user agent", http.StatusBadRequest) |
| 56 |
return |
| 57 |
} |
| 58 |
w.Header().Set("Content-Type", "application/json") |
| 59 |
w.Write([]byte("{}")) |
| 60 |
})) |
| 61 |
ts.Start() |
| 62 |
defer ts.Close() |
| 63 |
|
| 64 |
gv := v1.SchemeGroupVersion |
| 65 |
config := &rest.Config{ |
| 66 |
Host: ts.URL, |
| 67 |
} |
| 68 |
config.GroupVersion = &gv |
| 69 |
config.NegotiatedSerializer = scheme.Codecs.WithoutConversion() |
| 70 |
config.UserAgent = tc.userAgent |
| 71 |
config.ContentType = "application/json" |
| 72 |
|
| 73 |
client, err := kubernetes.NewForConfig(config) |
| 74 |
if err != nil { |
| 75 |
t.Fatalf("failed to create REST client: %v", err) |
| 76 |
} |
| 77 |
_, err = client.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{}) |
| 78 |
if err != nil { |
| 79 |
t.Error(err) |
| 80 |
} |
| 81 |
_, err = client.CoreV1().Secrets("").List(context.TODO(), metav1.ListOptions{}) |
| 82 |
if err != nil { |
| 83 |
t.Error(err) |
| 84 |
} |
| 85 |
}) |
| 86 |
} |
| 87 |
|
| 88 |
} |