encoding_test.go (2697B)
1 // Copyright 2020 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package encoding
15
16 import (
17 "html/template"
18 "math"
19 "testing"
20
21 qt "github.com/frankban/quicktest"
22 )
23
24 type tstNoStringer struct{}
25
26 func TestBase64Decode(t *testing.T) {
27 t.Parallel()
28 c := qt.New(t)
29
30 ns := New()
31
32 for _, test := range []struct {
33 v any
34 expect any
35 }{
36 {"YWJjMTIzIT8kKiYoKSctPUB+", "abc123!?$*&()'-=@~"},
37 // errors
38 {t, false},
39 } {
40
41 result, err := ns.Base64Decode(test.v)
42
43 if b, ok := test.expect.(bool); ok && !b {
44 c.Assert(err, qt.Not(qt.IsNil))
45 continue
46 }
47
48 c.Assert(err, qt.IsNil)
49 c.Assert(result, qt.Equals, test.expect)
50 }
51 }
52
53 func TestBase64Encode(t *testing.T) {
54 t.Parallel()
55 c := qt.New(t)
56
57 ns := New()
58
59 for _, test := range []struct {
60 v any
61 expect any
62 }{
63 {"YWJjMTIzIT8kKiYoKSctPUB+", "WVdKak1USXpJVDhrS2lZb0tTY3RQVUIr"},
64 // errors
65 {t, false},
66 } {
67
68 result, err := ns.Base64Encode(test.v)
69
70 if b, ok := test.expect.(bool); ok && !b {
71 c.Assert(err, qt.Not(qt.IsNil))
72 continue
73 }
74
75 c.Assert(err, qt.IsNil)
76 c.Assert(result, qt.Equals, test.expect)
77 }
78 }
79
80 func TestJsonify(t *testing.T) {
81 t.Parallel()
82 c := qt.New(t)
83 ns := New()
84
85 for _, test := range []struct {
86 opts any
87 v any
88 expect any
89 }{
90 {nil, []string{"a", "b"}, template.HTML(`["a","b"]`)},
91 {map[string]string{"indent": "<i>"}, []string{"a", "b"}, template.HTML("[\n<i>\"a\",\n<i>\"b\"\n]")},
92 {map[string]string{"prefix": "<p>"}, []string{"a", "b"}, template.HTML("[\n<p>\"a\",\n<p>\"b\"\n<p>]")},
93 {map[string]string{"prefix": "<p>", "indent": "<i>"}, []string{"a", "b"}, template.HTML("[\n<p><i>\"a\",\n<p><i>\"b\"\n<p>]")},
94 {nil, tstNoStringer{}, template.HTML("{}")},
95 {nil, nil, template.HTML("null")},
96 // errors
97 {nil, math.NaN(), false},
98 {tstNoStringer{}, []string{"a", "b"}, false},
99 } {
100 args := []any{}
101
102 if test.opts != nil {
103 args = append(args, test.opts)
104 }
105
106 args = append(args, test.v)
107
108 result, err := ns.Jsonify(args...)
109
110 if b, ok := test.expect.(bool); ok && !b {
111 c.Assert(err, qt.Not(qt.IsNil))
112 continue
113 }
114
115 c.Assert(err, qt.IsNil)
116 c.Assert(result, qt.Equals, test.expect)
117 }
118 }