public void ListWebHostingPlans()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(HttpPayload.ListWebHostingPlans)
            };

            var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };

            var client = GetWebSiteManagementClient(handler);

            var result = client.WebHostingPlans.List("space1");

            // Validate headers 
            Assert.Equal(HttpMethod.Get, handler.Method);

            // Validate response 
            Assert.NotNull(result.WebHostingPlans);
            Assert.Equal(1, result.WebHostingPlans.Count);
            Assert.NotNull(result.WebHostingPlans.ElementAt(0));
            Assert.Equal("Default1", result.WebHostingPlans.ElementAt(0).Name);
            Assert.Equal(SkuOptions.Standard, result.WebHostingPlans.ElementAt(0).SKU);
            Assert.Equal(1, result.WebHostingPlans.ElementAt(0).NumberOfWorkers);
            Assert.Equal("adminsite1", result.WebHostingPlans.ElementAt(0).AdminSiteName);
        }
        public void ListBackups()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(HttpPayload.ListBackups)
            };

            var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };

            var client = GetWebSiteManagementClient(handler);

            var result = client.WebSites.ListBackups("space1", "site1");

            // Validate headers 
            Assert.Equal(HttpMethod.Get, handler.Method);

            // Validate response 
            Assert.Equal(10, result.BackupItems.Count);

            var firstResult = result.BackupItems[0];
            Assert.Equal(firstResult.Status, BackupItemStatus.Succeeded);

            Assert.Equal("baysite_201408052247.zip", firstResult.BlobName);
            Assert.True(firstResult.Name.StartsWith("baysite_"));
            Assert.Equal(54503, firstResult.SizeInBytes);
            Assert.False(firstResult.Scheduled);
            Assert.True(firstResult.StorageAccountUrl.StartsWith("https://"));

            var dbResult = result.BackupItems[9];
            Assert.Equal("30d04e4b-adc2-4632-93ba-0dca15a5c778", dbResult.CorrelationId);
            Assert.Equal(1, dbResult.Databases.Count);
            Assert.Equal("MySql", dbResult.Databases[0].DatabaseType);
            Assert.Equal("db1", dbResult.Databases[0].Name);
            Assert.True(!string.IsNullOrEmpty(dbResult.Databases[0].ConnectionString));
        }
        public void GetWebSiteConfig()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(HttpPayload.GetSiteConfig)
            };

            var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };

            var client = GetWebSiteManagementClient(handler);

            var result = client.WebSites.GetConfiguration("space1", "site1");

            // Validate headers
            Assert.Equal(HttpMethod.Get, handler.Method);

            // Validate response
            Assert.Equal(2, result.AppSettings.Count);
            Assert.NotNull(result.AppSettings.ElementAt(0));
            Assert.Equal("prop1", result.AppSettings.ElementAt(0).Key);
            Assert.Equal("value1", result.AppSettings.ElementAt(0).Value);

            Assert.Equal(2, result.ConnectionStrings.Count);

            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
            Assert.Equal(1, result.RoutingRules.Count);
            Assert.True(result.RoutingRules[0] is RampUpRule);

            var rule = (RampUpRule)result.RoutingRules[0];
            Assert.Equal(45, rule.ReroutePercentage);
            Assert.Equal("rule1", rule.Name);
            Assert.Equal("test-host.antares-int.windows-int.net", rule.ActionHostName);

            Assert.NotNull(result.ConnectionStrings);
            Assert.NotNull(result.ConnectionStrings[0]);
            Assert.Equal("connection1", result.ConnectionStrings[0].Name);
            Assert.Equal("mssql", result.ConnectionStrings[0].ConnectionString);
            Assert.Equal(ConnectionStringType.SqlAzure, result.ConnectionStrings[0].Type);

            var expectedSiteLimits = new WebSiteUpdateConfigurationParameters.SiteLimits()
            {
                MaxDiskSizeInMb = 1024,
                MaxMemoryInMb = 512,
                MaxPercentageCpu = 70.5
            };

            Assert.NotNull(result.Limits);
            Assert.Equal(expectedSiteLimits.MaxDiskSizeInMb, result.Limits.MaxDiskSizeInMb);
            Assert.Equal(expectedSiteLimits.MaxMemoryInMb, result.Limits.MaxMemoryInMb);
            Assert.Equal(expectedSiteLimits.MaxPercentageCpu, result.Limits.MaxPercentageCpu);

            bool siteAuthEnabled = result.SiteAuthEnabled.GetValueOrDefault();
            SiteAuthSettings siteAuthSettings = result.SiteAuthSettings;
            Assert.True(siteAuthEnabled);
            Assert.NotNull(siteAuthSettings);
            Assert.Equal("00000000-0000-0000-0000-7984e05b758c", siteAuthSettings.AADClientId);
            Assert.Equal("https://sts.windows.net/00000000-0000-0000-0000-19d76fef90d7/", siteAuthSettings.OpenIdIssuer);
            Assert.Equal(RemoteDebuggingVersion.VS2015, result.RemoteDebuggingVersion);
        }
 public WebSiteManagementClient GetWebSiteManagementClient(RecordedDelegatingHandler handler)
 {
     handler.IsPassThrough = false;
     var token = new TokenCloudCredentials(Guid.NewGuid().ToString(), "abc123");
     var client = new WebSiteManagementClient(token).WithHandler(handler);
     client = client.WithHandler(handler);
     return client;
 }
        public void ListHistoryActiveFaults()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(ExpectedResults.HistoryActiveFaultListResponse)
            };

            var handler = new RecordedDelegatingHandler(response)
            {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            var subscriptionId = Guid.NewGuid().ToString();

            var token = new TokenCloudCredentials(subscriptionId, Constants.TokenString);
            var client = GetClient(handler, token);
            var startTime = new DateTime(2015, 3, 18);
            var endTime = new DateTime(2015, 3, 18);
            var ResourceUri = "/subscriptions/serviceAdmin/resourceGroups/system/providers/Microsoft.Storage.Admin/farms/WEST_US_1/tableserverinstances/woss-node1";

            var result = client.Faults.ListHistoryFaults(
                Constants.ResourceGroupName,
                Constants.FarmId,
                startTime.ToString("o"),
                endTime.ToString("o"),
                ResourceUri);

            // validate requestor
            Assert.Equal(handler.Method, HttpMethod.Get);

            var expectedUri = string.Format(
                FaultListUriTemplate,
                Constants.BaseUri,
                subscriptionId,
                Constants.ResourceGroupName,
                Constants.FarmId);

            var expectedFilterUri = string.Format(
                HistoryFaultFilterUriTemplate,
                Uri.EscapeDataString(startTime.ToString("o")),
                Uri.EscapeDataString(endTime.ToString("o")),
                Uri.EscapeDataString(ResourceUri));

            expectedUri = string.Concat(expectedUri, expectedFilterUri);
            expectedUri = expectedUri.Replace(" ", "%20");

            Assert.Equal(handler.Uri.AbsoluteUri, expectedUri);

            Assert.True(result.Faults.Count > 1);
            CompareExpectedResult(result.Faults[0], false);
        }
        public void ApplySlotConfiguragion()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(HttpPayload.GetWebSiteMetricsPerInstancePerMinute)
            };

            var handler = new RecordedDelegatingHandler(response) {StatusCodeToReturn = HttpStatusCode.OK};

            var client = GetWebSiteManagementClient(handler);

            var result = client.WebSites.ApplySlotConfiguration("space1", "site1(staging)", "production");

            // Validate headers
            Assert.Equal(HttpMethod.Post, handler.Method);
        }
        public void GetHybridConnectionsTest()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(HttpPayload.GetHybridConnection)
            };

            var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };

            var client = GetWebSiteManagementClient(handler);

            var result = client.WebSites.GetHybridConnection("space1", "site1", "testhybrid1");

            Assert.True(result.HybridConnection.EntityName == "testhybrid1");
            Assert.True(result.HybridConnection.Hostname == "myhost1");
            Assert.Equal(result.HybridConnection.Port, 80);
        }
        public void ListHybridConnectionsTest()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(HttpPayload.ListHybridConnections)
            };

            var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };

            var client = GetWebSiteManagementClient(handler);

            var result = client.WebSites.ListHybridConnections("space1", "site1");

            // Verify that we have two connections, one called "testhybrid1" and another called "testhybrid2"
            foreach (var connection in result.HybridConnections)
            {
                Assert.True(connection.EntityName == "testhybrid1" || connection.EntityName == "testhybrid2");
                Assert.True(connection.Hostname == "myhost1" || connection.Hostname == "myhost2");
                Assert.Equal(connection.Port, 80);
            }
        }
        public void GetBackupConfiguration()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(HttpPayload.GetBackupConfiguration)
            };

            var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };

            var client = GetWebSiteManagementClient(handler);

            var backupConfiguration = client.WebSites.GetBackupConfiguration("space1", "baysite");

            Assert.Equal(17, backupConfiguration.BackupSchedule.FrequencyInterval);
            Assert.Equal(FrequencyUnit.Day, backupConfiguration.BackupSchedule.FrequencyUnit);
            Assert.Equal(true, backupConfiguration.BackupSchedule.KeepAtLeastOneBackup);
            Assert.Equal(26, backupConfiguration.BackupSchedule.RetentionPeriodInDays);
            Assert.Equal(new DateTime(635435517126146425).ToLocalTime(), backupConfiguration.BackupSchedule.StartTime);

            Assert.Equal(false, backupConfiguration.Enabled);
            Assert.True(backupConfiguration.StorageAccountUrl.StartsWith("https://"));
        }
        public void BackupSite()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(HttpPayload.BackupSite)
            };

            var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };

            var client = GetWebSiteManagementClient(handler);

            BackupRequest backupRequest = new BackupRequest()
            {
                Name = "abc.zip",
                Databases = new List<DatabaseBackupSetting>(),
                StorageAccountUrl = "https://username.blob.core.windows.net/backup/?sv=2012-02-12"
            };
            backupRequest.Databases.Add(new DatabaseBackupSetting()
            {
                ConnectionString = "Server=someserver;Database=somedatabase;Uid=someusername;Pwd=somepassword;",
                DatabaseType = "MySql",
                Name = "db1"
            });

            var backupResponse = client.WebSites.Backup("space1", "baysite", backupRequest);
            Assert.Equal(HttpStatusCode.OK, backupResponse.StatusCode);

            var backupResult = backupResponse.BackupItem;
            Assert.Equal(backupResult.Status, BackupItemStatus.Created);
            Assert.Equal(1, backupResult.Databases.Count);

            Assert.Equal("abc.zip", backupResult.BlobName);
            Assert.Equal("abc.zip", backupResult.Name);
            Assert.Equal(0, backupResult.SizeInBytes);
            Assert.False(backupResult.Scheduled);
            Assert.True(backupResult.StorageAccountUrl.StartsWith("https://"));

            Assert.Equal("MySql", backupResult.Databases[0].DatabaseType);
            Assert.Equal("db1", backupResult.Databases[0].Name);
            Assert.True(!string.IsNullOrEmpty(backupResult.Databases[0].ConnectionString));
        }
Beispiel #11
0
        public void VirtualNetworkApiTest()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient         = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(context, handler1);
                var networkManagementClient = NetworkManagementTestUtilities.GetNetworkManagementClientWithHandler(context, handler2);

                var location = NetworkManagementTestUtilities.GetResourceLocation(resourcesClient, "Microsoft.Network/virtualNetworks");

                string resourceGroupName = TestUtilities.GenerateName("csmrg");
                resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName,
                                                              new ResourceGroup
                {
                    Location = location
                });

                string vnetName    = TestUtilities.GenerateName();
                string subnet1Name = TestUtilities.GenerateName();
                string subnet2Name = TestUtilities.GenerateName();

                var vnet = new VirtualNetwork()
                {
                    Location = location,

                    AddressSpace = new AddressSpace()
                    {
                        AddressPrefixes = new List <string>()
                        {
                            "10.0.0.0/16",
                        }
                    },
                    DhcpOptions = new DhcpOptions()
                    {
                        DnsServers = new List <string>()
                        {
                            "10.1.1.1",
                            "10.1.2.4"
                        }
                    },
                    Subnets = new List <Subnet>()
                    {
                        new Subnet()
                        {
                            Name          = subnet1Name,
                            AddressPrefix = "10.0.1.0/24",
                        },
                        new Subnet()
                        {
                            Name          = subnet2Name,
                            AddressPrefix = "10.0.2.0/24",
                        }
                    }
                };

                // Put Vnet
                var putVnetResponse = networkManagementClient.VirtualNetworks.CreateOrUpdate(resourceGroupName, vnetName, vnet);
                Assert.Equal("Succeeded", putVnetResponse.ProvisioningState);

                // Get Vnet
                var getVnetResponse = networkManagementClient.VirtualNetworks.Get(resourceGroupName, vnetName);
                Assert.Equal(vnetName, getVnetResponse.Name);
                Assert.NotNull(getVnetResponse.ResourceGuid);
                Assert.Equal("Succeeded", getVnetResponse.ProvisioningState);
                Assert.Equal("10.1.1.1", getVnetResponse.DhcpOptions.DnsServers[0]);
                Assert.Equal("10.1.2.4", getVnetResponse.DhcpOptions.DnsServers[1]);
                Assert.Equal("10.0.0.0/16", getVnetResponse.AddressSpace.AddressPrefixes[0]);
                Assert.Equal(subnet1Name, getVnetResponse.Subnets[0].Name);
                Assert.Equal(subnet2Name, getVnetResponse.Subnets[1].Name);

                // Get all Vnets
                var getAllVnets = networkManagementClient.VirtualNetworks.List(resourceGroupName);
                Assert.Equal(vnetName, getAllVnets.ElementAt(0).Name);
                Assert.Equal("Succeeded", getAllVnets.ElementAt(0).ProvisioningState);
                Assert.Equal("10.0.0.0/16", getAllVnets.ElementAt(0).AddressSpace.AddressPrefixes[0]);
                Assert.Equal(subnet1Name, getAllVnets.ElementAt(0).Subnets[0].Name);
                Assert.Equal(subnet2Name, getAllVnets.ElementAt(0).Subnets[1].Name);

                // Get all Vnets in a subscription
                var getAllVnetInSubscription = networkManagementClient.VirtualNetworks.ListAll();
                Assert.NotEqual(0, getAllVnetInSubscription.Count());

                // Delete Vnet
                networkManagementClient.VirtualNetworks.Delete(resourceGroupName, vnetName);

                // Get all Vnets
                getAllVnets = networkManagementClient.VirtualNetworks.List(resourceGroupName);
                Assert.Equal(0, getAllVnets.Count());
            }
        }
        public void UpdateSiteConfig()
        {
            var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
            var client = GetWebSiteManagementClient(handler);

            string expectedClientId = Guid.NewGuid().ToString();
            string expectedIssuer = "https://sts.microsoft.net/" + Guid.NewGuid() + "/";

            var expectedLimits = new WebSiteUpdateConfigurationParameters.SiteLimits()
            {
                MaxDiskSizeInMb = 1024,
                MaxMemoryInMb = 512,
                MaxPercentageCpu = 70.5
            };

            var parameters = new WebSiteUpdateConfigurationParameters
            {
                SiteAuthEnabled = true,
                SiteAuthSettings = new SiteAuthSettings
                {
                    AADClientId = expectedClientId,
                    OpenIdIssuer = expectedIssuer,
                },
                Limits = expectedLimits 
            };

            // Simulate a PUT request to update the config
            client.WebSites.UpdateConfiguration("webspace", "website", parameters);

            // Check the payload of the previous request to see if it matches our expectations
            Assert.Equal(handler.Method, HttpMethod.Put);
            Assert.NotEmpty(handler.Request);
            JObject requestJson = JObject.Parse(handler.Request);

            JToken token;
            Assert.True(requestJson.TryGetValue("SiteAuthEnabled", out token));
            Assert.Equal(JTokenType.Boolean, token.Type);
            Assert.True(token.Value<bool>());

            Assert.True(requestJson.TryGetValue("SiteAuthSettings", out token));
            Assert.Equal(JTokenType.Object, token.Type);

            JObject siteAuthSettingsJson = (JObject)token;
            Assert.True(siteAuthSettingsJson.TryGetValue("AADClientId", out token));
            Assert.Equal(JTokenType.String, token.Type);
            Assert.Equal(expectedClientId, token.Value<string>());

            Assert.True(siteAuthSettingsJson.TryGetValue("OpenIdIssuer", out token));
            Assert.Equal(JTokenType.String, token.Type);
            Assert.Equal(expectedIssuer, token.Value<string>());

            Assert.True(requestJson.TryGetValue("limits", out token));
            Assert.Equal(JTokenType.Object, token.Type);
            JObject limitsJson = (JObject)token;

            Assert.True(limitsJson.TryGetValue("maxDiskSizeInMb", out token));
            Assert.Equal(JTokenType.Integer, token.Type);
            Assert.Equal(expectedLimits.MaxDiskSizeInMb, token.Value<long>());

            Assert.True(limitsJson.TryGetValue("maxMemoryInMb", out token));
            Assert.Equal(JTokenType.Integer, token.Type);
            Assert.Equal(expectedLimits.MaxMemoryInMb, token.Value<long>());

            Assert.True(limitsJson.TryGetValue("maxPercentageCpu", out token));
            Assert.Equal(JTokenType.Float, token.Type);
            Assert.Equal(expectedLimits.MaxPercentageCpu, token.Value<double>());
        }
        public void InMemory_JobCollectionCreateOrUpdateThrowsException()
        {
            var response = new HttpResponseMessage(HttpStatusCode.BadRequest);
            var handler  = new RecordedDelegatingHandler(response);
            var client   = this.GetSchedulerManagementClient(handler);

            Assert.Throws <ValidationException>(() => client.JobCollections.CreateOrUpdate(
                                                    resourceGroupName: null,
                                                    jobCollectionName: "bar",
                                                    jobCollection: new JobCollectionDefinition()
            {
                Name       = "jc1",
                Location   = "South Central US",
                Properties = new JobCollectionProperties()
                {
                    Sku = new Sku()
                    {
                        Name = SkuDefinition.Standard,
                    },
                    State = JobCollectionState.Suspended,
                    Quota = new JobCollectionQuota()
                    {
                        MaxJobCount      = 20,
                        MaxJobOccurrence = 300,
                        MaxRecurrence    = new JobMaxRecurrence()
                        {
                            Frequency = RecurrenceFrequency.Week,
                            Interval  = 1,
                        }
                    }
                }
            }));

            Assert.Throws <ValidationException>(() => client.JobCollections.CreateOrUpdate(
                                                    resourceGroupName: "foo",
                                                    jobCollectionName: null,
                                                    jobCollection: new JobCollectionDefinition()
            {
                Name       = "jc1",
                Location   = "South Central US",
                Properties = new JobCollectionProperties()
                {
                    Sku = new Sku()
                    {
                        Name = SkuDefinition.Standard,
                    },
                    State = JobCollectionState.Suspended,
                    Quota = new JobCollectionQuota()
                    {
                        MaxJobCount      = 20,
                        MaxJobOccurrence = 300,
                        MaxRecurrence    = new JobMaxRecurrence()
                        {
                            Frequency = RecurrenceFrequency.Week,
                            Interval  = 1,
                        }
                    }
                }
            }));

            Assert.Throws <ValidationException>(() => client.JobCollections.CreateOrUpdate(
                                                    resourceGroupName: "foo",
                                                    jobCollectionName: "bar",
                                                    jobCollection: null));

            Assert.Throws <CloudException>(() => client.JobCollections.CreateOrUpdate(
                                               resourceGroupName: "foo",
                                               jobCollectionName: "bar",
                                               jobCollection: new JobCollectionDefinition()
            {
                Name       = "jc1",
                Location   = "South Central US",
                Properties = new JobCollectionProperties()
                {
                    Sku = new Sku()
                    {
                        Name = SkuDefinition.Standard,
                    },
                    State = JobCollectionState.Suspended,
                    Quota = new JobCollectionQuota()
                    {
                        MaxJobCount      = 20,
                        MaxJobOccurrence = 300,
                        MaxRecurrence    = new JobMaxRecurrence()
                        {
                            Frequency = RecurrenceFrequency.Week,
                            Interval  = 1,
                        }
                    }
                }
            }));
        }
