public void Initialize(string className)
        {
            if (initialized)
                return;
            
            if (HttpMockServer.GetCurrentMode() == HttpRecorderMode.Record)
            {
                var testFactory = new CSMTestEnvironmentFactory();
                var testEnv = testFactory.GetTestEnvironment();
                var resourcesClient = TestBase.GetServiceClient<ResourceManagementClient>(testFactory);
                var mgmtClient = TestBase.GetServiceClient<KeyVaultManagementClient>(testFactory);
                var tenantId = testEnv.AuthorizationContext.TenantId;

                //Figure out which locations are available for Key Vault
                location = GetKeyVaultLocation(resourcesClient);

                //Create a resource group in that location
                preCreatedVault = TestUtilities.GenerateName("pshtestvault");
                resourceGroupName = TestUtilities.GenerateName("pshtestrg");

                resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = location });
                var createResponse = CreateVault(mgmtClient, location, tenantId);
            }

            initialized = true;
        }
        public void RunPsTestWorkflow(
            Func<string[]> scriptBuilder,
            Action<CSMTestEnvironmentFactory> initialize,
            Action cleanup,
            string callingClassType,
            string mockName, string tenant)
        {
            Dictionary<string, string> d = new Dictionary<string, string>();
            d.Add("Microsoft.Resources", null);
            d.Add("Microsoft.Features", null);
            d.Add("Microsoft.Authorization", null);
            var providersToIgnore = new Dictionary<string, string>();
            providersToIgnore.Add("Microsoft.Azure.Management.Resources.ResourceManagementClient", "2016-02-01");
            HttpMockServer.Matcher = new PermissiveRecordMatcherWithApiExclusion(true, d, providersToIgnore);

            using (UndoContext context = UndoContext.Current)
            {
                context.Start(callingClassType, mockName);

                this.csmTestFactory = new CSMTestEnvironmentFactory();

                if (initialize != null)
                {
                    initialize(this.csmTestFactory);
                }

                SetupManagementClients();

                helper.SetupEnvironment(AzureModule.AzureResourceManager);
                var oldFactory = AzureSession.AuthenticationFactory as MockTokenAuthenticationFactory;
                AzureSession.AuthenticationFactory = new MockTokenAuthenticationFactory(oldFactory.Token.UserId, oldFactory.Token.AccessToken, tenant);

                var callingClassName = callingClassType
                    .Split(new[] {"."}, StringSplitOptions.RemoveEmptyEntries)
                    .Last();
                helper.SetupModules(AzureModule.AzureResourceManager, 
                    callingClassName + ".ps1", 
                    helper.RMProfileModule);

                try
                {
                    if (scriptBuilder != null)
                    {
                        var psScripts = scriptBuilder();

                        if (psScripts != null)
                        {
                            helper.RunPowerShellTest(psScripts);
                        }
                    }
                }
                finally
                {
                    if (cleanup != null)
                    {
                        cleanup();
                    }
                }
            }
        }
        /// <summary>
        /// This overrides the default subscription and default account. This allows the 
        /// test to get the tenant id in the test.
        /// </summary>
        public void SetupEnvironment()
        {
            base.SetupEnvironment(AzureModule.AzureResourceManager);

            TestEnvironment csmEnvironment = new CSMTestEnvironmentFactory().GetTestEnvironment();

            if (csmEnvironment.SubscriptionId != null)
            {
                //Overwrite the default subscription and default account
                //with ones using user ID and tenant ID from auth context
                var user = GetUser(csmEnvironment);
                var tenantId = GetTenantId(csmEnvironment);

                // Existing test will not have a user or tenant id set
                if (tenantId != null && user != null)
                {
                    var testSubscription = new AzureSubscription()
                    {
                        Id = new Guid(csmEnvironment.SubscriptionId),
                        Name = AzureRmProfileProvider.Instance.Profile.Context.Subscription.Name,
                        Environment = AzureRmProfileProvider.Instance.Profile.Context.Subscription.Environment,
                        Account = user,
                        Properties = new Dictionary<AzureSubscription.Property, string>
                    {
                        {
                            AzureSubscription.Property.Default, "True"
                        },
                        {
                            AzureSubscription.Property.StorageAccount,
                            Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT")
                        },
                        {
                            AzureSubscription.Property.Tenants, tenantId
                        },
                    }
                    };

                    var testAccount = new AzureAccount()
                    {
                        Id = user,
                        Type = AzureAccount.AccountType.User,
                        Properties = new Dictionary<AzureAccount.Property, string>
                    {
                        {
                            AzureAccount.Property.Subscriptions, csmEnvironment.SubscriptionId
                        },
                    }
                    };

                    AzureRmProfileProvider.Instance.Profile.Context.Subscription.Name = testSubscription.Name;
                    AzureRmProfileProvider.Instance.Profile.Context.Subscription.Id = testSubscription.Id;
                    AzureRmProfileProvider.Instance.Profile.Context.Subscription.Account = testSubscription.Account;

                    var environment = AzureRmProfileProvider.Instance.Profile.Environments[AzureRmProfileProvider.Instance.Profile.Context.Subscription.Environment];
                    environment.Endpoints[AzureEnvironment.Endpoint.Graph] = csmEnvironment.Endpoints.GraphUri.AbsoluteUri;
                    environment.Endpoints[AzureEnvironment.Endpoint.StorageEndpointSuffix] = "core.windows.net"; 
                    AzureRmProfileProvider.Instance.Profile.Save();
                }
            }
        }
        /// <summary>
        /// Default constructor for management clients, using the TestSupport Infrastructure
        /// </summary>
        /// <param name="testBase">the test class</param>
        /// <returns>A site recovery management client, created from the current context (environment variables)</returns>
        public static SiteRecoveryManagementClient GetSiteRecoveryManagementClient(this TestBase testBase)
        {
            if (ServicePointManager.ServerCertificateValidationCallback == null)
            {
                ServicePointManager.ServerCertificateValidationCallback =
                    IgnoreCertificateErrorHandler;
            }

            TestEnvironment environment = new CSMTestEnvironmentFactory().GetTestEnvironment();
            // TestEnvironment environment = new RDFETestEnvironmentFactory().GetTestEnvironment();
            // environment.BaseUri = new Uri("https://localhost:8443/Rdfeproxy.svc");
            // environment.BaseUri = new Uri("https://sea-bvtd2-srs1-t56tl.cloudapp.net");


            SiteRecoveryTestsBase.MyCloudService = (HttpMockServer.Mode == HttpRecorderMode.Playback) ?
                "RecoveryServices-WHNOWF6LI6NM4B55QDIYR3YG3YAEZNTDUOWHPQX7NJB2LHDGTXJA-West-US" :
                Environment.GetEnvironmentVariable("CLOUD_SERVICE_NAME");

            SiteRecoveryTestsBase.MyVaultName = (HttpMockServer.Mode == HttpRecorderMode.Playback) ?
                "hydratest" :
                Environment.GetEnvironmentVariable("RESOURCE_NAME");

            SiteRecoveryTestsBase.VaultKey = (HttpMockServer.Mode == HttpRecorderMode.Playback) ?
                "loMUdckuT9SEvpQKcSG07A==" :
                Environment.GetEnvironmentVariable("CHANNEL_INTEGRITY_KEY");

            SiteRecoveryTestsBase.MyResourceGroupName = (HttpMockServer.Mode == HttpRecorderMode.Playback) ?
                "RecoveryServices-WHNOWF6LI6NM4B55QDIYR3YG3YAEZNTDUOWHPQX7NJB2LHDGTXJA-West-US" :
                Environment.GetEnvironmentVariable("RESOURCE_GROUP_NAME");

            if (string.IsNullOrEmpty(SiteRecoveryTestsBase.MyCloudService))
            {
                throw new Exception("Please set CLOUD_SERVICE_NAME" + 
                    " environment variable before running the tests in Live mode");
            }
            if (string.IsNullOrEmpty(SiteRecoveryTestsBase.MyVaultName))
            {
                throw new Exception("Please set RESOURCE_NAME" +
                    " environment variable before running the tests in Live mode");
            }
            if (string.IsNullOrEmpty(SiteRecoveryTestsBase.VaultKey))
            {
                throw new Exception("Please set CHANNEL_INTEGRITY_KEY" +
                    " environment variable before running the tests in Live mode");
            }
            if (string.IsNullOrEmpty(SiteRecoveryTestsBase.MyResourceGroupName))
            {
                throw new Exception("Please set RESOURCE_GROUP_NAME" +
                    " environment variable before running the tests in Live mode");
            }

            return new SiteRecoveryManagementClient(
                SiteRecoveryTestsBase.MyVaultName,
                SiteRecoveryTestsBase.MyResourceGroupName,
                "Microsoft.SiteRecoveryBVTD2",
                "SiteRecoveryVault",
                (SubscriptionCloudCredentials)environment.Credentials,
                environment.BaseUri).WithHandler(HttpMockServer.CreateInstance());
        }
        /// <summary>
        /// Default constructor for management clients, using the TestSupport Infrastructure
        /// </summary>
        /// <param name="testBase">the test class</param>
        /// <returns>A site recovery management client, created from the current context (environment variables)</returns>
        public static SiteRecoveryManagementClient GetSiteRecoveryManagementClient(this TestBase testBase)
        {
            if (ServicePointManager.ServerCertificateValidationCallback == null)
            {
                ServicePointManager.ServerCertificateValidationCallback =
                    IgnoreCertificateErrorHandler;
            }

            TestEnvironment environment = new CSMTestEnvironmentFactory().GetTestEnvironment();
            //TestEnvironment environment = new RDFETestEnvironmentFactory().GetTestEnvironment();
            //environment.BaseUri = new Uri("https://localhost:8443/Rdfeproxy.svc");
            // environment.BaseUri = new Uri("https://sea-bvtd2-srs1-t56tl.cloudapp.net");


            SiteRecoveryTestsBase.MyCloudService = (HttpMockServer.Mode == HttpRecorderMode.Playback) ?
                "rg1" :
                Environment.GetEnvironmentVariable("CLOUD_SERVICE_NAME");

            SiteRecoveryTestsBase.MyVaultName = (HttpMockServer.Mode == HttpRecorderMode.Playback) ?
                "S91-1-2-3-4-5" :
                Environment.GetEnvironmentVariable("RESOURCE_NAME");

            SiteRecoveryTestsBase.VaultKey = (HttpMockServer.Mode == HttpRecorderMode.Playback) ?
                "8dr012Ze+WIPM5z1xSNGZA==" :
                Environment.GetEnvironmentVariable("CHANNEL_INTEGRITY_KEY");

            SiteRecoveryTestsBase.MyResourceGroupName = (HttpMockServer.Mode == HttpRecorderMode.Playback) ?
                "S91-1" :
                Environment.GetEnvironmentVariable("RESOURCE_GROUP_NAME");

            if (string.IsNullOrEmpty(SiteRecoveryTestsBase.MyCloudService))
            {
                throw new Exception("Please set CLOUD_SERVICE_NAME" + 
                    " environment variable before running the tests in Live mode");
            }
            if (string.IsNullOrEmpty(SiteRecoveryTestsBase.MyVaultName))
            {
                throw new Exception("Please set RESOURCE_NAME" +
                    " environment variable before running the tests in Live mode");
            }
            if (string.IsNullOrEmpty(SiteRecoveryTestsBase.VaultKey))
            {
                throw new Exception("Please set CHANNEL_INTEGRITY_KEY" +
                    " environment variable before running the tests in Live mode");
            }
            if (string.IsNullOrEmpty(SiteRecoveryTestsBase.MyResourceGroupName))
            {
                throw new Exception("Please set RESOURCE_GROUP_NAME" +
                    " environment variable before running the tests in Live mode");
            }

            return new SiteRecoveryManagementClient(
                SiteRecoveryTestsBase.MyVaultName,
                SiteRecoveryTestsBase.MyResourceGroupName,
                "Microsoft.RecoveryServicesBVTD2",
                "vaults",
                (SubscriptionCloudCredentials)environment.Credentials,
                environment.BaseUri).WithHandler(HttpMockServer.CreateInstance());
        }
        /// <summary>
        /// Default constructor for management clients, using the TestSupport Infrastructure
        /// </summary>
        /// <param name="testBase">the test class</param>
        /// <returns>A site recovery management client, created from the current context (environment variables)</returns>
        public static SiteRecoveryManagementClient GetSiteRecoveryManagementClient(this TestBase testBase)
        {
            if (ServicePointManager.ServerCertificateValidationCallback == null)
            {
                ServicePointManager.ServerCertificateValidationCallback =
                    IgnoreCertificateErrorHandler;
            }

            TestEnvironment environment = new CSMTestEnvironmentFactory().GetTestEnvironment();

            SiteRecoveryTestsBase.MyCloudService = (HttpMockServer.Mode == HttpRecorderMode.Playback) ?
                "testsitegroup" :
                Environment.GetEnvironmentVariable("CLOUD_SERVICE_NAME");

            SiteRecoveryTestsBase.MyVaultName = (HttpMockServer.Mode == HttpRecorderMode.Playback) ?
                "ppeVault2" :
                Environment.GetEnvironmentVariable("RESOURCE_NAME");

            SiteRecoveryTestsBase.VaultKey = (HttpMockServer.Mode == HttpRecorderMode.Playback) ?
                "tmPfTki5UFSdaEq2JFvzuw==" :
                Environment.GetEnvironmentVariable("CHANNEL_INTEGRITY_KEY");

            SiteRecoveryTestsBase.MyResourceGroupName = (HttpMockServer.Mode == HttpRecorderMode.Playback) ?
                "testsitegroup" :
                Environment.GetEnvironmentVariable("RESOURCE_GROUP_NAME");


            if (string.IsNullOrEmpty(SiteRecoveryTestsBase.MyCloudService))
            {
                throw new Exception("Please set CLOUD_SERVICE_NAME" + 
                    " environment variable before running the tests in Live mode");
            }
            if (string.IsNullOrEmpty(SiteRecoveryTestsBase.MyVaultName))
            {
                throw new Exception("Please set RESOURCE_NAME" +
                    " environment variable before running the tests in Live mode");
            }
            if (string.IsNullOrEmpty(SiteRecoveryTestsBase.VaultKey))
            {
                throw new Exception("Please set CHANNEL_INTEGRITY_KEY" +
                    " environment variable before running the tests in Live mode");
            }
            if (string.IsNullOrEmpty(SiteRecoveryTestsBase.MyResourceGroupName))
            {
                throw new Exception("Please set RESOURCE_GROUP_NAME" +
                    " environment variable before running the tests in Live mode");
            }

            return new SiteRecoveryManagementClient(
                SiteRecoveryTestsBase.MyVaultName,
                SiteRecoveryTestsBase.MyResourceGroupName,
                "Microsoft.SiteRecovery",
                (SubscriptionCloudCredentials)environment.Credentials,
                environment.BaseUri).WithHandler(HttpMockServer.CreateInstance());
        }
        public void RunPsTestWorkflow(
            Func<string[]> scriptBuilder,
            Action initialize,
            Action cleanup,
            string callingClassType,
            string mockName)
        {
            Dictionary<string, string> d = new Dictionary<string, string>();
            d.Add("Microsoft.Authorization", "2014-07-01-preview");
            HttpMockServer.Matcher = new PermissiveRecordMatcherWithApiExclusion(false, d);
            using (UndoContext context = UndoContext.Current)
            {
                context.Start(callingClassType, mockName);
                this.csmTestFactory = SetupCSMTestEnvironmentFactory();
                SetupManagementClients();

                helper.SetupEnvironment(AzureModule.AzureResourceManager);

                var callingClassName = callingClassType
                                        .Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries)
                                        .Last();
                helper.SetupModules(AzureModule.AzureResourceManager, 
                    "ScenarioTests\\Common.ps1", 
                    "ScenarioTests\\" + callingClassName + ".ps1", 
                    "Microsoft.Azure.Commands.Batch.Test.dll",
                    helper.RMProfileModule, 
                    helper.RMResourceModule,
                    helper.GetRMModulePath("AzureRM.Batch.psd1"));

                try
                {
                    if (initialize != null)
                    {
                        initialize();
                    }

                    if (scriptBuilder != null)
                    {
                        var psScripts = scriptBuilder();

                        if (psScripts != null)
                        {
                            helper.RunPowerShellTest(psScripts);
                        }
                    }
                }
                finally
                {
                    if (cleanup != null)
                    {
                        cleanup();
                    }
                }
            }
        }
        public static SearchServiceClient GetSearchServiceClient(this SearchServiceFixture fixture)
        {
            var factory = new CSMTestEnvironmentFactory();
            TestEnvironment currentEnvironment = factory.GetTestEnvironment();
            Uri baseUri = currentEnvironment.GetBaseSearchUri(ExecutionMode.CSM, fixture.SearchServiceName);

            SearchServiceClient client =
                new SearchServiceClient(new SearchCredentials(fixture.PrimaryApiKey), baseUri);

            return TestBaseCopy.AddMockHandler<SearchServiceClient>(ref client);
        }
        public void RunPsTestWorkflow(
            Func<string[]> scriptBuilder, 
            Action<CSMTestEnvironmentFactory> initialize, 
            Action cleanup,
            string callingClassType,
            string mockName)
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start(callingClassType, mockName);

                this.csmTestFactory = new CSMTestEnvironmentFactory();

                if(initialize != null)
                {
                    initialize(this.csmTestFactory);
                }

                SetupManagementClients();

                helper.SetupEnvironment(AzureModule.AzureResourceManager);
                
                var callingClassName = callingClassType
                                        .Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries)
                                        .Last();
                helper.SetupModules(AzureModule.AzureResourceManager, 
                    "ScenarioTests\\Common.ps1", 
                    "ScenarioTests\\" + callingClassName + ".ps1", 
                    helper.RMProfileModule, 
                    helper.RMResourceModule, 
                    helper.GetRMModulePath("AzureRM.Network.psd1"));

                try
                {
                    if (scriptBuilder != null)
                    {
                        var psScripts = scriptBuilder();

                        if (psScripts != null)
                        {
                            helper.RunPowerShellTest(psScripts);
                        }
                    }
                }
                finally
                {
                    if(cleanup !=null)
                    {
                        cleanup();
                    }
                }
            }
        }
