Skip to content

Commit

Permalink
runtime/evm: add tests for JSON round trip
Browse files Browse the repository at this point in the history
  • Loading branch information
pro-wh committed Nov 17, 2023
1 parent 3f99aac commit 50f26a2
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
6 changes: 5 additions & 1 deletion analyzer/evmnfts/evm_nfts.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,11 @@ func (p *processor) ProcessItem(ctx context.Context, batch *storage.QueryBatch,
staleNFT.DownloadRound,
storage.SanitizeStringP(nftData.MetadataURI),
nftData.MetadataAccessed,
// If SanitizeString can affect JSON validity, we're doomed.
// Metadata has already gone through a round trip of JSON Unmarshal
// and Marshal, which should already make it safe for PostgreSQL. But
// for consistency, pass it through SanitizeString as well. This
// shouldn't have any effect, and if it does, it shouldn't affect the
// JSON syntax.
storage.SanitizeStringP(nftData.Metadata),
storage.SanitizeStringP(nftData.Name),
storage.SanitizeStringP(nftData.Description),
Expand Down
42 changes: 42 additions & 0 deletions analyzer/runtime/evm/erc721_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package evm

import (
"encoding/json"
"testing"
"unicode/utf8"

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

func TestJSONRoundTrip(t *testing.T) {
for _, s := range []string{
// Invalid UTF-8.
"{\"a\": \"\xff\"}",
"{\"\xff\": \"a\"}",
// NUL bytes.
"{\"a\": \"\x00\"}",
"{\"\x00\": \"a\"}",
// Codepoint zero.
"{\"a\": \"\\u0000\"}",
"{\"\\u0000\": \"a\"}",
} {
var parsed any
err := json.Unmarshal([]byte(s), &parsed)
if err != nil {
// Erroring out while unmarshalling is fine.
t.Logf("%#v -> parsing: %v\n", s, err)
continue
}
roundTripBuf, err := json.Marshal(parsed)
if err != nil {
// Erroring out while marshalling is uncool, but not a showstopper.
t.Logf("%#v -> stringifying: %v\n", s, err)
continue
}
roundTrip := string(roundTripBuf)
// If it gets through the round trip, it'd better be clean.
require.True(t, utf8.ValidString(roundTrip), "%#v -> invalid UTF-8 %#v", s, roundTrip)
require.NotContains(t, roundTrip, 0x0, "%#v -> contains NUL byte %#v", s, roundTrip)
t.Logf("%#v -> %#v\n", s, roundTrip)
}
}

0 comments on commit 50f26a2

Please sign in to comment.