github.com/kubevela/workflow@v0.6.0/pkg/cue/model/sets/walk_test.go (about) 1 /* 2 Copyright 2022 The KubeVela Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package sets 18 19 import ( 20 "testing" 21 22 "cuelang.org/go/cue/ast" 23 "cuelang.org/go/cue/cuecontext" 24 "cuelang.org/go/cue/parser" 25 "github.com/stretchr/testify/require" 26 ) 27 28 func TestWalk(t *testing.T) { 29 30 testCases := []string{ 31 `x: "124"`, 32 33 `{ x: y: string }`, 34 35 `x: {y: 124}`, 36 37 `kind: "Deployment" 38 metadata: name: "test" 39 spec: replicas: 12`, 40 41 `sidecar: { 42 name: "agent" 43 image: "test.com/agent:0.1" 44 } 45 containers: [{ 46 name: "main" 47 image: "webserver:0.2" 48 },sidecar] 49 `, 50 51 ` x: 12 52 if x==12 { 53 y: "test string" 54 } 55 `, 56 57 ` item1: { 58 x: 12 59 if x==12 { 60 y: "test string" 61 } 62 } 63 output: [item1] 64 `, 65 `import "strings" 66 67 #User: { 68 tags_str: string 69 tags_map: { 70 for k, v in strings.Split(tags_str, " ") { 71 "\(v)": string 72 } 73 "{a}": string 74 } 75 } 76 77 user: { 78 #User 79 tags_str: "b {c}" 80 } 81 `, 82 `import "strings" 83 84 b: string 85 user: { 86 tags_str: strings.Compare(b,"c") 87 } 88 `, 89 `a: [1, 2, 3]`, 90 } 91 92 for _, src := range testCases { 93 r := require.New(t) 94 inst := cuecontext.New().CompileString(src) 95 nsrc, err := toString(inst.Value()) 96 r.NoError(err) 97 f, err := parser.ParseFile("-", nsrc) 98 r.NoError(err) 99 100 newWalker(func(node ast.Node, ctx walkCtx) { 101 if len(ctx.Pos()) == 0 { 102 return 103 } 104 105 if _, ok := node.(ast.Expr); !ok { 106 return 107 } 108 if _, ok := node.(*ast.CallExpr); ok { 109 return 110 } 111 112 n, err := lookUp(f, ctx.Pos()...) 113 r.NoError(err) 114 115 r.Equal(n, node, nsrc) 116 }).walk(f) 117 } 118 119 } 120 121 func TestRemoveTmpVar(t *testing.T) { 122 src := `spec: { 123 _tmp: "x" 124 list: [{ 125 _tmp: "x" 126 retain: "y" 127 }, { 128 _tmp: "x" 129 retain: "z" 130 }] 131 retain: "y" 132 } 133 ` 134 r := require.New(t) 135 v := cuecontext.New().CompileString(src) 136 s, err := toString(v, removeTmpVar) 137 r.NoError(err) 138 r.Equal(`spec: { 139 list: [{ 140 retain: "y" 141 }, { 142 retain: "z" 143 }] 144 retain: "y" 145 } 146 `, s) 147 }