Left: | ||
Right: |
LEFT | RIGHT |
---|---|
1 /* | 1 /* |
2 Copyright 2013 Google Inc | 2 Copyright 2013 Google Inc |
3 | 3 |
4 Licensed under the Apache License, Version 2.0 (the "License"); | 4 Licensed under the Apache License, Version 2.0 (the "License"); |
5 you may not use this file except in compliance with the License. | 5 you may not use this file except in compliance with the License. |
6 You may obtain a copy of the License at | 6 You may obtain a copy of the License at |
7 | 7 |
8 http://www.apache.org/licenses/LICENSE-2.0 | 8 http://www.apache.org/licenses/LICENSE-2.0 |
9 | 9 |
10 Unless required by applicable law or agreed to in writing, software | 10 Unless required by applicable law or agreed to in writing, software |
(...skipping 15 matching lines...) Expand all Loading... | |
26 using System.Threading.Tasks; | 26 using System.Threading.Tasks; |
27 | 27 |
28 using NUnit.Framework; | 28 using NUnit.Framework; |
29 | 29 |
30 using Google.Apis.Http; | 30 using Google.Apis.Http; |
31 using Google.Apis.Util; | 31 using Google.Apis.Util; |
32 using Google.Apis.Testing; | 32 using Google.Apis.Testing; |
33 | 33 |
34 namespace Google.Apis.Tests.Apis.Http | 34 namespace Google.Apis.Tests.Apis.Http |
35 { | 35 { |
36 /// <summary> Tests for <see cref="Google.Apis.Http.ConfigurableMessageHandl er"/>. </summary> | 36 /// <summary>Tests for <see cref="Google.Apis.Http.ConfigurableMessageHandle r"/>.</summary> |
37 [TestFixture] | 37 [TestFixture] |
38 public class ConfigurableMessageHandlerTest | 38 public class ConfigurableMessageHandlerTest |
39 { | 39 { |
40 #region Handlers | 40 #region Handlers |
41 | 41 |
42 /// <summary> Unsuccessful handler which always returns <c>true</c>. </s ummary> | 42 /// <summary>Unsuccessful handler which always returns <c>true</c>.</sum mary> |
43 private class TrueUnsuccessfulResponseHandler : IHttpUnsuccessfulRespons eHandler | 43 private class TrueUnsuccessfulResponseHandler : IHttpUnsuccessfulRespons eHandler |
44 { | 44 { |
45 public Task<bool> HandleResponseAsync(HandleUnsuccessfulResponseArgs args) | 45 public Task<bool> HandleResponseAsync(HandleUnsuccessfulResponseArgs args) |
class
2013/09/16 23:47:29
Missing documentation tags, not sure how important
peleyal
2013/09/17 15:53:40
I don't like to add documentation of inherited met
| |
46 { | 46 { |
47 TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>( ); | 47 TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>( ); |
48 tcs.SetResult(true); | 48 tcs.SetResult(true); |
49 return tcs.Task; | 49 return tcs.Task; |
50 } | 50 } |
51 } | 51 } |
52 | 52 |
53 /// <summary> Message handler which returns a new successful (and empty) response. </summary> | 53 /// <summary>Message handler which returns a new successful (and empty) response.</summary> |
54 private class MockMessageHandler : HttpMessageHandler | 54 private class MockMessageHandler : HttpMessageHandler |
55 { | 55 { |
56 protected override Task<HttpResponseMessage> SendAsync(HttpRequestMe ssage request, | 56 protected override Task<HttpResponseMessage> SendAsync(HttpRequestMe ssage request, |
57 CancellationToken cancellationToken) | 57 CancellationToken cancellationToken) |
58 { | 58 { |
59 TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompleti onSource<HttpResponseMessage>(); | 59 TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompleti onSource<HttpResponseMessage>(); |
60 tcs.SetResult(new HttpResponseMessage()); | 60 tcs.SetResult(new HttpResponseMessage()); |
61 return tcs.Task; | 61 return tcs.Task; |
62 } | 62 } |
63 } | 63 } |
64 | 64 |
65 #endregion | 65 #endregion |
66 | 66 |
67 #region Redirect | 67 #region Redirect |
68 | 68 |
69 /// <summary> Redirect message handler which return redirect response. < /summary> | 69 /// <summary>Redirect message handler which return redirect response.</s ummary> |
70 private class RedirectMessageHandler : CountableMessageHandler | 70 private class RedirectMessageHandler : CountableMessageHandler |
71 { | 71 { |
72 /// <summary> Gets or sets the redirect location Uri string. </summa ry> | 72 /// <summary>Gets or sets the redirect location Uri string.</summary > |
73 private string Location { get; set; } | 73 private string Location { get; set; } |
74 | 74 |
75 /// <summary> Constructs a new redirect message handler with the giv en location. </summary> | 75 /// <summary>Constructs a new redirect message handler with the give n location.</summary> |
76 public RedirectMessageHandler(string location) | 76 public RedirectMessageHandler(string location) |
77 { | 77 { |
78 Location = location; | 78 Location = location; |
79 } | 79 } |
80 | 80 |
81 protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsyncCore( | 81 protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsyncCore( |
82 HttpRequestMessage request, CancellationToken cancellationToken) | 82 HttpRequestMessage request, CancellationToken cancellationToken) |
83 { | 83 { |
84 TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompleti onSource<HttpResponseMessage>(); | 84 TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompleti onSource<HttpResponseMessage>(); |
85 var response = new HttpResponseMessage(); | 85 var response = new HttpResponseMessage(); |
(...skipping 19 matching lines...) Expand all Loading... | |
105 Assert.That(request.Headers.IfNoneMatch.Count == 0); | 105 Assert.That(request.Headers.IfNoneMatch.Count == 0); |
106 Assert.IsNull(request.Headers.IfModifiedSince); | 106 Assert.IsNull(request.Headers.IfModifiedSince); |
107 Assert.IsNull(request.Headers.IfUnmodifiedSince); | 107 Assert.IsNull(request.Headers.IfUnmodifiedSince); |
108 } | 108 } |
109 | 109 |
110 tcs.SetResult(response); | 110 tcs.SetResult(response); |
111 return tcs.Task; | 111 return tcs.Task; |
112 } | 112 } |
113 } | 113 } |
114 | 114 |
115 /// <summary> Tests that the message handler handles redirect messages s uccessfully. </summary> | 115 /// <summary>Tests that the message handler handles redirect messages su ccessfully.</summary> |
116 [Test] | 116 [Test] |
117 public void SendAsync_Redirect() | 117 public void SendAsync_Redirect() |
118 { | 118 { |
119 var location = "https://google.com"; | 119 var location = "https://google.com"; |
120 var redirectHandler = new RedirectMessageHandler(location); | 120 var redirectHandler = new RedirectMessageHandler(location); |
121 var configurableHanlder = new ConfigurableMessageHandler(redirectHan dler) | 121 var configurableHanlder = new ConfigurableMessageHandler(redirectHan dler) |
122 { | 122 { |
123 NumTries = 8 | 123 NumTries = 8 |
124 }; | 124 }; |
125 using (var client = new HttpClient(configurableHanlder)) | 125 using (var client = new HttpClient(configurableHanlder)) |
126 { | 126 { |
127 var request = new HttpRequestMessage(HttpMethod.Get, location); | 127 var request = new HttpRequestMessage(HttpMethod.Get, location); |
128 request.Headers.IfModifiedSince = new DateTimeOffset(DateTime.No w); | 128 request.Headers.IfModifiedSince = new DateTimeOffset(DateTime.No w); |
129 request.Headers.IfUnmodifiedSince = new DateTimeOffset(DateTime. Now); | 129 request.Headers.IfUnmodifiedSince = new DateTimeOffset(DateTime. Now); |
130 request.Headers.IfMatch.Add(new EntityTagHeaderValue("\"a\"")); | 130 request.Headers.IfMatch.Add(new EntityTagHeaderValue("\"a\"")); |
131 request.Headers.IfNoneMatch.Add(new EntityTagHeaderValue("\"b\"" )); | 131 request.Headers.IfNoneMatch.Add(new EntityTagHeaderValue("\"b\"" )); |
132 | 132 |
133 HttpResponseMessage response = client.SendAsync(request).Result; | 133 HttpResponseMessage response = client.SendAsync(request).Result; |
134 | 134 |
135 Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Redir ect)); | 135 Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Redir ect)); |
136 Assert.That(response.Headers.Location, Is.EqualTo(new Uri(locati on configurableHanlder.NumTries))); | 136 Assert.That(response.Headers.Location, Is.EqualTo(new Uri(locati on configurableHanlder.NumTries))); |
137 Assert.That(redirectHandler.Calls, Is.EqualTo(configurableHanlde r.NumTries)); | 137 Assert.That(redirectHandler.Calls, Is.EqualTo(configurableHanlde r.NumTries)); |
138 } | 138 } |
139 } | 139 } |
140 | 140 |
141 /// <summary> | 141 /// <summary> |
142 /// Tests that the message handler doesn't handle redirect messages when follow redirect is <c>false</c>.· | 142 /// Tests that the message handler doesn't handle redirect messages when follow redirect is <c>false</c>.· |
143 /// </summary> | 143 /// </summary> |
144 [Test] | 144 [Test] |
145 public void SendAsync_Redirect_FollowRedirectFalse() | 145 public void SendAsync_Redirect_FollowRedirectFalse() |
146 { | 146 { |
147 const int tries = 12; | 147 const int tries = 12; |
148 var location = "https://google.com"; | 148 var location = "https://google.com"; |
149 var redirectHandler = new RedirectMessageHandler(location); | 149 var redirectHandler = new RedirectMessageHandler(location); |
150 var configurableHanlder = new ConfigurableMessageHandler(redirectHan dler) | 150 var configurableHanlder = new ConfigurableMessageHandler(redirectHan dler) |
151 { | 151 { |
(...skipping 14 matching lines...) Expand all Loading... | |
166 Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Redir ect)); | 166 Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Redir ect)); |
167 Assert.That(response.Headers.Location, Is.EqualTo(new Uri(locati on 1))); | 167 Assert.That(response.Headers.Location, Is.EqualTo(new Uri(locati on 1))); |
168 Assert.That(redirectHandler.Calls, Is.EqualTo(1)); | 168 Assert.That(redirectHandler.Calls, Is.EqualTo(1)); |
169 } | 169 } |
170 } | 170 } |
171 | 171 |
172 #endregion | 172 #endregion |
173 | 173 |
174 #region Execute interceptor | 174 #region Execute interceptor |
175 | 175 |
176 /// <summary> | 176 /// <summary> |
177 /// Mock interceptor handler which verifies that an interceptor is being called on a request.· | 177 /// Mock interceptor handler which verifies that an interceptor is being called on a request.· |
178 /// </summary> | 178 /// </summary> |
179 private class InterceptorMessageHandler : CountableMessageHandler | 179 private class InterceptorMessageHandler : CountableMessageHandler |
180 { | 180 { |
181 /// <summary> Gets or sets an injected response message which will b e returned on send. </summary> | 181 /// <summary>Gets or sets an injected response message which will be returned on send.</summary> |
182 public HttpResponseMessage InjectedResponseMessage { get; set; } | 182 public HttpResponseMessage InjectedResponseMessage { get; set; } |
183 | 183 |
184 const string InjectedHeader = "Some-Header"; | 184 const string InjectedHeader = "Some-Header"; |
185 const string InjectedValue = "123"; | 185 const string InjectedValue = "123"; |
186 | 186 |
187 protected override Task<HttpResponseMessage> SendAsyncCore(HttpReque stMessage request, | 187 protected override Task<HttpResponseMessage> SendAsyncCore(HttpReque stMessage request, |
188 CancellationToken cancellationToken) | 188 CancellationToken cancellationToken) |
189 { | 189 { |
190 Assert.That(request.Headers.GetValues(InjectedHeader).First(), I s.EqualTo(InjectedValue)); | 190 Assert.That(request.Headers.GetValues(InjectedHeader).First(), I s.EqualTo(InjectedValue)); |
191 | 191 |
192 TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompleti onSource<HttpResponseMessage>(); | 192 TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompleti onSource<HttpResponseMessage>(); |
193 tcs.SetResult(InjectedResponseMessage); | 193 tcs.SetResult(InjectedResponseMessage); |
194 return tcs.Task; | 194 return tcs.Task; |
195 } | 195 } |
196 | 196 |
197 /// <summary> A mock interceptor which inject a header to a request. </summary> | 197 /// <summary>A mock interceptor which inject a header to a request.< /summary> |
198 internal class Interceptor : IHttpExecuteInterceptor | 198 internal class Interceptor : IHttpExecuteInterceptor |
199 { | 199 { |
200 public int Calls { get; set; } | 200 public int Calls { get; set; } |
201 | 201 |
202 public Task InterceptAsync(HttpRequestMessage request, Cancellat ionToken token) | 202 public Task InterceptAsync(HttpRequestMessage request, Cancellat ionToken token) |
203 { | 203 { |
204 Calls; | 204 Calls; |
205 request.Headers.Add(InjectedHeader, InjectedValue); | 205 request.Headers.Add(InjectedHeader, InjectedValue); |
206 return TaskEx.Delay(0); | 206 return TaskEx.Delay(0); |
207 } | 207 } |
208 } | 208 } |
209 } | 209 } |
210 | 210 |
211 /// <summary> Tests that execute interceptor is called on successful res ponse. </summary> | 211 /// <summary>Tests that execute interceptor is called on successful resp onse.</summary> |
212 [Test] | 212 [Test] |
213 public void SendAsync_ExecuteInterceptor() | 213 public void SendAsync_ExecuteInterceptor() |
214 { | 214 { |
215 SubtestSendAsyncExecuteInterceptor(HttpStatusCode.OK); | 215 SubtestSendAsyncExecuteInterceptor(HttpStatusCode.OK); |
216 } | 216 } |
217 | 217 |
218 /// <summary> | 218 /// <summary> |
219 /// Tests that execute interceptor is called once on unsuccessful reques t. In this test unsuccessful response· | 219 /// Tests that execute interceptor is called once on unsuccessful reques t. In this test unsuccessful response· |
220 /// handler isn't plugged to the handler.· | 220 /// handler isn't plugged to the handler.· |
221 /// </summary> | 221 /// </summary> |
222 [Test] | 222 [Test] |
223 public void SendAsync_ExecuteInterceptor_AbnormalResponse() | 223 public void SendAsync_ExecuteInterceptor_AbnormalResponse() |
224 { | 224 { |
225 SubtestSendAsyncExecuteInterceptor(HttpStatusCode.BadRequest); | 225 SubtestSendAsyncExecuteInterceptor(HttpStatusCode.BadRequest); |
226 } | 226 } |
227 | 227 |
228 /// <summary> Tests that execute interceptor is called. </summary> | 228 /// <summary>Tests that execute interceptor is called.</summary> |
229 private void SubtestSendAsyncExecuteInterceptor(HttpStatusCode code) | 229 private void SubtestSendAsyncExecuteInterceptor(HttpStatusCode code) |
230 { | 230 { |
231 var handler = new InterceptorMessageHandler(); | 231 var handler = new InterceptorMessageHandler(); |
232 handler.InjectedResponseMessage = new HttpResponseMessage() | 232 handler.InjectedResponseMessage = new HttpResponseMessage() |
233 { | 233 { |
234 StatusCode = code | 234 StatusCode = code |
235 }; | 235 }; |
236 | 236 |
237 var configurableHanlder = new ConfigurableMessageHandler(handler); | 237 var configurableHanlder = new ConfigurableMessageHandler(handler); |
238 var interceptor = new InterceptorMessageHandler.Interceptor(); | 238 var interceptor = new InterceptorMessageHandler.Interceptor(); |
239 configurableHanlder.ExecuteInterceptors.Add(interceptor); | 239 configurableHanlder.ExecuteInterceptors.Add(interceptor); |
240 | 240 |
241 using (var client = new HttpClient(configurableHanlder)) | 241 using (var client = new HttpClient(configurableHanlder)) |
242 { | 242 { |
243 var request = new HttpRequestMessage(HttpMethod.Get, "https://te st-execute-interceptor"); | 243 var request = new HttpRequestMessage(HttpMethod.Get, "https://te st-execute-interceptor"); |
244 | 244 |
245 HttpResponseMessage response = client.SendAsync(request).Result; | 245 HttpResponseMessage response = client.SendAsync(request).Result; |
246 Assert.That(interceptor.Calls, Is.EqualTo(1)); | 246 Assert.That(interceptor.Calls, Is.EqualTo(1)); |
247 Assert.That(handler.Calls, Is.EqualTo(1)); | 247 Assert.That(handler.Calls, Is.EqualTo(1)); |
248 } | 248 } |
249 } | 249 } |
250 | 250 |
251 /// <summary> | 251 /// <summary> |
252 /// Tests that execute interceptor is called for each request. In this c ase an unsuccessful response handler is· | 252 /// Tests that execute interceptor is called for each request. In this c ase an unsuccessful response handler is· |
253 /// plugged to the handler | 253 /// plugged to the handler |
254 /// </summary> | 254 /// </summary> |
255 [Test] | 255 [Test] |
256 public void SendAsync_ExecuteInterceptor_AbnormalResponse_UnsuccessfulRe sponseHandler() | 256 public void SendAsync_ExecuteInterceptor_AbnormalResponse_UnsuccessfulRe sponseHandler() |
257 { | 257 { |
258 var handler = new InterceptorMessageHandler(); | 258 var handler = new InterceptorMessageHandler(); |
259 handler.InjectedResponseMessage = new HttpResponseMessage() | 259 handler.InjectedResponseMessage = new HttpResponseMessage() |
260 { | 260 { |
261 StatusCode = HttpStatusCode.ServiceUnavailable | 261 StatusCode = HttpStatusCode.ServiceUnavailable |
(...skipping 11 matching lines...) Expand all Loading... | |
273 HttpResponseMessage response = client.SendAsync(request).Result; | 273 HttpResponseMessage response = client.SendAsync(request).Result; |
274 Assert.That(interceptor.Calls, Is.EqualTo(configurableHanlder.Nu mTries)); | 274 Assert.That(interceptor.Calls, Is.EqualTo(configurableHanlder.Nu mTries)); |
275 Assert.That(handler.Calls, Is.EqualTo(configurableHanlder.NumTri es)); | 275 Assert.That(handler.Calls, Is.EqualTo(configurableHanlder.NumTri es)); |
276 } | 276 } |
277 } | 277 } |
278 | 278 |
279 #endregion | 279 #endregion |
280 | 280 |
281 #region Unsuccessful reponse handler | 281 #region Unsuccessful reponse handler |
282 | 282 |
283 /// <summary> | 283 /// <summary> |
284 /// Mock unsuccessful response handler which verifies that unsuccessful response handler is being called. | 284 /// Mock unsuccessful response handler which verifies that unsuccessful response handler is being called. |
285 /// </summary> | 285 /// </summary> |
286 private class UnsuccessfulResponseMessageHandler : CountableMessageHandl er | 286 private class UnsuccessfulResponseMessageHandler : CountableMessageHandl er |
287 { | 287 { |
288 /// <summary> Gets or sets the status code to return on the response .</summary> | 288 /// <summary>Gets or sets the status code to return on the response. </summary> |
289 public HttpStatusCode ResponseStatusCode { get; set; } | 289 public HttpStatusCode ResponseStatusCode { get; set; } |
290 | 290 |
291 /// <summary> Gets or sets the cancellation token source.</summary> | 291 /// <summary>Gets or sets the cancellation token source.</summary> |
292 public CancellationTokenSource CancellationTokenSource { get; set; } | 292 public CancellationTokenSource CancellationTokenSource { get; set; } |
293 | 293 |
294 /// <summary> | 294 /// <summary> |
295 /// Gets or sets the request number to invoke the Cancel method on < see cref="CancellationTokenSource"/>. | 295 /// Gets or sets the request number to invoke the Cancel method on < see cref="CancellationTokenSource"/>. |
296 /// </summary> | 296 /// </summary> |
297 public int CancelRequestNum { get; set; } | 297 public int CancelRequestNum { get; set; } |
298 | 298 |
299 protected override Task<HttpResponseMessage> SendAsyncCore(HttpReque stMessage request, | 299 protected override Task<HttpResponseMessage> SendAsyncCore(HttpReque stMessage request, |
300 CancellationToken cancellationToken) | 300 CancellationToken cancellationToken) |
301 { | 301 { |
302 if (Calls == CancelRequestNum) | 302 if (Calls == CancelRequestNum) |
303 { | 303 { |
304 CancellationTokenSource.Cancel(); | 304 CancellationTokenSource.Cancel(); |
305 } | 305 } |
306 | 306 |
307 TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompleti onSource<HttpResponseMessage>(); | 307 TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompleti onSource<HttpResponseMessage>(); |
308 tcs.SetResult(new HttpResponseMessage { StatusCode = ResponseSta tusCode }); | 308 tcs.SetResult(new HttpResponseMessage { StatusCode = ResponseSta tusCode }); |
309 return tcs.Task; | 309 return tcs.Task; |
310 } | 310 } |
311 | 311 |
312 /// <summary> Unsuccessful response handler which "handles" only ser vice unavailable responses. </summary> | 312 /// <summary>Unsuccessful response handler which "handles" only serv ice unavailable responses.</summary> |
313 internal class ServiceUnavailableResponseHandler : IHttpUnsuccessful ResponseHandler | 313 internal class ServiceUnavailableResponseHandler : IHttpUnsuccessful ResponseHandler |
314 { | 314 { |
315 public int Calls { get; set; } | 315 public int Calls { get; set; } |
316 | 316 |
317 public Task<bool> HandleResponseAsync(HandleUnsuccessfulResponse Args args) | 317 public Task<bool> HandleResponseAsync(HandleUnsuccessfulResponse Args args) |
318 { | 318 { |
319 Calls; | 319 Calls; |
320 TaskCompletionSource<bool> tcs = new TaskCompletionSource<bo ol>(); | 320 TaskCompletionSource<bool> tcs = new TaskCompletionSource<bo ol>(); |
321 tcs.SetResult(args.Response.StatusCode.Equals(HttpStatusCode .ServiceUnavailable)); | 321 tcs.SetResult(args.Response.StatusCode.Equals(HttpStatusCode .ServiceUnavailable)); |
322 return tcs.Task; | 322 return tcs.Task; |
323 } | 323 } |
324 } | 324 } |
325 } | 325 } |
326 | 326 |
327 /// <summary> Test helper for testing unsuccessful response handlers. </ summary> | 327 /// <summary>Test helper for testing unsuccessful response handlers.</su mmary> |
328 private void SubtestSendAsyncUnsuccessfulReponseHanlder(HttpStatusCode c ode) | 328 private void SubtestSendAsyncUnsuccessfulReponseHanlder(HttpStatusCode c ode) |
329 { | 329 { |
330 var handler = new UnsuccessfulResponseMessageHandler { ResponseStatu sCode = code }; | 330 var handler = new UnsuccessfulResponseMessageHandler { ResponseStatu sCode = code }; |
331 | 331 |
332 var configurableHanlder = new ConfigurableMessageHandler(handler); | 332 var configurableHanlder = new ConfigurableMessageHandler(handler); |
333 var unsuccessfulHandler = new UnsuccessfulResponseMessageHandler.Ser viceUnavailableResponseHandler(); | 333 var unsuccessfulHandler = new UnsuccessfulResponseMessageHandler.Ser viceUnavailableResponseHandler(); |
334 configurableHanlder.UnsuccessfulResponseHandlers.Add(unsuccessfulHan dler); | 334 configurableHanlder.UnsuccessfulResponseHandlers.Add(unsuccessfulHan dler); |
335 | 335 |
336 using (var client = new HttpClient(configurableHanlder)) | 336 using (var client = new HttpClient(configurableHanlder)) |
337 { | 337 { |
(...skipping 11 matching lines...) Expand all Loading... | |
349 } | 349 } |
350 else | 350 else |
351 { | 351 { |
352 // if status is OK, there isn't any call to unsuccessful res ponse handler | 352 // if status is OK, there isn't any call to unsuccessful res ponse handler |
353 Assert.That(unsuccessfulHandler.Calls, Is.EqualTo(code != Ht tpStatusCode.OK ? 1 : 0)); | 353 Assert.That(unsuccessfulHandler.Calls, Is.EqualTo(code != Ht tpStatusCode.OK ? 1 : 0)); |
354 Assert.That(handler.Calls, Is.EqualTo(1)); | 354 Assert.That(handler.Calls, Is.EqualTo(1)); |
355 } | 355 } |
356 } | 356 } |
357 } | 357 } |
358 | 358 |
359 /// <summary> Tests that unsuccessful response handler isn't called when the response is successful. </summary> | 359 /// <summary>Tests that unsuccessful response handler isn't called when the response is successful.</summary> |
360 [Test] | 360 [Test] |
361 public void SendAsync_UnsuccessfulReponseHanlder_SuccessfulReponse() | 361 public void SendAsync_UnsuccessfulReponseHanlder_SuccessfulReponse() |
362 { | 362 { |
363 SubtestSendAsyncUnsuccessfulReponseHanlder(HttpStatusCode.OK); | 363 SubtestSendAsyncUnsuccessfulReponseHanlder(HttpStatusCode.OK); |
364 } | 364 } |
365 | 365 |
366 /// <summary> | 366 /// <summary> |
367 /// Tests that unsuccessful response handler is called when the response is unsuccessful, but the handler can't | 367 /// Tests that unsuccessful response handler is called when the response is unsuccessful, but the handler can't |
368 /// handle the abnormal response (e.g. different status code). | 368 /// handle the abnormal response (e.g. different status code). |
369 /// </summary> | 369 /// </summary> |
370 [Test] | 370 [Test] |
371 public void SendAsync_UnsuccessfulReponseHanlder_AbnormalResponse_Differ entStatusCode() | 371 public void SendAsync_UnsuccessfulReponseHanlder_AbnormalResponse_Differ entStatusCode() |
372 { | 372 { |
373 SubtestSendAsyncUnsuccessfulReponseHanlder(HttpStatusCode.BadGateway ); | 373 SubtestSendAsyncUnsuccessfulReponseHanlder(HttpStatusCode.BadGateway ); |
374 } | 374 } |
375 | 375 |
376 /// <summary> | 376 /// <summary> |
377 /// Tests that unsuccessful response handler is called when the response is unsuccessful and the handler can· | 377 /// Tests that unsuccessful response handler is called when the response is unsuccessful and the handler can· |
378 /// handle the abnormal response (e.g. same status code). | 378 /// handle the abnormal response (e.g. same status code). |
379 /// </summary> | 379 /// </summary> |
380 [Test] | 380 [Test] |
381 public void SendAsync_UnsuccessfulReponseHanlder_AbnormalResponse_SameSt atusCode() | 381 public void SendAsync_UnsuccessfulReponseHanlder_AbnormalResponse_SameSt atusCode() |
382 { | 382 { |
383 SubtestSendAsyncUnsuccessfulReponseHanlder(HttpStatusCode.ServiceUna vailable); | 383 SubtestSendAsyncUnsuccessfulReponseHanlder(HttpStatusCode.ServiceUna vailable); |
384 } | 384 } |
385 | 385 |
386 /// <summary> Tests abnormal response when unsuccessful response handler isn't plugged. </summary> | 386 /// <summary>Tests abnormal response when unsuccessful response handler isn't plugged.</summary> |
387 [Test] | 387 [Test] |
388 public void SendAsync_AbnormalResponse_WithoutUnsuccessfulReponseHandler () | 388 public void SendAsync_AbnormalResponse_WithoutUnsuccessfulReponseHandler () |
389 { | 389 { |
390 var handler = new UnsuccessfulResponseMessageHandler | 390 var handler = new UnsuccessfulResponseMessageHandler |
391 { | 391 { |
392 ResponseStatusCode = HttpStatusCode.ServiceUnavailable | 392 ResponseStatusCode = HttpStatusCode.ServiceUnavailable |
393 }; | 393 }; |
394 | 394 |
395 var configurableHanlder = new ConfigurableMessageHandler(handler); | 395 var configurableHanlder = new ConfigurableMessageHandler(handler); |
396 using (var client = new HttpClient(configurableHanlder)) | 396 using (var client = new HttpClient(configurableHanlder)) |
397 { | 397 { |
398 var request = new HttpRequestMessage(HttpMethod.Get, "https://te st-unsuccessful-handler"); | 398 var request = new HttpRequestMessage(HttpMethod.Get, "https://te st-unsuccessful-handler"); |
399 | 399 |
400 HttpResponseMessage response = client.SendAsync(request).Result; | 400 HttpResponseMessage response = client.SendAsync(request).Result; |
401 Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Servi ceUnavailable)); | 401 Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Servi ceUnavailable)); |
402 Assert.That(handler.Calls, Is.EqualTo(1)); | 402 Assert.That(handler.Calls, Is.EqualTo(1)); |
403 } | 403 } |
404 } | 404 } |
405 | 405 |
406 #endregion | 406 #endregion |
407 | 407 |
408 #region Exception Handler | 408 #region Exception Handler |
409 | 409 |
410 /// <summary> Mock exception message handler which verifies that excepti on handler is being called. </summary> | 410 /// <summary>Mock exception message handler which verifies that exceptio n handler is being called.</summary> |
411 private class ExceptionMessageHandler : CountableMessageHandler | 411 private class ExceptionMessageHandler : CountableMessageHandler |
412 { | 412 { |
413 public ExceptionMessageHandler() | 413 public ExceptionMessageHandler() |
414 { | 414 { |
415 Exception = new Exception(ExceptionMessage); | 415 Exception = new Exception(ExceptionMessage); |
416 } | 416 } |
417 | 417 |
418 /// <summary> Gets or sets indication if exception should be thrown. </summary> | 418 /// <summary>Gets or sets indication if exception should be thrown.< /summary> |
419 public bool ThrowException { get; set; } | 419 public bool ThrowException { get; set; } |
420 | 420 |
421 /// <summary> | 421 /// <summary> |
422 /// Gets or sets a specific exception to throw. Default value is <se ealso cref="System.Exception"/>· | 422 /// Gets or sets a specific exception to throw. Default value is <se ealso cref="System.Exception"/>· |
423 /// with <see cref="ExceptionMessage"/>. </summary> | 423 /// with <see cref="ExceptionMessage"/>.</summary> |
424 public Exception Exception { get; set; } | 424 public Exception Exception { get; set; } |
425 | 425 |
426 /// <summary> | 426 /// <summary> |
427 /// The exception message which is thrown in case <see cref="ThrowEx ception"/> is <c>true</c>.· | 427 /// The exception message which is thrown in case <see cref="ThrowEx ception"/> is <c>true</c>.· |
428 /// </summary> | 428 /// </summary> |
429 public const string ExceptionMessage = "Exception from execute"; | 429 public const string ExceptionMessage = "Exception from execute"; |
430 | 430 |
431 protected override Task<HttpResponseMessage> SendAsyncCore(HttpReque stMessage request, | 431 protected override Task<HttpResponseMessage> SendAsyncCore(HttpReque stMessage request, |
432 CancellationToken cancellationToken) | 432 CancellationToken cancellationToken) |
433 { | 433 { |
434 if (ThrowException) | 434 if (ThrowException) |
435 { | 435 { |
436 throw Exception; | 436 throw Exception; |
437 } | 437 } |
438 | 438 |
439 TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompleti onSource<HttpResponseMessage>(); | 439 TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompleti onSource<HttpResponseMessage>(); |
440 tcs.SetResult(new HttpResponseMessage()); | 440 tcs.SetResult(new HttpResponseMessage()); |
441 return tcs.Task; | 441 return tcs.Task; |
442 } | 442 } |
443 | 443 |
444 /// <summary> Mock Exception handler which "handles" the exception. </summary> | 444 /// <summary>Mock Exception handler which "handles" the exception.</ summary> |
445 internal class ExceptionHandler : IHttpExceptionHandler | 445 internal class ExceptionHandler : IHttpExceptionHandler |
446 { | 446 { |
447 public int Calls { get; set; } | 447 public int Calls { get; set; } |
448 public bool Handle { get; set; } | 448 public bool Handle { get; set; } |
449 | 449 |
450 public ExceptionHandler(bool handle = true) | 450 public ExceptionHandler(bool handle = true) |
451 { | 451 { |
452 Handle = handle; | 452 Handle = handle; |
453 } | 453 } |
454 | 454 |
455 public Task<bool> HandleExceptionAsync(HandleExceptionArgs args) | 455 public Task<bool> HandleExceptionAsync(HandleExceptionArgs args) |
456 { | 456 { |
457 Calls; | 457 Calls; |
458 TaskCompletionSource<bool> tcs = new TaskCompletionSource<bo ol>(); | 458 TaskCompletionSource<bool> tcs = new TaskCompletionSource<bo ol>(); |
459 tcs.SetResult(Handle); | 459 tcs.SetResult(Handle); |
460 return tcs.Task; | 460 return tcs.Task; |
461 } | 461 } |
462 } | 462 } |
463 } | 463 } |
464 | 464 |
465 /// <summary> Subtest for exception handler which tests that exception h andler is invoked. </summary> | 465 /// <summary>Subtest for exception handler which tests that exception ha ndler is invoked.</summary> |
466 private void SubtestSendAsyncExceptionHandler(bool throwException, bool handle) | 466 private void SubtestSendAsyncExceptionHandler(bool throwException, bool handle) |
467 { | 467 { |
468 var handler = new ExceptionMessageHandler { ThrowException = throwEx ception }; | 468 var handler = new ExceptionMessageHandler { ThrowException = throwEx ception }; |
469 | 469 |
470 var configurableHanlder = new ConfigurableMessageHandler(handler); | 470 var configurableHanlder = new ConfigurableMessageHandler(handler); |
471 var exceptionHandler = new ExceptionMessageHandler.ExceptionHandler { Handle = handle }; | 471 var exceptionHandler = new ExceptionMessageHandler.ExceptionHandler { Handle = handle }; |
472 configurableHanlder.ExceptionHandlers.Add(exceptionHandler); | 472 configurableHanlder.ExceptionHandlers.Add(exceptionHandler); |
473 | 473 |
474 using (var client = new HttpClient(configurableHanlder)) | 474 using (var client = new HttpClient(configurableHanlder)) |
475 { | 475 { |
(...skipping 21 matching lines...) Expand all Loading... | |
497 else | 497 else |
498 { | 498 { |
499 Assert.That(exceptionHandler.Calls, Is.EqualTo(0)); | 499 Assert.That(exceptionHandler.Calls, Is.EqualTo(0)); |
500 } | 500 } |
501 | 501 |
502 Assert.That(handler.Calls, Is.EqualTo(throwException & handle ? configurableHanlder.NumTries : 1)); | 502 Assert.That(handler.Calls, Is.EqualTo(throwException & handle ? configurableHanlder.NumTries : 1)); |
503 } | 503 } |
504 } | 504 } |
505 | 505 |
506 | 506 |
507 /// <summary> Tests that the exception handler isn't called on successfu l response. </summary> | 507 /// <summary>Tests that the exception handler isn't called on successful response.</summary> |
508 [Test] | 508 [Test] |
509 public void SendAsync_ExceptionHandler_SuccessReponse() | 509 public void SendAsync_ExceptionHandler_SuccessReponse() |
510 { | 510 { |
511 SubtestSendAsyncExceptionHandler(false, true); | 511 SubtestSendAsyncExceptionHandler(false, true); |
512 } | 512 } |
513 | 513 |
514 /// <summary> | 514 /// <summary> |
515 /// Tests that the exception handler is called when exception is thrown on execute, but it can't handle the· | 515 /// Tests that the exception handler is called when exception is thrown on execute, but it can't handle the· |
516 /// exception.· | 516 /// exception.· |
517 /// </summary> | 517 /// </summary> |
518 [Test] | 518 [Test] |
519 public void SendAsync_ExceptionHandler_ThrowException_DontHandle() | 519 public void SendAsync_ExceptionHandler_ThrowException_DontHandle() |
520 { | 520 { |
521 SubtestSendAsyncExceptionHandler(true, false); | 521 SubtestSendAsyncExceptionHandler(true, false); |
522 } | 522 } |
523 | 523 |
524 /// <summary> | 524 /// <summary> |
525 /// Tests that the exception handler is called when exception is thrown on execute, and it handles the· | 525 /// Tests that the exception handler is called when exception is thrown on execute, and it handles the· |
526 /// exception.· | 526 /// exception.· |
527 /// </summary> | 527 /// </summary> |
528 [Test] | 528 [Test] |
529 public void SendAsync_ExceptionHandler_ThrowException_Handle() | 529 public void SendAsync_ExceptionHandler_ThrowException_Handle() |
530 { | 530 { |
531 SubtestSendAsyncExceptionHandler(true, true); | 531 SubtestSendAsyncExceptionHandler(true, true); |
532 } | 532 } |
533 | 533 |
534 /// <summary> Tests an exception is thrown on execute and there is no ex ception handler. </summary> | 534 /// <summary>Tests an exception is thrown on execute and there is no exc eption handler.</summary> |
535 [Test] | 535 [Test] |
536 public void SendAsync_ThrowException_WithoutExceptionHandler() | 536 public void SendAsync_ThrowException_WithoutExceptionHandler() |
537 { | 537 { |
538 var handler = new ExceptionMessageHandler { ThrowException = true }; | 538 var handler = new ExceptionMessageHandler { ThrowException = true }; |
539 | 539 |
540 var configurableHanlder = new ConfigurableMessageHandler(handler); | 540 var configurableHanlder = new ConfigurableMessageHandler(handler); |
541 | 541 |
542 using (var client = new HttpClient(configurableHanlder)) | 542 using (var client = new HttpClient(configurableHanlder)) |
543 { | 543 { |
544 var request = new HttpRequestMessage(HttpMethod.Get, "https://te st-exception-handler"); | 544 var request = new HttpRequestMessage(HttpMethod.Get, "https://te st-exception-handler"); |
(...skipping 13 matching lines...) Expand all Loading... | |
558 Assert.That(handler.Calls, Is.EqualTo(1)); | 558 Assert.That(handler.Calls, Is.EqualTo(1)); |
559 } | 559 } |
560 } | 560 } |
561 | 561 |
562 #endregion | 562 #endregion |
563 | 563 |
564 #region Back-off | 564 #region Back-off |
565 | 565 |
566 #region Exception | 566 #region Exception |
567 | 567 |
568 /// <summary> | 568 /// <summary> |
569 /// Tests that back-off handler works as expected when exception is thro wn.· | 569 /// Tests that back-off handler works as expected when exception is thro wn.· |
570 /// Use default max time span (2 minutes). | 570 /// Use default max time span (2 minutes). |
571 /// </summary> | 571 /// </summary> |
572 [Test] | 572 [Test] |
573 public void SendAsync_BackOffExceptionHandler_Throw_Max2Minutes() | 573 public void SendAsync_BackOffExceptionHandler_Throw_Max2Minutes() |
574 { | 574 { |
575 // create exponential back-off without delta interval, so expected s econds are exactly 1, 2, 4, 8, etc. | 575 // create exponential back-off without delta interval, so expected s econds are exactly 1, 2, 4, 8, etc. |
576 var initializer = new BackOffHandler.Initializer(new ExponentialBack Off(TimeSpan.Zero)); | 576 var initializer = new BackOffHandler.Initializer(new ExponentialBack Off(TimeSpan.Zero)); |
577 SubtestSendAsync_BackOffExceptionHandler(true, initializer); | 577 SubtestSendAsync_BackOffExceptionHandler(true, initializer); |
578 } | 578 } |
579 | 579 |
580 /// <summary> | 580 /// <summary> |
581 /// Tests that back-off handler works as expected when exception is thro wn.· | 581 /// Tests that back-off handler works as expected when exception is thro wn.· |
582 /// Max time span is set to 200 milliseconds (as a result the back-off h andler can't handle the exception). | 582 /// Max time span is set to 200 milliseconds (as a result the back-off h andler can't handle the exception). |
583 /// </summary> | 583 /// </summary> |
584 [Test] | 584 [Test] |
585 public void SendAsync_BackOffExceptionHandler_Throw_Max200Milliseconds() | 585 public void SendAsync_BackOffExceptionHandler_Throw_Max200Milliseconds() |
586 { | 586 { |
587 var initializer = new BackOffHandler.Initializer(new ExponentialBack Off(TimeSpan.Zero)) | 587 var initializer = new BackOffHandler.Initializer(new ExponentialBack Off(TimeSpan.Zero)) |
588 { | 588 { |
589 MaxTimeSpan = TimeSpan.FromMilliseconds(200) | 589 MaxTimeSpan = TimeSpan.FromMilliseconds(200) |
590 }; | 590 }; |
591 SubtestSendAsync_BackOffExceptionHandler(true, initializer); | 591 SubtestSendAsync_BackOffExceptionHandler(true, initializer); |
592 } | 592 } |
593 | 593 |
863 /// <summary> | 863 /// <summary> |
595 /// Tests that back-off handler works as expected when exception is thro wn.· | 595 /// Tests that back-off handler works as expected when exception is thro wn.· |
596 /// Max time span is set to 1 hour. | 596 /// Max time span is set to 1 hour. |
597 /// </summary> | 597 /// </summary> |
598 [Test] | 598 [Test] |
599 public void SendAsync_BackOffExceptionHandler_Throw_Max1Hour() | 599 public void SendAsync_BackOffExceptionHandler_Throw_Max1Hour() |
600 { | 600 { |
601 var initializer = new BackOffHandler.Initializer(new ExponentialBack Off(TimeSpan.Zero)) | 601 var initializer = new BackOffHandler.Initializer(new ExponentialBack Off(TimeSpan.Zero)) |
602 { | 602 { |
603 MaxTimeSpan = TimeSpan.FromHours(1) | 603 MaxTimeSpan = TimeSpan.FromHours(1) |
604 }; | 604 }; |
605 SubtestSendAsync_BackOffExceptionHandler(true, initializer); | 605 SubtestSendAsync_BackOffExceptionHandler(true, initializer); |
606 } | 606 } |
607 | 607 |
608 /// <summary> | 608 /// <summary> |
609 /// Tests that back-off handler works as expected when· | 609 /// Tests that back-off handler works as expected when· |
610 /// <seealso cref="System.Threading.Tasks.TaskCanceledException"/>> is t hrown.· | 610 /// <seealso cref="System.Threading.Tasks.TaskCanceledException"/>> is t hrown.· |
611 /// </summary> | 611 /// </summary> |
612 [Test] | 612 [Test] |
613 public void SendAsync_BackOffExceptionHandler_ThrowCanceledException() | 613 public void SendAsync_BackOffExceptionHandler_ThrowCanceledException() |
614 { | 614 { |
615 var initializer = new BackOffHandler.Initializer(new ExponentialBack Off(TimeSpan.Zero)); | 615 var initializer = new BackOffHandler.Initializer(new ExponentialBack Off(TimeSpan.Zero)); |
616 SubtestSendAsync_BackOffExceptionHandler(true, initializer, new Task CanceledException()); | 616 SubtestSendAsync_BackOffExceptionHandler(true, initializer, new Task CanceledException()); |
617 } | 617 } |
618 | 618 |
619 /// <summary> | 619 /// <summary> |
620 /// Tests that back-off handler works as expected with the not defaulted exception handler.· | 620 /// Tests that back-off handler works as expected with the not defaulted exception handler.· |
621 /// </summary> | 621 /// </summary> |
622 [Test] | 622 [Test] |
623 public void SendAsync_BackOffExceptionHandler_DifferentHandler() | 623 public void SendAsync_BackOffExceptionHandler_DifferentHandler() |
624 { | 624 { |
625 var initializer = new BackOffHandler.Initializer(new ExponentialBack Off(TimeSpan.Zero)); | 625 var initializer = new BackOffHandler.Initializer(new ExponentialBack Off(TimeSpan.Zero)); |
626 initializer.HandleExceptionFunc = e => (e is InvalidCastException); | 626 initializer.HandleExceptionFunc = e => (e is InvalidCastException); |
627 SubtestSendAsync_BackOffExceptionHandler(true, initializer, new Inva lidCastException()); | 627 SubtestSendAsync_BackOffExceptionHandler(true, initializer, new Inva lidCastException()); |
628 | 628 |
629 initializer.HandleExceptionFunc = e => !(e is InvalidCastException); | 629 initializer.HandleExceptionFunc = e => !(e is InvalidCastException); |
630 SubtestSendAsync_BackOffExceptionHandler(true, initializer, new Inva lidCastException()); | 630 SubtestSendAsync_BackOffExceptionHandler(true, initializer, new Inva lidCastException()); |
631 } | 631 } |
632 | 632 |
633 /// <summary> Tests that back-off handler works as expected when excepti on isn't thrown. </summary> | 633 /// <summary>Tests that back-off handler works as expected when exceptio n isn't thrown.</summary> |
634 [Test] | 634 [Test] |
635 public void SendAsync_BackOffExceptionHandler_DontThrow() | 635 public void SendAsync_BackOffExceptionHandler_DontThrow() |
636 { | 636 { |
637 var initializer = new BackOffHandler.Initializer(new ExponentialBack Off(TimeSpan.Zero)); | 637 var initializer = new BackOffHandler.Initializer(new ExponentialBack Off(TimeSpan.Zero)); |
638 SubtestSendAsync_BackOffExceptionHandler(false, initializer); | 638 SubtestSendAsync_BackOffExceptionHandler(false, initializer); |
639 } | 639 } |
640 | 640 |
641 /// <summary> Subtest that back-off handler works as expected when excep tion is or isn't thrown. </summary> | 641 /// <summary>Subtest that back-off handler works as expected when except ion is or isn't thrown.</summary> |
642 private void SubtestSendAsync_BackOffExceptionHandler(bool throwExceptio n, | 642 private void SubtestSendAsync_BackOffExceptionHandler(bool throwExceptio n, |
643 BackOffHandler.Initializer initializer, Exception exceptionToThrow = null) | 643 BackOffHandler.Initializer initializer, Exception exceptionToThrow = null) |
644 { | 644 { |
645 var handler = new ExceptionMessageHandler { ThrowException = throwEx ception }; | 645 var handler = new ExceptionMessageHandler { ThrowException = throwEx ception }; |
646 if (exceptionToThrow != null) | 646 if (exceptionToThrow != null) |
647 { | 647 { |
648 handler.Exception = exceptionToThrow; | 648 handler.Exception = exceptionToThrow; |
649 } | 649 } |
650 | 650 |
651 var configurableHanlder = new ConfigurableMessageHandler(handler); | 651 var configurableHanlder = new ConfigurableMessageHandler(handler); |
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
686 } | 686 } |
687 } | 687 } |
688 Assert.That(handler.Calls, Is.EqualTo(boHandleCount 1)); | 688 Assert.That(handler.Calls, Is.EqualTo(boHandleCount 1)); |
689 } | 689 } |
690 } | 690 } |
691 | 691 |
692 #endregion | 692 #endregion |
693 | 693 |
694 #region Unsuccessful Response Handler | 694 #region Unsuccessful Response Handler |
695 | 695 |
696 /// <summary> | 696 /// <summary> |
697 /// Tests that back-off handler works as expected when the server return s 5xx and the maximum time span is set | 697 /// Tests that back-off handler works as expected when the server return s 5xx and the maximum time span is set |
698 /// to 5 seconds. | 698 /// to 5 seconds. |
699 /// </summary> | 699 /// </summary> |
700 [Test] | 700 [Test] |
701 public void SendAsync_BackOffUnsuccessfulResponseHandler_ServiceUnavaila ble_Max5Seconds() | 701 public void SendAsync_BackOffUnsuccessfulResponseHandler_ServiceUnavaila ble_Max5Seconds() |
702 { | 702 { |
703 var initializer = new BackOffHandler.Initializer(new ExponentialBack Off(TimeSpan.Zero)) | 703 var initializer = new BackOffHandler.Initializer(new ExponentialBack Off(TimeSpan.Zero)) |
704 { | 704 { |
705 MaxTimeSpan = TimeSpan.FromSeconds(5) | 705 MaxTimeSpan = TimeSpan.FromSeconds(5) |
706 }; | 706 }; |
707 SubtestSendAsync_BackOffUnsuccessfulResponseHandler(HttpStatusCode.S erviceUnavailable, initializer); | 707 SubtestSendAsync_BackOffUnsuccessfulResponseHandler(HttpStatusCode.S erviceUnavailable, initializer); |
708 } | 708 } |
709 | 709 |
710 /// <summary> | 710 /// <summary> |
711 /// Tests that back-off handler works as expected when the server return s 5xx and the maximum time span is set | 711 /// Tests that back-off handler works as expected when the server return s 5xx and the maximum time span is set |
712 /// to 10 hours. | 712 /// to 10 hours. |
713 /// </summary> | 713 /// </summary> |
714 [Test] | 714 [Test] |
715 public void SendAsync_BackOffUnsuccessfulResponseHandler_ServiceUnavaila ble_Max10Hours() | 715 public void SendAsync_BackOffUnsuccessfulResponseHandler_ServiceUnavaila ble_Max10Hours() |
716 { | 716 { |
717 var initializer = new BackOffHandler.Initializer(new ExponentialBack Off(TimeSpan.Zero)) | 717 var initializer = new BackOffHandler.Initializer(new ExponentialBack Off(TimeSpan.Zero)) |
718 { | 718 { |
719 MaxTimeSpan = TimeSpan.FromHours(10) | 719 MaxTimeSpan = TimeSpan.FromHours(10) |
720 }; | 720 }; |
721 SubtestSendAsync_BackOffUnsuccessfulResponseHandler(HttpStatusCode.S erviceUnavailable, initializer); | 721 SubtestSendAsync_BackOffUnsuccessfulResponseHandler(HttpStatusCode.S erviceUnavailable, initializer); |
722 } | 722 } |
723 | 723 |
724 /// <summary> | 724 /// <summary> |
725 /// Tests that back-off handler isn't be called when the server returns a successful response. | 725 /// Tests that back-off handler isn't be called when the server returns a successful response. |
726 /// </summary> | 726 /// </summary> |
727 [Test] | 727 [Test] |
728 public void SendAsync_BackOffUnsuccessfulResponseHandler_OK() | 728 public void SendAsync_BackOffUnsuccessfulResponseHandler_OK() |
729 { | 729 { |
730 var initializer = new BackOffHandler.Initializer(new ExponentialBack Off(TimeSpan.Zero)); | 730 var initializer = new BackOffHandler.Initializer(new ExponentialBack Off(TimeSpan.Zero)); |
731 SubtestSendAsync_BackOffUnsuccessfulResponseHandler(HttpStatusCode.O K, initializer); | 731 SubtestSendAsync_BackOffUnsuccessfulResponseHandler(HttpStatusCode.O K, initializer); |
732 } | 732 } |
733 | 733 |
734 /// <summary> Tests that back-off handler is canceled when cancellation token is used.</summary> | 734 /// <summary>Tests that back-off handler is canceled when cancellation t oken is used.</summary> |
735 [Test] | 735 [Test] |
736 public void SendAsync_BackOffUnsuccessfulResponseHandler_Cancel() | 736 public void SendAsync_BackOffUnsuccessfulResponseHandler_Cancel() |
737 { | 737 { |
738 // test back-off with maximum 30 minutes per single request | 738 // test back-off with maximum 30 minutes per single request |
739 var initializer = new BackOffHandler.Initializer(new ExponentialBack Off(TimeSpan.Zero)) | 739 var initializer = new BackOffHandler.Initializer(new ExponentialBack Off(TimeSpan.Zero)) |
740 { | 740 { |
741 MaxTimeSpan = TimeSpan.FromMinutes(30) | 741 MaxTimeSpan = TimeSpan.FromMinutes(30) |
742 }; | 742 }; |
743 SubtestSendAsync_BackOffUnsuccessfulResponseHandler(HttpStatusCode.S erviceUnavailable, initializer, 2); | 743 SubtestSendAsync_BackOffUnsuccessfulResponseHandler(HttpStatusCode.S erviceUnavailable, initializer, 2); |
744 SubtestSendAsync_BackOffUnsuccessfulResponseHandler(HttpStatusCode.S erviceUnavailable, initializer, 6); | 744 SubtestSendAsync_BackOffUnsuccessfulResponseHandler(HttpStatusCode.S erviceUnavailable, initializer, 6); |
745 } | 745 } |
746 | 746 |
747 /// <summary> | 747 /// <summary> |
748 /// Subtest that back-off handler works as expected when a successful or abnormal response is returned. | 748 /// Subtest that back-off handler works as expected when a successful or abnormal response is returned. |
749 /// For testing the back-off handler in case of a canceled request, set the <code>cancelRequestNum</code> | 749 /// For testing the back-off handler in case of a canceled request, set the <code>cancelRequestNum</code> |
750 /// parameter to the index of the request you want to cancel. | 750 /// parameter to the index of the request you want to cancel. |
751 /// </summary> | 751 /// </summary> |
752 private void SubtestSendAsync_BackOffUnsuccessfulResponseHandler(HttpSta tusCode statusCode, | 752 private void SubtestSendAsync_BackOffUnsuccessfulResponseHandler(HttpSta tusCode statusCode, |
753 BackOffHandler.Initializer initializer, int cancelRequestNum = 0, in t numTries = 10) | 753 BackOffHandler.Initializer initializer, int cancelRequestNum = 0, in t numTries = 10) |
754 { | 754 { |
755 var handler = new UnsuccessfulResponseMessageHandler { ResponseStatu sCode = statusCode }; | 755 var handler = new UnsuccessfulResponseMessageHandler { ResponseStatu sCode = statusCode }; |
756 | 756 |
757 CancellationToken cancellationToken = CancellationToken.None; | 757 CancellationToken cancellationToken = CancellationToken.None; |
(...skipping 55 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
813 Assert.That(handler.Calls, Is.EqualTo(boHandleCount (cancel ? 0 : 1))); | 813 Assert.That(handler.Calls, Is.EqualTo(boHandleCount (cancel ? 0 : 1))); |
814 } | 814 } |
815 } | 815 } |
816 | 816 |
817 #endregion | 817 #endregion |
818 | 818 |
819 #endregion | 819 #endregion |
820 | 820 |
821 #region Content | 821 #region Content |
822 | 822 |
823 /// <summary> Mock message handler which verifies that the content is co rrect on retry. </summary> | 823 /// <summary>Mock message handler which verifies that the content is cor rect on retry.</summary> |
824 private class ContentMessageHandler : CountableMessageHandler | 824 private class ContentMessageHandler : CountableMessageHandler |
825 { | 825 { |
826 public const int NumFails = 4; | 826 public const int NumFails = 4; |
827 public string ReadContent; | 827 public string ReadContent; |
828 | 828 |
829 protected override async Task<HttpResponseMessage> SendAsyncCore(Htt pRequestMessage request, | 829 protected override async Task<HttpResponseMessage> SendAsyncCore(Htt pRequestMessage request, |
830 CancellationToken cancellationToken) | 830 CancellationToken cancellationToken) |
831 { | 831 { |
832 if (Calls < NumFails) | 832 if (Calls < NumFails) |
833 { | 833 { |
834 return new HttpResponseMessage() { StatusCode = HttpStatusCo de.ServiceUnavailable }; | 834 return new HttpResponseMessage() { StatusCode = HttpStatusCo de.ServiceUnavailable }; |
835 } | 835 } |
836 | 836 |
837 ReadContent = await request.Content.ReadAsStringAsync(); | 837 ReadContent = await request.Content.ReadAsStringAsync(); |
838 return new HttpResponseMessage(); | 838 return new HttpResponseMessage(); |
839 } | 839 } |
840 } | 840 } |
841 | 841 |
842 /// <summary> | 842 /// <summary> |
843 /// Defines the different content types we test in <see cref="SubtestSen dAsyncRetryContent"/>. | 843 /// Defines the different content types we test in <see cref="SubtestSen dAsyncRetryContent"/>. |
844 /// </summary> | 844 /// </summary> |
845 private enum ContentType | 845 private enum ContentType |
846 { | 846 { |
847 String, | 847 String, |
848 Stream, | 848 Stream, |
849 ByteArray | 849 ByteArray |
850 } | 850 } |
851 | 851 |
852 /// <summary> Tests that retry works with different kind of contents (St ring, Stream and ByteArray). </summary> | 852 /// <summary>Tests that retry works with different kind of contents (Str ing, Stream and ByteArray).</summary> |
853 private void SubtestSendAsyncRetryContent(ContentType type) | 853 private void SubtestSendAsyncRetryContent(ContentType type) |
854 { | 854 { |
855 var content = "test-content"; | 855 var content = "test-content"; |
856 var contentHandler = new ContentMessageHandler(); | 856 var contentHandler = new ContentMessageHandler(); |
857 var configurableHanlder = new ConfigurableMessageHandler(contentHand ler) | 857 var configurableHanlder = new ConfigurableMessageHandler(contentHand ler) |
858 { | 858 { |
859 NumTries = 10 | 859 NumTries = 10 |
860 }; | 860 }; |
861 configurableHanlder.UnsuccessfulResponseHandlers.Add(new TrueUnsucce ssfulResponseHandler()); | 861 configurableHanlder.UnsuccessfulResponseHandlers.Add(new TrueUnsucce ssfulResponseHandler()); |
862 using (var client = new HttpClient(configurableHanlder)) | 862 using (var client = new HttpClient(configurableHanlder)) |
(...skipping 19 matching lines...) Expand all Loading... | |
882 break; | 882 break; |
883 } | 883 } |
884 | 884 |
885 HttpResponseMessage response = client.SendAsync(request).Result; | 885 HttpResponseMessage response = client.SendAsync(request).Result; |
886 Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); | 886 Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); |
887 Assert.That(contentHandler.Calls, Is.EqualTo(ContentMessageHandl er.NumFails)); | 887 Assert.That(contentHandler.Calls, Is.EqualTo(ContentMessageHandl er.NumFails)); |
888 Assert.That(contentHandler.ReadContent, Is.EqualTo(content)); | 888 Assert.That(contentHandler.ReadContent, Is.EqualTo(content)); |
889 } | 889 } |
890 } | 890 } |
891 | 891 |
892 /// <summary> Tests that a string content works as expected on retry. </ summary> | 892 /// <summary>Tests that a string content works as expected on retry.</su mmary> |
893 [Test] | 893 [Test] |
894 public void SendAsync_Retry_CorrectStringContent() | 894 public void SendAsync_Retry_CorrectStringContent() |
895 { | 895 { |
896 SubtestSendAsyncRetryContent(ContentType.String); | 896 SubtestSendAsyncRetryContent(ContentType.String); |
897 } | 897 } |
898 | 898 |
899 /// <summary> Tests that a stream content works as expected on retry. </ summary> | 899 /// <summary>Tests that a stream content works as expected on retry.</su mmary> |
900 [Test] | 900 [Test] |
901 public void SendAsync_Retry_CorrectStreamContent() | 901 public void SendAsync_Retry_CorrectStreamContent() |
902 { | 902 { |
903 SubtestSendAsyncRetryContent(ContentType.Stream); | 903 SubtestSendAsyncRetryContent(ContentType.Stream); |
904 } | 904 } |
905 | 905 |
906 /// <summary> Tests that a byte array content works as expected on retry . </summary> | 906 /// <summary>Tests that a byte array content works as expected on retry. </summary> |
907 [Test] | 907 [Test] |
908 public void SendAsync_Retry_CorrectByteArrayContent() | 908 public void SendAsync_Retry_CorrectByteArrayContent() |
909 { | 909 { |
910 SubtestSendAsyncRetryContent(ContentType.ByteArray); | 910 SubtestSendAsyncRetryContent(ContentType.ByteArray); |
911 } | 911 } |
912 | 912 |
913 #endregion | 913 #endregion |
914 | 914 |
915 /// <summary> Tests setting number of tries. </summary> | 915 /// <summary>Tests setting number of tries.</summary> |
916 [Test] | 916 [Test] |
917 public void NumTries_Setter() | 917 public void NumTries_Setter() |
918 { | 918 { |
919 var configurableHanlder = new ConfigurableMessageHandler(new HttpCli entHandler()); | 919 var configurableHanlder = new ConfigurableMessageHandler(new HttpCli entHandler()); |
920 | 920 |
921 // valid values | 921 // valid values |
922 configurableHanlder.NumTries = ConfigurableMessageHandler.MaxAllowed NumTries; | 922 configurableHanlder.NumTries = ConfigurableMessageHandler.MaxAllowed NumTries; |
923 configurableHanlder.NumTries = ConfigurableMessageHandler.MaxAllowed NumTries - 1; | 923 configurableHanlder.NumTries = ConfigurableMessageHandler.MaxAllowed NumTries - 1; |
924 configurableHanlder.NumTries = 1; | 924 configurableHanlder.NumTries = 1; |
925 | 925 |
(...skipping 20 matching lines...) Expand all Loading... | |
946 { | 946 { |
947 configurableHanlder.NumTries = -2; | 947 configurableHanlder.NumTries = -2; |
948 Assert.Fail(); | 948 Assert.Fail(); |
949 } | 949 } |
950 catch (ArgumentOutOfRangeException ex) | 950 catch (ArgumentOutOfRangeException ex) |
951 { | 951 { |
952 Assert.True(ex.Message.Contains("Parameter name: NumTries")); | 952 Assert.True(ex.Message.Contains("Parameter name: NumTries")); |
953 } | 953 } |
954 } | 954 } |
955 | 955 |
956 /// <summary> | 956 /// <summary> |
957 /// Tests the number of tries in case of unsuccessful response when unsu ccessful response handler is plugged to· | 957 /// Tests the number of tries in case of unsuccessful response when unsu ccessful response handler is plugged to· |
958 /// the message handler.· | 958 /// the message handler.· |
959 /// </summary> | 959 /// </summary> |
960 [Test] | 960 [Test] |
961 public void SendAsync_NumTries() | 961 public void SendAsync_NumTries() |
962 { | 962 { |
963 SubtestSendAsyncNumTries(5, false); | 963 SubtestSendAsyncNumTries(5, false); |
964 SubtestSendAsyncNumTries(5); | 964 SubtestSendAsyncNumTries(5); |
965 SubtestSendAsyncNumTries(1); | 965 SubtestSendAsyncNumTries(1); |
966 SubtestSendAsyncNumTries(1, false); | 966 SubtestSendAsyncNumTries(1, false); |
(...skipping 23 matching lines...) Expand all Loading... | |
990 configurableHanlder.UnsuccessfulResponseHandlers.Add(unsuccessfu lHandler); | 990 configurableHanlder.UnsuccessfulResponseHandlers.Add(unsuccessfu lHandler); |
991 } | 991 } |
992 | 992 |
993 using (var client = new HttpClient(configurableHanlder)) | 993 using (var client = new HttpClient(configurableHanlder)) |
994 { | 994 { |
995 client.GetAsync("http://num-retres"); | 995 client.GetAsync("http://num-retres"); |
996 Assert.That(handler.Calls, Is.EqualTo(handle ? numTries : 1)); | 996 Assert.That(handler.Calls, Is.EqualTo(handle ? numTries : 1)); |
997 } | 997 } |
998 } | 998 } |
999 | 999 |
1000 /// <summary> Tests that the configurable message handler sets the User- Agent header. </summary> | 1000 /// <summary>Tests that the configurable message handler sets the User-A gent header.</summary> |
1001 [Test] | 1001 [Test] |
1002 public void SendAsync_UserAgent() | 1002 public void SendAsync_UserAgent() |
1003 { | 1003 { |
1004 var apiVersion = string.Format("google-api-dotnet-client/{0} (gzip)" , Utilities.GetLibraryVersion()); | 1004 var apiVersion = string.Format("google-api-dotnet-client/{0} (gzip)" , Utilities.GetLibraryVersion()); |
1005 const string applicationName = "NO NAME"; | 1005 const string applicationName = "NO NAME"; |
1006 | 1006 |
1007 var handler = new MockMessageHandler(); | 1007 var handler = new MockMessageHandler(); |
1008 var configurableHanlder = new ConfigurableMessageHandler(handler); | 1008 var configurableHanlder = new ConfigurableMessageHandler(handler); |
1009 | 1009 |
1010 using (var client = new HttpClient(configurableHanlder)) | 1010 using (var client = new HttpClient(configurableHanlder)) |
1011 { | 1011 { |
1012 // without application name | 1012 // without application name |
1013 var request = new HttpRequestMessage(HttpMethod.Get, "https://te st-user-agent"); | 1013 var request = new HttpRequestMessage(HttpMethod.Get, "https://te st-user-agent"); |
1014 HttpResponseMessage response = client.SendAsync(request).Result; | 1014 HttpResponseMessage response = client.SendAsync(request).Result; |
1015 var userAgent = string.Join(" ", request.Headers.GetValues("User -Agent").ToArray()); | 1015 var userAgent = string.Join(" ", request.Headers.GetValues("User -Agent").ToArray()); |
1016 Assert.That(userAgent, Is.EqualTo(apiVersion)); | 1016 Assert.That(userAgent, Is.EqualTo(apiVersion)); |
1017 | 1017 |
1018 // with application name | 1018 // with application name |
1019 configurableHanlder.ApplicationName = applicationName; | 1019 configurableHanlder.ApplicationName = applicationName; |
1020 request = new HttpRequestMessage(HttpMethod.Get, "https://test-u ser-agent"); | 1020 request = new HttpRequestMessage(HttpMethod.Get, "https://test-u ser-agent"); |
1021 response = client.SendAsync(request).Result; | 1021 response = client.SendAsync(request).Result; |
1022 userAgent = string.Join(" ", request.Headers.GetValues("User-Age nt").ToArray()); | 1022 userAgent = string.Join(" ", request.Headers.GetValues("User-Age nt").ToArray()); |
1023 Assert.That(userAgent, Is.EqualTo(applicationName " " apiVer sion)); | 1023 Assert.That(userAgent, Is.EqualTo(applicationName " " apiVer sion)); |
1024 } | 1024 } |
1025 } | 1025 } |
1026 } | 1026 } |
1027 } | 1027 } |
LEFT | RIGHT |