Beispiel #14
0
        public void EndpointStartStopTest()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                // Create clients
                var cdnMgmtClient   = CdnTestUtilities.GetCdnManagementClient(context, handler1);
                var resourcesClient = CdnTestUtilities.GetResourceManagementClient(context, handler2);

                // Create resource group
                var resourceGroupName = CdnTestUtilities.CreateResourceGroup(resourcesClient);

                // Create a standard cdn profile
                string profileName = TestUtilities.GenerateName("profile");
                ProfileCreateParameters createParameters = new ProfileCreateParameters
                {
                    Location = "WestUs",
                    Sku      = new Sku {
                        Name = SkuName.StandardVerizon
                    },
                    Tags = new Dictionary <string, string>
                    {
                        { "key1", "value1" },
                        { "key2", "value2" }
                    }
                };

                var profile = cdnMgmtClient.Profiles.Create(profileName, createParameters, resourceGroupName);

                // Create a cdn endpoint with minimum requirements should succeed
                string endpointName             = TestUtilities.GenerateName("endpoint");
                var    endpointCreateParameters = new EndpointCreateParameters
                {
                    Location       = "WestUs",
                    IsHttpAllowed  = true,
                    IsHttpsAllowed = true,
                    Origins        = new List <DeepCreatedOrigin>
                    {
                        new DeepCreatedOrigin
                        {
                            Name     = "origin1",
                            HostName = "host1.hello.com"
                        }
                    }
                };

                cdnMgmtClient.Endpoints.Create(endpointName, endpointCreateParameters, profileName, resourceGroupName);

                // Stop a running endpoint should succeed
                cdnMgmtClient.Endpoints.Stop(endpointName, profileName, resourceGroupName);
                var endpoint = cdnMgmtClient.Endpoints.Get(endpointName, profileName, resourceGroupName);
                Assert.Equal(endpoint.ResourceState, EndpointResourceState.Stopped);

                // Start a stopped endpoint should succeed
                cdnMgmtClient.Endpoints.Start(endpointName, profileName, resourceGroupName);
                endpoint = cdnMgmtClient.Endpoints.Get(endpointName, profileName, resourceGroupName);
                Assert.Equal(endpoint.ResourceState, EndpointResourceState.Running);

                // Delete resource group
                CdnTestUtilities.DeleteResourceGroup(resourcesClient, resourceGroupName);
            }
        }
        public void InMemory_JobCollectionCreateUpdateDelete()
        {
            var createRresponse = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(@"{
                  'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Scheduler/jobCollections/jc1',
                  'type': 'Microsoft.Scheduler/jobCollections',
                  'name': 'jc1',
                  'location': 'South Central US',
                  'properties': {
                        'sku': {
			                'name': 'Standard'
		                },
		                'state': 'Suspended',
		                'quota': {
			                'maxJobCount': 20,
                            'maxJobOccurrence': 300,
			                'maxRecurrence': {
				                'frequency': 'Week',
				                'interval': 1
			                }
		                }
                    }
                }")
            };

            createRresponse.Headers.Add("x-ms-request-id", "1");
            var createHandler = new RecordedDelegatingHandler(createRresponse)
            {
                StatusCodeToReturn = HttpStatusCode.Created
            };
            var createClient = this.GetSchedulerManagementClient(createHandler);

            var result = createClient.JobCollections.CreateOrUpdate(
                resourceGroupName: "foo",
                jobCollectionName: "jc1",
                jobCollection: new JobCollectionDefinition()
            {
                Name       = "jc1",
                Location   = "South Central US",
                Properties = new JobCollectionProperties()
                {
                    Sku = new Sku()
                    {
                        Name = SkuDefinition.Standard,
                    },
                    State = JobCollectionState.Suspended,
                    Quota = new JobCollectionQuota()
                    {
                        MaxJobCount      = 20,
                        MaxJobOccurrence = 300,
                        MaxRecurrence    = new JobMaxRecurrence()
                        {
                            Frequency = RecurrenceFrequency.Week,
                            Interval  = 1,
                        }
                    }
                }
            });

            // Validate headers
            Assert.Equal(HttpMethod.Put, createHandler.Method);
            Assert.NotNull(createHandler.RequestHeaders.GetValues("Authorization"));

            Assert.Equal("South Central US", result.Location);
            Assert.Equal("Microsoft.Scheduler/jobCollections", result.Type);
            Assert.Equal("jc1", result.Name);
            Assert.Equal("/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Scheduler/jobCollections/jc1", result.Id);
            Assert.Equal(SkuDefinition.Standard, result.Properties.Sku.Name);
            Assert.Equal(JobCollectionState.Suspended, result.Properties.State);
            Assert.Equal(20, result.Properties.Quota.MaxJobCount);
            Assert.Equal(300, result.Properties.Quota.MaxJobOccurrence);
            Assert.Equal(RecurrenceFrequency.Week, result.Properties.Quota.MaxRecurrence.Frequency);
            Assert.Equal(1, result.Properties.Quota.MaxRecurrence.Interval);

            var deleteHandler = new RecordedDelegatingHandler()
            {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var deleteClient = this.GetSchedulerManagementClient(deleteHandler);

            deleteClient.JobCollections.Delete("foo", "jc1");
        }
 public static ResourceManagementClient GetResourceManagementClient(MockContext context, RecordedDelegatingHandler handler)
 {
     if (IsTestTenant)
     {
         return(null);
     }
     else
     {
         handler.IsPassThrough = true;
         ResourceManagementClient resourcesClient = context.GetServiceClient <ResourceManagementClient>(handlers: handler);
         return(resourcesClient);
     }
 }
Beispiel #17
0
        public void EndpointCreateTest()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                // Create clients
                var cdnMgmtClient   = CdnTestUtilities.GetCdnManagementClient(context, handler1);
                var resourcesClient = CdnTestUtilities.GetResourceManagementClient(context, handler2);

                // Create resource group
                var resourceGroupName = CdnTestUtilities.CreateResourceGroup(resourcesClient);

                // Create a standard cdn profile
                string profileName = TestUtilities.GenerateName("profile");
                ProfileCreateParameters createParameters = new ProfileCreateParameters
                {
                    Location = "WestUs",
                    Sku      = new Sku {
                        Name = SkuName.StandardVerizon
                    },
                    Tags = new Dictionary <string, string>
                    {
                        { "key1", "value1" },
                        { "key2", "value2" }
                    }
                };

                var profile = cdnMgmtClient.Profiles.Create(profileName, createParameters, resourceGroupName);

                // Create a cdn endpoint with minimum requirements should succeed
                string endpointName             = TestUtilities.GenerateName("endpoint");
                var    endpointCreateParameters = new EndpointCreateParameters
                {
                    Location       = "WestUs",
                    IsHttpAllowed  = true,
                    IsHttpsAllowed = true,
                    Origins        = new List <DeepCreatedOrigin>
                    {
                        new DeepCreatedOrigin
                        {
                            Name     = "origin1",
                            HostName = "host1.hello.com"
                        }
                    }
                };

                var endpoint         = cdnMgmtClient.Endpoints.Create(endpointName, endpointCreateParameters, profileName, resourceGroupName);
                var existingEndpoint = cdnMgmtClient.Endpoints.Get(endpointName, profileName, resourceGroupName);

                // Create endpoint with same name should fail
                endpointCreateParameters = new EndpointCreateParameters
                {
                    Location       = "EastUs",
                    IsHttpAllowed  = false,
                    IsHttpsAllowed = true,
                    Origins        = new List <DeepCreatedOrigin>
                    {
                        new DeepCreatedOrigin
                        {
                            Name     = "origin2",
                            HostName = "host2.hello.com"
                        }
                    }
                };

                Assert.ThrowsAny <ErrorResponseException>(() => {
                    cdnMgmtClient.Endpoints.Create(endpointName, endpointCreateParameters, profileName, resourceGroupName);
                });

                // Create a cdn endpoint with full properties should succeed
                endpointName             = TestUtilities.GenerateName("endpoint");
                endpointCreateParameters = new EndpointCreateParameters
                {
                    Location                   = "WestUs",
                    IsHttpAllowed              = true,
                    IsHttpsAllowed             = true,
                    IsCompressionEnabled       = true,
                    OriginHostHeader           = "www.bing.com",
                    OriginPath                 = "/photos",
                    QueryStringCachingBehavior = QueryStringCachingBehavior.BypassCaching,
                    ContentTypesToCompress     = new List <string> {
                        "text/html", "application/octet-stream"
                    },
                    Tags = new Dictionary <string, string> {
                        { "kay1", "value1" }
                    },
                    Origins = new List <DeepCreatedOrigin>
                    {
                        new DeepCreatedOrigin
                        {
                            Name     = "origin1",
                            HostName = "host1.hello.com"
                        }
                    }
                };

                endpoint = cdnMgmtClient.Endpoints.Create(endpointName, endpointCreateParameters, profileName, resourceGroupName);
                Assert.NotNull(endpoint);

                // Create a cdn endpoint with no origins should fail
                endpointName             = TestUtilities.GenerateName("endpoint");
                endpointCreateParameters = new EndpointCreateParameters
                {
                    Location                   = "WestUs",
                    IsHttpAllowed              = true,
                    IsHttpsAllowed             = true,
                    IsCompressionEnabled       = true,
                    OriginHostHeader           = "www.bing.com",
                    OriginPath                 = "/photos",
                    QueryStringCachingBehavior = QueryStringCachingBehavior.BypassCaching,
                    ContentTypesToCompress     = new List <string> {
                        "text/html", "application/octet-stream"
                    },
                    Tags = new Dictionary <string, string> {
                        { "kay1", "value1" }
                    }
                };

                Assert.ThrowsAny <ValidationException>(() => {
                    cdnMgmtClient.Endpoints.Create(endpointName, endpointCreateParameters, profileName, resourceGroupName);
                });

                // Create a cdn endpoint with both http and https disallowed should fail
                endpointName             = TestUtilities.GenerateName("endpoint");
                endpointCreateParameters = new EndpointCreateParameters
                {
                    Location                   = "WestUs",
                    IsHttpAllowed              = false,
                    IsHttpsAllowed             = false,
                    IsCompressionEnabled       = true,
                    OriginHostHeader           = "www.bing.com",
                    OriginPath                 = "/photos",
                    QueryStringCachingBehavior = QueryStringCachingBehavior.BypassCaching,
                    ContentTypesToCompress     = new List <string> {
                        "text/html", "application/octet-stream"
                    },
                    Tags = new Dictionary <string, string> {
                        { "kay1", "value1" }
                    }
                };

                Assert.ThrowsAny <ValidationException>(() => {
                    cdnMgmtClient.Endpoints.Create(endpointName, endpointCreateParameters, profileName, resourceGroupName);
                });

                // Delete resource group
                CdnTestUtilities.DeleteResourceGroup(resourcesClient, resourceGroupName);
            }
        }
        public FluxConfigurationTestBase(MockContext context)
        {
            var handler = new RecordedDelegatingHandler();

            SourceControlConfigurationClient = context.GetServiceClient <SourceControlConfigurationClient>(false, handler);
        }
        public static StorageManagementClient GetStorageManagementClient(MockContext context, RecordedDelegatingHandler handler)
        {
            StorageManagementClient storageClient;

            if (IsTestTenant)
            {
                storageClient = new StorageManagementClient(new TokenCredentials("xyz"), GetHandler());
                storageClient.SubscriptionId = testSubscription;
                storageClient.BaseUri        = testUri;
            }
            else
            {
                handler.IsPassThrough = true;
                storageClient         = context.GetServiceClient <StorageManagementClient>(handlers: handler);
            }
            return(storageClient);
        }
        public void VerifyIpFlowApiTest()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler3 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var resourcesClient         = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(context, handler1);
                var networkManagementClient = NetworkManagementTestUtilities.GetNetworkManagementClientWithHandler(context, handler2);
                var computeManagementClient = NetworkManagementTestUtilities.GetComputeManagementClientWithHandler(context, handler3);

                string location = "eastus";

                string resourceGroupName = TestUtilities.GenerateName();
                resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName,
                                                              new ResourceGroup
                {
                    Location = location
                });

                string virtualMachineName1      = TestUtilities.GenerateName();
                string networkInterfaceName1    = TestUtilities.GenerateName();
                string networkSecurityGroupName = virtualMachineName1 + "-nsg";

                //Deploy VM with a template
                Deployments.CreateVm(
                    resourcesClient: resourcesClient,
                    resourceGroupName: resourceGroupName,
                    location: location,
                    virtualMachineName: virtualMachineName1,
                    storageAccountName: TestUtilities.GenerateName(),
                    networkInterfaceName: networkInterfaceName1,
                    networkSecurityGroupName: networkSecurityGroupName,
                    diagnosticsStorageAccountName: TestUtilities.GenerateName(),
                    deploymentName: TestUtilities.GenerateName()
                    );

                string         networkWatcherName = TestUtilities.GenerateName();
                NetworkWatcher properties         = new NetworkWatcher();
                properties.Location = location;

                //Create network Watcher
                var createNetworkWatcher = networkManagementClient.NetworkWatchers.CreateOrUpdate(resourceGroupName, networkWatcherName, properties);

                var    getVm1         = computeManagementClient.VirtualMachines.Get(resourceGroupName, virtualMachineName1);
                string localIPAddress = networkManagementClient.NetworkInterfaces.Get(resourceGroupName, networkInterfaceName1).IpConfigurations.FirstOrDefault().PrivateIPAddress;


                string securityRule1 = TestUtilities.GenerateName();

                // Add a security rule
                var SecurityRule = new SecurityRule()
                {
                    Name        = securityRule1,
                    Access      = SecurityRuleAccess.Deny,
                    Description = "Test outbound security rule",
                    DestinationAddressPrefix = "*",
                    DestinationPortRange     = "80",
                    Direction           = SecurityRuleDirection.Outbound,
                    Priority            = 501,
                    Protocol            = SecurityRuleProtocol.Tcp,
                    SourceAddressPrefix = "*",
                    SourcePortRange     = "*",
                };

                var nsg = networkManagementClient.NetworkSecurityGroups.Get(resourceGroupName, networkSecurityGroupName);
                nsg.SecurityRules.Add(SecurityRule);
                networkManagementClient.NetworkSecurityGroups.CreateOrUpdate(resourceGroupName, networkSecurityGroupName, nsg);

                VerificationIPFlowParameters ipFlowProperties = new VerificationIPFlowParameters()
                {
                    TargetResourceId = getVm1.Id,
                    Direction        = "Outbound",
                    Protocol         = "TCP",
                    LocalPort        = "80",
                    RemotePort       = "80",
                    LocalIPAddress   = localIPAddress,
                    RemoteIPAddress  = "12.11.12.14"
                };

                //Verify IP flow from a VM to a location given the configured  rule
                var verifyIpFlow = networkManagementClient.NetworkWatchers.VerifyIPFlow(resourceGroupName, networkWatcherName, ipFlowProperties);

                //Verify validity of the result
                Assert.Equal("Deny", verifyIpFlow.Access);
                Assert.Equal("securityRules/" + securityRule1, verifyIpFlow.RuleName);
            }
        }
