github.com/ipld/go-ipld-prime@v0.21.0/schema/dmt/roundtrip_test.go (about)

     1  package schemadmt_test
     2  
     3  import (
     4  	"bytes"
     5  	"os"
     6  	"regexp"
     7  	"strings"
     8  	"testing"
     9  
    10  	ipldjson "github.com/ipld/go-ipld-prime/codec/json"
    11  	"github.com/ipld/go-ipld-prime/node/bindnode"
    12  	"github.com/ipld/go-ipld-prime/schema"
    13  	schemadmt "github.com/ipld/go-ipld-prime/schema/dmt"
    14  
    15  	qt "github.com/frankban/quicktest"
    16  )
    17  
    18  func TestRoundtripSchemaSchema(t *testing.T) {
    19  	t.Parallel()
    20  
    21  	input := "../../.ipld/specs/schemas/schema-schema.ipldsch.json"
    22  
    23  	src, err := os.ReadFile(input)
    24  	qt.Assert(t, err, qt.IsNil)
    25  	testRoundtrip(t, string(src), func(updated string) {
    26  		err := os.WriteFile(input, []byte(updated), 0o777)
    27  		qt.Assert(t, err, qt.IsNil)
    28  	})
    29  }
    30  
    31  func testRoundtrip(t *testing.T, want string, updateFn func(string)) {
    32  	t.Helper()
    33  
    34  	crre := regexp.MustCompile(`\r?\n`)
    35  	want = crre.ReplaceAllString(want, "\n")
    36  	nb := schemadmt.Prototypes.Schema.Representation().NewBuilder()
    37  	err := ipldjson.Decode(nb, strings.NewReader(want))
    38  	qt.Assert(t, err, qt.IsNil)
    39  	node := nb.Build().(schema.TypedNode)
    40  
    41  	// Ensure the decoded schema compiles as expected.
    42  	{
    43  		sch := bindnode.Unwrap(node).(*schemadmt.Schema)
    44  
    45  		var ts schema.TypeSystem
    46  		ts.Init()
    47  		err := schemadmt.Compile(&ts, sch)
    48  		qt.Assert(t, err, qt.IsNil)
    49  
    50  		typeStruct := ts.TypeByName("TypeDefnStruct")
    51  		if typeStruct == nil {
    52  			t.Fatal("TypeStruct not found")
    53  		}
    54  	}
    55  
    56  	// Ensure we can re-encode the schema as dag-json,
    57  	// and that it results in the same bytes as prettified by encoding/json.
    58  	{
    59  		var buf bytes.Buffer
    60  		err := ipldjson.Encode(node.Representation(), &buf)
    61  		qt.Assert(t, err, qt.IsNil)
    62  
    63  		got := buf.String()
    64  		qt.Assert(t, got, qt.Equals, want)
    65  	}
    66  
    67  	// For the sake of completeness, check that we can encode the non-repr node.
    68  	// This just ensures we don't panic or error.
    69  	{
    70  		var buf bytes.Buffer
    71  		err := ipldjson.Encode(node, &buf)
    72  		qt.Assert(t, err, qt.IsNil)
    73  	}
    74  }