roundtrip_test.go 1.93 KB
Newer Older
1 2 3 4
package dagjson

import (
	"bytes"
5
	"strings"
6 7 8 9 10 11 12 13
	"testing"

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

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

14
var n = fluent.MustBuildMap(basicnode.Prototype__Map{}, 4, func(na fluent.MapAssembler) {
15 16 17 18
	na.AssembleEntry("plain").AssignString("olde string")
	na.AssembleEntry("map").CreateMap(2, func(na fluent.MapAssembler) {
		na.AssembleEntry("one").AssignInt(1)
		na.AssembleEntry("two").AssignInt(2)
19
	})
20
	na.AssembleEntry("list").CreateList(2, func(na fluent.ListAssembler) {
21 22 23
		na.AssembleValue().AssignString("three")
		na.AssembleValue().AssignString("four")
	})
24 25
	na.AssembleEntry("nested").CreateMap(1, func(na fluent.MapAssembler) {
		na.AssembleEntry("deeper").CreateList(1, func(na fluent.ListAssembler) {
26 27 28 29
			na.AssembleValue().AssignString("things")
		})
	})
})
30
var serial = `{"list":["three","four"],"map":{"one":1,"two":2},"nested":{"deeper":["things"]},"plain":"olde string"}`
31 32 33 34

func TestRoundtrip(t *testing.T) {
	t.Run("encoding", func(t *testing.T) {
		var buf bytes.Buffer
Eric Myhre's avatar
Eric Myhre committed
35
		err := Encode(n, &buf)
36 37 38 39
		Require(t, err, ShouldEqual, nil)
		Wish(t, buf.String(), ShouldEqual, serial)
	})
	t.Run("decoding", func(t *testing.T) {
40
		buf := strings.NewReader(serial)
41
		nb := basicnode.Prototype__Map{}.NewBuilder()
Eric Myhre's avatar
Eric Myhre committed
42
		err := Decode(nb, buf)
43 44 45 46 47 48
		Require(t, err, ShouldEqual, nil)
		Wish(t, nb.Build(), ShouldEqual, n)
	})
}

func TestRoundtripScalar(t *testing.T) {
49
	nb := basicnode.Prototype__String{}.NewBuilder()
50 51 52 53
	nb.AssignString("applesauce")
	simple := nb.Build()
	t.Run("encoding", func(t *testing.T) {
		var buf bytes.Buffer
Eric Myhre's avatar
Eric Myhre committed
54
		err := Encode(simple, &buf)
55 56 57 58
		Require(t, err, ShouldEqual, nil)
		Wish(t, buf.String(), ShouldEqual, `"applesauce"`)
	})
	t.Run("decoding", func(t *testing.T) {
59
		buf := strings.NewReader(`"applesauce"`)
60
		nb := basicnode.Prototype__String{}.NewBuilder()
Eric Myhre's avatar
Eric Myhre committed
61
		err := Decode(nb, buf)
62 63 64 65
		Require(t, err, ShouldEqual, nil)
		Wish(t, nb.Build(), ShouldEqual, simple)
	})
}