Skip to content

Commit 42e8446

Browse files
committed
kubeadm: increase ut coverage for util/version
Signed-off-by: xin.li <[email protected]>
1 parent 60c4c2b commit 42e8446

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

cmd/kubeadm/app/util/version_test.go

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ package util
1818

1919
import (
2020
"fmt"
21+
"net/http"
22+
"net/http/httptest"
2123
"os"
2224
"path"
2325
"strings"
@@ -525,3 +527,72 @@ func TestValidateStableVersion(t *testing.T) {
525527
func errorFetcher(url string, timeout time.Duration) (string, error) {
526528
return "should not make internet calls", errors.Errorf("should not make internet calls, tried to request url: %s", url)
527529
}
530+
531+
func TestFetchFromURL(t *testing.T) {
532+
tests := []struct {
533+
name string
534+
url string
535+
expected string
536+
timeout time.Duration
537+
code int
538+
body string
539+
expectErr bool
540+
}{
541+
{
542+
name: "normal success",
543+
url: "/normal",
544+
code: http.StatusOK,
545+
body: "normal response",
546+
expected: "normal response",
547+
expectErr: false,
548+
},
549+
{
550+
name: "HTTP error status",
551+
url: "/error",
552+
code: http.StatusBadRequest,
553+
body: "bad request",
554+
expected: "bad request",
555+
expectErr: true,
556+
},
557+
{
558+
name: "Request timeout",
559+
url: "/timeout",
560+
timeout: time.Millisecond * 50,
561+
expectErr: true,
562+
},
563+
}
564+
565+
for _, tt := range tests {
566+
t.Run(tt.name, func(t *testing.T) {
567+
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
568+
if tt.code != 0 {
569+
w.WriteHeader(tt.code)
570+
}
571+
if tt.body != "" {
572+
if _, err := w.Write([]byte(tt.body)); err != nil {
573+
t.Error("Write body failed.")
574+
}
575+
}
576+
if tt.timeout == time.Millisecond*50 {
577+
time.Sleep(time.Millisecond * 200)
578+
w.WriteHeader(http.StatusOK)
579+
if _, err := w.Write([]byte("Delayed response")); err != nil {
580+
t.Error("Write body failed.")
581+
}
582+
}
583+
})
584+
585+
ts := httptest.NewServer(handler)
586+
defer ts.Close()
587+
588+
url := ts.URL + tt.url
589+
result, err := fetchFromURL(url, tt.timeout)
590+
if (err != nil) != tt.expectErr {
591+
t.Errorf("expected error: %v, got: %v", tt.expectErr, err)
592+
}
593+
if tt.expected != result {
594+
t.Errorf("expected result: %q, got: %q", tt.expected, result)
595+
}
596+
})
597+
}
598+
}

0 commit comments

Comments
 (0)