serializer.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package assertions
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/smartystreets/goconvey/convey/reporting"
  6. )
  7. type Serializer interface {
  8. serialize(expected, actual interface{}, message string) string
  9. serializeDetailed(expected, actual interface{}, message string) string
  10. }
  11. type failureSerializer struct{}
  12. func (self *failureSerializer) serializeDetailed(expected, actual interface{}, message string) string {
  13. view := self.format(expected, actual, message, "%#v")
  14. serialized, err := json.Marshal(view)
  15. if err != nil {
  16. return message
  17. }
  18. return string(serialized)
  19. }
  20. func (self *failureSerializer) serialize(expected, actual interface{}, message string) string {
  21. view := self.format(expected, actual, message, "%+v")
  22. serialized, err := json.Marshal(view)
  23. if err != nil {
  24. return message
  25. }
  26. return string(serialized)
  27. }
  28. func (self *failureSerializer) format(expected, actual interface{}, message string, format string) reporting.FailureView {
  29. return reporting.FailureView{
  30. Message: message,
  31. Expected: fmt.Sprintf(format, expected),
  32. Actual: fmt.Sprintf(format, actual),
  33. }
  34. }
  35. func newSerializer() *failureSerializer {
  36. return &failureSerializer{}
  37. }
  38. ///////////////////////////////////////////////////////
  39. // noopSerializer just gives back the original message. This is useful when we are using
  40. // the assertions from a context other than the web UI, that requires the JSON structure
  41. // provided by the failureSerializer.
  42. type noopSerializer struct{}
  43. func (self *noopSerializer) serialize(expected, actual interface{}, message string) string {
  44. return message
  45. }
  46. func (self *noopSerializer) serializeDetailed(expected, actual interface{}, message string) string {
  47. return message
  48. }