From c5523d39fc7badb5cab6c370b87b4fb23943d418 Mon Sep 17 00:00:00 2001 From: Jonathan Claudius Date: Tue, 30 May 2023 16:48:17 -0400 Subject: [PATCH] sdk: Add unit-testing and fuzz-testing for leftpadbytes (#2997) --- sdk/vaa/payloads_test.go | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/sdk/vaa/payloads_test.go b/sdk/vaa/payloads_test.go index 0797210fd..e11eecefb 100644 --- a/sdk/vaa/payloads_test.go +++ b/sdk/vaa/payloads_test.go @@ -1,6 +1,7 @@ package vaa import ( + "bytes" "encoding/hex" "testing" @@ -162,3 +163,40 @@ func TestBodyIbcReceiverUpdateChannelChain(t *testing.T) { } assert.Equal(t, expected, hex.EncodeToString(bodyIbcReceiverUpdateChannelChain.Serialize())) } + +func TestLeftPadBytes(t *testing.T) { + payload := "AAAA" + paddedPayload := LeftPadBytes(payload, int(8)) + + buf := &bytes.Buffer{} + buf.WriteByte(0x00) + buf.WriteByte(0x00) + buf.WriteByte(0x00) + buf.WriteByte(0x00) + buf.Write([]byte(payload)) + + assert.Equal(t, paddedPayload, buf) +} + +func FuzzLeftPadBytes(f *testing.F) { + // Add examples to our fuzz corpus + f.Add("FOO", 8) + f.Add("123", 8) + + f.Fuzz(func(t *testing.T, payload string, length int) { + // We know length could be negative, but we panic if it is in the implementation + if length < 0 { + t.Skip() + } + + // We know we cannot left pad something shorter than the payload being provided, but we panic if it is + if len(payload) > length { + t.Skip() + } + + paddedPayload := LeftPadBytes(payload, length) + + // paddedPayload must always be equal to length + assert.Equal(t, paddedPayload.Len(), length) + }) +}