public void SaveAzureWebsiteLogWithNoFileExtensionTest()
        {
            TestExecutionHelpers.RetryAction(
                () =>
            {
                // Setup
                string expectedOutput = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "file_without_ext.zip");

                SimpleDeploymentServiceManagement deploymentChannel = new SimpleDeploymentServiceManagement
                {
                    DownloadLogsThunk = ar => new MemoryStream(Encoding.UTF8.GetBytes("test with no extension"))
                };

                // Test
                SaveAzureWebsiteLogCommand getAzureWebsiteLogCommand = new SaveAzureWebsiteLogCommand(deploymentChannel)
                {
                    Name           = "website1",
                    ShareChannel   = true,
                    WebsitesClient = clientMock.Object,
                    CommandRuntime = new MockCommandRuntime(),
                    Output         = "file_without_ext"
                };
                currentProfile   = new AzureSMProfile();
                var subscription = new AzureSubscription {
                    Id = base.subscriptionId
                };
                subscription.SetDefault();
                currentProfile.SubscriptionTable[new Guid(base.subscriptionId)] = subscription;

                getAzureWebsiteLogCommand.DefaultCurrentPath = AppDomain.CurrentDomain.BaseDirectory;
                getAzureWebsiteLogCommand.ExecuteCmdlet();
                Assert.Equal("test with no extension", FileUtilities.DataStore.ReadFileAsText(expectedOutput));
            });
        }
예제 #2
0
        public DisableAzureRmActivityLogAlertTests(Xunit.Abstractions.ITestOutputHelper output)
        {
            ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output));
            TestExecutionHelpers.SetUpSessionAndProfile();
            insightsOperationsMock = new Mock <IActivityLogAlertsOperations>();
            monitorClientMock      = new Mock <MonitorManagementClient>();
            commandRuntimeMock     = new Mock <ICommandRuntime>();
            cmdlet = new DisableAzureRmActivityLogAlertCommand()
            {
                CommandRuntime          = commandRuntimeMock.Object,
                MonitorManagementClient = monitorClientMock.Object
            };

            response = new AzureOperationResponse <ActivityLogAlertResource>()
            {
                Body = ActivityLogAlertsUtilities.CreateActivityLogAlertResource(location: "westus", name: "alert1")
            };

            insightsOperationsMock.Setup(f => f.UpdateWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <ActivityLogAlertPatchBody>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <AzureOperationResponse <ActivityLogAlertResource> >(response))
            .Callback((string r, string n, ActivityLogAlertPatchBody b, Dictionary <string, List <string> > headers, CancellationToken t) =>
            {
                this.resourceGroup = r;
                this.name          = n;
                this.body          = b;
            });

            monitorClientMock.SetupGet(f => f.ActivityLogAlerts).Returns(this.insightsOperationsMock.Object);

            // Setup Confirmation
            commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny <string>())).Returns(true);
            commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny <string>(), It.IsAny <string>())).Returns(true);
            commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).Returns(true);
            commandRuntimeMock.Setup(f => f.ShouldContinue(It.IsAny <string>(), It.IsAny <string>())).Returns(true);
        }
        public EnvironmentSetupHelper()
        {
            TestExecutionHelpers.SetUpSessionAndProfile();
            var datastore = new MemoryDataStore();

            AzureSession.Instance.DataStore = datastore;
            var rmprofile = new AzureRmProfile(Path.Combine(AzureSession.Instance.ProfileDirectory, AzureSession.Instance.ProfileFile));

            rmprofile.EnvironmentTable.Add("foo", new AzureEnvironment(AzureEnvironment.PublicEnvironments.Values.FirstOrDefault()));
            rmprofile.DefaultContext = new AzureContext(new AzureSubscription(), new AzureAccount(), rmprofile.EnvironmentTable["foo"], new AzureTenant());
            rmprofile.DefaultContext.Subscription.SetEnvironment("foo");
            if (AzureRmProfileProvider.Instance.Profile == null)
            {
                AzureRmProfileProvider.Instance.Profile = rmprofile;
            }

            AzureSession.Instance.DataStore = datastore;

            // Ignore SSL errors
            System.Net.ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) => true;

#if !NETSTANDARD
            ServiceManagementProfileProvider.InitializeServiceManagementProfile();
            var profile = new AzureSMProfile(Path.Combine(AzureSession.Instance.ProfileDirectory, AzureSession.Instance.ProfileFile));
            ProfileClient = new ProfileClient(profile);
            AdalTokenCache.ClearCookies();
