subject.go 1.6 KB

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