4
0

errors_test.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package errs
  2. import (
  3. "fmt"
  4. "reflect"
  5. "testing"
  6. )
  7. func TestError_MarshalJSON(t *testing.T) {
  8. type fields struct {
  9. Status int
  10. Err error
  11. }
  12. tests := []struct {
  13. name string
  14. fields fields
  15. want []byte
  16. wantErr bool
  17. }{
  18. {"ok", fields{400, fmt.Errorf("bad request")}, []byte(`{"status":400,"message":"Bad Request"}`), false},
  19. {"ok no error", fields{500, nil}, []byte(`{"status":500,"message":"Internal Server Error"}`), false},
  20. }
  21. for _, tt := range tests {
  22. t.Run(tt.name, func(t *testing.T) {
  23. e := &Error{
  24. Status: tt.fields.Status,
  25. Err: tt.fields.Err,
  26. }
  27. got, err := e.MarshalJSON()
  28. if (err != nil) != tt.wantErr {
  29. t.Errorf("Error.MarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
  30. return
  31. }
  32. if !reflect.DeepEqual(got, tt.want) {
  33. t.Errorf("Error.MarshalJSON() = %s, want %s", got, tt.want)
  34. }
  35. })
  36. }
  37. }
  38. func TestError_UnmarshalJSON(t *testing.T) {
  39. type args struct {
  40. data []byte
  41. }
  42. tests := []struct {
  43. name string
  44. args args
  45. expected *Error
  46. wantErr bool
  47. }{
  48. {"ok", args{[]byte(`{"status":400,"message":"bad request"}`)}, &Error{Status: 400, Err: fmt.Errorf("bad request")}, false},
  49. {"fail", args{[]byte(`{"status":"400","message":"bad request"}`)}, &Error{}, true},
  50. }
  51. for _, tt := range tests {
  52. t.Run(tt.name, func(t *testing.T) {
  53. e := new(Error)
  54. if err := e.UnmarshalJSON(tt.args.data); (err != nil) != tt.wantErr {
  55. t.Errorf("Error.UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
  56. }
  57. //nolint:govet // best option
  58. if !reflect.DeepEqual(tt.expected, e) {
  59. t.Errorf("Error.UnmarshalJSON() wants = %+v, got %+v", tt.expected, e)
  60. }
  61. })
  62. }
  63. }