Skip to content

Commit

Permalink
chore(bindnode): add test for sub-node unwrapping
Browse files Browse the repository at this point in the history
Closes: #339

I can't repro the error in 339, so I'm adding this test and will close the issue
  • Loading branch information
rvagg committed May 24, 2022
1 parent e01280e commit 6293f42
Showing 1 changed file with 125 additions and 0 deletions.
125 changes: 125 additions & 0 deletions node/bindnode/api_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package bindnode_test

import (
"encoding/hex"
"testing"

qt "github.com/frankban/quicktest"
"github.com/ipld/go-ipld-prime"
"github.com/ipld/go-ipld-prime/codec/dagcbor"
"github.com/ipld/go-ipld-prime/datamodel"
"github.com/ipld/go-ipld-prime/node/bindnode"
)

func TestSubNodeUnwrap(t *testing.T) {
type F struct {
F bool
}
type B struct {
B int
}
type A struct {
A string
}
type S struct {
F F
B B
A *A
}

schema := `
type F struct {
F Bool
} representation tuple
type B struct {
B Int
} representation tuple
type A struct {
A String
} representation tuple
type S struct {
F F
B B
A optional A
} representation tuple
`

encodedHex := "8381f581186581624141" // [[true],[101],["AA"]]
expected := S{
F: F{true},
B: B{101},
A: &A{"AA"},
}

typeSystem, err := ipld.LoadSchemaBytes([]byte(schema))
qt.Assert(t, err, qt.IsNil)
schemaType := typeSystem.TypeByName("S")

verifyMap := func(node datamodel.Node) {
mi := node.MapIterator()

key, value, err := mi.Next()
qt.Assert(t, err, qt.IsNil)

str, err := key.AsString()
qt.Assert(t, err, qt.IsNil)
qt.Assert(t, str, qt.Equals, "F")

typ := bindnode.Unwrap(value)
instF, ok := typ.(*F)
qt.Assert(t, ok, qt.IsTrue)
qt.Assert(t, *instF, qt.Equals, F{true})

key, value, err = mi.Next()
qt.Assert(t, err, qt.IsNil)

str, err = key.AsString()
qt.Assert(t, err, qt.IsNil)
qt.Assert(t, str, qt.Equals, "B")

typ = bindnode.Unwrap(value)
instB, ok := typ.(*B)
qt.Assert(t, ok, qt.IsTrue)
qt.Assert(t, *instB, qt.Equals, B{101})

key, value, err = mi.Next()
qt.Assert(t, err, qt.IsNil)

str, err = key.AsString()
qt.Assert(t, err, qt.IsNil)
qt.Assert(t, str, qt.Equals, "A")

typ = bindnode.Unwrap(value)
instA, ok := typ.(*A)
qt.Assert(t, ok, qt.IsTrue)
qt.Assert(t, *instA, qt.Equals, A{"AA"})
}

t.Run("decode", func(t *testing.T) {
encoded, _ := hex.DecodeString(encodedHex)

proto := bindnode.Prototype(&S{}, schemaType)

node, err := ipld.DecodeUsingPrototype([]byte(encoded), dagcbor.Decode, proto)
qt.Assert(t, err, qt.IsNil)

typ := bindnode.Unwrap(node)
instS, ok := typ.(*S)
qt.Assert(t, ok, qt.IsTrue)

qt.Assert(t, *instS, qt.DeepEquals, expected)

verifyMap(node)
})

t.Run("encode", func(t *testing.T) {
node := bindnode.Wrap(&expected, schemaType)

byts, err := ipld.Encode(node, dagcbor.Encode)
qt.Assert(t, err, qt.IsNil)

qt.Assert(t, hex.EncodeToString(byts), qt.Equals, encodedHex)

verifyMap(node)
})
}

0 comments on commit 6293f42

Please sign in to comment.