Esempio n. 10
0
        public void RunPsTestWorkflow(
            Func <string[]> scriptBuilder,
            Action <CSMTestEnvironmentFactory> initialize,
            Action cleanup,
            string callingClassType,
            string mockName, string tenant)
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start(callingClassType, mockName);

                this.csmTestFactory = new CSMTestEnvironmentFactory();

                if (initialize != null)
                {
                    initialize(this.csmTestFactory);
                }

                SetupManagementClients();

                helper.SetupEnvironment(AzureModule.AzureResourceManager);
                var oldFactory = AzureSession.AuthenticationFactory as MockTokenAuthenticationFactory;
                AzureSession.AuthenticationFactory = new MockTokenAuthenticationFactory(oldFactory.Token.UserId, oldFactory.Token.AccessToken, tenant);

                var callingClassName = callingClassType
                                       .Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries)
                                       .Last();
                helper.SetupModules(AzureModule.AzureResourceManager,
                                    callingClassName + ".ps1",
                                    helper.RMProfileModule);

                try
                {
                    if (scriptBuilder != null)
                    {
                        var psScripts = scriptBuilder();

                        if (psScripts != null)
                        {
                            helper.RunPowerShellTest(psScripts);
                        }
                    }
                }
                finally
                {
                    if (cleanup != null)
                    {
                        cleanup();
                    }
                }
            }
        }
Esempio n. 11
0
        public void RunPsTestWorkflow(
            Func <string[]> scriptBuilder,
            Action <CSMTestEnvironmentFactory> initialize,
            Action cleanup,
            string callingClassType,
            string mockName)
        {
            HttpMockServer.RecordsDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SessionRecords");
            using (MockContext context = MockContext.Start(callingClassType, mockName))
            {
                this.csmTestFactory = new CSMTestEnvironmentFactory();
                if (initialize != null)
                {
                    initialize(this.csmTestFactory);
                }
                SetupManagementClients(context);

                helper.SetupEnvironment(AzureModule.AzureResourceManager);

                var callingClassName = callingClassType
                                       .Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries)
                                       .Last();
                helper.SetupModules(AzureModule.AzureResourceManager,
                                    "ScenarioTests\\" + callingClassName + ".ps1",
                                    helper.RMProfileModule,
                                    helper.RMResourceModule,
                                    helper.GetRMModulePath(@"AzureRM.DeviceProvisioningServices.psd1"),
                                    helper.GetRMModulePath(@"AzureRM.IotHub.psd1"),
                                    "AzureRM.Resources.ps1"
                                    );

                try
                {
                    if (scriptBuilder != null)
                    {
                        var psScripts = scriptBuilder();

                        if (psScripts != null)
                        {
                            helper.RunPowerShellTest(psScripts);
                        }
                    }
                }
                finally
                {
                    if (cleanup != null)
                    {
                        cleanup();
                    }
                }
            }
        }
        public void RunPsTestWorkflow(
            Func<string[]> scriptBuilder,
            Action<CSMTestEnvironmentFactory> initialize,
            Action cleanup,
            string callingClassType,
            string mockName, string tenant)
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start(callingClassType, mockName);

                this.csmTestFactory = new CSMTestEnvironmentFactory();

                if (initialize != null)
                {
                    initialize(this.csmTestFactory);
                }

                SetupManagementClients();

                helper.SetupEnvironment(AzureModule.AzureResourceManager);
                var oldFactory = AzureSession.AuthenticationFactory as MockTokenAuthenticationFactory;
                AzureSession.AuthenticationFactory = new MockTokenAuthenticationFactory(oldFactory.Token.UserId, oldFactory.Token.AccessToken, tenant);

                var callingClassName = callingClassType
                    .Split(new[] {"."}, StringSplitOptions.RemoveEmptyEntries)
                    .Last();
                helper.SetupModules(AzureModule.AzureResourceManager, 
                    callingClassName + ".ps1", 
                    helper.RMProfileModule);

                try
                {
                    if (scriptBuilder != null)
                    {
                        var psScripts = scriptBuilder();

                        if (psScripts != null)
                        {
                            helper.RunPowerShellTest(psScripts);
                        }
                    }
                }
                finally
                {
                    if (cleanup != null)
                    {
                        cleanup();
                    }
                }
            }
        }
        public void RunPsTestWorkflow(
            Func <string[]> scriptBuilder,
            Action <CSMTestEnvironmentFactory> initialize,
            Action cleanup,
            string callingClassType,
            string mockName)
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start(callingClassType, mockName);

                this.csmTestFactory = new CSMTestEnvironmentFactory();

                if (initialize != null)
                {
                    initialize(this.csmTestFactory);
                }

                SetupManagementClients();

                helper.SetupEnvironment(AzureModule.AzureResourceManager);

                var callingClassName = callingClassType
                                       .Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries)
                                       .Last();
                helper.SetupModules(
                    AzureModule.AzureResourceManager,
                    "ScenarioTests\\Common.ps1",
                    "ScenarioTests\\" + callingClassName + ".ps1",
                    "ResourceManagerStartup.ps1");

                try
                {
                    if (scriptBuilder != null)
                    {
                        var psScripts = scriptBuilder();

                        if (psScripts != null)
                        {
                            helper.RunPowerShellTest(psScripts);
                        }
                    }
                }
                finally
                {
                    if (cleanup != null)
                    {
                        cleanup();
                    }
                }
            }
        }
