@@ -18,6 +18,8 @@ package util
18
18
19
19
import (
20
20
"fmt"
21
+ "net/http"
22
+ "net/http/httptest"
21
23
"os"
22
24
"path"
23
25
"strings"
@@ -525,3 +527,72 @@ func TestValidateStableVersion(t *testing.T) {
525
527
func errorFetcher (url string , timeout time.Duration ) (string , error ) {
526
528
return "should not make internet calls" , errors .Errorf ("should not make internet calls, tried to request url: %s" , url )
527
529
}
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