< Summary

Class:IntegrationTestCommon.IntegrationTestCommon
Assembly:Microsoft.Azure.Batch.IntegrationTestCommon
File(s):C:\Git\azure-sdk-for-net\sdk\batch\Microsoft.Azure.Batch\tests\IntegrationTestCommon\IntegrationTestCommon.cs
Covered lines:3
Uncovered lines:85
Coverable lines:88
Total lines:197
Line coverage:3.4% (3 of 88)
Covered branches:0
Total branches:16
Branch coverage:0% (0 of 16)

Metrics

MethodCyclomatic complexity Line coverage Branch coverage
OpenBatchManagementClient()-0%0%
IsManagementUrlAValidProductionURL()-0%100%
GetAuthenticationTokenAsync()-0%100%
GetBatchTestTenantCloudCredentials()-0%0%
EnableAutoStorageAsync()-0%0%
UploadTestApplicationAsync()-0%100%
GetTemporaryCertificateFilePath(...)-100%100%

File(s)

C:\Git\azure-sdk-for-net\sdk\batch\Microsoft.Azure.Batch\tests\IntegrationTestCommon\IntegrationTestCommon.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
 4namespace IntegrationTestCommon
 5{
 6    using System;
 7    using System.Collections.Generic;
 8    using System.IO;
 9    using System.IO.Compression;
 10    using System.Linq;
 11    using System.Net;
 12    using System.Net.Security;
 13    using System.Security.Cryptography.X509Certificates;
 14    using System.Threading.Tasks;
 15    using Microsoft.Azure.Batch.IntegrationTestCommon.Tests.Helpers;
 16    using Microsoft.Azure.Management.Batch;
 17    using Microsoft.Azure.Management.Batch.Models;
 18    using Microsoft.IdentityModel.Clients.ActiveDirectory;
 19    using System.Text;
 20    using Microsoft.WindowsAzure.Storage.Blob;
 21    using BatchTestCommon;
 22    using Microsoft.Rest;
 23
 24    public class IntegrationTestCommon
 25    {
 26        public static BatchManagementClient OpenBatchManagementClient()
 27        {
 28            ServiceClientCredentials credentials;
 29
 030            if (IsManagementUrlAValidProductionURL())
 31            {
 032                string accessToken = GetAuthenticationTokenAsync("https://management.core.windows.net/").Result;
 033                credentials = new TokenCredentials(accessToken);
 34            }
 35            else
 36            {
 037                credentials = GetBatchTestTenantCloudCredentials();
 38            }
 39
 040            string managementUrl = TestCommon.Configuration.BatchManagementUrl;
 41
 042            var managementClient = new BatchManagementClient(credentials)
 043            {
 044                BaseUri = new Uri(managementUrl),
 045                SubscriptionId = TestCommon.Configuration.BatchSubscription
 046            };
 47
 48            //Add the extra headers as specified in the configuration
 049            foreach (KeyValuePair<string, string> extraHeader in TestCommon.Configuration.BatchTRPExtraHeaders)
 50            {
 051                managementClient.HttpClient.DefaultRequestHeaders.Add(extraHeader.Key, extraHeader.Value);
 52            }
 53
 054            return managementClient;
 55        }
 56
 57        private static bool IsManagementUrlAValidProductionURL()
 58        {
 059            return new[] { "https://management.azure.com" }.Any(x => TestCommon.Configuration.BatchManagementUrl.StartsW
 60        }
 61
 62        public static async Task<string> GetAuthenticationTokenAsync(string resource)
 63        {
 064            var authContext = new AuthenticationContext(TestCommon.Configuration.BatchAuthorityUrl);
 65
 066            var authResult = await authContext.AcquireTokenAsync(resource, new ClientCredential(TestCommon.Configuration
 67
 068            return authResult.AccessToken;
 069        }
 70
 71        private static ServiceClientCredentials GetBatchTestTenantCloudCredentials()
 72        {
 073            X509Certificate2 certificate2 = null;
 074            X509Store store = null;
 75
 76            try
 77            {
 078                store = new X509Store(StoreLocation.CurrentUser);
 79
 080                store.Open(OpenFlags.ReadOnly);
 81
 082                X509Certificate2Collection certificates = store.Certificates;
 83
 084                certificate2 = certificates.Cast<X509Certificate2>().FirstOrDefault(
 085                    c => String.Equals(
 086                        c.Thumbprint,
 087                        TestCommon.Configuration.BatchTRPCertificateThumbprint(),
 088                        StringComparison.OrdinalIgnoreCase));
 89
 090                if (certificate2 == null)
 91                {
 092                    throw new InvalidOperationException("The certificate with thumbprint '" + TestCommon.Configuration.B
 093                        "' is not installed on your machine. Refer to the howto.txt for information about setting up you
 94                }
 095            }
 96            finally
 97            {
 098                if (store != null)
 99                {
 0100                    store.Close();
 101                }
 0102            }
 103#if FullNetFx
 104            return new CertificateCredentials(certificate2);
 105# else
 0106            return new CertificateCredentialsNetCore(certificate2);
 107#endif
 108        }
 109
 110        public static async Task EnableAutoStorageAsync()
 111        {
 0112            using (BatchManagementClient managementClient = OpenBatchManagementClient())
 113            {
 114                //TODO: Why do we need this...?
 0115                ServicePointManager.ServerCertificateValidationCallback =
 0116                    delegate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErro
 0117                    {
 0118                        HttpWebRequest request = sender as HttpWebRequest;
 0119                        if (request != null)
 0120                        {
 0121                            if (request.Address.ToString().Contains(TestCommon.Configuration.BatchManagementUrl))
 0122                            {
 0123                                return true;
 0124                            }
 0125                        }
 0126                        return sslPolicyErrors == SslPolicyErrors.None; //use the default validation for all other certi
 0127                    };
 128
 129                //If the account doesn't already have auto storage enabled, enable it
 0130                BatchAccount batchAccount = await managementClient.BatchAccount.GetAsync(TestCommon.Configuration.BatchA
 0131                if (batchAccount.AutoStorage == null)
 132                {
 133                    const string classicStorageAccountGroup = "Microsoft.ClassicStorage";
 134                    const string storageAccountGroup = "Microsoft.Storage";
 0135                    string resourceFormatString = $"/subscriptions/{TestCommon.Configuration.BatchSubscription}/resource
 0136                        $"/storageAccounts/{TestCommon.Configuration.StorageAccountName}";
 137
 0138                    string classicStorageAccountFullResourceId = string.Format(resourceFormatString, classicStorageAccou
 0139                    string storageAccountFullResourceId = string.Format(resourceFormatString, storageAccountGroup);
 140
 0141                    var updateParameters = new BatchAccountUpdateParameters()
 0142                    {
 0143                        AutoStorage = new AutoStorageBaseProperties
 0144                        {
 0145                            StorageAccountId = classicStorageAccountFullResourceId
 0146                        }
 0147                    };
 148                    try
 149                    {
 0150                        await managementClient.BatchAccount.UpdateAsync(TestCommon.Configuration.BatchAccountResourceGro
 0151                    }
 0152                    catch (Exception e) when (e.Message.Contains("The specified storage account could not be found"))
 153                    {
 154                        //If the storage account could not be found, it might be because we looked in "Classic" -- in th
 155                        //the exception.
 0156                    }
 157
 0158                    updateParameters.AutoStorage.StorageAccountId = storageAccountFullResourceId;
 0159                    await managementClient.BatchAccount.UpdateAsync(TestCommon.Configuration.BatchAccountResourceGroup, 
 0160                }
 0161            }
 0162        }
 163
 164        public static async Task UploadTestApplicationAsync(string storageUrl)
 165        {
 0166            CloudBlockBlob blob = new CloudBlockBlob(new Uri(storageUrl));
 167
 168            const string dummyPackageContentFile = @"TestApplicationPackage.zip";
 169
 0170            using (MemoryStream fakeApplicationPackageZip = new MemoryStream())
 171            {
 0172                using (ZipArchive zip = new ZipArchive(fakeApplicationPackageZip, ZipArchiveMode.Create, leaveOpen: true
 173                {
 0174                    ZipArchiveEntry entry = zip.CreateEntry(dummyPackageContentFile);
 0175                    using (var s = entry.Open())
 176                    {
 0177                        byte[] bytes = Encoding.UTF8.GetBytes("The quick brown fox jumps over the lazy dog.");
 0178                        s.Write(bytes, 0, bytes.Length);
 0179                    }
 0180                }
 181
 0182                fakeApplicationPackageZip.Seek(0, SeekOrigin.Begin);
 183
 0184                await blob.UploadFromStreamAsync(fakeApplicationPackageZip).ConfigureAwait(false);
 0185            }
 0186        }
 187
 188        public static string GetTemporaryCertificateFilePath(string fileName)
 189        {
 8190            string certificateFolderPath = Path.Combine(Path.GetTempPath(), @"BatchTestCertificates");
 191
 8192            Directory.CreateDirectory(certificateFolderPath);
 193
 8194            return Path.Combine(certificateFolderPath, fileName);
 195        }
 196    }
 197}