errors_test.go 1.7 KB

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