From e83eec9479533c5d32f6717f5e2074d5c5933323 Mon Sep 17 00:00:00 2001 From: V2Ray Date: Thu, 24 Sep 2015 21:46:25 +0200 Subject: [PATCH] Print out the correct point of error --- testing/unit/subject.go | 44 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/testing/unit/subject.go b/testing/unit/subject.go index f1db48323..9f7cb79ad 100644 --- a/testing/unit/subject.go +++ b/testing/unit/subject.go @@ -1,5 +1,12 @@ package unit +import ( + "bytes" + "fmt" + "runtime" + "strings" +) + type Subject struct { assert *Assertion name string @@ -12,8 +19,43 @@ func NewSubject(assert *Assertion) *Subject { } } +// decorate prefixes the string with the file and line of the call site +// and inserts the final newline if needed and indentation tabs for formatting. +func decorate(s string) string { + _, file, line, ok := runtime.Caller(4) // decorate + log + public function. + if ok { + // Truncate file name at last file name separator. + if index := strings.LastIndex(file, "/"); index >= 0 { + file = file[index+1:] + } else if index = strings.LastIndex(file, "\\"); index >= 0 { + file = file[index+1:] + } + } else { + file = "???" + line = 1 + } + buf := new(bytes.Buffer) + // Every line is indented at least one tab. + buf.WriteString(" ") + fmt.Fprintf(buf, "%s:%d: ", file, line) + lines := strings.Split(s, "\n") + if l := len(lines); l > 1 && lines[l-1] == "" { + lines = lines[:l-1] + } + for i, line := range lines { + if i > 0 { + // Second and subsequent lines are indented an extra tab. + buf.WriteString("\n\t\t") + } + buf.WriteString(line) + } + buf.WriteByte('\n') + return buf.String() +} + func (subject *Subject) FailWithMessage(message string) { - subject.assert.t.Error(message) + fmt.Println(decorate(message)) + subject.assert.t.Fail() } func (subject *Subject) Named(name string) {