Beispiel #21
0
        public void GraphCRUDTests()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                // Create client
                CosmosDBManagementClient cosmosDBManagementClient = CosmosDBTestUtilities.GetCosmosDBClient(context, handler1);

                bool isDatabaseNameExists = cosmosDBManagementClient.DatabaseAccounts.CheckNameExistsWithHttpMessagesAsync(databaseAccountName).GetAwaiter().GetResult().Body;

                if (!isDatabaseNameExists)
                {
                    return;
                }

                GremlinDatabaseCreateUpdateParameters gremlinDatabaseCreateUpdateParameters = new GremlinDatabaseCreateUpdateParameters
                {
                    Resource = new GremlinDatabaseResource {
                        Id = databaseName
                    },
                    Options = new CreateUpdateOptions()
                };

                GremlinDatabaseGetResults gremlinDatabaseGetResults = cosmosDBManagementClient.GremlinResources.CreateUpdateGremlinDatabaseWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, gremlinDatabaseCreateUpdateParameters).GetAwaiter().GetResult().Body;
                Assert.NotNull(gremlinDatabaseGetResults);
                Assert.Equal(databaseName, gremlinDatabaseGetResults.Name);

                GremlinDatabaseGetResults gremlinDatabaseGetResults1 = cosmosDBManagementClient.GremlinResources.GetGremlinDatabaseWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName).GetAwaiter().GetResult().Body;
                Assert.NotNull(gremlinDatabaseGetResults1);
                Assert.Equal(databaseName, gremlinDatabaseGetResults1.Name);

                VerifyEqualGremlinDatabases(gremlinDatabaseGetResults, gremlinDatabaseGetResults1);

                GremlinDatabaseCreateUpdateParameters gremlinDatabaseCreateUpdateParameters2 = new GremlinDatabaseCreateUpdateParameters
                {
                    Location = location,
                    Tags     = tags,
                    Resource = new GremlinDatabaseResource {
                        Id = databaseName2
                    },
                    Options = new CreateUpdateOptions
                    {
                        Throughput = sampleThroughput
                    }
                };

                GremlinDatabaseGetResults gremlinDatabaseGetResults2 = cosmosDBManagementClient.GremlinResources.CreateUpdateGremlinDatabaseWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName2, gremlinDatabaseCreateUpdateParameters2).GetAwaiter().GetResult().Body;
                Assert.NotNull(gremlinDatabaseGetResults2);
                Assert.Equal(databaseName2, gremlinDatabaseGetResults2.Name);

                IEnumerable <GremlinDatabaseGetResults> gremlinDatabases = cosmosDBManagementClient.GremlinResources.ListGremlinDatabasesWithHttpMessagesAsync(resourceGroupName, databaseAccountName).GetAwaiter().GetResult().Body;
                Assert.NotNull(gremlinDatabases);

                ThroughputSettingsGetResults throughputSettingsGetResults = cosmosDBManagementClient.GremlinResources.GetGremlinDatabaseThroughputWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName2).GetAwaiter().GetResult().Body;
                Assert.NotNull(throughputSettingsGetResults);
                Assert.NotNull(throughputSettingsGetResults.Name);
                Assert.Equal(throughputSettingsGetResults.Resource.Throughput, sampleThroughput);
                Assert.Equal(graphThroughputType, throughputSettingsGetResults.Type);

                GremlinGraphCreateUpdateParameters gremlinGraphCreateUpdateParameters = new GremlinGraphCreateUpdateParameters
                {
                    Resource = new GremlinGraphResource
                    {
                        Id           = gremlinGraphName,
                        DefaultTtl   = -1,
                        PartitionKey = new ContainerPartitionKey
                        {
                            Kind  = "Hash",
                            Paths = new List <string> {
                                "/address"
                            }
                        },
                        IndexingPolicy = new IndexingPolicy
                        {
                            Automatic     = true,
                            IndexingMode  = IndexingMode.Consistent,
                            IncludedPaths = new List <IncludedPath>
                            {
                                new IncludedPath {
                                    Path = "/*"
                                }
                            },
                            ExcludedPaths = new List <ExcludedPath>
                            {
                                new ExcludedPath {
                                    Path = "/pathToNotIndex/*"
                                }
                            },
                            CompositeIndexes = new List <IList <CompositePath> >
                            {
                                new List <CompositePath>
                                {
                                    new CompositePath {
                                        Path = "/orderByPath1", Order = CompositePathSortOrder.Ascending
                                    },
                                    new CompositePath {
                                        Path = "/orderByPath2", Order = CompositePathSortOrder.Descending
                                    }
                                },
                                new List <CompositePath>
                                {
                                    new CompositePath {
                                        Path = "/orderByPath3", Order = CompositePathSortOrder.Ascending
                                    },
                                    new CompositePath {
                                        Path = "/orderByPath4", Order = CompositePathSortOrder.Descending
                                    }
                                }
                            }
                        }
                    },
                    Options = new CreateUpdateOptions
                    {
                        Throughput = sampleThroughput
                    }
                };

                GremlinGraphGetResults gremlinGraphGetResults = cosmosDBManagementClient.GremlinResources.CreateUpdateGremlinGraphWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, gremlinGraphName, gremlinGraphCreateUpdateParameters).GetAwaiter().GetResult().Body;
                Assert.NotNull(gremlinGraphGetResults);
                VerifyGremlinGraphCreation(gremlinGraphGetResults, gremlinGraphCreateUpdateParameters);

                IEnumerable <GremlinGraphGetResults> gremlinGraphs = cosmosDBManagementClient.GremlinResources.ListGremlinGraphsWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName).GetAwaiter().GetResult().Body;
                Assert.NotNull(gremlinGraphs);

                foreach (GremlinGraphGetResults gremlinGraph in gremlinGraphs)
                {
                    cosmosDBManagementClient.GremlinResources.DeleteGremlinGraphWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, gremlinGraph.Name);
                }

                foreach (GremlinDatabaseGetResults gremlinDatabase in gremlinDatabases)
                {
                    cosmosDBManagementClient.GremlinResources.DeleteGremlinDatabaseWithHttpMessagesAsync(resourceGroupName, databaseAccountName, gremlinDatabase.Name);
                }
            }
        }
Beispiel #22
0
        public void EndpointCheckNameAvailabilityTest()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                // Create clients
                var cdnMgmtClient   = CdnTestUtilities.GetCdnManagementClient(context, handler1);
                var resourcesClient = CdnTestUtilities.GetResourceManagementClient(context, handler2);

                // Generate new endpoint name
                string endpointName = TestUtilities.GenerateName("endpoint-unique");


                // CheckNameAvailability should return true
                var output = cdnMgmtClient.CheckNameAvailability(endpointName);
                Assert.True(output.NameAvailable);

                // Create endpoint with that name then CheckNameAvailability again

                // Create resource group
                var resourceGroupName = CdnTestUtilities.CreateResourceGroup(resourcesClient);

                // Create a standard cdn profile
                string  profileName      = TestUtilities.GenerateName("profile");
                Profile createParameters = new Profile
                {
                    Location = "WestUs",
                    Sku      = new Sku {
                        Name = SkuName.StandardVerizon
                    },
                    Tags = new Dictionary <string, string>
                    {
                        { "key1", "value1" },
                        { "key2", "value2" }
                    }
                };
                var profile = cdnMgmtClient.Profiles.Create(resourceGroupName, profileName, createParameters);

                // Create endpoint with this name
                var endpointCreateParameters = new Endpoint
                {
                    Location       = "WestUs",
                    IsHttpAllowed  = true,
                    IsHttpsAllowed = true,
                    Origins        = new List <DeepCreatedOrigin>
                    {
                        new DeepCreatedOrigin
                        {
                            Name     = "origin1",
                            HostName = "host1.hello.com"
                        }
                    }
                };
                var endpoint = cdnMgmtClient.Endpoints.Create(resourceGroupName, profileName, endpointName, endpointCreateParameters);

                // CheckNameAvailability after endpoint was created should return false
                output = cdnMgmtClient.CheckNameAvailability(endpointName);
                Assert.False(output.NameAvailable);

                // Delete resource group
                CdnTestUtilities.DeleteResourceGroup(resourcesClient, resourceGroupName);
            }
        }
Beispiel #23
0
        protected ChaosManagementClient GetChaosManagementClient(MockContext mockContext, RecordedDelegatingHandler recordedDelegationHandler)
        {
            var subscriptionId = Environment.GetEnvironmentVariable(TestSubscriptionIdEnvironmentVariableName);

            subscriptionId      = string.IsNullOrWhiteSpace(subscriptionId) ? TestDependencies.TestConstants.DefaultTestSubscriptionId : subscriptionId;
            this.SubscriptionId = subscriptionId;

            var connnectionString = Environment.GetEnvironmentVariable(ConnectionStringEnvironmentVariableName);

            this.ConnectionString = string.IsNullOrEmpty(connnectionString) ? SanatizedSecret : connnectionString;

            var azureTestMode = Environment.GetEnvironmentVariable(AzureTestModeEnvironmentVariableName);

            this.AzureTestMode = string.IsNullOrEmpty(azureTestMode) ? DefaultAzureTestMode : azureTestMode;

            if (recordedDelegationHandler != null)
            {
                recordedDelegationHandler.IsPassThrough = true;
            }

            ChaosManagementClient chaosManagementClient;

            if (string.Equals(this.AzureTestMode, RecordAzureTestMode, StringComparison.InvariantCultureIgnoreCase))
            {
                var testEnvironment = new TestEnvironment(connectionString: this.ConnectionString);
                chaosManagementClient = mockContext.GetServiceClient <ChaosManagementClient>(
                    currentEnvironment: testEnvironment,
                    handlers: recordedDelegationHandler ?? new RecordedDelegatingHandler {
                    SubsequentStatusCodeToReturn = System.Net.HttpStatusCode.OK
                });
            }
            else
            {
                chaosManagementClient = mockContext.GetServiceClient <ChaosManagementClient>(
                    handlers: recordedDelegationHandler ?? new RecordedDelegatingHandler {
                    SubsequentStatusCodeToReturn = System.Net.HttpStatusCode.OK
                });
            }

            return(chaosManagementClient);
        }
 public static Microsoft.Azure.Management.KeyVault.KeyVaultManagementClient GetKeyVaultManagementClient(MockContext context, RecordedDelegatingHandler handler)
 {
     Microsoft.Azure.Management.KeyVault.KeyVaultManagementClient keyVaultMgmtClient;
     if (IsTestTenant)
     {
         keyVaultMgmtClient = new Microsoft.Azure.Management.KeyVault.KeyVaultManagementClient(new TokenCredentials("xyz"), GetHandler());
         keyVaultMgmtClient.SubscriptionId = testSubscription;
         keyVaultMgmtClient.BaseUri        = testUri;
     }
     else
     {
         handler.IsPassThrough = true;
         keyVaultMgmtClient    = context.GetServiceClient <Microsoft.Azure.Management.KeyVault.KeyVaultManagementClient>(handlers: handler);
     }
     return(keyVaultMgmtClient);
 }
