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
15package jsonpb_test
16
17import (
18 "strings"
19 "testing"
20
21 "cuelang.org/go/cue"
22 "cuelang.org/go/cue/ast"
23 "cuelang.org/go/cue/ast/astutil"
24 "cuelang.org/go/cue/cuecontext"
25 "cuelang.org/go/cue/errors"
26 "cuelang.org/go/cue/format"
27 "cuelang.org/go/cue/parser"
28 "cuelang.org/go/encoding/json"
29 "cuelang.org/go/encoding/protobuf/jsonpb"
30 "cuelang.org/go/encoding/yaml"
31 "cuelang.org/go/internal/cuetxtar"
32)
33
34func TestParse(t *testing.T) {
35 test := cuetxtar.TxTarTest{
36 Root: "./testdata/decoder",
37 Name: "jsonpb",
38 }
39
40 test.Run(t, func(t *cuetxtar.Test) {
41 // TODO: use high-level API.
42
43 var schema cue.Value
44 var file *ast.File
45
46 for _, f := range t.Archive.Files {
47 switch {
48 case f.Name == "schema.cue":
49 schema = t.CueContext().CompileBytes(f.Data, cue.Filename(f.Name))
50 if err := schema.Err(); err != nil {
51 t.WriteErrors(errors.Promote(err, "test"))
52 return
53 }
54 continue
55
56 case strings.HasPrefix(f.Name, "out/"):
57 continue
58
59 case strings.HasSuffix(f.Name, ".cue"):
60 f, err := parser.ParseFile(f.Name, f.Data, parser.ParseComments)
61 if err != nil {
62 t.Fatal(err)
63 }
64 file = f
65
66 case strings.HasSuffix(f.Name, ".json"):
67 x, err := json.Extract(f.Name, f.Data)
68 if err != nil {
69 t.Fatal(err)
70 }
71 file, err = astutil.ToFile(x)
72 if err != nil {
73 t.Fatal(err)
74 }
75
76 case strings.HasSuffix(f.Name, ".yaml"):
77 f, err := yaml.Extract(f.Name, f.Data)
78 if err != nil {
79 t.Fatal(err)
80 }
81 file = f
82 }
83
84 w := t.Writer(f.Name)
85 err := jsonpb.NewDecoder(schema).RewriteFile(file)
86 if err != nil {
87 errors.Print(w, err, nil)
88 continue
89 }
90
91 b, err := format.Node(file)
92 if err != nil {
93 t.Fatal(err)
94 }
95 _, _ = w.Write(b)
96 }
97 })
98}
99
100// For debugging purposes: DO NOT REMOVE.
101func TestX(t *testing.T) {
102 const schema = `
103
104 `
105 const data = `
106`
107 if strings.TrimSpace(data) == "" {
108 t.Skip()
109 }
110 val := cuecontext.New().CompileString(schema)
111 if err := val.Err(); err != nil {
112 t.Fatal(err)
113 }
114
115 file, err := parser.ParseFile("data", data)
116 if err != nil {
117 t.Fatal(err)
118 }
119
120 if err := jsonpb.NewDecoder(val).RewriteFile(file); err != nil {
121 t.Fatal(err)
122 }
123
124 b, err := format.Node(file)
125 if err != nil {
126 t.Fatal(err)
127 }
128 t.Error(string(b))
129}