< Summary

Class:KeyVault.TestFramework.KeyVaultTestFixture
Assembly:Microsoft.Azure.KeyVault.TestFramework
File(s):C:\Git\azure-sdk-for-net\sdk\keyvault\Microsoft.Azure.KeyVault\tests\TestFramework\KeyVaultTestFixture.cs
Covered lines:43
Uncovered lines:77
Coverable lines:120
Total lines:258
Line coverage:35.8% (43 of 120)
Covered branches:13
Total branches:28
Branch coverage:46.4% (13 of 28)

Metrics

MethodCyclomatic complexity Line coverage Branch coverage
.ctor()-35.29%50%
Initialize(...)-100%100%
GetKeyVaultLocation(...)-0%0%
CreateServicePrincipal(...)-0%100%
CreateApplication(...)-0%100%
FromConfiguration()-57.14%50%
GetAccessToken()-0%100%
GetUserAccessToken()-0%0%
CreateKeyVaultClient()-100%100%
CreateKeyVaultUserClient()-100%100%
WaitOnDeletedKey(...)-100%100%
WaitOnDeletedSecret(...)-100%100%
WaitOnDeletedCertificate(...)-100%100%
WaitOnKey(...)-100%100%
WaitOnSecret(...)-100%100%
WaitOnCertificate(...)-0%100%
GetHandlers()-100%100%
Dispose()-20%50%

File(s)

C:\Git\azure-sdk-for-net\sdk\keyvault\Microsoft.Azure.KeyVault\tests\TestFramework\KeyVaultTestFixture.cs

