github.com/hashicorp/terraform-plugin-sdk@v1.17.2/internal/httpclient/client_test.go (about) 1 package httpclient 2 3 import ( 4 "fmt" 5 "net/http" 6 "net/http/httptest" 7 "net/url" 8 "os" 9 "testing" 10 11 "github.com/hashicorp/terraform-plugin-sdk/internal/version" 12 ) 13 14 func TestUserAgentString_env(t *testing.T) { 15 expectedBase := fmt.Sprintf(userAgentFormat, version.Version) 16 if oldenv, isSet := os.LookupEnv(uaEnvVar); isSet { 17 defer os.Setenv(uaEnvVar, oldenv) 18 } else { 19 defer os.Unsetenv(uaEnvVar) 20 } 21 22 for i, c := range []struct { 23 expected string 24 additional string 25 }{ 26 {expectedBase, ""}, 27 {expectedBase, " "}, 28 {expectedBase, " \n"}, 29 30 {fmt.Sprintf("%s test/1", expectedBase), "test/1"}, 31 {fmt.Sprintf("%s test/2", expectedBase), "test/2 "}, 32 {fmt.Sprintf("%s test/3", expectedBase), " test/3 "}, 33 {fmt.Sprintf("%s test/4", expectedBase), "test/4 \n"}, 34 } { 35 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { 36 if c.additional == "" { 37 os.Unsetenv(uaEnvVar) 38 } else { 39 os.Setenv(uaEnvVar, c.additional) 40 } 41 42 actual := UserAgentString() 43 44 if c.expected != actual { 45 t.Fatalf("Expected User-Agent '%s' does not match '%s'", c.expected, actual) 46 } 47 }) 48 } 49 } 50 51 func TestNew_userAgent(t *testing.T) { 52 var actualUserAgent string 53 ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { 54 actualUserAgent = req.UserAgent() 55 })) 56 defer ts.Close() 57 58 tsURL, err := url.Parse(ts.URL) 59 if err != nil { 60 t.Fatal(err) 61 } 62 63 for i, c := range []struct { 64 expected string 65 request func(c *http.Client) error 66 }{ 67 { 68 fmt.Sprintf("Terraform/%s", version.Version), 69 func(c *http.Client) error { 70 _, err := c.Get(ts.URL) 71 return err 72 }, 73 }, 74 { 75 "foo/1", 76 func(c *http.Client) error { 77 req := &http.Request{ 78 Method: "GET", 79 URL: tsURL, 80 Header: http.Header{ 81 "User-Agent": []string{"foo/1"}, 82 }, 83 } 84 _, err := c.Do(req) 85 return err 86 }, 87 }, 88 { 89 "", 90 func(c *http.Client) error { 91 req := &http.Request{ 92 Method: "GET", 93 URL: tsURL, 94 Header: http.Header{ 95 "User-Agent": []string{""}, 96 }, 97 } 98 _, err := c.Do(req) 99 return err 100 }, 101 }, 102 } { 103 t.Run(fmt.Sprintf("%d %s", i, c.expected), func(t *testing.T) { 104 actualUserAgent = "" 105 cli := New() 106 err := c.request(cli) 107 if err != nil { 108 t.Fatal(err) 109 } 110 if actualUserAgent != c.expected { 111 t.Fatalf("actual User-Agent '%s' is not '%s'", actualUserAgent, c.expected) 112 } 113 }) 114 } 115 }