Skip to content

Commit 1fadbd9

Browse files
authored
Tests | Move fixtures to common project (#3402)
1 parent b9b9153 commit 1fadbd9

18 files changed

+562
-517
lines changed

src/Microsoft.Data.SqlClient/tests/Common/Common.csproj

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,4 +51,10 @@
5151
</ContentWithTargetPath>
5252
</ItemGroup>
5353

54+
<!-- Fixture-specific References -->
55+
<ItemGroup>
56+
<PackageReference Include="Azure.Identity" />
57+
<PackageReference Include="Azure.Security.KeyVault.Keys" />
58+
</ItemGroup>
59+
5460
</Project>
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for more information.using System;
4+
5+
using System;
6+
using System.Collections.Generic;
7+
using Azure.Core;
8+
using Azure.Security.KeyVault.Keys;
9+
10+
namespace Microsoft.Data.SqlClient.Tests.Common.Fixtures;
11+
12+
/// <summary>
13+
/// Provides a base class for managing Azure Key Vault keys in test fixtures.
14+
/// </summary>
15+
/// <remarks>
16+
/// This class simplifies the creation and cleanup of RSA keys in an Azure Key Vault during testing
17+
/// scenarios. It ensures that any keys created during the fixture's lifetime are properly deleted when the fixture is
18+
/// disposed.
19+
/// </remarks>
20+
public abstract class AzureKeyVaultKeyFixtureBase : IDisposable
21+
{
22+
private readonly KeyClient _keyClient;
23+
private readonly Random _randomGenerator;
24+
25+
private readonly List<KeyVaultKey> _createdKeys = new List<KeyVaultKey>();
26+
27+
protected AzureKeyVaultKeyFixtureBase(Uri keyVaultUri, TokenCredential keyVaultToken)
28+
{
29+
_keyClient = new KeyClient(keyVaultUri, keyVaultToken);
30+
_randomGenerator = new Random();
31+
}
32+
33+
protected Uri CreateKey(string name, int keySize)
34+
{
35+
CreateRsaKeyOptions createOptions = new CreateRsaKeyOptions(GenerateUniqueName(name)) { KeySize = keySize };
36+
KeyVaultKey created = _keyClient.CreateRsaKey(createOptions);
37+
38+
_createdKeys.Add(created);
39+
return created.Id;
40+
}
41+
42+
private string GenerateUniqueName(string name)
43+
{
44+
byte[] rndBytes = new byte[16];
45+
46+
_randomGenerator.NextBytes(rndBytes);
47+
return name + "-" + BitConverter.ToString(rndBytes);
48+
}
49+
50+
public void Dispose()
51+
{
52+
Dispose(true);
53+
GC.SuppressFinalize(this);
54+
}
55+
56+
protected virtual void Dispose(bool disposing)
57+
{
58+
foreach (KeyVaultKey key in _createdKeys)
59+
{
60+
try
61+
{
62+
_keyClient.StartDeleteKey(key.Name).WaitForCompletion();
63+
}
64+
catch (Exception)
65+
{
66+
continue;
67+
}
68+
}
69+
}
70+
}

0 commit comments

Comments
 (0)