Skip to content

Commit

Permalink
Merge pull request #115 from jarcoal/responder-delay
Browse files Browse the repository at this point in the history
feat(Responder): add Delay(time.Duration) method
  • Loading branch information
maxatome authored Dec 18, 2021
2 parents 7aa310d + b88dbe7 commit 8c2c5b7
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
21 changes: 21 additions & 0 deletions response.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"strconv"
"strings"
"sync"
"time"

"github.com/jarcoal/httpmock/internal"
)
Expand Down Expand Up @@ -101,6 +102,26 @@ func (r Responder) Trace(fn func(...interface{})) Responder {
}
}

// Delay returns a new Responder that calls the original r Responder
// after a delay of d.
// import (
// "testing"
// "time"
// "github.com/jarcoal/httpmock"
// )
// ...
// func TestMyApp(t *testing.T) {
// ...
// httpmock.RegisterResponder("GET", "/foo/bar",
// httpmock.NewStringResponder(200, "{}").Delay(100*time.Millisecond),
// )
func (r Responder) Delay(d time.Duration) Responder {
return func(req *http.Request) (*http.Response, error) {
time.Sleep(d)
return r(req)
}
}

// ResponderFromResponse wraps an *http.Response in a Responder.
//
// Be careful, except for responses generated by httpmock
Expand Down
12 changes: 12 additions & 0 deletions response_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"strings"
"sync"
"testing"
"time"

. "github.com/jarcoal/httpmock"
"github.com/jarcoal/httpmock/internal"
Expand Down Expand Up @@ -597,6 +598,17 @@ func TestResponder(t *testing.T) {

chk(rt, resp, "")
chkCalled()

//
// Delay
rt = r.Delay(100 * time.Millisecond)
before := time.Now()
chk(rt, resp, "")
duration := time.Since(before)
chkCalled()
if duration < 100*time.Millisecond {
t.Errorf("Responder is not delayed, only %s elapsed", duration)
}
}

func TestParallelResponder(t *testing.T) {
Expand Down

0 comments on commit 8c2c5b7

Please sign in to comment.