github.com/lulzWill/go-agent@v2.1.2+incompatible/internal/url_test.go (about) 1 package internal 2 3 import ( 4 "net/url" 5 "strings" 6 "testing" 7 8 "github.com/lulzWill/go-agent/internal/crossagent" 9 ) 10 11 func TestSafeURLNil(t *testing.T) { 12 if out := SafeURL(nil); "" != out { 13 t.Error(out) 14 } 15 } 16 17 func TestSafeURL(t *testing.T) { 18 var testcases []struct { 19 Testname string `json:"testname"` 20 Expect string `json:"expected"` 21 Input string `json:"input"` 22 } 23 24 err := crossagent.ReadJSON("url_clean.json", &testcases) 25 if err != nil { 26 t.Fatal(err) 27 } 28 29 for _, tc := range testcases { 30 if strings.Contains(tc.Input, ";") { 31 // This test case was over defensive: 32 // http://www.ietf.org/rfc/rfc3986.txt 33 continue 34 } 35 36 // Only use testcases which have a scheme, otherwise the urls 37 // may not be valid and may not be correctly handled by 38 // url.Parse. 39 if strings.HasPrefix(tc.Input, "p:") { 40 u, err := url.Parse(tc.Input) 41 if nil != err { 42 t.Error(tc.Testname, tc.Input, err) 43 continue 44 } 45 out := SafeURL(u) 46 if out != tc.Expect { 47 t.Error(tc.Testname, tc.Input, tc.Expect) 48 } 49 } 50 } 51 } 52 53 func TestSafeURLFromString(t *testing.T) { 54 out := SafeURLFromString(`http://localhost:8000/hello?zip=zap`) 55 if `http://localhost:8000/hello` != out { 56 t.Error(out) 57 } 58 out = SafeURLFromString("?????") 59 if "" != out { 60 t.Error(out) 61 } 62 } 63 64 func TestHostFromURL(t *testing.T) { 65 u, err := url.Parse("http://example.com/zip/zap?secret=shh") 66 if nil != err { 67 t.Fatal(err) 68 } 69 host := HostFromURL(u) 70 if host != "example.com" { 71 t.Error(host) 72 } 73 host = HostFromURL(nil) 74 if host != "" { 75 t.Error(host) 76 } 77 u, err = url.Parse("scheme:opaque") 78 if nil != err { 79 t.Fatal(err) 80 } 81 host = HostFromURL(u) 82 if host != "opaque" { 83 t.Error(host) 84 } 85 }