2016-06-12 20:19:23 +02:00
|
|
|
package main
|
2016-03-28 10:17:41 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2016-09-24 09:51:02 +02:00
|
|
|
"fmt"
|
2016-03-28 10:17:41 +02:00
|
|
|
"io"
|
2016-09-24 09:51:02 +02:00
|
|
|
"os"
|
|
|
|
"strings"
|
2016-03-28 10:17:41 +02:00
|
|
|
"testing"
|
|
|
|
)
|
|
|
|
|
2016-04-06 22:10:12 +02:00
|
|
|
type NopWriteCloser struct {
|
|
|
|
io.Writer
|
|
|
|
}
|
2016-03-28 10:17:41 +02:00
|
|
|
|
2016-04-06 22:10:12 +02:00
|
|
|
func (NopWriteCloser) Close() error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func nopCloser(w io.Writer) io.WriteCloser {
|
|
|
|
return NopWriteCloser{w}
|
|
|
|
}
|
|
|
|
|
2016-09-24 09:51:02 +02:00
|
|
|
func TestWriteFile(t *testing.T) {
|
2016-08-18 14:29:14 +02:00
|
|
|
// t.Parallel() cannot be used
|
|
|
|
|
2016-04-06 22:10:12 +02:00
|
|
|
// set the function pointer back to its original value
|
|
|
|
// after we modify it for the test
|
2016-09-24 09:51:02 +02:00
|
|
|
saveTestHarnessWriteFile := testHarnessWriteFile
|
2016-03-28 10:17:41 +02:00
|
|
|
defer func() {
|
2016-09-24 09:51:02 +02:00
|
|
|
testHarnessWriteFile = saveTestHarnessWriteFile
|
2016-03-28 10:17:41 +02:00
|
|
|
}()
|
|
|
|
|
2016-09-24 09:51:02 +02:00
|
|
|
var output []byte
|
|
|
|
testHarnessWriteFile = func(_ string, in []byte, _ os.FileMode) error {
|
|
|
|
output = in
|
|
|
|
return nil
|
2016-03-28 10:17:41 +02:00
|
|
|
}
|
|
|
|
|
2016-09-24 09:51:02 +02:00
|
|
|
buf := &bytes.Buffer{}
|
|
|
|
writePackageName(buf, "pkg")
|
|
|
|
fmt.Fprintf(buf, "func hello() {}\n\n\nfunc world() {\nreturn\n}\n\n\n\n")
|
2016-03-28 10:17:41 +02:00
|
|
|
|
2016-09-24 09:51:02 +02:00
|
|
|
if err := writeFile("", "", buf); err != nil {
|
2016-03-28 10:17:41 +02:00
|
|
|
t.Error(err)
|
|
|
|
}
|
|
|
|
|
2016-09-24 09:51:02 +02:00
|
|
|
if string(output) != "package pkg\n\nfunc hello() {}\n\nfunc world() {\n\treturn\n}\n" {
|
|
|
|
t.Errorf("Wrong output: %q", output)
|
2016-03-28 10:17:41 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-09-24 09:51:02 +02:00
|
|
|
func TestFormatBuffer(t *testing.T) {
|
|
|
|
t.Parallel()
|
2016-03-28 10:17:41 +02:00
|
|
|
|
2016-09-24 09:51:02 +02:00
|
|
|
buf := &bytes.Buffer{}
|
2016-03-28 10:17:41 +02:00
|
|
|
|
2016-09-24 09:51:02 +02:00
|
|
|
fmt.Fprintf(buf, "package pkg\n\nfunc() {a}\n")
|
2016-03-28 10:17:41 +02:00
|
|
|
|
2016-09-24 09:51:02 +02:00
|
|
|
// Only test error case - happy case is taken care of by template test
|
|
|
|
_, err := formatBuffer(buf)
|
|
|
|
if err == nil {
|
|
|
|
t.Error("want an error")
|
2016-03-28 10:17:41 +02:00
|
|
|
}
|
|
|
|
|
2016-09-24 09:51:02 +02:00
|
|
|
if txt := err.Error(); !strings.Contains(txt, ">>>> func() {a}") {
|
|
|
|
t.Error("got:\n", txt)
|
2016-03-28 10:17:41 +02:00
|
|
|
}
|
|
|
|
}
|