Beispiel #25
0
        public void EndpointUpdateTest()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                // Create clients
                var cdnMgmtClient   = CdnTestUtilities.GetCdnManagementClient(context, handler1);
                var resourcesClient = CdnTestUtilities.GetResourceManagementClient(context, handler2);

                // Create resource group
                var resourceGroupName = CdnTestUtilities.CreateResourceGroup(resourcesClient);

                // Create a standard cdn profile
                string profileName = TestUtilities.GenerateName("profile");
                ProfileCreateParameters createParameters = new ProfileCreateParameters
                {
                    Location = "WestUs",
                    Sku      = new Sku {
                        Name = SkuName.StandardVerizon
                    },
                    Tags = new Dictionary <string, string>
                    {
                        { "key1", "value1" },
                        { "key2", "value2" }
                    }
                };

                var profile = cdnMgmtClient.Profiles.Create(profileName, createParameters, resourceGroupName);

                // Create a cdn endpoint with minimum requirements should succeed
                string endpointName             = TestUtilities.GenerateName("endpoint");
                var    endpointCreateParameters = new EndpointCreateParameters
                {
                    Location       = "WestUs",
                    IsHttpAllowed  = true,
                    IsHttpsAllowed = true,
                    Origins        = new List <DeepCreatedOrigin>
                    {
                        new DeepCreatedOrigin
                        {
                            Name     = "origin1",
                            HostName = "host1.hello.com"
                        }
                    }
                };

                cdnMgmtClient.Endpoints.Create(endpointName, endpointCreateParameters, profileName, resourceGroupName);

                // Update endpoint with invalid origin path should fail
                var endpointUpdateParameters = new EndpointUpdateParameters
                {
                    IsHttpAllowed    = false,
                    OriginPath       = "\\&123invalid_path/.",
                    OriginHostHeader = "www.bing.com"
                };

                Assert.ThrowsAny <ErrorResponseException>(() => {
                    cdnMgmtClient.Endpoints.Update(endpointName, endpointUpdateParameters, profileName, resourceGroupName);
                });

                // Update endpoint to enable compression without specifying compression types should fail
                endpointUpdateParameters = new EndpointUpdateParameters
                {
                    IsHttpAllowed              = false,
                    OriginPath                 = "/path/valid",
                    OriginHostHeader           = "www.bing.com",
                    IsCompressionEnabled       = true,
                    QueryStringCachingBehavior = QueryStringCachingBehavior.IgnoreQueryString
                };

                Assert.ThrowsAny <ErrorResponseException>(() => {
                    cdnMgmtClient.Endpoints.Update(endpointName, endpointUpdateParameters, profileName, resourceGroupName);
                });

                // Update endpoint with valid properties should succeed
                endpointUpdateParameters = new EndpointUpdateParameters
                {
                    IsHttpAllowed          = false,
                    OriginPath             = "/path/valid",
                    OriginHostHeader       = "www.bing.com",
                    IsCompressionEnabled   = true,
                    ContentTypesToCompress = new List <string> {
                        "text/html", "application/octet-stream"
                    },
                    QueryStringCachingBehavior = QueryStringCachingBehavior.IgnoreQueryString
                };

                var endpoint = cdnMgmtClient.Endpoints.Update(endpointName, endpointUpdateParameters, profileName, resourceGroupName);

                // Create a cdn endpoint but don't wait for creation to complete
                endpointName             = TestUtilities.GenerateName("endpoint");
                endpointCreateParameters = new EndpointCreateParameters
                {
                    Location       = "WestUs",
                    IsHttpAllowed  = true,
                    IsHttpsAllowed = true,
                    Origins        = new List <DeepCreatedOrigin>
                    {
                        new DeepCreatedOrigin
                        {
                            Name     = "origin1",
                            HostName = "host1.hello.com"
                        }
                    }
                };

                cdnMgmtClient.Endpoints.BeginCreateAsync(endpointName, endpointCreateParameters, profileName, resourceGroupName).Wait(5000);

                // Update endpoint in creating state should fail
                endpointUpdateParameters = new EndpointUpdateParameters
                {
                    IsHttpAllowed    = false,
                    OriginHostHeader = "www.bing.com"
                };

                Assert.ThrowsAny <ErrorResponseException>(() => {
                    cdnMgmtClient.Endpoints.Update(endpointName, endpointUpdateParameters, profileName, resourceGroupName);
                });

                // Delete resource group
                CdnTestUtilities.DeleteResourceGroup(resourcesClient, resourceGroupName);
            }
        }
        public void ServerEndpointAllOperationsTest()
        {
            var handler = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                IResourceManagementClient    resourcesClient             = StorageSyncManagementTestUtilities.GetResourceManagementClient(context, handler);
                IStorageSyncManagementClient storageSyncManagementClient = StorageSyncManagementTestUtilities.GetStorageSyncManagementClient(context, handler);

                // Create ResourceGroup
                string resourceGroupName = StorageSyncManagementTestUtilities.CreateResourceGroup(resourcesClient);

                // Create ServerEndpoint
                string storageSyncServiceName = TestUtilities.GenerateName("sss-sepall");
                string syncGroupName          = TestUtilities.GenerateName("sg-sepall");
                string resourceName           = TestUtilities.GenerateName("sepall");

                var storageSyncServiceParameters = StorageSyncManagementTestUtilities.GetDefaultStorageSyncServiceParameters();
                var syncGroupParameters          = StorageSyncManagementTestUtilities.GetDefaultSyncGroupParameters();
                var cloudEndpointParameters      = StorageSyncManagementTestUtilities.GetDefaultCloudEndpointParameters();

                StorageSyncService storageSyncServiceResource = storageSyncManagementClient.StorageSyncServices.Create(resourceGroupName, storageSyncServiceName, storageSyncServiceParameters);
                Assert.NotNull(storageSyncServiceResource);
                StorageSyncManagementTestUtilities.VerifyStorageSyncServiceProperties(storageSyncServiceResource, true);

                SyncGroup syncGroupResource = storageSyncManagementClient.SyncGroups.Create(resourceGroupName, storageSyncServiceResource.Name, syncGroupName, syncGroupParameters);
                Assert.NotNull(syncGroupResource);
                StorageSyncManagementTestUtilities.VerifySyncGroupProperties(syncGroupResource, true);

                CloudEndpoint cloudEndpointResource = storageSyncManagementClient.CloudEndpoints.Create(resourceGroupName, storageSyncServiceResource.Name, syncGroupResource.Name, resourceName, cloudEndpointParameters);
                Assert.NotNull(cloudEndpointResource);
                StorageSyncManagementTestUtilities.VerifyCloudEndpointProperties(cloudEndpointResource, true);

                RegisteredServer registeredServerResource = EnsureRegisteredServerResource(storageSyncManagementClient, resourceGroupName, storageSyncServiceName, syncGroupName, storageSyncServiceResource);
                Assert.NotNull(registeredServerResource);

                StorageSyncManagementTestUtilities.VerifyRegisteredServerProperties(registeredServerResource, true);

                var serverEndpointParameters       = StorageSyncManagementTestUtilities.GetDefaultServerEndpointParameters(registeredServerResource.Id);
                var serverEndpointUpdateParameters = StorageSyncManagementTestUtilities.GetDefaultServerEndpointUpdateParameters();

                // Delete Test before it exists.
                storageSyncManagementClient.ServerEndpoints.Delete(resourceGroupName, storageSyncServiceResource.Name, syncGroupResource.Name, resourceName);

                ServerEndpoint serverEndpointResource = storageSyncManagementClient.ServerEndpoints.Create(resourceGroupName, storageSyncServiceResource.Name, syncGroupResource.Name, resourceName, serverEndpointParameters);
                Assert.NotNull(serverEndpointResource);
                StorageSyncManagementTestUtilities.VerifyServerEndpointProperties(serverEndpointResource, true);

                // GET Test
                serverEndpointResource = storageSyncManagementClient.ServerEndpoints.Get(resourceGroupName, storageSyncServiceResource.Name, syncGroupResource.Name, resourceName);
                Assert.NotNull(serverEndpointResource);
                StorageSyncManagementTestUtilities.VerifyServerEndpointProperties(serverEndpointResource, true);

                // List Test
                IEnumerable <ServerEndpoint> serverEndpoints = storageSyncManagementClient.ServerEndpoints.ListBySyncGroup(resourceGroupName, storageSyncServiceResource.Name, syncGroupResource.Name);
                Assert.Single(serverEndpoints);
                Assert.NotNull(serverEndpoints.Single());
                StorageSyncManagementTestUtilities.VerifyServerEndpointProperties(serverEndpoints.Single(), true);

                // Recall Test
                RecallActionParameters             recallActionParameters             = StorageSyncManagementTestUtilities.GetDefaultRecallActionParameters();
                ServerEndpointsRecallActionHeaders serverEndpointsRecallActionHeaders = storageSyncManagementClient.ServerEndpoints.RecallAction(resourceGroupName, storageSyncServiceResource.Name, syncGroupResource.Name, resourceName, recallActionParameters);
                Assert.NotNull(serverEndpointsRecallActionHeaders);
                Assert.NotEmpty(serverEndpointsRecallActionHeaders.XMsCorrelationRequestId);
                Assert.NotEmpty(serverEndpointsRecallActionHeaders.XMsRequestId);

                // Update Test
                serverEndpointResource = storageSyncManagementClient.ServerEndpoints.Update(resourceGroupName, storageSyncServiceResource.Name, syncGroupResource.Name, resourceName, serverEndpointUpdateParameters);
                Assert.NotNull(serverEndpointResource);
                StorageSyncManagementTestUtilities.VerifyServerEndpointUpdateProperties(serverEndpointResource, true);

                // Delete Test
                storageSyncManagementClient.ServerEndpoints.Delete(resourceGroupName, storageSyncServiceResource.Name, syncGroupResource.Name, resourceName);

                storageSyncManagementClient.CloudEndpoints.Delete(resourceGroupName, storageSyncServiceResource.Name, syncGroupName, resourceName);
                storageSyncManagementClient.SyncGroups.Delete(resourceGroupName, storageSyncServiceResource.Name, syncGroupName);
                storageSyncManagementClient.RegisteredServers.Delete(resourceGroupName, storageSyncServiceResource.Name, registeredServerResource.ServerId.Trim('"'));
                storageSyncManagementClient.StorageSyncServices.Delete(resourceGroupName, storageSyncServiceResource.Name);
                StorageSyncManagementTestUtilities.RemoveResourceGroup(resourcesClient, resourceGroupName);
            }
        }
Beispiel #27
0
        public void EndpointGetListTest()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                // Create clients
                var cdnMgmtClient   = CdnTestUtilities.GetCdnManagementClient(context, handler1);
                var resourcesClient = CdnTestUtilities.GetResourceManagementClient(context, handler2);

                // Create resource group
                var resourceGroupName = CdnTestUtilities.CreateResourceGroup(resourcesClient);

                // Create a standard cdn profile
                string profileName = TestUtilities.GenerateName("profile");
                ProfileCreateParameters createParameters = new ProfileCreateParameters
                {
                    Location = "WestUs",
                    Sku      = new Sku {
                        Name = SkuName.StandardVerizon
                    },
                    Tags = new Dictionary <string, string>
                    {
                        { "key1", "value1" },
                        { "key2", "value2" }
                    }
                };

                var profile = cdnMgmtClient.Profiles.Create(profileName, createParameters, resourceGroupName);

                // List endpoints should return none
                var endpoints = cdnMgmtClient.Endpoints.ListByProfile(profileName, resourceGroupName);
                Assert.Equal(0, endpoints.Count());

                // Create a cdn endpoint should succeed
                string endpointName             = TestUtilities.GenerateName("endpoint");
                var    endpointCreateParameters = new EndpointCreateParameters
                {
                    Location       = "WestUs",
                    IsHttpAllowed  = true,
                    IsHttpsAllowed = true,
                    Origins        = new List <DeepCreatedOrigin>
                    {
                        new DeepCreatedOrigin
                        {
                            Name     = "origin1",
                            HostName = "host1.hello.com"
                        }
                    }
                };

                var endpoint = cdnMgmtClient.Endpoints.Create(endpointName, endpointCreateParameters, profileName, resourceGroupName);

                // Get endpoint returns the created endpoint
                var existingEndpoint = cdnMgmtClient.Endpoints.Get(endpointName, profileName, resourceGroupName);
                Assert.NotNull(existingEndpoint);
                Assert.Equal(existingEndpoint.ResourceState, EndpointResourceState.Running);

                // List endpoints should return one endpoint
                endpoints = cdnMgmtClient.Endpoints.ListByProfile(profileName, resourceGroupName);
                Assert.Equal(1, endpoints.Count());

                // Create a cdn endpoint and don't wait for creation to finish
                string endpointName2 = TestUtilities.GenerateName("endpoint");
                endpointCreateParameters = new EndpointCreateParameters
                {
                    Location       = "WestUs",
                    IsHttpAllowed  = true,
                    IsHttpsAllowed = true,
                    Origins        = new List <DeepCreatedOrigin>
                    {
                        new DeepCreatedOrigin
                        {
                            Name     = "origin1",
                            HostName = "host1.hello.com"
                        }
                    }
                };

                cdnMgmtClient.Endpoints.BeginCreateAsync(endpointName2, endpointCreateParameters, profileName, resourceGroupName).Wait(5000);

                // List endpoints should return two endpoints
                endpoints = cdnMgmtClient.Endpoints.ListByProfile(profileName, resourceGroupName);
                Assert.Equal(2, endpoints.Count());

                // Delete first endpoint should succeed
                cdnMgmtClient.Endpoints.DeleteIfExists(endpointName, profileName, resourceGroupName);

                // Get deleted endpoint fails
                Assert.ThrowsAny <ErrorResponseException>(() => {
                    cdnMgmtClient.Endpoints.Get(endpointName, profileName, resourceGroupName);
                });

                // List endpoints should return 1 endpoint
                endpoints = cdnMgmtClient.Endpoints.ListByProfile(profileName, resourceGroupName);
                Assert.Equal(1, endpoints.Count());

                // Wait for second endpoint to complete creation
                CdnTestUtilities.WaitIfNotInPlaybackMode();

                // Delete second endpoint but don't wait for operation to complete
                cdnMgmtClient.Endpoints.BeginDeleteIfExistsAsync(endpointName2, profileName, resourceGroupName).Wait(2000);

                // Get second endpoint returns endpoint in Deleting state
                existingEndpoint = cdnMgmtClient.Endpoints.Get(endpointName2, profileName, resourceGroupName);
                Assert.Equal(existingEndpoint.ResourceState, EndpointResourceState.Deleting);

                // Wait for second endpoint deletion to complete
                CdnTestUtilities.WaitIfNotInPlaybackMode();

                // List endpoints should return none
                endpoints = cdnMgmtClient.Endpoints.ListByProfile(profileName, resourceGroupName);
                Assert.Equal(0, endpoints.Count());

                // Delete resource group
                CdnTestUtilities.DeleteResourceGroup(resourcesClient, resourceGroupName);
            }
        }
        public void VirtualNetworkApiTest()
        {
            var handler = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (var context = UndoContext.Current)
            {
                context.Start();
                var resourcesClient = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(handler);
                var networkResourceProviderClient = NetworkManagementTestUtilities.GetNetworkResourceProviderClient(handler);

                var location = NetworkManagementTestUtilities.GetResourceLocation(resourcesClient, "Microsoft.Network/virtualNetworks");

                string resourceGroupName = TestUtilities.GenerateName("csmrg");
                resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName,
                                                              new ResourceGroup
                {
                    Location = location
                });

                string vnetName    = TestUtilities.GenerateName();
                string subnet1Name = TestUtilities.GenerateName();
                string subnet2Name = TestUtilities.GenerateName();

                var vnet = new VirtualNetwork()
                {
                    Location = location,

                    AddressSpace = new AddressSpace()
                    {
                        AddressPrefixes = new List <string>()
                        {
                            "10.0.0.0/16",
                        }
                    },
                    DhcpOptions = new DhcpOptions()
                    {
                        DnsServers = new List <string>()
                        {
                            "10.1.1.1",
                            "10.1.2.4"
                        }
                    },
                    Subnets = new List <Subnet>()
                    {
                        new Subnet()
                        {
                            Name          = subnet1Name,
                            AddressPrefix = "10.0.1.0/24",
                        },
                        new Subnet()
                        {
                            Name          = subnet2Name,
                            AddressPrefix = "10.0.2.0/24",
                        }
                    }
                };

                // Put Vnet
                var putVnetResponse = networkResourceProviderClient.VirtualNetworks.CreateOrUpdate(resourceGroupName, vnetName, vnet);
                Assert.Equal(HttpStatusCode.OK, putVnetResponse.StatusCode);
                Assert.Equal("Succeeded", putVnetResponse.Status);

                // Get Vnet
                var getVnetResponse = networkResourceProviderClient.VirtualNetworks.Get(resourceGroupName, vnetName);
                Assert.Equal(HttpStatusCode.OK, getVnetResponse.StatusCode);
                Assert.Equal(vnetName, getVnetResponse.VirtualNetwork.Name);
                Assert.Equal(Microsoft.Azure.Management.Resources.Models.ProvisioningState.Succeeded, getVnetResponse.VirtualNetwork.ProvisioningState);
                Assert.Equal("10.1.1.1", getVnetResponse.VirtualNetwork.DhcpOptions.DnsServers[0]);
                Assert.Equal("10.1.2.4", getVnetResponse.VirtualNetwork.DhcpOptions.DnsServers[1]);
                Assert.Equal("10.0.0.0/16", getVnetResponse.VirtualNetwork.AddressSpace.AddressPrefixes[0]);
                Assert.Equal(subnet1Name, getVnetResponse.VirtualNetwork.Subnets[0].Name);
                Assert.Equal(subnet2Name, getVnetResponse.VirtualNetwork.Subnets[1].Name);

                // Get all Vnets
                var getAllVnets = networkResourceProviderClient.VirtualNetworks.List(resourceGroupName);
                Assert.Equal(HttpStatusCode.OK, getAllVnets.StatusCode);
                Assert.Equal(vnetName, getAllVnets.VirtualNetworks[0].Name);
                Assert.Equal(Microsoft.Azure.Management.Resources.Models.ProvisioningState.Succeeded, getAllVnets.VirtualNetworks[0].ProvisioningState);
                Assert.Equal("10.0.0.0/16", getAllVnets.VirtualNetworks[0].AddressSpace.AddressPrefixes[0]);
                Assert.Equal(subnet1Name, getAllVnets.VirtualNetworks[0].Subnets[0].Name);
                Assert.Equal(subnet2Name, getAllVnets.VirtualNetworks[0].Subnets[1].Name);

                // Get all Vnets in a subscription
                var getAllVnetInSubscription = networkResourceProviderClient.VirtualNetworks.ListAll();
                Assert.Equal(HttpStatusCode.OK, getAllVnetInSubscription.StatusCode);
                Assert.Equal(vnetName, getAllVnetInSubscription.VirtualNetworks[0].Name);
                Assert.Equal(Microsoft.Azure.Management.Resources.Models.ProvisioningState.Succeeded, getAllVnetInSubscription.VirtualNetworks[0].ProvisioningState);
                Assert.Equal("10.0.0.0/16", getAllVnetInSubscription.VirtualNetworks[0].AddressSpace.AddressPrefixes[0]);
                Assert.Equal(subnet1Name, getAllVnetInSubscription.VirtualNetworks[0].Subnets[0].Name);
                Assert.Equal(subnet2Name, getAllVnetInSubscription.VirtualNetworks[0].Subnets[1].Name);

                // Delete Vnet
                var deleteVnetResponse = networkResourceProviderClient.VirtualNetworks.Delete(resourceGroupName, vnetName);
                Assert.Equal(HttpStatusCode.OK, deleteVnetResponse.StatusCode);

                // Get all Vnets
                getAllVnets = networkResourceProviderClient.VirtualNetworks.List(resourceGroupName);
                Assert.Equal(HttpStatusCode.OK, getAllVnets.StatusCode);
                Assert.Equal(0, getAllVnets.VirtualNetworks.Count);
            }
        }
