url_test.go 40.8 KB
Newer Older
1 2 3 4
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

Rob Pike's avatar
Rob Pike committed
5
package url
6 7

import (
8 9 10 11
	"bytes"
	encodingPkg "encoding"
	"encoding/gob"
	"encoding/json"
12
	"fmt"
13 14
	"io"
	"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
}

Robert Griesemer's avatar
Robert Griesemer committed
26
var urltests = []URLTest{
27
	// no path
Robert Griesemer's avatar
Robert Griesemer committed
28
	{
29 30
		"http://www.google.com",
		&URL{
31 32
			Scheme: "http",
			Host:   "www.google.com",
Steve Newman's avatar
Steve Newman committed
33
		},
Robert Griesemer's avatar
Robert Griesemer committed
34
		"",
35 36
	},
	// path
Robert Griesemer's avatar
Robert Griesemer committed
37
	{
38 39
		"http://www.google.com/",
		&URL{
40 41 42
			Scheme: "http",
			Host:   "www.google.com",
			Path:   "/",
Steve Newman's avatar
Steve Newman committed
43
		},
Robert Griesemer's avatar
Robert Griesemer committed
44
		"",
Steve Newman's avatar
Steve Newman committed
45
	},
46
	// path with hex escaping
Robert Griesemer's avatar
Robert Griesemer committed
47
	{
Steve Newman's avatar
Steve Newman committed
48 49
		"http://www.google.com/file%20one%26two",
		&URL{
50 51 52 53
			Scheme:  "http",
			Host:    "www.google.com",
			Path:    "/file one&two",
			RawPath: "/file%20one%26two",
Steve Newman's avatar
Steve Newman committed
54
		},
55
		"",
56 57
	},
	// user
Robert Griesemer's avatar
Robert Griesemer committed
58
	{
59 60
		"ftp://webmaster@www.google.com/",
		&URL{
61 62 63 64
			Scheme: "ftp",
			User:   User("webmaster"),
			Host:   "www.google.com",
			Path:   "/",
Steve Newman's avatar
Steve Newman committed
65
		},
Robert Griesemer's avatar
Robert Griesemer committed
66
		"",
Steve Newman's avatar
Steve Newman committed
67 68
	},
	// escape sequence in username
Robert Griesemer's avatar
Robert Griesemer committed
69
	{
Steve Newman's avatar
Steve Newman committed
70 71
		"ftp://john%20doe@www.google.com/",
		&URL{
72 73 74 75
			Scheme: "ftp",
			User:   User("john doe"),
			Host:   "www.google.com",
			Path:   "/",
Steve Newman's avatar
Steve Newman committed
76
		},
77
		"ftp://john%20doe@www.google.com/",
78
	},
79 80 81 82 83 84 85 86 87 88 89
	// empty query
	{
		"http://www.google.com/?",
		&URL{
			Scheme:     "http",
			Host:       "www.google.com",
			Path:       "/",
			ForceQuery: true,
		},
		"",
	},
90 91 92 93 94 95 96 97 98 99 100
	// query ending in question mark (Issue 14573)
	{
		"http://www.google.com/?foo=bar?",
		&URL{
			Scheme:   "http",
			Host:     "www.google.com",
			Path:     "/",
			RawQuery: "foo=bar?",
		},
		"",
	},
101
	// query
Robert Griesemer's avatar
Robert Griesemer committed
102
	{
103 104
		"http://www.google.com/?q=go+language",
		&URL{
105 106 107 108
			Scheme:   "http",
			Host:     "www.google.com",
			Path:     "/",
			RawQuery: "q=go+language",
Steve Newman's avatar
Steve Newman committed
109
		},
Robert Griesemer's avatar
Robert Griesemer committed
110
		"",
Steve Newman's avatar
Steve Newman committed
111 112
	},
	// query with hex escaping: NOT parsed
Robert Griesemer's avatar
Robert Griesemer committed
113
	{
Steve Newman's avatar
Steve Newman committed
114 115
		"http://www.google.com/?q=go%20language",
		&URL{
116 117 118 119
			Scheme:   "http",
			Host:     "www.google.com",
			Path:     "/",
			RawQuery: "q=go%20language",
Steve Newman's avatar
Steve Newman committed
120
		},
Robert Griesemer's avatar
Robert Griesemer committed
121
		"",
122
	},
123
	// %20 outside query
Robert Griesemer's avatar
Robert Griesemer committed
124
	{
125 126
		"http://www.google.com/a%20b?q=c+d",
		&URL{
127 128 129 130
			Scheme:   "http",
			Host:     "www.google.com",
			Path:     "/a b",
			RawQuery: "q=c+d",
131 132 133
		},
		"",
	},
134
	// path without leading /, so no parsing
Robert Griesemer's avatar
Robert Griesemer committed
135
	{
136 137
		"http:www.google.com/?q=go+language",
		&URL{
138 139 140
			Scheme:   "http",
			Opaque:   "www.google.com/",
			RawQuery: "q=go+language",
141 142 143
		},
		"http:www.google.com/?q=go+language",
	},
144
	// path without leading /, so no parsing
Robert Griesemer's avatar
Robert Griesemer committed
145
	{
146 147
		"http:%2f%2fwww.google.com/?q=go+language",
		&URL{
148 149 150
			Scheme:   "http",
			Opaque:   "%2f%2fwww.google.com/",
			RawQuery: "q=go+language",
Steve Newman's avatar
Steve Newman committed
151
		},
152
		"http:%2f%2fwww.google.com/?q=go+language",
153
	},
154
	// non-authority with path
Robert Griesemer's avatar
Robert Griesemer committed
155
	{
156 157
		"mailto:/webmaster@golang.org",
		&URL{
158 159
			Scheme: "mailto",
			Path:   "/webmaster@golang.org",
Steve Newman's avatar
Steve Newman committed
160
		},
161
		"mailto:///webmaster@golang.org", // unfortunate compromise
162 163
	},
	// non-authority
Robert Griesemer's avatar
Robert Griesemer committed
164
	{
165 166
		"mailto:webmaster@golang.org",
		&URL{
167 168
			Scheme: "mailto",
			Opaque: "webmaster@golang.org",
Steve Newman's avatar
Steve Newman committed
169
		},
Robert Griesemer's avatar
Robert Griesemer committed
170
		"",
171
	},
172
	// unescaped :// in query should not create a scheme
Robert Griesemer's avatar
Robert Griesemer committed
173
	{
174 175
		"/foo?query=http://bad",
		&URL{
176 177
			Path:     "/foo",
			RawQuery: "query=http://bad",
178
		},
Robert Griesemer's avatar
Robert Griesemer committed
179
		"",
180
	},
181
	// leading // without scheme should create an authority
Robert Griesemer's avatar
Robert Griesemer committed
182
	{
183 184
		"//foo",
		&URL{
185
			Host: "foo",
186 187 188 189 190 191 192
		},
		"",
	},
	// leading // without scheme, with userinfo, path, and query
	{
		"//user@foo/path?a=b",
		&URL{
193 194 195 196
			User:     User("user"),
			Host:     "foo",
			Path:     "/path",
			RawQuery: "a=b",
197 198 199 200 201
		},
		"",
	},
	// Three leading slashes isn't an authority, but doesn't return an error.
	// (We can't return an error, as this code is also used via
Rob Pike's avatar
Rob Pike committed
202
	// ServeHTTP -> ReadRequest -> Parse, which is arguably a
203 204 205 206 207
	// different URL parsing context, but currently shares the
	// same codepath)
	{
		"///threeslashes",
		&URL{
208
			Path: "///threeslashes",
209 210 211
		},
		"",
	},
Robert Griesemer's avatar
Robert Griesemer committed
212
	{
213 214
		"http://user:password@google.com",
		&URL{
215 216 217
			Scheme: "http",
			User:   UserPassword("user", "password"),
			Host:   "google.com",
218
		},
219
		"http://user:password@google.com",
220
	},
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
	// unescaped @ in username should not confuse host
	{
		"http://j@ne:password@google.com",
		&URL{
			Scheme: "http",
			User:   UserPassword("j@ne", "password"),
			Host:   "google.com",
		},
		"http://j%40ne:password@google.com",
	},
	// unescaped @ in password should not confuse host
	{
		"http://jane:p@ssword@google.com",
		&URL{
			Scheme: "http",
			User:   UserPassword("jane", "p@ssword"),
			Host:   "google.com",
		},
		"http://jane:p%40ssword@google.com",
	},
	{
		"http://j@ne:password@google.com/p@th?q=@go",
		&URL{
			Scheme:   "http",
			User:     UserPassword("j@ne", "password"),
			Host:     "google.com",
			Path:     "/p@th",
			RawQuery: "q=@go",
		},
		"http://j%40ne:password@google.com/p@th?q=@go",
	},
Robert Griesemer's avatar
Robert Griesemer committed
252
	{
253 254
		"http://www.google.com/?q=go+language#foo",
		&URL{
255 256 257 258 259
			Scheme:   "http",
			Host:     "www.google.com",
			Path:     "/",
			RawQuery: "q=go+language",
			Fragment: "foo",
Steve Newman's avatar
Steve Newman committed
260
		},
Robert Griesemer's avatar
Robert Griesemer committed
261
		"",
Steve Newman's avatar
Steve Newman committed
262
	},
Robert Griesemer's avatar
Robert Griesemer committed
263
	{
Steve Newman's avatar
Steve Newman committed
264 265
		"http://www.google.com/?q=go+language#foo%26bar",
		&URL{
266 267 268 269 270
			Scheme:   "http",
			Host:     "www.google.com",
			Path:     "/",
			RawQuery: "q=go+language",
			Fragment: "foo&bar",
Steve Newman's avatar
Steve Newman committed
271
		},
272
		"http://www.google.com/?q=go+language#foo&bar",
273
	},
274 275 276 277 278 279 280 281 282
	{
		"file:///home/adg/rabbits",
		&URL{
			Scheme: "file",
			Host:   "",
			Path:   "/home/adg/rabbits",
		},
		"file:///home/adg/rabbits",
	},
283 284 285 286 287 288 289 290 291 292 293
	// "Windows" paths are no exception to the rule.
	// See golang.org/issue/6027, especially comment #9.
	{
		"file:///C:/FooBar/Baz.txt",
		&URL{
			Scheme: "file",
			Host:   "",
			Path:   "/C:/FooBar/Baz.txt",
		},
		"file:///C:/FooBar/Baz.txt",
	},
294 295 296 297 298 299 300 301 302
	// case-insensitive scheme
	{
		"MaIlTo:webmaster@golang.org",
		&URL{
			Scheme: "mailto",
			Opaque: "webmaster@golang.org",
		},
		"mailto:webmaster@golang.org",
	},
303 304 305 306 307 308 309 310
	// Relative path
	{
		"a/b/c",
		&URL{
			Path: "a/b/c",
		},
		"a/b/c",
	},
311 312 313 314 315 316 317 318 319 320
	// escaped '?' in username and password
	{
		"http://%3Fam:pa%3Fsword@google.com",
		&URL{
			Scheme: "http",
			User:   UserPassword("?am", "pa?sword"),
			Host:   "google.com",
		},
		"",
	},
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
	// host subcomponent; IPv4 address in RFC 3986
	{
		"http://192.168.0.1/",
		&URL{
			Scheme: "http",
			Host:   "192.168.0.1",
			Path:   "/",
		},
		"",
	},
	// host and port subcomponents; IPv4 address in RFC 3986
	{
		"http://192.168.0.1:8080/",
		&URL{
			Scheme: "http",
			Host:   "192.168.0.1:8080",
			Path:   "/",
		},
		"",
	},
	// host subcomponent; IPv6 address in RFC 3986
	{
		"http://[fe80::1]/",
		&URL{
			Scheme: "http",
			Host:   "[fe80::1]",
			Path:   "/",
		},
		"",
	},
	// host and port subcomponents; IPv6 address in RFC 3986
	{
		"http://[fe80::1]:8080/",
		&URL{
			Scheme: "http",
			Host:   "[fe80::1]:8080",
			Path:   "/",
		},
		"",
	},
361
	// host subcomponent; IPv6 address with zone identifier in RFC 6874
362 363 364 365 366 367 368 369 370
	{
		"http://[fe80::1%25en0]/", // alphanum zone identifier
		&URL{
			Scheme: "http",
			Host:   "[fe80::1%en0]",
			Path:   "/",
		},
		"",
	},
371
	// host and port subcomponents; IPv6 address with zone identifier in RFC 6874
372 373 374 375 376 377 378 379 380
	{
		"http://[fe80::1%25en0]:8080/", // alphanum zone identifier
		&URL{
			Scheme: "http",
			Host:   "[fe80::1%en0]:8080",
			Path:   "/",
		},
		"",
	},
381
	// host subcomponent; IPv6 address with zone identifier in RFC 6874
382 383 384 385 386 387 388 389 390
	{
		"http://[fe80::1%25%65%6e%301-._~]/", // percent-encoded+unreserved zone identifier
		&URL{
			Scheme: "http",
			Host:   "[fe80::1%en01-._~]",
			Path:   "/",
		},
		"http://[fe80::1%25en01-._~]/",
	},
391
	// host and port subcomponents; IPv6 address with zone identifier in RFC 6874
392 393 394 395 396 397 398 399 400
	{
		"http://[fe80::1%25%65%6e%301-._~]:8080/", // percent-encoded+unreserved zone identifier
		&URL{
			Scheme: "http",
			Host:   "[fe80::1%en01-._~]:8080",
			Path:   "/",
		},
		"http://[fe80::1%25en01-._~]:8080/",
	},
401 402 403 404 405 406 407 408 409 410 411 412
	// alternate escapings of path survive round trip
	{
		"http://rest.rsc.io/foo%2fbar/baz%2Fquux?alt=media",
		&URL{
			Scheme:   "http",
			Host:     "rest.rsc.io",
			Path:     "/foo/bar/baz/quux",
			RawPath:  "/foo%2fbar/baz%2Fquux",
			RawQuery: "alt=media",
		},
		"",
	},
413 414 415 416 417 418 419 420 421 422
	// issue 12036
	{
		"mysql://a,b,c/bar",
		&URL{
			Scheme: "mysql",
			Host:   "a,b,c",
			Path:   "/bar",
		},
		"",
	},
423
	// worst case host, still round trips
424
	{
425
		"scheme://!$&'()*+,;=hello!:port/path",
426 427
		&URL{
			Scheme: "scheme",
428
			Host:   "!$&'()*+,;=hello!:port",
429 430 431 432
			Path:   "/path",
		},
		"",
	},
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
	// worst case path, still round trips
	{
		"http://host/!$&'()*+,;=:@[hello]",
		&URL{
			Scheme:  "http",
			Host:    "host",
			Path:    "/!$&'()*+,;=:@[hello]",
			RawPath: "/!$&'()*+,;=:@[hello]",
		},
		"",
	},
	// golang.org/issue/5684
	{
		"http://example.com/oid/[order_id]",
		&URL{
			Scheme:  "http",
			Host:    "example.com",
			Path:    "/oid/[order_id]",
			RawPath: "/oid/[order_id]",
		},
		"",
	},
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
	// golang.org/issue/12200 (colon with empty port)
	{
		"http://192.168.0.2:8080/foo",
		&URL{
			Scheme: "http",
			Host:   "192.168.0.2:8080",
			Path:   "/foo",
		},
		"",
	},
	{
		"http://192.168.0.2:/foo",
		&URL{
			Scheme: "http",
			Host:   "192.168.0.2:",
			Path:   "/foo",
		},
		"",
	},
	{
		// Malformed IPv6 but still accepted.
		"http://2b01:e34:ef40:7730:8e70:5aff:fefe:edac:8080/foo",
		&URL{
			Scheme: "http",
			Host:   "2b01:e34:ef40:7730:8e70:5aff:fefe:edac:8080",
			Path:   "/foo",
		},
		"",
	},
	{
		// Malformed IPv6 but still accepted.
		"http://2b01:e34:ef40:7730:8e70:5aff:fefe:edac:/foo",
		&URL{
			Scheme: "http",
			Host:   "2b01:e34:ef40:7730:8e70:5aff:fefe:edac:",
			Path:   "/foo",
		},
		"",
	},
	{
		"http://[2b01:e34:ef40:7730:8e70:5aff:fefe:edac]:8080/foo",
		&URL{
			Scheme: "http",
			Host:   "[2b01:e34:ef40:7730:8e70:5aff:fefe:edac]:8080",
			Path:   "/foo",
		},
		"",
	},
	{
		"http://[2b01:e34:ef40:7730:8e70:5aff:fefe:edac]:/foo",
		&URL{
			Scheme: "http",
			Host:   "[2b01:e34:ef40:7730:8e70:5aff:fefe:edac]:",
			Path:   "/foo",
		},
		"",
	},
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
	// golang.org/issue/7991 and golang.org/issue/12719 (non-ascii %-encoded in host)
	{
		"http://hello.世界.com/foo",
		&URL{
			Scheme: "http",
			Host:   "hello.世界.com",
			Path:   "/foo",
		},
		"http://hello.%E4%B8%96%E7%95%8C.com/foo",
	},
	{
		"http://hello.%e4%b8%96%e7%95%8c.com/foo",
		&URL{
			Scheme: "http",
			Host:   "hello.世界.com",
			Path:   "/foo",
		},
		"http://hello.%E4%B8%96%E7%95%8C.com/foo",
	},
	{
		"http://hello.%E4%B8%96%E7%95%8C.com/foo",
		&URL{
			Scheme: "http",
			Host:   "hello.世界.com",
			Path:   "/foo",
		},
		"",
	},
540 541 542 543 544 545 546 547 548 549
	// golang.org/issue/10433 (path beginning with //)
	{
		"http://example.com//foo",
		&URL{
			Scheme: "http",
			Host:   "example.com",
			Path:   "//foo",
		},
		"",
	},
550 551 552 553 554 555 556 557 558 559
	// test that we can reparse the host names we accept.
	{
		"myscheme://authority<\"hi\">/foo",
		&URL{
			Scheme: "myscheme",
			Host:   "authority<\"hi\">",
			Path:   "/foo",
		},
		"",
	},
560 561 562 563 564 565 566 567 568 569 570
	// spaces in hosts are disallowed but escaped spaces in IPv6 scope IDs are grudgingly OK.
	// This happens on Windows.
	// golang.org/issue/14002
	{
		"tcp://[2020::2020:20:2020:2020%25Windows%20Loves%20Spaces]:2020",
		&URL{
			Scheme: "tcp",
			Host:   "[2020::2020:20:2020:2020%Windows Loves Spaces]:2020",
		},
		"",
	},
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
	// test we can roundtrip magnet url
	// fix issue https://golang.org/issue/20054
	{
		"magnet:?xt=urn:btih:c12fe1c06bba254a9dc9f519b335aa7c1367a88a&dn",
		&URL{
			Scheme:   "magnet",
			Host:     "",
			Path:     "",
			RawQuery: "xt=urn:btih:c12fe1c06bba254a9dc9f519b335aa7c1367a88a&dn",
		},
		"magnet:?xt=urn:btih:c12fe1c06bba254a9dc9f519b335aa7c1367a88a&dn",
	},
	{
		"mailto:?subject=hi",
		&URL{
			Scheme:   "mailto",
			Host:     "",
			Path:     "",
			RawQuery: "subject=hi",
		},
		"mailto:?subject=hi",
	},
593 594 595 596
}