#endif
            // Set RunningMocked
            TestMockSupport.RunningMocked = HttpMockServer.GetCurrentMode() == HttpRecorderMode.Playback;
        }
        public AddAzureRmAutoscaleSettingTests(Xunit.Abstractions.ITestOutputHelper output)
        {
            ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output));
            TestExecutionHelpers.SetUpSessionAndProfile();
            insightsAutoscaleOperationsMock = new Mock <IAutoscaleSettingsOperations>();
            insightsManagementClientMock    = new Mock <MonitorManagementClient>();
            commandRuntimeMock = new Mock <ICommandRuntime>();
            cmdlet             = new AddAzureRmAutoscaleSettingCommand()
            {
                CommandRuntime          = commandRuntimeMock.Object,
                MonitorManagementClient = insightsManagementClientMock.Object
            };

            response = new AzureOperationResponse <AutoscaleSettingResource>()
            {
                Body = new AutoscaleSettingResource()
            };

            insightsAutoscaleOperationsMock.Setup(f => f.CreateOrUpdateWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <AutoscaleSettingResource>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <Microsoft.Rest.Azure.AzureOperationResponse <AutoscaleSettingResource> >(response))
            .Callback((string resourceGrp, string settingNm, AutoscaleSettingResource createOrUpdateParams, Dictionary <string, List <string> > headers, CancellationToken t) =>
            {
                resourceGroup      = resourceGrp;
                settingName        = settingNm;
                createOrUpdatePrms = createOrUpdateParams;
            });

            insightsManagementClientMock.SetupGet(f => f.AutoscaleSettings).Returns(this.insightsAutoscaleOperationsMock.Object);

            // Setup Confirmation
            commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny <string>())).Returns(true);
            commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny <string>(), It.IsAny <string>())).Returns(true);
            commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).Returns(true);
            commandRuntimeMock.Setup(f => f.ShouldContinue(It.IsAny <string>(), It.IsAny <string>())).Returns(true);
        }
 public EnvironmentCmdletTests(ITestOutputHelper output)
 {
     TestExecutionHelpers.SetUpSessionAndProfile();
     XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output));
     dataStore = new MemoryDataStore();
     AzureSession.Instance.DataStore = dataStore;
 }
예제 #6
0
        public GetAzureRmAutoscaleHistoryTests(Xunit.Abstractions.ITestOutputHelper output)
        {
            ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output));
            TestExecutionHelpers.SetUpSessionAndProfile();
            insightsEventOperationsMock = new Mock <IActivityLogsOperations>();
            MonitorClientMock           = new Mock <MonitorClient>();
            commandRuntimeMock          = new Mock <ICommandRuntime>();
            cmdlet = new GetAzureRmAutoscaleHistoryCommand()
            {
                CommandRuntime = commandRuntimeMock.Object,
                MonitorClient  = MonitorClientMock.Object
            };

            response      = Test.Utilities.InitializeResponse();
            finalResponse = Utilities.InitializeFinalResponse();

            insightsEventOperationsMock.Setup(f => f.ListWithHttpMessagesAsync(It.IsAny <ODataQuery <EventData> >(), It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <AzureOperationResponse <IPage <EventData> > >(response))
            .Callback((ODataQuery <EventData> f, string s, Dictionary <string, List <string> > headers, CancellationToken t) =>
            {
                filter   = f;
                selected = s;
            });

            insightsEventOperationsMock.Setup(f => f.ListNextWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <AzureOperationResponse <IPage <EventData> > >(finalResponse))
            .Callback((string next, Dictionary <string, List <string> > headers, CancellationToken t) =>
            {
                nextLink = next;
            });

            MonitorClientMock.SetupGet(f => f.ActivityLogs).Returns(this.insightsEventOperationsMock.Object);
        }
