Left: | ||
Right: |
LEFT | RIGHT |
---|---|
1 /* | 1 /* |
2 Copyright 2011 Google Inc | 2 Copyright 2011 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 20 matching lines...) Expand all Loading... | |
31 using Google.Apis.Discovery; | 31 using Google.Apis.Discovery; |
32 using Google.Apis.Http; | 32 using Google.Apis.Http; |
33 using Google.Apis.Requests; | 33 using Google.Apis.Requests; |
34 using Google.Apis.Services; | 34 using Google.Apis.Services; |
35 using Google.Apis.Testing; | 35 using Google.Apis.Testing; |
36 using Google.Apis.Util; | 36 using Google.Apis.Util; |
37 | 37 |
38 | 38 |
39 namespace Google.Apis.Tests.Apis.Requests | 39 namespace Google.Apis.Tests.Apis.Requests |
40 { | 40 { |
41 /// <summary> Tests for the <see cref="Google.Apis.Requests.ClientServiceReq uest"/>. </summary> | 41 /// <summary>Tests for the <see cref="Google.Apis.Requests.ClientServiceRequ est"/>.</summary> |
42 [TestFixture] | 42 [TestFixture] |
43 public class ClientServiceRequestTest | 43 public class ClientServiceRequestTest |
44 { | 44 { |
45 [TestFixtureSetUp] | 45 [TestFixtureSetUp] |
46 public void SetUp() | 46 public void SetUp() |
47 { | 47 { |
48 // Uncomment to enable logging during tests | 48 // Uncomment to enable logging during tests |
49 // ApplicationContext.RegisterLogger(new Google.Apis.Logging.Log4Net Logger()); | 49 // ApplicationContext.RegisterLogger(new Google.Apis.Logging.Log4Net Logger()); |
50 } | 50 } |
51 | 51 |
52 /// <summary> Helper method to get a string from the stream. </summary> | 52 /// <summary>Helper method to get a string from the stream.</summary> |
53 private static string ExtractStringFromStream(Stream stream) | 53 private static string ExtractStringFromStream(Stream stream) |
54 { | 54 { |
55 var buffer = new byte[1000]; | 55 var buffer = new byte[1000]; |
56 var len = stream.Read(buffer, 0, 1000); | 56 var len = stream.Read(buffer, 0, 1000); |
57 return Encoding.UTF8.GetString(buffer, 0, len); | 57 return Encoding.UTF8.GetString(buffer, 0, len); |
58 } | 58 } |
59 | 59 |
60 /// <summary> A mock response class. </summary> | 60 /// <summary>A mock response class.</summary> |
61 class MockResponse : IDirectResponseSchema | 61 class MockResponse : IDirectResponseSchema |
62 { | 62 { |
63 [Newtonsoft.Json.JsonPropertyAttribute("etag")] | 63 [Newtonsoft.Json.JsonPropertyAttribute("etag")] |
64 public string ETag { get; set; } | 64 public string ETag { get; set; } |
65 | 65 |
66 [Newtonsoft.Json.JsonPropertyAttribute("name")] | 66 [Newtonsoft.Json.JsonPropertyAttribute("name")] |
67 public string Name { get; set; } | 67 public string Name { get; set; } |
68 | 68 |
69 [Newtonsoft.Json.JsonPropertyAttribute("id")] | 69 [Newtonsoft.Json.JsonPropertyAttribute("id")] |
70 public int Id { get; set; } | 70 public int Id { get; set; } |
71 | 71 |
72 public override bool Equals(object obj) | 72 public override bool Equals(object obj) |
73 { | 73 { |
74 var other = obj as MockResponse; | 74 var other = obj as MockResponse; |
75 return (other != null && other.ETag == ETag && other.Name == Nam e && other.Id == Id); | 75 return (other != null && other.ETag == ETag && other.Name == Nam e && other.Id == Id); |
76 } | 76 } |
77 | 77 |
78 public override int GetHashCode() | 78 public override int GetHashCode() |
79 { | 79 { |
80 return (ETag ?? string.Empty).GetHashCode() ^ (Name ?? string.Em pty).GetHashCode() + Id; | 80 return (ETag ?? string.Empty).GetHashCode() ^ (Name ?? string.Em pty).GetHashCode() + Id; |
81 } | 81 } |
82 } | 82 } |
83 | 83 |
84 /// <summary> A mock request class. </summary> | 84 /// <summary>A mock request class.</summary> |
85 class MockRequest : IDirectResponseSchema | 85 class MockRequest : IDirectResponseSchema |
86 { | 86 { |
87 [Newtonsoft.Json.JsonPropertyAttribute("etag")] | 87 [Newtonsoft.Json.JsonPropertyAttribute("etag")] |
88 public string ETag { get; set; } | 88 public string ETag { get; set; } |
89 | 89 |
90 [Newtonsoft.Json.JsonPropertyAttribute("long_name")] | 90 [Newtonsoft.Json.JsonPropertyAttribute("long_name")] |
91 public string Name { get; set; } | 91 public string Name { get; set; } |
92 | 92 |
93 public override bool Equals(object obj) | 93 public override bool Equals(object obj) |
94 { | 94 { |
95 var other = obj as MockRequest; | 95 var other = obj as MockRequest; |
96 return (other != null && other.ETag == ETag && other.Name == Nam e); | 96 return (other != null && other.ETag == ETag && other.Name == Nam e); |
97 } | 97 } |
98 | 98 |
99 public override int GetHashCode() | 99 public override int GetHashCode() |
100 { | 100 { |
101 return (ETag ?? string.Empty).GetHashCode() ^ (Name ?? string.Em pty).GetHashCode(); | 101 return (ETag ?? string.Empty).GetHashCode() ^ (Name ?? string.Em pty).GetHashCode(); |
102 } | 102 } |
103 } | 103 } |
104 | 104 |
105 /// <summary> A mock service request which returns <see cref="MockRespon se"/>. </summary> | 105 /// <summary>A mock service request which returns <see cref="MockRespons e"/>.</summary> |
106 class TestClientServiceRequest : ClientServiceRequest<MockResponse> | 106 class TestClientServiceRequest : ClientServiceRequest<MockResponse> |
107 { | 107 { |
108 /// <summary> Gets or sets a request number. It's used on concurrent tests. </summary> | 108 /// <summary>Gets or sets a request number. It's used on concurrent tests.</summary> |
109 public int CallNum { get; set; } | 109 public int CallNum { get; set; } |
110 private string httpMethod; | 110 private string httpMethod; |
111 private object body; | 111 private object body; |
112 | 112 |
113 public TestClientServiceRequest(IClientService service, string httpM ethod, object body) | 113 public TestClientServiceRequest(IClientService service, string httpM ethod, object body) |
114 : base(service) | 114 : base(service) |
115 { | 115 { |
116 this.httpMethod = httpMethod; | 116 this.httpMethod = httpMethod; |
117 this.body = body; | 117 this.body = body; |
118 InitParameters(); | 118 InitParameters(); |
(...skipping 13 matching lines...) Expand all Loading... | |
132 { | 132 { |
133 get { return httpMethod; } | 133 get { return httpMethod; } |
134 } | 134 } |
135 | 135 |
136 protected override object GetBody() | 136 protected override object GetBody() |
137 { | 137 { |
138 return body; | 138 return body; |
139 } | 139 } |
140 } | 140 } |
141 | 141 |
142 /// <summary> A mock message handler which returns an error. </summary> | 142 /// <summary>A mock message handler which returns an error.</summary> |
143 class ErrorMessageHanlder : CountableMessageHandler | 143 class ErrorMessageHanlder : CountableMessageHandler |
144 { | 144 { |
145 public string ExpectedError = | 145 public string ExpectedError = |
146 @"Message[Login Required] Location[Authorization - header] Reaso n[required] Domain[global]"; | 146 @"Message[Login Required] Location[Authorization - header] Reaso n[required] Domain[global]"; |
147 | 147 |
148 protected override Task<HttpResponseMessage> SendAsyncCore(HttpReque stMessage request, | 148 protected override Task<HttpResponseMessage> SendAsyncCore(HttpReque stMessage request, |
149 CancellationToken cancellationToken) | 149 CancellationToken cancellationToken) |
150 { | 150 { |
151 var error = @"{ | 151 var error = @"{ |
152 ""error"": { | 152 ""error"": { |
(...skipping 16 matching lines...) Expand all Loading... | |
169 Content = new StringContent(error), | 169 Content = new StringContent(error), |
170 StatusCode = System.Net.HttpStatusCode.Unauthorized | 170 StatusCode = System.Net.HttpStatusCode.Unauthorized |
171 }; | 171 }; |
172 | 172 |
173 TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompleti onSource<HttpResponseMessage>(); | 173 TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompleti onSource<HttpResponseMessage>(); |
174 tcs.SetResult(response); | 174 tcs.SetResult(response); |
175 return tcs.Task; | 175 return tcs.Task; |
176 } | 176 } |
177 } | 177 } |
178 | 178 |
179 /// <summary> Tests message handler which tests the content on the reque st and the response. </summary> | 179 /// <summary>Tests message handler which tests the content on the reques t and the response.</summary> |
180 class TestBodyMessageHnalder : CountableMessageHandler | 180 class TestBodyMessageHandler : CountableMessageHandler |
181 { | 181 { |
182 /// <summary> Gets or sets indication is GZip is eanbled. </summary> | 182 /// <summary>Gets or sets indication is GZip is eanbled.</summary> |
183 public bool GZipEnabled { get; set; } | 183 public bool GZipEnabled { get; set; } |
184 | 184 |
185 /// <summary> Gets or sets the expected request object. </summary> | 185 /// <summary>Gets or sets the expected request object.</summary> |
186 public MockRequest ExpectedRequestObject { get; set; } | 186 public MockRequest ExpectedRequestObject { get; set; } |
187 | 187 |
188 /// <summary> Gets or sets the returned response object </summary> | 188 /// <summary>Gets or sets the returned response object </summary> |
189 public MockResponse ResponseObject { get; set; } | 189 public MockResponse ResponseObject { get; set; } |
190 | 190 |
191 /// <summary> Gets or sets the Serializer which is used to serialize and deserialize messages. </summary> | 191 /// <summary>Gets or sets the Serializer which is used to serialize and deserialize messages.</summary> |
192 public ISerializer Serializer { get; set; } | 192 public ISerializer Serializer { get; set; } |
193 | 193 |
194 /// <summary> Gets the thread id in which this handler was invoked. </summary> | 194 /// <summary>Gets the thread id in which this handler was invoked.</ summary> |
195 public int ThreadId { get; private set; } | 195 public int ThreadId { get; private set; } |
196 | 196 |
197 public string ResponseETag = "\"some-etag-here\""; | 197 public string ResponseETag = "\"some-etag-here\""; |
198 | 198 |
199 protected override async Task<HttpResponseMessage> SendAsyncCore(Htt pRequestMessage request, | 199 protected override async Task<HttpResponseMessage> SendAsyncCore(Htt pRequestMessage request, |
200 CancellationToken cancellationToken) | 200 CancellationToken cancellationToken) |
201 { | 201 { |
202 ThreadId = Thread.CurrentThread.ManagedThreadId; | 202 ThreadId = Thread.CurrentThread.ManagedThreadId; |
203 var mediaType = "application/json"; | 203 var mediaType = "application/json"; |
204 string strObject = null; | 204 string strObject = null; |
205 | 205 |
206 // if gzip enabled the request content is a gzip stream, otherwi se it's a string content | 206 // If gzip enabled the request content is a gzip stream, otherwi se it's a string content. |
207 if (GZipEnabled) | 207 if (GZipEnabled) |
208 { | 208 { |
209 Assert.That(request.Content, Is.AssignableFrom<StreamContent >()); | 209 Assert.That(request.Content, Is.AssignableFrom<StreamContent >()); |
210 var encoding = request.Content.Headers.ContentEncoding; | 210 var encoding = request.Content.Headers.ContentEncoding; |
211 Assert.That(encoding.Count == 1 && encoding.First().Equals(" gzip"), | 211 Assert.That(encoding.Count == 1 && encoding.First().Equals(" gzip"), |
212 "Content-Encoding should be 'gzip'"); | 212 "Content-Encoding should be 'gzip'"); |
213 var stream = await request.Content.ReadAsStreamAsync(); | 213 var stream = await request.Content.ReadAsStreamAsync(); |
214 using (GZipStream gzipStream = new GZipStream(stream, Compre ssionMode.Decompress)) | 214 using (GZipStream gzipStream = new GZipStream(stream, Compre ssionMode.Decompress)) |
215 { | 215 { |
216 strObject = ExtractStringFromStream(gzipStream); | 216 strObject = ExtractStringFromStream(gzipStream); |
217 } | 217 } |
218 } | 218 } |
219 else | 219 else |
220 { | 220 { |
221 Assert.That(request.Content, Is.AssignableFrom<StringContent >()); | 221 Assert.That(request.Content, Is.AssignableFrom<StringContent >()); |
222 strObject = await request.Content.ReadAsStringAsync(); | 222 strObject = await request.Content.ReadAsStringAsync(); |
223 } | 223 } |
224 | 224 |
225 Assert.That(request.Content.Headers.ContentType, Is.EqualTo(new MediaTypeHeaderValue(mediaType) | 225 Assert.That(request.Content.Headers.ContentType, Is.EqualTo(new MediaTypeHeaderValue(mediaType) |
226 { | 226 { |
227 CharSet = Encoding.UTF8.WebName | 227 CharSet = Encoding.UTF8.WebName |
228 })); | 228 })); |
229 | 229 |
230 // deserialize the requested object and check it's equal to the expected object | 230 // Deserialize the requested object and check it's equal to the expected object. |
231 var obj = Serializer.Deserialize<MockRequest>(strObject); | 231 var obj = Serializer.Deserialize<MockRequest>(strObject); |
232 Assert.That(obj, Is.EqualTo(ExpectedRequestObject)); | 232 Assert.That(obj, Is.EqualTo(ExpectedRequestObject)); |
233 | 233 |
234 // return the response (with ETag) | 234 // Return the response (with ETag). |
235 var response = new HttpResponseMessage(); | 235 var response = new HttpResponseMessage(); |
236 var serializedObject = Serializer.Serialize(ResponseObject); | 236 var serializedObject = Serializer.Serialize(ResponseObject); |
237 response.Content = new StringContent(serializedObject, Encoding. UTF8, mediaType); | 237 response.Content = new StringContent(serializedObject, Encoding. UTF8, mediaType); |
238 response.Headers.ETag = new EntityTagHeaderValue(ResponseETag); | 238 response.Headers.ETag = new EntityTagHeaderValue(ResponseETag); |
239 return response; | 239 return response; |
240 } | 240 } |
241 } | 241 } |
242 | 242 |
243 /// <summary> | 243 /// <summary> |
244 /// A mock exception which is thrown from a mock message handler in case it is configured to throw exceptions.· | 244 /// A mock exception which is thrown from a mock message handler in case it is configured to throw exceptions.· |
245 /// </summary> | 245 /// </summary> |
246 class InvalidOperationMockException : Exception | 246 class InvalidOperationMockException : Exception |
247 { | 247 { |
248 public InvalidOperationMockException(string str) | 248 public InvalidOperationMockException(string str) |
249 : base(str) | 249 : base(str) |
250 { | 250 { |
251 } | 251 } |
252 } | 252 } |
253 | 253 |
254 /// <summary> A message handler which returns a HTTP response message or throw an exception. </summary> | 254 /// <summary>A message handler which returns a HTTP response message or throw an exception.</summary> |
peleyal
2013/09/10 01:14:44
remove space at the end of the comment
peleyal
2013/09/10 12:32:22
Done.
| |
255 class MockMessageHandler : CountableMessageHandler | 255 class MockMessageHandler : CountableMessageHandler |
256 { | 256 { |
257 private bool ThrowException { get; set; } | 257 private bool ThrowException { get; set; } |
258 public MockMessageHandler(bool throwException = false) | 258 public MockMessageHandler(bool throwException = false) |
259 { | 259 { |
260 ThrowException = throwException; | 260 ThrowException = throwException; |
261 } | 261 } |
262 | 262 |
263 protected override Task<HttpResponseMessage> SendAsyncCore(HttpReque stMessage request, | 263 protected override Task<HttpResponseMessage> SendAsyncCore(HttpReque stMessage request, |
264 CancellationToken cancellationToken) | 264 CancellationToken cancellationToken) |
265 { | 265 { |
266 if (ThrowException) | 266 if (ThrowException) |
267 { | 267 { |
268 throw new InvalidOperationMockException("INVALID"); | 268 throw new InvalidOperationMockException("INVALID"); |
269 } | 269 } |
270 | 270 |
271 TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompleti onSource<HttpResponseMessage>(); | 271 TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompleti onSource<HttpResponseMessage>(); |
272 tcs.SetResult(new HttpResponseMessage()); | 272 tcs.SetResult(new HttpResponseMessage()); |
273 return tcs.Task; | 273 return tcs.Task; |
274 } | 274 } |
275 } | 275 } |
276 | 276 |
277 /// <summary> A message handler which is used to cancel a HTTP request i n the middle.</summary> | 277 /// <summary>A message handler which is used to cancel a HTTP request in the middle.</summary> |
278 class CancelRedirectMessageHandler : CountableMessageHandler | 278 class CancelRedirectMessageHandler : CountableMessageHandler |
279 { | 279 { |
280 /// <summary> The cancellation token we are going to use to cancel a request.</summary> | 280 /// <summary>The cancellation token we are going to use to cancel a request.</summary> |
281 public CancellationTokenSource CancellationTokenSource { get; set; } | 281 public CancellationTokenSource CancellationTokenSource { get; set; } |
282 | 282 |
283 /// <summary> The request index we are going to cancel.</summary> | 283 /// <summary>The request index we are going to cancel.</summary> |
284 public int CancelRequestNum { get; set; } | 284 public int CancelRequestNum { get; set; } |
285 | 285 |
286 protected override Task<HttpResponseMessage> SendAsyncCore(HttpReque stMessage request, | 286 protected override Task<HttpResponseMessage> SendAsyncCore(HttpReque stMessage request, |
287 CancellationToken cancellationToken) | 287 CancellationToken cancellationToken) |
288 { | 288 { |
289 if (Calls == CancelRequestNum) | 289 if (Calls == CancelRequestNum) |
290 { | 290 { |
291 CancellationTokenSource.Cancel(); | 291 CancellationTokenSource.Cancel(); |
292 } | 292 } |
293 var response = new HttpResponseMessage() | 293 var response = new HttpResponseMessage() |
294 { | 294 { |
295 StatusCode = HttpStatusCode.Redirect, | 295 StatusCode = HttpStatusCode.Redirect, |
296 RequestMessage = request | 296 RequestMessage = request |
297 }; | 297 }; |
298 response.Headers.Location = new Uri("http://www.test.com"); | 298 response.Headers.Location = new Uri("http://www.test.com"); |
299 | 299 |
300 TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompleti onSource<HttpResponseMessage>(); | 300 TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompleti onSource<HttpResponseMessage>(); |
301 tcs.SetResult(response); | 301 tcs.SetResult(response); |
302 return tcs.Task; | 302 return tcs.Task; |
303 } | 303 } |
304 } | 304 } |
305 | 305 |
306 /// <summary> | 306 /// <summary> |
307 /// A message handler which checks concurrent calls (each odd request wi ll succeeded, and even request will· | 307 /// A message handler which checks concurrent calls (each odd request wi ll succeeded, and even request will· |
308 /// fail on the first try and will succeeded in the second try. | 308 /// fail on the first try and will succeeded in the second try. |
309 /// </summary> | 309 /// </summary> |
310 class ConcurrentCallsHandler : CountableMessageHandler | 310 class ConcurrentCallsHandler : CountableMessageHandler |
311 { | 311 { |
312 /// <summary> Gets or sets the Serializer which is used to serialize and deserialize messages. </summary> | 312 /// <summary>Gets or sets the Serializer which is used to serialize and deserialize messages.</summary> |
313 public ISerializer Serializer { get; set; } | 313 public ISerializer Serializer { get; set; } |
314 | 314 |
315 protected override Task<HttpResponseMessage> SendAsyncCore(HttpReque stMessage request, | 315 protected override Task<HttpResponseMessage> SendAsyncCore(HttpReque stMessage request, |
316 CancellationToken cancellationToken) | 316 CancellationToken cancellationToken) |
317 { | 317 { |
318 var response = new HttpResponseMessage(); | 318 var response = new HttpResponseMessage(); |
319 var uri = request.RequestUri.AbsoluteUri; | 319 var uri = request.RequestUri.AbsoluteUri; |
320 int lastDigit = 0; | 320 int lastDigit = 0; |
321 if (int.TryParse(uri[uri.Length - 1].ToString(), out lastDigit) && lastDigit % 2 == 0) | 321 if (int.TryParse(uri[uri.Length - 1].ToString(), out lastDigit) && lastDigit % 2 == 0) |
322 { | 322 { |
323 response.StatusCode = System.Net.HttpStatusCode.ServiceUnava ilable; | 323 response.StatusCode = System.Net.HttpStatusCode.ServiceUnava ilable; |
324 request.RequestUri = new Uri(uri + (lastDigit + 1)); | 324 request.RequestUri = new Uri(uri + (lastDigit + 1)); |
325 } | 325 } |
326 else | 326 else |
327 { | 327 { |
328 var mockObject = new MockResponse { Name = "Name-" + lastDig it }; | 328 var mockObject = new MockResponse { Name = "Name-" + lastDig it }; |
329 var serializedObject = Serializer.Serialize(mockObject); | 329 var serializedObject = Serializer.Serialize(mockObject); |
330 response.Content = new StringContent(serializedObject, Encod ing.UTF8, "application/json"); | 330 response.Content = new StringContent(serializedObject, Encod ing.UTF8, "application/json"); |
331 } | 331 } |
332 | 332 |
333 TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompleti onSource<HttpResponseMessage>(); | 333 TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompleti onSource<HttpResponseMessage>(); |
334 tcs.SetResult(response); | 334 tcs.SetResult(response); |
335 return tcs.Task; | 335 return tcs.Task; |
336 } | 336 } |
337 | 337 |
338 /// <summary> Unsuccessful response handler which "handles" service unavailable responses. </summary> | 338 /// <summary>Unsuccessful response handler which "handles" service u navailable responses.</summary> |
339 internal class ServiceUnavailableUnsuccessfulResponseHandler : IHttp UnsuccessfulResponseHandler | 339 internal class ServiceUnavailableUnsuccessfulResponseHandler : IHttp UnsuccessfulResponseHandler |
340 { | 340 { |
341 public Task<bool> HandleResponseAsync(HandleUnsuccessfulResponse Args args) | 341 public Task<bool> HandleResponseAsync(HandleUnsuccessfulResponse Args args) |
342 { | 342 { |
343 TaskCompletionSource<bool> tcs = new TaskCompletionSource<bo ol>(); | 343 TaskCompletionSource<bool> tcs = new TaskCompletionSource<bo ol>(); |
344 tcs.SetResult(args.Response.StatusCode.Equals(HttpStatusCode .ServiceUnavailable)); | 344 tcs.SetResult(args.Response.StatusCode.Equals(HttpStatusCode .ServiceUnavailable)); |
345 return tcs.Task; | 345 return tcs.Task; |
346 } | 346 } |
347 } | 347 } |
348 | 348 |
349 /// <summary> | 349 /// <summary> |
350 /// Adds service unavailable unsuccessful response handler to the co nfigurable message handler. | 350 /// Adds service unavailable unsuccessful response handler to the co nfigurable message handler. |
351 /// </summary> | 351 /// </summary> |
352 internal class Initializer : IConfigurableHttpClientInitializer | 352 internal class Initializer : IConfigurableHttpClientInitializer |
353 { | 353 { |
354 public void Initialize(ConfigurableHttpClient httpClient) | 354 public void Initialize(ConfigurableHttpClient httpClient) |
355 { | 355 { |
356 httpClient.MessageHandler.UnsuccessfulResponseHandlers.Add( | 356 httpClient.MessageHandler.UnsuccessfulResponseHandlers.Add( |
357 new ServiceUnavailableUnsuccessfulResponseHandler()); | 357 new ServiceUnavailableUnsuccessfulResponseHandler()); |
358 } | 358 } |
359 } | 359 } |
360 } | 360 } |
361 | 361 |
362 #region Execute (and ExecuteAsync) | 362 #region Execute (and ExecuteAsync) |
363 | 363 |
364 /// <summary> Tests that canceling a outgoing request to the server work s as expected.</summary> | 364 /// <summary>Tests that canceling a outgoing request to the server works as expected.</summary> |
365 [Test] | 365 [Test] |
366 public void ExecuteAsync_Cancel() | 366 public void ExecuteAsync_Cancel() |
367 { | 367 { |
368 SubtestExecuteAsync_Cancel(1); | 368 SubtestExecuteAsync_Cancel(1); |
369 SubtestExecuteAsync_Cancel(5); | 369 SubtestExecuteAsync_Cancel(5); |
370 SubtestExecuteAsync_Cancel(10); | 370 SubtestExecuteAsync_Cancel(10); |
371 SubtestExecuteAsync_Cancel(11); | 371 SubtestExecuteAsync_Cancel(11); |
372 } | 372 } |
373 | 373 |
374 /// <summary> | 374 /// <summary> |
(...skipping 19 matching lines...) Expand all Loading... | |
394 request = new TestClientServiceRequest(service, "POST", new Mock Request()); | 394 request = new TestClientServiceRequest(service, "POST", new Mock Request()); |
395 try | 395 try |
396 { | 396 { |
397 request.ExecuteAsync(handler.CancellationTokenSource.Token). Wait(); | 397 request.ExecuteAsync(handler.CancellationTokenSource.Token). Wait(); |
398 Assert.Fail(); | 398 Assert.Fail(); |
399 } | 399 } |
400 catch (AggregateException ex) | 400 catch (AggregateException ex) |
401 { | 401 { |
402 if (ex.InnerException is TaskCanceledException) | 402 if (ex.InnerException is TaskCanceledException) |
403 { | 403 { |
404 // we expect a task canceled exception in case the cance led request is less or equal total | 404 // We expect a task canceled exception in case the cance led request is less or equal total |
405 // number of retries | 405 // number of retries. |
406 Assert.False(cancelRequestNum > service.HttpClient.Messa geHandler.NumTries); | 406 Assert.False(cancelRequestNum > service.HttpClient.Messa geHandler.NumTries); |
407 } | 407 } |
408 else | 408 else |
409 { | 409 { |
410 // exception should be thrown as a result of casting to MockResponse object | 410 // Canceled exception wasn't thrown, in that case the ca ncel request number is bigger than |
411 // the actual number of tries. | |
411 Assert.True(cancelRequestNum > service.HttpClient.Messag eHandler.NumTries); | 412 Assert.True(cancelRequestNum > service.HttpClient.Messag eHandler.NumTries); |
412 } | 413 } |
413 } | 414 } |
414 | 415 |
415 var expectedCalls = Math.Min(service.HttpClient.MessageHandler.N umTries, cancelRequestNum); | 416 var expectedCalls = Math.Min(service.HttpClient.MessageHandler.N umTries, cancelRequestNum); |
416 Assert.That(handler.Calls, Is.EqualTo(expectedCalls)); | 417 Assert.That(handler.Calls, Is.EqualTo(expectedCalls)); |
417 } | 418 } |
418 } | 419 } |
419 | 420 |
421 /// <summary>Tests the execute method in case the service was disposed.< /summary> | |
420 [Test] | 422 [Test] |
421 public void Execute_DisposeService() | 423 public void Execute_DisposeService() |
422 { | 424 { |
423 var handler = new MockMessageHandler(); | 425 var handler = new MockMessageHandler(); |
424 var initializer = new BaseClientService.Initializer() | 426 var initializer = new BaseClientService.Initializer() |
425 { | 427 { |
426 HttpClientFactory = new MockHttpClientFactory(handler) | 428 HttpClientFactory = new MockHttpClientFactory(handler) |
427 }; | 429 }; |
428 | 430 |
429 TestClientServiceRequest request; | 431 TestClientServiceRequest request; |
430 using (var service = new MockClientService(initializer)) | 432 using (var service = new MockClientService(initializer)) |
431 { | 433 { |
432 request = new TestClientServiceRequest(service, "POST", new Mock Request()); | 434 request = new TestClientServiceRequest(service, "POST", new Mock Request()); |
433 } | 435 } |
434 | 436 |
435 // the service was disposed before the request was made (and the mes sage handler as well). As a result an· | 437 // the service was disposed before the request was made (and the mes sage handler as well). As a result an· |
436 // exception should be thrown before we try to send the request | 438 // exception should be thrown before we try to send the request |
437 Assert.Throws<ObjectDisposedException>(() => request.Execute()); | 439 Assert.Throws<ObjectDisposedException>(() => request.Execute()); |
438 } | 440 } |
439 | 441 |
440 /// <summary> A subtest for testing GZip and sync-async calls. </summary > | 442 /// <summary>A subtest for testing GZip and sync-async calls.</summary> |
443 /// <param name="gzip">Defines if GZip is enabled</param> | |
444 /// <param name="async">Defines which method is going to be called (Exec ute or ExecuteAsync)</param> | |
441 private void SubtestExecute_GZip(bool gzip, bool async) | 445 private void SubtestExecute_GZip(bool gzip, bool async) |
442 { | 446 { |
443 var handler = new TestBodyMessageHnalder() | 447 var handler = new TestBodyMessageHandler() |
444 { | 448 { |
445 GZipEnabled = gzip, | 449 GZipEnabled = gzip, |
446 ResponseObject = new MockResponse { Id = 100, Name = "sample name" }, | 450 ResponseObject = new MockResponse { Id = 100, Name = "sample nam e" }, |
447 ExpectedRequestObject = new MockRequest { Name = "long long name" } | 451 ExpectedRequestObject = new MockRequest { Name = "long long name " } |
448 }; | 452 }; |
453 | |
449 var initializer = new BaseClientService.Initializer() | 454 var initializer = new BaseClientService.Initializer() |
450 { | 455 { |
451 GZipEnabled = gzip, | 456 GZipEnabled = gzip, |
452 HttpClientFactory = new MockHttpClientFactory(handler) | 457 HttpClientFactory = new MockHttpClientFactory(handler) |
453 }; | 458 }; |
459 | |
454 using (var service = new MockClientService(initializer)) | 460 using (var service = new MockClientService(initializer)) |
455 { | 461 { |
456 handler.Serializer = service.Serializer; | 462 handler.Serializer = service.Serializer; |
457 | 463 |
458 var request = new TestClientServiceRequest(service, "POST", hand ler.ExpectedRequestObject); | 464 var request = new TestClientServiceRequest(service, "POST", hand ler.ExpectedRequestObject); |
459 MockResponse response = null; | 465 MockResponse response = null; |
460 if (async) | 466 if (async) |
461 { | 467 { |
462 var task = request.ExecuteAsync(); | 468 var task = request.ExecuteAsync(); |
463 response = task.Result; | 469 response = task.Result; |
464 Assert.AreNotEqual(Thread.CurrentThread.ManagedThreadId, han dler.ThreadId); | 470 Assert.AreNotEqual(Thread.CurrentThread.ManagedThreadId, han dler.ThreadId); |
465 } | 471 } |
466 else | 472 else |
467 { | 473 { |
468 response = request.Execute(); | 474 response = request.Execute(); |
469 Assert.AreEqual(Thread.CurrentThread.ManagedThreadId, handle r.ThreadId); | 475 Assert.AreEqual(Thread.CurrentThread.ManagedThreadId, handle r.ThreadId); |
470 } | 476 } |
471 | 477 |
472 // NOTICE: even if GZipEnabled is true, we don't need to extract the real string from the GZip stream, | 478 // Note: Even if GZipEnabled is true, we don't need to extract t he real string from the GZip stream, |
473 // because in a real request we use HttpClientHandler which its AutomaticDecompression is set to· | 479 // because in a real request we use HttpClientHandler which its AutomaticDecompression is set to· |
474 // System.Net.DecompressionMethods.GZip. | 480 // System.Net.DecompressionMethods.GZip. |
475 | 481 |
476 Assert.That(handler.Calls, Is.EqualTo(1)); | 482 Assert.That(handler.Calls, Is.EqualTo(1)); |
477 // the returned response should contain ETag, check that the ser vice add the right ETag property on· | 483 // The returned response should contain ETag, check that the ser vice adds the right ETag property on· |
478 // the response | 484 // the response. |
479 handler.ResponseObject.ETag = handler.ResponseETag; | 485 handler.ResponseObject.ETag = handler.ResponseETag; |
480 Assert.That(response, Is.EqualTo(handler.ResponseObject)); | 486 Assert.That(response, Is.EqualTo(handler.ResponseObject)); |
481 } | 487 } |
482 } | 488 } |
483 | 489 |
484 /// <summary> Tests execute when GZip is enabled. </summary> | 490 /// <summary>Tests execute when GZip is enabled.</summary> |
485 [Test] | 491 [Test] |
486 public void Execute_GZipEnabled() | 492 public void Execute_GZipEnabled() |
487 { | 493 { |
488 SubtestExecute_GZip(true, false); | 494 SubtestExecute_GZip(true, false); |
489 } | 495 } |
490 | 496 |
491 /// <summary> Tests execute when GZip is disabled. </summary> | 497 /// <summary>Tests execute when GZip is disabled.</summary> |
492 [Test] | 498 [Test] |
493 public void Execute_GZipDisabled() | 499 public void Execute_GZipDisabled() |
494 { | 500 { |
495 SubtestExecute_GZip(false, false); | 501 SubtestExecute_GZip(false, false); |
496 } | 502 } |
497 | 503 |
498 /// <summary> Tests async execute when GZip is enabled. </summary> | 504 /// <summary>Tests async execute when GZip is enabled.</summary> |
499 [Test] | 505 [Test] |
500 public void ExecuteAsync_GZipEnabled() | 506 public void ExecuteAsync_GZipEnabled() |
501 { | 507 { |
502 SubtestExecute_GZip(true, true); | 508 SubtestExecute_GZip(true, true); |
503 } | 509 } |
504 | 510 |
505 /// <summary> Tests async execute when GZip is disabled. </summary> | 511 /// <summary>Tests async execute when GZip is disabled.</summary> |
506 [Test] | 512 [Test] |
507 public void ExecuteAsync_GZipDisabled() | 513 public void ExecuteAsync_GZipDisabled() |
508 { | 514 { |
509 SubtestExecute_GZip(false, true); | 515 SubtestExecute_GZip(false, true); |
510 } | 516 } |
511 | 517 |
512 /// <summary> Tests execute with unicode characters. </summary> | 518 /// <summary>Tests execute with unicode characters.</summary> |
513 [Test] | 519 [Test] |
514 public void Execute_UnicodeCharacters() | 520 public void Execute_UnicodeCharacters() |
515 { | 521 { |
516 var handler = new TestBodyMessageHnalder() | 522 var handler = new TestBodyMessageHandler() |
517 { | 523 { |
518 GZipEnabled = false, | 524 GZipEnabled = false, |
519 ResponseObject = new MockResponse { Id = 100, Name = @"مرحبا العالم" }, | 525 ResponseObject = new MockResponse { Id = 100, Name = @"مرحبا الع الم" }, |
520 ExpectedRequestObject = new MockRequest { Name = @"مرحبا الع الم! 您好,世界!" } | 526 ExpectedRequestObject = new MockRequest { Name = @"مرحبا العالم! 您好,世界!" } |
521 }; | 527 }; |
528 | |
522 var initializer = new BaseClientService.Initializer() | 529 var initializer = new BaseClientService.Initializer() |
523 { | 530 { |
524 GZipEnabled = false, | 531 GZipEnabled = false, |
525 HttpClientFactory = new MockHttpClientFactory(handler) | 532 HttpClientFactory = new MockHttpClientFactory(handler) |
526 }; | 533 }; |
534 | |
527 using (var service = new MockClientService(initializer)) | 535 using (var service = new MockClientService(initializer)) |
528 { | 536 { |
529 handler.Serializer = service.Serializer; | 537 handler.Serializer = service.Serializer; |
530 | 538 |
531 var request = new TestClientServiceRequest(service, "GET", handl er.ExpectedRequestObject); | 539 var request = new TestClientServiceRequest(service, "GET", handl er.ExpectedRequestObject); |
532 var response = request.Execute(); | 540 var response = request.Execute(); |
533 Assert.That(handler.Calls, Is.EqualTo(1)); | 541 Assert.That(handler.Calls, Is.EqualTo(1)); |
534 // the returned response should contain ETag, check that the ser vice add the right ETag property on· | 542 // The returned response should contain ETag, check that the ser vice add the right ETag property on· |
535 // the response | 543 // the response. |
536 handler.ResponseObject.ETag = handler.ResponseETag; | 544 handler.ResponseObject.ETag = handler.ResponseETag; |
537 Assert.That(response, Is.EqualTo(handler.ResponseObject)); | 545 Assert.That(response, Is.EqualTo(handler.ResponseObject)); |
538 } | 546 } |
539 } | 547 } |
540 | 548 |
541 /// <summary> | 549 /// <summary> |
542 /// A subtest for testing execute when an exception is thrown during sen ding the request, with or without | 550 /// A subtest for testing Execute when an exception is thrown while send ing the request. This is tested with |
543 /// back-off. If back-off handler is attached to the service's message h andler, there are going to be 3 tries | 551 /// and without back-off. If back-off handler is attached to the service 's message handler, there should be 3 |
544 /// (3 is the default value of <seealso cref="ConfigurableMessageHandler .NumTries" />) before the operation· | 552 /// tries (the default value of <seealso cref="ConfigurableMessageHandle r.NumTries"/>) before the operation· |
545 /// fails. | 553 /// fails. |
546 /// </summary> | 554 /// </summary> |
547 /// <param name="backOff">Indicates if back-off handler is attached to t he service.</param> | 555 /// <param name="backOff">Indicates if back-off handler is attached to t he service.</param> |
548 private void SubtestExecute_ThrowException(bool backOff) | 556 private void SubtestExecute_ThrowException(bool backOff) |
549 { | 557 { |
550 var handler = new MockMessageHandler(true); | 558 var handler = new MockMessageHandler(true); |
551 var initializer = new BaseClientService.Initializer() | 559 var initializer = new BaseClientService.Initializer() |
552 { | 560 { |
553 HttpClientFactory = new MockHttpClientFactory(handler) | 561 HttpClientFactory = new MockHttpClientFactory(handler) |
554 }; | 562 }; |
555 | 563 |
556 // sets the default exponential back-off policy by the input | 564 // Set the default exponential back-off policy by the input. |
557 initializer.DefaultExponentialBackOffPolicy = backOff ? | 565 initializer.DefaultExponentialBackOffPolicy = backOff ? |
558 ExponentialBackOffPolicy.Exception : | 566 ExponentialBackOffPolicy.Exception : ExponentialBackOffPolicy.No ne; |
559 ExponentialBackOffPolicy.None; | |
560 | 567 |
561 using (var service = new MockClientService(initializer)) | 568 using (var service = new MockClientService(initializer)) |
562 { | 569 { |
563 var request = new TestClientServiceRequest(service, "GET", null) ; | 570 var request = new TestClientServiceRequest(service, "GET", null) ; |
564 Assert.Throws<InvalidOperationMockException>(() => request.Execu te()); | 571 Assert.Throws<InvalidOperationMockException>(() => request.Execu te()); |
565 | 572 |
566 int calls = backOff ? service.HttpClient.MessageHandler.NumTries : 1; | 573 int calls = backOff ? service.HttpClient.MessageHandler.NumTries : 1; |
567 Assert.That(handler.Calls, Is.EqualTo(calls)); | 574 Assert.That(handler.Calls, Is.EqualTo(calls)); |
568 } | 575 } |
569 } | 576 } |
570 | 577 |
571 /// <summary> | 578 /// <summary> |
572 /// Tests execute when an exception is thrown during a request and expon ential back-off is enabled. | 579 /// Tests execute when an exception is thrown during a request and expon ential back-off is enabled. |
573 /// </summary> | 580 /// </summary> |
574 [Test] | 581 [Test] |
575 public void Execute_ThrowException_WithBackOff() | 582 public void Execute_ThrowException_WithBackOff() |
576 { | 583 { |
577 SubtestExecute_ThrowException(true); | 584 SubtestExecute_ThrowException(true); |
578 } | 585 } |
579 | 586 |
580 /// <summary> | 587 /// <summary> |
581 /// Tests execute when an exception is thrown during a request and expon ential back-off is disabled. | 588 /// Tests execute when an exception is thrown during a request and expon ential back-off is disabled. |
582 /// </summary> | 589 /// </summary> |
583 [Test] | 590 [Test] |
584 public void Execute_ThrowException_WithoutBackOff() | 591 public void Execute_ThrowException_WithoutBackOff() |
585 { | 592 { |
586 SubtestExecute_ThrowException(false); | 593 SubtestExecute_ThrowException(false); |
587 } | 594 } |
588 | 595 |
589 /// <summary> | 596 /// <summary> |
590 /// A subtest for testing async execute when an exception is thrown duri ng sending the request, with or without· | 597 /// A subtest for testing ExecuteAsync when an exception is thrown whil e sending the request. This is tested· |
591 /// back-off handler. If back-off handler is attached to the service's m essage handler, there are going to be 3 | 598 /// with and without back-off. If back-off handler is attached to the se rvice's message handler, there should |
592 /// tries (3 is the default value of <seealso cref="ConfigurableMessageH andler.NumTries" />) before the· | 599 /// be 3 tries (the default value of <seealso cref="ConfigurableMessageH andler.NumTries"/>) before the· |
593 /// operation fails. | 600 /// operation fails. |
594 /// </summary> | 601 /// </summary> |
595 /// <param name="backOff">Indicates if back-off handler is attached to t he service.</param> | 602 /// <param name="backOff">Indicates if back-off handler is attached to t he service.</param> |
596 private void SubtestExecuteAsync_ThrowException(bool backOff) | 603 private void SubtestExecuteAsync_ThrowException(bool backOff) |
597 { | 604 { |
598 var handler = new MockMessageHandler(true); | 605 var handler = new MockMessageHandler(true); |
599 var initializer = new BaseClientService.Initializer() | 606 var initializer = new BaseClientService.Initializer() |
600 { | 607 { |
601 HttpClientFactory = new MockHttpClientFactory(handler) | 608 HttpClientFactory = new MockHttpClientFactory(handler) |
602 }; | 609 }; |
603 | 610 |
604 // configure the back-off behavior by the input | 611 // Configure the back-off behavior by the input. |
605 initializer.DefaultExponentialBackOffPolicy = backOff ? | 612 initializer.DefaultExponentialBackOffPolicy = backOff ? |
606 ExponentialBackOffPolicy.Exception : | 613 ExponentialBackOffPolicy.Exception : ExponentialBackOffPolicy.No ne; |
607 ExponentialBackOffPolicy.None; | |
608 | 614 |
609 using (var service = new MockClientService(initializer)) | 615 using (var service = new MockClientService(initializer)) |
610 { | 616 { |
611 var request = new TestClientServiceRequest(service, "GET", null) ; | 617 var request = new TestClientServiceRequest(service, "GET", null) ; |
612 var task = request.ExecuteAsync(); | 618 var task = request.ExecuteAsync(); |
613 try | 619 try |
614 { | 620 { |
615 var result = task.Result; | 621 var result = task.Result; |
616 Assert.Fail("Exception should be thrown"); | 622 Assert.Fail("Exception should be thrown"); |
617 } | 623 } |
618 catch (AggregateException ex) | 624 catch (AggregateException ex) |
619 { | 625 { |
620 Assert.That(ex.InnerException, Is.AssignableFrom(typeof(Inva lidOperationMockException))); | 626 Assert.That(ex.InnerException, Is.AssignableFrom(typeof(Inva lidOperationMockException))); |
621 } | 627 } |
622 | 628 |
623 int calls = backOff ? service.HttpClient.MessageHandler.NumTries : 1; | 629 int calls = backOff ? service.HttpClient.MessageHandler.NumTries : 1; |
624 Assert.That(handler.Calls, Is.EqualTo(calls)); | 630 Assert.That(handler.Calls, Is.EqualTo(calls)); |
625 } | 631 } |
626 } | 632 } |
627 | 633 |
628 /// <summary> | 634 /// <summary> |
629 /// Tests async execute when an exception is thrown during a request and exponential back-off is enabled. | 635 /// Tests async execute when an exception is thrown during a request and exponential back-off is enabled. |
630 /// </summary> | 636 /// </summary> |
631 [Test] | 637 [Test] |
632 public void ExecuteAsync_ThrowException_WithBackOff() | 638 public void ExecuteAsync_ThrowException_WithBackOff() |
633 { | 639 { |
634 SubtestExecuteAsync_ThrowException(true); | 640 SubtestExecuteAsync_ThrowException(true); |
635 } | 641 } |
636 | 642 |
637 /// <summary> | 643 /// <summary> |
638 /// Tests async execute when an exception is thrown during a request and exponential back-off is disabled. | 644 /// Tests async execute when an exception is thrown during a request and exponential back-off is disabled. |
639 /// </summary> | 645 /// </summary> |
640 [Test] | 646 [Test] |
641 public void ExecuteAsync_ThrowException_WithoutBackOff() | 647 public void ExecuteAsync_ThrowException_WithoutBackOff() |
642 { | 648 { |
643 SubtestExecuteAsync_ThrowException(false); | 649 SubtestExecuteAsync_ThrowException(false); |
644 } | 650 } |
645 | 651 |
646 /// <summary> Tests execute when server returned an error. </summary> | 652 /// <summary>Tests execute when server returned an error.</summary> |
647 [Test] | 653 [Test] |
648 public void Execute_Error() | 654 public void Execute_Error() |
649 { | 655 { |
650 var handler = new ErrorMessageHanlder(); | 656 var handler = new ErrorMessageHanlder(); |
651 var initializer = new BaseClientService.Initializer() | 657 var initializer = new BaseClientService.Initializer() |
652 { | 658 { |
653 HttpClientFactory = new MockHttpClientFactory(handler) | 659 HttpClientFactory = new MockHttpClientFactory(handler) |
654 }; | 660 }; |
661 | |
655 using (var service = new MockClientService(initializer)) | 662 using (var service = new MockClientService(initializer)) |
656 { | 663 { |
657 var request = new TestClientServiceRequest(service, "GET", null) ; | 664 var request = new TestClientServiceRequest(service, "GET", null) ; |
658 try | 665 try |
659 { | 666 { |
660 request.Execute(); | 667 request.Execute(); |
661 Assert.Fail(); | 668 Assert.Fail(); |
662 } | 669 } |
663 catch (Exception ex) | 670 catch (Exception ex) |
664 { | 671 { |
665 Assert.True(ex.Message.Contains(handler.ExpectedError), "Err or message is invalid"); | 672 Assert.True(ex.Message.Contains(handler.ExpectedError), "Err or message is invalid"); |
666 } | 673 } |
667 Assert.That(handler.Calls, Is.EqualTo(1)); | 674 Assert.That(handler.Calls, Is.EqualTo(1)); |
668 } | 675 } |
669 } | 676 } |
670 | 677 |
671 /// <summary> Tests execute when server returned an error. </summary> | 678 /// <summary>Tests execute when server returned an error.</summary> |
672 [Test] | 679 [Test] |
673 public void ExecuteAsync_Error() | 680 public void ExecuteAsync_Error() |
674 { | 681 { |
675 var handler = new ErrorMessageHanlder(); | 682 var handler = new ErrorMessageHanlder(); |
676 var initializer = new BaseClientService.Initializer | 683 var initializer = new BaseClientService.Initializer |
677 { | 684 { |
678 HttpClientFactory = new MockHttpClientFactory(handler) | 685 HttpClientFactory = new MockHttpClientFactory(handler) |
679 }; | 686 }; |
687 | |
680 using (var service = new MockClientService(initializer)) | 688 using (var service = new MockClientService(initializer)) |
681 { | 689 { |
682 var request = new TestClientServiceRequest(service, "GET", null) ; | 690 var request = new TestClientServiceRequest(service, "GET", null) ; |
683 AutoResetEvent resetEvent = new AutoResetEvent(false); | 691 AutoResetEvent resetEvent = new AutoResetEvent(false); |
684 var task = request.ExecuteAsync(); | 692 var task = request.ExecuteAsync(); |
685 var error = string.Empty; | 693 var error = string.Empty; |
686 task.ContinueWith(t => | 694 task.ContinueWith(t => |
687 { | 695 { |
688 // should not ENTER this code, the task should fail | 696 // should not ENTER this code, the task should fail |
689 resetEvent.Set(); | 697 resetEvent.Set(); |
690 }, TaskContinuationOptions.OnlyOnRanToCompletion); | 698 }, TaskContinuationOptions.OnlyOnRanToCompletion); |
691 task.ContinueWith(t => | 699 task.ContinueWith(t => |
692 { | 700 { |
693 // catch the error | 701 // catch the error |
694 error = t.Exception.InnerException.ToString(); | 702 error = t.Exception.InnerException.ToString(); |
695 resetEvent.Set(); | 703 resetEvent.Set(); |
696 }, TaskContinuationOptions.NotOnRanToCompletion); | 704 }, TaskContinuationOptions.NotOnRanToCompletion); |
697 resetEvent.WaitOne(); | 705 resetEvent.WaitOne(); |
698 Assert.True(error.Contains(handler.ExpectedError), "Error messag e is invalid"); | 706 Assert.True(error.Contains(handler.ExpectedError), "Error messag e is invalid"); |
699 Assert.That(handler.Calls, Is.EqualTo(1)); | 707 Assert.That(handler.Calls, Is.EqualTo(1)); |
700 } | 708 } |
701 } | 709 } |
702 | 710 |
703 /// <summary> Tests async execution of multiple request simultaneously. </summary> | 711 /// <summary>Tests async execution of multiple request simultaneously.</ summary> |
704 [Test] | 712 [Test] |
705 public void ExecuteAsync_Simultaneously() | 713 public void ExecuteAsync_Simultaneously() |
706 { | 714 { |
707 var tasks = new List<Task<MockResponse>>(); | 715 var tasks = new List<Task<MockResponse>>(); |
708 var handler = new ConcurrentCallsHandler(); | 716 var handler = new ConcurrentCallsHandler(); |
709 var initializer = new BaseClientService.Initializer() | 717 var initializer = new BaseClientService.Initializer() |
710 { | 718 { |
711 HttpClientFactory = new MockHttpClientFactory(handler), | 719 HttpClientFactory = new MockHttpClientFactory(handler), |
712 HttpClientInitializer = new ConcurrentCallsHandler.Initializ er() | 720 HttpClientInitializer = new ConcurrentCallsHandler.Initializer() |
713 }; | 721 }; |
714 | 722 |
715 using (var service = new MockClientService(initializer)) | 723 using (var service = new MockClientService(initializer)) |
716 { | 724 { |
717 int calls = 100; | 725 int calls = 100; |
718 handler.Serializer = service.Serializer; | 726 handler.Serializer = service.Serializer; |
719 | 727 |
720 CountdownEvent ce = new CountdownEvent(calls); | 728 CountdownEvent ce = new CountdownEvent(calls); |
721 foreach (var i in Enumerable.Range(1, calls)) | 729 foreach (var i in Enumerable.Range(1, calls)) |
722 { | 730 { |
723 var request = new TestClientServiceRequest(service, "GET", n ull) { CallNum = i }; | 731 var request = new TestClientServiceRequest(service, "GET", n ull) { CallNum = i }; |
(...skipping 17 matching lines...) Expand all Loading... | |
741 | 749 |
742 // half of the request should succeed in the second call, so tot al calls should be calls + calls/2 | 750 // half of the request should succeed in the second call, so tot al calls should be calls + calls/2 |
743 Assert.That(handler.Calls, Is.EqualTo(calls + calls / 2)); | 751 Assert.That(handler.Calls, Is.EqualTo(calls + calls / 2)); |
744 } | 752 } |
745 } | 753 } |
746 | 754 |
747 #endregion | 755 #endregion |
748 | 756 |
749 #region ExecuteStream (and ExecuteAsStreamAsync) | 757 #region ExecuteStream (and ExecuteAsStreamAsync) |
750 | 758 |
751 /// <summary> A subtest for testing execute as stream (async and sync). </summary> | 759 /// <summary>A subtest for testing execute as stream (async and sync).</ summary> |
752 private void SubtestExecuteAsStream(bool async) | 760 private void SubtestExecuteAsStream(bool async) |
753 { | 761 { |
754 var handler = new TestBodyMessageHnalder | 762 var handler = new TestBodyMessageHandler |
755 { | 763 { |
756 GZipEnabled = false, | 764 GZipEnabled = false, |
757 ResponseObject = new MockResponse { Id = 100, Name = "sample name" }, | 765 ResponseObject = new MockResponse { Id = 100, Name = "sample nam e" }, |
758 ExpectedRequestObject = new MockRequest { Name = "long long name" } | 766 ExpectedRequestObject = new MockRequest { Name = "long long name " } |
759 }; | 767 }; |
768 | |
760 var initializer = new BaseClientService.Initializer | 769 var initializer = new BaseClientService.Initializer |
761 { | 770 { |
762 GZipEnabled = false, | 771 GZipEnabled = false, |
763 HttpClientFactory = new MockHttpClientFactory(handler) | 772 HttpClientFactory = new MockHttpClientFactory(handler) |
764 }; | 773 }; |
774 | |
765 using (var service = new MockClientService(initializer)) | 775 using (var service = new MockClientService(initializer)) |
766 { | 776 { |
767 handler.Serializer = service.Serializer; | 777 handler.Serializer = service.Serializer; |
768 | 778 |
769 var request = new TestClientServiceRequest(service, "GET", handl er.ExpectedRequestObject); | 779 var request = new TestClientServiceRequest(service, "GET", handl er.ExpectedRequestObject); |
770 | 780 |
771 MockResponse response = null; | 781 MockResponse response = null; |
772 Stream stream = null; | 782 Stream stream = null; |
773 if (async) | 783 if (async) |
774 { | 784 { |
775 request.ExecuteAsStreamAsync().ContinueWith(t => | 785 request.ExecuteAsStreamAsync().ContinueWith(t => |
776 { | 786 { |
777 stream = t.Result; | 787 stream = t.Result; |
778 }, TaskContinuationOptions.OnlyOnRanToCompletion).Wait(); | 788 }, TaskContinuationOptions.OnlyOnRanToCompletion).Wait(); |
779 Assert.AreNotEqual(Thread.CurrentThread.ManagedThreadId, han dler.ThreadId); | 789 Assert.AreNotEqual(Thread.CurrentThread.ManagedThreadId, han dler.ThreadId); |
780 } | 790 } |
781 else | 791 else |
782 { | 792 { |
783 stream = request.ExecuteAsStream(); | 793 stream = request.ExecuteAsStream(); |
784 Assert.AreEqual(Thread.CurrentThread.ManagedThreadId, handle r.ThreadId); | 794 Assert.AreEqual(Thread.CurrentThread.ManagedThreadId, handle r.ThreadId); |
785 } | 795 } |
786 | 796 |
787 // read the object | 797 // Read the object. |
788 var str = ExtractStringFromStream(stream); | 798 var str = ExtractStringFromStream(stream); |
789 response = service.Serializer.Deserialize<MockResponse>(str); | 799 response = service.Serializer.Deserialize<MockResponse>(str); |
790 | 800 |
791 Assert.That(handler.Calls, Is.EqualTo(1)); | 801 Assert.That(handler.Calls, Is.EqualTo(1)); |
792 Assert.That(response, Is.EqualTo(handler.ResponseObject)); | 802 Assert.That(response, Is.EqualTo(handler.ResponseObject)); |
793 } | 803 } |
794 } | 804 } |
795 | 805 |
796 /// <summary> Tests execute stream. </summary> | 806 /// <summary>Tests execute stream.</summary> |
797 [Test] | 807 [Test] |
798 public void ExecuteAsStream() | 808 public void ExecuteAsStream() |
799 { | 809 { |
800 SubtestExecuteAsStream(false); | 810 SubtestExecuteAsStream(false); |
801 } | 811 } |
802 | 812 |
803 /// <summary> Tests execute stream (async). </summary> | 813 /// <summary>Tests execute stream (async).</summary> |
804 [Test] | 814 [Test] |
805 public void ExecuteAsStreamAsync() | 815 public void ExecuteAsStreamAsync() |
806 { | 816 { |
807 SubtestExecuteAsStream(true); | 817 SubtestExecuteAsStream(true); |
808 } | 818 } |
809 | 819 |
810 #endregion | 820 #endregion |
811 | 821 |
812 #region Parameters | 822 #region Parameters |
813 | 823 |
814 #region Query Parameters | 824 #region Query Parameters |
815 | 825 |
816 /// <summary> Client request which contains query parameters. </summary> | 826 /// <summary>Client request which contains query parameters.</summary> |
817 class ClientServiceRequestWithQueryParameters : TestClientServiceRequest | 827 class ClientServiceRequestWithQueryParameters : TestClientServiceRequest |
818 { | 828 { |
819 [RequestParameterAttribute("required", Google.Apis.Util.RequestParam eterType.Query)] | 829 [RequestParameterAttribute("required", Google.Apis.Util.RequestParam eterType.Query)] |
820 public string Required { get; set; } | 830 public string Required { get; set; } |
821 | 831 |
822 [RequestParameterAttribute("optionalWithValue", Google.Apis.Util.Req uestParameterType.Query)] | 832 [RequestParameterAttribute("optionalWithValue", Google.Apis.Util.Req uestParameterType.Query)] |
823 public string OptionalWithValue { get; set; } | 833 public string OptionalWithValue { get; set; } |
824 | 834 |
825 [RequestParameterAttribute("optionalWithValue2", Google.Apis.Util.Re questParameterType.Query)] | 835 [RequestParameterAttribute("optionalWithValue2", Google.Apis.Util.Re questParameterType.Query)] |
826 public string OptionalWithValue2 { get; set; } | 836 public string OptionalWithValue2 { get; set; } |
827 | 837 |
828 [RequestParameterAttribute("optionalNull", Google.Apis.Util.RequestP arameterType.Query)] | 838 [RequestParameterAttribute("optionalNull", Google.Apis.Util.RequestP arameterType.Query)] |
829 public string OptionalNull { get; set; } | 839 public string OptionalNull { get; set; } |
830 | 840 |
831 [RequestParameterAttribute("optionalEmpty", Google.Apis.Util.Request ParameterType.Query)] | 841 [RequestParameterAttribute("optionalEmpty", Google.Apis.Util.Request ParameterType.Query)] |
832 public string OptionalEmpty { get; set; } | 842 public string OptionalEmpty { get; set; } |
833 | 843 |
834 [RequestParameterAttribute("optionalNotPressent", Google.Apis.Util.R equestParameterType.Query)] | 844 [RequestParameterAttribute("optionalNotPressent", Google.Apis.Util.R equestParameterType.Query)] |
835 public string OptionalNotPressent { get; set; } | 845 public string OptionalNotPressent { get; set; } |
836 | 846 |
837 public ClientServiceRequestWithQueryParameters(IClientService servic e, string method, object body) | 847 public ClientServiceRequestWithQueryParameters(IClientService servic e, string method, object body) |
838 : base(service, method, body) | 848 : base(service, method, body) |
839 { | 849 { |
840 RequestParameters.Add("required", new Parameter | 850 RequestParameters.Add("required", new Parameter |
841 { | 851 { |
842 Name = "required", | 852 Name = "required", |
843 IsRequired = true, | 853 IsRequired = true, |
844 ParameterType = "query" | 854 ParameterType = "query" |
845 }); | 855 }); |
846 RequestParameters.Add("optionalWithValue", new Parameter | 856 RequestParameters.Add("optionalWithValue", new Parameter |
847 { | 857 { |
848 Name = "optionalWithValue", | 858 Name = "optionalWithValue", |
849 IsRequired = false, | 859 IsRequired = false, |
850 ParameterType = "query", | 860 ParameterType = "query", |
851 DefaultValue = "DoesNotDisplay" | 861 DefaultValue = "DoesNotDisplay" |
852 }); | 862 }); |
853 RequestParameters.Add("optionalWithValue2", new Parameter | 863 RequestParameters.Add("optionalWithValue2", new Parameter |
854 { | 864 { |
855 Name = "optionalWithValue", | 865 Name = "optionalWithValue", |
856 IsRequired = false, | 866 IsRequired = false, |
857 ParameterType = "query", | 867 ParameterType = "query", |
858 DefaultValue = "DoesNotDisplay" | 868 DefaultValue = "DoesNotDisplay" |
859 }); | 869 }); |
860 RequestParameters.Add("optionalWithNull", new Parameter | 870 RequestParameters.Add("optionalWithNull", new Parameter |
861 { | 871 { |
862 Name = "optionalWithNull", | 872 Name = "optionalWithNull", |
863 IsRequired = false, | 873 IsRequired = false, |
864 ParameterType = "query", | 874 ParameterType = "query", |
865 DefaultValue = "c" | 875 DefaultValue = "c" |
866 }); | 876 }); |
867 RequestParameters.Add("optionalEmpty", new Parameter | 877 RequestParameters.Add("optionalEmpty", new Parameter |
868 { | 878 { |
869 Name = "optionalEmpty", | 879 Name = "optionalEmpty", |
870 IsRequired = false, | 880 IsRequired = false, |
871 ParameterType = "query", | 881 ParameterType = "query", |
872 DefaultValue = "d" | 882 DefaultValue = "d" |
873 }); | 883 }); |
874 RequestParameters.Add("optionalNotPressent", new Parameter | 884 RequestParameters.Add("optionalNotPressent", new Parameter |
875 { | 885 { |
876 Name = "optionalNotPressent", | 886 Name = "optionalNotPressent", |
877 IsRequired = false, | 887 IsRequired = false, |
878 ParameterType = "query", | 888 ParameterType = "query", |
879 DefaultValue = "DoesNotDisplay" | 889 DefaultValue = "DoesNotDisplay" |
880 }); | 890 }); |
881 } | 891 } |
882 } | 892 } |
883 | 893 |
884 /// <summary> Tests build request with query parameters. </summary> | 894 /// <summary>Tests build request with query parameters.</summary> |
885 [Test] | 895 [Test] |
886 public void CreateRequest_QueryParameters() | 896 public void CreateRequest_QueryParameters() |
887 { | 897 { |
888 using (var service = new MockClientService("https://build_request_pa rams")) | 898 using (var service = new MockClientService("https://build_request_pa rams")) |
889 { | 899 { |
890 var request = new ClientServiceRequestWithQueryParameters(servic e, "GET", null); | 900 var request = new ClientServiceRequestWithQueryParameters(servic e, "GET", null); |
891 request.Required = "a"; | 901 request.Required = "a"; |
892 request.OptionalWithValue = "b"; | 902 request.OptionalWithValue = "b"; |
893 request.OptionalWithValue2 = "DoesNotDisplay"; | 903 request.OptionalWithValue2 = "DoesNotDisplay"; |
894 request.OptionalNull = null; | 904 request.OptionalNull = null; |
895 request.OptionalEmpty = string.Empty; | 905 request.OptionalEmpty = string.Empty; |
896 var httpRequest = request.CreateRequest(); | 906 var httpRequest = request.CreateRequest(); |
897 Assert.That(httpRequest.RequestUri, Is.EqualTo(new Uri( | 907 Assert.That(httpRequest.RequestUri, Is.EqualTo(new Uri( |
898 "https://build_request_params/restPath0?required=a&optionalW ithValue=b&optionalEmpty"))); | 908 "https://build_request_params/restPath0?required=a&optionalW ithValue=b&optionalEmpty"))); |
899 } | 909 } |
900 } | 910 } |
901 | 911 |
902 /// <summary> Tests build request with missing required query parameter. </summary> | 912 /// <summary>Tests build request with missing required query parameter.< /summary> |
903 [Test] | 913 [Test] |
904 public void CreateRequest_QueryParameterIsMissing() | 914 public void CreateRequest_QueryParameterIsMissing() |
905 { | 915 { |
906 using (var service = new MockClientService("https://build_request_pa rams")) | 916 using (var service = new MockClientService("https://build_request_pa rams")) |
907 { | 917 { |
908 var request = new ClientServiceRequestWithQueryParameters(servic e, "GET", null); | 918 var request = new ClientServiceRequestWithQueryParameters(servic e, "GET", null); |
909 // request.Required is missing! | 919 // request.Required is missing! |
910 try | 920 try |
911 { | 921 { |
912 var httpRequest = request.CreateRequest(); | 922 var httpRequest = request.CreateRequest(); |
913 Assert.Fail(); | 923 Assert.Fail(); |
914 } | 924 } |
915 catch (GoogleApiException ex) | 925 catch (GoogleApiException ex) |
916 { | 926 { |
917 Assert.True(ex.Message.Contains("Parameter \"required\" is m issing"), | 927 Assert.True(ex.Message.Contains("Parameter \"required\" is m issing"), |
918 "Exception with missing parameter should be thrown"); | 928 "Exception with missing parameter should be thrown"); |
919 } | 929 } |
920 } | 930 } |
921 } | 931 } |
922 | 932 |
923 #endregion | 933 #endregion |
924 | 934 |
925 #region Path Parameters | 935 #region Path Parameters |
926 | 936 |
927 /// <summary> Client request which contains path parameters. </summary> | 937 /// <summary>Client request which contains path parameters.</summary> |
928 class ClientServiceRequestWithPathParameters : TestClientServiceRequest | 938 class ClientServiceRequestWithPathParameters : TestClientServiceRequest |
929 { | 939 { |
930 [RequestParameter("path1", RequestParameterType.Path)] | 940 [RequestParameter("path1", RequestParameterType.Path)] |
931 public int TestParameterA { get; set; } | 941 public int TestParameterA { get; set; } |
932 | 942 |
933 [RequestParameter("path2", RequestParameterType.Path)] | 943 [RequestParameter("path2", RequestParameterType.Path)] |
934 public int TestParameterB { get; set; } | 944 public int TestParameterB { get; set; } |
935 | 945 |
936 public int TestParameterC { get; set; } | 946 public int TestParameterC { get; set; } |
937 | 947 |
(...skipping 11 matching lines...) Expand all Loading... | |
949 ParameterType = "path", | 959 ParameterType = "path", |
950 }); | 960 }); |
951 } | 961 } |
952 | 962 |
953 public override string RestPath | 963 public override string RestPath |
954 { | 964 { |
955 get { return "restPath/{path1}/something/{path2}"; } | 965 get { return "restPath/{path1}/something/{path2}"; } |
956 } | 966 } |
957 } | 967 } |
958 | 968 |
959 /// <summary> Tests build request with path parameters. </summary> | 969 /// <summary>Tests build request with path parameters.</summary> |
960 [Test] | 970 [Test] |
961 public void CreateRequest_PathParameters() | 971 public void CreateRequest_PathParameters() |
962 { | 972 { |
963 using (var service = new MockClientService("https://build_request_pa rams")) | 973 using (var service = new MockClientService("https://build_request_pa rams")) |
964 { | 974 { |
965 var request = new ClientServiceRequestWithPathParameters(service , "GET", null); | 975 var request = new ClientServiceRequestWithPathParameters(service , "GET", null); |
966 request.TestParameterA = 42; | 976 request.TestParameterA = 42; |
967 request.TestParameterB = 43; | 977 request.TestParameterB = 43; |
968 request.TestParameterC = 44; // ignore it, because it doesn't co ntain RequestParameter attribute | 978 request.TestParameterC = 44; // ignore it, because it doesn't co ntain RequestParameter attribute |
969 var httpRequest = request.CreateRequest(); | 979 var httpRequest = request.CreateRequest(); |
970 Assert.That(httpRequest.RequestUri, Is.EqualTo(new Uri( | 980 Assert.That(httpRequest.RequestUri, Is.EqualTo(new Uri( |
971 "https://build_request_params/restPath/42/something/43"))); | 981 "https://build_request_params/restPath/42/something/43"))); |
972 } | 982 } |
973 } | 983 } |
974 | 984 |
975 #endregion | 985 #endregion |
976 | 986 |
977 #region Developer Key | 987 #region Developer Key |
978 | 988 |
979 private const string SimpleDeveloperKey = "ABC123"; | 989 private const string SimpleDeveloperKey = "ABC123"; |
980 private const string ComplexDeveloperKey = "?&^% ABC123"; | 990 private const string ComplexDeveloperKey = "?&^% ABC123"; |
981 | 991 |
982 /// <summary> Tests build request with simple developer key. </summary> | 992 /// <summary>Tests build request with simple developer key.</summary> |
983 [Test] | 993 [Test] |
984 public void CreateRequest_DeveloperKey() | 994 public void CreateRequest_DeveloperKey() |
985 { | 995 { |
986 var initializer = new BaseClientService.Initializer | 996 var initializer = new BaseClientService.Initializer |
987 { | 997 { |
988 ApiKey = SimpleDeveloperKey | 998 ApiKey = SimpleDeveloperKey |
989 }; | 999 }; |
1000 | |
990 using (var service = new MockClientService(initializer, "https://bui ld_request_params")) | 1001 using (var service = new MockClientService(initializer, "https://bui ld_request_params")) |
991 { | 1002 { |
992 var request = new TestClientServiceRequest(service, "GET", null) ; | 1003 var request = new TestClientServiceRequest(service, "GET", null) ; |
993 var httpRequest = request.CreateRequest(); | 1004 var httpRequest = request.CreateRequest(); |
994 Assert.That(httpRequest.RequestUri, Is.EqualTo(new Uri( | 1005 Assert.That(httpRequest.RequestUri, Is.EqualTo(new Uri( |
995 "https://build_request_params/restPath0?key=" + SimpleDevelo perKey))); | 1006 "https://build_request_params/restPath0?key=" + SimpleDevelo perKey))); |
996 } | 1007 } |
997 } | 1008 } |
998 | 1009 |
999 /// <summary> Tests build request with complex developer key. </summary> | 1010 /// <summary>Tests build request with complex developer key.</summary> |
1000 [Test] | 1011 [Test] |
1001 public void CreateRequest_DeveloperKey_RequiresEscape() | 1012 public void CreateRequest_DeveloperKey_RequiresEscape() |
1002 { | 1013 { |
1003 var initializer = new BaseClientService.Initializer | 1014 var initializer = new BaseClientService.Initializer |
1004 { | 1015 { |
1005 ApiKey = ComplexDeveloperKey | 1016 ApiKey = ComplexDeveloperKey |
1006 }; | 1017 }; |
1018 | |
1007 using (var service = new MockClientService(initializer, "https://bui ld_request_params")) | 1019 using (var service = new MockClientService(initializer, "https://bui ld_request_params")) |
1008 { | 1020 { |
1009 var request = new TestClientServiceRequest(service, "GET", null) ; | 1021 var request = new TestClientServiceRequest(service, "GET", null) ; |
1010 var httpRequest = request.CreateRequest(); | 1022 var httpRequest = request.CreateRequest(); |
1011 Assert.That(httpRequest.RequestUri, Is.EqualTo(new Uri( | 1023 Assert.That(httpRequest.RequestUri, Is.EqualTo(new Uri( |
1012 "https://build_request_params/restPath0?key=%3F%26%5E%25%20% 20ABC123"))); | 1024 "https://build_request_params/restPath0?key=%3F%26%5E%25%20% 20ABC123"))); |
1013 } | 1025 } |
1014 } | 1026 } |
1015 | 1027 |
1016 #endregion | 1028 #endregion |
1017 | 1029 |
1018 #endregion | 1030 #endregion |
1019 | 1031 |
1020 #region Supported Methods | 1032 #region Supported Methods |
1021 | 1033 |
1022 /// <summary> Tests if invalid method throws an exception. </summary> | 1034 /// <summary>Tests if invalid method throws an exception.</summary> |
1023 [Test] | 1035 [Test] |
1024 public void CreateRequest_UnsupportedMethods() | 1036 public void CreateRequest_UnsupportedMethods() |
1025 { | 1037 { |
1026 using (var service = new MockClientService("https://build_request_pa rams")) | 1038 using (var service = new MockClientService("https://build_request_pa rams")) |
1027 { | 1039 { |
1028 var request = new TestClientServiceRequest(service, "Unsupported ", null); | 1040 var request = new TestClientServiceRequest(service, "Unsupported ", null); |
1029 Assert.Throws<ArgumentOutOfRangeException>(() => request.CreateR equest()); | 1041 Assert.Throws<ArgumentOutOfRangeException>(() => request.CreateR equest()); |
1030 } | 1042 } |
1031 } | 1043 } |
1032 | 1044 |
1033 /// <summary> Tests that valid method doesn't throw an exception. </summ ary> | 1045 /// <summary>Tests that valid method doesn't throw an exception.</summar y> |
1034 [Test] | 1046 [Test] |
1035 public void CreateRequest_SupportedMethods() | 1047 public void CreateRequest_SupportedMethods() |
1036 { | 1048 { |
1037 SubtestCreateRequest_SupportedMethod(HttpConsts.Get); | 1049 SubtestCreateRequest_SupportedMethod(HttpConsts.Get); |
1038 SubtestCreateRequest_SupportedMethod(HttpConsts.Put); | 1050 SubtestCreateRequest_SupportedMethod(HttpConsts.Put); |
1039 SubtestCreateRequest_SupportedMethod(HttpConsts.Post); | 1051 SubtestCreateRequest_SupportedMethod(HttpConsts.Post); |
1040 SubtestCreateRequest_SupportedMethod(HttpConsts.Patch); | 1052 SubtestCreateRequest_SupportedMethod(HttpConsts.Patch); |
1041 SubtestCreateRequest_SupportedMethod(HttpConsts.Delete); | 1053 SubtestCreateRequest_SupportedMethod(HttpConsts.Delete); |
1042 } | 1054 } |
1043 | 1055 |
1044 private void SubtestCreateRequest_SupportedMethod(string method) | 1056 private void SubtestCreateRequest_SupportedMethod(string method) |
1045 { | 1057 { |
1046 using (var service = new MockClientService("https://build_request_pa rams")) | 1058 using (var service = new MockClientService("https://build_request_pa rams")) |
1047 { | 1059 { |
1048 var request = new TestClientServiceRequest(service, method, null ); | 1060 var request = new TestClientServiceRequest(service, method, null ); |
1049 var httpRequest = request.CreateRequest(); | 1061 var httpRequest = request.CreateRequest(); |
1050 } | 1062 } |
1051 } | 1063 } |
1052 | 1064 |
1053 #endregion | 1065 #endregion |
1054 | 1066 |
1055 #region ETag | 1067 #region ETag |
1056 | 1068 |
1057 /// <summary> Tests the create request method with different ETags. </su mmary> | 1069 /// <summary>Tests the create request method with different ETags.</summ ary> |
1058 [Test] | 1070 [Test] |
1059 public void CreateRequest_ETag() | 1071 public void CreateRequest_ETag() |
1060 { | 1072 { |
1061 var body = new MockRequest { Name = "long long name" }; | 1073 var body = new MockRequest { Name = "long long name" }; |
1062 using (var service = new MockClientService()) | 1074 using (var service = new MockClientService()) |
1063 { | 1075 { |
1064 // no ETag (ETag = null) | 1076 // No ETag (ETag = null). |
1065 var request = new TestClientServiceRequest(service, HttpConsts.G et, body); | 1077 var request = new TestClientServiceRequest(service, HttpConsts.G et, body); |
1066 var httpRequest = request.CreateRequest(); | 1078 var httpRequest = request.CreateRequest(); |
1067 Assert.That(httpRequest.Headers.IfMatch.Count, Is.EqualTo(0)); | 1079 Assert.That(httpRequest.Headers.IfMatch.Count, Is.EqualTo(0)); |
1068 Assert.That(httpRequest.Headers.IfNoneMatch.Count, Is.EqualTo(0) ); | 1080 Assert.That(httpRequest.Headers.IfNoneMatch.Count, Is.EqualTo(0) ); |
1069 | 1081 |
1070 // ETag has a value, but ETag action is ignored | 1082 // ETag has a value, but ETag action is ignored. |
1071 body.ETag = "\"ETAG_HERE\""; | 1083 body.ETag = "\"ETAG_HERE\""; |
1072 request = new TestClientServiceRequest(service, HttpConsts.Get, body); | 1084 request = new TestClientServiceRequest(service, HttpConsts.Get, body); |
1073 request.ETagAction = ETagAction.Ignore; | 1085 request.ETagAction = ETagAction.Ignore; |
1074 httpRequest = request.CreateRequest(); | 1086 httpRequest = request.CreateRequest(); |
1075 Assert.That(httpRequest.Headers.IfMatch.Count, Is.EqualTo(0)); | 1087 Assert.That(httpRequest.Headers.IfMatch.Count, Is.EqualTo(0)); |
1076 Assert.That(httpRequest.Headers.IfNoneMatch.Count, Is.EqualTo(0) ); | 1088 Assert.That(httpRequest.Headers.IfNoneMatch.Count, Is.EqualTo(0) ); |
1077 | 1089 |
1078 // ETag has a value, so use default action (Get -> If-None-Match ) | 1090 // ETag has a value, so use default action (Get -> If-None-Match ). |
1079 request = new TestClientServiceRequest(service, HttpConsts.Get, body); | 1091 request = new TestClientServiceRequest(service, HttpConsts.Get, body); |
1080 httpRequest = request.CreateRequest(); | 1092 httpRequest = request.CreateRequest(); |
1081 Assert.That(httpRequest.Headers.IfMatch.Count, Is.EqualTo(0)); | 1093 Assert.That(httpRequest.Headers.IfMatch.Count, Is.EqualTo(0)); |
1082 Assert.That(httpRequest.Headers.IfNoneMatch.Count, Is.EqualTo(1) ); | 1094 Assert.That(httpRequest.Headers.IfNoneMatch.Count, Is.EqualTo(1) ); |
1083 Assert.That(httpRequest.Headers.IfNoneMatch.First(), Is.EqualTo( new EntityTagHeaderValue(body.ETag))); | 1095 Assert.That(httpRequest.Headers.IfNoneMatch.First(), Is.EqualTo( new EntityTagHeaderValue(body.ETag))); |
1084 | 1096 |
1085 // ETag has a value, so use default action (Post -> If-Match) | 1097 // ETag has a value, so use default action (Post -> If-Match). |
1086 request = new TestClientServiceRequest(service, HttpConsts.Post, body); | 1098 request = new TestClientServiceRequest(service, HttpConsts.Post, body); |
1087 httpRequest = request.CreateRequest(); | 1099 httpRequest = request.CreateRequest(); |
1088 Assert.That(httpRequest.Headers.IfNoneMatch.Count, Is.EqualTo(0) ); | 1100 Assert.That(httpRequest.Headers.IfNoneMatch.Count, Is.EqualTo(0) ); |
1089 Assert.That(httpRequest.Headers.IfMatch.Count, Is.EqualTo(1)); | 1101 Assert.That(httpRequest.Headers.IfMatch.Count, Is.EqualTo(1)); |
1090 Assert.That(httpRequest.Headers.IfMatch.First(), Is.EqualTo(new EntityTagHeaderValue(body.ETag))); | 1102 Assert.That(httpRequest.Headers.IfMatch.First(), Is.EqualTo(new EntityTagHeaderValue(body.ETag))); |
1091 | 1103 |
1092 // ETag has a value, default is override, use the specified ETag action | 1104 // ETag has a value, default is override, use the specified ETag action. |
1093 request = new TestClientServiceRequest(service, HttpConsts.Post, body); | 1105 request = new TestClientServiceRequest(service, HttpConsts.Post, body); |
1094 request.ETagAction = ETagAction.IfNoneMatch; | 1106 request.ETagAction = ETagAction.IfNoneMatch; |
1095 httpRequest = request.CreateRequest(); | 1107 httpRequest = request.CreateRequest(); |
1096 Assert.That(httpRequest.Headers.IfMatch.Count, Is.EqualTo(0)); | 1108 Assert.That(httpRequest.Headers.IfMatch.Count, Is.EqualTo(0)); |
1097 Assert.That(httpRequest.Headers.IfNoneMatch.Count, Is.EqualTo(1) ); | 1109 Assert.That(httpRequest.Headers.IfNoneMatch.Count, Is.EqualTo(1) ); |
1098 Assert.That(httpRequest.Headers.IfNoneMatch.First(), Is.EqualTo( new EntityTagHeaderValue(body.ETag))); | 1110 Assert.That(httpRequest.Headers.IfNoneMatch.First(), Is.EqualTo( new EntityTagHeaderValue(body.ETag))); |
1099 | 1111 |
1100 // ETag has a value, default is override, use the specified ETag action | 1112 // ETag has a value, default is override, use the specified ETag action. |
1101 request = new TestClientServiceRequest(service, HttpConsts.Get, body); | 1113 request = new TestClientServiceRequest(service, HttpConsts.Get, body); |
1102 request.ETagAction = ETagAction.IfMatch; | 1114 request.ETagAction = ETagAction.IfMatch; |
1103 httpRequest = request.CreateRequest(); | 1115 httpRequest = request.CreateRequest(); |
1104 Assert.That(httpRequest.Headers.IfNoneMatch.Count, Is.EqualTo(0) ); | 1116 Assert.That(httpRequest.Headers.IfNoneMatch.Count, Is.EqualTo(0) ); |
1105 Assert.That(httpRequest.Headers.IfMatch.Count, Is.EqualTo(1)); | 1117 Assert.That(httpRequest.Headers.IfMatch.Count, Is.EqualTo(1)); |
1106 Assert.That(httpRequest.Headers.IfMatch.First(), Is.EqualTo(new EntityTagHeaderValue(body.ETag))); | 1118 Assert.That(httpRequest.Headers.IfMatch.First(), Is.EqualTo(new EntityTagHeaderValue(body.ETag))); |
1107 } | 1119 } |
1108 } | 1120 } |
1109 | 1121 |
1110 /// <summary> Tests that get default ETag action works as expected. </su mmary> | 1122 /// <summary>Tests that get default ETag action works as expected.</summ ary> |
1111 [Test] | 1123 [Test] |
1112 public void GetDefaultETagActionTest() | 1124 public void GetDefaultETagActionTest() |
1113 { | 1125 { |
1114 Assert.AreEqual(ETagAction.IfNoneMatch, ClientServiceRequest<object> .GetDefaultETagAction(HttpConsts.Get)); | 1126 Assert.AreEqual(ETagAction.IfNoneMatch, ClientServiceRequest<object> .GetDefaultETagAction(HttpConsts.Get)); |
1115 Assert.AreEqual(ETagAction.IfMatch, ClientServiceRequest<object>.Get DefaultETagAction(HttpConsts.Post)); | 1127 Assert.AreEqual(ETagAction.IfMatch, ClientServiceRequest<object>.Get DefaultETagAction(HttpConsts.Post)); |
1116 Assert.AreEqual(ETagAction.IfMatch, ClientServiceRequest<object>.Get DefaultETagAction(HttpConsts.Patch)); | 1128 Assert.AreEqual(ETagAction.IfMatch, ClientServiceRequest<object>.Get DefaultETagAction(HttpConsts.Patch)); |
1117 Assert.AreEqual(ETagAction.IfMatch, ClientServiceRequest<object>.Get DefaultETagAction(HttpConsts.Put)); | 1129 Assert.AreEqual(ETagAction.IfMatch, ClientServiceRequest<object>.Get DefaultETagAction(HttpConsts.Put)); |
1118 Assert.AreEqual(ETagAction.IfMatch, ClientServiceRequest<object>.Get DefaultETagAction(HttpConsts.Delete)); | 1130 Assert.AreEqual(ETagAction.IfMatch, ClientServiceRequest<object>.Get DefaultETagAction(HttpConsts.Delete)); |
1119 Assert.AreEqual(ETagAction.Ignore, ClientServiceRequest<object>.GetD efaultETagAction("INVALID")); | 1131 Assert.AreEqual(ETagAction.Ignore, ClientServiceRequest<object>.GetD efaultETagAction("INVALID")); |
1120 } | 1132 } |
1121 | 1133 |
1122 #endregion | 1134 #endregion |
1123 } | 1135 } |
1124 } | 1136 } |
LEFT | RIGHT |