// more useful string for debugging than fmt's struct printer
func ufmt(u *URL) string {
597 598 599 600 601 602 603
	var user, pass interface{}
	if u.User != nil {
		user = u.User.Username()
		if p, ok := u.User.Password(); ok {
			pass = p
		}
	}
604 605
	return fmt.Sprintf("opaque=%q, scheme=%q, user=%#v, pass=%#v, host=%q, path=%q, rawpath=%q, rawq=%q, frag=%q, forcequery=%v",
		u.Opaque, u.Scheme, user, pass, u.Host, u.Path, u.RawPath, u.RawQuery, u.Fragment, u.ForceQuery)
606 607
}

608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
func BenchmarkString(b *testing.B) {
	b.StopTimer()
	b.ReportAllocs()
	for _, tt := range urltests {
		u, err := Parse(tt.in)
		if err != nil {
			b.Errorf("Parse(%q) returned error %s", tt.in, err)
			continue
		}
		if tt.roundtrip == "" {
			continue
		}
		b.StartTimer()
		var g string
		for i := 0; i < b.N; i++ {
			g = u.String()
		}
		b.StopTimer()
626
		if w := tt.roundtrip; b.N > 0 && g != w {
627 628 629 630 631
			b.Errorf("Parse(%q).String() == %q, want %q", tt.in, g, w)
		}
	}
}

