serializer.go 2.0 KB

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