Beispiel #29
0
        public void EndpointPurgeLoadTest()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                // Create clients
                var cdnMgmtClient   = CdnTestUtilities.GetCdnManagementClient(context, handler1);
                var resourcesClient = CdnTestUtilities.GetResourceManagementClient(context, handler2);

                // Create resource group
                var resourceGroupName = CdnTestUtilities.CreateResourceGroup(resourcesClient);

                // Create a standard cdn profile
                string profileName = TestUtilities.GenerateName("profile");
                ProfileCreateParameters createParameters = new ProfileCreateParameters
                {
                    Location = "WestUs",
                    Sku      = new Sku {
                        Name = SkuName.StandardVerizon
                    },
                    Tags = new Dictionary <string, string>
                    {
                        { "key1", "value1" },
                        { "key2", "value2" }
                    }
                };

                var profile = cdnMgmtClient.Profiles.Create(profileName, createParameters, resourceGroupName);

                // Create a cdn endpoint with minimum requirements should succeed
                string endpointName             = TestUtilities.GenerateName("endpoint");
                var    endpointCreateParameters = new EndpointCreateParameters
                {
                    Location                   = "WestUs",
                    IsHttpAllowed              = true,
                    IsHttpsAllowed             = true,
                    IsCompressionEnabled       = true,
                    OriginHostHeader           = "www.bing.com",
                    OriginPath                 = "/photos",
                    QueryStringCachingBehavior = QueryStringCachingBehavior.IgnoreQueryString,
                    ContentTypesToCompress     = new List <string> {
                        "text/html", "text/css"
                    },
                    Tags = new Dictionary <string, string> {
                        { "kay1", "value1" }
                    },
                    Origins = new List <DeepCreatedOrigin>
                    {
                        new DeepCreatedOrigin
                        {
                            Name     = TestUtilities.GenerateName("origin"),
                            HostName = "custom.hello.com"
                        }
                    }
                };

                cdnMgmtClient.Endpoints.Create(endpointName, endpointCreateParameters, profileName, resourceGroupName);

                // Purge content on endpoint should succeed
                var purgeContentPaths = new List <string>
                {
                    "/movies/*",
                    "/pictures/pic1.jpg"
                };
                cdnMgmtClient.Endpoints.PurgeContent(endpointName, profileName, resourceGroupName, purgeContentPaths);

                // Purge content on non-existing endpoint should fail
                Assert.Throws <ErrorResponseException>(() => {
                    cdnMgmtClient.Endpoints.PurgeContent("fakeEndpoint", profileName, resourceGroupName, purgeContentPaths);
                });

                // Purge content on endpoint with invalid content paths should fail
                var invalidPurgeContentPaths = new List <string> {
                    "invalidpath!"
                };
                Assert.Throws <ErrorResponseException>(() => {
                    cdnMgmtClient.Endpoints.PurgeContent(endpointName, profileName, resourceGroupName, invalidPurgeContentPaths);
                });

                // Load content on endpoint should succeed
                var loadContentPaths = new List <string>
                {
                    "/movies/amazing.mp4",
                    "/pictures/pic1.jpg"
                };
                cdnMgmtClient.Endpoints.LoadContent(endpointName, profileName, resourceGroupName, loadContentPaths);

                // Load content on non-existing endpoint should fail
                Assert.Throws <ErrorResponseException>(() => {
                    cdnMgmtClient.Endpoints.LoadContent("fakeEndpoint", profileName, resourceGroupName, loadContentPaths);
                });

                // Load content on endpoint with invalid content paths should fail
                var invalidLoadContentPaths = new List <string> {
                    "/movies/*"
                };
                Assert.Throws <ErrorResponseException>(() => {
                    cdnMgmtClient.Endpoints.LoadContent(endpointName, profileName, resourceGroupName, invalidLoadContentPaths);
                });

                // Stop the running endpoint
                cdnMgmtClient.Endpoints.Stop(endpointName, profileName, resourceGroupName);
                var endpoint = cdnMgmtClient.Endpoints.Get(endpointName, profileName, resourceGroupName);
                Assert.Equal(endpoint.ResourceState, EndpointResourceState.Stopped);

                // Purge content on stopped endpoint should fail
                Assert.Throws <ErrorResponseException>(() => {
                    cdnMgmtClient.Endpoints.PurgeContent(endpointName, profileName, resourceGroupName, purgeContentPaths);
                });

                // Load content on stopped endpoint should fail
                Assert.Throws <ErrorResponseException>(() => {
                    cdnMgmtClient.Endpoints.LoadContent(endpointName, profileName, resourceGroupName, loadContentPaths);
                });

                // Delete resource group
                CdnTestUtilities.DeleteResourceGroup(resourcesClient, resourceGroupName);
            }
        }
Beispiel #30
0
        public void GetFault()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(ExpectedResults.FaultGetResponse)
            };
            var handler = new RecordedDelegatingHandler(response)
            {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var subscriptionId = Guid.NewGuid().ToString();
            var token = new TokenCloudCredentials(subscriptionId, Constants.TokenString);
            var client = GetClient(handler, token);
            var result = client.Faults.Get(
                Constants.ResourceGroupName,
                Constants.FarmId,
                Constants.FaultId
                );

            // validate requestor
            Assert.Equal(handler.Method, HttpMethod.Get);

            var expectedUri = string.Format(
                FaultGetUriTemplate,
                Constants.BaseUri,
                subscriptionId,
                Constants.ResourceGroupName,
                Constants.FarmId,
                Constants.FaultId);
            
            Assert.Equal(handler.Uri.AbsoluteUri, expectedUri);
            CompareExpectedResult(result.Fault, true);
        }
        public void InMemory_JobCollectionPatchThrowsException()
        {
            var response = new HttpResponseMessage(HttpStatusCode.BadRequest);
            var handler  = new RecordedDelegatingHandler(response);
            var client   = this.GetSchedulerManagementClient(handler);

            Assert.Throws <ValidationException>(() => client.JobCollections.Patch(
                                                    resourceGroupName: null,
                                                    jobCollectionName: "bar",
                                                    jobCollection: new JobCollectionDefinition()
            {
                Properties = new JobCollectionProperties()
                {
                    State = JobCollectionState.Enabled,
                    Quota = new JobCollectionQuota()
                    {
                        MaxJobCount      = 30,
                        MaxJobOccurrence = 100,
                        MaxRecurrence    = new JobMaxRecurrence()
                        {
                            Frequency = RecurrenceFrequency.Month,
                            Interval  = 2,
                        }
                    }
                }
            }));

            Assert.Throws <ValidationException>(() => client.JobCollections.Patch(
                                                    resourceGroupName: "foo",
                                                    jobCollectionName: null,
                                                    jobCollection: new JobCollectionDefinition()
            {
                Properties = new JobCollectionProperties()
                {
                    State = JobCollectionState.Enabled,
                    Quota = new JobCollectionQuota()
                    {
                        MaxJobCount      = 30,
                        MaxJobOccurrence = 100,
                        MaxRecurrence    = new JobMaxRecurrence()
                        {
                            Frequency = RecurrenceFrequency.Month,
                            Interval  = 2,
                        }
                    }
                }
            }));

            Assert.Throws <ValidationException>(() => client.JobCollections.Patch(
                                                    resourceGroupName: "foo",
                                                    jobCollectionName: "bar",
                                                    jobCollection: null));

            Assert.Throws <CloudException>(() => client.JobCollections.Patch(
                                               resourceGroupName: "foo",
                                               jobCollectionName: "bar",
                                               jobCollection: new JobCollectionDefinition()
            {
                Properties = new JobCollectionProperties()
                {
                    State = JobCollectionState.Enabled,
                    Quota = new JobCollectionQuota()
                    {
                        MaxJobCount      = 30,
                        MaxJobOccurrence = 100,
                        MaxRecurrence    = new JobMaxRecurrence()
                        {
                            Frequency = RecurrenceFrequency.Month,
                            Interval  = 2,
                        }
                    }
                }
            }));
        }
Beispiel #32
0
        public void WafPolicyCreateOrUpdateTest()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                // Create clients
                var cdnMgmtClient   = CdnTestUtilities.GetCdnManagementClient(context, handler1);
                var resourcesClient = CdnTestUtilities.GetResourceManagementClient(context, handler2);

                // Create resource group
                var resourceGroupName = CdnTestUtilities.CreateResourceGroup(resourcesClient);

                // Create a minimal cdn waf policy should succeed
                var policyName = TestUtilities.GenerateName("policy");
                var policy     = cdnMgmtClient.Policies.CreateOrUpdate(resourceGroupName, policyName, new CdnWebApplicationFirewallPolicy
                {
                    Sku      = new Sku(SkuName.StandardMicrosoft),
                    Location = "Global",
                });
                //Assert.NotNull(policy.Etag);
                Assert.Equal(policyName, policy.Name);
                Assert.Equal($"/subscriptions/{resourcesClient.SubscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnwebapplicationfirewallpolicies/{policy.Name}", policy.Id);
                Assert.Equal("Global", policy.Location);
                Assert.Equal(SkuName.StandardMicrosoft, policy.Sku.Name);
                Assert.Equal(ProvisioningState.Succeeded, policy.ProvisioningState);
                Assert.Equal(PolicyResourceState.Enabled, policy.ResourceState);
                Assert.Empty(policy.EndpointLinks);
                Assert.Empty(policy.ManagedRules.ManagedRuleSets);
                Assert.Empty(policy.RateLimitRules.Rules);
                Assert.Empty(policy.CustomRules.Rules);
                Assert.Null(policy.PolicySettings.DefaultCustomBlockResponseBody);
                Assert.Null(policy.PolicySettings.DefaultCustomBlockResponseStatusCode);
                Assert.Null(policy.PolicySettings.DefaultRedirectUrl);
                Assert.Equal(PolicyEnabledState.Enabled, policy.PolicySettings.EnabledState);
                Assert.Equal(PolicyMode.Prevention, policy.PolicySettings.Mode);

                // Update policy with all parameters should succeed
                var expect = new CdnWebApplicationFirewallPolicy
                {
                    Location       = "Global",
                    Sku            = new Sku(SkuName.StandardMicrosoft),
                    PolicySettings = new PolicySettings
                    {
                        EnabledState = "Enabled",
                        Mode         = "Detection",
                        DefaultCustomBlockResponseBody       = "PGh0bWw+PGJvZHk+PGgzPkludmFsaWQgcmVxdWVzdDwvaDM+PC9ib2R5PjwvaHRtbD4=",
                        DefaultRedirectUrl                   = "https://example.com/redirected",
                        DefaultCustomBlockResponseStatusCode = 406
                    },
                    CustomRules = new CustomRuleList(new List <CustomRule>
                    {
                        new CustomRule {
                            Name            = "CustomRule1",
                            Priority        = 2,
                            EnabledState    = "Enabled",
                            Action          = "Block",
                            MatchConditions = new List <MatchCondition>
                            {
                                new MatchCondition {
                                    MatchVariable    = "QueryString",
                                    OperatorProperty = "Contains",
                                    NegateCondition  = false,
                                    MatchValue       = new List <string> {
                                        "TestTrigger123"
                                    },
                                    //Transforms = new List<String> { "Uppercase" }
                                }
                            }
                        }
                    }),
                    RateLimitRules = new RateLimitRuleList(new List <RateLimitRule>
                    {
                        new RateLimitRule {
                            Name         = "RateLimitRule1",
                            Priority     = 1,
                            EnabledState = "Disabled",
                            RateLimitDurationInMinutes = 1,
                            RateLimitThreshold         = 3,
                            MatchConditions            = new List <MatchCondition> {
                                new MatchCondition {
                                    MatchVariable    = "RemoteAddr",
                                    Selector         = null,
                                    OperatorProperty = "IPMatch",
                                    NegateCondition  = false,
                                    MatchValue       = new List <string> {
                                        "131.107.0.0/16",
                                        "167.220.0.0/16"
                                    }
                                }
                            },
                            Action = "Block"
                        },
                        new RateLimitRule {
                            Name         = "RateLimitRule2",
                            Priority     = 10,
                            EnabledState = "Enabled",
                            RateLimitDurationInMinutes = 1,
                            RateLimitThreshold         = 1,
                            MatchConditions            = new List <MatchCondition> {
                                new MatchCondition {
                                    MatchVariable    = "RequestUri",
                                    Selector         = null,
                                    OperatorProperty = "Contains",
                                    NegateCondition  = false,
                                    MatchValue       = new List <string> {
                                        "yes"
                                    }
                                }
                            },
                            Action = "Block"
                        }
                    }),
                    ManagedRules = new ManagedRuleSetList(new List <ManagedRuleSet>
                    {
                        new ManagedRuleSet {
                            RuleSetType        = "DefaultRuleSet",
                            RuleSetVersion     = "1.0",
                            RuleGroupOverrides = new List <ManagedRuleGroupOverride> {
                                new ManagedRuleGroupOverride {
                                    RuleGroupName = "JAVA",
                                    Rules         = new List <ManagedRuleOverride> {
                                        new ManagedRuleOverride {
                                            RuleId       = "944100",
                                            EnabledState = "Disabled",
                                            Action       = "Redirect"
                                        }
                                    }
                                }
                            }
                        }
                    }),
                    Tags = new Dictionary <string, string>
                    {
                        { "abc", "123" }
                    }
                };
                policy = cdnMgmtClient.Policies.CreateOrUpdate(resourceGroupName, policyName, expect);
                AssertPoliciesEqual(resourcesClient.SubscriptionId, resourceGroupName, policyName, new List <CdnEndpoint>(), expect, policy);

                // Create a complete cdn waf policy should succeed
                var policy2Name = TestUtilities.GenerateName("policy");
                var expect2     = new CdnWebApplicationFirewallPolicy
                {
                    Location       = "Global",
                    Sku            = new Sku(SkuName.StandardMicrosoft),
                    PolicySettings = new PolicySettings
                    {
                        EnabledState = "Enabled",
                        Mode         = "Detection",
                        DefaultCustomBlockResponseBody       = "PGh0bWw+PGJvZHk+PGgzPkludmFsaWQgcmVxdWVzdDwvaDM+PC9ib2R5PjwvaHRtbD4=",
                        DefaultRedirectUrl                   = "https://example.com/redirected",
                        DefaultCustomBlockResponseStatusCode = 406
                    },
                    CustomRules = new CustomRuleList(new List <CustomRule>
                    {
                        new CustomRule {
                            Name            = "CustomRule1",
                            Priority        = 2,
                            EnabledState    = "Enabled",
                            Action          = "Block",
                            MatchConditions = new List <MatchCondition>
                            {
                                new MatchCondition {
                                    MatchVariable    = "QueryString",
                                    OperatorProperty = "Contains",
                                    NegateCondition  = false,
                                    MatchValue       = new List <string> {
                                        "TestTrigger123"
                                    },
                                    //Transforms = new List<String> { "Uppercase" }
                                }
                            }
                        }
                    }),
                    RateLimitRules = new RateLimitRuleList(new List <RateLimitRule>
                    {
                        new RateLimitRule {
                            Name         = "RateLimitRule1",
                            Priority     = 1,
                            EnabledState = "Disabled",
                            RateLimitDurationInMinutes = 1,
                            RateLimitThreshold         = 3,
                            MatchConditions            = new List <MatchCondition> {
                                new MatchCondition {
                                    MatchVariable    = "RemoteAddr",
                                    Selector         = null,
                                    OperatorProperty = "IPMatch",
                                    NegateCondition  = false,
                                    MatchValue       = new List <string> {
                                        "131.107.0.0/16",
                                        "167.220.0.0/16"
                                    }
                                }
                            },
                            Action = "Block"
                        },
                        new RateLimitRule {
                            Name         = "RateLimitRule2",
                            Priority     = 10,
                            EnabledState = "Enabled",
                            RateLimitDurationInMinutes = 1,
                            RateLimitThreshold         = 1,
                            MatchConditions            = new List <MatchCondition> {
                                new MatchCondition {
                                    MatchVariable    = "RequestUri",
                                    Selector         = null,
                                    OperatorProperty = "Contains",
                                    NegateCondition  = false,
                                    MatchValue       = new List <string> {
                                        "yes"
                                    }
                                }
                            },
                            Action = "Block"
                        }
                    }),
                    ManagedRules = new ManagedRuleSetList(new List <ManagedRuleSet>
                    {
                        new ManagedRuleSet {
                            RuleSetType        = "DefaultRuleSet",
                            RuleSetVersion     = "1.0",
                            RuleGroupOverrides = new List <ManagedRuleGroupOverride> {
                                new ManagedRuleGroupOverride {
                                    RuleGroupName = "JAVA",
                                    Rules         = new List <ManagedRuleOverride> {
                                        new ManagedRuleOverride {
                                            RuleId       = "944100",
                                            EnabledState = "Disabled",
                                            Action       = "Redirect"
                                        }
                                    }
                                }
                            }
                        }
                    }),
                    Tags = new Dictionary <string, string>
                    {
                        { "abc", "123" }
                    }
                };
                var policy2 = cdnMgmtClient.Policies.CreateOrUpdate(resourceGroupName, policy2Name, expect2);
                AssertPoliciesEqual(resourcesClient.SubscriptionId, resourceGroupName, policy2Name, new List <CdnEndpoint>(), expect2, policy2);
            }
        }
        public void GetWebSiteMetrics()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(HttpPayload.GetWebSiteMetricsPerInstancePerMinute)
            };

            var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };

            var client = GetWebSiteManagementClient(handler);

            var result = client.WebSites.GetHistoricalUsageMetrics("space1", "site1", new WebSiteGetHistoricalUsageMetricsParameters()
            {
                TimeGrain = "PT1M",
                StartTime = DateTime.UtcNow.AddHours(-3),
                EndTime = DateTime.UtcNow,
                IncludeInstanceBreakdown = true,
            });

            // Validate headers 
            Assert.Equal(HttpMethod.Get, handler.Method);


            // Validate response 
            Assert.NotNull(result);
            Assert.NotNull(result.UsageMetrics);
            Assert.NotNull(result.UsageMetrics[0]);
            Assert.NotNull(result.UsageMetrics[0].Data);
            Assert.Equal("CpuTime", result.UsageMetrics[0].Data.Name);
            Assert.NotNull(result.UsageMetrics[0].Data.Values);
            Assert.Equal("PT1M", result.UsageMetrics[0].Data.TimeGrain);
            Assert.Equal("15", result.UsageMetrics[0].Data.Values[0].Total);
            Assert.Null(result.UsageMetrics[0].Data.Values[0].InstanceName);
            Assert.Equal("Total", result.UsageMetrics[0].Data.PrimaryAggregationType);

            // check instance
            Assert.NotNull(result.UsageMetrics[1]);
            Assert.NotNull(result.UsageMetrics[1].Data);
            Assert.Equal("CpuTime", result.UsageMetrics[1].Data.Name);
            Assert.NotNull(result.UsageMetrics[1].Data.Values);
            Assert.Equal("PT1M", result.UsageMetrics[1].Data.TimeGrain);
            Assert.Equal("15", result.UsageMetrics[1].Data.Values[0].Total);
            Assert.Equal("Instance", result.UsageMetrics[1].Data.PrimaryAggregationType);
            Assert.Equal("RD00155D4409B6", result.UsageMetrics[1].Data.Values[0].InstanceName);
        }