Esempio n. 14
0
        public void RunPsTestWorkflow(
            Func<string[]> scriptBuilder,
            Action initialize,
            Action cleanup,
            string callingClassType,
            string mockName)
        {
            HttpMockServer.Matcher = new PermissiveRecordMatcher();
            using (UndoContext context = UndoContext.Current)
            {
                context.Start(callingClassType, mockName);
                this.csmTestFactory = SetupCSMTestEnvironmentFactory();
                SetupManagementClients();

                helper.SetupEnvironment(AzureModule.AzureResourceManager);

                var callingClassName = callingClassType
                                        .Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries)
                                        .Last();
                helper.SetupModules(
                    AzureModule.AzureResourceManager,
                    "ScenarioTests\\Common.ps1",
                    "ScenarioTests\\" + callingClassName + ".ps1",
                    "Microsoft.Azure.Commands.Batch.Test.dll"
                    );

                try
                {
                    if (initialize != null)
                    {
                        initialize();
                    }

                    if (scriptBuilder != null)
                    {
                        var psScripts = scriptBuilder();

                        if (psScripts != null)
                        {
                            helper.RunPowerShellTest(psScripts);
                        }
                    }
                }
                finally
                {
                    if (cleanup != null)
                    {
                        cleanup();
                    }
                }
            }
        }
        /// <summary>
        /// Default constructor for management clients, using the TestSupport Infrastructure
        /// </summary>
        /// <param name="testBase">the test class</param>
        /// <returns>A recovery services management client, created from the current context (environment variables)</returns>
        public static RecoveryServicesManagementClient GetRecoveryServicesManagementClient(this TestBase testBase)
        {
            TestEnvironment environment = new CSMTestEnvironmentFactory().GetTestEnvironment();

            if (ServicePointManager.ServerCertificateValidationCallback == null)
            {
                ServicePointManager.ServerCertificateValidationCallback =
                    IgnoreCertificateErrorHandler;
            }

            return new RecoveryServicesManagementClient(
                (SubscriptionCloudCredentials)environment.Credentials,
                environment.BaseUri).WithHandler(HttpMockServer.CreateInstance());
        }
        /// <summary>
        /// Default constructor for management clients, using the TestSupport Infrastructure
        /// </summary>
        /// <param name="testBase">the test class</param>
        /// <returns>A recovery services management client, created from the current context (environment variables)</returns>
        public static RecoveryServicesManagementClient GetRecoveryServicesManagementClient(this TestBase testBase)
        {
            TestEnvironment environment = new CSMTestEnvironmentFactory().GetTestEnvironment();

            if (ServicePointManager.ServerCertificateValidationCallback == null)
            {
                ServicePointManager.ServerCertificateValidationCallback =
                    IgnoreCertificateErrorHandler;
            }

            return(new RecoveryServicesManagementClient(
                       (SubscriptionCloudCredentials)environment.Credentials,
                       environment.BaseUri).WithHandler(HttpMockServer.CreateInstance()));
        }
        private SearchIndexClient GetSearchIndexClientForKey(string indexName, string apiKey)
        {
            var             factory            = new CSMTestEnvironmentFactory();
            TestEnvironment currentEnvironment = factory.GetTestEnvironment();

            Uri baseUri =
                new Uri(
                    currentEnvironment.GetBaseSearchUri(ExecutionMode.CSM, SearchServiceName),
                    String.Format("indexes/{0}/", indexName));

            SearchIndexClient client = new SearchIndexClient(new SearchCredentials(apiKey), baseUri);

            return(TestBaseCopy.AddMockHandler <SearchIndexClient>(ref client));
        }
Esempio n. 18
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (HttpMockServer.Mode == HttpRecorderMode.Record && initialized)
                {
                    var testFactory     = new CSMTestEnvironmentFactory();
                    var testEnv         = testFactory.GetTestEnvironment();
                    var resourcesClient = TestBase.GetServiceClient <ResourceManagementClient>(testFactory);

                    resourcesClient.ResourceGroups.Delete(resourceGroupName);
                }
            }
        }
        public void SetupEnvironment()
        {
            base.SetupEnvironment(AzureModule.AzureResourceManager);

            TestEnvironment csmEnvironment = new CSMTestEnvironmentFactory().GetTestEnvironment();

            if (csmEnvironment.SubscriptionId != null)
            {
                //Overwrite the default subscription and default account
                //with ones using user ID and tenant ID from auth context
                var user = GetUser(csmEnvironment);
                var tenantId = GetTenantId(csmEnvironment);                

                var testSubscription = new AzureSubscription()
                {
                    Id = new Guid(csmEnvironment.SubscriptionId),
                    Name = ProfileClient.Profile.DefaultSubscription.Name,
                    Environment = ProfileClient.Profile.DefaultSubscription.Environment,
                    Account = user,
                    Properties = new Dictionary<AzureSubscription.Property, string>
                    {
                        {AzureSubscription.Property.Default, "True"},
                        {
                            AzureSubscription.Property.StorageAccount,
                            Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT")
                        },
                        {AzureSubscription.Property.Tenants, tenantId},
                    }
                };

                var testAccount = new AzureAccount()
                {
                    Id = user,
                    Type = AzureAccount.AccountType.User,
                    Properties = new Dictionary<AzureAccount.Property, string>
                    {
                        {AzureAccount.Property.Subscriptions, csmEnvironment.SubscriptionId},
                    }
                };

                ProfileClient.Profile.Accounts.Remove(ProfileClient.Profile.DefaultSubscription.Account);
                ProfileClient.Profile.Subscriptions[testSubscription.Id] = testSubscription;
                ProfileClient.Profile.Accounts[testAccount.Id] = testAccount;                
                ProfileClient.SetSubscriptionAsDefault(testSubscription.Name, testSubscription.Account);
                
                ProfileClient.Profile.Save();
            }
        }
Esempio n. 20
0
        public void SetupEnvironment()
        {
            base.SetupEnvironment(AzureModule.AzureResourceManager);

            TestEnvironment csmEnvironment = new CSMTestEnvironmentFactory().GetTestEnvironment();

            if (csmEnvironment.SubscriptionId != null)
            {
                //Overwrite the default subscription and default account
                //with ones using user ID and tenant ID from auth context
                var user     = GetUser(csmEnvironment);
                var tenantId = GetTenantId(csmEnvironment);

                var testSubscription = new AzureSubscription()
                {
                    Id          = new Guid(csmEnvironment.SubscriptionId),
                    Name        = ProfileClient.Profile.DefaultSubscription.Name,
                    Environment = ProfileClient.Profile.DefaultSubscription.Environment,
                    Account     = user,
                    Properties  = new Dictionary <AzureSubscription.Property, string>
                    {
                        { AzureSubscription.Property.Default, "True" },
                        {
                            AzureSubscription.Property.StorageAccount,
                            Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT")
                        },
                        { AzureSubscription.Property.Tenants, tenantId },
                    }
                };

                var testAccount = new AzureAccount()
                {
                    Id         = user,
                    Type       = AzureAccount.AccountType.User,
                    Properties = new Dictionary <AzureAccount.Property, string>
                    {
                        { AzureAccount.Property.Subscriptions, csmEnvironment.SubscriptionId },
                    }
                };

                ProfileClient.Profile.Accounts.Remove(ProfileClient.Profile.DefaultSubscription.Account);
                ProfileClient.Profile.Subscriptions[testSubscription.Id] = testSubscription;
                ProfileClient.Profile.Accounts[testAccount.Id]           = testAccount;
                ProfileClient.SetSubscriptionAsDefault(testSubscription.Name, testSubscription.Account);

                ProfileClient.Profile.Save();
            }
        }
        public static void RefreshAccessToken(this ApiManagementClient apiManagementClient)
        {
            if (HttpMockServer.Mode == HttpRecorderMode.Playback)
            {
                // if it's playback then do nothing
                return;
            }

            var testEnvironment = new CSMTestEnvironmentFactory().GetTestEnvironment();
            var context = new AuthenticationContext(new Uri(testEnvironment.Endpoints.AADAuthUri, testEnvironment.Tenant).AbsoluteUri);

            var result = context.AcquireToken("https://management.core.windows.net/", testEnvironment.ClientId, new Uri("urn:ietf:wg:oauth:2.0:oob"), PromptBehavior.Auto);
            var newToken = context.AcquireTokenByRefreshToken(result.RefreshToken, testEnvironment.ClientId, "https://management.core.windows.net/");

            ((TokenCloudCredentials) apiManagementClient.Credentials).Token = newToken.AccessToken;
        }
        public static void RefreshAccessToken(this ApiManagementClient apiManagementClient)
        {
            if (HttpMockServer.Mode == HttpRecorderMode.Playback)
            {
                // if it's playback then do nothing
                return;
            }

            var testEnvironment = new CSMTestEnvironmentFactory().GetTestEnvironment();
            var context         = new AuthenticationContext(new Uri(testEnvironment.Endpoints.AADAuthUri, testEnvironment.Tenant).AbsoluteUri);

            var result   = context.AcquireToken("https://management.core.windows.net/", testEnvironment.ClientId, new Uri("urn:ietf:wg:oauth:2.0:oob"), PromptBehavior.Auto);
            var newToken = context.AcquireTokenByRefreshToken(result.RefreshToken, testEnvironment.ClientId, "https://management.core.windows.net/");

            ((TokenCloudCredentials)apiManagementClient.Credentials).Token = newToken.AccessToken;
        }
        public void Dispose()
        {
            if (HttpMockServer.Mode == HttpRecorderMode.Record && !fromConfig)
            {
                var testFactory     = new CSMTestEnvironmentFactory();
                var testEnv         = testFactory.GetTestEnvironment();
                var mgmtClient      = TestBase.GetServiceClient <KeyVaultManagementClient>(testFactory);
                var resourcesClient = TestBase.GetServiceClient <ResourceManagementClient>(testFactory);
                var tenantId        = testEnv.AuthorizationContext.TenatId;
                var graphClient     = TestBase.GetGraphServiceClient <GraphRbacManagementClient>(testFactory, tenantId);

                mgmtClient.Vaults.Delete(rgName, vaultName);
                graphClient.Application.Delete(appObjectId);
                resourcesClient.ResourceGroups.Delete(rgName);
            }
        }
Esempio n. 24
0
        protected void RunPowerShellTest(params string[] scripts)
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start(TestUtilities.GetCallingClass(2), TestUtilities.GetCurrentMethodName(2));

                this.armTestFactory = new CSMTestEnvironmentFactory();

                SetupManagementClients();

                helper.SetupEnvironment(AzureModule.AzureServiceManagement);
                helper.SetupModules(AzureModule.AzureResourceManager,
                                    "ScenarioTests\\" + this.GetType().Name + ".ps1");

                helper.RunPowerShellTest(scripts);
            }
        }
