@@ -3,26 +3,65 @@ package queryrange
33import (
44 "context"
55 fmt "fmt"
6+ "net/http"
67 "sync/atomic"
78 "testing"
89
910 "github.com/go-kit/kit/log"
1011 "github.com/stretchr/testify/require"
12+ "github.com/weaveworks/common/httpgrpc"
1113)
1214
1315func TestRetry (t * testing.T ) {
14- try := int32 ( 0 )
16+ var try int32
1517
16- h := NewRetryMiddleware (log .NewNopLogger (), 5 ).Wrap (
17- HandlerFunc (func (_ context.Context , req * Request ) (* APIResponse , error ) {
18- if atomic .AddInt32 (& try , 1 ) == 5 {
19- return & APIResponse {Status : "Hello World" }, nil
20- }
21- return nil , fmt .Errorf ("fail" )
22- }),
23- )
24-
25- resp , err := h .Do (nil , nil )
26- require .NoError (t , err )
27- require .Equal (t , & APIResponse {Status : "Hello World" }, resp )
18+ for _ , tc := range []struct {
19+ name string
20+ handler Handler
21+ resp * APIResponse
22+ err error
23+ }{
24+ {
25+ name : "retry failures" ,
26+ handler : HandlerFunc (func (_ context.Context , req * Request ) (* APIResponse , error ) {
27+ if atomic .AddInt32 (& try , 1 ) == 5 {
28+ return & APIResponse {Status : "Hello World" }, nil
29+ }
30+ return nil , fmt .Errorf ("fail" )
31+ }),
32+ resp : & APIResponse {Status : "Hello World" },
33+ },
34+ {
35+ name : "don't retry 400s" ,
36+ handler : HandlerFunc (func (_ context.Context , req * Request ) (* APIResponse , error ) {
37+ return nil , httpgrpc .Errorf (http .StatusBadRequest , "Bad Request" )
38+ }),
39+ err : httpgrpc .Errorf (http .StatusBadRequest , "Bad Request" ),
40+ },
41+ {
42+ name : "retry 500s" ,
43+ handler : HandlerFunc (func (_ context.Context , req * Request ) (* APIResponse , error ) {
44+ return nil , httpgrpc .Errorf (http .StatusInternalServerError , "Internal Server Error" )
45+ }),
46+ err : httpgrpc .Errorf (http .StatusInternalServerError , "Internal Server Error" ),
47+ },
48+ {
49+ name : "last error" ,
50+ handler : HandlerFunc (func (_ context.Context , req * Request ) (* APIResponse , error ) {
51+ if atomic .AddInt32 (& try , 1 ) == 5 {
52+ return nil , httpgrpc .Errorf (http .StatusBadRequest , "Bad Request" )
53+ }
54+ return nil , httpgrpc .Errorf (http .StatusInternalServerError , "Internal Server Error" )
55+ }),
56+ err : httpgrpc .Errorf (http .StatusBadRequest , "Bad Request" ),
57+ },
58+ } {
59+ t .Run (tc .name , func (t * testing.T ) {
60+ try = 0
61+ h := NewRetryMiddleware (log .NewNopLogger (), 5 ).Wrap (tc .handler )
62+ resp , err := h .Do (nil , nil )
63+ require .Equal (t , tc .err , err )
64+ require .Equal (t , tc .resp , resp )
65+ })
66+ }
2867}
0 commit comments