Beispiel #34
0
        public void WafPolicyLinkTest()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                // Create clients
                var cdnMgmtClient   = CdnTestUtilities.GetCdnManagementClient(context, handler1);
                var resourcesClient = CdnTestUtilities.GetResourceManagementClient(context, handler2);

                // Create resource group
                var resourceGroupName = CdnTestUtilities.CreateResourceGroup(resourcesClient);

                // Create a cdn waf policy
                var policyName = TestUtilities.GenerateName("policy");
                var policy     = cdnMgmtClient.Policies.CreateOrUpdate(resourceGroupName, policyName, new CdnWebApplicationFirewallPolicy
                {
                    Location       = "Global",
                    Sku            = new Sku("Standard_Microsoft"),
                    PolicySettings = new PolicySettings
                    {
                        EnabledState = "Enabled",
                        Mode         = "Detection",
                        DefaultCustomBlockResponseBody       = "PGh0bWw+PGJvZHk+PGgzPkludmFsaWQgcmVxdWVzdDwvaDM+PC9ib2R5PjwvaHRtbD4=",
                        DefaultRedirectUrl                   = "https://example.com/redirected",
                        DefaultCustomBlockResponseStatusCode = 406
                    },
                    CustomRules = new CustomRuleList(new List <CustomRule>
                    {
                        new CustomRule {
                            Name            = "CustomRule1",
                            Priority        = 2,
                            EnabledState    = "Enabled",
                            Action          = "Block",
                            MatchConditions = new List <MatchCondition>
                            {
                                new MatchCondition {
                                    MatchVariable    = "QueryString",
                                    OperatorProperty = "Contains",
                                    NegateCondition  = false,
                                    MatchValue       = new List <string> {
                                        "TestTrigger123"
                                    },
                                    //Transforms = new List<String> { "Uppercase" }
                                }
                            }
                        }
                    }),
                    RateLimitRules = new RateLimitRuleList(new List <RateLimitRule>
                    {
                        new RateLimitRule {
                            Name         = "RateLimitRule1",
                            Priority     = 1,
                            EnabledState = "Disabled",
                            RateLimitDurationInMinutes = 1,
                            RateLimitThreshold         = 3,
                            MatchConditions            = new List <MatchCondition> {
                                new MatchCondition {
                                    MatchVariable    = "RemoteAddr",
                                    Selector         = null,
                                    OperatorProperty = "IPMatch",
                                    NegateCondition  = false,
                                    MatchValue       = new List <string> {
                                        "131.107.0.0/16",
                                        "167.220.0.0/16"
                                    }
                                }
                            },
                            Action = "Block"
                        },
                        new RateLimitRule {
                            Name         = "RateLimitRule2",
                            Priority     = 10,
                            EnabledState = "Enabled",
                            RateLimitDurationInMinutes = 1,
                            RateLimitThreshold         = 1,
                            MatchConditions            = new List <MatchCondition> {
                                new MatchCondition {
                                    MatchVariable    = "RequestUri",
                                    Selector         = null,
                                    OperatorProperty = "Contains",
                                    NegateCondition  = false,
                                    MatchValue       = new List <string> {
                                        "yes"
                                    }
                                }
                            },
                            Action = "Block"
                        }
                    }),
                    ManagedRules = new ManagedRuleSetList(new List <ManagedRuleSet>
                    {
                        new ManagedRuleSet {
                            RuleSetType        = "DefaultRuleSet",
                            RuleSetVersion     = "1.0",
                            RuleGroupOverrides = new List <ManagedRuleGroupOverride> {
                                new ManagedRuleGroupOverride {
                                    RuleGroupName = "JAVA",
                                    Rules         = new List <ManagedRuleOverride> {
                                        new ManagedRuleOverride {
                                            RuleId       = "944100",
                                            EnabledState = "Disabled",
                                            Action       = "Redirect"
                                        }
                                    }
                                }
                            }
                        }
                    }),
                    Tags = new Dictionary <string, string>
                    {
                        { "abc", "123" }
                    }
                });

                // Create a standard Microsoft cdn profile
                string  profileName      = TestUtilities.GenerateName("profile");
                Profile createParameters = new Profile
                {
                    Location = "WestUs",
                    Sku      = new Sku {
                        Name = SkuName.StandardMicrosoft
                    },
                    Tags = new Dictionary <string, string>
                    {
                        { "key1", "value1" },
                        { "key2", "value2" }
                    }
                };

                // Wait for policy to complete creation
                CdnTestUtilities.WaitIfNotInPlaybackMode();

                var profile = cdnMgmtClient.Profiles.Create(resourceGroupName, profileName, createParameters);

                // Create a cdn endpoint with waf link should succeed
                string endpointName = TestUtilities.GenerateName("endpoint");
                var    endpoint     = cdnMgmtClient.Endpoints.Create(resourceGroupName, profileName, endpointName, new Endpoint
                {
                    Location       = "WestUs",
                    IsHttpAllowed  = true,
                    IsHttpsAllowed = true,
                    WebApplicationFirewallPolicyLink = new EndpointPropertiesUpdateParametersWebApplicationFirewallPolicyLink(policy.Id.ToString()),
                    Origins = new List <DeepCreatedOrigin>
                    {
                        new DeepCreatedOrigin
                        {
                            Name     = "origin1",
                            HostName = "host1.hello.com"
                        }
                    }
                });

                // Verify linked endpoint
                var existingEndpoint = cdnMgmtClient.Endpoints.Get(resourceGroupName, profileName, endpointName);
                Assert.Equal(policy.Id.ToString(), existingEndpoint.WebApplicationFirewallPolicyLink.Id);

                // Verify policy shows linked endpoint
                var existingPolicy = cdnMgmtClient.Policies.Get(resourceGroupName, policyName);
                Assert.Single(existingPolicy.EndpointLinks);
                Assert.Contains(endpoint.Id, existingPolicy.EndpointLinks.Select(l => l.Id));

                // Create second endpoint linked to the same profile should succeed
                var endpoint2Name = TestUtilities.GenerateName("endpoint");
                var endpoint2     = cdnMgmtClient.Endpoints.Create(resourceGroupName, profileName, endpoint2Name, new Endpoint
                {
                    Location       = "EastUs",
                    IsHttpAllowed  = false,
                    IsHttpsAllowed = true,
                    WebApplicationFirewallPolicyLink = new EndpointPropertiesUpdateParametersWebApplicationFirewallPolicyLink(policy.Id.ToString()),
                    Origins = new List <DeepCreatedOrigin>
                    {
                        new DeepCreatedOrigin
                        {
                            Name     = "origin2",
                            HostName = "host2.hello.com"
                        }
                    }
                });

                // Verify second linked endpoint
                var existingEndpoint2 = cdnMgmtClient.Endpoints.Get(resourceGroupName, profileName, endpoint2Name);
                Assert.Equal(policy.Id.ToString(), existingEndpoint2.WebApplicationFirewallPolicyLink.Id);

                // Verify policy shows both linked endpoints.
                existingPolicy = cdnMgmtClient.Policies.Get(resourceGroupName, policyName);
                Assert.Equal(2, existingPolicy.EndpointLinks.Count());
                Assert.Contains(endpoint.Id, existingPolicy.EndpointLinks.Select(l => l.Id));
                Assert.Contains(endpoint2.Id, existingPolicy.EndpointLinks.Select(l => l.Id));

                // Unlink endpoint should succeed.
                endpoint.WebApplicationFirewallPolicyLink = null;
                endpoint = cdnMgmtClient.Endpoints.Create(resourceGroupName, profileName, endpointName, endpoint);
                Assert.Null(endpoint.WebApplicationFirewallPolicyLink);

                // Verify policy shows only second linked endpoint.
                existingPolicy = cdnMgmtClient.Policies.Get(resourceGroupName, policyName);
                Assert.Single(existingPolicy.EndpointLinks);
                Assert.Contains(endpoint2.Id, existingPolicy.EndpointLinks.Select(l => l.Id));

                // Unlink second endpoint should succeed
                endpoint2.WebApplicationFirewallPolicyLink = null;
                endpoint2 = cdnMgmtClient.Endpoints.Create(resourceGroupName, profileName, endpoint2Name, endpoint2);
                Assert.Null(endpoint2.WebApplicationFirewallPolicyLink);

                // Verify policy shows no linked endpoints
                existingPolicy = cdnMgmtClient.Policies.Get(resourceGroupName, policyName);
                Assert.Empty(existingPolicy.EndpointLinks);

                // Delete resource group
                CdnTestUtilities.DeleteResourceGroup(resourcesClient, resourceGroupName);
            }
        }
        public void InMemory_JobCollectionListBySubscription()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(@"{
	                'value': [{
		                'id': '/subscriptions/12345/providers/Microsoft.Scheduler/jobCollections/jc1',
		                'type': 'Microsoft.Scheduler/jobCollections',
		                'name': 'jc1',
		                'location': 'North Central US',
		                'properties': {
			                'sku': {
				                'name': 'standard'
			                },
			                'state': 'Enabled',
			                'quota': {
				                'maxJobCount': 5,
                                'maxJobOccurrence': 200,
				                'maxRecurrence': {
					                'frequency': 'minute',
					                'interval': 10
				                }
			                }
		                }
	                },
	                {
		                'id': '/subscriptions/12345/providers/Microsoft.Scheduler/jobCollections/jc2',
		                'type': 'Microsoft.Scheduler/jobCollections',
		                'name': 'jc2',
		                'location': 'South Central US',
		                'properties': {
			                'sku': {
				                'name': 'P20Premium'
			                },
			                'state': 'Enabled',
			                'quota': {
				                'maxJobCount': 10,
                                'maxJobOccurrence': 100,
				                'maxRecurrence': {
					                'frequency': 'hour',
					                'interval': 5
				                }
			                }
		                }
	                }],
	                'nextLink': null
                }")
            };

            response.Headers.Add("x-ms-request-id", "1");
            var handler = new RecordedDelegatingHandler(response)
            {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var client = this.GetSchedulerManagementClient(handler);

            var result = client.JobCollections.ListBySubscription();

            // Validate headers
            Assert.Equal(HttpMethod.Get, handler.Method);
            Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));

            Assert.Null(result.NextPageLink);

            var jc1 = result.Where(jc => string.Compare(jc.Id, "/subscriptions/12345/providers/Microsoft.Scheduler/jobCollections/jc1") == 0).FirstOrDefault();

            Assert.NotNull(jc1);
            Assert.Equal("North Central US", jc1.Location);
            Assert.Equal("Microsoft.Scheduler/jobCollections", jc1.Type);
            Assert.Equal("jc1", jc1.Name);
            Assert.Equal(SkuDefinition.Standard, jc1.Properties.Sku.Name);
            Assert.Equal(JobCollectionState.Enabled, jc1.Properties.State);
            Assert.Equal(5, jc1.Properties.Quota.MaxJobCount);
            Assert.Equal(200, jc1.Properties.Quota.MaxJobOccurrence);
            Assert.Equal(RecurrenceFrequency.Minute, jc1.Properties.Quota.MaxRecurrence.Frequency);
            Assert.Equal(10, jc1.Properties.Quota.MaxRecurrence.Interval);

            var jc2 = result.Where(jc => string.Compare(jc.Id, "/subscriptions/12345/providers/Microsoft.Scheduler/jobCollections/jc2") == 0).FirstOrDefault();

            Assert.NotNull(jc2);
            Assert.Equal("South Central US", jc2.Location);
            Assert.Equal("Microsoft.Scheduler/jobCollections", jc2.Type);
            Assert.Equal("jc2", jc2.Name);
            Assert.Equal(SkuDefinition.P20Premium, jc2.Properties.Sku.Name);
            Assert.Equal(JobCollectionState.Enabled, jc2.Properties.State);
            Assert.Equal(10, jc2.Properties.Quota.MaxJobCount);
            Assert.Equal(100, jc2.Properties.Quota.MaxJobOccurrence);
            Assert.Equal(RecurrenceFrequency.Hour, jc2.Properties.Quota.MaxRecurrence.Frequency);
            Assert.Equal(5, jc2.Properties.Quota.MaxRecurrence.Interval);
        }
