1// Copyright 2018 The 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
15package ast_test
16
17import (
18	"testing"
19
20	"github.com/stretchr/testify/assert"
21
22	"cuelang.org/go/cue/ast"
23	"cuelang.org/go/cue/parser"
24)
25
26func TestCommentText(t *testing.T) {
27	testCases := []struct {
28		list []string
29		text string
30	}{
31		{[]string{"//"}, ""},
32		{[]string{"//   "}, ""},
33		{[]string{"//", "//", "//   "}, ""},
34		{[]string{"// foo   "}, "foo\n"},
35		{[]string{"//", "//", "// foo"}, "foo\n"},
36		{[]string{"// foo  bar  "}, "foo  bar\n"},
37		{[]string{"// foo", "// bar"}, "foo\nbar\n"},
38		{[]string{"// foo", "//", "//", "//", "// bar"}, "foo\n\nbar\n"},
39		{[]string{"// foo", "/* bar */"}, "foo\n bar\n"},
40		{[]string{"//", "//", "//", "// foo", "//", "//", "//"}, "foo\n"},
41
42		{[]string{"/**/"}, ""},
43		{[]string{"/*   */"}, ""},
44		{[]string{"/**/", "/**/", "/*   */"}, ""},
45		{[]string{"/* Foo   */"}, " Foo\n"},
46		{[]string{"/* Foo  Bar  */"}, " Foo  Bar\n"},
47		{[]string{"/* Foo*/", "/* Bar*/"}, " Foo\n Bar\n"},
48		{[]string{"/* Foo*/", "/**/", "/**/", "/**/", "// Bar"}, " Foo\n\nBar\n"},
49		{[]string{"/* Foo*/", "/*\n*/", "//", "/*\n*/", "// Bar"}, " Foo\n\nBar\n"},
50		{[]string{"/* Foo*/", "// Bar"}, " Foo\nBar\n"},
51		{[]string{"/* Foo\n Bar*/"}, " Foo\n Bar\n"},
52	}
53
54	for i, c := range testCases {
55		list := make([]*ast.Comment, len(c.list))
56		for i, s := range c.list {
57			list[i] = &ast.Comment{Text: s}
58		}
59
60		text := (&ast.CommentGroup{List: list}).Text()
61		if text != c.text {
62			t.Errorf("case %d: got %q; expected %q", i, text, c.text)
63		}
64	}
65}
66
67func TestPackageName(t *testing.T) {
68	testCases := []struct {
69		input string
70		pkg   string
71	}{{
72		input: `
73		package foo
74		`,
75		pkg: "foo",
76	}, {
77		input: `
78		a: 2
79		`,
80	}, {
81		input: `
82		// Comment
83
84		// Package foo ...
85		package foo
86		`,
87		pkg: "foo",
88	}}
89	for _, tc := range testCases {
90		t.Run("", func(t *testing.T) {
91			f, err := parser.ParseFile("test", tc.input)
92			if err != nil {
93				t.Fatal(err)
94			}
95			assert.Equal(t, f.PackageName(), tc.pkg)
96		})
97	}
98}
99