Esempio n. 25
0
        /// <summary>
        /// This overrides the default subscription and default account. This allows the
        /// test to get the tenant id in the test.
        /// </summary>
        public void SetupEnvironment()
        {
            base.SetupEnvironment(AzureModule.AzureResourceManager);

            TestEnvironment csmEnvironment = new CSMTestEnvironmentFactory().GetTestEnvironment();

            if (csmEnvironment.SubscriptionId != null)
            {
                //Overwrite the default subscription and default account
                //with ones using user ID and tenant ID from auth context
                var user     = GetUser(csmEnvironment);
                var tenantId = GetTenantId(csmEnvironment);

                // Existing test will not have a user or tenant id set
                if (tenantId != null && user != null)
                {
                    var testSubscription = new AzureSubscription()
                    {
                        Id   = csmEnvironment.SubscriptionId,
                        Name = AzureRmProfileProvider.Instance.Profile.DefaultContext.Subscription.Name,
                    };

                    testSubscription.SetAccount(user);
                    testSubscription.SetEnvironment(AzureRmProfileProvider.Instance.Profile.DefaultContext.Subscription.GetEnvironment());
                    testSubscription.SetDefault();
                    testSubscription.SetStorageAccount(Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT"));
                    testSubscription.SetTenant(tenantId);
                    var testAccount = new AzureAccount()
                    {
                        Id   = user,
                        Type = AzureAccount.AccountType.User,
                    };

                    testAccount.SetSubscriptions(csmEnvironment.SubscriptionId);

                    AzureRmProfileProvider.Instance.Profile.DefaultContext.Subscription.Name = testSubscription.Name;
                    AzureRmProfileProvider.Instance.Profile.DefaultContext.Subscription.Id   = testSubscription.Id;
                    AzureRmProfileProvider.Instance.Profile.DefaultContext.Subscription.SetAccount(testSubscription.GetAccount());

                    var environment = AzureRmProfileProvider.Instance.Profile.GetEnvironment(AzureRmProfileProvider.Instance.Profile.DefaultContext.Subscription.GetEnvironment());
                    environment.SetEndpoint(AzureEnvironment.Endpoint.Graph, csmEnvironment.Endpoints.GraphUri.AbsoluteUri);
                    environment.SetEndpoint(AzureEnvironment.Endpoint.StorageEndpointSuffix, "core.windows.net");
                    AzureRmProfileProvider.Instance.GetProfile <AzureRmProfile>().Save();
                }
            }
        }
Esempio n. 26
0
        public KeyVaultTestBase()
        {
            var testFactory = new CSMTestEnvironmentFactory();
            var testEnv     = testFactory.GetTestEnvironment();

            this.client          = GetServiceClient <KeyVaultManagementClient>(testFactory);
            this.resourcesClient = GetServiceClient <ResourceManagementClient>(testFactory);

            if (HttpMockServer.Mode == HttpRecorderMode.Record)
            {
                this.tenantId       = testEnv.AuthorizationContext.TenantId;
                this.subscriptionId = testEnv.SubscriptionId;
                var graphClient = GetGraphServiceClient <GraphRbacManagementClient>(testFactory, tenantId);
                this.objectId      = graphClient.User.Get(testEnv.AuthorizationContext.UserId).User.ObjectId;
                this.applicationId = Guid.NewGuid().ToString();
                HttpMockServer.Variables[TenantIdKey]      = tenantId;
                HttpMockServer.Variables[ObjectIdKey]      = objectId;
                HttpMockServer.Variables[SubIdKey]         = subscriptionId;
                HttpMockServer.Variables[ApplicationIdKey] = applicationId;
            }
            else if (HttpMockServer.Mode == HttpRecorderMode.Playback)
            {
                tenantId       = HttpMockServer.Variables[TenantIdKey];
                objectId       = HttpMockServer.Variables[ObjectIdKey];
                subscriptionId = HttpMockServer.Variables[SubIdKey];
                applicationId  = HttpMockServer.Variables[ApplicationIdKey];
            }

            var providers = resourcesClient.Providers.Get("Microsoft.KeyVault");

            this.location = providers.Provider.ResourceTypes.Where(
                (resType) =>
            {
                if (resType.Name == "vaults")
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
                ).First().Locations.FirstOrDefault();
        }
Esempio n. 27
0
        public void Initialize(string className)
        {
            if (initialized)
            {
                return;
            }

            HttpMockServer server;

            try
            {
                server = HttpMockServer.CreateInstance();
            }
            catch (ApplicationException)
            {
                // mock server has never been initialized, we will need to initialize it.
                HttpMockServer.Initialize(className, "InitialCreation");
                server = HttpMockServer.CreateInstance();
            }

            if (HttpMockServer.Mode == HttpRecorderMode.Record)
            {
                var testFactory     = new CSMTestEnvironmentFactory();
                var testEnv         = testFactory.GetTestEnvironment();
                var resourcesClient = TestBase.GetServiceClient <ResourceManagementClient>(testFactory);
                var mgmtClient      = TestBase.GetServiceClient <KeyVaultManagementClient>(testFactory);
                var tenantId        = testEnv.AuthorizationContext.TenantId;

                //Figure out which locations are available for Key Vault
                location = GetKeyVaultLocation(resourcesClient);

                //Create a resource group in that location
                preCreatedVault   = TestUtilities.GenerateName("pshtestvault");
                resourceGroupName = TestUtilities.GenerateName("pshtestrg");

                resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup {
                    Location = location
                });
                var createResponse = CreateVault(mgmtClient, location, tenantId);
            }

            initialized = true;
        }
        public KeyVaultTestBase()
        {
            var testFactory = new CSMTestEnvironmentFactory();
            var testEnv = testFactory.GetTestEnvironment();
            this.client = GetServiceClient<KeyVaultManagementClient>(testFactory);
            this.resourcesClient = GetServiceClient<ResourceManagementClient>(testFactory);
            
            if (HttpMockServer.Mode == HttpRecorderMode.Record)
            {
                this.tenantId = testEnv.AuthorizationContext.TenatId;
                this.subscriptionId = testEnv.SubscriptionId;
                var graphClient = GetGraphServiceClient<GraphRbacManagementClient>(testFactory, tenantId);
                this.objectId = graphClient.User.Get(testEnv.AuthorizationContext.UserId).User.ObjectId;
                this.applicationId = Guid.NewGuid().ToString();                
                HttpMockServer.Variables[TenantIdKey] = tenantId;
                HttpMockServer.Variables[ObjectIdKey] = objectId;
                HttpMockServer.Variables[SubIdKey] = subscriptionId;
                HttpMockServer.Variables[ApplicationIdKey] = applicationId;
            }
            else if (HttpMockServer.Mode == HttpRecorderMode.Playback)
            {
                tenantId = HttpMockServer.Variables[TenantIdKey];
                objectId = HttpMockServer.Variables[ObjectIdKey];
                subscriptionId = HttpMockServer.Variables[SubIdKey];
                applicationId = HttpMockServer.Variables[ApplicationIdKey];
            }

            var providers = resourcesClient.Providers.Get("Microsoft.KeyVault");
            this.location = providers.Provider.ResourceTypes.Where(
                (resType) =>
                {
                    if (resType.Name == "vaults")
                        return true;
                    else
                        return false;
                }
                ).First().Locations.FirstOrDefault();

        }
        public void Initialize(string className)
        {
            if (initialized)
                return;

            HttpMockServer server;

            try
            {
                server = HttpMockServer.CreateInstance();
            }
            catch (ApplicationException)
            {
                // mock server has never been initialized, we will need to initialize it.
                HttpMockServer.Initialize(className, "InitialCreation");
                server = HttpMockServer.CreateInstance();
            }

            if (HttpMockServer.Mode == HttpRecorderMode.Record)
            {
                var testFactory = new CSMTestEnvironmentFactory();
                var testEnv = testFactory.GetTestEnvironment();
                var resourcesClient = TestBase.GetServiceClient<ResourceManagementClient>(testFactory);
                var mgmtClient = TestBase.GetServiceClient<KeyVaultManagementClient>(testFactory);
                var tenantId = testEnv.AuthorizationContext.TenantId;                

                //Figure out which locations are available for Key Vault
                location = GetKeyVaultLocation(resourcesClient);

                //Create a resource group in that location
                preCreatedVault = TestUtilities.GenerateName("pshtestvault");
                resourceGroupName = TestUtilities.GenerateName("pshtestrg");

                resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = location });
                var createResponse = CreateVault(mgmtClient, location, tenantId);                
            }

            initialized = true;
        }
        /// <summary>
        /// Default constructor for management clients, using the TestSupport Infrastructure
        /// </summary>
        /// <param name="testBase">the test class</param>
        /// <returns>A site recovery management client, created from the current context (environment variables)</returns>
        public static SiteRecoveryManagementClient GetSiteRecoveryManagementClient(this TestBase testBase, String scenario = "")
        {
            if (ServicePointManager.ServerCertificateValidationCallback == null)
            {
                ServicePointManager.ServerCertificateValidationCallback =
                    IgnoreCertificateErrorHandler;
            }

            TestEnvironment environment = new CSMTestEnvironmentFactory().GetTestEnvironment();

            switch (scenario)
            {
            case Constants.A2A:
                SiteRecoveryTestsBase.MyVaultName         = "integrationTest1";
                SiteRecoveryTestsBase.MyResourceGroupName = "rg1";
                SiteRecoveryTestsBase.ResourceNamespace   = "Microsoft.RecoveryServicesBVTD2";
                SiteRecoveryTestsBase.ResourceType        = "RecoveryServicesVault";
                environment.BaseUri = new Uri("https://sriramvu:8443/Rdfeproxy.svc");
                break;

            default:
                SiteRecoveryTestsBase.MyVaultName         = "hydratest";
                SiteRecoveryTestsBase.VaultKey            = "loMUdckuT9SEvpQKcSG07A==";
                SiteRecoveryTestsBase.MyResourceGroupName = "RecoveryServices-WHNOWF6LI6NM4B55QDIYR3YG3YAEZNTDUOWHPQX7NJB2LHDGTXJA-West-US";
                SiteRecoveryTestsBase.ResourceNamespace   = "Microsoft.SiteRecoveryBVTD2";
                SiteRecoveryTestsBase.ResourceType        = "SiteRecoveryVault";
                break;
            }
            ;

            return(new SiteRecoveryManagementClient(
                       SiteRecoveryTestsBase.MyVaultName,
                       SiteRecoveryTestsBase.MyResourceGroupName,
                       SiteRecoveryTestsBase.ResourceNamespace,
                       SiteRecoveryTestsBase.ResourceType,
                       (SubscriptionCloudCredentials)environment.Credentials,
                       environment.BaseUri).WithHandler(HttpMockServer.CreateInstance()));
        }
        /// <summary>
        /// Default constructor for management clients, using the TestSupport Infrastructure
        /// </summary>
        /// <param name="testBase">the test class</param>
        /// <returns>A site recovery management client, created from the current context (environment variables)</returns>
        public static SiteRecoveryManagementClient GetSiteRecoveryManagementClient(this TestBase testBase, String scenario = "")
        {
            if (ServicePointManager.ServerCertificateValidationCallback == null)
            {
                ServicePointManager.ServerCertificateValidationCallback =
                    IgnoreCertificateErrorHandler;
            }

            TestEnvironment environment = new CSMTestEnvironmentFactory().GetTestEnvironment();

            switch(scenario)
            {
                case Constants.A2A:
                    SiteRecoveryTestsBase.MyVaultName = "integrationTest1";
                    SiteRecoveryTestsBase.MyResourceGroupName = "rg1";
                    SiteRecoveryTestsBase.ResourceNamespace = "Microsoft.RecoveryServicesBVTD2";
                    SiteRecoveryTestsBase.ResourceType = "RecoveryServicesVault";
                    environment.BaseUri = new Uri("https://sriramvu:8443/Rdfeproxy.svc");
                    break;
                
                default:
                    SiteRecoveryTestsBase.MyVaultName = "hydratest";
                    SiteRecoveryTestsBase.VaultKey = "loMUdckuT9SEvpQKcSG07A==";
                    SiteRecoveryTestsBase.MyResourceGroupName = "RecoveryServices-WHNOWF6LI6NM4B55QDIYR3YG3YAEZNTDUOWHPQX7NJB2LHDGTXJA-West-US";
                    SiteRecoveryTestsBase.ResourceNamespace = "Microsoft.SiteRecoveryBVTD2";
                    SiteRecoveryTestsBase.ResourceType = "SiteRecoveryVault";
                    break;
            };

            return new SiteRecoveryManagementClient(
                SiteRecoveryTestsBase.MyVaultName,
                SiteRecoveryTestsBase.MyResourceGroupName,
                SiteRecoveryTestsBase.ResourceNamespace,
                SiteRecoveryTestsBase.ResourceType,
                (SubscriptionCloudCredentials)environment.Credentials,
                environment.BaseUri).WithHandler(HttpMockServer.CreateInstance());
        }
        public void SetupEnvironment()
        {
            base.SetupEnvironment(AzureModule.AzureResourceManager);

            TestEnvironment csmEnvironment = new CSMTestEnvironmentFactory().GetTestEnvironment();

            if (csmEnvironment.SubscriptionId != null)
            {
                //Overwrite the default subscription and default account
                //with ones using user ID and tenant ID from auth context
                var user     = GetUser(csmEnvironment);
                var tenantId = GetTenantId(csmEnvironment);

                var context          = AzureRmProfileProvider.Instance.Profile.DefaultContext;
                var testSubscription = new AzureSubscription()
                {
                    Id   = csmEnvironment.SubscriptionId,
                    Name = context.Subscription.Name
                };
                testSubscription.SetEnvironment(context.Environment.Name);
                testSubscription.SetAccount(user);
                testSubscription.SetDefault();
                testSubscription.SetStorageAccount(Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT"));
                testSubscription.SetTenant(tenantId);

                var testAccount = new AzureAccount()
                {
                    Id   = user,
                    Type = AzureAccount.AccountType.User
                };
                testAccount.SetSubscriptions(csmEnvironment.SubscriptionId);

                AzureRmProfileProvider.Instance.Profile.DefaultContext = new AzureContext(testSubscription, testAccount, context.Environment, new AzureTenant {
                    Id = tenantId
                });
            }
        }
Esempio n. 33
0
        public GraphTestBase()
        {
            var testFactory = new CSMTestEnvironmentFactory();
            TestEnvironment environment = testFactory.GetTestEnvironment();

            string tenantId = null;
            if (HttpMockServer.Mode == HttpRecorderMode.Record)
            {
                tenantId = environment.AuthorizationContext.TenantId;
                Domain = environment.AuthorizationContext.UserId
                            .Split(new [] {"@"}, StringSplitOptions.RemoveEmptyEntries)
                            .Last();

                HttpMockServer.Variables[TenantIdKey] = tenantId;
                HttpMockServer.Variables[DomainKey] = Domain;
            }
            else if (HttpMockServer.Mode == HttpRecorderMode.Playback)
            {
                tenantId = HttpMockServer.Variables[TenantIdKey];
                Domain = HttpMockServer.Variables[DomainKey];
            }

            GraphClient = TestBase.GetGraphServiceClient<GraphRbacManagementClient>(testFactory, tenantId);
        }
Esempio n. 34
0
        public void RunPsTestWorkflow(
            Func<string[]> scriptBuilder,
            Action<CSMTestEnvironmentFactory> initialize,
            Action cleanup,
            string callingClassType,
            string mockName)
        {

            var d = new Dictionary<string, string>();
            d.Add("Microsoft.Resources", null);
            d.Add("Microsoft.Features", null);
            d.Add("Microsoft.Authorization", null);
            d.Add("Microsoft.Compute", null);
            var providersToIgnore = new Dictionary<string, string>();
            providersToIgnore.Add("Microsoft.Azure.Management.Resources.ResourceManagementClient", "2016-02-01");
            HttpMockServer.Matcher = new PermissiveRecordMatcherWithApiExclusion(true, d, providersToIgnore);

            HttpMockServer.RecordsDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SessionRecords");

            using (var context = MockContext.Start(callingClassType, mockName))
            {

                _csmTestFactory = new CSMTestEnvironmentFactory();

                if (initialize != null)
                {
                    initialize(_csmTestFactory);
                }

                SetupManagementClients(context);

                _helper.SetupEnvironment(AzureModule.AzureResourceManager);

                var callingClassName = callingClassType
                                        .Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries)
                                        .Last();

                _helper.SetupModules(AzureModule.AzureResourceManager,
                    "ScenarioTests\\Common.ps1",
                    "ScenarioTests\\" + callingClassName + ".ps1",
                    _helper.RMProfileModule,
                    _helper.RMResourceModule,
                    @"AzureRM.Cdn.psd1");

                try
                {
                    if (scriptBuilder != null)
                    {
                        var psScripts = scriptBuilder();

                        if (psScripts != null)
                        {
                            _helper.RunPowerShellTest(psScripts);
                        }
                    }
                }
                finally
                {
                    if (cleanup != null)
                    {
                        cleanup();
                    }
                }
            }
        }
