-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathTemporaryBlobContainer.cs
More file actions
622 lines (554 loc) · 34.7 KB
/
TemporaryBlobContainer.cs
File metadata and controls
622 lines (554 loc) · 34.7 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
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Identity;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace Arcus.Testing
{
/// <summary>
/// Represents the available options when the <see cref="TemporaryBlobContainer"/> is created.
/// </summary>
internal enum OnSetupContainer { LeaveExisted = 0, CleanIfExisted = 1, CleanIfMatched = 2 }
/// <summary>
/// Represents the available options when the <see cref="TemporaryBlobContainer"/> is cleaned.
/// </summary>
internal enum OnTeardownBlobs { CleanIfUpserted = 0, CleanAll = 1, CleanIfMatched = 2 }
/// <summary>
/// Represents the available options when the <see cref="TemporaryBlobContainer"/> is deleted.
/// </summary>
internal enum OnTeardownContainer { DeleteIfCreated = 0, DeleteIfExists = 1 }
/// <summary>
/// Represents the available options when creating a <see cref="TemporaryBlobContainer"/>.
/// </summary>
public class OnSetupBlobContainerOptions
{
private readonly List<Func<BlobItem, bool>> _filters = [];
/// <summary>
/// Gets the configurable setup option on what to do with existing Azure Blobs in the Azure Blob container upon the test fixture creation.
/// </summary>
internal OnSetupContainer Blobs { get; private set; } = OnSetupContainer.LeaveExisted;
/// <summary>
/// Configures the <see cref="TemporaryBlobContainer"/> to delete all the Azure Blobs upon the test fixture creation.
/// </summary>
/// <returns></returns>
public OnSetupBlobContainerOptions CleanAllBlobs()
{
Blobs = OnSetupContainer.CleanIfExisted;
return this;
}
/// <summary>
/// Configures the <see cref="TemporaryBlobContainer"/> to delete the Azure Blobs upon the test fixture creation that matched the configured <paramref name="filters"/>.
/// </summary>
/// <param name="filters">The filters to match the blobs in the Azure Blob container.</param>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="filters"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentException">Thrown when any of the <paramref name="filters"/> is <c>null</c>.</exception>>
public OnSetupBlobContainerOptions CleanMatchingBlobs(params Func<BlobItem, bool>[] filters)
{
ArgumentNullException.ThrowIfNull(filters);
if (Array.Exists(filters, f => f is null))
{
throw new ArgumentException("Requires all filters to be non-null", nameof(filters));
}
Blobs = OnSetupContainer.CleanIfMatched;
_filters.AddRange(filters);
return this;
}
/// <summary>
/// (default) Configures the <see cref="TemporaryBlobContainer"/> to leave all Azure Blobs untouched
/// that already existed upon the test fixture creation, when there was already an Azure Blob container available.
/// </summary>
public OnSetupBlobContainerOptions LeaveAllBlobs()
{
Blobs = OnSetupContainer.LeaveExisted;
return this;
}
/// <summary>
/// Determines whether the given <paramref name="blob"/> matches the configured filter.
/// </summary>
/// <param name="blob">The blob to match the filter against.</param>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="blob"/> is <c>null</c>.</exception>
internal bool IsMatched(BlobItem blob)
{
ArgumentNullException.ThrowIfNull(blob);
return Blobs switch
{
OnSetupContainer.LeaveExisted => false,
OnSetupContainer.CleanIfExisted => true,
OnSetupContainer.CleanIfMatched => _filters.Exists(filter => filter(blob)),
_ => false
};
}
}
/// <summary>
/// Represents the available options when deleting a <see cref="TemporaryBlobContainer"/>.
/// </summary>
public class OnTeardownBlobContainerOptions
{
private readonly List<Func<BlobItem, bool>> _filters = [];
/// <summary>
/// Gets the configurable option on what to do with unlinked Azure Blobs in the Azure Blob container upon the disposal of the test fixture.
/// </summary>
internal OnTeardownBlobs Blobs { get; private set; } = OnTeardownBlobs.CleanIfUpserted;
/// <summary>
/// Gets the configurable option on what to do with the Azure Blob container upon the disposal of the test fixture.
/// </summary>
internal OnTeardownContainer Container { get; private set; } = OnTeardownContainer.DeleteIfCreated;
/// <summary>
/// (default for cleaning blobs) Configures the <see cref="TemporaryBlobContainer"/> to only delete the Azure Blobs upon disposal
/// if the blob was upserted by the test fixture (using <see cref="TemporaryBlobContainer.UpsertBlobFileAsync(string,BinaryData,CancellationToken)"/>).
/// </summary>
[Obsolete("Will be removed in v3, please use " + nameof(CleanUpsertedBlobs) + " instead that provides exactly the same on-teardown functionality", DiagnosticId = ObsoleteDefaults.DiagnosticId)]
public OnTeardownBlobContainerOptions CleanCreatedBlobs()
{
return CleanUpsertedBlobs();
}
/// <summary>
/// (default for cleaning blobs) Configures the <see cref="TemporaryBlobContainer"/> to only delete the Azure Blobs upon disposal
/// if the blob was upserted by the test fixture (using <see cref="TemporaryBlobContainer.UpsertBlobFileAsync(string,BinaryData,CancellationToken)"/>).
/// </summary>
public OnTeardownBlobContainerOptions CleanUpsertedBlobs()
{
Blobs = OnTeardownBlobs.CleanIfUpserted;
return this;
}
/// <summary>
/// Configures the <see cref="TemporaryBlobContainer"/> to delete all the blobs upon disposal - even if the test fixture didn't upload them.
/// </summary>
public OnTeardownBlobContainerOptions CleanAllBlobs()
{
Blobs = OnTeardownBlobs.CleanAll;
return this;
}
/// <summary>
/// Configures the <see cref="TemporaryBlobContainer"/> to delete the blobs upon disposal that matched the configured <paramref name="filters"/>.
/// </summary>
/// <remarks>
/// <para>⚡ The matching of blobs only happens on Azure Blobs instances that were created outside the scope of the test fixture.</para>
/// <para>⚡ All Blobs created by the test fixture will be deleted upon disposal, regardless of the filters.
/// This follows the 'clean environment' principle where the test fixture should clean up after itself and not linger around any state it created.</para>
/// </remarks>
/// <param name="filters">The filters to match the blobs in the Azure Blob container.</param>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="filters"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentException">Thrown when any of the <paramref name="filters"/> is <c>null</c>.</exception>
public OnTeardownBlobContainerOptions CleanMatchingBlobs(params Func<BlobItem, bool>[] filters)
{
ArgumentNullException.ThrowIfNull(filters);
if (Array.Exists(filters, f => f is null))
{
throw new ArgumentException("Requires all filters to be non-null", nameof(filters));
}
Blobs = OnTeardownBlobs.CleanIfMatched;
_filters.AddRange(filters);
return this;
}
/// <summary>
/// (default for deleting container) Configures the <see cref="TemporaryBlobContainer"/> to only delete the Azure Blob container upon disposal if the test fixture created the container.
/// </summary>
public OnTeardownBlobContainerOptions DeleteCreatedContainer()
{
Container = OnTeardownContainer.DeleteIfCreated;
return this;
}
/// <summary>
/// Configures the <see cref="TemporaryBlobContainer"/> to delete the Azure Blob container upon disposal, even if it already existed previously - outside the fixture's scope.
/// </summary>
public OnTeardownBlobContainerOptions DeleteExistingContainer()
{
Container = OnTeardownContainer.DeleteIfExists;
return this;
}
/// <summary>
/// Determines whether the given <paramref name="blob"/> should be deleted upon the disposal of the <see cref="TemporaryBlobContainer"/>.
/// </summary>
/// <param name="blob">The blob to match the filter against.</param>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="blob"/> is <c>null</c>.</exception>
internal bool IsMatched(BlobItem blob)
{
ArgumentNullException.ThrowIfNull(blob);
return Blobs switch
{
OnTeardownBlobs.CleanAll => true,
OnTeardownBlobs.CleanIfMatched => _filters.Exists(filter => filter(blob)),
_ => false
};
}
}
/// <summary>
/// Represents the available options when creating a <see cref="TemporaryBlobContainer"/>.
/// </summary>
public class TemporaryBlobContainerOptions
{
/// <summary>
/// Gets the additional options to manipulate the creation of the <see cref="TemporaryBlobContainer"/>.
/// </summary>
public OnSetupBlobContainerOptions OnSetup { get; } = new OnSetupBlobContainerOptions().LeaveAllBlobs();
/// <summary>
/// Gets the additional options to manipulate the deletion of the <see cref="TemporaryBlobContainer"/>.
/// </summary>
public OnTeardownBlobContainerOptions OnTeardown { get; } = new OnTeardownBlobContainerOptions().CleanUpsertedBlobs().DeleteCreatedContainer();
}
/// <summary>
/// Represents a temporary Azure Blob container that will be deleted after the instance is disposed.
/// </summary>
public class TemporaryBlobContainer : IAsyncDisposable
{
private readonly BlobContainerClient _containerClient;
private readonly bool _createdByUs;
private readonly Collection<TemporaryBlobFile> _blobs = [];
private readonly TemporaryBlobContainerOptions _options;
private readonly DisposableCollection _disposables;
private readonly ILogger _logger;
private TemporaryBlobContainer(
BlobContainerClient containerClient,
bool createdByUs,
TemporaryBlobContainerOptions options,
ILogger logger)
{
ArgumentNullException.ThrowIfNull(containerClient);
ArgumentNullException.ThrowIfNull(options);
_containerClient = containerClient;
_createdByUs = createdByUs;
_options = options;
_logger = logger ?? NullLogger.Instance;
_disposables = new DisposableCollection(_logger);
}
/// <summary>
/// Gets the name of the temporary Azure Blob container currently in storage.
/// </summary>
/// <exception cref="ObjectDisposedException">Thrown when the test fixture was already teared down.</exception>
public string Name => Client.Name;
/// <summary>
/// Gets the <see cref="BlobContainerClient"/> instance that represents the temporary Azure Blob container.
/// </summary>
/// <exception cref="ObjectDisposedException">Thrown when the test fixture was already teared down.</exception>
public BlobContainerClient Client
{
get
{
ObjectDisposedException.ThrowIf(_disposables.IsDisposed, this);
return _containerClient;
}
}
/// <summary>
/// Gets the additional options to manipulate the deletion of the <see cref="TemporaryBlobContainer"/>.
/// </summary>
/// <exception cref="ObjectDisposedException">Thrown when the test fixture was already teared down.</exception>
public OnTeardownBlobContainerOptions OnTeardown
{
get
{
ObjectDisposedException.ThrowIf(_disposables.IsDisposed, this);
return _options.OnTeardown;
}
}
/// <summary>
/// Creates a new instance of the <see cref="TemporaryBlobContainer"/> which creates a new Azure Blob Storage container if it doesn't exist yet.
/// </summary>
/// <remarks>
/// <para>⚡ Uses <see cref="DefaultAzureCredential"/> to authenticate with Azure Blob Storage.</para>
/// </remarks>
/// <param name="accountName">The name of the Azure Storage account to create the temporary Azure Blob container in.</param>
/// <param name="containerName">The name of the Azure Blob container to create.</param>
/// <param name="logger">The logger to write diagnostic messages during the lifetime of the Azure Blob container.</param>
/// <exception cref="ArgumentException">Thrown when the <paramref name="accountName"/> or <paramref name="containerName"/> is blank.</exception>
/// <exception cref="RequestFailedException">Thrown when the interaction with Azure failed.</exception>
[Obsolete("Will be removed in v3, please use the " + nameof(CreateIfNotExistsAsync) + " overload instead that provides cancellation token support", DiagnosticId = ObsoleteDefaults.DiagnosticId)]
public static Task<TemporaryBlobContainer> CreateIfNotExistsAsync(string accountName, string containerName, ILogger logger)
{
return CreateIfNotExistsAsync(accountName, containerName, logger, CancellationToken.None);
}
/// <summary>
/// Creates a new instance of the <see cref="TemporaryBlobContainer"/> which creates a new Azure Blob Storage container if it doesn't exist yet.
/// </summary>
/// <remarks>
/// <para>⚡ Uses <see cref="DefaultAzureCredential"/> to authenticate with Azure Blob Storage.</para>
/// </remarks>
/// <param name="accountName">The name of the Azure Storage account to create the temporary Azure Blob container in.</param>
/// <param name="containerName">The name of the Azure Blob container to create.</param>
/// <param name="logger">The logger to write diagnostic messages during the lifetime of the Azure Blob container.</param>
/// <param name="cancellationToken">The optional token to propagate notifications that the operation should be cancelled.</param>
/// <exception cref="ArgumentException">Thrown when the <paramref name="accountName"/> or <paramref name="containerName"/> is blank.</exception>
/// <exception cref="RequestFailedException">Thrown when the interaction with Azure failed.</exception>
public static Task<TemporaryBlobContainer> CreateIfNotExistsAsync(string accountName, string containerName, ILogger logger, CancellationToken cancellationToken)
{
return CreateIfNotExistsAsync(accountName, containerName, logger, configureOptions: null, cancellationToken);
}
/// <summary>
/// Creates a new instance of the <see cref="TemporaryBlobContainer"/> which creates a new Azure Blob Storage container if it doesn't exist yet.
/// </summary>
/// <remarks>
/// <para>⚡ Uses <see cref="DefaultAzureCredential"/> to authenticate with Azure Blob Storage.</para>
/// </remarks>
/// <param name="accountName">The name of the Azure Storage account to create the temporary Azure Blob container in.</param>
/// <param name="containerName">The name of the Azure Blob container to create.</param>
/// <param name="logger">The logger to write diagnostic messages during the lifetime of the Azure Blob container.</param>
/// <param name="configureOptions">The additional options to manipulate the behavior of the test fixture during its lifetime.</param>
/// <exception cref="ArgumentException">Thrown when the <paramref name="accountName"/> or <paramref name="containerName"/> is blank.</exception>
/// <exception cref="RequestFailedException">Thrown when the interaction with Azure failed.</exception>
[Obsolete("Will be removed in v3, please use the " + nameof(CreateIfNotExistsAsync) + " overload instead that provides cancellation token support", DiagnosticId = ObsoleteDefaults.DiagnosticId)]
public static Task<TemporaryBlobContainer> CreateIfNotExistsAsync(
string accountName,
string containerName,
ILogger logger,
Action<TemporaryBlobContainerOptions> configureOptions)
{
return CreateIfNotExistsAsync(accountName, containerName, logger, configureOptions, CancellationToken.None);
}
/// <summary>
/// Creates a new instance of the <see cref="TemporaryBlobContainer"/> which creates a new Azure Blob Storage container if it doesn't exist yet.
/// </summary>
/// <remarks>
/// <para>⚡ Uses <see cref="DefaultAzureCredential"/> to authenticate with Azure Blob Storage.</para>
/// </remarks>
/// <param name="accountName">The name of the Azure Storage account to create the temporary Azure Blob container in.</param>
/// <param name="containerName">The name of the Azure Blob container to create.</param>
/// <param name="logger">The logger to write diagnostic messages during the lifetime of the Azure Blob container.</param>
/// <param name="configureOptions">The additional options to manipulate the behavior of the test fixture during its lifetime.</param>
/// <param name="cancellationToken">The optional token to propagate notifications that the operation should be cancelled.</param>
/// <exception cref="ArgumentException">Thrown when the <paramref name="accountName"/> or <paramref name="containerName"/> is blank.</exception>
/// <exception cref="RequestFailedException">Thrown when the interaction with Azure failed.</exception>
public static Task<TemporaryBlobContainer> CreateIfNotExistsAsync(
string accountName,
string containerName,
ILogger logger,
Action<TemporaryBlobContainerOptions> configureOptions,
CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrWhiteSpace(accountName);
ArgumentException.ThrowIfNullOrWhiteSpace(containerName);
cancellationToken.ThrowIfCancellationRequested();
var blobContainerUri = new Uri($"https://{accountName}.blob.core.windows.net/{containerName}");
var containerClient = new BlobContainerClient(blobContainerUri, new DefaultAzureCredential());
return CreateIfNotExistsAsync(containerClient, logger, configureOptions, cancellationToken);
}
/// <summary>
/// Creates a new instance of the <see cref="TemporaryBlobContainer"/> which creates a new Azure Blob Storage container if it doesn't exist yet.
/// </summary>
/// <param name="containerClient">The client to interact with the Azure Blob Storage container.</param>
/// <param name="logger">The logger to write diagnostic messages during the creation of the Azure Blob container.</param>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="containerClient"/> is <c>null</c>.</exception>
/// <exception cref="RequestFailedException">Thrown when the interaction with Azure failed.</exception>
[Obsolete("Will be removed in v3, please use the " + nameof(CreateIfNotExistsAsync) + " overload instead that provides cancellation token support", DiagnosticId = ObsoleteDefaults.DiagnosticId)]
public static Task<TemporaryBlobContainer> CreateIfNotExistsAsync(BlobContainerClient containerClient, ILogger logger)
{
return CreateIfNotExistsAsync(containerClient, logger, CancellationToken.None);
}
/// <summary>
/// Creates a new instance of the <see cref="TemporaryBlobContainer"/> which creates a new Azure Blob Storage container if it doesn't exist yet.
/// </summary>
/// <param name="containerClient">The client to interact with the Azure Blob Storage container.</param>
/// <param name="logger">The logger to write diagnostic messages during the creation of the Azure Blob container.</param>
/// <param name="cancellationToken">The optional token to propagate notifications that the operation should be cancelled.</param>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="containerClient"/> is <c>null</c>.</exception>
/// <exception cref="RequestFailedException">Thrown when the interaction with Azure failed.</exception>
public static Task<TemporaryBlobContainer> CreateIfNotExistsAsync(BlobContainerClient containerClient, ILogger logger, CancellationToken cancellationToken)
{
return CreateIfNotExistsAsync(containerClient, logger, configureOptions: null, cancellationToken);
}
/// <summary>
/// Creates a new instance of the <see cref="TemporaryBlobContainer"/> which creates a new Azure Blob Storage container if it doesn't exist yet.
/// </summary>
/// <param name="containerClient">The client to interact with the Azure Blob Storage container.</param>
/// <param name="logger">The logger to write diagnostic messages during the creation of the Azure Blob container.</param>
/// <param name="configureOptions">The additional options to manipulate the behavior of the test fixture during its lifetime.</param>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="containerClient"/> is <c>null</c>.</exception>
/// <exception cref="RequestFailedException">Thrown when the interaction with Azure failed.</exception>
[Obsolete("Will be removed in v3, please use the " + nameof(CreateIfNotExistsAsync) + " overload instead that provides cancellation token support", DiagnosticId = ObsoleteDefaults.DiagnosticId)]
public static Task<TemporaryBlobContainer> CreateIfNotExistsAsync(
BlobContainerClient containerClient,
ILogger logger,
Action<TemporaryBlobContainerOptions> configureOptions)
{
return CreateIfNotExistsAsync(containerClient, logger, configureOptions, CancellationToken.None);
}
/// <summary>
/// Creates a new instance of the <see cref="TemporaryBlobContainer"/> which creates a new Azure Blob Storage container if it doesn't exist yet.
/// </summary>
/// <param name="containerClient">The client to interact with the Azure Blob Storage container.</param>
/// <param name="logger">The logger to write diagnostic messages during the creation of the Azure Blob container.</param>
/// <param name="configureOptions">The additional options to manipulate the behavior of the test fixture during its lifetime.</param>
/// <param name="cancellationToken">The optional token to propagate notifications that the operation should be cancelled.</param>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="containerClient"/> is <c>null</c>.</exception>
/// <exception cref="RequestFailedException">Thrown when the interaction with Azure failed.</exception>
public static async Task<TemporaryBlobContainer> CreateIfNotExistsAsync(
BlobContainerClient containerClient,
ILogger logger,
Action<TemporaryBlobContainerOptions> configureOptions,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(containerClient);
cancellationToken.ThrowIfCancellationRequested();
logger ??= NullLogger.Instance;
var options = new TemporaryBlobContainerOptions();
configureOptions?.Invoke(options);
bool createdByUs = await EnsureContainerCreatedAsync(containerClient, logger, cancellationToken).ConfigureAwait(false);
await CleanBlobContainerUponCreationAsync(containerClient, options, logger, cancellationToken).ConfigureAwait(false);
return new TemporaryBlobContainer(containerClient, createdByUs, options, logger);
}
private static async Task<bool> EnsureContainerCreatedAsync(BlobContainerClient containerClient, ILogger logger, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
bool createdByUs = false;
if (!await containerClient.ExistsAsync(cancellationToken).ConfigureAwait(false))
{
logger.LogSetupCreateNewContainer(containerClient.Name, containerClient.AccountName);
await containerClient.CreateIfNotExistsAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
createdByUs = true;
}
else
{
logger.LogSetupUseExistingContainer(containerClient.Name, containerClient.AccountName);
}
return createdByUs;
}
/// <summary>
/// Uploads a temporary blob to the Azure Blob container.
/// </summary>
/// <param name="blobName">The name of the blob to upload.</param>
/// <param name="blobContent">The content of the blob to upload.</param>
/// <exception cref="ArgumentException">Thrown when the <paramref name="blobName"/> is blank.</exception>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="blobContent"/> is <c>null</c>.</exception>
[Obsolete("Will be removed in v3, please use the " + nameof(UpsertBlobFileAsync) + "instead that provides exactly the same functionality with cancellation token support", DiagnosticId = ObsoleteDefaults.DiagnosticId)]
public Task<BlobClient> UploadBlobAsync(string blobName, BinaryData blobContent)
{
return UpsertBlobFileAsync(blobName, blobContent);
}
/// <summary>
/// Uploads a new or replaces an existing blob in the Azure Blob container (a.k.a. UPSERT).
/// </summary>
/// <remarks>
/// ⚡ Any blob files upserted via this call will always be deleted (if new) or reverted (if existing)
/// when the <see cref="TemporaryBlobContainer"/> is disposed.
/// </remarks>
/// <param name="blobName">The name of the blob to upload.</param>
/// <param name="blobContent">The content of the blob to upload.</param>
/// <exception cref="ObjectDisposedException">Thrown when the test fixture was already teared down.</exception>
/// <exception cref="ArgumentException">Thrown when the <paramref name="blobName"/> is blank.</exception>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="blobContent"/> is <c>null</c>.</exception>
/// <exception cref="RequestFailedException">Thrown when the interaction with Azure failed.</exception>
[Obsolete("Will be removed in v3, please use the " + nameof(UpsertBlobFileAsync) + " overload instead that provides cancellation token support", DiagnosticId = ObsoleteDefaults.DiagnosticId)]
public Task<BlobClient> UpsertBlobFileAsync(string blobName, BinaryData blobContent)
{
return UpsertBlobFileAsync(blobName, blobContent, CancellationToken.None);
}
/// <summary>
/// Uploads a new or replaces an existing blob in the Azure Blob container (a.k.a. UPSERT).
/// </summary>
/// <remarks>
/// ⚡ Any blob files upserted via this call will always be deleted (if new) or reverted (if existing)
/// when the <see cref="TemporaryBlobContainer"/> is disposed.
/// </remarks>
/// <param name="blobName">The name of the blob to upload.</param>
/// <param name="blobContent">The content of the blob to upload.</param>
/// <param name="cancellationToken">The optional token to propagate notifications that the operation should be cancelled.</param>
/// <exception cref="ObjectDisposedException">Thrown when the test fixture was already teared down.</exception>
/// <exception cref="ArgumentException">Thrown when the <paramref name="blobName"/> is blank.</exception>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="blobContent"/> is <c>null</c>.</exception>
/// <exception cref="RequestFailedException">Thrown when the interaction with Azure failed.</exception>
public async Task<BlobClient> UpsertBlobFileAsync(string blobName, BinaryData blobContent, CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposables.IsDisposed, this);
ArgumentException.ThrowIfNullOrWhiteSpace(blobName);
ArgumentNullException.ThrowIfNull(blobContent);
cancellationToken.ThrowIfCancellationRequested();
BlobClient blobClient = _containerClient.GetBlobClient(blobName);
_blobs.Add(await TemporaryBlobFile.UpsertFileAsync(blobClient, blobContent, _logger, cancellationToken).ConfigureAwait(false));
return blobClient;
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources asynchronously.
/// </summary>
/// <returns>A task that represents the asynchronous dispose operation.</returns>
public async ValueTask DisposeAsync()
{
if (_disposables.IsDisposed)
{
return;
}
await using (_disposables.ConfigureAwait(false))
{
_disposables.AddRange(_blobs);
_disposables.Add(AsyncDisposable.Create(async () =>
{
await CleanBlobContainerUponDeletionAsync(_containerClient, _options, _logger).ConfigureAwait(false);
}));
if (_createdByUs || _options.OnTeardown.Container is OnTeardownContainer.DeleteIfExists)
{
_disposables.Add(AsyncDisposable.Create(async () =>
{
_logger.LogTeardownDeleteContainer(_containerClient.Name, _containerClient.AccountName);
await _containerClient.DeleteIfExistsAsync().ConfigureAwait(false);
}));
}
}
GC.SuppressFinalize(this);
}
private static async Task CleanBlobContainerUponCreationAsync(
BlobContainerClient containerClient,
TemporaryBlobContainerOptions options,
ILogger logger,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (options.OnSetup.Blobs is OnSetupContainer.LeaveExisted)
{
return;
}
#pragma warning disable S3267 // Sonar recommends LINQ on loops, but Microsoft has no Async LINQ built-in, besides the additional/outdated `System.Linq.Async` package.
await foreach (BlobItem blob in containerClient.GetBlobsAsync(cancellationToken: cancellationToken).ConfigureAwait(false))
#pragma warning restore
{
if (options.OnSetup.IsMatched(blob))
{
logger.LogSetupDeleteFile(blob.Name, containerClient.AccountName, containerClient.Name);
await containerClient.GetBlobClient(blob.Name)
.DeleteIfExistsAsync(cancellationToken: cancellationToken)
.ConfigureAwait(false);
}
}
}
private static async Task CleanBlobContainerUponDeletionAsync(BlobContainerClient containerClient, TemporaryBlobContainerOptions options, ILogger logger)
{
if (options.OnTeardown.Blobs is OnTeardownBlobs.CleanIfUpserted)
{
return;
}
#pragma warning disable S3267 // Sonar recommends LINQ on loops, but Microsoft has no Async LINQ built-in, besides the additional/outdated `System.Linq.Async` package.
await foreach (BlobItem blob in containerClient.GetBlobsAsync().ConfigureAwait(false))
#pragma warning restore
{
if (options.OnTeardown.IsMatched(blob))
{
logger.LogTeardownDeleteFile(blob.Name, containerClient.AccountName, containerClient.Name);
await containerClient.GetBlobClient(blob.Name).DeleteIfExistsAsync().ConfigureAwait(false);
}
}
}
}
internal static partial class TempBlobContainerILoggerExtensions
{
private const LogLevel SetupTeardownLogLevel = LogLevel.Debug;
[LoggerMessage(
Level = SetupTeardownLogLevel,
Message = "[Test:Setup] Create new Azure Blob container '{ContainerName}' in account '{AccountName}'")]
internal static partial void LogSetupCreateNewContainer(this ILogger logger, string containerName, string accountName);
[LoggerMessage(
Level = SetupTeardownLogLevel,
Message = "[Test:Setup] Use already existing Azure Blob container '{ContainerName}' in account '{AccountName}'")]
internal static partial void LogSetupUseExistingContainer(this ILogger logger, string containerName, string accountName);
[LoggerMessage(
Level = SetupTeardownLogLevel,
Message = "[Test:Setup] Delete Azure Blob file '{BlobName}' from container '{AccountName}/{ContainerName}'")]
internal static partial void LogSetupDeleteFile(this ILogger logger, string blobName, string accountName, string containerName);
[LoggerMessage(
Level = SetupTeardownLogLevel,
Message = "[Test:Teardown] Delete Azure Blob container '{ContainerName}' from account '{AccountName}'")]
internal static partial void LogTeardownDeleteContainer(this ILogger logger, string containerName, string accountName);
}
}