This repository was archived by the owner on Aug 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 371
/
Copy pathTestHelper.Common.cs
754 lines (672 loc) · 28.8 KB
/
TestHelper.Common.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
// -----------------------------------------------------------------------------------------
// <copyright file="TestHelper.Common.cs" company="Microsoft">
// Copyright 2013 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// -----------------------------------------------------------------------------------------
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Azure.Storage.Blob;
using Microsoft.Azure.Storage.File;
using Microsoft.Azure.Storage.File.Protocol;
using Microsoft.Azure.Storage.Shared.Protocol;
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
namespace Microsoft.Azure.Storage
{
public partial class TestHelper
{
/// <summary>
/// Runs a given operation that is expected to throw an exception.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="operation"></param>
/// <param name="operationDescription"></param>
internal static T ExpectedException<T>(Action operation, string operationDescription, string expectedMessage = null)
where T : Exception
{
try
{
operation();
}
catch (T e)
{
if (!string.IsNullOrEmpty(expectedMessage))
{
if (!expectedMessage.Equals(e.Message, StringComparison.Ordinal))
{
Assert.Fail("Incorrect message in exception. Expected: {0}, actual: {1}", expectedMessage, e.Message);
}
}
return e;
}
//#if NETCORE
catch (AggregateException ex)
{
ex = ex.Flatten();
if (ex.InnerExceptions.Count > 1)
{
Assert.Fail("Multiple exceptions {0} for operation: {1}", ex.GetType(), operationDescription);
}
T e = ex.InnerException as T; // Test framework changes the value under debugger
if (e != null)
{
return e;
}
Assert.Fail("Invalid exception {0} for operation: {1}", ex.GetType(), operationDescription);
}
//#endif
catch (Exception ex)
{
T e = ex as T; // Test framework changes the value under debugger
if (e != null)
{
return e;
}
Assert.Fail("Invalid exception {0} for operation: {1}", ex.GetType(), operationDescription);
}
Assert.Fail("No exception received while expecting {0}: {1}", typeof(T).ToString(), operationDescription);
return null;
}
/// <summary>
/// Runs a given operation that is expected to throw an exception.
/// </summary>
/// <param name="operation"></param>
/// <param name="operationDescription"></param>
/// <param name="expectedStatusCode"></param>
internal static void ExpectedException(Action<OperationContext> operation, string operationDescription, int expectedStatusCode)
{
OperationContext opContext = new OperationContext();
try
{
operation(opContext);
}
catch (Exception)
{
Assert.AreEqual(expectedStatusCode, opContext.LastResult.HttpStatusCode, "Http status code is unexpected.");
return;
}
Assert.Fail("No exception received while expecting {0}: {1}", expectedStatusCode, operationDescription);
}
internal static void AssertNAttempts(OperationContext ctx, int n)
{
Assert.AreEqual(n, ctx.RequestResults.Count(), String.Format("Operation took more than {0} attempt(s) to complete", n));
}
#if TASK
internal static void AssertCancellationOperation(OperationContext ctx)
{
TestHelper.AssertNAttempts(ctx, 1);
Assert.IsInstanceOfType(ctx.LastResult.Exception.InnerException, typeof(OperationCanceledException));
Assert.AreEqual("The operation was canceled.", ctx.LastResult.Exception.InnerException.Message);
}
internal static void AssertCancellationTask(OperationContext ctx)
{
TestHelper.AssertNAttempts(ctx, 1);
Assert.IsInstanceOfType(ctx.LastResult.Exception.InnerException, typeof(OperationCanceledException));
Assert.AreEqual("A task was canceled.", ctx.LastResult.Exception.InnerException.Message);
}
/// <summary>
/// Runs a given operation that is expected to throw an exception.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="operation"></param>
/// <param name="operationDescription"></param>
internal static T ExpectedExceptionTask<T>(Task operation, string operationDescription)
where T : Exception
{
try
{
operation.Wait();
}
catch (AggregateException ex)
{
ex = ex.Flatten();
if (ex.InnerExceptions.Count > 1)
{
Assert.Fail("Multiple exceptions {0} for operation: {1}", ex.GetType(), operationDescription);
}
T e = ex.InnerException as T; // Test framework changes the value under debugger
if (e != null)
{
Assert.IsTrue(operation.IsCompleted);
if (ex.InnerException is OperationCanceledException)
{
Assert.IsTrue(operation.IsCanceled);
Assert.IsFalse(operation.IsFaulted);
Assert.AreEqual(TaskStatus.Canceled, operation.Status);
}
else
{
Assert.IsFalse(operation.IsCanceled);
Assert.IsTrue(operation.IsFaulted);
Assert.AreEqual(TaskStatus.Faulted, operation.Status);
}
return e;
}
Assert.Fail("Invalid exception {0} for operation: {1}", ex.GetType(), operationDescription);
}
catch (Exception ex)
{
Assert.Fail("Invalid exception {0} for operation: {1}", ex.GetType(), operationDescription);
}
Assert.Fail("No exception received while expecting {0}: {1}", typeof(T).ToString(), operationDescription);
return null;
}
#endif
/// <summary>
/// Compares two streams.
/// </summary>
internal static void AssertStreamsAreEqual(Stream src, Stream dst)
{
Assert.AreEqual(src.Length, dst.Length);
long origDstPosition = dst.Position;
long origSrcPosition = src.Position;
dst.Position = 0;
src.Position = 0;
for (int i = 0; i < src.Length; i++)
{
Assert.AreEqual(src.ReadByte(), dst.ReadByte());
}
dst.Position = origDstPosition;
src.Position = origSrcPosition;
}
/// <summary>
/// Compares two streams fast, will fallback to normal stream comaparison if necessary.
/// </summary>
internal static void AssertStreamsAreEqualFast(Stream src, Stream dst)
{
Assert.AreEqual(src.Length, dst.Length);
const int bufferSize = 4 * 1024;
byte[] buffer1 = new byte[bufferSize];
byte[] buffer2 = new byte[bufferSize];
long origDstPosition = dst.Position;
long origSrcPosition = src.Position;
long bytesRead1 = 0;
long bytesRead2 = 0;
while (true)
{
int count1 = src.Read(buffer1, 0, bufferSize);
bytesRead1 += count1;
int count2 = dst.Read(buffer2, 0, bufferSize);
bytesRead2 += count2;
if (count1 != count2 || count1 == 0)
{
break;
}
int iterations = (int)Math.Ceiling((double)count1 / sizeof(Int64));
for (int i = 0; i < iterations; i++)
{
Assert.AreEqual(BitConverter.ToInt64(buffer1, i * sizeof(Int64)), BitConverter.ToInt64(buffer2, i * sizeof(Int64)));
}
}
if (bytesRead1 == bytesRead2)
{
if (bytesRead1 != (src.Length - origSrcPosition))
{
AssertStreamsAreEqual(src, dst);
}
}
else
{
dst.Position = origDstPosition;
src.Position = origSrcPosition;
AssertStreamsAreEqual(src, dst);
}
dst.Position = origDstPosition;
src.Position = origSrcPosition;
}
/// <summary>
/// Compares two streams from the starting positions and up to length bytes.
/// </summary>
internal static void AssertStreamsAreEqualAtIndex(MemoryStream src, MemoryStream dst, int srcIndex, int dstIndex, int length)
{
byte[] origBuffer = src.ToArray();
byte[] retrBuffer = dst.ToArray();
for (int i = 0; i < length; i++)
{
Assert.AreEqual(origBuffer[srcIndex + i], retrBuffer[dstIndex + i]);
}
}
/// <summary>
/// Compares two byte buffers.
/// </summary>
internal static void AssertBuffersAreEqual(byte[] src, byte[] dst)
{
Assert.AreEqual(src.Length, dst.Length);
for (int i = 0; i < src.Length; i++)
{
Assert.AreEqual(src[i], dst[i], "Mismatch of data at index : " + i);
}
}
/// <summary>
/// Compares two byte buffers.
/// </summary>
internal static void AssertBuffersAreEqualUptoIndex(byte[] src, byte[] dst, int index)
{
for (int i = 0; i <= index; i++)
{
Assert.AreEqual(src[i], dst[i], "Mismatch of data at index : " + i);
}
}
/// <summary>
/// Validates if this test supports the current target tenant.
/// Skips the current test if the target tenant is not supported.
/// </summary>
public static void ValidateIfTestSupportTargetTenant(TenantType supportedTenantTypes)
{
if ((supportedTenantTypes & TestBase.CurrentTenantType) == 0)
{
Assert.Inconclusive("This test is skipped because the target test tenant is {0}.", TestBase.CurrentTenantType);
}
}
/// <summary>
/// Remove the local fiddler proxy from a URI.
/// </summary>
/// <param name="uri">The URI to change.</param>
/// <returns>The URI without the local fiddler proxy.</returns>
internal static Uri Defiddler(Uri uri)
{
string fiddlerString = "ipv4.fiddler";
string replacementString = "127.0.0.1";
string uriString = uri.AbsoluteUri;
if (uriString.Contains(fiddlerString))
{
return new Uri(uriString.Replace(fiddlerString, replacementString));
}
else
{
return uri;
}
}
/// <summary>
/// Remove the local fiddler proxy from a blob reference.
/// </summary>
/// <param name="blob">The blob to change.</param>
/// <returns>A blob reference without the local fiddler proxy.
/// If no fiddler proxy is present, the old blob reference is returned.</returns>
internal static CloudBlockBlob Defiddler(CloudBlockBlob blob)
{
Uri oldUri = blob.Uri;
Uri newUri = Defiddler(oldUri);
if (newUri != oldUri)
{
return new CloudBlockBlob(newUri, blob.SnapshotTime, blob.ServiceClient.Credentials);
}
else
{
return blob;
}
}
/// <summary>
/// Remove the local fiddler proxy from a blob reference.
/// </summary>
/// <param name="blob">The blob to change.</param>
/// <returns>A blob reference without the local fiddler proxy.
/// If no fiddler proxy is present, the old blob reference is returned.</returns>
internal static CloudPageBlob Defiddler(CloudPageBlob blob)
{
Uri oldUri = blob.Uri;
Uri newUri = Defiddler(oldUri);
if (newUri != oldUri)
{
return new CloudPageBlob(newUri, blob.SnapshotTime, blob.ServiceClient.Credentials);
}
else
{
return blob;
}
}
/// <summary>
/// Remove the local fiddler proxy from a file reference.
/// </summary>
/// <param name="file">The file to change.</param>
/// <returns>A file reference without the local fiddler proxy.
/// If no fiddler proxy is present, the old file reference is returned.</returns>
internal static CloudFile Defiddler(CloudFile file)
{
Uri oldUri = file.Uri;
Uri newUri = Defiddler(oldUri);
if (newUri != oldUri)
{
return new CloudFile(newUri, file.ServiceClient.Credentials);
}
else
{
return file;
}
}
internal static void ValidateResponse(OperationContext opContext, int expectedAttempts, int expectedStatusCode, string[] allowedErrorCodes, string errorMessageBeginsWith, string expectedStatusMessageBeginsWith = null)
{
ValidateResponse(opContext, expectedAttempts, expectedStatusCode, allowedErrorCodes, new string[] { errorMessageBeginsWith }, expectedStatusMessageBeginsWith);
}
internal static void ValidateResponse(OperationContext opContext, int expectedAttempts, int expectedStatusCode, string[] allowedErrorCodes, string[] errorMessageBeginsWith, string expectedStatusMessageBeginsWith = null)
{
ValidateResponse(opContext, expectedAttempts, expectedStatusCode, allowedErrorCodes, errorMessageBeginsWith, true, expectedStatusMessageBeginsWith);
}
internal static void ValidateResponse(OperationContext opContext, int expectedAttempts, int expectedStatusCode, string[] allowedErrorCodes, string[] errorMessageBeginsWith, bool stripIndex, string expectedStatusMessageBeginsWith = null)
{
TestHelper.AssertNAttempts(opContext, 1);
Assert.AreEqual(opContext.LastResult.HttpStatusCode, expectedStatusCode);
if (!string.IsNullOrEmpty(expectedStatusMessageBeginsWith))
{
Assert.IsTrue(opContext.LastResult.HttpStatusMessage.ToString().Contains(expectedStatusMessageBeginsWith));
}
Assert.IsTrue(allowedErrorCodes.Contains(opContext.LastResult.ExtendedErrorInformation.ErrorCode), "Unexpected Error Code, received " + opContext.LastResult.ExtendedErrorInformation.ErrorCode);
if (errorMessageBeginsWith != null)
{
Assert.IsNotNull(opContext.LastResult.ExtendedErrorInformation.ErrorMessage);
string message = opContext.LastResult.ExtendedErrorInformation.ErrorMessage;
if (stripIndex)
{
int semDex = opContext.LastResult.ExtendedErrorInformation.ErrorMessage.IndexOf(":");
semDex = semDex > 2 ? -1 : semDex;
message = message.Substring(semDex + 1);
}
Assert.IsTrue(errorMessageBeginsWith.Where((s) => message.StartsWith(s)).Count() > 0, opContext.LastResult.ExtendedErrorInformation.ErrorMessage);
}
}
internal static void SeekRandomly(Stream stream, long offset)
{
Random random = new Random();
int randomOrigin = random.Next(3);
SeekOrigin origin = SeekOrigin.Begin;
switch (randomOrigin)
{
case 1:
origin = SeekOrigin.Current;
offset = offset - stream.Position;
break;
case 2:
origin = SeekOrigin.End;
offset = offset - stream.Length;
break;
}
stream.Seek(offset, origin);
}
internal static void VerifyServiceStats(ServiceStats stats)
{
Assert.IsNotNull(stats);
if (stats.GeoReplication.LastSyncTime.HasValue)
{
Assert.AreEqual(GeoReplicationStatus.Live, stats.GeoReplication.Status);
}
else
{
Assert.AreNotEqual(GeoReplicationStatus.Live, stats.GeoReplication.Status);
}
}
internal static void AssertFileServicePropertiesAreEqual(FileServiceProperties propsA, FileServiceProperties propsB)
{
if (propsA == null || propsB == null)
{
Assert.IsNull(propsA);
Assert.IsNull(propsB);
}
else
{
AssertPropertiesAreEqual(propsA, propsA.serviceProperties);
AssertPropertiesAreEqual(propsB, propsB.serviceProperties);
AssertServicePropertiesAreEqual(propsA.serviceProperties, propsB.serviceProperties);
}
}
private static void AssertPropertiesAreEqual(FileServiceProperties fileProps, ServiceProperties props)
{
if (fileProps == null || props == null)
{
Assert.IsNull(fileProps);
Assert.IsNull(props);
}
else
{
Assert.AreEqual(fileProps.Cors, props.Cors);
Assert.AreEqual(fileProps.MinuteMetrics, props.MinuteMetrics);
Assert.AreEqual(fileProps.HourMetrics, props.HourMetrics);
}
}
internal static void AssertServicePropertiesAreEqual(ServiceProperties propsA, ServiceProperties propsB)
{
if (propsA.Logging != null && propsB.Logging != null)
{
Assert.AreEqual(propsA.Logging.LoggingOperations, propsB.Logging.LoggingOperations);
Assert.AreEqual(propsA.Logging.RetentionDays, propsB.Logging.RetentionDays);
Assert.AreEqual(propsA.Logging.Version, propsB.Logging.Version);
}
else
{
Assert.IsNull(propsA.Logging);
Assert.IsNull(propsB.Logging);
}
if (propsA.HourMetrics != null && propsB.HourMetrics != null)
{
Assert.AreEqual(propsA.HourMetrics.MetricsLevel, propsB.HourMetrics.MetricsLevel);
Assert.AreEqual(propsA.HourMetrics.RetentionDays, propsB.HourMetrics.RetentionDays);
Assert.AreEqual(propsA.HourMetrics.Version, propsB.HourMetrics.Version);
}
else
{
Assert.IsNull(propsA.HourMetrics);
Assert.IsNull(propsB.HourMetrics);
}
if (propsA.MinuteMetrics != null && propsB.MinuteMetrics != null)
{
Assert.AreEqual(propsA.MinuteMetrics.MetricsLevel, propsB.MinuteMetrics.MetricsLevel);
Assert.AreEqual(propsA.MinuteMetrics.RetentionDays, propsB.MinuteMetrics.RetentionDays);
Assert.AreEqual(propsA.MinuteMetrics.Version, propsB.MinuteMetrics.Version);
}
else
{
Assert.IsNull(propsA.MinuteMetrics);
Assert.IsNull(propsB.MinuteMetrics);
}
if (propsA.DefaultServiceVersion != null && propsB.DefaultServiceVersion != null)
{
Assert.AreEqual(propsA.DefaultServiceVersion, propsB.DefaultServiceVersion);
}
else
{
Assert.IsNull(propsA.DefaultServiceVersion);
Assert.IsNull(propsB.DefaultServiceVersion);
}
if (propsA.Cors != null && propsB.Cors != null)
{
Assert.AreEqual(propsA.Cors.CorsRules.Count, propsB.Cors.CorsRules.Count);
// Check that rules are equal and in the same order.
for (int i = 0; i < propsA.Cors.CorsRules.Count; i++)
{
CorsRule ruleA = propsA.Cors.CorsRules.ElementAt(i);
CorsRule ruleB = propsB.Cors.CorsRules.ElementAt(i);
Assert.IsTrue(
ruleA.AllowedOrigins.Count == ruleB.AllowedOrigins.Count
&& !ruleA.AllowedOrigins.Except(ruleB.AllowedOrigins).Any());
Assert.IsTrue(
ruleA.ExposedHeaders.Count == ruleB.ExposedHeaders.Count
&& !ruleA.ExposedHeaders.Except(ruleB.ExposedHeaders).Any());
Assert.IsTrue(
ruleA.AllowedHeaders.Count == ruleB.AllowedHeaders.Count
&& !ruleA.AllowedHeaders.Except(ruleB.AllowedHeaders).Any());
Assert.IsTrue(ruleA.AllowedMethods == ruleB.AllowedMethods);
Assert.IsTrue(ruleA.MaxAgeInSeconds == ruleB.MaxAgeInSeconds);
}
}
else
{
Assert.IsNull(propsA.Cors);
Assert.IsNull(propsB.Cors);
}
if (propsA.DeleteRetentionPolicy != null && propsB.DeleteRetentionPolicy != null)
{
Assert.AreEqual(propsA.DeleteRetentionPolicy.Enabled, propsB.DeleteRetentionPolicy.Enabled);
Assert.AreEqual(propsA.DeleteRetentionPolicy.RetentionDays, propsB.DeleteRetentionPolicy.RetentionDays);
}
else
{
Assert.IsNull(propsA.DeleteRetentionPolicy);
Assert.IsNull(propsB.DeleteRetentionPolicy);
}
if (propsA.StaticWebsite != null && propsB.StaticWebsite != null)
{
Assert.AreEqual(propsA.StaticWebsite.IndexDocument, propsB.StaticWebsite.IndexDocument);
Assert.AreEqual(propsA.StaticWebsite.ErrorDocument404Path, propsB.StaticWebsite.ErrorDocument404Path);
}
else
{
Assert.IsNull(propsA.StaticWebsite);
Assert.IsNull(propsB.StaticWebsite);
}
}
internal static async Task SpinUpToNSecondsIgnoringFailuresAsync(Func<Task> test, int secondCount)
{
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
while (true)
{
try
{
await test();
return;
}
catch (Exception)
{
if (stopwatch.Elapsed > TimeSpan.FromSeconds(secondCount))
{
throw;
}
}
await Task.Delay(TimeSpan.FromSeconds(1));
}
}
internal static void SpinUpToNSecondsIgnoringFailures(Action test, int secondCount)
{
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
while (true)
{
try
{
test();
return;
}
catch (Exception)
{
if (stopwatch.Elapsed > TimeSpan.FromSeconds(secondCount))
{
throw;
}
else
{
Task.Delay(TimeSpan.FromSeconds(1)).Wait();
}
}
}
}
internal static Task SpinUpTo30SecondsIgnoringFailuresAsync(Func<Task> test)
{
return SpinUpToNSecondsIgnoringFailuresAsync(test, 30);
}
internal static void SpinUpTo30SecondsIgnoringFailures(Action test)
{
SpinUpToNSecondsIgnoringFailures(test, 30);
}
/// <summary>
/// Compares the streams from the current position to the end.
/// </summary>
/// <param name="src">source stream for comparison</param>
/// <param name="dst">destination stream for comparison</param>
/// <returns></returns>
internal static async Task AssertStreamsAreEqualAsync(Stream src, Stream dst)
{
Stream srcAsStream = src;
Stream dstAsStream = dst;
byte[] srcBuffer = new byte[64 * 1024];
int srcRead;
byte[] dstBuffer = new byte[64 * 1024];
int dstRead;
do
{
srcRead = await srcAsStream.ReadAsync(srcBuffer, 0, srcBuffer.Length);
dstRead = await dstAsStream.ReadAsync(dstBuffer, 0, dstBuffer.Length);
Assert.AreEqual(srcRead, dstRead);
for (int i = 0; i < srcRead; i++)
{
Assert.AreEqual(srcBuffer[i], dstBuffer[i]);
}
}
while (srcRead > 0);
}
/// <summary>
/// Runs a given operation that is expected to throw an exception.
/// </summary>
/// <typeparam name="T">Exeption type</typeparam>
/// <param name="operation">operation to run</param>
/// <param name="operationDescription">operation description</param>
internal static async Task<T> ExpectedExceptionAsync<T>(Func<Task> operation, string operationDescription)
where T : Exception
{
try
{
await operation();
}
catch (T e)
{
return e;
}
catch (Exception ex)
{
T e = ex as T; // Test framework changes the value under debugger
if (e != null)
{
return e;
}
Assert.Fail("Invalid exception {0} for operation: {1}", ex.GetType(), operationDescription);
}
Assert.Fail("No exception received while expecting {0}: {1}", typeof(T).ToString(), operationDescription);
return null;
}
/// <summary>
/// Runs a given operation that is expected to throw an exception.
/// </summary>
/// <param name="operation">operation to run</param>
/// <param name="operationDescription">operation description</param>
/// <param name="expectedStatusCode">Expected status code</param>
internal static async Task ExpectedExceptionAsync(Func<Task> operation, OperationContext operationContext, string operationDescription, HttpStatusCode expectedStatusCode, string requestErrorCode = null)
{
try
{
await operation();
}
catch (StorageException storageException)
{
Assert.AreEqual((int)expectedStatusCode, storageException.RequestInformation.HttpStatusCode, "Http status code is unexpected.");
if (!string.IsNullOrEmpty(requestErrorCode))
{
Assert.IsNotNull(storageException.RequestInformation.ExtendedErrorInformation);
Assert.AreEqual(requestErrorCode, storageException.RequestInformation.ExtendedErrorInformation.ErrorCode);
}
return;
}
catch (Exception)
{
Assert.AreEqual((int)expectedStatusCode, operationContext.LastResult.HttpStatusCode, "Http status code is unexpected.");
if (!string.IsNullOrEmpty(requestErrorCode))
{
Assert.IsNotNull(operationContext.LastResult.ExtendedErrorInformation);
Assert.AreEqual(requestErrorCode, operationContext.LastResult.ExtendedErrorInformation.ErrorCode);
}
return;
}
Assert.Fail("No exception received while expecting {0}: {1}", expectedStatusCode, operationDescription);
}
}
}