github.com/ipld/go-ipld-prime@v0.21.0/codec/dagjson/roundtripCidlink_test.go (about)

     1  package dagjson_test
     2  
     3  import (
     4  	"bytes"
     5  	"io"
     6  	"strings"
     7  	"testing"
     8  
     9  	qt "github.com/frankban/quicktest"
    10  
    11  	cid "github.com/ipfs/go-cid"
    12  	"github.com/ipld/go-ipld-prime/codec/dagjson"
    13  	"github.com/ipld/go-ipld-prime/datamodel"
    14  	"github.com/ipld/go-ipld-prime/linking"
    15  	cidlink "github.com/ipld/go-ipld-prime/linking/cid"
    16  	"github.com/ipld/go-ipld-prime/node/basicnode"
    17  	nodetests "github.com/ipld/go-ipld-prime/node/tests"
    18  )
    19  
    20  func TestRoundtripCidlink(t *testing.T) {
    21  	lp := cidlink.LinkPrototype{Prefix: cid.Prefix{
    22  		Version:  1,
    23  		Codec:    0x0129,
    24  		MhType:   0x13,
    25  		MhLength: 4,
    26  	}}
    27  	lsys := cidlink.DefaultLinkSystem()
    28  
    29  	buf := bytes.Buffer{}
    30  	lsys.StorageWriteOpener = func(lnkCtx linking.LinkContext) (io.Writer, linking.BlockWriteCommitter, error) {
    31  		return &buf, func(lnk datamodel.Link) error { return nil }, nil
    32  	}
    33  	lsys.StorageReadOpener = func(lnkCtx linking.LinkContext, lnk datamodel.Link) (io.Reader, error) {
    34  		return bytes.NewReader(buf.Bytes()), nil
    35  	}
    36  
    37  	lnk, err := lsys.Store(linking.LinkContext{}, lp, n)
    38  	qt.Assert(t, err, qt.IsNil)
    39  
    40  	n2, err := lsys.Load(linking.LinkContext{}, lnk, basicnode.Prototype.Any)
    41  	qt.Assert(t, err, qt.IsNil)
    42  	qt.Check(t, n2, nodetests.NodeContentEquals, nSorted)
    43  }
    44  
    45  // Make sure that a map that *almost* looks like a link is handled safely.
    46  //
    47  // This is aiming very specifically at the corner case where a minimal number of
    48  // tokens have to be reprocessed before a recursion that find a real link appears.
    49  func TestUnmarshalTrickyMapContainingLink(t *testing.T) {
    50  	// Create a link; don't particularly care about its contents.
    51  	lnk := cidlink.LinkPrototype{Prefix: cid.Prefix{
    52  		Version:  1,
    53  		Codec:    0x71,
    54  		MhType:   0x13,
    55  		MhLength: 4,
    56  	}}.BuildLink([]byte{1, 2, 3, 4}) // dummy value, content does not matter to this test.
    57  
    58  	// Compose the tricky corpus.  (lnk.String "happens" to work here, although this isn't recommended or correct in general.)
    59  	tricky := `{"/":{"/":"` + lnk.String() + `"}}`
    60  
    61  	// Unmarshal.  Hopefully we get a map with a link in it.
    62  	nb := basicnode.Prototype.Any.NewBuilder()
    63  	err := dagjson.Decode(nb, strings.NewReader(tricky))
    64  	qt.Assert(t, err, qt.IsNil)
    65  	n := nb.Build()
    66  	qt.Check(t, n.Kind(), qt.Equals, datamodel.Kind_Map)
    67  	n2, err := n.LookupByString("/")
    68  	qt.Assert(t, err, qt.IsNil)
    69  	qt.Check(t, n2.Kind(), qt.Equals, datamodel.Kind_Link)
    70  }