Esempio n. 35
0
        public void RunPsTestWorkflow(
            PsBackupProviderTypes providerType,
            Func <string[]> scriptBuilder,
            Action <CSMTestEnvironmentFactory> initialize,
            Action cleanup,
            string callingClassType,
            string mockName)
        {
            Dictionary <string, string> providers = new Dictionary <string, string>();

            providers.Add("Microsoft.Resources", null);
            providers.Add("Microsoft.Features", null);
            providers.Add("Microsoft.Authorization", null);
            providers.Add("Microsoft.Compute", null);
            var providersToIgnore = new Dictionary <string, string>();

            providersToIgnore.Add("Microsoft.Azure.Management.Resources.ResourceManagementClient", "2016-02-01");
            HttpMockServer.Matcher = new PermissiveRecordMatcherWithApiExclusion(true, providers, providersToIgnore);

            HttpMockServer.RecordsDirectory =
                Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SessionRecords");

            using (RestTestFramework.MockContext context =
                       RestTestFramework.MockContext.Start(callingClassType, mockName))
            {
                csmTestFactory = new CSMTestEnvironmentFactory();

                if (initialize != null)
                {
                    initialize.Invoke(csmTestFactory);
                }

                SetupManagementClients(context);

                helper.SetupEnvironment(AzureModule.AzureResourceManager);

                var testFolderName   = providerType.ToString();
                var callingClassName =
                    callingClassType
                    .Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries).Last();
                string psFile =
                    "ScenarioTests\\" + testFolderName + "\\" + callingClassName + ".ps1";
                string commonPsFile               = "ScenarioTests\\" + testFolderName + "\\Common.ps1";
                string rmProfileModule            = helper.RMProfileModule;
                string rmModulePath               = helper.GetRMModulePath("AzureRM.RecoveryServices.Backup.psd1");
                string recoveryServicesModulePath =
                    helper.GetRMModulePath("AzureRM.RecoveryServices.psd1");

                List <string> modules = new List <string>();

                if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, commonPsFile)))
                {
                    modules.Add(commonPsFile);
                }

                modules.Add(psFile);
                modules.Add(rmProfileModule);
                modules.Add(rmModulePath);
                modules.Add(recoveryServicesModulePath);

                helper.SetupModules(AzureModule.AzureResourceManager, modules.ToArray());

                try
                {
                    if (scriptBuilder != null)
                    {
                        var psScripts = scriptBuilder();

                        if (psScripts != null)
                        {
                            helper.RunPowerShellTest(psScripts);
                        }
                    }
                }
                finally
                {
                    if (cleanup != null)
                    {
                        cleanup.Invoke();
                    }
                }
            }
        }
        private void SetupAzureEnvironmentFromEnvironmentVariables(AzureModule mode)
        {
            TestEnvironment currentEnvironment = null;

            if (mode == AzureModule.AzureResourceManager)
            {
#if !NETSTANDARD
                currentEnvironment = new CSMTestEnvironmentFactory().GetTestEnvironment();
#else
                currentEnvironment = TestEnvironmentFactory.GetTestEnvironment();
#endif
            }
            else
            {
#if !NETSTANDARD
                currentEnvironment = new RDFETestEnvironmentFactory().GetTestEnvironment();
#else
                throw new NotSupportedException("RDFE environment is not supported in .Net Core");
#endif
            }

            if (currentEnvironment.UserName == null)
            {
                currentEnvironment.UserName = "******";
            }

            SetAuthenticationFactory(mode, currentEnvironment);

            AzureEnvironment environment = new AzureEnvironment {
                Name = testEnvironmentName
            };

            Debug.Assert(currentEnvironment != null);
            environment.ActiveDirectoryAuthority = currentEnvironment.Endpoints.AADAuthUri.AbsoluteUri;
            environment.GalleryUrl           = currentEnvironment.Endpoints.GalleryUri.AbsoluteUri;
            environment.ServiceManagementUrl = currentEnvironment.BaseUri.AbsoluteUri;
            environment.ResourceManagerUrl   = currentEnvironment.Endpoints.ResourceManagementUri.AbsoluteUri;
            environment.GraphUrl             = currentEnvironment.Endpoints.GraphUri.AbsoluteUri;
            environment.AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix = currentEnvironment.Endpoints.DataLakeAnalyticsJobAndCatalogServiceUri.OriginalString.Replace("https://", ""); // because it is just a sufix
            environment.AzureDataLakeStoreFileSystemEndpointSuffix        = currentEnvironment.Endpoints.DataLakeStoreServiceUri.OriginalString.Replace("https://", "");                  // because it is just a sufix
#if !NETSTANDARD
            if (!ProfileClient.Profile.EnvironmentTable.ContainsKey(testEnvironmentName))
            {
                ProfileClient.AddOrSetEnvironment(environment);
            }
#endif
            if (!AzureRmProfileProvider.Instance.GetProfile <AzureRmProfile>().EnvironmentTable.ContainsKey(testEnvironmentName))
            {
                AzureRmProfileProvider.Instance.GetProfile <AzureRmProfile>().EnvironmentTable[testEnvironmentName] = environment;
            }

            if (currentEnvironment.SubscriptionId != null)
            {
                testSubscription = new AzureSubscription()
                {
                    Id   = currentEnvironment.SubscriptionId,
                    Name = testSubscriptionName,
                };

                testSubscription.SetEnvironment(testEnvironmentName);
                testSubscription.SetAccount(currentEnvironment.UserName);
                testSubscription.SetDefault();
                testSubscription.SetStorageAccount(Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT"));

                testAccount = new AzureAccount()
                {
                    Id   = currentEnvironment.UserName,
                    Type = AzureAccount.AccountType.User,
                };

                testAccount.SetSubscriptions(currentEnvironment.SubscriptionId);
#if !NETSTANDARD
                ProfileClient.Profile.SubscriptionTable[testSubscription.GetId()] = testSubscription;
                ProfileClient.Profile.AccountTable[testAccount.Id] = testAccount;
                ProfileClient.SetSubscriptionAsDefault(testSubscription.Name, testSubscription.GetAccount());
#endif
                var testTenant = new AzureTenant()
                {
                    Id = Guid.NewGuid().ToString()
                };
                if (!string.IsNullOrEmpty(currentEnvironment.Tenant))
                {
                    Guid tenant;
                    if (Guid.TryParse(currentEnvironment.Tenant, out tenant))
                    {
                        testTenant.Id = currentEnvironment.Tenant;
                    }
                }
                AzureRmProfileProvider.Instance.Profile.DefaultContext = new AzureContext(testSubscription, testAccount, environment, testTenant);
            }
        }
 private CSMTestEnvironmentFactory SetupCSMTestEnvironmentFactory()
 {
     CSMTestEnvironmentFactory factory = new CSMTestEnvironmentFactory();
     // to set test environment to Current add Environment=Current in TEST_CSM_ORGID_AUTHENTICATION env. variable
     // available configurations are: Prod/Dogfood/Next/Current
     return factory;
 }
        public void RunPsTestWorkflow(
            Func<string[]> scriptBuilder, 
            Action<CSMTestEnvironmentFactory> initialize, 
            Action cleanup,
            string callingClassType,
            string mockName)
        {
            Dictionary<string, string> d = new Dictionary<string, string>();
            d.Add("Microsoft.Authorization", null);
            HttpMockServer.Matcher = new PermissiveRecordMatcherWithApiExclusion(false, d);

            using (RestTestFramework.MockContext context = RestTestFramework.MockContext.Start(callingClassType, mockName))
            {
                this.csmTestFactory = new CSMTestEnvironmentFactory();

                if(initialize != null)
                {
                    initialize(this.csmTestFactory);
                }

                SetupManagementClients(context);

                helper.SetupEnvironment(AzureModule.AzureResourceManager);
                
                var callingClassName = callingClassType
                                        .Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries)
                                        .Last();
                helper.SetupModules(AzureModule.AzureResourceManager, 
                    "ScenarioTests\\Common.ps1", 
                    "ScenarioTests\\ComputeTestCommon.ps1", 
                    "ScenarioTests\\" + callingClassName + ".ps1", 
                    helper.RMProfileModule,
                    helper.RMResourceModule,
                    helper.RMStorageDataPlaneModule,
                    helper.RMStorageModule,
                    helper.GetRMModulePath("AzureRM.Compute.psd1"),
                    helper.GetRMModulePath("AzureRM.Network.psd1"));

                try
                {
                    if (scriptBuilder != null)
                    {
                        var psScripts = scriptBuilder();

                        if (psScripts != null)
                        {
                            helper.RunPowerShellTest(psScripts);
                        }
                    }
                }
                finally
                {
                    if(cleanup !=null)
                    {
                        cleanup();
                    }
                }
            }
        }
        private void SetupAzureEnvironmentFromEnvironmentVariables(AzureModule mode)
        {
            TestEnvironment rdfeEnvironment    = new RDFETestEnvironmentFactory().GetTestEnvironment();
            TestEnvironment csmEnvironment     = new CSMTestEnvironmentFactory().GetTestEnvironment();
            TestEnvironment currentEnvironment = (mode == AzureModule.AzureResourceManager ? csmEnvironment : rdfeEnvironment);

            if (currentEnvironment.UserName == null)
            {
                currentEnvironment.UserName = "******";
            }

            SetAuthenticationFactory(mode, rdfeEnvironment, csmEnvironment);

            AzureEnvironment environment = new AzureEnvironment {
                Name = testEnvironmentName
            };

            Debug.Assert(currentEnvironment != null);
            environment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectory] = currentEnvironment.Endpoints.AADAuthUri.AbsoluteUri;
            environment.Endpoints[AzureEnvironment.Endpoint.Gallery]         = currentEnvironment.Endpoints.GalleryUri.AbsoluteUri;

            if (csmEnvironment != null)
            {
                environment.Endpoints[AzureEnvironment.Endpoint.ResourceManager] = csmEnvironment.BaseUri.AbsoluteUri;
            }

            if (rdfeEnvironment != null)
            {
                environment.Endpoints[AzureEnvironment.Endpoint.ServiceManagement] = rdfeEnvironment.BaseUri.AbsoluteUri;
            }

            if (!ProfileClient.Profile.Environments.ContainsKey(testEnvironmentName))
            {
                ProfileClient.AddOrSetEnvironment(environment);
            }

            if (currentEnvironment.SubscriptionId != null)
            {
                testSubscription = new AzureSubscription()
                {
                    Id          = new Guid(currentEnvironment.SubscriptionId),
                    Name        = testSubscriptionName,
                    Environment = testEnvironmentName,
                    Account     = currentEnvironment.UserName,
                    Properties  = new Dictionary <AzureSubscription.Property, string>
                    {
                        { AzureSubscription.Property.Default, "True" },
                        {
                            AzureSubscription.Property.StorageAccount,
                            Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT")
                        },
                    }
                };

                testAccount = new AzureAccount()
                {
                    Id         = currentEnvironment.UserName,
                    Type       = AzureAccount.AccountType.User,
                    Properties = new Dictionary <AzureAccount.Property, string>
                    {
                        { AzureAccount.Property.Subscriptions, currentEnvironment.SubscriptionId },
                    }
                };

                ProfileClient.Profile.Subscriptions[testSubscription.Id] = testSubscription;
                ProfileClient.Profile.Accounts[testAccount.Id]           = testAccount;
                ProfileClient.SetSubscriptionAsDefault(testSubscription.Name, testSubscription.Account);
            }
        }
