git.lukeshu.com/go/lowmemjson@v0.3.9-0.20230723050957-72f6d13f6fb2/internal/base64dec/base64_test.go (about)

     1  // Copyright (C) 2022-2023  Luke Shumaker <lukeshu@lukeshu.com>
     2  //
     3  // SPDX-License-Identifier: GPL-2.0-or-later
     4  
     5  package base64dec
     6  
     7  import (
     8  	"bytes"
     9  	"encoding/base64"
    10  	"testing"
    11  
    12  	"github.com/stretchr/testify/require"
    13  )
    14  
    15  func b64encode(t *testing.T, input []byte) []byte {
    16  	var encoded bytes.Buffer
    17  	enc := base64.NewEncoder(base64.StdEncoding, &encoded)
    18  	_, err := enc.Write(input)
    19  	require.NoError(t, err)
    20  	require.NoError(t, enc.Close())
    21  	return encoded.Bytes()
    22  }
    23  
    24  func b64decode(t *testing.T, input []byte) []byte {
    25  	var decoded bytes.Buffer
    26  	dec := NewBase64Decoder(&decoded)
    27  	_, err := dec.Write(input)
    28  	require.NoError(t, err)
    29  	require.NoError(t, dec.Close())
    30  	return decoded.Bytes()
    31  }
    32  
    33  func FuzzBase64Decoder(f *testing.F) {
    34  	f.Fuzz(func(t *testing.T, input []byte) {
    35  		encoded := b64encode(t, input)
    36  		decoded := b64decode(t, encoded)
    37  		t.Logf("input b64        = %q", encoded)
    38  		t.Logf("expected decoded = %#v", input)
    39  		t.Logf("actual decoded   = %#v", decoded)
    40  		if !bytes.Equal(input, decoded) {
    41  			t.Fail()
    42  		}
    43  	})
    44  }