예제 #7
0
        public ArgumentCompleterTests(ITestOutputHelper output)
        {
            TestExecutionHelpers.SetUpSessionAndProfile();
            ResourceManagerProfileProvider.InitializeResourceManagerProfile(true);

            xunitLogger = new XunitTracingInterceptor(output);
        }
        public AddAzureRmLogProfileTests(ITestOutputHelper output)
        {
            ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output));
            TestExecutionHelpers.SetUpSessionAndProfile();
            insightsLogProfileOperationsMock = new Mock <ILogProfilesOperations>();
            insightsManagementClientMock     = new Mock <MonitorManagementClient>();
            commandRuntimeMock = new Mock <ICommandRuntime>();
            cmdlet             = new AddAzureRmLogProfileCommand()
            {
                CommandRuntime          = commandRuntimeMock.Object,
                MonitorManagementClient = insightsManagementClientMock.Object
            };

            response = Utilities.InitializeLogProfileResponse();

            insightsLogProfileOperationsMock.Setup(f => f.CreateOrUpdateWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <LogProfileResource>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <Rest.Azure.AzureOperationResponse <LogProfileResource> >(response))
            .Callback((string logProfileName, LogProfileResource createOrUpdateParams, Dictionary <string, List <string> > headers, CancellationToken t) =>
            {
                this.logProfileName = logProfileName;
                createOrUpdatePrms  = createOrUpdateParams;
            });

            insightsManagementClientMock.SetupGet(f => f.LogProfiles).Returns(this.insightsLogProfileOperationsMock.Object);

            // Setup Confirmation
            commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny <string>())).Returns(true);
            commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny <string>(), It.IsAny <string>())).Returns(true);
            commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).Returns(true);
            commandRuntimeMock.Setup(f => f.ShouldContinue(It.IsAny <string>(), It.IsAny <string>())).Returns(true);
        }
예제 #9
0
        public AddAzureRmWebtestAlertRuleTests(ITestOutputHelper output)
        {
            ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output));
            TestExecutionHelpers.SetUpSessionAndProfile();
            insightsAlertRuleOperationsMock = new Mock <IAlertRulesOperations>();
            insightsManagementClientMock    = new Mock <MonitorManagementClient>();
            commandRuntimeMock = new Mock <ICommandRuntime>();
            cmdlet             = new AddAzureRmWebtestAlertRuleCommand()
            {
                CommandRuntime          = commandRuntimeMock.Object,
                MonitorManagementClient = insightsManagementClientMock.Object
            };

            AlertRuleResource alertRuleResourceInput = new AlertRuleResource()
            {
                Location              = null,
                IsEnabled             = true,
                AlertRuleResourceName = "a name"
            };

            response = new Rest.Azure.AzureOperationResponse <AlertRuleResource>()
            {
                Body = alertRuleResourceInput
            };

            insightsAlertRuleOperationsMock.Setup(f => f.CreateOrUpdateWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <AlertRuleResource>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <Rest.Azure.AzureOperationResponse <AlertRuleResource> >(response))
            .Callback((string resourceGrp, string name, AlertRuleResource createOrUpdateParams, Dictionary <string, List <string> > headers, CancellationToken t) =>
            {
                resourceGroup      = resourceGrp;
                createOrUpdatePrms = createOrUpdateParams;
            });

            insightsManagementClientMock.SetupGet(f => f.AlertRules).Returns(this.insightsAlertRuleOperationsMock.Object);
        }
        public void SaveAzureWebsiteLogWithSlotTest()
        {
            TestExecutionHelpers.RetryAction(
                () =>
            {
                // Setup
                SimpleDeploymentServiceManagement deploymentChannel = new SimpleDeploymentServiceManagement
                {
                    DownloadLogsThunk = ar => new MemoryStream(Encoding.UTF8.GetBytes("test"))
                };

                // Test
                SaveAzureWebsiteLogCommand getAzureWebsiteLogCommand = new SaveAzureWebsiteLogCommand(deploymentChannel)
                {
                    Name           = "website1",
                    ShareChannel   = true,
                    WebsitesClient = clientMock.Object,
                    CommandRuntime = new MockCommandRuntime(),
                    Slot           = slot
                };
                currentProfile   = new AzureSMProfile();
                var subscription = new AzureSubscription {
                    Id = new Guid(base.subscriptionId)
                };
                subscription.Properties[AzureSubscription.Property.Default] = "True";
                currentProfile.Subscriptions[new Guid(base.subscriptionId)] = subscription;

                getAzureWebsiteLogCommand.DefaultCurrentPath = AppDomain.CurrentDomain.BaseDirectory;
                getAzureWebsiteLogCommand.ExecuteCmdlet();
                Assert.Equal("test", FileUtilities.DataStore.ReadFileAsText(
                                 Path.Combine(AppDomain.CurrentDomain.BaseDirectory, SaveAzureWebsiteLogCommand.DefaultOutput)));
            });
        }
