statistics.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package reporting
  2. import (
  3. "fmt"
  4. "sync"
  5. )
  6. func (self *statistics) BeginStory(story *StoryReport) {}
  7. func (self *statistics) Enter(scope *ScopeReport) {}
  8. func (self *statistics) Report(report *AssertionResult) {
  9. self.Lock()
  10. defer self.Unlock()
  11. if !self.failing && report.Failure != "" {
  12. self.failing = true
  13. }
  14. if !self.erroring && report.Error != nil {
  15. self.erroring = true
  16. }
  17. if report.Skipped {
  18. self.skipped += 1
  19. } else {
  20. self.total++
  21. }
  22. }
  23. func (self *statistics) Exit() {}
  24. func (self *statistics) EndStory() {
  25. self.Lock()
  26. defer self.Unlock()
  27. if !self.suppressed {
  28. self.printSummaryLocked()
  29. }
  30. }
  31. func (self *statistics) Suppress() {
  32. self.Lock()
  33. defer self.Unlock()
  34. self.suppressed = true
  35. }
  36. func (self *statistics) PrintSummary() {
  37. self.Lock()
  38. defer self.Unlock()
  39. self.printSummaryLocked()
  40. }
  41. func (self *statistics) printSummaryLocked() {
  42. self.reportAssertionsLocked()
  43. self.reportSkippedSectionsLocked()
  44. self.completeReportLocked()
  45. }
  46. func (self *statistics) reportAssertionsLocked() {
  47. self.decideColorLocked()
  48. self.out.Print("\n%d total %s", self.total, plural("assertion", self.total))
  49. }
  50. func (self *statistics) decideColorLocked() {
  51. if self.failing && !self.erroring {
  52. fmt.Print(yellowColor)
  53. } else if self.erroring {
  54. fmt.Print(redColor)
  55. } else {
  56. fmt.Print(greenColor)
  57. }
  58. }
  59. func (self *statistics) reportSkippedSectionsLocked() {
  60. if self.skipped > 0 {
  61. fmt.Print(yellowColor)
  62. self.out.Print(" (one or more sections skipped)")
  63. }
  64. }
  65. func (self *statistics) completeReportLocked() {
  66. fmt.Print(resetColor)
  67. self.out.Print("\n")
  68. self.out.Print("\n")
  69. }
  70. func (self *statistics) Write(content []byte) (written int, err error) {
  71. return len(content), nil // no-op
  72. }
  73. func NewStatisticsReporter(out *Printer) *statistics {
  74. self := statistics{}
  75. self.out = out
  76. return &self
  77. }
  78. type statistics struct {
  79. sync.Mutex
  80. out *Printer
  81. total int
  82. failing bool
  83. erroring bool
  84. skipped int
  85. suppressed bool
  86. }
  87. func plural(word string, count int) string {
  88. if count == 1 {
  89. return word
  90. }
  91. return word + "s"
  92. }