github.com/hlts2/go@v0.0.0-20170904000733-812b34efaed8/src/net/url/url_test.go (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 "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 // Scheme-relative 1036 {"https://foo.com/bar?a=b", "//bar.com/quux", "https://bar.com/quux"}, 1037 1038 // Path-relative references: 1039 1040 // ... current directory 1041 {"http://foo.com", ".", "http://foo.com/"}, 1042 {"http://foo.com/bar", ".", "http://foo.com/"}, 1043 {"http://foo.com/bar/", ".", "http://foo.com/bar/"}, 1044 1045 // ... going down 1046 {"http://foo.com", "bar", "http://foo.com/bar"}, 1047 {"http://foo.com/", "bar", "http://foo.com/bar"}, 1048 {"http://foo.com/bar/baz", "quux", "http://foo.com/bar/quux"}, 1049 1050 // ... going up 1051 {"http://foo.com/bar/baz", "../quux", "http://foo.com/quux"}, 1052 {"http://foo.com/bar/baz", "../../../../../quux", "http://foo.com/quux"}, 1053 {"http://foo.com/bar", "..", "http://foo.com/"}, 1054 {"http://foo.com/bar/baz", "./..", "http://foo.com/"}, 1055 // ".." in the middle (issue 3560) 1056 {"http://foo.com/bar/baz", "quux/dotdot/../tail", "http://foo.com/bar/quux/tail"}, 1057 {"http://foo.com/bar/baz", "quux/./dotdot/../tail", "http://foo.com/bar/quux/tail"}, 1058 {"http://foo.com/bar/baz", "quux/./dotdot/.././tail", "http://foo.com/bar/quux/tail"}, 1059 {"http://foo.com/bar/baz", "quux/./dotdot/./../tail", "http://foo.com/bar/quux/tail"}, 1060 {"http://foo.com/bar/baz", "quux/./dotdot/dotdot/././../../tail", "http://foo.com/bar/quux/tail"}, 1061 {"http://foo.com/bar/baz", "quux/./dotdot/dotdot/./.././../tail", "http://foo.com/bar/quux/tail"}, 1062 {"http://foo.com/bar/baz", "quux/./dotdot/dotdot/dotdot/./../../.././././tail", "http://foo.com/bar/quux/tail"}, 1063 {"http://foo.com/bar/baz", "quux/./dotdot/../dotdot/../dot/./tail/..", "http://foo.com/bar/quux/dot/"}, 1064 1065 // Remove any dot-segments prior to forming the target URI. 1066 // http://tools.ietf.org/html/rfc3986#section-5.2.4 1067 {"http://foo.com/dot/./dotdot/../foo/bar", "../baz", "http://foo.com/dot/baz"}, 1068 1069 // Triple dot isn't special 1070 {"http://foo.com/bar", "...", "http://foo.com/..."}, 1071 1072 // Fragment 1073 {"http://foo.com/bar", ".#frag", "http://foo.com/#frag"}, 1074 1075 // Paths with escaping (issue 16947). 1076 {"http://foo.com/foo%2fbar/", "../baz", "http://foo.com/baz"}, 1077 {"http://foo.com/1/2%2f/3%2f4/5", "../../a/b/c", "http://foo.com/1/a/b/c"}, 1078 {"http://foo.com/1/2/3", "./a%2f../../b/..%2fc", "http://foo.com/1/2/b/..%2fc"}, 1079 {"http://foo.com/1/2%2f/3%2f4/5", "./a%2f../b/../c", "http://foo.com/1/2%2f/3%2f4/a%2f../c"}, 1080 {"http://foo.com/foo%20bar/", "../baz", "http://foo.com/baz"}, 1081 {"http://foo.com/foo", "../bar%2fbaz", "http://foo.com/bar%2fbaz"}, 1082 {"http://foo.com/foo%2dbar/", "./baz-quux", "http://foo.com/foo%2dbar/baz-quux"}, 1083 1084 // RFC 3986: Normal Examples 1085 // http://tools.ietf.org/html/rfc3986#section-5.4.1 1086 {"http://a/b/c/d;p?q", "g:h", "g:h"}, 1087 {"http://a/b/c/d;p?q", "g", "http://a/b/c/g"}, 1088 {"http://a/b/c/d;p?q", "./g", "http://a/b/c/g"}, 1089 {"http://a/b/c/d;p?q", "g/", "http://a/b/c/g/"}, 1090 {"http://a/b/c/d;p?q", "/g", "http://a/g"}, 1091 {"http://a/b/c/d;p?q", "//g", "http://g"}, 1092 {"http://a/b/c/d;p?q", "?y", "http://a/b/c/d;p?y"}, 1093 {"http://a/b/c/d;p?q", "g?y", "http://a/b/c/g?y"}, 1094 {"http://a/b/c/d;p?q", "#s", "http://a/b/c/d;p?q#s"}, 1095 {"http://a/b/c/d;p?q", "g#s", "http://a/b/c/g#s"}, 1096 {"http://a/b/c/d;p?q", "g?y#s", "http://a/b/c/g?y#s"}, 1097 {"http://a/b/c/d;p?q", ";x", "http://a/b/c/;x"}, 1098 {"http://a/b/c/d;p?q", "g;x", "http://a/b/c/g;x"}, 1099 {"http://a/b/c/d;p?q", "g;x?y#s", "http://a/b/c/g;x?y#s"}, 1100 {"http://a/b/c/d;p?q", "", "http://a/b/c/d;p?q"}, 1101 {"http://a/b/c/d;p?q", ".", "http://a/b/c/"}, 1102 {"http://a/b/c/d;p?q", "./", "http://a/b/c/"}, 1103 {"http://a/b/c/d;p?q", "..", "http://a/b/"}, 1104 {"http://a/b/c/d;p?q", "../", "http://a/b/"}, 1105 {"http://a/b/c/d;p?q", "../g", "http://a/b/g"}, 1106 {"http://a/b/c/d;p?q", "../..", "http://a/"}, 1107 {"http://a/b/c/d;p?q", "../../", "http://a/"}, 1108 {"http://a/b/c/d;p?q", "../../g", "http://a/g"}, 1109 1110 // RFC 3986: Abnormal Examples 1111 // http://tools.ietf.org/html/rfc3986#section-5.4.2 1112 {"http://a/b/c/d;p?q", "../../../g", "http://a/g"}, 1113 {"http://a/b/c/d;p?q", "../../../../g", "http://a/g"}, 1114 {"http://a/b/c/d;p?q", "/./g", "http://a/g"}, 1115 {"http://a/b/c/d;p?q", "/../g", "http://a/g"}, 1116 {"http://a/b/c/d;p?q", "g.", "http://a/b/c/g."}, 1117 {"http://a/b/c/d;p?q", ".g", "http://a/b/c/.g"}, 1118 {"http://a/b/c/d;p?q", "g..", "http://a/b/c/g.."}, 1119 {"http://a/b/c/d;p?q", "..g", "http://a/b/c/..g"}, 1120 {"http://a/b/c/d;p?q", "./../g", "http://a/b/g"}, 1121 {"http://a/b/c/d;p?q", "./g/.", "http://a/b/c/g/"}, 1122 {"http://a/b/c/d;p?q", "g/./h", "http://a/b/c/g/h"}, 1123 {"http://a/b/c/d;p?q", "g/../h", "http://a/b/c/h"}, 1124 {"http://a/b/c/d;p?q", "g;x=1/./y", "http://a/b/c/g;x=1/y"}, 1125 {"http://a/b/c/d;p?q", "g;x=1/../y", "http://a/b/c/y"}, 1126 {"http://a/b/c/d;p?q", "g?y/./x", "http://a/b/c/g?y/./x"}, 1127 {"http://a/b/c/d;p?q", "g?y/../x", "http://a/b/c/g?y/../x"}, 1128 {"http://a/b/c/d;p?q", "g#s/./x", "http://a/b/c/g#s/./x"}, 1129 {"http://a/b/c/d;p?q", "g#s/../x", "http://a/b/c/g#s/../x"}, 1130 1131 // Extras. 1132 {"https://a/b/c/d;p?q", "//g?q", "https://g?q"}, 1133 {"https://a/b/c/d;p?q", "//g#s", "https://g#s"}, 1134 {"https://a/b/c/d;p?q", "//g/d/e/f?y#s", "https://g/d/e/f?y#s"}, 1135 {"https://a/b/c/d;p#s", "?y", "https://a/b/c/d;p?y"}, 1136 {"https://a/b/c/d;p?q#s", "?y", "https://a/b/c/d;p?y"}, 1137 } 1138 1139 func TestResolveReference(t *testing.T) { 1140 mustParse := func(url string) *URL { 1141 u, err := Parse(url) 1142 if err != nil { 1143 t.Fatalf("Parse(%q) got err %v", url, err) 1144 } 1145 return u 1146 } 1147 opaque := &URL{Scheme: "scheme", Opaque: "opaque"} 1148 for _, test := range resolveReferenceTests { 1149 base := mustParse(test.base) 1150 rel := mustParse(test.rel) 1151 url := base.ResolveReference(rel) 1152 if got := url.String(); got != test.expected { 1153 t.Errorf("URL(%q).ResolveReference(%q)\ngot %q\nwant %q", test.base, test.rel, got, test.expected) 1154 } 1155 // Ensure that new instances are returned. 1156 if base == url { 1157 t.Errorf("Expected URL.ResolveReference to return new URL instance.") 1158 } 1159 // Test the convenience wrapper too. 1160 url, err := base.Parse(test.rel) 1161 if err != nil { 1162 t.Errorf("URL(%q).Parse(%q) failed: %v", test.base, test.rel, err) 1163 } else if got := url.String(); got != test.expected { 1164 t.Errorf("URL(%q).Parse(%q)\ngot %q\nwant %q", test.base, test.rel, got, test.expected) 1165 } else if base == url { 1166 // Ensure that new instances are returned for the wrapper too. 1167 t.Errorf("Expected URL.Parse to return new URL instance.") 1168 } 1169 // Ensure Opaque resets the URL. 1170 url = base.ResolveReference(opaque) 1171 if *url != *opaque { 1172 t.Errorf("ResolveReference failed to resolve opaque URL:\ngot %#v\nwant %#v", url, opaque) 1173 } 1174 // Test the convenience wrapper with an opaque URL too. 1175 url, err = base.Parse("scheme:opaque") 1176 if err != nil { 1177 t.Errorf(`URL(%q).Parse("scheme:opaque") failed: %v`, test.base, err) 1178 } else if *url != *opaque { 1179 t.Errorf("Parse failed to resolve opaque URL:\ngot %#v\nwant %#v", opaque, url) 1180 } else if base == url { 1181 // Ensure that new instances are returned, again. 1182 t.Errorf("Expected URL.Parse to return new URL instance.") 1183 } 1184 } 1185 } 1186 1187 func TestQueryValues(t *testing.T) { 1188 u, _ := Parse("http://x.com?foo=bar&bar=1&bar=2") 1189 v := u.Query() 1190 if len(v) != 2 { 1191 t.Errorf("got %d keys in Query values, want 2", len(v)) 1192 } 1193 if g, e := v.Get("foo"), "bar"; g != e { 1194 t.Errorf("Get(foo) = %q, want %q", g, e) 1195 } 1196 // Case sensitive: 1197 if g, e := v.Get("Foo"), ""; g != e { 1198 t.Errorf("Get(Foo) = %q, want %q", g, e) 1199 } 1200 if g, e := v.Get("bar"), "1"; g != e { 1201 t.Errorf("Get(bar) = %q, want %q", g, e) 1202 } 1203 if g, e := v.Get("baz"), ""; g != e { 1204 t.Errorf("Get(baz) = %q, want %q", g, e) 1205 } 1206 v.Del("bar") 1207 if g, e := v.Get("bar"), ""; g != e { 1208 t.Errorf("second Get(bar) = %q, want %q", g, e) 1209 } 1210 } 1211 1212 type parseTest struct { 1213 query string 1214 out Values 1215 } 1216 1217 var parseTests = []parseTest{ 1218 { 1219 query: "a=1&b=2", 1220 out: Values{"a": []string{"1"}, "b": []string{"2"}}, 1221 }, 1222 { 1223 query: "a=1&a=2&a=banana", 1224 out: Values{"a": []string{"1", "2", "banana"}}, 1225 }, 1226 { 1227 query: "ascii=%3Ckey%3A+0x90%3E", 1228 out: Values{"ascii": []string{"<key: 0x90>"}}, 1229 }, 1230 { 1231 query: "a=1;b=2", 1232 out: Values{"a": []string{"1"}, "b": []string{"2"}}, 1233 }, 1234 { 1235 query: "a=1&a=2;a=banana", 1236 out: Values{"a": []string{"1", "2", "banana"}}, 1237 }, 1238 } 1239 1240 func TestParseQuery(t *testing.T) { 1241 for i, test := range parseTests { 1242 form, err := ParseQuery(test.query) 1243 if err != nil { 1244 t.Errorf("test %d: Unexpected error: %v", i, err) 1245 continue 1246 } 1247 if len(form) != len(test.out) { 1248 t.Errorf("test %d: len(form) = %d, want %d", i, len(form), len(test.out)) 1249 } 1250 for k, evs := range test.out { 1251 vs, ok := form[k] 1252 if !ok { 1253 t.Errorf("test %d: Missing key %q", i, k) 1254 continue 1255 } 1256 if len(vs) != len(evs) { 1257 t.Errorf("test %d: len(form[%q]) = %d, want %d", i, k, len(vs), len(evs)) 1258 continue 1259 } 1260 for j, ev := range evs { 1261 if v := vs[j]; v != ev { 1262 t.Errorf("test %d: form[%q][%d] = %q, want %q", i, k, j, v, ev) 1263 } 1264 } 1265 } 1266 } 1267 } 1268 1269 type RequestURITest struct { 1270 url *URL 1271 out string 1272 } 1273 1274 var requritests = []RequestURITest{ 1275 { 1276 &URL{ 1277 Scheme: "http", 1278 Host: "example.com", 1279 Path: "", 1280 }, 1281 "/", 1282 }, 1283 { 1284 &URL{ 1285 Scheme: "http", 1286 Host: "example.com", 1287 Path: "/a b", 1288 }, 1289 "/a%20b", 1290 }, 1291 // golang.org/issue/4860 variant 1 1292 { 1293 &URL{ 1294 Scheme: "http", 1295 Host: "example.com", 1296 Opaque: "/%2F/%2F/", 1297 }, 1298 "/%2F/%2F/", 1299 }, 1300 // golang.org/issue/4860 variant 2 1301 { 1302 &URL{ 1303 Scheme: "http", 1304 Host: "example.com", 1305 Opaque: "//other.example.com/%2F/%2F/", 1306 }, 1307 "http://other.example.com/%2F/%2F/", 1308 }, 1309 // better fix for issue 4860 1310 { 1311 &URL{ 1312 Scheme: "http", 1313 Host: "example.com", 1314 Path: "/////", 1315 RawPath: "/%2F/%2F/", 1316 }, 1317 "/%2F/%2F/", 1318 }, 1319 { 1320 &URL{ 1321 Scheme: "http", 1322 Host: "example.com", 1323 Path: "/////", 1324 RawPath: "/WRONG/", // ignored because doesn't match Path 1325 }, 1326 "/////", 1327 }, 1328 { 1329 &URL{ 1330 Scheme: "http", 1331 Host: "example.com", 1332 Path: "/a b", 1333 RawQuery: "q=go+language", 1334 }, 1335 "/a%20b?q=go+language", 1336 }, 1337 { 1338 &URL{ 1339 Scheme: "http", 1340 Host: "example.com", 1341 Path: "/a b", 1342 RawPath: "/a b", // ignored because invalid 1343 RawQuery: "q=go+language", 1344 }, 1345 "/a%20b?q=go+language", 1346 }, 1347 { 1348 &URL{ 1349 Scheme: "http", 1350 Host: "example.com", 1351 Path: "/a?b", 1352 RawPath: "/a?b", // ignored because invalid 1353 RawQuery: "q=go+language", 1354 }, 1355 "/a%3Fb?q=go+language", 1356 }, 1357 { 1358 &URL{ 1359 Scheme: "myschema", 1360 Opaque: "opaque", 1361 }, 1362 "opaque", 1363 }, 1364 { 1365 &URL{ 1366 Scheme: "myschema", 1367 Opaque: "opaque", 1368 RawQuery: "q=go+language", 1369 }, 1370 "opaque?q=go+language", 1371 }, 1372 { 1373 &URL{ 1374 Scheme: "http", 1375 Host: "example.com", 1376 Path: "//foo", 1377 }, 1378 "//foo", 1379 }, 1380 { 1381 &URL{ 1382 Scheme: "http", 1383 Host: "example.com", 1384 Path: "/foo", 1385 ForceQuery: true, 1386 }, 1387 "/foo?", 1388 }, 1389 } 1390 1391 func TestRequestURI(t *testing.T) { 1392 for _, tt := range requritests { 1393 s := tt.url.RequestURI() 1394 if s != tt.out { 1395 t.Errorf("%#v.RequestURI() == %q (expected %q)", tt.url, s, tt.out) 1396 } 1397 } 1398 } 1399 1400 func TestParseFailure(t *testing.T) { 1401 // Test that the first parse error is returned. 1402 const url = "%gh&%ij" 1403 _, err := ParseQuery(url) 1404 errStr := fmt.Sprint(err) 1405 if !strings.Contains(errStr, "%gh") { 1406 t.Errorf(`ParseQuery(%q) returned error %q, want something containing %q"`, url, errStr, "%gh") 1407 } 1408 } 1409 1410 func TestParseErrors(t *testing.T) { 1411 tests := []struct { 1412 in string 1413 wantErr bool 1414 }{ 1415 {"http://[::1]", false}, 1416 {"http://[::1]:80", false}, 1417 {"http://[::1]:namedport", true}, // rfc3986 3.2.3 1418 {"http://[::1]/", false}, 1419 {"http://[::1]a", true}, 1420 {"http://[::1]%23", true}, 1421 {"http://[::1%25en0]", false}, // valid zone id 1422 {"http://[::1]:", false}, // colon, but no port OK 1423 {"http://[::1]:%38%30", true}, // not allowed: % encoding only for non-ASCII 1424 {"http://[::1%25%41]", false}, // RFC 6874 allows over-escaping in zone 1425 {"http://[%10::1]", true}, // no %xx escapes in IP address 1426 {"http://[::1]/%48", false}, // %xx in path is fine 1427 {"http://%41:8080/", true}, // not allowed: % encoding only for non-ASCII 1428 {"mysql://x@y(z:123)/foo", false}, // golang.org/issue/12023 1429 {"mysql://x@y(1.2.3.4:123)/foo", false}, 1430 1431 {"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 1432 {"http://a b.com/", true}, // no space in host name please 1433 {"cache_object://foo", true}, // scheme cannot have _, relative path cannot have : in first segment 1434 {"cache_object:foo", true}, 1435 {"cache_object:foo/bar", true}, 1436 {"cache_object/:foo/bar", false}, 1437 } 1438 for _, tt := range tests { 1439 u, err := Parse(tt.in) 1440 if tt.wantErr { 1441 if err == nil { 1442 t.Errorf("Parse(%q) = %#v; want an error", tt.in, u) 1443 } 1444 continue 1445 } 1446 if err != nil { 1447 t.Logf("Parse(%q) = %v; want no error", tt.in, err) 1448 } 1449 } 1450 } 1451 1452 // Issue 11202 1453 func TestStarRequest(t *testing.T) { 1454 u, err := Parse("*") 1455 if err != nil { 1456 t.Fatal(err) 1457 } 1458 if got, want := u.RequestURI(), "*"; got != want { 1459 t.Errorf("RequestURI = %q; want %q", got, want) 1460 } 1461 } 1462 1463 type shouldEscapeTest struct { 1464 in byte 1465 mode encoding 1466 escape bool 1467 } 1468 1469 var shouldEscapeTests = []shouldEscapeTest{ 1470 // Unreserved characters (§2.3) 1471 {'a', encodePath, false}, 1472 {'a', encodeUserPassword, false}, 1473 {'a', encodeQueryComponent, false}, 1474 {'a', encodeFragment, false}, 1475 {'a', encodeHost, false}, 1476 {'z', encodePath, false}, 1477 {'A', encodePath, false}, 1478 {'Z', encodePath, false}, 1479 {'0', encodePath, false}, 1480 {'9', encodePath, false}, 1481 {'-', encodePath, false}, 1482 {'-', encodeUserPassword, false}, 1483 {'-', encodeQueryComponent, false}, 1484 {'-', encodeFragment, false}, 1485 {'.', encodePath, false}, 1486 {'_', encodePath, false}, 1487 {'~', encodePath, false}, 1488 1489 // User information (§3.2.1) 1490 {':', encodeUserPassword, true}, 1491 {'/', encodeUserPassword, true}, 1492 {'?', encodeUserPassword, true}, 1493 {'@', encodeUserPassword, true}, 1494 {'$', encodeUserPassword, false}, 1495 {'&', encodeUserPassword, false}, 1496 {'+', encodeUserPassword, false}, 1497 {',', encodeUserPassword, false}, 1498 {';', encodeUserPassword, false}, 1499 {'=', encodeUserPassword, false}, 1500 1501 // Host (IP address, IPv6 address, registered name, port suffix; §3.2.2) 1502 {'!', encodeHost, false}, 1503 {'$', encodeHost, false}, 1504 {'&', encodeHost, false}, 1505 {'\'', encodeHost, false}, 1506 {'(', encodeHost, false}, 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 {'0', encodeHost, false}, 1517 {'9', encodeHost, false}, 1518 {'A', encodeHost, false}, 1519 {'z', encodeHost, false}, 1520 {'_', encodeHost, false}, 1521 {'-', encodeHost, false}, 1522 {'.', encodeHost, false}, 1523 } 1524 1525 func TestShouldEscape(t *testing.T) { 1526 for _, tt := range shouldEscapeTests { 1527 if shouldEscape(tt.in, tt.mode) != tt.escape { 1528 t.Errorf("shouldEscape(%q, %v) returned %v; expected %v", tt.in, tt.mode, !tt.escape, tt.escape) 1529 } 1530 } 1531 } 1532 1533 type timeoutError struct { 1534 timeout bool 1535 } 1536 1537 func (e *timeoutError) Error() string { return "timeout error" } 1538 func (e *timeoutError) Timeout() bool { return e.timeout } 1539 1540 type temporaryError struct { 1541 temporary bool 1542 } 1543 1544 func (e *temporaryError) Error() string { return "temporary error" } 1545 func (e *temporaryError) Temporary() bool { return e.temporary } 1546 1547 type timeoutTemporaryError struct { 1548 timeoutError 1549 temporaryError 1550 } 1551 1552 func (e *timeoutTemporaryError) Error() string { return "timeout/temporary error" } 1553 1554 var netErrorTests = []struct { 1555 err error 1556 timeout bool 1557 temporary bool 1558 }{{ 1559 err: &Error{"Get", "http://google.com/", &timeoutError{timeout: true}}, 1560 timeout: true, 1561 temporary: false, 1562 }, { 1563 err: &Error{"Get", "http://google.com/", &timeoutError{timeout: false}}, 1564 timeout: false, 1565 temporary: false, 1566 }, { 1567 err: &Error{"Get", "http://google.com/", &temporaryError{temporary: true}}, 1568 timeout: false, 1569 temporary: true, 1570 }, { 1571 err: &Error{"Get", "http://google.com/", &temporaryError{temporary: false}}, 1572 timeout: false, 1573 temporary: false, 1574 }, { 1575 err: &Error{"Get", "http://google.com/", &timeoutTemporaryError{timeoutError{timeout: true}, temporaryError{temporary: true}}}, 1576 timeout: true, 1577 temporary: true, 1578 }, { 1579 err: &Error{"Get", "http://google.com/", &timeoutTemporaryError{timeoutError{timeout: false}, temporaryError{temporary: true}}}, 1580 timeout: false, 1581 temporary: true, 1582 }, { 1583 err: &Error{"Get", "http://google.com/", &timeoutTemporaryError{timeoutError{timeout: true}, temporaryError{temporary: false}}}, 1584 timeout: true, 1585 temporary: false, 1586 }, { 1587 err: &Error{"Get", "http://google.com/", &timeoutTemporaryError{timeoutError{timeout: false}, temporaryError{temporary: false}}}, 1588 timeout: false, 1589 temporary: false, 1590 }, { 1591 err: &Error{"Get", "http://google.com/", io.EOF}, 1592 timeout: false, 1593 temporary: false, 1594 }} 1595 1596 // Test that url.Error implements net.Error and that it forwards 1597 func TestURLErrorImplementsNetError(t *testing.T) { 1598 for i, tt := range netErrorTests { 1599 err, ok := tt.err.(net.Error) 1600 if !ok { 1601 t.Errorf("%d: %T does not implement net.Error", i+1, tt.err) 1602 continue 1603 } 1604 if err.Timeout() != tt.timeout { 1605 t.Errorf("%d: err.Timeout(): got %v, want %v", i+1, err.Timeout(), tt.timeout) 1606 continue 1607 } 1608 if err.Temporary() != tt.temporary { 1609 t.Errorf("%d: err.Temporary(): got %v, want %v", i+1, err.Temporary(), tt.temporary) 1610 } 1611 } 1612 } 1613 1614 func TestURLHostname(t *testing.T) { 1615 tests := []struct { 1616 host string // URL.Host field 1617 want string 1618 }{ 1619 {"foo.com:80", "foo.com"}, 1620 {"foo.com", "foo.com"}, 1621 {"FOO.COM", "FOO.COM"}, // no canonicalization (yet?) 1622 {"1.2.3.4", "1.2.3.4"}, 1623 {"1.2.3.4:80", "1.2.3.4"}, 1624 {"[1:2:3:4]", "1:2:3:4"}, 1625 {"[1:2:3:4]:80", "1:2:3:4"}, 1626 {"[::1]:80", "::1"}, 1627 } 1628 for _, tt := range tests { 1629 u := &URL{Host: tt.host} 1630 got := u.Hostname() 1631 if got != tt.want { 1632 t.Errorf("Hostname for Host %q = %q; want %q", tt.host, got, tt.want) 1633 } 1634 } 1635 } 1636 1637 func TestURLPort(t *testing.T) { 1638 tests := []struct { 1639 host string // URL.Host field 1640 want string 1641 }{ 1642 {"foo.com", ""}, 1643 {"foo.com:80", "80"}, 1644 {"1.2.3.4", ""}, 1645 {"1.2.3.4:80", "80"}, 1646 {"[1:2:3:4]", ""}, 1647 {"[1:2:3:4]:80", "80"}, 1648 } 1649 for _, tt := range tests { 1650 u := &URL{Host: tt.host} 1651 got := u.Port() 1652 if got != tt.want { 1653 t.Errorf("Port for Host %q = %q; want %q", tt.host, got, tt.want) 1654 } 1655 } 1656 } 1657 1658 var _ encodingPkg.BinaryMarshaler = (*URL)(nil) 1659 var _ encodingPkg.BinaryUnmarshaler = (*URL)(nil) 1660 1661 func TestJSON(t *testing.T) { 1662 u, err := Parse("https://www.google.com/x?y=z") 1663 if err != nil { 1664 t.Fatal(err) 1665 } 1666 js, err := json.Marshal(u) 1667 if err != nil { 1668 t.Fatal(err) 1669 } 1670 1671 // If only we could implement TextMarshaler/TextUnmarshaler, 1672 // this would work: 1673 // 1674 // if string(js) != strconv.Quote(u.String()) { 1675 // t.Errorf("json encoding: %s\nwant: %s\n", js, strconv.Quote(u.String())) 1676 // } 1677 1678 u1 := new(URL) 1679 err = json.Unmarshal(js, u1) 1680 if err != nil { 1681 t.Fatal(err) 1682 } 1683 if u1.String() != u.String() { 1684 t.Errorf("json decoded to: %s\nwant: %s\n", u1, u) 1685 } 1686 } 1687 1688 func TestGob(t *testing.T) { 1689 u, err := Parse("https://www.google.com/x?y=z") 1690 if err != nil { 1691 t.Fatal(err) 1692 } 1693 var w bytes.Buffer 1694 err = gob.NewEncoder(&w).Encode(u) 1695 if err != nil { 1696 t.Fatal(err) 1697 } 1698 1699 u1 := new(URL) 1700 err = gob.NewDecoder(&w).Decode(u1) 1701 if err != nil { 1702 t.Fatal(err) 1703 } 1704 if u1.String() != u.String() { 1705 t.Errorf("json decoded to: %s\nwant: %s\n", u1, u) 1706 } 1707 }