Esempio n. 40
0
        public void RunPsTestWorkflow(
            Func <string[]> scriptBuilder,
            Action <CSMTestEnvironmentFactory> initialize,
            Action cleanup,
            string callingClassType,
            string mockName)
        {
            Dictionary <string, string> d = new Dictionary <string, string>();

            d.Add("Microsoft.Resources", null);
            d.Add("Microsoft.Features", null);
            d.Add("Microsoft.Authorization", null);
            d.Add("Microsoft.Compute", null);
            var providersToIgnore = new Dictionary <string, string>();

            providersToIgnore.Add("Microsoft.Azure.Management.Resources.ResourceManagementClient", "2016-02-01");
            HttpMockServer.Matcher = new PermissiveRecordMatcherWithApiExclusion(true, d, providersToIgnore);

            HttpMockServer.RecordsDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SessionRecords");
            using (MockContext context = MockContext.Start(callingClassType, mockName))
            {
                this.csmTestFactory = new CSMTestEnvironmentFactory();

                if (initialize != null)
                {
                    initialize(this.csmTestFactory);
                }

                SetupManagementClients(context);

                helper.SetupEnvironment(AzureModule.AzureResourceManager);

                var callingClassName = callingClassType
                                       .Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries)
                                       .Last();
                helper.SetupModules(AzureModule.AzureResourceManager,
                                    "ScenarioTests\\Common.ps1",
                                    "ScenarioTests\\" + callingClassName + ".ps1",
                                    helper.RMProfileModule,
                                    helper.RMResourceModule,
                                    helper.GetRMModulePath(@"AzureRM.DataMigration.psd1"),
                                    "AzureRM.Resources.ps1"
                                    );

                try
                {
                    if (scriptBuilder != null)
                    {
                        var psScripts = scriptBuilder();

                        if (psScripts != null)
                        {
                            helper.RunPowerShellTest(psScripts);
                        }
                    }
                }
                finally
                {
                    if (cleanup != null)
                    {
                        cleanup();
                    }
                }
            }
        }
Esempio n. 41
0
        /// <summary>
        /// Generate a Resource Management client from the test base to use for managing resource groups.
        /// </summary>
        /// <returns>Resource Management client</returns>
        public static ResourceManagementClient GetResourceClient(DelegatingHandler handler)
        {
            CSMTestEnvironmentFactory factory = new CSMTestEnvironmentFactory();

            return(TestBase.GetServiceClient <ResourceManagementClient>(factory).WithHandler(handler));
        }
Esempio n. 42
0
        private void RunPsTestWorkflow(
            Func <string[]> scriptBuilder,
            Action <CSMTestEnvironmentFactory> initialize,
            Action cleanup,
            string callingClassType,
            string mockName, string tenant)
        {
            Dictionary <string, string> d = new Dictionary <string, string>();

            d.Add("Microsoft.Resources", null);
            d.Add("Microsoft.Features", null);
            d.Add("Microsoft.Authorization", null);
            var providersToIgnore = new Dictionary <string, string>();

            providersToIgnore.Add("Microsoft.Azure.Management.Resources.ResourceManagementClient", "2016-02-01");
            HttpMockServer.Matcher = new PermissiveRecordMatcherWithApiExclusion(true, d, providersToIgnore);

            using (UndoContext context = UndoContext.Current)
            {
                context.Start(callingClassType, mockName);

                this.csmTestFactory = new CSMTestEnvironmentFactory();

                if (initialize != null)
                {
                    initialize(this.csmTestFactory);
                }

                SetupManagementClients();

                helper.SetupEnvironment(AzureModule.AzureResourceManager);
                var oldFactory = AzureSession.AuthenticationFactory as MockTokenAuthenticationFactory;
                AzureSession.AuthenticationFactory = new MockTokenAuthenticationFactory(oldFactory.Token.UserId, oldFactory.Token.AccessToken, tenant);

                var callingClassName = callingClassType
                                       .Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries)
                                       .Last();
                helper.SetupModules(AzureModule.AzureResourceManager,
                                    callingClassName + ".ps1",
                                    helper.RMProfileModule);

                try
                {
                    if (scriptBuilder != null)
                    {
                        var psScripts = scriptBuilder();

                        if (psScripts != null)
                        {
                            helper.RunPowerShellTest(psScripts);
                        }
                    }
                }
                finally
                {
                    if (cleanup != null)
                    {
                        cleanup();
                    }
                }
            }
        }
        private void SetupAzureEnvironmentFromEnvironmentVariables(AzureModule mode)
        {
            TestEnvironment rdfeEnvironment = new RDFETestEnvironmentFactory().GetTestEnvironment();
            TestEnvironment csmEnvironment = new CSMTestEnvironmentFactory().GetTestEnvironment();
            TestEnvironment currentEnvironment = (mode == AzureModule.AzureResourceManager ? csmEnvironment : rdfeEnvironment);

            string jwtToken;

            if (mode == AzureModule.AzureResourceManager)
            {
                jwtToken = csmEnvironment.Credentials != null ?
                ((TokenCloudCredentials)csmEnvironment.Credentials).Token : null;
            }
            else if (mode == AzureModule.AzureServiceManagement)
            {
                jwtToken = rdfeEnvironment.Credentials != null ?
                ((TokenCloudCredentials)rdfeEnvironment.Credentials).Token : null;
            }
            else
            {
                throw new ArgumentException("Invalid module mode.");
            }

            SetEndpointsToDefaults(rdfeEnvironment, csmEnvironment);

            /*
                WindowsAzureProfile.Instance.TokenProvider = new FakeAccessTokenProvider(
                jwtToken,
                csmEnvironment.UserName,
                csmEnvironment.AuthorizationContext == null ? null : csmEnvironment.AuthorizationContext.TenatId);
            */
            if (HttpMockServer.GetCurrentMode() == HttpRecorderMode.Playback)
            {
                AzureSession.AuthenticationFactory = new MockAuthenticationFactory();
            }
            else
            {
                AzureSession.AuthenticationFactory = new MockAuthenticationFactory(currentEnvironment.UserName, jwtToken);
            }

            AzureEnvironment environment = new AzureEnvironment { Name = testEnvironmentName };

            Debug.Assert(currentEnvironment != null);
            environment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectory] = currentEnvironment.ActiveDirectoryEndpoint.AbsoluteUri;
            environment.Endpoints[AzureEnvironment.Endpoint.Gallery] = currentEnvironment.GalleryUri.AbsoluteUri;

            if (csmEnvironment != null)
            {
                environment.Endpoints[AzureEnvironment.Endpoint.ResourceManager] = csmEnvironment.BaseUri.AbsoluteUri;                
            }

            if (rdfeEnvironment != null)
            {
                environment.Endpoints[AzureEnvironment.Endpoint.ServiceManagement] = rdfeEnvironment.BaseUri.AbsoluteUri;                
            }

            if (currentEnvironment.UserName == null)
            {
                currentEnvironment.UserName = "******";
            }

            if (!client.Profile.Environments.ContainsKey(testEnvironmentName))
            {
                client.AddOrSetEnvironment(environment);
            }

            testSubscription = new AzureSubscription()
            {
                Id = new Guid(currentEnvironment.SubscriptionId),
                Name = testSubscriptionName,
                Environment = testEnvironmentName,
                Account = currentEnvironment.UserName,
                Properties = new Dictionary<AzureSubscription.Property,string> 
                {
                     { AzureSubscription.Property.Default, "True"},
                     { AzureSubscription.Property.StorageAccount, Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT")},
                }
            };

            testAccount = new AzureAccount()
            {
                Id = currentEnvironment.UserName,
                Type = AzureAccount.AccountType.User,
                Properties = new Dictionary<AzureAccount.Property, string> 
                {
                     { AzureAccount.Property.Subscriptions, currentEnvironment.SubscriptionId},
                }
            };

            client.Profile.Subscriptions[testSubscription.Id] = testSubscription;
            client.Profile.Accounts[testAccount.Id] = testAccount;
            client.SetSubscriptionAsCurrent(testSubscription.Name, testSubscription.Account);
        }
        private void SetupAzureEnvironmentFromEnvironmentVariables(AzureModule mode)
        {
            TestEnvironment currentEnvironment = null;
            if (mode == AzureModule.AzureResourceManager)
            {
                currentEnvironment = new CSMTestEnvironmentFactory().GetTestEnvironment();
            }
            else
            {
                currentEnvironment = new RDFETestEnvironmentFactory().GetTestEnvironment();
            }

            if (currentEnvironment.UserName == null)
            {
                currentEnvironment.UserName = "******";
            }

            SetAuthenticationFactory(mode, currentEnvironment);

            AzureEnvironment environment = new AzureEnvironment { Name = testEnvironmentName };

            Debug.Assert(currentEnvironment != null);
            environment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectory] = currentEnvironment.Endpoints.AADAuthUri.AbsoluteUri;
            environment.Endpoints[AzureEnvironment.Endpoint.Gallery] = currentEnvironment.Endpoints.GalleryUri.AbsoluteUri;
            environment.Endpoints[AzureEnvironment.Endpoint.ServiceManagement] = currentEnvironment.BaseUri.AbsoluteUri;
            environment.Endpoints[AzureEnvironment.Endpoint.ResourceManager] = currentEnvironment.Endpoints.ResourceManagementUri.AbsoluteUri;
            environment.Endpoints[AzureEnvironment.Endpoint.Graph] = currentEnvironment.Endpoints.GraphUri.AbsoluteUri;
            environment.Endpoints[AzureEnvironment.Endpoint.AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix] = currentEnvironment.Endpoints.DataLakeAnalyticsJobAndCatalogServiceUri.OriginalString.Replace("https://", ""); // because it is just a sufix
            environment.Endpoints[AzureEnvironment.Endpoint.AzureDataLakeStoreFileSystemEndpointSuffix] = currentEnvironment.Endpoints.DataLakeStoreServiceUri.OriginalString.Replace("https://", ""); // because it is just a sufix

            if (!ProfileClient.Profile.Environments.ContainsKey(testEnvironmentName))
            {
                ProfileClient.AddOrSetEnvironment(environment);
            }

            if (!AzureRmProfileProvider.Instance.Profile.Environments.ContainsKey(testEnvironmentName))
            {
                AzureRmProfileProvider.Instance.Profile.Environments[testEnvironmentName] = environment;
            }

            if (currentEnvironment.SubscriptionId != null)
            {
                testSubscription = new AzureSubscription()
                {
                    Id = new Guid(currentEnvironment.SubscriptionId),
                    Name = testSubscriptionName,
                    Environment = testEnvironmentName,
                    Account = currentEnvironment.UserName,
                    Properties = new Dictionary<AzureSubscription.Property, string>
                    {
                        {AzureSubscription.Property.Default, "True"},
                        {
                            AzureSubscription.Property.StorageAccount,
                            Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT")
                        },
                    }
                };

                testAccount = new AzureAccount()
                {
                    Id = currentEnvironment.UserName,
                    Type = AzureAccount.AccountType.User,
                    Properties = new Dictionary<AzureAccount.Property, string>
                    {
                        {AzureAccount.Property.Subscriptions, currentEnvironment.SubscriptionId},
                    }
                };

                ProfileClient.Profile.Subscriptions[testSubscription.Id] = testSubscription;
                ProfileClient.Profile.Accounts[testAccount.Id] = testAccount;
                ProfileClient.SetSubscriptionAsDefault(testSubscription.Name, testSubscription.Account);

                var testTenant = new AzureTenant() { Id = Guid.NewGuid() };
                if (!string.IsNullOrEmpty(currentEnvironment.Tenant))
                {
                    Guid tenant;
                    if (Guid.TryParse(currentEnvironment.Tenant, out tenant))
                    {
                        testTenant.Id = tenant;
                    }
                }
                AzureRmProfileProvider.Instance.Profile.Context = new AzureContext(testSubscription, testAccount, environment, testTenant);
            }
        }
