global.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package unit
  2. import (
  3. "bytes"
  4. "fmt"
  5. "runtime"
  6. "strings"
  7. "testing"
  8. )
  9. var tGlobal *testing.T
  10. func Current(t *testing.T) {
  11. tGlobal = t
  12. }
  13. func getCaller() (string, int) {
  14. stackLevel := 3
  15. for {
  16. _, file, line, ok := runtime.Caller(stackLevel)
  17. if strings.Contains(file, "assert") {
  18. stackLevel++
  19. } else {
  20. if ok {
  21. // Truncate file name at last file name separator.
  22. if index := strings.LastIndex(file, "/"); index >= 0 {
  23. file = file[index+1:]
  24. } else if index = strings.LastIndex(file, "\\"); index >= 0 {
  25. file = file[index+1:]
  26. }
  27. } else {
  28. file = "???"
  29. line = 1
  30. }
  31. return file, line
  32. }
  33. }
  34. }
  35. // decorate prefixes the string with the file and line of the call site
  36. // and inserts the final newline if needed and indentation tabs for formatting.
  37. func decorate(s string) string {
  38. file, line := getCaller()
  39. buf := new(bytes.Buffer)
  40. // Every line is indented at least one tab.
  41. buf.WriteString(" ")
  42. fmt.Fprintf(buf, "%s:%d: ", file, line)
  43. lines := strings.Split(s, "\n")
  44. if l := len(lines); l > 1 && lines[l-1] == "" {
  45. lines = lines[:l-1]
  46. }
  47. for i, line := range lines {
  48. if i > 0 {
  49. // Second and subsequent lines are indented an extra tab.
  50. buf.WriteString("\n\t\t")
  51. }
  52. buf.WriteString(line)
  53. }
  54. buf.WriteByte('\n')
  55. return buf.String()
  56. }
  57. func Fail(message string) {
  58. fmt.Println(decorate(message))
  59. tGlobal.Fail()
  60. }