...
Run Format

Source file src/net/url/url_test.go

Documentation: net/url

     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; RawPath="" means same as Path
    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  	// user
    58  	{
    59  		"ftp://webmaster@www.google.com/",
    60  		&URL{
    61  			Scheme: "ftp",
    62  			User:   User("webmaster"),
    63  			Host:   "www.google.com",
    64  			Path:   "/",
    65  		},
    66  		"",
    67  	},
    68  	// escape sequence in username
    69  	{
    70  		"ftp://john%20doe@www.google.com/",
    71  		&URL{
    72  			Scheme: "ftp",
    73  			User:   User("john doe"),
    74  			Host:   "www.google.com",
    75  			Path:   "/",
    76  		},
    77  		"ftp://john%20doe@www.google.com/",
    78  	},
    79  	// empty query
    80  	{
    81  		"http://www.google.com/?",
    82  		&URL{
    83  			Scheme:     "http",
    84  			Host:       "www.google.com",
    85  			Path:       "/",
    86  			ForceQuery: true,
    87  		},
    88  		"",
    89  	},
    90  	// query ending in question mark (Issue 14573)
    91  	{
    92  		"http://www.google.com/?foo=bar?",
    93  		&URL{
    94  			Scheme:   "http",
    95  			Host:     "www.google.com",
    96  			Path:     "/",
    97  			RawQuery: "foo=bar?",
    98  		},
    99  		"",
   100  	},
   101  	// query
   102  	{
   103  		"http://www.google.com/?q=go+language",
   104  		&URL{
   105  			Scheme:   "http",
   106  			Host:     "www.google.com",
   107  			Path:     "/",
   108  			RawQuery: "q=go+language",
   109  		},
   110  		"",
   111  	},
   112  	// query with hex escaping: NOT parsed
   113  	{
   114  		"http://www.google.com/?q=go%20language",
   115  		&URL{
   116  			Scheme:   "http",
   117  			Host:     "www.google.com",
   118  			Path:     "/",
   119  			RawQuery: "q=go%20language",
   120  		},
   121  		"",
   122  	},
   123  	// %20 outside query
   124  	{
   125  		"http://www.google.com/a%20b?q=c+d",
   126  		&URL{
   127  			Scheme:   "http",
   128  			Host:     "www.google.com",
   129  			Path:     "/a b",
   130  			RawQuery: "q=c+d",
   131  		},
   132  		"",
   133  	},
   134  	// path without leading /, so no parsing
   135  	{
   136  		"http:www.google.com/?q=go+language",
   137  		&URL{
   138  			Scheme:   "http",
   139  			Opaque:   "www.google.com/",
   140  			RawQuery: "q=go+language",
   141  		},
   142  		"http:www.google.com/?q=go+language",
   143  	},
   144  	// path without leading /, so no parsing
   145  	{
   146  		"http:%2f%2fwww.google.com/?q=go+language",
   147  		&URL{
   148  			Scheme:   "http",
   149  			Opaque:   "%2f%2fwww.google.com/",
   150  			RawQuery: "q=go+language",
   151  		},
   152  		"http:%2f%2fwww.google.com/?q=go+language",
   153  	},
   154  	// non-authority with path
   155  	{
   156  		"mailto:/webmaster@golang.org",
   157  		&URL{
   158  			Scheme: "mailto",
   159  			Path:   "/webmaster@golang.org",
   160  		},
   161  		"mailto:///webmaster@golang.org", // unfortunate compromise
   162  	},
   163  	// non-authority
   164  	{
   165  		"mailto:webmaster@golang.org",
   166  		&URL{
   167  			Scheme: "mailto",
   168  			Opaque: "webmaster@golang.org",
   169  		},
   170  		"",
   171  	},
   172  	// unescaped :// in query should not create a scheme
   173  	{
   174  		"/foo?query=http://bad",
   175  		&URL{
   176  			Path:     "/foo",
   177  			RawQuery: "query=http://bad",
   178  		},
   179  		"",
   180  	},
   181  	// leading // without scheme should create an authority
   182  	{
   183  		"//foo",
   184  		&URL{
   185  			Host: "foo",
   186  		},
   187  		"",
   188  	},
   189  	// leading // without scheme, with userinfo, path, and query
   190  	{
   191  		"//user@foo/path?a=b",
   192  		&URL{
   193  			User:     User("user"),
   194  			Host:     "foo",
   195  			Path:     "/path",
   196  			RawQuery: "a=b",
   197  		},
   198  		"",
   199  	},
   200  	// Three leading slashes isn't an authority, but doesn't return an error.
   201  	// (We can't return an error, as this code is also used via
   202  	// ServeHTTP -> ReadRequest -> Parse, which is arguably a
   203  	// different URL parsing context, but currently shares the
   204  	// same codepath)
   205  	{
   206  		"///threeslashes",
   207  		&URL{
   208  			Path: "///threeslashes",
   209  		},
   210  		"",
   211  	},
   212  	{
   213  		"http://user:password@google.com",
   214  		&URL{
   215  			Scheme: "http",
   216  			User:   UserPassword("user", "password"),
   217  			Host:   "google.com",
   218  		},
   219  		"http://user:password@google.com",
   220  	},
   221  	// unescaped @ in username should not confuse host
   222  	{
   223  		"http://j@ne:password@google.com",
   224  		&URL{
   225  			Scheme: "http",
   226  			User:   UserPassword("j@ne", "password"),
   227  			Host:   "google.com",
   228  		},
   229  		"http://j%40ne:password@google.com",
   230  	},
   231  	// unescaped @ in password should not confuse host
   232  	{
   233  		"http://jane:p@ssword@google.com",
   234  		&URL{
   235  			Scheme: "http",
   236  			User:   UserPassword("jane", "p@ssword"),
   237  			Host:   "google.com",
   238  		},
   239  		"http://jane:p%40ssword@google.com",
   240  	},
   241  	{
   242  		"http://j@ne:password@google.com/p@th?q=@go",
   243  		&URL{
   244  			Scheme:   "http",
   245  			User:     UserPassword("j@ne", "password"),
   246  			Host:     "google.com",
   247  			Path:     "/p@th",
   248  			RawQuery: "q=@go",
   249  		},
   250  		"http://j%40ne:password@google.com/p@th?q=@go",
   251  	},
   252  	{
   253  		"http://www.google.com/?q=go+language#foo",
   254  		&URL{
   255  			Scheme:   "http",
   256  			Host:     "www.google.com",
   257  			Path:     "/",
   258  			RawQuery: "q=go+language",
   259  			Fragment: "foo",
   260  		},
   261  		"",
   262  	},
   263  	{
   264  		"http://www.google.com/?q=go+language#foo%26bar",
   265  		&URL{
   266  			Scheme:   "http",
   267  			Host:     "www.google.com",
   268  			Path:     "/",
   269  			RawQuery: "q=go+language",
   270  			Fragment: "foo&bar",
   271  		},
   272  		"http://www.google.com/?q=go+language#foo&bar",
   273  	},
   274  	{
   275  		"file:///home/adg/rabbits",
   276  		&URL{
   277  			Scheme: "file",
   278  			Host:   "",
   279  			Path:   "/home/adg/rabbits",
   280  		},
   281  		"file:///home/adg/rabbits",
   282  	},
   283  	// "Windows" paths are no exception to the rule.
   284  	// See golang.org/issue/6027, especially comment #9.
   285  	{
   286  		"file:///C:/FooBar/Baz.txt",
   287  		&URL{
   288  			Scheme: "file",
   289  			Host:   "",
   290  			Path:   "/C:/FooBar/Baz.txt",
   291  		},
   292  		"file:///C:/FooBar/Baz.txt",
   293  	},
   294  	// case-insensitive scheme
   295  	{
   296  		"MaIlTo:webmaster@golang.org",
   297  		&URL{
   298  			Scheme: "mailto",
   299  			Opaque: "webmaster@golang.org",
   300  		},
   301  		"mailto:webmaster@golang.org",
   302  	},
   303  	// Relative path
   304  	{
   305  		"a/b/c",
   306  		&URL{
   307  			Path: "a/b/c",
   308  		},
   309  		"a/b/c",
   310  	},
   311  	// escaped '?' in username and password
   312  	{
   313  		"http://%3Fam:pa%3Fsword@google.com",
   314  		&URL{
   315  			Scheme: "http",
   316  			User:   UserPassword("?am", "pa?sword"),
   317  			Host:   "google.com",
   318  		},
   319  		"",
   320  	},
   321  	// host subcomponent; IPv4 address in RFC 3986
   322  	{
   323  		"http://192.168.0.1/",
   324  		&URL{
   325  			Scheme: "http",
   326  			Host:   "192.168.0.1",
   327  			Path:   "/",
   328  		},
   329  		"",
   330  	},
   331  	// host and port subcomponents; IPv4 address in RFC 3986
   332  	{
   333  		"http://192.168.0.1:8080/",
   334  		&URL{
   335  			Scheme: "http",
   336  			Host:   "192.168.0.1:8080",
   337  			Path:   "/",
   338  		},
   339  		"",
   340  	},
   341  	// host subcomponent; IPv6 address in RFC 3986
   342  	{
   343  		"http://[fe80::1]/",
   344  		&URL{
   345  			Scheme: "http",
   346  			Host:   "[fe80::1]",
   347  			Path:   "/",
   348  		},
   349  		"",
   350  	},
   351  	// host and port subcomponents; IPv6 address in RFC 3986
   352  	{
   353  		"http://[fe80::1]:8080/",
   354  		&URL{
   355  			Scheme: "http",
   356  			Host:   "[fe80::1]:8080",
   357  			Path:   "/",
   358  		},
   359  		"",
   360  	},
   361  	// host subcomponent; IPv6 address with zone identifier in RFC 6874
   362  	{
   363  		"http://[fe80::1%25en0]/", // alphanum zone identifier
   364  		&URL{
   365  			Scheme: "http",
   366  			Host:   "[fe80::1%en0]",
   367  			Path:   "/",
   368  		},
   369  		"",
   370  	},
   371  	// host and port subcomponents; IPv6 address with zone identifier in RFC 6874
   372  	{
   373  		"http://[fe80::1%25en0]:8080/", // alphanum zone identifier
   374  		&URL{
   375  			Scheme: "http",
   376  			Host:   "[fe80::1%en0]:8080",
   377  			Path:   "/",
   378  		},
   379  		"",
   380  	},
   381  	// host subcomponent; IPv6 address with zone identifier in RFC 6874
   382  	{
   383  		"http://[fe80::1%25%65%6e%301-._~]/", // percent-encoded+unreserved zone identifier
   384  		&URL{
   385  			Scheme: "http",
   386  			Host:   "[fe80::1%en01-._~]",
   387  			Path:   "/",
   388  		},
   389  		"http://[fe80::1%25en01-._~]/",
   390  	},
   391  	// host and port subcomponents; IPv6 address with zone identifier in RFC 6874
   392  	{
   393  		"http://[fe80::1%25%65%6e%301-._~]:8080/", // percent-encoded+unreserved zone identifier
   394  		&URL{
   395  			Scheme: "http",
   396  			Host:   "[fe80::1%en01-._~]:8080",
   397  			Path:   "/",
   398  		},
   399  		"http://[fe80::1%25en01-._~]:8080/",
   400  	},
   401  	// alternate escapings of path survive round trip
   402  	{
   403  		"http://rest.rsc.io/foo%2fbar/baz%2Fquux?alt=media",
   404  		&URL{
   405  			Scheme:   "http",
   406  			Host:     "rest.rsc.io",
   407  			Path:     "/foo/bar/baz/quux",
   408  			RawPath:  "/foo%2fbar/baz%2Fquux",
   409  			RawQuery: "alt=media",
   410  		},
   411  		"",
   412  	},
   413  	// issue 12036
   414  	{
   415  		"mysql://a,b,c/bar",
   416  		&URL{
   417  			Scheme: "mysql",
   418  			Host:   "a,b,c",
   419  			Path:   "/bar",
   420  		},
   421  		"",
   422  	},
   423  	// worst case host, still round trips
   424  	{
   425  		"scheme://!$&'()*+,;=hello!:port/path",
   426  		&URL{
   427  			Scheme: "scheme",
   428  			Host:   "!$&'()*+,;=hello!:port",
   429  			Path:   "/path",
   430  		},
   431  		"",
   432  	},
   433  	// worst case path, still round trips
   434  	{
   435  		"http://host/!$&'()*+,;=:@[hello]",
   436  		&URL{
   437  			Scheme:  "http",
   438  			Host:    "host",
   439  			Path:    "/!$&'()*+,;=:@[hello]",
   440  			RawPath: "/!$&'()*+,;=:@[hello]",
   441  		},
   442  		"",
   443  	},
   444  	// golang.org/issue/5684
   445  	{
   446  		"http://example.com/oid/[order_id]",
   447  		&URL{
   448  			Scheme:  "http",
   449  			Host:    "example.com",
   450  			Path:    "/oid/[order_id]",
   451  			RawPath: "/oid/[order_id]",
   452  		},
   453  		"",
   454  	},
   455  	// golang.org/issue/12200 (colon with empty port)
   456  	{
   457  		"http://192.168.0.2:8080/foo",
   458  		&URL{
   459  			Scheme: "http",
   460  			Host:   "192.168.0.2:8080",
   461  			Path:   "/foo",
   462  		},
   463  		"",
   464  	},
   465  	{
   466  		"http://192.168.0.2:/foo",
   467  		&URL{
   468  			Scheme: "http",
   469  			Host:   "192.168.0.2:",
   470  			Path:   "/foo",
   471  		},
   472  		"",
   473  	},
   474  	{
   475  		// Malformed IPv6 but still accepted.
   476  		"http://2b01:e34:ef40:7730:8e70:5aff:fefe:edac:8080/foo",
   477  		&URL{
   478  			Scheme: "http",
   479  			Host:   "2b01:e34:ef40:7730:8e70:5aff:fefe:edac:8080",
   480  			Path:   "/foo",
   481  		},
   482  		"",
   483  	},
   484  	{
   485  		// Malformed IPv6 but still accepted.
   486  		"http://2b01:e34:ef40:7730:8e70:5aff:fefe:edac:/foo",
   487  		&URL{
   488  			Scheme: "http",
   489  			Host:   "2b01:e34:ef40:7730:8e70:5aff:fefe:edac:",
   490  			Path:   "/foo",
   491  		},
   492  		"",
   493  	},
   494  	{
   495  		"http://[2b01:e34:ef40:7730:8e70:5aff:fefe:edac]:8080/foo",
   496  		&URL{
   497  			Scheme: "http",
   498  			Host:   "[2b01:e34:ef40:7730:8e70:5aff:fefe:edac]:8080",
   499  			Path:   "/foo",
   500  		},
   501  		"",
   502  	},
   503  	{
   504  		"http://[2b01:e34:ef40:7730:8e70:5aff:fefe:edac]:/foo",
   505  		&URL{
   506  			Scheme: "http",
   507  			Host:   "[2b01:e34:ef40:7730:8e70:5aff:fefe:edac]:",
   508  			Path:   "/foo",
   509  		},
   510  		"",
   511  	},
   512  	// golang.org/issue/7991 and golang.org/issue/12719 (non-ascii %-encoded in host)
   513  	{
   514  		"http://hello.世界.com/foo",
   515  		&URL{
   516  			Scheme: "http",
   517  			Host:   "hello.世界.com",
   518  			Path:   "/foo",
   519  		},
   520  		"http://hello.%E4%B8%96%E7%95%8C.com/foo",
   521  	},
   522  	{
   523  		"http://hello.%e4%b8%96%e7%95%8c.com/foo",
   524  		&URL{
   525  			Scheme: "http",
   526  			Host:   "hello.世界.com",
   527  			Path:   "/foo",
   528  		},
   529  		"http://hello.%E4%B8%96%E7%95%8C.com/foo",
   530  	},
   531  	{
   532  		"http://hello.%E4%B8%96%E7%95%8C.com/foo",
   533  		&URL{
   534  			Scheme: "http",
   535  			Host:   "hello.世界.com",
   536  			Path:   "/foo",
   537  		},
   538  		"",
   539  	},
   540  	// golang.org/issue/10433 (path beginning with //)
   541  	{
   542  		"http://example.com//foo",
   543  		&URL{
   544  			Scheme: "http",
   545  			Host:   "example.com",
   546  			Path:   "//foo",
   547  		},
   548  		"",
   549  	},
   550  	// test that we can reparse the host names we accept.
   551  	{
   552  		"myscheme://authority<\"hi\">/foo",
   553  		&URL{
   554  			Scheme: "myscheme",
   555  			Host:   "authority<\"hi\">",
   556  			Path:   "/foo",
   557  		},
   558  		"",
   559  	},
   560  	// spaces in hosts are disallowed but escaped spaces in IPv6 scope IDs are grudgingly OK.
   561  	// This happens on Windows.
   562  	// golang.org/issue/14002
   563  	{
   564  		"tcp://[2020::2020:20:2020:2020%25Windows%20Loves%20Spaces]:2020",
   565  		&URL{
   566  			Scheme: "tcp",
   567  			Host:   "[2020::2020:20:2020:2020%Windows Loves Spaces]:2020",
   568  		},
   569  		"",
   570  	},
   571  	// test we can roundtrip magnet url
   572  	// fix issue https://golang.org/issue/20054
   573  	{
   574  		"magnet:?xt=urn:btih:c12fe1c06bba254a9dc9f519b335aa7c1367a88a&dn",
   575  		&URL{
   576  			Scheme:   "magnet",
   577  			Host:     "",
   578  			Path:     "",
   579  			RawQuery: "xt=urn:btih:c12fe1c06bba254a9dc9f519b335aa7c1367a88a&dn",
   580  		},
   581  		"magnet:?xt=urn:btih:c12fe1c06bba254a9dc9f519b335aa7c1367a88a&dn",
   582  	},
   583  	{
   584  		"mailto:?subject=hi",
   585  		&URL{
   586  			Scheme:   "mailto",
   587  			Host:     "",
   588  			Path:     "",
   589  			RawQuery: "subject=hi",
   590  		},
   591  		"mailto:?subject=hi",
   592  	},
   593  }
   594  
   595  // more useful string for debugging than fmt's struct printer
   596  func ufmt(u *URL) string {
   597  	var user, pass interface{}
   598  	if u.User != nil {
   599  		user = u.User.Username()
   600  		if p, ok := u.User.Password(); ok {
   601  			pass = p
   602  		}
   603  	}
   604  	return fmt.Sprintf("opaque=%q, scheme=%q, user=%#v, pass=%#v, host=%q, path=%q, rawpath=%q, rawq=%q, frag=%q, forcequery=%v",
   605  		u.Opaque, u.Scheme, user, pass, u.Host, u.Path, u.RawPath, u.RawQuery, u.Fragment, u.ForceQuery)
   606  }
   607  
   608  func BenchmarkString(b *testing.B) {
   609  	b.StopTimer()
   610  	b.ReportAllocs()
   611  	for _, tt := range urltests {
   612  		u, err := Parse(tt.in)
   613  		if err != nil {
   614  			b.Errorf("Parse(%q) returned error %s", tt.in, err)
   615  			continue
   616  		}
   617  		if tt.roundtrip == "" {
   618  			continue
   619  		}
   620  		b.StartTimer()
   621  		var g string
   622  		for i := 0; i < b.N; i++ {
   623  			g = u.String()
   624  		}
   625  		b.StopTimer()
   626  		if w := tt.roundtrip; b.N > 0 && g != w {
   627  			b.Errorf("Parse(%q).String() == %q, want %q", tt.in, g, w)
   628  		}
   629  	}
   630  }
   631  
   632  func TestParse(t *testing.T) {
   633  	for _, tt := range urltests {
   634  		u, err := Parse(tt.in)
   635  		if err != nil {
   636  			t.Errorf("Parse(%q) returned error %v", tt.in, err)
   637  			continue
   638  		}
   639  		if !reflect.DeepEqual(u, tt.out) {
   640  			t.Errorf("Parse(%q):\n\tgot  %v\n\twant %v\n", tt.in, ufmt(u), ufmt(tt.out))
   641  		}
   642  	}
   643  }
   644  
   645  const pathThatLooksSchemeRelative = "//not.a.user@not.a.host/just/a/path"
   646  
   647  var parseRequestURLTests = []struct {
   648  	url           string
   649  	expectedValid bool
   650  }{
   651  	{"http://foo.com", true},
   652  	{"http://foo.com/", true},
   653  	{"http://foo.com/path", true},
   654  	{"/", true},
   655  	{pathThatLooksSchemeRelative, true},
   656  	{"//not.a.user@%66%6f%6f.com/just/a/path/also", true},
   657  	{"*", true},
   658  	{"http://192.168.0.1/", true},
   659  	{"http://192.168.0.1:8080/", true},
   660  	{"http://[fe80::1]/", true},
   661  	{"http://[fe80::1]:8080/", true},
   662  
   663  	// Tests exercising RFC 6874 compliance:
   664  	{"http://[fe80::1%25en0]/", true},                 // with alphanum zone identifier
   665  	{"http://[fe80::1%25en0]:8080/", true},            // with alphanum zone identifier
   666  	{"http://[fe80::1%25%65%6e%301-._~]/", true},      // with percent-encoded+unreserved zone identifier
   667  	{"http://[fe80::1%25%65%6e%301-._~]:8080/", true}, // with percent-encoded+unreserved zone identifier
   668  
   669  	{"foo.html", false},
   670  	{"../dir/", false},
   671  	{"http://192.168.0.%31/", false},
   672  	{"http://192.168.0.%31:8080/", false},
   673  	{"http://[fe80::%31]/", false},
   674  	{"http://[fe80::%31]:8080/", false},
   675  	{"http://[fe80::%31%25en0]/", false},
   676  	{"http://[fe80::%31%25en0]:8080/", false},
   677  
   678  	// These two cases are valid as textual representations as
   679  	// described in RFC 4007, but are not valid as address
   680  	// literals with IPv6 zone identifiers in URIs as described in
   681  	// RFC 6874.
   682  	{"http://[fe80::1%en0]/", false},
   683  	{"http://[fe80::1%en0]:8080/", false},
   684  }
   685  
   686  func TestParseRequestURI(t *testing.T) {
   687  	for _, test := range parseRequestURLTests {
   688  		_, err := ParseRequestURI(test.url)
   689  		if test.expectedValid && err != nil {
   690  			t.Errorf("ParseRequestURI(%q) gave err %v; want no error", test.url, err)
   691  		} else if !test.expectedValid && err == nil {
   692  			t.Errorf("ParseRequestURI(%q) gave nil error; want some error", test.url)
   693  		}
   694  	}
   695  
   696  	url, err := ParseRequestURI(pathThatLooksSchemeRelative)
   697  	if err != nil {
   698  		t.Fatalf("Unexpected error %v", err)
   699  	}
   700  	if url.Path != pathThatLooksSchemeRelative {
   701  		t.Errorf("ParseRequestURI path:\ngot  %q\nwant %q", url.Path, pathThatLooksSchemeRelative)
   702  	}
   703  }
   704  
   705  var stringURLTests = []struct {
   706  	url  URL
   707  	want string
   708  }{
   709  	// No leading slash on path should prepend slash on String() call
   710  	{
   711  		url: URL{
   712  			Scheme: "http",
   713  			Host:   "www.google.com",
   714  			Path:   "search",
   715  		},
   716  		want: "http://www.google.com/search",
   717  	},
   718  	// Relative path with first element containing ":" should be prepended with "./", golang.org/issue/17184
   719  	{
   720  		url: URL{
   721  			Path: "this:that",
   722  		},
   723  		want: "./this:that",
   724  	},
   725  	// Relative path with second element containing ":" should not be prepended with "./"
   726  	{
   727  		url: URL{
   728  			Path: "here/this:that",
   729  		},
   730  		want: "here/this:that",
   731  	},
   732  	// Non-relative path with first element containing ":" should not be prepended with "./"
   733  	{
   734  		url: URL{
   735  			Scheme: "http",
   736  			Host:   "www.google.com",
   737  			Path:   "this:that",
   738  		},
   739  		want: "http://www.google.com/this:that",
   740  	},
   741  }
   742  
   743  func TestURLString(t *testing.T) {
   744  	for _, tt := range urltests {
   745  		u, err := Parse(tt.in)
   746  		if err != nil {
   747  			t.Errorf("Parse(%q) returned error %s", tt.in, err)
   748  			continue
   749  		}
   750  		expected := tt.in
   751  		if tt.roundtrip != "" {
   752  			expected = tt.roundtrip
   753  		}
   754  		s := u.String()
   755  		if s != expected {
   756  			t.Errorf("Parse(%q).String() == %q (expected %q)", tt.in, s, expected)
   757  		}
   758  	}
   759  
   760  	for _, tt := range stringURLTests {
   761  		if got := tt.url.String(); got != tt.want {
   762  			t.Errorf("%+v.String() = %q; want %q", tt.url, got, tt.want)
   763  		}
   764  	}
   765  }
   766  
   767  type EscapeTest struct {
   768  	in  string
   769  	out string
   770  	err error
   771  }
   772  
   773  var unescapeTests = []EscapeTest{
   774  	{
   775  		"",
   776  		"",
   777  		nil,
   778  	},
   779  	{
   780  		"abc",
   781  		"abc",
   782  		nil,
   783  	},
   784  	{
   785  		"1%41",
   786  		"1A",
   787  		nil,
   788  	},
   789  	{
   790  		"1%41%42%43",
   791  		"1ABC",
   792  		nil,
   793  	},
   794  	{
   795  		"%4a",
   796  		"J",
   797  		nil,
   798  	},
   799  	{
   800  		"%6F",
   801  		"o",
   802  		nil,
   803  	},
   804  	{
   805  		"%", // not enough characters after %
   806  		"",
   807  		EscapeError("%"),
   808  	},
   809  	{
   810  		"%a", // not enough characters after %
   811  		"",
   812  		EscapeError("%a"),
   813  	},
   814  	{
   815  		"%1", // not enough characters after %
   816  		"",
   817  		EscapeError("%1"),
   818  	},
   819  	{
   820  		"123%45%6", // not enough characters after %
   821  		"",
   822  		EscapeError("%6"),
   823  	},
   824  	{
   825  		"%zzzzz", // invalid hex digits
   826  		"",
   827  		EscapeError("%zz"),
   828  	},
   829  	{
   830  		"a+b",
   831  		"a b",
   832  		nil,
   833  	},
   834  	{
   835  		"a%20b",
   836  		"a b",
   837  		nil,
   838  	},
   839  }
   840  
   841  func TestUnescape(t *testing.T) {
   842  	for _, tt := range unescapeTests {
   843  		actual, err := QueryUnescape(tt.in)
   844  		if actual != tt.out || (err != nil) != (tt.err != nil) {
   845  			t.Errorf("QueryUnescape(%q) = %q, %s; want %q, %s", tt.in, actual, err, tt.out, tt.err)
   846  		}
   847  
   848  		in := tt.in
   849  		out := tt.out
   850  		if strings.Contains(tt.in, "+") {
   851  			in = strings.Replace(tt.in, "+", "%20", -1)
   852  			actual, err := PathUnescape(in)
   853  			if actual != tt.out || (err != nil) != (tt.err != nil) {
   854  				t.Errorf("PathUnescape(%q) = %q, %s; want %q, %s", in, actual, err, tt.out, tt.err)
   855  			}
   856  			if tt.err == nil {
   857  				s, err := QueryUnescape(strings.Replace(tt.in, "+", "XXX", -1))
   858  				if err != nil {
   859  					continue
   860  				}
   861  				in = tt.in
   862  				out = strings.Replace(s, "XXX", "+", -1)
   863  			}
   864  		}
   865  
   866  		actual, err = PathUnescape(in)
   867  		if actual != out || (err != nil) != (tt.err != nil) {
   868  			t.Errorf("PathUnescape(%q) = %q, %s; want %q, %s", in, actual, err, out, tt.err)
   869  		}
   870  	}
   871  }
   872  
   873  var queryEscapeTests = []EscapeTest{
   874  	{
   875  		"",
   876  		"",
   877  		nil,
   878  	},
   879  	{
   880  		"abc",
   881  		"abc",
   882  		nil,
   883  	},
   884  	{
   885  		"one two",
   886  		"one+two",
   887  		nil,
   888  	},
   889  	{
   890  		"10%",
   891  		"10%25",
   892  		nil,
   893  	},
   894  	{
   895  		" ?&=#+%!<>#\"{}|\\^[]`☺\t:/@$'()*,;",
   896  		"+%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",
   897  		nil,
   898  	},
   899  }
   900  
   901  func TestQueryEscape(t *testing.T) {
   902  	for _, tt := range queryEscapeTests {
   903  		actual := QueryEscape(tt.in)
   904  		if tt.out != actual {
   905  			t.Errorf("QueryEscape(%q) = %q, want %q", tt.in, actual, tt.out)
   906  		}
   907  
   908  		// for bonus points, verify that escape:unescape is an identity.
   909  		roundtrip, err := QueryUnescape(actual)
   910  		if roundtrip != tt.in || err != nil {
   911  			t.Errorf("QueryUnescape(%q) = %q, %s; want %q, %s", actual, roundtrip, err, tt.in, "[no error]")
   912  		}
   913  	}
   914  }
   915  
   916  var pathEscapeTests = []EscapeTest{
   917  	{
   918  		"",
   919  		"",
   920  		nil,
   921  	},
   922  	{
   923  		"abc",
   924  		"abc",
   925  		nil,
   926  	},
   927  	{
   928  		"abc+def",
   929  		"abc+def",
   930  		nil,
   931  	},
   932  	{
   933  		"one two",
   934  		"one%20two",
   935  		nil,
   936  	},
   937  	{
   938  		"10%",
   939  		"10%25",
   940  		nil,
   941  	},
   942  	{
   943  		" ?&=#+%!<>#\"{}|\\^[]`☺\t:/@$'()*,;",
   944  		"%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",
   945  		nil,
   946  	},
   947  }
   948  
   949  func TestPathEscape(t *testing.T) {
   950  	for _, tt := range pathEscapeTests {
   951  		actual := PathEscape(tt.in)
   952  		if tt.out != actual {
   953  			t.Errorf("PathEscape(%q) = %q, want %q", tt.in, actual, tt.out)
   954  		}
   955  
   956  		// for bonus points, verify that escape:unescape is an identity.
   957  		roundtrip, err := PathUnescape(actual)
   958  		if roundtrip != tt.in || err != nil {
   959  			t.Errorf("PathUnescape(%q) = %q, %s; want %q, %s", actual, roundtrip, err, tt.in, "[no error]")
   960  		}
   961  	}
   962  }
   963  
   964  //var userinfoTests = []UserinfoTest{
   965  //	{"user", "password", "user:password"},
   966  //	{"foo:bar", "~!@#$%^&*()_+{}|[]\\-=`:;'\"<>?,./",
   967  //		"foo%3Abar:~!%40%23$%25%5E&*()_+%7B%7D%7C%5B%5D%5C-=%60%3A;'%22%3C%3E?,.%2F"},
   968  //}
   969  
   970  type EncodeQueryTest struct {
   971  	m        Values
   972  	expected string
   973  }
   974  
   975  var encodeQueryTests = []EncodeQueryTest{
   976  	{nil, ""},
   977  	{Values{"q": {"puppies"}, "oe": {"utf8"}}, "oe=utf8&q=puppies"},
   978  	{Values{"q": {"dogs", "&", "7"}}, "q=dogs&q=%26&q=7"},
   979  	{Values{
   980  		"a": {"a1", "a2", "a3"},
   981  		"b": {"b1", "b2", "b3"},
   982  		"c": {"c1", "c2", "c3"},
   983  	}, "a=a1&a=a2&a=a3&b=b1&b=b2&b=b3&c=c1&c=c2&c=c3"},
   984  }
   985  
   986  func TestEncodeQuery(t *testing.T) {
   987  	for _, tt := range encodeQueryTests {
   988  		if q := tt.m.Encode(); q != tt.expected {
   989  			t.Errorf(`EncodeQuery(%+v) = %q, want %q`, tt.m, q, tt.expected)
   990  		}
   991  	}
   992  }
   993  
   994  var resolvePathTests = []struct {
   995  	base, ref, expected string
   996  }{
   997  	{"a/b", ".", "/a/"},
   998  	{"a/b", "c", "/a/c"},
   999  	{"a/b", "..", "/"},
  1000  	{"a/", "..", "/"},
  1001  	{"a/", "../..", "/"},
  1002  	{"a/b/c", "..", "/a/"},
  1003  	{"a/b/c", "../d", "/a/d"},
  1004  	{"a/b/c", ".././d", "/a/d"},
  1005  	{"a/b", "./..", "/"},
  1006  	{"a/./b", ".", "/a/"},
  1007  	{"a/../", ".", "/"},
  1008  	{"a/.././b", "c", "/c"},
  1009  }
  1010  
  1011  func TestResolvePath(t *testing.T) {
  1012  	for _, test := range resolvePathTests {
  1013  		got := resolvePath(test.base, test.ref)
  1014  		if got != test.expected {
  1015  			t.Errorf("For %q + %q got %q; expected %q", test.base, test.ref, got, test.expected)
  1016  		}
  1017  	}
  1018  }
  1019  
  1020  var resolveReferenceTests = []struct {
  1021  	base, rel, expected string
  1022  }{
  1023  	// Absolute URL references
  1024  	{"http://foo.com?a=b", "https://bar.com/", "https://bar.com/"},
  1025  	{"http://foo.com/", "https://bar.com/?a=b", "https://bar.com/?a=b"},
  1026  	{"http://foo.com/", "https://bar.com/?", "https://bar.com/?"},
  1027  	{"http://foo.com/bar", "mailto:foo@example.com", "mailto:foo@example.com"},
  1028  
  1029  	// Path-absolute references
  1030  	{"http://foo.com/bar", "/baz", "http://foo.com/baz"},
  1031  	{"http://foo.com/bar?a=b#f", "/baz", "http://foo.com/baz"},
  1032  	{"http://foo.com/bar?a=b", "/baz?", "http://foo.com/baz?"},
  1033  	{"http://foo.com/bar?a=b", "/baz?c=d", "http://foo.com/baz?c=d"},
  1034  
  1035  	// Multiple slashes
  1036  	{"http://foo.com/bar", "http://foo.com//baz", "http://foo.com//baz"},
  1037  	{"http://foo.com/bar", "http://foo.com///baz/quux", "http://foo.com///baz/quux"},
  1038  
  1039  	// Scheme-relative
  1040  	{"https://foo.com/bar?a=b", "//bar.com/quux", "https://bar.com/quux"},
  1041  
  1042  	// Path-relative references:
  1043  
  1044  	// ... current directory
  1045  	{"http://foo.com", ".", "http://foo.com/"},
  1046  	{"http://foo.com/bar", ".", "http://foo.com/"},
  1047  	{"http://foo.com/bar/", ".", "http://foo.com/bar/"},
  1048  
  1049  	// ... going down
  1050  	{"http://foo.com", "bar", "http://foo.com/bar"},
  1051  	{"http://foo.com/", "bar", "http://foo.com/bar"},
  1052  	{"http://foo.com/bar/baz", "quux", "http://foo.com/bar/quux"},
  1053  
  1054  	// ... going up
  1055  	{"http://foo.com/bar/baz", "../quux", "http://foo.com/quux"},
  1056  	{"http://foo.com/bar/baz", "../../../../../quux", "http://foo.com/quux"},
  1057  	{"http://foo.com/bar", "..", "http://foo.com/"},
  1058  	{"http://foo.com/bar/baz", "./..", "http://foo.com/"},
  1059  	// ".." in the middle (issue 3560)
  1060  	{"http://foo.com/bar/baz", "quux/dotdot/../tail", "http://foo.com/bar/quux/tail"},
  1061  	{"http://foo.com/bar/baz", "quux/./dotdot/../tail", "http://foo.com/bar/quux/tail"},
  1062  	{"http://foo.com/bar/baz", "quux/./dotdot/.././tail", "http://foo.com/bar/quux/tail"},
  1063  	{"http://foo.com/bar/baz", "quux/./dotdot/./../tail", "http://foo.com/bar/quux/tail"},
  1064  	{"http://foo.com/bar/baz", "quux/./dotdot/dotdot/././../../tail", "http://foo.com/bar/quux/tail"},
  1065  	{"http://foo.com/bar/baz", "quux/./dotdot/dotdot/./.././../tail", "http://foo.com/bar/quux/tail"},
  1066  	{"http://foo.com/bar/baz", "quux/./dotdot/dotdot/dotdot/./../../.././././tail", "http://foo.com/bar/quux/tail"},
  1067  	{"http://foo.com/bar/baz", "quux/./dotdot/../dotdot/../dot/./tail/..", "http://foo.com/bar/quux/dot/"},
  1068  
  1069  	// Remove any dot-segments prior to forming the target URI.
  1070  	// http://tools.ietf.org/html/rfc3986#section-5.2.4
  1071  	{"http://foo.com/dot/./dotdot/../foo/bar", "../baz", "http://foo.com/dot/baz"},
  1072  
  1073  	// Triple dot isn't special
  1074  	{"http://foo.com/bar", "...", "http://foo.com/..."},
  1075  
  1076  	// Fragment
  1077  	{"http://foo.com/bar", ".#frag", "http://foo.com/#frag"},
  1078  	{"http://example.org/", "#!$&%27()*+,;=", "http://example.org/#!$&%27()*+,;="},
  1079  
  1080  	// Paths with escaping (issue 16947).
  1081  	{"http://foo.com/foo%2fbar/", "../baz", "http://foo.com/baz"},
  1082  	{"http://foo.com/1/2%2f/3%2f4/5", "../../a/b/c", "http://foo.com/1/a/b/c"},
  1083  	{"http://foo.com/1/2/3", "./a%2f../../b/..%2fc", "http://foo.com/1/2/b/..%2fc"},
  1084  	{"http://foo.com/1/2%2f/3%2f4/5", "./a%2f../b/../c", "http://foo.com/1/2%2f/3%2f4/a%2f../c"},
  1085  	{"http://foo.com/foo%20bar/", "../baz", "http://foo.com/baz"},
  1086  	{"http://foo.com/foo", "../bar%2fbaz", "http://foo.com/bar%2fbaz"},
  1087  	{"http://foo.com/foo%2dbar/", "./baz-quux", "http://foo.com/foo%2dbar/baz-quux"},
  1088  
  1089  	// RFC 3986: Normal Examples
  1090  	// http://tools.ietf.org/html/rfc3986#section-5.4.1
  1091  	{"http://a/b/c/d;p?q", "g:h", "g:h"},
  1092  	{"http://a/b/c/d;p?q", "g", "http://a/b/c/g"},
  1093  	{"http://a/b/c/d;p?q", "./g", "http://a/b/c/g"},
  1094  	{"http://a/b/c/d;p?q", "g/", "http://a/b/c/g/"},
  1095  	{"http://a/b/c/d;p?q", "/g", "http://a/g"},
  1096  	{"http://a/b/c/d;p?q", "//g", "http://g"},
  1097  	{"http://a/b/c/d;p?q", "?y", "http://a/b/c/d;p?y"},
  1098  	{"http://a/b/c/d;p?q", "g?y", "http://a/b/c/g?y"},
  1099  	{"http://a/b/c/d;p?q", "#s", "http://a/b/c/d;p?q#s"},
  1100  	{"http://a/b/c/d;p?q", "g#s", "http://a/b/c/g#s"},
  1101  	{"http://a/b/c/d;p?q", "g?y#s", "http://a/b/c/g?y#s"},
  1102  	{"http://a/b/c/d;p?q", ";x", "http://a/b/c/;x"},
  1103  	{"http://a/b/c/d;p?q", "g;x", "http://a/b/c/g;x"},
  1104  	{"http://a/b/c/d;p?q", "g;x?y#s", "http://a/b/c/g;x?y#s"},
  1105  	{"http://a/b/c/d;p?q", "", "http://a/b/c/d;p?q"},
  1106  	{"http://a/b/c/d;p?q", ".", "http://a/b/c/"},
  1107  	{"http://a/b/c/d;p?q", "./", "http://a/b/c/"},
  1108  	{"http://a/b/c/d;p?q", "..", "http://a/b/"},
  1109  	{"http://a/b/c/d;p?q", "../", "http://a/b/"},
  1110  	{"http://a/b/c/d;p?q", "../g", "http://a/b/g"},
  1111  	{"http://a/b/c/d;p?q", "../..", "http://a/"},
  1112  	{"http://a/b/c/d;p?q", "../../", "http://a/"},
  1113  	{"http://a/b/c/d;p?q", "../../g", "http://a/g"},
  1114  
  1115  	// RFC 3986: Abnormal Examples
  1116  	// http://tools.ietf.org/html/rfc3986#section-5.4.2
  1117  	{"http://a/b/c/d;p?q", "../../../g", "http://a/g"},
  1118  	{"http://a/b/c/d;p?q", "../../../../g", "http://a/g"},
  1119  	{"http://a/b/c/d;p?q", "/./g", "http://a/g"},
  1120  	{"http://a/b/c/d;p?q", "/../g", "http://a/g"},
  1121  	{"http://a/b/c/d;p?q", "g.", "http://a/b/c/g."},
  1122  	{"http://a/b/c/d;p?q", ".g", "http://a/b/c/.g"},
  1123  	{"http://a/b/c/d;p?q", "g..", "http://a/b/c/g.."},
  1124  	{"http://a/b/c/d;p?q", "..g", "http://a/b/c/..g"},
  1125  	{"http://a/b/c/d;p?q", "./../g", "http://a/b/g"},
  1126  	{"http://a/b/c/d;p?q", "./g/.", "http://a/b/c/g/"},
  1127  	{"http://a/b/c/d;p?q", "g/./h", "http://a/b/c/g/h"},
  1128  	{"http://a/b/c/d;p?q", "g/../h", "http://a/b/c/h"},
  1129  	{"http://a/b/c/d;p?q", "g;x=1/./y", "http://a/b/c/g;x=1/y"},
  1130  	{"http://a/b/c/d;p?q", "g;x=1/../y", "http://a/b/c/y"},
  1131  	{"http://a/b/c/d;p?q", "g?y/./x", "http://a/b/c/g?y/./x"},
  1132  	{"http://a/b/c/d;p?q", "g?y/../x", "http://a/b/c/g?y/../x"},
  1133  	{"http://a/b/c/d;p?q", "g#s/./x", "http://a/b/c/g#s/./x"},
  1134  	{"http://a/b/c/d;p?q", "g#s/../x", "http://a/b/c/g#s/../x"},
  1135  
  1136  	// Extras.
  1137  	{"https://a/b/c/d;p?q", "//g?q", "https://g?q"},
  1138  	{"https://a/b/c/d;p?q", "//g#s", "https://g#s"},
  1139  	{"https://a/b/c/d;p?q", "//g/d/e/f?y#s", "https://g/d/e/f?y#s"},
  1140  	{"https://a/b/c/d;p#s", "?y", "https://a/b/c/d;p?y"},
  1141  	{"https://a/b/c/d;p?q#s", "?y", "https://a/b/c/d;p?y"},
  1142  }
  1143  
  1144  func TestResolveReference(t *testing.T) {
  1145  	mustParse := func(url string) *URL {
  1146  		u, err := Parse(url)
  1147  		if err != nil {
  1148  			t.Fatalf("Parse(%q) got err %v", url, err)
  1149  		}
  1150  		return u
  1151  	}
  1152  	opaque := &URL{Scheme: "scheme", Opaque: "opaque"}
  1153  	for _, test := range resolveReferenceTests {
  1154  		base := mustParse(test.base)
  1155  		rel := mustParse(test.rel)
  1156  		url := base.ResolveReference(rel)
  1157  		if got := url.String(); got != test.expected {
  1158  			t.Errorf("URL(%q).ResolveReference(%q)\ngot  %q\nwant %q", test.base, test.rel, got, test.expected)
  1159  		}
  1160  		// Ensure that new instances are returned.
  1161  		if base == url {
  1162  			t.Errorf("Expected URL.ResolveReference to return new URL instance.")
  1163  		}
  1164  		// Test the convenience wrapper too.
  1165  		url, err := base.Parse(test.rel)
  1166  		if err != nil {
  1167  			t.Errorf("URL(%q).Parse(%q) failed: %v", test.base, test.rel, err)
  1168  		} else if got := url.String(); got != test.expected {
  1169  			t.Errorf("URL(%q).Parse(%q)\ngot  %q\nwant %q", test.base, test.rel, got, test.expected)
  1170  		} else if base == url {
  1171  			// Ensure that new instances are returned for the wrapper too.
  1172  			t.Errorf("Expected URL.Parse to return new URL instance.")
  1173  		}
  1174  		// Ensure Opaque resets the URL.
  1175  		url = base.ResolveReference(opaque)
  1176  		if *url != *opaque {
  1177  			t.Errorf("ResolveReference failed to resolve opaque URL:\ngot  %#v\nwant %#v", url, opaque)
  1178  		}
  1179  		// Test the convenience wrapper with an opaque URL too.
  1180  		url, err = base.Parse("scheme:opaque")
  1181  		if err != nil {
  1182  			t.Errorf(`URL(%q).Parse("scheme:opaque") failed: %v`, test.base, err)
  1183  		} else if *url != *opaque {
  1184  			t.Errorf("Parse failed to resolve opaque URL:\ngot  %#v\nwant %#v", opaque, url)
  1185  		} else if base == url {
  1186  			// Ensure that new instances are returned, again.
  1187  			t.Errorf("Expected URL.Parse to return new URL instance.")
  1188  		}
  1189  	}
  1190  }
  1191  
  1192  func TestQueryValues(t *testing.T) {
  1193  	u, _ := Parse("http://x.com?foo=bar&bar=1&bar=2")
  1194  	v := u.Query()
  1195  	if len(v) != 2 {
  1196  		t.Errorf("got %d keys in Query values, want 2", len(v))
  1197  	}
  1198  	if g, e := v.Get("foo"), "bar"; g != e {
  1199  		t.Errorf("Get(foo) = %q, want %q", g, e)
  1200  	}
  1201  	// Case sensitive:
  1202  	if g, e := v.Get("Foo"), ""; g != e {
  1203  		t.Errorf("Get(Foo) = %q, want %q", g, e)
  1204  	}
  1205  	if g, e := v.Get("bar"), "1"; g != e {
  1206  		t.Errorf("Get(bar) = %q, want %q", g, e)
  1207  	}
  1208  	if g, e := v.Get("baz"), ""; g != e {
  1209  		t.Errorf("Get(baz) = %q, want %q", g, e)
  1210  	}
  1211  	v.Del("bar")
  1212  	if g, e := v.Get("bar"), ""; g != e {
  1213  		t.Errorf("second Get(bar) = %q, want %q", g, e)
  1214  	}
  1215  }
  1216  
  1217  type parseTest struct {
  1218  	query string
  1219  	out   Values
  1220  }
  1221  
  1222  var parseTests = []parseTest{
  1223  	{
  1224  		query: "a=1&b=2",
  1225  		out:   Values{"a": []string{"1"}, "b": []string{"2"}},
  1226  	},
  1227  	{
  1228  		query: "a=1&a=2&a=banana",
  1229  		out:   Values{"a": []string{"1", "2", "banana"}},
  1230  	},
  1231  	{
  1232  		query: "ascii=%3Ckey%3A+0x90%3E",
  1233  		out:   Values{"ascii": []string{"<key: 0x90>"}},
  1234  	},
  1235  	{
  1236  		query: "a=1;b=2",
  1237  		out:   Values{"a": []string{"1"}, "b": []string{"2"}},
  1238  	},
  1239  	{
  1240  		query: "a=1&a=2;a=banana",
  1241  		out:   Values{"a": []string{"1", "2", "banana"}},
  1242  	},
  1243  }
  1244  
  1245  func TestParseQuery(t *testing.T) {
  1246  	for i, test := range parseTests {
  1247  		form, err := ParseQuery(test.query)
  1248  		if err != nil {
  1249  			t.Errorf("test %d: Unexpected error: %v", i, err)
  1250  			continue
  1251  		}
  1252  		if len(form) != len(test.out) {
  1253  			t.Errorf("test %d: len(form) = %d, want %d", i, len(form), len(test.out))
  1254  		}
  1255  		for k, evs := range test.out {
  1256  			vs, ok := form[k]
  1257  			if !ok {
  1258  				t.Errorf("test %d: Missing key %q", i, k)
  1259  				continue
  1260  			}
  1261  			if len(vs) != len(evs) {
  1262  				t.Errorf("test %d: len(form[%q]) = %d, want %d", i, k, len(vs), len(evs))
  1263  				continue
  1264  			}
  1265  			for j, ev := range evs {
  1266  				if v := vs[j]; v != ev {
  1267  					t.Errorf("test %d: form[%q][%d] = %q, want %q", i, k, j, v, ev)
  1268  				}
  1269  			}
  1270  		}
  1271  	}
  1272  }
  1273  
  1274  type RequestURITest struct {
  1275  	url *URL
  1276  	out string
  1277  }
  1278  
  1279  var requritests = []RequestURITest{
  1280  	{
  1281  		&URL{
  1282  			Scheme: "http",
  1283  			Host:   "example.com",
  1284  			Path:   "",
  1285  		},
  1286  		"/",
  1287  	},
  1288  	{
  1289  		&URL{
  1290  			Scheme: "http",
  1291  			Host:   "example.com",
  1292  			Path:   "/a b",
  1293  		},
  1294  		"/a%20b",
  1295  	},
  1296  	// golang.org/issue/4860 variant 1
  1297  	{
  1298  		&URL{
  1299  			Scheme: "http",
  1300  			Host:   "example.com",
  1301  			Opaque: "/%2F/%2F/",
  1302  		},
  1303  		"/%2F/%2F/",
  1304  	},
  1305  	// golang.org/issue/4860 variant 2
  1306  	{
  1307  		&URL{
  1308  			Scheme: "http",
  1309  			Host:   "example.com",
  1310  			Opaque: "//other.example.com/%2F/%2F/",
  1311  		},
  1312  		"http://other.example.com/%2F/%2F/",
  1313  	},
  1314  	// better fix for issue 4860
  1315  	{
  1316  		&URL{
  1317  			Scheme:  "http",
  1318  			Host:    "example.com",
  1319  			Path:    "/////",
  1320  			RawPath: "/%2F/%2F/",
  1321  		},
  1322  		"/%2F/%2F/",
  1323  	},
  1324  	{
  1325  		&URL{
  1326  			Scheme:  "http",
  1327  			Host:    "example.com",
  1328  			Path:    "/////",
  1329  			RawPath: "/WRONG/", // ignored because doesn't match Path
  1330  		},
  1331  		"/////",
  1332  	},
  1333  	{
  1334  		&URL{
  1335  			Scheme:   "http",
  1336  			Host:     "example.com",
  1337  			Path:     "/a b",
  1338  			RawQuery: "q=go+language",
  1339  		},
  1340  		"/a%20b?q=go+language",
  1341  	},
  1342  	{
  1343  		&URL{
  1344  			Scheme:   "http",
  1345  			Host:     "example.com",
  1346  			Path:     "/a b",
  1347  			RawPath:  "/a b", // ignored because invalid
  1348  			RawQuery: "q=go+language",
  1349  		},
  1350  		"/a%20b?q=go+language",
  1351  	},
  1352  	{
  1353  		&URL{
  1354  			Scheme:   "http",
  1355  			Host:     "example.com",
  1356  			Path:     "/a?b",
  1357  			RawPath:  "/a?b", // ignored because invalid
  1358  			RawQuery: "q=go+language",
  1359  		},
  1360  		"/a%3Fb?q=go+language",
  1361  	},
  1362  	{
  1363  		&URL{
  1364  			Scheme: "myschema",
  1365  			Opaque: "opaque",
  1366  		},
  1367  		"opaque",
  1368  	},
  1369  	{
  1370  		&URL{
  1371  			Scheme:   "myschema",
  1372  			Opaque:   "opaque",
  1373  			RawQuery: "q=go+language",
  1374  		},
  1375  		"opaque?q=go+language",
  1376  	},
  1377  	{
  1378  		&URL{
  1379  			Scheme: "http",
  1380  			Host:   "example.com",
  1381  			Path:   "//foo",
  1382  		},
  1383  		"//foo",
  1384  	},
  1385  	{
  1386  		&URL{
  1387  			Scheme:     "http",
  1388  			Host:       "example.com",
  1389  			Path:       "/foo",
  1390  			ForceQuery: true,
  1391  		},
  1392  		"/foo?",
  1393  	},
  1394  }
  1395  
  1396  func TestRequestURI(t *testing.T) {
  1397  	for _, tt := range requritests {
  1398  		s := tt.url.RequestURI()
  1399  		if s != tt.out {
  1400  			t.Errorf("%#v.RequestURI() == %q (expected %q)", tt.url, s, tt.out)
  1401  		}
  1402  	}
  1403  }
  1404  
  1405  func TestParseFailure(t *testing.T) {
  1406  	// Test that the first parse error is returned.
  1407  	const url = "%gh&%ij"
  1408  	_, err := ParseQuery(url)
  1409  	errStr := fmt.Sprint(err)
  1410  	if !strings.Contains(errStr, "%gh") {
  1411  		t.Errorf(`ParseQuery(%q) returned error %q, want something containing %q"`, url, errStr, "%gh")
  1412  	}
  1413  }
  1414  
  1415  func TestParseErrors(t *testing.T) {
  1416  	tests := []struct {
  1417  		in      string
  1418  		wantErr bool
  1419  	}{
  1420  		{"http://[::1]", false},
  1421  		{"http://[::1]:80", false},
  1422  		{"http://[::1]:namedport", true}, // rfc3986 3.2.3
  1423  		{"http://[::1]/", false},
  1424  		{"http://[::1]a", true},
  1425  		{"http://[::1]%23", true},
  1426  		{"http://[::1%25en0]", false},     // valid zone id
  1427  		{"http://[::1]:", false},          // colon, but no port OK
  1428  		{"http://[::1]:%38%30", true},     // not allowed: % encoding only for non-ASCII
  1429  		{"http://[::1%25%41]", false},     // RFC 6874 allows over-escaping in zone
  1430  		{"http://[%10::1]", true},         // no %xx escapes in IP address
  1431  		{"http://[::1]/%48", false},       // %xx in path is fine
  1432  		{"http://%41:8080/", true},        // not allowed: % encoding only for non-ASCII
  1433  		{"mysql://x@y(z:123)/foo", false}, // golang.org/issue/12023
  1434  		{"mysql://x@y(1.2.3.4:123)/foo", false},
  1435  
  1436  		{"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
  1437  		{"http://a b.com/", true},    // no space in host name please
  1438  		{"cache_object://foo", true}, // scheme cannot have _, relative path cannot have : in first segment
  1439  		{"cache_object:foo", true},
  1440  		{"cache_object:foo/bar", true},
  1441  		{"cache_object/:foo/bar", false},
  1442  	}
  1443  	for _, tt := range tests {
  1444  		u, err := Parse(tt.in)
  1445  		if tt.wantErr {
  1446  			if err == nil {
  1447  				t.Errorf("Parse(%q) = %#v; want an error", tt.in, u)
  1448  			}
  1449  			continue
  1450  		}
  1451  		if err != nil {
  1452  			t.Logf("Parse(%q) = %v; want no error", tt.in, err)
  1453  		}
  1454  	}
  1455  }
  1456  
  1457  // Issue 11202
  1458  func TestStarRequest(t *testing.T) {
  1459  	u, err := Parse("*")
  1460  	if err != nil {
  1461  		t.Fatal(err)
  1462  	}
  1463  	if got, want := u.RequestURI(), "*"; got != want {
  1464  		t.Errorf("RequestURI = %q; want %q", got, want)
  1465  	}
  1466  }
  1467  
  1468  type shouldEscapeTest struct {
  1469  	in     byte
  1470  	mode   encoding
  1471  	escape bool
  1472  }
  1473  
  1474  var shouldEscapeTests = []shouldEscapeTest{
  1475  	// Unreserved characters (§2.3)
  1476  	{'a', encodePath, false},
  1477  	{'a', encodeUserPassword, false},
  1478  	{'a', encodeQueryComponent, false},
  1479  	{'a', encodeFragment, false},
  1480  	{'a', encodeHost, false},
  1481  	{'z', encodePath, false},
  1482  	{'A', encodePath, false},
  1483  	{'Z', encodePath, false},
  1484  	{'0', encodePath, false},
  1485  	{'9', encodePath, false},
  1486  	{'-', encodePath, false},
  1487  	{'-', encodeUserPassword, false},
  1488  	{'-', encodeQueryComponent, false},
  1489  	{'-', encodeFragment, false},
  1490  	{'.', encodePath, false},
  1491  	{'_', encodePath, false},
  1492  	{'~', encodePath, false},
  1493  
  1494  	// User information (§3.2.1)
  1495  	{':', encodeUserPassword, true},
  1496  	{'/', encodeUserPassword, true},
  1497  	{'?', encodeUserPassword, true},
  1498  	{'@', encodeUserPassword, true},
  1499  	{'$', encodeUserPassword, false},
  1500  	{'&', encodeUserPassword, false},
  1501  	{'+', encodeUserPassword, false},
  1502  	{',', encodeUserPassword, false},
  1503  	{';', encodeUserPassword, false},
  1504  	{'=', encodeUserPassword, false},
  1505  
  1506  	// Host (IP address, IPv6 address, registered name, port suffix; §3.2.2)
  1507  	{'!', encodeHost, false},
  1508  	{'$', encodeHost, false},
  1509  	{'&', encodeHost, false},
  1510  	{'\'', encodeHost, false},
  1511  	{'(', encodeHost, false},
  1512  	{')', encodeHost, false},
  1513  	{'*', encodeHost, false},
  1514  	{'+', encodeHost, false},
  1515  	{',', encodeHost, false},
  1516  	{';', encodeHost, false},
  1517  	{'=', encodeHost, false},
  1518  	{':', encodeHost, false},
  1519  	{'[', encodeHost, false},
  1520  	{']', encodeHost, false},
  1521  	{'0', encodeHost, false},
  1522  	{'9', encodeHost, false},
  1523  	{'A', encodeHost, false},
  1524  	{'z', encodeHost, false},
  1525  	{'_', encodeHost, false},
  1526  	{'-', encodeHost, false},
  1527  	{'.', encodeHost, false},
  1528  }
  1529  
  1530  func TestShouldEscape(t *testing.T) {
  1531  	for _, tt := range shouldEscapeTests {
  1532  		if shouldEscape(tt.in, tt.mode) != tt.escape {
  1533  			t.Errorf("shouldEscape(%q, %v) returned %v; expected %v", tt.in, tt.mode, !tt.escape, tt.escape)
  1534  		}
  1535  	}
  1536  }
  1537  
  1538  type timeoutError struct {
  1539  	timeout bool
  1540  }
  1541  
  1542  func (e *timeoutError) Error() string { return "timeout error" }
  1543  func (e *timeoutError) Timeout() bool { return e.timeout }
  1544  
  1545  type temporaryError struct {
  1546  	temporary bool
  1547  }
  1548  
  1549  func (e *temporaryError) Error() string   { return "temporary error" }
  1550  func (e *temporaryError) Temporary() bool { return e.temporary }
  1551  
  1552  type timeoutTemporaryError struct {
  1553  	timeoutError
  1554  	temporaryError
  1555  }
  1556  
  1557  func (e *timeoutTemporaryError) Error() string { return "timeout/temporary error" }
  1558  
  1559  var netErrorTests = []struct {
  1560  	err       error
  1561  	timeout   bool
  1562  	temporary bool
  1563  }{{
  1564  	err:       &Error{"Get", "http://google.com/", &timeoutError{timeout: true}},
  1565  	timeout:   true,
  1566  	temporary: false,
  1567  }, {
  1568  	err:       &Error{"Get", "http://google.com/", &timeoutError{timeout: false}},
  1569  	timeout:   false,
  1570  	temporary: false,
  1571  }, {
  1572  	err:       &Error{"Get", "http://google.com/", &temporaryError{temporary: true}},
  1573  	timeout:   false,
  1574  	temporary: true,
  1575  }, {
  1576  	err:       &Error{"Get", "http://google.com/", &temporaryError{temporary: false}},
  1577  	timeout:   false,
  1578  	temporary: false,
  1579  }, {
  1580  	err:       &Error{"Get", "http://google.com/", &timeoutTemporaryError{timeoutError{timeout: true}, temporaryError{temporary: true}}},
  1581  	timeout:   true,
  1582  	temporary: true,
  1583  }, {
  1584  	err:       &Error{"Get", "http://google.com/", &timeoutTemporaryError{timeoutError{timeout: false}, temporaryError{temporary: true}}},
  1585  	timeout:   false,
  1586  	temporary: true,
  1587  }, {
  1588  	err:       &Error{"Get", "http://google.com/", &timeoutTemporaryError{timeoutError{timeout: true}, temporaryError{temporary: false}}},
  1589  	timeout:   true,
  1590  	temporary: false,
  1591  }, {
  1592  	err:       &Error{"Get", "http://google.com/", &timeoutTemporaryError{timeoutError{timeout: false}, temporaryError{temporary: false}}},
  1593  	timeout:   false,
  1594  	temporary: false,
  1595  }, {
  1596  	err:       &Error{"Get", "http://google.com/", io.EOF},
  1597  	timeout:   false,
  1598  	temporary: false,
  1599  }}
  1600  
  1601  // Test that url.Error implements net.Error and that it forwards
  1602  func TestURLErrorImplementsNetError(t *testing.T) {
  1603  	for i, tt := range netErrorTests {
  1604  		err, ok := tt.err.(net.Error)
  1605  		if !ok {
  1606  			t.Errorf("%d: %T does not implement net.Error", i+1, tt.err)
  1607  			continue
  1608  		}
  1609  		if err.Timeout() != tt.timeout {
  1610  			t.Errorf("%d: err.Timeout(): got %v, want %v", i+1, err.Timeout(), tt.timeout)
  1611  			continue
  1612  		}
  1613  		if err.Temporary() != tt.temporary {
  1614  			t.Errorf("%d: err.Temporary(): got %v, want %v", i+1, err.Temporary(), tt.temporary)
  1615  		}
  1616  	}
  1617  }
  1618  
  1619  func TestURLHostname(t *testing.T) {
  1620  	tests := []struct {
  1621  		host string // URL.Host field
  1622  		want string
  1623  	}{
  1624  		{"foo.com:80", "foo.com"},
  1625  		{"foo.com", "foo.com"},
  1626  		{"FOO.COM", "FOO.COM"}, // no canonicalization (yet?)
  1627  		{"1.2.3.4", "1.2.3.4"},
  1628  		{"1.2.3.4:80", "1.2.3.4"},
  1629  		{"[1:2:3:4]", "1:2:3:4"},
  1630  		{"[1:2:3:4]:80", "1:2:3:4"},
  1631  		{"[::1]:80", "::1"},
  1632  	}
  1633  	for _, tt := range tests {
  1634  		u := &URL{Host: tt.host}
  1635  		got := u.Hostname()
  1636  		if got != tt.want {
  1637  			t.Errorf("Hostname for Host %q = %q; want %q", tt.host, got, tt.want)
  1638  		}
  1639  	}
  1640  }
  1641  
  1642  func TestURLPort(t *testing.T) {
  1643  	tests := []struct {
  1644  		host string // URL.Host field
  1645  		want string
  1646  	}{
  1647  		{"foo.com", ""},
  1648  		{"foo.com:80", "80"},
  1649  		{"1.2.3.4", ""},
  1650  		{"1.2.3.4:80", "80"},
  1651  		{"[1:2:3:4]", ""},
  1652  		{"[1:2:3:4]:80", "80"},
  1653  	}
  1654  	for _, tt := range tests {
  1655  		u := &URL{Host: tt.host}
  1656  		got := u.Port()
  1657  		if got != tt.want {
  1658  			t.Errorf("Port for Host %q = %q; want %q", tt.host, got, tt.want)
  1659  		}
  1660  	}
  1661  }
  1662  
  1663  var _ encodingPkg.BinaryMarshaler = (*URL)(nil)
  1664  var _ encodingPkg.BinaryUnmarshaler = (*URL)(nil)
  1665  
  1666  func TestJSON(t *testing.T) {
  1667  	u, err := Parse("https://www.google.com/x?y=z")
  1668  	if err != nil {
  1669  		t.Fatal(err)
  1670  	}
  1671  	js, err := json.Marshal(u)
  1672  	if err != nil {
  1673  		t.Fatal(err)
  1674  	}
  1675  
  1676  	// If only we could implement TextMarshaler/TextUnmarshaler,
  1677  	// this would work:
  1678  	//
  1679  	// if string(js) != strconv.Quote(u.String()) {
  1680  	// 	t.Errorf("json encoding: %s\nwant: %s\n", js, strconv.Quote(u.String()))
  1681  	// }
  1682  
  1683  	u1 := new(URL)
  1684  	err = json.Unmarshal(js, u1)
  1685  	if err != nil {
  1686  		t.Fatal(err)
  1687  	}
  1688  	if u1.String() != u.String() {
  1689  		t.Errorf("json decoded to: %s\nwant: %s\n", u1, u)
  1690  	}
  1691  }
  1692  
  1693  func TestGob(t *testing.T) {
  1694  	u, err := Parse("https://www.google.com/x?y=z")
  1695  	if err != nil {
  1696  		t.Fatal(err)
  1697  	}
  1698  	var w bytes.Buffer
  1699  	err = gob.NewEncoder(&w).Encode(u)
  1700  	if err != nil {
  1701  		t.Fatal(err)
  1702  	}
  1703  
  1704  	u1 := new(URL)
  1705  	err = gob.NewDecoder(&w).Decode(u1)
  1706  	if err != nil {
  1707  		t.Fatal(err)
  1708  	}
  1709  	if u1.String() != u.String() {
  1710  		t.Errorf("json decoded to: %s\nwant: %s\n", u1, u)
  1711  	}
  1712  }
  1713  
  1714  func TestNilUser(t *testing.T) {
  1715  	defer func() {
  1716  		if v := recover(); v != nil {
  1717  			t.Fatalf("unexpected panic: %v", v)
  1718  		}
  1719  	}()
  1720  
  1721  	u, err := Parse("http://foo.com/")
  1722  
  1723  	if err != nil {
  1724  		t.Fatalf("parse err: %v", err)
  1725  	}
  1726  
  1727  	if v := u.User.Username(); v != "" {
  1728  		t.Fatalf("expected empty username, got %s", v)
  1729  	}
  1730  
  1731  	if v, ok := u.User.Password(); v != "" || ok {
  1732  		t.Fatalf("expected empty password, got %s (%v)", v, ok)
  1733  	}
  1734  
  1735  	if v := u.User.String(); v != "" {
  1736  		t.Fatalf("expected empty string, got %s", v)
  1737  	}
  1738  }
  1739  
  1740  func TestInvalidUserPassword(t *testing.T) {
  1741  	_, err := Parse("http://us\ner:pass\nword@foo.com/")
  1742  	if got, wantsub := fmt.Sprint(err), "net/url: invalid userinfo"; !strings.Contains(got, wantsub) {
  1743  		t.Errorf("error = %q; want substring %q", got, wantsub)
  1744  	}
  1745  }
  1746  

View as plain text