Esempio n. 45
0
        private void SetupAzureEnvironmentFromEnvironmentVariables(AzureModule mode)
        {
            TestEnvironment rdfeEnvironment    = new RDFETestEnvironmentFactory().GetTestEnvironment();
            TestEnvironment csmEnvironment     = new CSMTestEnvironmentFactory().GetTestEnvironment();
            TestEnvironment currentEnvironment = (mode == AzureModule.AzureResourceManager ? csmEnvironment : rdfeEnvironment);

            if (currentEnvironment.UserName == null)
            {
                currentEnvironment.UserName = "******";
            }

            SetAuthenticationFactory(mode, rdfeEnvironment, csmEnvironment);

            AzureEnvironment environment = new AzureEnvironment {
                Name = testEnvironmentName
            };

            Debug.Assert(currentEnvironment != null);
            environment.ActiveDirectoryAuthority = currentEnvironment.Endpoints.AADAuthUri.AbsoluteUri;
            environment.GalleryUrl = currentEnvironment.Endpoints.GalleryUri.AbsoluteUri;

            if (csmEnvironment != null)
            {
                environment.ResourceManagerUrl = csmEnvironment.BaseUri.AbsoluteUri;
            }

            if (rdfeEnvironment != null)
            {
                environment.ServiceManagementUrl = rdfeEnvironment.BaseUri.AbsoluteUri;
            }

            if (!ProfileClient.Profile.EnvironmentTable.ContainsKey(testEnvironmentName))
            {
                ProfileClient.AddOrSetEnvironment(environment);
            }

            if (currentEnvironment.SubscriptionId != null)
            {
                testSubscription = new AzureSubscription()
                {
                    Id   = currentEnvironment.SubscriptionId,
                    Name = testSubscriptionName,
                };
                testSubscription.SetEnvironment(testEnvironmentName);
                testSubscription.SetAccount(currentEnvironment.UserName);
                testSubscription.SetStorageAccount(Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT"));
                testSubscription.SetDefault();

                testAccount = new AzureAccount()
                {
                    Id   = currentEnvironment.UserName,
                    Type = AzureAccount.AccountType.User,
                };

                testAccount.SetSubscriptions(currentEnvironment.SubscriptionId);

                ProfileClient.Profile.SubscriptionTable[testSubscription.GetId()] = testSubscription;
                ProfileClient.Profile.AccountTable[testAccount.Id] = testAccount;
                ProfileClient.SetSubscriptionAsDefault(testSubscription.Name, testSubscription.GetAccount());
            }
        }
Esempio n. 46
0
 /// <summary>
 /// Generate an Operational Insights client from the test base to use for managing Operational Insights resources.
 /// </summary>
 /// <returns>Operational Insights client</returns>
 public static OperationalInsightsManagementClient GetOperationalInsightsManagementClient(DelegatingHandler handler)
 {
     CSMTestEnvironmentFactory factory = new CSMTestEnvironmentFactory();
     return TestBase.GetServiceClient<OperationalInsightsManagementClient>(factory).WithHandler(handler);
 }
Esempio n. 47
0
        public void RunPsTestWorkflow(
            Func<string[]> scriptBuilder,
            Action<CSMTestEnvironmentFactory> initialize,
            Action cleanup,
            string callingClassType,
            string mockName)
        {
            Dictionary<string, string> d = new Dictionary<string, string>();
            d.Add("Microsoft.Resources", null);
            d.Add("Microsoft.Features", null);
            d.Add("Microsoft.Authorization", null);
            var providersToIgnore = new Dictionary<string, string>();
            providersToIgnore.Add("Microsoft.Azure.Management.Resources.ResourceManagementClient", "2016-02-01");
            HttpMockServer.Matcher = new PermissiveRecordMatcherWithApiExclusion(true, d, providersToIgnore);

            using (UndoContext context = UndoContext.Current)
            {
                context.Start(callingClassType, mockName);

                this.csmTestFactory = new CSMTestEnvironmentFactory();

                if (initialize != null)
                {
                    initialize(this.csmTestFactory);
                }

                this.helper.SetupEnvironment(AzureModule.AzureResourceManager);

                this.SetupManagementClients();

                string callingClassName = callingClassType
                                        .Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries)
                                        .Last();

                this.helper.SetupModules(AzureModule.AzureResourceManager, 
                    "ScenarioTests\\Common.ps1", 
                    "ScenarioTests\\" + callingClassName + ".ps1", 
                    helper.RMProfileModule, 
                    helper.RMResourceModule, 
                    helper.GetRMModulePath(@"AzureRM.TrafficManager.psd1"));

                try
                {
                    if (scriptBuilder != null)
                    {
                        string[] psScripts = scriptBuilder();

                        if (psScripts != null)
                        {
                            this.helper.RunPowerShellTest(psScripts);
                        }
                    }
                }
                finally
                {
                    if (cleanup != null)
                    {
                        cleanup();
                    }
                }
            }
        }
Esempio n. 48
0
        /// <summary>
        /// Generate an Operational Insights client from the test base to use for managing Operational Insights resources.
        /// </summary>
        /// <returns>Operational Insights client</returns>
        public static OperationalInsightsManagementClient GetOperationalInsightsManagementClient(DelegatingHandler handler)
        {
            CSMTestEnvironmentFactory factory = new CSMTestEnvironmentFactory();

            return(TestBase.GetServiceClient <OperationalInsightsManagementClient>(factory).WithHandler(handler));
        }
Esempio n. 49
0
        protected GraphRbacManagementClient GetGraphClient()
        {
            var testFactory = new CSMTestEnvironmentFactory();
            var environment = testFactory.GetTestEnvironment();
            string tenantId = Guid.Empty.ToString();

            if (HttpMockServer.Mode == HttpRecorderMode.Record)
            {
                tenantId = environment.AuthorizationContext.TenantId;
                UserDomain = environment.AuthorizationContext.UserDomain;

                HttpMockServer.Variables[TenantIdKey] = tenantId;
                HttpMockServer.Variables[DomainKey] = UserDomain;
            }
            else if (HttpMockServer.Mode == HttpRecorderMode.Playback)
            {
                if (HttpMockServer.Variables.ContainsKey(TenantIdKey))
                {
                    tenantId = HttpMockServer.Variables[TenantIdKey];
                    AzureRmProfileProvider.Instance.Profile.Context.Tenant.Id = new Guid(tenantId);
                }
                if (HttpMockServer.Variables.ContainsKey(DomainKey))
                {
                    UserDomain = HttpMockServer.Variables[DomainKey];
                    AzureRmProfileProvider.Instance.Profile.Context.Tenant.Domain = UserDomain;
                }
            }

            return TestBase.GetGraphServiceClient<GraphRbacManagementClient>(testFactory, tenantId);
        }
        public void RunPsTestWorkflow(
            string scenario,
            Func <string[]> scriptBuilder,
            Action <CSMTestEnvironmentFactory> initialize,
            Action cleanup,
            string callingClassType,
            string mockName)
        {
            var providers = new Dictionary <string, string>();

            providers.Add("Microsoft.Resources", null);
            providers.Add("Microsoft.Features", null);
            providers.Add("Microsoft.Authorization", null);

            var providersToIgnore = new Dictionary <string, string>();

            providersToIgnore.Add("Microsoft.Azure.Management.Internal.Resources.ResourceManagementClient", "2016-09-01");

            HttpMockServer.Matcher = new PermissiveRecordMatcherWithApiExclusion(
                true,
                providers,
                providersToIgnore);

            HttpMockServer.RecordsDirectory = Path.Combine(
                AppDomain.CurrentDomain.BaseDirectory,
                "SessionRecords");

            using (var context = RestTestFramework.MockContext.Start(
                       callingClassType,
                       mockName))
            {
                this.csmTestFactory = new CSMTestEnvironmentFactory();

                if (initialize != null)
                {
                    initialize.Invoke(this.csmTestFactory);
                }

                this.SetupManagementClients(context);

                this.helper.SetupEnvironment(AzureModule.AzureResourceManager);

                var rmProfileModule = this.helper.RMProfileModule;
                this.helper.SetupModules(
                    AzureModule.AzureResourceManager,
                    powershellFile,
                    powershellHelperFile,
                    rmProfileModule,
                    this.helper.RMResourceModule,
                    this.helper.GetRMModulePath("AzureRM.RecoveryServices.psd1"),
                    this.helper.GetRMModulePath("AzureRM.RecoveryServices.SiteRecovery.psd1"),
                    "AzureRm.Resources.ps1");

                try
                {
                    if (scriptBuilder != null)
                    {
                        var psScripts = scriptBuilder();

                        if (psScripts != null)
                        {
                            this.helper.RunPowerShellTest(psScripts);
                        }
                    }
                }
                finally
                {
                    if (cleanup != null)
                    {
                        cleanup.Invoke();
                    }
                }
            }
        }
Esempio n. 51
0
        public static StreamAnalyticsManagementClient GetStreamAnalyticsManagementClient(DelegatingHandler handler)
        {
            CSMTestEnvironmentFactory factory = new CSMTestEnvironmentFactory();

            return(TestBase.GetServiceClient <StreamAnalyticsManagementClient>(factory).WithHandler(handler));
        }
