bosun.org@v0.0.0-20210513094433-e25bc3e69a1f/graphite/graphite_test.go (about)

     1  package graphite
     2  
     3  import (
     4  	"bytes"
     5  	"io/ioutil"
     6  	"net/http"
     7  	"net/url"
     8  	"testing"
     9  
    10  	"github.com/stretchr/testify/assert"
    11  )
    12  
    13  // RoundTripFunc .
    14  type RoundTripFunc func(req *http.Request) *http.Response
    15  
    16  // RoundTrip .
    17  func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
    18  	return f(req), nil
    19  }
    20  
    21  //NewTestClient returns *http.Client with Transport replaced to avoid making real calls
    22  func NewTestClient(fn RoundTripFunc) *http.Client {
    23  	return &http.Client{
    24  		Transport: RoundTripFunc(fn),
    25  	}
    26  }
    27  
    28  func TestUrlParsePanic(t *testing.T) {
    29  	// url.Parse has unexpected behavior when not specifying a scheme
    30  	// This would cause a panic in Query when using ip addresses with no scheme
    31  	// e.g. 127.0.0.1:8080
    32  
    33  	tests := []struct {
    34  		host string
    35  		URL  url.URL
    36  	}{
    37  		{"localhost:8080", url.URL{Scheme: "http", Host: "localhost:8080", Path: "/render/", RawQuery: "format=json"}},
    38  		{"127.0.0.1:8080", url.URL{Scheme: "http", Host: "127.0.0.1:8080", Path: "/render/", RawQuery: "format=json"}},
    39  		{"https://graphite.skyscanner.net:8080", url.URL{Scheme: "https", Host: "graphite.skyscanner.net:8080", Path: "/render/", RawQuery: "format=json"}}}
    40  
    41  	r := Request{}
    42  	stockResponse := http.Response{
    43  		StatusCode: 200,
    44  		Body:       ioutil.NopCloser(bytes.NewBufferString(`OK`)),
    45  		Header:     make(http.Header),
    46  	}
    47  
    48  	for _, test := range tests {
    49  		DefaultClient = NewTestClient(func(req *http.Request) *http.Response {
    50  			assert.Equal(t, test.URL, *req.URL)
    51  			return &stockResponse
    52  
    53  		})
    54  		r.Query(test.host, nil)
    55  
    56  	}
    57  
    58  }