Debian Codegraph @

src/net/url/url_test.go

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