| 1 |
// Copyright 2011 The Go Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
package ast |
| 6 |
|
| 7 |
import ( |
| 8 |
"strings" |
| 9 |
"testing" |
| 10 |
) |
| 11 |
|
| 12 |
var tests = []struct { |
| 13 |
x any // x is printed as s |
| 14 |
s string |
| 15 |
}{ |
| 16 |
// basic types |
| 17 |
{nil, "0 nil"}, |
| 18 |
{true, "0 true"}, |
| 19 |
{42, "0 42"}, |
| 20 |
{3.14, "0 3.14"}, |
| 21 |
{1 + 2.718i, "0 (1+2.718i)"}, |
| 22 |
{"foobar", "0 \"foobar\""}, |
| 23 |
|
| 24 |
// maps |
| 25 |
{map[Expr]string{}, `0 map[ast.Expr]string (len = 0) {}`}, |
| 26 |
{map[string]int{"a": 1}, |
| 27 |
`0 map[string]int (len = 1) { |
| 28 |
1 . "a": 1 |
| 29 |
2 }`}, |
| 30 |
|
| 31 |
// pointers |
| 32 |
{new(int), "0 *0"}, |
| 33 |
|
| 34 |
// arrays |
| 35 |
{[0]int{}, `0 [0]int {}`}, |
| 36 |
{[3]int{1, 2, 3}, |
| 37 |
`0 [3]int { |
| 38 |
1 . 0: 1 |
| 39 |
2 . 1: 2 |
| 40 |
3 . 2: 3 |
| 41 |
4 }`}, |
| 42 |
{[...]int{42}, |
| 43 |
`0 [1]int { |
| 44 |
1 . 0: 42 |
| 45 |
2 }`}, |
| 46 |
|
| 47 |
// slices |
| 48 |
{[]int{}, `0 []int (len = 0) {}`}, |
| 49 |
{[]int{1, 2, 3}, |
| 50 |
`0 []int (len = 3) { |
| 51 |
1 . 0: 1 |
| 52 |
2 . 1: 2 |
| 53 |
3 . 2: 3 |
| 54 |
4 }`}, |
| 55 |
|
| 56 |
// structs |
| 57 |
{struct{}{}, `0 struct {} {}`}, |
| 58 |
{struct{ x int }{007}, `0 struct { x int } {}`}, |
| 59 |
{struct{ X, y int }{42, 991}, |
| 60 |
`0 struct { X int; y int } { |
| 61 |
1 . X: 42 |
| 62 |
2 }`}, |
| 63 |
{struct{ X, Y int }{42, 991}, |
| 64 |
`0 struct { X int; Y int } { |
| 65 |
1 . X: 42 |
| 66 |
2 . Y: 991 |
| 67 |
3 }`}, |
| 68 |
} |
| 69 |
|
| 70 |
// Split s into lines, trim whitespace from all lines, and return |
| 71 |
// the concatenated non-empty lines. |
| 72 |
func trim(s string) string { |
| 73 |
lines := strings.Split(s, "\n") |
| 74 |
i := 0 |
| 75 |
for _, line := range lines { |
| 76 |
line = strings.TrimSpace(line) |
| 77 |
if line != "" { |
| 78 |
lines[i] = line |
| 79 |
i++ |
| 80 |
} |
| 81 |
} |
| 82 |
return strings.Join(lines[0:i], "\n") |
| 83 |
} |
| 84 |
|
| 85 |
func TestPrint(t *testing.T) { |
| 86 |
var buf strings.Builder |
| 87 |
for _, test := range tests { |
| 88 |
buf.Reset() |
| 89 |
if err := Fprint(&buf, nil, test.x, nil); err != nil { |
| 90 |
t.Errorf("Fprint failed: %s", err) |
| 91 |
} |
| 92 |
if s, ts := trim(buf.String()), trim(test.s); s != ts { |
| 93 |
t.Errorf("got:\n%s\nexpected:\n%s\n", s, ts) |
| 94 |
} |
| 95 |
} |
| 96 |
} |