예제 #11
0
        public RemoveAzureRmActivityLogAlertTests(Xunit.Abstractions.ITestOutputHelper output)
        {
            ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output));
            TestExecutionHelpers.SetUpSessionAndProfile();
            insightsOperationsMock = new Mock <IActivityLogAlertsOperations>();
            monitorClientMock      = new Mock <MonitorManagementClient>();
            commandRuntimeMock     = new Mock <ICommandRuntime>();
            cmdlet = new RemoveAzureRmActivityLogAlertCommand()
            {
                CommandRuntime          = commandRuntimeMock.Object,
                MonitorManagementClient = monitorClientMock.Object
            };

            insightsOperationsMock.Setup(f => f.DeleteWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <Microsoft.Rest.Azure.AzureOperationResponse>(new Microsoft.Rest.Azure.AzureOperationResponse()))
            .Callback((string r, string n, Dictionary <string, List <string> > headers, CancellationToken t) =>
            {
                this.resourceGroup = r;
                this.name          = n;
            });

            monitorClientMock.SetupGet(f => f.ActivityLogAlerts).Returns(this.insightsOperationsMock.Object);

            // Setup Confirmation
            commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny <string>())).Returns(true);
            commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny <string>(), It.IsAny <string>())).Returns(true);
            commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).Returns(true);
            commandRuntimeMock.Setup(f => f.ShouldContinue(It.IsAny <string>(), It.IsAny <string>())).Returns(true);
        }
예제 #12
0
        public TenantCmdletTests(ITestOutputHelper output)
        {
            TestExecutionHelpers.SetUpSessionAndProfile();
            XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output));
            CommandRuntimeMock = new MockCommandRuntime();

            AzureSessionTestInitializer.Initialize();
        }
        public CommonDataCmdletTests(ITestOutputHelper output)
        {
            TestExecutionHelpers.SetUpSessionAndProfile();
            XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output));
#if !NETSTANDARD
            ServiceManagementProfileProvider.InitializeServiceManagementProfile();
#endif
        }
예제 #14
0
 public LoginCmdletTests(ITestOutputHelper output)
 {
     TestExecutionHelpers.SetUpSessionAndProfile();
     XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output));
     dataStore = new MemoryDataStore();
     AzureSession.Instance.DataStore = dataStore;
     commandRuntimeMock = new MockCommandRuntime();
     AzureRmProfileProvider.Instance.Profile = new AzureRmProfile();
 }
예제 #15
0
 public ProfileCmdletTests(ITestOutputHelper output)
 {
     TestExecutionHelpers.SetUpSessionAndProfile();
     XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output));
     dataStore = new MemoryDataStore();
     AzureSession.Instance.DataStore = dataStore;
     commandRuntimeMock = new MockCommandRuntime();
     AzureSession.Instance.AuthenticationFactory = new MockTokenAuthenticationFactory();
 }
예제 #16
0
        public TenantCmdletMockTests(ITestOutputHelper output)
        {
            TestExecutionHelpers.SetUpSessionAndProfile();
            XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output));

            AzureSession.Instance.AuthenticationFactory = new MockTokenAuthenticationFactory();
            ((MockTokenAuthenticationFactory)AzureSession.Instance.AuthenticationFactory).TokenProvider = (account, environment, tenant) =>
                                                                                                          new MockAccessToken
            {
                UserId      = "*****@*****.**",
                LoginType   = LoginType.OrgId,
                AccessToken = "bbb",
                TenantId    = tenant
            };

            commandRuntimeMock.Setup(f => f.WriteObject(It.IsAny <object>(), It.IsAny <bool>())).Callback(
                (Object o, bool enumerateCollection) =>
            {
                if (enumerateCollection)
                {
                    IEnumerable <object> objects = o as IEnumerable <object>;
                    objects?.ForEach(e => OutputPipeline.Add(e));
                }
                else
                {
                    OutputPipeline.Add(o);
                }
            });

            cmdlet = new GetAzureRMTenantCommandMock()
            {
                CommandRuntime = commandRuntimeMock.Object,
            };

            var sub = new AzureSubscription()
            {
                Id   = Guid.NewGuid().ToString(),
                Name = "Test subscription"
            };

            defaultContext = new AzureContext(sub,
                                              new AzureAccount()
            {
                Id = "*****@*****.**", Type = AzureAccount.AccountType.User
            },
                                              AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud],
                                              new AzureTenant()
            {
                Id = Guid.NewGuid().ToString()
            });
            var profile = new AzureRmProfile();

            profile.DefaultContext = defaultContext;
            cmdlet.profileClient   = new RMProfileClient(profile);
            cmdlet.profileClient.SubscriptionAndTenantClient = mockSubscriptionClient.Object;
        }
