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.
17 roundtrip string // expected result of reserializing the URL; empty means same as "in".
20 var urltests = []URLTest{
23 "http://www.google.com",
26 Host: "www.google.com",
32 "http://www.google.com/",
35 Host: "www.google.com",
40 // path with hex escaping
42 "http://www.google.com/file%20one%26two",
45 Host: "www.google.com",
46 Path: "/file one&two",
48 "http://www.google.com/file%20one&two",
52 "ftp://webmaster@www.google.com/",
55 User: User("webmaster"),
56 Host: "www.google.com",
61 // escape sequence in username
63 "ftp://john%20doe@www.google.com/",
66 User: User("john doe"),
67 Host: "www.google.com",
70 "ftp://john%20doe@www.google.com/",
74 "http://www.google.com/?q=go+language",
77 Host: "www.google.com",
79 RawQuery: "q=go+language",
83 // query with hex escaping: NOT parsed
85 "http://www.google.com/?q=go%20language",
88 Host: "www.google.com",
90 RawQuery: "q=go%20language",
96 "http://www.google.com/a%20b?q=c+d",
99 Host: "www.google.com",
105 // path without leading /, so no parsing
107 "http:www.google.com/?q=go+language",
110 Opaque: "www.google.com/",
111 RawQuery: "q=go+language",
113 "http:www.google.com/?q=go+language",
115 // path without leading /, so no parsing
117 "http:%2f%2fwww.google.com/?q=go+language",
120 Opaque: "%2f%2fwww.google.com/",
121 RawQuery: "q=go+language",
123 "http:%2f%2fwww.google.com/?q=go+language",
125 // non-authority with path
127 "mailto:/webmaster@golang.org",
130 Path: "/webmaster@golang.org",
132 "mailto:///webmaster@golang.org", // unfortunate compromise
136 "mailto:webmaster@golang.org",
139 Opaque: "webmaster@golang.org",
143 // unescaped :// in query should not create a scheme
145 "/foo?query=http://bad",
148 RawQuery: "query=http://bad",
152 // leading // without scheme should create an authority
160 // leading // without scheme, with userinfo, path, and query
162 "//user@foo/path?a=b",
171 // Three leading slashes isn't an authority, but doesn't return an error.
172 // (We can't return an error, as this code is also used via
173 // ServeHTTP -> ReadRequest -> Parse, which is arguably a
174 // different URL parsing context, but currently shares the
179 Path: "///threeslashes",
184 "http://user:password@google.com",
187 User: UserPassword("user", "password"),
190 "http://user:password@google.com",
192 // unescaped @ in username should not confuse host
194 "http://j@ne:password@google.com",
197 User: UserPassword("j@ne", "password"),
200 "http://j%40ne:password@google.com",
202 // unescaped @ in password should not confuse host
204 "http://jane:p@ssword@google.com",
207 User: UserPassword("jane", "p@ssword"),
210 "http://jane:p%40ssword@google.com",
213 "http://j@ne:password@google.com/p@th?q=@go",
216 User: UserPassword("j@ne", "password"),
221 "http://j%40ne:password@google.com/p@th?q=@go",
224 "http://www.google.com/?q=go+language#foo",
227 Host: "www.google.com",
229 RawQuery: "q=go+language",
235 "http://www.google.com/?q=go+language#foo%26bar",
238 Host: "www.google.com",
240 RawQuery: "q=go+language",
243 "http://www.google.com/?q=go+language#foo&bar",
246 "file:///home/adg/rabbits",
250 Path: "/home/adg/rabbits",
252 "file:///home/adg/rabbits",
256 // more useful string for debugging than fmt's struct printer
257 func ufmt(u *URL) string {
258 var user, pass interface{}
260 user = u.User.Username()
261 if p, ok := u.User.Password(); ok {
265 return fmt.Sprintf("opaque=%q, scheme=%q, user=%#v, pass=%#v, host=%q, path=%q, rawq=%q, frag=%q",
266 u.Opaque, u.Scheme, user, pass, u.Host, u.Path, u.RawQuery, u.Fragment)
269 func DoTest(t *testing.T, parse func(string) (*URL, error), name string, tests []URLTest) {
270 for _, tt := range tests {
271 u, err := parse(tt.in)
273 t.Errorf("%s(%q) returned error %s", name, tt.in, err)
276 if !reflect.DeepEqual(u, tt.out) {
277 t.Errorf("%s(%q):\n\thave %v\n\twant %v\n",
278 name, tt.in, ufmt(u), ufmt(tt.out))
283 func BenchmarkString(b *testing.B) {
286 for _, tt := range urltests {
287 u, err := Parse(tt.in)
289 b.Errorf("Parse(%q) returned error %s", tt.in, err)
292 if tt.roundtrip == "" {
297 for i := 0; i < b.N; i++ {
301 if w := tt.roundtrip; g != w {
302 b.Errorf("Parse(%q).String() == %q, want %q", tt.in, g, w)
307 func TestParse(t *testing.T) {
308 DoTest(t, Parse, "Parse", urltests)
311 const pathThatLooksSchemeRelative = "//not.a.user@not.a.host/just/a/path"
313 var parseRequestURLTests = []struct {
317 {"http://foo.com", true},
318 {"http://foo.com/", true},
319 {"http://foo.com/path", true},
321 {pathThatLooksSchemeRelative, true},
322 {"//not.a.user@%66%6f%6f.com/just/a/path/also", true},
328 func TestParseRequestURI(t *testing.T) {
329 for _, test := range parseRequestURLTests {
330 _, err := ParseRequestURI(test.url)
332 if valid != test.expectedValid {
333 t.Errorf("Expected valid=%v for %q; got %v", test.expectedValid, test.url, valid)
337 url, err := ParseRequestURI(pathThatLooksSchemeRelative)
339 t.Fatalf("Unexpected error %v", err)
341 if url.Path != pathThatLooksSchemeRelative {
342 t.Errorf("Expected path %q; got %q", pathThatLooksSchemeRelative, url.Path)
346 func DoTestString(t *testing.T, parse func(string) (*URL, error), name string, tests []URLTest) {
347 for _, tt := range tests {
348 u, err := parse(tt.in)
350 t.Errorf("%s(%q) returned error %s", name, tt.in, err)
354 if len(tt.roundtrip) > 0 {
355 expected = tt.roundtrip
359 t.Errorf("%s(%q).String() == %q (expected %q)", name, tt.in, s, expected)
364 func TestURLString(t *testing.T) {
365 DoTestString(t, Parse, "Parse", urltests)
368 type EscapeTest struct {
374 var unescapeTests = []EscapeTest{
406 "%", // not enough characters after %
411 "%a", // not enough characters after %
416 "%1", // not enough characters after %
421 "123%45%6", // not enough characters after %
426 "%zzzzz", // invalid hex digits
432 func TestUnescape(t *testing.T) {
433 for _, tt := range unescapeTests {
434 actual, err := QueryUnescape(tt.in)
435 if actual != tt.out || (err != nil) != (tt.err != nil) {
436 t.Errorf("QueryUnescape(%q) = %q, %s; want %q, %s", tt.in, actual, err, tt.out, tt.err)
441 var escapeTests = []EscapeTest{
463 " ?&=#+%!<>#\"{}|\\^[]`☺\t:/@$'()*,;",
464 "+%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",
469 func TestEscape(t *testing.T) {
470 for _, tt := range escapeTests {
471 actual := QueryEscape(tt.in)
472 if tt.out != actual {
473 t.Errorf("QueryEscape(%q) = %q, want %q", tt.in, actual, tt.out)
476 // for bonus points, verify that escape:unescape is an identity.
477 roundtrip, err := QueryUnescape(actual)
478 if roundtrip != tt.in || err != nil {
479 t.Errorf("QueryUnescape(%q) = %q, %s; want %q, %s", actual, roundtrip, err, tt.in, "[no error]")
484 //var userinfoTests = []UserinfoTest{
485 // {"user", "password", "user:password"},
486 // {"foo:bar", "~!@#$%^&*()_+{}|[]\\-=`:;'\"<>?,./",
487 // "foo%3Abar:~!%40%23$%25%5E&*()_+%7B%7D%7C%5B%5D%5C-=%60%3A;'%22%3C%3E?,.%2F"},
490 type EncodeQueryTest struct {
495 var encodeQueryTests = []EncodeQueryTest{
497 {Values{"q": {"puppies"}, "oe": {"utf8"}}, "oe=utf8&q=puppies"},
498 {Values{"q": {"dogs", "&", "7"}}, "q=dogs&q=%26&q=7"},
500 "a": {"a1", "a2", "a3"},
501 "b": {"b1", "b2", "b3"},
502 "c": {"c1", "c2", "c3"},
503 }, "a=a1&a=a2&a=a3&b=b1&b=b2&b=b3&c=c1&c=c2&c=c3"},
506 func TestEncodeQuery(t *testing.T) {
507 for _, tt := range encodeQueryTests {
508 if q := tt.m.Encode(); q != tt.expected {
509 t.Errorf(`EncodeQuery(%+v) = %q, want %q`, tt.m, q, tt.expected)
514 var resolvePathTests = []struct {
515 base, ref, expected string
522 {"a/b/c", "..", "a/"},
523 {"a/b/c", "../d", "a/d"},
524 {"a/b/c", ".././d", "a/d"},
526 {"a/./b", ".", "a/./"},
527 {"a/../", ".", "a/../"},
528 {"a/.././b", "c", "a/.././c"},
531 func TestResolvePath(t *testing.T) {
532 for _, test := range resolvePathTests {
533 got := resolvePath(test.base, test.ref)
534 if got != test.expected {
535 t.Errorf("For %q + %q got %q; expected %q", test.base, test.ref, got, test.expected)
540 var resolveReferenceTests = []struct {
541 base, rel, expected string
543 // Absolute URL references
544 {"http://foo.com?a=b", "https://bar.com/", "https://bar.com/"},
545 {"http://foo.com/", "https://bar.com/?a=b", "https://bar.com/?a=b"},
546 {"http://foo.com/bar", "mailto:foo@example.com", "mailto:foo@example.com"},
548 // Path-absolute references
549 {"http://foo.com/bar", "/baz", "http://foo.com/baz"},
550 {"http://foo.com/bar?a=b#f", "/baz", "http://foo.com/baz"},
551 {"http://foo.com/bar?a=b", "/baz?c=d", "http://foo.com/baz?c=d"},
554 {"https://foo.com/bar?a=b", "//bar.com/quux", "https://bar.com/quux"},
556 // Path-relative references:
558 // ... current directory
559 {"http://foo.com", ".", "http://foo.com/"},
560 {"http://foo.com/bar", ".", "http://foo.com/"},
561 {"http://foo.com/bar/", ".", "http://foo.com/bar/"},
564 {"http://foo.com", "bar", "http://foo.com/bar"},
565 {"http://foo.com/", "bar", "http://foo.com/bar"},
566 {"http://foo.com/bar/baz", "quux", "http://foo.com/bar/quux"},
569 {"http://foo.com/bar/baz", "../quux", "http://foo.com/quux"},
570 {"http://foo.com/bar/baz", "../../../../../quux", "http://foo.com/quux"},
571 {"http://foo.com/bar", "..", "http://foo.com/"},
572 {"http://foo.com/bar/baz", "./..", "http://foo.com/"},
573 // ".." in the middle (issue 3560)
574 {"http://foo.com/bar/baz", "quux/dotdot/../tail", "http://foo.com/bar/quux/tail"},
575 {"http://foo.com/bar/baz", "quux/./dotdot/../tail", "http://foo.com/bar/quux/tail"},
576 {"http://foo.com/bar/baz", "quux/./dotdot/.././tail", "http://foo.com/bar/quux/tail"},
577 {"http://foo.com/bar/baz", "quux/./dotdot/./../tail", "http://foo.com/bar/quux/tail"},
578 {"http://foo.com/bar/baz", "quux/./dotdot/dotdot/././../../tail", "http://foo.com/bar/quux/tail"},
579 {"http://foo.com/bar/baz", "quux/./dotdot/dotdot/./.././../tail", "http://foo.com/bar/quux/tail"},
580 {"http://foo.com/bar/baz", "quux/./dotdot/dotdot/dotdot/./../../.././././tail", "http://foo.com/bar/quux/tail"},
581 {"http://foo.com/bar/baz", "quux/./dotdot/../dotdot/../dot/./tail/..", "http://foo.com/bar/quux/dot"},
583 // "." and ".." in the base aren't special
584 {"http://foo.com/dot/./dotdot/../foo/bar", "../baz", "http://foo.com/dot/./dotdot/../baz"},
586 // Triple dot isn't special
587 {"http://foo.com/bar", "...", "http://foo.com/..."},
590 {"http://foo.com/bar", ".#frag", "http://foo.com/#frag"},
593 func TestResolveReference(t *testing.T) {
594 mustParse := func(url string) *URL {
597 t.Fatalf("Expected URL to parse: %q, got error: %v", url, err)
601 for _, test := range resolveReferenceTests {
602 base := mustParse(test.base)
603 rel := mustParse(test.rel)
604 url := base.ResolveReference(rel)
605 urlStr := url.String()
606 if urlStr != test.expected {
607 t.Errorf("Resolving %q + %q != %q; got %q", test.base, test.rel, test.expected, urlStr)
611 // Test that new instances are returned.
612 base := mustParse("http://foo.com/")
613 abs := base.ResolveReference(mustParse("."))
615 t.Errorf("Expected no-op reference to return new URL instance.")
617 barRef := mustParse("http://bar.com/")
618 abs = base.ResolveReference(barRef)
620 t.Errorf("Expected resolution of absolute reference to return new URL instance.")
623 // Test the convenience wrapper too
624 base = mustParse("http://foo.com/path/one/")
625 abs, _ = base.Parse("../two")
626 expected := "http://foo.com/path/two"
627 if abs.String() != expected {
628 t.Errorf("Parse wrapper got %q; expected %q", abs.String(), expected)
630 _, err := base.Parse("")
632 t.Errorf("Expected an error from Parse wrapper parsing an empty string.")
635 // Ensure Opaque resets the URL.
636 base = mustParse("scheme://user@foo.com/bar")
637 abs = base.ResolveReference(&URL{Opaque: "opaque"})
638 want := mustParse("scheme:opaque")
640 t.Errorf("ResolveReference failed to resolve opaque URL: want %#v, got %#v", abs, want)
644 func TestResolveReferenceOpaque(t *testing.T) {
645 mustParse := func(url string) *URL {
648 t.Fatalf("Expected URL to parse: %q, got error: %v", url, err)
652 for _, test := range resolveReferenceTests {
653 base := mustParse(test.base)
654 rel := mustParse(test.rel)
655 url := base.ResolveReference(rel)
656 urlStr := url.String()
657 if urlStr != test.expected {
658 t.Errorf("Resolving %q + %q != %q; got %q", test.base, test.rel, test.expected, urlStr)
662 // Test that new instances are returned.
663 base := mustParse("http://foo.com/")
664 abs := base.ResolveReference(mustParse("."))
666 t.Errorf("Expected no-op reference to return new URL instance.")
668 barRef := mustParse("http://bar.com/")
669 abs = base.ResolveReference(barRef)
671 t.Errorf("Expected resolution of absolute reference to return new URL instance.")
674 // Test the convenience wrapper too
675 base = mustParse("http://foo.com/path/one/")
676 abs, _ = base.Parse("../two")
677 expected := "http://foo.com/path/two"
678 if abs.String() != expected {
679 t.Errorf("Parse wrapper got %q; expected %q", abs.String(), expected)
681 _, err := base.Parse("")
683 t.Errorf("Expected an error from Parse wrapper parsing an empty string.")
688 func TestQueryValues(t *testing.T) {
689 u, _ := Parse("http://x.com?foo=bar&bar=1&bar=2")
692 t.Errorf("got %d keys in Query values, want 2", len(v))
694 if g, e := v.Get("foo"), "bar"; g != e {
695 t.Errorf("Get(foo) = %q, want %q", g, e)
698 if g, e := v.Get("Foo"), ""; g != e {
699 t.Errorf("Get(Foo) = %q, want %q", g, e)
701 if g, e := v.Get("bar"), "1"; g != e {
702 t.Errorf("Get(bar) = %q, want %q", g, e)
704 if g, e := v.Get("baz"), ""; g != e {
705 t.Errorf("Get(baz) = %q, want %q", g, e)
708 if g, e := v.Get("bar"), ""; g != e {
709 t.Errorf("second Get(bar) = %q, want %q", g, e)
713 type parseTest struct {
718 var parseTests = []parseTest{
721 out: Values{"a": []string{"1"}, "b": []string{"2"}},
724 query: "a=1&a=2&a=banana",
725 out: Values{"a": []string{"1", "2", "banana"}},
728 query: "ascii=%3Ckey%3A+0x90%3E",
729 out: Values{"ascii": []string{"<key: 0x90>"}},
733 out: Values{"a": []string{"1"}, "b": []string{"2"}},
736 query: "a=1&a=2;a=banana",
737 out: Values{"a": []string{"1", "2", "banana"}},
741 func TestParseQuery(t *testing.T) {
742 for i, test := range parseTests {
743 form, err := ParseQuery(test.query)
745 t.Errorf("test %d: Unexpected error: %v", i, err)
748 if len(form) != len(test.out) {
749 t.Errorf("test %d: len(form) = %d, want %d", i, len(form), len(test.out))
751 for k, evs := range test.out {
754 t.Errorf("test %d: Missing key %q", i, k)
757 if len(vs) != len(evs) {
758 t.Errorf("test %d: len(form[%q]) = %d, want %d", i, k, len(vs), len(evs))
761 for j, ev := range evs {
762 if v := vs[j]; v != ev {
763 t.Errorf("test %d: form[%q][%d] = %q, want %q", i, k, j, v, ev)
770 type RequestURITest struct {
775 var requritests = []RequestURITest{
797 RawQuery: "q=go+language",
799 "/a%20b?q=go+language",
812 RawQuery: "q=go+language",
814 "opaque?q=go+language",
818 func TestRequestURI(t *testing.T) {
819 for _, tt := range requritests {
820 s := tt.url.RequestURI()
822 t.Errorf("%#v.RequestURI() == %q (expected %q)", tt.url, s, tt.out)
827 func TestParseFailure(t *testing.T) {
828 // Test that the first parse error is returned.
829 const url = "%gh&%ij"
830 _, err := ParseQuery(url)
831 errStr := fmt.Sprint(err)
832 if !strings.Contains(errStr, "%gh") {
833 t.Errorf(`ParseQuery(%q) returned error %q, want something containing %q"`, url, errStr, "%gh")