Skip to content

Commit

Permalink
Shorten code required to instrument options (#15698)
Browse files Browse the repository at this point in the history
Fixes: #15692
  • Loading branch information
pakrym authored and JoshLove-msft committed Oct 22, 2020
1 parent 315b1df commit 88f5130
Show file tree
Hide file tree
Showing 37 changed files with 150 additions and 90 deletions.
2 changes: 1 addition & 1 deletion common/ManagementTestShared/ManagementRecordedTestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ protected ValueTask<Response<T>> WaitForCompletionAsync<T>(Operation<T> operatio

protected ResourcesManagementClient GetResourceManagementClient()
{
var options = Recording.InstrumentClientOptions(new ResourcesManagementClientOptions());
var options = InstrumentClientOptions(new ResourcesManagementClientOptions());
CleanupPolicy = new ResourceGroupCleanupPolicy();
options.AddPolicy(CleanupPolicy, HttpPipelinePosition.PerCall);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using Azure.Core;
using Azure.Core.TestFramework;

namespace Azure.AI.AnomalyDetector.Tests
{
public class AnomalyDetectorLiveTestBase : RecordedTestBase<AnomalyDetectorTestEnvironment>
{
public AnomalyDetectorLiveTestBase(bool isAsync) : base(isAsync)
{
Sanitizer = new AnomalyDetectorRecordedTestSanitizer();
}

/// <summary>
/// Creates a <see cref="AnomalyDetectorClient" /> with the endpoint and API key provided via environment
/// variables and instruments it to make use of the Azure Core Test Framework functionalities.
/// </summary>
/// <param name="useTokenCredential">Whether or not to use a <see cref="TokenCredential"/> to authenticate. An <see cref="AzureKeyCredential"/> is used by default.</param>
/// <param name="apiKey">The API key to use for authentication. Defaults to <see cref="AnomalyDetectorTestEnvironment.ApiKey"/>.</param>
/// <param name="skipInstrumenting">Whether or not instrumenting should be skipped. Avoid skipping it as much as possible.</param>
/// <returns>The instrumented <see cref="AnomalyDetectorClient" />.</returns>
protected AnomalyDetectorClient CreateAnomalyDetectorClient(bool useTokenCredential = false, string apiKey = default, bool skipInstrumenting = false)
{
var endpoint = new Uri(TestEnvironment.Endpoint);
var options = InstrumentClientOptions(new AnomalyDetectorClientOptions());
AnomalyDetectorClient client;

if (useTokenCredential)
{
client = new AnomalyDetectorClient(endpoint, TestEnvironment.Credential, options);
}
else
{
var credential = new AzureKeyCredential(apiKey ?? TestEnvironment.ApiKey);
client = new AnomalyDetectorClient(endpoint, credential, options);
}

return skipInstrumenting ? client : InstrumentClient(client);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,15 @@ private ConfigurationClient GetClient()
connectionString = connectionString.Replace(";Secret=;", ";Secret=Kg==;");
}

var options = Recording.InstrumentClientOptions(new ConfigurationClientOptions());
var options = InstrumentClientOptions(new ConfigurationClientOptions());
return InstrumentClient(new ConfigurationClient(connectionString, options));
}

private ConfigurationClient GetAADClient()
{
string endpoint = TestEnvironment.Endpoint;
TokenCredential credential = TestEnvironment.Credential;
ConfigurationClientOptions options = Recording.InstrumentClientOptions(new ConfigurationClientOptions());
ConfigurationClientOptions options = InstrumentClientOptions(new ConfigurationClientOptions());
return InstrumentClient(new ConfigurationClient(new Uri(endpoint), credential, options));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,13 +63,13 @@ internal AppConfigurationManagementClient GetAppConfigurationManagementClient()
{
return CreateClient<AppConfigurationManagementClient>(this.TestEnvironment.SubscriptionId,
TestEnvironment.Credential,
Recording.InstrumentClientOptions(new AppConfigurationManagementClientOptions()));
InstrumentClientOptions(new AppConfigurationManagementClientOptions()));
}
internal NetworkManagementClient GetNetworkManagementClient()
{
return CreateClient<NetworkManagementClient>(this.TestEnvironment.SubscriptionId,
TestEnvironment.Credential,
Recording.InstrumentClientOptions(new NetworkManagementClientOptions()));
InstrumentClientOptions(new NetworkManagementClientOptions()));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -134,19 +134,19 @@ internal ComputeManagementClient GetComputeManagementClient()
{
return CreateClient<ComputeManagementClient>(this.TestEnvironment.SubscriptionId,
TestEnvironment.Credential,
Recording.InstrumentClientOptions(new ComputeManagementClientOptions()));
InstrumentClientOptions(new ComputeManagementClientOptions()));
}
internal NetworkManagementClient GetNetworkManagementClient()
{
return CreateClient<NetworkManagementClient>(this.TestEnvironment.SubscriptionId,
TestEnvironment.Credential,
Recording.InstrumentClientOptions(new NetworkManagementClientOptions()));
InstrumentClientOptions(new NetworkManagementClientOptions()));
}
internal StorageManagementClient GetStorageManagementClient()
{
return CreateClient<StorageManagementClient>(this.TestEnvironment.SubscriptionId,
TestEnvironment.Credential,
Recording.InstrumentClientOptions(new StorageManagementClientOptions()));
InstrumentClientOptions(new StorageManagementClientOptions()));
}

public void WaitSeconds(int seconds)
Expand Down
8 changes: 4 additions & 4 deletions sdk/core/Azure.Core.TestFramework/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public class ConfigurationLiveTests: ClientTestBase
InstrumentClient(
new ConfigurationClient(
...,
Recording.InstrumentClientOptions(
InstrumentClientOptions(
new ConfigurationClientClientOptions())));
}

Expand Down Expand Up @@ -122,7 +122,7 @@ If a test or sample uses `TokenCredential` to construct the client use `TestEnvi
InstrumentClient(
new KeyClient(
new Uri(TestEnvironment.KeyVaultUrl),TestEnvironment.Credential,
Recording.InstrumentClientOptions(
InstrumentClientOptions(
new KeyClientOptions())));
}
}
Expand All @@ -133,7 +133,7 @@ If a test or sample uses `TokenCredential` to construct the client use `TestEnvi

The test framework provides an ability to record HTTP requests and responses and replay them for offline test runs. This allows the full suite of tests to be run as part of PR validation without running live tests. In general, live tests are run as part of a separate internal pipeline that runs nightly.

To use recorded test functionality inherit from `RecordedTestBase<T>` class and use `Recording.InstrumentClientOptions` method when creating the client instance. Pass the test environment class as a generic argument to `RecordedTestBase`.
To use recorded test functionality inherit from `RecordedTestBase<T>` class and use `InstrumentClientOptions` method when creating the client instance. Pass the test environment class as a generic argument to `RecordedTestBase`.


``` C#
Expand All @@ -147,7 +147,7 @@ public class ConfigurationLiveTests: RecordedTestBase<AppConfigurationTestEnviro
InstrumentClient(
new ConfigurationClient(
...,
Recording.InstrumentClientOptions(
InstrumentClientOptions(
new ConfigurationClientClientOptions())));
}

Expand Down
13 changes: 13 additions & 0 deletions sdk/core/Azure.Core.TestFramework/src/RecordedTestBase.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
Expand Down Expand Up @@ -53,6 +54,18 @@ protected RecordedTestBase(bool isAsync, RecordedTestMode mode) : base(isAsync)
Mode = mode;
}

public T InstrumentClientOptions<T>(T clientOptions) where T : ClientOptions
{
clientOptions.Transport = Recording.CreateTransport(clientOptions.Transport);
if (Mode == RecordedTestMode.Playback)
{
// Not making the timeout zero so retry code still goes async
clientOptions.Retry.Delay = TimeSpan.FromMilliseconds(10);
clientOptions.Retry.Mode = RetryMode.Fixed;
}
return clientOptions;
}

private string GetSessionFilePath()
{
TestContext.TestAdapter testAdapter = TestContext.CurrentContext.Test;
Expand Down
4 changes: 2 additions & 2 deletions sdk/digitaltwins/Azure.DigitalTwins.Core/tests/E2eTestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ protected DigitalTwinsClient GetClient()
new DigitalTwinsClient(
new Uri(TestEnvironment.DigitalTwinHostname),
TestEnvironment.Credential,
Recording.InstrumentClientOptions(new DigitalTwinsClientOptions())));
InstrumentClientOptions(new DigitalTwinsClientOptions())));
}

protected DigitalTwinsClient GetFakeClient()
Expand All @@ -52,7 +52,7 @@ protected DigitalTwinsClient GetFakeClient()
new DigitalTwinsClient(
new Uri(TestEnvironment.DigitalTwinHostname),
new FakeTokenCredential(),
Recording.InstrumentClientOptions(new DigitalTwinsClientOptions())));
InstrumentClientOptions(new DigitalTwinsClientOptions())));
}

public async Task<string> GetUniqueModelIdAsync(DigitalTwinsClient dtClient, string baseName)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ internal EventHubsManagementClient GetEventHubManagementClient()
{
return CreateClient<EventHubsManagementClient>(this.SubscriptionId,
TestEnvironment.Credential,
Recording.InstrumentClientOptions(new EventHubsManagementClientOptions()));
InstrumentClientOptions(new EventHubsManagementClientOptions()));
}

public async Task<string> GetLocation()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public FormRecognizerLiveTestBase(bool isAsync) : base(isAsync)
protected FormRecognizerClient CreateFormRecognizerClient(bool useTokenCredential = false, string apiKey = default, bool skipInstrumenting = false)
{
var endpoint = new Uri(TestEnvironment.Endpoint);
var options = Recording.InstrumentClientOptions(new FormRecognizerClientOptions());
var options = InstrumentClientOptions(new FormRecognizerClientOptions());
FormRecognizerClient client;

if (useTokenCredential)
Expand All @@ -56,7 +56,7 @@ protected FormRecognizerClient CreateFormRecognizerClient(bool useTokenCredentia
protected FormTrainingClient CreateFormTrainingClient(bool useTokenCredential = false, string apiKey = default, bool skipInstrumenting = false)
{
var endpoint = new Uri(TestEnvironment.Endpoint);
var options = Recording.InstrumentClientOptions(new FormRecognizerClientOptions());
var options = InstrumentClientOptions(new FormRecognizerClientOptions());
FormTrainingClient client;

if (useTokenCredential)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public async Task FromCertificatePath(bool usePem)
var clientId = TestEnvironment.ServicePrincipalClientId;
var certPath = usePem ? TestEnvironment.ServicePrincipalCertificatePemPath : TestEnvironment.ServicePrincipalCertificatePfxPath;

var options = Recording.InstrumentClientOptions(new TokenCredentialOptions());
var options = InstrumentClientOptions(new TokenCredentialOptions());

var credential = new ClientCertificateCredential(tenantId, clientId, certPath, options);

Expand Down Expand Up @@ -73,7 +73,7 @@ public async Task FromX509Certificate2()
var clientId = TestEnvironment.ServicePrincipalClientId;
var cert = new X509Certificate2(TestEnvironment.ServicePrincipalCertificatePfxPath);

var options = Recording.InstrumentClientOptions(new TokenCredentialOptions());
var options = InstrumentClientOptions(new TokenCredentialOptions());

var credential = new ClientCertificateCredential(tenantId, clientId, cert, options);

Expand Down Expand Up @@ -101,14 +101,33 @@ public async Task FromX509Certificate2()
}
}

[Test]
public async Task IncludeX5CCliamHeader()
{
var tenantId = TestEnvironment.ServicePrincipalTenantId;
var clientId = TestEnvironment.ServicePrincipalClientId;
var certPath = TestEnvironment.ServicePrincipalSniCertificatePath;

var options = Recording.InstrumentClientOptions(new ClientCertificateCredentialOptions { IncludeX5CCliamHeader = true });

var credential = new ClientCertificateCredential(tenantId, clientId, certPath, options);

var tokenRequestContext = new TokenRequestContext(new[] { AzureAuthorityHosts.GetDefaultScope(AzureAuthorityHosts.AzurePublicCloud) });

// ensure we can initially acquire a token
AccessToken token = await credential.GetTokenAsync(tokenRequestContext);

Assert.IsNotNull(token.Token);
}

[Test]
public void IncorrectCertificate()
{
var tenantId = TestEnvironment.ServicePrincipalTenantId;
var clientId = TestEnvironment.ServicePrincipalClientId;
var certPath = Path.Combine(TestContext.CurrentContext.TestDirectory, "Data", "cert.pfx");

var options = Recording.InstrumentClientOptions(new TokenCredentialOptions());
var options = InstrumentClientOptions(new TokenCredentialOptions());

var credential = new ClientCertificateCredential(tenantId, clientId, new X509Certificate2(certPath), options);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public async Task GetToken()
var clientId = TestEnvironment.ServicePrincipalClientId;
var secret = TestEnvironment.ServicePrincipalClientSecret;

var options = Recording.InstrumentClientOptions(new TokenCredentialOptions());
var options = InstrumentClientOptions(new TokenCredentialOptions());

var credential = new ClientSecretCredential(tenantId, clientId, secret, options);

Expand Down Expand Up @@ -69,7 +69,7 @@ public void GetTokenIncorrectPassword()
var clientId = TestEnvironment.ServicePrincipalClientId;
var secret = "badsecret";

var options = Recording.InstrumentClientOptions(new TokenCredentialOptions());
var options = InstrumentClientOptions(new TokenCredentialOptions());

var credential = new ClientSecretCredential(tenantId, clientId, secret, options);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public async Task ValidateImdsSystemAssignedIdentity()
var cred = CreateManagedIdentityCredential();

// Hard code service version or recorded tests will fail: https://github.com/Azure/azure-sdk-for-net/issues/10432
var kvoptions = Recording.InstrumentClientOptions(new SecretClientOptions(SecretClientOptions.ServiceVersion.V7_0));
var kvoptions = InstrumentClientOptions(new SecretClientOptions(SecretClientOptions.ServiceVersion.V7_0));

var kvclient = new SecretClient(vaultUri, cred, kvoptions);

Expand All @@ -61,7 +61,7 @@ public async Task ValidateImdsUserAssignedIdentity()
var cred = CreateManagedIdentityCredential(clientId);

// Hard code service version or recorded tests will fail: https://github.com/Azure/azure-sdk-for-net/issues/10432
var kvoptions = Recording.InstrumentClientOptions(new SecretClientOptions(SecretClientOptions.ServiceVersion.V7_0));
var kvoptions = InstrumentClientOptions(new SecretClientOptions(SecretClientOptions.ServiceVersion.V7_0));

var kvclient = new SecretClient(vaultUri, cred, kvoptions);

Expand All @@ -72,7 +72,7 @@ public async Task ValidateImdsUserAssignedIdentity()

private ManagedIdentityCredential CreateManagedIdentityCredential(string clientId = null, TokenCredentialOptions options = null)
{
options = Recording.InstrumentClientOptions(options ?? new TokenCredentialOptions());
options = InstrumentClientOptions(options ?? new TokenCredentialOptions());

var pipeline = CredentialPipeline.GetInstance(options);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public async Task GetToken()
var username = TestEnvironment.Username;
var password = TestEnvironment.TestPassword;

var options = Recording.InstrumentClientOptions(new TokenCredentialOptions());
var options = InstrumentClientOptions(new TokenCredentialOptions());

var cred = InstrumentClient(new UsernamePasswordCredential(username, password, tenantId, ClientId, options));

Expand All @@ -91,7 +91,7 @@ public async Task AuthenticateNoContext()
var username = TestEnvironment.Username;
var password = TestEnvironment.TestPassword;

var options = Recording.InstrumentClientOptions(new TokenCredentialOptions());
var options = InstrumentClientOptions(new TokenCredentialOptions());

var cred = InstrumentClient(new UsernamePasswordCredential(username, password, tenantId, ClientId, options));

Expand All @@ -110,7 +110,7 @@ public async Task AuthenticateWithContext()
var username = TestEnvironment.Username;
var password = TestEnvironment.TestPassword;

var options = Recording.InstrumentClientOptions(new TokenCredentialOptions());
var options = InstrumentClientOptions(new TokenCredentialOptions());

var cred = InstrumentClient(new UsernamePasswordCredential(username, password, tenantId, ClientId, options));

Expand Down
2 changes: 1 addition & 1 deletion sdk/iot/Azure.Iot.Hub.Service/tests/E2eTestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ protected IotHubServiceClient GetClient()
return InstrumentClient(
new IotHubServiceClient(
TestEnvironment.IotHubConnectionString,
Recording.InstrumentClientOptions(new IotHubServiceClientOptions())));
InstrumentClientOptions(new IotHubServiceClientOptions())));
}

protected string GetRandom()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ internal KeyVaultManagementClient GetKeyVaultManagementClient()
{
return InstrumentClient(new KeyVaultManagementClient(TestEnvironment.SubscriptionId,
TestEnvironment.Credential,
Recording.InstrumentClientOptions(new KeyVaultManagementClientOptions())));
InstrumentClientOptions(new KeyVaultManagementClientOptions())));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,24 +39,20 @@ public AccessControlTestBase(bool isAsync) : base(isAsync)

internal KeyVaultAccessControlClient GetClient(TestRecording recording = null)
{
recording ??= Recording;

return InstrumentClient
(new KeyVaultAccessControlClient(
new Uri(TestEnvironment.KeyVaultUrl),
TestEnvironment.Credential,
recording.InstrumentClientOptions(new KeyVaultAccessControlClientOptions())));
InstrumentClientOptions(new KeyVaultAccessControlClientOptions())));
}

internal KeyClient GetKeyClient(TestRecording recording = null)
{
recording ??= Recording;

return InstrumentClient
(new KeyClient(
new Uri(TestEnvironment.KeyVaultUrl),
TestEnvironment.Credential,
recording.InstrumentClientOptions(new KeyClientOptions())));
InstrumentClientOptions(new KeyClientOptions())));
}

[SetUp]
Expand Down
Loading

0 comments on commit 88f5130

Please sign in to comment.