...
1
2
3
4
5
6
7
8
9
10
11
12
13
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
27
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
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
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 }
100
View as plain text