cuelang.org/go@v0.10.1/cue/format/node_test.go (about) 1 // Copyright 2019 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 format 16 17 import ( 18 "strings" 19 "testing" 20 21 "cuelang.org/go/cue/ast" 22 "cuelang.org/go/cue/token" 23 "cuelang.org/go/internal" 24 ) 25 26 // TestInvalidAST verifies behavior for various invalid AST inputs. In some 27 // cases it is okay to be permissive, as long as the output is correct. 28 func TestInvalidAST(t *testing.T) { 29 ident := func(s string) *ast.Ident { 30 return &ast.Ident{NamePos: token.NoSpace.Pos(), Name: s} 31 } 32 testCases := []struct { 33 desc string 34 node ast.Node 35 out string 36 }{{ 37 desc: "label sequence for definition", 38 node: &ast.Field{Label: ident("foo"), Value: ast.NewStruct( 39 ident("#bar"), token.COLON, &ast.StructLit{}, 40 )}, 41 // Force a new struct. 42 out: `foo: { 43 #bar: {} 44 }`, 45 }, { 46 desc: "label with invalid identifier", 47 node: &ast.Field{Label: &ast.Ident{}, Value: ast.NewString("foo")}, 48 // Force a new struct. 49 out: `"": "foo"`, 50 }, { 51 desc: "ImportDecl without parens, but imports with comments", 52 node: func() ast.Node { 53 n := ast.NewImport(nil, "time") 54 ast.AddComment(n, internal.NewComment(true, "hello")) 55 return &ast.ImportDecl{Specs: []*ast.ImportSpec{n}} 56 }(), 57 out: `import ( 58 // hello 59 "time" 60 )`, 61 }} 62 for _, tc := range testCases { 63 t.Run(tc.desc, func(t *testing.T) { 64 b, err := Node(tc.node) 65 if err != nil { 66 t.Fatal(err) 67 } 68 got := string(b) 69 want := tc.out 70 if got != want { 71 t.Errorf("\ngot %v;\nwant %v", got, want) 72 } 73 }) 74 } 75 } 76 77 func TestErrors(t *testing.T) { 78 testCases := []struct { 79 desc string 80 node ast.Node 81 err string 82 }{{ 83 desc: "empty identifier", 84 node: ast.NewIdent(""), 85 err: "invalid identifier", 86 }} 87 for _, tc := range testCases { 88 t.Run(tc.desc, func(t *testing.T) { 89 b, err := Node(tc.node) 90 if err == nil { 91 t.Fatalf("expected error, found %q", b) 92 } 93 got := err.Error() 94 if !strings.Contains(got, tc.err) { 95 t.Errorf("\ngot %v;\nwant %v", got, tc.err) 96 } 97 }) 98 } 99 }