Rob Pike's avatar
Rob Pike committed
632
func TestParse(t *testing.T) {
633 634 635 636 637 638 639 640 641 642
	for _, tt := range urltests {
		u, err := Parse(tt.in)
		if err != nil {
			t.Errorf("Parse(%q) returned error %v", tt.in, err)
			continue
		}
		if !reflect.DeepEqual(u, tt.out) {
			t.Errorf("Parse(%q):\n\tgot  %v\n\twant %v\n", tt.in, ufmt(u), ufmt(tt.out))
		}
	}
643 644
}

645 646
const pathThatLooksSchemeRelative = "//not.a.user@not.a.host/just/a/path"

647
var parseRequestURLTests = []struct {
648 649 650 651 652 653 654 655 656
	url           string
	expectedValid bool
}{
	{"http://foo.com", true},
	{"http://foo.com/", true},
	{"http://foo.com/path", true},
	{"/", true},
	{pathThatLooksSchemeRelative, true},
	{"//not.a.user@%66%6f%6f.com/just/a/path/also", true},
657 658 659 660 661 662 663 664 665 666 667 668
	{"*", true},
	{"http://192.168.0.1/", true},
	{"http://192.168.0.1:8080/", true},
	{"http://[fe80::1]/", true},
	{"http://[fe80::1]:8080/", true},

	// Tests exercising RFC 6874 compliance:
	{"http://[fe80::1%25en0]/", true},                 // with alphanum zone identifier
	{"http://[fe80::1%25en0]:8080/", true},            // with alphanum zone identifier
	{"http://[fe80::1%25%65%6e%301-._~]/", true},      // with percent-encoded+unreserved zone identifier
	{"http://[fe80::1%25%65%6e%301-._~]:8080/", true}, // with percent-encoded+unreserved zone identifier

669 670
	{"foo.html", false},
	{"../dir/", false},
671 672 673 674 675 676 677 678 679 680 681 682 683
	{"http://192.168.0.%31/", false},
	{"http://192.168.0.%31:8080/", false},
	{"http://[fe80::%31]/", false},
	{"http://[fe80::%31]:8080/", false},
	{"http://[fe80::%31%25en0]/", false},
	{"http://[fe80::%31%25en0]:8080/", false},

	// These two cases are valid as textual representations as
	// described in RFC 4007, but are not valid as address
	// literals with IPv6 zone identifiers in URIs as described in
	// RFC 6874.
	{"http://[fe80::1%en0]/", false},
	{"http://[fe80::1%en0]:8080/", false},
684 685
}

Russ Cox's avatar
Russ Cox committed
686
func TestParseRequestURI(t *testing.T) {
687
	for _, test := range parseRequestURLTests {
Russ Cox's avatar
Russ Cox committed
688
		_, err := ParseRequestURI(test.url)
689 690 691 692
		if test.expectedValid && err != nil {
			t.Errorf("ParseRequestURI(%q) gave err %v; want no error", test.url, err)
		} else if !test.expectedValid && err == nil {
			t.Errorf("ParseRequestURI(%q) gave nil error; want some error", test.url)
693 694 695
		}
	}

Russ Cox's avatar
Russ Cox committed
696
	url, err := ParseRequestURI(pathThatLooksSchemeRelative)
697 698 699 700
	if err != nil {
		t.Fatalf("Unexpected error %v", err)
	}
	if url.Path != pathThatLooksSchemeRelative {
701
		t.Errorf("ParseRequestURI path:\ngot  %q\nwant %q", url.Path, pathThatLooksSchemeRelative)
702 703 704
	}
}

