summaryrefslogtreecommitdiff
path: root/src/cmd/gofmt/gofmt_test.go
blob: 2e35ce9a442fdaafa87d9642bb61e11180eb6039 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"bytes"
	"io/ioutil"
	"path/filepath"
	"strings"
	"testing"
)

func runTest(t *testing.T, dirname, in, out, flags string) {
	in = filepath.Join(dirname, in)
	out = filepath.Join(dirname, out)

	// process flags
	*simplifyAST = false
	*rewriteRule = ""
	for _, flag := range strings.Split(flags, " ") {
		elts := strings.SplitN(flag, "=", 2)
		name := elts[0]
		value := ""
		if len(elts) == 2 {
			value = elts[1]
		}
		switch name {
		case "":
			// no flags
		case "-r":
			*rewriteRule = value
		case "-s":
			*simplifyAST = true
		default:
			t.Errorf("unrecognized flag name: %s", name)
		}
	}

	initParserMode()
	initPrinterMode()
	initRewrite()

	var buf bytes.Buffer
	err := processFile(in, nil, &buf)
	if err != nil {
		t.Error(err)
		return
	}

	expected, err := ioutil.ReadFile(out)
	if err != nil {
		t.Error(err)
		return
	}

	if got := buf.Bytes(); bytes.Compare(got, expected) != 0 {
		t.Errorf("(gofmt %s) != %s (see %s.gofmt)", in, out, in)
		ioutil.WriteFile(in+".gofmt", got, 0666)
	}
}

// TODO(gri) Add more test cases!
var tests = []struct {
	dirname, in, out, flags string
}{
	{".", "gofmt.go", "gofmt.go", ""},
	{".", "gofmt_test.go", "gofmt_test.go", ""},
	{"testdata", "composites.input", "composites.golden", "-s"},
	{"testdata", "rewrite1.input", "rewrite1.golden", "-r=Foo->Bar"},
	{"testdata", "rewrite2.input", "rewrite2.golden", "-r=int->bool"},
}

func TestRewrite(t *testing.T) {
	for _, test := range tests {
		runTest(t, test.dirname, test.in, test.out, test.flags)
	}
}