예제 #17
0
 void ResetState()
 {
     TestExecutionHelpers.SetUpSessionAndProfile();
     ResourceManagerProfileProvider.InitializeResourceManagerProfile(true);
     AzureSession.Instance.DataStore             = dataStore;
     AzureSession.Instance.ARMContextSaveMode    = ContextSaveMode.Process;
     AzureSession.Instance.AuthenticationFactory = new MockTokenAuthenticationFactory();
     AzureSession.Instance.TokenCache            = new AuthenticationStoreTokenCache(new AzureTokenCache());
     Environment.SetEnvironmentVariable("Azure_PS_Data_Collection", "");
 }
 public void ParseTemplateParameterFileContents_DeserializeWithCorrectType()
 {
     // Add up to 3 retries for flaky test
     TestExecutionHelpers.RetryAction(() =>
     {
         Dictionary <string, TemplateFileParameterV1> result =
             TemplateUtility.ParseTemplateParameterFileContents(@"Resources/WebSite.param.dev.json".AsAbsoluteLocation());
         Assert.True(result["isWorker"].Value as bool?);
         Assert.Equal((System.Int64) 1, result["numberOfWorker"].Value);
     });
 }
예제 #19
0
 public KubernetesTests(ITestOutputHelper output)
 {
     XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output));
     TestExecutionHelpers.SetUpSessionAndProfile();
     if (HttpMockServer.GetCurrentMode() == HttpRecorderMode.Playback)
     {
         AzureSession.Instance.DataStore = new MemoryDataStore();
         var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
         AzureSession.Instance.DataStore.WriteFile(Path.Combine(home, ".ssh", "id_rsa.pub"), File.ReadAllText("Fixtures/id_rsa.pub"));
         AzureSession.Instance.DataStore.WriteFile(Path.Combine(home, ".azure", "acsServicePrincipal.json"), "Fixtures/acsServicePrincipal.json");
     }
 }
        public GetAzureRmActivityLogAlertTests(Xunit.Abstractions.ITestOutputHelper output)
        {
            ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output));
            TestExecutionHelpers.SetUpSessionAndProfile();
            insightsOperationsMock       = new Mock <IActivityLogAlertsOperations>();
            insightsManagementClientMock = new Mock <MonitorManagementClient>()
            {
                CallBase = true
            };
            commandRuntimeMock = new Mock <ICommandRuntime>();
            cmdlet             = new GetAzureRmActivityLogAlertCommand()
            {
                CommandRuntime          = commandRuntimeMock.Object,
                MonitorManagementClient = insightsManagementClientMock.Object
            };

            ActivityLogAlertResource responseObject = ActivityLogAlertsUtilities.CreateActivityLogAlertResource(location: "westus", name: "alert1");

            responseSimple = new AzureOperationResponse <ActivityLogAlertResource>()
            {
                Body = responseObject
            };

            responsePage = new AzureOperationResponse <IEnumerable <ActivityLogAlertResource> >()
            {
                Body = new List <ActivityLogAlertResource> {
                    responseObject
                }
            };

            insightsOperationsMock.Setup(f => f.GetWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <AzureOperationResponse <ActivityLogAlertResource> >(responseSimple))
            .Callback((string resourceGrp, string name, Dictionary <string, List <string> > headers, CancellationToken t) =>
            {
                this.resourceGroup = resourceGrp;
                this.name          = name;
            });

            insightsOperationsMock.Setup(f => f.ListByResourceGroupWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <AzureOperationResponse <IEnumerable <ActivityLogAlertResource> > >(responsePage))
            .Callback((string resourceGrp, Dictionary <string, List <string> > headers, CancellationToken t) =>
            {
                this.resourceGroup = resourceGrp;
            });

            insightsOperationsMock.Setup(f => f.ListBySubscriptionIdWithHttpMessagesAsync(It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <AzureOperationResponse <IEnumerable <ActivityLogAlertResource> > >(responsePage))
            .Callback((Dictionary <string, List <string> > headers, CancellationToken t) =>
                      {});

            insightsManagementClientMock.SetupGet(f => f.ActivityLogAlerts).Returns(this.insightsOperationsMock.Object);
        }
        public GetAzureRmActionGroupTests(Xunit.Abstractions.ITestOutputHelper output)
        {
            TestExecutionHelpers.SetUpSessionAndProfile();
            insightsOperationsMock       = new Mock <IActionGroupsOperations>();
            insightsManagementClientMock = new Mock <MonitorManagementClient>()
            {
                CallBase = true
            };
            commandRuntimeMock = new Mock <ICommandRuntime>();
            cmdlet             = new GetAzureRmActionGroupCommand()
            {
                CommandRuntime          = commandRuntimeMock.Object,
                MonitorManagementClient = insightsManagementClientMock.Object
            };

            ActionGroupResource responseObject = ActionGroupsUtilities.CreateActionGroupResource(name: "actiongroup1", shortName: "ag1");

            responseSimple = new AzureOperationResponse <ActionGroupResource>()
            {
                Body = responseObject
            };

            responsePage = new AzureOperationResponse <IEnumerable <ActionGroupResource> >()
            {
                Body = new List <ActionGroupResource> {
                    responseObject
                }
            };

            insightsOperationsMock.Setup(f => f.GetWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <AzureOperationResponse <ActionGroupResource> >(responseSimple))
            .Callback((string resourceGrp, string name, Dictionary <string, List <string> > headers, CancellationToken t) =>
            {
                this.resourceGroup = resourceGrp;
                this.name          = name;
            });

            insightsOperationsMock.Setup(f => f.ListByResourceGroupWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <AzureOperationResponse <IEnumerable <ActionGroupResource> > >(responsePage))
            .Callback((string resourceGrp, Dictionary <string, List <string> > headers, CancellationToken t) =>
            {
                this.resourceGroup = resourceGrp;
            });

            insightsOperationsMock.Setup(f => f.ListBySubscriptionIdWithHttpMessagesAsync(It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <AzureOperationResponse <IEnumerable <ActionGroupResource> > >(responsePage))
            .Callback((Dictionary <string, List <string> > headers, CancellationToken t) =>
                      { });

            insightsManagementClientMock.SetupGet(f => f.ActionGroups).Returns(this.insightsOperationsMock.Object);
        }
예제 #22
0
        public UpdateScheduledQueryRuleTests(Xunit.Abstractions.ITestOutputHelper output)
        {
            ServiceManagement.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagement.Common.Models.XunitTracingInterceptor(output));
            TestExecutionHelpers.SetUpSessionAndProfile();
            sqrOperationsMock           = new Mock <IScheduledQueryRulesOperations>();
            monitorManagementClientMock = new Mock <MonitorManagementClient>()
            {
                CallBase = true
            };
            commandRuntimeMock = new Mock <ICommandRuntime>();

            //testing update of "enabled" field
            cmdlet = new UpdateScheduledQueryRuleCommand
            {
                CommandRuntime          = commandRuntimeMock.Object,
                MonitorManagementClient = monitorManagementClientMock.Object,
                Enabled = true
            };

            response = new AzureOperationResponse <LogSearchRuleResource>()
            {
                Body = new LogSearchRuleResource()
            };

            sqrOperationsMock.Setup(f => f.GetWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <Microsoft.Rest.Azure.AzureOperationResponse <LogSearchRuleResource> >(response))
            .Callback((string resourceGrp, string name, Dictionary <string, List <string> > customHeaders, CancellationToken cancellationToken) =>
            {
                this.resourceGroup = resourceGrp;
                this.ruleName      = name;
                this.updatePrms    = response.Body;
            });

            sqrOperationsMock.Setup(f => f.UpdateWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <LogSearchRuleResourcePatch>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <Microsoft.Rest.Azure.AzureOperationResponse <LogSearchRuleResource> >(response))
            .Callback((string resourceGrp, string name, LogSearchRuleResourcePatch patchPrms, Dictionary <string, List <string> > headers, CancellationToken t) =>
            {
                this.resourceGroup = resourceGrp;
                this.ruleName      = name;
                this.patchPrms     = patchPrms;
                this.updatePrms    = response.Body;
            });

            monitorManagementClientMock.SetupGet(f => f.ScheduledQueryRules).Returns(this.sqrOperationsMock.Object);

            // Setup Confirmation
            commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny <string>())).Returns(true);
            commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny <string>(), It.IsAny <string>())).Returns(true);
            commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).Returns(true);
            commandRuntimeMock.Setup(f => f.ShouldContinue(It.IsAny <string>(), It.IsAny <string>())).Returns(true);
        }
