github.com/solo-io/cue@v0.4.7/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  	"github.com/solo-io/cue/cue"
    21  	"github.com/solo-io/cue/cue/ast"
    22  	"github.com/solo-io/cue/cue/errors"
    23  	"github.com/solo-io/cue/cue/format"
    24  	"github.com/solo-io/cue/cue/parser"
    25  	"github.com/solo-io/cue/encoding/protobuf/jsonpb"
    26  	"github.com/solo-io/cue/internal/cuetest"
    27  	"github.com/solo-io/cue/internal/cuetxtar"
    28  )
    29  
    30  func TestEncoder(t *testing.T) {
    31  	test := cuetxtar.TxTarTest{
    32  		Root:   "./testdata/encoder",
    33  		Name:   "jsonpb",
    34  		Update: cuetest.UpdateGoldenFiles,
    35  	}
    36  
    37  	r := cue.Runtime{}
    38  
    39  	test.Run(t, func(t *cuetxtar.Test) {
    40  		// TODO: use high-level API.
    41  
    42  		var schema cue.Value
    43  		var file *ast.File
    44  
    45  		for _, f := range t.Archive.Files {
    46  			switch {
    47  			case f.Name == "schema.cue":
    48  				inst, err := r.Compile(f.Name, f.Data)
    49  				if err != nil {
    50  					t.WriteErrors(errors.Promote(err, "test"))
    51  					return
    52  				}
    53  				schema = inst.Value()
    54  
    55  			case f.Name == "value.cue":
    56  				f, err := parser.ParseFile(f.Name, f.Data, parser.ParseComments)
    57  				if err != nil {
    58  					t.WriteErrors(errors.Promote(err, "test"))
    59  					return
    60  				}
    61  				file = f
    62  			}
    63  		}
    64  
    65  		if !schema.Exists() {
    66  			inst, err := r.CompileFile(file)
    67  			if err != nil {
    68  				t.WriteErrors(errors.Promote(err, "test"))
    69  			}
    70  			schema = inst.Value()
    71  		}
    72  
    73  		err := jsonpb.NewEncoder(schema).RewriteFile(file)
    74  		if err != nil {
    75  			errors.Print(t, err, nil)
    76  		}
    77  
    78  		b, err := format.Node(file)
    79  		if err != nil {
    80  			t.Fatal(err)
    81  		}
    82  		_, _ = t.Write(b)
    83  	})
    84  }