github.com/newrelic/go-agent@v3.26.0+incompatible/internal/url_test.go (about)

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