summaryrefslogtreecommitdiff
path: root/internal/funcs/base64_test.go
blob: 425a1218d9f0af393d0d8c2f213ea53b19c1e063 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package funcs

import (
	"bytes"
	"context"
	"strconv"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestCreateBase64Funcs(t *testing.T) {
	t.Parallel()

	for i := range 10 {
		// Run this a bunch to catch race conditions
		t.Run(strconv.Itoa(i), func(t *testing.T) {
			t.Parallel()

			ctx := context.Background()
			fmap := CreateBase64Funcs(ctx)
			actual := fmap["base64"].(func() any)

			assert.Equal(t, ctx, actual().(*Base64Funcs).ctx)
		})
	}
}

func TestBase64Encode(t *testing.T) {
	t.Parallel()

	bf := &Base64Funcs{}
	assert.Equal(t, "Zm9vYmFy", must(bf.Encode("foobar")))
}

func TestBase64Decode(t *testing.T) {
	t.Parallel()

	bf := &Base64Funcs{}
	assert.Equal(t, "foobar", must(bf.Decode("Zm9vYmFy")))
}

func TestBase64DecodeBytes(t *testing.T) {
	t.Parallel()

	bf := &Base64Funcs{}
	out, err := bf.DecodeBytes("Zm9vYmFy")
	require.NoError(t, err)
	assert.Equal(t, "foobar", string(out))
}

func TestToBytes(t *testing.T) {
	t.Parallel()

	assert.Equal(t, []byte{0, 1, 2, 3}, toBytes([]byte{0, 1, 2, 3}))

	buf := &bytes.Buffer{}
	buf.WriteString("hi")
	assert.Equal(t, []byte("hi"), toBytes(buf))
	assert.Equal(t, []byte{}, toBytes(nil))
	assert.Equal(t, []byte("42"), toBytes(42))
}

func BenchmarkToBytes(b *testing.B) {
	for b.Loop() {
		b.StopTimer()
		buf := &bytes.Buffer{}
		buf.WriteString("hi")
		bin := []byte{0, 1, 2, 3}
		b.StartTimer()

		toBytes(bin)

		toBytes(buf)
		toBytes(nil)
		toBytes(42)
	}
}