github.com/varialus/godfly@v0.0.0-20130904042352-1934f9f095ab/src/pkg/go/format/format_test.go (about) 1 // Copyright 2012 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 format 6 7 import ( 8 "bytes" 9 "go/parser" 10 "go/token" 11 "io/ioutil" 12 "strings" 13 "testing" 14 ) 15 16 const testfile = "format_test.go" 17 18 func diff(t *testing.T, dst, src []byte) { 19 line := 1 20 offs := 0 // line offset 21 for i := 0; i < len(dst) && i < len(src); i++ { 22 d := dst[i] 23 s := src[i] 24 if d != s { 25 t.Errorf("dst:%d: %s\n", line, dst[offs:i+1]) 26 t.Errorf("src:%d: %s\n", line, src[offs:i+1]) 27 return 28 } 29 if s == '\n' { 30 line++ 31 offs = i + 1 32 } 33 } 34 if len(dst) != len(src) { 35 t.Errorf("len(dst) = %d, len(src) = %d\nsrc = %q", len(dst), len(src), src) 36 } 37 } 38 39 func TestNode(t *testing.T) { 40 src, err := ioutil.ReadFile(testfile) 41 if err != nil { 42 t.Fatal(err) 43 } 44 45 fset := token.NewFileSet() 46 file, err := parser.ParseFile(fset, testfile, src, parser.ParseComments) 47 if err != nil { 48 t.Fatal(err) 49 } 50 51 var buf bytes.Buffer 52 53 if err = Node(&buf, fset, file); err != nil { 54 t.Fatal("Node failed:", err) 55 } 56 57 diff(t, buf.Bytes(), src) 58 } 59 60 func TestSource(t *testing.T) { 61 src, err := ioutil.ReadFile(testfile) 62 if err != nil { 63 t.Fatal(err) 64 } 65 66 res, err := Source(src) 67 if err != nil { 68 t.Fatal("Source failed:", err) 69 } 70 71 diff(t, res, src) 72 } 73 74 // Test cases that are expected to fail are marked by the prefix "ERROR". 75 var tests = []string{ 76 // declaration lists 77 `import "go/format"`, 78 "var x int", 79 "var x int\n\ntype T struct{}", 80 81 // statement lists 82 "x := 0", 83 "f(a, b, c)\nvar x int = f(1, 2, 3)", 84 85 // indentation, leading and trailing space 86 "\tx := 0\n\tgo f()", 87 "\tx := 0\n\tgo f()\n\n\n", 88 "\n\t\t\n\n\tx := 0\n\tgo f()\n\n\n", 89 "\n\t\t\n\n\t\t\tx := 0\n\t\t\tgo f()\n\n\n", 90 "\n\t\t\n\n\t\t\tx := 0\n\t\t\tconst s = `\nfoo\n`\n\n\n", // no indentation inside raw strings 91 92 // erroneous programs 93 "ERROR1 + 2 +", 94 "ERRORx := 0", 95 } 96 97 func String(s string) (string, error) { 98 res, err := Source([]byte(s)) 99 if err != nil { 100 return "", err 101 } 102 return string(res), nil 103 } 104 105 func TestPartial(t *testing.T) { 106 for _, src := range tests { 107 if strings.HasPrefix(src, "ERROR") { 108 // test expected to fail 109 src = src[5:] // remove ERROR prefix 110 res, err := String(src) 111 if err == nil && res == src { 112 t.Errorf("formatting succeeded but was expected to fail:\n%q", src) 113 } 114 } else { 115 // test expected to succeed 116 res, err := String(src) 117 if err != nil { 118 t.Errorf("formatting failed (%s):\n%q", err, src) 119 } else if res != src { 120 t.Errorf("formatting incorrect:\nsource: %q\nresult: %q", src, res) 121 } 122 } 123 } 124 }