metadata_test.go 1.95 KB
Newer Older
1 2 3
package metadata

import (
4
	"bytes"
5 6 7
	"math/rand"
	"testing"

8 9
	"github.com/ipld/go-ipld-prime/codec/dagcbor"
	"github.com/ipld/go-ipld-prime/fluent"
Hannah Howard's avatar
Hannah Howard committed
10
	"github.com/stretchr/testify/require"
11 12

	"github.com/ipfs/go-graphsync/testutil"
13 14
	cidlink "github.com/ipld/go-ipld-prime/linking/cid"
	basicnode "github.com/ipld/go-ipld-prime/node/basic"
15 16 17 18
)

func TestDecodeEncodeMetadata(t *testing.T) {
	cids := testutil.GenerateCids(10)
19
	initialMetadata := make(Metadata, 0, 10)
20 21 22 23 24 25 26 27 28 29 30 31
	nd := fluent.MustBuildList(basicnode.Style.List, 10, func(fla fluent.ListAssembler) {
		for _, k := range cids {
			blockPresent := rand.Int31()%2 == 0
			initialMetadata = append(initialMetadata, Item{k, blockPresent})
			fla.AssembleValue().CreateMap(2, func(fma fluent.MapAssembler) {
				fma.AssembleEntry("Link").AssignLink(cidlink.Link{Cid: k})
				fma.AssembleEntry("BlockPresent").AssignBool(blockPresent)
			})
		}
	})

	// verify metadata matches
32
	encoded, err := EncodeMetadata(initialMetadata)
Hannah Howard's avatar
Hannah Howard committed
33
	require.NoError(t, err, "encode errored")
34

35
	decodedMetadata, err := DecodeMetadata(encoded)
Hannah Howard's avatar
Hannah Howard committed
36 37
	require.NoError(t, err, "decode errored")
	require.Equal(t, initialMetadata, decodedMetadata, "metadata changed during encoding and decoding")
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

	// verify metadata is equivalent of IPLD node encoding
	encodedNode := new(bytes.Buffer)
	err = dagcbor.Encoder(nd, encodedNode)
	require.NoError(t, err)
	decodedMetadataFromNode, err := DecodeMetadata(encodedNode.Bytes())
	require.NoError(t, err)
	require.Equal(t, decodedMetadata, decodedMetadataFromNode, "metadata not equal to IPLD encoding")

	nb := basicnode.Style.List.NewBuilder()
	err = dagcbor.Decoder(nb, encodedNode)
	require.NoError(t, err)
	decodedNode := nb.Build()
	require.Equal(t, nd, decodedNode)
	nb = basicnode.Style.List.NewBuilder()
	err = dagcbor.Decoder(nb, bytes.NewReader(encoded))
	require.NoError(t, err)
	decodedNodeFromMetadata := nb.Build()
	require.Equal(t, decodedNode, decodedNodeFromMetadata, "deserialzed metadata does not match deserialized node")
57
}