roundtripBytes_test.go 1.72 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
package dagjson

import (
	"bytes"
	"strings"
	"testing"

	. "github.com/warpfork/go-wish"

	"github.com/ipld/go-ipld-prime/fluent"
	basicnode "github.com/ipld/go-ipld-prime/node/basic"
)

var byteNode = fluent.MustBuildMap(basicnode.Prototype__Map{}, 4, func(na fluent.MapAssembler) {
	na.AssembleEntry("plain").AssignString("olde string")
	na.AssembleEntry("bytes").AssignBytes([]byte("deadbeef"))
})
18
var byteSerial = `{"bytes":{"/":{"bytes":"ZGVhZGJlZWY="}},"plain":"olde string"}`
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

func TestRoundtripBytes(t *testing.T) {
	t.Run("encoding", func(t *testing.T) {
		var buf bytes.Buffer
		err := Encode(byteNode, &buf)
		Require(t, err, ShouldEqual, nil)
		Wish(t, buf.String(), ShouldEqual, byteSerial)
	})
	t.Run("decoding", func(t *testing.T) {
		buf := strings.NewReader(byteSerial)
		nb := basicnode.Prototype__Map{}.NewBuilder()
		err := Decode(nb, buf)
		Require(t, err, ShouldEqual, nil)
		Wish(t, nb.Build(), ShouldEqual, byteNode)
	})
}
Will Scott's avatar
Will Scott committed
35 36 37 38 39 40

var encapsulatedNode = fluent.MustBuildMap(basicnode.Prototype__Map{}, 1, func(na fluent.MapAssembler) {
	na.AssembleEntry("/").CreateMap(1, func(sa fluent.MapAssembler) {
		sa.AssembleEntry("bytes").AssignBytes([]byte("deadbeef"))
	})
})
Rod Vagg's avatar
Rod Vagg committed
41
var encapsulatedSerial = `{"/":{"bytes":{"/":{"bytes":"ZGVhZGJlZWY="}}}}`
Will Scott's avatar
Will Scott committed
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57

func TestEncapsulatedBytes(t *testing.T) {
	t.Run("encoding", func(t *testing.T) {
		var buf bytes.Buffer
		err := Encode(encapsulatedNode, &buf)
		Require(t, err, ShouldEqual, nil)
		Wish(t, buf.String(), ShouldEqual, encapsulatedSerial)
	})
	t.Run("decoding", func(t *testing.T) {
		buf := strings.NewReader(encapsulatedSerial)
		nb := basicnode.Prototype__Map{}.NewBuilder()
		err := Decode(nb, buf)
		Require(t, err, ShouldEqual, nil)
		Wish(t, nb.Build(), ShouldEqual, encapsulatedNode)
	})
}