string_test.go

 1package stringext
 2
 3import (
 4	"encoding/base64"
 5	"testing"
 6
 7	"github.com/stretchr/testify/require"
 8)
 9
10func TestIsValidBase64(t *testing.T) {
11	t.Parallel()
12
13	// Real PNG header encoded in standard base64.
14	pngHeader := []byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}
15	pngBase64 := base64.StdEncoding.EncodeToString(pngHeader)
16
17	tests := []struct {
18		name     string
19		input    string
20		expected bool
21	}{
22		{name: "empty string", input: "", expected: false},
23		{name: "valid no padding", input: "SGVsbG8gV29ybGQh", expected: true},
24		{name: "valid with padding", input: "YQ==", expected: true},
25		{name: "non-ASCII bytes", input: "abc\x80def", expected: false},
26		{name: "ASCII but not base64", input: "hello world!!!", expected: false},
27		{name: "raw encoding no padding", input: "YQ", expected: false},
28		{name: "trailing whitespace", input: "YQ==\n", expected: false},
29		{name: "valid PNG header base64", input: pngBase64, expected: true},
30	}
31
32	for _, tt := range tests {
33		t.Run(tt.name, func(t *testing.T) {
34			t.Parallel()
35			require.Equal(t, tt.expected, IsValidBase64(tt.input))
36		})
37	}
38}