Source file src/net/url/url_test.go

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package url
     6  
     7  import (
     8  	"bytes"
     9  	encodingPkg "encoding"
    10  	"encoding/gob"
    11  	"encoding/json"
    12  	"fmt"
    13  	"io"
    14  	"net"
    15  	"reflect"
    16  	"strings"
    17  	"testing"
    18  )
    19  
    20  type URLTest struct {
    21  	in        string
    22  	out       *URL   // expected parse
    23  	roundtrip string // expected result of reserializing the URL; empty means same as "in".
    24  }
    25  
    26  var urltests = []URLTest{
    27  	// no path
    28  	{
    29  		"http://www.google.com",
    30  		&URL{
    31  			Scheme: "http",
    32  			Host:   "www.google.com",
    33  		},
    34  		"",
    35  	},
    36  	// path
    37  	{
    38  		"http://www.google.com/",
    39  		&URL{
    40  			Scheme: "http",
    41  			Host:   "www.google.com",
    42  			Path:   "/",
    43  		},
    44  		"",
    45  	},
    46  	// path with hex escaping
    47  	{
    48  		"http://www.google.com/file%20one%26two",
    49  		&URL{
    50  			Scheme:  "http",
    51  			Host:    "www.google.com",
    52  			Path:    "/file one&two",
    53  			RawPath: "/file%20one%26two",
    54  		},
    55  		"",
    56  	},
    57  	// fragment with hex escaping
    58  	{
    59  		"http://www.google.com/#file%20one%26two",
    60  		&URL{
    61  			Scheme:      "http",
    62  			Host:        "www.google.com",
    63  			Path:        "/",
    64  			Fragment:    "file one&two",
    65  			RawFragment: "file%20one%26two",
    66  		},
    67  		"",
    68  	},
    69  	// user
    70  	{
    71  		"ftp://webmaster@www.google.com/",
    72  		&URL{
    73  			Scheme: "ftp",
    74  			User:   User("webmaster"),
    75  			Host:   "www.google.com",
    76  			Path:   "/",
    77  		},
    78  		"",
    79  	},
    80  	// escape sequence in username
    81  	{
    82  		"ftp://john%20doe@www.google.com/",
    83  		&URL{
    84  			Scheme: "ftp",
    85  			User:   User("john doe"),
    86  			Host:   "www.google.com",
    87  			Path:   "/",
    88  		},
    89  		"ftp://john%20doe@www.google.com/",
    90  	},
    91  	// empty query
    92  	{
    93  		"http://www.google.com/?",
    94  		&URL{
    95  			Scheme:     "http",
    96  			Host:       "www.google.com",
    97  			Path:       "/",
    98  			ForceQuery: true,
    99  		},
   100  		"",
   101  	},
   102  	// query ending in question mark (Issue 14573)
   103  	{
   104  		"http://www.google.com/?foo=bar?",
   105  		&URL{
   106  			Scheme:   "http",
   107  			Host:     "www.google.com",
   108  			Path:     "/",
   109  			RawQuery: "foo=bar?",
   110  		},
   111  		"",
   112  	},
   113  	// query
   114  	{
   115  		"http://www.google.com/?q=go+language",
   116  		&URL{
   117  			Scheme:   "http",
   118  			Host:     "www.google.com",
   119  			Path:     "/",
   120  			RawQuery: "q=go+language",
   121  		},
   122  		"",
   123  	},
   124  	// query with hex escaping: NOT parsed
   125  	{
   126  		"http://www.google.com/?q=go%20language",
   127  		&URL{
   128  			Scheme:   "http",
   129  			Host:     "www.google.com",
   130  			Path:     "/",
   131  			RawQuery: "q=go%20language",
   132  		},
   133  		"",
   134  	},
   135  	// %20 outside query
   136  	{
   137  		"http://www.google.com/a%20b?q=c+d",
   138  		&URL{
   139  			Scheme:   "http",
   140  			Host:     "www.google.com",
   141  			Path:     "/a b",
   142  			RawQuery: "q=c+d",
   143  		},
   144  		"",
   145  	},
   146  	// path without leading /, so no parsing
   147  	{
   148  		"http:www.google.com/?q=go+language",
   149  		&URL{
   150  			Scheme:   "http",
   151  			Opaque:   "www.google.com/",
   152  			RawQuery: "q=go+language",
   153  		},
   154  		"http:www.google.com/?q=go+language",
   155  	},
   156  	// path without leading /, so no parsing
   157  	{
   158  		"http:%2f%2fwww.google.com/?q=go+language",
   159  		&URL{
   160  			Scheme:   "http",
   161  			Opaque:   "%2f%2fwww.google.com/",
   162  			RawQuery: "q=go+language",
   163  		},
   164  		"http:%2f%2fwww.google.com/?q=go+language",
   165  	},
   166  	// non-authority with path; see golang.org/issue/46059
   167  	{
   168  		"mailto:/webmaster@golang.org",
   169  		&URL{
   170  			Scheme:   "mailto",
   171  			Path:     "/webmaster@golang.org",
   172  			OmitHost: true,
   173  		},
   174  		"",
   175  	},
   176  	// non-authority
   177  	{
   178  		"mailto:webmaster@golang.org",
   179  		&URL{
   180  			Scheme: "mailto",
   181  			Opaque: "webmaster@golang.org",
   182  		},
   183  		"",
   184  	},
   185  	// unescaped :// in query should not create a scheme
   186  	{
   187  		"/foo?query=http://bad",
   188  		&URL{
   189  			Path:     "/foo",
   190  			RawQuery: "query=http://bad",
   191  		},
   192  		"",
   193  	},
   194  	// leading // without scheme should create an authority
   195  	{
   196  		"//foo",
   197  		&URL{
   198  			Host: "foo",
   199  		},
   200  		"",
   201  	},
   202  	// leading // without scheme, with userinfo, path, and query
   203  	{
   204  		"//user@foo/path?a=b",
   205  		&URL{
   206  			User:     User("user"),
   207  			Host:     "foo",
   208  			Path:     "/path",
   209  			RawQuery: "a=b",
   210  		},
   211  		"",
   212  	},
   213  	// Three leading slashes isn't an authority, but doesn't return an error.
   214  	// (We can't return an error, as this code is also used via
   215  	// ServeHTTP -> ReadRequest -> Parse, which is arguably a
   216  	// different URL parsing context, but currently shares the
   217  	// same codepath)
   218  	{
   219  		"///threeslashes",
   220  		&URL{
   221  			Path: "///threeslashes",
   222  		},
   223  		"",
   224  	},
   225  	{
   226  		"http://user:password@google.com",
   227  		&URL{
   228  			Scheme: "http",
   229  			User:   UserPassword("user", "password"),
   230  			Host:   "google.com",
   231  		},
   232  		"http://user:password@google.com",
   233  	},
   234  	// unescaped @ in username should not confuse host
   235  	{
   236  		"http://j@ne:password@google.com",
   237  		&URL{
   238  			Scheme: "http",
   239  			User:   UserPassword("j@ne", "password"),
   240  			Host:   "google.com",
   241  		},
   242  		"http://j%40ne:password@google.com",
   243  	},
   244  	// unescaped @ in password should not confuse host
   245  	{
   246  		"http://jane:p@ssword@google.com",
   247  		&URL{
   248  			Scheme: "http",
   249  			User:   UserPassword("jane", "p@ssword"),
   250  			Host:   "google.com",
   251  		},
   252  		"http://jane:p%40ssword@google.com",
   253  	},
   254  	{
   255  		"http://j@ne:password@google.com/p@th?q=@go",
   256  		&URL{
   257  			Scheme:   "http",
   258  			User:     UserPassword("j@ne", "password"),
   259  			Host:     "google.com",
   260  			Path:     "/p@th",
   261  			RawQuery: "q=@go",
   262  		},
   263  		"http://j%40ne:password@google.com/p@th?q=@go",
   264  	},
   265  	{
   266  		"http://www.google.com/?q=go+language#foo",
   267  		&URL{
   268  			Scheme:   "http",
   269  			Host:     "www.google.com",
   270  			Path:     "/",
   271  			RawQuery: "q=go+language",
   272  			Fragment: "foo",
   273  		},
   274  		"",
   275  	},
   276  	{
   277  		"http://www.google.com/?q=go+language#foo&bar",
   278  		&URL{
   279  			Scheme:   "http",
   280  			Host:     "www.google.com",
   281  			Path:     "/",
   282  			RawQuery: "q=go+language",
   283  			Fragment: "foo&bar",
   284  		},
   285  		"http://www.google.com/?q=go+language#foo&bar",
   286  	},
   287  	{
   288  		"http://www.google.com/?q=go+language#foo%26bar",
   289  		&URL{
   290  			Scheme:      "http",
   291  			Host:        "www.google.com",
   292  			Path:        "/",
   293  			RawQuery:    "q=go+language",
   294  			Fragment:    "foo&bar",
   295  			RawFragment: "foo%26bar",
   296  		},
   297  		"http://www.google.com/?q=go+language#foo%26bar",
   298  	},
   299  	{
   300  		"file:///home/adg/rabbits",
   301  		&URL{
   302  			Scheme: "file",
   303  			Host:   "",
   304  			Path:   "/home/adg/rabbits",
   305  		},
   306  		"file:///home/adg/rabbits",
   307  	},
   308  	// "Windows" paths are no exception to the rule.
   309  	// See golang.org/issue/6027, especially comment #9.
   310  	{
   311  		"file:///C:/FooBar/Baz.txt",
   312  		&URL{
   313  			Scheme: "file",
   314  			Host:   "",
   315  			Path:   "/C:/FooBar/Baz.txt",
   316  		},
   317  		"file:///C:/FooBar/Baz.txt",
   318  	},
   319  	// case-insensitive scheme
   320  	{
   321  		"MaIlTo:webmaster@golang.org",
   322  		&URL{
   323  			Scheme: "mailto",
   324  			Opaque: "webmaster@golang.org",
   325  		},
   326  		"mailto:webmaster@golang.org",
   327  	},
   328  	// Relative path
   329  	{
   330  		"a/b/c",
   331  		&URL{
   332  			Path: "a/b/c",
   333  		},
   334  		"a/b/c",
   335  	},
   336  	// escaped '?' in username and password
   337  	{
   338  		"http://%3Fam:pa%3Fsword@google.com",
   339  		&URL{
   340  			Scheme: "http",
   341  			User:   UserPassword("?am", "pa?sword"),
   342  			Host:   "google.com",
   343  		},
   344  		"",
   345  	},
   346  	// host subcomponent; IPv4 address in RFC 3986
   347  	{
   348  		"http://192.168.0.1/",
   349  		&URL{
   350  			Scheme: "http",
   351  			Host:   "192.168.0.1",
   352  			Path:   "/",
   353  		},
   354  		"",
   355  	},
   356  	// host and port subcomponents; IPv4 address in RFC 3986
   357  	{
   358  		"http://192.168.0.1:8080/",
   359  		&URL{
   360  			Scheme: "http",
   361  			Host:   "192.168.0.1:8080",
   362  			Path:   "/",
   363  		},
   364  		"",
   365  	},
   366  	// host subcomponent; IPv6 address in RFC 3986
   367  	{
   368  		"http://[fe80::1]/",
   369  		&URL{
   370  			Scheme: "http",
   371  			Host:   "[fe80::1]",
   372  			Path:   "/",
   373  		},
   374  		"",
   375  	},
   376  	// host and port subcomponents; IPv6 address in RFC 3986
   377  	{
   378  		"http://[fe80::1]:8080/",
   379  		&URL{
   380  			Scheme: "http",
   381  			Host:   "[fe80::1]:8080",
   382  			Path:   "/",
   383  		},
   384  		"",
   385  	},
   386  	// host subcomponent; IPv6 address with zone identifier in RFC 6874
   387  	{
   388  		"http://[fe80::1%25en0]/", // alphanum zone identifier
   389  		&URL{
   390  			Scheme: "http",
   391  			Host:   "[fe80::1%en0]",
   392  			Path:   "/",
   393  		},
   394  		"",
   395  	},
   396  	// host and port subcomponents; IPv6 address with zone identifier in RFC 6874
   397  	{
   398  		"http://[fe80::1%25en0]:8080/", // alphanum zone identifier
   399  		&URL{
   400  			Scheme: "http",
   401  			Host:   "[fe80::1%en0]:8080",
   402  			Path:   "/",
   403  		},
   404  		"",
   405  	},
   406  	// host subcomponent; IPv6 address with zone identifier in RFC 6874
   407  	{
   408  		"http://[fe80::1%25%65%6e%301-._~]/", // percent-encoded+unreserved zone identifier
   409  		&URL{
   410  			Scheme: "http",
   411  			Host:   "[fe80::1%en01-._~]",
   412  			Path:   "/",
   413  		},
   414  		"http://[fe80::1%25en01-._~]/",
   415  	},
   416  	// host and port subcomponents; IPv6 address with zone identifier in RFC 6874
   417  	{
   418  		"http://[fe80::1%25%65%6e%301-._~]:8080/", // percent-encoded+unreserved zone identifier
   419  		&URL{
   420  			Scheme: "http",
   421  			Host:   "[fe80::1%en01-._~]:8080",
   422  			Path:   "/",
   423  		},
   424  		"http://[fe80::1%25en01-._~]:8080/",
   425  	},
   426  	// alternate escapings of path survive round trip
   427  	{
   428  		"http://rest.rsc.io/foo%2fbar/baz%2Fquux?alt=media",
   429  		&URL{
   430  			Scheme:   "http",
   431  			Host:     "rest.rsc.io",
   432  			Path:     "/foo/bar/baz/quux",
   433  			RawPath:  "/foo%2fbar/baz%2Fquux",
   434  			RawQuery: "alt=media",
   435  		},
   436  		"",
   437  	},
   438  	// issue 12036
   439  	{
   440  		"mysql://a,b,c/bar",
   441  		&URL{
   442  			Scheme: "mysql",
   443  			Host:   "a,b,c",
   444  			Path:   "/bar",
   445  		},
   446  		"",
   447  	},
   448  	// worst case host, still round trips
   449  	{
   450  		"scheme://!$&'()*+,;=hello!:1/path",
   451  		&URL{
   452  			Scheme: "scheme",
   453  			Host:   "!$&'()*+,;=hello!:1",
   454  			Path:   "/path",
   455  		},
   456  		"",
   457  	},
   458  	// worst case path, still round trips
   459  	{
   460  		"http://host/!$&'()*+,;=:@[hello]",
   461  		&URL{
   462  			Scheme:  "http",
   463  			Host:    "host",
   464  			Path:    "/!$&'()*+,;=:@[hello]",
   465  			RawPath: "/!$&'()*+,;=:@[hello]",
   466  		},
   467  		"",
   468  	},
   469  	// golang.org/issue/5684
   470  	{
   471  		"http://example.com/oid/[order_id]",
   472  		&URL{
   473  			Scheme:  "http",
   474  			Host:    "example.com",
   475  			Path:    "/oid/[order_id]",
   476  			RawPath: "/oid/[order_id]",
   477  		},
   478  		"",
   479  	},
   480  	// golang.org/issue/12200 (colon with empty port)
   481  	{
   482  		"http://192.168.0.2:8080/foo",
   483  		&URL{
   484  			Scheme: "http",
   485  			Host:   "192.168.0.2:8080",
   486  			Path:   "/foo",
   487  		},
   488  		"",
   489  	},
   490  	{
   491  		"http://192.168.0.2:/foo",
   492  		&URL{
   493  			Scheme: "http",
   494  			Host:   "192.168.0.2:",
   495  			Path:   "/foo",
   496  		},
   497  		"",
   498  	},
   499  	{
   500  		// Malformed IPv6 but still accepted.
   501  		"http://2b01:e34:ef40:7730:8e70:5aff:fefe:edac:8080/foo",
   502  		&URL{
   503  			Scheme: "http",
   504  			Host:   "2b01:e34:ef40:7730:8e70:5aff:fefe:edac:8080",
   505  			Path:   "/foo",
   506  		},
   507  		"",
   508  	},
   509  	{
   510  		// Malformed IPv6 but still accepted.
   511  		"http://2b01:e34:ef40:7730:8e70:5aff:fefe:edac:/foo",
   512  		&URL{
   513  			Scheme: "http",
   514  			Host:   "2b01:e34:ef40:7730:8e70:5aff:fefe:edac:",
   515  			Path:   "/foo",
   516  		},
   517  		"",
   518  	},
   519  	{
   520  		"http://[2b01:e34:ef40:7730:8e70:5aff:fefe:edac]:8080/foo",
   521  		&URL{
   522  			Scheme: "http",
   523  			Host:   "[2b01:e34:ef40:7730:8e70:5aff:fefe:edac]:8080",
   524  			Path:   "/foo",
   525  		},
   526  		"",
   527  	},
   528  	{
   529  		"http://[2b01:e34:ef40:7730:8e70:5aff:fefe:edac]:/foo",
   530  		&URL{
   531  			Scheme: "http",
   532  			Host:   "[2b01:e34:ef40:7730:8e70:5aff:fefe:edac]:",
   533  			Path:   "/foo",
   534  		},
   535  		"",
   536  	},
   537  	// golang.org/issue/7991 and golang.org/issue/12719 (non-ascii %-encoded in host)
   538  	{
   539  		"http://hello.世界.com/foo",
   540  		&URL{
   541  			Scheme: "http",
   542  			Host:   "hello.世界.com",
   543  			Path:   "/foo",
   544  		},
   545  		"http://hello.%E4%B8%96%E7%95%8C.com/foo",
   546  	},
   547  	{
   548  		"http://hello.%e4%b8%96%e7%95%8c.com/foo",
   549  		&URL{
   550  			Scheme: "http",
   551  			Host:   "hello.世界.com",
   552  			Path:   "/foo",
   553  		},
   554  		"http://hello.%E4%B8%96%E7%95%8C.com/foo",
   555  	},
   556  	{
   557  		"http://hello.%E4%B8%96%E7%95%8C.com/foo",
   558  		&URL{
   559  			Scheme: "http",
   560  			Host:   "hello.世界.com",
   561  			Path:   "/foo",
   562  		},
   563  		"",
   564  	},
   565  	// golang.org/issue/10433 (path beginning with //)
   566  	{
   567  		"http://example.com//foo",
   568  		&URL{
   569  			Scheme: "http",
   570  			Host:   "example.com",
   571  			Path:   "//foo",
   572  		},
   573  		"",
   574  	},
   575  	// test that we can reparse the host names we accept.
   576  	{
   577  		"myscheme://authority<\"hi\">/foo",
   578  		&URL{
   579  			Scheme: "myscheme",
   580  			Host:   "authority<\"hi\">",
   581  			Path:   "/foo",
   582  		},
   583  		"",
   584  	},
   585  	// spaces in hosts are disallowed but escaped spaces in IPv6 scope IDs are grudgingly OK.
   586  	// This happens on Windows.
   587  	// golang.org/issue/14002
   588  	{
   589  		"tcp://[2020::2020:20:2020:2020%25Windows%20Loves%20Spaces]:2020",
   590  		&URL{
   591  			Scheme: "tcp",
   592  			Host:   "[2020::2020:20:2020:2020%Windows Loves Spaces]:2020",
   593  		},
   594  		"",
   595  	},
   596  	// test we can roundtrip magnet url
   597  	// fix issue https://golang.org/issue/20054
   598  	{
   599  		"magnet:?xt=urn:btih:c12fe1c06bba254a9dc9f519b335aa7c1367a88a&dn",
   600  		&URL{
   601  			Scheme:   "magnet",
   602  			Host:     "",
   603  			Path:     "",
   604  			RawQuery: "xt=urn:btih:c12fe1c06bba254a9dc9f519b335aa7c1367a88a&dn",
   605  		},
   606  		"magnet:?xt=urn:btih:c12fe1c06bba254a9dc9f519b335aa7c1367a88a&dn",
   607  	},
   608  	{
   609  		"mailto:?subject=hi",
   610  		&URL{
   611  			Scheme:   "mailto",
   612  			Host:     "",
   613  			Path:     "",
   614  			RawQuery: "subject=hi",
   615  		},
   616  		"mailto:?subject=hi",
   617  	},
   618  }
   619  
   620  // more useful string for debugging than fmt's struct printer
   621  func ufmt(u *URL) string {
   622  	var user, pass any
   623  	if u.User != nil {
   624  		user = u.User.Username()
   625  		if p, ok := u.User.Password(); ok {
   626  			pass = p
   627  		}
   628  	}
   629  	return fmt.Sprintf("opaque=%q, scheme=%q, user=%#v, pass=%#v, host=%q, path=%q, rawpath=%q, rawq=%q, frag=%q, rawfrag=%q, forcequery=%v, omithost=%t",
   630  		u.Opaque, u.Scheme, user, pass, u.Host, u.Path, u.RawPath, u.RawQuery, u.Fragment, u.RawFragment, u.ForceQuery, u.OmitHost)
   631  }
   632  
   633  func BenchmarkString(b *testing.B) {
   634  	b.StopTimer()
   635  	b.ReportAllocs()
   636  	for _, tt := range urltests {
   637  		u, err := Parse(tt.in)
   638  		if err != nil {
   639  			b.Errorf("Parse(%q) returned error %s", tt.in, err)
   640  			continue
   641  		}
   642  		if tt.roundtrip == "" {
   643  			continue
   644  		}
   645  		b.StartTimer()
   646  		var g string
   647  		for i := 0; i < b.N; i++ {
   648  			g = u.String()
   649  		}
   650  		b.StopTimer()
   651  		if w := tt.roundtrip; b.N > 0 && g != w {
   652  			b.Errorf("Parse(%q).String() == %q, want %q", tt.in, g, w)
   653  		}
   654  	}
   655  }
   656  
   657  func TestParse(t *testing.T) {
   658  	for _, tt := range urltests {
   659  		u, err := Parse(tt.in)
   660  		if err != nil {
   661  			t.Errorf("Parse(%q) returned error %v", tt.in, err)
   662  			continue
   663  		}
   664  		if !reflect.DeepEqual(u, tt.out) {
   665  			t.Errorf("Parse(%q):\n\tgot  %v\n\twant %v\n", tt.in, ufmt(u), ufmt(tt.out))
   666  		}
   667  	}
   668  }
   669  
   670  const pathThatLooksSchemeRelative = "//not.a.user@not.a.host/just/a/path"
   671  
   672  var parseRequestURLTests = []struct {
   673  	url           string
   674  	expectedValid bool
   675  }{
   676  	{"http://foo.com", true},
   677  	{"http://foo.com/", true},
   678  	{"http://foo.com/path", true},
   679  	{"/", true},
   680  	{pathThatLooksSchemeRelative, true},
   681  	{"//not.a.user@%66%6f%6f.com/just/a/path/also", true},
   682  	{"*", true},
   683  	{"http://192.168.0.1/", true},
   684  	{"http://192.168.0.1:8080/", true},
   685  	{"http://[fe80::1]/", true},
   686  	{"http://[fe80::1]:8080/", true},
   687  
   688  	// Tests exercising RFC 6874 compliance:
   689  	{"http://[fe80::1%25en0]/", true},                 // with alphanum zone identifier
   690  	{"http://[fe80::1%25en0]:8080/", true},            // with alphanum zone identifier
   691  	{"http://[fe80::1%25%65%6e%301-._~]/", true},      // with percent-encoded+unreserved zone identifier
   692  	{"http://[fe80::1%25%65%6e%301-._~]:8080/", true}, // with percent-encoded+unreserved zone identifier
   693  
   694  	{"foo.html", false},
   695  	{"../dir/", false},
   696  	{" http://foo.com", false},
   697  	{"http://192.168.0.%31/", false},
   698  	{"http://192.168.0.%31:8080/", false},
   699  	{"http://[fe80::%31]/", false},
   700  	{"http://[fe80::%31]:8080/", false},
   701  	{"http://[fe80::%31%25en0]/", false},
   702  	{"http://[fe80::%31%25en0]:8080/", false},
   703  
   704  	// These two cases are valid as textual representations as
   705  	// described in RFC 4007, but are not valid as address
   706  	// literals with IPv6 zone identifiers in URIs as described in
   707  	// RFC 6874.
   708  	{"http://[fe80::1%en0]/", false},
   709  	{"http://[fe80::1%en0]:8080/", false},
   710  }
   711  
   712  func TestParseRequestURI(t *testing.T) {
   713  	for _, test := range parseRequestURLTests {
   714  		_, err := ParseRequestURI(test.url)
   715  		if test.expectedValid && err != nil {
   716  			t.Errorf("ParseRequestURI(%q) gave err %v; want no error", test.url, err)
   717  		} else if !test.expectedValid && err == nil {
   718  			t.Errorf("ParseRequestURI(%q) gave nil error; want some error", test.url)
   719  		}
   720  	}
   721  
   722  	url, err := ParseRequestURI(pathThatLooksSchemeRelative)
   723  	if err != nil {
   724  		t.Fatalf("Unexpected error %v", err)
   725  	}
   726  	if url.Path != pathThatLooksSchemeRelative {
   727  		t.Errorf("ParseRequestURI path:\ngot  %q\nwant %q", url.Path, pathThatLooksSchemeRelative)
   728  	}
   729  }
   730  
   731  var stringURLTests = []struct {
   732  	url  URL
   733  	want string
   734  }{
   735  	// No leading slash on path should prepend slash on String() call
   736  	{
   737  		url: URL{
   738  			Scheme: "http",
   739  			Host:   "www.google.com",
   740  			Path:   "search",
   741  		},
   742  		want: "http://www.google.com/search",
   743  	},
   744  	// Relative path with first element containing ":" should be prepended with "./", golang.org/issue/17184
   745  	{
   746  		url: URL{
   747  			Path: "this:that",
   748  		},
   749  		want: "./this:that",
   750  	},
   751  	// Relative path with second element containing ":" should not be prepended with "./"
   752  	{
   753  		url: URL{
   754  			Path: "here/this:that",
   755  		},
   756  		want: "here/this:that",
   757  	},
   758  	// Non-relative path with first element containing ":" should not be prepended with "./"
   759  	{
   760  		url: URL{
   761  			Scheme: "http",
   762  			Host:   "www.google.com",
   763  			Path:   "this:that",
   764  		},
   765  		want: "http://www.google.com/this:that",
   766  	},
   767  }
   768  
   769  func TestURLString(t *testing.T) {
   770  	for _, tt := range urltests {
   771  		u, err := Parse(tt.in)
   772  		if err != nil {
   773  			t.Errorf("Parse(%q) returned error %s", tt.in, err)
   774  			continue
   775  		}
   776  		expected := tt.in
   777  		if tt.roundtrip != "" {
   778  			expected = tt.roundtrip
   779  		}
   780  		s := u.String()
   781  		if s != expected {
   782  			t.Errorf("Parse(%q).String() == %q (expected %q)", tt.in, s, expected)
   783  		}
   784  	}
   785  
   786  	for _, tt := range stringURLTests {
   787  		if got := tt.url.String(); got != tt.want {
   788  			t.Errorf("%+v.String() = %q; want %q", tt.url, got, tt.want)
   789  		}
   790  	}
   791  }
   792  
   793  func TestURLRedacted(t *testing.T) {
   794  	cases := []struct {
   795  		name string
   796  		url  *URL
   797  		want string
   798  	}{
   799  		{
   800  			name: "non-blank Password",
   801  			url: &URL{
   802  				Scheme: "http",
   803  				Host:   "host.tld",
   804  				Path:   "this:that",
   805  				User:   UserPassword("user", "password"),
   806  			},
   807  			want: "http://user:xxxxx@host.tld/this:that",
   808  		},
   809  		{
   810  			name: "blank Password",
   811  			url: &URL{
   812  				Scheme: "http",
   813  				Host:   "host.tld",
   814  				Path:   "this:that",
   815  				User:   User("user"),
   816  			},
   817  			want: "http://user@host.tld/this:that",
   818  		},
   819  		{
   820  			name: "nil User",
   821  			url: &URL{
   822  				Scheme: "http",
   823  				Host:   "host.tld",
   824  				Path:   "this:that",
   825  				User:   UserPassword("", "password"),
   826  			},
   827  			want: "http://:xxxxx@host.tld/this:that",
   828  		},
   829  		{
   830  			name: "blank Username, blank Password",
   831  			url: &URL{
   832  				Scheme: "http",
   833  				Host:   "host.tld",
   834  				Path:   "this:that",
   835  			},
   836  			want: "http://host.tld/this:that",
   837  		},
   838  		{
   839  			name: "empty URL",
   840  			url:  &URL{},
   841  			want: "",
   842  		},
   843  		{
   844  			name: "nil URL",
   845  			url:  nil,
   846  			want: "",
   847  		},
   848  	}
   849  
   850  	for _, tt := range cases {
   851  		t := t
   852  		t.Run(tt.name, func(t *testing.T) {
   853  			if g, w := tt.url.Redacted(), tt.want; g != w {
   854  				t.Fatalf("got: %q\nwant: %q", g, w)
   855  			}
   856  		})
   857  	}
   858  }
   859  
   860  type EscapeTest struct {
   861  	in  string
   862  	out string
   863  	err error
   864  }
   865  
   866  var unescapeTests = []EscapeTest{
   867  	{
   868  		"",
   869  		"",
   870  		nil,
   871  	},
   872  	{
   873  		"abc",
   874  		"abc",
   875  		nil,
   876  	},
   877  	{
   878  		"1%41",
   879  		"1A",
   880  		nil,
   881  	},
   882  	{
   883  		"1%41%42%43",
   884  		"1ABC",
   885  		nil,
   886  	},
   887  	{
   888  		"%4a",
   889  		"J",
   890  		nil,
   891  	},
   892  	{
   893  		"%6F",
   894  		"o",
   895  		nil,
   896  	},
   897  	{
   898  		"%", // not enough characters after %
   899  		"",
   900  		EscapeError("%"),
   901  	},
   902  	{
   903  		"%a", // not enough characters after %
   904  		"",
   905  		EscapeError("%a"),
   906  	},
   907  	{
   908  		"%1", // not enough characters after %
   909  		"",
   910  		EscapeError("%1"),
   911  	},
   912  	{
   913  		"123%45%6", // not enough characters after %
   914  		"",
   915  		EscapeError("%6"),
   916  	},
   917  	{
   918  		"%zzzzz", // invalid hex digits
   919  		"",
   920  		EscapeError("%zz"),
   921  	},
   922  	{
   923  		"a+b",
   924  		"a b",
   925  		nil,
   926  	},
   927  	{
   928  		"a%20b",
   929  		"a b",
   930  		nil,
   931  	},
   932  }
   933  
   934  func TestUnescape(t *testing.T) {
   935  	for _, tt := range unescapeTests {
   936  		actual, err := QueryUnescape(tt.in)
   937  		if actual != tt.out || (err != nil) != (tt.err != nil) {
   938  			t.Errorf("QueryUnescape(%q) = %q, %s; want %q, %s", tt.in, actual, err, tt.out, tt.err)
   939  		}
   940  
   941  		in := tt.in
   942  		out := tt.out
   943  		if strings.Contains(tt.in, "+") {
   944  			in = strings.ReplaceAll(tt.in, "+", "%20")
   945  			actual, err := PathUnescape(in)
   946  			if actual != tt.out || (err != nil) != (tt.err != nil) {
   947  				t.Errorf("PathUnescape(%q) = %q, %s; want %q, %s", in, actual, err, tt.out, tt.err)
   948  			}
   949  			if tt.err == nil {
   950  				s, err := QueryUnescape(strings.ReplaceAll(tt.in, "+", "XXX"))
   951  				if err != nil {
   952  					continue
   953  				}
   954  				in = tt.in
   955  				out = strings.ReplaceAll(s, "XXX", "+")
   956  			}
   957  		}
   958  
   959  		actual, err = PathUnescape(in)
   960  		if actual != out || (err != nil) != (tt.err != nil) {
   961  			t.Errorf("PathUnescape(%q) = %q, %s; want %q, %s", in, actual, err, out, tt.err)
   962  		}
   963  	}
   964  }
   965  
   966  var queryEscapeTests = []EscapeTest{
   967  	{
   968  		"",
   969  		"",
   970  		nil,
   971  	},
   972  	{
   973  		"abc",
   974  		"abc",
   975  		nil,
   976  	},
   977  	{
   978  		"one two",
   979  		"one+two",
   980  		nil,
   981  	},
   982  	{
   983  		"10%",
   984  		"10%25",
   985  		nil,
   986  	},
   987  	{
   988  		" ?&=#+%!<>#\"{}|\\^[]`☺\t:/@$'()*,;",
   989  		"+%3F%26%3D%23%2B%25%21%3C%3E%23%22%7B%7D%7C%5C%5E%5B%5D%60%E2%98%BA%09%3A%2F%40%24%27%28%29%2A%2C%3B",
   990  		nil,
   991  	},
   992  }
   993  
   994  func TestQueryEscape(t *testing.T) {
   995  	for _, tt := range queryEscapeTests {
   996  		actual := QueryEscape(tt.in)
   997  		if tt.out != actual {
   998  			t.Errorf("QueryEscape(%q) = %q, want %q", tt.in, actual, tt.out)
   999  		}
  1000  
  1001  		// for bonus points, verify that escape:unescape is an identity.
  1002  		roundtrip, err := QueryUnescape(actual)
  1003  		if roundtrip != tt.in || err != nil {
  1004  			t.Errorf("QueryUnescape(%q) = %q, %s; want %q, %s", actual, roundtrip, err, tt.in, "[no error]")
  1005  		}
  1006  	}
  1007  }
  1008  
  1009  var pathEscapeTests = []EscapeTest{
  1010  	{
  1011  		"",
  1012  		"",
  1013  		nil,
  1014  	},
  1015  	{
  1016  		"abc",
  1017  		"abc",
  1018  		nil,
  1019  	},
  1020  	{
  1021  		"abc+def",
  1022  		"abc+def",
  1023  		nil,
  1024  	},
  1025  	{
  1026  		"a/b",
  1027  		"a%2Fb",
  1028  		nil,
  1029  	},
  1030  	{
  1031  		"one two",
  1032  		"one%20two",
  1033  		nil,
  1034  	},
  1035  	{
  1036  		"10%",
  1037  		"10%25",
  1038  		nil,
  1039  	},
  1040  	{
  1041  		" ?&=#+%!<>#\"{}|\\^[]`☺\t:/@$'()*,;",
  1042  		"%20%3F&=%23+%25%21%3C%3E%23%22%7B%7D%7C%5C%5E%5B%5D%60%E2%98%BA%09:%2F@$%27%28%29%2A%2C%3B",
  1043  		nil,
  1044  	},
  1045  }
  1046  
  1047  func TestPathEscape(t *testing.T) {
  1048  	for _, tt := range pathEscapeTests {
  1049  		actual := PathEscape(tt.in)
  1050  		if tt.out != actual {
  1051  			t.Errorf("PathEscape(%q) = %q, want %q", tt.in, actual, tt.out)
  1052  		}
  1053  
  1054  		// for bonus points, verify that escape:unescape is an identity.
  1055  		roundtrip, err := PathUnescape(actual)
  1056  		if roundtrip != tt.in || err != nil {
  1057  			t.Errorf("PathUnescape(%q) = %q, %s; want %q, %s", actual, roundtrip, err, tt.in, "[no error]")
  1058  		}
  1059  	}
  1060  }
  1061  
  1062  //var userinfoTests = []UserinfoTest{
  1063  //	{"user", "password", "user:password"},
  1064  //	{"foo:bar", "~!@#$%^&*()_+{}|[]\\-=`:;'\"<>?,./",
  1065  //		"foo%3Abar:~!%40%23$%25%5E&*()_+%7B%7D%7C%5B%5D%5C-=%60%3A;'%22%3C%3E?,.%2F"},
  1066  //}
  1067  
  1068  type EncodeQueryTest struct {
  1069  	m        Values
  1070  	expected string
  1071  }
  1072  
  1073  var encodeQueryTests = []EncodeQueryTest{
  1074  	{nil, ""},
  1075  	{Values{}, ""},
  1076  	{Values{"q": {"puppies"}, "oe": {"utf8"}}, "oe=utf8&q=puppies"},
  1077  	{Values{"q": {"dogs", "&", "7"}}, "q=dogs&q=%26&q=7"},
  1078  	{Values{
  1079  		"a": {"a1", "a2", "a3"},
  1080  		"b": {"b1", "b2", "b3"},
  1081  		"c": {"c1", "c2", "c3"},
  1082  	}, "a=a1&a=a2&a=a3&b=b1&b=b2&b=b3&c=c1&c=c2&c=c3"},
  1083  }
  1084  
  1085  func TestEncodeQuery(t *testing.T) {
  1086  	for _, tt := range encodeQueryTests {
  1087  		if q := tt.m.Encode(); q != tt.expected {
  1088  			t.Errorf(`EncodeQuery(%+v) = %q, want %q`, tt.m, q, tt.expected)
  1089  		}
  1090  	}
  1091  }
  1092  
  1093  var resolvePathTests = []struct {
  1094  	base, ref, expected string
  1095  }{
  1096  	{"a/b", ".", "/a/"},
  1097  	{"a/b", "c", "/a/c"},
  1098  	{"a/b", "..", "/"},
  1099  	{"a/", "..", "/"},
  1100  	{"a/", "../..", "/"},
  1101  	{"a/b/c", "..", "/a/"},
  1102  	{"a/b/c", "../d", "/a/d"},
  1103  	{"a/b/c", ".././d", "/a/d"},
  1104  	{"a/b", "./..", "/"},
  1105  	{"a/./b", ".", "/a/"},
  1106  	{"a/../", ".", "/"},
  1107  	{"a/.././b", "c", "/c"},
  1108  }
  1109  
  1110  func TestResolvePath(t *testing.T) {
  1111  	for _, test := range resolvePathTests {
  1112  		got := resolvePath(test.base, test.ref)
  1113  		if got != test.expected {
  1114  			t.Errorf("For %q + %q got %q; expected %q", test.base, test.ref, got, test.expected)
  1115  		}
  1116  	}
  1117  }
  1118  
  1119  func BenchmarkResolvePath(b *testing.B) {
  1120  	b.ReportAllocs()
  1121  	for i := 0; i < b.N; i++ {
  1122  		resolvePath("a/b/c", ".././d")
  1123  	}
  1124  }
  1125  
  1126  var resolveReferenceTests = []struct {
  1127  	base, rel, expected string
  1128  }{
  1129  	// Absolute URL references
  1130  	{"http://foo.com?a=b", "https://bar.com/", "https://bar.com/"},
  1131  	{"http://foo.com/", "https://bar.com/?a=b", "https://bar.com/?a=b"},
  1132  	{"http://foo.com/", "https://bar.com/?", "https://bar.com/?"},
  1133  	{"http://foo.com/bar", "mailto:foo@example.com", "mailto:foo@example.com"},
  1134  
  1135  	// Path-absolute references
  1136  	{"http://foo.com/bar", "/baz", "http://foo.com/baz"},
  1137  	{"http://foo.com/bar?a=b#f", "/baz", "http://foo.com/baz"},
  1138  	{"http://foo.com/bar?a=b", "/baz?", "http://foo.com/baz?"},
  1139  	{"http://foo.com/bar?a=b", "/baz?c=d", "http://foo.com/baz?c=d"},
  1140  
  1141  	// Multiple slashes
  1142  	{"http://foo.com/bar", "http://foo.com//baz", "http://foo.com//baz"},
  1143  	{"http://foo.com/bar", "http://foo.com///baz/quux", "http://foo.com///baz/quux"},
  1144  
  1145  	// Scheme-relative
  1146  	{"https://foo.com/bar?a=b", "//bar.com/quux", "https://bar.com/quux"},
  1147  
  1148  	// Path-relative references:
  1149  
  1150  	// ... current directory
  1151  	{"http://foo.com", ".", "http://foo.com/"},
  1152  	{"http://foo.com/bar", ".", "http://foo.com/"},
  1153  	{"http://foo.com/bar/", ".", "http://foo.com/bar/"},
  1154  
  1155  	// ... going down
  1156  	{"http://foo.com", "bar", "http://foo.com/bar"},
  1157  	{"http://foo.com/", "bar", "http://foo.com/bar"},
  1158  	{"http://foo.com/bar/baz", "quux", "http://foo.com/bar/quux"},
  1159  
  1160  	// ... going up
  1161  	{"http://foo.com/bar/baz", "../quux", "http://foo.com/quux"},
  1162  	{"http://foo.com/bar/baz", "../../../../../quux", "http://foo.com/quux"},
  1163  	{"http://foo.com/bar", "..", "http://foo.com/"},
  1164  	{"http://foo.com/bar/baz", "./..", "http://foo.com/"},
  1165  	// ".." in the middle (issue 3560)
  1166  	{"http://foo.com/bar/baz", "quux/dotdot/../tail", "http://foo.com/bar/quux/tail"},
  1167  	{"http://foo.com/bar/baz", "quux/./dotdot/../tail", "http://foo.com/bar/quux/tail"},
  1168  	{"http://foo.com/bar/baz", "quux/./dotdot/.././tail", "http://foo.com/bar/quux/tail"},
  1169  	{"http://foo.com/bar/baz", "quux/./dotdot/./../tail", "http://foo.com/bar/quux/tail"},
  1170  	{"http://foo.com/bar/baz", "quux/./dotdot/dotdot/././../../tail", "http://foo.com/bar/quux/tail"},
  1171  	{"http://foo.com/bar/baz", "quux/./dotdot/dotdot/./.././../tail", "http://foo.com/bar/quux/tail"},
  1172  	{"http://foo.com/bar/baz", "quux/./dotdot/dotdot/dotdot/./../../.././././tail", "http://foo.com/bar/quux/tail"},
  1173  	{"http://foo.com/bar/baz", "quux/./dotdot/../dotdot/../dot/./tail/..", "http://foo.com/bar/quux/dot/"},
  1174  
  1175  	// Remove any dot-segments prior to forming the target URI.
  1176  	// https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4
  1177  	{"http://foo.com/dot/./dotdot/../foo/bar", "../baz", "http://foo.com/dot/baz"},
  1178  
  1179  	// Triple dot isn't special
  1180  	{"http://foo.com/bar", "...", "http://foo.com/..."},
  1181  
  1182  	// Fragment
  1183  	{"http://foo.com/bar", ".#frag", "http://foo.com/#frag"},
  1184  	{"http://example.org/", "#!$&%27()*+,;=", "http://example.org/#!$&%27()*+,;="},
  1185  
  1186  	// Paths with escaping (issue 16947).
  1187  	{"http://foo.com/foo%2fbar/", "../baz", "http://foo.com/baz"},
  1188  	{"http://foo.com/1/2%2f/3%2f4/5", "../../a/b/c", "http://foo.com/1/a/b/c"},
  1189  	{"http://foo.com/1/2/3", "./a%2f../../b/..%2fc", "http://foo.com/1/2/b/..%2fc"},
  1190  	{"http://foo.com/1/2%2f/3%2f4/5", "./a%2f../b/../c", "http://foo.com/1/2%2f/3%2f4/a%2f../c"},
  1191  	{"http://foo.com/foo%20bar/", "../baz", "http://foo.com/baz"},
  1192  	{"http://foo.com/foo", "../bar%2fbaz", "http://foo.com/bar%2fbaz"},
  1193  	{"http://foo.com/foo%2dbar/", "./baz-quux", "http://foo.com/foo%2dbar/baz-quux"},
  1194  
  1195  	// RFC 3986: Normal Examples
  1196  	// https://datatracker.ietf.org/doc/html/rfc3986#section-5.4.1
  1197  	{"http://a/b/c/d;p?q", "g:h", "g:h"},
  1198  	{"http://a/b/c/d;p?q", "g", "http://a/b/c/g"},
  1199  	{"http://a/b/c/d;p?q", "./g", "http://a/b/c/g"},
  1200  	{"http://a/b/c/d;p?q", "g/", "http://a/b/c/g/"},
  1201  	{"http://a/b/c/d;p?q", "/g", "http://a/g"},
  1202  	{"http://a/b/c/d;p?q", "//g", "http://g"},
  1203  	{"http://a/b/c/d;p?q", "?y", "http://a/b/c/d;p?y"},
  1204  	{"http://a/b/c/d;p?q", "g?y", "http://a/b/c/g?y"},
  1205  	{"http://a/b/c/d;p?q", "#s", "http://a/b/c/d;p?q#s"},
  1206  	{"http://a/b/c/d;p?q", "g#s", "http://a/b/c/g#s"},
  1207  	{"http://a/b/c/d;p?q", "g?y#s", "http://a/b/c/g?y#s"},
  1208  	{"http://a/b/c/d;p?q", ";x", "http://a/b/c/;x"},
  1209  	{"http://a/b/c/d;p?q", "g;x", "http://a/b/c/g;x"},
  1210  	{"http://a/b/c/d;p?q", "g;x?y#s", "http://a/b/c/g;x?y#s"},
  1211  	{"http://a/b/c/d;p?q", "", "http://a/b/c/d;p?q"},
  1212  	{"http://a/b/c/d;p?q", ".", "http://a/b/c/"},
  1213  	{"http://a/b/c/d;p?q", "./", "http://a/b/c/"},
  1214  	{"http://a/b/c/d;p?q", "..", "http://a/b/"},
  1215  	{"http://a/b/c/d;p?q", "../", "http://a/b/"},
  1216  	{"http://a/b/c/d;p?q", "../g", "http://a/b/g"},
  1217  	{"http://a/b/c/d;p?q", "../..", "http://a/"},
  1218  	{"http://a/b/c/d;p?q", "../../", "http://a/"},
  1219  	{"http://a/b/c/d;p?q", "../../g", "http://a/g"},
  1220  
  1221  	// RFC 3986: Abnormal Examples
  1222  	// https://datatracker.ietf.org/doc/html/rfc3986#section-5.4.2
  1223  	{"http://a/b/c/d;p?q", "../../../g", "http://a/g"},
  1224  	{"http://a/b/c/d;p?q", "../../../../g", "http://a/g"},
  1225  	{"http://a/b/c/d;p?q", "/./g", "http://a/g"},
  1226  	{"http://a/b/c/d;p?q", "/../g", "http://a/g"},
  1227  	{"http://a/b/c/d;p?q", "g.", "http://a/b/c/g."},
  1228  	{"http://a/b/c/d;p?q", ".g", "http://a/b/c/.g"},
  1229  	{"http://a/b/c/d;p?q", "g..", "http://a/b/c/g.."},
  1230  	{"http://a/b/c/d;p?q", "..g", "http://a/b/c/..g"},
  1231  	{"http://a/b/c/d;p?q", "./../g", "http://a/b/g"},
  1232  	{"http://a/b/c/d;p?q", "./g/.", "http://a/b/c/g/"},
  1233  	{"http://a/b/c/d;p?q", "g/./h", "http://a/b/c/g/h"},
  1234  	{"http://a/b/c/d;p?q", "g/../h", "http://a/b/c/h"},
  1235  	{"http://a/b/c/d;p?q", "g;x=1/./y", "http://a/b/c/g;x=1/y"},
  1236  	{"http://a/b/c/d;p?q", "g;x=1/../y", "http://a/b/c/y"},
  1237  	{"http://a/b/c/d;p?q", "g?y/./x", "http://a/b/c/g?y/./x"},
  1238  	{"http://a/b/c/d;p?q", "g?y/../x", "http://a/b/c/g?y/../x"},
  1239  	{"http://a/b/c/d;p?q", "g#s/./x", "http://a/b/c/g#s/./x"},
  1240  	{"http://a/b/c/d;p?q", "g#s/../x", "http://a/b/c/g#s/../x"},
  1241  
  1242  	// Extras.
  1243  	{"https://a/b/c/d;p?q", "//g?q", "https://g?q"},
  1244  	{"https://a/b/c/d;p?q", "//g#s", "https://g#s"},
  1245  	{"https://a/b/c/d;p?q", "//g/d/e/f?y#s", "https://g/d/e/f?y#s"},
  1246  	{"https://a/b/c/d;p#s", "?y", "https://a/b/c/d;p?y"},
  1247  	{"https://a/b/c/d;p?q#s", "?y", "https://a/b/c/d;p?y"},
  1248  
  1249  	// Empty path and query but with ForceQuery (issue 46033).
  1250  	{"https://a/b/c/d;p?q#s", "?", "https://a/b/c/d;p?"},
  1251  }
  1252  
  1253  func TestResolveReference(t *testing.T) {
  1254  	mustParse := func(url string) *URL {
  1255  		u, err := Parse(url)
  1256  		if err != nil {
  1257  			t.Fatalf("Parse(%q) got err %v", url, err)
  1258  		}
  1259  		return u
  1260  	}
  1261  	opaque := &URL{Scheme: "scheme", Opaque: "opaque"}
  1262  	for _, test := range resolveReferenceTests {
  1263  		base := mustParse(test.base)
  1264  		rel := mustParse(test.rel)
  1265  		url := base.ResolveReference(rel)
  1266  		if got := url.String(); got != test.expected {
  1267  			t.Errorf("URL(%q).ResolveReference(%q)\ngot  %q\nwant %q", test.base, test.rel, got, test.expected)
  1268  		}
  1269  		// Ensure that new instances are returned.
  1270  		if base == url {
  1271  			t.Errorf("Expected URL.ResolveReference to return new URL instance.")
  1272  		}
  1273  		// Test the convenience wrapper too.
  1274  		url, err := base.Parse(test.rel)
  1275  		if err != nil {
  1276  			t.Errorf("URL(%q).Parse(%q) failed: %v", test.base, test.rel, err)
  1277  		} else if got := url.String(); got != test.expected {
  1278  			t.Errorf("URL(%q).Parse(%q)\ngot  %q\nwant %q", test.base, test.rel, got, test.expected)
  1279  		} else if base == url {
  1280  			// Ensure that new instances are returned for the wrapper too.
  1281  			t.Errorf("Expected URL.Parse to return new URL instance.")
  1282  		}
  1283  		// Ensure Opaque resets the URL.
  1284  		url = base.ResolveReference(opaque)
  1285  		if *url != *opaque {
  1286  			t.Errorf("ResolveReference failed to resolve opaque URL:\ngot  %#v\nwant %#v", url, opaque)
  1287  		}
  1288  		// Test the convenience wrapper with an opaque URL too.
  1289  		url, err = base.Parse("scheme:opaque")
  1290  		if err != nil {
  1291  			t.Errorf(`URL(%q).Parse("scheme:opaque") failed: %v`, test.base, err)
  1292  		} else if *url != *opaque {
  1293  			t.Errorf("Parse failed to resolve opaque URL:\ngot  %#v\nwant %#v", opaque, url)
  1294  		} else if base == url {
  1295  			// Ensure that new instances are returned, again.
  1296  			t.Errorf("Expected URL.Parse to return new URL instance.")
  1297  		}
  1298  	}
  1299  }
  1300  
  1301  func TestQueryValues(t *testing.T) {
  1302  	u, _ := Parse("http://x.com?foo=bar&bar=1&bar=2&baz")
  1303  	v := u.Query()
  1304  	if len(v) != 3 {
  1305  		t.Errorf("got %d keys in Query values, want 3", len(v))
  1306  	}
  1307  	if g, e := v.Get("foo"), "bar"; g != e {
  1308  		t.Errorf("Get(foo) = %q, want %q", g, e)
  1309  	}
  1310  	// Case sensitive:
  1311  	if g, e := v.Get("Foo"), ""; g != e {
  1312  		t.Errorf("Get(Foo) = %q, want %q", g, e)
  1313  	}
  1314  	if g, e := v.Get("bar"), "1"; g != e {
  1315  		t.Errorf("Get(bar) = %q, want %q", g, e)
  1316  	}
  1317  	if g, e := v.Get("baz"), ""; g != e {
  1318  		t.Errorf("Get(baz) = %q, want %q", g, e)
  1319  	}
  1320  	if h, e := v.Has("foo"), true; h != e {
  1321  		t.Errorf("Has(foo) = %t, want %t", h, e)
  1322  	}
  1323  	if h, e := v.Has("bar"), true; h != e {
  1324  		t.Errorf("Has(bar) = %t, want %t", h, e)
  1325  	}
  1326  	if h, e := v.Has("baz"), true; h != e {
  1327  		t.Errorf("Has(baz) = %t, want %t", h, e)
  1328  	}
  1329  	if h, e := v.Has("noexist"), false; h != e {
  1330  		t.Errorf("Has(noexist) = %t, want %t", h, e)
  1331  	}
  1332  	v.Del("bar")
  1333  	if g, e := v.Get("bar"), ""; g != e {
  1334  		t.Errorf("second Get(bar) = %q, want %q", g, e)
  1335  	}
  1336  }
  1337  
  1338  type parseTest struct {
  1339  	query string
  1340  	out   Values
  1341  	ok    bool
  1342  }
  1343  
  1344  var parseTests = []parseTest{
  1345  	{
  1346  		query: "a=1",
  1347  		out:   Values{"a": []string{"1"}},
  1348  		ok:    true,
  1349  	},
  1350  	{
  1351  		query: "a=1&b=2",
  1352  		out:   Values{"a": []string{"1"}, "b": []string{"2"}},
  1353  		ok:    true,
  1354  	},
  1355  	{
  1356  		query: "a=1&a=2&a=banana",
  1357  		out:   Values{"a": []string{"1", "2", "banana"}},
  1358  		ok:    true,
  1359  	},
  1360  	{
  1361  		query: "ascii=%3Ckey%3A+0x90%3E",
  1362  		out:   Values{"ascii": []string{"<key: 0x90>"}},
  1363  		ok:    true,
  1364  	}, {
  1365  		query: "a=1;b=2",
  1366  		out:   Values{},
  1367  		ok:    false,
  1368  	}, {
  1369  		query: "a;b=1",
  1370  		out:   Values{},
  1371  		ok:    false,
  1372  	}, {
  1373  		query: "a=%3B", // hex encoding for semicolon
  1374  		out:   Values{"a": []string{";"}},
  1375  		ok:    true,
  1376  	},
  1377  	{
  1378  		query: "a%3Bb=1",
  1379  		out:   Values{"a;b": []string{"1"}},
  1380  		ok:    true,
  1381  	},
  1382  	{
  1383  		query: "a=1&a=2;a=banana",
  1384  		out:   Values{"a": []string{"1"}},
  1385  		ok:    false,
  1386  	},
  1387  	{
  1388  		query: "a;b&c=1",
  1389  		out:   Values{"c": []string{"1"}},
  1390  		ok:    false,
  1391  	},
  1392  	{
  1393  		query: "a=1&b=2;a=3&c=4",
  1394  		out:   Values{"a": []string{"1"}, "c": []string{"4"}},
  1395  		ok:    false,
  1396  	},
  1397  	{
  1398  		query: "a=1&b=2;c=3",
  1399  		out:   Values{"a": []string{"1"}},
  1400  		ok:    false,
  1401  	},
  1402  	{
  1403  		query: ";",
  1404  		out:   Values{},
  1405  		ok:    false,
  1406  	},
  1407  	{
  1408  		query: "a=1;",
  1409  		out:   Values{},
  1410  		ok:    false,
  1411  	},
  1412  	{
  1413  		query: "a=1&;",
  1414  		out:   Values{"a": []string{"1"}},
  1415  		ok:    false,
  1416  	},
  1417  	{
  1418  		query: ";a=1&b=2",
  1419  		out:   Values{"b": []string{"2"}},
  1420  		ok:    false,
  1421  	},
  1422  	{
  1423  		query: "a=1&b=2;",
  1424  		out:   Values{"a": []string{"1"}},
  1425  		ok:    false,
  1426  	},
  1427  }
  1428  
  1429  func TestParseQuery(t *testing.T) {
  1430  	for _, test := range parseTests {
  1431  		t.Run(test.query, func(t *testing.T) {
  1432  			form, err := ParseQuery(test.query)
  1433  			if test.ok != (err == nil) {
  1434  				want := "<error>"
  1435  				if test.ok {
  1436  					want = "<nil>"
  1437  				}
  1438  				t.Errorf("Unexpected error: %v, want %v", err, want)
  1439  			}
  1440  			if len(form) != len(test.out) {
  1441  				t.Errorf("len(form) = %d, want %d", len(form), len(test.out))
  1442  			}
  1443  			for k, evs := range test.out {
  1444  				vs, ok := form[k]
  1445  				if !ok {
  1446  					t.Errorf("Missing key %q", k)
  1447  					continue
  1448  				}
  1449  				if len(vs) != len(evs) {
  1450  					t.Errorf("len(form[%q]) = %d, want %d", k, len(vs), len(evs))
  1451  					continue
  1452  				}
  1453  				for j, ev := range evs {
  1454  					if v := vs[j]; v != ev {
  1455  						t.Errorf("form[%q][%d] = %q, want %q", k, j, v, ev)
  1456  					}
  1457  				}
  1458  			}
  1459  		})
  1460  	}
  1461  }
  1462  
  1463  type RequestURITest struct {
  1464  	url *URL
  1465  	out string
  1466  }
  1467  
  1468  var requritests = []RequestURITest{
  1469  	{
  1470  		&URL{
  1471  			Scheme: "http",
  1472  			Host:   "example.com",
  1473  			Path:   "",
  1474  		},
  1475  		"/",
  1476  	},
  1477  	{
  1478  		&URL{
  1479  			Scheme: "http",
  1480  			Host:   "example.com",
  1481  			Path:   "/a b",
  1482  		},
  1483  		"/a%20b",
  1484  	},
  1485  	// golang.org/issue/4860 variant 1
  1486  	{
  1487  		&URL{
  1488  			Scheme: "http",
  1489  			Host:   "example.com",
  1490  			Opaque: "/%2F/%2F/",
  1491  		},
  1492  		"/%2F/%2F/",
  1493  	},
  1494  	// golang.org/issue/4860 variant 2
  1495  	{
  1496  		&URL{
  1497  			Scheme: "http",
  1498  			Host:   "example.com",
  1499  			Opaque: "//other.example.com/%2F/%2F/",
  1500  		},
  1501  		"http://other.example.com/%2F/%2F/",
  1502  	},
  1503  	// better fix for issue 4860
  1504  	{
  1505  		&URL{
  1506  			Scheme:  "http",
  1507  			Host:    "example.com",
  1508  			Path:    "/////",
  1509  			RawPath: "/%2F/%2F/",
  1510  		},
  1511  		"/%2F/%2F/",
  1512  	},
  1513  	{
  1514  		&URL{
  1515  			Scheme:  "http",
  1516  			Host:    "example.com",
  1517  			Path:    "/////",
  1518  			RawPath: "/WRONG/", // ignored because doesn't match Path
  1519  		},
  1520  		"/////",
  1521  	},
  1522  	{
  1523  		&URL{
  1524  			Scheme:   "http",
  1525  			Host:     "example.com",
  1526  			Path:     "/a b",
  1527  			RawQuery: "q=go+language",
  1528  		},
  1529  		"/a%20b?q=go+language",
  1530  	},
  1531  	{
  1532  		&URL{
  1533  			Scheme:   "http",
  1534  			Host:     "example.com",
  1535  			Path:     "/a b",
  1536  			RawPath:  "/a b", // ignored because invalid
  1537  			RawQuery: "q=go+language",
  1538  		},
  1539  		"/a%20b?q=go+language",
  1540  	},
  1541  	{
  1542  		&URL{
  1543  			Scheme:   "http",
  1544  			Host:     "example.com",
  1545  			Path:     "/a?b",
  1546  			RawPath:  "/a?b", // ignored because invalid
  1547  			RawQuery: "q=go+language",
  1548  		},
  1549  		"/a%3Fb?q=go+language",
  1550  	},
  1551  	{
  1552  		&URL{
  1553  			Scheme: "myschema",
  1554  			Opaque: "opaque",
  1555  		},
  1556  		"opaque",
  1557  	},
  1558  	{
  1559  		&URL{
  1560  			Scheme:   "myschema",
  1561  			Opaque:   "opaque",
  1562  			RawQuery: "q=go+language",
  1563  		},
  1564  		"opaque?q=go+language",
  1565  	},
  1566  	{
  1567  		&URL{
  1568  			Scheme: "http",
  1569  			Host:   "example.com",
  1570  			Path:   "//foo",
  1571  		},
  1572  		"//foo",
  1573  	},
  1574  	{
  1575  		&URL{
  1576  			Scheme:     "http",
  1577  			Host:       "example.com",
  1578  			Path:       "/foo",
  1579  			ForceQuery: true,
  1580  		},
  1581  		"/foo?",
  1582  	},
  1583  }
  1584  
  1585  func TestRequestURI(t *testing.T) {
  1586  	for _, tt := range requritests {
  1587  		s := tt.url.RequestURI()
  1588  		if s != tt.out {
  1589  			t.Errorf("%#v.RequestURI() == %q (expected %q)", tt.url, s, tt.out)
  1590  		}
  1591  	}
  1592  }
  1593  
  1594  func TestParseFailure(t *testing.T) {
  1595  	// Test that the first parse error is returned.
  1596  	const url = "%gh&%ij"
  1597  	_, err := ParseQuery(url)
  1598  	errStr := fmt.Sprint(err)
  1599  	if !strings.Contains(errStr, "%gh") {
  1600  		t.Errorf(`ParseQuery(%q) returned error %q, want something containing %q"`, url, errStr, "%gh")
  1601  	}
  1602  }
  1603  
  1604  func TestParseErrors(t *testing.T) {
  1605  	tests := []struct {
  1606  		in      string
  1607  		wantErr bool
  1608  	}{
  1609  		{"http://[::1]", false},
  1610  		{"http://[::1]:80", false},
  1611  		{"http://[::1]:namedport", true}, // rfc3986 3.2.3
  1612  		{"http://x:namedport", true},     // rfc3986 3.2.3
  1613  		{"http://[::1]/", false},
  1614  		{"http://[::1]a", true},
  1615  		{"http://[::1]%23", true},
  1616  		{"http://[::1%25en0]", false},    // valid zone id
  1617  		{"http://[::1]:", false},         // colon, but no port OK
  1618  		{"http://x:", false},             // colon, but no port OK
  1619  		{"http://[::1]:%38%30", true},    // not allowed: % encoding only for non-ASCII
  1620  		{"http://[::1%25%41]", false},    // RFC 6874 allows over-escaping in zone
  1621  		{"http://[%10::1]", true},        // no %xx escapes in IP address
  1622  		{"http://[::1]/%48", false},      // %xx in path is fine
  1623  		{"http://%41:8080/", true},       // not allowed: % encoding only for non-ASCII
  1624  		{"mysql://x@y(z:123)/foo", true}, // not well-formed per RFC 3986, golang.org/issue/33646
  1625  		{"mysql://x@y(1.2.3.4:123)/foo", true},
  1626  
  1627  		{" http://foo.com", true},  // invalid character in schema
  1628  		{"ht tp://foo.com", true},  // invalid character in schema
  1629  		{"ahttp://foo.com", false}, // valid schema characters
  1630  		{"1http://foo.com", true},  // invalid character in schema
  1631  
  1632  		{"http://[]%20%48%54%54%50%2f%31%2e%31%0a%4d%79%48%65%61%64%65%72%3a%20%31%32%33%0a%0a/", true}, // golang.org/issue/11208
  1633  		{"http://a b.com/", true},    // no space in host name please
  1634  		{"cache_object://foo", true}, // scheme cannot have _, relative path cannot have : in first segment
  1635  		{"cache_object:foo", true},
  1636  		{"cache_object:foo/bar", true},
  1637  		{"cache_object/:foo/bar", false},
  1638  	}
  1639  	for _, tt := range tests {
  1640  		u, err := Parse(tt.in)
  1641  		if tt.wantErr {
  1642  			if err == nil {
  1643  				t.Errorf("Parse(%q) = %#v; want an error", tt.in, u)
  1644  			}
  1645  			continue
  1646  		}
  1647  		if err != nil {
  1648  			t.Errorf("Parse(%q) = %v; want no error", tt.in, err)
  1649  		}
  1650  	}
  1651  }
  1652  
  1653  // Issue 11202
  1654  func TestStarRequest(t *testing.T) {
  1655  	u, err := Parse("*")
  1656  	if err != nil {
  1657  		t.Fatal(err)
  1658  	}
  1659  	if got, want := u.RequestURI(), "*"; got != want {
  1660  		t.Errorf("RequestURI = %q; want %q", got, want)
  1661  	}
  1662  }
  1663  
  1664  type shouldEscapeTest struct {
  1665  	in     byte
  1666  	mode   encoding
  1667  	escape bool
  1668  }
  1669  
  1670  var shouldEscapeTests = []shouldEscapeTest{
  1671  	// Unreserved characters (§2.3)
  1672  	{'a', encodePath, false},
  1673  	{'a', encodeUserPassword, false},
  1674  	{'a', encodeQueryComponent, false},
  1675  	{'a', encodeFragment, false},
  1676  	{'a', encodeHost, false},
  1677  	{'z', encodePath, false},
  1678  	{'A', encodePath, false},
  1679  	{'Z', encodePath, false},
  1680  	{'0', encodePath, false},
  1681  	{'9', encodePath, false},
  1682  	{'-', encodePath, false},
  1683  	{'-', encodeUserPassword, false},
  1684  	{'-', encodeQueryComponent, false},
  1685  	{'-', encodeFragment, false},
  1686  	{'.', encodePath, false},
  1687  	{'_', encodePath, false},
  1688  	{'~', encodePath, false},
  1689  
  1690  	// User information (§3.2.1)
  1691  	{':', encodeUserPassword, true},
  1692  	{'/', encodeUserPassword, true},
  1693  	{'?', encodeUserPassword, true},
  1694  	{'@', encodeUserPassword, true},
  1695  	{'$', encodeUserPassword, false},
  1696  	{'&', encodeUserPassword, false},
  1697  	{'+', encodeUserPassword, false},
  1698  	{',', encodeUserPassword, false},
  1699  	{';', encodeUserPassword, false},
  1700  	{'=', encodeUserPassword, false},
  1701  
  1702  	// Host (IP address, IPv6 address, registered name, port suffix; §3.2.2)
  1703  	{'!', encodeHost, false},
  1704  	{'$', encodeHost, false},
  1705  	{'&', encodeHost, false},
  1706  	{'\'', encodeHost, false},
  1707  	{'(', encodeHost, false},
  1708  	{')', encodeHost, false},
  1709  	{'*', encodeHost, false},
  1710  	{'+', encodeHost, false},
  1711  	{',', encodeHost, false},
  1712  	{';', encodeHost, false},
  1713  	{'=', encodeHost, false},
  1714  	{':', encodeHost, false},
  1715  	{'[', encodeHost, false},
  1716  	{']', encodeHost, false},
  1717  	{'0', encodeHost, false},
  1718  	{'9', encodeHost, false},
  1719  	{'A', encodeHost, false},
  1720  	{'z', encodeHost, false},
  1721  	{'_', encodeHost, false},
  1722  	{'-', encodeHost, false},
  1723  	{'.', encodeHost, false},
  1724  }
  1725  
  1726  func TestShouldEscape(t *testing.T) {
  1727  	for _, tt := range shouldEscapeTests {
  1728  		if shouldEscape(tt.in, tt.mode) != tt.escape {
  1729  			t.Errorf("shouldEscape(%q, %v) returned %v; expected %v", tt.in, tt.mode, !tt.escape, tt.escape)
  1730  		}
  1731  	}
  1732  }
  1733  
  1734  type timeoutError struct {
  1735  	timeout bool
  1736  }
  1737  
  1738  func (e *timeoutError) Error() string { return "timeout error" }
  1739  func (e *timeoutError) Timeout() bool { return e.timeout }
  1740  
  1741  type temporaryError struct {
  1742  	temporary bool
  1743  }
  1744  
  1745  func (e *temporaryError) Error() string   { return "temporary error" }
  1746  func (e *temporaryError) Temporary() bool { return e.temporary }
  1747  
  1748  type timeoutTemporaryError struct {
  1749  	timeoutError
  1750  	temporaryError
  1751  }
  1752  
  1753  func (e *timeoutTemporaryError) Error() string { return "timeout/temporary error" }
  1754  
  1755  var netErrorTests = []struct {
  1756  	err       error
  1757  	timeout   bool
  1758  	temporary bool
  1759  }{{
  1760  	err:       &Error{"Get", "http://google.com/", &timeoutError{timeout: true}},
  1761  	timeout:   true,
  1762  	temporary: false,
  1763  }, {
  1764  	err:       &Error{"Get", "http://google.com/", &timeoutError{timeout: false}},
  1765  	timeout:   false,
  1766  	temporary: false,
  1767  }, {
  1768  	err:       &Error{"Get", "http://google.com/", &temporaryError{temporary: true}},
  1769  	timeout:   false,
  1770  	temporary: true,
  1771  }, {
  1772  	err:       &Error{"Get", "http://google.com/", &temporaryError{temporary: false}},
  1773  	timeout:   false,
  1774  	temporary: false,
  1775  }, {
  1776  	err:       &Error{"Get", "http://google.com/", &timeoutTemporaryError{timeoutError{timeout: true}, temporaryError{temporary: true}}},
  1777  	timeout:   true,
  1778  	temporary: true,
  1779  }, {
  1780  	err:       &Error{"Get", "http://google.com/", &timeoutTemporaryError{timeoutError{timeout: false}, temporaryError{temporary: true}}},
  1781  	timeout:   false,
  1782  	temporary: true,
  1783  }, {
  1784  	err:       &Error{"Get", "http://google.com/", &timeoutTemporaryError{timeoutError{timeout: true}, temporaryError{temporary: false}}},
  1785  	timeout:   true,
  1786  	temporary: false,
  1787  }, {
  1788  	err:       &Error{"Get", "http://google.com/", &timeoutTemporaryError{timeoutError{timeout: false}, temporaryError{temporary: false}}},
  1789  	timeout:   false,
  1790  	temporary: false,
  1791  }, {
  1792  	err:       &Error{"Get", "http://google.com/", io.EOF},
  1793  	timeout:   false,
  1794  	temporary: false,
  1795  }}
  1796  
  1797  // Test that url.Error implements net.Error and that it forwards
  1798  func TestURLErrorImplementsNetError(t *testing.T) {
  1799  	for i, tt := range netErrorTests {
  1800  		err, ok := tt.err.(net.Error)
  1801  		if !ok {
  1802  			t.Errorf("%d: %T does not implement net.Error", i+1, tt.err)
  1803  			continue
  1804  		}
  1805  		if err.Timeout() != tt.timeout {
  1806  			t.Errorf("%d: err.Timeout(): got %v, want %v", i+1, err.Timeout(), tt.timeout)
  1807  			continue
  1808  		}
  1809  		if err.Temporary() != tt.temporary {
  1810  			t.Errorf("%d: err.Temporary(): got %v, want %v", i+1, err.Temporary(), tt.temporary)
  1811  		}
  1812  	}
  1813  }
  1814  
  1815  func TestURLHostnameAndPort(t *testing.T) {
  1816  	tests := []struct {
  1817  		in   string // URL.Host field
  1818  		host string
  1819  		port string
  1820  	}{
  1821  		{"foo.com:80", "foo.com", "80"},
  1822  		{"foo.com", "foo.com", ""},
  1823  		{"foo.com:", "foo.com", ""},
  1824  		{"FOO.COM", "FOO.COM", ""}, // no canonicalization
  1825  		{"1.2.3.4", "1.2.3.4", ""},
  1826  		{"1.2.3.4:80", "1.2.3.4", "80"},
  1827  		{"[1:2:3:4]", "1:2:3:4", ""},
  1828  		{"[1:2:3:4]:80", "1:2:3:4", "80"},
  1829  		{"[::1]:80", "::1", "80"},
  1830  		{"[::1]", "::1", ""},
  1831  		{"[::1]:", "::1", ""},
  1832  		{"localhost", "localhost", ""},
  1833  		{"localhost:443", "localhost", "443"},
  1834  		{"some.super.long.domain.example.org:8080", "some.super.long.domain.example.org", "8080"},
  1835  		{"[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:17000", "2001:0db8:85a3:0000:0000:8a2e:0370:7334", "17000"},
  1836  		{"[2001:0db8:85a3:0000:0000:8a2e:0370:7334]", "2001:0db8:85a3:0000:0000:8a2e:0370:7334", ""},
  1837  
  1838  		// Ensure that even when not valid, Host is one of "Hostname",
  1839  		// "Hostname:Port", "[Hostname]" or "[Hostname]:Port".
  1840  		// See https://golang.org/issue/29098.
  1841  		{"[google.com]:80", "google.com", "80"},
  1842  		{"google.com]:80", "google.com]", "80"},
  1843  		{"google.com:80_invalid_port", "google.com:80_invalid_port", ""},
  1844  		{"[::1]extra]:80", "::1]extra", "80"},
  1845  		{"google.com]extra:extra", "google.com]extra:extra", ""},
  1846  	}
  1847  	for _, tt := range tests {
  1848  		u := &URL{Host: tt.in}
  1849  		host, port := u.Hostname(), u.Port()
  1850  		if host != tt.host {
  1851  			t.Errorf("Hostname for Host %q = %q; want %q", tt.in, host, tt.host)
  1852  		}
  1853  		if port != tt.port {
  1854  			t.Errorf("Port for Host %q = %q; want %q", tt.in, port, tt.port)
  1855  		}
  1856  	}
  1857  }
  1858  
  1859  var _ encodingPkg.BinaryMarshaler = (*URL)(nil)
  1860  var _ encodingPkg.BinaryUnmarshaler = (*URL)(nil)
  1861  
  1862  func TestJSON(t *testing.T) {
  1863  	u, err := Parse("https://www.google.com/x?y=z")
  1864  	if err != nil {
  1865  		t.Fatal(err)
  1866  	}
  1867  	js, err := json.Marshal(u)
  1868  	if err != nil {
  1869  		t.Fatal(err)
  1870  	}
  1871  
  1872  	// If only we could implement TextMarshaler/TextUnmarshaler,
  1873  	// this would work:
  1874  	//
  1875  	// if string(js) != strconv.Quote(u.String()) {
  1876  	// 	t.Errorf("json encoding: %s\nwant: %s\n", js, strconv.Quote(u.String()))
  1877  	// }
  1878  
  1879  	u1 := new(URL)
  1880  	err = json.Unmarshal(js, u1)
  1881  	if err != nil {
  1882  		t.Fatal(err)
  1883  	}
  1884  	if u1.String() != u.String() {
  1885  		t.Errorf("json decoded to: %s\nwant: %s\n", u1, u)
  1886  	}
  1887  }
  1888  
  1889  func TestGob(t *testing.T) {
  1890  	u, err := Parse("https://www.google.com/x?y=z")
  1891  	if err != nil {
  1892  		t.Fatal(err)
  1893  	}
  1894  	var w bytes.Buffer
  1895  	err = gob.NewEncoder(&w).Encode(u)
  1896  	if err != nil {
  1897  		t.Fatal(err)
  1898  	}
  1899  
  1900  	u1 := new(URL)
  1901  	err = gob.NewDecoder(&w).Decode(u1)
  1902  	if err != nil {
  1903  		t.Fatal(err)
  1904  	}
  1905  	if u1.String() != u.String() {
  1906  		t.Errorf("json decoded to: %s\nwant: %s\n", u1, u)
  1907  	}
  1908  }
  1909  
  1910  func TestNilUser(t *testing.T) {
  1911  	defer func() {
  1912  		if v := recover(); v != nil {
  1913  			t.Fatalf("unexpected panic: %v", v)
  1914  		}
  1915  	}()
  1916  
  1917  	u, err := Parse("http://foo.com/")
  1918  
  1919  	if err != nil {
  1920  		t.Fatalf("parse err: %v", err)
  1921  	}
  1922  
  1923  	if v := u.User.Username(); v != "" {
  1924  		t.Fatalf("expected empty username, got %s", v)
  1925  	}
  1926  
  1927  	if v, ok := u.User.Password(); v != "" || ok {
  1928  		t.Fatalf("expected empty password, got %s (%v)", v, ok)
  1929  	}
  1930  
  1931  	if v := u.User.String(); v != "" {
  1932  		t.Fatalf("expected empty string, got %s", v)
  1933  	}
  1934  }
  1935  
  1936  func TestInvalidUserPassword(t *testing.T) {
  1937  	_, err := Parse("http://user^:passwo^rd@foo.com/")
  1938  	if got, wantsub := fmt.Sprint(err), "net/url: invalid userinfo"; !strings.Contains(got, wantsub) {
  1939  		t.Errorf("error = %q; want substring %q", got, wantsub)
  1940  	}
  1941  }
  1942  
  1943  func TestRejectControlCharacters(t *testing.T) {
  1944  	tests := []string{
  1945  		"http://foo.com/?foo\nbar",
  1946  		"http\r://foo.com/",
  1947  		"http://foo\x7f.com/",
  1948  	}
  1949  	for _, s := range tests {
  1950  		_, err := Parse(s)
  1951  		const wantSub = "net/url: invalid control character in URL"
  1952  		if got := fmt.Sprint(err); !strings.Contains(got, wantSub) {
  1953  			t.Errorf("Parse(%q) error = %q; want substring %q", s, got, wantSub)
  1954  		}
  1955  	}
  1956  
  1957  	// But don't reject non-ASCII CTLs, at least for now:
  1958  	if _, err := Parse("http://foo.com/ctl\x80"); err != nil {
  1959  		t.Errorf("error parsing URL with non-ASCII control byte: %v", err)
  1960  	}
  1961  
  1962  }
  1963  
  1964  var escapeBenchmarks = []struct {
  1965  	unescaped string
  1966  	query     string
  1967  	path      string
  1968  }{
  1969  	{
  1970  		unescaped: "one two",
  1971  		query:     "one+two",
  1972  		path:      "one%20two",
  1973  	},
  1974  	{
  1975  		unescaped: "Фотки собак",
  1976  		query:     "%D0%A4%D0%BE%D1%82%D0%BA%D0%B8+%D1%81%D0%BE%D0%B1%D0%B0%D0%BA",
  1977  		path:      "%D0%A4%D0%BE%D1%82%D0%BA%D0%B8%20%D1%81%D0%BE%D0%B1%D0%B0%D0%BA",
  1978  	},
  1979  
  1980  	{
  1981  		unescaped: "shortrun(break)shortrun",
  1982  		query:     "shortrun%28break%29shortrun",
  1983  		path:      "shortrun%28break%29shortrun",
  1984  	},
  1985  
  1986  	{
  1987  		unescaped: "longerrunofcharacters(break)anotherlongerrunofcharacters",
  1988  		query:     "longerrunofcharacters%28break%29anotherlongerrunofcharacters",
  1989  		path:      "longerrunofcharacters%28break%29anotherlongerrunofcharacters",
  1990  	},
  1991  
  1992  	{
  1993  		unescaped: strings.Repeat("padded/with+various%characters?that=need$some@escaping+paddedsowebreak/256bytes", 4),
  1994  		query:     strings.Repeat("padded%2Fwith%2Bvarious%25characters%3Fthat%3Dneed%24some%40escaping%2Bpaddedsowebreak%2F256bytes", 4),
  1995  		path:      strings.Repeat("padded%2Fwith+various%25characters%3Fthat=need$some@escaping+paddedsowebreak%2F256bytes", 4),
  1996  	},
  1997  }
  1998  
  1999  func BenchmarkQueryEscape(b *testing.B) {
  2000  	for _, tc := range escapeBenchmarks {
  2001  		b.Run("", func(b *testing.B) {
  2002  			b.ReportAllocs()
  2003  			var g string
  2004  			for i := 0; i < b.N; i++ {
  2005  				g = QueryEscape(tc.unescaped)
  2006  			}
  2007  			b.StopTimer()
  2008  			if g != tc.query {
  2009  				b.Errorf("QueryEscape(%q) == %q, want %q", tc.unescaped, g, tc.query)
  2010  			}
  2011  
  2012  		})
  2013  	}
  2014  }
  2015  
  2016  func BenchmarkPathEscape(b *testing.B) {
  2017  	for _, tc := range escapeBenchmarks {
  2018  		b.Run("", func(b *testing.B) {
  2019  			b.ReportAllocs()
  2020  			var g string
  2021  			for i := 0; i < b.N; i++ {
  2022  				g = PathEscape(tc.unescaped)
  2023  			}
  2024  			b.StopTimer()
  2025  			if g != tc.path {
  2026  				b.Errorf("PathEscape(%q) == %q, want %q", tc.unescaped, g, tc.path)
  2027  			}
  2028  
  2029  		})
  2030  	}
  2031  }
  2032  
  2033  func BenchmarkQueryUnescape(b *testing.B) {
  2034  	for _, tc := range escapeBenchmarks {
  2035  		b.Run("", func(b *testing.B) {
  2036  			b.ReportAllocs()
  2037  			var g string
  2038  			for i := 0; i < b.N; i++ {
  2039  				g, _ = QueryUnescape(tc.query)
  2040  			}
  2041  			b.StopTimer()
  2042  			if g != tc.unescaped {
  2043  				b.Errorf("QueryUnescape(%q) == %q, want %q", tc.query, g, tc.unescaped)
  2044  			}
  2045  
  2046  		})
  2047  	}
  2048  }
  2049  
  2050  func BenchmarkPathUnescape(b *testing.B) {
  2051  	for _, tc := range escapeBenchmarks {
  2052  		b.Run("", func(b *testing.B) {
  2053  			b.ReportAllocs()
  2054  			var g string
  2055  			for i := 0; i < b.N; i++ {
  2056  				g, _ = PathUnescape(tc.path)
  2057  			}
  2058  			b.StopTimer()
  2059  			if g != tc.unescaped {
  2060  				b.Errorf("PathUnescape(%q) == %q, want %q", tc.path, g, tc.unescaped)
  2061  			}
  2062  
  2063  		})
  2064  	}
  2065  }
  2066  
  2067  func TestJoinPath(t *testing.T) {
  2068  	tests := []struct {
  2069  		base string
  2070  		elem []string
  2071  		out  string
  2072  	}{
  2073  		{
  2074  			base: "https://go.googlesource.com",
  2075  			elem: []string{"go"},
  2076  			out:  "https://go.googlesource.com/go",
  2077  		},
  2078  		{
  2079  			base: "https://go.googlesource.com/a/b/c",
  2080  			elem: []string{"../../../go"},
  2081  			out:  "https://go.googlesource.com/go",
  2082  		},
  2083  		{
  2084  			base: "https://go.googlesource.com/",
  2085  			elem: []string{"../go"},
  2086  			out:  "https://go.googlesource.com/go",
  2087  		},
  2088  		{
  2089  			base: "https://go.googlesource.com",
  2090  			elem: []string{"../go"},
  2091  			out:  "https://go.googlesource.com/go",
  2092  		},
  2093  		{
  2094  			base: "https://go.googlesource.com",
  2095  			elem: []string{"../go", "../../go", "../../../go"},
  2096  			out:  "https://go.googlesource.com/go",
  2097  		},
  2098  		{
  2099  			base: "https://go.googlesource.com/../go",
  2100  			elem: nil,
  2101  			out:  "https://go.googlesource.com/go",
  2102  		},
  2103  		{
  2104  			base: "https://go.googlesource.com/",
  2105  			elem: []string{"./go"},
  2106  			out:  "https://go.googlesource.com/go",
  2107  		},
  2108  		{
  2109  			base: "https://go.googlesource.com//",
  2110  			elem: []string{"/go"},
  2111  			out:  "https://go.googlesource.com/go",
  2112  		},
  2113  		{
  2114  			base: "https://go.googlesource.com//",
  2115  			elem: []string{"/go", "a", "b", "c"},
  2116  			out:  "https://go.googlesource.com/go/a/b/c",
  2117  		},
  2118  		{
  2119  			base: "http://[fe80::1%en0]:8080/",
  2120  			elem: []string{"/go"},
  2121  		},
  2122  		{
  2123  			base: "https://go.googlesource.com",
  2124  			elem: []string{"go/"},
  2125  			out:  "https://go.googlesource.com/go/",
  2126  		},
  2127  		{
  2128  			base: "https://go.googlesource.com",
  2129  			elem: []string{"go//"},
  2130  			out:  "https://go.googlesource.com/go/",
  2131  		},
  2132  		{
  2133  			base: "https://go.googlesource.com",
  2134  			elem: nil,
  2135  			out:  "https://go.googlesource.com/",
  2136  		},
  2137  		{
  2138  			base: "https://go.googlesource.com/",
  2139  			elem: nil,
  2140  			out:  "https://go.googlesource.com/",
  2141  		},
  2142  		{
  2143  			base: "https://go.googlesource.com/a%2fb",
  2144  			elem: []string{"c"},
  2145  			out:  "https://go.googlesource.com/a%2fb/c",
  2146  		},
  2147  		{
  2148  			base: "https://go.googlesource.com/a%2fb",
  2149  			elem: []string{"c%2fd"},
  2150  			out:  "https://go.googlesource.com/a%2fb/c%2fd",
  2151  		},
  2152  		{
  2153  			base: "https://go.googlesource.com/a/b",
  2154  			elem: []string{"/go"},
  2155  			out:  "https://go.googlesource.com/a/b/go",
  2156  		},
  2157  		{
  2158  			base: "/",
  2159  			elem: nil,
  2160  			out:  "/",
  2161  		},
  2162  		{
  2163  			base: "a",
  2164  			elem: nil,
  2165  			out:  "a",
  2166  		},
  2167  		{
  2168  			base: "a",
  2169  			elem: []string{"b"},
  2170  			out:  "a/b",
  2171  		},
  2172  		{
  2173  			base: "a",
  2174  			elem: []string{"../b"},
  2175  			out:  "b",
  2176  		},
  2177  		{
  2178  			base: "a",
  2179  			elem: []string{"../../b"},
  2180  			out:  "b",
  2181  		},
  2182  		{
  2183  			base: "",
  2184  			elem: []string{"a"},
  2185  			out:  "a",
  2186  		},
  2187  		{
  2188  			base: "",
  2189  			elem: []string{"../a"},
  2190  			out:  "a",
  2191  		},
  2192  	}
  2193  	for _, tt := range tests {
  2194  		wantErr := "nil"
  2195  		if tt.out == "" {
  2196  			wantErr = "non-nil error"
  2197  		}
  2198  		if out, err := JoinPath(tt.base, tt.elem...); out != tt.out || (err == nil) != (tt.out != "") {
  2199  			t.Errorf("JoinPath(%q, %q) = %q, %v, want %q, %v", tt.base, tt.elem, out, err, tt.out, wantErr)
  2200  		}
  2201  		var out string
  2202  		u, err := Parse(tt.base)
  2203  		if err == nil {
  2204  			u = u.JoinPath(tt.elem...)
  2205  			out = u.String()
  2206  		}
  2207  		if out != tt.out || (err == nil) != (tt.out != "") {
  2208  			t.Errorf("Parse(%q).JoinPath(%q) = %q, %v, want %q, %v", tt.base, tt.elem, out, err, tt.out, wantErr)
  2209  		}
  2210  	}
  2211  }
  2212  

View as plain text