github.com/gogf/gf@v1.16.9/encoding/gurl/url_test.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 package gurl_test 7 8 import ( 9 "net/url" 10 "testing" 11 12 "github.com/gogf/gf/encoding/gurl" 13 "github.com/gogf/gf/test/gtest" 14 ) 15 16 var urlStr string = `https://golang.org/x/crypto?go-get=1 +` 17 var urlEncode string = `https%3A%2F%2Fgolang.org%2Fx%2Fcrypto%3Fgo-get%3D1+%2B` 18 var rawUrlEncode string = `https%3A%2F%2Fgolang.org%2Fx%2Fcrypto%3Fgo-get%3D1%20%2B` 19 20 func TestEncodeAndDecode(t *testing.T) { 21 gtest.C(t, func(t *gtest.T) { 22 t.Assert(gurl.Encode(urlStr), urlEncode) 23 24 res, err := gurl.Decode(urlEncode) 25 if err != nil { 26 t.Errorf("decode failed. %v", err) 27 return 28 } 29 t.Assert(res, urlStr) 30 }) 31 } 32 33 func TestRowEncodeAndDecode(t *testing.T) { 34 gtest.C(t, func(t *gtest.T) { 35 t.Assert(gurl.RawEncode(urlStr), rawUrlEncode) 36 37 res, err := gurl.RawDecode(rawUrlEncode) 38 if err != nil { 39 t.Errorf("decode failed. %v", err) 40 return 41 } 42 t.Assert(res, urlStr) 43 }) 44 } 45 46 func TestBuildQuery(t *testing.T) { 47 gtest.C(t, func(t *gtest.T) { 48 src := url.Values{ 49 "a": {"a2", "a1"}, 50 "b": {"b2", "b1"}, 51 "c": {"c1", "c2"}, 52 } 53 expect := "a=a2&a=a1&b=b2&b=b1&c=c1&c=c2" 54 t.Assert(gurl.BuildQuery(src), expect) 55 }) 56 } 57 58 func TestParseURL(t *testing.T) { 59 src := `http://username:password@hostname:9090/path?arg=value#anchor` 60 expect := map[string]string{ 61 "scheme": "http", 62 "host": "hostname", 63 "port": "9090", 64 "user": "username", 65 "pass": "password", 66 "path": "/path", 67 "query": "arg=value", 68 "fragment": "anchor", 69 } 70 71 gtest.C(t, func(t *gtest.T) { 72 component := 0 73 for k, v := range []string{"all", "scheme", "host", "port", "user", "pass", "path", "query", "fragment"} { 74 if v == "all" { 75 component = -1 76 } else { 77 component = 1 << (uint(k - 1)) 78 } 79 80 res, err := gurl.ParseURL(src, component) 81 if err != nil { 82 t.Errorf("ParseURL failed. component:%v, err:%v", component, err) 83 return 84 } 85 86 if v == "all" { 87 t.Assert(res, expect) 88 } else { 89 t.Assert(res[v], expect[v]) 90 } 91 92 } 93 }) 94 }