cuelang.org/go@v0.13.0/encoding/protobuf/jsonpb/encoder_test.go (about)

     1  // Copyright 2021 CUE Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package jsonpb_test
    16  
    17  import (
    18  	"testing"
    19  
    20  	"cuelang.org/go/cue"
    21  	"cuelang.org/go/cue/ast"
    22  	"cuelang.org/go/cue/errors"
    23  	"cuelang.org/go/cue/format"
    24  	"cuelang.org/go/cue/parser"
    25  	"cuelang.org/go/encoding/protobuf/jsonpb"
    26  	"cuelang.org/go/internal/cuetxtar"
    27  )
    28  
    29  func TestEncoder(t *testing.T) {
    30  	test := cuetxtar.TxTarTest{
    31  		Root: "./testdata/encoder",
    32  		Name: "jsonpb",
    33  	}
    34  
    35  	test.Run(t, func(t *cuetxtar.Test) {
    36  		// TODO: use high-level API.
    37  
    38  		var schema cue.Value
    39  		var file *ast.File
    40  
    41  		for _, f := range t.Archive.Files {
    42  			switch f.Name {
    43  			case "schema.cue":
    44  				schema = t.CueContext().CompileBytes(f.Data)
    45  				if err := schema.Err(); err != nil {
    46  					t.WriteErrors(errors.Promote(err, "test"))
    47  					return
    48  				}
    49  			case "value.cue":
    50  				f, err := parser.ParseFile(f.Name, f.Data, parser.ParseComments)
    51  				if err != nil {
    52  					t.WriteErrors(errors.Promote(err, "test"))
    53  					return
    54  				}
    55  				file = f
    56  			}
    57  		}
    58  
    59  		if !schema.Exists() {
    60  			schema = t.CueContext().BuildFile(file)
    61  			if err := schema.Err(); err != nil {
    62  				t.WriteErrors(errors.Promote(err, "test"))
    63  			}
    64  		}
    65  
    66  		err := jsonpb.NewEncoder(schema).RewriteFile(file)
    67  		if err != nil {
    68  			errors.Print(t, err, nil)
    69  		}
    70  
    71  		b, err := format.Node(file)
    72  		if err != nil {
    73  			t.Fatal(err)
    74  		}
    75  		_, _ = t.Write(b)
    76  	})
    77  }