705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
var stringURLTests = []struct {
	url  URL
	want string
}{
	// No leading slash on path should prepend slash on String() call
	{
		url: URL{
			Scheme: "http",
			Host:   "www.google.com",
			Path:   "search",
		},
		want: "http://www.google.com/search",
	},
	// Relative path with first element containing ":" should be prepended with "./", golang.org/issue/17184
	{
		url: URL{
			Path: "this:that",
		},
		want: "./this:that",
	},
	// Relative path with second element containing ":" should not be prepended with "./"
	{
		url: URL{
			Path: "here/this:that",
		},
		want: "here/this:that",
	},
	// Non-relative path with first element containing ":" should not be prepended with "./"
	{
		url: URL{
			Scheme: "http",
			Host:   "www.google.com",
			Path:   "this:that",
		},
		want: "http://www.google.com/this:that",
	},
}

743 744 745
func TestURLString(t *testing.T) {
	for _, tt := range urltests {
		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
Steve Newman's avatar
Steve Newman committed
753
		}
754
		s := u.String()
Steve Newman's avatar
Steve Newman committed
755
		if s != expected {
756
			t.Errorf("Parse(%q).String() == %q (expected %q)", tt.in, s, expected)
757 758 759
		}
	}

760 761 762 763
	for _, tt := range stringURLTests {
		if got := tt.url.String(); got != tt.want {
			t.Errorf("%+v.String() = %q; want %q", tt.url, got, tt.want)
		}
764
	}
765
}
Steve Newman's avatar
Steve Newman committed
766

Rob Pike's avatar
Rob Pike committed
767
type EscapeTest struct {
768 769
	in  string
	out string
770
	err error
Steve Newman's avatar
Steve Newman committed
771 772
}

Rob Pike's avatar
Rob Pike committed
773
var unescapeTests = []EscapeTest{
Robert Griesemer's avatar
Robert Griesemer committed
774
	{
Steve Newman's avatar
Steve Newman committed
775 776
		"",
		"",
Robert Griesemer's avatar
Robert Griesemer committed
777
		nil,
Steve Newman's avatar
Steve Newman committed
778
	},
Robert Griesemer's avatar
Robert Griesemer committed
779
	{
Steve Newman's avatar
Steve Newman committed
780 781
		"abc",
		"abc",
Robert Griesemer's avatar
Robert Griesemer committed
782
		nil,
Steve Newman's avatar
Steve Newman committed
783
	},
Robert Griesemer's avatar
Robert Griesemer committed
784
	{
Steve Newman's avatar
Steve Newman committed
785 786
		"1%41",
		"1A",
Robert Griesemer's avatar
Robert Griesemer committed
787
		nil,
Steve Newman's avatar
Steve Newman committed
788
	},
Robert Griesemer's avatar
Robert Griesemer committed
789
	{
Steve Newman's avatar
Steve Newman committed
790 791
		"1%41%42%43",
		"1ABC",
Robert Griesemer's avatar
Robert Griesemer committed
792
		nil,
Steve Newman's avatar
Steve Newman committed
793
	},
Robert Griesemer's avatar
Robert Griesemer committed
794
	{
Steve Newman's avatar
Steve Newman committed
795 796
		"%4a",
		"J",
Robert Griesemer's avatar
Robert Griesemer committed
797
		nil,
Steve Newman's avatar
Steve Newman committed
798
	},
Robert Griesemer's avatar
Robert Griesemer committed
799
	{
Steve Newman's avatar
Steve Newman committed
800 801
		"%6F",
		"o",
Robert Griesemer's avatar
Robert Griesemer committed
802
		nil,
Steve Newman's avatar
Steve Newman committed
803
	},
Robert Griesemer's avatar
Robert Griesemer committed
804
	{
805
		"%", // not enough characters after %
Steve Newman's avatar
Steve Newman committed
806
		"",
Rob Pike's avatar
Rob Pike committed
807
		EscapeError("%"),
Steve Newman's avatar
Steve Newman committed
808
	},
Robert Griesemer's avatar
Robert Griesemer committed
809
	{
810
		"%a", // not enough characters after %
Steve Newman's avatar
Steve Newman committed
811
		"",
Rob Pike's avatar
Rob Pike committed
812
		EscapeError("%a"),
Steve Newman's avatar
Steve Newman committed
813
	},
Robert Griesemer's avatar
Robert Griesemer committed
814
	{
815
		"%1", // not enough characters after %
Steve Newman's avatar
Steve Newman committed
816
		"",
Rob Pike's avatar
Rob Pike committed
817
		EscapeError("%1"),
Steve Newman's avatar
Steve Newman committed
818
	},
Robert Griesemer's avatar
Robert Griesemer committed
819
	{
820
		"123%45%6", // not enough characters after %
Steve Newman's avatar
Steve Newman committed
821
		"",
Rob Pike's avatar
Rob Pike committed
822
		EscapeError("%6"),
Steve Newman's avatar
Steve Newman committed
823
	},
Robert Griesemer's avatar
Robert Griesemer committed
824
	{
825
		"%zzzzz", // invalid hex digits
Steve Newman's avatar
Steve Newman committed
826
		"",
Rob Pike's avatar
Rob Pike committed
827
		EscapeError("%zz"),
Steve Newman's avatar
Steve Newman committed
828
	},
829 830 831 832 833 834 835 836 837 838
	{
		"a+b",
		"a b",
		nil,
	},
	{
		"a%20b",
		"a b",
		nil,
	},
Steve Newman's avatar
Steve Newman committed
839 840
}

Rob Pike's avatar
Rob Pike committed
841
func TestUnescape(t *testing.T) {
Russ Cox's avatar
Russ Cox committed
842
	for _, tt := range unescapeTests {
Rob Pike's avatar
Rob Pike committed
843
		actual, err := QueryUnescape(tt.in)
Steve Newman's avatar
Steve Newman committed
844
		if actual != tt.out || (err != nil) != (tt.err != nil) {
Rob Pike's avatar
Rob Pike committed
845
			t.Errorf("QueryUnescape(%q) = %q, %s; want %q, %s", tt.in, actual, err, tt.out, tt.err)
Steve Newman's avatar
Steve Newman committed
846
		}
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869

		in := tt.in
		out := tt.out
		if strings.Contains(tt.in, "+") {
			in = strings.Replace(tt.in, "+", "%20", -1)
			actual, err := PathUnescape(in)
			if actual != tt.out || (err != nil) != (tt.err != nil) {
				t.Errorf("PathUnescape(%q) = %q, %s; want %q, %s", in, actual, err, tt.out, tt.err)
			}
			if tt.err == nil {
				s, err := QueryUnescape(strings.Replace(tt.in, "+", "XXX", -1))
				if err != nil {
					continue
				}
				in = tt.in
				out = strings.Replace(s, "XXX", "+", -1)
			}
		}

		actual, err = PathUnescape(in)
		if actual != out || (err != nil) != (tt.err != nil) {
			t.Errorf("PathUnescape(%q) = %q, %s; want %q, %s", in, actual, err, out, tt.err)
		}
Steve Newman's avatar
Steve Newman committed
870 871 872
	}
}

873
var queryEscapeTests = []EscapeTest{
Robert Griesemer's avatar
Robert Griesemer committed
874
	{
Steve Newman's avatar
Steve Newman committed
875 876
		"",
		"",
Robert Griesemer's avatar
Robert Griesemer committed
877
		nil,
Steve Newman's avatar
Steve Newman committed
878
	},
Robert Griesemer's avatar
Robert Griesemer committed
879
	{
Steve Newman's avatar
Steve Newman committed
880 881
		"abc",
		"abc",
Robert Griesemer's avatar
Robert Griesemer committed
882
		nil,
Steve Newman's avatar
Steve Newman committed
883
	},
Robert Griesemer's avatar
Robert Griesemer committed
884
	{
Steve Newman's avatar
Steve Newman committed
885 886
		"one two",
		"one+two",
Robert Griesemer's avatar
Robert Griesemer committed
887
		nil,
Steve Newman's avatar
Steve Newman committed
888
	},
Robert Griesemer's avatar
Robert Griesemer committed
889
	{
Steve Newman's avatar
Steve Newman committed
890 891
		"10%",
		"10%25",
Robert Griesemer's avatar
Robert Griesemer committed
892
		nil,
Steve Newman's avatar
Steve Newman committed
893
	},
Robert Griesemer's avatar
Robert Griesemer committed
894
	{
895 896
		" ?&=#+%!<>#\"{}|\\^[]`☺\t:/@$'()*,;",
		"+%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",
Robert Griesemer's avatar
Robert Griesemer committed
897
		nil,
Steve Newman's avatar
Steve Newman committed
898 899 900
	},
}

