github.com/flyinox/gosm@v0.0.0-20171117061539-16768cb62077/src/go/ast/print_test.go (about)

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