예제 #23
0
        public void RunPsTest(params string[] scripts)
        {
            TestExecutionHelpers.SetUpSessionAndProfile();
            var sf = new StackTrace().GetFrame(1);
            var callingClassType = sf.GetMethod().ReflectedType?.ToString();
            var mockName         = sf.GetMethod().Name;

            RunPsTestWorkflow(
                () => scripts,
                // no custom cleanup
                null,
                callingClassType,
                mockName);
        }
예제 #24
0
        void ResetState()
        {
            TestExecutionHelpers.SetUpSessionAndProfile();
            ResourceManagerProfileProvider.InitializeResourceManagerProfile(true);
            // prevent token acquisition
            AzureRmProfileProvider.Instance.GetProfile <AzureRmProfile>().ShouldRefreshContextsFromCache = false;
            AzureSession.Instance.DataStore             = dataStore;
            AzureSession.Instance.ARMContextSaveMode    = ContextSaveMode.Process;
            AzureSession.Instance.AuthenticationFactory = new MockTokenAuthenticationFactory();
            Environment.SetEnvironmentVariable("Azure_PS_Data_Collection", "false");
            PowerShellTokenCacheProvider tokenProvider = new InMemoryTokenCacheProvider();

            AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => tokenProvider, true);
        }
예제 #25
0
        public NewAzureRmAutoscaleProfileTests(Xunit.Abstractions.ITestOutputHelper output = null)
        {
            TestExecutionHelpers.SetUpSessionAndProfile();
            if (output != null)
            {
                ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output));
            }

            commandRuntimeMock = new Mock <ICommandRuntime>();
            Cmdlet             = new NewAzureRmAutoscaleProfileCommand()
            {
                CommandRuntime = commandRuntimeMock.Object
            };
        }
