2019-12-20 21:30:05 +00:00
|
|
|
package errs
|
2019-11-27 20:25:40 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"testing"
|
2024-02-28 12:18:10 +00:00
|
|
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
2019-11-27 20:25:40 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestError_MarshalJSON(t *testing.T) {
|
|
|
|
type fields struct {
|
|
|
|
Status int
|
|
|
|
Err error
|
|
|
|
}
|
|
|
|
tests := []struct {
|
|
|
|
name string
|
|
|
|
fields fields
|
|
|
|
want []byte
|
|
|
|
wantErr bool
|
|
|
|
}{
|
|
|
|
{"ok", fields{400, fmt.Errorf("bad request")}, []byte(`{"status":400,"message":"Bad Request"}`), false},
|
|
|
|
{"ok no error", fields{500, nil}, []byte(`{"status":500,"message":"Internal Server Error"}`), false},
|
|
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
|
|
t.Run(tt.name, func(t *testing.T) {
|
2019-12-20 21:30:05 +00:00
|
|
|
e := &Error{
|
2019-11-27 20:25:40 +00:00
|
|
|
Status: tt.fields.Status,
|
|
|
|
Err: tt.fields.Err,
|
|
|
|
}
|
|
|
|
got, err := e.MarshalJSON()
|
2024-02-28 12:18:10 +00:00
|
|
|
if tt.wantErr {
|
|
|
|
assert.Error(t, err)
|
|
|
|
assert.Empty(t, got)
|
2019-11-27 20:25:40 +00:00
|
|
|
return
|
|
|
|
}
|
2024-02-28 12:18:10 +00:00
|
|
|
|
|
|
|
assert.NoError(t, err)
|
|
|
|
assert.Equal(t, tt.want, got)
|
2019-11-27 20:25:40 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestError_UnmarshalJSON(t *testing.T) {
|
|
|
|
type args struct {
|
|
|
|
data []byte
|
|
|
|
}
|
|
|
|
tests := []struct {
|
|
|
|
name string
|
|
|
|
args args
|
2019-12-20 21:30:05 +00:00
|
|
|
expected *Error
|
2019-11-27 20:25:40 +00:00
|
|
|
wantErr bool
|
|
|
|
}{
|
2019-12-20 21:30:05 +00:00
|
|
|
{"ok", args{[]byte(`{"status":400,"message":"bad request"}`)}, &Error{Status: 400, Err: fmt.Errorf("bad request")}, false},
|
|
|
|
{"fail", args{[]byte(`{"status":"400","message":"bad request"}`)}, &Error{}, true},
|
2019-11-27 20:25:40 +00:00
|
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
|
|
t.Run(tt.name, func(t *testing.T) {
|
2019-12-20 21:30:05 +00:00
|
|
|
e := new(Error)
|
2024-02-28 12:18:10 +00:00
|
|
|
err := e.UnmarshalJSON(tt.args.data)
|
|
|
|
if tt.wantErr {
|
|
|
|
assert.Error(t, err)
|
|
|
|
return
|
2019-11-27 20:25:40 +00:00
|
|
|
}
|
2024-02-28 12:18:10 +00:00
|
|
|
|
|
|
|
assert.NoError(t, err)
|
|
|
|
assert.Equal(t, tt.expected, e)
|
2019-11-27 20:25:40 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|