forked from Azure/azure-sdk-for-net
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPageBlobClientTests.cs
More file actions
4308 lines (3557 loc) · 179 KB
/
PageBlobClientTests.cs
File metadata and controls
4308 lines (3557 loc) · 179 KB
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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core.TestFramework;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Blobs.Specialized;
using Azure.Storage.Blobs.Tests;
using Azure.Storage.Sas;
using Azure.Storage.Shared;
using Azure.Storage.Test;
using Azure.Storage.Test.Shared;
using Azure.Storage.Tests;
using Microsoft.CodeAnalysis.CSharp;
using Moq;
using NUnit.Framework;
namespace Azure.Storage.Blobs.Test
{
public class PageBlobClientTests : BlobTestBase
{
private const string CacheControl = "control";
private const string ContentDisposition = "disposition";
private const string ContentEncoding = "encoding";
private const string ContentLanguage = "language";
private const string ContentType = "type";
public PageBlobClientTests(bool async, BlobClientOptions.ServiceVersion serviceVersion)
: base(async, serviceVersion, null /* RecordedTestMode.Record /* to re-record */)
{
}
[RecordedTest]
public void Ctor_ConnectionString()
{
var accountName = "accountName";
var accountKey = Convert.ToBase64String(new byte[] { 0, 1, 2, 3, 4, 5 });
var credentials = new StorageSharedKeyCredential(accountName, accountKey);
var blobEndpoint = new Uri("http://127.0.0.1/" + accountName);
var blobSecondaryEndpoint = new Uri("http://127.0.0.1/" + accountName + "-secondary");
var connectionString = new StorageConnectionString(credentials, blobStorageUri: (blobEndpoint, blobSecondaryEndpoint));
var containerName = GetNewContainerName();
var blobName = GetNewBlobName();
PageBlobClient blob = InstrumentClient(new PageBlobClient(connectionString.ToString(true), containerName, blobName, GetOptions()));
var builder = new BlobUriBuilder(blob.Uri);
Assert.AreEqual(containerName, builder.BlobContainerName);
Assert.AreEqual(blobName, builder.BlobName);
Assert.AreEqual("accountName", builder.AccountName);
}
[RecordedTest]
public void Ctor_Uri()
{
// Arrange
string accountName = "accountname";
string containerName = GetNewContainerName();
string blobName = GetNewBlobName();
Uri uri = new Uri($"https://{accountName}.blob.core.windows.net/{containerName}/{blobName}");
// Act
PageBlobClient pageBlobClient = new PageBlobClient(uri);
// Assert
BlobUriBuilder builder = new BlobUriBuilder(pageBlobClient.Uri);
Assert.AreEqual(containerName, builder.BlobContainerName);
Assert.AreEqual(blobName, builder.BlobName);
Assert.AreEqual(accountName, builder.AccountName);
}
[RecordedTest]
public void Ctor_TokenAuth_Http()
{
// Arrange
Uri httpUri = new Uri(Tenants.TestConfigOAuth.BlobServiceEndpoint).ToHttp();
// Act
TestHelper.AssertExpectedException(
() => new PageBlobClient(httpUri, Tenants.GetOAuthCredential()),
new ArgumentException("Cannot use TokenCredential without HTTPS."));
}
[RecordedTest]
public void Ctor_CPK_Http()
{
// Arrange
CustomerProvidedKey customerProvidedKey = GetCustomerProvidedKey();
BlobClientOptions blobClientOptions = new BlobClientOptions()
{
CustomerProvidedKey = customerProvidedKey
};
Uri httpUri = new Uri(TestConfigDefault.BlobServiceEndpoint).ToHttp();
// Act
TestHelper.AssertExpectedException(
() => new PageBlobClient(httpUri, blobClientOptions),
new ArgumentException("Cannot use client-provided key without HTTPS."));
}
[RecordedTest]
public async Task Ctor_AzureSasCredential()
{
// Arrange
await using DisposingContainer test = await GetTestContainerAsync();
string sas = GetContainerSas(test.Container.Name, BlobContainerSasPermissions.All).ToString();
var client = test.Container.GetPageBlobClient(GetNewBlobName());
await client.CreateAsync(1024);
Uri blobUri = client.Uri;
// Act
var sasClient = InstrumentClient(new PageBlobClient(blobUri, new AzureSasCredential(sas), GetOptions()));
BlobProperties blobProperties = await sasClient.GetPropertiesAsync();
// Assert
Assert.IsNotNull(blobProperties);
}
[RecordedTest]
public async Task Ctor_AzureSasCredential_VerifyNoSasInUri()
{
// Arrange
await using DisposingContainer test = await GetTestContainerAsync();
string sas = GetContainerSas(test.Container.Name, BlobContainerSasPermissions.All).ToString();
Uri blobUri = test.Container.GetPageBlobClient("foo").Uri;
blobUri = new Uri(blobUri.ToString() + "?" + sas);
// Act
TestHelper.AssertExpectedException<ArgumentException>(
() => new PageBlobClient(blobUri, new AzureSasCredential(sas)),
e => e.Message.Contains($"You cannot use {nameof(AzureSasCredential)} when the resource URI also contains a Shared Access Signature"));
}
[RecordedTest]
public async Task Ctor_DefaultAudience()
{
// Arrange
await using DisposingContainer test = await GetTestContainerAsync();
PageBlobClient blob = InstrumentClient(test.Container.GetPageBlobClient(GetNewBlobName()));
await blob.CreateIfNotExistsAsync(Constants.KB);
// Act - Create new blob client with the OAuth Credential and Audience
BlobClientOptions options = GetOptionsWithAudience(BlobAudience.DefaultAudience);
BlobUriBuilder uriBuilder = new BlobUriBuilder(new Uri(Tenants.TestConfigOAuth.BlobServiceEndpoint))
{
BlobContainerName = blob.BlobContainerName,
BlobName = blob.Name
};
PageBlobClient aadBlob = InstrumentClient(new PageBlobClient(
uriBuilder.ToUri(),
Tenants.GetOAuthCredential(),
options));
// Assert
bool exists = await aadBlob.ExistsAsync();
Assert.IsTrue(exists);
}
[RecordedTest]
public async Task Ctor_CustomAudience()
{
// Arrange
await using DisposingContainer test = await GetTestContainerAsync();
PageBlobClient blob = InstrumentClient(test.Container.GetPageBlobClient(GetNewBlobName()));
await blob.CreateIfNotExistsAsync(Constants.KB);
// Act - Create new blob client with the OAuth Credential and Audience
BlobClientOptions options = GetOptionsWithAudience(new BlobAudience($"https://{test.Container.AccountName}.blob.core.windows.net/"));
BlobUriBuilder uriBuilder = new BlobUriBuilder(new Uri(Tenants.TestConfigOAuth.BlobServiceEndpoint))
{
BlobContainerName = blob.BlobContainerName,
BlobName = blob.Name
};
PageBlobClient aadBlob = InstrumentClient(new PageBlobClient(
uriBuilder.ToUri(),
Tenants.GetOAuthCredential(),
options));
// Assert
bool exists = await aadBlob.ExistsAsync();
Assert.IsTrue(exists);
}
[RecordedTest]
public async Task Ctor_StorageAccountAudience()
{
// Arrange
await using DisposingContainer test = await GetTestContainerAsync();
PageBlobClient blob = InstrumentClient(test.Container.GetPageBlobClient(GetNewBlobName()));
await blob.CreateIfNotExistsAsync(Constants.KB);
// Act - Create new blob client with the OAuth Credential and Audience
BlobClientOptions options = GetOptionsWithAudience(BlobAudience.CreateBlobServiceAccountAudience(test.Container.AccountName));
BlobUriBuilder uriBuilder = new BlobUriBuilder(new Uri(Tenants.TestConfigOAuth.BlobServiceEndpoint))
{
BlobContainerName = blob.BlobContainerName,
BlobName = blob.Name
};
PageBlobClient aadBlob = InstrumentClient(new PageBlobClient(
uriBuilder.ToUri(),
Tenants.GetOAuthCredential(),
options));
// Assert
bool exists = await aadBlob.ExistsAsync();
Assert.IsTrue(exists);
}
[RecordedTest]
public async Task Ctor_AudienceError()
{
// Arrange
await using DisposingContainer test = await GetTestContainerAsync();
PageBlobClient blob = InstrumentClient(test.Container.GetPageBlobClient(GetNewBlobName()));
await blob.CreateIfNotExistsAsync(Constants.KB);
// Act - Create new blob client with the OAuth Credential and Audience
BlobClientOptions options = GetOptionsWithAudience(new BlobAudience("https://badaudience.blob.core.windows.net"));
BlobUriBuilder uriBuilder = new BlobUriBuilder(new Uri(Tenants.TestConfigOAuth.BlobServiceEndpoint))
{
BlobContainerName = blob.BlobContainerName,
BlobName = blob.Name
};
PageBlobClient aadBlob = InstrumentClient(new PageBlobClient(
uriBuilder.ToUri(),
new MockCredential(),
options));
// Assert
await TestHelper.AssertExpectedExceptionAsync<RequestFailedException>(
aadBlob.ExistsAsync(),
e => Assert.AreEqual(BlobErrorCode.InvalidAuthenticationInfo.ToString(), e.ErrorCode));
}
[RecordedTest]
public async Task CreateAsync_Min()
{
await using DisposingContainer test = await GetTestContainerAsync();
// Arrange
PageBlobClient blob = InstrumentClient(test.Container.GetPageBlobClient(GetNewBlobName()));
// Act
Response<BlobContentInfo> response = await blob.CreateAsync(Constants.KB);
// Assert
// Ensure that we grab the whole ETag value from the service without removing the quotes
Assert.AreEqual(response.Value.ETag.ToString(), $"\"{response.GetRawResponse().Headers.ETag}\"");
Assert.IsNotNull(response.GetRawResponse().Headers.RequestId);
}
[RecordedTest]
[TestCase(nameof(PageBlobRequestConditions.IfSequenceNumberLessThanOrEqual))]
[TestCase(nameof(PageBlobRequestConditions.IfSequenceNumberLessThan))]
[TestCase(nameof(PageBlobRequestConditions.IfSequenceNumberEqual))]
public async Task CreateAsync_InvalidRequestConditions(string invalidCondition)
{
// Arrange
Uri uri = new Uri("https://www.doesntmatter.com");
PageBlobClient pageBlobClient = new PageBlobClient(uri, GetOptions());
PageBlobRequestConditions conditions = new PageBlobRequestConditions();
switch (invalidCondition)
{
case nameof(PageBlobRequestConditions.IfSequenceNumberLessThanOrEqual):
conditions.IfSequenceNumberLessThanOrEqual = 0;
break;
case nameof(PageBlobRequestConditions.IfSequenceNumberLessThan):
conditions.IfSequenceNumberLessThan = 0;
break;
case nameof(PageBlobRequestConditions.IfSequenceNumberEqual):
conditions.IfSequenceNumberEqual = 0;
break;
}
PageBlobCreateOptions options = new PageBlobCreateOptions
{
Conditions = conditions
};
// Act
await TestHelper.AssertExpectedExceptionAsync<ArgumentException>(
pageBlobClient.CreateAsync(
size: 0,
options),
e =>
{
Assert.IsTrue(e.Message.Contains($"Create does not support the {invalidCondition} condition(s)."));
Assert.IsTrue(e.Message.Contains("conditions"));
});
}
[RecordedTest]
[ServiceVersion(Min = BlobClientOptions.ServiceVersion.V2019_12_12)]
public async Task CreateAsync_Tags()
{
// Arrange
await using DisposingContainer test = await GetTestContainerAsync();
PageBlobClient blob = InstrumentClient(test.Container.GetPageBlobClient(GetNewBlobName()));
PageBlobCreateOptions options = new PageBlobCreateOptions
{
Tags = BuildTags()
};
// Act
await blob.CreateAsync(Constants.KB, options);
Response<GetBlobTagResult> response = await blob.GetTagsAsync();
// Assert
AssertDictionaryEquality(options.Tags, response.Value.Tags);
}
[RecordedTest]
public async Task CreateAsync_SequenceNumber()
{
await using DisposingContainer test = await GetTestContainerAsync();
// Arrange
PageBlobClient blob = InstrumentClient(test.Container.GetPageBlobClient(GetNewBlobName()));
// Act
await blob.CreateAsync(
size: Constants.KB,
sequenceNumber: 2);
// Assert
Response<BlobProperties> response = await blob.GetPropertiesAsync();
Assert.AreEqual(2, response.Value.BlobSequenceNumber);
}
[RecordedTest]
public async Task CreateAsync_Metadata()
{
await using DisposingContainer test = await GetTestContainerAsync();
// Arrange
IDictionary<string, string> metadata = BuildMetadata();
PageBlobClient blob = InstrumentClient(test.Container.GetPageBlobClient(GetNewBlobName()));
// Act
await blob.CreateAsync(Constants.KB, metadata: metadata);
// Assert
Response<BlobProperties> getPropertiesResponse = await blob.GetPropertiesAsync();
AssertDictionaryEquality(metadata, getPropertiesResponse.Value.Metadata);
Assert.AreEqual(BlobType.Page, getPropertiesResponse.Value.BlobType);
}
[RecordedTest]
public async Task CreateAsync_CPK()
{
await using DisposingContainer test = await GetTestContainerAsync();
// Arrange
PageBlobClient blob = InstrumentClient(test.Container.GetPageBlobClient(GetNewBlobName()));
CustomerProvidedKey customerProvidedKey = GetCustomerProvidedKey();
blob = InstrumentClient(blob.WithCustomerProvidedKey(customerProvidedKey));
// Act
Response<BlobContentInfo> response = await blob.CreateAsync(Constants.KB);
// Assert
Assert.AreEqual(customerProvidedKey.EncryptionKeyHash, response.Value.EncryptionKeySha256);
}
[RecordedTest]
[ServiceVersion(Min = BlobClientOptions.ServiceVersion.V2019_07_07)]
public async Task CreateAsync_EncryptionScope()
{
await using DisposingContainer test = await GetTestContainerAsync();
// Arrange
PageBlobClient blob = InstrumentClient(test.Container.GetPageBlobClient(GetNewBlobName()));
blob = InstrumentClient(blob.WithEncryptionScope(TestConfigDefault.EncryptionScope));
// Act
Response<BlobContentInfo> response = await blob.CreateAsync(Constants.KB);
// Assert
Assert.AreEqual(TestConfigDefault.EncryptionScope, response.Value.EncryptionScope);
}
[RecordedTest]
[ServiceVersion(Min = BlobClientOptions.ServiceVersion.V2019_12_12)]
public async Task CreateAsync_VersionId()
{
await using DisposingContainer test = await GetTestContainerAsync();
// Arrange
PageBlobClient blob = InstrumentClient(test.Container.GetPageBlobClient(GetNewBlobName()));
// Act
Response<BlobContentInfo> response = await blob.CreateAsync(Constants.KB);
// Assert
Assert.IsNotNull(response.Value.VersionId);
}
/// <summary>
/// Data for CreateAsync, GetPageRangesAsync, GetPageRangesDiffAsync, ResizeAsync, and
/// UpdateSequenceNumber AccessConditions tests.
/// </summary>
public IEnumerable<AccessConditionParameters> Reduced_AccessConditions_Data
=> new[]
{
new AccessConditionParameters(),
new AccessConditionParameters { IfModifiedSince = OldDate },
new AccessConditionParameters { IfUnmodifiedSince = NewDate },
new AccessConditionParameters { Match = ReceivedETag },
new AccessConditionParameters { NoneMatch = GarbageETag },
new AccessConditionParameters { LeaseId = ReceivedLeaseId }
};
[RecordedTest]
public async Task CreateAsync_AccessConditions()
{
var garbageLeaseId = GetGarbageLeaseId();
foreach (AccessConditionParameters parameters in Reduced_AccessConditions_Data)
{
await using DisposingContainer test = await GetTestContainerAsync();
// Arrange
// This PageBlob is intentionally created twice to test the PageBlobAccessConditions
PageBlobClient blob = await CreatePageBlobClientAsync(test.Container, Constants.KB);
parameters.Match = await SetupBlobMatchCondition(blob, parameters.Match);
parameters.LeaseId = await SetupBlobLeaseCondition(blob, parameters.LeaseId, garbageLeaseId);
PageBlobRequestConditions accessConditions = BuildAccessConditions(
parameters: parameters,
lease: true);
// Act
Response<BlobContentInfo> response = await blob.CreateAsync(
size: Constants.KB,
conditions: accessConditions);
// Assert
Assert.IsNotNull(response.GetRawResponse().Headers.RequestId);
}
}
/// <summary>
/// Data for CreateAsync, GetPageRangesAsync, and GetPageRangesDiffAsync AccessConditions Fail tests.
/// </summary>
public IEnumerable<AccessConditionParameters> GetReduced_AccessConditionsFail_Data(string garbageLeaseId)
=> new[]
{
new AccessConditionParameters { IfModifiedSince = NewDate },
new AccessConditionParameters { IfUnmodifiedSince = OldDate },
new AccessConditionParameters { Match = GarbageETag },
new AccessConditionParameters { NoneMatch = ReceivedETag },
new AccessConditionParameters { LeaseId = garbageLeaseId }
};
[RecordedTest]
public async Task CreateAsync_AccessConditionsFail()
{
var garbageLeaseId = GetGarbageLeaseId();
foreach (AccessConditionParameters parameters in GetReduced_AccessConditionsFail_Data(garbageLeaseId))
{
await using DisposingContainer test = await GetTestContainerAsync();
// Arrange
// This PageBlob is intentionally created twice to test the PageBlobAccessConditions
PageBlobClient blob = await CreatePageBlobClientAsync(test.Container, Constants.KB);
parameters.NoneMatch = await SetupBlobMatchCondition(blob, parameters.NoneMatch);
await SetupBlobLeaseCondition(blob, parameters.LeaseId, garbageLeaseId);
PageBlobRequestConditions accessConditions = BuildAccessConditions(
parameters: parameters,
lease: true);
// Act
await TestHelper.AssertExpectedExceptionAsync<RequestFailedException>(
blob.CreateAsync(
size: Constants.KB,
conditions: accessConditions),
actualException => Assert.IsTrue(true));
}
}
[RecordedTest]
[ServiceVersion(Min = BlobClientOptions.ServiceVersion.V2019_12_12)]
public async Task CreateAsync_IfTag()
{
// Arrange
await using DisposingContainer test = await GetTestContainerAsync();
PageBlobClient blob = InstrumentClient(test.Container.GetPageBlobClient(GetNewBlobName()));
await blob.CreateAsync(Constants.KB);
Dictionary<string, string> tags = new Dictionary<string, string>
{
{ "coolTag", "true" }
};
await blob.SetTagsAsync(tags);
PageBlobRequestConditions conditions = new PageBlobRequestConditions
{
TagConditions = "\"coolTag\" = 'true'"
};
// Act
await blob.CreateAsync(
Constants.KB,
conditions: conditions);
}
[RecordedTest]
[ServiceVersion(Min = BlobClientOptions.ServiceVersion.V2019_12_12)]
public async Task CreateAsync_IfTagFailed()
{
// Arrange
await using DisposingContainer test = await GetTestContainerAsync();
PageBlobClient blob = InstrumentClient(test.Container.GetPageBlobClient(GetNewBlobName()));
await blob.CreateAsync(Constants.KB);
PageBlobRequestConditions conditions = new PageBlobRequestConditions
{
TagConditions = "\"coolTag\" = 'true'"
};
// Act
await TestHelper.AssertExpectedExceptionAsync<RequestFailedException>(
blob.CreateAsync(
Constants.KB,
conditions: conditions),
e => Assert.AreEqual("ConditionNotMet", e.ErrorCode));
}
[RecordedTest]
public async Task CreateAsync_Headers()
{
var contentMD5 = MD5.Create().ComputeHash(GetRandomBuffer(16));
await using DisposingContainer test = await GetTestContainerAsync();
// Arrange
var headers = new BlobHttpHeaders
{
ContentType = ContentType,
ContentHash = contentMD5,
ContentEncoding = ContentEncoding,
ContentLanguage = ContentLanguage,
ContentDisposition = ContentDisposition,
CacheControl = CacheControl
};
PageBlobClient blob = InstrumentClient(test.Container.GetPageBlobClient(GetNewBlobName()));
// Act
await blob.CreateAsync(
size: Constants.KB,
httpHeaders: headers);
// Assert
Response<BlobProperties> response = await blob.GetPropertiesAsync();
Assert.AreEqual(ContentType, response.Value.ContentType);
TestHelper.AssertSequenceEqual(contentMD5, response.Value.ContentHash);
Assert.AreEqual(ContentEncoding, response.Value.ContentEncoding);
Assert.AreEqual(ContentLanguage, response.Value.ContentLanguage);
Assert.AreEqual(ContentDisposition, response.Value.ContentDisposition);
Assert.AreEqual(CacheControl, response.Value.CacheControl);
}
[RecordedTest]
public async Task CreateAsync_Error()
{
await using DisposingContainer test = await GetTestContainerAsync();
// Arrange
var invalidPageSize = 511;
PageBlobClient blob = InstrumentClient(test.Container.GetPageBlobClient(GetNewBlobName()));
// Act
await TestHelper.AssertExpectedExceptionAsync<RequestFailedException>(
blob.CreateAsync(invalidPageSize),
e =>
{
Assert.AreEqual("InvalidHeaderValue", e.ErrorCode);
Assert.AreEqual("The value for one of the HTTP headers is not in the correct format.",
e.Message.Split('\n')[0]);
});
}
[RecordedTest]
public async Task UploadPagesAsync()
{
await using DisposingContainer test = await GetTestContainerAsync();
// Arrange
PageBlobClient blob = await CreatePageBlobClientAsync(test.Container, 4 * Constants.KB);
var data = GetRandomBuffer(Constants.KB);
Response<PageInfo> response;
using (var stream = new MemoryStream(data))
{
// Act
response = await blob.UploadPagesAsync(
content: stream,
offset: Constants.KB);
}
// Assert
// Ensure that we grab the whole ETag value from the service without removing the quotes
Assert.AreEqual(response.Value.ETag.ToString(), $"\"{response.GetRawResponse().Headers.ETag}\"");
// Ensure we uploaded the pages correctly by downloading and checking the content against the upload content
var expectedData = new byte[4 * Constants.KB];
data.CopyTo(expectedData, Constants.KB);
Response<BlobDownloadInfo> downloadRepsonse = await blob.DownloadAsync(range: new HttpRange(0, 4 * Constants.KB));
var actualData = new byte[4 * Constants.KB];
using var actualStream = new MemoryStream(actualData);
await downloadRepsonse.Value.Content.CopyToAsync(actualStream);
TestHelper.AssertSequenceEqual(expectedData, actualData);
}
[RecordedTest]
public async Task UploadPagesAsync_CPK()
{
await using DisposingContainer test = await GetTestContainerAsync();
// Arrange
var blobName = GetNewBlobName();
PageBlobClient blob = InstrumentClient(test.Container.GetPageBlobClient(blobName));
CustomerProvidedKey customerProvidedKey = GetCustomerProvidedKey();
blob = InstrumentClient(blob.WithCustomerProvidedKey(customerProvidedKey));
var data = GetRandomBuffer(Constants.KB);
await blob.CreateIfNotExistsAsync(Constants.KB);
using var stream = new MemoryStream(data);
// Act
Response<PageInfo> response = await blob.UploadPagesAsync(
content: stream,
offset: 0);
// Assert
Assert.AreEqual(customerProvidedKey.EncryptionKeyHash, response.Value.EncryptionKeySha256);
}
[RecordedTest]
[ServiceVersion(Min = BlobClientOptions.ServiceVersion.V2019_07_07)]
public async Task UploadPagesAsync_EncryptionScope()
{
await using DisposingContainer test = await GetTestContainerAsync();
// Arrange
var blobName = GetNewBlobName();
PageBlobClient blob = InstrumentClient(test.Container.GetPageBlobClient(blobName));
blob = InstrumentClient(blob.WithEncryptionScope(TestConfigDefault.EncryptionScope));
var data = GetRandomBuffer(Constants.KB);
await blob.CreateIfNotExistsAsync(Constants.KB);
using var stream = new MemoryStream(data);
// Act
Response<PageInfo> response = await blob.UploadPagesAsync(
content: stream,
offset: 0);
// Assert
Assert.AreEqual(TestConfigDefault.EncryptionScope, response.Value.EncryptionScope);
}
[RecordedTest]
public async Task UploadPagesAsync_Error()
{
await using DisposingContainer test = await GetTestContainerAsync();
// Arrange
PageBlobClient blob = await CreatePageBlobClientAsync(test.Container, 4 * Constants.KB);
// Act
var data = GetRandomBuffer(Constants.KB);
using (var stream = new MemoryStream(data))
{
await TestHelper.AssertExpectedExceptionAsync<RequestFailedException>(
blob.UploadPagesAsync(stream, 5 * Constants.KB),
e => Assert.AreEqual("InvalidPageRange", e.ErrorCode));
}
}
[RecordedTest]
public async Task UploadPagesAsync_NullStream_Error()
{
await using DisposingContainer test = await GetTestContainerAsync();
// Arrange
PageBlobClient blob = InstrumentClient(test.Container.GetPageBlobClient(GetNewBlobName()));
// Act
using (var stream = (MemoryStream)null)
{
// Check if the correct param name that is causing the error is being returned
await TestHelper.AssertExpectedExceptionAsync<ArgumentNullException>(
blob.UploadPagesAsync(
content: stream,
offset: 0),
e => Assert.AreEqual("body", e.ParamName));
}
}
public IEnumerable<AccessConditionParameters> UploadClearAsync_AccessConditions_Data(bool noSequenceNumberConditions)
=> new[]
{
new AccessConditionParameters(),
new AccessConditionParameters { IfModifiedSince = OldDate },
new AccessConditionParameters { IfUnmodifiedSince = NewDate },
new AccessConditionParameters { Match = ReceivedETag },
new AccessConditionParameters { NoneMatch = GarbageETag },
new AccessConditionParameters { LeaseId = ReceivedLeaseId },
new AccessConditionParameters { SequenceNumberLT = noSequenceNumberConditions ? null : 5 },
new AccessConditionParameters { SequenceNumberLTE = noSequenceNumberConditions? null : 3 },
new AccessConditionParameters { SequenceNumberEqual = noSequenceNumberConditions ? null : 0 }
};
[RecordedTest]
public async Task UploadAsync_AccessConditions()
{
var garbageLeaseId = GetGarbageLeaseId();
foreach (AccessConditionParameters parameters in UploadClearAsync_AccessConditions_Data(noSequenceNumberConditions: false))
{
await using DisposingContainer test = await GetTestContainerAsync();
// Arrange
PageBlobClient blob = await CreatePageBlobClientAsync(test.Container, Constants.KB);
parameters.Match = await SetupBlobMatchCondition(blob, parameters.Match);
parameters.LeaseId = await SetupBlobLeaseCondition(blob, parameters.LeaseId, garbageLeaseId);
PageBlobRequestConditions accessConditions = BuildAccessConditions(
parameters: parameters,
lease: true,
sequenceNumbers: true);
var data = GetRandomBuffer(Constants.KB);
using (var stream = new MemoryStream(data))
{
// Act
Response<PageInfo> response = await blob.UploadPagesAsync(
content: stream,
offset: 0,
options: new PageBlobUploadPagesOptions
{
Conditions = accessConditions
});
// Assert
Assert.IsNotNull(response.GetRawResponse().Headers.RequestId);
}
}
}
public IEnumerable<AccessConditionParameters> GetUploadClearAsync_AccessConditionsFail_Data(string garbageLeaseId)
=> new[]
{
new AccessConditionParameters { IfModifiedSince = NewDate },
new AccessConditionParameters { IfUnmodifiedSince = OldDate },
new AccessConditionParameters { Match = GarbageETag },
new AccessConditionParameters { NoneMatch = ReceivedETag },
new AccessConditionParameters { LeaseId = garbageLeaseId },
new AccessConditionParameters { SequenceNumberLT = -1 },
new AccessConditionParameters { SequenceNumberLTE = -1 },
new AccessConditionParameters { SequenceNumberEqual = 100 }
};
[RecordedTest]
public async Task UploadAsync_AccessConditionsFail()
{
var garbageLeaseId = GetGarbageLeaseId();
foreach (AccessConditionParameters parameters in GetUploadClearAsync_AccessConditionsFail_Data(garbageLeaseId))
{
await using DisposingContainer test = await GetTestContainerAsync();
// Arrange
PageBlobClient blob = await CreatePageBlobClientAsync(test.Container, Constants.KB);
parameters.NoneMatch = await SetupBlobMatchCondition(blob, parameters.NoneMatch);
await SetupBlobLeaseCondition(blob, parameters.LeaseId, garbageLeaseId);
PageBlobRequestConditions accessConditions = BuildAccessConditions(
parameters: parameters,
lease: true,
sequenceNumbers: true);
var data = GetRandomBuffer(Constants.KB);
using (var stream = new MemoryStream(data))
{
// Act
await TestHelper.AssertExpectedExceptionAsync<RequestFailedException>(
blob.UploadPagesAsync(
content: stream,
offset: 0,
options: new PageBlobUploadPagesOptions
{
Conditions = accessConditions
}),
e => Assert.IsTrue(true));
}
}
}
[RecordedTest]
[ServiceVersion(Min = BlobClientOptions.ServiceVersion.V2019_12_12)]
public async Task UploadPagesAsync_IfTags()
{
await using DisposingContainer test = await GetTestContainerAsync();
// Arrange
PageBlobClient blob = await CreatePageBlobClientAsync(test.Container, 4 * Constants.KB);
Dictionary<string, string> tags = new Dictionary<string, string>
{
{ "coolTag", "true" }
};
await blob.SetTagsAsync(tags);
var data = GetRandomBuffer(Constants.KB);
using Stream stream = new MemoryStream(data);
PageBlobRequestConditions conditions = new PageBlobRequestConditions
{
TagConditions = "\"coolTag\" = 'true'"
};
// Act
await blob.UploadPagesAsync(
content: stream,
offset: Constants.KB,
options: new PageBlobUploadPagesOptions
{
Conditions = conditions
});
}
[RecordedTest]
[ServiceVersion(Min = BlobClientOptions.ServiceVersion.V2019_12_12)]
public async Task UploadPagesAsync_IfTagsFailed()
{
await using DisposingContainer test = await GetTestContainerAsync();
// Arrange
PageBlobClient blob = await CreatePageBlobClientAsync(test.Container, 4 * Constants.KB);
var data = GetRandomBuffer(Constants.KB);
using Stream stream = new MemoryStream(data);
PageBlobRequestConditions conditions = new PageBlobRequestConditions
{
TagConditions = "\"coolTag\" = 'true'"
};
// Act
await TestHelper.AssertExpectedExceptionAsync<RequestFailedException>(
blob.UploadPagesAsync(
content: stream,
offset: Constants.KB,
options: new PageBlobUploadPagesOptions
{
Conditions = conditions
}),
e => Assert.AreEqual("ConditionNotMet", e.ErrorCode));
}
[RecordedTest]
public async Task UploadPagesAsync_WithUnreliableConnection()
{
const int blobSize = 1 * Constants.MB;
await using DisposingContainer test = await GetTestContainerAsync();
var credentials = new StorageSharedKeyCredential(
TestConfigDefault.AccountName,
TestConfigDefault.AccountKey);
BlobContainerClient containerClientFaulty = InstrumentClient(
new BlobContainerClient(
test.Container.Uri,
credentials,
GetFaultyBlobConnectionOptions()));
// Arrange
var pageBlobName = GetNewBlobName();
PageBlobClient blobFaulty = InstrumentClient(containerClientFaulty.GetPageBlobClient(pageBlobName));
PageBlobClient blob = InstrumentClient(test.Container.GetPageBlobClient(pageBlobName));
await blob.CreateIfNotExistsAsync(blobSize)
.ConfigureAwait(false);
var offset = 0 * Constants.KB;
var data = GetRandomBuffer(blobSize);
var progressBag = new System.Collections.Concurrent.ConcurrentBag<long>();
var progressHandler = new Progress<long>(progress => progressBag.Add(progress));
var timesFaulted = 0;
// Act
using (var stream = new FaultyStream(
new MemoryStream(data),
256 * Constants.KB,
1,
new IOException("Simulated stream fault"),
() => timesFaulted++))
{
await blobFaulty.UploadPagesAsync(stream, offset, new PageBlobUploadPagesOptions
{
ProgressHandler = progressHandler
});
await WaitForProgressAsync(progressBag, data.LongLength);
Assert.IsTrue(progressBag.Count > 1, "Too few progress received");
// Changing from Assert.AreEqual because these don't always update fast enough
Assert.GreaterOrEqual(data.LongLength, progressBag.Max(), "Final progress has unexpected value");
}
// Assert
Response<BlobDownloadInfo> downloadResponse = await blob.DownloadAsync(
new HttpRange(offset, data.LongLength));
var actual = new MemoryStream();
await downloadResponse.Value.Content.CopyToAsync(actual);
TestHelper.AssertSequenceEqual(data, actual.ToArray());
Assert.AreNotEqual(0, timesFaulted);
}
[LiveOnly]
[Test]
public async Task UploadPagesAsync_ProgressReporting()
{
await using DisposingContainer test = await GetTestContainerAsync();
// Arrange
long blobSize = 4 * Constants.MB;
PageBlobClient blob = await CreatePageBlobClientAsync(test.Container, blobSize);
var data = GetRandomBuffer(blobSize);
TestProgress progress = new TestProgress();
using (var stream = new MemoryStream(data))
{
// Act
await blob.UploadPagesAsync(
content: stream,
offset: 0,
new PageBlobUploadPagesOptions
{
ProgressHandler = progress
});
}
// Assert
Assert.IsFalse(progress.List.Count == 0);
Assert.AreEqual(blobSize, progress.List[progress.List.Count - 1]);
}
[RecordedTest]
public async Task UploadPagesAsync_InvalidStreamPosition()
{
await using DisposingContainer test = await GetTestContainerAsync();
// Arrange
PageBlobClient blob = await CreatePageBlobClientAsync(test.Container, 4 * Constants.KB);
long size = Constants.KB;
byte[] data = GetRandomBuffer(size);
using Stream stream = new MemoryStream(data)
{
Position = size
};
// Act
await TestHelper.AssertExpectedExceptionAsync<ArgumentException>(