diff --git a/src/Compute/Compute.Test/ScenarioTests/ComputeTestCommon.ps1 b/src/Compute/Compute.Test/ScenarioTests/ComputeTestCommon.ps1 index 6824036f7f55..49077ac67226 100644 --- a/src/Compute/Compute.Test/ScenarioTests/ComputeTestCommon.ps1 +++ b/src/Compute/Compute.Test/ScenarioTests/ComputeTestCommon.ps1 @@ -13,39 +13,32 @@ # ---------------------------------------------------------------------------------- $PLACEHOLDER = "PLACEHOLDER1@" -$TestOutputRoot = [System.AppDomain]::CurrentDomain.BaseDirectory; -$TemplatesPath = Join-Path $TestOutputRoot "Templates"; -$ConfigFilesPath = Join-Path $TestOutputRoot "ConfigFiles"; +$TestOutputRoot = [System.AppDomain]::CurrentDomain.BaseDirectory +$TemplatesPath = Join-Path $TestOutputRoot "Templates" +$ConfigFilesPath = Join-Path $TestOutputRoot "ConfigFiles" <# .SYNOPSIS Gets valid resource name for compute test #> -function Get-ComputeTestResourceName -{ +function Get-ComputeTestResourceName { $stack = Get-PSCallStack - $testName = $null; - foreach ($frame in $stack) - { - if ($frame.Command.StartsWith("Test-", "CurrentCultureIgnoreCase")) - { - $testName = $frame.Command; + $testName = $null + foreach ($frame in $stack) { + if ($frame.Command.StartsWith("Test-", "CurrentCultureIgnoreCase")) { + $testName = $frame.Command } } - try - { - $assetName = [Microsoft.Azure.Test.HttpRecorder.HttpMockServer]::GetAssetName($testName, "crptestps"); + try { + $assetName = [Microsoft.Azure.Test.HttpRecorder.HttpMockServer]::GetAssetName($testName, "crptestps") } - catch - { - if ($PSItem.Exception.Message -like '*Unable to find type*') - { - $assetName = Get-RandomItemName; + catch { + if ($PSItem.Exception.Message -like '*Unable to find type*') { + $assetName = Get-RandomItemName } - else - { - throw; + else { + throw } } @@ -56,63 +49,60 @@ function Get-ComputeTestResourceName .SYNOPSIS Gets test mode - 'Record' or 'Playback' #> -function Get-ComputeTestMode -{ - try - { - $testMode = [Microsoft.Azure.Test.HttpRecorder.HttpMockServer]::Mode; - $testMode = $testMode.ToString(); - } - catch - { - if ($PSItem.Exception.Message -like '*Unable to find type*') - { - $testMode = 'Record'; +function Get-ComputeTestMode { + try { + $testMode = [Microsoft.Azure.Test.HttpRecorder.HttpMockServer]::Mode + $testMode = $testMode.ToString() + } + catch { + if ($PSItem.Exception.Message -like '*Unable to find type*') { + $testMode = 'Record' } - else - { - throw; + else { + throw } } - return $testMode; + return $testMode } # Get Compute Test Location -function Get-ComputeTestLocation -{ - return $env:AZURE_COMPUTE_TEST_LOCATION; +function Get-ComputeTestLocation { + return $env:AZURE_COMPUTE_TEST_LOCATION } # Get Compute Default Test Location -function Get-ComputeDefaultLocation -{ - $test_location = Get-ComputeTestLocation; - if ($test_location -eq '' -or $test_location -eq $null) - { - $test_location = 'westus'; +function Get-ComputeDefaultLocation { + $test_location = Get-ComputeTestLocation + if ($test_location -eq '' -or $test_location -eq $null) { + $test_location = 'westus' } - return $test_location; + return $test_location } # Create key vault resources -function Create-KeyVault -{ +function Create-KeyVault { Param ( - [Parameter(Mandatory=$true, Position=0)] + [Parameter(Mandatory = $true, Position = 0)] [string] $resourceGroupName, - [Parameter(Mandatory=$true, Position=1)] + [Parameter(Mandatory = $true, Position = 1)] [string] $location, - [Parameter(Mandatory=$false, Position=2)] + [Parameter(Mandatory = $false, Position = 2)] [string] $vaultName ) # initialize parameters if needed - if ([string]::IsNullOrEmpty($resourceGroupName)) { $resourceGroupName = Get-ComputeTestResourceName } - if ([string]::IsNullOrEmpty($location)) { $location = Get-ComputeVMLocation } - if ([string]::IsNullOrEmpty($vaultName)) { $vaultName = 'kv' + $resourceGroupName } + if ([string]::IsNullOrEmpty($resourceGroupName)) { + $resourceGroupName = Get-ComputeTestResourceName + } + if ([string]::IsNullOrEmpty($location)) { + $location = Get-ComputeVMLocation + } + if ([string]::IsNullOrEmpty($vaultName)) { + $vaultName = 'kv' + $resourceGroupName + } # create vault $vault = New-AzKeyVault -VaultName $vaultName -ResourceGroupName $resourceGroupName -Location $location -Sku standard @@ -124,13 +114,13 @@ function Create-KeyVault #Set-AzKeyVaultAccessPolicy -VaultName $vaultName -ResourceGroupName $resourceGroupName -ServicePrincipalName $servicePrincipalName -PermissionsToKeys Create Set-AzKeyVaultAccessPolicy -VaultName $vaultName -ResourceGroupName $resourceGroupName -EnabledForDiskEncryption -EnabledForDeployment -EnabledForTemplateDeployment - # create key encryption key + # create key encryption key #$kekName = 'kek' + $resourceGroupName #$kek = Add-AzKeyVaultKey -VaultName $vaultName -Name $kekName -Destination "Software" # return the newly created key vault properties $properties = New-Object PSObject -Property @{ - DiskEncryptionKeyVaultId = $vault.ResourceId + DiskEncryptionKeyVaultId = $vault.ResourceId DiskEncryptionKeyVaultUrl = $vault.VaultUri #KeyEncryptionKeyVaultId = $vault.ResourceId #KeyEncryptionKeyUrl = $kek.Key.kid @@ -139,24 +129,29 @@ function Create-KeyVault } # Create key vault resources -function Create-KeyVaultWithAclEncryptionIdentity -{ +function Create-KeyVaultWithAclEncryptionIdentity { Param ( - [Parameter(Mandatory=$true, Position=0)] + [Parameter(Mandatory = $true, Position = 0)] [string] $resourceGroupName, - [Parameter(Mandatory=$true, Position=1)] + [Parameter(Mandatory = $true, Position = 1)] [string] $location, - [Parameter(Mandatory=$false, Position=2)] + [Parameter(Mandatory = $false, Position = 2)] [string] $vaultName, - [Parameter(Mandatory=$false, Position=3)] + [Parameter(Mandatory = $false, Position = 3)] [String] $userIdentityPrincipalId ) # initialize parameters if needed - if ([string]::IsNullOrEmpty($resourceGroupName)) { $resourceGroupName = Get-ComputeTestResourceName } - if ([string]::IsNullOrEmpty($location)) { $location = Get-ComputeVMLocation } - if ([string]::IsNullOrEmpty($vaultName)) { $vaultName = 'kv' + $resourceGroupName } + if ([string]::IsNullOrEmpty($resourceGroupName)) { + $resourceGroupName = Get-ComputeTestResourceName + } + if ([string]::IsNullOrEmpty($location)) { + $location = Get-ComputeVMLocation + } + if ([string]::IsNullOrEmpty($vaultName)) { + $vaultName = 'kv' + $resourceGroupName + } # create vault $vault = New-AzKeyVault -VaultName $vaultName -ResourceGroupName $resourceGroupName -Location $location -Sku standard -DisableRbacAuthorization @@ -166,13 +161,13 @@ function Create-KeyVaultWithAclEncryptionIdentity $servicePrincipalName = (Get-AzContext).Account.Id Assert-NotNull $servicePrincipalName if (-not [string]::IsNullOrEmpty($userIdentityPrincipalId)) { - Set-AzKeyVaultAccessPolicy -VaultName $vaultName -ResourceGroupName $resourceGroupName -ObjectId $userIdentityPrincipalId -PermissionsToKeys all -PermissionsToSecrets all + Set-AzKeyVaultAccessPolicy -VaultName $vaultName -ResourceGroupName $resourceGroupName -ObjectId $userIdentityPrincipalId -PermissionsToKeys all -PermissionsToSecrets all } Set-AzKeyVaultAccessPolicy -VaultName $vaultName -ResourceGroupName $resourceGroupName -EnabledForDeployment -EnabledForTemplateDeployment # return the newly created key vault properties $properties = New-Object PSObject -Property @{ - DiskEncryptionKeyVaultId = $vault.ResourceId + DiskEncryptionKeyVaultId = $vault.ResourceId DiskEncryptionKeyVaultUrl = $vault.VaultUri #KeyEncryptionKeyUrl = $kek.Key.kid } @@ -180,215 +175,223 @@ function Create-KeyVaultWithAclEncryptionIdentity } # Create a new virtual machine with other necessary resources configured -function Create-VirtualMachine -{ +function Create-VirtualMachine { Param ( - [Parameter(Mandatory=$false, Position=0)] + [Parameter(Mandatory = $false, Position = 0)] [string] $rgname, - [Parameter(Mandatory=$false, Position=1)] + [Parameter(Mandatory = $false, Position = 1)] [string] $vmname, - [Parameter(Mandatory=$false, Position=2)] - [string] $loc + [Parameter(Mandatory = $false, Position = 2)] + [string] $loc ) # initialize parameters if needed - if ([string]::IsNullOrEmpty($rgname)) { $rgname = Get-ComputeTestResourceName } - if ([string]::IsNullOrEmpty($vmname)) { $vmname = 'vm' + $rgname } - if ([string]::IsNullOrEmpty($loc)) { $loc = Get-ComputeVMLocation } + if ([string]::IsNullOrEmpty($rgname)) { + $rgname = Get-ComputeTestResourceName + } + if ([string]::IsNullOrEmpty($vmname)) { + $vmname = 'vm' + $rgname + } + if ([string]::IsNullOrEmpty($loc)) { + $loc = Get-ComputeVMLocation + } # Common - $g = New-AzResourceGroup -Name $rgname -Location $loc -Force; + $g = New-AzResourceGroup -Name $rgname -Location $loc -Force # VM Profile & Hardware - $vmsize = 'Standard_A2'; - $stnd = "Standard"; - $p = New-AzVMConfig -VMName $vmname -VMSize $vmsize -SecurityType $stnd; - Assert-AreEqual $p.HardwareProfile.VmSize $vmsize; + $vmsize = 'Standard_A2' + $stnd = "Standard" + $p = New-AzVMConfig -VMName $vmname -VMSize $vmsize -SecurityType $stnd + Assert-AreEqual $p.HardwareProfile.VmSize $vmsize # NRP - $subnet = New-AzVirtualNetworkSubnetConfig -Name ('subnet' + $rgname) -AddressPrefix "10.0.0.0/24"; - $vnet = New-AzVirtualNetwork -Force -Name ('vnet' + $rgname) -ResourceGroupName $rgname -Location $loc -AddressPrefix "10.0.0.0/16" -Subnet $subnet; - $vnet = Get-AzVirtualNetwork -Name ('vnet' + $rgname) -ResourceGroupName $rgname; - $subnetId = $vnet.Subnets[0].Id; - $pubip = New-AzPublicIpAddress -Force -Name ('pubip' + $rgname) -ResourceGroupName $rgname -Location $loc -AllocationMethod Dynamic -DomainNameLabel ('pubip' + $rgname); - $pubip = Get-AzPublicIpAddress -Name ('pubip' + $rgname) -ResourceGroupName $rgname; - $pubipId = $pubip.Id; - $nic = New-AzNetworkInterface -Force -Name ('nic' + $rgname) -ResourceGroupName $rgname -Location $loc -SubnetId $subnetId -PublicIpAddressId $pubip.Id; - $nic = Get-AzNetworkInterface -Name ('nic' + $rgname) -ResourceGroupName $rgname; - $nicId = $nic.Id; - - $p = Add-AzVMNetworkInterface -VM $p -Id $nicId; - Assert-AreEqual $p.NetworkProfile.NetworkInterfaces.Count 1; - Assert-AreEqual $p.NetworkProfile.NetworkInterfaces[0].Id $nicId; + $subnet = New-AzVirtualNetworkSubnetConfig -Name ('subnet' + $rgname) -AddressPrefix "10.0.0.0/24" + $vnet = New-AzVirtualNetwork -Force -Name ('vnet' + $rgname) -ResourceGroupName $rgname -Location $loc -AddressPrefix "10.0.0.0/16" -Subnet $subnet + $vnet = Get-AzVirtualNetwork -Name ('vnet' + $rgname) -ResourceGroupName $rgname + $subnetId = $vnet.Subnets[0].Id + $pubip = New-AzPublicIpAddress -Force -Name ('pubip' + $rgname) -ResourceGroupName $rgname -Location $loc -AllocationMethod Dynamic -DomainNameLabel ('pubip' + $rgname) + $pubip = Get-AzPublicIpAddress -Name ('pubip' + $rgname) -ResourceGroupName $rgname + $pubipId = $pubip.Id + $nic = New-AzNetworkInterface -Force -Name ('nic' + $rgname) -ResourceGroupName $rgname -Location $loc -SubnetId $subnetId -PublicIpAddressId $pubip.Id + $nic = Get-AzNetworkInterface -Name ('nic' + $rgname) -ResourceGroupName $rgname + $nicId = $nic.Id + + $p = Add-AzVMNetworkInterface -VM $p -Id $nicId + Assert-AreEqual $p.NetworkProfile.NetworkInterfaces.Count 1 + Assert-AreEqual $p.NetworkProfile.NetworkInterfaces[0].Id $nicId # Storage Account (SA) - $stoname = 'sto' + $rgname; - $stotype = 'Standard_GRS'; - $sa = New-AzStorageAccount -ResourceGroupName $rgname -Name $stoname -Location $loc -Type $stotype; + $stoname = 'sto' + $rgname + $stotype = 'Standard_GRS' + $sa = New-AzStorageAccount -ResourceGroupName $rgname -Name $stoname -Location $loc -Type $stotype Retry-IfException { $global:stoaccount = Get-AzStorageAccount -ResourceGroupName $rgname -Name $stoname; } - $stokey = (Get-AzStorageAccountKey -ResourceGroupName $rgname -Name $stoname).Key1; - - $osDiskName = 'osDisk'; - $osDiskCaching = 'ReadWrite'; - $osDiskVhdUri = "https://$stoname.blob.core.windows.net/test/os.vhd"; - $dataDiskVhdUri1 = "https://$stoname.blob.core.windows.net/test/data1.vhd"; - $dataDiskVhdUri2 = "https://$stoname.blob.core.windows.net/test/data2.vhd"; - $dataDiskVhdUri3 = "https://$stoname.blob.core.windows.net/test/data3.vhd"; - - $p = Set-AzVMOSDisk -VM $p -Name $osDiskName -VhdUri $osDiskVhdUri -Caching $osDiskCaching -CreateOption FromImage; - - $p = Add-AzVMDataDisk -VM $p -Name 'testDataDisk1' -Caching 'ReadOnly' -DiskSizeInGB 10 -Lun 1 -VhdUri $dataDiskVhdUri1 -CreateOption Empty; - $p = Add-AzVMDataDisk -VM $p -Name 'testDataDisk2' -Caching 'ReadOnly' -DiskSizeInGB 11 -Lun 2 -VhdUri $dataDiskVhdUri2 -CreateOption Empty; - $p = Add-AzVMDataDisk -VM $p -Name 'testDataDisk3' -Caching 'ReadOnly' -DiskSizeInGB 12 -Lun 3 -VhdUri $dataDiskVhdUri3 -CreateOption Empty; - $p = Remove-AzVMDataDisk -VM $p -Name 'testDataDisk3'; - - Assert-AreEqual $p.StorageProfile.OsDisk.Caching $osDiskCaching; - Assert-AreEqual $p.StorageProfile.OsDisk.Name $osDiskName; - Assert-AreEqual $p.StorageProfile.OsDisk.Vhd.Uri $osDiskVhdUri; - Assert-AreEqual $p.StorageProfile.DataDisks.Count 2; - Assert-AreEqual $p.StorageProfile.DataDisks[0].Caching 'ReadOnly'; - Assert-AreEqual $p.StorageProfile.DataDisks[0].DiskSizeGB 10; - Assert-AreEqual $p.StorageProfile.DataDisks[0].Lun 1; - Assert-AreEqual $p.StorageProfile.DataDisks[0].Vhd.Uri $dataDiskVhdUri1; - Assert-AreEqual $p.StorageProfile.DataDisks[1].Caching 'ReadOnly'; - Assert-AreEqual $p.StorageProfile.DataDisks[1].DiskSizeGB 11; - Assert-AreEqual $p.StorageProfile.DataDisks[1].Lun 2; - Assert-AreEqual $p.StorageProfile.DataDisks[1].Vhd.Uri $dataDiskVhdUri2; + $stokey = (Get-AzStorageAccountKey -ResourceGroupName $rgname -Name $stoname).Key1 + + $osDiskName = 'osDisk' + $osDiskCaching = 'ReadWrite' + $osDiskVhdUri = "https://$stoname.blob.core.windows.net/test/os.vhd" + $dataDiskVhdUri1 = "https://$stoname.blob.core.windows.net/test/data1.vhd" + $dataDiskVhdUri2 = "https://$stoname.blob.core.windows.net/test/data2.vhd" + $dataDiskVhdUri3 = "https://$stoname.blob.core.windows.net/test/data3.vhd" + + $p = Set-AzVMOSDisk -VM $p -Name $osDiskName -VhdUri $osDiskVhdUri -Caching $osDiskCaching -CreateOption FromImage + + $p = Add-AzVMDataDisk -VM $p -Name 'testDataDisk1' -Caching 'ReadOnly' -DiskSizeInGB 10 -Lun 1 -VhdUri $dataDiskVhdUri1 -CreateOption Empty + $p = Add-AzVMDataDisk -VM $p -Name 'testDataDisk2' -Caching 'ReadOnly' -DiskSizeInGB 11 -Lun 2 -VhdUri $dataDiskVhdUri2 -CreateOption Empty + $p = Add-AzVMDataDisk -VM $p -Name 'testDataDisk3' -Caching 'ReadOnly' -DiskSizeInGB 12 -Lun 3 -VhdUri $dataDiskVhdUri3 -CreateOption Empty + $p = Remove-AzVMDataDisk -VM $p -Name 'testDataDisk3' + + Assert-AreEqual $p.StorageProfile.OsDisk.Caching $osDiskCaching + Assert-AreEqual $p.StorageProfile.OsDisk.Name $osDiskName + Assert-AreEqual $p.StorageProfile.OsDisk.Vhd.Uri $osDiskVhdUri + Assert-AreEqual $p.StorageProfile.DataDisks.Count 2 + Assert-AreEqual $p.StorageProfile.DataDisks[0].Caching 'ReadOnly' + Assert-AreEqual $p.StorageProfile.DataDisks[0].DiskSizeGB 10 + Assert-AreEqual $p.StorageProfile.DataDisks[0].Lun 1 + Assert-AreEqual $p.StorageProfile.DataDisks[0].Vhd.Uri $dataDiskVhdUri1 + Assert-AreEqual $p.StorageProfile.DataDisks[1].Caching 'ReadOnly' + Assert-AreEqual $p.StorageProfile.DataDisks[1].DiskSizeGB 11 + Assert-AreEqual $p.StorageProfile.DataDisks[1].Lun 2 + Assert-AreEqual $p.StorageProfile.DataDisks[1].Vhd.Uri $dataDiskVhdUri2 # OS & Image - $user = "Foo12"; - $password = $PLACEHOLDER; - $securePassword = ConvertTo-SecureString $password -AsPlainText -Force; - $cred = New-Object System.Management.Automation.PSCredential ($user, $securePassword); - $computerName = 'test'; - $vhdContainer = "https://$stoname.blob.core.windows.net/test"; + $user = "Foo12" + $password = $PLACEHOLDER + $securePassword = ConvertTo-SecureString $password -AsPlainText -Force + $cred = New-Object System.Management.Automation.PSCredential ($user, $securePassword) + $computerName = 'test' + $vhdContainer = "https://$stoname.blob.core.windows.net/test" - $p = Set-AzVMOperatingSystem -VM $p -Windows -ComputerName $computerName -Credential $cred -ProvisionVMAgent; + $p = Set-AzVMOperatingSystem -VM $p -Windows -ComputerName $computerName -Credential $cred -ProvisionVMAgent - $imgRef = Get-DefaultCRPWindowsImageOffline; - $p = ($imgRef | Set-AzVMSourceImage -VM $p); + $imgRef = Get-DefaultCRPWindowsImageOffline + $p = ($imgRef | Set-AzVMSourceImage -VM $p) - Assert-AreEqual $p.OSProfile.AdminUsername $user; - Assert-AreEqual $p.OSProfile.ComputerName $computerName; - Assert-AreEqual $p.OSProfile.AdminPassword $password; - Assert-AreEqual $p.OSProfile.WindowsConfiguration.ProvisionVMAgent $true; + Assert-AreEqual $p.OSProfile.AdminUsername $user + Assert-AreEqual $p.OSProfile.ComputerName $computerName + Assert-AreEqual $p.OSProfile.AdminPassword $password + Assert-AreEqual $p.OSProfile.WindowsConfiguration.ProvisionVMAgent $true - Assert-AreEqual $p.StorageProfile.ImageReference.Offer $imgRef.Offer; - Assert-AreEqual $p.StorageProfile.ImageReference.Publisher $imgRef.PublisherName; - Assert-AreEqual $p.StorageProfile.ImageReference.Sku $imgRef.Skus; - Assert-AreEqual $p.StorageProfile.ImageReference.Version $imgRef.Version; + Assert-AreEqual $p.StorageProfile.ImageReference.Offer $imgRef.Offer + Assert-AreEqual $p.StorageProfile.ImageReference.Publisher $imgRef.PublisherName + Assert-AreEqual $p.StorageProfile.ImageReference.Sku $imgRef.Skus + Assert-AreEqual $p.StorageProfile.ImageReference.Version $imgRef.Version # Virtual Machine - $v = New-AzVM -ResourceGroupName $rgname -Location $loc -VM $p; + $v = New-AzVM -ResourceGroupName $rgname -Location $loc -VM $p $vm = Get-AzVM -ResourceGroupName $rgname -VMName $vmname return $vm } # Create a new virtual machine with other necessary resources configured -function Create-VirtualMachineNoDataDisks -{ +function Create-VirtualMachineNoDataDisks { Param ( - [Parameter(Mandatory=$false, Position=0)] + [Parameter(Mandatory = $false, Position = 0)] [string] $rgname, - [Parameter(Mandatory=$false, Position=1)] + [Parameter(Mandatory = $false, Position = 1)] [string] $vmname, - [Parameter(Mandatory=$false, Position=2)] - [string] $loc + [Parameter(Mandatory = $false, Position = 2)] + [string] $loc ) # initialize parameters if needed - if ([string]::IsNullOrEmpty($rgname)) { $rgname = Get-ComputeTestResourceName } - if ([string]::IsNullOrEmpty($vmname)) { $vmname = 'vm' + $rgname } - if ([string]::IsNullOrEmpty($loc)) { $loc = Get-ComputeVMLocation } + if ([string]::IsNullOrEmpty($rgname)) { + $rgname = Get-ComputeTestResourceName + } + if ([string]::IsNullOrEmpty($vmname)) { + $vmname = 'vm' + $rgname + } + if ([string]::IsNullOrEmpty($loc)) { + $loc = Get-ComputeVMLocation + } # Common - $g = New-AzResourceGroup -Name $rgname -Location $loc -Force; + $g = New-AzResourceGroup -Name $rgname -Location $loc -Force # VM Profile & Hardware - $vmsize = 'Standard_D2S_V3'; - $stnd = "Standard"; - $p = New-AzVMConfig -VMName $vmname -VMSize $vmsize -SecurityType $stnd; - Assert-AreEqual $p.HardwareProfile.VmSize $vmsize; + $vmsize = 'Standard_D2S_V3' + $stnd = "Standard" + $p = New-AzVMConfig -VMName $vmname -VMSize $vmsize -SecurityType $stnd + Assert-AreEqual $p.HardwareProfile.VmSize $vmsize # NRP - $subnet = New-AzVirtualNetworkSubnetConfig -Name ('subnet' + $rgname) -AddressPrefix "10.0.0.0/24"; - $vnet = New-AzVirtualNetwork -Force -Name ('vnet' + $rgname) -ResourceGroupName $rgname -Location $loc -AddressPrefix "10.0.0.0/16" -Subnet $subnet; - $vnet = Get-AzVirtualNetwork -Name ('vnet' + $rgname) -ResourceGroupName $rgname; - $subnetId = $vnet.Subnets[0].Id; - $pubip = New-AzPublicIpAddress -Force -Name ('pubip' + $rgname) -ResourceGroupName $rgname -Location $loc -AllocationMethod Dynamic -DomainNameLabel ('pubip' + $rgname); - $pubip = Get-AzPublicIpAddress -Name ('pubip' + $rgname) -ResourceGroupName $rgname; - $pubipId = $pubip.Id; - $nic = New-AzNetworkInterface -Force -Name ('nic' + $rgname) -ResourceGroupName $rgname -Location $loc -SubnetId $subnetId -PublicIpAddressId $pubip.Id; - $nic = Get-AzNetworkInterface -Name ('nic' + $rgname) -ResourceGroupName $rgname; - $nicId = $nic.Id; - - $p = Add-AzVMNetworkInterface -VM $p -Id $nicId; - Assert-AreEqual $p.NetworkProfile.NetworkInterfaces.Count 1; - Assert-AreEqual $p.NetworkProfile.NetworkInterfaces[0].Id $nicId; + $subnet = New-AzVirtualNetworkSubnetConfig -Name ('subnet' + $rgname) -AddressPrefix "10.0.0.0/24" + $vnet = New-AzVirtualNetwork -Force -Name ('vnet' + $rgname) -ResourceGroupName $rgname -Location $loc -AddressPrefix "10.0.0.0/16" -Subnet $subnet + $vnet = Get-AzVirtualNetwork -Name ('vnet' + $rgname) -ResourceGroupName $rgname + $subnetId = $vnet.Subnets[0].Id + $pubip = New-AzPublicIpAddress -Force -Name ('pubip' + $rgname) -ResourceGroupName $rgname -Location $loc -AllocationMethod Dynamic -DomainNameLabel ('pubip' + $rgname) + $pubip = Get-AzPublicIpAddress -Name ('pubip' + $rgname) -ResourceGroupName $rgname + $pubipId = $pubip.Id + $nic = New-AzNetworkInterface -Force -Name ('nic' + $rgname) -ResourceGroupName $rgname -Location $loc -SubnetId $subnetId -PublicIpAddressId $pubip.Id + $nic = Get-AzNetworkInterface -Name ('nic' + $rgname) -ResourceGroupName $rgname + $nicId = $nic.Id + + $p = Add-AzVMNetworkInterface -VM $p -Id $nicId + Assert-AreEqual $p.NetworkProfile.NetworkInterfaces.Count 1 + Assert-AreEqual $p.NetworkProfile.NetworkInterfaces[0].Id $nicId # Storage Account (SA) - $stoname = 'sto' + $rgname; - $stotype = 'Standard_GRS'; - $sa = New-AzStorageAccount -ResourceGroupName $rgname -Name $stoname -Location $loc -Type $stotype; + $stoname = 'sto' + $rgname + $stotype = 'Standard_GRS' + $sa = New-AzStorageAccount -ResourceGroupName $rgname -Name $stoname -Location $loc -Type $stotype Retry-IfException { $global:stoaccount = Get-AzStorageAccount -ResourceGroupName $rgname -Name $stoname; } - $stokey = (Get-AzStorageAccountKey -ResourceGroupName $rgname -Name $stoname).Key1; + $stokey = (Get-AzStorageAccountKey -ResourceGroupName $rgname -Name $stoname).Key1 - $osDiskName = 'osDisk'; - $osDiskCaching = 'ReadWrite'; - $osDiskVhdUri = "https://$stoname.blob.core.windows.net/test/os.vhd"; + $osDiskName = 'osDisk' + $osDiskCaching = 'ReadWrite' + $osDiskVhdUri = "https://$stoname.blob.core.windows.net/test/os.vhd" - $p = Set-AzVMOSDisk -VM $p -Name $osDiskName -VhdUri $osDiskVhdUri -Caching $osDiskCaching -CreateOption FromImage; + $p = Set-AzVMOSDisk -VM $p -Name $osDiskName -VhdUri $osDiskVhdUri -Caching $osDiskCaching -CreateOption FromImage - Assert-AreEqual $p.StorageProfile.OsDisk.Caching $osDiskCaching; - Assert-AreEqual $p.StorageProfile.OsDisk.Name $osDiskName; - Assert-AreEqual $p.StorageProfile.OsDisk.Vhd.Uri $osDiskVhdUri; - Assert-AreEqual $p.StorageProfile.DataDisks.Count 0; + Assert-AreEqual $p.StorageProfile.OsDisk.Caching $osDiskCaching + Assert-AreEqual $p.StorageProfile.OsDisk.Name $osDiskName + Assert-AreEqual $p.StorageProfile.OsDisk.Vhd.Uri $osDiskVhdUri + Assert-AreEqual $p.StorageProfile.DataDisks.Count 0 # OS & Image - $user = "Foo12"; - $password = $PLACEHOLDER; - $securePassword = ConvertTo-SecureString $password -AsPlainText -Force; - $cred = New-Object System.Management.Automation.PSCredential ($user, $securePassword); - $computerName = 'test'; - $vhdContainer = "https://$stoname.blob.core.windows.net/test"; + $user = "Foo12" + $password = $PLACEHOLDER + $securePassword = ConvertTo-SecureString $password -AsPlainText -Force + $cred = New-Object System.Management.Automation.PSCredential ($user, $securePassword) + $computerName = 'test' + $vhdContainer = "https://$stoname.blob.core.windows.net/test" - $p = Set-AzVMOperatingSystem -VM $p -Windows -ComputerName $computerName -Credential $cred -ProvisionVMAgent; + $p = Set-AzVMOperatingSystem -VM $p -Windows -ComputerName $computerName -Credential $cred -ProvisionVMAgent - $imgRef = Get-DefaultCRPWindowsImageOffline; - $p = ($imgRef | Set-AzVMSourceImage -VM $p); + $imgRef = Get-DefaultCRPWindowsImageOffline + $p = ($imgRef | Set-AzVMSourceImage -VM $p) - Assert-AreEqual $p.OSProfile.AdminUsername $user; - Assert-AreEqual $p.OSProfile.ComputerName $computerName; - Assert-AreEqual $p.OSProfile.AdminPassword $password; - Assert-AreEqual $p.OSProfile.WindowsConfiguration.ProvisionVMAgent $true; + Assert-AreEqual $p.OSProfile.AdminUsername $user + Assert-AreEqual $p.OSProfile.ComputerName $computerName + Assert-AreEqual $p.OSProfile.AdminPassword $password + Assert-AreEqual $p.OSProfile.WindowsConfiguration.ProvisionVMAgent $true - Assert-AreEqual $p.StorageProfile.ImageReference.Offer $imgRef.Offer; - Assert-AreEqual $p.StorageProfile.ImageReference.Publisher $imgRef.PublisherName; - Assert-AreEqual $p.StorageProfile.ImageReference.Sku $imgRef.Skus; - Assert-AreEqual $p.StorageProfile.ImageReference.Version $imgRef.Version; + Assert-AreEqual $p.StorageProfile.ImageReference.Offer $imgRef.Offer + Assert-AreEqual $p.StorageProfile.ImageReference.Publisher $imgRef.PublisherName + Assert-AreEqual $p.StorageProfile.ImageReference.Sku $imgRef.Skus + Assert-AreEqual $p.StorageProfile.ImageReference.Version $imgRef.Version # Virtual Machine - $v = New-AzVM -ResourceGroupName $rgname -Location $loc -VM $p; + $v = New-AzVM -ResourceGroupName $rgname -Location $loc -VM $p $vm = Get-AzVM -ResourceGroupName $rgname -VMName $vmname return $vm } # Cleans the created resource group -function Clean-ResourceGroup($rgname) -{ - Remove-AzResourceGroup -Name $rgname -Force; +function Clean-ResourceGroup($rgname) { + Remove-AzResourceGroup -Name $rgname -Force } # Get Compute Test Tag -function Get-ComputeTestTag -{ +function Get-ComputeTestTag { param ([string] $tagname) - return @{ Name = $tagname; Value = (Get-Date).ToUniversalTime().ToString("u") }; + return @{ Name = $tagname; Value = (Get-Date).ToUniversalTime().ToString("u") } } ###################### @@ -399,72 +402,64 @@ function Get-ComputeTestTag # param [int] $times : The times of running the code # param [string] $message : The text of the exception that should be thrown ####################### -function Retry-IfException -{ +function Retry-IfException { param([ScriptBlock] $script, [int] $times = 30, [string] $message = "*") - if ($times -le 0) - { - throw 'Retry time(s) should not be equal to or less than 0.'; + if ($times -le 0) { + throw 'Retry time(s) should not be equal to or less than 0.' } - $oldErrorActionPreferenceValue = $ErrorActionPreference; - $ErrorActionPreference = "SilentlyContinue"; + $oldErrorActionPreferenceValue = $ErrorActionPreference + $ErrorActionPreference = "SilentlyContinue" - $iter = 0; - $succeeded = $false; - while (($iter -lt $times) -and (-not $succeeded)) - { - $iter += 1; + $iter = 0 + $succeeded = $false + while (($iter -lt $times) -and (-not $succeeded)) { + $iter += 1 - &$script; + &$script - if ($Error.Count -gt 0) - { - $actualMessage = $Error[0].Exception.Message; + if ($Error.Count -gt 0) { + $actualMessage = $Error[0].Exception.Message - Write-Output ("Caught exception: '$actualMessage'"); + Write-Output ("Caught exception: '$actualMessage'") - if (-not ($actualMessage -like $message)) - { - $ErrorActionPreference = $oldErrorActionPreferenceValue; - throw "Expected exception not received: '$message' the actual message is '$actualMessage'"; + if (-not ($actualMessage -like $message)) { + $ErrorActionPreference = $oldErrorActionPreferenceValue + throw "Expected exception not received: '$message' the actual message is '$actualMessage'" } - $Error.Clear(); - Wait-Seconds 10; - continue; + $Error.Clear() + Wait-Seconds 10 + continue } - $succeeded = $true; + $succeeded = $true } - $ErrorActionPreference = $oldErrorActionPreferenceValue; + $ErrorActionPreference = $oldErrorActionPreferenceValue } <# .SYNOPSIS Gets random resource name #> -function Get-RandomItemName -{ +function Get-RandomItemName { param([string] $prefix = "crptestps") - - if ($prefix -eq $null -or $prefix -eq '') - { - $prefix = "crptestps"; + + if ($prefix -eq $null -or $prefix -eq '') { + $prefix = "crptestps" } - $str = $prefix + ((Get-Random) % 10000); - return $str; + $str = $prefix + ((Get-Random) % 10000) + return $str } <# .SYNOPSIS Gets default VM size string #> -function Get-DefaultVMSize -{ +function Get-DefaultVMSize { param([string] $location = "westus") $vmSizes = Get-AzComputeResourceSku -Location $location | Where-Object { $_.ResourceType -eq "virtualMachines" -and @@ -472,15 +467,13 @@ function Get-DefaultVMSize ([int]($_.Capabilities | Where-Object { $_.Name -eq "MaxDataDiskCount" }).Value) -ge 8 } - foreach ($sz in $vmSizes) - { - if ($sz.Name -eq 'Standard_A3') - { - return $sz.Name; + foreach ($sz in $vmSizes) { + if ($sz.Name -eq 'Standard_A3') { + return $sz.Name } } - return $vmSizes[0].Name; + return $vmSizes[0].Name } @@ -488,19 +481,16 @@ function Get-DefaultVMSize .SYNOPSIS Gets default RDFE Image #> -function Get-DefaultRDFEImage -{ +function Get-DefaultRDFEImage { param([string] $loca = "East Asia", [string] $query = '*Windows*Data*Center*') - $d = (Azure\Get-AzVMImage | where {$_.ImageName -like $query -and ($_.Location -like "*;$loca;*" -or $_.Location -like "$loca;*" -or $_.Location -like "*;$loca" -or $_.Location -eq "$loca")}); + $d = (Azure\Get-AzVMImage | where { $_.ImageName -like $query -and ($_.Location -like "*;$loca;*" -or $_.Location -like "$loca;*" -or $_.Location -like "*;$loca" -or $_.Location -eq "$loca") }) - if ($d -eq $null) - { - return $null; + if ($d -eq $null) { + return $null } - else - { - return $d[-1].ImageName; + else { + return $d[-1].ImageName } } @@ -508,115 +498,99 @@ function Get-DefaultRDFEImage .SYNOPSIS Gets default storage type string #> -function Get-DefaultStorageType -{ - return 'Standard_GRS'; +function Get-DefaultStorageType { + return 'Standard_GRS' } <# .SYNOPSIS Gets default CRP Image #> -function Get-DefaultCRPImage -{ +function Get-DefaultCRPImage { param([string] $loc = "westus", [string] $query = '*Microsoft*Windows*Server*', [bool] $New = $False) - $result = (Get-AzVMImagePublisher -Location $loc) | select -ExpandProperty PublisherName | where { $_ -like $query }; - if ($result.Count -eq 1) - { - $defaultPublisher = $result; + $result = (Get-AzVMImagePublisher -Location $loc) | select -ExpandProperty PublisherName | where { $_ -like $query } + if ($result.Count -eq 1) { + $defaultPublisher = $result } - else - { - $defaultPublisher = $result[0]; + else { + $defaultPublisher = $result[0] } - $result = (Get-AzVMImageOffer -Location $loc -PublisherName $defaultPublisher) | select -ExpandProperty Offer | where { $_ -like '*WindowsServer*' -and -not ($_ -like '*HUB') }; - if ($result.Count -eq 1) - { - $defaultOffer = $result; + $result = (Get-AzVMImageOffer -Location $loc -PublisherName $defaultPublisher) | select -ExpandProperty Offer | where { $_ -like '*WindowsServer*' -and -not ($_ -like '*HUB') } + if ($result.Count -eq 1) { + $defaultOffer = $result } - else - { - $defaultOffer = $result[0]; + else { + $defaultOffer = $result[0] } - if ($New -eq $True){ - $result = (Get-AzVMImageSku -Location $loc -PublisherName $defaultPublisher -Offer $defaultOffer) | select -ExpandProperty Skus| where { $_ -like '*2022-datacenter*'}; + if ($New -eq $True) { + $result = (Get-AzVMImageSku -Location $loc -PublisherName $defaultPublisher -Offer $defaultOffer) | select -ExpandProperty Skus | where { $_ -like '*2022-datacenter*' } } else { - $result = (Get-AzVMImageSku -Location $loc -PublisherName $defaultPublisher -Offer $defaultOffer) | select -ExpandProperty Skus; + $result = (Get-AzVMImageSku -Location $loc -PublisherName $defaultPublisher -Offer $defaultOffer) | select -ExpandProperty Skus } - if ($result.Count -eq 1) - { - $defaultSku = $result; + if ($result.Count -eq 1) { + $defaultSku = $result } - else - { - $defaultSku = $result[0]; + else { + $defaultSku = $result[0] } - $result = (Get-AzVMImage -Location $loc -Offer $defaultOffer -PublisherName $defaultPublisher -Skus $defaultSku) | select -ExpandProperty Version; - if ($result.Count -eq 1) - { - $defaultVersion = $result; + $result = (Get-AzVMImage -Location $loc -Offer $defaultOffer -PublisherName $defaultPublisher -Skus $defaultSku) | select -ExpandProperty Version + if ($result.Count -eq 1) { + $defaultVersion = $result } - else - { - $defaultVersion = $result[0]; + else { + $defaultVersion = $result[0] } - - $vmimg = Get-AzVMImage -Location $loc -Offer $defaultOffer -PublisherName $defaultPublisher -Skus $defaultSku -Version $defaultVersion; + $vmimg = Get-AzVMImage -Location $loc -Offer $defaultOffer -PublisherName $defaultPublisher -Skus $defaultSku -Version $defaultVersion - return $vmimg; + + return $vmimg } # Create Image Object -function Create-ComputeVMImageObject -{ +function Create-ComputeVMImageObject { param ([string] $publisherName, [string] $offer, [string] $skus, [string] $version) - $img = New-Object -TypeName 'Microsoft.Azure.Commands.Compute.Models.PSVirtualMachineImage'; - $img.PublisherName = $publisherName; - $img.Offer = $offer; - $img.Skus = $skus; - $img.Version = $version; + $img = New-Object -TypeName 'Microsoft.Azure.Commands.Compute.Models.PSVirtualMachineImage' + $img.PublisherName = $publisherName + $img.Offer = $offer + $img.Skus = $skus + $img.Version = $version - return $img; + return $img } # Get Default CRP Windows Image Object Offline -function Get-DefaultCRPWindowsImageOffline -{ - return Create-ComputeVMImageObject 'MicrosoftWindowsServer' 'WindowsServer' '2008-R2-SP1' 'latest'; +function Get-DefaultCRPWindowsImageOffline { + return Create-ComputeVMImageObject 'MicrosoftWindowsServer' 'WindowsServer' '2008-R2-SP1' 'latest' } # Get Default CRP Linux Image Object Offline -function Get-DefaultCRPLinuxImageOffline -{ - return Create-ComputeVMImageObject 'SUSE' 'openSUSE-Leap' '42.3' 'latest'; +function Get-DefaultCRPLinuxImageOffline { + return Create-ComputeVMImageObject 'SUSE' 'openSUSE-Leap' '42.3' 'latest' } <# .SYNOPSIS Gets VMM Images #> -function Get-MarketplaceImage -{ +function Get-MarketplaceImage { param([string] $location = "westus", [string] $pubFilter = '*', [string] $offerFilter = '*') - $imgs = Get-AzVMImagePublisher -Location $location | where { $_.PublisherName -like $pubFilter } | Get-AzVMImageOffer | where { $_.Offer -like $offerFilter } | Get-AzVMImageSku | Get-AzVMImage | Get-AzVMImage | where { $_.PurchasePlan -ne $null }; + $imgs = Get-AzVMImagePublisher -Location $location | where { $_.PublisherName -like $pubFilter } | Get-AzVMImageOffer | where { $_.Offer -like $offerFilter } | Get-AzVMImageSku | Get-AzVMImage | Get-AzVMImage | where { $_.PurchasePlan -ne $null } - return $imgs; + return $imgs } -function Get-FirstMarketPlaceImage -{ - $img = Get-AzVMImagePublisher -Location westus | where { $_.PublisherName -eq "1e" } | Get-AzVMImageOffer | Get-AzVMImageSku | Get-AzVMImage | Get-AzVMImage | where {$_.PurchasePlan -ne $null } - - if ($img -eq $null) - { +function Get-FirstMarketPlaceImage { + $img = Get-AzVMImagePublisher -Location westus | where { $_.PublisherName -eq "1e" } | Get-AzVMImageOffer | Get-AzVMImageSku | Get-AzVMImage | Get-AzVMImage | where { $_.PurchasePlan -ne $null } + + if ($img -eq $null) { $img = Get-MarketplaceImage[0] } @@ -627,153 +601,131 @@ function Get-FirstMarketPlaceImage .SYNOPSIS Gets default VM config object #> -function Get-DefaultVMConfig -{ +function Get-DefaultVMConfig { param([string] $location = "westus") # VM Profile & Hardware - $vmsize = Get-DefaultVMSize $location; - $vmname = Get-RandomItemName 'crptestps'; + $vmsize = Get-DefaultVMSize $location + $vmname = Get-RandomItemName 'crptestps' - $vm = New-AzVMConfig -VMName $vmname -VMSize $vmsize; + $vm = New-AzVMConfig -VMName $vmname -VMSize $vmsize - return $vm; + return $vm } # Assert Output Contains -function Assert-OutputContains -{ - param([string] $cmd, [string[]] $sstr) - - $st = Write-Verbose ('Running Command : ' + $cmd); - $output = Invoke-Expression $cmd | Out-String; - - $max_output_len = 1500; - if ($output.Length -gt $max_output_len) - { +function Assert-OutputContains { + param([ScriptBlock] $cmd, [string[]] $sstr) + + $st = Write-Verbose ('Running Command : ' + $cmd.ToString()) + $output = & $cmd | Out-String + + $max_output_len = 1500 + if ($output.Length -gt $max_output_len) { # Truncate Long Output in Logs - $st = Write-Verbose ('Output String : ' + $output.Substring(0, $max_output_len) + '...'); + $st = Write-Verbose ('Output String : ' + $output.Substring(0, $max_output_len) + '...') } - else - { - $st = Write-Verbose ('Output String : ' + $output); + else { + $st = Write-Verbose ('Output String : ' + $output) } - $index = 1; + $index = 1 - try - { - foreach ($str in $sstr) - { - $st = Write-Verbose ('Search String ' + $index++ + " : `'" + $str + "`'"); + try { + foreach ($str in $sstr) { + $st = Write-Verbose ('Search String ' + $index++ + " : `'" + $str + "`'") Assert-True { $output.Contains($str) } - $st = Write-Verbose "Found."; + $st = Write-Verbose "Found." } } - catch - { - Write-Verbose ("output: " + $output); - Write-Verbose ("str: " + $str); - throw; + catch { + Write-Verbose ("output: " + $output) + Write-Verbose ("str: " + $str) + throw } } # Create a SAS Uri -function Get-SasUri -{ +function Get-SasUri { param ([string] $storageAccount, [string] $storageKey, [string] $container, [string] $file, [TimeSpan] $duration, [Microsoft.WindowsAzure.Storage.Blob.SharedAccessBlobPermissions] $type) - $uri = [string]::Format("https://{0}.blob.core.windows.net/{1}/{2}", $storageAccount, $container, $file); + $uri = [string]::Format("https://{0}.blob.core.windows.net/{1}/{2}", $storageAccount, $container, $file) - $destUri = New-Object -TypeName System.Uri($uri); - $cred = New-Object -TypeName Microsoft.WindowsAzure.Storage.Auth.StorageCredentials($storageAccount, $storageKey); - $destBlob = New-Object -TypeName Microsoft.WindowsAzure.Storage.Blob.CloudPageBlob($destUri, $cred); - $policy = New-Object Microsoft.WindowsAzure.Storage.Blob.SharedAccessBlobPolicy; - $policy.Permissions = $type; - $policy.SharedAccessExpiryTime = [DateTime]::UtcNow.Add($duration); - $uri += $destBlob.GetSharedAccessSignature($policy); + $destUri = New-Object -TypeName System.Uri($uri) + $cred = New-Object -TypeName Microsoft.WindowsAzure.Storage.Auth.StorageCredentials($storageAccount, $storageKey) + $destBlob = New-Object -TypeName Microsoft.WindowsAzure.Storage.Blob.CloudPageBlob($destUri, $cred) + $policy = New-Object Microsoft.WindowsAzure.Storage.Blob.SharedAccessBlobPolicy + $policy.Permissions = $type + $policy.SharedAccessExpiryTime = [DateTime]::UtcNow.Add($duration) + $uri += $destBlob.GetSharedAccessSignature($policy) - return $uri; + return $uri } # Get a Location according to resource provider. -function Get-ResourceProviderLocation -{ +function Get-ResourceProviderLocation { param ([string] $provider) - $namespace = $provider.Split("/")[0]; - if($provider.Contains("/")) - { - $type = $provider.Substring($namespace.Length + 1); - $location = Get-AzResourceProvider -ProviderNamespace $namespace | where {$_.ResourceTypes[0].ResourceTypeName -eq $type}; - - if ($location -eq $null) - { - return "westus"; + $namespace = $provider.Split("/")[0] + if ($provider.Contains("/")) { + $type = $provider.Substring($namespace.Length + 1) + $location = Get-AzResourceProvider -ProviderNamespace $namespace | where { $_.ResourceTypes[0].ResourceTypeName -eq $type } + + if ($location -eq $null) { + return "westus" } - else - { - return $location.Locations[0]; + else { + return $location.Locations[0] } } - return "westus"; + return "westus" } -function Get-ComputeVMLocation -{ - $result = Get-Location "Microsoft.Compute" "virtualMachines" "East US"; - $result = $result.Replace(' ', ''); +function Get-ComputeVMLocation { + $result = Get-Location "Microsoft.Compute" "virtualMachines" "East US" + $result = $result.Replace(' ', '') return $result } -function Get-ComputeAvailabilitySetLocation -{ - Get-Location "Microsoft.Compute" "availabilitySets" "West US"; +function Get-ComputeAvailabilitySetLocation { + Get-Location "Microsoft.Compute" "availabilitySets" "West US" } -function Get-ComputeVMExtensionLocation -{ - Get-Location "Microsoft.Compute" "virtualMachines/extensions" "West US"; +function Get-ComputeVMExtensionLocation { + Get-Location "Microsoft.Compute" "virtualMachines/extensions" "West US" } -function Get-ComputeVMDiagnosticSettingLocation -{ - Get-Location "Microsoft.Compute" "virtualMachines/diagnosticSettings" "West US"; +function Get-ComputeVMDiagnosticSettingLocation { + Get-Location "Microsoft.Compute" "virtualMachines/diagnosticSettings" "West US" } -function Get-ComputeVMMetricDefinitionLocation -{ - Get-Location "Microsoft.Compute" "virtualMachines/metricDefinitions" "West US"; +function Get-ComputeVMMetricDefinitionLocation { + Get-Location "Microsoft.Compute" "virtualMachines/metricDefinitions" "West US" } -function Get-ComputeOperationLocation -{ - Get-Location "Microsoft.Compute" "locations/operations" "West US"; +function Get-ComputeOperationLocation { + Get-Location "Microsoft.Compute" "locations/operations" "West US" } -function Get-ComputeVMSizeLocation -{ - Get-Location "Microsoft.Compute" "locations/vmSizes" "West US"; +function Get-ComputeVMSizeLocation { + Get-Location "Microsoft.Compute" "locations/vmSizes" "West US" } -function Get-ComputeUsageLocation -{ - Get-Location "Microsoft.Compute" "locations/usages" "West US"; +function Get-ComputeUsageLocation { + Get-Location "Microsoft.Compute" "locations/usages" "West US" } -function Get-ComputePublisherLocation -{ - Get-Location "Microsoft.Compute" "locations/publishers" "West US"; +function Get-ComputePublisherLocation { + Get-Location "Microsoft.Compute" "locations/publishers" "West US" } -function Get-SubscriptionIdFromResourceGroup -{ +function Get-SubscriptionIdFromResourceGroup { param ([string] $rgname) - $rg = Get-AzResourceGroup -ResourceGroupName $rgname; + $rg = Get-AzResourceGroup -ResourceGroupName $rgname - $rgid = $rg.ResourceId; + $rgid = $rg.ResourceId if ([string]::IsNullOrEmpty($rgid)) { #Get the subscription from the current context @@ -783,53 +735,50 @@ function Get-SubscriptionIdFromResourceGroup # ResouceId is a form of "/subscriptions//resourceGroups/" # So return the second part to get subscription Id - $first = $rgid.IndexOf('/', 1); - $last = $rgid.IndexOf('/', $first + 1); - return $rgid.Substring($first + 1, $last - $first - 1); + $first = $rgid.IndexOf('/', 1) + $last = $rgid.IndexOf('/', $first + 1) + return $rgid.Substring($first + 1, $last - $first - 1) } -function Get-ComputeVmssLocation -{ +function Get-ComputeVmssLocation { Get-ResourceProviderLocation "Microsoft.Compute/virtualMachineScaleSets" } -function Verify-PSComputeLongRunningOperation -{ +function Verify-PSComputeLongRunningOperation { param ($result) - Assert-NotNull $result; - $id = New-Object System.Guid; - Assert-True { [System.Guid]::TryParse($result.OperationId, [REF] $id) }; - Assert-AreEqual "Succeeded" $result.Status; - Assert-NotNull $result.StartTime; - Assert-NotNull $result.EndTime; - Assert-Null $result.Error; + Assert-NotNull $result + $id = New-Object System.Guid + Assert-True { [System.Guid]::TryParse($result.OperationId, [REF] $id) } + Assert-AreEqual "Succeeded" $result.Status + Assert-NotNull $result.StartTime + Assert-NotNull $result.EndTime + Assert-Null $result.Error } -function Verify-PSOperationStatusResponse -{ +function Verify-PSOperationStatusResponse { param ($result) - Assert-NotNull $result; - $id = New-Object System.Guid; - Assert-True { [System.Guid]::TryParse($result.Name, [REF] $id) }; - Assert-AreEqual "Succeeded" $result.Status; - Assert-NotNull $result.StartTime; - Assert-NotNull $result.EndTime; - Assert-Null $result.Error; + Assert-NotNull $result + $id = New-Object System.Guid + Assert-True { [System.Guid]::TryParse($result.Name, [REF] $id) } + Assert-AreEqual "Succeeded" $result.Status + Assert-NotNull $result.StartTime + Assert-NotNull $result.EndTime + Assert-Null $result.Error } function Get-VMImageVersion { - param([string] $publisher, [string] $offer, [string] $sku, [string] $location) + param([string] $publisher, [string] $offer, [string] $sku, [string] $location) - if ([string]::IsNullOrEmpty($location)) { - $location = "East US" - } + if ([string]::IsNullOrEmpty($location)) { + $location = "East US" + } - return (Get-AzVMImage -PublisherName $publisher ` - -Location $location ` - -Offer $offer ` - -Skus $sku | Sort-Object -Descending Version | select -First 1).Version + return (Get-AzVMImage -PublisherName $publisher ` + -Location $location ` + -Offer $offer ` + -Skus $sku | Sort-Object -Descending Version | select -First 1).Version } @@ -837,14 +786,13 @@ function Get-VMImageVersion { .SYNOPSIS Gets a sku that is available for the location, subscription, and resourceType #> -function Get-AvailableSku -{ +function Get-AvailableSku { param([string] $location, [string] $resourceType) $res = get-azcomputeresourcesku $location | where-object ResourceType -match $resourceType - $res = $res.where({$_.restrictions.count -eq 0}) - if ($resourceType -match "virtualmachine"){ - $res = $res.where({$_.Name -notmatch "Standard_B"}) + $res = $res.where({ $_.restrictions.count -eq 0 }) + if ($resourceType -match "virtualmachine") { + $res = $res.where({ $_.Name -notmatch "Standard_B" }) } return $res[0].Name } diff --git a/src/Compute/Compute.Test/ScenarioTests/VirtualMachineTests.ps1 b/src/Compute/Compute.Test/ScenarioTests/VirtualMachineTests.ps1 index 0c444929b1d6..927b5bae7a40 100644 --- a/src/Compute/Compute.Test/ScenarioTests/VirtualMachineTests.ps1 +++ b/src/Compute/Compute.Test/ScenarioTests/VirtualMachineTests.ps1 @@ -2129,20 +2129,20 @@ function Test-VMImageCmdletOutputFormat $sku = $imgRef.Skus; $ver = $imgRef.Version; - Assert-OutputContains " Get-AzVMImagePublisher -Location '$locStr'" @('Id', 'Location', 'PublisherName'); + Assert-OutputContains { Get-AzVMImagePublisher -Location $locStr } @('Id', 'Location', 'PublisherName'); - Assert-OutputContains " Get-AzVMImagePublisher -Location '$locStr' | ? { `$_.PublisherName -eq `'$publisher`' } " @('Id', 'Location', 'PublisherName'); + Assert-OutputContains { Get-AzVMImagePublisher -Location $locStr | ? { $_.PublisherName -eq $publisher } } @('Id', 'Location', 'PublisherName'); - Assert-OutputContains " Get-AzVMImagePublisher -Location '$locStr' | ? { `$_.PublisherName -eq `'$publisher`' } | Get-AzVMImageOffer " @('Id', 'Location', 'PublisherName', 'Offer'); + Assert-OutputContains { Get-AzVMImagePublisher -Location $locStr | ? { $_.PublisherName -eq $publisher } | Get-AzVMImageOffer } @('Id', 'Location', 'PublisherName', 'Offer'); - Assert-OutputContains " Get-AzVMImagePublisher -Location '$locStr' | ? { `$_.PublisherName -eq `'$publisher`' } | Get-AzVMImageOffer | Get-AzVMImageSku " @('Publisher', 'Offer', 'Skus'); + Assert-OutputContains { Get-AzVMImagePublisher -Location $locStr | ? { $_.PublisherName -eq $publisher } | Get-AzVMImageOffer | Get-AzVMImageSku } @('Publisher', 'Offer', 'Skus'); # Updated Get-AzVmImage list output. No need to output sku when user inputed that. There are more valuable information to display. - Assert-OutputContains " Get-AzVMImagePublisher -Location '$locStr' | ? { `$_.PublisherName -eq `'$publisher`' } | Get-AzVMImageOffer | Get-AzVMImageSku | Get-AzVMImage " @('Version', 'Location'); + Assert-OutputContains { Get-AzVMImagePublisher -Location $locStr | ? { $_.PublisherName -eq $publisher } | Get-AzVMImageOffer | Get-AzVMImageSku | Get-AzVMImage } @('Version', 'Location'); - Assert-OutputContains " Get-AzVMImage -Location '$locStr' -PublisherName $publisher -Offer $offer -Skus $sku -Version $ver " @('Id', 'Location', 'PublisherName', 'Offer', 'Sku', 'Version', 'Name', 'DataDiskImages', 'OSDiskImage', 'PurchasePlan'); + Assert-OutputContains { Get-AzVMImage -Location $locStr -PublisherName $publisher -Offer $offer -Skus $sku -Version $ver } @('Id', 'Location', 'PublisherName', 'Offer', 'Sku', 'Version', 'Name', 'DataDiskImages', 'OSDiskImage', 'PurchasePlan'); - Assert-OutputContains " Get-AzVMImage -Location '$locStr' -PublisherName $publisher -Offer $offer -Skus $sku -Version $ver " @('Id', 'Location', 'PublisherName', 'Offer', 'Sku', 'Version', 'Name', 'DataDiskImages', 'OSDiskImage', 'PurchasePlan'); + Assert-OutputContains { Get-AzVMImage -Location $locStr -PublisherName $publisher -Offer $offer -Skus $sku -Version $ver } @('Id', 'Location', 'PublisherName', 'Offer', 'Sku', 'Version', 'Name', 'DataDiskImages', 'OSDiskImage', 'PurchasePlan'); } # Test Image Cmdlet Output Format with EdgeZone @@ -2159,15 +2159,15 @@ function Test-VMImageEdgeZoneCmdletOutputFormat $ver = "14393.4048.2011170655"; $edgeZone = "microsoftlosangeles1"; - Assert-OutputContains " Get-AzVMImagePublisher -Location '$locStr' | ? { `$_.PublisherName -eq `'$publisher`' } | Get-AzVMImageOffer -EdgeZone '$edgeZone' | Select EdgeZone, Location " @('microsoftlosangeles1', 'westus'); + Assert-OutputContains { Get-AzVMImagePublisher -Location $locStr | ? { $_.PublisherName -eq $publisher } | Get-AzVMImageOffer -EdgeZone $edgeZone | Select EdgeZone, Location } @('microsoftlosangeles1', 'westus'); - Assert-OutputContains " Get-AzVMImagePublisher -Location '$locStr' | ? { `$_.PublisherName -eq `'$publisher`' } | Get-AzVMImageOffer -EdgeZone '$edgeZone'| Get-AzVMImageSku " @('Publisher', 'Offer', 'Skus'); + Assert-OutputContains { Get-AzVMImagePublisher -Location $locStr | ? { $_.PublisherName -eq $publisher } | Get-AzVMImageOffer -EdgeZone $edgeZone | Get-AzVMImageSku } @('Publisher', 'Offer', 'Skus'); - Assert-OutputContains " Get-AzVMImagePublisher -Location '$locStr' | ? { `$_.PublisherName -eq `'$publisher`' } | Get-AzVMImageOffer -EdgeZone '$edgeZone' | Get-AzVMImageSku | Get-AzVMImage " @('Version', 'Location'); + Assert-OutputContains { Get-AzVMImagePublisher -Location $locStr | ? { $_.PublisherName -eq $publisher } | Get-AzVMImageOffer -EdgeZone $edgeZone | Get-AzVMImageSku | Get-AzVMImage } @('Version', 'Location'); - Assert-OutputContains " Get-AzVMImage -Location '$locStr' -EdgeZone '$edgeZone' -PublisherName $publisher -Offer $offer -Skus $sku -Version $ver " @('Id', 'Location', 'PublisherName', 'Offer', 'Sku', 'Version', 'Name', 'DataDiskImages', 'OSDiskImage', 'PurchasePlan'); + Assert-OutputContains { Get-AzVMImage -Location $locStr -EdgeZone $edgeZone -PublisherName $publisher -Offer $offer -Skus $sku -Version $ver } @('Id', 'Location', 'PublisherName', 'Offer', 'Sku', 'Version', 'Name', 'DataDiskImages', 'OSDiskImage', 'PurchasePlan'); - Assert-OutputContains " Get-AzVMImage -Location '$locStr' -EdgeZone '$edgeZone' -PublisherName $publisher -Offer $offer -Skus $sku -Version $ver " @('Id', 'Location', 'PublisherName', 'Offer', 'Sku', 'Version', 'Name', 'DataDiskImages', 'OSDiskImage', 'PurchasePlan'); + Assert-OutputContains { Get-AzVMImage -Location $locStr -EdgeZone $edgeZone -PublisherName $publisher -Offer $offer -Skus $sku -Version $ver } @('Id', 'Location', 'PublisherName', 'Offer', 'Sku', 'Version', 'Name', 'DataDiskImages', 'OSDiskImage', 'PurchasePlan'); } function get_all_vm_locations diff --git a/src/Resources/Resources.Test/ScenarioTests/RoleDefinitionTests.ps1 b/src/Resources/Resources.Test/ScenarioTests/RoleDefinitionTests.ps1 index bd492c26aa69..366b193ce68d 100644 --- a/src/Resources/Resources.Test/ScenarioTests/RoleDefinitionTests.ps1 +++ b/src/Resources/Resources.Test/ScenarioTests/RoleDefinitionTests.ps1 @@ -16,8 +16,7 @@ .SYNOPSIS Tests verify scenarios for RoleDefinitions creation. #> -function Test-RDWithAbacConditionsGet -{ +function Test-RDWithAbacConditionsGet { # Setup $subscription = $(Get-AzContext).Subscription @@ -61,12 +60,11 @@ function Test-RDWithAbacConditionsGet .SYNOPSIS Tests verify scenarios for RoleDefinitions creation. #> -function Test-RoleDefinitionCreateTests -{ +function Test-RoleDefinitionCreateTests { # Setup # Basic positive case - read from file $rdName = 'CustomRole Tests Role' - $inputFilePath = Join-Path -Path $TestOutputRoot -ChildPath Resources\NewRoleDefinition.json + $inputFilePath = Join-Path -Path $TestOutputRoot -ChildPath Resources\NewRoleDefinition.json New-AzRoleDefinitionWithId -InputFile $inputFilePath -RoleDefinitionId ee78fa8a-3cdd-418e-a4d8-949b57a33dcd $rd = Get-AzRoleDefinition -Name $rdName @@ -103,8 +101,7 @@ function Test-RoleDefinitionCreateTests .SYNOPSIS Tests verify negative scenarios for RoleDefinitions #> -function Test-RdNegativeScenarios -{ +function Test-RdNegativeScenarios { # Setup # Does not throw when getting a non-existing role assignment $rdName = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' @@ -117,7 +114,7 @@ function Test-RdNegativeScenarios # Throws on trying to update the a role that does not exist $inputFilePath = Join-Path -Path $TestOutputRoot -ChildPath Resources\RoleDefinition.json - Assert-Throws { Set-AzRoleDefinition -InputFile $inputFilePath } $badIdException + Assert-Throws { Set-AzRoleDefinition -InputFile $inputFilePath } $badIdException # Role Defintion not provided. $roleDefNotProvided = "Parameter set cannot be resolved using the specified named parameters." @@ -138,19 +135,18 @@ function Test-RdNegativeScenarios $removeRoleException = "The specified role definition with ID '" + $rdId + "' does not exist." # Throws on trying to delete a role that does not exist $missingSubscription = "MissingSubscription: The request did not have a provided subscription. All requests must have an associated subscription Id." - Assert-Throws { Remove-AzRoleDefinition -Id $rdId -Force} $removeRoleException + Assert-Throws { Remove-AzRoleDefinition -Id $rdId -Force } $removeRoleException } <# .SYNOPSIS Tests verify positive scenarios for RoleDefinitions. #> -function Test-RDPositiveScenarios -{ +function Test-RDPositiveScenarios { # Setup # Create a role definition with Name rdNamme. $rdName = 'Another tests role' - $inputFilePath = Join-Path -Path $TestOutputRoot -ChildPath Resources\RoleDefinition.json + $inputFilePath = Join-Path -Path $TestOutputRoot -ChildPath Resources\RoleDefinition.json $rd = New-AzRoleDefinitionWithId -InputFile $inputFilePath -RoleDefinitionId 0a0e83bc-50b9-4c4d-b2c2-3f41e1a8baf2 $rd = Get-AzRoleDefinition -Name $rdName @@ -172,12 +168,11 @@ function Test-RDPositiveScenarios .SYNOPSIS Tests verify roledefinition update with interchanged assignablescopes. #> -function Test-RDUpdate -{ +function Test-RDUpdate { # Create a role definition with Name rdNamme. $rdName = 'Another tests role' - $inputFilePath = Join-Path -Path $TestOutputRoot -ChildPath Resources\RoleDefinition.json + $inputFilePath = Join-Path -Path $TestOutputRoot -ChildPath Resources\RoleDefinition.json $rd = New-AzRoleDefinitionWithId -InputFile $inputFilePath -RoleDefinitionId 3d95b97a-5745-4c39-950c-0b608dea635f $rd = Get-AzRoleDefinition -Name $rdName @@ -185,7 +180,7 @@ function Test-RDUpdate $scopes = $rd.AssignableScopes | foreach { $_ } $rd.AssignableScopes.Clear() $rd.AssignableScopes.Add('/subscriptions/0b1f6471-1bf0-4dda-aec3-cb9272f09590/resourcegroups/rbactest') - for($i = $scopes.Count - 1 ; $i -ge 0; $i--){ + for ($i = $scopes.Count - 1 ; $i -ge 0; $i--) { $rd.AssignableScopes.Add($scopes[$i]) } $updatedRd = Set-AzRoleDefinition -Role $rd @@ -200,29 +195,25 @@ function Test-RDUpdate .SYNOPSIS Tests verify roledefinition create with invalid scope. #> -function Test-RDCreateFromFile -{ +function Test-RDCreateFromFile { # Setup # Create a role definition with invalid assignable scopes. $badScopeException = "Exception calling `"ExecuteCmdlet`" with `"0`" argument(s): `"Scope '/subscriptions/4004a9fd-d58e-48dc-aeb2-4a4aec58606f/ResourceGroups' should have even number of parts.`"" - try - { - $inputFilePath = Join-Path -Path $TestOutputRoot -ChildPath Resources\InvalidRoleDefinition.json - $rd = New-AzRoleDefinitionWithId -InputFile $inputFilePath -RoleDefinitionId 4482e4d1-8757-4d67-b3c1-5c8ccee3fdcc - Assert-AreEqual "This assertion shouldn't be hit'" "New-AzRoleDefinition should've thrown an exception" - } - catch - { - Assert-AreEqual $badScopeException $_ - } + try { + $inputFilePath = Join-Path -Path $TestOutputRoot -ChildPath Resources\InvalidRoleDefinition.json + $rd = New-AzRoleDefinitionWithId -InputFile $inputFilePath -RoleDefinitionId 4482e4d1-8757-4d67-b3c1-5c8ccee3fdcc + Assert-AreEqual "This assertion shouldn't be hit'" "New-AzRoleDefinition should've thrown an exception" + } + catch { + Assert-AreEqual $badScopeException $_ + } } <# .SYNOPSIS Verify positive and negative scenarios for RoleDefinition remove. #> -function Test-RDRemove -{ +function Test-RDRemove { # Setup # Create a role definition at RG Scope. @@ -243,11 +234,11 @@ function Test-RDRemove # try to delete the role definition with subscription scope - should fail $badIdException = "RoleDefinitionDoesNotExist: The specified role definition with ID '" + $Rd.Id + "' does not exist." - Assert-Throws { Remove-AzRoleDefinition -Id $Rd.Id -Scope $scope -Force -PassThru} $badIdException + Assert-Throws { Remove-AzRoleDefinition -Id $Rd.Id -Scope $scope -Force -PassThru } $badIdException # try to delete the role definition without specifying scope (default to subscription scope) - should fail $badIdException = "RoleDefinitionDoesNotExist: The specified role definition with ID '" + $Rd.Id + "' does not exist." - Assert-Throws { Remove-AzRoleDefinition -Id $Rd.Id -Scope $scope -Force -PassThru} $badIdException + Assert-Throws { Remove-AzRoleDefinition -Id $Rd.Id -Scope $scope -Force -PassThru } $badIdException # try to delete the role definition with RG scope - should succeed $deletedRd = Remove-AzRoleDefinition -Id $Rd.Id -Scope $rgScope -Force -PassThru @@ -258,8 +249,7 @@ function Test-RDRemove .SYNOPSIS Verify positive and negative scenarios for RoleDefinition Get. #> -function Test-RDGet -{ +function Test-RDGet { # Setup $subscription = $(Get-AzContext).Subscription @@ -325,12 +315,11 @@ function Test-RDGet .SYNOPSIS Tests verify scenarios for RoleDefinitions creation. #> -function Test-RoleDefinitionDataActionsCreateTests -{ +function Test-RoleDefinitionDataActionsCreateTests { # Setup # Basic positive case - read from file $rdName = 'CustomRole Tests Role New' - $inputFilePath = Join-Path -Path $TestOutputRoot -ChildPath Resources\DataActionsRoleDefinition.json + $inputFilePath = Join-Path -Path $TestOutputRoot -ChildPath Resources\DataActionsRoleDefinition.json New-AzRoleDefinitionWithId -InputFile $inputFilePath -RoleDefinitionId e3efe8c9-d9ae-4f0e-838d-57ce43068a13 $rd = Get-AzRoleDefinition -Name $rdName @@ -368,18 +357,17 @@ function Test-RoleDefinitionDataActionsCreateTests .SYNOPSIS Tests verify scenarios for RoleDefinitions creation. #> -function Test-RDGetCustomRoles -{ +function Test-RDGetCustomRoles { # Setup # Basic positive case - read from file $rdName = 'Another tests role' - $inputFilePath = Join-Path -Path $TestOutputRoot -ChildPath Resources\RoleDefinition.json + $inputFilePath = Join-Path -Path $TestOutputRoot -ChildPath Resources\RoleDefinition.json $rd = New-AzRoleDefinitionWithId -InputFile $inputFilePath -RoleDefinitionId 3d95b97a-5745-4c39-950c-0b608dea635f $rd = Get-AzRoleDefinition -Name $rdName $roles = Get-AzRoleDefinition -Custom Assert-NotNull $roles - foreach($roleDefinition in $roles){ + foreach ($roleDefinition in $roles) { Assert-AreEqual $roleDefinition.IsCustom $true } @@ -391,8 +379,7 @@ function Test-RDGetCustomRoles .SYNOPSIS Tests validate input parameters #> -function Test-RdValidateInputParameters ($cmdName) -{ +function Test-RdValidateInputParameters ($cmdName) { # Setup # Note: All below scenarios are invalid, we'll expect an exception during scope validation so the ID parameter doesn't need to be a valid one. @@ -400,23 +387,23 @@ function Test-RdValidateInputParameters ($cmdName) # Check if Scope is valid. $scope = "/subscriptions/e9ee799d-6ab2-4084-b952-e7c86344bbab/Should be 'ResourceGroups'/any group name" $invalidScope = "Scope '/subscriptions/e9ee799d-6ab2-4084-b952-e7c86344bbab/Should be 'ResourceGroups'/any group name' should begin with '/subscriptions//resourceGroups'." - Assert-Throws { invoke-expression ($cmdName + " -Scope `"" + $scope + "`" -Id D46245F8-7E18-4499-8E1F-784A6DA5BE25") } $invalidScope + Assert-Throws { &$cmdName -Scope $scope -Id D46245F8-7E18-4499-8E1F-784A6DA5BE25 } $invalidScope $scope = "/subscriptions/e9ee799d-6ab2-4084-b952-e7c86344bbab/ResourceGroups" $invalidScope = "Scope '/subscriptions/e9ee799d-6ab2-4084-b952-e7c86344bbab/ResourceGroups' should have even number of parts." - Assert-Throws { &$cmdName -Scope $scope -Id D46245F8-7E18-4499-8E1F-784A6DA5BE25} $invalidScope + Assert-Throws { &$cmdName -Scope $scope -Id D46245F8-7E18-4499-8E1F-784A6DA5BE25 } $invalidScope $scope = "/subscriptions/e9ee799d-6ab2-4084-b952-e7c86344bbab/ResourceGroups/" $invalidScope = "Scope '/subscriptions/e9ee799d-6ab2-4084-b952-e7c86344bbab/ResourceGroups' should have even number of parts." - Assert-Throws { &$cmdName -Scope $scope -Id D46245F8-7E18-4499-8E1F-784A6DA5BE25} $invalidScope + Assert-Throws { &$cmdName -Scope $scope -Id D46245F8-7E18-4499-8E1F-784A6DA5BE25 } $invalidScope $scope = "/subscriptions/e9ee799d-6ab2-4084-b952-e7c86344bbab/ResourceGroups/groupname/Should be 'Providers'/any provider name" $invalidScope = "Scope '/subscriptions/e9ee799d-6ab2-4084-b952-e7c86344bbab/ResourceGroups/groupname/Should be 'Providers'/any provider name' should begin with '/subscriptions//resourceGroups//providers'." - Assert-Throws { &$cmdName -Scope $scope -Id D46245F8-7E18-4499-8E1F-784A6DA5BE25} $invalidScope + Assert-Throws { &$cmdName -Scope $scope -Id D46245F8-7E18-4499-8E1F-784A6DA5BE25 } $invalidScope $scope = "/subscriptions/e9ee799d-6ab2-4084-b952-e7c86344bbab/ResourceGroups/groupname/Providers/providername" $invalidScope = "Scope '/subscriptions/e9ee799d-6ab2-4084-b952-e7c86344bbab/ResourceGroups/groupname/Providers/providername' should have at least one pair of resource type and resource name. e.g. '/subscriptions//resourceGroups//providers///'." - Assert-Throws { &$cmdName -Scope $scope -Id D46245F8-7E18-4499-8E1F-784A6DA5BE25} $invalidScope + Assert-Throws { &$cmdName -Scope $scope -Id D46245F8-7E18-4499-8E1F-784A6DA5BE25 } $invalidScope } @@ -424,8 +411,7 @@ function Test-RdValidateInputParameters ($cmdName) .SYNOPSIS Tests validate input parameters #> -function Test-RdValidateInputParameters2 ($cmdName) -{ +function Test-RdValidateInputParameters2 ($cmdName) { # Setup # Note: All below scenarios are invalid, we'll expect an exception during scope validation so the ID parameter doesn't need to be a valid one. @@ -437,27 +423,27 @@ function Test-RdValidateInputParameters2 ($cmdName) # Check if Scope is valid. $scope = "/subscriptions/e9ee799d-6ab2-4084-b952-e7c86344bbab/Should be 'ResourceGroups'/any group name" $invalidScope = "Scope '/subscriptions/e9ee799d-6ab2-4084-b952-e7c86344bbab/Should be 'ResourceGroups'/any group name' should begin with '/subscriptions//resourceGroups'." - $roleDef.AssignableScopes[0] = $scope; + $roleDef.AssignableScopes[0] = $scope Assert-Throws { &$cmdName -Role $roleDef } $invalidScope $scope = "/subscriptions/e9ee799d-6ab2-4084-b952-e7c86344bbab/ResourceGroups" $invalidScope = "Scope '/subscriptions/e9ee799d-6ab2-4084-b952-e7c86344bbab/ResourceGroups' should have even number of parts." - $roleDef.AssignableScopes[0] = $scope; + $roleDef.AssignableScopes[0] = $scope Assert-Throws { &$cmdName -Role $roleDef } $invalidScope $scope = "/subscriptions/e9ee799d-6ab2-4084-b952-e7c86344bbab/ResourceGroups/" $invalidScope = "Scope '/subscriptions/e9ee799d-6ab2-4084-b952-e7c86344bbab/ResourceGroups' should have even number of parts." - $roleDef.AssignableScopes[0] = $scope; + $roleDef.AssignableScopes[0] = $scope Assert-Throws { &$cmdName -Role $roleDef } $invalidScope $scope = "/subscriptions/e9ee799d-6ab2-4084-b952-e7c86344bbab/ResourceGroups/groupname/Should be 'Providers'/any provider name" $invalidScope = "Scope '/subscriptions/e9ee799d-6ab2-4084-b952-e7c86344bbab/ResourceGroups/groupname/Should be 'Providers'/any provider name' should begin with '/subscriptions//resourceGroups//providers'." - $roleDef.AssignableScopes[0] = $scope; + $roleDef.AssignableScopes[0] = $scope Assert-Throws { &$cmdName -Role $roleDef } $invalidScope $scope = "/subscriptions/e9ee799d-6ab2-4084-b952-e7c86344bbab/ResourceGroups/groupname/Providers/providername" $invalidScope = "Scope '/subscriptions/e9ee799d-6ab2-4084-b952-e7c86344bbab/ResourceGroups/groupname/Providers/providername' should have at least one pair of resource type and resource name. e.g. '/subscriptions//resourceGroups//providers///'." - $roleDef.AssignableScopes[0] = $scope; + $roleDef.AssignableScopes[0] = $scope Assert-Throws { &$cmdName -Role $roleDef } $invalidScope } @@ -465,8 +451,7 @@ function Test-RdValidateInputParameters2 ($cmdName) .SYNOPSIS Verify positive and negative scenarios for RoleDefinition Get with filters. #> -function Test-RDFilter -{ +function Test-RDFilter { # Setup $readerRole = Get-AzRoleDefinition -Name "Reader" Assert-NotNull $readerRole @@ -474,7 +459,7 @@ function Test-RDFilter $customRoles = Get-AzRoleDefinition -Custom Assert-NotNull $customRoles - foreach($role in $customRoles){ + foreach ($role in $customRoles) { Assert-NotNull $role Assert-AreEqual $role.IsCustom $true } @@ -484,12 +469,11 @@ function Test-RDFilter .SYNOPSIS Tests verify scenarios for RoleDefinitions creation. #> -function Test-RDDataActionsNegativeTestCases -{ +function Test-RDDataActionsNegativeTestCases { # Setup # Basic positive case - read from file $rdName = 'Another tests role' - $inputFilePath = Join-Path -Path $TestOutputRoot -ChildPath Resources\RoleDefinition.json + $inputFilePath = Join-Path -Path $TestOutputRoot -ChildPath Resources\RoleDefinition.json $rd = New-AzRoleDefinitionWithId -InputFile $inputFilePath -RoleDefinitionId 3d95b97a-5745-4c39-950c-0b608dea635f $rd = Get-AzRoleDefinition -Name $rdName @@ -517,4 +501,4 @@ function Test-RDDataActionsNegativeTestCases # Basic positive case - read from object Remove-AzRoleDefinition -Id $createdRole.Id -Force -} \ No newline at end of file +} diff --git a/tools/Test/SmokeTest/RmCoreSmokeTests.ps1 b/tools/Test/SmokeTest/RmCoreSmokeTests.ps1 index b7bb870dcbcb..51cce77675c9 100644 --- a/tools/Test/SmokeTest/RmCoreSmokeTests.ps1 +++ b/tools/Test/SmokeTest/RmCoreSmokeTests.ps1 @@ -10,25 +10,23 @@ param( $Reverse ) -if (Get-Module -ListAVailable 'Az.Accounts') -{ +if (Get-Module -ListAVailable 'Az.Accounts') { Enable-AzureRmAlias } $testInfo = @{ - TotalCount = 0; - PassedCount = 0; - PassedTests = @(); - FailedTests = @(); - FailureDetails = @(); - Times = @() + TotalCount = 0 + PassedCount = 0 + PassedTests = @() + FailedTests = @() + FailureDetails = @() + Times = @() } # Generate random suffix ^\d[\da-z]{9}$ $strarray = "0123456789abcdefghijklmnopqurstuvxxyz" $randomValue = $strarray[(Get-Random -Maximum 10)] -for($i=0; $i -lt 9; $i++) -{ +for ($i = 0; $i -lt 9; $i++) { $randomValue += $strarray[(Get-Random -Maximum $strarray.Length)] } @@ -49,25 +47,27 @@ function Retry-AzCommand { [int] $Sleep ) + $originalErrorActionPreference = $ErrorActionPreference + + $ErrorActionPreference = 'Continue' $loopLimit = 0 do { try { - $script = "`$ErrorActionPreference='Continue' `n" - $script += $Command.ToString() - &([ScriptBlock]::Create($script)) + & $Command break } catch { - $commandName = ($Command -split ' ')[0] - if (++$loopLimit -gt $Retry) - { + if (++$loopLimit -gt $Retry) { throw "Failed to invoke script of $Name. $_" - } else { + } + else { Write-Warning "Retry $Name after $Sleep seconds" Start-Sleep -Seconds $Sleep } } } while ($true) + + $ErrorActionPreference = $originalErrorActionPreference } # The name of resource group is 1~90 charactors complying with ^[-\w\._\(\)]+$ @@ -75,95 +75,95 @@ $resourceGroupName = "azpssmokerg$randomValue" # The name of storage account should be 3~24 lowercase letters and numbers. $storageAccountName = "azpssmokesa$randomValue" -$resourceSetUpCommands=@( - @{Name = "Az.Resources"; Command = {New-AzResourceGroup -Name $resourceGroupName -Location westus}} +$resourceSetUpCommands = @( + @{Name = "Az.Resources"; Command = { New-AzResourceGroup -Name $resourceGroupName -Location westus } } ) $resourceCleanUpCommands = @( - @{Name = "Az.Storage [Cleanup]"; Command = {Remove-AzStorageAccount -Name $storageAccountName -ResourceGroupName $resourceGroupName -Force}}, - @{Name = "Az.Resources [Cleanup]"; Command = {Remove-AzResourceGroup -Name $resourceGroupName -Force}} + @{Name = "Az.Storage [Cleanup]"; Command = { Remove-AzStorageAccount -Name $storageAccountName -ResourceGroupName $resourceGroupName -Force } }, + @{Name = "Az.Resources [Cleanup]"; Command = { Remove-AzResourceGroup -Name $resourceGroupName -Force } } ) $resourceTestCommands = @( - @{Name = "Az.Storage [Management]"; Command = {New-AzStorageAccount -Name $storageAccountName -SkuName Standard_LRS -Location westus -ResourceGroupName $resourceGroupName}}, - @{Name = "Az.Storage [Data]"; Command = {New-AzStorageContext -StorageAccountName $storageAccountName -StorageAccountKey 12345678}}, - @{Name = "Az.Storage [Data 1]"; Command = {Get-Command Get-AzStorageBlob}}, - @{Name = "Az.Accounts"; Command = {Get-AzDomain}}, - @{Name = "Az.Accounts [DefaultProfile]"; Command = {Get-AzSubscription -DefaultProfile (Get-AzContext)}}, - @{Name = "Az.Advisor"; Command = {Get-AzAdvisorConfiguration}}, - @{Name = "Az.Aks"; Command = {Get-AzAksCluster}}, - @{Name = "Az.AnalysisServices"; Command = {Get-AzAnalysisServicesServer}}, - @{Name = "Az.ApiManagement"; Command = {Get-AzApiManagement}}, - @{Name = "Az.ApplicationInsights"; Command = {Get-AzApplicationInsights}}, - @{Name = "Az.Automation"; Command = {Get-AzAutomationAccount}}, - @{Name = "Az.Batch [MngmPlane]"; Command = {Get-AzBatchAccount}}, - @{Name = "Az.Batch [DataPlane]"; Command = {Get-Command Get-AzBatchSupportedImage}}, - @{Name = "Az.Billing"; Command = {Get-AzBillingInvoice}}, - @{Name = "Az.Billing [Consumption]"; Command = {Get-AzConsumptionBudget}}, - @{Name = "Az.Cdn"; Command = {Get-AzCdnProfile}}, - @{Name = "Az.CognitiveServices"; Command = {Get-AzCognitiveServicesAccount}}, - @{Name = "Az.Compute"; Command = {Get-AzVM}; Since="7.0.0"}, - @{Name = "Az.ContainerInstance"; Command = {Get-AzContainerGroup}}, - @{Name = "Az.ContainerRegistry [MngmPlane]"; Command = {Get-AzContainerRegistry}}, - @{Name = "Az.ContainerRegistry [DataPlane]"; Command = {Get-Command Get-AzContainerRegistryManifest}}, - @{Name = "Az.DataBoxEdge"; Command = {Get-AzDataBoxEdgeDevice -ResourceGroupName $resourceGroupName}}, - @{Name = "Az.Databricks"; Command = {Get-AzDatabricksWorkspace -ResourceGroupName $resourceGroupName}}, + @{Name = "Az.Storage [Management]"; Command = { New-AzStorageAccount -Name $storageAccountName -SkuName Standard_LRS -Location westus -ResourceGroupName $resourceGroupName } }, + @{Name = "Az.Storage [Data]"; Command = { New-AzStorageContext -StorageAccountName $storageAccountName -StorageAccountKey 12345678 } }, + @{Name = "Az.Storage [Data 1]"; Command = { Get-Command Get-AzStorageBlob } }, + @{Name = "Az.Accounts"; Command = { Get-AzDomain } }, + @{Name = "Az.Accounts [DefaultProfile]"; Command = { Get-AzSubscription -DefaultProfile (Get-AzContext) } }, + @{Name = "Az.Advisor"; Command = { Get-AzAdvisorConfiguration } }, + @{Name = "Az.Aks"; Command = { Get-AzAksCluster } }, + @{Name = "Az.AnalysisServices"; Command = { Get-AzAnalysisServicesServer } }, + @{Name = "Az.ApiManagement"; Command = { Get-AzApiManagement } }, + @{Name = "Az.ApplicationInsights"; Command = { Get-AzApplicationInsights } }, + @{Name = "Az.Automation"; Command = { Get-AzAutomationAccount } }, + @{Name = "Az.Batch [MngmPlane]"; Command = { Get-AzBatchAccount } }, + @{Name = "Az.Batch [DataPlane]"; Command = { Get-Command Get-AzBatchSupportedImage } }, + @{Name = "Az.Billing"; Command = { Get-AzBillingInvoice } }, + @{Name = "Az.Billing [Consumption]"; Command = { Get-AzConsumptionBudget } }, + @{Name = "Az.Cdn"; Command = { Get-AzCdnProfile } }, + @{Name = "Az.CognitiveServices"; Command = { Get-AzCognitiveServicesAccount } }, + @{Name = "Az.Compute"; Command = { Get-AzVM }; Since = "7.0.0" }, + @{Name = "Az.ContainerInstance"; Command = { Get-AzContainerGroup } }, + @{Name = "Az.ContainerRegistry [MngmPlane]"; Command = { Get-AzContainerRegistry } }, + @{Name = "Az.ContainerRegistry [DataPlane]"; Command = { Get-Command Get-AzContainerRegistryManifest } }, + @{Name = "Az.DataBoxEdge"; Command = { Get-AzDataBoxEdgeDevice -ResourceGroupName $resourceGroupName } }, + @{Name = "Az.Databricks"; Command = { Get-AzDatabricksWorkspace -ResourceGroupName $resourceGroupName } }, # The resource type could not be found in the namespace 'Microsoft.DataFactory' for api version '2015-10-01'. # @{Name = "Az.DataFactory [V1]"; Command = {Get-AzDataFactory -ResourceGroupName $resourceGroupName}}, - @{Name = "Az.DataFactoryV2 [V2]"; Command = {Get-AzDataFactoryV2}}, - @{Name = "Az.DataLakeAnalytics"; Command = {Get-AzDataLakeAnalyticsAccount}}, + @{Name = "Az.DataFactoryV2 [V2]"; Command = { Get-AzDataFactoryV2 } }, + @{Name = "Az.DataLakeAnalytics"; Command = { Get-AzDataLakeAnalyticsAccount } }, # The resource type could not be found in the namespace 'Microsoft.DataLakeStore' for api version '2016-11-01'. # @{Name = "Az.DataLakeStore [MngmPlane]"; Command = {Get-AzDataLakeStoreAccount}}, - @{Name = "Az.DataLakeStore [DataPlane]"; Command = {Get-Command New-AzDataLakeStoreItem}}, - @{Name = "Az.DataShare"; Command = {Get-AzDataShareAccount -ResourceGroupName $resourceGroupName}}, - @{Name = "Az.DesktopVirtualization"; Command = {Get-AzWvdApplicationGroup -ResourceGroupName $resourceGroupName}}, - @{Name = "Az.Dns"; Command = {Get-AzDnsZone}}, - @{Name = "Az.EventGrid"; Command = {Get-AzEventGridTopic}}, - @{Name = "Az.EventHub"; Command = {Get-AzEventHubNamespace}}, - @{Name = "Az.FrontDoor"; Command = {Get-AzFrontDoor}}, - @{Name = "Az.Functions"; Command = {Get-AzFunctionApp}}, - @{Name = "Az.HDInsight "; Command = {Get-AzHDInsightCluster}}, - @{Name = "Az.HealthcareApis"; Command = {Get-AzHealthcareApisService}}, - @{Name = "Az.IotHub [MngmPlane]"; Command = {Get-AzIotHub}}, - @{Name = "Az.IotHub [DataPlane]"; Command = {Get-Command Get-AzIotHubModuleConnectionString}}, - @{Name = "Az.KeyVault [MngmPlane]"; Command = {Get-AzKeyVault}}, - @{Name = "Az.KeyVault [DataPlane]"; Command = {Get-Command Get-AzKeyVaultKey}}, - @{Name = "Az.Kusto"; Command = {Get-AzKustoCluster}}, - @{Name = "Az.LogicApp"; Command = {Get-AzIntegrationAccount}}, + @{Name = "Az.DataLakeStore [DataPlane]"; Command = { Get-Command New-AzDataLakeStoreItem } }, + @{Name = "Az.DataShare"; Command = { Get-AzDataShareAccount -ResourceGroupName $resourceGroupName } }, + @{Name = "Az.DesktopVirtualization"; Command = { Get-AzWvdApplicationGroup -ResourceGroupName $resourceGroupName } }, + @{Name = "Az.Dns"; Command = { Get-AzDnsZone } }, + @{Name = "Az.EventGrid"; Command = { Get-AzEventGridTopic } }, + @{Name = "Az.EventHub"; Command = { Get-AzEventHubNamespace } }, + @{Name = "Az.FrontDoor"; Command = { Get-AzFrontDoor } }, + @{Name = "Az.Functions"; Command = { Get-AzFunctionApp } }, + @{Name = "Az.HDInsight "; Command = { Get-AzHDInsightCluster } }, + @{Name = "Az.HealthcareApis"; Command = { Get-AzHealthcareApisService } }, + @{Name = "Az.IotHub [MngmPlane]"; Command = { Get-AzIotHub } }, + @{Name = "Az.IotHub [DataPlane]"; Command = { Get-Command Get-AzIotHubModuleConnectionString } }, + @{Name = "Az.KeyVault [MngmPlane]"; Command = { Get-AzKeyVault } }, + @{Name = "Az.KeyVault [DataPlane]"; Command = { Get-Command Get-AzKeyVaultKey } }, + @{Name = "Az.Kusto"; Command = { Get-AzKustoCluster } }, + @{Name = "Az.LogicApp"; Command = { Get-AzIntegrationAccount } }, # The request uri is invalid. The requested path '/subscriptions/$subId/providers/Microsoft.MachineLearning/webServices' is not found # @{Name = "Az.MachineLearning"; Command = {Get-AzMlWebService}}, - @{Name = "Az.Maintenance"; Command = {Get-AzMaintenanceConfiguration}}, - @{Name = "Az.ManagedServices"; Command = {Get-AzManagedServicesAssignment}}, - @{Name = "Az.Monitor"; Command = {Get-AzLogProfile}}, - @{Name = "Az.Network"; Command = {Get-AzNetworkInterface}}, - @{Name = "Az.NotificationHubs"; Command = {Get-AzNotificationHubsNamespace}}, - @{Name = "Az.OperationalInsights [MngmPlane]"; Command = {Get-AzOperationalInsightsWorkspace}}, - @{Name = "Az.OperationalInsights [DataPlane]"; Command = {Get-Command Invoke-AzOperationalInsightsQuery}}, - @{Name = "Az.PolicyInsights"; Command = {Get-AzPolicyEvent -Top 10}}, # without -Top service may return 400: ResponseTooLarge - @{Name = "Az.PowerBIEmbedded"; Command = {Get-AzPowerBIEmbeddedCapacity}}, - @{Name = "Az.PrivateDns"; Command = {Get-AzPrivateDnsZone}}, - @{Name = "Az.RecoveryServices"; Command = {Get-AzRecoveryServicesVault}}, - @{Name = "Az.RedisCache"; Command = {Get-AzRedisCache}}, - @{Name = "Az.Relay"; Command = {Get-AzRelayNamespace}}, - @{Name = "Az.ServiceBus"; Command = {Get-AzServiceBusNamespace}}, - @{Name = "Az.ServiceFabric [MngmPlane]"; Command = {Get-AzServiceFabricCluster}}, - @{Name = "Az.ServiceFabric [DataPlane]"; Command = {Get-Command New-AzServiceFabricCluster}}, - @{Name = "Az.SignalR"; Command = {Get-AzSignalR}}, - @{Name = "Az.Sql"; Command = {Get-AzSqlServer}}, - @{Name = "Az.SqlVirtualMachine"; Command = {Get-AzSqlVM}}, - @{Name = "Az.StreamAnalytics"; Command = {Get-AzStreamAnalyticsJob}}, - @{Name = "Az.StorageSync"; Command = {Get-AzStorageSyncService}}, - @{Name = "Az.Support"; Command = {Get-AzSupportTicket}}, - @{Name = "Az.Resources [Tags]"; Command = {Get-AzTag}}, - @{Name = "Az.Resources [MSGraph]"; Command = {Get-AzADUser -First 1 -Select Id}}, - @{Name = "Az.TrafficManager"; Command = {Get-AzTrafficManagerProfile}}, - @{Name = "Az.Billing [UsageAggregates]"; Command = {Get-UsageAggregates -ReportedStartTime '1/1/2018' -ReportedEndTime '1/2/2018'}}, - @{Name = "Az.Websites"; Command = {Get-AzWebApp -ResourceGroupName $resourceGroupName}} + @{Name = "Az.Maintenance"; Command = { Get-AzMaintenanceConfiguration } }, + @{Name = "Az.ManagedServices"; Command = { Get-AzManagedServicesAssignment } }, + @{Name = "Az.Monitor"; Command = { Get-AzLogProfile } }, + @{Name = "Az.Network"; Command = { Get-AzNetworkInterface } }, + @{Name = "Az.NotificationHubs"; Command = { Get-AzNotificationHubsNamespace } }, + @{Name = "Az.OperationalInsights [MngmPlane]"; Command = { Get-AzOperationalInsightsWorkspace } }, + @{Name = "Az.OperationalInsights [DataPlane]"; Command = { Get-Command Invoke-AzOperationalInsightsQuery } }, + @{Name = "Az.PolicyInsights"; Command = { Get-AzPolicyEvent -Top 10 } }, # without -Top service may return 400: ResponseTooLarge + @{Name = "Az.PowerBIEmbedded"; Command = { Get-AzPowerBIEmbeddedCapacity } }, + @{Name = "Az.PrivateDns"; Command = { Get-AzPrivateDnsZone } }, + @{Name = "Az.RecoveryServices"; Command = { Get-AzRecoveryServicesVault } }, + @{Name = "Az.RedisCache"; Command = { Get-AzRedisCache } }, + @{Name = "Az.Relay"; Command = { Get-AzRelayNamespace } }, + @{Name = "Az.ServiceBus"; Command = { Get-AzServiceBusNamespace } }, + @{Name = "Az.ServiceFabric [MngmPlane]"; Command = { Get-AzServiceFabricCluster } }, + @{Name = "Az.ServiceFabric [DataPlane]"; Command = { Get-Command New-AzServiceFabricCluster } }, + @{Name = "Az.SignalR"; Command = { Get-AzSignalR } }, + @{Name = "Az.Sql"; Command = { Get-AzSqlServer } }, + @{Name = "Az.SqlVirtualMachine"; Command = { Get-AzSqlVM } }, + @{Name = "Az.StreamAnalytics"; Command = { Get-AzStreamAnalyticsJob } }, + @{Name = "Az.StorageSync"; Command = { Get-AzStorageSyncService } }, + @{Name = "Az.Support"; Command = { Get-AzSupportTicket } }, + @{Name = "Az.Resources [Tags]"; Command = { Get-AzTag } }, + @{Name = "Az.Resources [MSGraph]"; Command = { Get-AzADUser -First 1 -Select Id } }, + @{Name = "Az.TrafficManager"; Command = { Get-AzTrafficManagerProfile } }, + @{Name = "Az.Billing [UsageAggregates]"; Command = { Get-UsageAggregates -ReportedStartTime '1/1/2018' -ReportedEndTime '1/2/2018' } }, + @{Name = "Az.Websites"; Command = { Get-AzWebApp -ResourceGroupName $resourceGroupName } } ) $generalCommands = @( @{ - Name = "Import Az.Accounts in Parallel (Process)"; + Name = "Import Az.Accounts in Parallel (Process)" Command = { if ($null -ne $env:SYSTEM_DEFINITIONID -or $null -ne $env:Release_DefinitionId -or $null -ne $env:AZUREPS_HOST_ENVIRONMENT) { Write-Warning "Skipping because 'Start-Job' is not supported by design in scenarios where PowerShell is being hosted in other applications." @@ -180,11 +180,11 @@ $generalCommands = @( throw "Some jobs have failed." } } - }; - Retry = 0; # no need to retry + } + Retry = 0; # no need to retry } @{ - Name = "Import Az.Accounts in Parallel (Thread)"; + Name = "Import Az.Accounts in Parallel (Thread)" Command = { $importJobs = @() @@ -198,12 +198,12 @@ $generalCommands = @( throw "Some jobs have failed." } } - }; - Retry = 0; # no need to retry + } + Retry = 0; # no need to retry } ) -if($Reverse.IsPresent){ +if ($Reverse.IsPresent) { [array]::Reverse($resourceTestCommands) } @@ -213,57 +213,63 @@ $startTime = Get-Date $resourceCommands | ForEach-Object { $testName = $_.Name $script = $_.Command - $retry = if($null -eq $_.Retry) {3} Else {$_.Retry} - $sleep = if($null -eq $_.Sleep) {30} Else {$_.Sleep} - if($null -ne $_.Since -and "Core" -eq $PSVersionTable.PSEdition -and $PSVersionTable.PSVersion -lt [System.Version]$_.Since) { + $retry = if ($null -eq $_.Retry) { + 3 + } + Else { + $_.Retry + } + $sleep = if ($null -eq $_.Sleep) { + 30 + } + Else { + $_.Sleep + } + if ($null -ne $_.Since -and "Core" -eq $PSVersionTable.PSEdition -and $PSVersionTable.PSVersion -lt [System.Version]$_.Since) { Write-Output "Skip test $testName" $testInfo.SkippedCount += 1 return } Write-Output "Running test $testName" $testStart = Get-Date - try - { + try { Retry-AzCommand -Name $testName -Command $script -Retry $retry -Sleep $sleep $testInfo.PassedCount += 1 $testInfo.PassedTests += $testName } - catch - { + catch { Write-Error $_.Exception $detail = Resolve-AzError -Last - $testInfo.FailureDetails += (New-Object PSObject -Property @{Name = $testName; Details = $detail}) + $testInfo.FailureDetails += (New-Object PSObject -Property @{Name = $testName; Details = $detail }) $testInfo.FailedTests += $testName } - finally - { + finally { $testEnd = Get-Date $testElapsed = $testEnd - $testStart - $testInfo.Times += (New-Object PSObject -Property @{TestName = $testName; ElapsedTime = $testElapsed}) + $testInfo.Times += (New-Object PSObject -Property @{TestName = $testName; ElapsedTime = $testElapsed }) $testInfo.TotalCount += 1 } } $endTime = Get-Date @{ - Subscription = $context.Context.Subscription.Name; - StartTime = $startTime; - EndTime = $endTime; - Elapsed = $endTime - $startTime; - TotalTests = $testInfo.TotalCount; - PassedTests = $testInfo.PassedTests; - SkippedTests = $testInfo.SkippedCount; - FailedTests = $testInfo.FailedTests + Subscription = $context.Context.Subscription.Name + StartTime = $startTime + EndTime = $endTime + Elapsed = $endTime - $startTime + TotalTests = $testInfo.TotalCount + PassedTests = $testInfo.PassedTests + SkippedTests = $testInfo.SkippedCount + FailedTests = $testInfo.FailedTests } | Write-Output -$testInfo.FailureDetails | ForEach-Object{ +$testInfo.FailureDetails | ForEach-Object { $_ | Select-Object -Property Name | Write-Output $_.Details | Write-Output } $testInfo.Times | Format-Table -if ($testInfo.FailedTests.Count -gt 0) -{ +if ($testInfo.FailedTests.Count -gt 0) { throw ("Test run failed with " + $testInfo.FailedTests.Count + " failures.") }