#LineLine coverage
 1// Copyright (c) Microsoft Corporation. All rights reserved.
 2// Licensed under the MIT License. See License.txt in the project root for license information.
 3
 4using System;
 5using System.Collections.Generic;
 6using System.Linq;
 7using System.Net.Http;
 8using System.Threading.Tasks;
 9using Microsoft.Azure.Graph.RBAC;
 10using Microsoft.Azure.Graph.RBAC.Models;
 11using Microsoft.Azure.KeyVault;
 12using Microsoft.Azure.KeyVault.Models;
 13using Microsoft.Azure.KeyVault.WebKey;
 14using Microsoft.Azure.Test.HttpRecorder;
 15using Microsoft.IdentityModel.Clients.ActiveDirectory;
 16using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
 17using Microsoft.Azure.Management.ResourceManager;
 18using System.Net;
 19using Microsoft.Rest.TransientFaultHandling;
 20using System.Diagnostics;
 21
 22namespace KeyVault.TestFramework
 23{
 24    public class KeyVaultTestFixture : IDisposable
 25    {
 26        // Required in test code
 27        public string vaultAddress;
 28        public bool standardVaultOnly;
 29        public bool softDeleteEnabled;
 30        public string keyName;
 31        public string keyVersion;
 32        public KeyIdentifier keyIdentifier;
 33        public ClientCredential clientCredential;
 34        public RetryPolicy retryExecutor;
 35        public string StorageResourceUrl1;
 36        public string StorageResourceUrl2;
 37
 38        // Required for cleaning up at the end of the test
 839        private string rgName = "", appObjectId = "";
 40        private bool fromConfig;
 41        private TokenCache tokenCache;
 42        private DeviceCodeResult _deviceCodeForStorageTests;
 43
 444        public KeyVaultTestFixture()
 45        {
 446            Initialize(this.GetType());
 47
 448            if (vaultAddress != null && HttpMockServer.Mode == HttpRecorderMode.Record)
 49            {
 50                //Create one key to use for testing. Key creation is expensive.
 051                var myClient = new KeyVaultClient(new TestKeyVaultCredential(GetAccessToken), GetHandlers());
 052                keyName = "sdktestkey";
 053                var attributes = new KeyAttributes();
 054                var createdKey = myClient.CreateKeyAsync(vaultAddress, keyName, JsonWebKeyType.Rsa, 2048,
 055                    JsonWebKeyOperation.AllOperations, attributes).GetAwaiter().GetResult();
 056                keyIdentifier = new KeyIdentifier(createdKey.Key.Kid);
 057                keyName = keyIdentifier.Name;
 058                keyVersion = keyIdentifier.Version;
 059                tokenCache = new TokenCache();
 060                _deviceCodeForStorageTests = null;
 061                retryExecutor = new RetryPolicy<SoftDeleteErrorDetectionStrategy>(new ExponentialBackoffRetryStrategy(8,
 62            } else
 63            {
 464                retryExecutor = new RetryPolicy<SoftDeleteErrorDetectionStrategy>( new FixedIntervalRetryStrategy( 5, Ti
 65            }
 466        }
 67
 68        public void Initialize(Type type)
 69        {
 470            HttpMockServer.FileSystemUtilsObject = new FileSystemUtils();
 471            HttpMockServer.Initialize(type, "InitialCreation", HttpRecorderMode.Record);
 472            HttpMockServer.CreateInstance();
 73
 474            if (HttpMockServer.Mode == HttpRecorderMode.Record)
 75            {
 476                fromConfig = FromConfiguration();
 77            }
 478        }
 79
 80        private static string GetKeyVaultLocation(ResourceManagementClient resourcesClient)
 81        {
 082            var providers = resourcesClient.Providers.Get("Microsoft.KeyVault");
 083            var location = providers.ResourceTypes.Where(
 084                (resType) =>
 085                {
 086                    if (resType.ResourceType == "vaults")
 087                        return true;
 088                    else
 089                        return false;
 090                }
 091                ).First().Locations.FirstOrDefault();
 092            return location;
 93        }
 94
 95        private static ServicePrincipal CreateServicePrincipal(Application app,
 96            GraphRbacManagementClient graphClient)
 97        {
 098            var parameters = new ServicePrincipalCreateParameters
 099            {
 0100                AccountEnabled = true,
 0101                AppId = app.AppId
 0102            };
 0103            var servicePrincipal = graphClient.ServicePrincipal.Create(parameters);
 0104            return servicePrincipal;
 105        }
 106
 107        private static Application CreateApplication(GraphRbacManagementClient graphClient, string appDisplayName, strin
 108        {
 0109            return graphClient.Application.Create(new ApplicationCreateParameters
 0110            {
 0111                DisplayName = appDisplayName,
 0112                IdentifierUris = new List<string>() { "http://" + Guid.NewGuid().ToString() + ".com" },
 0113                Homepage = "http://contoso.com",
 0114                AvailableToOtherTenants = false,
 0115                PasswordCredentials = new[]
 0116                {
 0117                    new PasswordCredential
 0118                    {
 0119                        Value = secret,
 0120                        StartDate = DateTime.Now - TimeSpan.FromDays(1),
 0121                        EndDate = DateTime.Now + TimeSpan.FromDays(1),
 0122                        KeyId = Guid.NewGuid().ToString()
 0123                    }
 0124                }
 0125            });
 126        }
 127
 128        private bool FromConfiguration()
 129        {
 4130            string vault = TestConfigurationManager.TryGetEnvironmentOrAppSetting("VaultUrl");
 4131            string authClientId = TestConfigurationManager.TryGetEnvironmentOrAppSetting("AuthClientId");
 4132            string authSecret = TestConfigurationManager.TryGetEnvironmentOrAppSetting("AuthClientSecret");
 4133            string standardVaultOnlyString = TestConfigurationManager.TryGetEnvironmentOrAppSetting("StandardVaultOnly")
 4134            string softDeleteEnabledString = TestConfigurationManager.TryGetEnvironmentOrAppSetting("SoftDeleteEnabled")
 4135            string storageUrl1 = TestConfigurationManager.TryGetEnvironmentOrAppSetting("StorageResourceUrl1");
 4136            string storageUrl2 = TestConfigurationManager.TryGetEnvironmentOrAppSetting("StorageResourceUrl2");
 137            bool standardVaultOnlyresult;
 4138            if (!bool.TryParse(standardVaultOnlyString, out standardVaultOnlyresult))
 139            {
 0140                standardVaultOnlyresult = false;
 141            }
 142
 143            bool softDeleteEnabledresult;
 4144            if (!bool.TryParse(softDeleteEnabledString, out softDeleteEnabledresult))
 145            {
 0146                softDeleteEnabledresult = false;
 147            }
 148
 4149            if (string.IsNullOrWhiteSpace(vault) || string.IsNullOrWhiteSpace(authClientId) || string.IsNullOrWhiteSpace
 4150                string.IsNullOrWhiteSpace(storageUrl1) || string.IsNullOrWhiteSpace(storageUrl2))
 4151                return false;
 152            else
 153            {
 0154                this.vaultAddress = vault;
 0155                this.clientCredential = new ClientCredential(authClientId, authSecret);
 0156                this.standardVaultOnly = standardVaultOnlyresult;
 0157                this.softDeleteEnabled = softDeleteEnabledresult;
 0158                this.StorageResourceUrl1 = storageUrl1;
 0159                this.StorageResourceUrl2 = storageUrl2;
 0160                return true;
 161            }
 162        }
 163
 164        public async Task<string> GetAccessToken(string authority, string resource, string scope)
 165        {
 0166            var context = new AuthenticationContext(authority, tokenCache);
 0167            var result = await context.AcquireTokenAsync(resource, clientCredential).ConfigureAwait(false);
 168
 0169            return result.AccessToken;
 0170        }
 171
 172        public async Task<string> GetUserAccessToken(string authority, string resource, string scope)
 173        {
 0174            string clientId = TestConfigurationManager.TryGetEnvironmentOrAppSetting("NativeClientId");
 0175            var context = new AuthenticationContext(authority, tokenCache);
 0176            if (_deviceCodeForStorageTests == null)
 177            {
 0178                _deviceCodeForStorageTests =
 0179                    await context.AcquireDeviceCodeAsync(resource, clientId).ConfigureAwait(false);
 180
 181                Debug.WriteLine("#######################################################################################
 182                Debug.WriteLine("Test won't run until you perform following steps:");
 183                Debug.WriteLine($"1. Go to following url: {_deviceCodeForStorageTests.VerificationUrl}.");
 184                Debug.WriteLine($"2. Insert following User Code: {_deviceCodeForStorageTests.UserCode}.");
 185                Debug.WriteLine("3. Login with your username and password credentials.");
 186                Debug.WriteLine("#######################################################################################
 187            }
 188
 0189            var result = await context.AcquireTokenByDeviceCodeAsync(_deviceCodeForStorageTests).ConfigureAwait(false);
 0190            return result.AccessToken;
 0191        }
 192
 193        public KeyVaultClient CreateKeyVaultClient()
 194        {
 106195            var myclient = new KeyVaultClient(new TestKeyVaultCredential(GetAccessToken), GetHandlers());
 106196            return myclient;
 197        }
 198
 199        public KeyVaultClient CreateKeyVaultUserClient()
 200        {
 12201            var myclient = new KeyVaultClient(new TestKeyVaultCredential(GetUserAccessToken), GetHandlers());
 12202            return myclient;
 203        }
 204
 205        public void WaitOnDeletedKey(KeyVaultClient client, string vaultAddress, string keyName)
 206        {
 104207            this.retryExecutor.ExecuteAction(() => client.GetDeletedKeyAsync(vaultAddress, keyName).GetAwaiter().GetResu
 22208        }
 209
 210        public void WaitOnDeletedSecret(KeyVaultClient client, string vaultAddress, string secretName)
 211        {
 82212            this.retryExecutor.ExecuteAction(() => client.GetDeletedSecretAsync(vaultAddress, secretName).GetAwaiter().G
 18213        }
 214
 215        public void WaitOnDeletedCertificate(KeyVaultClient client, string vaultAddress, string certificateName)
 216        {
 60217            this.retryExecutor.ExecuteAction(() => client.GetDeletedCertificateAsync(vaultAddress, certificateName).GetA
 12218        }
 219
 220        public void WaitOnKey(KeyVaultClient client, string vaultAddress, string keyName)
 221        {
 4222            this.retryExecutor.ExecuteAction(() => client.GetKeyAsync(vaultAddress, keyName).GetAwaiter().GetResult());
 2223        }
 224
 225        public void WaitOnSecret(KeyVaultClient client, string vaultAddress, string secretName)
 226        {
 4227            this.retryExecutor.ExecuteAction(() => client.GetSecretAsync(vaultAddress, secretName).GetAwaiter().GetResul
 2228        }
 229
 230        public void WaitOnCertificate(KeyVaultClient client, string vaultAddress, string certificateName)
 231        {
 0232            this.retryExecutor.ExecuteAction(() => client.GetCertificateAsync(vaultAddress, certificateName).GetAwaiter(
 0233        }
 234
 235        public DelegatingHandler[ ] GetHandlers()
 236        {
 120237            HttpMockServer server = HttpMockServer.CreateInstance();
 120238            var testHttpHandler = new TestHttpMessageHandler();
 120239            return new DelegatingHandler[] { server, testHttpHandler };
 240        }
 241        public void Dispose()
 242        {
 4243            if (HttpMockServer.Mode == HttpRecorderMode.Record && !fromConfig)
 244            {
 0245                var testEnv = TestEnvironmentFactory.GetTestEnvironment();
 0246                var context = new MockContext();
 247
 0248                var resourcesClient = context.GetServiceClient<ResourceManagementClient>();
 0249                var graphClient = context.GetServiceClient<GraphRbacManagementClient>();
 0250                graphClient.TenantID = testEnv.Tenant;
 0251                graphClient.BaseUri = new Uri("https://graph.windows.net");
 252
 0253                graphClient.Application.Delete(appObjectId);
 0254                resourcesClient.ResourceGroups.Delete(rgName);
 255            }
 4256        }
 257    }
 258}