public void TestListVMsInSubscriptionByLocation() { using (MockContext context = MockContext.Start(this.GetType().FullName)) { EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); string baseResourceGroupName = ComputeManagementTestUtilities.GenerateName(TestPrefix); string resourceGroup1Name = baseResourceGroupName + "a"; string resourceGroup2Name = baseResourceGroupName + "b"; string availabilitySetName = ComputeManagementTestUtilities.GenerateName(TestPrefix); string storageAccountName = ComputeManagementTestUtilities.GenerateName(TestPrefix); VirtualMachine inputVM1, inputVM2; try { // Create Storage Account, so that both VMs can share it StorageAccount storageAccountOutput = CreateStorageAccount(resourceGroup1Name, storageAccountName); VirtualMachine vm1 = CreateVM(resourceGroup1Name, availabilitySetName, storageAccountOutput, imageRef, out inputVM1); VirtualMachine vm2 = CreateVM(resourceGroup2Name, availabilitySetName, storageAccountOutput, imageRef, out inputVM2); var listResponse = m_CrpClient.VirtualMachines.ListByLocation(ComputeManagementTestUtilities.DefaultLocation); Assert.True(listResponse.Count() >= 2); Assert.Null(listResponse.NextPageLink); int vmsValidatedCount = 0; foreach (VirtualMachine vm in listResponse) { if (vm.Name.Equals(vm1.Name)) { ValidateVM(vm, vm1, Helpers.GetVMReferenceId(m_subId, resourceGroup1Name, vm1.Name)); vmsValidatedCount++; } else if (vm.Name.Equals(vm2.Name)) { ValidateVM(vm, vm2, Helpers.GetVMReferenceId(m_subId, resourceGroup2Name, vm2.Name)); vmsValidatedCount++; } } Assert.Equal(2, vmsValidatedCount); } finally { // Cleanup the created resources. rg2 first since the VM in it needs to be deleted before the // storage account, which is in rg1. try { m_ResourcesClient.ResourceGroups.Delete(resourceGroup2Name); } finally { m_ResourcesClient.ResourceGroups.Delete(resourceGroup1Name); } } } }
public void TestVMImageGet() { using (var context = UndoContext.Current) { context.Start(); ComputeManagementClient _pirClient = ComputeManagementTestUtilities.GetComputeManagementClient(new RDFETestEnvironmentFactory(), new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var vmimage = _pirClient.VirtualMachineImages.Get(parameters); Assert.True(vmimage.VirtualMachineImage.Name == "1.0.0"); Assert.True(vmimage.VirtualMachineImage.Location == "westus"); Assert.True(vmimage.VirtualMachineImage.PurchasePlan.Name == "name"); Assert.True(vmimage.VirtualMachineImage.PurchasePlan.Publisher == "publisher"); Assert.True(vmimage.VirtualMachineImage.PurchasePlan.Product == "product"); Assert.True(vmimage.VirtualMachineImage.OSDiskImage.OperatingSystem == "Linux"); Assert.True(vmimage.VirtualMachineImage.DataDiskImages.Count(ddi => ddi.Lun == 123456789) != 0); } }
private void VerifyDefaultValuesSucceed() { var inputAvailabilitySetName = ComputeManagementTestUtilities.GenerateName("asdefaultvalues"); var inputAvailabilitySet = new AvailabilitySet { Location = location, Tags = new Dictionary <string, string>() { { "RG", "rg" }, { "testTag", "1" }, }, }; var createOrUpdateResponse = computeClient.AvailabilitySets.CreateOrUpdate( resourceGroupName, inputAvailabilitySetName, inputAvailabilitySet); // List AvailabilitySets string expectedAvailabilitySetId = Helpers.GetAvailabilitySetRef(subId, resourceGroupName, inputAvailabilitySetName); var listResponse = computeClient.AvailabilitySets.List(resourceGroupName); ValidateAvailabilitySet(inputAvailabilitySet, listResponse.FirstOrDefault(x => x.Name == inputAvailabilitySetName), inputAvailabilitySetName, expectedAvailabilitySetId, defaultFD, defaultUD); // This call will also delete the Availability Set ValidateResults(createOrUpdateResponse, inputAvailabilitySet, inputAvailabilitySetName, defaultFD, defaultUD); }
private string CreateApplicationMediaLink(string rgName, string fileName) { string storageAccountName = ComputeManagementTestUtilities.GenerateName("saforgallery"); string asName = ComputeManagementTestUtilities.GenerateName("asforgallery"); StorageAccount storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); // resource group is also created in this method. string applicationMediaLink = @"https://saforgallery1969.blob.core.windows.net/sascontainer/test.txt\"; if (HttpMockServer.Mode == HttpRecorderMode.Record) { var accountKeyResult = m_SrpClient.StorageAccounts.ListKeysWithHttpMessagesAsync(rgName, storageAccountName).Result; CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(storageAccountName, accountKeyResult.Body.Key1), useHttps: true); var blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("sascontainer"); bool created = container.CreateIfNotExistsAsync().Result; CloudPageBlob pageBlob = container.GetPageBlobReference(fileName); byte[] blobContent = Encoding.UTF8.GetBytes("Application Package Test"); byte[] bytes = new byte[512]; // Page blob must be multiple of 512 System.Buffer.BlockCopy(blobContent, 0, bytes, 0, blobContent.Length); pageBlob.UploadFromByteArrayAsync(bytes, 0, bytes.Length); SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy(); sasConstraints.SharedAccessStartTime = DateTime.UtcNow.AddDays(-1); sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddDays(2); sasConstraints.Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Write; //Generate the shared access signature on the blob, setting the constraints directly on the signature. string sasContainerToken = pageBlob.GetSharedAccessSignature(sasConstraints); //Return the URI string for the container, including the SAS token. applicationMediaLink = pageBlob.Uri + sasContainerToken; } return(applicationMediaLink); }
protected void EnsureClientsInitialized(MockContext context) { if (!m_initialized) { lock (m_lock) { if (!m_initialized) { m_ResourcesClient = ComputeManagementTestUtilities.GetResourceManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); m_CrpClient = ComputeManagementTestUtilities.GetComputeManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); m_SrpClient = ComputeManagementTestUtilities.GetStorageManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); m_NrpClient = ComputeManagementTestUtilities.GetNetworkManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); m_subId = m_CrpClient.SubscriptionId; if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"))) { m_location = ComputeManagementTestUtilities.DefaultLocation; } else { m_location = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION").Replace(" ", "").ToLower(); } } } } }
public void TestExtImgGet() { using (MockContext context = MockContext.Start(this.GetType())) { ComputeManagementClient _pirClient = ComputeManagementTestUtilities.GetComputeManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var vmimageext = _pirClient.VirtualMachineExtensionImages.Get( parameters.Location, parameters.PublisherName, parameters.Type, "2.0"); Assert.True(vmimageext.Name == "2.0"); Assert.True(vmimageext.Location == "westus"); Assert.True(vmimageext.OperatingSystem == "Windows"); Assert.True(vmimageext.ComputeRole == "IaaS"); Assert.True(vmimageext.HandlerSchema == null); Assert.True(vmimageext.VmScaleSetEnabled == false); Assert.True(vmimageext.SupportsMultipleExtensions == false); } }
protected PublicIPAddress CreatePublicIP(string rgName) { // Create publicIP string publicIpName = ComputeManagementTestUtilities.GenerateName("pip"); string domainNameLabel = ComputeManagementTestUtilities.GenerateName("dn"); var publicIp = new PublicIPAddress() { Location = m_location, Tags = new Dictionary <string, string>() { { "key", "value" } }, PublicIPAllocationMethod = IPAllocationMethod.Dynamic, DnsSettings = new PublicIPAddressDnsSettings() { DomainNameLabel = domainNameLabel } }; var putPublicIpAddressResponse = m_NrpClient.PublicIPAddresses.CreateOrUpdate(rgName, publicIpName, publicIp); var getPublicIpAddressResponse = m_NrpClient.PublicIPAddresses.Get(rgName, publicIpName); return(getPublicIpAddressResponse); }
protected void EnsureClientsInitialized(bool useSPN = false) { if (!m_initialized) { lock (m_lock) { if (!m_initialized) { var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; if (useSPN) { m_ResourcesClient = ComputeManagementTestUtilities.GetResourceManagementClientWithSpn(handler); m_CrpClient = ComputeManagementTestUtilities.GetComputeManagementClientWithSpn(handler); m_SrpClient = ComputeManagementTestUtilities.GetStorageManagementClientSpn(handler); m_NrpClient = ComputeManagementTestUtilities.GetNetworkResourceProviderClientSpn(handler); } else { m_ResourcesClient = ComputeManagementTestUtilities.GetResourceManagementClient(handler); m_CrpClient = ComputeManagementTestUtilities.GetComputeManagementClient(handler); m_SrpClient = ComputeManagementTestUtilities.GetStorageManagementClient(handler); m_NrpClient = ComputeManagementTestUtilities.GetNetworkResourceProviderClient(handler); } m_subId = m_CrpClient.Credentials.SubscriptionId; m_location = ComputeManagementTestUtilities.DefaultLocation; } } } }
public void TestListVMRunCommands() { using (MockContext context = MockContext.Start(this.GetType())) { var computeClient = ComputeManagementTestUtilities.GetComputeManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); string location = ComputeManagementTestUtilities.DefaultLocation.Replace(" ", ""); string documentId = "RunPowerShellScript"; // Verify the List of commands IEnumerable <RunCommandDocumentBase> runCommandListResponse = computeClient.VirtualMachineRunCommands.List(location); Assert.NotNull(runCommandListResponse); Assert.True(runCommandListResponse.Count() > 0, "ListRunCommands should return at least 1 command"); RunCommandDocumentBase documentBase = runCommandListResponse.FirstOrDefault(x => string.Equals(x.Id, documentId)); Assert.NotNull(documentBase); // Verify Get a specific RunCommand RunCommandDocument document = computeClient.VirtualMachineRunCommands.Get(location, documentId); Assert.NotNull(document); Assert.NotNull(document.Script); Assert.True(document.Script.Count > 0, "Script should contain at least one command."); Assert.NotNull(document.Parameters); Assert.True(document.Parameters.Count == 2, "Script should have 2 parameters."); } }
private void Initialize(MockContext context) { handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; resourcesClient = ComputeManagementTestUtilities.GetResourceManagementClient(context, handler); computeClient = ComputeManagementTestUtilities.GetComputeManagementClient(context, handler); subId = computeClient.SubscriptionId; location = m_location; baseResourceGroupName = ComputeManagementTestUtilities.GenerateName(TestPrefix); resourceGroup1Name = baseResourceGroupName + "_1"; resourceGroup1 = resourcesClient.ResourceGroups.CreateOrUpdate( resourceGroup1Name, new ResourceGroup { Location = location, Tags = new Dictionary <string, string>() { { resourceGroup1Name, DateTime.UtcNow.ToString("u") } } }); }
private void VerifyNonDefaultValuesSucceed() { // Negative tests for a bug in 5.0.0 that read-only fields have side-effect on the request body var testStatus = new InstanceViewStatus { Code = "test", DisplayStatus = "test", Message = "test" }; string inputAvailabilitySetName = ComputeManagementTestUtilities.GenerateName("asnondefault"); var inputAvailabilitySet = new AvailabilitySet { Location = location, Tags = new Dictionary <string, string>() { { "RG", "rg" }, { "testTag", "1" }, }, PlatformFaultDomainCount = nonDefaultFD, PlatformUpdateDomainCount = nonDefaultUD, Statuses = new List <InstanceViewStatus>() { testStatus } }; var createOrUpdateResponse = computeClient.AvailabilitySets.CreateOrUpdate( resourceGroupName, inputAvailabilitySetName, inputAvailabilitySet); // This call will also delete the Availability Set ValidateResults(createOrUpdateResponse, inputAvailabilitySet, inputAvailabilitySetName, nonDefaultFD, nonDefaultUD); }
public void TestVMCertificatesOperations() { using (MockContext context = MockContext.Start(this.GetType().FullName)) { EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); // Create resource group var rgName = ComputeManagementTestUtilities.GenerateName(TestPrefix); string storageAccountName = ComputeManagementTestUtilities.GenerateName(TestPrefix); string asName = ComputeManagementTestUtilities.GenerateName("as"); VirtualMachine inputVM; Action <VirtualMachine> AddCertificateInfo = SetCertificateInfo; try { // Create Storage Account, so that both the VMs can share it var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); var vm1 = CreateVM_NoAsyncTracking(rgName, asName, storageAccountOutput, imageRef, out inputVM, AddCertificateInfo); m_CrpClient.VirtualMachines.Delete(rgName, inputVM.Name); } finally { m_ResourcesClient.ResourceGroups.Delete(rgName); } } }
private VirtualMachine CreateCRPImage(string rgName, string imageName, ref string sourceImageId) { string storageAccountName = ComputeManagementTestUtilities.GenerateName("saforgallery"); string asName = ComputeManagementTestUtilities.GenerateName("asforgallery"); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); StorageAccount storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); // resource group is also created in this method. VirtualMachine inputVM = null; VirtualMachine createdVM = CreateVM(rgName, asName, storageAccountOutput, imageRef, out inputVM); Image imageInput = new Image() { Location = m_location, Tags = new Dictionary <string, string>() { { "RG", "rg" }, { "testTag", "1" }, }, StorageProfile = new ImageStorageProfile() { OsDisk = new ImageOSDisk() { BlobUri = createdVM.StorageProfile.OsDisk.Vhd.Uri, OsState = OperatingSystemStateTypes.Generalized, OsType = OperatingSystemTypes.Windows, }, ZoneResilient = true }, HyperVGeneration = HyperVGenerationTypes.V1 }; m_CrpClient.Images.CreateOrUpdate(rgName, imageName, imageInput); Image getImage = m_CrpClient.Images.Get(rgName, imageName); sourceImageId = getImage.Id; return(createdVM); }
protected string CreateCspkgSasUrl(string rgName, string fileName) { string storageAccountName = ComputeManagementTestUtilities.GenerateName("saforcspkg"); string asName = ComputeManagementTestUtilities.GenerateName("asforcspkg"); StorageAccount storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); // resource group is also created in this method. string applicationMediaLink = @"https://saforcspkg1969.blob.core.windows.net/sascontainer/" + fileName; if (HttpMockServer.Mode == HttpRecorderMode.Record) { var accountKeyResult = m_SrpClient.StorageAccounts.ListKeysWithHttpMessagesAsync(rgName, storageAccountName).Result; CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(storageAccountName, accountKeyResult.Body.Key1), useHttps: true); var blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("sascontainer"); container.CreateIfNotExistsAsync().Wait(); CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName); blockBlob.UploadFromFileAsync(Path.Combine(Directory.GetCurrentDirectory(), "Resources", fileName)).Wait(); SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy(); sasConstraints.SharedAccessStartTime = DateTime.UtcNow.AddDays(-1); sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddDays(2); sasConstraints.Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Write; //Generate the shared access signature on the blob, setting the constraints directly on the signature. string sasContainerToken = blockBlob.GetSharedAccessSignature(sasConstraints); //Return the URI string for the container, including the SAS token. applicationMediaLink = blockBlob.Uri + sasContainerToken; } return(applicationMediaLink); }
protected VirtualMachine CreateDefaultVMInput(string rgName, string storageAccountName, ImageReference imageRef, string asetId, string nicId) { // Generate Container name to hold disk VHds string containerName = ComputeManagementTestUtilities.GenerateName(TestPrefix); var vhdContainer = "https://" + storageAccountName + ".blob.core.windows.net/" + containerName; var vhduri = vhdContainer + string.Format("/{0}.vhd", ComputeManagementTestUtilities.GenerateName(TestPrefix)); var osVhduri = vhdContainer + string.Format("/os{0}.vhd", ComputeManagementTestUtilities.GenerateName(TestPrefix)); var vm = new VirtualMachine { Location = m_location, Tags = new Dictionary <string, string>() { { "RG", "rg" }, { "testTag", "1" } }, AvailabilitySet = new Microsoft.Azure.Management.Compute.Models.SubResource() { Id = asetId }, HardwareProfile = new HardwareProfile { VmSize = VirtualMachineSizeTypes.StandardA0 }, StorageProfile = new StorageProfile { ImageReference = imageRef, OsDisk = new OSDisk { Caching = CachingTypes.None, CreateOption = DiskCreateOptionTypes.FromImage, Name = "test", Vhd = new VirtualHardDisk { Uri = osVhduri } }, DataDisks = null, }, NetworkProfile = new NetworkProfile { NetworkInterfaces = new List <NetworkInterfaceReference> { new NetworkInterfaceReference { Id = nicId } } }, OsProfile = new OSProfile { AdminUsername = "******", AdminPassword = "******" + rgName, ComputerName = "test" } }; typeof(Microsoft.Azure.Management.Compute.Models.Resource).GetRuntimeProperty("Name").SetValue(vm, ComputeManagementTestUtilities.GenerateName("vm")); typeof(Microsoft.Azure.Management.Compute.Models.Resource).GetRuntimeProperty("Type").SetValue(vm, ComputeManagementTestUtilities.GenerateName("Microsoft.Compute/virtualMachines")); return(vm); }
public void TestVMDiskSizeScenario() { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); var image = m_CrpClient.VirtualMachineImages.Get( this.m_location, imageRef.Publisher, imageRef.Offer, imageRef.Sku, imageRef.Version); Assert.True(image != null); // Create resource group var rgName = ComputeManagementTestUtilities.GenerateName(TestPrefix); string storageAccountName = ComputeManagementTestUtilities.GenerateName(TestPrefix); string asName = ComputeManagementTestUtilities.GenerateName("as"); VirtualMachine inputVM; try { var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); var vm1 = CreateVM(rgName, asName, storageAccountOutput, imageRef, out inputVM, (vm) => { vm.StorageProfile.OsDisk.DiskSizeGB = 150; }); var getVMResponse = m_CrpClient.VirtualMachines.Get(rgName, inputVM.Name); ValidateVM(inputVM, getVMResponse, Helpers.GetVMReferenceId(m_subId, rgName, inputVM.Name)); } finally { m_ResourcesClient.ResourceGroups.Delete(rgName); } } }
public void TestVMScaleSetRollingUpgradeHistory() { using (MockContext context = MockContext.Start(this.GetType())) { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); // Create resource group var rgName = TestUtilities.GenerateName(TestPrefix); var vmssName = TestUtilities.GenerateName("vmss"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "southcentralus"); EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); imageRef.Version = "latest"; var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); m_CrpClient.VirtualMachineScaleSets.Delete(rgName, "VMScaleSetDoesNotExist"); var getResponse = CreateVMScaleSet_NoAsyncTracking( rgName, vmssName, storageAccountOutput, imageRef, out inputVMScaleSet, null, (vmScaleSet) => { vmScaleSet.Overprovision = false; vmScaleSet.UpgradePolicy.Mode = UpgradeMode.Rolling; }, createWithManagedDisks: true, createWithPublicIpAddress: false, createWithHealthProbe: true); ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true); ComputeManagementTestUtilities.WaitSeconds(600); var vmssStatus = m_CrpClient.VirtualMachineScaleSets.GetInstanceView(rgName, vmssName); m_CrpClient.VirtualMachineScaleSetRollingUpgrades.StartOSUpgrade(rgName, vmssName); var rollingUpgradeHistory = m_CrpClient.VirtualMachineScaleSets.GetOSUpgradeHistory(rgName, vmssName); Assert.NotNull(rollingUpgradeHistory); Assert.True(rollingUpgradeHistory.Count() == 1); Assert.Equal(inputVMScaleSet.Sku.Capacity, rollingUpgradeHistory.First().Properties.Progress.SuccessfulInstanceCount); } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); //Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose //of the test to cover deletion. CSM does persistent retrying over all RG resources. m_ResourcesClient.ResourceGroups.Delete(rgName); } } }
public void TestExportingThrottlingLogs() { using (MockContext context = MockContext.Start(this.GetType())) { string rg1Name = ComputeManagementTestUtilities.GenerateName(TestPrefix); string storageAccountName = ComputeManagementTestUtilities.GenerateName(TestPrefix); try { EnsureClientsInitialized(context); string sasUri = GetBlobContainerSasUri(rg1Name, storageAccountName); RequestRateByIntervalInput requestRateByIntervalInput = new RequestRateByIntervalInput() { BlobContainerSasUri = sasUri, FromTime = DateTime.UtcNow.AddDays(-10), ToTime = DateTime.UtcNow.AddDays(-8), IntervalLength = IntervalInMins.FiveMins, }; var result = m_CrpClient.LogAnalytics.ExportRequestRateByInterval(requestRateByIntervalInput, "westcentralus"); //BUG: LogAnalytics API does not return correct result. //Assert.EndsWith(".csv", result.Properties.Output); ThrottledRequestsInput throttledRequestsInput = new ThrottledRequestsInput() { BlobContainerSasUri = sasUri, FromTime = DateTime.UtcNow.AddDays(-10), ToTime = DateTime.UtcNow.AddDays(-8), GroupByOperationName = true, }; result = m_CrpClient.LogAnalytics.ExportThrottledRequests(throttledRequestsInput, "westcentralus"); //BUG: LogAnalytics API does not return correct result. //Assert.EndsWith(".csv", result.Properties.Output); ThrottledRequestsInput throttledRequestsInput2 = new ThrottledRequestsInput() { BlobContainerSasUri = sasUri, FromTime = DateTime.UtcNow.AddDays(-10), ToTime = DateTime.UtcNow.AddDays(-8), GroupByOperationName = false, GroupByClientApplicationId = true, GroupByUserAgent = false, }; result = m_CrpClient.LogAnalytics.ExportThrottledRequests(throttledRequestsInput2, "eastus2"); } finally { m_ResourcesClient.ResourceGroups.Delete(rg1Name); } } }
public void TestVMBYOL() { using (MockContext context = MockContext.Start(this.GetType().FullName)) { EnsureClientsInitialized(context); // Create resource group var rgName = ComputeManagementTestUtilities.GenerateName(TestPrefix); string asName = ComputeManagementTestUtilities.GenerateName("as"); VirtualMachine inputVM; string storageAccountName = ComputeManagementTestUtilities.GenerateName(TestPrefix); ImageReference dummyImageRef = null; // Create Storage Account, so that both the VMs can share it var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); try { Action <VirtualMachine> useVMMImage = vm => { vm.StorageProfile.ImageReference = GetPlatformVMImage(true); vm.LicenseType = "Windows_Server"; }; VirtualMachine vm1 = null; try { vm1 = CreateVM_NoAsyncTracking(rgName, asName, storageAccountOutput, dummyImageRef, out inputVM, useVMMImage); } catch (Exception ex) { if (ex.Message.Contains("License type cannot be specified when creating a virtual machine from platform image. Please use an image from on-premises instead.")) { return; } throw; } var getResponse = m_CrpClient.VirtualMachines.GetWithHttpMessagesAsync(rgName, vm1.Name).GetAwaiter().GetResult(); Assert.True(getResponse.Response.StatusCode == HttpStatusCode.OK); ValidateVM(inputVM, getResponse.Body, Helpers.GetVMReferenceId(m_subId, rgName, inputVM.Name)); var lroResponse = m_CrpClient.VirtualMachines.DeleteWithHttpMessagesAsync(rgName, inputVM.Name).GetAwaiter().GetResult(); Assert.True(lroResponse.Response.StatusCode == HttpStatusCode.OK); } finally { // Don't wait for RG deletion since it's too slow, and there is nothing interesting expected with // the resources from this test. //var deleteResourceGroupResponse = m_ResourcesClient.ResourceGroups.BeginDeleteWithHttpMessagesAsync(rgName); m_ResourcesClient.ResourceGroups.BeginDeleteWithHttpMessagesAsync(rgName); //Assert.True(deleteResourceGroupResponse.Result.Response.StatusCode == HttpStatusCode.Accepted || // deleteResourceGroupResponse.Result.Response.StatusCode == HttpStatusCode.NotFound); } } }
private void VerifyPutPatchGetAndDeleteOperations_Scenarios(ProximityPlacementGroup inputProximityPlacementGroup, ProximityPlacementGroup expectedProximityPlacementGroup) { var proximityPlacementGroupName = ComputeManagementTestUtilities.GenerateName("testppg"); // Create and expect success. ProximityPlacementGroup outProximityPlacementGroup = m_CrpClient.ProximityPlacementGroups.CreateOrUpdate(m_resourceGroup1Name, proximityPlacementGroupName, inputProximityPlacementGroup); ValidateProximityPlacementGroup(expectedProximityPlacementGroup, outProximityPlacementGroup, proximityPlacementGroupName); // Update and expect success. inputProximityPlacementGroup.Tags.Add("UpdateTag1", "updateValue1"); outProximityPlacementGroup = m_CrpClient.ProximityPlacementGroups.CreateOrUpdate(m_resourceGroup1Name, proximityPlacementGroupName, inputProximityPlacementGroup); ValidateProximityPlacementGroup(expectedProximityPlacementGroup, outProximityPlacementGroup, proximityPlacementGroupName); // Get and expect success. outProximityPlacementGroup = m_CrpClient.ProximityPlacementGroups.Get(m_resourceGroup1Name, proximityPlacementGroupName); ValidateProximityPlacementGroup(expectedProximityPlacementGroup, outProximityPlacementGroup, proximityPlacementGroupName); // Put and expect failure try { //Updating ProximityPlacementGroupType in inputProximityPlacementGroup for a Update call. if (expectedProximityPlacementGroup.ProximityPlacementGroupType == ProximityPlacementGroupType.Standard) { inputProximityPlacementGroup.ProximityPlacementGroupType = ProximityPlacementGroupType.Ultra; } else { inputProximityPlacementGroup.ProximityPlacementGroupType = ProximityPlacementGroupType.Standard; } outProximityPlacementGroup = null; outProximityPlacementGroup = m_CrpClient.ProximityPlacementGroups.CreateOrUpdate(m_resourceGroup1Name, proximityPlacementGroupName, inputProximityPlacementGroup); } catch (CloudException ex) { Assert.True(ex.Response.StatusCode == HttpStatusCode.Conflict, $"Expecting HttpStatusCode {HttpStatusCode.Conflict}, while actual HttpStatusCode is {ex.Response.StatusCode}."); Assert.Equal("Changing property 'proximityPlacementGroup.properties.proximityPlacementGroupType' is not allowed.", ex.Message, StringComparer.OrdinalIgnoreCase); } Assert.True(outProximityPlacementGroup == null, "ProximityPlacementGroup in response should be null."); //Patch and expect success ProximityPlacementGroupUpdate proximityPlacementGroupUpdate = new ProximityPlacementGroupUpdate() { Tags = inputProximityPlacementGroup.Tags }; //Note: Same Tags object is referred in proximityPlacementGroupUpdate and expectedProximityPlacementGroup, //hence this will also update tags in expectedProximityPlacementGroup. proximityPlacementGroupUpdate.Tags.Add("UpdateTag2", "updateValue2"); outProximityPlacementGroup = m_CrpClient.ProximityPlacementGroups.Update(m_resourceGroup1Name, proximityPlacementGroupName, proximityPlacementGroupUpdate.Tags); ValidateProximityPlacementGroup(expectedProximityPlacementGroup, outProximityPlacementGroup, proximityPlacementGroupName); // Clean up m_CrpClient.ProximityPlacementGroups.Delete(m_resourceGroup1Name, proximityPlacementGroupName); }
public void TestVMWithLinuxOSProfile() { using (MockContext context = MockContext.Start(this.GetType().FullName)) { EnsureClientsInitialized(context); string rgName = ComputeManagementTestUtilities.GenerateName(TestPrefix); string sshPath = null; Action <VirtualMachine> enableSSHAndCustomData = customizedVM => { var osProfile = customizedVM.OsProfile; sshPath = "/home/" + osProfile.AdminUsername + "/.ssh/authorized_keys"; osProfile.CustomData = CustomData; osProfile.LinuxConfiguration = new LinuxConfiguration { DisablePasswordAuthentication = false, Ssh = new SshConfiguration { PublicKeys = new List <SshPublicKey> { new SshPublicKey { Path = sshPath, KeyData = DefaultSshPublicKey, } } } }; }; Action <VirtualMachine> validateWinRMCustomDataAndUnattendContent = outputVM => { var osProfile = outputVM.OsProfile; Assert.Equal <string>(CustomData, osProfile.CustomData); Assert.Null(osProfile.WindowsConfiguration); Assert.NotNull(osProfile.LinuxConfiguration); Assert.NotNull(osProfile.LinuxConfiguration.Ssh); var publicKeys = osProfile.LinuxConfiguration.Ssh.PublicKeys; Assert.NotNull(osProfile.LinuxConfiguration.Ssh.PublicKeys); Assert.True(osProfile.LinuxConfiguration.DisablePasswordAuthentication != null && !osProfile.LinuxConfiguration.DisablePasswordAuthentication.Value); Assert.Equal(1, publicKeys.Count); Assert.Equal(sshPath, publicKeys[0].Path); Assert.Equal(DefaultSshPublicKey, publicKeys[0].KeyData); }; TestVMWithOSProfile( rgName: rgName, useWindowsProfile: false, vmCustomizer: enableSSHAndCustomData, vmValidator: validateWinRMCustomDataAndUnattendContent); } }
public void TestVMIdentitySystemAssignedUserAssigned() { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); // Create resource group var rgName = ComputeManagementTestUtilities.GenerateName(TestPrefix); string storageAccountName = ComputeManagementTestUtilities.GenerateName(TestPrefix); string asName = ComputeManagementTestUtilities.GenerateName("as"); string userIdentityName = ComputeManagementTestUtilities.GenerateName("userid"); VirtualMachine inputVM; try { var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); // Creating User Assigned Managed Identity Identity identityResponse = m_MsiClient.UserAssignedIdentities.CreateOrUpdate(rgName, userIdentityName, new Identity(location: ComputeManagementTestUtilities.DefaultLocation)); string identity = identityResponse.Id; Action <VirtualMachine> addUserIdentity = vm => { vm.Identity = new VirtualMachineIdentity(); vm.Identity.Type = ResourceIdentityType.SystemAssignedUserAssigned; vm.Identity.UserAssignedIdentities = new Dictionary <string, VirtualMachineIdentityUserAssignedIdentitiesValue>() { { identity, new VirtualMachineIdentityUserAssignedIdentitiesValue() } }; }; var vmResult = CreateVM(rgName, asName, storageAccountOutput, imageRef, out inputVM, addUserIdentity); Assert.Equal(ResourceIdentityType.SystemAssignedUserAssigned, vmResult.Identity.Type); Assert.NotNull(vmResult.Identity.PrincipalId); Assert.NotNull(vmResult.Identity.TenantId); Assert.True(vmResult.Identity.UserAssignedIdentities.Keys.Contains(identity)); Assert.NotNull(vmResult.Identity.UserAssignedIdentities[identity].PrincipalId); Assert.NotNull(vmResult.Identity.UserAssignedIdentities[identity].ClientId); var getVM = m_CrpClient.VirtualMachines.Get(rgName, inputVM.Name); Assert.Equal(ResourceIdentityType.SystemAssignedUserAssigned, getVM.Identity.Type); Assert.NotNull(getVM.Identity.PrincipalId); Assert.NotNull(getVM.Identity.TenantId); Assert.True(getVM.Identity.UserAssignedIdentities.Keys.Contains(identity)); Assert.NotNull(getVM.Identity.UserAssignedIdentities[identity].PrincipalId); Assert.NotNull(getVM.Identity.UserAssignedIdentities[identity].ClientId); } finally { m_ResourcesClient.ResourceGroups.Delete(rgName); } } }
public void TestVMExtensionOperations() { using (MockContext context = MockContext.Start(this.GetType().FullName)) { EnsureClientsInitialized(context); //VMNetworkInterfaceTests.FixRecords(); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); // Create resource group var rgName = ComputeManagementTestUtilities.GenerateName(TestPrefix); string storageAccountName = ComputeManagementTestUtilities.GenerateName(TestPrefix); string asName = ComputeManagementTestUtilities.GenerateName("as"); VirtualMachine inputVM; try { // Create Storage Account, so that both the VMs can share it var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); var vm = CreateVM_NoAsyncTracking(rgName, asName, storageAccountOutput, imageRef, out inputVM); // Delete an extension that does not exist in the VM. A http status code of NoContent should be returned which translates to operation success. m_CrpClient.VirtualMachineExtensions.Delete(rgName, vm.Name, "VMExtensionDoesNotExist"); // Add an extension to the VM var vmExtension = GetTestVMExtension(); var response = m_CrpClient.VirtualMachineExtensions.CreateOrUpdate(rgName, vm.Name, vmExtension.Name, vmExtension); ValidateVMExtension(vmExtension, response); // Perform a Get operation on the extension var getVMExtResponse = m_CrpClient.VirtualMachineExtensions.Get(rgName, vm.Name, vmExtension.Name); ValidateVMExtension(vmExtension, getVMExtResponse); // Validate Get InstanceView for the extension var getVMExtInstanceViewResponse = m_CrpClient.VirtualMachineExtensions.Get(rgName, vm.Name, vmExtension.Name, "instanceView"); ValidateVMExtensionInstanceView(getVMExtInstanceViewResponse.InstanceView); // Validate the extension in the VM info var getVMResponse = m_CrpClient.VirtualMachines.Get(rgName, vm.Name); // TODO AutoRest: Recording Passed, but these assertions failed in Playback mode ValidateVMExtension(vmExtension, getVMResponse.Resources.FirstOrDefault()); // Validate the extension instance view in the VM instance-view var getVMWithInstanceViewResponse = m_CrpClient.VirtualMachines.Get(rgName, vm.Name, InstanceViewTypes.InstanceView); ValidateVMExtensionInstanceView(getVMWithInstanceViewResponse.InstanceView.Extensions.FirstOrDefault()); // Validate the extension delete API m_CrpClient.VirtualMachineExtensions.Delete(rgName, vm.Name, vmExtension.Name); } finally { m_ResourcesClient.ResourceGroups.Delete(rgName); } } }
public void Gallery_CRUD_Tests() { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); string rgName = ComputeManagementTestUtilities.GenerateName(ResourceGroupPrefix); string rgName2 = rgName + "New"; m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = galleryHomeLocation }); Trace.TraceInformation("Created the resource group: " + rgName); string galleryName = ComputeManagementTestUtilities.GenerateName(GalleryNamePrefix); Gallery galleryIn = GetTestInputGallery(); m_CrpClient.Galleries.CreateOrUpdate(rgName, galleryName, galleryIn); Trace.TraceInformation(string.Format("Created the gallery: {0} in resource group: {1}", galleryName, rgName)); Gallery galleryOut = m_CrpClient.Galleries.Get(rgName, galleryName); Trace.TraceInformation("Got the gallery."); Assert.NotNull(galleryOut); ValidateGallery(galleryIn, galleryOut); galleryIn.Description = "This is an updated description"; m_CrpClient.Galleries.CreateOrUpdate(rgName, galleryName, galleryIn); Trace.TraceInformation("Updated the gallery."); galleryOut = m_CrpClient.Galleries.Get(rgName, galleryName); ValidateGallery(galleryIn, galleryOut); Trace.TraceInformation("Listing galleries."); string galleryName2 = galleryName + "New"; m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName2, new ResourceGroup { Location = galleryHomeLocation }); Trace.TraceInformation("Created the resource group: " + rgName2); ComputeManagementTestUtilities.WaitSeconds(10); m_CrpClient.Galleries.CreateOrUpdate(rgName2, galleryName2, galleryIn); Trace.TraceInformation(string.Format("Created the gallery: {0} in resource group: {1}", galleryName2, rgName2)); IPage <Gallery> listGalleriesInRgResult = m_CrpClient.Galleries.ListByResourceGroup(rgName); Assert.Single(listGalleriesInRgResult); Assert.Null(listGalleriesInRgResult.NextPageLink); IPage <Gallery> listGalleriesInSubIdResult = m_CrpClient.Galleries.List(); // Below, >= instead of == is used because this subscription is shared in the group so other developers // might have created galleries in this subscription. Assert.True(listGalleriesInSubIdResult.Count() >= 2); Trace.TraceInformation("Deleting 2 galleries."); m_CrpClient.Galleries.Delete(rgName, galleryName); m_CrpClient.Galleries.Delete(rgName2, galleryName2); listGalleriesInRgResult = m_CrpClient.Galleries.ListByResourceGroup(rgName); Assert.Empty(listGalleriesInRgResult); // resource groups cleanup is taken cared by MockContext.Dispose() method. } }
public void VMApplicationProfile_Tests() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); using (MockContext context = MockContext.Start(this.GetType())) { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "centraluseuap"); EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); var image = m_CrpClient.VirtualMachineImages.Get( this.m_location, imageRef.Publisher, imageRef.Offer, imageRef.Sku, imageRef.Version); Assert.True(image != null); // Create resource group var rgName = ComputeManagementTestUtilities.GenerateName(TestPrefix); string storageAccountName = ComputeManagementTestUtilities.GenerateName(TestPrefix); string asName = ComputeManagementTestUtilities.GenerateName("as"); VirtualMachine inputVM; try { var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); IList <VMGalleryApplication> galleryApplications = new List <VMGalleryApplication>() { // when re-recording the test ensure that you use a valid packageReferenceId // refer to https://microsoft.sharepoint.com/:w:/t/ComputeVM/EcYeD-HHrLZHpYyxo3iRCtkB-VeO8BuWE4dq4hoX9tlzEg?e=nOTgTu // for how to create a valid VMApplication new VMGalleryApplication("/subscriptions/a53f7094-a16c-47af-abe4-b05c05d0d79a/resourceGroups/bhbrahma/providers/Microsoft.Compute/galleries/bhbrahmaGallery/applications/go/versions/1.15.8", treatFailureAsDeploymentFailure: true, enableAutomaticUpgrade: true) }; var vm1 = CreateVM(rgName, asName, storageAccountOutput, imageRef, out inputVM, (vm) => { vm.StorageProfile.OsDisk.DiskSizeGB = 150; vm.ApplicationProfile = new ApplicationProfile(galleryApplications); }); var getVMResponse = m_CrpClient.VirtualMachines.Get(rgName, inputVM.Name); ValidateVM(inputVM, getVMResponse, Helpers.GetVMReferenceId(m_subId, rgName, inputVM.Name)); Assert.NotNull(getVMResponse.ApplicationProfile); Assert.NotNull(getVMResponse.ApplicationProfile.GalleryApplications); Assert.Equal(1, getVMResponse.ApplicationProfile.GalleryApplications.Count); VMGalleryApplication vmGalleryApplication = getVMResponse.ApplicationProfile.GalleryApplications[0]; Assert.True(vmGalleryApplication.TreatFailureAsDeploymentFailure); Assert.True(vmGalleryApplication.EnableAutomaticUpgrade); } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); m_ResourcesClient.ResourceGroups.Delete(rgName); } } }
public void TestListVMSizes() { using (MockContext context = MockContext.Start(this.GetType())) { var computeClient = ComputeManagementTestUtilities.GetComputeManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); string location = ComputeManagementTestUtilities.DefaultLocation.Replace(" ", ""); var virtualMachineSizeListResponse = computeClient.VirtualMachineSizes.List(location); Helpers.ValidateVirtualMachineSizeListResponse(virtualMachineSizeListResponse); } }
public void CreateLocalRestorePointWithSecurityProfile() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); using (MockContext context = MockContext.Start(this.GetType().FullName)) { string location = "southcentralus"; Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", location); EnsureClientsInitialized(context); var rgName = ComputeManagementTestUtilities.GenerateName(TestPrefix); ImageReference imageRef = new ImageReference(publisher: "MICROSOFTWINDOWSDESKTOP", offer: "WINDOWS-10", version: "latest", sku: "20H2-ENT-G2"); VirtualMachine inputVM; string storageAccountForDisks = TestUtilities.GenerateName(TestPrefix); string availabilitySetName = TestUtilities.GenerateName(TestPrefix); try { // PUT VM with SecurityType = TrustedLaunch VirtualMachine createdVM = CreateVM(rgName, availabilitySetName, storageAccountForDisks, imageRef, out inputVM, hasManagedDisks: true, vmSize: VirtualMachineSizeTypes.StandardD2sV3, securityType: "TrustedLaunch"); string rpcName = ComputeManagementTestUtilities.GenerateName("rpcClientTest"); string rpName = ComputeManagementTestUtilities.GenerateName("rpClientTest"); // Create Restore Point Collection string vmId = createdVM.Id; string vmSize = createdVM.HardwareProfile.VmSize; Dictionary <string, string> tags = new Dictionary <string, string>() { { "testTag", "testTagValue" } }; RestorePointCollection createdRpc = CreateRpc(vmId, rpcName, rgName, location, tags); // Create Restore Point RestorePoint createdRP = CreateRestorePoint(rgName, rpcName, rpName, diskToExclude: null, sourceRestorePointId: null); // GET Disk Restore Point IPage <DiskRestorePoint> listDiskRestorePoint = m_CrpClient.DiskRestorePoint.ListByRestorePoint(rgName, rpcName, rpName); var getDrp = m_CrpClient.DiskRestorePoint.Get(rgName, rpcName, rpName, listDiskRestorePoint.First().Name); Assert.Equal("TrustedLaunch", getDrp.SecurityProfile.SecurityType); } catch (Exception e) { throw e; } finally { m_ResourcesClient.ResourceGroups.Delete(rgName); Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } }
private void VerifyPutPatchGetAndDeleteWithInvalidValues_Failure() { var ProximityPlacementGroupName = ComputeManagementTestUtilities.GenerateName("testppg"); var inputProximityPlacementGroup = new ProximityPlacementGroup { Location = "", Tags = new Dictionary <string, string>() { { "RG", "rg" }, { "testTag", "1" }, }, }; // Put and expect failure ProximityPlacementGroup expectedProximityPlacementGroup = null; void CreateAndExpectFailure() { try { // Create and expect success. expectedProximityPlacementGroup = m_CrpClient.ProximityPlacementGroups.CreateOrUpdate( m_resourceGroup1Name, ProximityPlacementGroupName, inputProximityPlacementGroup); } catch (CloudException ex) { Assert.True(ex.Response.StatusCode == HttpStatusCode.BadRequest, $"Expecting HttpStatusCode {HttpStatusCode.BadRequest}, while actual HttpStatusCode is {ex.Response.StatusCode}."); } Assert.True(expectedProximityPlacementGroup == null); } //Verify failure when location is invalid CreateAndExpectFailure(); //Verify failure when ProximityPlacementGroupType is invalid inputProximityPlacementGroup.Location = m_location; inputProximityPlacementGroup.ProximityPlacementGroupType = "Invalid"; CreateAndExpectFailure(); //Verify success when ProximityPlacementGroup is valid inputProximityPlacementGroup.ProximityPlacementGroupType = ProximityPlacementGroupType.Standard; expectedProximityPlacementGroup = m_CrpClient.ProximityPlacementGroups.CreateOrUpdate( m_resourceGroup1Name, ProximityPlacementGroupName, inputProximityPlacementGroup); ValidateProximityPlacementGroup(inputProximityPlacementGroup, expectedProximityPlacementGroup, ProximityPlacementGroupName); // Get and expect success. expectedProximityPlacementGroup = m_CrpClient.ProximityPlacementGroups.Get(m_resourceGroup1Name, ProximityPlacementGroupName); ValidateProximityPlacementGroup(inputProximityPlacementGroup, expectedProximityPlacementGroup, ProximityPlacementGroupName); // Clean up m_CrpClient.ProximityPlacementGroups.Delete(m_resourceGroup1Name, ProximityPlacementGroupName); }
public void TestVMImageListPublishers() { using (var context = UndoContext.Current) { context.Start(); ComputeManagementClient _pirClient = ComputeManagementTestUtilities.GetComputeManagementClient(); var publishers = _pirClient.VirtualMachineImages.ListPublishers(parameters); Assert.True(publishers.Resources.Count > 0); Assert.True(publishers.Resources.Count(pub => pub.Name == parameters.PublisherName) != 0); } }
public void TestVMImageListSkus() { using (var context = UndoContext.Current) { context.Start(); ComputeManagementClient _pirClient = ComputeManagementTestUtilities.GetComputeManagementClient(); var skus = _pirClient.VirtualMachineImages.ListSkus(parameters); Assert.True(skus.Resources.Count > 0); Assert.True(skus.Resources.Count(sku => sku.Name == parameters.Skus) != 0); } }