Esempio n. 52
0
 protected TestsBase()
 {
     this.helper         = new EnvironmentSetupHelper();
     this.csmTestFactory = new CSMTestEnvironmentFactory();
     ResourceNamespace   = "Microsoft.RecoveryServices";
 }
        private void SetupAzureEnvironmentFromEnvironmentVariables(AzureModule mode)
        {
            TestEnvironment currentEnvironment = null;

            if (mode == AzureModule.AzureResourceManager)
            {
                currentEnvironment = new CSMTestEnvironmentFactory().GetTestEnvironment();
            }
            else
            {
                currentEnvironment = new RDFETestEnvironmentFactory().GetTestEnvironment();
            }

            if (currentEnvironment.UserName == null)
            {
                currentEnvironment.UserName = "******";
            }

            SetAuthenticationFactory(mode, currentEnvironment);

            AzureEnvironment environment = new AzureEnvironment {
                Name = testEnvironmentName
            };

            Debug.Assert(currentEnvironment != null);
            environment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectory]   = currentEnvironment.Endpoints.AADAuthUri.AbsoluteUri;
            environment.Endpoints[AzureEnvironment.Endpoint.Gallery]           = currentEnvironment.Endpoints.GalleryUri.AbsoluteUri;
            environment.Endpoints[AzureEnvironment.Endpoint.ServiceManagement] = currentEnvironment.BaseUri.AbsoluteUri;
            environment.Endpoints[AzureEnvironment.Endpoint.ResourceManager]   = currentEnvironment.Endpoints.ResourceManagementUri.AbsoluteUri;
            environment.Endpoints[AzureEnvironment.Endpoint.Graph]             = currentEnvironment.Endpoints.GraphUri.AbsoluteUri;
            environment.Endpoints[AzureEnvironment.Endpoint.AzureDataLakeAnalyticsCatalogAndJobEndpointSuffix] = currentEnvironment.Endpoints.DataLakeAnalyticsJobAndCatalogServiceUri.OriginalString.Replace("https://", ""); // because it is just a sufix
            environment.Endpoints[AzureEnvironment.Endpoint.AzureDataLakeStoreFileSystemEndpointSuffix]        = currentEnvironment.Endpoints.DataLakeStoreServiceUri.OriginalString.Replace("https://", "");                  // because it is just a sufix

            if (!ProfileClient.Profile.Environments.ContainsKey(testEnvironmentName))
            {
                ProfileClient.AddOrSetEnvironment(environment);
            }

            if (!AzureRmProfileProvider.Instance.Profile.Environments.ContainsKey(testEnvironmentName))
            {
                AzureRmProfileProvider.Instance.Profile.Environments[testEnvironmentName] = environment;
            }

            if (currentEnvironment.SubscriptionId != null)
            {
                testSubscription = new AzureSubscription()
                {
                    Id          = new Guid(currentEnvironment.SubscriptionId),
                    Name        = testSubscriptionName,
                    Environment = testEnvironmentName,
                    Account     = currentEnvironment.UserName,
                    Properties  = new Dictionary <AzureSubscription.Property, string>
                    {
                        { AzureSubscription.Property.Default, "True" },
                        {
                            AzureSubscription.Property.StorageAccount,
                            Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT")
                        },
                    }
                };

                testAccount = new AzureAccount()
                {
                    Id         = currentEnvironment.UserName,
                    Type       = AzureAccount.AccountType.User,
                    Properties = new Dictionary <AzureAccount.Property, string>
                    {
                        { AzureAccount.Property.Subscriptions, currentEnvironment.SubscriptionId },
                    }
                };

                ProfileClient.Profile.Subscriptions[testSubscription.Id] = testSubscription;
                ProfileClient.Profile.Accounts[testAccount.Id]           = testAccount;
                ProfileClient.SetSubscriptionAsDefault(testSubscription.Name, testSubscription.Account);

                var testTenant = new AzureTenant()
                {
                    Id = Guid.NewGuid()
                };
                if (!string.IsNullOrEmpty(currentEnvironment.Tenant))
                {
                    Guid tenant;
                    if (Guid.TryParse(currentEnvironment.Tenant, out tenant))
                    {
                        testTenant.Id = tenant;
                    }
                }
                AzureRmProfileProvider.Instance.Profile.Context = new AzureContext(testSubscription, testAccount, environment, testTenant);
            }
        }
 protected AzureBackupTestsBase()
 {
     this.helper         = new EnvironmentSetupHelper();
     this.csmTestFactory = new CSMTestEnvironmentFactory();
 }
        public void Initialize(string className)
        {
            if (initialized)
            {
                return;
            }

            HttpMockServer server;

            try
            {
                server = HttpMockServer.CreateInstance();
            }
            catch (ApplicationException)
            {
                // mock server has never been initialized, we will need to initialize it.
                HttpMockServer.Initialize(className, "InitialCreation");
                server = HttpMockServer.CreateInstance();
            }

            if (HttpMockServer.Mode == HttpRecorderMode.Record)
            {
                fromConfig = FromConfiguration();

                if (!fromConfig)
                {
                    var testFactory     = new CSMTestEnvironmentFactory();
                    var testEnv         = testFactory.GetTestEnvironment();
                    var secret          = Guid.NewGuid().ToString();
                    var mgmtClient      = TestBase.GetServiceClient <KeyVaultManagementClient>(testFactory);
                    var resourcesClient = TestBase.GetServiceClient <ResourceManagementClient>(testFactory);
                    var tenantId        = testEnv.AuthorizationContext.TenatId;
                    var graphClient     = TestBase.GetGraphServiceClient <GraphRbacManagementClient>(testFactory, tenantId);
                    var appDisplayName  = TestUtilities.GenerateName("sdktestapp");

                    //Setup things in AAD

                    //Create an application
                    var app = CreateApplication(graphClient, appDisplayName, secret);
                    appObjectId = app.Application.ObjectId;

                    //Create a corresponding service principal
                    var servicePrincipal = CreateServicePrincipal(app, graphClient);

                    //Figure out which locations are available for Key Vault
                    var location = GetKeyVaultLocation(resourcesClient);

                    //Create a resource group in that location
                    vaultName = TestUtilities.GenerateName("sdktestvault");
                    rgName    = TestUtilities.GenerateName("sdktestrg");

                    resourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup {
                        Location = location
                    });

                    //Create a key vault in that resource group
                    var createResponse = CreateVault(mgmtClient, location, tenantId, servicePrincipal);

                    vaultAddress      = createResponse.Vault.Properties.VaultUri;
                    _ClientCredential = new ClientCredential(app.Application.AppId, secret);

                    //Wait a few seconds before trying to authenticate
                    TestUtilities.Wait(TimeSpan.FromSeconds(30));
                }
            }

            initialized = true;
        }
        private void SetupAzureEnvironmentFromEnvironmentVariables(AzureModule mode)
        {
            TestEnvironment rdfeEnvironment = new RDFETestEnvironmentFactory().GetTestEnvironment();
            TestEnvironment csmEnvironment = new CSMTestEnvironmentFactory().GetTestEnvironment();
            TestEnvironment currentEnvironment = (mode == AzureModule.AzureResourceManager ? csmEnvironment : rdfeEnvironment);

            if (currentEnvironment.UserName == null)
            {
                currentEnvironment.UserName = "******";
            }

            SetEndpointsToDefaults(rdfeEnvironment, csmEnvironment);

            SetAuthenticationFactory(mode, rdfeEnvironment, csmEnvironment);

            AzureEnvironment environment = new AzureEnvironment { Name = testEnvironmentName };

            Debug.Assert(currentEnvironment != null);
            environment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectory] = currentEnvironment.ActiveDirectoryEndpoint.AbsoluteUri;
            environment.Endpoints[AzureEnvironment.Endpoint.Gallery] = currentEnvironment.GalleryUri.AbsoluteUri;

            if (csmEnvironment != null)
            {
                environment.Endpoints[AzureEnvironment.Endpoint.ResourceManager] = csmEnvironment.BaseUri.AbsoluteUri;                
            }

            if (rdfeEnvironment != null)
            {
                environment.Endpoints[AzureEnvironment.Endpoint.ServiceManagement] = rdfeEnvironment.BaseUri.AbsoluteUri;                
            }

            if (!client.Profile.Environments.ContainsKey(testEnvironmentName))
            {
                client.AddOrSetEnvironment(environment);
            }

            testSubscription = new AzureSubscription()
            {
                Id = new Guid(currentEnvironment.SubscriptionId),
                Name = testSubscriptionName,
                Environment = testEnvironmentName,
                Account = currentEnvironment.UserName,
                Properties = new Dictionary<AzureSubscription.Property,string> 
                {
                     { AzureSubscription.Property.Default, "True"},
                     { AzureSubscription.Property.StorageAccount, Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT")},
                }
            };

            testAccount = new AzureAccount()
            {
                Id = currentEnvironment.UserName,
                Type = AzureAccount.AccountType.User,
                Properties = new Dictionary<AzureAccount.Property, string> 
                {
                     { AzureAccount.Property.Subscriptions, currentEnvironment.SubscriptionId},
                }
            };

            client.Profile.Subscriptions[testSubscription.Id] = testSubscription;
            client.Profile.Accounts[testAccount.Id] = testAccount;
            client.SetSubscriptionAsCurrent(testSubscription.Name, testSubscription.Account);
        }
        public void Dispose()
        {
            if (HttpMockServer.Mode == HttpRecorderMode.Record && !fromConfig)
            {
                var testFactory = new CSMTestEnvironmentFactory();
                var testEnv = testFactory.GetTestEnvironment();
                var mgmtClient = TestBase.GetServiceClient<KeyVaultManagementClient>(testFactory);
                var resourcesClient = TestBase.GetServiceClient<ResourceManagementClient>(testFactory);
                var tenantId = testEnv.AuthorizationContext.TenantId;
                var graphClient = TestBase.GetGraphServiceClient<GraphRbacManagementClient>(testFactory, tenantId);

                mgmtClient.Vaults.Delete(rgName, vaultName);
                graphClient.Application.Delete(appObjectId);
                resourcesClient.ResourceGroups.Delete(rgName);
            }
        }
Esempio n. 58
0
        public void RunPsTestWorkflow(
            Func <string[]> scriptBuilder,
            Action <CSMTestEnvironmentFactory> initialize,
            Action cleanup,
            string callingClassType,
            string mockName)
        {
            Dictionary <string, string> d = new Dictionary <string, string>();

            d.Add("Microsoft.Authorization", null);
            HttpMockServer.Matcher = new PermissiveRecordMatcherWithApiExclusion(false, d);

            using (UndoContext context = UndoContext.Current)
            {
                context.Start(callingClassType, mockName);


                this.csmTestFactory = new CSMTestEnvironmentFactory();


                if (initialize != null)
                {
                    initialize(this.csmTestFactory);
                }


                this.SetupManagementClients();


                this.helper.SetupEnvironment(AzureModule.AzureResourceManager);


                string callingClassName = callingClassType
                                          .Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries)
                                          .Last();


                this.helper.SetupModules(AzureModule.AzureResourceManager, "ScenarioTests\\Common.ps1", "ScenarioTests\\" + callingClassName + ".ps1",
                                         helper.RMProfileModule,
                                         helper.RMResourceModule,
                                         helper.GetRMModulePath("AzureRM.Dns.psd1"));

                try
                {
                    if (scriptBuilder != null)
                    {
                        string[] psScripts = scriptBuilder();


                        if (psScripts != null)
                        {
                            this.helper.RunPowerShellTest(psScripts);
                        }
                    }
                }
                finally
                {
                    if (cleanup != null)
                    {
                        cleanup();
                    }
                }
            }
        }
        private void RunPsTestWorkflow(
           Func<string[]> scriptBuilder,
           Action<CSMTestEnvironmentFactory> initialize,
           Action cleanup,
           string callingClassType,
           string mockName)
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start(callingClassType, mockName);

                this.armTestEnvironmentFactory = new CSMTestEnvironmentFactory();

                if (initialize != null)
                {
                    initialize(this.armTestEnvironmentFactory);
                }

                helper.SetupEnvironment(AzureModule.AzureResourceManager);

                SetupManagementClients();

                var callingClassName = callingClassType
                                        .Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries)
                                        .Last();

                List<string> modules = this.SetupCommonModules();
                modules.Add(callingClassName + ".ps1");
                modules.Add(helper.RMProfileModule);
                modules.Add(helper.RMResourceModule);
                helper.SetupModules(AzureModule.AzureResourceManager, modules.ToArray());

                try
                {
                    if (scriptBuilder != null)
                    {
                        var psScripts = scriptBuilder();

                        if (psScripts != null)
                        {
                            helper.RunPowerShellTest(psScripts);
                        }
                    }
                }
                finally
                {
                    if (cleanup != null)
                    {
                        cleanup();
                    }
                }
            }
        }
        public void Initialize(string className)
        {
            if (initialized)
                return;

            HttpMockServer server;

            try
            {
                server = HttpMockServer.CreateInstance();
            }
            catch (ApplicationException)
            {
                // mock server has never been initialized, we will need to initialize it.
                HttpMockServer.Initialize(className, "InitialCreation");
                server = HttpMockServer.CreateInstance();
            }
            
            if (HttpMockServer.Mode == HttpRecorderMode.Record)
            {
                fromConfig = FromConfiguration();

                if (!fromConfig)
                {
                    var testFactory = new CSMTestEnvironmentFactory();
                    var testEnv = testFactory.GetTestEnvironment();
                    var secret = Guid.NewGuid().ToString();
                    var mgmtClient = TestBase.GetServiceClient<KeyVaultManagementClient>(testFactory);
                    var resourcesClient = TestBase.GetServiceClient<ResourceManagementClient>(testFactory);
                    var tenantId = testEnv.AuthorizationContext.TenantId;
                    var graphClient = TestBase.GetGraphServiceClient<GraphRbacManagementClient>(testFactory, tenantId);
                    var appDisplayName = TestUtilities.GenerateName("sdktestapp");

                    //Setup things in AAD

                    //Create an application
                    var app = CreateApplication(graphClient, appDisplayName, secret);
                    appObjectId = app.Application.ObjectId;

                    //Create a corresponding service principal
                    var servicePrincipal = CreateServicePrincipal(app, graphClient);

                    //Figure out which locations are available for Key Vault
                    var location = GetKeyVaultLocation(resourcesClient);

                    //Create a resource group in that location
                    vaultName = TestUtilities.GenerateName("sdktestvault");
                    rgName = TestUtilities.GenerateName("sdktestrg");

                    resourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup {Location = location});

                    //Create a key vault in that resource group
                    var createResponse = CreateVault(mgmtClient, location, tenantId, servicePrincipal);

                    vaultAddress = createResponse.Vault.Properties.VaultUri;
                    _ClientCredential = new ClientCredential(app.Application.AppId, secret);

                    //Wait a few seconds before trying to authenticate
                    TestUtilities.Wait(TimeSpan.FromSeconds(30));
                }
            }

            initialized = true;
        }