github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/gnovm/stdlibs/net/url/url_test.gno (about)

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