serializer.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package assertions
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/smartystreets/assertions/internal/go-render/render"
  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 := FailureView{
  14. Message: message,
  15. Expected: render.Render(expected),
  16. Actual: render.Render(actual),
  17. }
  18. serialized, err := json.Marshal(view)
  19. if err != nil {
  20. return message
  21. }
  22. return string(serialized)
  23. }
  24. func (self *failureSerializer) serialize(expected, actual interface{}, message string) string {
  25. view := FailureView{
  26. Message: message,
  27. Expected: fmt.Sprintf("%+v", expected),
  28. Actual: fmt.Sprintf("%+v", actual),
  29. }
  30. serialized, err := json.Marshal(view)
  31. if err != nil {
  32. return message
  33. }
  34. return string(serialized)
  35. }
  36. func newSerializer() *failureSerializer {
  37. return &failureSerializer{}
  38. }
  39. ///////////////////////////////////////////////////////////////////////////////
  40. // This struct is also declared in github.com/smartystreets/goconvey/convey/reporting.
  41. // The json struct tags should be equal in both declarations.
  42. type FailureView struct {
  43. Message string `json:"Message"`
  44. Expected string `json:"Expected"`
  45. Actual string `json:"Actual"`
  46. }
  47. ///////////////////////////////////////////////////////
  48. // noopSerializer just gives back the original message. This is useful when we are using
  49. // the assertions from a context other than the web UI, that requires the JSON structure
  50. // provided by the failureSerializer.
  51. type noopSerializer struct{}
  52. func (self *noopSerializer) serialize(expected, actual interface{}, message string) string {
  53. return message
  54. }
  55. func (self *noopSerializer) serializeDetailed(expected, actual interface{}, message string) string {
  56. return message
  57. }