Beispiel #36
0
        public void VirtualNetworkCheckIpAddressAvailabilityTest()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient         = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(context, handler1);
                var networkManagementClient = NetworkManagementTestUtilities.GetNetworkManagementClientWithHandler(context, handler2);

                var location = NetworkManagementTestUtilities.GetResourceLocation(resourcesClient, "Microsoft.Network/virtualNetworks");

                string resourceGroupName = TestUtilities.GenerateName("csmrg");
                resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName,
                                                              new ResourceGroup
                {
                    Location = location
                });

                string vnetName   = TestUtilities.GenerateName();
                string subnetName = TestUtilities.GenerateName();

                var vnet = new VirtualNetwork()
                {
                    Location = location,

                    AddressSpace = new AddressSpace()
                    {
                        AddressPrefixes = new List <string>()
                        {
                            "10.0.0.0/16",
                        }
                    },
                    DhcpOptions = new DhcpOptions()
                    {
                        DnsServers = new List <string>()
                        {
                            "10.1.1.1",
                            "10.1.2.4"
                        }
                    },
                    Subnets = new List <Subnet>()
                    {
                        new Subnet()
                        {
                            Name          = subnetName,
                            AddressPrefix = "10.0.1.0/24",
                        },
                    }
                };

                // Put Vnet
                var putVnetResponse = networkManagementClient.VirtualNetworks.CreateOrUpdate(resourceGroupName, vnetName, vnet);
                Assert.Equal("Succeeded", putVnetResponse.ProvisioningState);

                var getSubnetResponse = networkManagementClient.Subnets.Get(resourceGroupName, vnetName, subnetName);

                // Create Nic
                string nicName      = TestUtilities.GenerateName();
                string ipConfigName = TestUtilities.GenerateName();

                var nicParameters = new NetworkInterface()
                {
                    Location = location,
                    Tags     = new Dictionary <string, string>()
                    {
                        { "key", "value" }
                    },
                    IpConfigurations = new List <NetworkInterfaceIPConfiguration>()
                    {
                        new NetworkInterfaceIPConfiguration()
                        {
                            Name = ipConfigName,
                            PrivateIPAllocationMethod = IPAllocationMethod.Static,
                            PrivateIPAddress          = "10.0.1.9",
                            Subnet = new Subnet()
                            {
                                Id = getSubnetResponse.Id
                            }
                        }
                    }
                };

                var putNicResponse = networkManagementClient.NetworkInterfaces.CreateOrUpdate(resourceGroupName, nicName, nicParameters);

                // Check Ip Address availability API
                var responseAvailable = networkManagementClient.VirtualNetworks.CheckIPAddressAvailability(resourceGroupName, vnetName, "10.0.1.10");

                Assert.True(responseAvailable.Available);
                Assert.Null(responseAvailable.AvailableIPAddresses);

                var responseTaken = networkManagementClient.VirtualNetworks.CheckIPAddressAvailability(resourceGroupName, vnetName, "10.0.1.9");

                Assert.False(responseTaken.Available);
                Assert.Equal(5, responseTaken.AvailableIPAddresses.Count);

                networkManagementClient.NetworkInterfaces.Delete(resourceGroupName, nicName);
                networkManagementClient.VirtualNetworks.Delete(resourceGroupName, vnetName);
            }
        }
        public void RestoreSiteDiscover()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(HttpPayload.RestoreSiteDiscover)
            };

            var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };

            var client = GetWebSiteManagementClient(handler);

            RestoreRequest req = new RestoreRequest()
            {
                BlobName = "abc.zip",
                StorageAccountUrl = "https://someuser.blob.core.windows.net/backup/?sv=2012-02-12",
                Overwrite = false
            };

            string newSiteName = "site1";
            var discoverResponse = client.WebSites.Discover("space1", newSiteName, req);

            Assert.Equal(1, discoverResponse.Databases.Count);
            Assert.Equal("MySql", discoverResponse.Databases[0].DatabaseType);
            Assert.Equal("db1", discoverResponse.Databases[0].Name);
            Assert.True(string.IsNullOrEmpty(discoverResponse.Databases[0].ConnectionString));
            Assert.True(string.IsNullOrEmpty(discoverResponse.Databases[0].ConnectionStringName));

            Assert.Equal("abc.zip", discoverResponse.BlobName);
            Assert.Equal(false, discoverResponse.Overwrite);
            Assert.True(discoverResponse.StorageAccountUrl.StartsWith("https://someuser.blob"));
        }
        public void ListOutboundNetworkDependenciesEndpointsValidateResponse()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(@"{
                    'value': [
                    {
                      'category': 'Azure Batch',
                      'endpoints': [
                        {
                          'domainName': 'japaneast.batch.azure.com',
                          'description': 'Applicable to all Azure Batch pools.',
                          'endpointDetails': [
                            {
                              'port': 443
                            }
                          ]
                        }
                      ]
                    },
                    {
                      'category': 'Azure Storage',
                      'endpoints': [
                        {
                          'domainName': 'sampleautostorageaccountname.blob.core.windows.net',
                          'description': 'AutoStorage endpoint for this Batch account. Applicable to all Azure Batch pools under this account.',
                          'endpointDetails': [
                            {
                              'port': 443
                            }
                          ]
                        }
                      ]
                    }
                  ]
                }")
            };

            response.Headers.Add("x-ms-request-id", "1");
            var handler = new RecordedDelegatingHandler(response)
            {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var client = BatchTestHelper.GetBatchManagementClient(handler);

            IPage <OutboundEnvironmentEndpoint> result = client.BatchAccount.ListOutboundNetworkDependenciesEndpoints("default-azurebatch-japaneast", "sampleacct");

            Assert.Equal(2, result.Count());

            OutboundEnvironmentEndpoint endpoint = result.ElementAt(0);

            Assert.Equal("Azure Batch", endpoint.Category);
            Assert.Equal("japaneast.batch.azure.com", endpoint.Endpoints[0].DomainName);
            Assert.Equal("Applicable to all Azure Batch pools.", endpoint.Endpoints[0].Description);
            Assert.Equal(443, endpoint.Endpoints[0].EndpointDetails[0].Port);

            endpoint = result.ElementAt(1);
            Assert.Equal("Azure Storage", endpoint.Category);
            Assert.Equal("sampleautostorageaccountname.blob.core.windows.net", endpoint.Endpoints[0].DomainName);
            Assert.Equal("AutoStorage endpoint for this Batch account. Applicable to all Azure Batch pools under this account.", endpoint.Endpoints[0].Description);
            Assert.Equal(443, endpoint.Endpoints[0].EndpointDetails[0].Port);
        }
        public void NetworkExperimentCRUDTest()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                // Create clients
                var frontDoorMgmtClient = FrontDoorTestUtilities.GetFrontDoorManagementClient(context, handler1);
                var resourcesClient     = FrontDoorTestUtilities.GetResourceManagementClient(context, handler2);

                // Get subscription id
                string subid = frontDoorMgmtClient.SubscriptionId;

                // Create resource group
                var resourceGroupName = FrontDoorTestUtilities.CreateResourceGroup(resourcesClient);

                // Create profile and experiment names
                string profileName    = TestUtilities.GenerateName("networkExperimentProfile");
                string experimentName = TestUtilities.GenerateName("experiment");

                Profile profile = new Profile(
                    enabledState: "Enabled",
                    location: "EastUS",
                    tags: new Dictionary <string, string>
                {
                    { "key1", "value1" },
                    { "key2", "value2" }
                });

                Experiment experiment = new Experiment(
                    endpointA: new Endpoint(
                        endpointProperty: "www.bing.com",
                        name: "bing"),
                    endpointB: new Endpoint(
                        endpointProperty: "www.constoso.com",
                        name: "contoso"));

                var createdProfile = frontDoorMgmtClient.NetworkExperimentProfiles.CreateOrUpdate(profileName, resourceGroupName, profile);

                // validate that correct profile is created
                VerifyProfile(profile, createdProfile);

                // Retrieve profile
                var retrievedProfile = frontDoorMgmtClient.NetworkExperimentProfiles.Get(resourceGroupName, profileName);

                // validate that correct profile is retrieved
                VerifyProfile(profile, retrievedProfile);

                // update profile
                retrievedProfile.Tags = new Dictionary <string, string>
                {
                    { "key3", "value3" },
                    { "key4", "value4" }
                };

                var updatedProfile = frontDoorMgmtClient.NetworkExperimentProfiles.CreateOrUpdate(profileName, resourceGroupName, retrievedProfile);

                // validate that profile is correctly updated
                VerifyProfile(retrievedProfile, updatedProfile);

                // add experiment to profile
                var createdExperiment = frontDoorMgmtClient.Experiments.CreateOrUpdate(resourceGroupName, profileName, experimentName, experiment);

                // validate experiment
                VerifyExperiment(experiment, createdExperiment);

                // get experiment
                var retrievedExperiment = frontDoorMgmtClient.Experiments.Get(resourceGroupName, profileName, experimentName);

                // validate experiment
                VerifyExperiment(experiment, retrievedExperiment);

                // delete experiment
                frontDoorMgmtClient.Experiments.Delete(resourceGroupName, profileName, experimentName);

                // verify experiment is deleted
                Assert.ThrowsAny <ErrorResponseException>(() =>
                {
                    frontDoorMgmtClient.Experiments.Get(resourceGroupName, profileName, experimentName);
                });

                // delete profile
                frontDoorMgmtClient.NetworkExperimentProfiles.Delete(resourceGroupName, profileName);

                // Verify that profile is deleted
                Assert.ThrowsAny <ErrorResponseException>(() =>
                {
                    frontDoorMgmtClient.NetworkExperimentProfiles.Get(resourceGroupName, profileName);
                });

                FrontDoorTestUtilities.DeleteResourceGroup(resourcesClient, resourceGroupName);
            }
        }
        public void FlowLogApiTest()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler3 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler4 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler5 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var resourcesClient                     = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(context, handler1);
                var networkManagementClient             = NetworkManagementTestUtilities.GetNetworkManagementClientWithHandler(context, handler2);
                var computeManagementClient             = NetworkManagementTestUtilities.GetComputeManagementClientWithHandler(context, handler3);
                var storageManagementClient             = NetworkManagementTestUtilities.GetStorageManagementClientWithHandler(context, handler4);
                var operationalInsightsManagementClient = NetworkManagementTestUtilities.GetOperationalInsightsManagementClientWithHandler(context, handler5);

                string location          = "eastus2euap";
                string workspaceLocation = "East US";

                string resourceGroupName = TestUtilities.GenerateName();
                resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName,
                                                              new ResourceGroup
                {
                    Location = location
                });

                //Create network security group
                string networkSecurityGroupName = TestUtilities.GenerateName();

                var networkSecurityGroup = new NetworkSecurityGroup()
                {
                    Location = location,
                };

                // Put Nsg
                var putNsgResponse = networkManagementClient.NetworkSecurityGroups.CreateOrUpdate(resourceGroupName, networkSecurityGroupName, networkSecurityGroup);

                // Get NSG
                var getNsgResponse = networkManagementClient.NetworkSecurityGroups.Get(resourceGroupName, networkSecurityGroupName);

                string         networkWatcherName = TestUtilities.GenerateName();
                NetworkWatcher properties         = new NetworkWatcher();
                properties.Location = location;

                //Create network Watcher
                var createNetworkWatcher = networkManagementClient.NetworkWatchers.CreateOrUpdate(resourceGroupName, networkWatcherName, properties);

                //Create storage
                string storageName = TestUtilities.GenerateName();

                var storageParameters = new StorageAccountCreateParameters()
                {
                    Location = location,
                    Kind     = Kind.Storage,
                    Sku      = new Sku
                    {
                        Name = SkuName.StandardLRS
                    }
                };

                var storageAccount = storageManagementClient.StorageAccounts.Create(resourceGroupName, storageName, storageParameters);

                //create workspace
                string workspaceName = TestUtilities.GenerateName();

                var workSpaceParameters = new Workspace()
                {
                    Location = workspaceLocation
                };

                var workspace = operationalInsightsManagementClient.Workspaces.CreateOrUpdate(resourceGroupName, workspaceName, workSpaceParameters);

                FlowLogInformation configParameters = new FlowLogInformation()
                {
                    TargetResourceId = getNsgResponse.Id,
                    Enabled          = true,
                    StorageId        = storageAccount.Id,
                    RetentionPolicy  = new RetentionPolicyParameters
                    {
                        Days    = 5,
                        Enabled = true
                    },
                    FlowAnalyticsConfiguration = new TrafficAnalyticsProperties()
                    {
                        NetworkWatcherFlowAnalyticsConfiguration = new TrafficAnalyticsConfigurationProperties()
                        {
                            Enabled             = true,
                            WorkspaceId         = workspace.CustomerId,
                            WorkspaceRegion     = workspace.Location,
                            WorkspaceResourceId = workspace.Id
                        }
                    }
                };


                //configure flowlog and TA
                var configureFlowLog1 = networkManagementClient.NetworkWatchers.SetFlowLogConfiguration(resourceGroupName, networkWatcherName, configParameters);

                FlowLogStatusParameters flowLogParameters = new FlowLogStatusParameters()
                {
                    TargetResourceId = getNsgResponse.Id
                };

                var queryFlowLogStatus1 = networkManagementClient.NetworkWatchers.GetFlowLogStatus(resourceGroupName, networkWatcherName, flowLogParameters);

                //check both flowlog and TA config and enabled status
                Assert.Equal(queryFlowLogStatus1.TargetResourceId, configParameters.TargetResourceId);
                Assert.True(queryFlowLogStatus1.Enabled);
                Assert.Equal(queryFlowLogStatus1.StorageId, configParameters.StorageId);
                Assert.Equal(queryFlowLogStatus1.RetentionPolicy.Days, configParameters.RetentionPolicy.Days);
                Assert.Equal(queryFlowLogStatus1.RetentionPolicy.Enabled, configParameters.RetentionPolicy.Enabled);
                Assert.True(queryFlowLogStatus1.FlowAnalyticsConfiguration.NetworkWatcherFlowAnalyticsConfiguration.Enabled);
                Assert.Equal(queryFlowLogStatus1.FlowAnalyticsConfiguration.NetworkWatcherFlowAnalyticsConfiguration.WorkspaceId,
                             configParameters.FlowAnalyticsConfiguration.NetworkWatcherFlowAnalyticsConfiguration.WorkspaceId);
                Assert.Equal(queryFlowLogStatus1.FlowAnalyticsConfiguration.NetworkWatcherFlowAnalyticsConfiguration.WorkspaceRegion,
                             configParameters.FlowAnalyticsConfiguration.NetworkWatcherFlowAnalyticsConfiguration.WorkspaceRegion);
                Assert.Equal(queryFlowLogStatus1.FlowAnalyticsConfiguration.NetworkWatcherFlowAnalyticsConfiguration.WorkspaceResourceId,
                             configParameters.FlowAnalyticsConfiguration.NetworkWatcherFlowAnalyticsConfiguration.WorkspaceResourceId);

                //disable TA
                configParameters.FlowAnalyticsConfiguration.NetworkWatcherFlowAnalyticsConfiguration.Enabled = false;
                var configureFlowLog2   = networkManagementClient.NetworkWatchers.SetFlowLogConfiguration(resourceGroupName, networkWatcherName, configParameters);
                var queryFlowLogStatus2 = networkManagementClient.NetworkWatchers.GetFlowLogStatus(resourceGroupName, networkWatcherName, flowLogParameters);

                //check TA disabled and ensure flowlog config is unchanged
                Assert.Equal(queryFlowLogStatus2.TargetResourceId, configParameters.TargetResourceId);
                Assert.True(queryFlowLogStatus2.Enabled);
                Assert.Equal(queryFlowLogStatus2.StorageId, configParameters.StorageId);
                Assert.Equal(queryFlowLogStatus2.RetentionPolicy.Days, configParameters.RetentionPolicy.Days);
                Assert.Equal(queryFlowLogStatus2.RetentionPolicy.Enabled, configParameters.RetentionPolicy.Enabled);
                Assert.False(queryFlowLogStatus2.FlowAnalyticsConfiguration.NetworkWatcherFlowAnalyticsConfiguration.Enabled);

                //disable flowlog (and TA)
                configParameters.Enabled = false;
                var configureFlowLog3   = networkManagementClient.NetworkWatchers.SetFlowLogConfiguration(resourceGroupName, networkWatcherName, configParameters);
                var queryFlowLogStatus3 = networkManagementClient.NetworkWatchers.GetFlowLogStatus(resourceGroupName, networkWatcherName, flowLogParameters);

                //check both flowlog and TA disabled
                Assert.False(queryFlowLogStatus3.Enabled);
                Assert.False(queryFlowLogStatus3.FlowAnalyticsConfiguration.NetworkWatcherFlowAnalyticsConfiguration.Enabled);
            }
        }
