twitter: Tidy test coverage

This commit is contained in:
Rob Watson 2022-05-23 05:11:17 +02:00
parent 2bca3c882f
commit 993f07c08e
1 changed files with 22 additions and 11 deletions

View File

@ -1,6 +1,7 @@
package twitter_test
import (
"errors"
"io"
"net/http"
"strings"
@ -16,6 +17,7 @@ func TestGetMe(t *testing.T) {
name string
responseStatusCode int
responseBody io.Reader
responseErr error
wantUser *twitter.User
wantErr string
}{
@ -25,6 +27,11 @@ func TestGetMe(t *testing.T) {
responseBody: strings.NewReader(`{"Data": {"id": "1", "name": "foo", "username": "foo bar"}}`),
wantUser: &twitter.User{ID: "1", Name: "foo", Username: "foo bar"},
},
{
name: "network error",
responseErr: errors.New("boom"),
wantErr: "error fetching resource: boom",
},
{
name: "500 response",
responseStatusCode: 500,
@ -46,7 +53,7 @@ func TestGetMe(t *testing.T) {
var getter mocks.Getter
getter.
On("Get", "https://api.twitter.com/2/users/me").
Return(&http.Response{StatusCode: tc.responseStatusCode, Body: io.NopCloser(tc.responseBody)}, nil)
Return(&http.Response{StatusCode: tc.responseStatusCode, Body: io.NopCloser(tc.responseBody)}, tc.responseErr)
client := twitter.NewAPIClient(&getter)
user, err := client.GetMe()
@ -62,26 +69,32 @@ func TestGetMe(t *testing.T) {
}
func TestGetTweets(t *testing.T) {
const (
userID = "1"
sinceID = "2"
)
testCases := []struct {
name string
userID, sinceID string
responseStatusCode int
responseBody io.Reader
responseErr error
wantTweets []*twitter.Tweet
wantErr string
}{
{
name: "successful request",
userID: "1",
sinceID: "1000",
responseStatusCode: 200,
responseBody: strings.NewReader(`{"Data": [{"id": "101", "text": "foo"}, {"id": "102", "text": "bar"}]}`),
wantTweets: []*twitter.Tweet{{ID: "101", Text: "foo"}, {ID: "102", Text: "bar"}},
},
{
name: "network error",
responseErr: errors.New("network error"),
wantTweets: nil,
wantErr: "error fetching resource: network error",
},
{
name: "500 response",
userID: "1",
sinceID: "1000",
responseStatusCode: 500,
responseBody: strings.NewReader("whale"),
wantTweets: nil,
@ -89,8 +102,6 @@ func TestGetTweets(t *testing.T) {
},
{
name: "decoder error",
userID: "1",
sinceID: "1000",
responseStatusCode: 200,
responseBody: strings.NewReader("<html></html>"),
wantTweets: nil,
@ -102,11 +113,11 @@ func TestGetTweets(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
var getter mocks.Getter
getter.
On("Get", "https://api.twitter.com/2/users/"+tc.userID+"/tweets?since_id="+tc.sinceID).
Return(&http.Response{StatusCode: tc.responseStatusCode, Body: io.NopCloser(tc.responseBody)}, nil)
On("Get", "https://api.twitter.com/2/users/"+userID+"/tweets?since_id="+sinceID).
Return(&http.Response{StatusCode: tc.responseStatusCode, Body: io.NopCloser(tc.responseBody)}, tc.responseErr)
client := twitter.NewAPIClient(&getter)
tweets, err := client.GetTweets(tc.userID, tc.sinceID)
tweets, err := client.GetTweets(userID, sinceID)
assert.Equal(t, tc.wantTweets, tweets)
if tc.wantErr == "" {