-
Notifications
You must be signed in to change notification settings - Fork 0
/
assert.go
70 lines (64 loc) · 1.4 KB
/
assert.go
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
package assert
import (
"bytes"
"fmt"
"runtime"
"strings"
"testing"
)
func On(t *testing.T) *Assert {
return &Assert{
t: t,
}
}
type Assert struct {
t *testing.T
}
func (v *Assert) Fail(message string) {
fmt.Println(decorate(message))
v.t.Fail()
}
func getCaller() (string, int) {
stackLevel := 3
for {
_, file, line, ok := runtime.Caller(stackLevel)
if strings.Contains(file, "assert") {
stackLevel++
} else {
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
}
return file, line
}
}
}
// 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 := getCaller()
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()
}