json.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // TODO: under unit test
  2. package reporting
  3. import (
  4. "bytes"
  5. "encoding/json"
  6. "fmt"
  7. "strings"
  8. )
  9. type JsonReporter struct {
  10. out *Printer
  11. currentKey []string
  12. current *ScopeResult
  13. index map[string]*ScopeResult
  14. scopes []*ScopeResult
  15. }
  16. func (self *JsonReporter) depth() int { return len(self.currentKey) }
  17. func (self *JsonReporter) BeginStory(story *StoryReport) {}
  18. func (self *JsonReporter) Enter(scope *ScopeReport) {
  19. self.currentKey = append(self.currentKey, scope.Title)
  20. ID := strings.Join(self.currentKey, "|")
  21. if _, found := self.index[ID]; !found {
  22. next := newScopeResult(scope.Title, self.depth(), scope.File, scope.Line)
  23. self.scopes = append(self.scopes, next)
  24. self.index[ID] = next
  25. }
  26. self.current = self.index[ID]
  27. }
  28. func (self *JsonReporter) Report(report *AssertionResult) {
  29. self.current.Assertions = append(self.current.Assertions, report)
  30. }
  31. func (self *JsonReporter) Exit() {
  32. self.currentKey = self.currentKey[:len(self.currentKey)-1]
  33. }
  34. func (self *JsonReporter) EndStory() {
  35. self.report()
  36. self.reset()
  37. }
  38. func (self *JsonReporter) report() {
  39. scopes := []string{}
  40. for _, scope := range self.scopes {
  41. serialized, err := json.Marshal(scope)
  42. if err != nil {
  43. self.out.Println(jsonMarshalFailure)
  44. panic(err)
  45. }
  46. var buffer bytes.Buffer
  47. json.Indent(&buffer, serialized, "", " ")
  48. scopes = append(scopes, buffer.String())
  49. }
  50. self.out.Print(fmt.Sprintf("%s\n%s,\n%s\n", OpenJson, strings.Join(scopes, ","), CloseJson))
  51. }
  52. func (self *JsonReporter) reset() {
  53. self.scopes = []*ScopeResult{}
  54. self.index = map[string]*ScopeResult{}
  55. self.currentKey = nil
  56. }
  57. func (self *JsonReporter) Write(content []byte) (written int, err error) {
  58. self.current.Output += string(content)
  59. return len(content), nil
  60. }
  61. func NewJsonReporter(out *Printer) *JsonReporter {
  62. self := new(JsonReporter)
  63. self.out = out
  64. self.reset()
  65. return self
  66. }
  67. const OpenJson = ">->->OPEN-JSON->->->" // "⌦"
  68. const CloseJson = "<-<-<-CLOSE-JSON<-<-<" // "⌫"
  69. const jsonMarshalFailure = `
  70. GOCONVEY_JSON_MARSHALL_FAILURE: There was an error when attempting to convert test results to JSON.
  71. Please file a bug report and reference the code that caused this failure if possible.
  72. Here's the panic:
  73. `