github.com/graywolf-at-work-2/terraform-vendor@v1.4.5/internal/httpclient/useragent_test.go (about) 1 package httpclient 2 3 import ( 4 "fmt" 5 "os" 6 "testing" 7 8 "github.com/hashicorp/terraform/version" 9 ) 10 11 func TestUserAgentString_env(t *testing.T) { 12 expectedBase := fmt.Sprintf(userAgentFormat, version.Version) 13 if oldenv, isSet := os.LookupEnv(uaEnvVar); isSet { 14 defer os.Setenv(uaEnvVar, oldenv) 15 } else { 16 defer os.Unsetenv(uaEnvVar) 17 } 18 19 for i, c := range []struct { 20 expected string 21 additional string 22 }{ 23 {expectedBase, ""}, 24 {expectedBase, " "}, 25 {expectedBase, " \n"}, 26 27 {fmt.Sprintf("%s test/1", expectedBase), "test/1"}, 28 {fmt.Sprintf("%s test/2", expectedBase), "test/2 "}, 29 {fmt.Sprintf("%s test/3", expectedBase), " test/3 "}, 30 {fmt.Sprintf("%s test/4", expectedBase), "test/4 \n"}, 31 } { 32 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { 33 if c.additional == "" { 34 os.Unsetenv(uaEnvVar) 35 } else { 36 os.Setenv(uaEnvVar, c.additional) 37 } 38 39 actual := UserAgentString() 40 41 if c.expected != actual { 42 t.Fatalf("Expected User-Agent '%s' does not match '%s'", c.expected, actual) 43 } 44 }) 45 } 46 } 47 48 func TestUserAgentAppendViaEnvVar(t *testing.T) { 49 if oldenv, isSet := os.LookupEnv(uaEnvVar); isSet { 50 defer os.Setenv(uaEnvVar, oldenv) 51 } else { 52 defer os.Unsetenv(uaEnvVar) 53 } 54 55 expectedBase := "HashiCorp Terraform/0.0.0 (+https://www.terraform.io)" 56 57 testCases := []struct { 58 envVarValue string 59 expected string 60 }{ 61 {"", expectedBase}, 62 {" ", expectedBase}, 63 {" \n", expectedBase}, 64 {"test/1", expectedBase + " test/1"}, 65 {"test/1 (comment)", expectedBase + " test/1 (comment)"}, 66 } 67 68 for i, tc := range testCases { 69 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { 70 os.Unsetenv(uaEnvVar) 71 os.Setenv(uaEnvVar, tc.envVarValue) 72 givenUA := TerraformUserAgent("0.0.0") 73 if givenUA != tc.expected { 74 t.Fatalf("Expected User-Agent '%s' does not match '%s'", tc.expected, givenUA) 75 } 76 }) 77 } 78 }