github.com/gogf/gf@v1.16.9/encoding/gbase64/gbase64_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 7 package gbase64_test 8 9 import ( 10 "github.com/gogf/gf/debug/gdebug" 11 "testing" 12 13 "github.com/gogf/gf/encoding/gbase64" 14 "github.com/gogf/gf/test/gtest" 15 ) 16 17 type testPair struct { 18 decoded, encoded string 19 } 20 21 var pairs = []testPair{ 22 // RFC 3548 examples 23 {"\x14\xfb\x9c\x03\xd9\x7e", "FPucA9l+"}, 24 {"\x14\xfb\x9c\x03\xd9", "FPucA9k="}, 25 {"\x14\xfb\x9c\x03", "FPucAw=="}, 26 27 // RFC 4648 examples 28 {"", ""}, 29 {"f", "Zg=="}, 30 {"fo", "Zm8="}, 31 {"foo", "Zm9v"}, 32 {"foob", "Zm9vYg=="}, 33 {"fooba", "Zm9vYmE="}, 34 {"foobar", "Zm9vYmFy"}, 35 36 // Wikipedia examples 37 {"sure.", "c3VyZS4="}, 38 {"sure", "c3VyZQ=="}, 39 {"sur", "c3Vy"}, 40 {"su", "c3U="}, 41 {"leasure.", "bGVhc3VyZS4="}, 42 {"easure.", "ZWFzdXJlLg=="}, 43 {"asure.", "YXN1cmUu"}, 44 {"sure.", "c3VyZS4="}, 45 } 46 47 func Test_Basic(t *testing.T) { 48 gtest.C(t, func(t *gtest.T) { 49 for k := range pairs { 50 // Encode 51 t.Assert(gbase64.Encode([]byte(pairs[k].decoded)), []byte(pairs[k].encoded)) 52 t.Assert(gbase64.EncodeToString([]byte(pairs[k].decoded)), pairs[k].encoded) 53 t.Assert(gbase64.EncodeString(pairs[k].decoded), pairs[k].encoded) 54 55 // Decode 56 r1, _ := gbase64.Decode([]byte(pairs[k].encoded)) 57 t.Assert(r1, []byte(pairs[k].decoded)) 58 59 r2, _ := gbase64.DecodeString(pairs[k].encoded) 60 t.Assert(r2, []byte(pairs[k].decoded)) 61 62 r3, _ := gbase64.DecodeToString(pairs[k].encoded) 63 t.Assert(r3, pairs[k].decoded) 64 } 65 }) 66 } 67 68 func Test_File(t *testing.T) { 69 path := gdebug.TestDataPath("test") 70 expect := "dGVzdA==" 71 gtest.C(t, func(t *gtest.T) { 72 b, err := gbase64.EncodeFile(path) 73 t.Assert(err, nil) 74 t.Assert(string(b), expect) 75 }) 76 gtest.C(t, func(t *gtest.T) { 77 s, err := gbase64.EncodeFileToString(path) 78 t.Assert(err, nil) 79 t.Assert(s, expect) 80 }) 81 } 82 83 func Test_File_Error(t *testing.T) { 84 path := "none-exist-file" 85 expect := "" 86 gtest.C(t, func(t *gtest.T) { 87 b, err := gbase64.EncodeFile(path) 88 t.AssertNE(err, nil) 89 t.Assert(string(b), expect) 90 }) 91 gtest.C(t, func(t *gtest.T) { 92 s, err := gbase64.EncodeFileToString(path) 93 t.AssertNE(err, nil) 94 t.Assert(s, expect) 95 }) 96 }