Beispiel #41
0
        public void DismissFaults()
        {
            var handler = new RecordedDelegatingHandler
            {
                StatusCodeToReturn = HttpStatusCode.NoContent
            };

            var subscriptionId = Guid.NewGuid().ToString();

            var token = new TokenCloudCredentials(subscriptionId, Constants.TokenString);
            var client = GetClient(handler, token);

            client.Faults.Dismiss(
                Constants.ResourceGroupName,
                Constants.FarmId,
                Constants.FaultId
                );

            Assert.Equal(handler.Method, HttpMethod.Post);

            var expectedUri = string.Format(
                FaultDismissUriTemplate,
                Constants.BaseUri,
                subscriptionId,
                Constants.ResourceGroupName,
                Constants.FarmId,
                Constants.FaultId);

            Assert.Equal(handler.Uri.AbsoluteUri, expectedUri);
        }
 public AlertsTests() : base()
 {
     handler = new RecordedDelegatingHandler {
         SubsequentStatusCodeToReturn = HttpStatusCode.OK
     };
 }
        public void AccountListValidateMessage()
        {
            var allSubsResponseEmptyNextLink = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(@"{
                            'value':
                            [
                                {
                                    'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctname',
                                    'type' : 'Microsoft.Batch/batchAccounts',
                                    'name': 'acctname',
                                    'location': 'West US',
                                    'properties': {
                                        'accountEndpoint' : 'http://acctname.batch.core.windows.net/',
                                        'provisioningState' : 'Succeeded',
                                        'dedicatedCoreQuota' : '20',
                                        'lowPriorityCoreQuota' : '50',
                                        'poolQuota' : '100',
                                        'activeJobAndJobScheduleQuota' : '200'
                                    },
                                    'tags' : {
                                        'tag1' : 'value for tag1',
                                        'tag2' : 'value for tag2',
                                    }
                                },
                                {
                                    'id': '/subscriptions/12345/resourceGroups/bar/providers/Microsoft.Batch/batchAccounts/acctname1',
                                    'type' : 'Microsoft.Batch/batchAccounts',
                                    'name': 'acctname1',
                                    'location': 'South Central US',
                                    'properties': {
                                        'accountEndpoint' : 'http://acctname1.batch.core.windows.net/',
                                        'provisioningState' : 'Succeeded',
                                        'dedicatedCoreQuota' : '20',
                                        'lowPriorityCoreQuota' : '50',
                                        'poolQuota' : '100',
                                        'activeJobAndJobScheduleQuota' : '200'
                                    },
                                    'tags' : {
                                        'tag1' : 'value for tag1',
                                        'tag2' : 'value for tag2',
                                    }
                                }
                            ],
                            'nextLink' : ''
                        }")
            };

            var allSubsResponseNonemptyNextLink = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(@"
                    {
                        'value':
                        [
                            {
                                'id': '/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctname',
                                'type' : 'Microsoft.Batch/batchAccounts',
                                'name': 'acctname',
                                'location': 'West US',
                                'properties': {
                                    'accountEndpoint' : 'http://acctname.batch.core.windows.net/',
                                    'provisioningState' : 'Succeeded',
                                    'dedicatedCoreQuota' : '20',
                                    'lowPriorityCoreQuota' : '50',
                                    'poolQuota' : '100',
                                    'activeJobAndJobScheduleQuota' : '200'
                                },
                                'tags' : {
                                    'tag1' : 'value for tag1',
                                    'tag2' : 'value for tag2',
                                }
                            },
                            {
                                'id': '/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctname1',
                                'type' : 'Microsoft.Batch/batchAccounts',
                                'name': 'acctname1',
                                'location': 'South Central US',
                                'properties': {
                                    'accountEndpoint' : 'http://acctname1.batch.core.windows.net/',
                                    'provisioningState' : 'Succeeded'
                                },
                                'tags' : {
                                    'tag1' : 'value for tag1',
                                    'tag2' : 'value for tag2',
                                }
                            }
                        ],
                        'nextLink' : 'https://fake.net/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctname?$skipToken=opaqueStringThatYouShouldntCrack'
                    }
                 ")
            };


            var allSubsResponseNonemptyNextLink1 = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(@"
                    {
                        'value':
                        [
                            {
                                'id': '/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctname',
                                'type' : 'Microsoft.Batch/batchAccounts',
                                'name': 'acctname',
                                'location': 'West US',
                                'properties': {
                                    'accountEndpoint' : 'http://acctname.batch.core.windows.net/',
                                    'provisioningState' : 'Succeeded',
                                    'dedicatedCoreQuota' : '20',
                                    'lowPriorityCoreQuota' : '50',
                                    'poolQuota' : '100',
                                    'activeJobAndJobScheduleQuota' : '200'

                                },
                                'tags' : {
                                    'tag1' : 'value for tag1',
                                    'tag2' : 'value for tag2',
                                }
                            },
                            {
                                'id': '/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctname1',
                                'type' : 'Microsoft.Batch/batchAccounts',
                                'name': 'acctname1',
                                'location': 'South Central US',
                                'properties': {
                                    'accountEndpoint' : 'http://acctname1.batch.core.windows.net/',
                                    'provisioningState' : 'Succeeded',
                                    'dedicatedCoreQuota' : '20',
                                    'lowPriorityCoreQuota' : '50',
                                    'poolQuota' : '100',
                                    'activeJobAndJobScheduleQuota' : '200'
                                },
                                'tags' : {
                                    'tag1' : 'value for tag1',
                                    'tag2' : 'value for tag2',
                                }
                            }
                        ],
                        'nextLink' : 'https://fake.net/subscriptions/12345/resourceGroups/resGroup/providers/Microsoft.Batch/batchAccounts/acctname?$skipToken=opaqueStringThatYouShouldntCrack'
                    }
                 ")
            };

            allSubsResponseEmptyNextLink.Headers.Add("x-ms-request-id", "1");
            allSubsResponseNonemptyNextLink.Headers.Add("x-ms-request-id", "1");
            allSubsResponseNonemptyNextLink1.Headers.Add("x-ms-request-id", "1");

            // all accounts under sub and empty next link
            var handler = new RecordedDelegatingHandler(allSubsResponseEmptyNextLink)
            {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var client = BatchTestHelper.GetBatchManagementClient(handler);

            var result = Task.Factory.StartNew(() => client.BatchAccount.ListWithHttpMessagesAsync())
                         .Unwrap()
                         .GetAwaiter()
                         .GetResult();

            // Validate headers
            Assert.Equal(HttpMethod.Get, handler.Method);
            Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent"));

            // Validate result
            Assert.Equal(HttpStatusCode.OK, result.Response.StatusCode);

            // Validate result
            Assert.Equal(2, result.Body.Count());

            var account1 = result.Body.ElementAt(0);
            var account2 = result.Body.ElementAt(1);

            Assert.Equal("West US", account1.Location);
            Assert.Equal("acctname", account1.Name);
            Assert.Equal("/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctname", account1.Id);
            Assert.Equal("/subscriptions/12345/resourceGroups/bar/providers/Microsoft.Batch/batchAccounts/acctname1", account2.Id);
            Assert.NotEmpty(account1.AccountEndpoint);
            Assert.Equal(20, account1.DedicatedCoreQuota);
            Assert.Equal(50, account1.LowPriorityCoreQuota);
            Assert.Equal(100, account1.PoolQuota);
            Assert.Equal(200, account2.ActiveJobAndJobScheduleQuota);

            Assert.True(account1.Tags.ContainsKey("tag1"));

            // all accounts under sub and a non-empty nextLink
            handler = new RecordedDelegatingHandler(allSubsResponseNonemptyNextLink)
            {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            client = BatchTestHelper.GetBatchManagementClient(handler);

            var result1 = client.BatchAccount.List();

            // Validate headers
            Assert.Equal(HttpMethod.Get, handler.Method);
            Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent"));

            // all accounts under sub with a non-empty nextLink response
            handler = new RecordedDelegatingHandler(allSubsResponseNonemptyNextLink1)
            {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            client = BatchTestHelper.GetBatchManagementClient(handler);

            result1 = client.BatchAccount.ListNext(result1.NextPageLink);

            // Validate headers
            Assert.Equal(HttpMethod.Get, handler.Method);
            Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent"));
        }
        public void AccountListByResourceGroupValidateMessage()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(@"
                    {
                        'value':
                        [
                            {
                                'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctname',
                                'type' : 'Microsoft.Batch/batchAccounts',
                                'name': 'acctname',
                                'location': 'West US',
                                'properties': {
                                    'accountEndpoint' : 'http://acctname.batch.core.windows.net/',
                                    'provisioningState' : 'Succeeded',
                                    'dedicatedCoreQuota' : '20',
                                    'lowPriorityCoreQuota' : '50',
                                    'poolQuota' : '100',
                                    'activeJobAndJobScheduleQuota' : '200'
                                },
                                'tags' : {
                                    'tag1' : 'value for tag1',
                                    'tag2' : 'value for tag2',
                                }
                            },
                            {
                                'id': '/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctname1',
                                'type' : 'Microsoft.Batch/batchAccounts',
                                'name': 'acctname1',
                                'location': 'South Central US',
                                'properties': {
                                    'accountEndpoint' : 'http://acctname1.batch.core.windows.net/',
                                    'provisioningState' : 'Failed',
                                    'dedicatedCoreQuota' : '10',
                                    'lowPriorityCoreQuota' : '50',
                                    'poolQuota' : '50',
                                    'activeJobAndJobScheduleQuota' : '100'
                                },
                                'tags' : {
                                    'tag1' : 'value for tag1'
                                }
                            }
                        ],
                        'nextLink' : 'originalRequestURl?$skipToken=opaqueStringThatYouShouldntCrack'
                    }")
            };

            response.Headers.Add("x-ms-request-id", "1");
            var handler = new RecordedDelegatingHandler(response)
            {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var client = BatchTestHelper.GetBatchManagementClient(handler);

            var result = client.BatchAccount.List();

            // Validate headers
            Assert.Equal(HttpMethod.Get, handler.Method);
            Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent"));

            // Validate result
            Assert.Equal(2, result.Count());

            var account1 = result.ElementAt(0);
            var account2 = result.ElementAt(1);

            Assert.Equal("West US", account1.Location);
            Assert.Equal("acctname", account1.Name);
            Assert.Equal(@"/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctname", account1.Id);
            Assert.Equal(@"http://acctname.batch.core.windows.net/", account1.AccountEndpoint);
            Assert.Equal(ProvisioningState.Succeeded, account1.ProvisioningState);
            Assert.Equal(20, account1.DedicatedCoreQuota);
            Assert.Equal(50, account1.LowPriorityCoreQuota);
            Assert.Equal(100, account1.PoolQuota);
            Assert.Equal(200, account1.ActiveJobAndJobScheduleQuota);

            Assert.Equal("South Central US", account2.Location);
            Assert.Equal("acctname1", account2.Name);
            Assert.Equal(@"/subscriptions/12345/resourceGroups/foo/providers/Microsoft.Batch/batchAccounts/acctname1", account2.Id);
            Assert.Equal(@"http://acctname1.batch.core.windows.net/", account2.AccountEndpoint);
            Assert.Equal(ProvisioningState.Failed, account2.ProvisioningState);
            Assert.Equal(10, account2.DedicatedCoreQuota);
            Assert.Equal(50, account2.LowPriorityCoreQuota);
            Assert.Equal(50, account2.PoolQuota);
            Assert.Equal(100, account2.ActiveJobAndJobScheduleQuota);

            Assert.Equal(2, account1.Tags.Count);
            Assert.True(account1.Tags.ContainsKey("tag2"));

            Assert.Equal(1, account2.Tags.Count);
            Assert.True(account2.Tags.ContainsKey("tag1"));

            Assert.Equal(@"originalRequestURl?$skipToken=opaqueStringThatYouShouldntCrack", result.NextPageLink);
        }
        public void GetWebHostingPlanMetrics()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(HttpPayload.GetWebHostingPlanMetrics)
            };

            var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };

            var client = GetWebSiteManagementClient(handler);

            var result = client.WebHostingPlans.GetHistoricalUsageMetrics("space1", "Default1", 
                new WebHostingPlanGetHistoricalUsageMetricsParameters
                {
                    TimeGrain = "PT1M",
                IncludeInstanceBreakdown = true,
                });

            // Validate headers 
            Assert.Equal(HttpMethod.Get, handler.Method);

            // Validate response 
            Assert.NotNull(result);
            Assert.NotNull(result.UsageMetrics);
            Assert.NotNull(result.UsageMetrics[0]);
            Assert.NotNull(result.UsageMetrics[0].Data);
            Assert.Equal("CpuPercentage", result.UsageMetrics[0].Data.Name);
            Assert.NotNull(result.UsageMetrics[0].Data.Values);
            Assert.Equal("PT1M", result.UsageMetrics[0].Data.TimeGrain);
            Assert.Equal("6", result.UsageMetrics[0].Data.Values[0].Total);
            Assert.Equal("Average", result.UsageMetrics[0].Data.PrimaryAggregationType);

            // check instance level data
            Assert.NotNull(result.UsageMetrics[1]);
            Assert.NotNull(result.UsageMetrics[1].Data);
            Assert.Equal("CpuPercentage", result.UsageMetrics[1].Data.Name);
            Assert.NotNull(result.UsageMetrics[1].Data.Values);
            Assert.Equal("PT1M", result.UsageMetrics[1].Data.TimeGrain);
            Assert.Equal("6", result.UsageMetrics[1].Data.Values[0].Total);
            Assert.Equal("Instance", result.UsageMetrics[1].Data.PrimaryAggregationType);
        }
        public void NetworkInterfaceDnsSettingsTest()
        {
            var handler = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (var context = UndoContext.Current)
            {
                context.Start();
                var resourcesClient = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(handler);
                var networkResourceProviderClient = NetworkManagementTestUtilities.GetNetworkResourceProviderClient(handler);

                // IDNS is supported only in centralus currently
                // var location = NetworkManagementTestUtilities.GetResourceLocation(resourcesClient, "Microsoft.Network/networkInterfaces");
                var location = "centralus";

                string resourceGroupName = TestUtilities.GenerateName("csmrg");
                resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName,
                                                              new ResourceGroup
                {
                    Location = location
                });

                // Create Vnet
                // Populate parameter for Put Vnet
                string vnetName   = TestUtilities.GenerateName();
                string subnetName = TestUtilities.GenerateName();

                var vnet = new VirtualNetwork()
                {
                    Location = location,

                    AddressSpace = new AddressSpace()
                    {
                        AddressPrefixes = new List <string>()
                        {
                            "10.0.0.0/16",
                        }
                    },
                    DhcpOptions = new DhcpOptions()
                    {
                        DnsServers = new List <string>()
                        {
                            "10.1.1.1",
                            "10.1.2.4"
                        }
                    },
                    Subnets = new List <Subnet>()
                    {
                        new Subnet()
                        {
                            Name          = subnetName,
                            AddressPrefix = "10.0.0.0/24",
                        }
                    }
                };

                var putVnetResponse = networkResourceProviderClient.VirtualNetworks.CreateOrUpdate(resourceGroupName, vnetName, vnet);
                Assert.Equal(HttpStatusCode.OK, putVnetResponse.StatusCode);

                var getSubnetResponse = networkResourceProviderClient.Subnets.Get(resourceGroupName, vnetName, subnetName);

                // Create Nic
                string nicName      = TestUtilities.GenerateName();
                string ipConfigName = TestUtilities.GenerateName();

                var nicParameters = new NetworkInterface()
                {
                    Location = location,
                    Name     = nicName,
                    Tags     = new Dictionary <string, string>()
                    {
                        { "key", "value" }
                    },
                    IpConfigurations = new List <NetworkInterfaceIpConfiguration>()
                    {
                        new NetworkInterfaceIpConfiguration()
                        {
                            Name = ipConfigName,
                            PrivateIpAllocationMethod = IpAllocationMethod.Dynamic,
                            Subnet = new ResourceId()
                            {
                                Id = getSubnetResponse.Subnet.Id
                            }
                        }
                    },
                    DnsSettings = new NetworkInterfaceDnsSettings()
                    {
                        DnsServers = new List <string> {
                            "1.0.0.1", "1.0.0.2"
                        },
                        InternalDnsNameLabel = "idnstest",
                    }
                };

                // Test NIC apis
                var putNicResponse = networkResourceProviderClient.NetworkInterfaces.CreateOrUpdate(resourceGroupName, nicName, nicParameters);
                Assert.Equal(HttpStatusCode.OK, putNicResponse.StatusCode);

                var getNicResponse = networkResourceProviderClient.NetworkInterfaces.Get(resourceGroupName, nicName);
                Assert.Equal(getNicResponse.NetworkInterface.Name, nicName);
                Assert.Equal(getNicResponse.NetworkInterface.ProvisioningState, Microsoft.Azure.Management.Resources.Models.ProvisioningState.Succeeded);
                Assert.Null(getNicResponse.NetworkInterface.VirtualMachine);
                Assert.Null(getNicResponse.NetworkInterface.MacAddress);
                Assert.Equal(1, getNicResponse.NetworkInterface.IpConfigurations.Count);
                Assert.Equal(ipConfigName, getNicResponse.NetworkInterface.IpConfigurations[0].Name);
                Assert.Equal(2, getNicResponse.NetworkInterface.DnsSettings.DnsServers.Count);
                Assert.Contains("1.0.0.1", getNicResponse.NetworkInterface.DnsSettings.DnsServers);
                Assert.Contains("1.0.0.2", getNicResponse.NetworkInterface.DnsSettings.DnsServers);
                Assert.Equal("idnstest", getNicResponse.NetworkInterface.DnsSettings.InternalDnsNameLabel);
                Assert.Equal(0, getNicResponse.NetworkInterface.DnsSettings.AppliedDnsServers.Count);
                Assert.Null(getNicResponse.NetworkInterface.DnsSettings.InternalFqdn);

                // Delete Nic
                var deleteNicResponse = networkResourceProviderClient.NetworkInterfaces.Delete(resourceGroupName, nicName);
                Assert.Equal(HttpStatusCode.OK, deleteNicResponse.StatusCode);

                var getListNicResponse = networkResourceProviderClient.NetworkInterfaces.List(resourceGroupName);
                Assert.Equal(0, getListNicResponse.NetworkInterfaces.Count);

                // Delete VirtualNetwork
                var deleteVnetResponse = networkResourceProviderClient.VirtualNetworks.Delete(resourceGroupName, vnetName);
                Assert.Equal(HttpStatusCode.OK, deleteVnetResponse.StatusCode);
            }
        }