github.com/storacha/go-ucanto@v0.7.2/core/schema/struct_test.go (about)

     1  package schema
     2  
     3  import (
     4  	"fmt"
     5  	"testing"
     6  
     7  	"github.com/ipld/go-ipld-prime"
     8  	"github.com/ipld/go-ipld-prime/node/basicnode"
     9  	"github.com/storacha/go-ucanto/testing/helpers"
    10  	"github.com/stretchr/testify/require"
    11  )
    12  
    13  func TestReadStruct(t *testing.T) {
    14  	type TestStruct struct {
    15  		Name string
    16  	}
    17  
    18  	ts := helpers.Must(ipld.LoadSchemaBytes([]byte(`
    19  		type TestStruct struct {
    20  			name String
    21  		}
    22  	`)))
    23  
    24  	t.Run("Success", func(t *testing.T) {
    25  		np := basicnode.Prototype.Any
    26  		nb := np.NewBuilder()
    27  		ma := helpers.Must(nb.BeginMap(2))
    28  		ma.AssembleKey().AssignString("name")
    29  		ma.AssembleValue().AssignString("foo")
    30  		ma.Finish()
    31  		nd := nb.Build()
    32  
    33  		res, err := Struct[TestStruct](ts.TypeByName("TestStruct"), nil).Read(nd)
    34  		require.NoError(t, err)
    35  		fmt.Printf("%+v\n", res)
    36  		require.Equal(t, res.Name, "foo")
    37  	})
    38  
    39  	t.Run("Failure", func(t *testing.T) {
    40  		np := basicnode.Prototype.Any
    41  		nb := np.NewBuilder()
    42  		ma := helpers.Must(nb.BeginMap(2))
    43  		ma.AssembleKey().AssignString("foo")
    44  		ma.AssembleValue().AssignString("bar")
    45  		ma.Finish()
    46  		nd := nb.Build()
    47  
    48  		_, err := Struct[TestStruct](ts.TypeByName("TestStruct"), nil).Read(nd)
    49  		require.Error(t, err)
    50  		fmt.Printf("%+v\n", err)
    51  		require.Equal(t, err.Name(), "SchemaError")
    52  	})
    53  }