901 902
func TestQueryEscape(t *testing.T) {
	for _, tt := range queryEscapeTests {
Rob Pike's avatar
Rob Pike committed
903
		actual := QueryEscape(tt.in)
Steve Newman's avatar
Steve Newman committed
904
		if tt.out != actual {
Rob Pike's avatar
Rob Pike committed
905
			t.Errorf("QueryEscape(%q) = %q, want %q", tt.in, actual, tt.out)
Steve Newman's avatar
Steve Newman committed
906 907 908
		}

		// for bonus points, verify that escape:unescape is an identity.
Rob Pike's avatar
Rob Pike committed
909
		roundtrip, err := QueryUnescape(actual)
Steve Newman's avatar
Steve Newman committed
910
		if roundtrip != tt.in || err != nil {
Rob Pike's avatar
Rob Pike committed
911
			t.Errorf("QueryUnescape(%q) = %q, %s; want %q, %s", actual, roundtrip, err, tt.in, "[no error]")
Steve Newman's avatar
Steve Newman committed
912 913 914
		}
	}
}
915

916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
var pathEscapeTests = []EscapeTest{
	{
		"",
		"",
		nil,
	},
	{
		"abc",
		"abc",
		nil,
	},
	{
		"abc+def",
		"abc+def",
		nil,
	},
	{
		"one two",
		"one%20two",
		nil,
	},
	{
		"10%",
		"10%25",
		nil,
	},
	{
		" ?&=#+%!<>#\"{}|\\^[]`☺\t:/@$'()*,;",
		"%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",
		nil,
	},
}

func TestPathEscape(t *testing.T) {
	for _, tt := range pathEscapeTests {
		actual := PathEscape(tt.in)
		if tt.out != actual {
			t.Errorf("PathEscape(%q) = %q, want %q", tt.in, actual, tt.out)
		}

		// for bonus points, verify that escape:unescape is an identity.
		roundtrip, err := PathUnescape(actual)
		if roundtrip != tt.in || err != nil {
			t.Errorf("PathUnescape(%q) = %q, %s; want %q, %s", actual, roundtrip, err, tt.in, "[no error]")
		}
	}
}

964 965 966 967 968
//var userinfoTests = []UserinfoTest{
//	{"user", "password", "user:password"},
//	{"foo:bar", "~!@#$%^&*()_+{}|[]\\-=`:;'\"<>?,./",
//		"foo%3Abar:~!%40%23$%25%5E&*()_+%7B%7D%7C%5B%5D%5C-=%60%3A;'%22%3C%3E?,.%2F"},
//}
969 970

type EncodeQueryTest struct {
971 972
	m        Values
	expected string
973 974 975
}

var encodeQueryTests = []EncodeQueryTest{
976 977 978 979 980 981 982 983
	{nil, ""},
	{Values{"q": {"puppies"}, "oe": {"utf8"}}, "oe=utf8&q=puppies"},
	{Values{"q": {"dogs", "&", "7"}}, "q=dogs&q=%26&q=7"},
	{Values{
		"a": {"a1", "a2", "a3"},
		"b": {"b1", "b2", "b3"},
		"c": {"c1", "c2", "c3"},
	}, "a=a1&a=a2&a=a3&b=b1&b=b2&b=b3&c=c1&c=c2&c=c3"},
984 985 986 987
}

func TestEncodeQuery(t *testing.T) {
	for _, tt := range encodeQueryTests {
988
		if q := tt.m.Encode(); q != tt.expected {
989 990 991 992
			t.Errorf(`EncodeQuery(%+v) = %q, want %q`, tt.m, q, tt.expected)
		}
	}
}
993 994 995 996

var resolvePathTests = []struct {
	base, ref, expected string
}{
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
	{"a/b", ".", "/a/"},
	{"a/b", "c", "/a/c"},
	{"a/b", "..", "/"},
	{"a/", "..", "/"},
	{"a/", "../..", "/"},
	{"a/b/c", "..", "/a/"},
	{"a/b/c", "../d", "/a/d"},
	{"a/b/c", ".././d", "/a/d"},
	{"a/b", "./..", "/"},
	{"a/./b", ".", "/a/"},
	{"a/../", ".", "/"},
	{"a/.././b", "c", "/c"},
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
}

func TestResolvePath(t *testing.T) {
	for _, test := range resolvePathTests {
		got := resolvePath(test.base, test.ref)
		if got != test.expected {
			t.Errorf("For %q + %q got %q; expected %q", test.base, test.ref, got, test.expected)
		}
	}
}

