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.
16
const testfile = "format_test.go"
18
func diff(t *testing.T, dst, src []byte) {
20
offs := 0 // line offset
21
for i := 0; i < len(dst) && i < len(src); i++ {
25
t.Errorf("dst:%d: %s\n", line, dst[offs:i+1])
26
t.Errorf("src:%d: %s\n", line, src[offs:i+1])
34
if len(dst) != len(src) {
35
t.Errorf("len(dst) = %d, len(src) = %d\nsrc = %q", len(dst), len(src), src)
39
func TestNode(t *testing.T) {
40
src, err := ioutil.ReadFile(testfile)
45
fset := token.NewFileSet()
46
file, err := parser.ParseFile(fset, testfile, src, parser.ParseComments)
53
if err = Node(&buf, fset, file); err != nil {
54
t.Fatal("Node failed:", err)
57
diff(t, buf.Bytes(), src)
60
func TestSource(t *testing.T) {
61
src, err := ioutil.ReadFile(testfile)
66
res, err := Source(src)
68
t.Fatal("Source failed:", err)
74
// Test cases that are expected to fail are marked by the prefix "ERROR".
79
"var x int\n\ntype T struct{}",
83
"f(a, b, c)\nvar x int = f(1, 2, 3)",
85
// indentation, leading and trailing space
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
98
func String(s string) (string, error) {
99
res, err := Source([]byte(s))
103
return string(res), nil
106
func TestPartial(t *testing.T) {
107
for _, src := range tests {
108
if strings.HasPrefix(src, "ERROR") {
109
// test expected to fail
110
src = src[5:] // remove ERROR prefix
111
res, err := String(src)
112
if err == nil && res == src {
113
t.Errorf("formatting succeeded but was expected to fail:\n%q", src)
116
// test expected to succeed
117
res, err := String(src)
119
t.Errorf("formatting failed (%s):\n%q", err, src)
120
} else if res != src {
121
t.Errorf("formatting incorrect:\nsource: %q\nresult: %q", src, res)