2021-08-14 17:42:28 +00:00
|
|
|
package reddit
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/DataDog/datadog-go/statsd"
|
2022-03-26 17:29:58 +00:00
|
|
|
"github.com/go-redis/redismock/v8"
|
2021-08-14 17:42:28 +00:00
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
)
|
|
|
|
|
|
|
|
// RoundTripFunc .
|
|
|
|
type RoundTripFunc func(req *http.Request) *http.Response
|
|
|
|
|
|
|
|
// RoundTrip .
|
|
|
|
func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
|
|
|
|
return f(req), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
//NewTestClient returns *http.Client with Transport replaced to avoid making real calls
|
|
|
|
func NewTestClient(fn RoundTripFunc) *http.Client {
|
|
|
|
return &http.Client{
|
|
|
|
Transport: RoundTripFunc(fn),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestErrorResponse(t *testing.T) {
|
2022-03-26 17:29:58 +00:00
|
|
|
db, _ := redismock.NewClientMock()
|
|
|
|
|
2022-03-26 17:40:51 +00:00
|
|
|
rc := NewClient("", "", &statsd.NoOpClient{}, db, 1, WithRetry(false))
|
2022-03-26 17:29:58 +00:00
|
|
|
rac := rc.NewAuthenticatedClient(SkipRateLimiting, "", "")
|
2021-08-14 17:42:28 +00:00
|
|
|
|
|
|
|
errortests := []struct {
|
|
|
|
name string
|
|
|
|
call func() error
|
|
|
|
|
|
|
|
status int
|
|
|
|
body string
|
|
|
|
err error
|
|
|
|
}{
|
2022-03-26 17:40:51 +00:00
|
|
|
{"/api/v1/me 500 returns ServerError", func() error { _, err := rac.Me(); return err }, 500, "", ServerError{500}},
|
|
|
|
{"/api/v1/access_token 400 returns ErrOauthRevoked", func() error { _, err := rac.RefreshTokens(); return err }, 400, "", ErrOauthRevoked},
|
|
|
|
{"/api/v1/message/inbox 403 returns ErrOauthRevoked", func() error { _, err := rac.MessageInbox(); return err }, 403, "", ErrOauthRevoked},
|
|
|
|
{"/api/v1/message/unread 403 returns ErrOauthRevoked", func() error { _, err := rac.MessageUnread(); return err }, 403, "", ErrOauthRevoked},
|
|
|
|
{"/api/v1/me 403 returns ErrOauthRevoked", func() error { _, err := rac.Me(); return err }, 403, "", ErrOauthRevoked},
|
2021-08-14 17:42:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
for _, tt := range errortests {
|
|
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
|
|
rac.client = NewTestClient(func(req *http.Request) *http.Response {
|
|
|
|
return &http.Response{
|
|
|
|
StatusCode: tt.status,
|
|
|
|
Body: ioutil.NopCloser(bytes.NewBufferString(tt.body)),
|
|
|
|
Header: make(http.Header),
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
err := tt.call()
|
|
|
|
|
|
|
|
assert.ErrorIs(t, err, tt.err)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|