var resolveReferenceTests = []struct {
	base, rel, expected string
}{
	// Absolute URL references
	{"http://foo.com?a=b", "https://bar.com/", "https://bar.com/"},
	{"http://foo.com/", "https://bar.com/?a=b", "https://bar.com/?a=b"},
1026
	{"http://foo.com/", "https://bar.com/?", "https://bar.com/?"},
1027 1028 1029 1030 1031
	{"http://foo.com/bar", "mailto:foo@example.com", "mailto:foo@example.com"},

	// Path-absolute references
	{"http://foo.com/bar", "/baz", "http://foo.com/baz"},
	{"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 1034
	{"http://foo.com/bar?a=b", "/baz?c=d", "http://foo.com/baz?c=d"},

1035 1036 1037 1038
	// Multiple slashes
	{"http://foo.com/bar", "http://foo.com//baz", "http://foo.com//baz"},
	{"http://foo.com/bar", "http://foo.com///baz/quux", "http://foo.com///baz/quux"},

1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
	// Scheme-relative
	{"https://foo.com/bar?a=b", "//bar.com/quux", "https://bar.com/quux"},

	// Path-relative references:

	// ... current directory
	{"http://foo.com", ".", "http://foo.com/"},
	{"http://foo.com/bar", ".", "http://foo.com/"},
	{"http://foo.com/bar/", ".", "http://foo.com/bar/"},

	// ... going down
	{"http://foo.com", "bar", "http://foo.com/bar"},
	{"http://foo.com/", "bar", "http://foo.com/bar"},
	{"http://foo.com/bar/baz", "quux", "http://foo.com/bar/quux"},

	// ... going up
	{"http://foo.com/bar/baz", "../quux", "http://foo.com/quux"},
	{"http://foo.com/bar/baz", "../../../../../quux", "http://foo.com/quux"},
	{"http://foo.com/bar", "..", "http://foo.com/"},
	{"http://foo.com/bar/baz", "./..", "http://foo.com/"},
1059 1060 1061 1062 1063 1064 1065 1066
	// ".." in the middle (issue 3560)
	{"http://foo.com/bar/baz", "quux/dotdot/../tail", "http://foo.com/bar/quux/tail"},
	{"http://foo.com/bar/baz", "quux/./dotdot/../tail", "http://foo.com/bar/quux/tail"},
	{"http://foo.com/bar/baz", "quux/./dotdot/.././tail", "http://foo.com/bar/quux/tail"},
	{"http://foo.com/bar/baz", "quux/./dotdot/./../tail", "http://foo.com/bar/quux/tail"},
	{"http://foo.com/bar/baz", "quux/./dotdot/dotdot/././../../tail", "http://foo.com/bar/quux/tail"},
	{"http://foo.com/bar/baz", "quux/./dotdot/dotdot/./.././../tail", "http://foo.com/bar/quux/tail"},
	{"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 1070 1071
	// Remove any dot-segments prior to forming the target URI.
	// http://tools.ietf.org/html/rfc3986#section-5.2.4
	{"http://foo.com/dot/./dotdot/../foo/bar", "../baz", "http://foo.com/dot/baz"},
1072 1073 1074 1075 1076 1077

	// Triple dot isn't special
	{"http://foo.com/bar", "...", "http://foo.com/..."},

	// Fragment
	{"http://foo.com/bar", ".#frag", "http://foo.com/#frag"},
1078

1079 1080 1081 1082 1083 1084 1085 1086 1087
	// Paths with escaping (issue 16947).
	{"http://foo.com/foo%2fbar/", "../baz", "http://foo.com/baz"},
	{"http://foo.com/1/2%2f/3%2f4/5", "../../a/b/c", "http://foo.com/1/a/b/c"},
	{"http://foo.com/1/2/3", "./a%2f../../b/..%2fc", "http://foo.com/1/2/b/..%2fc"},
	{"http://foo.com/1/2%2f/3%2f4/5", "./a%2f../b/../c", "http://foo.com/1/2%2f/3%2f4/a%2f../c"},
	{"http://foo.com/foo%20bar/", "../baz", "http://foo.com/baz"},
	{"http://foo.com/foo", "../bar%2fbaz", "http://foo.com/bar%2fbaz"},
	{"http://foo.com/foo%2dbar/", "./baz-quux", "http://foo.com/foo%2dbar/baz-quux"},

1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
	// RFC 3986: Normal Examples
	// http://tools.ietf.org/html/rfc3986#section-5.4.1
	{"http://a/b/c/d;p?q", "g:h", "g:h"},
	{"http://a/b/c/d;p?q", "g", "http://a/b/c/g"},
	{"http://a/b/c/d;p?q", "./g", "http://a/b/c/g"},
	{"http://a/b/c/d;p?q", "g/", "http://a/b/c/g/"},
	{"http://a/b/c/d;p?q", "/g", "http://a/g"},
	{"http://a/b/c/d;p?q", "//g", "http://g"},
	{"http://a/b/c/d;p?q", "?y", "http://a/b/c/d;p?y"},
	{"http://a/b/c/d;p?q", "g?y", "http://a/b/c/g?y"},
	{"http://a/b/c/d;p?q", "#s", "http://a/b/c/d;p?q#s"},
	{"http://a/b/c/d;p?q", "g#s", "http://a/b/c/g#s"},
	{"http://a/b/c/d;p?q", "g?y#s", "http://a/b/c/g?y#s"},
	{"http://a/b/c/d;p?q", ";x", "http://a/b/c/;x"},
	{"http://a/b/c/d;p?q", "g;x", "http://a/b/c/g;x"},
	{"http://a/b/c/d;p?q", "g;x?y#s", "http://a/b/c/g;x?y#s"},
	{"http://a/b/c/d;p?q", "", "http://a/b/c/d;p?q"},
	{"http://a/b/c/d;p?q", ".", "http://a/b/c/"},
	{"http://a/b/c/d;p?q", "./", "http://a/b/c/"},
	{"http://a/b/c/d;p?q", "..", "http://a/b/"},
	{"http://a/b/c/d;p?q", "../", "http://a/b/"},
	{"http://a/b/c/d;p?q", "../g", "http://a/b/g"},
	{"http://a/b/c/d;p?q", "../..", "http://a/"},
	{"http://a/b/c/d;p?q", "../../", "http://a/"},
	{"http://a/b/c/d;p?q", "../../g", "http://a/g"},

	// RFC 3986: Abnormal Examples
	// http://tools.ietf.org/html/rfc3986#section-5.4.2
	{"http://a/b/c/d;p?q", "../../../g", "http://a/g"},
	{"http://a/b/c/d;p?q", "../../../../g", "http://a/g"},
	{"http://a/b/c/d;p?q", "/./g", "http://a/g"},
	{"http://a/b/c/d;p?q", "/../g", "http://a/g"},
	{"http://a/b/c/d;p?q", "g.", "http://a/b/c/g."},
	{"http://a/b/c/d;p?q", ".g", "http://a/b/c/.g"},
	{"http://a/b/c/d;p?q", "g..", "http://a/b/c/g.."},
	{"http://a/b/c/d;p?q", "..g", "http://a/b/c/..g"},
	{"http://a/b/c/d;p?q", "./../g", "http://a/b/g"},
	{"http://a/b/c/d;p?q", "./g/.", "http://a/b/c/g/"},
	{"http://a/b/c/d;p?q", "g/./h", "http://a/b/c/g/h"},
	{"http://a/b/c/d;p?q", "g/../h", "http://a/b/c/h"},
	{"http://a/b/c/d;p?q", "g;x=1/./y", "http://a/b/c/g;x=1/y"},
	{"http://a/b/c/d;p?q", "g;x=1/../y", "http://a/b/c/y"},
	{"http://a/b/c/d;p?q", "g?y/./x", "http://a/b/c/g?y/./x"},
	{"http://a/b/c/d;p?q", "g?y/../x", "http://a/b/c/g?y/../x"},
	{"http://a/b/c/d;p?q", "g#s/./x", "http://a/b/c/g#s/./x"},
	{"http://a/b/c/d;p?q", "g#s/../x", "http://a/b/c/g#s/../x"},

	// Extras.
	{"https://a/b/c/d;p?q", "//g?q", "https://g?q"},
	{"https://a/b/c/d;p?q", "//g#s", "https://g#s"},
	{"https://a/b/c/d;p?q", "//g/d/e/f?y#s", "https://g/d/e/f?y#s"},
	{"https://a/b/c/d;p#s", "?y", "https://a/b/c/d;p?y"},
	{"https://a/b/c/d;p?q#s", "?y", "https://a/b/c/d;p?y"},
1141 1142 1143
}

func TestResolveReference(t *testing.T) {
Rob Pike's avatar
Rob Pike committed
1144
	mustParse := func(url string) *URL {
Russ Cox's avatar
Russ Cox committed
1145
		u, err := Parse(url)
1146
		if err != nil {
1147
			t.Fatalf("Parse(%q) got err %v", url, err)
1148 1149 1150
		}
		return u
	}
1151
	opaque := &URL{Scheme: "scheme", Opaque: "opaque"}
1152
	for _, test := range resolveReferenceTests {
Rob Pike's avatar
Rob Pike committed
1153 1154
		base := mustParse(test.base)
		rel := mustParse(test.rel)
1155
		url := base.ResolveReference(rel)
1156 1157
		if got := url.String(); got != test.expected {
			t.Errorf("URL(%q).ResolveReference(%q)\ngot  %q\nwant %q", test.base, test.rel, got, test.expected)
1158
		}
1159 1160 1161 1162 1163 1164
		// Ensure that new instances are returned.
		if base == url {
			t.Errorf("Expected URL.ResolveReference to return new URL instance.")
		}
		// Test the convenience wrapper too.
		url, err := base.Parse(test.rel)
1165
		if err != nil {
1166
			t.Errorf("URL(%q).Parse(%q) failed: %v", test.base, test.rel, err)
1167 1168
		} else if got := url.String(); got != test.expected {
			t.Errorf("URL(%q).Parse(%q)\ngot  %q\nwant %q", test.base, test.rel, got, test.expected)
1169 1170 1171
		} else if base == url {
			// Ensure that new instances are returned for the wrapper too.
			t.Errorf("Expected URL.Parse to return new URL instance.")
1172
		}
1173 1174 1175
		// Ensure Opaque resets the URL.
		url = base.ResolveReference(opaque)
		if *url != *opaque {
1176
			t.Errorf("ResolveReference failed to resolve opaque URL:\ngot  %#v\nwant %#v", url, opaque)
1177 1178 1179 1180 1181 1182
		}
		// Test the convenience wrapper with an opaque URL too.
		url, err = base.Parse("scheme:opaque")
		if err != nil {
			t.Errorf(`URL(%q).Parse("scheme:opaque") failed: %v`, test.base, err)
		} else if *url != *opaque {
1183
			t.Errorf("Parse failed to resolve opaque URL:\ngot  %#v\nwant %#v", opaque, url)
1184 1185 1186
		} else if base == url {
			// Ensure that new instances are returned, again.
			t.Errorf("Expected URL.Parse to return new URL instance.")
1187 1188
		}
	}
1189
}
1190 1191

func TestQueryValues(t *testing.T) {
Rob Pike's avatar
Rob Pike committed
1192
	u, _ := Parse("http://x.com?foo=bar&bar=1&bar=2")
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
	v := u.Query()
	if len(v) != 2 {
		t.Errorf("got %d keys in Query values, want 2", len(v))
	}
	if g, e := v.Get("foo"), "bar"; g != e {
		t.Errorf("Get(foo) = %q, want %q", g, e)
	}
	// Case sensitive:
	if g, e := v.Get("Foo"), ""; g != e {
		t.Errorf("Get(Foo) = %q, want %q", g, e)
	}
	if g, e := v.Get("bar"), "1"; g != e {
		t.Errorf("Get(bar) = %q, want %q", g, e)
	}
	if g, e := v.Get("baz"), ""; g != e {
		t.Errorf("Get(baz) = %q, want %q", g, e)
	}
	v.Del("bar")
	if g, e := v.Get("bar"), ""; g != e {
		t.Errorf("second Get(bar) = %q, want %q", g, e)
	}
}
Russ Cox's avatar
Russ Cox committed
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271

type parseTest struct {
	query string
	out   Values
}

var parseTests = []parseTest{
	{
		query: "a=1&b=2",
		out:   Values{"a": []string{"1"}, "b": []string{"2"}},
	},
	{
		query: "a=1&a=2&a=banana",
		out:   Values{"a": []string{"1", "2", "banana"}},
	},
	{
		query: "ascii=%3Ckey%3A+0x90%3E",
		out:   Values{"ascii": []string{"<key: 0x90>"}},
	},
	{
		query: "a=1;b=2",
		out:   Values{"a": []string{"1"}, "b": []string{"2"}},
	},
	{
		query: "a=1&a=2;a=banana",
		out:   Values{"a": []string{"1", "2", "banana"}},
	},
}

func TestParseQuery(t *testing.T) {
	for i, test := range parseTests {
		form, err := ParseQuery(test.query)
		if err != nil {
			t.Errorf("test %d: Unexpected error: %v", i, err)
			continue
		}
		if len(form) != len(test.out) {
			t.Errorf("test %d: len(form) = %d, want %d", i, len(form), len(test.out))
		}
		for k, evs := range test.out {
			vs, ok := form[k]
			if !ok {
				t.Errorf("test %d: Missing key %q", i, k)
				continue
			}
			if len(vs) != len(evs) {
				t.Errorf("test %d: len(form[%q]) = %d, want %d", i, k, len(vs), len(evs))
				continue
			}
			for j, ev := range evs {
				if v := vs[j]; v != ev {
					t.Errorf("test %d: form[%q][%d] = %q, want %q", i, k, j, v, ev)
				}
			}
		}
	}
}
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294

type RequestURITest struct {
	url *URL
	out string
}

var requritests = []RequestURITest{
	{
		&URL{
			Scheme: "http",
			Host:   "example.com",
			Path:   "",
		},
		"/",
	},
	{
		&URL{
			Scheme: "http",
			Host:   "example.com",
			Path:   "/a b",
		},
		"/a%20b",
	},
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
	// golang.org/issue/4860 variant 1
	{
		&URL{
			Scheme: "http",
			Host:   "example.com",
			Opaque: "/%2F/%2F/",
		},
		"/%2F/%2F/",
	},
	// golang.org/issue/4860 variant 2
	{
		&URL{
			Scheme: "http",
			Host:   "example.com",
			Opaque: "//other.example.com/%2F/%2F/",
		},
		"http://other.example.com/%2F/%2F/",
	},
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
	// better fix for issue 4860
	{
		&URL{
			Scheme:  "http",
			Host:    "example.com",
			Path:    "/////",
			RawPath: "/%2F/%2F/",
		},
		"/%2F/%2F/",
	},
	{
		&URL{
			Scheme:  "http",
			Host:    "example.com",
			Path:    "/////",
			RawPath: "/WRONG/", // ignored because doesn't match Path
		},
		"/////",
	},
1332 1333 1334 1335 1336 1337 1338 1339 1340
	{
		&URL{
			Scheme:   "http",
			Host:     "example.com",
			Path:     "/a b",
			RawQuery: "q=go+language",
		},
		"/a%20b?q=go+language",
	},
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
	{
		&URL{
			Scheme:   "http",
			Host:     "example.com",
			Path:     "/a b",
			RawPath:  "/a b", // ignored because invalid
			RawQuery: "q=go+language",
		},
		"/a%20b?q=go+language",
	},
	{
		&URL{
			Scheme:   "http",
			Host:     "example.com",
			Path:     "/a?b",
			RawPath:  "/a?b", // ignored because invalid
			RawQuery: "q=go+language",
		},
		"/a%3Fb?q=go+language",
	},
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
	{
		&URL{
			Scheme: "myschema",
			Opaque: "opaque",
		},
		"opaque",
	},
	{
		&URL{
			Scheme:   "myschema",
			Opaque:   "opaque",
			RawQuery: "q=go+language",
		},
		"opaque?q=go+language",
	},
1376 1377 1378 1379 1380 1381 1382 1383
	{
		&URL{
			Scheme: "http",
			Host:   "example.com",
			Path:   "//foo",
		},
		"//foo",
	},
1384 1385 1386 1387 1388 1389 1390 1391 1392
	{
		&URL{
			Scheme:     "http",
			Host:       "example.com",
			Path:       "/foo",
			ForceQuery: true,
		},
		"/foo?",
	},
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
}

func TestRequestURI(t *testing.T) {
	for _, tt := range requritests {
		s := tt.url.RequestURI()
		if s != tt.out {
			t.Errorf("%#v.RequestURI() == %q (expected %q)", tt.url, s, tt.out)
		}
	}
}
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412

func TestParseFailure(t *testing.T) {
	// Test that the first parse error is returned.
	const url = "%gh&%ij"
	_, err := ParseQuery(url)
	errStr := fmt.Sprint(err)
	if !strings.Contains(errStr, "%gh") {
		t.Errorf(`ParseQuery(%q) returned error %q, want something containing %q"`, url, errStr, "%gh")
	}
}
1413

1414
func TestParseErrors(t *testing.T) {
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
	tests := []struct {
		in      string
		wantErr bool
	}{
		{"http://[::1]", false},
		{"http://[::1]:80", false},
		{"http://[::1]:namedport", true}, // rfc3986 3.2.3
		{"http://[::1]/", false},
		{"http://[::1]a", true},
		{"http://[::1]%23", true},
1425
		{"http://[::1%25en0]", false},     // valid zone id
1426
		{"http://[::1]:", false},          // colon, but no port OK
1427 1428
		{"http://[::1]:%38%30", true},     // not allowed: % encoding only for non-ASCII
		{"http://[::1%25%41]", false},     // RFC 6874 allows over-escaping in zone
1429 1430
		{"http://[%10::1]", true},         // no %xx escapes in IP address
		{"http://[::1]/%48", false},       // %xx in path is fine
1431
		{"http://%41:8080/", true},        // not allowed: % encoding only for non-ASCII
1432 1433
		{"mysql://x@y(z:123)/foo", false}, // golang.org/issue/12023
		{"mysql://x@y(1.2.3.4:123)/foo", false},
1434

1435
		{"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
1436
		{"http://a b.com/", true},                                                                       // no space in host name please
1437 1438 1439 1440
		{"cache_object://foo", true},                                                                    // scheme cannot have _, relative path cannot have : in first segment
		{"cache_object:foo", true},
		{"cache_object:foo/bar", true},
		{"cache_object/:foo/bar", false},
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
	}
	for _, tt := range tests {
		u, err := Parse(tt.in)
		if tt.wantErr {
			if err == nil {
				t.Errorf("Parse(%q) = %#v; want an error", tt.in, u)
			}
			continue
		}
		if err != nil {
			t.Logf("Parse(%q) = %v; want no error", tt.in, err)
		}
	}
}

1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
// Issue 11202
func TestStarRequest(t *testing.T) {
	u, err := Parse("*")
	if err != nil {
		t.Fatal(err)
	}
	if got, want := u.RequestURI(), "*"; got != want {
		t.Errorf("RequestURI = %q; want %q", got, want)
	}
}

1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
type shouldEscapeTest struct {
	in     byte
	mode   encoding
	escape bool
}

var shouldEscapeTests = []shouldEscapeTest{
	// Unreserved characters (§2.3)
	{'a', encodePath, false},
	{'a', encodeUserPassword, false},
	{'a', encodeQueryComponent, false},
	{'a', encodeFragment, false},
1479
	{'a', encodeHost, false},
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
	{'z', encodePath, false},
	{'A', encodePath, false},
	{'Z', encodePath, false},
	{'0', encodePath, false},
	{'9', encodePath, false},
	{'-', encodePath, false},
	{'-', encodeUserPassword, false},
	{'-', encodeQueryComponent, false},
	{'-', encodeFragment, false},
	{'.', encodePath, false},
	{'_', encodePath, false},
	{'~', encodePath, false},

	// User information (§3.2.1)
	{':', encodeUserPassword, true},
	{'/', encodeUserPassword, true},
	{'?', encodeUserPassword, true},
	{'@', encodeUserPassword, true},
	{'$', encodeUserPassword, false},
	{'&', encodeUserPassword, false},
	{'+', encodeUserPassword, false},
	{',', encodeUserPassword, false},
	{';', encodeUserPassword, false},
	{'=', encodeUserPassword, false},
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526

	// Host (IP address, IPv6 address, registered name, port suffix; §3.2.2)
	{'!', encodeHost, false},
	{'$', encodeHost, false},
	{'&', encodeHost, false},
	{'\'', encodeHost, false},
	{'(', encodeHost, false},
	{')', encodeHost, false},
	{'*', encodeHost, false},
	{'+', encodeHost, false},
	{',', encodeHost, false},
	{';', encodeHost, false},
	{'=', encodeHost, false},
	{':', encodeHost, false},
	{'[', encodeHost, false},
	{']', encodeHost, false},
	{'0', encodeHost, false},
	{'9', encodeHost, false},
	{'A', encodeHost, false},
	{'z', encodeHost, false},
	{'_', encodeHost, false},
	{'-', encodeHost, false},
	{'.', encodeHost, false},
1527 1528 1529 1530 1531 1532 1533 1534 1535
}

func TestShouldEscape(t *testing.T) {
	for _, tt := range shouldEscapeTests {
		if shouldEscape(tt.in, tt.mode) != tt.escape {
			t.Errorf("shouldEscape(%q, %v) returned %v; expected %v", tt.in, tt.mode, !tt.escape, tt.escape)
		}
	}
}
1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608

type timeoutError struct {
	timeout bool
}

func (e *timeoutError) Error() string { return "timeout error" }
func (e *timeoutError) Timeout() bool { return e.timeout }

type temporaryError struct {
	temporary bool
}

func (e *temporaryError) Error() string   { return "temporary error" }
func (e *temporaryError) Temporary() bool { return e.temporary }

type timeoutTemporaryError struct {
	timeoutError
	temporaryError
}

func (e *timeoutTemporaryError) Error() string { return "timeout/temporary error" }

var netErrorTests = []struct {
	err       error
	timeout   bool
	temporary bool
}{{
	err:       &Error{"Get", "http://google.com/", &timeoutError{timeout: true}},
	timeout:   true,
	temporary: false,
}, {
	err:       &Error{"Get", "http://google.com/", &timeoutError{timeout: false}},
	timeout:   false,
	temporary: false,
}, {
	err:       &Error{"Get", "http://google.com/", &temporaryError{temporary: true}},
	timeout:   false,
	temporary: true,
}, {
	err:       &Error{"Get", "http://google.com/", &temporaryError{temporary: false}},
	timeout:   false,
	temporary: false,
}, {
	err:       &Error{"Get", "http://google.com/", &timeoutTemporaryError{timeoutError{timeout: true}, temporaryError{temporary: true}}},
	timeout:   true,
	temporary: true,
}, {
	err:       &Error{"Get", "http://google.com/", &timeoutTemporaryError{timeoutError{timeout: false}, temporaryError{temporary: true}}},
	timeout:   false,
	temporary: true,
}, {
	err:       &Error{"Get", "http://google.com/", &timeoutTemporaryError{timeoutError{timeout: true}, temporaryError{temporary: false}}},
	timeout:   true,
	temporary: false,
}, {
	err:       &Error{"Get", "http://google.com/", &timeoutTemporaryError{timeoutError{timeout: false}, temporaryError{temporary: false}}},
	timeout:   false,
	temporary: false,
}, {
	err:       &Error{"Get", "http://google.com/", io.EOF},
	timeout:   false,
	temporary: false,
}}

// Test that url.Error implements net.Error and that it forwards
func TestURLErrorImplementsNetError(t *testing.T) {
	for i, tt := range netErrorTests {
		err, ok := tt.err.(net.Error)
		if !ok {
			t.Errorf("%d: %T does not implement net.Error", i+1, tt.err)
			continue
		}
		if err.Timeout() != tt.timeout {
1609
			t.Errorf("%d: err.Timeout(): got %v, want %v", i+1, err.Timeout(), tt.timeout)
1610 1611 1612
			continue
		}
		if err.Temporary() != tt.temporary {
1613
			t.Errorf("%d: err.Temporary(): got %v, want %v", i+1, err.Temporary(), tt.temporary)
1614 1615 1616
		}
	}
}
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660

func TestURLHostname(t *testing.T) {
	tests := []struct {
		host string // URL.Host field
		want string
	}{
		{"foo.com:80", "foo.com"},
		{"foo.com", "foo.com"},
		{"FOO.COM", "FOO.COM"}, // no canonicalization (yet?)
		{"1.2.3.4", "1.2.3.4"},
		{"1.2.3.4:80", "1.2.3.4"},
		{"[1:2:3:4]", "1:2:3:4"},
		{"[1:2:3:4]:80", "1:2:3:4"},
		{"[::1]:80", "::1"},
	}
	for _, tt := range tests {
		u := &URL{Host: tt.host}
		got := u.Hostname()
		if got != tt.want {
			t.Errorf("Hostname for Host %q = %q; want %q", tt.host, got, tt.want)
		}
	}
}

func TestURLPort(t *testing.T) {
	tests := []struct {
		host string // URL.Host field
		want string
	}{
		{"foo.com", ""},
		{"foo.com:80", "80"},
		{"1.2.3.4", ""},
		{"1.2.3.4:80", "80"},
		{"[1:2:3:4]", ""},
		{"[1:2:3:4]:80", "80"},
	}
	for _, tt := range tests {
		u := &URL{Host: tt.host}
		got := u.Port()
		if got != tt.want {
			t.Errorf("Port for Host %q = %q; want %q", tt.host, got, tt.want)
		}
	}
}
1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711

var _ encodingPkg.BinaryMarshaler = (*URL)(nil)
var _ encodingPkg.BinaryUnmarshaler = (*URL)(nil)

func TestJSON(t *testing.T) {
	u, err := Parse("https://www.google.com/x?y=z")
	if err != nil {
		t.Fatal(err)
	}
	js, err := json.Marshal(u)
	if err != nil {
		t.Fatal(err)
	}

	// If only we could implement TextMarshaler/TextUnmarshaler,
	// this would work:
	//
	// if string(js) != strconv.Quote(u.String()) {
	// 	t.Errorf("json encoding: %s\nwant: %s\n", js, strconv.Quote(u.String()))
	// }

	u1 := new(URL)
	err = json.Unmarshal(js, u1)
	if err != nil {
		t.Fatal(err)
	}
	if u1.String() != u.String() {
		t.Errorf("json decoded to: %s\nwant: %s\n", u1, u)
	}
}

func TestGob(t *testing.T) {
	u, err := Parse("https://www.google.com/x?y=z")
	if err != nil {
		t.Fatal(err)
	}
	var w bytes.Buffer
	err = gob.NewEncoder(&w).Encode(u)
	if err != nil {
		t.Fatal(err)
	}

	u1 := new(URL)
	err = gob.NewDecoder(&w).Decode(u1)
	if err != nil {
		t.Fatal(err)
	}
	if u1.String() != u.String() {
		t.Errorf("json decoded to: %s\nwant: %s\n", u1, u)
	}
}
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737

func TestNilUser(t *testing.T) {
	defer func() {
		if v := recover(); v != nil {
			t.Fatalf("unexpected panic: %v", v)
		}
	}()

	u, err := Parse("http://foo.com/")

	if err != nil {
		t.Fatalf("parse err: %v", err)
	}

	if v := u.User.Username(); v != "" {
		t.Fatalf("expected empty username, got %s", v)
	}

	if v, ok := u.User.Password(); v != "" || ok {
		t.Fatalf("expected empty password, got %s (%v)", v, ok)
	}

	if v := u.User.String(); v != "" {
		t.Fatalf("expected empty string, got %s", v)
	}
}