github.com/joomcode/cue@v0.4.4-0.20221111115225-539fe3512047/cue/ast/astutil/file_test.go (about) 1 // Copyright 2020 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 astutil_test 16 17 import ( 18 "strings" 19 "testing" 20 21 "github.com/google/go-cmp/cmp" 22 23 "github.com/joomcode/cue/cue" 24 "github.com/joomcode/cue/cue/ast" 25 "github.com/joomcode/cue/cue/ast/astutil" 26 "github.com/joomcode/cue/cue/format" 27 "github.com/joomcode/cue/cue/token" 28 _ "github.com/joomcode/cue/pkg" 29 ) 30 31 func TestToFile(t *testing.T) { 32 mat := ast.NewIdent("math") 33 mat.Node = ast.NewImport(nil, "math") 34 pi := ast.NewSel(mat, "Pi") 35 36 testCases := []struct { 37 desc string 38 expr ast.Expr 39 want string 40 }{{ 41 desc: "add import", 42 expr: ast.NewBinExpr(token.ADD, ast.NewLit(token.INT, "1"), pi), 43 want: "4.14159265358979323846264", 44 }, { 45 desc: "resolve unresolved within struct", 46 expr: ast.NewStruct( 47 ast.NewIdent("a"), ast.NewString("foo"), 48 ast.NewIdent("b"), ast.NewIdent("a"), 49 ), 50 want: `{ 51 a: "foo" 52 b: "foo" 53 }`, 54 }, { 55 desc: "unshadow", 56 expr: func() ast.Expr { 57 ident := ast.NewIdent("a") 58 ref := ast.NewIdent("a") 59 ref.Node = ident 60 61 return ast.NewStruct( 62 ident, ast.NewString("bar"), 63 ast.NewIdent("c"), ast.NewStruct( 64 ast.NewIdent("a"), ast.NewString("foo"), 65 ast.NewIdent("b"), ref, // refers to outer `a`. 66 )) 67 }(), 68 want: `{ 69 a: "bar" 70 c: { 71 a: "foo" 72 b: "bar" 73 } 74 }`, 75 }} 76 for _, tc := range testCases { 77 t.Run(tc.desc, func(t *testing.T) { 78 f, err := astutil.ToFile(tc.expr) 79 if err != nil { 80 t.Fatal(err) 81 } 82 83 var r cue.Runtime 84 85 inst, err := r.CompileFile(f) 86 if err != nil { 87 t.Fatal(err) 88 } 89 90 b, err := format.Node(inst.Value().Syntax(cue.Concrete(true))) 91 if err != nil { 92 t.Fatal(err) 93 } 94 95 got := string(b) 96 want := strings.TrimLeft(tc.want, "\n") 97 if got != want { 98 t.Error(cmp.Diff(want, got)) 99 } 100 }) 101 } 102 }