예제 #26
0
        public void RunPsTest(params string[] scripts)
        {
            TestExecutionHelpers.SetUpSessionAndProfile();
            var callingClassType = TestUtilities.GetCallingClass(2);
            var mockName         = TestUtilities.GetCurrentMethodName(2);

            RunPsTestWorkflow(
                () => scripts,
                // no custom initializer
                null,
                // no custom cleanup
                null,
                callingClassType,
                mockName);
        }
예제 #27
0
        protected void RunPowerShellTest(params string[] scripts)
        {
            TestExecutionHelpers.SetUpSessionAndProfile();
            var sf = new StackTrace().GetFrame(1);
            var callingClassType = sf.GetMethod().ReflectedType?.ToString();
            var mockName         = sf.GetMethod().Name;

            var d = new Dictionary <string, string>
            {
                { "Microsoft.Resources", null },
                { "Microsoft.Features", null },
                { "Microsoft.Authorization", null },
                { "Microsoft.Network", null },
                { "Microsoft.KeyVault", null },
                { "Microsoft.EventHub", null },
                { "Microsoft.Insights", null },
                { "Microsoft.OperationalInsights", null }
            };

            var providersToIgnore = new Dictionary <string, string>
            {
                { "Microsoft.Azure.Graph.RBAC.Version1_6.GraphRbacManagementClient", "1.42-previewInternal" },
                { "Microsoft.Azure.Management.Resources.ResourceManagementClient", "2016-02-01" }
            };

            HttpMockServer.Matcher          = new PermissiveRecordMatcherWithResourceApiExclusion(true, d, providersToIgnore, resourceTypesToIgnoreApiVersion);
            HttpMockServer.RecordsDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SessionRecords");

            // Enable undo functionality as well as mock recording
            using (var context = MockContext.Start(callingClassType, mockName))
            {
                Helper.SetupEnvironment(AzureModule.AzureResourceManager);
                SetupManagementClients(context);
                Helper.SetupModules(AzureModule.AzureResourceManager,
                                    "ScenarioTests\\Common.ps1",
                                    "ScenarioTests\\" + GetType().Name + ".ps1",
                                    Helper.RMProfileModule,
                                    Helper.GetRMModulePath(@"AzureRM.Sql.psd1"),
                                    Helper.RMNetworkModule,
                                    "AzureRM.Storage.ps1",
                                    "AzureRM.Resources.ps1",
                                    Helper.RMOperationalInsightsModule,
                                    Helper.RMEventHubModule,
                                    Helper.RMMonitorModule,
                                    Helper.RMKeyVaultModule);
                Helper.RunPowerShellTest(scripts);
            }
        }
