github.com/gavriloga/terraform@v0.11.12-beta1/httpclient/client_test.go (about)

     1  package httpclient
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"net/http/httptest"
     7  	"net/url"
     8  	"testing"
     9  
    10  	"github.com/hashicorp/terraform/version"
    11  )
    12  
    13  func TestNew_userAgent(t *testing.T) {
    14  	var actualUserAgent string
    15  	ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
    16  		actualUserAgent = req.UserAgent()
    17  	}))
    18  	defer ts.Close()
    19  
    20  	tsURL, err := url.Parse(ts.URL)
    21  	if err != nil {
    22  		t.Fatal(err)
    23  	}
    24  
    25  	for i, c := range []struct {
    26  		expected string
    27  		request  func(c *http.Client) error
    28  	}{
    29  		{
    30  			fmt.Sprintf("Terraform/%s", version.Version),
    31  			func(c *http.Client) error {
    32  				_, err := c.Get(ts.URL)
    33  				return err
    34  			},
    35  		},
    36  		{
    37  			"foo/1",
    38  			func(c *http.Client) error {
    39  				req := &http.Request{
    40  					Method: "GET",
    41  					URL:    tsURL,
    42  					Header: http.Header{
    43  						"User-Agent": []string{"foo/1"},
    44  					},
    45  				}
    46  				_, err := c.Do(req)
    47  				return err
    48  			},
    49  		},
    50  		{
    51  			"",
    52  			func(c *http.Client) error {
    53  				req := &http.Request{
    54  					Method: "GET",
    55  					URL:    tsURL,
    56  					Header: http.Header{
    57  						"User-Agent": []string{""},
    58  					},
    59  				}
    60  				_, err := c.Do(req)
    61  				return err
    62  			},
    63  		},
    64  	} {
    65  		t.Run(fmt.Sprintf("%d %s", i, c.expected), func(t *testing.T) {
    66  			actualUserAgent = ""
    67  			cli := New()
    68  			err := c.request(cli)
    69  			if err != nil {
    70  				t.Fatal(err)
    71  			}
    72  			if actualUserAgent != c.expected {
    73  				t.Fatalf("actual User-Agent '%s' is not '%s'", actualUserAgent, c.expected)
    74  			}
    75  		})
    76  	}
    77  }