...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package astutil_test
16
17 import (
18 "strings"
19 "testing"
20
21 "github.com/google/go-cmp/cmp"
22
23 "cuelang.org/go/cue"
24 "cuelang.org/go/cue/ast"
25 "cuelang.org/go/cue/ast/astutil"
26 "cuelang.org/go/cue/format"
27 "cuelang.org/go/cue/token"
28 _ "cuelang.org/go/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.141592653589793238462643383279503",
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,
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 }
103
View as plain text