예제 #28
0
        public GetAzureRmAutoscaleSettingTests(Xunit.Abstractions.ITestOutputHelper output)
        {
            ServiceManagement.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagement.Common.Models.XunitTracingInterceptor(output));
            TestExecutionHelpers.SetUpSessionAndProfile();
            insightsAutoscaleOperationsMock = new Mock <IAutoscaleSettingsOperations>();
            insightsManagementClientMock    = new Mock <MonitorManagementClient>()
            {
                CallBase = true
            };
            commandRuntimeMock = new Mock <ICommandRuntime>();
            cmdlet             = new GetAzureRmAutoscaleSettingCommand()
            {
                CommandRuntime          = commandRuntimeMock.Object,
                MonitorManagementClient = insightsManagementClientMock.Object
            };

            var responseObject = new AutoscaleSettingResource(id: "", location: "", profiles: null, autoscaleSettingResourceName: "", name: "")
            {
                Tags = null,
            };

            responseSimple = new Microsoft.Rest.Azure.AzureOperationResponse <AutoscaleSettingResource>()
            {
                Body = responseObject
            };

            responsePage = new AzureOperationResponse <IPage <AutoscaleSettingResource> >()
            {
                Body = JsonConvert.DeserializeObject <Microsoft.Azure.Management.Monitor.Models.Page <AutoscaleSettingResource> >(JsonConvert.SerializeObject(responseObject))
            };

            insightsAutoscaleOperationsMock.Setup(f => f.GetWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <Microsoft.Rest.Azure.AzureOperationResponse <AutoscaleSettingResource> >(responseSimple))
            .Callback((string resourceGrp, string settingNm, Dictionary <string, List <string> > headers, CancellationToken t) =>
            {
                resourceGroup = resourceGrp;
                settingName   = settingNm;
            });

            insightsAutoscaleOperationsMock.Setup(f => f.ListByResourceGroupWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <Microsoft.Rest.Azure.AzureOperationResponse <IPage <AutoscaleSettingResource> > >(responsePage))
            .Callback((string resourceGrp, Dictionary <string, List <string> > headers, CancellationToken t) =>
            {
                resourceGroup = resourceGrp;
            });

            insightsManagementClientMock.SetupGet(f => f.AutoscaleSettings).Returns(this.insightsAutoscaleOperationsMock.Object);
        }
예제 #29
0
        public SubscriptionClientSwitchTest(ITestOutputHelper output)
        {
            TestExecutionHelpers.SetUpSessionAndProfile();
            XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output));

            AzureSession.Instance.AuthenticationFactory = new MockTokenAuthenticationFactory(DefaultAccount,
                                                                                             Guid.NewGuid().ToString(), DefaultTenant.ToString());
            ((MockTokenAuthenticationFactory)AzureSession.Instance.AuthenticationFactory).TokenProvider = (account, environment, tenant) =>
                                                                                                          new MockAccessToken
            {
                UserId      = "*****@*****.**",
                LoginType   = LoginType.OrgId,
                AccessToken = "bbb",
                TenantId    = DefaultTenant.ToString()
            };
        }
예제 #30
0
        public void DoesNotThrowWithNullError()
        {
            TestExecutionHelpers.SetUpSessionAndProfile();
            var cmdlet = new ResolveError();
            var output = cmdlet.ExecuteCmdletInPipeline <AzureErrorRecord>("Resolve-Error");

            Assert.True(output == null || output.Count == 0);
            output = cmdlet.ExecuteCmdletInPipeline <AzureErrorRecord>("Resolve-Error", new ErrorRecord[] { null, null });
            Assert.True(output == null || output.Count == 0);
            output = cmdlet.ExecuteCmdletInPipeline <AzureErrorRecord>("Resolve-Error", new ErrorRecord[] { null, new ErrorRecord(new Exception(null), null, ErrorCategory.AuthenticationError, null) });
            Assert.NotNull(output);
            Assert.Single(output);
            var record = output[0] as AzureExceptionRecord;

            Assert.NotNull(record);
            Assert.Equal(ErrorCategory.AuthenticationError, record.ErrorCategory.Category);
        }