Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(18)

Side by Side Diff: Src/GoogleApis.Tests/Apis/Requests/ClientServiceRequestTest.cs

Issue 13412046: Reimplement OAuth2 library - Step 1 (Closed) Base URL: https://google-api-dotnet-client.googlecode.com/hg/
Patch Set: minor Created 10 years, 10 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
View unified diff | Download patch
OLDNEW
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
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
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
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 an Http response message o r throw an exception. </summary> 254 /// <summary>A message handler which returns a HTTP response message or throw an exception.</summary>
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 an Http request in 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 bool HandleResponse(HandleUnsuccessfulResponseArgs args) 341 public Task<bool> HandleResponseAsync(HandleUnsuccessfulResponse Args args)
342 { 342 {
343 return args.Response.StatusCode == System.Net.HttpStatusCode .ServiceUnavailable; 343 TaskCompletionSource<bool> tcs = new TaskCompletionSource<bo ol>();
344 tcs.SetResult(args.Response.StatusCode.Equals(HttpStatusCode .ServiceUnavailable));
345 return tcs.Task;
344 } 346 }
345 } 347 }
346 348
347 /// <summary> 349 /// <summary>
348 /// 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.
349 /// </summary> 351 /// </summary>
350 internal class Initializer : IConfigurableHttpClientInitializer 352 internal class Initializer : IConfigurableHttpClientInitializer
351 { 353 {
352 public void Initialize(ConfigurableHttpClient httpClient) 354 public void Initialize(ConfigurableHttpClient httpClient)
353 { 355 {
354 httpClient.MessageHandler.UnsuccessfulResponseHandlers.Add( 356 httpClient.MessageHandler.UnsuccessfulResponseHandlers.Add(
355 new ServiceUnavailableUnsuccessfulResponseHandler()); 357 new ServiceUnavailableUnsuccessfulResponseHandler());
356 } 358 }
357 } 359 }
358 } 360 }
359 361
360 #region Execute (and ExecuteAsync) 362 #region Execute (and ExecuteAsync)
361 363
362 /// <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>
363 [Test] 365 [Test]
364 public void ExecuteAsync_Cancel() 366 public void ExecuteAsync_Cancel()
365 { 367 {
366 SubtestExecuteAsync_Cancel(1); 368 SubtestExecuteAsync_Cancel(1);
367 SubtestExecuteAsync_Cancel(5); 369 SubtestExecuteAsync_Cancel(5);
368 SubtestExecuteAsync_Cancel(10); 370 SubtestExecuteAsync_Cancel(10);
369 SubtestExecuteAsync_Cancel(11); 371 SubtestExecuteAsync_Cancel(11);
370 } 372 }
371 373
372 /// <summary> 374 /// <summary>
(...skipping 19 matching lines...) Expand all
392 request = new TestClientServiceRequest(service, "POST", new Mock Request()); 394 request = new TestClientServiceRequest(service, "POST", new Mock Request());
393 try 395 try
394 { 396 {
395 request.ExecuteAsync(handler.CancellationTokenSource.Token). Wait(); 397 request.ExecuteAsync(handler.CancellationTokenSource.Token). Wait();
396 Assert.Fail(); 398 Assert.Fail();
397 } 399 }
398 catch (AggregateException ex) 400 catch (AggregateException ex)
399 { 401 {
400 if (ex.InnerException is TaskCanceledException) 402 if (ex.InnerException is TaskCanceledException)
401 { 403 {
402 // 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
403 // number of retries 405 // number of retries.
404 Assert.False(cancelRequestNum > service.HttpClient.Messa geHandler.NumTries); 406 Assert.False(cancelRequestNum > service.HttpClient.Messa geHandler.NumTries);
405 } 407 }
406 else 408 else
407 { 409 {
408 // 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.
409 Assert.True(cancelRequestNum > service.HttpClient.Messag eHandler.NumTries); 412 Assert.True(cancelRequestNum > service.HttpClient.Messag eHandler.NumTries);
410 } 413 }
411 } 414 }
412 415
413 var expectedCalls = Math.Min(service.HttpClient.MessageHandler.N umTries, cancelRequestNum); 416 var expectedCalls = Math.Min(service.HttpClient.MessageHandler.N umTries, cancelRequestNum);
414 Assert.That(handler.Calls, Is.EqualTo(expectedCalls)); 417 Assert.That(handler.Calls, Is.EqualTo(expectedCalls));
415 } 418 }
416 } 419 }
417 420
421 /// <summary>Tests the execute method in case the service was disposed.< /summary>
418 [Test] 422 [Test]
419 public void Execute_DisposeService() 423 public void Execute_DisposeService()
420 { 424 {
421 var handler = new MockMessageHandler(); 425 var handler = new MockMessageHandler();
422 var initializer = new BaseClientService.Initializer() 426 var initializer = new BaseClientService.Initializer()
423 { 427 {
424 HttpClientFactory = new MockHttpClientFactory(handler) 428 HttpClientFactory = new MockHttpClientFactory(handler)
425 }; 429 };
426 430
427 TestClientServiceRequest request; 431 TestClientServiceRequest request;
428 using (var service = new MockClientService(initializer)) 432 using (var service = new MockClientService(initializer))
429 { 433 {
430 request = new TestClientServiceRequest(service, "POST", new Mock Request()); 434 request = new TestClientServiceRequest(service, "POST", new Mock Request());
431 } 435 }
432 436
433 // 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·
434 // exception should be thrown before we try to send the request 438 // exception should be thrown before we try to send the request
435 Assert.Throws<ObjectDisposedException>(() => request.Execute()); 439 Assert.Throws<ObjectDisposedException>(() => request.Execute());
436 } 440 }
437 441
438 /// <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>
439 private void SubtestExecute_GZip(bool gzip, bool async) 445 private void SubtestExecute_GZip(bool gzip, bool async)
440 { 446 {
441 var handler = new TestBodyMessageHnalder() 447 var handler = new TestBodyMessageHandler()
442 { 448 {
443 GZipEnabled = gzip, 449 GZipEnabled = gzip,
444 ResponseObject = new MockResponse { Id = 100, Name = "sample name" }, 450 ResponseObject = new MockResponse { Id = 100, Name = "sample nam e" },
445 ExpectedRequestObject = new MockRequest { Name = "long long name" } 451 ExpectedRequestObject = new MockRequest { Name = "long long name " }
446 }; 452 };
453
447 var initializer = new BaseClientService.Initializer() 454 var initializer = new BaseClientService.Initializer()
448 { 455 {
449 GZipEnabled = gzip, 456 GZipEnabled = gzip,
450 HttpClientFactory = new MockHttpClientFactory(handler) 457 HttpClientFactory = new MockHttpClientFactory(handler)
451 }; 458 };
459
452 using (var service = new MockClientService(initializer)) 460 using (var service = new MockClientService(initializer))
453 { 461 {
454 handler.Serializer = service.Serializer; 462 handler.Serializer = service.Serializer;
455 463
456 var request = new TestClientServiceRequest(service, "POST", hand ler.ExpectedRequestObject); 464 var request = new TestClientServiceRequest(service, "POST", hand ler.ExpectedRequestObject);
457 MockResponse response = null; 465 MockResponse response = null;
458 if (async) 466 if (async)
459 { 467 {
460 var task = request.ExecuteAsync(); 468 var task = request.ExecuteAsync();
461 response = task.Result; 469 response = task.Result;
462 Assert.AreNotEqual(Thread.CurrentThread.ManagedThreadId, han dler.ThreadId); 470 Assert.AreNotEqual(Thread.CurrentThread.ManagedThreadId, han dler.ThreadId);
463 } 471 }
464 else 472 else
465 { 473 {
466 response = request.Execute(); 474 response = request.Execute();
467 Assert.AreEqual(Thread.CurrentThread.ManagedThreadId, handle r.ThreadId); 475 Assert.AreEqual(Thread.CurrentThread.ManagedThreadId, handle r.ThreadId);
468 } 476 }
469 477
470 // 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,
471 // 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·
472 // System.Net.DecompressionMethods.GZip. 480 // System.Net.DecompressionMethods.GZip.
473 481
474 Assert.That(handler.Calls, Is.EqualTo(1)); 482 Assert.That(handler.Calls, Is.EqualTo(1));
475 // 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·
476 // the response 484 // the response.
477 handler.ResponseObject.ETag = handler.ResponseETag; 485 handler.ResponseObject.ETag = handler.ResponseETag;
478 Assert.That(response, Is.EqualTo(handler.ResponseObject)); 486 Assert.That(response, Is.EqualTo(handler.ResponseObject));
479 } 487 }
480 } 488 }
481 489
482 /// <summary> Tests execute when GZip is enabled. </summary> 490 /// <summary>Tests execute when GZip is enabled.</summary>
483 [Test] 491 [Test]
484 public void Execute_GZipEnabled() 492 public void Execute_GZipEnabled()
485 { 493 {
486 SubtestExecute_GZip(true, false); 494 SubtestExecute_GZip(true, false);
487 } 495 }
488 496
489 /// <summary> Tests execute when GZip is disabled. </summary> 497 /// <summary>Tests execute when GZip is disabled.</summary>
490 [Test] 498 [Test]
491 public void Execute_GZipDisabled() 499 public void Execute_GZipDisabled()
492 { 500 {
493 SubtestExecute_GZip(false, false); 501 SubtestExecute_GZip(false, false);
494 } 502 }
495 503
496 /// <summary> Tests async execute when GZip is enabled. </summary> 504 /// <summary>Tests async execute when GZip is enabled.</summary>
497 [Test] 505 [Test]
498 public void ExecuteAsync_GZipEnabled() 506 public void ExecuteAsync_GZipEnabled()
499 { 507 {
500 SubtestExecute_GZip(true, true); 508 SubtestExecute_GZip(true, true);
501 } 509 }
502 510
503 /// <summary> Tests async execute when GZip is disabled. </summary> 511 /// <summary>Tests async execute when GZip is disabled.</summary>
504 [Test] 512 [Test]
505 public void ExecuteAsync_GZipDisabled() 513 public void ExecuteAsync_GZipDisabled()
506 { 514 {
507 SubtestExecute_GZip(false, true); 515 SubtestExecute_GZip(false, true);
508 } 516 }
509 517
510 /// <summary> Tests execute with unicode characters. </summary> 518 /// <summary>Tests execute with unicode characters.</summary>
511 [Test] 519 [Test]
512 public void Execute_UnicodeCharacters() 520 public void Execute_UnicodeCharacters()
513 { 521 {
514 var handler = new TestBodyMessageHnalder() 522 var handler = new TestBodyMessageHandler()
515 { 523 {
516 GZipEnabled = false, 524 GZipEnabled = false,
517 ResponseObject = new MockResponse { Id = 100, Name = @"مرحبا العالم" }, 525 ResponseObject = new MockResponse { Id = 100, Name = @"مرحبا الع الم" },
518 ExpectedRequestObject = new MockRequest { Name = @"مرحبا الع الم! 您好,世界!" } 526 ExpectedRequestObject = new MockRequest { Name = @"مرحبا العالم! 您好,世界!" }
519 }; 527 };
528
520 var initializer = new BaseClientService.Initializer() 529 var initializer = new BaseClientService.Initializer()
521 { 530 {
522 GZipEnabled = false, 531 GZipEnabled = false,
523 HttpClientFactory = new MockHttpClientFactory(handler) 532 HttpClientFactory = new MockHttpClientFactory(handler)
524 }; 533 };
534
525 using (var service = new MockClientService(initializer)) 535 using (var service = new MockClientService(initializer))
526 { 536 {
527 handler.Serializer = service.Serializer; 537 handler.Serializer = service.Serializer;
528 538
529 var request = new TestClientServiceRequest(service, "GET", handl er.ExpectedRequestObject); 539 var request = new TestClientServiceRequest(service, "GET", handl er.ExpectedRequestObject);
530 var response = request.Execute(); 540 var response = request.Execute();
531 Assert.That(handler.Calls, Is.EqualTo(1)); 541 Assert.That(handler.Calls, Is.EqualTo(1));
532 // 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·
533 // the response 543 // the response.
534 handler.ResponseObject.ETag = handler.ResponseETag; 544 handler.ResponseObject.ETag = handler.ResponseETag;
535 Assert.That(response, Is.EqualTo(handler.ResponseObject)); 545 Assert.That(response, Is.EqualTo(handler.ResponseObject));
536 } 546 }
537 } 547 }
538 548
539 /// <summary> 549 /// <summary>
540 /// 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
541 /// 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
542 /// (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·
543 /// fails. 553 /// fails.
544 /// </summary> 554 /// </summary>
545 /// <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>
546 private void SubtestExecute_ThrowException(bool backOff) 556 private void SubtestExecute_ThrowException(bool backOff)
547 { 557 {
548 var handler = new MockMessageHandler(true); 558 var handler = new MockMessageHandler(true);
549 var initializer = new BaseClientService.Initializer() 559 var initializer = new BaseClientService.Initializer()
550 { 560 {
551 HttpClientFactory = new MockHttpClientFactory(handler) 561 HttpClientFactory = new MockHttpClientFactory(handler)
552 }; 562 };
553 563
554 // sets the default exponential back-off policy by the input 564 // Set the default exponential back-off policy by the input.
555 initializer.DefaultExponentialBackOffPolicy = backOff ? 565 initializer.DefaultExponentialBackOffPolicy = backOff ?
556 BaseClientService.ExponentialBackOffPolicy.Exception : 566 ExponentialBackOffPolicy.Exception : ExponentialBackOffPolicy.No ne;
557 BaseClientService.ExponentialBackOffPolicy.None;
558 567
559 using (var service = new MockClientService(initializer)) 568 using (var service = new MockClientService(initializer))
560 { 569 {
561 var request = new TestClientServiceRequest(service, "GET", null) ; 570 var request = new TestClientServiceRequest(service, "GET", null) ;
562 Assert.Throws<InvalidOperationMockException>(() => request.Execu te()); 571 Assert.Throws<InvalidOperationMockException>(() => request.Execu te());
563 572
564 int calls = backOff ? service.HttpClient.MessageHandler.NumTries : 1; 573 int calls = backOff ? service.HttpClient.MessageHandler.NumTries : 1;
565 Assert.That(handler.Calls, Is.EqualTo(calls)); 574 Assert.That(handler.Calls, Is.EqualTo(calls));
566 } 575 }
567 } 576 }
568 577
569 /// <summary> 578 /// <summary>
570 /// 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.
571 /// </summary> 580 /// </summary>
572 [Test] 581 [Test]
573 public void Execute_ThrowException_WithBackOff() 582 public void Execute_ThrowException_WithBackOff()
574 { 583 {
575 SubtestExecute_ThrowException(true); 584 SubtestExecute_ThrowException(true);
576 } 585 }
577 586
578 /// <summary> 587 /// <summary>
579 /// 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.
580 /// </summary> 589 /// </summary>
581 [Test] 590 [Test]
582 public void Execute_ThrowException_WithoutBackOff() 591 public void Execute_ThrowException_WithoutBackOff()
583 { 592 {
584 SubtestExecute_ThrowException(false); 593 SubtestExecute_ThrowException(false);
585 } 863 }
586 595
587 /// <summary> 596 /// <summary>
588 /// 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·
589 /// 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
590 /// 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·
591 /// operation fails. 600 /// operation fails.
592 /// </summary> 601 /// </summary>
593 /// <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>
863 private void SubtestExecuteAsync_ThrowException(bool backOff) 603 private void SubtestExecuteAsync_ThrowException(bool backOff)
595 { 604 {
596 var handler = new MockMessageHandler(true); 605 var handler = new MockMessageHandler(true);
597 var initializer = new BaseClientService.Initializer() 606 var initializer = new BaseClientService.Initializer()
598 { 607 {
599 HttpClientFactory = new MockHttpClientFactory(handler) 608 HttpClientFactory = new MockHttpClientFactory(handler)
600 }; 609 };
601 610
602 // configure the back-off behavior by the input 611 // Configure the back-off behavior by the input.
603 initializer.DefaultExponentialBackOffPolicy = backOff ? 612 initializer.DefaultExponentialBackOffPolicy = backOff ?
604 BaseClientService.ExponentialBackOffPolicy.Exception : 613 ExponentialBackOffPolicy.Exception : ExponentialBackOffPolicy.No ne;
605 BaseClientService.ExponentialBackOffPolicy.None;
606 614
607 using (var service = new MockClientService(initializer)) 615 using (var service = new MockClientService(initializer))
608 { 616 {
609 var request = new TestClientServiceRequest(service, "GET", null) ; 617 var request = new TestClientServiceRequest(service, "GET", null) ;
610 var task = request.ExecuteAsync(); 618 var task = request.ExecuteAsync();
611 try 619 try
612 { 620 {
613 var result = task.Result; 621 var result = task.Result;
614 Assert.Fail("Exception should be thrown"); 622 Assert.Fail("Exception should be thrown");
615 } 623 }
616 catch (AggregateException ex) 624 catch (AggregateException ex)
617 { 625 {
618 Assert.That(ex.InnerException, Is.AssignableFrom(typeof(Inva lidOperationMockException))); 626 Assert.That(ex.InnerException, Is.AssignableFrom(typeof(Inva lidOperationMockException)));
619 } 627 }
620 628
621 int calls = backOff ? service.HttpClient.MessageHandler.NumTries : 1; 629 int calls = backOff ? service.HttpClient.MessageHandler.NumTries : 1;
622 Assert.That(handler.Calls, Is.EqualTo(calls)); 630 Assert.That(handler.Calls, Is.EqualTo(calls));
623 } 631 }
624 } 632 }
625 633
626 /// <summary> 634 /// <summary>
627 /// 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.
628 /// </summary> 636 /// </summary>
629 [Test] 637 [Test]
630 public void ExecuteAsync_ThrowException_WithBackOff() 638 public void ExecuteAsync_ThrowException_WithBackOff()
631 { 639 {
632 SubtestExecuteAsync_ThrowException(true); 640 SubtestExecuteAsync_ThrowException(true);
633 } 641 }
634 642
635 /// <summary> 643 /// <summary>
636 /// 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.
637 /// </summary> 645 /// </summary>
638 [Test] 646 [Test]
639 public void ExecuteAsync_ThrowException_WithoutBackOff() 647 public void ExecuteAsync_ThrowException_WithoutBackOff()
640 { 648 {
641 SubtestExecuteAsync_ThrowException(false); 649 SubtestExecuteAsync_ThrowException(false);
642 } 650 }
643 651
644 /// <summary> Tests execute when server returned an error. </summary> 652 /// <summary>Tests execute when server returned an error.</summary>
645 [Test] 653 [Test]
646 public void Execute_Error() 654 public void Execute_Error()
647 { 655 {
648 var handler = new ErrorMessageHanlder(); 656 var handler = new ErrorMessageHanlder();
649 var initializer = new BaseClientService.Initializer() 657 var initializer = new BaseClientService.Initializer()
650 { 658 {
651 HttpClientFactory = new MockHttpClientFactory(handler) 659 HttpClientFactory = new MockHttpClientFactory(handler)
652 }; 660 };
661
653 using (var service = new MockClientService(initializer)) 662 using (var service = new MockClientService(initializer))
654 { 663 {
655 var request = new TestClientServiceRequest(service, "GET", null) ; 664 var request = new TestClientServiceRequest(service, "GET", null) ;
656 try 665 try
657 { 666 {
658 request.Execute(); 667 request.Execute();
659 Assert.Fail(); 668 Assert.Fail();
660 } 669 }
661 catch (Exception ex) 670 catch (Exception ex)
662 { 671 {
663 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");
664 } 673 }
665 Assert.That(handler.Calls, Is.EqualTo(1)); 674 Assert.That(handler.Calls, Is.EqualTo(1));
666 } 675 }
667 } 676 }
668 677
669 /// <summary> Tests execute when server returned an error. </summary> 678 /// <summary>Tests execute when server returned an error.</summary>
670 [Test] 679 [Test]
671 public void ExecuteAsync_Error() 680 public void ExecuteAsync_Error()
672 { 681 {
673 var handler = new ErrorMessageHanlder(); 682 var handler = new ErrorMessageHanlder();
674 var initializer = new BaseClientService.Initializer 683 var initializer = new BaseClientService.Initializer
675 { 684 {
676 HttpClientFactory = new MockHttpClientFactory(handler) 685 HttpClientFactory = new MockHttpClientFactory(handler)
677 }; 686 };
687
678 using (var service = new MockClientService(initializer)) 688 using (var service = new MockClientService(initializer))
679 { 689 {
680 var request = new TestClientServiceRequest(service, "GET", null) ; 690 var request = new TestClientServiceRequest(service, "GET", null) ;
681 AutoResetEvent resetEvent = new AutoResetEvent(false); 691 AutoResetEvent resetEvent = new AutoResetEvent(false);
682 var task = request.ExecuteAsync(); 692 var task = request.ExecuteAsync();
683 var error = string.Empty; 693 var error = string.Empty;
684 task.ContinueWith(t => 694 task.ContinueWith(t =>
685 { 695 {
686 // should not ENTER this code, the task should fail 696 // should not ENTER this code, the task should fail
687 resetEvent.Set(); 697 resetEvent.Set();
688 }, TaskContinuationOptions.OnlyOnRanToCompletion); 698 }, TaskContinuationOptions.OnlyOnRanToCompletion);
689 task.ContinueWith(t => 699 task.ContinueWith(t =>
690 { 700 {
691 // catch the error 701 // catch the error
692 error = t.Exception.InnerException.ToString(); 702 error = t.Exception.InnerException.ToString();
693 resetEvent.Set(); 703 resetEvent.Set();
694 }, TaskContinuationOptions.NotOnRanToCompletion); 704 }, TaskContinuationOptions.NotOnRanToCompletion);
695 resetEvent.WaitOne(); 705 resetEvent.WaitOne();
696 Assert.True(error.Contains(handler.ExpectedError), "Error messag e is invalid"); 706 Assert.True(error.Contains(handler.ExpectedError), "Error messag e is invalid");
697 Assert.That(handler.Calls, Is.EqualTo(1)); 707 Assert.That(handler.Calls, Is.EqualTo(1));
698 } 708 }
699 } 709 }
700 710
701 /// <summary> Tests async execution of multiple request simultaneously. </summary> 711 /// <summary>Tests async execution of multiple request simultaneously.</ summary>
702 [Test] 712 [Test]
703 public void ExecuteAsync_Simultaneously() 713 public void ExecuteAsync_Simultaneously()
704 { 714 {
705 var tasks = new List<Task<MockResponse>>(); 715 var tasks = new List<Task<MockResponse>>();
706 var handler = new ConcurrentCallsHandler(); 716 var handler = new ConcurrentCallsHandler();
707 var initializer = new BaseClientService.Initializer() 717 var initializer = new BaseClientService.Initializer()
708 { 718 {
709 HttpClientFactory = new MockHttpClientFactory(handler), 719 HttpClientFactory = new MockHttpClientFactory(handler),
710 HttpClientInitializer = new ConcurrentCallsHandler.Initializ er() 720 HttpClientInitializer = new ConcurrentCallsHandler.Initializer()
711 }; 721 };
712 722
713 using (var service = new MockClientService(initializer)) 723 using (var service = new MockClientService(initializer))
714 { 724 {
715 int calls = 100; 725 int calls = 100;
716 handler.Serializer = service.Serializer; 726 handler.Serializer = service.Serializer;
717 727
718 CountdownEvent ce = new CountdownEvent(calls); 728 CountdownEvent ce = new CountdownEvent(calls);
719 foreach (var i in Enumerable.Range(1, calls)) 729 foreach (var i in Enumerable.Range(1, calls))
720 { 730 {
721 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
739 749
740 // 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
741 Assert.That(handler.Calls, Is.EqualTo(calls calls / 2)); 751 Assert.That(handler.Calls, Is.EqualTo(calls calls / 2));
742 } 752 }
743 } 753 }
744 754
745 #endregion 755 #endregion
746 756
747 #region ExecuteStream (and ExecuteAsStreamAsync) 757 #region ExecuteStream (and ExecuteAsStreamAsync)
748 758
749 /// <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>
750 private void SubtestExecuteAsStream(bool async) 760 private void SubtestExecuteAsStream(bool async)
751 { 761 {
752 var handler = new TestBodyMessageHnalder 762 var handler = new TestBodyMessageHandler
753 { 763 {
754 GZipEnabled = false, 764 GZipEnabled = false,
755 ResponseObject = new MockResponse { Id = 100, Name = "sample name" }, 765 ResponseObject = new MockResponse { Id = 100, Name = "sample nam e" },
756 ExpectedRequestObject = new MockRequest { Name = "long long name" } 766 ExpectedRequestObject = new MockRequest { Name = "long long name " }
757 }; 767 };
768
758 var initializer = new BaseClientService.Initializer 769 var initializer = new BaseClientService.Initializer
759 { 770 {
760 GZipEnabled = false, 771 GZipEnabled = false,
761 HttpClientFactory = new MockHttpClientFactory(handler) 772 HttpClientFactory = new MockHttpClientFactory(handler)
762 }; 773 };
774
763 using (var service = new MockClientService(initializer)) 775 using (var service = new MockClientService(initializer))
764 { 776 {
765 handler.Serializer = service.Serializer; 777 handler.Serializer = service.Serializer;
766 778
767 var request = new TestClientServiceRequest(service, "GET", handl er.ExpectedRequestObject); 779 var request = new TestClientServiceRequest(service, "GET", handl er.ExpectedRequestObject);
768 780
769 MockResponse response = null; 781 MockResponse response = null;
770 Stream stream = null; 782 Stream stream = null;
771 if (async) 783 if (async)
772 { 784 {
773 request.ExecuteAsStreamAsync().ContinueWith(t => 785 request.ExecuteAsStreamAsync().ContinueWith(t =>
774 { 786 {
775 stream = t.Result; 787 stream = t.Result;
776 }, TaskContinuationOptions.OnlyOnRanToCompletion).Wait(); 788 }, TaskContinuationOptions.OnlyOnRanToCompletion).Wait();
777 Assert.AreNotEqual(Thread.CurrentThread.ManagedThreadId, han dler.ThreadId); 789 Assert.AreNotEqual(Thread.CurrentThread.ManagedThreadId, han dler.ThreadId);
778 } 790 }
779 else 791 else
780 { 792 {
781 stream = request.ExecuteAsStream(); 793 stream = request.ExecuteAsStream();
782 Assert.AreEqual(Thread.CurrentThread.ManagedThreadId, handle r.ThreadId); 794 Assert.AreEqual(Thread.CurrentThread.ManagedThreadId, handle r.ThreadId);
783 } 795 }
784 796
785 // read the object 797 // Read the object.
786 var str = ExtractStringFromStream(stream); 798 var str = ExtractStringFromStream(stream);
787 response = service.Serializer.Deserialize<MockResponse>(str); 799 response = service.Serializer.Deserialize<MockResponse>(str);
788 800
789 Assert.That(handler.Calls, Is.EqualTo(1)); 801 Assert.That(handler.Calls, Is.EqualTo(1));
790 Assert.That(response, Is.EqualTo(handler.ResponseObject)); 802 Assert.That(response, Is.EqualTo(handler.ResponseObject));
791 } 803 }
792 } 804 }
793 805
794 /// <summary> Tests execute stream. </summary> 806 /// <summary>Tests execute stream.</summary>
795 [Test] 807 [Test]
796 public void ExecuteAsStream() 808 public void ExecuteAsStream()
797 { 809 {
798 SubtestExecuteAsStream(false); 810 SubtestExecuteAsStream(false);
799 } 811 }
800 812
801 /// <summary> Tests execute stream (async). </summary> 813 /// <summary>Tests execute stream (async).</summary>
802 [Test] 814 [Test]
803 public void ExecuteAsStreamAsync() 815 public void ExecuteAsStreamAsync()
804 { 816 {
805 SubtestExecuteAsStream(true); 817 SubtestExecuteAsStream(true);
806 } 818 }
807 819
808 #endregion 820 #endregion
809 821
810 #region Parameters 822 #region Parameters
811 823
812 #region Query Parameters 824 #region Query Parameters
813 825
814 /// <summary> Client request which contains query parameters. </summary> 826 /// <summary>Client request which contains query parameters.</summary>
815 class ClientServiceRequestWithQueryParameters : TestClientServiceRequest 827 class ClientServiceRequestWithQueryParameters : TestClientServiceRequest
816 { 828 {
817 [RequestParameterAttribute("required", Google.Apis.Util.RequestParam eterType.Query)] 829 [RequestParameterAttribute("required", Google.Apis.Util.RequestParam eterType.Query)]
818 public string Required { get; set; } 830 public string Required { get; set; }
819 831
820 [RequestParameterAttribute("optionalWithValue", Google.Apis.Util.Req uestParameterType.Query)] 832 [RequestParameterAttribute("optionalWithValue", Google.Apis.Util.Req uestParameterType.Query)]
821 public string OptionalWithValue { get; set; } 833 public string OptionalWithValue { get; set; }
822 834
823 [RequestParameterAttribute("optionalWithValue2", Google.Apis.Util.Re questParameterType.Query)] 835 [RequestParameterAttribute("optionalWithValue2", Google.Apis.Util.Re questParameterType.Query)]
824 public string OptionalWithValue2 { get; set; } 836 public string OptionalWithValue2 { get; set; }
825 837
826 [RequestParameterAttribute("optionalNull", Google.Apis.Util.RequestP arameterType.Query)] 838 [RequestParameterAttribute("optionalNull", Google.Apis.Util.RequestP arameterType.Query)]
827 public string OptionalNull { get; set; } 839 public string OptionalNull { get; set; }
828 840
829 [RequestParameterAttribute("optionalEmpty", Google.Apis.Util.Request ParameterType.Query)] 841 [RequestParameterAttribute("optionalEmpty", Google.Apis.Util.Request ParameterType.Query)]
830 public string OptionalEmpty { get; set; } 842 public string OptionalEmpty { get; set; }
831 843
832 [RequestParameterAttribute("optionalNotPressent", Google.Apis.Util.R equestParameterType.Query)] 844 [RequestParameterAttribute("optionalNotPressent", Google.Apis.Util.R equestParameterType.Query)]
833 public string OptionalNotPressent { get; set; } 845 public string OptionalNotPressent { get; set; }
834 846
835 public ClientServiceRequestWithQueryParameters(IClientService servic e, string method, object body) 847 public ClientServiceRequestWithQueryParameters(IClientService servic e, string method, object body)
836 : base(service, method, body) 848 : base(service, method, body)
837 { 849 {
838 RequestParameters.Add("required", new Parameter 850 RequestParameters.Add("required", new Parameter
839 { 851 {
840 Name = "required", 852 Name = "required",
841 IsRequired = true, 853 IsRequired = true,
842 ParameterType = "query" 854 ParameterType = "query"
843 }); 855 });
844 RequestParameters.Add("optionalWithValue", new Parameter 856 RequestParameters.Add("optionalWithValue", new Parameter
845 { 857 {
846 Name = "optionalWithValue", 858 Name = "optionalWithValue",
847 IsRequired = false, 859 IsRequired = false,
848 ParameterType = "query", 860 ParameterType = "query",
849 DefaultValue = "DoesNotDisplay" 861 DefaultValue = "DoesNotDisplay"
850 }); 862 });
851 RequestParameters.Add("optionalWithValue2", new Parameter 863 RequestParameters.Add("optionalWithValue2", new Parameter
852 { 864 {
853 Name = "optionalWithValue", 865 Name = "optionalWithValue",
854 IsRequired = false, 866 IsRequired = false,
855 ParameterType = "query", 867 ParameterType = "query",
856 DefaultValue = "DoesNotDisplay" 868 DefaultValue = "DoesNotDisplay"
857 }); 869 });
858 RequestParameters.Add("optionalWithNull", new Parameter 870 RequestParameters.Add("optionalWithNull", new Parameter
859 { 871 {
860 Name = "optionalWithNull", 872 Name = "optionalWithNull",
861 IsRequired = false, 873 IsRequired = false,
862 ParameterType = "query", 874 ParameterType = "query",
863 DefaultValue = "c" 875 DefaultValue = "c"
864 }); 876 });
865 RequestParameters.Add("optionalEmpty", new Parameter 877 RequestParameters.Add("optionalEmpty", new Parameter
866 { 878 {
867 Name = "optionalEmpty", 879 Name = "optionalEmpty",
868 IsRequired = false, 880 IsRequired = false,
869 ParameterType = "query", 881 ParameterType = "query",
870 DefaultValue = "d" 882 DefaultValue = "d"
871 }); 883 });
872 RequestParameters.Add("optionalNotPressent", new Parameter 884 RequestParameters.Add("optionalNotPressent", new Parameter
873 { 885 {
874 Name = "optionalNotPressent", 886 Name = "optionalNotPressent",
875 IsRequired = false, 887 IsRequired = false,
876 ParameterType = "query", 888 ParameterType = "query",
877 DefaultValue = "DoesNotDisplay" 889 DefaultValue = "DoesNotDisplay"
878 }); 890 });
879 } 891 }
880 } 892 }
881 893
882 /// <summary> Tests build request with query parameters. </summary> 894 /// <summary>Tests build request with query parameters.</summary>
883 [Test] 895 [Test]
884 public void CreateRequest_QueryParameters() 896 public void CreateRequest_QueryParameters()
885 { 897 {
886 using (var service = new MockClientService("https://build_request_pa rams")) 898 using (var service = new MockClientService("https://build_request_pa rams"))
887 { 899 {
888 var request = new ClientServiceRequestWithQueryParameters(servic e, "GET", null); 900 var request = new ClientServiceRequestWithQueryParameters(servic e, "GET", null);
889 request.Required = "a"; 901 request.Required = "a";
890 request.OptionalWithValue = "b"; 902 request.OptionalWithValue = "b";
891 request.OptionalWithValue2 = "DoesNotDisplay"; 903 request.OptionalWithValue2 = "DoesNotDisplay";
892 request.OptionalNull = null; 904 request.OptionalNull = null;
893 request.OptionalEmpty = string.Empty; 905 request.OptionalEmpty = string.Empty;
894 var httpRequest = request.CreateRequest(); 906 var httpRequest = request.CreateRequest();
895 Assert.That(httpRequest.RequestUri, Is.EqualTo(new Uri( 907 Assert.That(httpRequest.RequestUri, Is.EqualTo(new Uri(
896 "https://build_request_params/restPath0?required=a&optionalW ithValue=b&optionalEmpty"))); 908 "https://build_request_params/restPath0?required=a&optionalW ithValue=b&optionalEmpty")));
897 } 909 }
898 } 910 }
899 911
900 /// <summary> Tests build request with missing required query parameter. </summary> 912 /// <summary>Tests build request with missing required query parameter.< /summary>
901 [Test] 913 [Test]
902 public void CreateRequest_QueryParameterIsMissing() 914 public void CreateRequest_QueryParameterIsMissing()
903 { 915 {
904 using (var service = new MockClientService("https://build_request_pa rams")) 916 using (var service = new MockClientService("https://build_request_pa rams"))
905 { 917 {
906 var request = new ClientServiceRequestWithQueryParameters(servic e, "GET", null); 918 var request = new ClientServiceRequestWithQueryParameters(servic e, "GET", null);
907 // request.Required is missing! 919 // request.Required is missing!
908 try 920 try
909 { 921 {
910 var httpRequest = request.CreateRequest(); 922 var httpRequest = request.CreateRequest();
911 Assert.Fail(); 923 Assert.Fail();
912 } 924 }
913 catch (GoogleApiException ex) 925 catch (GoogleApiException ex)
914 { 926 {
915 Assert.True(ex.Message.Contains("Parameter \"required\" is m issing"), 927 Assert.True(ex.Message.Contains("Parameter \"required\" is m issing"),
916 "Exception with missing parameter should be thrown"); 928 "Exception with missing parameter should be thrown");
917 } 929 }
918 } 930 }
919 } 931 }
920 932
921 #endregion 933 #endregion
922 934
923 #region Path Parameters 935 #region Path Parameters
924 936
925 /// <summary> Client request which contains path parameters. </summary> 937 /// <summary>Client request which contains path parameters.</summary>
926 class ClientServiceRequestWithPathParameters : TestClientServiceRequest 938 class ClientServiceRequestWithPathParameters : TestClientServiceRequest
927 { 939 {
928 [RequestParameter("path1", RequestParameterType.Path)] 940 [RequestParameter("path1", RequestParameterType.Path)]
929 public int TestParameterA { get; set; } 941 public int TestParameterA { get; set; }
930 942
931 [RequestParameter("path2", RequestParameterType.Path)] 943 [RequestParameter("path2", RequestParameterType.Path)]
932 public int TestParameterB { get; set; } 944 public int TestParameterB { get; set; }
933 945
934 public int TestParameterC { get; set; } 946 public int TestParameterC { get; set; }
935 947
(...skipping 11 matching lines...) Expand all
947 ParameterType = "path", 959 ParameterType = "path",
948 }); 960 });
949 } 961 }
950 962
951 public override string RestPath 963 public override string RestPath
952 { 964 {
953 get { return "restPath/{path1}/something/{path2}"; } 965 get { return "restPath/{path1}/something/{path2}"; }
954 } 966 }
955 } 967 }
956 968
957 /// <summary> Tests build request with path parameters. </summary> 969 /// <summary>Tests build request with path parameters.</summary>
958 [Test] 970 [Test]
959 public void CreateRequest_PathParameters() 971 public void CreateRequest_PathParameters()
960 { 972 {
961 using (var service = new MockClientService("https://build_request_pa rams")) 973 using (var service = new MockClientService("https://build_request_pa rams"))
962 { 974 {
963 var request = new ClientServiceRequestWithPathParameters(service , "GET", null); 975 var request = new ClientServiceRequestWithPathParameters(service , "GET", null);
964 request.TestParameterA = 42; 976 request.TestParameterA = 42;
965 request.TestParameterB = 43; 977 request.TestParameterB = 43;
966 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
967 var httpRequest = request.CreateRequest(); 979 var httpRequest = request.CreateRequest();
968 Assert.That(httpRequest.RequestUri, Is.EqualTo(new Uri( 980 Assert.That(httpRequest.RequestUri, Is.EqualTo(new Uri(
969 "https://build_request_params/restPath/42/something/43"))); 981 "https://build_request_params/restPath/42/something/43")));
970 } 982 }
971 } 983 }
972 984
973 #endregion 985 #endregion
974 986
975 #region Developer Key 987 #region Developer Key
976 988
977 private const string SimpleDeveloperKey = "ABC123"; 989 private const string SimpleDeveloperKey = "ABC123";
978 private const string ComplexDeveloperKey = "?&^% ABC123"; 990 private const string ComplexDeveloperKey = "?&^% ABC123";
979 991
980 /// <summary> Tests build request with simple developer key. </summary> 992 /// <summary>Tests build request with simple developer key.</summary>
981 [Test] 993 [Test]
982 public void CreateRequest_DeveloperKey() 994 public void CreateRequest_DeveloperKey()
983 { 995 {
984 var initializer = new BaseClientService.Initializer 996 var initializer = new BaseClientService.Initializer
985 { 997 {
986 ApiKey = SimpleDeveloperKey 998 ApiKey = SimpleDeveloperKey
987 }; 999 };
1000
988 using (var service = new MockClientService(initializer, "https://bui ld_request_params")) 1001 using (var service = new MockClientService(initializer, "https://bui ld_request_params"))
989 { 1002 {
990 var request = new TestClientServiceRequest(service, "GET", null) ; 1003 var request = new TestClientServiceRequest(service, "GET", null) ;
991 var httpRequest = request.CreateRequest(); 1004 var httpRequest = request.CreateRequest();
992 Assert.That(httpRequest.RequestUri, Is.EqualTo(new Uri( 1005 Assert.That(httpRequest.RequestUri, Is.EqualTo(new Uri(
993 "https://build_request_params/restPath0?key=" SimpleDevelo perKey))); 1006 "https://build_request_params/restPath0?key=" SimpleDevelo perKey)));
994 } 1007 }
995 } 1008 }
996 1009
997 /// <summary> Tests build request with complex developer key. </summary> 1010 /// <summary>Tests build request with complex developer key.</summary>
998 [Test] 1011 [Test]
999 public void CreateRequest_DeveloperKey_RequiresEscape() 1012 public void CreateRequest_DeveloperKey_RequiresEscape()
1000 { 1013 {
1001 var initializer = new BaseClientService.Initializer 1014 var initializer = new BaseClientService.Initializer
1002 { 1015 {
1003 ApiKey = ComplexDeveloperKey 1016 ApiKey = ComplexDeveloperKey
1004 }; 1017 };
1018
1005 using (var service = new MockClientService(initializer, "https://bui ld_request_params")) 1019 using (var service = new MockClientService(initializer, "https://bui ld_request_params"))
1006 { 1020 {
1007 var request = new TestClientServiceRequest(service, "GET", null) ; 1021 var request = new TestClientServiceRequest(service, "GET", null) ;
1008 var httpRequest = request.CreateRequest(); 1022 var httpRequest = request.CreateRequest();
1009 Assert.That(httpRequest.RequestUri, Is.EqualTo(new Uri( 1023 Assert.That(httpRequest.RequestUri, Is.EqualTo(new Uri(
1010 "https://build_request_params/restPath0?key=?&^% % 20ABC123"))); 1024 "https://build_request_params/restPath0?key=?&^% % 20ABC123")));
1011 } 1025 }
1012 } 1026 }
1013 1027
1014 #endregion 1028 #endregion
1015 1029
1016 #endregion 1030 #endregion
1017 1031
1018 #region Supported Methods 1032 #region Supported Methods
1019 1033
1020 /// <summary> Tests if invalid method throws an exception. </summary> 1034 /// <summary>Tests if invalid method throws an exception.</summary>
1021 [Test] 1035 [Test]
1022 public void CreateRequest_UnsupportedMethods() 1036 public void CreateRequest_UnsupportedMethods()
1023 { 1037 {
1024 using (var service = new MockClientService("https://build_request_pa rams")) 1038 using (var service = new MockClientService("https://build_request_pa rams"))
1025 { 1039 {
1026 var request = new TestClientServiceRequest(service, "Unsupported ", null); 1040 var request = new TestClientServiceRequest(service, "Unsupported ", null);
1027 Assert.Throws<ArgumentOutOfRangeException>(() => request.CreateR equest()); 1041 Assert.Throws<ArgumentOutOfRangeException>(() => request.CreateR equest());
1028 } 1042 }
1029 } 1043 }
1030 1044
1031 /// <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>
1032 [Test] 1046 [Test]
1033 public void CreateRequest_SupportedMethods() 1047 public void CreateRequest_SupportedMethods()
1034 { 1048 {
1035 SubtestCreateRequest_SupportedMethod(HttpConsts.Get); 1049 SubtestCreateRequest_SupportedMethod(HttpConsts.Get);
1036 SubtestCreateRequest_SupportedMethod(HttpConsts.Put); 1050 SubtestCreateRequest_SupportedMethod(HttpConsts.Put);
1037 SubtestCreateRequest_SupportedMethod(HttpConsts.Post); 1051 SubtestCreateRequest_SupportedMethod(HttpConsts.Post);
1038 SubtestCreateRequest_SupportedMethod(HttpConsts.Patch); 1052 SubtestCreateRequest_SupportedMethod(HttpConsts.Patch);
1039 SubtestCreateRequest_SupportedMethod(HttpConsts.Delete); 1053 SubtestCreateRequest_SupportedMethod(HttpConsts.Delete);
1040 } 1054 }
1041 1055
1042 private void SubtestCreateRequest_SupportedMethod(string method) 1056 private void SubtestCreateRequest_SupportedMethod(string method)
1043 { 1057 {
1044 using (var service = new MockClientService("https://build_request_pa rams")) 1058 using (var service = new MockClientService("https://build_request_pa rams"))
1045 { 1059 {
1046 var request = new TestClientServiceRequest(service, method, null ); 1060 var request = new TestClientServiceRequest(service, method, null );
1047 var httpRequest = request.CreateRequest(); 1061 var httpRequest = request.CreateRequest();
1048 } 1062 }
1049 } 1063 }
1050 1064
1051 #endregion 1065 #endregion
1052 1066
1053 #region ETag 1067 #region ETag
1054 1068
1055 /// <summary> Tests the create request method with different ETags. </su mmary> 1069 /// <summary>Tests the create request method with different ETags.</summ ary>
1056 [Test] 1070 [Test]
1057 public void CreateRequest_ETag() 1071 public void CreateRequest_ETag()
1058 { 1072 {
1059 var body = new MockRequest { Name = "long long name" }; 1073 var body = new MockRequest { Name = "long long name" };
1060 using (var service = new MockClientService()) 1074 using (var service = new MockClientService())
1061 { 1075 {
1062 // no ETag (ETag = null) 1076 // No ETag (ETag = null).
1063 var request = new TestClientServiceRequest(service, HttpConsts.G et, body); 1077 var request = new TestClientServiceRequest(service, HttpConsts.G et, body);
1064 var httpRequest = request.CreateRequest(); 1078 var httpRequest = request.CreateRequest();
1065 Assert.That(httpRequest.Headers.IfMatch.Count, Is.EqualTo(0)); 1079 Assert.That(httpRequest.Headers.IfMatch.Count, Is.EqualTo(0));
1066 Assert.That(httpRequest.Headers.IfNoneMatch.Count, Is.EqualTo(0) ); 1080 Assert.That(httpRequest.Headers.IfNoneMatch.Count, Is.EqualTo(0) );
1067 1081
1068 // ETag has a value, but ETag action is ignored 1082 // ETag has a value, but ETag action is ignored.
1069 body.ETag = "\"ETAG_HERE\""; 1083 body.ETag = "\"ETAG_HERE\"";
1070 request = new TestClientServiceRequest(service, HttpConsts.Get, body); 1084 request = new TestClientServiceRequest(service, HttpConsts.Get, body);
1071 request.ETagAction = ETagAction.Ignore; 1085 request.ETagAction = ETagAction.Ignore;
1072 httpRequest = request.CreateRequest(); 1086 httpRequest = request.CreateRequest();
1073 Assert.That(httpRequest.Headers.IfMatch.Count, Is.EqualTo(0)); 1087 Assert.That(httpRequest.Headers.IfMatch.Count, Is.EqualTo(0));
1074 Assert.That(httpRequest.Headers.IfNoneMatch.Count, Is.EqualTo(0) ); 1088 Assert.That(httpRequest.Headers.IfNoneMatch.Count, Is.EqualTo(0) );
1075 1089
1076 // 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 ).
1077 request = new TestClientServiceRequest(service, HttpConsts.Get, body); 1091 request = new TestClientServiceRequest(service, HttpConsts.Get, body);
1078 httpRequest = request.CreateRequest(); 1092 httpRequest = request.CreateRequest();
1079 Assert.That(httpRequest.Headers.IfMatch.Count, Is.EqualTo(0)); 1093 Assert.That(httpRequest.Headers.IfMatch.Count, Is.EqualTo(0));
1080 Assert.That(httpRequest.Headers.IfNoneMatch.Count, Is.EqualTo(1) ); 1094 Assert.That(httpRequest.Headers.IfNoneMatch.Count, Is.EqualTo(1) );
1081 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)));
1082 1096
1083 // ETag has a value, so use default action (Post -> If-Match) 1097 // ETag has a value, so use default action (Post -> If-Match).
1084 request = new TestClientServiceRequest(service, HttpConsts.Post, body); 1098 request = new TestClientServiceRequest(service, HttpConsts.Post, body);
1085 httpRequest = request.CreateRequest(); 1099 httpRequest = request.CreateRequest();
1086 Assert.That(httpRequest.Headers.IfNoneMatch.Count, Is.EqualTo(0) ); 1100 Assert.That(httpRequest.Headers.IfNoneMatch.Count, Is.EqualTo(0) );
1087 Assert.That(httpRequest.Headers.IfMatch.Count, Is.EqualTo(1)); 1101 Assert.That(httpRequest.Headers.IfMatch.Count, Is.EqualTo(1));
1088 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)));
1089 1103
1090 // 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.
1091 request = new TestClientServiceRequest(service, HttpConsts.Post, body); 1105 request = new TestClientServiceRequest(service, HttpConsts.Post, body);
1092 request.ETagAction = ETagAction.IfNoneMatch; 1106 request.ETagAction = ETagAction.IfNoneMatch;
1093 httpRequest = request.CreateRequest(); 1107 httpRequest = request.CreateRequest();
1094 Assert.That(httpRequest.Headers.IfMatch.Count, Is.EqualTo(0)); 1108 Assert.That(httpRequest.Headers.IfMatch.Count, Is.EqualTo(0));
1095 Assert.That(httpRequest.Headers.IfNoneMatch.Count, Is.EqualTo(1) ); 1109 Assert.That(httpRequest.Headers.IfNoneMatch.Count, Is.EqualTo(1) );
1096 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)));
1097 1111
1098 // 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.
1099 request = new TestClientServiceRequest(service, HttpConsts.Get, body); 1113 request = new TestClientServiceRequest(service, HttpConsts.Get, body);
1100 request.ETagAction = ETagAction.IfMatch; 1114 request.ETagAction = ETagAction.IfMatch;
1101 httpRequest = request.CreateRequest(); 1115 httpRequest = request.CreateRequest();
1102 Assert.That(httpRequest.Headers.IfNoneMatch.Count, Is.EqualTo(0) ); 1116 Assert.That(httpRequest.Headers.IfNoneMatch.Count, Is.EqualTo(0) );
1103 Assert.That(httpRequest.Headers.IfMatch.Count, Is.EqualTo(1)); 1117 Assert.That(httpRequest.Headers.IfMatch.Count, Is.EqualTo(1));
1104 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)));
1105 } 1119 }
1106 } 1120 }
1107 1121
1108 /// <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>
1109 [Test] 1123 [Test]
1110 public void GetDefaultETagActionTest() 1124 public void GetDefaultETagActionTest()
1111 { 1125 {
1112 Assert.AreEqual(ETagAction.IfNoneMatch, ClientServiceRequest<object> .GetDefaultETagAction(HttpConsts.Get)); 1126 Assert.AreEqual(ETagAction.IfNoneMatch, ClientServiceRequest<object> .GetDefaultETagAction(HttpConsts.Get));
1113 Assert.AreEqual(ETagAction.IfMatch, ClientServiceRequest<object>.Get DefaultETagAction(HttpConsts.Post)); 1127 Assert.AreEqual(ETagAction.IfMatch, ClientServiceRequest<object>.Get DefaultETagAction(HttpConsts.Post));
1114 Assert.AreEqual(ETagAction.IfMatch, ClientServiceRequest<object>.Get DefaultETagAction(HttpConsts.Patch)); 1128 Assert.AreEqual(ETagAction.IfMatch, ClientServiceRequest<object>.Get DefaultETagAction(HttpConsts.Patch));
1115 Assert.AreEqual(ETagAction.IfMatch, ClientServiceRequest<object>.Get DefaultETagAction(HttpConsts.Put)); 1129 Assert.AreEqual(ETagAction.IfMatch, ClientServiceRequest<object>.Get DefaultETagAction(HttpConsts.Put));
1116 Assert.AreEqual(ETagAction.IfMatch, ClientServiceRequest<object>.Get DefaultETagAction(HttpConsts.Delete)); 1130 Assert.AreEqual(ETagAction.IfMatch, ClientServiceRequest<object>.Get DefaultETagAction(HttpConsts.Delete));
1117 Assert.AreEqual(ETagAction.Ignore, ClientServiceRequest<object>.GetD efaultETagAction("INVALID")); 1131 Assert.AreEqual(ETagAction.Ignore, ClientServiceRequest<object>.GetD efaultETagAction("INVALID"));
1118 } 1132 }
1119 1133
1120 #endregion 1134 #endregion
1121 } 1135 }
1122 } 1136 }
OLDNEW

Powered by Google App Engine
RSS Feeds Recent Issues | This issue
This is Rietveld f62528b