@@ -10,11 +10,11 @@ import (
1010 "time"
1111)
1212
13- type mockRountTripper struct {
13+ type mockRoundTripper struct {
1414 Response []byte
1515}
1616
17- func (m * mockRountTripper ) RoundTrip (r * http.Request ) (* http.Response , error ) {
17+ func (m * mockRoundTripper ) RoundTrip (r * http.Request ) (* http.Response , error ) {
1818 bodyReader := bytes .NewReader (m .Response )
1919 bodyReadCloser := io .NopCloser (bodyReader )
2020
@@ -29,7 +29,7 @@ func TestNiceClient(t *testing.T) {
2929 throttle := NewMemoryHTTPThrottle ()
3030 cache := NewMemoryHTTPCache (context .Background (), 1000 )
3131
32- roundTripper := & mockRountTripper {
32+ roundTripper := & mockRoundTripper {
3333 Response : []byte ("test" ),
3434 }
3535
@@ -47,12 +47,67 @@ func TestNiceClient(t *testing.T) {
4747 if err != nil {
4848 t .Fatal (err )
4949 }
50+
5051 throttle .Block (& http.Request {
5152 URL : url ,
5253 Method : "GET" ,
5354 }, 3 * time .Second )
55+
5456 client .RoundTrip (req )
55- if time .Since (start ) < 4 * time .Second {
57+
58+ if time .Since (start ) < 3 * time .Second {
5659 t .FailNow ()
5760 }
5861}
62+
63+ func TestNiceClientThrottle (t * testing.T ) {
64+ cache := NewMemoryHTTPCache (context .Background (), 1000 )
65+ throttle := NewMemoryHTTPThrottle ()
66+
67+ throttleDuration := 20 * time .Millisecond
68+
69+ url , err := url .Parse ("http://example.com" )
70+ if err != nil {
71+ panic (err )
72+ }
73+ throttle .SetThrottle (& http.Request {
74+ Method : "GET" ,
75+ URL : url ,
76+ }, throttleDuration )
77+ throttle .SetThrottle (& http.Request {
78+ Method : "POST" ,
79+ URL : url ,
80+ }, throttleDuration * 100 )
81+
82+ url , err = url .Parse ("http://example.com/test" )
83+ if err != nil {
84+ panic (err )
85+ }
86+ throttle .SetThrottle (& http.Request {
87+ Method : "GET" ,
88+ URL : url ,
89+ }, throttleDuration * 100 )
90+
91+ roundTripper := & mockRoundTripper {
92+ Response : []byte ("test" ),
93+ }
94+
95+ client := NewNiceClient (context .Background (), roundTripper , throttle , cache )
96+
97+ for i := 0 ; i < 100 ; i ++ {
98+ req , _ := http .NewRequest ("GET" , "http://example.com" , nil )
99+ start := time .Now ()
100+ client .RoundTrip (req )
101+
102+ timeTaken := time .Since (start )
103+
104+ if timeTaken < throttleDuration - 5 * time .Millisecond {
105+ t .Fatal ("not enough time since last request" )
106+ }
107+
108+ if timeTaken > throttleDuration + 5 * time .Millisecond {
109+ t .Fatal ("too much time since last request" )
110+ }
111+ }
112+
113+ }
0 commit comments