string_test.go 1.1 KB

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