Skip to content

Commit

Permalink
added SetTimeout() method on Client
Browse files Browse the repository at this point in the history
  • Loading branch information
utekaravinash committed Mar 3, 2020
1 parent 660db26 commit 3d2dc87
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
6 changes: 6 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"io/ioutil"
"net/http"
"time"

"github.com/utekaravinash/gopaapi5/api"
)
Expand Down Expand Up @@ -70,6 +71,11 @@ func NewClient(accessKey, secretKey, associateTag string, locale api.Locale) (*C
return client, nil
}

// SetTimeout sets a time limit for the operations made by the Client.
func (c *Client) SetTimeout(duration time.Duration) {
c.httpClient.Timeout = duration
}

// send sends a http request to Amazon Product Advertising service and returns response or error
func (c *Client) send(req *request, v interface{}) error {

Expand Down
57 changes: 57 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
package gopaapi5

import (
"io/ioutil"
"net/http"
"os"
"strings"
"testing"
"time"

"github.com/utekaravinash/gopaapi5/api"
)
Expand Down Expand Up @@ -59,3 +64,55 @@ func TestNewClient(t *testing.T) {
})
}
}

func TestSetTimeout(t *testing.T) {
params := api.GetItemsParams{
ItemIds: []string{"0892131349"},
}

client, _ := NewClient("accessKey", "secretKey", "associateTag", api.UnitedStates)
client.testing = true

h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(time.Nanosecond * 10)
file, err := os.Open("_response/get_items.json")
if err != nil {
t.Errorf("Cannot open _response/get_items.json")
}

jo, err := ioutil.ReadAll(file)
if err != nil {
t.Errorf("Cannot read _response/get_items.json")
}

w.Write(jo)
})

httpClient, teardown := testingHTTPClient(h)
defer teardown()

client.httpClient = httpClient

client.SetTimeout(time.Nanosecond * 1)
_, err1 := client.GetItems(&params)

client.SetTimeout(time.Hour * 1)
response, _ := client.GetItems(&params)

tests := []struct {
name string
expected interface{}
actual interface{}
}{
{"Request Timeout", true, strings.Contains(err1.Error(), "Client.Timeout exceeded while awaiting headers")},
{"Request Completed", 2, len(response.ItemsResult.Items)},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if test.expected != test.actual {
t.Errorf("Expected: %v, Actual: %v", test.expected, test.actual)
}
})
}
}

0 comments on commit 3d2dc87

Please sign in to comment.