From 6beafc0d8dbbe2ae56e652b799d3831cfb7e3106 Mon Sep 17 00:00:00 2001 From: kalgiz Date: Wed, 28 Mar 2018 15:30:45 -0700 Subject: [PATCH 01/58] commit --- test/powershell/engine/Basic/DefaultCommands.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 b/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 index 1907240b6a0..57164b3cb9c 100644 --- a/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 +++ b/test/powershell/engine/Basic/DefaultCommands.Tests.ps1 @@ -440,7 +440,7 @@ Describe "Verify approved aliases list" -Tags "CI" { "Cmdlet", "Test-ComputerSecureChannel", , $($FullCLR ) "Cmdlet", "Test-FileCatalog", , $($FullCLR -or $CoreWindows ) "Cmdlet", "Test-ModuleManifest", , $($FullCLR -or $CoreWindows -or $CoreUnix) -"Cmdlet", "Test-Json", , $( $CoreWindows -or $CoreUnix) +"Cmdlet", "Test-Json", , $( $CoreWindows -or $CoreUnix) "Cmdlet", "Test-Path", , $($FullCLR -or $CoreWindows -or $CoreUnix) "Cmdlet", "Test-PSSessionConfigurationFile", , $($FullCLR -or $CoreWindows ) "Cmdlet", "Test-WSMan", , $($FullCLR -or $CoreWindows ) From 051fd4190d588b50a2eae111f0586da7eff81228 Mon Sep 17 00:00:00 2001 From: algizklaudia Date: Tue, 17 Apr 2018 11:12:02 -0700 Subject: [PATCH 02/58] [Feature] CimCmdlets and Diagnostics module Error tests fix. --- .../Modules/CimCmdlets/CimInstance.Tests.ps1 | 8 ++------ .../Modules/CimCmdlets/Get-CimClass.Tests.ps1 | 18 ++++-------------- .../New-WinEvent.Tests.ps1 | 8 ++++---- 3 files changed, 10 insertions(+), 24 deletions(-) diff --git a/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 b/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 index c4960a2b463..075fbf6f602 100644 --- a/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 +++ b/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 @@ -28,12 +28,8 @@ Try { $instance.GetCimSessionInstanceId() | Should -BeOfType "Guid" } It "should produce an error for a non-existing classname" { - try { - get-ciminstance -classname thisnameshouldnotexist -ea stop - throw "expected error did not occur" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "HRESULT 0x80041010,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstanceCommand" + { get-ciminstance -classname thisnameshouldnotexist -ea stop } | + Should -Throw -ErrorId "HRESULT 0x80041010,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstanceCommand" } } } diff --git a/test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 b/test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 index 203feaea9cb..b8af13164da 100644 --- a/test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 +++ b/test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 @@ -15,22 +15,12 @@ try { } It 'produces an error when a non-existent class is used' { - try { - Get-CimClass -ClassName thisclasstypedoesnotexist -ea stop - throw "Expected error did not occur" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "HRESULT 0x80041002,Microsoft.Management.Infrastructure.CimCmdlets.GetCimClassCommand" - } + { Get-CimClass -ClassName thisclasstypedoesnotexist -ea stop | + Should -Throw -ErrorId "HRESULT 0x80041002,Microsoft.Management.Infrastructure.CimCmdlets.GetCimClassCommand" } It 'produces an error when an improper namespace is used' { - try { - Get-CimClass -ClassName CIM_OperatingSystem -Namespace badnamespace -ea stop - throw "Expected error did not occur" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "HRESULT 0x8004100e,Microsoft.Management.Infrastructure.CimCmdlets.GetCimClassCommand" - } + { Get-CimClass -ClassName CIM_OperatingSystem -Namespace badnamespace -ea stop } | + Should -Throw -ErrorId "HRESULT 0x8004100e,Microsoft.Management.Infrastructure.CimCmdlets.GetCimClassCommand" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Diagnostics/New-WinEvent.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Diagnostics/New-WinEvent.Tests.ps1 index 4fe72908eee..96ec01605be 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Diagnostics/New-WinEvent.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Diagnostics/New-WinEvent.Tests.ps1 @@ -26,19 +26,19 @@ Describe 'New-WinEvent' -Tags "CI" { } It 'No provider found error' { - { New-WinEvent -ProviderName NonExistingProvider -Id 0 } | ShouldBeErrorId 'System.ArgumentException,Microsoft.PowerShell.Commands.NewWinEventCommand' + { New-WinEvent -ProviderName NonExistingProvider -Id 0 } | Should -Throw -ErrorId 'System.ArgumentException,Microsoft.PowerShell.Commands.NewWinEventCommand' } It 'EmptyProviderName error' { - { New-WinEvent -ProviderName $null -Id 0 } | ShouldBeErrorId 'ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.NewWinEventCommand' + { New-WinEvent -ProviderName $null -Id 0 } | Should -Throw -ErrorId 'ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.NewWinEventCommand' } It 'IncorrectEventId error' { - { New-WinEvent $ProviderName -Id 999999 } | ShouldBeErrorId 'Microsoft.PowerShell.Commands.EventWriteException,Microsoft.PowerShell.Commands.NewWinEventCommand' + { New-WinEvent $ProviderName -Id 999999 } | Should -Throw -ErrorId 'Microsoft.PowerShell.Commands.EventWriteException,Microsoft.PowerShell.Commands.NewWinEventCommand' } It 'IncorrectEventVersion error' { - { New-WinEvent -ProviderName $ProviderName -Id $SimpleEventId -Version 99 } | ShouldBeErrorId 'Microsoft.PowerShell.Commands.EventWriteException,Microsoft.PowerShell.Commands.NewWinEventCommand' + { New-WinEvent -ProviderName $ProviderName -Id $SimpleEventId -Version 99 } | Should -Throw -ErrorId 'Microsoft.PowerShell.Commands.EventWriteException,Microsoft.PowerShell.Commands.NewWinEventCommand' } It 'PayloadMismatch error' { From c99c2f280cb8f529963ca245e18d5771fbbe00f0 Mon Sep 17 00:00:00 2001 From: algizklaudia Date: Tue, 17 Apr 2018 11:25:29 -0700 Subject: [PATCH 03/58] [Featur] ShouldBeErrorId => Should -Throw -ErrorId in Core module. --- .../Modules/Microsoft.PowerShell.Core/Import-Module.Tests.ps1 | 2 +- .../Modules/Microsoft.PowerShell.Core/Job.Tests.ps1 | 2 +- .../Microsoft.PowerShell.Core/RemoteGetModule.Tests.ps1 | 4 ++-- .../Microsoft.PowerShell.Core/RemoteImportModule.Tests.ps1 | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Core/Import-Module.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Core/Import-Module.Tests.ps1 index 04577e954f9..80139e8f624 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Core/Import-Module.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Core/Import-Module.Tests.ps1 @@ -111,7 +111,7 @@ Describe "Import-Module for Binary Modules in GAC" -Tags 'CI' { It "Load PSScheduledJob from Windows Powershell Modules folder should fail" -Skip:(-not $IsWindows) { $modulePath = Join-Path $env:windir "System32/WindowsPowershell/v1.0/Modules/PSScheduledJob" - { Import-Module $modulePath -ErrorAction SilentlyContinue } | ShouldBeErrorId 'FormatXmlUpdateException,Microsoft.PowerShell.Commands.ImportModuleCommand' + { Import-Module $modulePath -ErrorAction SilentlyContinue } | Should -Throw -ErrorId 'FormatXmlUpdateException,Microsoft.PowerShell.Commands.ImportModuleCommand' } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Core/Job.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Core/Job.Tests.ps1 index 8be26300e39..c997bb84cb0 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Core/Job.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Core/Job.Tests.ps1 @@ -26,7 +26,7 @@ Describe "Job Cmdlet Tests" -Tag "CI" { } It "Remove-Job can remove a job" { Remove-Job $j -Force - { Get-Job $j -ErrorAction Stop } | ShouldBeErrorId "JobWithSpecifiedNameNotFound,Microsoft.PowerShell.Commands.GetJobCommand" + { Get-Job $j -ErrorAction Stop } | Should -Throw -ErrorId "JobWithSpecifiedNameNotFound,Microsoft.PowerShell.Commands.GetJobCommand" } It "Receive-Job can retrieve job results" { Wait-Job -Timeout 60 -id $j.id | Should -Not -BeNullOrEmpty diff --git a/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteGetModule.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteGetModule.Tests.ps1 index 6e484e29566..985b20291e0 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteGetModule.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteGetModule.Tests.ps1 @@ -23,7 +23,7 @@ Describe "Remote module tests" -Tags 'Feature','RequireAdminOnWindows' { ) { param($parameter, $value) $parameters = @{$parameter=$value} - { Get-Module @parameters -ErrorAction Stop } | ShouldBeErrorId "RemoteDiscoveryWorksOnlyInListAvailableMode,Microsoft.PowerShell.Commands.GetModuleCommand" + { Get-Module @parameters -ErrorAction Stop } | Should -Throw -ErrorId "RemoteDiscoveryWorksOnlyInListAvailableMode,Microsoft.PowerShell.Commands.GetModuleCommand" } It "Get-Module succeeds using -ListAvailable with ''" -TestCases @( @@ -73,7 +73,7 @@ Describe "Remote module tests" -Tags 'Feature','RequireAdminOnWindows' { } It "Failure if -Name and -FullyQualifiedName are both specified" { - { Get-Module -Name foo -FullyQualifiedName @{ModuleName='foo'} -ErrorAction Stop } | ShouldBeErrorId "CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.GetModuleCommand" + { Get-Module -Name foo -FullyQualifiedName @{ModuleName='foo'} -ErrorAction Stop } | Should -Throw -ErrorId "CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.GetModuleCommand" } It "Get-Module supports pipeline" { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteImportModule.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteImportModule.Tests.ps1 index f4b86ad1665..9e869cb8fba 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteImportModule.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteImportModule.Tests.ps1 @@ -98,7 +98,7 @@ Describe "Remote import-module tests" -Tags 'Feature','RequireAdminOnWindows' { Invoke-Command -Session $pssession -ScriptBlock { $env:PSModulePath += ";$(Split-Path $using:modulePath)"} Get-Module TestImport | Should -BeNullOrEmpty if ($errorid) { - { Import-Module @parameters -ErrorAction Stop } | ShouldBeErrorId $errorid + { Import-Module @parameters -ErrorAction Stop } | Should -Throw -ErrorId $errorid } else { Import-Module @parameters $module = Get-Module TestImport From e0607f173c9d5b022859ea1edc4de93e50d8b208 Mon Sep 17 00:00:00 2001 From: algizklaudia Date: Tue, 17 Apr 2018 11:29:54 -0700 Subject: [PATCH 04/58] [Feature] Should Be => Should -BeTrue in Host module. --- .../Microsoft.Powershell.Host/Start-Transcript.Tests.ps1 | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/powershell/Modules/Microsoft.Powershell.Host/Start-Transcript.Tests.ps1 b/test/powershell/Modules/Microsoft.Powershell.Host/Start-Transcript.Tests.ps1 index b004e647649..5b4b3ab233d 100644 --- a/test/powershell/Modules/Microsoft.Powershell.Host/Start-Transcript.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.Powershell.Host/Start-Transcript.Tests.ps1 @@ -26,14 +26,14 @@ Describe "Start-Transcript, Stop-Transcript tests" -tags "CI" { $ps.commands.clear() if($expectedError) { - $ps.hadErrors | Should be $true + $ps.hadErrors | Should -BeTrue $ps.Streams.Error.FullyQualifiedErrorId | Should be $expectedError } else { $ps.addscript("Get-Date").Invoke() $ps.commands.clear() $ps.addscript("Stop-Transcript").Invoke() - Test-Path $outputFilePath | Should be $true + Test-Path $outputFilePath | Should -BeTrue $outputFilePath | should FileContentMatch "Get-Date" if($append) { $outputFilePath | Should FileContentMatch $content @@ -131,7 +131,7 @@ Describe "Start-Transcript, Stop-Transcript tests" -tags "CI" { $powerShellCommand = $powerShellPath + ' -c "start-transcript $transcriptFilePath; Write-Host ''Before Dispose'';"' Invoke-Expression $powerShellCommand - Test-Path $transcriptFilePath | Should be $true + Test-Path $transcriptFilePath | Should -BeTrue $transcriptFilePath | Should FileContentMatch "Before Dispose" $transcriptFilePath | Should FileContentMatch "PowerShell transcript end" } @@ -142,7 +142,7 @@ Describe "Start-Transcript, Stop-Transcript tests" -tags "CI" { hostname Stop-Transcript } & $script - Test-Path $transcriptFilePath | Should be $true + Test-Path $transcriptFilePath | Should -BeTrue $machineName = [System.Environment]::MachineName $transcriptFilePath | Should FileContentMatch $machineName From 0defa7321787c47fe37f62795fd9586629555b31 Mon Sep 17 00:00:00 2001 From: algizklaudia Date: Tue, 17 Apr 2018 11:40:56 -0700 Subject: [PATCH 05/58] [Feature] ShouldBeErrorId => Should -Throw -ErrorId in Security module. --- .../CertificateProvider.Tests.ps1 | 4 ++-- .../Microsoft.PowerShell.Security/CmsMessage.Tests.ps1 | 3 ++- .../Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 | 6 +++--- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/CertificateProvider.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/CertificateProvider.Tests.ps1 index 86b311caf63..bcb644d4370 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/CertificateProvider.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/CertificateProvider.Tests.ps1 @@ -62,10 +62,10 @@ Describe "Certificate Provider tests" -Tags "CI" { (get-item cert:\LocalMachine , cert:\CurrentUser).Count | Should -Be 2 } it "Should return PathNotFound when getting a non-existant certificate store" { - {Get-Item cert:\IDONTEXIST -ErrorAction Stop} | ShouldBeErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" + {Get-Item cert:\IDONTEXIST -ErrorAction Stop} | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } it "Should return PathNotFound when getting a non-existant certificate" { - {Get-Item cert:\currentuser\my\IDONTEXIST -ErrorAction Stop} | ShouldBeErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" + {Get-Item cert:\currentuser\my\IDONTEXIST -ErrorAction Stop} | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } } Context "Get-ChildItem tests"{ diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/CmsMessage.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/CmsMessage.Tests.ps1 index db0eb51ed64..f35c24d9ec7 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/CmsMessage.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/CmsMessage.Tests.ps1 @@ -37,7 +37,8 @@ Describe "CmsMessage cmdlets and Get-PfxCertificate basic tests" -Tags "CI" { It "Verify Get-PfxCertificate wrong password" { #[SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Test secret.")] $pass = ConvertTo-SecureString "wrongpass" -AsPlainText -Force - $e = { Get-PfxCertificate $protectedCertLocation -Password $pass -ErrorAction Stop } | ShouldBeErrorId "GetPfxCertificateUnknownCryptoError,Microsoft.PowerShell.Commands.GetPfxCertificateCommand" + { Get-PfxCertificate $protectedCertLocation -Password $pass -ErrorAction Stop } | + Should -Throw -ErrorId "GetPfxCertificateUnknownCryptoError,Microsoft.PowerShell.Commands.GetPfxCertificateCommand" } It "Verify CMS message recipient resolution by path" -Skip:(!$IsWindows) { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 index 853a7a10de6..f26f55a8a91 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 @@ -684,7 +684,7 @@ ZoneId=$FileType $testScript = {Import-Module -Name $module -Force} if($error) { - $testScript | ShouldBeErrorId $error + $testScript | Should -Throw -ErrorId $error } else { @@ -929,7 +929,7 @@ ZoneId=$FileType $testScript = {Import-Module -Name $module -Force} if($error) { - $testScript | ShouldBeErrorId $error + $testScript | Should -Throw -ErrorId $error } else { @@ -1028,7 +1028,7 @@ ZoneId=$FileType $testScript | Should -Exist if($error) { - {& $testScript} | ShouldBeErrorId $error + {& $testScript} | Should -Throw -ErrorId $error } else { From 2a4a2939412a99e987ad9f1b85b92c2b4df95b39 Mon Sep 17 00:00:00 2001 From: kalgiz Date: Tue, 17 Apr 2018 16:06:52 -0700 Subject: [PATCH 06/58] [Feature] ShouldBeErrorId => Should -Throw -ErrorId in Management module. --- .../FileSystem.Tests.ps1 | 20 +++++++++---------- .../FunctionProvider.Tests.ps1 | 16 +++++++-------- .../Get-Content.Tests.ps1 | 14 ++++++------- .../Get-Item.Tests.ps1 | 4 ++-- .../Get-Service.Tests.ps1 | 2 +- .../Registry.Tests.ps1 | 2 +- .../Rename-Computer.Tests.ps1 | 2 +- .../Restart-Computer.Tests.ps1 | 6 +++--- .../Set-Service.Tests.ps1 | 6 +++--- .../Start-Process.Tests.ps1 | 6 +++--- .../Test-Connection.Tests.ps1 | 18 ++++++++--------- 11 files changed, 48 insertions(+), 48 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 index 974c69568ec..757f614c643 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 @@ -79,7 +79,7 @@ Describe "Basic FileSystem Provider Tests" -Tags "CI" { } It "Verify Rename-Item will not rename to an existing name" { - { Rename-Item -Path $testFile -NewName $testDir -ErrorAction Stop } | ShouldBeErrorId "RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand" + { Rename-Item -Path $testFile -NewName $testDir -ErrorAction Stop } | Should -Throw -ErrorId "RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand" $Error[0].Exception | Should -BeOfType System.IO.IOException $testFile | Should -Exist } @@ -108,7 +108,7 @@ Describe "Basic FileSystem Provider Tests" -Tags "CI" { } It "Verify Move-Item will not move to an existing file" { - { Move-Item -Path $testDir -Destination $testFile -ErrorAction Stop } | ShouldBeErrorId "MoveDirectoryItemIOError,Microsoft.PowerShell.Commands.MoveItemCommand" + { Move-Item -Path $testDir -Destination $testFile -ErrorAction Stop } | Should -Throw -ErrorId "MoveDirectoryItemIOError,Microsoft.PowerShell.Commands.MoveItemCommand" $Error[0].Exception | Should -BeOfType System.IO.IOException $testDir | Should -Exist } @@ -157,21 +157,21 @@ Describe "Basic FileSystem Provider Tests" -Tags "CI" { It "Copy-Item on Windows rejects Windows reserved device names" -Skip:(-not $IsWindows) { foreach ($deviceName in $reservedNames) { - { Copy-Item -Path $testFile -Destination $deviceName -ErrorAction Stop } | ShouldBeErrorId "CopyError,Microsoft.PowerShell.Commands.CopyItemCommand" + { Copy-Item -Path $testFile -Destination $deviceName -ErrorAction Stop } | Should -Throw -ErrorId "CopyError,Microsoft.PowerShell.Commands.CopyItemCommand" } } It "Move-Item on Windows rejects Windows reserved device names" -Skip:(-not $IsWindows) { foreach ($deviceName in $reservedNames) { - { Move-Item -Path $testFile -Destination $deviceName -ErrorAction Stop } | ShouldBeErrorId "MoveError,Microsoft.PowerShell.Commands.MoveItemCommand" + { Move-Item -Path $testFile -Destination $deviceName -ErrorAction Stop } | Should -Throw -ErrorId "MoveError,Microsoft.PowerShell.Commands.MoveItemCommand" } } It "Rename-Item on Windows rejects Windows reserved device names" -Skip:(-not $IsWindows) { foreach ($deviceName in $reservedNames) { - { Rename-Item -Path $testFile -NewName $deviceName -ErrorAction Stop } | ShouldBeErrorId "RenameError,Microsoft.PowerShell.Commands.RenameItemCommand" + { Rename-Item -Path $testFile -NewName $deviceName -ErrorAction Stop } | Should -Throw -ErrorId "RenameError,Microsoft.PowerShell.Commands.RenameItemCommand" } } @@ -399,7 +399,7 @@ Describe "Handling of globbing patterns" -Tags "CI" { Context "Handle asterisks in name" { It "Remove-Item -LiteralPath should fail if it contains asterisk and file doesn't exist" { - { Remove-Item -LiteralPath ./foo*.txt -ErrorAction Stop } | ShouldBeErrorId "PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand" + { Remove-Item -LiteralPath ./foo*.txt -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand" } It "Remove-Item -LiteralPath should succeed for file with asterisk in name" -Skip:($IsWindows) { @@ -473,7 +473,7 @@ Describe "Hard link and symbolic link tests" -Tags "CI", "RequireAdminOnWindows" $link.Target | Should -Be $nonFile } It "New-Item emits an error when path to symbolic link already exists." { - { New-Item -ItemType SymbolicLink -Path $realDir -Value $symLinkToDir -ErrorAction Stop } | ShouldBeErrorId "SymLinkExists,Microsoft.PowerShell.Commands.NewItemCommand" + { New-Item -ItemType SymbolicLink -Path $realDir -Value $symLinkToDir -ErrorAction Stop } | Should -Throw -ErrorId "SymLinkExists,Microsoft.PowerShell.Commands.NewItemCommand" } It "New-Item can create a symbolic link to a directory" -Skip:($IsWindows) { New-Item -ItemType SymbolicLink -Path $symLinkToDir -Value $realDir @@ -720,7 +720,7 @@ Describe "Copy-Item can avoid copying an item onto itself" -Tags "CI", "RequireA } else { - { Copy-Item -Path $sourcePath -Destination $destinationPath -ErrorAction Stop } | ShouldBeErrorId "CopyError,Microsoft.PowerShell.Commands.CopyItemCommand" + { Copy-Item -Path $sourcePath -Destination $destinationPath -ErrorAction Stop } | Should -Throw -ErrorId "CopyError,Microsoft.PowerShell.Commands.CopyItemCommand" $Error[0].Exception | Should -BeOfType System.IO.IOException $Error[0].Exception.Data[$selfCopyKey] | Should -Not -BeNullOrEmpty } @@ -783,7 +783,7 @@ Describe "Copy-Item can avoid copying an item onto itself" -Tags "CI", "RequireA [string]$Destination ) - { Copy-Item -Path $Source -Destination $Destination -ErrorAction Stop } | ShouldBeErrorId "CopyError,Microsoft.PowerShell.Commands.CopyItemCommand" + { Copy-Item -Path $Source -Destination $Destination -ErrorAction Stop } | Should -Throw -ErrorId "CopyError,Microsoft.PowerShell.Commands.CopyItemCommand" $Error[0].Exception | Should -BeOfType System.IO.IOException $Error[0].Exception.Data[$selfCopyKey] | Should -Not -BeNullOrEmpty } @@ -939,7 +939,7 @@ Describe "Extended FileSystem Item/Content Cmdlet Provider Tests" -Tags "Feature } It "Verify -LiteralPath with wildcard fails for file that doesn't exist" { - { Get-Item -LiteralPath "a*b.txt" -ErrorAction Stop } | ShouldBeErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" + { Get-Item -LiteralPath "a*b.txt" -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } It "Verify -LiteralPath with wildcard succeeds for file" -Skip:($IsWindows) { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/FunctionProvider.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/FunctionProvider.Tests.ps1 index f287c404cf6..b21a8977b7d 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/FunctionProvider.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/FunctionProvider.Tests.ps1 @@ -58,7 +58,7 @@ Describe "Basic Function Provider Tests" -Tags "CI" { } It "Throws PSArgumentException when Set-Item is called with incorrect function value" { - { Set-Item $nonExistingFunction -Value 123 -ErrorAction Stop } | ShouldBeErrorId "Argument,Microsoft.PowerShell.Commands.SetItemCommand" + { Set-Item $nonExistingFunction -Value 123 -ErrorAction Stop } | Should -Throw -ErrorId "Argument,Microsoft.PowerShell.Commands.SetItemCommand" } } @@ -88,39 +88,39 @@ Describe "Basic Function Provider Tests" -Tags "CI" { Context "Validate Remove-Item Cmdlet" { It "Removes function" { Remove-Item $existingFunction - { Get-Item $existingFunction -ErrorAction Stop } | ShouldBeErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" + { Get-Item $existingFunction -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } It "Fails to remove not existing function" { - { Remove-Item $nonExistingFunction -ErrorAction Stop } | ShouldBeErrorId "PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand" + { Remove-Item $nonExistingFunction -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand" } } Context "Validate Rename-Item Cmdlet" { It "Renames existing function with None options" { Rename-Item $existingFunction -NewName $newName - { Get-Item $existingFunction -ErrorAction Stop } | ShouldBeErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" + { Get-Item $existingFunction -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" (Get-Item $newName).Count | Should -BeExactly 1 } It "Fails to rename not existing function" { - { Rename-Item $nonExistingFunction -NewName $newName -ErrorAction Stop } | ShouldBeErrorId "InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand" + { Rename-Item $nonExistingFunction -NewName $newName -ErrorAction Stop } | Should -Throw -ErrorId "InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand" } It "Fails to rename function which is Constant" { Set-Item $nonExistingFunction -Options "Constant" -Value $functionValue - { Rename-Item $nonExistingFunction -NewName $newName -ErrorAction Stop } | ShouldBeErrorId "CannotRenameFunction,Microsoft.PowerShell.Commands.RenameItemCommand" + { Rename-Item $nonExistingFunction -NewName $newName -ErrorAction Stop } | Should -Throw -ErrorId "CannotRenameFunction,Microsoft.PowerShell.Commands.RenameItemCommand" } It "Fails to rename function which is ReadOnly" { Set-Item $nonExistingFunction -Options "ReadOnly" - { Rename-Item $nonExistingFunction -NewName $newName -ErrorAction Stop } | ShouldBeErrorId "InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand" + { Rename-Item $nonExistingFunction -NewName $newName -ErrorAction Stop } | Should -Throw -ErrorId "InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand" } It "Renames ReadOnly function when -Force parameter is on" { Set-Item $nonExistingFunction -Options "ReadOnly" -Value $functionValue Rename-Item $nonExistingFunction -NewName $newName -Force - { Get-Item $nonExistingFunction -ErrorAction Stop } | ShouldBeErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" + { Get-Item $nonExistingFunction -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" (Get-Item $newName).Count | Should -BeExactly 1 } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 index 9ba435313ca..68e69060837 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 @@ -91,11 +91,11 @@ Describe "Get-Content" -Tags "CI" { } It 'Verifies -Tail reports a TailNotSupported error for unsupported providers' { - {Get-Content -Path Variable:\PSHOME -Tail 1 -ErrorAction Stop} | ShouldBeErrorId 'TailNotSupported,Microsoft.PowerShell.Commands.GetContentCommand' + {Get-Content -Path Variable:\PSHOME -Tail 1 -ErrorAction Stop} | Should -Throw -ErrorId 'TailNotSupported,Microsoft.PowerShell.Commands.GetContentCommand' } It 'Verifies using -Tail and -TotalCount together reports a TailAndHeadCannotCoexist error' { - { Get-Content -Path Variable:\PSHOME -Tail 1 -TotalCount 5 -ErrorAction Stop} | ShouldBeErrorId 'TailAndHeadCannotCoexist,Microsoft.PowerShell.Commands.GetContentCommand' + { Get-Content -Path Variable:\PSHOME -Tail 1 -TotalCount 5 -ErrorAction Stop} | Should -Throw -ErrorId 'TailAndHeadCannotCoexist,Microsoft.PowerShell.Commands.GetContentCommand' } It 'Verifies -Tail with content that uses an explicit encoding' -TestCases @( @@ -219,7 +219,7 @@ baz It "Should support NTFS streams using colon syntax" -Skip:(!$IsWindows) { Set-Content "${testPath}:Stream" -Value "Foo" - { Test-Path "${testPath}:Stream" | ShouldBeErrorId "ItemExistsNotSupportedError,Microsoft.PowerShell.Commands,TestPathCommand" } + { Test-Path "${testPath}:Stream" | Should -Throw -ErrorId "ItemExistsNotSupportedError,Microsoft.PowerShell.Commands,TestPathCommand" } Get-Content "${testPath}:Stream" | Should -BeExactly "Foo" Get-Content $testPath | Should -BeExactly $testString } @@ -234,7 +234,7 @@ baz Clear-Content -Path $testPath -Stream hello Get-Content -Path $testPath -Stream hello | Should -BeNullOrEmpty Remove-Item -Path $testPath -Stream hello - { Get-Content -Path $testPath -Stream hello | ShouldBeErrorId "GetContentReaderFileNotFoundError,Microsoft.PowerShell.Commands.GetContentCommand" } + { Get-Content -Path $testPath -Stream hello | Should -Throw -ErrorId "GetContentReaderFileNotFoundError,Microsoft.PowerShell.Commands.GetContentCommand" } } It "Should support colons in filename on Linux/Mac" -Skip:($IsWindows) { @@ -266,21 +266,21 @@ baz It "Should throw TailAndHeadCannotCoexist when both -Tail and -TotalCount are used" { { Get-Content -Path $testPath -Tail 1 -TotalCount 1 -ErrorAction Stop - } | ShouldBeErrorId "TailAndHeadCannotCoexist,Microsoft.PowerShell.Commands.GetContentCommand" + } | Should -Throw -ErrorId "TailAndHeadCannotCoexist,Microsoft.PowerShell.Commands.GetContentCommand" } It "Should throw TailNotSupported when -Tail used with an unsupported provider" { Push-Location env: { Get-Content PATH -Tail 1 -ErrorAction Stop - } | ShouldBeErrorId "TailNotSupported,Microsoft.PowerShell.Commands.GetContentCommand" + } | Should -Throw -ErrorId "TailNotSupported,Microsoft.PowerShell.Commands.GetContentCommand" Pop-Location } It "Should throw InvalidOperation when -Tail and -Raw are used" { { Get-Content -Path $testPath -Tail 1 -ErrorAction Stop -Raw - } | ShouldBeErrorId "InvalidOperation,Microsoft.PowerShell.Commands.GetContentCommand" + } | Should -Throw -ErrorId "InvalidOperation,Microsoft.PowerShell.Commands.GetContentCommand" } Context "Check Get-Content containing multi-byte chars" { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Item.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Item.Tests.ps1 index c66ba603afb..d1e37919d82 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Item.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Item.Tests.ps1 @@ -83,11 +83,11 @@ Describe "Get-Item" -Tags "CI" { Context "Error Condition Checking" { It "Should return an error if the provider does not exist" { - { Get-Item BadProvider::/BadFile -ErrorAction Stop } | ShouldBeErrorId "ProviderNotFound,Microsoft.PowerShell.Commands.GetItemCommand" + { Get-Item BadProvider::/BadFile -ErrorAction Stop } | Should -Throw -ErrorId "ProviderNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } It "Should return an error if the drive does not exist" { - { Get-Item BadDrive:/BadFile -ErrorAction Stop } | ShouldBeErrorId "DriveNotFound,Microsoft.PowerShell.Commands.GetItemCommand" + { Get-Item BadDrive:/BadFile -ErrorAction Stop } | Should -Throw -ErrorId "DriveNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Service.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Service.Tests.ps1 index 11cdf70e23b..75c7977c9d1 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Service.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Service.Tests.ps1 @@ -89,6 +89,6 @@ Describe "Get-Service cmdlet tests" -Tags "CI" { ErrorId = "NoServiceFoundForGivenDisplayName,Microsoft.PowerShell.Commands.GetServiceCommand" } ) { param($script,$errorid) - { & $script } | ShouldBeErrorId $errorid + { & $script } | Should -Throw -ErrorId $errorid } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Registry.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Registry.Tests.ps1 index 27798c83928..1e3a141a1bf 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Registry.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Registry.Tests.ps1 @@ -60,7 +60,7 @@ Describe "Basic Registry Provider Tests" -Tags @("CI", "RequireAdminOnWindows") } It "Verify Get-Item on inaccessible path" { - { Get-Item HKLM:\SAM\SAM -ErrorAction Stop } | ShouldBeErrorId "System.Security.SecurityException,Microsoft.PowerShell.Commands.GetItemCommand" + { Get-Item HKLM:\SAM\SAM -ErrorAction Stop } | Should -Throw -ErrorId "System.Security.SecurityException,Microsoft.PowerShell.Commands.GetItemCommand" } It "Verify Get-ChildItem" { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Rename-Computer.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Rename-Computer.Tests.ps1 index 64a30df86be..8cb63a0583a 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Rename-Computer.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Rename-Computer.Tests.ps1 @@ -65,7 +65,7 @@ try It "Renaming '' to '' creates the right error" -testcase $testcases { param ( $OldName, $NewName, $ExpectedError ) Set-TesthookResult -testhookName $RenameResultName -value 0x1 - { Rename-Computer -ComputerName $OldName -NewName $NewName -ErrorAction Stop } | ShouldBeErrorId $ExpectedError + { Rename-Computer -ComputerName $OldName -NewName $NewName -ErrorAction Stop } | Should -Throw -ErrorId $ExpectedError } } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Restart-Computer.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Restart-Computer.Tests.ps1 index 8c6c07c78dc..feb4c07e096 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Restart-Computer.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Restart-Computer.Tests.ps1 @@ -78,17 +78,17 @@ try } It "Should produce an error when 'Delay' is specified" { - { Restart-Computer -Delay 30 } | ShouldBeErrorId "RestartComputerInvalidParameter,Microsoft.PowerShell.Commands.RestartComputerCommand" + { Restart-Computer -Delay 30 } | Should -Throw -ErrorId "RestartComputerInvalidParameter,Microsoft.PowerShell.Commands.RestartComputerCommand" } It "Should not support timeout on localhost" { Set-TesthookResult -testhookName $restartTesthookResultName -value $defaultResultValue - { Restart-Computer -timeout 3 -ErrorAction Stop } | ShouldBeErrorId "RestartComputerInvalidParameter,Microsoft.PowerShell.Commands.RestartComputerCommand" + { Restart-Computer -timeout 3 -ErrorAction Stop } | Should -Throw -ErrorId "RestartComputerInvalidParameter,Microsoft.PowerShell.Commands.RestartComputerCommand" } It "Should not support timeout on localhost" { Set-TesthookResult -testhookName $restartTesthookResultName -value $defaultResultValue - { Restart-Computer -timeout 3 -ErrorAction Stop } | ShouldBeErrorId "RestartComputerInvalidParameter,Microsoft.PowerShell.Commands.RestartComputerCommand" + { Restart-Computer -timeout 3 -ErrorAction Stop } | Should -Throw -ErrorId "RestartComputerInvalidParameter,Microsoft.PowerShell.Commands.RestartComputerCommand" } } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Set-Service.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Set-Service.Tests.ps1 index 11ef0cb03e7..c2920d61235 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Set-Service.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Set-Service.Tests.ps1 @@ -59,7 +59,7 @@ Describe "Set/New/Remove-Service cmdlet tests" -Tags "Feature", "RequireAdminOnW } ) { param($script, $errorid) - { & $script } | ShouldBeErrorId $errorid + { & $script } | Should -Throw -ErrorId $errorid } It "Set-Service can change '' to ''" -TestCases @( @@ -240,7 +240,7 @@ Describe "Set/New/Remove-Service cmdlet tests" -Tags "Feature", "RequireAdminOnW } It "Remove-Service cannot accept a service that does not exist" { - { Remove-Service -Name "testremoveservice" -ErrorAction 'Stop' } | ShouldBeErrorId "InvalidOperationException,Microsoft.PowerShell.Commands.RemoveServiceCommand" + { Remove-Service -Name "testremoveservice" -ErrorAction 'Stop' } | Should -Throw -ErrorId "InvalidOperationException,Microsoft.PowerShell.Commands.RemoveServiceCommand" } It "Get-Service can get the '' of a service" -TestCases @( @@ -327,6 +327,6 @@ Describe "Set/New/Remove-Service cmdlet tests" -Tags "Feature", "RequireAdminOnW if ($cmdlet -eq "New-Service") { $parameters += @{Binary = "$PSHOME\pwsh.exe"}; } - { & $cmdlet @parameters } | ShouldBeErrorId $errorid + { & $cmdlet @parameters } | Should -Throw -ErrorId $errorid } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Start-Process.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Start-Process.Tests.ps1 index afaf014e9dd..4f968679851 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Start-Process.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Start-Process.Tests.ps1 @@ -88,16 +88,16 @@ Describe "Start-Process" -Tags @("Feature") { ## -Verb is supported in PowerShell core on Windows full desktop. It "Should give an error when -Verb parameter is used" -Skip:$isFullWin { - { Start-Process -Verb runas -FilePath $pingCommand } | ShouldBeErrorId "NotSupportedException,Microsoft.PowerShell.Commands.StartProcessCommand" + { Start-Process -Verb runas -FilePath $pingCommand } | Should -Throw -ErrorId "NotSupportedException,Microsoft.PowerShell.Commands.StartProcessCommand" } ## -WindowStyle is supported in PowerShell core on Windows full desktop. It "Should give an error when -WindowStyle parameter is used" -Skip:$isFullWin { - { Start-Process -FilePath $pingCommand -WindowStyle Normal } | ShouldBeErrorId "NotSupportedException,Microsoft.PowerShell.Commands.StartProcessCommand" + { Start-Process -FilePath $pingCommand -WindowStyle Normal } | Should -Throw -ErrorId "NotSupportedException,Microsoft.PowerShell.Commands.StartProcessCommand" } It "Should give an error when both -NoNewWindow and -WindowStyle are specified" -Skip:(!$isFullWin) { - { Start-Process -FilePath $pingCommand -NoNewWindow -WindowStyle Normal -ErrorAction Stop } | ShouldBeErrorId "InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand" + { Start-Process -FilePath $pingCommand -NoNewWindow -WindowStyle Normal -ErrorAction Stop } | Should -Throw -ErrorId "InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand" } It "Should start cmd.exe with Verb 'open' and WindowStyle 'Minimized'" -Skip:(!$isFullWin) { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Test-Connection.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Test-Connection.Tests.ps1 index 1e049a2b77d..075958f98f8 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Test-Connection.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Test-Connection.Tests.ps1 @@ -69,7 +69,7 @@ Describe "Test-Connection" -tags "CI" { It "Ping fake host" { - { $result = Test-Connection "fakeHost" -Count 1 -Quiet -ErrorAction Stop } | ShouldBeErrorId "TestConnectionException,Microsoft.PowerShell.Commands.TestConnectionCommand" + { $result = Test-Connection "fakeHost" -Count 1 -Quiet -ErrorAction Stop } | Should -Throw -ErrorId "TestConnectionException,Microsoft.PowerShell.Commands.TestConnectionCommand" # Error code = 11001 - Host not found. if (!$isWindows) { $Error[0].Exception.InnerException.ErrorCode | Should -Be 6 @@ -118,18 +118,18 @@ Describe "Test-Connection" -tags "CI" { } It "MaxHops Should -Be greater 0" { - { Test-Connection $targetName -MaxHops 0 } | ShouldBeErrorId "System.ArgumentOutOfRangeException,Microsoft.PowerShell.Commands.TestConnectionCommand" - { Test-Connection $targetName -MaxHops -1 } | ShouldBeErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" + { Test-Connection $targetName -MaxHops 0 } | Should -Throw -ErrorId "System.ArgumentOutOfRangeException,Microsoft.PowerShell.Commands.TestConnectionCommand" + { Test-Connection $targetName -MaxHops -1 } | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" } It "Count Should -Be greater 0" { - { Test-Connection $targetName -Count 0 } | ShouldBeErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" - { Test-Connection $targetName -Count -1 } | ShouldBeErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" + { Test-Connection $targetName -Count 0 } | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" + { Test-Connection $targetName -Count -1 } | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" } It "Delay Should -Be greater 0" { - { Test-Connection $targetName -Delay 0 } | ShouldBeErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" - { Test-Connection $targetName -Delay -1 } | ShouldBeErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" + { Test-Connection $targetName -Delay 0 } | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" + { Test-Connection $targetName -Delay -1 } | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" } It "Delay works" { @@ -143,8 +143,8 @@ Describe "Test-Connection" -tags "CI" { It "BufferSize Should -Be between 0 and 65500" { { Test-Connection $targetName -BufferSize 0 } | Should Not Throw - { Test-Connection $targetName -BufferSize -1 } | ShouldBeErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" - { Test-Connection $targetName -BufferSize 65501 } | ShouldBeErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" + { Test-Connection $targetName -BufferSize -1 } | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" + { Test-Connection $targetName -BufferSize 65501 } | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" } It "BufferSize works" { From d4bb02699a1e42d119295e6c45fa3e20beb1f4ba Mon Sep 17 00:00:00 2001 From: kalgiz Date: Tue, 17 Apr 2018 17:36:01 -0700 Subject: [PATCH 07/58] [Feature] ShouldBeErrorId => Should -Throw -ErrorId in Utility module. --- .../Clear-Variable.Tests.ps1 | 4 +- .../ConvertTo-Csv.Tests.ps1 | 2 +- .../Export-Csv.Tests.ps1 | 4 +- .../Get-Date.Tests.ps1 | 2 +- .../JsonObject.Tests.ps1 | 2 +- .../New-Object.Tests.ps1 | 6 +- .../Out-String.Tests.ps1 | 2 +- .../Remove-Alias.Tests.ps1 | 18 +++--- .../Set-Date.Tests.ps1 | 2 +- .../Test-Json.Tests.ps1 | 2 +- .../Unblock-File.Tests.ps1 | 6 +- .../Update-FormatData.Tests.ps1 | 2 +- .../WebCmdlets.Tests.ps1 | 59 +++++++++---------- .../Write-Error.Tests.ps1 | 15 +---- 14 files changed, 54 insertions(+), 72 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 index 3099e88b6ea..50ff168743e 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 @@ -14,7 +14,7 @@ Describe "Clear-Variable DRT Unit Tests" -Tags "CI" { It "Clear-Variable ReadOnly variable Name should throw exception and force Clear-Variable should works"{ Set-Variable foo bar -Option ReadOnly - $e = { Clear-Variable -Name foo -Scope 1 -EA Stop } | ShouldBeErrorId "VariableNotWritable,Microsoft.PowerShell.Commands.ClearVariableCommand" + $e = { Clear-Variable -Name foo -Scope 1 -EA Stop } | Should -Throw -ErrorId "VariableNotWritable,Microsoft.PowerShell.Commands.ClearVariableCommand" $e.CategoryInfo | Should -Match "SessionStateUnauthorizedAccessException" Clear-Variable -Name foo -Force @@ -50,7 +50,7 @@ Describe "Clear-Variable DRT Unit Tests" -Tags "CI" { Set-Variable foo bar -Option Private &{ $e = { Get-Variable -Name foo -Scope local -EA Stop } | - ShouldBeErrorId "VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand" + Should -Throw -ErrorId "VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand" $e.CategoryInfo | Should -Match "ItemNotFoundException" } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Csv.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Csv.Tests.ps1 index c98d082a10d..f5f8c18ee6e 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Csv.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Csv.Tests.ps1 @@ -91,7 +91,7 @@ Describe "ConvertTo-Csv" -Tags "CI" { It "Does not support -IncludeTypeInformation and -NoTypeInformation at the same time" { { $testObject | ConvertTo-Csv -IncludeTypeInformation -NoTypeInformation } | - ShouldBeErrorId "CannotSpecifyIncludeTypeInformationAndNoTypeInformation,Microsoft.PowerShell.Commands.ConvertToCsvCommand" + Should -Throw -ErrorId "CannotSpecifyIncludeTypeInformationAndNoTypeInformation,Microsoft.PowerShell.Commands.ConvertToCsvCommand" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Csv.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Csv.Tests.ps1 index 6dc8c328dfc..616010e29f3 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Csv.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Csv.Tests.ps1 @@ -15,7 +15,7 @@ Describe "Export-Csv" -Tags "CI" { } It "Should throw if an output file isn't specified" { - { $testObject | Export-Csv -ErrorAction Stop } | ShouldBeErrorId "CannotSpecifyPathAndLiteralPath,Microsoft.PowerShell.Commands.ExportCsvCommand" + { $testObject | Export-Csv -ErrorAction Stop } | Should -Throw -ErrorId "CannotSpecifyPathAndLiteralPath,Microsoft.PowerShell.Commands.ExportCsvCommand" } It "Should be a string when exporting via pipe" { @@ -69,7 +69,7 @@ Describe "Export-Csv" -Tags "CI" { It "Does not support -IncludeTypeInformation and -NoTypeInformation at the same time" { { $testObject | Export-Csv -Path $testCsv -IncludeTypeInformation -NoTypeInformation } | - ShouldBeErrorId "CannotSpecifyIncludeTypeInformationAndNoTypeInformation,Microsoft.PowerShell.Commands.ExportCsvCommand" + Should -Throw -ErrorId "CannotSpecifyIncludeTypeInformationAndNoTypeInformation,Microsoft.PowerShell.Commands.ExportCsvCommand" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Date.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Date.Tests.ps1 index b5e448277a8..170bea0edc4 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Date.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Date.Tests.ps1 @@ -76,7 +76,7 @@ Describe "Get-Date DRT Unit Tests" -Tags "CI" { @{ name = "empty string"; value = "" } ) { param($value) - { Get-date -Date 1/1/1970 -uformat $value -ErrorAction Stop } | ShouldBeErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetDateCommand" + { Get-date -Date 1/1/1970 -uformat $value -ErrorAction Stop } | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetDateCommand" } It "Get-date works with pipeline input" { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/JsonObject.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/JsonObject.Tests.ps1 index 7c6e0a7d64f..a23d404bb1b 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/JsonObject.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/JsonObject.Tests.ps1 @@ -31,7 +31,7 @@ Describe 'Unit tests for JsonObject' -tags "CI" { ) { param ($str, $ReturnHashTable) $errRecord = $null - { [Microsoft.PowerShell.Commands.JsonObject]::ConvertFromJson($str, $ReturnHashTable, [ref]$errRecord) } | ShouldBeErrorId "ArgumentException" + { [Microsoft.PowerShell.Commands.JsonObject]::ConvertFromJson($str, $ReturnHashTable, [ref]$errRecord) } | Should -Throw -ErrorId "ArgumentException" } Context 'Empty key name' { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/New-Object.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/New-Object.Tests.ps1 index 2a20fae24af..2046ab829ca 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/New-Object.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/New-Object.Tests.ps1 @@ -3,7 +3,7 @@ Describe "New-Object" -Tags "CI" { It "Support 'ComObject' parameter on platforms" { if ($IsLinux -or $IsMacOs ) { - { New-Object -ComObject "Shell.Application" } | ShouldBeErrorId "NamedParameterNotFound,Microsoft.PowerShell.Commands.NewObjectCommand" + { New-Object -ComObject "Shell.Application" } | Should -Throw -ErrorId "NamedParameterNotFound,Microsoft.PowerShell.Commands.NewObjectCommand" } else { # It works on NanoServer and IoT too (Get-Command "New-Object").Parameters.ContainsKey("ComObject") | Should -BeTrue @@ -116,7 +116,7 @@ Describe "New-Object DRT basic functionality" -Tags "CI" { { Add-Type -TypeDefinition "public class Employee{public Employee(string firstName,string lastName,int yearsInMS){FirstName = firstName;LastName=lastName;YearsInMS = yearsInMS;}public string FirstName;public string LastName;public int YearsInMS;}" } - { New-Object -TypeName Employee -EA Stop } | ShouldBeErrorId "CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand" + { New-Object -TypeName Employee -EA Stop } | Should -Throw -ErrorId "CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand" } It "New-Object with Private Nested class should throw Exception"{ @@ -158,7 +158,7 @@ try } It "Should fail with correct error when creating a COM object that dose not exist" { - {New-Object -ComObject 'doesnotexist'} | ShouldBeErrorId 'NoCOMClassIdentified,Microsoft.PowerShell.Commands.NewObjectCommand' + {New-Object -ComObject 'doesnotexist'} | Should -Throw -ErrorId 'NoCOMClassIdentified,Microsoft.PowerShell.Commands.NewObjectCommand' } } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Out-String.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Out-String.Tests.ps1 index 165ee0f0d52..fb85450c6ca 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Out-String.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Out-String.Tests.ps1 @@ -60,6 +60,6 @@ Describe "Out-String" -Tags "CI" { It "Should throw error when NoNewLine and Stream are used together" { $testArray = "a", "b" - { $testArray | Out-String -NoNewLine -Stream } | ShouldBeErrorId "AmbiguousParameterSet,Microsoft.PowerShell.Commands.OutStringCommand" + { $testArray | Out-String -NoNewLine -Stream } | Should -Throw -ErrorId "AmbiguousParameterSet,Microsoft.PowerShell.Commands.OutStringCommand" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Remove-Alias.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Remove-Alias.Tests.ps1 index 5c3b8683a06..80b12ce3e91 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Remove-Alias.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Remove-Alias.Tests.ps1 @@ -11,14 +11,14 @@ Describe "Remove-Alias" -Tags "CI" { Set-Alias -Name $testAliasName -Value "Remove-Alias" -ErrorAction Stop Remove-Alias -Name $testAliasName -ErrorAction Stop Get-Alias -Name $testAliasName -ErrorAction Stop - } | ShouldBeErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.GetAliasCommand' + } | Should -Throw -ErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.GetAliasCommand' } It "Remove-Alias should throw on a readonly alias"{ { Set-Alias -Name $testAliasName -Value "Remove-Alias" -Option ReadOnly -ErrorAction Stop Remove-Alias -Name $testAliasName -ErrorAction Stop - } | ShouldBeErrorId 'AliasNotRemovable,Microsoft.PowerShell.Commands.RemoveAliasCommand' + } | Should -Throw -ErrorId 'AliasNotRemovable,Microsoft.PowerShell.Commands.RemoveAliasCommand' } It "Remove-Alias should remove a non-readonly alias with force"{ @@ -26,7 +26,7 @@ Describe "Remove-Alias" -Tags "CI" { Set-Alias -Name $testAliasName -Value "Remove-Alias" -ErrorAction Stop Remove-Alias -Name $testAliasName -Force -ErrorAction Stop Get-Alias -Name $testAliasName -ErrorAction Stop - } | ShouldBeErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.GetAliasCommand' + } | Should -Throw -ErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.GetAliasCommand' } It "Remove-Alias should remove a readonly alias with force"{ @@ -34,14 +34,14 @@ Describe "Remove-Alias" -Tags "CI" { Set-Alias -Name $testAliasName -Value "Remove-Alias" -Option ReadOnly -ErrorAction Stop Remove-Alias -Name $testAliasName -Force -ErrorAction Stop Get-Alias -Name $testAliasName -ErrorAction Stop - } | ShouldBeErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.GetAliasCommand' + } | Should -Throw -ErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.GetAliasCommand' } It "Remove-Alias should throw if alias does not exist"{ { Get-Alias -Name $testAliasName -ErrorAction SilentlyContinue | Should -BeNullorEmpty Remove-Alias -Name $testAliasName -ErrorAction Stop - } | ShouldBeErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.RemoveAliasCommand' + } | Should -Throw -ErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.RemoveAliasCommand' } It "Remove-Alias should remove multiple alias at once"{ @@ -50,9 +50,9 @@ Describe "Remove-Alias" -Tags "CI" { Set-Alias -Name "$testAliasName-2" -Value "Remove-Alias" -ErrorAction Stop Set-Alias -Name "$testAliasName-3" -Value "Remove-Alias" -ErrorAction Stop Remove-Alias -Name "$testAliasName","$testAliasName-2","$testAliasName-3" -ErrorAction Stop - Get-Alias -Name "$testAliasName" -ErrorAction Stop | ShouldBeErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.GetAliasCommand' - Get-Alias -Name "$testAliasName-2" -ErrorAction Stop | ShouldBeErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.GetAliasCommand' - Get-Alias -Name "$testAliasName-3" -ErrorAction Stop | ShouldBeErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.GetAliasCommand' + Get-Alias -Name "$testAliasName" -ErrorAction Stop | Should -Throw -ErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.GetAliasCommand' + Get-Alias -Name "$testAliasName-2" -ErrorAction Stop | Should -Throw -ErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.GetAliasCommand' + Get-Alias -Name "$testAliasName-3" -ErrorAction Stop | Should -Throw -ErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.GetAliasCommand' } } @@ -60,6 +60,6 @@ Describe "Remove-Alias" -Tags "CI" { { Set-Alias -Name $testAliasName -Value "Remove-Alias" -ErrorAction Stop Remove-Alias -Name $testAliasName -Scope 99999 -ErrorAction Stop - } | ShouldBeErrorId "ArgumentOutOfRange,Microsoft.PowerShell.Commands.RemoveAliasCommand" + } | Should -Throw -ErrorId "ArgumentOutOfRange,Microsoft.PowerShell.Commands.RemoveAliasCommand" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Set-Date.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Set-Date.Tests.ps1 index 2e2234d2336..ffd5ea9ffb2 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Set-Date.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Set-Date.Tests.ps1 @@ -14,6 +14,6 @@ Describe "Set-Date for admin" -Tag @('CI', 'RequireAdminOnWindows', 'RequireSudo Describe "Set-Date" -Tag 'CI' { It "Set-Date should produce an error in a non-elevated context" { - { Get-Date | Set-Date } | ShouldBeErrorId "System.ComponentModel.Win32Exception,Microsoft.PowerShell.Commands.SetDateCommand" + { Get-Date | Set-Date } | Should -Throw -ErrorId "System.ComponentModel.Win32Exception,Microsoft.PowerShell.Commands.SetDateCommand" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Test-Json.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Test-Json.Tests.ps1 index e7bc5c6106a..d659c382dce 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Test-Json.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Test-Json.Tests.ps1 @@ -79,7 +79,7 @@ Describe "Test-Json" -Tags "CI" { } It "Test-Json throw if a schema is invalid" { - { Test-Json -Json $validJson -Schema $invalidSchemaJson -ErrorAction Stop } | ShouldBeErrorId "InvalidJsonSchema,Microsoft.PowerShell.Commands.TestJsonCommand" + { Test-Json -Json $validJson -Schema $invalidSchemaJson -ErrorAction Stop } | Should -Throw -ErrorId "InvalidJsonSchema,Microsoft.PowerShell.Commands.TestJsonCommand" } It "Test-Json write an error on invalid () Json aganist a valid schema" -TestCases @( diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 index 8242d13ec70..c615191d22a 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 @@ -39,11 +39,11 @@ Describe "Unblock-File" -Tags "CI" { } It "With '-Path': no file exist" { - { Unblock-File -Path nofileexist.ttt -ErrorAction Stop } | ShouldBeErrorId "FileNotFound,Microsoft.PowerShell.Commands.UnblockFileCommand" + { Unblock-File -Path nofileexist.ttt -ErrorAction Stop } | Should -Throw -ErrorId "FileNotFound,Microsoft.PowerShell.Commands.UnblockFileCommand" } It "With '-LiteralPath': no file exist" { - { Unblock-File -LiteralPath nofileexist.ttt -ErrorAction Stop } | ShouldBeErrorId "FileNotFound,Microsoft.PowerShell.Commands.UnblockFileCommand" + { Unblock-File -LiteralPath nofileexist.ttt -ErrorAction Stop } | Should -Throw -ErrorId "FileNotFound,Microsoft.PowerShell.Commands.UnblockFileCommand" } It "With '-Path': file exist" { @@ -72,6 +72,6 @@ Describe "Unblock-File" -Tags "CI" { $TestFileCreated = Get-ChildItem $TestFile $TestFileCreated.IsReadOnly | Should -BeTrue - { Unblock-File -LiteralPath $TestFile -ErrorAction Stop } | ShouldBeErrorId "RemoveItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.UnblockFileCommand" + { Unblock-File -LiteralPath $TestFile -ErrorAction Stop } | Should -Throw -ErrorId "RemoveItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.UnblockFileCommand" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Update-FormatData.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Update-FormatData.Tests.ps1 index 43df9b2d24b..e50cd51acd0 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Update-FormatData.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Update-FormatData.Tests.ps1 @@ -70,7 +70,7 @@ Describe "Update-FormatData basic functionality" -Tags "CI" { "@ $xmlContent | Out-File -FilePath "$testdrive\test.format.ps1xml" -Encoding ascii - { Update-FormatData -Path "$testdrive\test.format.ps1xml" -ErrorAction Stop } | ShouldBeErrorId "FormatXmlUpdateException,Microsoft.PowerShell.Commands.UpdateFormatDataCommand" + { Update-FormatData -Path "$testdrive\test.format.ps1xml" -ErrorAction Stop } | Should -Throw -ErrorId "FormatXmlUpdateException,Microsoft.PowerShell.Commands.UpdateFormatDataCommand" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index 1f7bb99f172..e6f341bee81 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -654,7 +654,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { $uri = Get-WebListenerUrl -Test 'Get' #Validate that parameter sets are functioning correctly $errorId = "AmbiguousParameterSet,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" - { Invoke-WebRequest -Uri $uri -Method GET -CustomMethod TEST } | ShouldBeErrorId $errorId + { Invoke-WebRequest -Uri $uri -Method GET -CustomMethod TEST } | Should -Throw -ErrorId $errorId } It "Validate Invoke-WebRequest CustomMethod method is used" { @@ -927,7 +927,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { $uri = Get-WebListenerUrl -Test 'Post' { Invoke-WebRequest -Uri $uri -Method 'Post' -ContentType $contentType -Body $body -ErrorAction 'Stop' } | - ShouldBeErrorId "WebCmdletContentTypeException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" + Should -Throw -ErrorId "WebCmdletContentTypeException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" } It "Verifies Invoke-WebRequest ContentType handling reports no error is returned for an invalid Content-Type header value, -Body, and -SkipHeaderValidation" { @@ -959,7 +959,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { $uri = Get-WebListenerUrl -Test 'Post' { Invoke-WebRequest -Uri $uri -Method 'Post' -ContentType $contentType -InFile $Testfile -ErrorAction 'Stop' } | - ShouldBeErrorId "WebCmdletContentTypeException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" + Should -Throw -ErrorId "WebCmdletContentTypeException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" } It "Verifies Invoke-WebRequest default ContentType handling reports no error is returned for an invalid Content-Type header value, -Infile, and -SkipHeaderValidation" { @@ -1375,7 +1375,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { $uri = Get-WebListenerUrl -Test 'Multipart' {Invoke-WebRequest -Uri $uri -Form $form -Body $Body -ErrorAction 'Stop'} | - ShouldBeErrorId 'WebCmdletBodyFormConflictException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand' + Should -Throw -ErrorId 'WebCmdletBodyFormConflictException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand' } It "Verifies Invoke-WebRequest -Form is mutually exclusive with -InFile" { @@ -1383,7 +1383,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { $uri = Get-WebListenerUrl -Test 'Multipart' {Invoke-WebRequest -Uri $uri -Form $form -InFile $file1Path -ErrorAction 'Stop'} | - ShouldBeErrorId 'WebCmdletFormInFileConflictException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand' + Should -Throw -ErrorId 'WebCmdletFormInFileConflictException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand' } } @@ -1438,7 +1438,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { ErrorAction = 'Stop' SkipCertificateCheck = $true } - { Invoke-WebRequest @params } | ShouldBeErrorId "WebCmdletAuthenticationConflictException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" + { Invoke-WebRequest @params } | Should -Throw -ErrorId "WebCmdletAuthenticationConflictException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" } It "Verifies Invoke-WebRequest -Authentication does not support Both -Credential and -Token" { @@ -1450,7 +1450,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { ErrorAction = 'Stop' SkipCertificateCheck = $true } - { Invoke-WebRequest @params } | ShouldBeErrorId "WebCmdletAuthenticationTokenConflictException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" + { Invoke-WebRequest @params } | Should -Throw -ErrorId "WebCmdletAuthenticationTokenConflictException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" } It "Verifies Invoke-WebRequest -Authentication requires -Token" -TestCases $testCases { @@ -1461,7 +1461,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { ErrorAction = 'Stop' SkipCertificateCheck = $true } - { Invoke-WebRequest @params } | ShouldBeErrorId "WebCmdletAuthenticationTokenNotSuppliedException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" + { Invoke-WebRequest @params } | Should -Throw -ErrorId "WebCmdletAuthenticationTokenNotSuppliedException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" } It "Verifies Invoke-WebRequest -Authentication Basic requires -Credential" { @@ -1471,7 +1471,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { ErrorAction = 'Stop' SkipCertificateCheck = $true } - { Invoke-WebRequest @params } | ShouldBeErrorId "WebCmdletAuthenticationCredentialNotSuppliedException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" + { Invoke-WebRequest @params } | Should -Throw -ErrorId "WebCmdletAuthenticationCredentialNotSuppliedException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" } It "Verifies Invoke-WebRequest -Authentication Requires HTTPS" { @@ -1481,7 +1481,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { Authentication = "OAuth" ErrorAction = 'Stop' } - { Invoke-WebRequest @params } | ShouldBeErrorId "WebCmdletAllowUnencryptedAuthenticationRequiredException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" + { Invoke-WebRequest @params } | Should -Throw -ErrorId "WebCmdletAllowUnencryptedAuthenticationRequiredException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" } It "Verifies Invoke-WebRequest -Authentication Can use HTTP with -AllowUnencryptedAuthentication" { @@ -1515,7 +1515,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { Credential = $credential ErrorAction = 'Stop' } - { Invoke-WebRequest @params } | ShouldBeErrorId "WebCmdletAllowUnencryptedAuthenticationRequiredException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" + { Invoke-WebRequest @params } | Should -Throw -ErrorId "WebCmdletAllowUnencryptedAuthenticationRequiredException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" } It "Verifies Invoke-WebRequest Negotiated -Credential Can use HTTP with -AllowUnencryptedAuthentication" { @@ -1554,7 +1554,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { UseDefaultCredentials = $true ErrorAction = 'Stop' } - { Invoke-WebRequest @params } | ShouldBeErrorId "WebCmdletAllowUnencryptedAuthenticationRequiredException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" + { Invoke-WebRequest @params } | Should -Throw -ErrorId "WebCmdletAllowUnencryptedAuthenticationRequiredException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" } # UseDefaultCredentials is only reliably testable on Windows @@ -1634,7 +1634,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { SkipCertificateCheck = $true ErrorAction = 'Stop' } - { Invoke-WebRequest @params } | ShouldBeErrorId 'WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand' + { Invoke-WebRequest @params } | Should -Throw -ErrorId 'WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand' } } } @@ -2019,7 +2019,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" { It "Validate Invoke-RestMethod StandardMethod and CustomMethod parameter sets" { $uri = Get-WebListenerUrl -Test 'Get' $errorId = "AmbiguousParameterSet,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" - { Invoke-RestMethod -Uri $uri -Method GET -CustomMethod TEST } | ShouldBeErrorId $errorId + { Invoke-RestMethod -Uri $uri -Method GET -CustomMethod TEST } | Should -Throw -ErrorId $errorId } It "Validate CustomMethod method is used" { @@ -2262,7 +2262,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" { $uri = Get-WebListenerUrl -Test 'Post' { Invoke-RestMethod -Uri $uri -Method 'Post' -ContentType $contentType -Body $body -ErrorAction 'Stop' } | - ShouldBeErrorId "WebCmdletContentTypeException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" + Should -Throw -ErrorId "WebCmdletContentTypeException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" } It "Verifies Invoke-RestMethod ContentType handling reports no error is returned for an invalid Content-Type header value, -Body, and -SkipHeaderValidation" { @@ -2292,7 +2292,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" { $uri = Get-WebListenerUrl -Test 'Post' { Invoke-RestMethod -Uri $uri -Method 'Post' -ContentType $contentType -InFile $Testfile -ErrorAction 'Stop' } | - ShouldBeErrorId "WebCmdletContentTypeException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" + Should -Throw -ErrorId "WebCmdletContentTypeException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" } It "Verifies Invoke-RestMethod default ContentType handling reports no error is returned for an invalid Content-Type header value, -Infile, and -SkipHeaderValidation" { @@ -2493,7 +2493,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" { $uri = Get-WebListenerUrl -Test 'Multipart' {Invoke-RestMethod -Uri $uri -Form $form -Body $Body -ErrorAction 'Stop'} | - ShouldBeErrorId 'WebCmdletBodyFormConflictException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand' + Should -Throw -ErrorId 'WebCmdletBodyFormConflictException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand' } It "Verifies Invoke-RestMethod -Form is mutually exclusive with -InFile" { @@ -2501,7 +2501,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" { $uri = Get-WebListenerUrl -Test 'Multipart' {Invoke-RestMethod -Uri $uri -Form $form -InFile $file1Path -ErrorAction 'Stop'} | - ShouldBeErrorId 'WebCmdletFormInFileConflictException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand' + Should -Throw -ErrorId 'WebCmdletFormInFileConflictException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand' } } @@ -2714,7 +2714,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" { ErrorAction = 'Stop' SkipCertificateCheck = $true } - { Invoke-RestMethod @params } | ShouldBeErrorId "WebCmdletAuthenticationConflictException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" + { Invoke-RestMethod @params } | Should -Throw -ErrorId "WebCmdletAuthenticationConflictException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" } It "Verifies Invoke-RestMethod -Authentication does not support Both -Credential and -Token" { @@ -2726,7 +2726,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" { ErrorAction = 'Stop' SkipCertificateCheck = $true } - { Invoke-RestMethod @params } | ShouldBeErrorId "WebCmdletAuthenticationTokenConflictException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" + { Invoke-RestMethod @params } | Should -Throw -ErrorId "WebCmdletAuthenticationTokenConflictException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" } It "Verifies Invoke-RestMethod -Authentication requires -Token" -TestCases $testCases { @@ -2737,7 +2737,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" { ErrorAction = 'Stop' SkipCertificateCheck = $true } - { Invoke-RestMethod @params } | ShouldBeErrorId "WebCmdletAuthenticationTokenNotSuppliedException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" + { Invoke-RestMethod @params } | Should -Throw -ErrorId "WebCmdletAuthenticationTokenNotSuppliedException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" } It "Verifies Invoke-RestMethod -Authentication Basic requires -Credential" { @@ -2747,7 +2747,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" { ErrorAction = 'Stop' SkipCertificateCheck = $true } - { Invoke-RestMethod @params } | ShouldBeErrorId "WebCmdletAuthenticationCredentialNotSuppliedException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" + { Invoke-RestMethod @params } | Should -Throw -ErrorId "WebCmdletAuthenticationCredentialNotSuppliedException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" } It "Verifies Invoke-RestMethod -Authentication Requires HTTPS" { @@ -2757,7 +2757,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" { Authentication = "OAuth" ErrorAction = 'Stop' } - { Invoke-RestMethod @params } | ShouldBeErrorId "WebCmdletAllowUnencryptedAuthenticationRequiredException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" + { Invoke-RestMethod @params } | Should -Throw -ErrorId "WebCmdletAllowUnencryptedAuthenticationRequiredException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" } It "Verifies Invoke-RestMethod -Authentication Can use HTTP with -AllowUnencryptedAuthentication" { @@ -2789,7 +2789,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" { Credential = $credential ErrorAction = 'Stop' } - { Invoke-RestMethod @params } | ShouldBeErrorId "WebCmdletAllowUnencryptedAuthenticationRequiredException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" + { Invoke-RestMethod @params } | Should -Throw -ErrorId "WebCmdletAllowUnencryptedAuthenticationRequiredException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" } It "Verifies Invoke-RestMethod Negotiated -Credential Can use HTTP with -AllowUnencryptedAuthentication" { @@ -2826,7 +2826,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" { UseDefaultCredentials = $true ErrorAction = 'Stop' } - { Invoke-RestMethod @params } | ShouldBeErrorId "WebCmdletAllowUnencryptedAuthenticationRequiredException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" + { Invoke-RestMethod @params } | Should -Throw -ErrorId "WebCmdletAllowUnencryptedAuthenticationRequiredException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" } # UseDefaultCredentials is only reliably testable on Windows @@ -2903,7 +2903,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" { SkipCertificateCheck = $true ErrorAction = 'Stop' } - { Invoke-RestMethod @params } | ShouldBeErrorId 'WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand' + { Invoke-RestMethod @params } | Should -Throw -ErrorId 'WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand' } } } @@ -3120,12 +3120,7 @@ Describe "Validate Invoke-WebRequest and Invoke-RestMethod -InFile" -Tags "Featu It "" -TestCases $testCases { param ($scriptblock, $expectedFullyQualifiedErrorId) - try { - & $scriptblock - throw "No Exception!" - } catch { - $_.FullyQualifiedErrorId | Should -Be $ExpectedFullyQualifiedErrorId - } + { & $scriptblock } | Should -Throw -ErrorId $ExpectedFullyQualifiedErrorId } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Error.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Error.Tests.ps1 index 54818d132e3..22734cc2a0c 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Error.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Error.Tests.ps1 @@ -86,20 +86,7 @@ Describe "Write-Error Tests" -Tags "CI" { } It "Should trip an exception using the exception switch" { - $var = 0 - try - { - Write-Error -Exception -Message "test throw" - } - catch [System.Exception] - { - - $var++ - } - finally - { - $var | Should -Be 1 - } + { Write-Error -Exception -Message "test throw" } | Should -Throw -ErrorId "MissingArgument,Microsoft.PowerShell.Commands.WriteErrorCommand" } It "Should output the error message to the `$error automatic variable" { From d116ebc71cd408958819c2f679d1d0f1389a7778 Mon Sep 17 00:00:00 2001 From: kalgiz Date: Tue, 17 Apr 2018 17:41:44 -0700 Subject: [PATCH 08/58] [Feature] ShouldBeErrorId => Should -Throw -ErrorId in WSMan.Management module. --- .../ConfigProvider.Tests.ps1 | 20 +++++++++---------- .../CredSSP.Tests.ps1 | 2 +- .../TestWSMan.Tests.ps1 | 2 +- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/test/powershell/Modules/Microsoft.WSMan.Management/ConfigProvider.Tests.ps1 b/test/powershell/Modules/Microsoft.WSMan.Management/ConfigProvider.Tests.ps1 index 9e144aa6e8c..93ad0f557bb 100644 --- a/test/powershell/Modules/Microsoft.WSMan.Management/ConfigProvider.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.WSMan.Management/ConfigProvider.Tests.ps1 @@ -58,7 +58,7 @@ Describe "WSMan Config Provider" -Tag Feature,RequireAdminOnWindows { It "Can remove and add wsman drive" { $wsmanDrive = Get-PSDrive -Name WSMan Remove-PSDrive -Name wsman - { Get-PSDrive -Name wsman -ErrorAction Stop } | ShouldBeErrorId "GetLocationNoMatchingDrive,Microsoft.PowerShell.Commands.GetPSDriveCommand" + { Get-PSDrive -Name wsman -ErrorAction Stop } | Should -Throw -ErrorId "GetLocationNoMatchingDrive,Microsoft.PowerShell.Commands.GetPSDriveCommand" $wsmanDrive2 = $wsmanDrive | New-PSDrive -PSProvider WSMan $wsmanDrive2 | Should -BeOfType System.Management.Automation.PSDriveInfo $wsmanDrive2.Name | Should -BeExactly "WSMan" @@ -130,7 +130,7 @@ Describe "WSMan Config Provider" -Tag Feature,RequireAdminOnWindows { Context "Set-Item tests" { It "Set-Item should fail for `$null value" { - { Set-Item WSMan:\localhost\Client\TrustedHosts $null } | ShouldBeErrorId "System.ArgumentException,Microsoft.PowerShell.Commands.SetItemCommand" + { Set-Item WSMan:\localhost\Client\TrustedHosts $null } | Should -Throw -ErrorId "System.ArgumentException,Microsoft.PowerShell.Commands.SetItemCommand" } It "Set-Item should fail for " -TestCases @( @@ -138,7 +138,7 @@ Describe "WSMan Config Provider" -Tag Feature,RequireAdminOnWindows { @{path="WSMan:\localhost"} ) { param ($path) - { Set-Item $path "foo" } | ShouldBeErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" + { Set-Item $path "foo" } | Should -Throw -ErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" } It "Set-Item -WhatIf should work" { @@ -164,7 +164,7 @@ Describe "WSMan Config Provider" -Tag Feature,RequireAdminOnWindows { #[SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Demo/doc/test secret.")] $password = ConvertTo-SecureString "My voice is my passport, verify me" -AsPlainText -Force $creds = [pscredential]::new((Get-Random),$password) - $exception = { Set-Item $testPluginPath\RunAsUser $creds } | ShouldBeErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" + $exception = { Set-Item $testPluginPath\RunAsUser $creds } | Should -Throw -ErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" -PassThru $exception.Exception.Message | Should -Match ".*$badCredentialError.*" } @@ -183,7 +183,7 @@ Describe "WSMan Config Provider" -Tag Feature,RequireAdminOnWindows { #[SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Demo/doc/test secret.")] $password = ConvertTo-SecureString "My voice is my passport, verify me" -AsPlainText -Force $creds = [pscredential]::new($testUser,$password) - $exception = { Set-Item $testPluginPath\RunAsUser $creds } | ShouldBeErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" + $exception = { Set-Item $testPluginPath\RunAsUser $creds } | Should -Throw -ErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" -PassThru $exception.Exception.Message | Should -Match ".*$badCredentialError.*" } @@ -195,7 +195,7 @@ Describe "WSMan Config Provider" -Tag Feature,RequireAdminOnWindows { ) { param($password) Clear-Item $testPluginPath\RunAsUser -WarningAction SilentlyContinue - { Set-Item $testPluginPath\RunAsPassword $password } | ShouldBeErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" + { Set-Item $testPluginPath\RunAsPassword $password } | Should -Throw -ErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" } It "Set-Item on plugin XmlRenderingType property should succeed for ''" -TestCases @( @@ -210,7 +210,7 @@ Describe "WSMan Config Provider" -Tag Feature,RequireAdminOnWindows { } It "Set-Item on non-existent property should fail" { - { Set-Item $testPluginPath\foo "bar" } | ShouldBeErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" + { Set-Item $testPluginPath\foo "bar" } | Should -Throw -ErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" } It "Set-Item on plugin Resource '' property with '' should succeed" -TestCases @( @@ -243,7 +243,7 @@ Describe "WSMan Config Provider" -Tag Feature,RequireAdminOnWindows { param($property, $value, $expected) $resource = Get-ChildItem "$testPluginPath\Resources" | Select-Object -First 1 $security = Get-ChildItem "$($resource.PSPath)\Security" | Select-Object -First 1 - { Set-Item "$($security.PSPath)\$property" $value -Force } | ShouldBeErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" + { Set-Item "$($security.PSPath)\$property" $value -Force } | Should -Throw -ErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" } It "Set-Item on plugin InitializationParameters '' property with '' should succeed" -TestCases @( @@ -271,7 +271,7 @@ Describe "WSMan Config Provider" -Tag Feature,RequireAdminOnWindows { @{property="MaxShells"; value=0} ) { param($property, $value) - { Set-Item "$testPluginPath\Quotas\$property" $value -WarningAction SilentlyContinue } | ShouldBeErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" + { Set-Item "$testPluginPath\Quotas\$property" $value -WarningAction SilentlyContinue } | Should -Throw -ErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" } } @@ -281,7 +281,7 @@ Describe "WSMan Config Provider" -Tag Feature,RequireAdminOnWindows { @{property="Quotas\IdleTimeoutms"}, @{property="InitializationParameters\PSVersion"} ) { - { Clear-Item "$testPluginPath\$property" -WarningAction SilentlyContinue } | ShouldBeErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.ClearItemCommand" + { Clear-Item "$testPluginPath\$property" -WarningAction SilentlyContinue } | Should -Throw -ErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.ClearItemCommand" } } diff --git a/test/powershell/Modules/Microsoft.WSMan.Management/CredSSP.Tests.ps1 b/test/powershell/Modules/Microsoft.WSMan.Management/CredSSP.Tests.ps1 index bb01010b575..1cd07f8af87 100644 --- a/test/powershell/Modules/Microsoft.WSMan.Management/CredSSP.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.WSMan.Management/CredSSP.Tests.ps1 @@ -40,7 +40,7 @@ Describe "CredSSP cmdlet tests" -Tags 'Feature','RequireAdminOnWindows' { @{params=@{Role="Server";DelegateComputer="."};Description="Server role w/ DelegateComputer"} ) { param ($params) - { Enable-WSManCredSSP @params } | ShouldBeErrorId "System.InvalidOperationException,Microsoft.WSMan.Management.EnableWSManCredSSPCommand" + { Enable-WSManCredSSP @params } | Should -Throw -ErrorId "System.InvalidOperationException,Microsoft.WSMan.Management.EnableWSManCredSSPCommand" } It "Enable-WSManCredSSP works: " -Skip:($NotEnglish -or $IsToBeSkipped) -TestCases @( diff --git a/test/powershell/Modules/Microsoft.WSMan.Management/TestWSMan.Tests.ps1 b/test/powershell/Modules/Microsoft.WSMan.Management/TestWSMan.Tests.ps1 index 15c3d78c61e..9db02182b46 100644 --- a/test/powershell/Modules/Microsoft.WSMan.Management/TestWSMan.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.WSMan.Management/TestWSMan.Tests.ps1 @@ -43,7 +43,7 @@ Describe "TestWSMan tests" -Tags 'Feature' { } It "-Authentication for unsupported type should return error" { - { Test-WSMan -Authentication foo -ErrorAction Stop } | ShouldBeErrorId "CannotConvertArgumentNoMessage,Microsoft.WSMan.Management.TestWSManCommand" + { Test-WSMan -Authentication foo -ErrorAction Stop } | Should -Throw -ErrorId "CannotConvertArgumentNoMessage,Microsoft.WSMan.Management.TestWSManCommand" } It "Test-WSMan works for ''" -TestCases @( From 5cb96ac35d809ad746c0a4c0ddef0362228f1b0d Mon Sep 17 00:00:00 2001 From: kalgiz Date: Tue, 17 Apr 2018 18:16:24 -0700 Subject: [PATCH 09/58] [Feature] ShouldBeErrorId => Should -Throw -ErrorId in engine. --- .../powershell/engine/Basic/Attributes.Tests.ps1 | 2 +- .../engine/Basic/SemanticVersion.Tests.ps1 | 16 ++++++++-------- .../engine/Basic/ValidateAttributes.Tests.ps1 | 8 ++++---- test/powershell/engine/Cdxml/Cdxml.Tests.ps1 | 4 ++-- test/powershell/engine/Job/Jobs.Tests.ps1 | 4 ++-- .../engine/Module/NewModuleManifest.Tests.ps1 | 2 +- .../engine/Module/TestModuleManifest.Tests.ps1 | 10 +++++----- .../Remoting/RemoteSession.Basic.Tests.ps1 | 2 +- .../engine/Remoting/SSHRemotingAPI.Tests.ps1 | 2 +- 9 files changed, 25 insertions(+), 25 deletions(-) diff --git a/test/powershell/engine/Basic/Attributes.Tests.ps1 b/test/powershell/engine/Basic/Attributes.Tests.ps1 index 5e4e233498b..074c492b5fc 100644 --- a/test/powershell/engine/Basic/Attributes.Tests.ps1 +++ b/test/powershell/engine/Basic/Attributes.Tests.ps1 @@ -21,6 +21,6 @@ Param ( Write-Output "Hello" "@ New-Item -Path $testdrive/test.ps1 -Value $script -ItemType File - { & $testdrive/test.ps1 } | ShouldBeErrorId "Argument" + { & $testdrive/test.ps1 } | Should -Throw -ErrorId "Argument" } } diff --git a/test/powershell/engine/Basic/SemanticVersion.Tests.ps1 b/test/powershell/engine/Basic/SemanticVersion.Tests.ps1 index 55a2d2ab6eb..4a6d9bd5ab3 100644 --- a/test/powershell/engine/Basic/SemanticVersion.Tests.ps1 +++ b/test/powershell/engine/Basic/SemanticVersion.Tests.ps1 @@ -203,12 +203,12 @@ Describe "SemanticVersion api tests" -Tags 'CI' { @{ name = "Format errors"; errorId = "FormatException"; expectedResult = $false; version = "1.0.cc" } ) { param($version, $expectedResult, $errorId) - { [SemanticVersion]::new($version) } | ShouldBeErrorId $errorId + { [SemanticVersion]::new($version) } | Should -Throw -ErrorId $errorId if ($version -eq $null) { # PowerShell convert $null to Empty string - { [SemanticVersion]::Parse($version) } | ShouldBeErrorId "FormatException" + { [SemanticVersion]::Parse($version) } | Should -Throw -ErrorId "FormatException" } else { - { [SemanticVersion]::Parse($version) } | ShouldBeErrorId $errorId + { [SemanticVersion]::Parse($version) } | Should -Throw -ErrorId $errorId } $semVer = $null [SemanticVersion]::TryParse($_, [ref]$semVer) | Should -Be $expectedResult @@ -216,15 +216,15 @@ Describe "SemanticVersion api tests" -Tags 'CI' { } It "Negative version arguments" { - { [SemanticVersion]::new(-1, 0) } | ShouldBeErrorId "PSArgumentException" - { [SemanticVersion]::new(1, -1) } | ShouldBeErrorId "PSArgumentException" - { [SemanticVersion]::new(1, 1, -1) } | ShouldBeErrorId "PSArgumentException" + { [SemanticVersion]::new(-1, 0) } | Should -Throw -ErrorId "PSArgumentException" + { [SemanticVersion]::new(1, -1) } | Should -Throw -ErrorId "PSArgumentException" + { [SemanticVersion]::new(1, 1, -1) } | Should -Throw -ErrorId "PSArgumentException" } It "Incompatible 'Version' throws" { # Revision isn't supported - { [SemanticVersion]::new([Version]::new(0, 0, 0, 4)) } | ShouldBeErrorId "PSArgumentException" - { [SemanticVersion]::new([Version]::new("1.2.3.4")) } | ShouldBeErrorId "PSArgumentException" + { [SemanticVersion]::new([Version]::new(0, 0, 0, 4)) } | Should -Throw -ErrorId "PSArgumentException" + { [SemanticVersion]::new([Version]::new("1.2.3.4")) } | Should -Throw -ErrorId "PSArgumentException" } } diff --git a/test/powershell/engine/Basic/ValidateAttributes.Tests.ps1 b/test/powershell/engine/Basic/ValidateAttributes.Tests.ps1 index 471e30ab837..87b9fdf5c1f 100644 --- a/test/powershell/engine/Basic/ValidateAttributes.Tests.ps1 +++ b/test/powershell/engine/Basic/ValidateAttributes.Tests.ps1 @@ -41,7 +41,7 @@ Describe 'Validate Attributes Tests' -Tags 'CI' { It 'Exception: :' -TestCases $testCases { param($ScriptBlock, $FullyQualifiedErrorId, $InnerErrorId) - $ScriptBlock | ShouldBeErrorId $FullyQualifiedErrorId + $ScriptBlock | Should -Throw -ErrorId $FullyQualifiedErrorId if ($InnerErrorId) { $error[0].exception.innerexception.errorrecord.FullyQualifiedErrorId | Should -Be $InnerErrorId } @@ -81,7 +81,7 @@ Describe 'Validate Attributes Tests' -Tags 'CI' { It 'Exception: :' -TestCases $testCases { param($ScriptBlock, $FullyQualifiedErrorId, $InnerErrorId) - $ScriptBlock | ShouldBeErrorId $FullyQualifiedErrorId + $ScriptBlock | Should -Throw -ErrorId $FullyQualifiedErrorId if ($InnerErrorId) { $error[0].exception.innerexception.errorrecord.FullyQualifiedErrorId | Should -Be $InnerErrorId } @@ -117,7 +117,7 @@ Describe 'Validate Attributes Tests' -Tags 'CI' { It 'Exception: :' -TestCases $testCases { param($ScriptBlock, $FullyQualifiedErrorId, $InnerErrorId) - $ScriptBlock | ShouldBeErrorId $FullyQualifiedErrorId + $ScriptBlock | Should -Throw -ErrorId $FullyQualifiedErrorId if ($InnerErrorId) { $error[0].exception.innerexception.errorrecord.FullyQualifiedErrorId | Should -Be $InnerErrorId } @@ -251,7 +251,7 @@ Describe 'Validate Attributes Tests' -Tags 'CI' { It 'Exception: :, RangeType: ' -TestCases $testCases { param($ScriptBlock, $RangeType, $FullyQualifiedErrorId, $InnerErrorId) - $ScriptBlock | ShouldBeErrorId $FullyQualifiedErrorId + $ScriptBlock | Should -Throw -ErrorId $FullyQualifiedErrorId if ($InnerErrorId) { $error[0].exception.innerexception.errorrecord.FullyQualifiedErrorId | Should -Be $InnerErrorId } diff --git a/test/powershell/engine/Cdxml/Cdxml.Tests.ps1 b/test/powershell/engine/Cdxml/Cdxml.Tests.ps1 index ebd1ec43c95..16061a9e00e 100644 --- a/test/powershell/engine/Cdxml/Cdxml.Tests.ps1 +++ b/test/powershell/engine/Cdxml/Cdxml.Tests.ps1 @@ -138,7 +138,7 @@ Describe "Cdxml cmdlets are supported" -Tag CI,RequireAdminOnWindows { } It "The Get-CimTest cmdlet should return the proper error if the instance does not exist" @ItSkipOrPending { - { Get-CimTest -ea stop -id "ThisIdDoesNotExist" } | ShouldBeErrorId "CmdletizationQuery_NotFound_Id,Get-CimTest" + { Get-CimTest -ea stop -id "ThisIdDoesNotExist" } | Should -Throw -ErrorId "CmdletizationQuery_NotFound_Id,Get-CimTest" } It "The Get-CimTest cmdlet should work as a job" @ItSkipOrPending { @@ -230,7 +230,7 @@ Describe "Cdxml cmdlets are supported" -Tag CI,RequireAdminOnWindows { field1 = "a string" field2 = "a bad string" # this needs to be an int } - { New-CimTest @instanceArgs } | ShouldBeErrorId "ParameterArgumentTransformationError,New-CimTest" + { New-CimTest @instanceArgs } | Should -Throw -ErrorId "ParameterArgumentTransformationError,New-CimTest" # just make sure that it wasn't added Get-CimTest -id $instanceArgs.Id -ea SilentlyContinue | Should -BeNullOrEmpty } diff --git a/test/powershell/engine/Job/Jobs.Tests.ps1 b/test/powershell/engine/Job/Jobs.Tests.ps1 index e2903a2b483..63cbee16f7c 100644 --- a/test/powershell/engine/Job/Jobs.Tests.ps1 +++ b/test/powershell/engine/Job/Jobs.Tests.ps1 @@ -77,7 +77,7 @@ Describe 'Basic Job Tests' -Tags 'CI' { $nativeJob.HasMoreData | Should -BeTrue Receive-Job $nativeJob | Should -BeExactly 2 Remove-Job $nativeJob - { Get-Job $nativeJob -ErrorAction Stop } | ShouldBeErrorId "JobWithSpecifiedNameNotFound,Microsoft.PowerShell.Commands.GetJobCommand" + { Get-Job $nativeJob -ErrorAction Stop } | Should -Throw -ErrorId "JobWithSpecifiedNameNotFound,Microsoft.PowerShell.Commands.GetJobCommand" } finally { Remove-Job $nativeJob -Force -ErrorAction SilentlyContinue @@ -144,7 +144,7 @@ Describe 'Basic Job Tests' -Tags 'CI' { It 'Can Receive-Job and autoremove' { $result = Start-Job -Name 'ReceiveJobAutoRemove' -ScriptBlock { 1 + 1 } | Receive-Job -Wait -AutoRemoveJob $result | Should -Be 2 - { Get-Job -Name 'ReceiveJobAutoRemove' -ErrorAction Stop } | ShouldBeErrorId 'JobWithSpecifiedNameNotFound,Microsoft.PowerShell.Commands.GetJobCommand' + { Get-Job -Name 'ReceiveJobAutoRemove' -ErrorAction Stop } | Should -Throw -ErrorId 'JobWithSpecifiedNameNotFound,Microsoft.PowerShell.Commands.GetJobCommand' } It 'Can Receive-Job and keep results' { diff --git a/test/powershell/engine/Module/NewModuleManifest.Tests.ps1 b/test/powershell/engine/Module/NewModuleManifest.Tests.ps1 index b6bf9d96137..945b90f62a1 100644 --- a/test/powershell/engine/Module/NewModuleManifest.Tests.ps1 +++ b/test/powershell/engine/Module/NewModuleManifest.Tests.ps1 @@ -46,6 +46,6 @@ Describe "New-ModuleManifest tests" -tags "CI" { It "Relative URIs are not allowed" { $testUri = [Uri]"../foo" - { New-ModuleManifest -Path $testModulePath -ProjectUri $testUri -LicenseUri $testUri -IconUri $testUri } | ShouldBeErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.NewModuleManifestCommand" + { New-ModuleManifest -Path $testModulePath -ProjectUri $testUri -LicenseUri $testUri -IconUri $testUri } | Should -Throw -ErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.NewModuleManifestCommand" } } diff --git a/test/powershell/engine/Module/TestModuleManifest.Tests.ps1 b/test/powershell/engine/Module/TestModuleManifest.Tests.ps1 index a4e62b15b0b..bbd0093c6c1 100644 --- a/test/powershell/engine/Module/TestModuleManifest.Tests.ps1 +++ b/test/powershell/engine/Module/TestModuleManifest.Tests.ps1 @@ -47,7 +47,7 @@ Describe "Test-ModuleManifest tests" -tags "CI" { New-ModuleManifest -Path $testModulePath @args [string]$errorId = "$error,Microsoft.PowerShell.Commands.TestModuleManifestCommand" - { Test-ModuleManifest -Path $testModulePath -ErrorAction Stop } | ShouldBeErrorId $errorId + { Test-ModuleManifest -Path $testModulePath -ErrorAction Stop } | Should -Throw -ErrorId $errorId } It "module manifest containing valid unprocessed rootmodule file type succeeds: " -TestCases ( @@ -79,7 +79,7 @@ Describe "Test-ModuleManifest tests" -tags "CI" { New-Item -ItemType File -Path testdrive:/module/$rootModuleValue New-ModuleManifest -Path $testModulePath -RootModule $rootModuleValue - { Test-ModuleManifest -Path $testModulePath -ErrorAction Stop } | ShouldBeErrorId "$error,Microsoft.PowerShell.Commands.TestModuleManifestCommand" + { Test-ModuleManifest -Path $testModulePath -ErrorAction Stop } | Should -Throw -ErrorId "$error,Microsoft.PowerShell.Commands.TestModuleManifestCommand" } It "module manifest containing empty rootmodule succeeds: " -TestCases ( @@ -109,7 +109,7 @@ Describe "Test-ModuleManifest tests" -tags "CI" { New-Item -ItemType File -Path testdrive:/module/$rootModuleValue New-ModuleManifest -Path $testModulePath -RootModule $rootModuleValue - { Test-ModuleManifest -Path $testModulePath -ErrorAction Stop } | ShouldBeErrorId "$error,Microsoft.PowerShell.Commands.TestModuleManifestCommand" + { Test-ModuleManifest -Path $testModulePath -ErrorAction Stop } | Should -Throw -ErrorId "$error,Microsoft.PowerShell.Commands.TestModuleManifestCommand" } It "module manifest containing non-existing rootmodule returns error: " -TestCases ( @@ -122,7 +122,7 @@ Describe "Test-ModuleManifest tests" -tags "CI" { New-Item -ItemType Directory -Path testdrive:/module New-ModuleManifest -Path $testModulePath -RootModule $rootModuleValue - { Test-ModuleManifest -Path $testModulePath -ErrorAction Stop } | ShouldBeErrorId "$error,Microsoft.PowerShell.Commands.TestModuleManifestCommand" + { Test-ModuleManifest -Path $testModulePath -ErrorAction Stop } | Should -Throw -ErrorId "$error,Microsoft.PowerShell.Commands.TestModuleManifestCommand" } } @@ -215,7 +215,7 @@ Describe "Tests for circular references in required modules" -tags "CI" { } It "Add a circular reference to RequiredModules and verify error" { - { TestImportModule $false $false $true } | ShouldBeErrorId "Modules_InvalidManifest,Microsoft.PowerShell.Commands.ImportModuleCommand" + { TestImportModule $false $false $true } | Should -Throw -ErrorId "Modules_InvalidManifest,Microsoft.PowerShell.Commands.ImportModuleCommand" } } diff --git a/test/powershell/engine/Remoting/RemoteSession.Basic.Tests.ps1 b/test/powershell/engine/Remoting/RemoteSession.Basic.Tests.ps1 index bad76d962f6..dbf82de1bd6 100644 --- a/test/powershell/engine/Remoting/RemoteSession.Basic.Tests.ps1 +++ b/test/powershell/engine/Remoting/RemoteSession.Basic.Tests.ps1 @@ -220,7 +220,7 @@ Describe "Remoting loopback tests" -Tags @('CI', 'RequireAdminOnWindows') { It "" -TestCases $ParameterError { param($parameters, $expectedError) - { Invoke-Command @parameters } | ShouldBeErrorId $expectedError + { Invoke-Command @parameters } | Should -Throw -ErrorId $expectedError } It 'Can execute command if one of the sessions is available' { diff --git a/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 b/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 index 9af74de0aef..15677636d99 100644 --- a/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 +++ b/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 @@ -21,7 +21,7 @@ Describe "SSH Remoting API Tests" -Tags "Feature" { "UserName", [System.Management.Automation.Internal.AutomationNull]::Value, [System.Management.Automation.Internal.AutomationNull]::Value, - 0) } | ShouldBeErrorId "PSArgumentNullException" + 0) } | Should -Throw -ErrorId "PSArgumentNullException" } It "SSHConnectionInfo should throw file not found exception for invalid key file path" -Skip:$skipTest { From 58e7d14b6b1fc75e9e5c4d7147a31e2fa2e1565a Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Tue, 17 Apr 2018 18:34:40 -0700 Subject: [PATCH 10/58] [Feature] try {} catch {} => Should -Throw -ErrorId in engine. --- .../engine/Basic/CommandDiscovery.Tests.ps1 | 26 +------ .../engine/Basic/PropertyAccessor.Tests.ps1 | 8 +-- .../Help/HelpSystem.OnlineHelp.Tests.ps1 | 11 +-- .../ParameterBinding.Tests.ps1 | 72 +++++-------------- 4 files changed, 22 insertions(+), 95 deletions(-) diff --git a/test/powershell/engine/Basic/CommandDiscovery.Tests.ps1 b/test/powershell/engine/Basic/CommandDiscovery.Tests.ps1 index 86f754be0f2..408e6d81e90 100644 --- a/test/powershell/engine/Basic/CommandDiscovery.Tests.ps1 +++ b/test/powershell/engine/Basic/CommandDiscovery.Tests.ps1 @@ -17,15 +17,7 @@ Describe "Command Discovery tests" -Tags "CI" { It "<testName>" -TestCases $TestCasesCommandNotFound { param($command) - try - { - & $command - throw "Should not have found command: '$command'" - } - catch - { - $_.FullyQualifiedErrorId | Should -Be 'CommandNotFoundException' - } + { & $command } | Should -Throw -ErrorId 'CommandNotFoundException' } It "Command lookup with duplicate paths" { @@ -57,32 +49,20 @@ Describe "Command Discovery tests" -Tags "CI" { } It "Cyclic aliases - direct" { - try { Set-Alias CyclicAliasA CyclicAliasB -Force Set-Alias CyclicAliasB CyclicAliasA -Force & CyclicAliasA - throw "Execution should not reach here. '& CyclicAliasA' should have thrown." - } - catch - { - $_.FullyQualifiedErrorId | Should -Be 'CommandNotFoundException' - } + } | Should -Throw -ErrorId 'CommandNotFoundException' } It "Cyclic aliases - indirect" { - try { Set-Alias CyclicAliasA CyclicAliasB -Force Set-Alias CyclicAliasB CyclicAliasC -Force Set-Alias CyclicAliasC CyclicAliasA -Force & CyclicAliasA - throw "Execution should not reach here. '& CyclicAliasA' should have thrown." - } - catch - { - $_.FullyQualifiedErrorId | Should -Be 'CommandNotFoundException' - } + } | Should -Throw -ErrorId 'CommandNotFoundException' } It "Get-Command should return only CmdletInfo, FunctionInfo, AliasInfo or FilterInfo" { diff --git a/test/powershell/engine/Basic/PropertyAccessor.Tests.ps1 b/test/powershell/engine/Basic/PropertyAccessor.Tests.ps1 index eb0c322e0ce..2238166a4ae 100644 --- a/test/powershell/engine/Basic/PropertyAccessor.Tests.ps1 +++ b/test/powershell/engine/Basic/PropertyAccessor.Tests.ps1 @@ -71,13 +71,7 @@ try { Get-ExecutionPolicy -Scope CurrentUser | Should -Be "Undefined" # Verify the file was not created during the test - try { - $propFile = Get-Item $userPropertiesFile -ErrorAction Stop - throw "Properties file genererated during read operation" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" - } + { $propFile = Get-Item $userPropertiesFile -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } It "Verify Queries for Non-Existant Properties Return Default Value" { diff --git a/test/powershell/engine/Help/HelpSystem.OnlineHelp.Tests.ps1 b/test/powershell/engine/Help/HelpSystem.OnlineHelp.Tests.ps1 index 81ad67404bf..ccc68e7be27 100644 --- a/test/powershell/engine/Help/HelpSystem.OnlineHelp.Tests.ps1 +++ b/test/powershell/engine/Help/HelpSystem.OnlineHelp.Tests.ps1 @@ -91,15 +91,6 @@ Describe 'Get-Help -Online is not supported on Nano Server and IoT' -Tags "CI" { $skipTest = -not ([System.Management.Automation.Platform]::IsIoT -or [System.Management.Automation.Platform]::IsNanoServer) It "Get-help -online <cmdletName> throws InvalidOperation." -skip:$skipTest { - - try - { - Get-Help Get-Help -Online - throw "Execution should not have succeeded" - } - catch - { - $_.FullyQualifiedErrorId | Should -Be "InvalidOperation,Microsoft.PowerShell.Commands.GetHelpCommand" - } + { Get-Help Get-Help -Online } | Should -Throw -ErrorId "InvalidOperation,Microsoft.PowerShell.Commands.GetHelpCommand" } } diff --git a/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 b/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 index 299060c6275..975a8b96510 100644 --- a/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 +++ b/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 @@ -14,15 +14,7 @@ Describe "Parameter Binding Tests" -Tags "CI" { } } - try - { - test-PositionalBinding1 1 - throw "No Exception!" - } - catch - { - $_.FullyQualifiedErrorId | should -Be "AmbiguousPositionalParameterNoName,test-PositionalBinding1" - } + { test-PositionalBinding1 1 } | Should -Throw -ErrorId "AmbiguousPositionalParameterNoName,test-PositionalBinding1" } It "a mandatory parameter can't be passed a null if it doesn't have AllowNullAttribute" { @@ -64,17 +56,10 @@ Describe "Parameter Binding Tests" -Tags "CI" { } } - try - { - test-allownullattributes -Parameter2 1 -Parameter3 $null -ShowMe 1 - throw "No Exception!" - } - catch - { - $_.FullyQualifiedErrorId | should -Be "ParameterArgumentValidationErrorEmptyStringNotAllowed,test-allownullattributes" - $_.CategoryInfo | Should -Match "ParameterBindingValidationException" - $_.Exception.Message | should -Match "Parameter3" - } + $e = { test-allownullattributes -Parameter2 1 -Parameter3 $null -ShowMe 1 } | + Should -Throw -ErrorId "ParameterArgumentValidationErrorEmptyStringNotAllowed,test-allownullattributes" -PassThru + $e.CategoryInfo | Should -Match "ParameterBindingValidationException" + $e.Exception.Message | Should -Match "Parameter3" } It "can't pass an argument that looks like a boolean parameter to a named string parameter" { @@ -90,17 +75,9 @@ Describe "Parameter Binding Tests" -Tags "CI" { } } - try - { - test-namedwithboolishargument -Parameter2 -Parameter1 - throw "No Exception!" - } - catch - { - $_.FullyQualifiedErrorId | should -Be "MissingArgument,test-namedwithboolishargument" - $_.CategoryInfo | Should -Match "ParameterBindingException" - $_.Exception.Message | should -Match "Parameter2" - } + $e = { test-namedwithboolishargument -Parameter2 -Parameter1 } | Should -Throw -ErrorId "MissingArgument,test-namedwithboolishargument" -PassThru + $e.CategoryInfo | Should -Match "ParameterBindingException" + $e.Exception.Message | Should -Match "Parameter2" } It "Verify that a SwitchParameter's IsPresent member is false if the parameter is not specified" { @@ -150,18 +127,11 @@ Describe "Parameter Binding Tests" -Tags "CI" { } } - try - { - test-singleintparameter -Parameter1 'exampleInvalidParam' - throw "No Exception!" - } - catch - { - $_.FullyQualifiedErrorId | should -Be "ParameterArgumentTransformationError,test-singleintparameter" - $_.CategoryInfo | Should -Match "ParameterBindingArgumentTransformationException" - $_.Exception.Message | should -Match "Input string was not in a correct format" - $_.Exception.Message | should -Match "Parameter1" - } + $e = { test-singleintparameter -Parameter1 'exampleInvalidParam' } | + Should -Throw -ErrorId "ParameterArgumentTransformationError,test-singleintparameter" -PassThru + $e.CategoryInfo | Should -Match "ParameterBindingArgumentTransformationException" + $e.Exception.Message | Should -Match "Input string was not in a correct format" + $e.Exception.Message | should -Match "Parameter1" } It "Verify that WhatIf is available when SupportShouldProcess is true" { @@ -269,18 +239,10 @@ Describe "Parameter Binding Tests" -Tags "CI" { ) } - try - { - test-nameconflicts6 -Parameter2 1 - throw "No Exception!" - } - catch - { - $_.FullyQualifiedErrorId | should -Be "ParameterNameConflictsWithAlias" - $_.CategoryInfo | Should -Match "MetadataException" - $_.Exception.Message | should -Match "Parameter1" - $_.Exception.Message | should -Match "Parameter2" - } + $e = { test-nameconflicts6 -Parameter2 1 } | Should -Throw -ErrorId "ParameterNameConflictsWithAlias" -PassThru + $e.CategoryInfo | Should -Match "MetadataException" + $e.Exception.Message | should -Match "Parameter1" + $e.Exception.Message | should -Match "Parameter2" } It "PipelineVariable shouldn't cause a NullRef exception when 'DynamicParam' block is present" { From 83413ddbf72e6a1fae5e1fb083863d2438916dde Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Wed, 18 Apr 2018 11:49:45 -0700 Subject: [PATCH 11/58] [Feature] Tests fix --- test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 | 5 ++--- test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 b/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 index 075fbf6f602..aaf5519ec60 100644 --- a/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 +++ b/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 @@ -28,9 +28,8 @@ Try { $instance.GetCimSessionInstanceId() | Should -BeOfType "Guid" } It "should produce an error for a non-existing classname" { - { get-ciminstance -classname thisnameshouldnotexist -ea stop } | - Should -Throw -ErrorId "HRESULT 0x80041010,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstanceCommand" - } + { get-ciminstance -classname thisnameshouldnotexist -ea stop } | + Should -Throw -ErrorId "HRESULT 0x80041010,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstanceCommand" } } } diff --git a/test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 b/test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 index b8af13164da..114a5ff7e80 100644 --- a/test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 +++ b/test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 @@ -15,7 +15,7 @@ try { } It 'produces an error when a non-existent class is used' { - { Get-CimClass -ClassName thisclasstypedoesnotexist -ea stop | + { Get-CimClass -ClassName thisclasstypedoesnotexist -ea stop } | Should -Throw -ErrorId "HRESULT 0x80041002,Microsoft.Management.Infrastructure.CimCmdlets.GetCimClassCommand" } It 'produces an error when an improper namespace is used' { From dac144254d02e426a691010d90e65e59aa18fdc3 Mon Sep 17 00:00:00 2001 From: Klaudia Algiz <klalgiz@microsoft.com> Date: Wed, 18 Apr 2018 14:10:23 -0700 Subject: [PATCH 12/58] [Feature] try {} catch {} => Should -Throw -ErrorId in engine. --- .../Remoting/RemoteSession.Basic.Tests.ps1 | 8 ++--- .../Remoting/RoleCapabilityFiles.Tests.ps1 | 35 ++++--------------- .../engine/Remoting/SSHRemotingAPI.Tests.ps1 | 30 ++++------------ .../Remoting/SSHRemotingCmdlets.Tests.ps1 | 21 ++--------- 4 files changed, 17 insertions(+), 77 deletions(-) diff --git a/test/powershell/engine/Remoting/RemoteSession.Basic.Tests.ps1 b/test/powershell/engine/Remoting/RemoteSession.Basic.Tests.ps1 index dbf82de1bd6..7aef5bbe112 100644 --- a/test/powershell/engine/Remoting/RemoteSession.Basic.Tests.ps1 +++ b/test/powershell/engine/Remoting/RemoteSession.Basic.Tests.ps1 @@ -2,12 +2,8 @@ # Licensed under the MIT License. Describe "New-PSSession basic test" -Tag @("CI") { It "New-PSSession should not crash powershell" { - try { - New-PSSession -ComputerName nonexistcomputer -Authentication Basic - throw "New-PSSession should throw" - } catch { - $_.FullyQualifiedErrorId | Should -Be "InvalidOperation,Microsoft.PowerShell.Commands.NewPSSessionCommand" - } + { New-PSSession -ComputerName nonexistcomputer -Authentication Basic } | + Should -Throw -ErrorId "InvalidOperation,Microsoft.PowerShell.Commands.NewPSSessionCommand" } } diff --git a/test/powershell/engine/Remoting/RoleCapabilityFiles.Tests.ps1 b/test/powershell/engine/Remoting/RoleCapabilityFiles.Tests.ps1 index ddc1287ae67..67ca0d1e2b1 100644 --- a/test/powershell/engine/Remoting/RoleCapabilityFiles.Tests.ps1 +++ b/test/powershell/engine/Remoting/RoleCapabilityFiles.Tests.ps1 @@ -42,21 +42,11 @@ Describe "Remote session configuration RoleDefintion RoleCapabilityFiles key tes Administrators = @{ RoleCapabilityFiles = "$RoleCapDirectory\NoFile.psrc" } } - $fullyQualifiedErrorId = "" - try - { + $e = { $iss = [initialsessionstate]::CreateFromSessionConfigurationFile($PSSessionConfigFile, { $true }) - throw 'No Exception!' - } - catch - { - $psioe = [System.Management.Automation.PSInvalidOperationException] ($_.Exception).InnerException - if ($null -ne $psioe) - { - $fullyQualifiedErrorId = $psioe.ErrorRecord.FullyQualifiedErrorId - } - $fullyQualifiedErrorId | Should -Be 'CouldNotFindRoleCapabilityFile' - } + } | Should -Throw -PassThru + + $e.Exception.InnerException.ErrorRecord.FullyQualifiedErrorId | Should -BeExactly 'CouldNotFindRoleCapabilityFile' } It "Verifies incorrect role capability file extenstion error" { @@ -65,21 +55,10 @@ Describe "Remote session configuration RoleDefintion RoleCapabilityFiles key tes Administrators = @{ RoleCapabilityFiles = "$BadRoleCapFile" } } - $fullyQualifiedErrorId = "" - try - { + $e = { $iss = [initialsessionstate]::CreateFromSessionConfigurationFile($PSSessionConfigFile, { $true }) - throw 'No Exception!' - } - catch - { - $psioe = [System.Management.Automation.PSInvalidOperationException] ($_.Exception).InnerException - if ($null -ne $psioe) - { - $fullyQualifiedErrorId = $psioe.ErrorRecord.FullyQualifiedErrorId - } - $fullyQualifiedErrorId | Should -Be 'InvalidRoleCapabilityFileExtension' - } + } | Should -Throw -PassThru + $e.Exception.InnerException.ErrorRecord.FullyQualifiedErrorId | Should -BeExactly 'InvalidRoleCapabilityFileExtension' } It "Verifies restriction on good role capability file" { diff --git a/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 b/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 index 15677636d99..a07a4c9c641 100644 --- a/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 +++ b/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 @@ -26,8 +26,7 @@ Describe "SSH Remoting API Tests" -Tags "Feature" { It "SSHConnectionInfo should throw file not found exception for invalid key file path" -Skip:$skipTest { - try - { + $e = { $sshConnectionInfo = [System.Management.Automation.Runspaces.SSHConnectionInfo]::new( "UserName", "localhost", @@ -36,18 +35,12 @@ Describe "SSH Remoting API Tests" -Tags "Feature" { $rs = [runspacefactory]::CreateRunspace($sshConnectionInfo) $rs.Open() - - throw "No Exception!" - } - catch - { - $_.Exception.InnerException.InnerException | Should -BeOfType "System.IO.FileNotFoundException" - } + } | Should -Throw -PassThru + $e.Exception.InnerException.InnerException | Should -BeOfType "System.IO.FileNotFoundException" } It "SSHConnectionInfo should throw argument exception for invalid port (non 16bit uint)" { - try - { + $e = { $sshConnectionInfo = [System.Management.Automation.Runspaces.SSHConnectionInfo]::new( "UserName", "localhost", @@ -56,19 +49,8 @@ Describe "SSH Remoting API Tests" -Tags "Feature" { $rs = [runspacefactory]::CreateRunspace($sshConnectionInfo) $rs.Open() - - throw "No Exception!" - } - catch - { - $expectedArgumentException = $_.Exception - if ($null -ne $_.Exception.InnerException) - { - $expectedArgumentException = $_.Exception.InnerException - } - - $expectedArgumentException | Should -BeOfType "System.ArgumentException" - } + } | Should -Throw -PassThru + $e.Exception.InnerException | Should -BeOfType "System.ArgumentException" } } } diff --git a/test/powershell/engine/Remoting/SSHRemotingCmdlets.Tests.ps1 b/test/powershell/engine/Remoting/SSHRemotingCmdlets.Tests.ps1 index 312268f6d61..4141ab6c1ba 100644 --- a/test/powershell/engine/Remoting/SSHRemotingCmdlets.Tests.ps1 +++ b/test/powershell/engine/Remoting/SSHRemotingCmdlets.Tests.ps1 @@ -16,17 +16,8 @@ Describe "SSHTransport switch parameter value" -Tags 'Feature' { } It "<testName>" -TestCases $TestCasesSSHTransport { - param($scriptBlock) - try - { - & $scriptBlock - throw "Parameter argument should not be valid" - } - catch - { - $_.FullyQualifiedErrorId | Should -Match "ParameterArgumentValidationError" - } + { & $scriptBlock } | Should -Throw -ErrorId "ParameterArgumentValidationError" } } @@ -46,14 +37,6 @@ Describe "SSHConnection parameter hashtable error conditions" -Tags 'Feature' { It "<testName>" -TestCases $TestCasesSSHConnection { param ($scriptBlock) - try - { - & $scriptBlock - throw "Parameter set should not be valid" - } - catch - { - $_.FullyQualifiedErrorId | Should -Match "Argument,Microsoft.PowerShell.Commands.NewPSSessionCommand" - } + { & $scriptBlock } | Should -Throw -ErrorId "Argument,Microsoft.PowerShell.Commands.NewPSSessionCommand" } } From c6affbef2d0d62d4e2deaec80b301e9ed4c9bed7 Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Wed, 18 Apr 2018 14:14:54 -0700 Subject: [PATCH 13/58] [Feature] ShouldBeErrorId => Should -Throw -ErrorId in Host. --- test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index f0270b14778..a0216b84413 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -839,7 +839,7 @@ dir -Recurse ` It "Input '<inputStr>' should throw in tab completion" -TestCases $testCases { param($inputStr, $expected) - $inputStr | ShouldBeErrorId $expected + $inputStr | Should -Throw -ErrorId $expected } } From 9df619d6852a4c658664d1d896e7cc4965705944 Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Wed, 18 Apr 2018 14:29:07 -0700 Subject: [PATCH 14/58] [Feature] try {} catch {} => Should -Throw -ErrorId in Host --- test/powershell/Host/ConsoleHost.Tests.ps1 | 50 ++++---------------- test/powershell/Host/HostUtilities.Tests.ps1 | 24 ++-------- 2 files changed, 14 insertions(+), 60 deletions(-) diff --git a/test/powershell/Host/ConsoleHost.Tests.ps1 b/test/powershell/Host/ConsoleHost.Tests.ps1 index caa075e825a..eb4641576f3 100644 --- a/test/powershell/Host/ConsoleHost.Tests.ps1 +++ b/test/powershell/Host/ConsoleHost.Tests.ps1 @@ -93,35 +93,21 @@ Describe "ConsoleHost unit tests" -tags "Feature" { Context "ShellInterop" { It "Verify Parsing Error Output Format Single Shell should throw exception" { - try - { - & $powershell -outp blah -comm { $input } - Throw "Test execution should not reach here!" - } - catch - { - $_.FullyQualifiedErrorId | Should -Be "IncorrectValueForFormatParameter" - } + { & $powershell -outp blah -comm { $input } } | Should -Throw -ErrorId "IncorrectValueForFormatParameter" } It "Verify Validate Dollar Error Populated should throw exception" { $origEA = $ErrorActionPreference $ErrorActionPreference = "Stop" - try - { + $e = { $a = 1,2,3 $a | & $powershell -noprofile -command { wgwg-wrwrhqwrhrh35h3h3} - Throw "Test execution should not reach here!" - } - catch - { - $_.ToString() | Should -Match "wgwg-wrwrhqwrhrh35h3h3" - $_.FullyQualifiedErrorId | Should -Be "CommandNotFoundException" - } - finally - { - $ErrorActionPreference = $origEA - } + } | Should -Throw -PassThru + + $e.ToString() | Should -Match "wgwg-wrwrhqwrhrh35h3h3" + $e.FullyQualifiedErrorId | Should -Be "CommandNotFoundException" + + $ErrorActionPreference = $origEA } It "Verify Validate Output Format As Text Explicitly Child Single Shell does not throw" { @@ -131,15 +117,7 @@ Describe "ConsoleHost unit tests" -tags "Feature" { } It "Verify Parsing Error Input Format Single Shell should throw exception" { - try - { - & $powershell -input blah -comm { $input } - Throw "Test execution should not reach here!" - } - catch - { - $_.FullyQualifiedErrorId | Should -Be "IncorrectValueForFormatParameter" - } + { & $powershell -input blah -comm { $input } } | Should -Throw -ErrorId "IncorrectValueForFormatParameter" } } Context "CommandLine" { @@ -496,15 +474,7 @@ foo recurse $args } - try - { - recurse "args" - Throw "Incorrect exception" - } - catch - { - $_.FullyQualifiedErrorId | Should -Be "CallDepthOverflow" - } + { recurse "args" } | Should -Throw -ErrorId "CallDepthOverflow" } } diff --git a/test/powershell/Host/HostUtilities.Tests.ps1 b/test/powershell/Host/HostUtilities.Tests.ps1 index c2e8cb80867..96145b41ca7 100644 --- a/test/powershell/Host/HostUtilities.Tests.ps1 +++ b/test/powershell/Host/HostUtilities.Tests.ps1 @@ -8,29 +8,13 @@ Describe "InvokeOnRunspace method argument error handling" -tags "Feature" { } It "Null argument exception should be thrown for null PSCommand argument" { - - try - { - [System.Management.Automation.HostUtilities]::InvokeOnRunspace($null, $localRunspace) - throw "InvokeOnRunspace method did not throw expected PSArgumentNullException exception" - } - catch - { - $_.FullyQualifiedErrorId | Should -Be "PSArgumentNullException" - } + { [System.Management.Automation.HostUtilities]::InvokeOnRunspace($null, $localRunspace) } | + Should -Throw -ErrorId "PSArgumentNullException" } It "Null argument exception should be thrown for null Runspace argument" { - - try - { - [System.Management.Automation.HostUtilities]::InvokeOnRunspace($command, $null) - throw "InvokeOnRunspace method did not throw expected PSArgumentNullException exception" - } - catch - { - $_.FullyQualifiedErrorId | Should -Be "PSArgumentNullException" - } + { [System.Management.Automation.HostUtilities]::InvokeOnRunspace($command, $null) } | + Should -Throw -ErrorId "PSArgumentNullException" } } From 56524ca432c0d4d496cd6302fdbd6feb856754f3 Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Wed, 18 Apr 2018 14:30:49 -0700 Subject: [PATCH 15/58] [Feature] Use new Pester syntax -Parameter in Installer. --- test/powershell/Installer/WindowsInstaller.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/powershell/Installer/WindowsInstaller.Tests.ps1 b/test/powershell/Installer/WindowsInstaller.Tests.ps1 index ac8168a2f82..5b88d653afe 100644 --- a/test/powershell/Installer/WindowsInstaller.Tests.ps1 +++ b/test/powershell/Installer/WindowsInstaller.Tests.ps1 @@ -33,6 +33,6 @@ Describe "Windows Installer" -Tags "Scenario" { } } - $result | Should Not Be $null + $result | Should -Not -Be $null } } From 8f905ee3fa67b87657450105ad7ac1b3b1d6f68e Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Wed, 18 Apr 2018 15:12:46 -0700 Subject: [PATCH 16/58] [Feature] ShouldBeErrorId => Should -Throw -ErrorId in Language. --- .../Classes/Scripting.Classes.Attributes.Tests.ps1 | 10 +++++----- .../Language/Operators/ComparisonOperator.Tests.ps1 | 2 +- .../Language/Operators/SplitOperator.Tests.ps1 | 2 +- .../Language/Parser/UsingNamespace.Tests.ps1 | 2 +- .../Language/Scripting/ActionPreference.Tests.ps1 | 2 +- .../NativeExecution/NativeCommandProcessor.Tests.ps1 | 2 +- .../Language/Scripting/ParameterBinding.Tests.ps1 | 8 ++++---- 7 files changed, 14 insertions(+), 14 deletions(-) diff --git a/test/powershell/Language/Classes/Scripting.Classes.Attributes.Tests.ps1 b/test/powershell/Language/Classes/Scripting.Classes.Attributes.Tests.ps1 index b659f8de2dd..c9a17bb54e0 100644 --- a/test/powershell/Language/Classes/Scripting.Classes.Attributes.Tests.ps1 +++ b/test/powershell/Language/Classes/Scripting.Classes.Attributes.Tests.ps1 @@ -260,7 +260,7 @@ Describe 'ValidateSet support a dynamically generated set' -Tag "CI" { } It 'Throw if IValidateSetValuesGenerator is not implemented' { - { Get-TestValidateSet0 -Param1 "TestString" -ErrorAction Stop } | ShouldBeErrorId "Argument" + { Get-TestValidateSet0 -Param1 "TestString" -ErrorAction Stop } | Should -Throw -ErrorId "Argument" } It 'Dynamically generated set works in C# with default (immediate) cache expire' { @@ -270,7 +270,7 @@ Describe 'ValidateSet support a dynamically generated set' -Tag "CI" { It 'Empty dynamically generated set throws in C#' { $exc = { Get-TestValidateSet5 -Param1 "TestString1" -ErrorAction Stop - } | ShouldBeErrorId "ParameterArgumentValidationError,Test.Language.TestValidateSetCommand5" + } | Should -Throw -ErrorId "ParameterArgumentValidationError,Test.Language.TestValidateSetCommand5" -PassThru $exc.Exception.InnerException.ErrorRecord.FullyQualifiedErrorId | Should -BeExactly "ValidateSetGeneratedValidValuesListIsNull" } } @@ -356,20 +356,20 @@ Describe 'ValidateSet support a dynamically generated set' -Tag "CI" { } It 'Get the appropriate error message' { - {Get-TestValidateSetPS4 -Param1 "TestStringWrong" -ErrorAction Stop} | ShouldBeErrorId "ParameterArgumentValidationError,Get-TestValidateSetPS4" + {Get-TestValidateSetPS4 -Param1 "TestStringWrong" -ErrorAction Stop} | Should -Throw -ErrorId "ParameterArgumentValidationError,Get-TestValidateSetPS4" } It 'Empty dynamically generated set throws in PowerShell script' { $exc = { Get-TestValidateSetPS5 -Param1 "TestString1" -ErrorAction Stop - } | ShouldBeErrorId "ParameterArgumentValidationError,Get-TestValidateSetPS5" + } | Should -Throw -ErrorId "ParameterArgumentValidationError,Get-TestValidateSetPS5" -PassThru $exc.Exception.InnerException.ErrorRecord.FullyQualifiedErrorId | Should -BeExactly "ValidateSetGeneratedValidValuesListIsNull" } It 'Unimplemented valid values generator type throws in PowerShell script' { { Get-TestValidateSetPS6 -Param1 "AnyTestString" -ErrorAction Stop - } | ShouldBeErrorId "TypeNotFound" + } | Should -Throw -ErrorId "TypeNotFound" } It 'IValidateSetValuesGenerator works in PowerShell module' { diff --git a/test/powershell/Language/Operators/ComparisonOperator.Tests.ps1 b/test/powershell/Language/Operators/ComparisonOperator.Tests.ps1 index 92c52641943..2c0847dee63 100644 --- a/test/powershell/Language/Operators/ComparisonOperator.Tests.ps1 +++ b/test/powershell/Language/Operators/ComparisonOperator.Tests.ps1 @@ -58,7 +58,7 @@ Describe "ComparisonOperator" -tag "CI" { @{operator = "-isnot"; type = "[foo]"; expectedError='TypeNotFound,Microsoft.PowerShell.Commands.InvokeExpressionCommand'} ) { param($operator, $type, $expectedError) - { Invoke-Expression "'Hello' $operator $type" } | ShouldBeErrorId $expectedError + { Invoke-Expression "'Hello' $operator $type" } | Should -Throw -ErrorId $expectedError } It "Should succeed in comparing type: <lhs> <operator> <rhs>" -TestCases @( diff --git a/test/powershell/Language/Operators/SplitOperator.Tests.ps1 b/test/powershell/Language/Operators/SplitOperator.Tests.ps1 index 25514c9a75a..1e508f4a47a 100644 --- a/test/powershell/Language/Operators/SplitOperator.Tests.ps1 +++ b/test/powershell/Language/Operators/SplitOperator.Tests.ps1 @@ -210,7 +210,7 @@ Describe "Split Operator" -Tags CI { } It "Binary split operator doesn't works with RegexMatch,SimpleMatch" { - { "abc" -split "B", 0, 'RegexMatch,SimpleMatch' } | ShouldBeErrorId "InvalidSplitOptionCombination" + { "abc" -split "B", 0, 'RegexMatch,SimpleMatch' } | Should -Throw -ErrorId "InvalidSplitOptionCombination" } } diff --git a/test/powershell/Language/Parser/UsingNamespace.Tests.ps1 b/test/powershell/Language/Parser/UsingNamespace.Tests.ps1 index caeb570013c..e0b7550636a 100644 --- a/test/powershell/Language/Parser/UsingNamespace.Tests.ps1 +++ b/test/powershell/Language/Parser/UsingNamespace.Tests.ps1 @@ -96,7 +96,7 @@ Describe "Using Namespace" -Tags "CI" { } It "Ambiguous type reference" { - { [ThreadState] } | ShouldBeErrorId AmbiguousTypeReference + { [ThreadState] } | Should -Throw -ErrorId AmbiguousTypeReference } It "Parameters" { diff --git a/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 b/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 index f9fbf3f5e24..3b90565e03b 100644 --- a/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 +++ b/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 @@ -144,7 +144,7 @@ Describe "Tests for (error, warning, etc) action preference" -Tags "CI" { $params += @{$switch=$true} { New-Item @params } | Should -Not -Throw $ErrorActionPreference = "Stop" - { New-Item @params } | ShouldBeErrorId "NewItemIOError,Microsoft.PowerShell.Commands.NewItemCommand" + { New-Item @params } | Should -Throw -ErrorId "NewItemIOError,Microsoft.PowerShell.Commands.NewItemCommand" Remove-Item "$testdrive\test.txt" -Force } } diff --git a/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 b/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 index 4bbef895f82..ef4898ffd75 100644 --- a/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 +++ b/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 @@ -218,6 +218,6 @@ Categories=Application; } It "Opening a file with an unregistered extension on Windows should fail" -Skip:(!$IsWindows) { - { $dllFile = "$PSHOME\System.Management.Automation.dll"; & $dllFile } | ShouldBeErrorId "NativeCommandFailed" + { $dllFile = "$PSHOME\System.Management.Automation.dll"; & $dllFile } | Should -Throw -ErrorId "NativeCommandFailed" } } diff --git a/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 b/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 index a572b74a592..634d75331cb 100644 --- a/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 +++ b/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 @@ -165,7 +165,7 @@ Describe "Tests for parameter binding" -Tags "CI" { $foo } - { get-foo -a a -b b c d } | ShouldBeErrorId 'AmbiguousParameterSet,get-foo' + { get-foo -a a -b b c d } | Should -Throw -ErrorId 'AmbiguousParameterSet,get-foo' ( get-foo -a a b c d ) -join ',' | Should -BeExactly 'b,c,d' ( get-foo -b b a c d ) -join ',' | Should -BeExactly 'a,c,d' } @@ -230,7 +230,7 @@ Describe "Tests for parameter binding" -Tags "CI" { $a } - { get-foo -a $null } | ShouldBeErrorId 'ParameterArgumentValidationErrorNullNotAllowed,get-foo' + { get-foo -a $null } | Should -Throw -ErrorId 'ParameterArgumentValidationErrorNullNotAllowed,get-foo' } @@ -272,7 +272,7 @@ Describe "Tests for parameter binding" -Tags "CI" { $a } - { get-foo -a @() } | ShouldBeErrorId 'ParameterArgumentValidationErrorEmptyArrayNotAllowed,get-foo' + { get-foo -a @() } | Should -Throw -ErrorId 'ParameterArgumentValidationErrorEmptyArrayNotAllowed,get-foo' } It 'Empty collection is allowed when allowEmptyCollection is set' { @@ -315,7 +315,7 @@ Describe "Tests for parameter binding" -Tags "CI" { $Parameter } - { get-foo 'a','b' } | ShouldBeErrorId 'ParameterArgumentTransformationError,get-foo' + { get-foo 'a','b' } | Should -Throw -ErrorId 'ParameterArgumentTransformationError,get-foo' } It "Binding array of string to array of bool should succeed" { From 0955b7a9f64e72037c7f7e68f5370f057aeb0e7e Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Wed, 18 Apr 2018 17:21:37 -0700 Subject: [PATCH 17/58] [Feature] try {} catch {} => Should -Throw -ErrorId in Language. --- .../Scripting.Classes.Exceptions.Tests.ps1 | 86 ++------- .../LanguageAndParser.TestFollowup.Tests.ps1 | 12 +- .../Language/Parser/Parser.Tests.ps1 | 176 +++--------------- .../Language/Parser/UsingAssembly.Tests.ps1 | 11 +- .../Scripting/ActionPreference.Tests.ps1 | 63 ++----- .../CheckRestrictedlanguage.Tests.ps1 | 45 +---- .../Scripting/CommonParameters.Tests.ps1 | 10 +- .../Debugging/DebuggerScriptTests.Tests.ps1 | 14 +- .../DeserializedTypeConversion.Tests.ps1 | 19 +- .../Scripting/Dynamicparameters.Tests.ps1 | 7 +- .../Language/Scripting/Generics.Tests.ps1 | 10 +- ...htableToPSCustomObjectConversion.Tests.ps1 | 36 ++-- .../Scripting/ParameterBinding.Tests.ps1 | 39 +--- .../Language/Scripting/Requires.Tests.ps1 | 12 +- 14 files changed, 97 insertions(+), 443 deletions(-) diff --git a/test/powershell/Language/Classes/Scripting.Classes.Exceptions.Tests.ps1 b/test/powershell/Language/Classes/Scripting.Classes.Exceptions.Tests.ps1 index f38d2fda1c0..a27f05eefc4 100644 --- a/test/powershell/Language/Classes/Scripting.Classes.Exceptions.Tests.ps1 +++ b/test/powershell/Language/Classes/Scripting.Classes.Exceptions.Tests.ps1 @@ -235,39 +235,23 @@ Describe "Exception error position" -Tags "CI" { } It "Setting a property that doesn't exist" { - try { - [MSFT_3090412]::f1() - throw "f1 should have thrown" - } catch { - $_.InvocationInfo.Line | Should -Match ([regex]::Escape('[MSFT_3090412]::bar = 42')) - } + $e = { [MSFT_3090412]::f1() } | Should -Throw -PassThru -ErrorId 'PropertyAssignmentException' + $e.InvocationInfo.Line | Should -Match ([regex]::Escape('[MSFT_3090412]::bar = 42')) } It "Throwing an exception" { - try { - [MSFT_3090412]::f2() - throw "f2 should have thrown" - } catch { - $_.InvocationInfo.Line | Should -Match ([regex]::Escape('throw "an error in f2"')) - } + $e = { [MSFT_3090412]::f2() } | Should -Throw -PassThru -ErrorId 'an error in f2' + $e.InvocationInfo.Line | Should -Match ([regex]::Escape('throw "an error in f2"')) } It "Calling a .Net method that throws" { - try { - [MSFT_3090412]::f3() - throw "f3 should have thrown" - } catch { - $_.InvocationInfo.Line | Should -Match ([regex]::Escape('"".Substring(0, 10)')) - } + $e = { [MSFT_3090412]::f3() } | Should -Throw -PassThru -ErrorId 'ArgumentOutOfRangeException' + $e.InvocationInfo.Line | Should -Match ([regex]::Escape('"".Substring(0, 10)')) } It "Terminating error" { - try { - [MSFT_3090412]::f4() - throw "f4 should have thrown" - } catch { - $_.InvocationInfo.Line | Should -Match ([regex]::Escape('dir nosuchfile -ea Stop')) - } + $e = { [MSFT_3090412]::f4() } | Should -Throw -PassThru -ErrorId 'PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand' + $e.InvocationInfo.Line | Should -Match ([regex]::Escape('dir nosuchfile -ea Stop')) } } @@ -295,56 +279,26 @@ Describe "Exception from initializer" -Tags "CI" { } It "instance member w/ ctor" { - try { - [MSFT_6397334a]::new() - throw "[MSFT_6397334a]::new() should have thrown" - } - catch - { - $e = $_ - $e.FullyQualifiedErrorId | Should -BeExactly 'InvalidCastFromStringToInteger' - $e.InvocationInfo.Line | Should -Match 'a = "zz"' - } + $e = { [MSFT_6397334a]::new() } | Should -Throw -ErrorId 'InvalidCastFromStringToInteger' -PassThru + $e.InvocationInfo.Line | Should -Match 'a = "zz"' } It "instance member w/o ctor" { - try { - [MSFT_6397334b]::new() - throw "[MSFT_6397334b]::new() should have thrown" - } - catch - { - $e = $_ - $e.FullyQualifiedErrorId | Should -BeExactly 'InvalidCastFromStringToInteger' - $e.InvocationInfo.Line | Should -Match 'a = "zz"' - } + $e = { [MSFT_6397334b]::new() } | Should -Throw -ErrorId 'InvalidCastFromStringToInteger' -PassThru + $e.InvocationInfo.Line | Should -Match 'a = "zz"' } It "static member w/ ctor" { - try { - $null = [MSFT_6397334c]::a - throw "No Exception!" - } - catch - { - $_.Exception | Should -BeOfType System.TypeInitializationException - $e = $_.Exception.InnerException.InnerException.ErrorRecord - $e.FullyQualifiedErrorId | Should -BeExactly 'InvalidCastFromStringToInteger' - $e.InvocationInfo.Line | Should -Match 'a = "zz"' - } + $e = { $null = [MSFT_6397334c]::a } | Should -Throw -PassThru + $e.Exception | Should -BeOfType 'System.TypeInitializationException' + $e.Exception.InnerException.ErrorRecord.FullyQualifiedErrorId | Should -BeExactly 'InvalidCastFromStringToInteger' + $e.Exception.InnerException.InnerException.ErrorRecord.InvocationInfo.Line | Should -Match 'a = "zz"' } It "static member w/o ctor" { - try { - $null = [MSFT_6397334d]::a - throw "No Exception!" - } - catch - { - $_.Exception | Should -BeOfType System.TypeInitializationException - $e = $_.Exception.InnerException.InnerException.ErrorRecord - $e.FullyQualifiedErrorId | Should -BeExactly 'InvalidCastFromStringToInteger' - $e.InvocationInfo.Line | Should -Match 'a = "zz"' - } + $e = { $null = [MSFT_6397334d]::a } | Should -Throw -PassThru + $e.Exception | Should -BeOfType System.TypeInitializationException + $e.Exception.InnerException.InnerException.ErrorRecord.FullyQualifiedErrorId | Should -BeExactly 'InvalidCastFromStringToInteger' + $e.Exception.InnerException.InnerException.ErrorRecord.InvocationInfo.Line | Should -Match 'a = "zz"' } } diff --git a/test/powershell/Language/Parser/LanguageAndParser.TestFollowup.Tests.ps1 b/test/powershell/Language/Parser/LanguageAndParser.TestFollowup.Tests.ps1 index 39d9d23eaac..8860d492c24 100644 --- a/test/powershell/Language/Parser/LanguageAndParser.TestFollowup.Tests.ps1 +++ b/test/powershell/Language/Parser/LanguageAndParser.TestFollowup.Tests.ps1 @@ -172,21 +172,15 @@ Describe "Assign readonly/constant variables" -Tags "CI" { Describe "Attribute error position" -Tags "CI" { It "Ambiguous overloads" { - try - { + $e = { & { param( [ValidateNotNull(1,2,3,4)] $param ) } - throw "Should have thrown" - } - catch - { - $_.InvocationInfo.Line | Should -Match ValidateNotNull - $_.FullyQualifiedErrorId | Should -Be MethodCountCouldNotFindBest - } + } | Should -Throw -PassThru -ErrorId 'MethodCountCouldNotFindBest' + $e.InvocationInfo.Line | Should -Match ValidateNotNull } } diff --git a/test/powershell/Language/Parser/Parser.Tests.ps1 b/test/powershell/Language/Parser/Parser.Tests.ps1 index 0824a6dc870..d9921c63ab3 100644 --- a/test/powershell/Language/Parser/Parser.Tests.ps1 +++ b/test/powershell/Language/Parser/Parser.Tests.ps1 @@ -138,33 +138,15 @@ Describe "ParserTests (admin\monad\tests\monad\src\engine\core\ParserTests.cs)" } It "Throws a syntax error when parsing a string without a closing quote. (line 164)" { - try { - ExecuteCommand '"This is a test' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "IncompleteParseException" - } + { ExecuteCommand '"This is a test' } | Should -Throw -ErrorId "IncompleteParseException" } It "Throws an error if an open parenthesis is not closed (line 176)" { - try { - ExecuteCommand "(" - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "IncompleteParseException" - } + { ExecuteCommand "(" } | Should -Throw -ErrorId "IncompleteParseException" } It "Throws an exception if the the first statement starts with an empty pipe element (line 188)" { - try { - ExecuteCommand "| get-location" - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand "| get-location" } | Should -Throw -ErrorId "ParseException" } It "Throws an CommandNotFoundException exception if using a label in front of an if statement is not allowed. (line 225)"{ @@ -175,51 +157,21 @@ Describe "ParserTests (admin\monad\tests\monad\src\engine\core\ParserTests.cs)" } It "Pipe an expression into a value expression. (line 237)" { - try { - ExecuteCommand "testcmd-parserbvt | 3" - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand "testcmd-parserbvt | 3" } | Should -Throw -ErrorId "ParseException" - try { - ExecuteCommand "testcmd-parserbvt | $(1 + 1)" - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand "testcmd-parserbvt | $(1 + 1)" } | Should -Throw -ErrorId "ParseException" - try { - ExecuteCommand "testcmd-parserbvt | 'abc'" - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand "testcmd-parserbvt | 'abc'" } | Should -Throw -ErrorId "ParseException" } It "Throws when you pipe into a value expression (line 238)" { foreach($command in "1;2;3|3",'1;2;3|$(1+1)',"1;2;3|'abc'") { - try { - ExecuteCommand $command - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand $command } | Should -Throw -ErrorId "ParseException" } } It "Throws an incomplete parse exception when a comma follows an expression (line 247)" { - try { - ExecuteCommand "(1+ 1)," - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "IncompleteParseException" - } + { ExecuteCommand "(1+ 1)," } | Should -Throw -ErrorId "IncompleteParseException" } It "Test that invoke has a higher precedence for a script than for an executable. (line 279)" { @@ -469,83 +421,35 @@ foo``u{2195}abc } It "This test will check that it is a syntax error to use if without a code block. (line 1141)" { - try { - ExecuteCommand 'if ("true")' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "IncompleteParseException" - } + { ExecuteCommand 'if ("true")' } | Should -Throw -ErrorId "IncompleteParseException" } It "This test will check that it is a syntax error if the if condition is not complete. (line 1150)" { - try { - ExecuteCommand 'if (' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "IncompleteParseException" - } + { ExecuteCommand 'if (' } | Should -Throw -ErrorId "IncompleteParseException" } It "This test will check that it is a syntax error to have an if condition without parentheses. (line 1159)" { - try { - ExecuteCommand 'if "true" { 1} else {2}' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand 'if "true" { 1} else {2}' } | Should -Throw -ErrorId "ParseException" } It "This test will check that the parser throws a syntax error when the if condition is missing the closing parentheses. (line 1168)" { - try { - ExecuteCommand 'if ("true" { 1};' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand 'if ("true" { 1};' } | Should -Throw -ErrorId "ParseException" } It "This test will check that it is a syntax error to have an else keyword without the corresponding code block. (line 1177)" { - try { - ExecuteCommand 'if ("true") {1} else' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "IncompleteParseException" - } + { ExecuteCommand 'if ("true") {1} else' } | Should -Throw -ErrorId "IncompleteParseException" } It "This test will check that the parser throws a syntax error when a foreach loop is not complete. (line 1238)" { - try { - ExecuteCommand '$count=0;$files = $(get-childitem / -filter *.txt );foreach ($i ;$count' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand '$count=0;$files = $(get-childitem / -filter *.txt );foreach ($i ;$count' } | Should -Throw -ErrorId "ParseException" } It "This test will check that the parser throws a syntax error if the foreach loop is not complete. (line 1248)" { - try { - ExecuteCommand '$count=0;$files = $(get-childitem / -filter *.txt );foreach ($i in ;$count' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand '$count=0;$files = $(get-childitem / -filter *.txt );foreach ($i in ;$count' } | Should -Throw -ErrorId "ParseException" } It "This will test that the parser throws a syntax error if the foreach loop is missing a closing parentheses. (line 1258)" { - try { - ExecuteCommand '$count=0;$files = $(get-childitem / -filter *.txt );foreach ($i in $files ;$count' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand '$count=0;$files = $(get-childitem / -filter *.txt );foreach ($i in $files ;$count' } | Should -Throw -ErrorId "ParseException" } It "Test that if an exception is thrown from the try block it will be caught in the appropropriate catch block and that the finally block will run regardless of whether an exception is thrown. (line 1317)" { @@ -782,33 +686,15 @@ foo``u{2195}abc } It "Test that an incomplete parse exception is thrown if the array is unfinished. (line 2473)"{ - try { - ExecuteCommand '1,2,' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "IncompleteParseException" - } + { ExecuteCommand '1,2,' } | Should -Throw -ErrorId "IncompleteParseException" } It "Test that the unary comma is not valid in cmdlet parameters. (line 2482)"{ - try { - ExecuteCommand 'write-output 2,,1' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand 'write-output 2,,1' } | Should -Throw -ErrorId "ParseException" } It 'Test that "$var:" will expand to nothing inside a string. (line 2551)'{ - try { - ExecuteCommand '"$var:"' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand '"$var:"' } | Should -Throw -ErrorId "ParseException" } It "Tests the assignment to a read-only property (line 2593)"{ @@ -824,23 +710,11 @@ foo``u{2195}abc } It 'Tests the parser response to ArrayName[. (line 2678)'{ - try { - ExecuteCommand '$A=$(testcmd-parserBVT -returntype array); $A[ ;' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand '$A=$(testcmd-parserBVT -returntype array); $A[ ;' } | Should -Throw -ErrorId "ParseException" } It 'Tests the parser response to ArrayName[]. (line 2687)'{ - try { - ExecuteCommand '$A=$(testcmd-parserBVT -returntype array); $A[] ;' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand '$A=$(testcmd-parserBVT -returntype array); $A[] ;' } | Should -Throw -ErrorId "ParseException" } #Issue#1430 @@ -902,13 +776,7 @@ foo``u{2195}abc } It "A here string must have one line (line 3266)" { - try { - ExecuteCommand "@`"`"@" - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand "@`"`"@" } | Should -Throw -ErrorId "ParseException" } It "A here string should not throw on '`$herestr=@`"``n'`"'``n`"@'" { diff --git a/test/powershell/Language/Parser/UsingAssembly.Tests.ps1 b/test/powershell/Language/Parser/UsingAssembly.Tests.ps1 index 42b33d9ea29..7eda4785887 100644 --- a/test/powershell/Language/Parser/UsingAssembly.Tests.ps1 +++ b/test/powershell/Language/Parser/UsingAssembly.Tests.ps1 @@ -69,15 +69,8 @@ public class ABC {} } It "reports runtime error about non-existing assembly with relative path" { - $failed = $true - try { - [scriptblock]::Create("using assembly .\NonExistingAssembly.dll") - $failed = $false - } catch { - $_.FullyQualifiedErrorId | Should -Be 'ParseException' - $_.Exception.InnerException.ErrorRecord.FullyQualifiedErrorId | Should -Be 'ErrorLoadingAssembly' - } - $failed | Should -BeTrue + $e = { [scriptblock]::Create("using assembly .\NonExistingAssembly.dll") } | Should -Throw -ErrorId 'ParseException' -PassThru + $e.Exception.InnerException.ErrorRecord.FullyQualifiedErrorId | Should -Be 'ErrorLoadingAssembly' } #> It "Assembly loaded at runtime" -pending { diff --git a/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 b/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 index 3b90565e03b..f4fbcbc0413 100644 --- a/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 +++ b/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 @@ -34,29 +34,23 @@ Describe "Tests for (error, warning, etc) action preference" -Tags "CI" { } It 'action preference of Ignore cannot be set as a preference variable' { - try { + $e = { $GLOBAL:errorActionPreference = "Ignore" Get-Process -Name asdfasdfasdf - Throw "Exception expected, execution should not have reached here" - } catch { - $_.CategoryInfo.Reason | Should -BeExactly 'NotSupportedException' - } finally { - $GLOBAL:errorActionPreference = $orgin - } + } | Should -Throw -ErrorId 'System.NotSupportedException,Microsoft.PowerShell.Commands.GetProcessCommand' -PassThru + $e.CategoryInfo.Reason | Should -BeExactly 'NotSupportedException' + $GLOBAL:errorActionPreference = $orgin } It 'action preference of Suspend cannot be set as a preference variable' { - try { - $GLOBAL:errorActionPreference = "Suspend" - Get-Process -Name asdfasdfasdf - Throw "Exception expected, execution should not have reached here" - } catch { - $_.CategoryInfo.Reason | Should -BeExactly 'ArgumentTransformationMetadataException' - } - finally { - $GLOBAL:errorActionPreference = $orgin - } + $e = { + $GLOBAL:errorActionPreference = "Suspend" + Get-Process -Name asdfasdfasdf + } | Should -Throw -ErrorId 'RuntimeException' -PassThru + $e.CategoryInfo.Reason | Should -BeExactly 'ArgumentTransformationMetadataException' + + $GLOBAL:errorActionPreference = $orgin } It 'enum disambiguation works' { @@ -78,35 +72,15 @@ Describe "Tests for (error, warning, etc) action preference" -Tags "CI" { "Hello" } - try - { - MyHelperFunction -ErrorAction Suspend - Throw "Exception expected, execution should not have reached here" - } catch { - $_.FullyQualifiedErrorId | Should -BeExactly "ParameterBindingFailed,MyHelperFunction" - } + { MyHelperFunction -ErrorAction Suspend } | Should -Throw -ErrorId "ParameterBindingFailed,MyHelperFunction" } It 'ErrorAction = Suspend does not work on cmdlets' { - try - { - Get-Process -ErrorAction Suspend - Throw "Exception expected, execution should not have reached here" - } - catch { - $_.FullyQualifiedErrorId | Should -BeExactly "ParameterBindingFailed,Microsoft.PowerShell.Commands.GetProcessCommand" - } + { Get-Process -ErrorAction Suspend } | Should -Throw -ErrorId "ParameterBindingFailed,Microsoft.PowerShell.Commands.GetProcessCommand" } It 'WarningAction = Suspend does not work' { - try - { - Get-Process -WarningAction Suspend - Throw "Exception expected, execution should not have reached here" - } - catch { - $_.FullyQualifiedErrorId | Should -BeExactly "ParameterBindingFailed,Microsoft.PowerShell.Commands.GetProcessCommand" - } + { Get-Process -WarningAction Suspend } | Should -Throw -ErrorId "ParameterBindingFailed,Microsoft.PowerShell.Commands.GetProcessCommand" } #issue 2076 @@ -118,15 +92,8 @@ Describe "Tests for (error, warning, etc) action preference" -Tags "CI" { $params | ForEach-Object { $input=@{'InputObject' = 'Test';$_='Suspend'} - - try { - Write-Output @input - } catch { - $_.FullyQualifiedErrorId | Should -BeExactly "ParameterBindingFailed,Microsoft.PowerShell.Commands.WriteOutputCommand" - $num++ - } + { Write-Output @input } | Should -Throw -ErrorId "ParameterBindingFailed,Microsoft.PowerShell.Commands.WriteOutputCommand" } - $num | Should -Be 2 } It '<switch> does not take precedence over $ErrorActionPreference' -TestCases @( diff --git a/test/powershell/Language/Scripting/CheckRestrictedlanguage.Tests.ps1 b/test/powershell/Language/Scripting/CheckRestrictedlanguage.Tests.ps1 index 11c988af65f..ab2ab662030 100644 --- a/test/powershell/Language/Scripting/CheckRestrictedlanguage.Tests.ps1 +++ b/test/powershell/Language/Scripting/CheckRestrictedlanguage.Tests.ps1 @@ -25,17 +25,7 @@ Describe "Test restricted language check method on scriptblocks" -Tags "CI" { } It 'Check default variables' { - - try - { - {2+$a}.CheckRestrictedLanguage($null, $null, $false) - Throw "Exception expected, execution should not have reached here" - } - catch - { - $_.FullyQualifiedErrorId | Should -BeExactly 'ParseException' - } - + { {2+$a}.CheckRestrictedLanguage($null, $null, $false) } | Should -Throw -ErrorId 'ParseException' } It 'Check union of default + one allowed variables' { @@ -54,29 +44,11 @@ Describe "Test restricted language check method on scriptblocks" -Tags "CI" { } It 'Check union of default + one disallowed variables' { - - try - { - { $a + $b + $c }.CheckRestrictedLanguage($null, (list a b), $false) # fail - Throw "Exception expected, execution should not have reached here" - } - catch - { - $_.FullyQualifiedErrorId | Should -BeExactly 'ParseException' - } + { { $a + $b + $c }.CheckRestrictedLanguage($null, (list a b), $false) } | Should -Throw -ErrorId 'ParseException' } It 'Check union of default + one allowed variable and but not allow environment variable' { - - try - { - { 2 + $a + $env:foo }.CheckRestrictedLanguage($null, (list a), $false) # fail - Throw "Exception expected, execution should not have reached here" - } - catch - { - $_.FullyQualifiedErrorId | Should -BeExactly 'ParseException' - } + { { 2 + $a + $env:foo }.CheckRestrictedLanguage($null, (list a), $false) } | Should -Throw -ErrorId 'ParseException' } It 'Check union of default + one allowed variable name and allow environment variable ' { @@ -90,16 +62,7 @@ Describe "Test restricted language check method on scriptblocks" -Tags "CI" { } It 'Check for restricted commands' { - - try - { - {get-date}.CheckRestrictedLangauge($null, $null, $false) - Throw "Exception expected, execution should not have reached here" - } - catch - { - $_.FullyQualifiedErrorId | Should -BeExactly 'MethodNotFound' - } + { {get-date}.CheckRestrictedLangauge($null, $null, $false) } | Should -Throw -ErrorId 'MethodNotFound' } It 'Check for allowed commands and variables' { diff --git a/test/powershell/Language/Scripting/CommonParameters.Tests.ps1 b/test/powershell/Language/Scripting/CommonParameters.Tests.ps1 index 955e922786b..dce1c1e3d31 100644 --- a/test/powershell/Language/Scripting/CommonParameters.Tests.ps1 +++ b/test/powershell/Language/Scripting/CommonParameters.Tests.ps1 @@ -137,14 +137,8 @@ Describe "Common parameters support for script cmdlets" -Tags "CI" { [void] $ps.AddScript($script + $command) $asyncResult = $ps.BeginInvoke() - try - { - $ps.EndInvoke($asyncResult) - Throw "Exception expected, execution should not have reached here" - } - catch { - $_.FullyQualifiedErrorId | Should -BeExactly "ActionPreferenceStopException" - } # Exception: "Command execution stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: error foo" + { $ps.EndInvoke($asyncResult) } | Should -Throw -ErrorId "ActionPreferenceStopException" + # Exception: "Command execution stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: error foo" # BUG in runspace api. #$ps.error.count | Should Be 1 diff --git a/test/powershell/Language/Scripting/Debugging/DebuggerScriptTests.Tests.ps1 b/test/powershell/Language/Scripting/Debugging/DebuggerScriptTests.Tests.ps1 index bcac808cee8..2eb919d9a7e 100644 --- a/test/powershell/Language/Scripting/Debugging/DebuggerScriptTests.Tests.ps1 +++ b/test/powershell/Language/Scripting/Debugging/DebuggerScriptTests.Tests.ps1 @@ -278,18 +278,8 @@ Describe "Unit tests for various script breakpoints" -Tags "CI" { # function VerifyException([ScriptBlock] $command, [string] $exception) { - try - { - & $command - - throw "No Exception!" - } - catch - { - It "Script failed expected exception '${command}'" { - $_.Exception.GetType().Name | Should -Be $exception - } - } + $e = { & $command } | Should -Throw -PassThru + $e.Exception.GetType().Name | Should -Be $exception } # diff --git a/test/powershell/Language/Scripting/DeserializedTypeConversion.Tests.ps1 b/test/powershell/Language/Scripting/DeserializedTypeConversion.Tests.ps1 index c848028454b..7960fe2ba4a 100644 --- a/test/powershell/Language/Scripting/DeserializedTypeConversion.Tests.ps1 +++ b/test/powershell/Language/Scripting/DeserializedTypeConversion.Tests.ps1 @@ -144,15 +144,7 @@ Describe "Tests conversion of deserialized types to original type using object p } It 'Type casts should fail.' { - - try - { - $tc3 = [test3]$dst3 - Throw "Exception expected, execution should not have reached here" - } - catch { - $_.FullyQualifiedErrorId | Should -BeExactly 'InvalidCastConstructorException' - } + { $tc3 = [test3]$dst3 } | Should -Throw -ErrorId 'InvalidCastConstructorException' } It 'Parameter bindings should fail.' { @@ -167,14 +159,7 @@ Describe "Tests conversion of deserialized types to original type using object p $test | Format-List | Out-String } - try - { - test-3 $dst3 - Throw "Exception expected, execution should not have reached here" - } - catch { - $_.FullyQualifiedErrorId | Should -BeExactly 'ParameterArgumentTransformationError,test-3' - } + { test-3 $dst3 } | Should -Throw -ErrorId 'ParameterArgumentTransformationError,test-3' } } diff --git a/test/powershell/Language/Scripting/Dynamicparameters.Tests.ps1 b/test/powershell/Language/Scripting/Dynamicparameters.Tests.ps1 index 525dcc7296b..1c17a467ade 100644 --- a/test/powershell/Language/Scripting/Dynamicparameters.Tests.ps1 +++ b/test/powershell/Language/Scripting/Dynamicparameters.Tests.ps1 @@ -64,12 +64,7 @@ Describe "Dynamic parameter support in script cmdlets." -Tags "CI" { } It "When the dynamic parameter is not available, and raises an error when specified" { - try { - foo-bar -path def -dp1 42 - Throw "Exception expected, execution should not have reached here" - } catch { - $_.FullyQualifiedErrorId | Should -BeExactly "NamedParameterNotFound,foo-bar" - } + { foo-bar -path def -dp1 42 } | Should -Throw -ErrorId "NamedParameterNotFound,foo-bar" } It "No dynamic parameter shouldn't cause an errr " { diff --git a/test/powershell/Language/Scripting/Generics.Tests.ps1 b/test/powershell/Language/Scripting/Generics.Tests.ps1 index 42af8395e2e..e3843256953 100644 --- a/test/powershell/Language/Scripting/Generics.Tests.ps1 +++ b/test/powershell/Language/Scripting/Generics.Tests.ps1 @@ -61,14 +61,8 @@ Describe "Generics support" -Tags "CI" { # The error message for a generic that doesn't meet the constraints should mention which # argument failed. - $ex = $null - try { - [nullable[object]] - Throw "Exception expected, execution should not have reached here" - } catch { - $_.FullyQualifiedErrorId | Should -BeExactly 'TypeNotFoundWithMessage' - $_ | Should -Match "\[T\]" - } + $e = { [nullable[object]] } | Should -Throw -ErrorId 'TypeNotFoundWithMessage' -PassThru + $e | Should -Match "\[T\]" } It 'Array type works properly' -skip:$IsCoreCLR{ diff --git a/test/powershell/Language/Scripting/HashtableToPSCustomObjectConversion.Tests.ps1 b/test/powershell/Language/Scripting/HashtableToPSCustomObjectConversion.Tests.ps1 index 745497c4c0d..11fb9004c5e 100644 --- a/test/powershell/Language/Scripting/HashtableToPSCustomObjectConversion.Tests.ps1 +++ b/test/powershell/Language/Scripting/HashtableToPSCustomObjectConversion.Tests.ps1 @@ -99,20 +99,14 @@ Describe "Tests for hashtable to PSCustomObject conversion" -Tags "CI" { It '<Name>' -TestCases:$testData1 { param ($Name, $Cmd, $ErrorID, $InnerException) - try + $e = { Invoke-Expression $Cmd } | Should -Throw -PassThru + + if($InnerException) { - Invoke-Expression $Cmd - Throw "Exception expected, execution should not have reached here" - } catch { - - if($InnerException) - { - $_.Exception.InnerException.ErrorRecord.FullyQualifiedErrorId | Should -BeExactly $ErrorID - } - else { - $_.FullyQualifiedErrorId | Should -BeExactly $ErrorID - } - } + $e.Exception.InnerException.ErrorRecord.FullyQualifiedErrorId | Should -BeExactly $ErrorID + } else { + $e.FullyQualifiedErrorId | Should -BeExactly $ErrorID + } } It 'Creating an object of an existing type from hashtable should succeed' { @@ -139,20 +133,12 @@ Describe "Tests for hashtable to PSCustomObject conversion" -Tags "CI" { $obj.PSTypeNames[0] | Should -BeExactly 'System.Object' } It "new-object should fail to create object for System.Management.Automation.PSCustomObject" { - - $errorObj = $null $obj = $null - $ht = @{one=1;two=2} - try - { - $obj = New-Object System.Management.Automation.PSCustomObject -property $ht - } - catch - { - $errorObj = $_ - } + $ht = @{one=1;two=2} + + { $obj = New-Object System.Management.Automation.PSCustomObject -property $ht } | + Should -Throw -ErrorId "CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand" $obj | Should -BeNullOrEmpty - $errorObj.FullyQualifiedErrorId | Should -BeExactly "CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand" } } diff --git a/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 b/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 index 634d75331cb..a0dc9c1d669 100644 --- a/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 +++ b/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 @@ -420,16 +420,9 @@ Describe "Tests for parameter binding" -Tags "CI" { param([ValidateScript({$_ -gt 2}, ErrorMessage = "Item '{0}' failed '{1}' validation")] $p) $p } - $errMsg = '' - try - { - get-fooi -p 2 - } - catch - { - $errMsg = $_.Exception.Message - } - $errMsg | Should -BeExactly "Cannot validate argument on parameter 'p'. Item '2' failed '`$_ -gt 2' validation" + + $err = { get-fooi -p 2 } | Should -Throw -ErrorId 'ParameterArgumentValidationError,get-fooi' -PassThru + $err.Exception.Message | Should -BeExactly "Cannot validate argument on parameter 'p'. Item '2' failed '`$_ -gt 2' validation" } It "ValidatePattern can use custom ErrorMessage" { @@ -439,16 +432,9 @@ Describe "Tests for parameter binding" -Tags "CI" { param([ValidatePattern("\s+", ErrorMessage = "Item '{0}' failed '{1}' regex")] $p) $p } - $errMsg = '' - try - { - get-fooj -p 2 - } - catch - { - $errMsg = $_.Exception.Message - } - $errMsg | Should -BeExactly "Cannot validate argument on parameter 'p'. Item '2' failed '\s+' regex" + + $err = { get-fooj -p 2 } | Should -Throw -ErrorId 'ParameterArgumentValidationError,get-fooj' -PassThru + $err.Exception.Message | Should -BeExactly "Cannot validate argument on parameter 'p'. Item '2' failed '\s+' regex" } It "ValidateSet can use custom ErrorMessage" { @@ -456,17 +442,10 @@ Describe "Tests for parameter binding" -Tags "CI" { { param([ValidateSet('A', 'B', 'C', IgnoreCase=$false, ErrorMessage="Item '{0}' is not in '{1}'")] $p) } - $errMsg = '' - try - { - get-fook -p 2 - } - catch - { - $errMsg = $_.Exception.Message - } + + $err = { get-fook -p 2 } | Should -Throw -ErrorId 'ParameterArgumentValidationError,get-fook' -PassThru $set = 'A','B','C' -join [Globalization.CultureInfo]::CurrentUICulture.TextInfo.ListSeparator - $errMsg | Should -BeExactly "Cannot validate argument on parameter 'p'. Item '2' is not in '$set'" + $err.Exception.Message | Should -BeExactly "Cannot validate argument on parameter 'p'. Item '2' is not in '$set'" } } diff --git a/test/powershell/Language/Scripting/Requires.Tests.ps1 b/test/powershell/Language/Scripting/Requires.Tests.ps1 index c7bcd051fd6..6d28a1d25d7 100644 --- a/test/powershell/Language/Scripting/Requires.Tests.ps1 +++ b/test/powershell/Language/Scripting/Requires.Tests.ps1 @@ -15,16 +15,8 @@ Describe "Requires tests" -Tags "CI" { It "throws ParserException - <testname>" -TestCases $testcases { param($command) - try - { - [scriptblock]::Create($command) - throw "'$command' should have thrown ParserError" - } - catch - { - $_.FullyQualifiedErrorId | Should -BeExactly "ParseException" - } + { [scriptblock]::Create($command) } | Should -Throw -ErrorId "ParseException" } } +} -} \ No newline at end of file From f58b56ecccb58eb858181f0d637025cee3ccf013 Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Wed, 18 Apr 2018 18:02:44 -0700 Subject: [PATCH 18/58] [Feature] try {} catch {} => Should -Throw -ErrorId in Management. --- .../Clear-Content.Tests.ps1 | 75 +++++-------------- .../Copy.Item.Tests.ps1 | 68 ++++------------- .../FileSystem.Tests.ps1 | 52 +++---------- .../Get-Content.Tests.ps1 | 19 ++--- .../Get-Service.Tests.ps1 | 18 +---- .../Join-Path.Tests.ps1 | 8 +- 6 files changed, 59 insertions(+), 181 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Clear-Content.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Clear-Content.Tests.ps1 index f4e1d02385a..b21a744a057 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Clear-Content.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Clear-Content.Tests.ps1 @@ -97,87 +97,50 @@ Describe "Clear-Content cmdlet tests" -Tags "CI" { } It "the '-Stream' dynamic parameter should not be visible to get-command in the function provider" { - try { - Push-Location -Path function: - Get-Command Clear-Content -Stream $streamName - throw "ExpectedExceptionNotDelivered" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "NamedParameterNotFound,Microsoft.PowerShell.Commands.GetCommandCommand" - } - finally { - Pop-Location - } + Push-Location -Path function: + { Get-Command Clear-Content -Stream $streamName } | + Should -Throw -ErrorId "NamedParameterNotFound,Microsoft.PowerShell.Commands.GetCommandCommand" + Pop-Location } } Context "Proper errors should be delivered when bad locations are specified" { It "should throw `"Cannot bind argument to parameter 'Path'`" when -Path is `$null" { - try { - Clear-Content -Path $null -ErrorAction Stop - throw "expected exception was not delivered" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ClearContentCommand" - } + { Clear-Content -Path $null -ErrorAction Stop } | + Should -Throw -ErrorId "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ClearContentCommand" } #[BugId(BugDatabase.WindowsOutOfBandReleases, 903880)] It "should throw `"Cannot bind argument to parameter 'Path'`" when -Path is `$()" { - try { - Clear-Content -Path $() -ErrorAction Stop - throw "expected exception was not delivered" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ClearContentCommand" - } + { Clear-Content -Path $() -ErrorAction Stop } | + Should -Throw -ErrorId "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ClearContentCommand" } #[DRT][BugId(BugDatabase.WindowsOutOfBandReleases, 906022)] It "should throw 'PSNotSupportedException' when you clear-content to an unsupported provider" { $functionName = Get-NonExistantFunctionName $null = New-Item -Path function:$functionName -Value { 1 } - try { - Clear-Content -Path function:$functionName -ErrorAction Stop - throw "Expected exception was not thrown" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "NotSupported,Microsoft.PowerShell.Commands.ClearContentCommand" - } + { Clear-Content -Path function:$functionName -ErrorAction Stop } | + Should -Throw -ErrorId "NotSupported,Microsoft.PowerShell.Commands.ClearContentCommand" } It "should throw FileNotFound error when referencing a non-existant file" { - try { - $badFile = "TestDrive:/badfilename.txt" - Clear-Content -Path $badFile -ErrorAction Stop - throw "ExpectedExceptionNotDelivered" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "PathNotFound,Microsoft.PowerShell.Commands.ClearContentCommand" - } + $badFile = "TestDrive:/badfilename.txt" + { Clear-Content -Path $badFile -ErrorAction Stop } | + Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.ClearContentCommand" } It "should throw DriveNotFound error when referencing a non-existant drive" { - try { - $badDrive = "{0}:/file.txt" -f (Get-NonExistantDriveName) - Clear-Content -Path $badDrive -ErrorAction Stop - throw "ExpectedExceptionNotDelivered" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "DriveNotFound,Microsoft.PowerShell.Commands.ClearContentCommand" - } + $badDrive = "{0}:/file.txt" -f (Get-NonExistantDriveName) + { Clear-Content -Path $badDrive -ErrorAction Stop } | + Should -Throw -ErrorId "DriveNotFound,Microsoft.PowerShell.Commands.ClearContentCommand" } # we'll use a provider qualified path to produce this error It "should throw ProviderNotFound error when referencing a non-existant provider" { - try { - $badProviderPath = "{0}::C:/file.txt" -f (Get-NonExistantProviderName) - Clear-Content -Path $badProviderPath -ErrorAction Stop - throw "ExpectedExceptionNotDelivered" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ProviderNotFound,Microsoft.PowerShell.Commands.ClearContentCommand" - } + $badProviderPath = "{0}::C:/file.txt" -f (Get-NonExistantProviderName) + { Clear-Content -Path $badProviderPath -ErrorAction Stop } | + Should -Throw -ErrorId "ProviderNotFound,Microsoft.PowerShell.Commands.ClearContentCommand" } } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Copy.Item.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Copy.Item.Tests.ps1 index 0471d1afe8c..ffed38232cc 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Copy.Item.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Copy.Item.Tests.ps1 @@ -322,15 +322,8 @@ Describe "Validate Copy-Item Remotely" -Tags "CI" { $destinationFolderPath = Join-Path $destinationFolderPath "A\B\C\D\E" $expectedFullyQualifiedErrorId = 'RemotePathNotFound,Microsoft.PowerShell.Commands.CopyItemCommand' - try - { - Copy-Item -Path $filePath -ToSession $s -Destination $destinationFolderPath -ErrorAction Stop - throw "CodeExecuted" - } - catch - { - $_.FullyQualifiedErrorId | Should -Be $expectedFullyQualifiedErrorId - } + { Copy-Item -Path $filePath -ToSession $s -Destination $destinationFolderPath -ErrorAction Stop } | + Should -Throw -ErrorId $expectedFullyQualifiedErrorId } It "Copy folder to remote session recursively works even if the target directory does not exist." { @@ -408,20 +401,13 @@ Describe "Validate Copy-Item Remotely" -Tags "CI" { } It "Copy one file from remote session fails when the target directory does not exist." { - $filePath = CreateTestFile $destinationFolderPath = GetDestinationFolderPath $destinationFolderPath = Join-Path $destinationFolderPath "A\B\C\D\E" $expectedFullyQualifiedErrorId = 'CopyItemRemotelyIOError,Microsoft.PowerShell.Commands.CopyItemCommand' - try - { - Copy-Item -Path $filePath -FromSession $s -Destination $destinationFolderPath -ErrorAction Stop - throw "CodeExecuted" - } - catch - { - $_.FullyQualifiedErrorId | Should -Be $expectedFullyQualifiedErrorId - } + + { Copy-Item -Path $filePath -FromSession $s -Destination $destinationFolderPath -ErrorAction Stop } | + Should -Throw -ErrorId $expectedFullyQualifiedErrorId } It "Copy folder from remote session recursively works even if the target directory does not exist." { @@ -565,29 +551,15 @@ Describe "Validate Copy-Item Remotely" -Tags "CI" { if ($fromSession) { It "Copy-Item FromSession -Path '$path' throws $expectedFullyQualifiedErrorId" { - try - { - Copy-Item -Path $path -FromSession $s -Destination $destination -ErrorAction Stop - throw "CodeExecuted" - } - catch - { - $_.FullyQualifiedErrorId | Should -Be $expectedFullyQualifiedErrorId - } + { Copy-Item -Path $path -FromSession $s -Destination $destination -ErrorAction Stop } | + Should -Throw -ErrorId $expectedFullyQualifiedErrorId } } else { It "Copy-Item ToSession -Destination '$path' throws $expectedFullyQualifiedErrorId" { - try - { - Copy-Item -Path $path -ToSession $s -Destination $destination -ErrorAction Stop - throw "CodeExecuted" - } - catch - { - $_.FullyQualifiedErrorId | Should -Be $expectedFullyQualifiedErrorId - } + { Copy-Item -Path $path -ToSession $s -Destination $destination -ErrorAction Stop } | + Should -Throw -ErrorId $expectedFullyQualifiedErrorId } } } @@ -733,26 +705,12 @@ Describe "Validate Copy-Item error for target sessions not in FullLanguageMode." It "Copy-Item throws 'SessionIsNotInFullLanguageMode' error for a session in '$languageMode'" { # FromSession - try - { - Copy-Item -Path $testFilePath -FromSession $session -Destination $destination -Force -Verbose -ErrorAction Stop - throw "CodeExecuted" - } - catch - { - $_.FullyQualifiedErrorId | Should -Be "SessionIsNotInFullLanguageMode,Microsoft.PowerShell.Commands.CopyItemCommand" - } + { Copy-Item -Path $testFilePath -FromSession $session -Destination $destination -Force -Verbose -ErrorAction Stop } | + Should -Throw -ErrorId "SessionIsNotInFullLanguageMode,Microsoft.PowerShell.Commands.CopyItemCommand" # ToSession - try - { - Copy-Item -Path $testFilePath -ToSession $session -Destination $destination -Force -Verbose -ErrorAction Stop - throw "CodeExecuted" - } - catch - { - $_.FullyQualifiedErrorId | Should -Be "SessionIsNotInFullLanguageMode,Microsoft.PowerShell.Commands.CopyItemCommand" - } + { Copy-Item -Path $testFilePath -ToSession $session -Destination $destination -Force -Verbose -ErrorAction Stop } | + Should -Throw -ErrorId "SessionIsNotInFullLanguageMode,Microsoft.PowerShell.Commands.CopyItemCommand" } } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 index 757f614c643..e1f397978d8 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 @@ -886,11 +886,8 @@ Describe "Extended FileSystem Item/Content Cmdlet Provider Tests" -Tags "Feature It "Verify Directory + Whatif" { New-Item -Path . -ItemType Directory -Name $testDir -WhatIf > $null - try { - Get-Item -Path $testDir -ErrorAction Stop - throw "Expected exception not thrown" - } - catch { $_.FullyQualifiedErrorId | Should -Be "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } + { Get-Item -Path $testDir -ErrorAction Stop } | + Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } It "Verify Directory + Confirm bypass" { @@ -965,11 +962,8 @@ Describe "Extended FileSystem Item/Content Cmdlet Provider Tests" -Tags "Feature It "Verify WhatIf" { Move-Item -Path $testFile -Destination $altTestFile -WhatIf - try { - Get-Item -Path $altTestFile -ErrorAction Stop - throw "Expected exception not thrown" - } - catch { $_.FullyQualifiedErrorId | Should -Be "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } + { Get-Item -Path $altTestFile -ErrorAction Stop } | + Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } It "Verify Include and Exclude Intersection" { @@ -997,11 +991,8 @@ Describe "Extended FileSystem Item/Content Cmdlet Provider Tests" -Tags "Feature It "Verify WhatIf" { Rename-Item -Path $testFile -NewName $newFile -WhatIf - try { - Get-Item -Path $newFile -ErrorAction Stop - throw "Expected exception not thrown" - } - catch { $_.FullyQualifiedErrorId | Should -Be "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } + { Get-Item -Path $newFile -ErrorAction Stop } | + Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } It "Verify Confirm can be bypassed" { @@ -1022,20 +1013,12 @@ Describe "Extended FileSystem Item/Content Cmdlet Provider Tests" -Tags "Feature It "Verify Confirm can be bypassed" { Remove-Item $testFile -Confirm:$false - try { - Get-Item $testFile -ErrorAction Stop - throw "Expected exception not thrown" - } - catch { $_.FullyQualifiedErrorId | Should -Be "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } + { Get-Item $testFile -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } It "Verify LiteralPath" { Remove-Item -LiteralPath "TestDrive:\$testFile" -Recurse - try { - Get-Item $testFile -ErrorAction Stop - throw "Expected exception not thrown" - } - catch { $_.FullyQualifiedErrorId | Should -Be "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } + { Get-Item $testFile -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } It "Verify Filter" { @@ -1046,11 +1029,7 @@ Describe "Extended FileSystem Item/Content Cmdlet Provider Tests" -Tags "Feature It "Verify Include" { Remove-Item "TestDrive:\*" -Include "*2.txt" - try { - Get-Item $testFile2 -ErrorAction Stop - throw "Expected exception not thrown" - } - catch { $_.FullyQualifiedErrorId | Should -Be "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } + { Get-Item $testFile2 -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } It "Verify Include and Exclude Intersection" { @@ -1307,11 +1286,7 @@ Describe "Extended FileSystem Path/Location Cmdlet Provider Tests" -Tags "Featur } It "WhatIf is Not Supported" { - try { - Set-Location $level1_0 -WhatIf - throw "Expected exception not thrown" - } - catch { $_.FullyQualifiedErrorId | Should -Be "NamedParameterNotFound,Microsoft.PowerShell.Commands.SetLocationCommand" } + { Set-Location $level1_0 -WhatIf } | Should -Throw -ErrorId "NamedParameterNotFound,Microsoft.PowerShell.Commands.SetLocationCommand" } } @@ -1359,11 +1334,8 @@ Describe "Extended FileSystem Path/Location Cmdlet Provider Tests" -Tags "Featur } It "Verify Pop + Invalid Stack Name" { - try { - Pop-Location -StackName UnknownStackName -ErrorAction Stop - throw "Expected exception not thrown" - } - catch { $_.FullyQualifiedErrorId | Should -Be "Argument,Microsoft.PowerShell.Commands.PopLocationCommand" } + { Pop-Location -StackName UnknownStackName -ErrorAction Stop } | + Should -Throw -ErrorId "Argument,Microsoft.PowerShell.Commands.PopLocationCommand" } } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 index 68e69060837..dfb389e024f 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 @@ -23,15 +23,10 @@ Describe "Get-Content" -Tags "CI" { Remove-Item -Path $testPath -Force Remove-Item -Path $testPath2 -Force } - + It "Should throw an error on a directory " { - try { - Get-Content . -ErrorAction Stop - throw "No Exception!" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "GetContentReaderUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetContentCommand" - } + { Get-Content . -ErrorAction Stop } | + Should -Throw -ErrorId "GetContentReaderUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetContentCommand" } It "Should return an Object when listing only a single line and the correct information from a file" { @@ -254,7 +249,7 @@ baz param($cmdlet) (Get-Command $cmdlet).Parameters["stream"] | Should -BeNullOrEmpty } - + It "Should return no content when an empty path is used with -Raw switch" { Get-ChildItem $TestDrive -Filter "*.raw" | Get-Content -Raw | Should -BeNullOrEmpty } @@ -264,7 +259,7 @@ baz } It "Should throw TailAndHeadCannotCoexist when both -Tail and -TotalCount are used" { - { + { Get-Content -Path $testPath -Tail 1 -TotalCount 1 -ErrorAction Stop } | Should -Throw -ErrorId "TailAndHeadCannotCoexist,Microsoft.PowerShell.Commands.GetContentCommand" } @@ -347,11 +342,11 @@ baz Describe "Get-Content -Raw test" -Tags "CI" { - It "Reads - <testname> in full" -TestCases @( + It "Reads - <testname> in full" -TestCases @( @{character = "a`nb`n"; testname = "LF-terminated files"; filename = "lf.txt"} @{character = "a`r`nb`r`n"; testname = "CRLF-terminated files"; filename = "crlf.txt"} @{character = "a`nb"; testname = "LF-separated files without trailing newline"; filename = "lf-nt.txt"} - @{character = "a`r`nb"; testname = "CRLF-separated files without trailing newline"; filename = "crlf-nt.txt"} + @{character = "a`r`nb"; testname = "CRLF-separated files without trailing newline"; filename = "crlf-nt.txt"} ) { param ($character, $filename) Set-Content -Encoding Ascii -NoNewline "$TestDrive\$filename" -Value $character diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Service.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Service.Tests.ps1 index 75c7977c9d1..8b9a55308eb 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Service.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Service.Tests.ps1 @@ -21,26 +21,16 @@ Describe "Get-Service cmdlet tests" -Tags "CI" { Context 'Check null or empty value to the -Name parameter' { It 'Should throw if <value> is passed to -Name parameter' -TestCases $testCases { param($data) - try { - $null = Get-Service -Name $data -ErrorAction Stop - throw 'Expected error on previous command' - } - catch { - $_.FullyQualifiedErrorId | Should -Be 'ParameterArgumentValidationError,Microsoft.Powershell.Commands.GetServiceCommand' - } + { $null = Get-Service -Name $data -ErrorAction Stop } | + Should -Throw -ErrorId 'ParameterArgumentValidationError,Microsoft.Powershell.Commands.GetServiceCommand' } } Context 'Check null or empty value to the -Name parameter via pipeline' { It 'Should throw if <value> is passed through pipeline to -Name parameter' -TestCases $testCases { param($data) - try { - $null = Get-Service -Name $data -ErrorAction Stop - throw 'Expected error on previous command' - } - catch { - $_.FullyQualifiedErrorId | Should -Be 'ParameterArgumentValidationError,Microsoft.Powershell.Commands.GetServiceCommand' - } + { $null = Get-Service -Name $data -ErrorAction Stop } | + Should -Throw -ErrorId 'ParameterArgumentValidationError,Microsoft.Powershell.Commands.GetServiceCommand' } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Join-Path.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Join-Path.Tests.ps1 index d56fa7941e3..3c607d6253a 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Join-Path.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Join-Path.Tests.ps1 @@ -13,12 +13,12 @@ Describe "Join-Path cmdlet tests" -Tags "CI" { (Join-Path -Path TestDrive:,$TestDrive -ChildPath "SubDir1" -resolve).Length | Should -Be 2 } It "should throw 'DriveNotFound' when called with -Resolve and drive does not exist" { - try {Join-Path bogusdrive:\\somedir otherdir -resolve -ErrorAction Stop; Throw "Previous statement unexpectedly succeeded..." - } catch {$_.FullyQualifiedErrorId | Should -Be "DriveNotFound,Microsoft.PowerShell.Commands.JoinPathCommand"} + { Join-Path bogusdrive:\\somedir otherdir -resolve -ErrorAction Stop; Throw "Previous statement unexpectedly succeeded..." } | + Should -Throw -ErrorId "DriveNotFound,Microsoft.PowerShell.Commands.JoinPathCommand" } It "should throw 'PathNotFound' when called with -Resolve and item does not exist" { - try {Join-Path "Bogus" "Path" -resolve -ErrorAction Stop; Throw "Previous statement unexpectedly succeeded..." - } catch {$_.FullyQualifiedErrorId | Should -Be "PathNotFound,Microsoft.PowerShell.Commands.JoinPathCommand"} + { Join-Path "Bogus" "Path" -resolve -ErrorAction Stop; Throw "Previous statement unexpectedly succeeded..." } | + Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.JoinPathCommand" } #[BugId(BugDatabase.WindowsOutOfBandReleases, 905237)] Note: Result should be the same on non-Windows platforms too It "should return one object when called with a Windows FileSystem::Redirector" { From 78189ba9ecf19e46c73c0fda35ea04df968b7036 Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Thu, 19 Apr 2018 09:12:46 -0700 Subject: [PATCH 19/58] [Feature] try {} catch {} => Should -Throw -ErrorId in Security module. --- .../AmsiInterface.Tests.ps1 | 11 +- .../CmsMessage.Tests.ps1 | 32 +- .../ConstrainedLanguageRestriction.Tests.ps1 | 342 +++++------------- .../ExecutionPolicy.Tests.ps1 | 16 +- .../SecureString.Tests.ps1 | 21 +- 5 files changed, 106 insertions(+), 316 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/AmsiInterface.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/AmsiInterface.Tests.ps1 index ef60650054b..f342afcd3fa 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/AmsiInterface.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/AmsiInterface.Tests.ps1 @@ -21,15 +21,8 @@ try $EICAR_STRING_B64 = "awZ8EmMWc3JjaAdvY2lrBgcbY20aBHBwGgROF3Z6cHJhHmBncn13cmF3HnJ9Z3plemFmYB5ndmBnHnV6f3YSF3sYexk= " $bytes = [System.Convert]::FromBase64String($EICAR_STRING_B64) $EICAR_STRING = -join ($bytes | % { [char]($_ -bxor 0x33) }) - try - { - Invoke-Expression -Command "echo '$EICAR_STRING'" - throw "No exception thrown!" - } - catch - { - $_.FullyQualifiedErrorId | Should Be "ScriptContainedMaliciousContent,Microsoft.PowerShell.Commands.InvokeExpressionCommand" - } + { Invoke-Expression -Command "echo '$EICAR_STRING'" } | + Should -Throw -ErrorId "ScriptContainedMaliciousContent,Microsoft.PowerShell.Commands.InvokeExpressionCommand" } } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/CmsMessage.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/CmsMessage.Tests.ps1 index f35c24d9ec7..0865032b85b 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/CmsMessage.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/CmsMessage.Tests.ps1 @@ -223,12 +223,8 @@ Describe "CmsMessage cmdlets thorough tests" -Tags "Feature" { } It "Verify Protect-CmsMessage emits recipient errors" { - try { - "Hello World" | Protect-CmsMessage -To "SomeThumbprintThatDoesNotExist" -ErrorAction Stop - throw "No Exception!" - } catch { - $_.FullyQualifiedErrorId | Should -Be "NoCertificateFound,Microsoft.PowerShell.Commands.ProtectCmsMessageCommand" - } + { "Hello World" | Protect-CmsMessage -To "SomeThumbprintThatDoesNotExist" -ErrorAction Stop } | + Should -Throw -ErrorId "NoCertificateFound,Microsoft.PowerShell.Commands.ProtectCmsMessageCommand" } It "Verify CmsMessage cmdlets works with paths" { @@ -270,30 +266,18 @@ Describe "CmsMessage cmdlets thorough tests" -Tags "Feature" { } It "Verify Unprotect-CmsMessage emits recipient errors" { - try { - "" | Unprotect-CmsMessage -To "SomeThumbprintThatDoesNotExist" -IncludeContext -ErrorAction Stop - throw "No Exception!" - } catch { - $_.FullyQualifiedErrorId | Should -Be "NoCertificateFound,Microsoft.PowerShell.Commands.UnprotectCmsMessageCommand" - } + { "" | Unprotect-CmsMessage -To "SomeThumbprintThatDoesNotExist" -IncludeContext -ErrorAction Stop } | + Should -Throw -ErrorId "NoCertificateFound,Microsoft.PowerShell.Commands.UnprotectCmsMessageCommand" } It "Verify failure to extract Ascii armor generates an error [Unprotect-CmsMessage]" { - try { - "Hello World" | Unprotect-CmsMessage -ErrorAction Stop - throw "No Exception!" - } catch { - $_.FullyQualifiedErrorId | Should -Be "InputContainedNoEncryptedContentIncludeContext,Microsoft.PowerShell.Commands.UnprotectCmsMessageCommand" - } + { "Hello World" | Unprotect-CmsMessage -ErrorAction Stop } | + Should -Throw -ErrorId "InputContainedNoEncryptedContentIncludeContext,Microsoft.PowerShell.Commands.UnprotectCmsMessageCommand" } It "Verify failure to extract Ascii armor generates an error [Get-CmsMessage]" { - try { - "Hello World" | Get-CmsMessage -ErrorAction Stop - throw "No Exception!" - } catch { - $_.FullyQualifiedErrorId | Should -Be "InputContainedNoEncryptedContent,Microsoft.PowerShell.Commands.GetCmsMessageCommand" - } + { "Hello World" | Get-CmsMessage -ErrorAction Stop } | + Should -Throw -ErrorId "InputContainedNoEncryptedContent,Microsoft.PowerShell.Commands.GetCmsMessageCommand" } It "Verify 'Unprotect-CmsMessage -IncludeContext' with no encrypted input" { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/ConstrainedLanguageRestriction.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/ConstrainedLanguageRestriction.Tests.ps1 index 4c5073c4a95..368303b9fde 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/ConstrainedLanguageRestriction.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/ConstrainedLanguageRestriction.Tests.ps1 @@ -155,24 +155,15 @@ try Context "Background jobs within inconsistent mode" { It "Verifies that background job is denied when mode is inconsistent" { - - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" Start-Job { [object]::Equals("A", "B") } - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru - $exception.FullyQualifiedErrorId | Should -Match "CannotStartJobInconsistentLanguageMode" + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode + + $e.FullyQualifiedErrorId | Should -Match "CannotStartJobInconsistentLanguageMode" } } } @@ -180,24 +171,14 @@ try Describe "Add-Type in constrained language" -Tags 'Feature','RequireAdminOnWindows' { It "Verifies Add-Type fails in constrained language mode" { - - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" Add-Type -TypeDefinition 'public class ConstrainedLanguageTest { public static string Hello = "HelloConstrained"; }' - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - $exception.FullyQualifiedErrorId | Should -Match "CannotDefineNewType" + $e.FullyQualifiedErrorId | Should -Match "CannotDefineNewType" } It "Verifies Add-Type works back in full language mode again" { @@ -228,23 +209,15 @@ try It "Verifies New-Object throws error in constrained language for disallowed IntPtr type" { - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" New-Object System.IntPtr 1234 - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru - $exception.FullyQualifiedErrorId | Should -Match "CannotCreateTypeConstrainedLanguage" + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode + + $e.FullyQualifiedErrorId | Should -Match "CannotCreateTypeConstrainedLanguage" } It "Verifies New-Object works for IntPtr type back in full language mode again" { @@ -257,24 +230,16 @@ try It "Verifies New-Object with COM types is disallowed in system lock down" { - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" Invoke-LanguageModeTestingSupportCmdlet -SetLockdownMode New-Object -Com ADODB.Parameter - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -RevertLockdownMode -EnableFullLanguageMode - } + } | Should -Throw -PassThru + + Invoke-LanguageModeTestingSupportCmdlet -RevertLockdownMode -EnableFullLanguageMode - $exception.FullyQualifiedErrorId | Should -Match "CannotCreateComTypeConstrainedLanguage" + $e.FullyQualifiedErrorId | Should -Match "CannotCreateComTypeConstrainedLanguage" } It "Verifies New-Object with COM types works back in full language mode again" { @@ -288,49 +253,29 @@ try Describe "New-Item command on function drive in constrained language" -Tags 'Feature','RequireAdminOnWindows' { It "Verifies New-Item directory on function drive is not allowed in constrained language mode" { - - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" $null = New-Item -Path function:\SomeEvilFunction -ItemType Directory -Value SomeBadScriptBlock -ErrorAction Stop - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } - - $exception.FullyQualifiedErrorId | Should -Match "NotSupported" + } | Should -Throw -PassThru + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode + $e.FullyQualifiedErrorId | Should -Match "NotSupported" } } Describe "Script debugging in constrained language" -Tags 'Feature','RequireAdminOnWindows' { It "Verifies that a debugging breakpoint cannot be set in constrained language and no system lockdown" { - - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" function MyDebuggerFunction {} Set-PSBreakpoint -Command MyDebuggerFunction - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru - $exception.FullyQualifiedErrorId | Should -Match "CannotSetBreakpointInconsistentLanguageMode" + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode + + $e.FullyQualifiedErrorId | Should -Match "CannotSetBreakpointInconsistentLanguageMode" } It "Verifies that a debugging breakpoint can be set in constrained language with system lockdown" { @@ -354,9 +299,7 @@ try } It "Verifies that debugger commands do not run in full language mode when system is locked down" { - - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" function MyDebuggerFunction3 {} @@ -365,19 +308,12 @@ try $restoreEAPreference = $ErrorActionPreference $ErrorActionPreference = "Stop" MyDebuggerFunction3 - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - if ($restoreEAPreference -ne $null) { $ErrorActionPreference = $restoreEAPreference } - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru + + if ($restoreEAPreference -ne $null) { $ErrorActionPreference = $restoreEAPreference } + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - $exception.FullyQualifiedErrorId | Should Match "CannotSetBreakpointInconsistentLanguageMode" + $e.FullyQualifiedErrorId | Should Match "CannotSetBreakpointInconsistentLanguageMode" } It "Verifies that debugger command injection is blocked in system lock down" { @@ -445,23 +381,14 @@ try Import-Module PSDiagnostics $module = Get-Module PSDiagnostics - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - & $module { [object]::Equals("A", "B") } - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru + + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - $exception.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" + $e.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" } } @@ -475,21 +402,11 @@ try $rs.Open() $pl = $rs.CreatePipeline("switch -file $testDrive/foo.txt { 'A' { 'B' } }") - try - { - $pl.Invoke() - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - $rs.Dispose() - } + $e = { $pl.Invoke() } | Should -Throw -PassThru + + $rs.Dispose() - $exception.FullyQualifiedErrorId | Should -Match "DriveNotFoundException" + $e.FullyQualifiedErrorId | Should -Match "DriveNotFoundException" } } @@ -521,21 +438,11 @@ try $rs.Open() $pl = $rs.CreatePipeline('"Hello" > c:\temp\foo.txt') - try - { - $pl.Invoke() - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - $rs.Dispose() - } + $e = { $pl.Invoke() } | Should -Throw -PassThru + + $rs.Dispose() - $exception.FullyQualifiedErrorId | Should -Match "CmdletInvocationException" + $e.FullyQualifiedErrorId | Should -Match "CmdletInvocationException" } } @@ -557,23 +464,15 @@ try param ($scriptblock) - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" & $scriptblock - throw 'No Exception!' - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru + + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - $exception.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" + $e.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" } } @@ -581,48 +480,33 @@ try It "Verifies dynamic method invocation does not bypass constrained language mode" { - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" $type = [IO.Path] $method = "GetRandomFileName" $type::$method() throw 'No Exception!' - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru + + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - $exception.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" + $e.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" } It "Verifies dynamic methods invocation does not bypass constrained language mode" { - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" $type = [IO.Path] $methods = "GetRandomFileName","GetTempPath" $type::($methods[0])() - throw 'No Exception!' - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru + + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - $exception.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" + $e.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" } } @@ -649,44 +533,28 @@ try It "Verifies Set-Variable cannot create AllScope in constrained language" { - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" Set-Variable -Name SetVariableAllScopeNotSupported -Value bar -Option AllScope - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru + + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - $exception.FullyQualifiedErrorId | Should -Match "NotSupported" + $e.FullyQualifiedErrorId | Should -Match "NotSupported" } It "Verifies New-Variable cannot create AllScope in constrained language" { - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" New-Variable -Name NewVarialbeAllScopeNotSupported -Value bar -Option AllScope - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru - $exception.FullyQualifiedErrorId | Should -Match "NotSupported" + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode + + $e.FullyQualifiedErrorId | Should -Match "NotSupported" } } @@ -694,17 +562,9 @@ try function InvokeDataSectionConstrained { - try - { - Invoke-Expression 'data foo -SupportedCommand Add-Type { Add-Type }' - throw "No Exception!" - } - catch - { - $exception = $_ - } + $e = { Invoke-Expression 'data foo -SupportedCommand Add-Type { Add-Type }' } | Should -Throw -PassThru - return $exception + return $e } It "Verifies data section Add-Type additional command is disallowed in constrained language" { @@ -728,24 +588,16 @@ try It "Verifies data section with no-constant expression Add-Type additional command is disallowed in constrained language" { - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" $addedCommand = "Add-Type" Invoke-Expression 'data foo -SupportedCommand $addedCommand { Add-Type }' - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru - $exception.FullyQualifiedErrorId | Should -Match "DataSectionAllowedCommandDisallowed" + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode + + $e.FullyQualifiedErrorId | Should -Match "DataSectionAllowedCommandDisallowed" } } @@ -753,25 +605,17 @@ try It "Verifies Import-LocalizedData disallows Add-Type in constrained language" { - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" $localizedDataFileName = Join-Path $TestDrive ImportLocalizedDataAdditionalCommandsNotSupported.psd1 $null = New-Item -ItemType File -Path $localizedDataFileName -Force Import-LocalizedData -SupportedCommand Add-Type -BaseDirectory $TestDrive -FileName ImportLocalizedDataAdditionalCommandsNotSupported - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru + + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - $exception.FullyQualifiedErrorId | Should -Match "CannotDefineSupportedCommand" + $e.FullyQualifiedErrorId | Should -Match "CannotDefineSupportedCommand" } } @@ -861,25 +705,17 @@ try [string] $script ) - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" # Scriptblock must be created inside constrained language. $sb = [scriptblock]::Create($script) & sb - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru + + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - $exception.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" + $e.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 index f26f55a8a91..e5f71072759 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 @@ -559,21 +559,9 @@ ZoneId=$FileType $scriptName = $testScript - $exception = $null - try { - & $scriptName - } - catch - { - $exception = $_ - } - - $exception.Exception | Should -Not -BeNullOrEmpty - - $exceptionType = $exception.Exception.getType() - $result = $exceptionType + $exception = { & $scriptName } | Should -Throw -PassThru - $result | Should -Be "System.Management.Automation.PSSecurityException" + $exception.Exception | Should -BeOfType "System.Management.Automation.PSSecurityException" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/SecureString.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/SecureString.Tests.ps1 index 9f49c94f2d9..a97c32a1080 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/SecureString.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/SecureString.Tests.ps1 @@ -14,25 +14,14 @@ Describe "SecureString conversion tests" -Tags "CI" { } It "using null arguments to ConvertFrom-SecureString produces an exception" { - try { - ConvertFrom-SecureString -secureString $null -key $null - throw "No Exception!" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertFromSecureStringCommand" - } - + { ConvertFrom-SecureString -secureString $null -key $null } | + Should -Throw -ErrorId "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertFromSecureStringCommand" } It "using a bad key produces an exception" { - try { - $badkey = [byte[]]@(1,2) - ConvertFrom-SecureString -securestring $secureString -key $badkey - throw "Command did not throw exception" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "Argument,Microsoft.PowerShell.Commands.ConvertFromSecureStringCommand" - } + $badkey = [byte[]]@(1,2) + { ConvertFrom-SecureString -securestring $secureString -key $badkey } | + Should -Throw -ErrorId "Argument,Microsoft.PowerShell.Commands.ConvertFromSecureStringCommand" } It "Can convert to a secure string" { From a60304cfe88a370dfa8dbc68652ee2ab155e8708 Mon Sep 17 00:00:00 2001 From: Klaudia Algiz <klalgiz@microsoft.com> Date: Thu, 19 Apr 2018 10:52:31 -0700 Subject: [PATCH 20/58] [Feature] ConstrainedLanguageRestriction tests fixes. --- .../ConstrainedLanguageRestriction.Tests.ps1 | 172 +++++------------- 1 file changed, 49 insertions(+), 123 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/ConstrainedLanguageRestriction.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/ConstrainedLanguageRestriction.Tests.ps1 index 368303b9fde..512f8dbedea 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/ConstrainedLanguageRestriction.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/ConstrainedLanguageRestriction.Tests.ps1 @@ -155,15 +155,10 @@ try Context "Background jobs within inconsistent mode" { It "Verifies that background job is denied when mode is inconsistent" { - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - - Start-Job { [object]::Equals("A", "B") } - } | Should -Throw -PassThru + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + { Start-Job { [object]::Equals("A", "B") } } | Should -Throw -ErrorId "CannotStartJobInconsistentLanguageMode" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "CannotStartJobInconsistentLanguageMode" } } } @@ -171,14 +166,10 @@ try Describe "Add-Type in constrained language" -Tags 'Feature','RequireAdminOnWindows' { It "Verifies Add-Type fails in constrained language mode" { - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - - Add-Type -TypeDefinition 'public class ConstrainedLanguageTest { public static string Hello = "HelloConstrained"; }' - } | Should -Throw -PassThru + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + { Add-Type -TypeDefinition 'public class ConstrainedLanguageTest { public static string Hello = "HelloConstrained"; }' } | + Should -Throw -ErrorId "CannotDefineNewType" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "CannotDefineNewType" } It "Verifies Add-Type works back in full language mode again" { @@ -208,16 +199,10 @@ try } It "Verifies New-Object throws error in constrained language for disallowed IntPtr type" { - - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - - New-Object System.IntPtr 1234 - } | Should -Throw -PassThru + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + { New-Object System.IntPtr 1234 } | Should -Throw -ErrorId "CannotCreateTypeConstrainedLanguage" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "CannotCreateTypeConstrainedLanguage" } It "Verifies New-Object works for IntPtr type back in full language mode again" { @@ -229,17 +214,12 @@ try Context "New-Object with COM types" { It "Verifies New-Object with COM types is disallowed in system lock down" { + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + Invoke-LanguageModeTestingSupportCmdlet -SetLockdownMode - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - Invoke-LanguageModeTestingSupportCmdlet -SetLockdownMode - - New-Object -Com ADODB.Parameter - } | Should -Throw -PassThru + { New-Object -Com ADODB.Parameter } | Should -Throw -ErrorId "CannotCreateComTypeConstrainedLanguage" Invoke-LanguageModeTestingSupportCmdlet -RevertLockdownMode -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "CannotCreateComTypeConstrainedLanguage" } It "Verifies New-Object with COM types works back in full language mode again" { @@ -253,29 +233,22 @@ try Describe "New-Item command on function drive in constrained language" -Tags 'Feature','RequireAdminOnWindows' { It "Verifies New-Item directory on function drive is not allowed in constrained language mode" { - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - - $null = New-Item -Path function:\SomeEvilFunction -ItemType Directory -Value SomeBadScriptBlock -ErrorAction Stop - } | Should -Throw -PassThru + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + { $null = New-Item -Path function:\SomeEvilFunction -ItemType Directory -Value SomeBadScriptBlock -ErrorAction Stop } | + Should -Throw -ErrorId "NotSupported" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - $e.FullyQualifiedErrorId | Should -Match "NotSupported" } } Describe "Script debugging in constrained language" -Tags 'Feature','RequireAdminOnWindows' { It "Verifies that a debugging breakpoint cannot be set in constrained language and no system lockdown" { - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + function MyDebuggerFunction {} - function MyDebuggerFunction {} - Set-PSBreakpoint -Command MyDebuggerFunction - } | Should -Throw -PassThru + { Set-PSBreakpoint -Command MyDebuggerFunction } | Should -Throw -ErrorId "CannotSetBreakpointInconsistentLanguageMode" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "CannotSetBreakpointInconsistentLanguageMode" } It "Verifies that a debugging breakpoint can be set in constrained language with system lockdown" { @@ -299,21 +272,19 @@ try } It "Verifies that debugger commands do not run in full language mode when system is locked down" { - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - function MyDebuggerFunction3 {} - $null = Set-PSBreakpoint -Command MyDebuggerFunction3 -Action { $Global:dbgResult = [object]::Equals("A", "B") } + function MyDebuggerFunction3 {} + { + $null = Set-PSBreakpoint -Command MyDebuggerFunction3 -Action { $Global:dbgResult = [object]::Equals("A", "B") } $restoreEAPreference = $ErrorActionPreference $ErrorActionPreference = "Stop" MyDebuggerFunction3 - } | Should -Throw -PassThru + } | Should -Throw -ErrorId "CannotSetBreakpointInconsistentLanguageMode" if ($restoreEAPreference -ne $null) { $ErrorActionPreference = $restoreEAPreference } Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should Match "CannotSetBreakpointInconsistentLanguageMode" } It "Verifies that debugger command injection is blocked in system lock down" { @@ -381,14 +352,10 @@ try Import-Module PSDiagnostics $module = Get-Module PSDiagnostics - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - & $module { [object]::Equals("A", "B") } - } | Should -Throw -PassThru + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + { & $module { [object]::Equals("A", "B") } } | Should -Throw -ErrorId "MethodInvocationNotSupportedInConstrainedLanguage" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" } } @@ -402,11 +369,9 @@ try $rs.Open() $pl = $rs.CreatePipeline("switch -file $testDrive/foo.txt { 'A' { 'B' } }") - $e = { $pl.Invoke() } | Should -Throw -PassThru + $e = { $pl.Invoke() } | Should -Throw -ErrorId "DriveNotFoundException" $rs.Dispose() - - $e.FullyQualifiedErrorId | Should -Match "DriveNotFoundException" } } @@ -438,11 +403,9 @@ try $rs.Open() $pl = $rs.CreatePipeline('"Hello" > c:\temp\foo.txt') - $e = { $pl.Invoke() } | Should -Throw -PassThru + $e = { $pl.Invoke() } | Should -Throw -ErrorId "CmdletInvocationException" $rs.Dispose() - - $e.FullyQualifiedErrorId | Should -Match "CmdletInvocationException" } } @@ -464,49 +427,35 @@ try param ($scriptblock) - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - - & $scriptblock - } | Should -Throw -PassThru + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + { & $scriptblock } | Should -Throw -ErrorId "MethodInvocationNotSupportedInConstrainedLanguage" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" } } Describe "Dynamic method invocation in constrained language mode" -Tags 'Feature','RequireAdminOnWindows' { It "Verifies dynamic method invocation does not bypass constrained language mode" { - - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + { $type = [IO.Path] $method = "GetRandomFileName" $type::$method() - throw 'No Exception!' - } | Should -Throw -PassThru + } | Should -Throw -ErrorId "MethodInvocationNotSupportedInConstrainedLanguage" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" } It "Verifies dynamic methods invocation does not bypass constrained language mode" { - - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + { $type = [IO.Path] $methods = "GetRandomFileName","GetTempPath" $type::($methods[0])() - } | Should -Throw -PassThru + } | Should -Throw -ErrorId "MethodInvocationNotSupportedInConstrainedLanguage" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" } } @@ -532,29 +481,19 @@ try Describe "Variable AllScope in constrained language mode" -Tags 'Feature','RequireAdminOnWindows' { It "Verifies Set-Variable cannot create AllScope in constrained language" { - - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - - Set-Variable -Name SetVariableAllScopeNotSupported -Value bar -Option AllScope - } | Should -Throw -PassThru + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + { Set-Variable -Name SetVariableAllScopeNotSupported -Value bar -Option AllScope } | + Should -Throw -ErrorId "NotSupported" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "NotSupported" } It "Verifies New-Variable cannot create AllScope in constrained language" { - - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - - New-Variable -Name NewVarialbeAllScopeNotSupported -Value bar -Option AllScope - } | Should -Throw -PassThru + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + { New-Variable -Name NewVarialbeAllScopeNotSupported -Value bar -Option AllScope } | + Should -Throw -ErrorId "NotSupported" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "NotSupported" } } @@ -587,35 +526,26 @@ try } It "Verifies data section with no-constant expression Add-Type additional command is disallowed in constrained language" { - - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - - $addedCommand = "Add-Type" - Invoke-Expression 'data foo -SupportedCommand $addedCommand { Add-Type }' - } | Should -Throw -PassThru + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + $addedCommand = "Add-Type" + { Invoke-Expression 'data foo -SupportedCommand $addedCommand { Add-Type }' } | + Should -Throw -ErrorId "DataSectionAllowedCommandDisallowed" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "DataSectionAllowedCommandDisallowed" } } Describe "Import-LocalizedData additional commands in constrained language" -Tags 'Feature','RequireAdminOnWindows' { It "Verifies Import-LocalizedData disallows Add-Type in constrained language" { - - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + { $localizedDataFileName = Join-Path $TestDrive ImportLocalizedDataAdditionalCommandsNotSupported.psd1 $null = New-Item -ItemType File -Path $localizedDataFileName -Force Import-LocalizedData -SupportedCommand Add-Type -BaseDirectory $TestDrive -FileName ImportLocalizedDataAdditionalCommandsNotSupported - } | Should -Throw -PassThru + } | Should -Throw -ErrorId "CannotDefineSupportedCommand" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "CannotDefineSupportedCommand" } } @@ -704,18 +634,14 @@ try param ( [string] $script ) - - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + { # Scriptblock must be created inside constrained language. $sb = [scriptblock]::Create($script) & sb - } | Should -Throw -PassThru + } | Should -Throw -ErrorId "MethodInvocationNotSupportedInConstrainedLanguage" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" } } From af33b1eb95589b7f1234af564965ce017c70b9fa Mon Sep 17 00:00:00 2001 From: Klaudia Algiz <klalgiz@microsoft.com> Date: Thu, 19 Apr 2018 11:08:09 -0700 Subject: [PATCH 21/58] [Feature] try {} catch {} => Should -Throw -ErrorId in Security module continued. --- .../ExecutionPolicy.Tests.ps1 | 20 +++++-------------- 1 file changed, 5 insertions(+), 15 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 index e5f71072759..d1a704bb56d 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 @@ -1032,13 +1032,8 @@ ZoneId=$FileType [string] $policyScope ) - try { - Set-ExecutionPolicy -Scope $policyScope -ExecutionPolicy Restricted - throw "No Exception!" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "CantSetGroupPolicy,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand" - } + { Set-ExecutionPolicy -Scope $policyScope -ExecutionPolicy Restricted } | + Should -Throw -ErrorId "CantSetGroupPolicy,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand" } function RestoreExecutionPolicy @@ -1152,14 +1147,9 @@ ZoneId=$FileType Set-ExecutionPolicy -Scope Process -ExecutionPolicy Undefined Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Restricted - try - { - Set-ExecutionPolicy -Scope LocalMachine -ExecutionPolicy ByPass - throw "Expected exception: ExecutionPolicyOverride" - } - catch [System.Security.SecurityException] { - $_.FullyQualifiedErrorId | Should -Be 'ExecutionPolicyOverride,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand' - } + + { Set-ExecutionPolicy -Scope LocalMachine -ExecutionPolicy ByPass } | + Should -Throw -ErrorId 'ExecutionPolicyOverride,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand' Get-ExecutionPolicy -Scope LocalMachine | Should -Be "ByPass" } From 6069527ac0ea69ec889b92dc81df905546ce2000 Mon Sep 17 00:00:00 2001 From: Klaudia Algiz <klalgiz@microsoft.com> Date: Thu, 19 Apr 2018 11:30:26 -0700 Subject: [PATCH 22/58] [Feature] try {} catch {} => Should -Throw -ErrorId in Utility module. --- .../Implicit.Remoting.Tests.ps1 | 29 ++++++++----------- .../Unblock-File.Tests.ps1 | 16 +++------- 2 files changed, 16 insertions(+), 29 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Implicit.Remoting.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Implicit.Remoting.Tests.ps1 index 16d772a98e6..abe47d5dae0 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Implicit.Remoting.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Implicit.Remoting.Tests.ps1 @@ -340,13 +340,12 @@ try } It "Verifies that Export-PSSession fails when a module directory already exists" { - try { - Export-PSSession -Session $session -CommandName Get-Variable -AllowClobber -ModuleName $file -EA SilentlyContinue -ErrorVariable expectedError - } catch { } + $e = { Export-PSSession -Session $session -CommandName Get-Variable -AllowClobber -ModuleName $file -ErrorAction Stop } | + Should -Throw -PassThru - $expectedError | Should -Not -BeNullOrEmpty + $e | Should -Not -BeNullOrEmpty # Error contains reference to the directory that already exists - ([string]($expectedError[0]) -like "*$file*") | Should -BeTrue + ([string]($e[0]) -like "*$file*") | Should -BeTrue } It "Verifies that overwriting an existing directory succeeds with -Force" { @@ -1686,19 +1685,15 @@ try } It "Get-Command returns something that is not CommandInfo" { - try { - Invoke-Command $session { $oldGetCommand = ${function:Get-Command} } - Invoke-Command $session { function Get-Command { Microsoft.PowerShell.Utility\Get-Variable } } + Invoke-Command $session { $oldGetCommand = ${function:Get-Command} } + Invoke-Command $session { function Get-Command { Microsoft.PowerShell.Utility\Get-Variable } } + $e = { $module = Import-PSSession -Session $session -AllowClobber } | Should -Throw -PassThru - $module = Import-PSSession -Session $session -AllowClobber - throw "Import-PSSession should throw" - } catch { - $msg = [string]($_) - $msg.Contains("Get-Command") | Should -BeTrue - } finally { - if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } - Invoke-Command $session { ${function:Get-Command} = $oldGetCommand } - } + $msg = [string]($e) + $msg.Contains("Get-Command") | Should -BeTrue + + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + Invoke-Command $session { ${function:Get-Command} = $oldGetCommand } } # Test order of remote commands (alias > function > cmdlet > external script) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 index c615191d22a..b85cb1156f0 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 @@ -1,16 +1,8 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. function Test-UnblockFile { - try { - Get-Content -Path $testfilepath -Stream Zone.Identifier -ErrorAction Stop | Out-Null - } - catch { - if ($_.FullyQualifiedErrorId -eq "GetContentReaderFileNotFoundError,Microsoft.PowerShell.Commands.GetContentCommand") { - return $true - } - } - - return $false + { Get-Content -Path $testfilepath -Stream Zone.Identifier -ErrorAction Stop | Out-Null } | + Should -Throw -ErrorId "GetContentReaderFileNotFoundError,Microsoft.PowerShell.Commands.GetContentCommand" } Describe "Unblock-File" -Tags "CI" { @@ -48,7 +40,7 @@ Describe "Unblock-File" -Tags "CI" { It "With '-Path': file exist" { Unblock-File -Path $testfilepath - Test-UnblockFile | Should -BeTrue + Test-UnblockFile # If a file is not blocked we silently return without an error. { Unblock-File -Path $testfilepath -ErrorAction Stop } | Should -Not -Throw @@ -56,7 +48,7 @@ Describe "Unblock-File" -Tags "CI" { It "With '-LiteralPath': file exist" { Unblock-File -LiteralPath $testfilepath - Test-UnblockFile | Should -BeTrue + Test-UnblockFile } It "Write an error if a file is read only" { From 59b73511936c8ce8790533f7c30380d65fbf42fa Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Thu, 19 Apr 2018 13:08:15 -0700 Subject: [PATCH 23/58] [Feature] Tests fixes. --- .../Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 index 50ff168743e..2b994a5dc8d 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 @@ -14,7 +14,7 @@ Describe "Clear-Variable DRT Unit Tests" -Tags "CI" { It "Clear-Variable ReadOnly variable Name should throw exception and force Clear-Variable should works"{ Set-Variable foo bar -Option ReadOnly - $e = { Clear-Variable -Name foo -Scope 1 -EA Stop } | Should -Throw -ErrorId "VariableNotWritable,Microsoft.PowerShell.Commands.ClearVariableCommand" + $e = { Clear-Variable -Name foo -Scope 1 -EA Stop } | Should -Throw -ErrorId "VariableNotWritable,Microsoft.PowerShell.Commands.ClearVariableCommand" -PassThru $e.CategoryInfo | Should -Match "SessionStateUnauthorizedAccessException" Clear-Variable -Name foo -Force @@ -50,7 +50,7 @@ Describe "Clear-Variable DRT Unit Tests" -Tags "CI" { Set-Variable foo bar -Option Private &{ $e = { Get-Variable -Name foo -Scope local -EA Stop } | - Should -Throw -ErrorId "VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand" + Should -Throw -ErrorId "VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand" -PassThru $e.CategoryInfo | Should -Match "ItemNotFoundException" } From 3a1007f134431f6f26f5a79faa6d60896deafc9a Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Fri, 20 Apr 2018 09:07:18 -0700 Subject: [PATCH 24/58] [Feature] Tests fixes. --- test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 | 2 +- .../Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 | 6 +++--- .../Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 b/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 index aaf5519ec60..e5d6fecf29a 100644 --- a/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 +++ b/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 @@ -28,7 +28,7 @@ Try { $instance.GetCimSessionInstanceId() | Should -BeOfType "Guid" } It "should produce an error for a non-existing classname" { - { get-ciminstance -classname thisnameshouldnotexist -ea stop } | + { get-ciminstance -classname thisnameshouldnotexist -ErrorAction stop } | Should -Throw -ErrorId "HRESULT 0x80041010,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstanceCommand" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 index 2b994a5dc8d..52922bce7ce 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 @@ -14,7 +14,7 @@ Describe "Clear-Variable DRT Unit Tests" -Tags "CI" { It "Clear-Variable ReadOnly variable Name should throw exception and force Clear-Variable should works"{ Set-Variable foo bar -Option ReadOnly - $e = { Clear-Variable -Name foo -Scope 1 -EA Stop } | Should -Throw -ErrorId "VariableNotWritable,Microsoft.PowerShell.Commands.ClearVariableCommand" -PassThru + $e = { Clear-Variable -Name foo -Scope 1 -ErrorAction Stop } | Should -Throw -ErrorId "VariableNotWritable,Microsoft.PowerShell.Commands.ClearVariableCommand" -PassThru $e.CategoryInfo | Should -Match "SessionStateUnauthorizedAccessException" Clear-Variable -Name foo -Force @@ -49,7 +49,7 @@ Describe "Clear-Variable DRT Unit Tests" -Tags "CI" { It "Clear-Variable Private variable Name should works and Get-Variable with local scope should throw exception"{ Set-Variable foo bar -Option Private &{ - $e = { Get-Variable -Name foo -Scope local -EA Stop } | + $e = { Get-Variable -Name foo -Scope local -ErrorAction Stop } | Should -Throw -ErrorId "VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand" -PassThru $e.CategoryInfo | Should -Match "ItemNotFoundException" } @@ -176,7 +176,7 @@ Describe "Clear-Variable" -Tags "CI" { It "Should throw error when trying to clear variable that is read-only without using the Force parameter" { New-Variable -Name var2 -Option ReadOnly -Value 100 - { Clear-Variable -Name var2 -Scope 1 -ea stop } | Should -Throw -ErrorId "VariableNotWritable,Microsoft.PowerShell.Commands.ClearVariableCommand" + { Clear-Variable -Name var2 -Scope 1 -ErrorAction stop } | Should -Throw -ErrorId "VariableNotWritable,Microsoft.PowerShell.Commands.ClearVariableCommand" $var2 | Should -Not -BeNullOrEmpty diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 index b85cb1156f0..1b3a3e69d7d 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 @@ -40,7 +40,7 @@ Describe "Unblock-File" -Tags "CI" { It "With '-Path': file exist" { Unblock-File -Path $testfilepath - Test-UnblockFile + Test-UnblockFile | Should -BeTrue # If a file is not blocked we silently return without an error. { Unblock-File -Path $testfilepath -ErrorAction Stop } | Should -Not -Throw @@ -48,7 +48,7 @@ Describe "Unblock-File" -Tags "CI" { It "With '-LiteralPath': file exist" { Unblock-File -LiteralPath $testfilepath - Test-UnblockFile + Test-UnblockFile | Should -BeTrue } It "Write an error if a file is read only" { From 75a4c4a97b26b94fa0b11bef9e4e5e9192d6b91d Mon Sep 17 00:00:00 2001 From: Klaudia Algiz <klalgiz@microsoft.com> Date: Fri, 20 Apr 2018 13:03:58 -0700 Subject: [PATCH 25/58] [Feature] Unblock-File tests fix. --- .../Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 index 1b3a3e69d7d..b85cb1156f0 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 @@ -40,7 +40,7 @@ Describe "Unblock-File" -Tags "CI" { It "With '-Path': file exist" { Unblock-File -Path $testfilepath - Test-UnblockFile | Should -BeTrue + Test-UnblockFile # If a file is not blocked we silently return without an error. { Unblock-File -Path $testfilepath -ErrorAction Stop } | Should -Not -Throw @@ -48,7 +48,7 @@ Describe "Unblock-File" -Tags "CI" { It "With '-LiteralPath': file exist" { Unblock-File -LiteralPath $testfilepath - Test-UnblockFile | Should -BeTrue + Test-UnblockFile } It "Write an error if a file is read only" { From 89d29e4e0755daaa2214edfcdad66c89699e9be5 Mon Sep 17 00:00:00 2001 From: algizklaudia <algizklaudia@gmail.com> Date: Tue, 17 Apr 2018 11:12:02 -0700 Subject: [PATCH 26/58] [Feature] CimCmdlets and Diagnostics module Error tests fix. --- .../Modules/CimCmdlets/CimInstance.Tests.ps1 | 8 ++------ .../Modules/CimCmdlets/Get-CimClass.Tests.ps1 | 18 ++++-------------- .../New-WinEvent.Tests.ps1 | 8 ++++---- 3 files changed, 10 insertions(+), 24 deletions(-) diff --git a/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 b/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 index c4960a2b463..075fbf6f602 100644 --- a/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 +++ b/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 @@ -28,12 +28,8 @@ Try { $instance.GetCimSessionInstanceId() | Should -BeOfType "Guid" } It "should produce an error for a non-existing classname" { - try { - get-ciminstance -classname thisnameshouldnotexist -ea stop - throw "expected error did not occur" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "HRESULT 0x80041010,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstanceCommand" + { get-ciminstance -classname thisnameshouldnotexist -ea stop } | + Should -Throw -ErrorId "HRESULT 0x80041010,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstanceCommand" } } } diff --git a/test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 b/test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 index 203feaea9cb..b8af13164da 100644 --- a/test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 +++ b/test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 @@ -15,22 +15,12 @@ try { } It 'produces an error when a non-existent class is used' { - try { - Get-CimClass -ClassName thisclasstypedoesnotexist -ea stop - throw "Expected error did not occur" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "HRESULT 0x80041002,Microsoft.Management.Infrastructure.CimCmdlets.GetCimClassCommand" - } + { Get-CimClass -ClassName thisclasstypedoesnotexist -ea stop | + Should -Throw -ErrorId "HRESULT 0x80041002,Microsoft.Management.Infrastructure.CimCmdlets.GetCimClassCommand" } It 'produces an error when an improper namespace is used' { - try { - Get-CimClass -ClassName CIM_OperatingSystem -Namespace badnamespace -ea stop - throw "Expected error did not occur" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "HRESULT 0x8004100e,Microsoft.Management.Infrastructure.CimCmdlets.GetCimClassCommand" - } + { Get-CimClass -ClassName CIM_OperatingSystem -Namespace badnamespace -ea stop } | + Should -Throw -ErrorId "HRESULT 0x8004100e,Microsoft.Management.Infrastructure.CimCmdlets.GetCimClassCommand" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Diagnostics/New-WinEvent.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Diagnostics/New-WinEvent.Tests.ps1 index 4fe72908eee..96ec01605be 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Diagnostics/New-WinEvent.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Diagnostics/New-WinEvent.Tests.ps1 @@ -26,19 +26,19 @@ Describe 'New-WinEvent' -Tags "CI" { } It 'No provider found error' { - { New-WinEvent -ProviderName NonExistingProvider -Id 0 } | ShouldBeErrorId 'System.ArgumentException,Microsoft.PowerShell.Commands.NewWinEventCommand' + { New-WinEvent -ProviderName NonExistingProvider -Id 0 } | Should -Throw -ErrorId 'System.ArgumentException,Microsoft.PowerShell.Commands.NewWinEventCommand' } It 'EmptyProviderName error' { - { New-WinEvent -ProviderName $null -Id 0 } | ShouldBeErrorId 'ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.NewWinEventCommand' + { New-WinEvent -ProviderName $null -Id 0 } | Should -Throw -ErrorId 'ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.NewWinEventCommand' } It 'IncorrectEventId error' { - { New-WinEvent $ProviderName -Id 999999 } | ShouldBeErrorId 'Microsoft.PowerShell.Commands.EventWriteException,Microsoft.PowerShell.Commands.NewWinEventCommand' + { New-WinEvent $ProviderName -Id 999999 } | Should -Throw -ErrorId 'Microsoft.PowerShell.Commands.EventWriteException,Microsoft.PowerShell.Commands.NewWinEventCommand' } It 'IncorrectEventVersion error' { - { New-WinEvent -ProviderName $ProviderName -Id $SimpleEventId -Version 99 } | ShouldBeErrorId 'Microsoft.PowerShell.Commands.EventWriteException,Microsoft.PowerShell.Commands.NewWinEventCommand' + { New-WinEvent -ProviderName $ProviderName -Id $SimpleEventId -Version 99 } | Should -Throw -ErrorId 'Microsoft.PowerShell.Commands.EventWriteException,Microsoft.PowerShell.Commands.NewWinEventCommand' } It 'PayloadMismatch error' { From 46d83f1a2cc467265cc1743487348ffaf519aef8 Mon Sep 17 00:00:00 2001 From: algizklaudia <algizklaudia@gmail.com> Date: Tue, 17 Apr 2018 11:25:29 -0700 Subject: [PATCH 27/58] [Featur] ShouldBeErrorId => Should -Throw -ErrorId in Core module. --- .../Modules/Microsoft.PowerShell.Core/Import-Module.Tests.ps1 | 2 +- .../Modules/Microsoft.PowerShell.Core/Job.Tests.ps1 | 2 +- .../Microsoft.PowerShell.Core/RemoteGetModule.Tests.ps1 | 4 ++-- .../Microsoft.PowerShell.Core/RemoteImportModule.Tests.ps1 | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Core/Import-Module.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Core/Import-Module.Tests.ps1 index 04577e954f9..80139e8f624 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Core/Import-Module.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Core/Import-Module.Tests.ps1 @@ -111,7 +111,7 @@ Describe "Import-Module for Binary Modules in GAC" -Tags 'CI' { It "Load PSScheduledJob from Windows Powershell Modules folder should fail" -Skip:(-not $IsWindows) { $modulePath = Join-Path $env:windir "System32/WindowsPowershell/v1.0/Modules/PSScheduledJob" - { Import-Module $modulePath -ErrorAction SilentlyContinue } | ShouldBeErrorId 'FormatXmlUpdateException,Microsoft.PowerShell.Commands.ImportModuleCommand' + { Import-Module $modulePath -ErrorAction SilentlyContinue } | Should -Throw -ErrorId 'FormatXmlUpdateException,Microsoft.PowerShell.Commands.ImportModuleCommand' } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Core/Job.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Core/Job.Tests.ps1 index 8be26300e39..c997bb84cb0 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Core/Job.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Core/Job.Tests.ps1 @@ -26,7 +26,7 @@ Describe "Job Cmdlet Tests" -Tag "CI" { } It "Remove-Job can remove a job" { Remove-Job $j -Force - { Get-Job $j -ErrorAction Stop } | ShouldBeErrorId "JobWithSpecifiedNameNotFound,Microsoft.PowerShell.Commands.GetJobCommand" + { Get-Job $j -ErrorAction Stop } | Should -Throw -ErrorId "JobWithSpecifiedNameNotFound,Microsoft.PowerShell.Commands.GetJobCommand" } It "Receive-Job can retrieve job results" { Wait-Job -Timeout 60 -id $j.id | Should -Not -BeNullOrEmpty diff --git a/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteGetModule.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteGetModule.Tests.ps1 index 6e484e29566..985b20291e0 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteGetModule.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteGetModule.Tests.ps1 @@ -23,7 +23,7 @@ Describe "Remote module tests" -Tags 'Feature','RequireAdminOnWindows' { ) { param($parameter, $value) $parameters = @{$parameter=$value} - { Get-Module @parameters -ErrorAction Stop } | ShouldBeErrorId "RemoteDiscoveryWorksOnlyInListAvailableMode,Microsoft.PowerShell.Commands.GetModuleCommand" + { Get-Module @parameters -ErrorAction Stop } | Should -Throw -ErrorId "RemoteDiscoveryWorksOnlyInListAvailableMode,Microsoft.PowerShell.Commands.GetModuleCommand" } It "Get-Module succeeds using -ListAvailable with '<parameter>'" -TestCases @( @@ -73,7 +73,7 @@ Describe "Remote module tests" -Tags 'Feature','RequireAdminOnWindows' { } It "Failure if -Name and -FullyQualifiedName are both specified" { - { Get-Module -Name foo -FullyQualifiedName @{ModuleName='foo'} -ErrorAction Stop } | ShouldBeErrorId "CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.GetModuleCommand" + { Get-Module -Name foo -FullyQualifiedName @{ModuleName='foo'} -ErrorAction Stop } | Should -Throw -ErrorId "CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.GetModuleCommand" } It "Get-Module supports pipeline" { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteImportModule.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteImportModule.Tests.ps1 index f4b86ad1665..9e869cb8fba 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteImportModule.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Core/RemoteImportModule.Tests.ps1 @@ -98,7 +98,7 @@ Describe "Remote import-module tests" -Tags 'Feature','RequireAdminOnWindows' { Invoke-Command -Session $pssession -ScriptBlock { $env:PSModulePath += ";$(Split-Path $using:modulePath)"} Get-Module TestImport | Should -BeNullOrEmpty if ($errorid) { - { Import-Module @parameters -ErrorAction Stop } | ShouldBeErrorId $errorid + { Import-Module @parameters -ErrorAction Stop } | Should -Throw -ErrorId $errorid } else { Import-Module @parameters $module = Get-Module TestImport From ca2ab950123f09e41ce74f0da686c23f55ef36cd Mon Sep 17 00:00:00 2001 From: algizklaudia <algizklaudia@gmail.com> Date: Tue, 17 Apr 2018 11:29:54 -0700 Subject: [PATCH 28/58] [Feature] Should Be => Should -BeTrue in Host module. --- .../Microsoft.Powershell.Host/Start-Transcript.Tests.ps1 | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/powershell/Modules/Microsoft.Powershell.Host/Start-Transcript.Tests.ps1 b/test/powershell/Modules/Microsoft.Powershell.Host/Start-Transcript.Tests.ps1 index b004e647649..5b4b3ab233d 100644 --- a/test/powershell/Modules/Microsoft.Powershell.Host/Start-Transcript.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.Powershell.Host/Start-Transcript.Tests.ps1 @@ -26,14 +26,14 @@ Describe "Start-Transcript, Stop-Transcript tests" -tags "CI" { $ps.commands.clear() if($expectedError) { - $ps.hadErrors | Should be $true + $ps.hadErrors | Should -BeTrue $ps.Streams.Error.FullyQualifiedErrorId | Should be $expectedError } else { $ps.addscript("Get-Date").Invoke() $ps.commands.clear() $ps.addscript("Stop-Transcript").Invoke() - Test-Path $outputFilePath | Should be $true + Test-Path $outputFilePath | Should -BeTrue $outputFilePath | should FileContentMatch "Get-Date" if($append) { $outputFilePath | Should FileContentMatch $content @@ -131,7 +131,7 @@ Describe "Start-Transcript, Stop-Transcript tests" -tags "CI" { $powerShellCommand = $powerShellPath + ' -c "start-transcript $transcriptFilePath; Write-Host ''Before Dispose'';"' Invoke-Expression $powerShellCommand - Test-Path $transcriptFilePath | Should be $true + Test-Path $transcriptFilePath | Should -BeTrue $transcriptFilePath | Should FileContentMatch "Before Dispose" $transcriptFilePath | Should FileContentMatch "PowerShell transcript end" } @@ -142,7 +142,7 @@ Describe "Start-Transcript, Stop-Transcript tests" -tags "CI" { hostname Stop-Transcript } & $script - Test-Path $transcriptFilePath | Should be $true + Test-Path $transcriptFilePath | Should -BeTrue $machineName = [System.Environment]::MachineName $transcriptFilePath | Should FileContentMatch $machineName From f6d878f2a9dd4bbff03bfd3335a5629e14ea09e8 Mon Sep 17 00:00:00 2001 From: algizklaudia <algizklaudia@gmail.com> Date: Tue, 17 Apr 2018 11:40:56 -0700 Subject: [PATCH 29/58] [Feature] ShouldBeErrorId => Should -Throw -ErrorId in Security module. --- .../CertificateProvider.Tests.ps1 | 4 ++-- .../Microsoft.PowerShell.Security/CmsMessage.Tests.ps1 | 3 ++- .../Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 | 6 +++--- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/CertificateProvider.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/CertificateProvider.Tests.ps1 index 86b311caf63..bcb644d4370 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/CertificateProvider.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/CertificateProvider.Tests.ps1 @@ -62,10 +62,10 @@ Describe "Certificate Provider tests" -Tags "CI" { (get-item cert:\LocalMachine , cert:\CurrentUser).Count | Should -Be 2 } it "Should return PathNotFound when getting a non-existant certificate store" { - {Get-Item cert:\IDONTEXIST -ErrorAction Stop} | ShouldBeErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" + {Get-Item cert:\IDONTEXIST -ErrorAction Stop} | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } it "Should return PathNotFound when getting a non-existant certificate" { - {Get-Item cert:\currentuser\my\IDONTEXIST -ErrorAction Stop} | ShouldBeErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" + {Get-Item cert:\currentuser\my\IDONTEXIST -ErrorAction Stop} | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } } Context "Get-ChildItem tests"{ diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/CmsMessage.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/CmsMessage.Tests.ps1 index db0eb51ed64..f35c24d9ec7 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/CmsMessage.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/CmsMessage.Tests.ps1 @@ -37,7 +37,8 @@ Describe "CmsMessage cmdlets and Get-PfxCertificate basic tests" -Tags "CI" { It "Verify Get-PfxCertificate wrong password" { #[SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Test secret.")] $pass = ConvertTo-SecureString "wrongpass" -AsPlainText -Force - $e = { Get-PfxCertificate $protectedCertLocation -Password $pass -ErrorAction Stop } | ShouldBeErrorId "GetPfxCertificateUnknownCryptoError,Microsoft.PowerShell.Commands.GetPfxCertificateCommand" + { Get-PfxCertificate $protectedCertLocation -Password $pass -ErrorAction Stop } | + Should -Throw -ErrorId "GetPfxCertificateUnknownCryptoError,Microsoft.PowerShell.Commands.GetPfxCertificateCommand" } It "Verify CMS message recipient resolution by path" -Skip:(!$IsWindows) { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 index 853a7a10de6..f26f55a8a91 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 @@ -684,7 +684,7 @@ ZoneId=$FileType $testScript = {Import-Module -Name $module -Force} if($error) { - $testScript | ShouldBeErrorId $error + $testScript | Should -Throw -ErrorId $error } else { @@ -929,7 +929,7 @@ ZoneId=$FileType $testScript = {Import-Module -Name $module -Force} if($error) { - $testScript | ShouldBeErrorId $error + $testScript | Should -Throw -ErrorId $error } else { @@ -1028,7 +1028,7 @@ ZoneId=$FileType $testScript | Should -Exist if($error) { - {& $testScript} | ShouldBeErrorId $error + {& $testScript} | Should -Throw -ErrorId $error } else { From e05e4c7e67d04e2169a1b744fa3483459166db49 Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Tue, 17 Apr 2018 16:06:52 -0700 Subject: [PATCH 30/58] [Feature] ShouldBeErrorId => Should -Throw -ErrorId in Management module. --- .../FileSystem.Tests.ps1 | 20 +++++++++---------- .../FunctionProvider.Tests.ps1 | 16 +++++++-------- .../Get-Content.Tests.ps1 | 14 ++++++------- .../Get-Item.Tests.ps1 | 4 ++-- .../Get-Service.Tests.ps1 | 2 +- .../Registry.Tests.ps1 | 2 +- .../Rename-Computer.Tests.ps1 | 2 +- .../Restart-Computer.Tests.ps1 | 6 +++--- .../Set-Service.Tests.ps1 | 6 +++--- .../Start-Process.Tests.ps1 | 6 +++--- .../Test-Connection.Tests.ps1 | 18 ++++++++--------- 11 files changed, 48 insertions(+), 48 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 index 974c69568ec..757f614c643 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 @@ -79,7 +79,7 @@ Describe "Basic FileSystem Provider Tests" -Tags "CI" { } It "Verify Rename-Item will not rename to an existing name" { - { Rename-Item -Path $testFile -NewName $testDir -ErrorAction Stop } | ShouldBeErrorId "RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand" + { Rename-Item -Path $testFile -NewName $testDir -ErrorAction Stop } | Should -Throw -ErrorId "RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand" $Error[0].Exception | Should -BeOfType System.IO.IOException $testFile | Should -Exist } @@ -108,7 +108,7 @@ Describe "Basic FileSystem Provider Tests" -Tags "CI" { } It "Verify Move-Item will not move to an existing file" { - { Move-Item -Path $testDir -Destination $testFile -ErrorAction Stop } | ShouldBeErrorId "MoveDirectoryItemIOError,Microsoft.PowerShell.Commands.MoveItemCommand" + { Move-Item -Path $testDir -Destination $testFile -ErrorAction Stop } | Should -Throw -ErrorId "MoveDirectoryItemIOError,Microsoft.PowerShell.Commands.MoveItemCommand" $Error[0].Exception | Should -BeOfType System.IO.IOException $testDir | Should -Exist } @@ -157,21 +157,21 @@ Describe "Basic FileSystem Provider Tests" -Tags "CI" { It "Copy-Item on Windows rejects Windows reserved device names" -Skip:(-not $IsWindows) { foreach ($deviceName in $reservedNames) { - { Copy-Item -Path $testFile -Destination $deviceName -ErrorAction Stop } | ShouldBeErrorId "CopyError,Microsoft.PowerShell.Commands.CopyItemCommand" + { Copy-Item -Path $testFile -Destination $deviceName -ErrorAction Stop } | Should -Throw -ErrorId "CopyError,Microsoft.PowerShell.Commands.CopyItemCommand" } } It "Move-Item on Windows rejects Windows reserved device names" -Skip:(-not $IsWindows) { foreach ($deviceName in $reservedNames) { - { Move-Item -Path $testFile -Destination $deviceName -ErrorAction Stop } | ShouldBeErrorId "MoveError,Microsoft.PowerShell.Commands.MoveItemCommand" + { Move-Item -Path $testFile -Destination $deviceName -ErrorAction Stop } | Should -Throw -ErrorId "MoveError,Microsoft.PowerShell.Commands.MoveItemCommand" } } It "Rename-Item on Windows rejects Windows reserved device names" -Skip:(-not $IsWindows) { foreach ($deviceName in $reservedNames) { - { Rename-Item -Path $testFile -NewName $deviceName -ErrorAction Stop } | ShouldBeErrorId "RenameError,Microsoft.PowerShell.Commands.RenameItemCommand" + { Rename-Item -Path $testFile -NewName $deviceName -ErrorAction Stop } | Should -Throw -ErrorId "RenameError,Microsoft.PowerShell.Commands.RenameItemCommand" } } @@ -399,7 +399,7 @@ Describe "Handling of globbing patterns" -Tags "CI" { Context "Handle asterisks in name" { It "Remove-Item -LiteralPath should fail if it contains asterisk and file doesn't exist" { - { Remove-Item -LiteralPath ./foo*.txt -ErrorAction Stop } | ShouldBeErrorId "PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand" + { Remove-Item -LiteralPath ./foo*.txt -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand" } It "Remove-Item -LiteralPath should succeed for file with asterisk in name" -Skip:($IsWindows) { @@ -473,7 +473,7 @@ Describe "Hard link and symbolic link tests" -Tags "CI", "RequireAdminOnWindows" $link.Target | Should -Be $nonFile } It "New-Item emits an error when path to symbolic link already exists." { - { New-Item -ItemType SymbolicLink -Path $realDir -Value $symLinkToDir -ErrorAction Stop } | ShouldBeErrorId "SymLinkExists,Microsoft.PowerShell.Commands.NewItemCommand" + { New-Item -ItemType SymbolicLink -Path $realDir -Value $symLinkToDir -ErrorAction Stop } | Should -Throw -ErrorId "SymLinkExists,Microsoft.PowerShell.Commands.NewItemCommand" } It "New-Item can create a symbolic link to a directory" -Skip:($IsWindows) { New-Item -ItemType SymbolicLink -Path $symLinkToDir -Value $realDir @@ -720,7 +720,7 @@ Describe "Copy-Item can avoid copying an item onto itself" -Tags "CI", "RequireA } else { - { Copy-Item -Path $sourcePath -Destination $destinationPath -ErrorAction Stop } | ShouldBeErrorId "CopyError,Microsoft.PowerShell.Commands.CopyItemCommand" + { Copy-Item -Path $sourcePath -Destination $destinationPath -ErrorAction Stop } | Should -Throw -ErrorId "CopyError,Microsoft.PowerShell.Commands.CopyItemCommand" $Error[0].Exception | Should -BeOfType System.IO.IOException $Error[0].Exception.Data[$selfCopyKey] | Should -Not -BeNullOrEmpty } @@ -783,7 +783,7 @@ Describe "Copy-Item can avoid copying an item onto itself" -Tags "CI", "RequireA [string]$Destination ) - { Copy-Item -Path $Source -Destination $Destination -ErrorAction Stop } | ShouldBeErrorId "CopyError,Microsoft.PowerShell.Commands.CopyItemCommand" + { Copy-Item -Path $Source -Destination $Destination -ErrorAction Stop } | Should -Throw -ErrorId "CopyError,Microsoft.PowerShell.Commands.CopyItemCommand" $Error[0].Exception | Should -BeOfType System.IO.IOException $Error[0].Exception.Data[$selfCopyKey] | Should -Not -BeNullOrEmpty } @@ -939,7 +939,7 @@ Describe "Extended FileSystem Item/Content Cmdlet Provider Tests" -Tags "Feature } It "Verify -LiteralPath with wildcard fails for file that doesn't exist" { - { Get-Item -LiteralPath "a*b.txt" -ErrorAction Stop } | ShouldBeErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" + { Get-Item -LiteralPath "a*b.txt" -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } It "Verify -LiteralPath with wildcard succeeds for file" -Skip:($IsWindows) { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/FunctionProvider.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/FunctionProvider.Tests.ps1 index f287c404cf6..b21a8977b7d 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/FunctionProvider.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/FunctionProvider.Tests.ps1 @@ -58,7 +58,7 @@ Describe "Basic Function Provider Tests" -Tags "CI" { } It "Throws PSArgumentException when Set-Item is called with incorrect function value" { - { Set-Item $nonExistingFunction -Value 123 -ErrorAction Stop } | ShouldBeErrorId "Argument,Microsoft.PowerShell.Commands.SetItemCommand" + { Set-Item $nonExistingFunction -Value 123 -ErrorAction Stop } | Should -Throw -ErrorId "Argument,Microsoft.PowerShell.Commands.SetItemCommand" } } @@ -88,39 +88,39 @@ Describe "Basic Function Provider Tests" -Tags "CI" { Context "Validate Remove-Item Cmdlet" { It "Removes function" { Remove-Item $existingFunction - { Get-Item $existingFunction -ErrorAction Stop } | ShouldBeErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" + { Get-Item $existingFunction -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } It "Fails to remove not existing function" { - { Remove-Item $nonExistingFunction -ErrorAction Stop } | ShouldBeErrorId "PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand" + { Remove-Item $nonExistingFunction -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand" } } Context "Validate Rename-Item Cmdlet" { It "Renames existing function with None options" { Rename-Item $existingFunction -NewName $newName - { Get-Item $existingFunction -ErrorAction Stop } | ShouldBeErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" + { Get-Item $existingFunction -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" (Get-Item $newName).Count | Should -BeExactly 1 } It "Fails to rename not existing function" { - { Rename-Item $nonExistingFunction -NewName $newName -ErrorAction Stop } | ShouldBeErrorId "InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand" + { Rename-Item $nonExistingFunction -NewName $newName -ErrorAction Stop } | Should -Throw -ErrorId "InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand" } It "Fails to rename function which is Constant" { Set-Item $nonExistingFunction -Options "Constant" -Value $functionValue - { Rename-Item $nonExistingFunction -NewName $newName -ErrorAction Stop } | ShouldBeErrorId "CannotRenameFunction,Microsoft.PowerShell.Commands.RenameItemCommand" + { Rename-Item $nonExistingFunction -NewName $newName -ErrorAction Stop } | Should -Throw -ErrorId "CannotRenameFunction,Microsoft.PowerShell.Commands.RenameItemCommand" } It "Fails to rename function which is ReadOnly" { Set-Item $nonExistingFunction -Options "ReadOnly" - { Rename-Item $nonExistingFunction -NewName $newName -ErrorAction Stop } | ShouldBeErrorId "InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand" + { Rename-Item $nonExistingFunction -NewName $newName -ErrorAction Stop } | Should -Throw -ErrorId "InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand" } It "Renames ReadOnly function when -Force parameter is on" { Set-Item $nonExistingFunction -Options "ReadOnly" -Value $functionValue Rename-Item $nonExistingFunction -NewName $newName -Force - { Get-Item $nonExistingFunction -ErrorAction Stop } | ShouldBeErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" + { Get-Item $nonExistingFunction -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" (Get-Item $newName).Count | Should -BeExactly 1 } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 index 9ba435313ca..68e69060837 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 @@ -91,11 +91,11 @@ Describe "Get-Content" -Tags "CI" { } It 'Verifies -Tail reports a TailNotSupported error for unsupported providers' { - {Get-Content -Path Variable:\PSHOME -Tail 1 -ErrorAction Stop} | ShouldBeErrorId 'TailNotSupported,Microsoft.PowerShell.Commands.GetContentCommand' + {Get-Content -Path Variable:\PSHOME -Tail 1 -ErrorAction Stop} | Should -Throw -ErrorId 'TailNotSupported,Microsoft.PowerShell.Commands.GetContentCommand' } It 'Verifies using -Tail and -TotalCount together reports a TailAndHeadCannotCoexist error' { - { Get-Content -Path Variable:\PSHOME -Tail 1 -TotalCount 5 -ErrorAction Stop} | ShouldBeErrorId 'TailAndHeadCannotCoexist,Microsoft.PowerShell.Commands.GetContentCommand' + { Get-Content -Path Variable:\PSHOME -Tail 1 -TotalCount 5 -ErrorAction Stop} | Should -Throw -ErrorId 'TailAndHeadCannotCoexist,Microsoft.PowerShell.Commands.GetContentCommand' } It 'Verifies -Tail with content that uses an explicit encoding' -TestCases @( @@ -219,7 +219,7 @@ baz It "Should support NTFS streams using colon syntax" -Skip:(!$IsWindows) { Set-Content "${testPath}:Stream" -Value "Foo" - { Test-Path "${testPath}:Stream" | ShouldBeErrorId "ItemExistsNotSupportedError,Microsoft.PowerShell.Commands,TestPathCommand" } + { Test-Path "${testPath}:Stream" | Should -Throw -ErrorId "ItemExistsNotSupportedError,Microsoft.PowerShell.Commands,TestPathCommand" } Get-Content "${testPath}:Stream" | Should -BeExactly "Foo" Get-Content $testPath | Should -BeExactly $testString } @@ -234,7 +234,7 @@ baz Clear-Content -Path $testPath -Stream hello Get-Content -Path $testPath -Stream hello | Should -BeNullOrEmpty Remove-Item -Path $testPath -Stream hello - { Get-Content -Path $testPath -Stream hello | ShouldBeErrorId "GetContentReaderFileNotFoundError,Microsoft.PowerShell.Commands.GetContentCommand" } + { Get-Content -Path $testPath -Stream hello | Should -Throw -ErrorId "GetContentReaderFileNotFoundError,Microsoft.PowerShell.Commands.GetContentCommand" } } It "Should support colons in filename on Linux/Mac" -Skip:($IsWindows) { @@ -266,21 +266,21 @@ baz It "Should throw TailAndHeadCannotCoexist when both -Tail and -TotalCount are used" { { Get-Content -Path $testPath -Tail 1 -TotalCount 1 -ErrorAction Stop - } | ShouldBeErrorId "TailAndHeadCannotCoexist,Microsoft.PowerShell.Commands.GetContentCommand" + } | Should -Throw -ErrorId "TailAndHeadCannotCoexist,Microsoft.PowerShell.Commands.GetContentCommand" } It "Should throw TailNotSupported when -Tail used with an unsupported provider" { Push-Location env: { Get-Content PATH -Tail 1 -ErrorAction Stop - } | ShouldBeErrorId "TailNotSupported,Microsoft.PowerShell.Commands.GetContentCommand" + } | Should -Throw -ErrorId "TailNotSupported,Microsoft.PowerShell.Commands.GetContentCommand" Pop-Location } It "Should throw InvalidOperation when -Tail and -Raw are used" { { Get-Content -Path $testPath -Tail 1 -ErrorAction Stop -Raw - } | ShouldBeErrorId "InvalidOperation,Microsoft.PowerShell.Commands.GetContentCommand" + } | Should -Throw -ErrorId "InvalidOperation,Microsoft.PowerShell.Commands.GetContentCommand" } Context "Check Get-Content containing multi-byte chars" { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Item.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Item.Tests.ps1 index c66ba603afb..d1e37919d82 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Item.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Item.Tests.ps1 @@ -83,11 +83,11 @@ Describe "Get-Item" -Tags "CI" { Context "Error Condition Checking" { It "Should return an error if the provider does not exist" { - { Get-Item BadProvider::/BadFile -ErrorAction Stop } | ShouldBeErrorId "ProviderNotFound,Microsoft.PowerShell.Commands.GetItemCommand" + { Get-Item BadProvider::/BadFile -ErrorAction Stop } | Should -Throw -ErrorId "ProviderNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } It "Should return an error if the drive does not exist" { - { Get-Item BadDrive:/BadFile -ErrorAction Stop } | ShouldBeErrorId "DriveNotFound,Microsoft.PowerShell.Commands.GetItemCommand" + { Get-Item BadDrive:/BadFile -ErrorAction Stop } | Should -Throw -ErrorId "DriveNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Service.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Service.Tests.ps1 index 11cdf70e23b..75c7977c9d1 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Service.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Service.Tests.ps1 @@ -89,6 +89,6 @@ Describe "Get-Service cmdlet tests" -Tags "CI" { ErrorId = "NoServiceFoundForGivenDisplayName,Microsoft.PowerShell.Commands.GetServiceCommand" } ) { param($script,$errorid) - { & $script } | ShouldBeErrorId $errorid + { & $script } | Should -Throw -ErrorId $errorid } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Registry.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Registry.Tests.ps1 index 27798c83928..1e3a141a1bf 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Registry.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Registry.Tests.ps1 @@ -60,7 +60,7 @@ Describe "Basic Registry Provider Tests" -Tags @("CI", "RequireAdminOnWindows") } It "Verify Get-Item on inaccessible path" { - { Get-Item HKLM:\SAM\SAM -ErrorAction Stop } | ShouldBeErrorId "System.Security.SecurityException,Microsoft.PowerShell.Commands.GetItemCommand" + { Get-Item HKLM:\SAM\SAM -ErrorAction Stop } | Should -Throw -ErrorId "System.Security.SecurityException,Microsoft.PowerShell.Commands.GetItemCommand" } It "Verify Get-ChildItem" { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Rename-Computer.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Rename-Computer.Tests.ps1 index 64a30df86be..8cb63a0583a 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Rename-Computer.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Rename-Computer.Tests.ps1 @@ -65,7 +65,7 @@ try It "Renaming '<OldName>' to '<NewName>' creates the right error" -testcase $testcases { param ( $OldName, $NewName, $ExpectedError ) Set-TesthookResult -testhookName $RenameResultName -value 0x1 - { Rename-Computer -ComputerName $OldName -NewName $NewName -ErrorAction Stop } | ShouldBeErrorId $ExpectedError + { Rename-Computer -ComputerName $OldName -NewName $NewName -ErrorAction Stop } | Should -Throw -ErrorId $ExpectedError } } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Restart-Computer.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Restart-Computer.Tests.ps1 index 8c6c07c78dc..feb4c07e096 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Restart-Computer.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Restart-Computer.Tests.ps1 @@ -78,17 +78,17 @@ try } It "Should produce an error when 'Delay' is specified" { - { Restart-Computer -Delay 30 } | ShouldBeErrorId "RestartComputerInvalidParameter,Microsoft.PowerShell.Commands.RestartComputerCommand" + { Restart-Computer -Delay 30 } | Should -Throw -ErrorId "RestartComputerInvalidParameter,Microsoft.PowerShell.Commands.RestartComputerCommand" } It "Should not support timeout on localhost" { Set-TesthookResult -testhookName $restartTesthookResultName -value $defaultResultValue - { Restart-Computer -timeout 3 -ErrorAction Stop } | ShouldBeErrorId "RestartComputerInvalidParameter,Microsoft.PowerShell.Commands.RestartComputerCommand" + { Restart-Computer -timeout 3 -ErrorAction Stop } | Should -Throw -ErrorId "RestartComputerInvalidParameter,Microsoft.PowerShell.Commands.RestartComputerCommand" } It "Should not support timeout on localhost" { Set-TesthookResult -testhookName $restartTesthookResultName -value $defaultResultValue - { Restart-Computer -timeout 3 -ErrorAction Stop } | ShouldBeErrorId "RestartComputerInvalidParameter,Microsoft.PowerShell.Commands.RestartComputerCommand" + { Restart-Computer -timeout 3 -ErrorAction Stop } | Should -Throw -ErrorId "RestartComputerInvalidParameter,Microsoft.PowerShell.Commands.RestartComputerCommand" } } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Set-Service.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Set-Service.Tests.ps1 index 11ef0cb03e7..c2920d61235 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Set-Service.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Set-Service.Tests.ps1 @@ -59,7 +59,7 @@ Describe "Set/New/Remove-Service cmdlet tests" -Tags "Feature", "RequireAdminOnW } ) { param($script, $errorid) - { & $script } | ShouldBeErrorId $errorid + { & $script } | Should -Throw -ErrorId $errorid } It "Set-Service can change '<parameter>' to '<value>'" -TestCases @( @@ -240,7 +240,7 @@ Describe "Set/New/Remove-Service cmdlet tests" -Tags "Feature", "RequireAdminOnW } It "Remove-Service cannot accept a service that does not exist" { - { Remove-Service -Name "testremoveservice" -ErrorAction 'Stop' } | ShouldBeErrorId "InvalidOperationException,Microsoft.PowerShell.Commands.RemoveServiceCommand" + { Remove-Service -Name "testremoveservice" -ErrorAction 'Stop' } | Should -Throw -ErrorId "InvalidOperationException,Microsoft.PowerShell.Commands.RemoveServiceCommand" } It "Get-Service can get the '<property>' of a service" -TestCases @( @@ -327,6 +327,6 @@ Describe "Set/New/Remove-Service cmdlet tests" -Tags "Feature", "RequireAdminOnW if ($cmdlet -eq "New-Service") { $parameters += @{Binary = "$PSHOME\pwsh.exe"}; } - { & $cmdlet @parameters } | ShouldBeErrorId $errorid + { & $cmdlet @parameters } | Should -Throw -ErrorId $errorid } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Start-Process.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Start-Process.Tests.ps1 index afaf014e9dd..4f968679851 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Start-Process.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Start-Process.Tests.ps1 @@ -88,16 +88,16 @@ Describe "Start-Process" -Tags @("Feature") { ## -Verb is supported in PowerShell core on Windows full desktop. It "Should give an error when -Verb parameter is used" -Skip:$isFullWin { - { Start-Process -Verb runas -FilePath $pingCommand } | ShouldBeErrorId "NotSupportedException,Microsoft.PowerShell.Commands.StartProcessCommand" + { Start-Process -Verb runas -FilePath $pingCommand } | Should -Throw -ErrorId "NotSupportedException,Microsoft.PowerShell.Commands.StartProcessCommand" } ## -WindowStyle is supported in PowerShell core on Windows full desktop. It "Should give an error when -WindowStyle parameter is used" -Skip:$isFullWin { - { Start-Process -FilePath $pingCommand -WindowStyle Normal } | ShouldBeErrorId "NotSupportedException,Microsoft.PowerShell.Commands.StartProcessCommand" + { Start-Process -FilePath $pingCommand -WindowStyle Normal } | Should -Throw -ErrorId "NotSupportedException,Microsoft.PowerShell.Commands.StartProcessCommand" } It "Should give an error when both -NoNewWindow and -WindowStyle are specified" -Skip:(!$isFullWin) { - { Start-Process -FilePath $pingCommand -NoNewWindow -WindowStyle Normal -ErrorAction Stop } | ShouldBeErrorId "InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand" + { Start-Process -FilePath $pingCommand -NoNewWindow -WindowStyle Normal -ErrorAction Stop } | Should -Throw -ErrorId "InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand" } It "Should start cmd.exe with Verb 'open' and WindowStyle 'Minimized'" -Skip:(!$isFullWin) { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Test-Connection.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Test-Connection.Tests.ps1 index 1e049a2b77d..075958f98f8 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Test-Connection.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Test-Connection.Tests.ps1 @@ -69,7 +69,7 @@ Describe "Test-Connection" -tags "CI" { It "Ping fake host" { - { $result = Test-Connection "fakeHost" -Count 1 -Quiet -ErrorAction Stop } | ShouldBeErrorId "TestConnectionException,Microsoft.PowerShell.Commands.TestConnectionCommand" + { $result = Test-Connection "fakeHost" -Count 1 -Quiet -ErrorAction Stop } | Should -Throw -ErrorId "TestConnectionException,Microsoft.PowerShell.Commands.TestConnectionCommand" # Error code = 11001 - Host not found. if (!$isWindows) { $Error[0].Exception.InnerException.ErrorCode | Should -Be 6 @@ -118,18 +118,18 @@ Describe "Test-Connection" -tags "CI" { } It "MaxHops Should -Be greater 0" { - { Test-Connection $targetName -MaxHops 0 } | ShouldBeErrorId "System.ArgumentOutOfRangeException,Microsoft.PowerShell.Commands.TestConnectionCommand" - { Test-Connection $targetName -MaxHops -1 } | ShouldBeErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" + { Test-Connection $targetName -MaxHops 0 } | Should -Throw -ErrorId "System.ArgumentOutOfRangeException,Microsoft.PowerShell.Commands.TestConnectionCommand" + { Test-Connection $targetName -MaxHops -1 } | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" } It "Count Should -Be greater 0" { - { Test-Connection $targetName -Count 0 } | ShouldBeErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" - { Test-Connection $targetName -Count -1 } | ShouldBeErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" + { Test-Connection $targetName -Count 0 } | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" + { Test-Connection $targetName -Count -1 } | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" } It "Delay Should -Be greater 0" { - { Test-Connection $targetName -Delay 0 } | ShouldBeErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" - { Test-Connection $targetName -Delay -1 } | ShouldBeErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" + { Test-Connection $targetName -Delay 0 } | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" + { Test-Connection $targetName -Delay -1 } | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" } It "Delay works" { @@ -143,8 +143,8 @@ Describe "Test-Connection" -tags "CI" { It "BufferSize Should -Be between 0 and 65500" { { Test-Connection $targetName -BufferSize 0 } | Should Not Throw - { Test-Connection $targetName -BufferSize -1 } | ShouldBeErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" - { Test-Connection $targetName -BufferSize 65501 } | ShouldBeErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" + { Test-Connection $targetName -BufferSize -1 } | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" + { Test-Connection $targetName -BufferSize 65501 } | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand" } It "BufferSize works" { From cde70ddf8b35d4213e6e91b5a632b520e86ea136 Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Tue, 17 Apr 2018 17:36:01 -0700 Subject: [PATCH 31/58] [Feature] ShouldBeErrorId => Should -Throw -ErrorId in Utility module. --- .../Clear-Variable.Tests.ps1 | 4 +- .../ConvertTo-Csv.Tests.ps1 | 2 +- .../Export-Csv.Tests.ps1 | 4 +- .../Get-Date.Tests.ps1 | 2 +- .../JsonObject.Tests.ps1 | 2 +- .../New-Object.Tests.ps1 | 6 +- .../Out-String.Tests.ps1 | 2 +- .../Remove-Alias.Tests.ps1 | 18 +++--- .../Set-Date.Tests.ps1 | 2 +- .../Test-Json.Tests.ps1 | 2 +- .../Unblock-File.Tests.ps1 | 6 +- .../Update-FormatData.Tests.ps1 | 2 +- .../WebCmdlets.Tests.ps1 | 59 +++++++++---------- .../Write-Error.Tests.ps1 | 15 +---- 14 files changed, 54 insertions(+), 72 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 index 3099e88b6ea..50ff168743e 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 @@ -14,7 +14,7 @@ Describe "Clear-Variable DRT Unit Tests" -Tags "CI" { It "Clear-Variable ReadOnly variable Name should throw exception and force Clear-Variable should works"{ Set-Variable foo bar -Option ReadOnly - $e = { Clear-Variable -Name foo -Scope 1 -EA Stop } | ShouldBeErrorId "VariableNotWritable,Microsoft.PowerShell.Commands.ClearVariableCommand" + $e = { Clear-Variable -Name foo -Scope 1 -EA Stop } | Should -Throw -ErrorId "VariableNotWritable,Microsoft.PowerShell.Commands.ClearVariableCommand" $e.CategoryInfo | Should -Match "SessionStateUnauthorizedAccessException" Clear-Variable -Name foo -Force @@ -50,7 +50,7 @@ Describe "Clear-Variable DRT Unit Tests" -Tags "CI" { Set-Variable foo bar -Option Private &{ $e = { Get-Variable -Name foo -Scope local -EA Stop } | - ShouldBeErrorId "VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand" + Should -Throw -ErrorId "VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand" $e.CategoryInfo | Should -Match "ItemNotFoundException" } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Csv.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Csv.Tests.ps1 index c98d082a10d..f5f8c18ee6e 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Csv.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/ConvertTo-Csv.Tests.ps1 @@ -91,7 +91,7 @@ Describe "ConvertTo-Csv" -Tags "CI" { It "Does not support -IncludeTypeInformation and -NoTypeInformation at the same time" { { $testObject | ConvertTo-Csv -IncludeTypeInformation -NoTypeInformation } | - ShouldBeErrorId "CannotSpecifyIncludeTypeInformationAndNoTypeInformation,Microsoft.PowerShell.Commands.ConvertToCsvCommand" + Should -Throw -ErrorId "CannotSpecifyIncludeTypeInformationAndNoTypeInformation,Microsoft.PowerShell.Commands.ConvertToCsvCommand" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Csv.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Csv.Tests.ps1 index 6dc8c328dfc..616010e29f3 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Csv.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Csv.Tests.ps1 @@ -15,7 +15,7 @@ Describe "Export-Csv" -Tags "CI" { } It "Should throw if an output file isn't specified" { - { $testObject | Export-Csv -ErrorAction Stop } | ShouldBeErrorId "CannotSpecifyPathAndLiteralPath,Microsoft.PowerShell.Commands.ExportCsvCommand" + { $testObject | Export-Csv -ErrorAction Stop } | Should -Throw -ErrorId "CannotSpecifyPathAndLiteralPath,Microsoft.PowerShell.Commands.ExportCsvCommand" } It "Should be a string when exporting via pipe" { @@ -69,7 +69,7 @@ Describe "Export-Csv" -Tags "CI" { It "Does not support -IncludeTypeInformation and -NoTypeInformation at the same time" { { $testObject | Export-Csv -Path $testCsv -IncludeTypeInformation -NoTypeInformation } | - ShouldBeErrorId "CannotSpecifyIncludeTypeInformationAndNoTypeInformation,Microsoft.PowerShell.Commands.ExportCsvCommand" + Should -Throw -ErrorId "CannotSpecifyIncludeTypeInformationAndNoTypeInformation,Microsoft.PowerShell.Commands.ExportCsvCommand" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Date.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Date.Tests.ps1 index 935b26e2b74..9b53b0572db 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Date.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Date.Tests.ps1 @@ -77,7 +77,7 @@ Describe "Get-Date DRT Unit Tests" -Tags "CI" { @{ name = "empty string"; value = "" } ) { param($value) - { Get-date -Date 1/1/1970 -uformat $value -ErrorAction Stop } | ShouldBeErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetDateCommand" + { Get-date -Date 1/1/1970 -uformat $value -ErrorAction Stop } | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetDateCommand" } It "Get-date works with pipeline input" { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/JsonObject.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/JsonObject.Tests.ps1 index 7c6e0a7d64f..a23d404bb1b 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/JsonObject.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/JsonObject.Tests.ps1 @@ -31,7 +31,7 @@ Describe 'Unit tests for JsonObject' -tags "CI" { ) { param ($str, $ReturnHashTable) $errRecord = $null - { [Microsoft.PowerShell.Commands.JsonObject]::ConvertFromJson($str, $ReturnHashTable, [ref]$errRecord) } | ShouldBeErrorId "ArgumentException" + { [Microsoft.PowerShell.Commands.JsonObject]::ConvertFromJson($str, $ReturnHashTable, [ref]$errRecord) } | Should -Throw -ErrorId "ArgumentException" } Context 'Empty key name' { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/New-Object.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/New-Object.Tests.ps1 index 2a20fae24af..2046ab829ca 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/New-Object.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/New-Object.Tests.ps1 @@ -3,7 +3,7 @@ Describe "New-Object" -Tags "CI" { It "Support 'ComObject' parameter on platforms" { if ($IsLinux -or $IsMacOs ) { - { New-Object -ComObject "Shell.Application" } | ShouldBeErrorId "NamedParameterNotFound,Microsoft.PowerShell.Commands.NewObjectCommand" + { New-Object -ComObject "Shell.Application" } | Should -Throw -ErrorId "NamedParameterNotFound,Microsoft.PowerShell.Commands.NewObjectCommand" } else { # It works on NanoServer and IoT too (Get-Command "New-Object").Parameters.ContainsKey("ComObject") | Should -BeTrue @@ -116,7 +116,7 @@ Describe "New-Object DRT basic functionality" -Tags "CI" { { Add-Type -TypeDefinition "public class Employee{public Employee(string firstName,string lastName,int yearsInMS){FirstName = firstName;LastName=lastName;YearsInMS = yearsInMS;}public string FirstName;public string LastName;public int YearsInMS;}" } - { New-Object -TypeName Employee -EA Stop } | ShouldBeErrorId "CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand" + { New-Object -TypeName Employee -EA Stop } | Should -Throw -ErrorId "CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand" } It "New-Object with Private Nested class should throw Exception"{ @@ -158,7 +158,7 @@ try } It "Should fail with correct error when creating a COM object that dose not exist" { - {New-Object -ComObject 'doesnotexist'} | ShouldBeErrorId 'NoCOMClassIdentified,Microsoft.PowerShell.Commands.NewObjectCommand' + {New-Object -ComObject 'doesnotexist'} | Should -Throw -ErrorId 'NoCOMClassIdentified,Microsoft.PowerShell.Commands.NewObjectCommand' } } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Out-String.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Out-String.Tests.ps1 index 165ee0f0d52..fb85450c6ca 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Out-String.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Out-String.Tests.ps1 @@ -60,6 +60,6 @@ Describe "Out-String" -Tags "CI" { It "Should throw error when NoNewLine and Stream are used together" { $testArray = "a", "b" - { $testArray | Out-String -NoNewLine -Stream } | ShouldBeErrorId "AmbiguousParameterSet,Microsoft.PowerShell.Commands.OutStringCommand" + { $testArray | Out-String -NoNewLine -Stream } | Should -Throw -ErrorId "AmbiguousParameterSet,Microsoft.PowerShell.Commands.OutStringCommand" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Remove-Alias.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Remove-Alias.Tests.ps1 index 5c3b8683a06..80b12ce3e91 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Remove-Alias.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Remove-Alias.Tests.ps1 @@ -11,14 +11,14 @@ Describe "Remove-Alias" -Tags "CI" { Set-Alias -Name $testAliasName -Value "Remove-Alias" -ErrorAction Stop Remove-Alias -Name $testAliasName -ErrorAction Stop Get-Alias -Name $testAliasName -ErrorAction Stop - } | ShouldBeErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.GetAliasCommand' + } | Should -Throw -ErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.GetAliasCommand' } It "Remove-Alias should throw on a readonly alias"{ { Set-Alias -Name $testAliasName -Value "Remove-Alias" -Option ReadOnly -ErrorAction Stop Remove-Alias -Name $testAliasName -ErrorAction Stop - } | ShouldBeErrorId 'AliasNotRemovable,Microsoft.PowerShell.Commands.RemoveAliasCommand' + } | Should -Throw -ErrorId 'AliasNotRemovable,Microsoft.PowerShell.Commands.RemoveAliasCommand' } It "Remove-Alias should remove a non-readonly alias with force"{ @@ -26,7 +26,7 @@ Describe "Remove-Alias" -Tags "CI" { Set-Alias -Name $testAliasName -Value "Remove-Alias" -ErrorAction Stop Remove-Alias -Name $testAliasName -Force -ErrorAction Stop Get-Alias -Name $testAliasName -ErrorAction Stop - } | ShouldBeErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.GetAliasCommand' + } | Should -Throw -ErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.GetAliasCommand' } It "Remove-Alias should remove a readonly alias with force"{ @@ -34,14 +34,14 @@ Describe "Remove-Alias" -Tags "CI" { Set-Alias -Name $testAliasName -Value "Remove-Alias" -Option ReadOnly -ErrorAction Stop Remove-Alias -Name $testAliasName -Force -ErrorAction Stop Get-Alias -Name $testAliasName -ErrorAction Stop - } | ShouldBeErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.GetAliasCommand' + } | Should -Throw -ErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.GetAliasCommand' } It "Remove-Alias should throw if alias does not exist"{ { Get-Alias -Name $testAliasName -ErrorAction SilentlyContinue | Should -BeNullorEmpty Remove-Alias -Name $testAliasName -ErrorAction Stop - } | ShouldBeErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.RemoveAliasCommand' + } | Should -Throw -ErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.RemoveAliasCommand' } It "Remove-Alias should remove multiple alias at once"{ @@ -50,9 +50,9 @@ Describe "Remove-Alias" -Tags "CI" { Set-Alias -Name "$testAliasName-2" -Value "Remove-Alias" -ErrorAction Stop Set-Alias -Name "$testAliasName-3" -Value "Remove-Alias" -ErrorAction Stop Remove-Alias -Name "$testAliasName","$testAliasName-2","$testAliasName-3" -ErrorAction Stop - Get-Alias -Name "$testAliasName" -ErrorAction Stop | ShouldBeErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.GetAliasCommand' - Get-Alias -Name "$testAliasName-2" -ErrorAction Stop | ShouldBeErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.GetAliasCommand' - Get-Alias -Name "$testAliasName-3" -ErrorAction Stop | ShouldBeErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.GetAliasCommand' + Get-Alias -Name "$testAliasName" -ErrorAction Stop | Should -Throw -ErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.GetAliasCommand' + Get-Alias -Name "$testAliasName-2" -ErrorAction Stop | Should -Throw -ErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.GetAliasCommand' + Get-Alias -Name "$testAliasName-3" -ErrorAction Stop | Should -Throw -ErrorId 'ItemNotFoundException,Microsoft.PowerShell.Commands.GetAliasCommand' } } @@ -60,6 +60,6 @@ Describe "Remove-Alias" -Tags "CI" { { Set-Alias -Name $testAliasName -Value "Remove-Alias" -ErrorAction Stop Remove-Alias -Name $testAliasName -Scope 99999 -ErrorAction Stop - } | ShouldBeErrorId "ArgumentOutOfRange,Microsoft.PowerShell.Commands.RemoveAliasCommand" + } | Should -Throw -ErrorId "ArgumentOutOfRange,Microsoft.PowerShell.Commands.RemoveAliasCommand" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Set-Date.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Set-Date.Tests.ps1 index 2e2234d2336..ffd5ea9ffb2 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Set-Date.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Set-Date.Tests.ps1 @@ -14,6 +14,6 @@ Describe "Set-Date for admin" -Tag @('CI', 'RequireAdminOnWindows', 'RequireSudo Describe "Set-Date" -Tag 'CI' { It "Set-Date should produce an error in a non-elevated context" { - { Get-Date | Set-Date } | ShouldBeErrorId "System.ComponentModel.Win32Exception,Microsoft.PowerShell.Commands.SetDateCommand" + { Get-Date | Set-Date } | Should -Throw -ErrorId "System.ComponentModel.Win32Exception,Microsoft.PowerShell.Commands.SetDateCommand" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Test-Json.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Test-Json.Tests.ps1 index e7bc5c6106a..d659c382dce 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Test-Json.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Test-Json.Tests.ps1 @@ -79,7 +79,7 @@ Describe "Test-Json" -Tags "CI" { } It "Test-Json throw if a schema is invalid" { - { Test-Json -Json $validJson -Schema $invalidSchemaJson -ErrorAction Stop } | ShouldBeErrorId "InvalidJsonSchema,Microsoft.PowerShell.Commands.TestJsonCommand" + { Test-Json -Json $validJson -Schema $invalidSchemaJson -ErrorAction Stop } | Should -Throw -ErrorId "InvalidJsonSchema,Microsoft.PowerShell.Commands.TestJsonCommand" } It "Test-Json write an error on invalid (<name>) Json aganist a valid schema" -TestCases @( diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 index 8242d13ec70..c615191d22a 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 @@ -39,11 +39,11 @@ Describe "Unblock-File" -Tags "CI" { } It "With '-Path': no file exist" { - { Unblock-File -Path nofileexist.ttt -ErrorAction Stop } | ShouldBeErrorId "FileNotFound,Microsoft.PowerShell.Commands.UnblockFileCommand" + { Unblock-File -Path nofileexist.ttt -ErrorAction Stop } | Should -Throw -ErrorId "FileNotFound,Microsoft.PowerShell.Commands.UnblockFileCommand" } It "With '-LiteralPath': no file exist" { - { Unblock-File -LiteralPath nofileexist.ttt -ErrorAction Stop } | ShouldBeErrorId "FileNotFound,Microsoft.PowerShell.Commands.UnblockFileCommand" + { Unblock-File -LiteralPath nofileexist.ttt -ErrorAction Stop } | Should -Throw -ErrorId "FileNotFound,Microsoft.PowerShell.Commands.UnblockFileCommand" } It "With '-Path': file exist" { @@ -72,6 +72,6 @@ Describe "Unblock-File" -Tags "CI" { $TestFileCreated = Get-ChildItem $TestFile $TestFileCreated.IsReadOnly | Should -BeTrue - { Unblock-File -LiteralPath $TestFile -ErrorAction Stop } | ShouldBeErrorId "RemoveItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.UnblockFileCommand" + { Unblock-File -LiteralPath $TestFile -ErrorAction Stop } | Should -Throw -ErrorId "RemoveItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.UnblockFileCommand" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Update-FormatData.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Update-FormatData.Tests.ps1 index 43df9b2d24b..e50cd51acd0 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Update-FormatData.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Update-FormatData.Tests.ps1 @@ -70,7 +70,7 @@ Describe "Update-FormatData basic functionality" -Tags "CI" { </Configuration> "@ $xmlContent | Out-File -FilePath "$testdrive\test.format.ps1xml" -Encoding ascii - { Update-FormatData -Path "$testdrive\test.format.ps1xml" -ErrorAction Stop } | ShouldBeErrorId "FormatXmlUpdateException,Microsoft.PowerShell.Commands.UpdateFormatDataCommand" + { Update-FormatData -Path "$testdrive\test.format.ps1xml" -ErrorAction Stop } | Should -Throw -ErrorId "FormatXmlUpdateException,Microsoft.PowerShell.Commands.UpdateFormatDataCommand" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index 1f7bb99f172..e6f341bee81 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -654,7 +654,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { $uri = Get-WebListenerUrl -Test 'Get' #Validate that parameter sets are functioning correctly $errorId = "AmbiguousParameterSet,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" - { Invoke-WebRequest -Uri $uri -Method GET -CustomMethod TEST } | ShouldBeErrorId $errorId + { Invoke-WebRequest -Uri $uri -Method GET -CustomMethod TEST } | Should -Throw -ErrorId $errorId } It "Validate Invoke-WebRequest CustomMethod method is used" { @@ -927,7 +927,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { $uri = Get-WebListenerUrl -Test 'Post' { Invoke-WebRequest -Uri $uri -Method 'Post' -ContentType $contentType -Body $body -ErrorAction 'Stop' } | - ShouldBeErrorId "WebCmdletContentTypeException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" + Should -Throw -ErrorId "WebCmdletContentTypeException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" } It "Verifies Invoke-WebRequest ContentType handling reports no error is returned for an invalid Content-Type header value, -Body, and -SkipHeaderValidation" { @@ -959,7 +959,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { $uri = Get-WebListenerUrl -Test 'Post' { Invoke-WebRequest -Uri $uri -Method 'Post' -ContentType $contentType -InFile $Testfile -ErrorAction 'Stop' } | - ShouldBeErrorId "WebCmdletContentTypeException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" + Should -Throw -ErrorId "WebCmdletContentTypeException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" } It "Verifies Invoke-WebRequest default ContentType handling reports no error is returned for an invalid Content-Type header value, -Infile, and -SkipHeaderValidation" { @@ -1375,7 +1375,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { $uri = Get-WebListenerUrl -Test 'Multipart' {Invoke-WebRequest -Uri $uri -Form $form -Body $Body -ErrorAction 'Stop'} | - ShouldBeErrorId 'WebCmdletBodyFormConflictException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand' + Should -Throw -ErrorId 'WebCmdletBodyFormConflictException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand' } It "Verifies Invoke-WebRequest -Form is mutually exclusive with -InFile" { @@ -1383,7 +1383,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { $uri = Get-WebListenerUrl -Test 'Multipart' {Invoke-WebRequest -Uri $uri -Form $form -InFile $file1Path -ErrorAction 'Stop'} | - ShouldBeErrorId 'WebCmdletFormInFileConflictException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand' + Should -Throw -ErrorId 'WebCmdletFormInFileConflictException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand' } } @@ -1438,7 +1438,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { ErrorAction = 'Stop' SkipCertificateCheck = $true } - { Invoke-WebRequest @params } | ShouldBeErrorId "WebCmdletAuthenticationConflictException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" + { Invoke-WebRequest @params } | Should -Throw -ErrorId "WebCmdletAuthenticationConflictException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" } It "Verifies Invoke-WebRequest -Authentication does not support Both -Credential and -Token" { @@ -1450,7 +1450,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { ErrorAction = 'Stop' SkipCertificateCheck = $true } - { Invoke-WebRequest @params } | ShouldBeErrorId "WebCmdletAuthenticationTokenConflictException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" + { Invoke-WebRequest @params } | Should -Throw -ErrorId "WebCmdletAuthenticationTokenConflictException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" } It "Verifies Invoke-WebRequest -Authentication <Authentication> requires -Token" -TestCases $testCases { @@ -1461,7 +1461,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { ErrorAction = 'Stop' SkipCertificateCheck = $true } - { Invoke-WebRequest @params } | ShouldBeErrorId "WebCmdletAuthenticationTokenNotSuppliedException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" + { Invoke-WebRequest @params } | Should -Throw -ErrorId "WebCmdletAuthenticationTokenNotSuppliedException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" } It "Verifies Invoke-WebRequest -Authentication Basic requires -Credential" { @@ -1471,7 +1471,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { ErrorAction = 'Stop' SkipCertificateCheck = $true } - { Invoke-WebRequest @params } | ShouldBeErrorId "WebCmdletAuthenticationCredentialNotSuppliedException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" + { Invoke-WebRequest @params } | Should -Throw -ErrorId "WebCmdletAuthenticationCredentialNotSuppliedException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" } It "Verifies Invoke-WebRequest -Authentication Requires HTTPS" { @@ -1481,7 +1481,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { Authentication = "OAuth" ErrorAction = 'Stop' } - { Invoke-WebRequest @params } | ShouldBeErrorId "WebCmdletAllowUnencryptedAuthenticationRequiredException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" + { Invoke-WebRequest @params } | Should -Throw -ErrorId "WebCmdletAllowUnencryptedAuthenticationRequiredException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" } It "Verifies Invoke-WebRequest -Authentication Can use HTTP with -AllowUnencryptedAuthentication" { @@ -1515,7 +1515,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { Credential = $credential ErrorAction = 'Stop' } - { Invoke-WebRequest @params } | ShouldBeErrorId "WebCmdletAllowUnencryptedAuthenticationRequiredException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" + { Invoke-WebRequest @params } | Should -Throw -ErrorId "WebCmdletAllowUnencryptedAuthenticationRequiredException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" } It "Verifies Invoke-WebRequest Negotiated -Credential Can use HTTP with -AllowUnencryptedAuthentication" { @@ -1554,7 +1554,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { UseDefaultCredentials = $true ErrorAction = 'Stop' } - { Invoke-WebRequest @params } | ShouldBeErrorId "WebCmdletAllowUnencryptedAuthenticationRequiredException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" + { Invoke-WebRequest @params } | Should -Throw -ErrorId "WebCmdletAllowUnencryptedAuthenticationRequiredException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand" } # UseDefaultCredentials is only reliably testable on Windows @@ -1634,7 +1634,7 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { SkipCertificateCheck = $true ErrorAction = 'Stop' } - { Invoke-WebRequest @params } | ShouldBeErrorId 'WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand' + { Invoke-WebRequest @params } | Should -Throw -ErrorId 'WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand' } } } @@ -2019,7 +2019,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" { It "Validate Invoke-RestMethod StandardMethod and CustomMethod parameter sets" { $uri = Get-WebListenerUrl -Test 'Get' $errorId = "AmbiguousParameterSet,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" - { Invoke-RestMethod -Uri $uri -Method GET -CustomMethod TEST } | ShouldBeErrorId $errorId + { Invoke-RestMethod -Uri $uri -Method GET -CustomMethod TEST } | Should -Throw -ErrorId $errorId } It "Validate CustomMethod method is used" { @@ -2262,7 +2262,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" { $uri = Get-WebListenerUrl -Test 'Post' { Invoke-RestMethod -Uri $uri -Method 'Post' -ContentType $contentType -Body $body -ErrorAction 'Stop' } | - ShouldBeErrorId "WebCmdletContentTypeException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" + Should -Throw -ErrorId "WebCmdletContentTypeException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" } It "Verifies Invoke-RestMethod ContentType handling reports no error is returned for an invalid Content-Type header value, -Body, and -SkipHeaderValidation" { @@ -2292,7 +2292,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" { $uri = Get-WebListenerUrl -Test 'Post' { Invoke-RestMethod -Uri $uri -Method 'Post' -ContentType $contentType -InFile $Testfile -ErrorAction 'Stop' } | - ShouldBeErrorId "WebCmdletContentTypeException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" + Should -Throw -ErrorId "WebCmdletContentTypeException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" } It "Verifies Invoke-RestMethod default ContentType handling reports no error is returned for an invalid Content-Type header value, -Infile, and -SkipHeaderValidation" { @@ -2493,7 +2493,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" { $uri = Get-WebListenerUrl -Test 'Multipart' {Invoke-RestMethod -Uri $uri -Form $form -Body $Body -ErrorAction 'Stop'} | - ShouldBeErrorId 'WebCmdletBodyFormConflictException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand' + Should -Throw -ErrorId 'WebCmdletBodyFormConflictException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand' } It "Verifies Invoke-RestMethod -Form is mutually exclusive with -InFile" { @@ -2501,7 +2501,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" { $uri = Get-WebListenerUrl -Test 'Multipart' {Invoke-RestMethod -Uri $uri -Form $form -InFile $file1Path -ErrorAction 'Stop'} | - ShouldBeErrorId 'WebCmdletFormInFileConflictException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand' + Should -Throw -ErrorId 'WebCmdletFormInFileConflictException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand' } } @@ -2714,7 +2714,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" { ErrorAction = 'Stop' SkipCertificateCheck = $true } - { Invoke-RestMethod @params } | ShouldBeErrorId "WebCmdletAuthenticationConflictException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" + { Invoke-RestMethod @params } | Should -Throw -ErrorId "WebCmdletAuthenticationConflictException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" } It "Verifies Invoke-RestMethod -Authentication does not support Both -Credential and -Token" { @@ -2726,7 +2726,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" { ErrorAction = 'Stop' SkipCertificateCheck = $true } - { Invoke-RestMethod @params } | ShouldBeErrorId "WebCmdletAuthenticationTokenConflictException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" + { Invoke-RestMethod @params } | Should -Throw -ErrorId "WebCmdletAuthenticationTokenConflictException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" } It "Verifies Invoke-RestMethod -Authentication <Authentication> requires -Token" -TestCases $testCases { @@ -2737,7 +2737,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" { ErrorAction = 'Stop' SkipCertificateCheck = $true } - { Invoke-RestMethod @params } | ShouldBeErrorId "WebCmdletAuthenticationTokenNotSuppliedException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" + { Invoke-RestMethod @params } | Should -Throw -ErrorId "WebCmdletAuthenticationTokenNotSuppliedException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" } It "Verifies Invoke-RestMethod -Authentication Basic requires -Credential" { @@ -2747,7 +2747,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" { ErrorAction = 'Stop' SkipCertificateCheck = $true } - { Invoke-RestMethod @params } | ShouldBeErrorId "WebCmdletAuthenticationCredentialNotSuppliedException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" + { Invoke-RestMethod @params } | Should -Throw -ErrorId "WebCmdletAuthenticationCredentialNotSuppliedException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" } It "Verifies Invoke-RestMethod -Authentication Requires HTTPS" { @@ -2757,7 +2757,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" { Authentication = "OAuth" ErrorAction = 'Stop' } - { Invoke-RestMethod @params } | ShouldBeErrorId "WebCmdletAllowUnencryptedAuthenticationRequiredException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" + { Invoke-RestMethod @params } | Should -Throw -ErrorId "WebCmdletAllowUnencryptedAuthenticationRequiredException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" } It "Verifies Invoke-RestMethod -Authentication Can use HTTP with -AllowUnencryptedAuthentication" { @@ -2789,7 +2789,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" { Credential = $credential ErrorAction = 'Stop' } - { Invoke-RestMethod @params } | ShouldBeErrorId "WebCmdletAllowUnencryptedAuthenticationRequiredException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" + { Invoke-RestMethod @params } | Should -Throw -ErrorId "WebCmdletAllowUnencryptedAuthenticationRequiredException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" } It "Verifies Invoke-RestMethod Negotiated -Credential Can use HTTP with -AllowUnencryptedAuthentication" { @@ -2826,7 +2826,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" { UseDefaultCredentials = $true ErrorAction = 'Stop' } - { Invoke-RestMethod @params } | ShouldBeErrorId "WebCmdletAllowUnencryptedAuthenticationRequiredException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" + { Invoke-RestMethod @params } | Should -Throw -ErrorId "WebCmdletAllowUnencryptedAuthenticationRequiredException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand" } # UseDefaultCredentials is only reliably testable on Windows @@ -2903,7 +2903,7 @@ Describe "Invoke-RestMethod tests" -Tags "Feature" { SkipCertificateCheck = $true ErrorAction = 'Stop' } - { Invoke-RestMethod @params } | ShouldBeErrorId 'WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand' + { Invoke-RestMethod @params } | Should -Throw -ErrorId 'WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand' } } } @@ -3120,12 +3120,7 @@ Describe "Validate Invoke-WebRequest and Invoke-RestMethod -InFile" -Tags "Featu It "<Name>" -TestCases $testCases { param ($scriptblock, $expectedFullyQualifiedErrorId) - try { - & $scriptblock - throw "No Exception!" - } catch { - $_.FullyQualifiedErrorId | Should -Be $ExpectedFullyQualifiedErrorId - } + { & $scriptblock } | Should -Throw -ErrorId $ExpectedFullyQualifiedErrorId } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Error.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Error.Tests.ps1 index 54818d132e3..22734cc2a0c 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Error.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Error.Tests.ps1 @@ -86,20 +86,7 @@ Describe "Write-Error Tests" -Tags "CI" { } It "Should trip an exception using the exception switch" { - $var = 0 - try - { - Write-Error -Exception -Message "test throw" - } - catch [System.Exception] - { - - $var++ - } - finally - { - $var | Should -Be 1 - } + { Write-Error -Exception -Message "test throw" } | Should -Throw -ErrorId "MissingArgument,Microsoft.PowerShell.Commands.WriteErrorCommand" } It "Should output the error message to the `$error automatic variable" { From def148f23def255dca01a011054da1f58fec3ff3 Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Tue, 17 Apr 2018 17:41:44 -0700 Subject: [PATCH 32/58] [Feature] ShouldBeErrorId => Should -Throw -ErrorId in WSMan.Management module. --- .../ConfigProvider.Tests.ps1 | 20 +++++++++---------- .../CredSSP.Tests.ps1 | 2 +- .../TestWSMan.Tests.ps1 | 2 +- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/test/powershell/Modules/Microsoft.WSMan.Management/ConfigProvider.Tests.ps1 b/test/powershell/Modules/Microsoft.WSMan.Management/ConfigProvider.Tests.ps1 index 9e144aa6e8c..93ad0f557bb 100644 --- a/test/powershell/Modules/Microsoft.WSMan.Management/ConfigProvider.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.WSMan.Management/ConfigProvider.Tests.ps1 @@ -58,7 +58,7 @@ Describe "WSMan Config Provider" -Tag Feature,RequireAdminOnWindows { It "Can remove and add wsman drive" { $wsmanDrive = Get-PSDrive -Name WSMan Remove-PSDrive -Name wsman - { Get-PSDrive -Name wsman -ErrorAction Stop } | ShouldBeErrorId "GetLocationNoMatchingDrive,Microsoft.PowerShell.Commands.GetPSDriveCommand" + { Get-PSDrive -Name wsman -ErrorAction Stop } | Should -Throw -ErrorId "GetLocationNoMatchingDrive,Microsoft.PowerShell.Commands.GetPSDriveCommand" $wsmanDrive2 = $wsmanDrive | New-PSDrive -PSProvider WSMan $wsmanDrive2 | Should -BeOfType System.Management.Automation.PSDriveInfo $wsmanDrive2.Name | Should -BeExactly "WSMan" @@ -130,7 +130,7 @@ Describe "WSMan Config Provider" -Tag Feature,RequireAdminOnWindows { Context "Set-Item tests" { It "Set-Item should fail for `$null value" { - { Set-Item WSMan:\localhost\Client\TrustedHosts $null } | ShouldBeErrorId "System.ArgumentException,Microsoft.PowerShell.Commands.SetItemCommand" + { Set-Item WSMan:\localhost\Client\TrustedHosts $null } | Should -Throw -ErrorId "System.ArgumentException,Microsoft.PowerShell.Commands.SetItemCommand" } It "Set-Item should fail for <path>" -TestCases @( @@ -138,7 +138,7 @@ Describe "WSMan Config Provider" -Tag Feature,RequireAdminOnWindows { @{path="WSMan:\localhost"} ) { param ($path) - { Set-Item $path "foo" } | ShouldBeErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" + { Set-Item $path "foo" } | Should -Throw -ErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" } It "Set-Item -WhatIf should work" { @@ -164,7 +164,7 @@ Describe "WSMan Config Provider" -Tag Feature,RequireAdminOnWindows { #[SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Demo/doc/test secret.")] $password = ConvertTo-SecureString "My voice is my passport, verify me" -AsPlainText -Force $creds = [pscredential]::new((Get-Random),$password) - $exception = { Set-Item $testPluginPath\RunAsUser $creds } | ShouldBeErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" + $exception = { Set-Item $testPluginPath\RunAsUser $creds } | Should -Throw -ErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" -PassThru $exception.Exception.Message | Should -Match ".*$badCredentialError.*" } @@ -183,7 +183,7 @@ Describe "WSMan Config Provider" -Tag Feature,RequireAdminOnWindows { #[SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Demo/doc/test secret.")] $password = ConvertTo-SecureString "My voice is my passport, verify me" -AsPlainText -Force $creds = [pscredential]::new($testUser,$password) - $exception = { Set-Item $testPluginPath\RunAsUser $creds } | ShouldBeErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" + $exception = { Set-Item $testPluginPath\RunAsUser $creds } | Should -Throw -ErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" -PassThru $exception.Exception.Message | Should -Match ".*$badCredentialError.*" } @@ -195,7 +195,7 @@ Describe "WSMan Config Provider" -Tag Feature,RequireAdminOnWindows { ) { param($password) Clear-Item $testPluginPath\RunAsUser -WarningAction SilentlyContinue - { Set-Item $testPluginPath\RunAsPassword $password } | ShouldBeErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" + { Set-Item $testPluginPath\RunAsPassword $password } | Should -Throw -ErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" } It "Set-Item on plugin XmlRenderingType property should succeed for '<type>'" -TestCases @( @@ -210,7 +210,7 @@ Describe "WSMan Config Provider" -Tag Feature,RequireAdminOnWindows { } It "Set-Item on non-existent property should fail" { - { Set-Item $testPluginPath\foo "bar" } | ShouldBeErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" + { Set-Item $testPluginPath\foo "bar" } | Should -Throw -ErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" } It "Set-Item on plugin Resource '<property>' property with '<value>' should succeed" -TestCases @( @@ -243,7 +243,7 @@ Describe "WSMan Config Provider" -Tag Feature,RequireAdminOnWindows { param($property, $value, $expected) $resource = Get-ChildItem "$testPluginPath\Resources" | Select-Object -First 1 $security = Get-ChildItem "$($resource.PSPath)\Security" | Select-Object -First 1 - { Set-Item "$($security.PSPath)\$property" $value -Force } | ShouldBeErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" + { Set-Item "$($security.PSPath)\$property" $value -Force } | Should -Throw -ErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" } It "Set-Item on plugin InitializationParameters '<property>' property with '<value>' should succeed" -TestCases @( @@ -271,7 +271,7 @@ Describe "WSMan Config Provider" -Tag Feature,RequireAdminOnWindows { @{property="MaxShells"; value=0} ) { param($property, $value) - { Set-Item "$testPluginPath\Quotas\$property" $value -WarningAction SilentlyContinue } | ShouldBeErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" + { Set-Item "$testPluginPath\Quotas\$property" $value -WarningAction SilentlyContinue } | Should -Throw -ErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.SetItemCommand" } } @@ -281,7 +281,7 @@ Describe "WSMan Config Provider" -Tag Feature,RequireAdminOnWindows { @{property="Quotas\IdleTimeoutms"}, @{property="InitializationParameters\PSVersion"} ) { - { Clear-Item "$testPluginPath\$property" -WarningAction SilentlyContinue } | ShouldBeErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.ClearItemCommand" + { Clear-Item "$testPluginPath\$property" -WarningAction SilentlyContinue } | Should -Throw -ErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.ClearItemCommand" } } diff --git a/test/powershell/Modules/Microsoft.WSMan.Management/CredSSP.Tests.ps1 b/test/powershell/Modules/Microsoft.WSMan.Management/CredSSP.Tests.ps1 index bb01010b575..1cd07f8af87 100644 --- a/test/powershell/Modules/Microsoft.WSMan.Management/CredSSP.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.WSMan.Management/CredSSP.Tests.ps1 @@ -40,7 +40,7 @@ Describe "CredSSP cmdlet tests" -Tags 'Feature','RequireAdminOnWindows' { @{params=@{Role="Server";DelegateComputer="."};Description="Server role w/ DelegateComputer"} ) { param ($params) - { Enable-WSManCredSSP @params } | ShouldBeErrorId "System.InvalidOperationException,Microsoft.WSMan.Management.EnableWSManCredSSPCommand" + { Enable-WSManCredSSP @params } | Should -Throw -ErrorId "System.InvalidOperationException,Microsoft.WSMan.Management.EnableWSManCredSSPCommand" } It "Enable-WSManCredSSP works: <description>" -Skip:($NotEnglish -or $IsToBeSkipped) -TestCases @( diff --git a/test/powershell/Modules/Microsoft.WSMan.Management/TestWSMan.Tests.ps1 b/test/powershell/Modules/Microsoft.WSMan.Management/TestWSMan.Tests.ps1 index 15c3d78c61e..9db02182b46 100644 --- a/test/powershell/Modules/Microsoft.WSMan.Management/TestWSMan.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.WSMan.Management/TestWSMan.Tests.ps1 @@ -43,7 +43,7 @@ Describe "TestWSMan tests" -Tags 'Feature' { } It "-Authentication for unsupported type should return error" { - { Test-WSMan -Authentication foo -ErrorAction Stop } | ShouldBeErrorId "CannotConvertArgumentNoMessage,Microsoft.WSMan.Management.TestWSManCommand" + { Test-WSMan -Authentication foo -ErrorAction Stop } | Should -Throw -ErrorId "CannotConvertArgumentNoMessage,Microsoft.WSMan.Management.TestWSManCommand" } It "Test-WSMan works for '<computername>'" -TestCases @( From 8b11e4238e0dd07faf451510cfdee9efc597ff55 Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Tue, 17 Apr 2018 18:16:24 -0700 Subject: [PATCH 33/58] [Feature] ShouldBeErrorId => Should -Throw -ErrorId in engine. --- .../powershell/engine/Basic/Attributes.Tests.ps1 | 2 +- .../engine/Basic/SemanticVersion.Tests.ps1 | 16 ++++++++-------- .../engine/Basic/ValidateAttributes.Tests.ps1 | 8 ++++---- test/powershell/engine/Cdxml/Cdxml.Tests.ps1 | 4 ++-- test/powershell/engine/Job/Jobs.Tests.ps1 | 4 ++-- .../engine/Module/NewModuleManifest.Tests.ps1 | 2 +- .../engine/Module/TestModuleManifest.Tests.ps1 | 10 +++++----- .../Remoting/RemoteSession.Basic.Tests.ps1 | 2 +- .../engine/Remoting/SSHRemotingAPI.Tests.ps1 | 2 +- 9 files changed, 25 insertions(+), 25 deletions(-) diff --git a/test/powershell/engine/Basic/Attributes.Tests.ps1 b/test/powershell/engine/Basic/Attributes.Tests.ps1 index 5e4e233498b..074c492b5fc 100644 --- a/test/powershell/engine/Basic/Attributes.Tests.ps1 +++ b/test/powershell/engine/Basic/Attributes.Tests.ps1 @@ -21,6 +21,6 @@ Param ( Write-Output "Hello" "@ New-Item -Path $testdrive/test.ps1 -Value $script -ItemType File - { & $testdrive/test.ps1 } | ShouldBeErrorId "Argument" + { & $testdrive/test.ps1 } | Should -Throw -ErrorId "Argument" } } diff --git a/test/powershell/engine/Basic/SemanticVersion.Tests.ps1 b/test/powershell/engine/Basic/SemanticVersion.Tests.ps1 index 55a2d2ab6eb..4a6d9bd5ab3 100644 --- a/test/powershell/engine/Basic/SemanticVersion.Tests.ps1 +++ b/test/powershell/engine/Basic/SemanticVersion.Tests.ps1 @@ -203,12 +203,12 @@ Describe "SemanticVersion api tests" -Tags 'CI' { @{ name = "Format errors"; errorId = "FormatException"; expectedResult = $false; version = "1.0.cc" } ) { param($version, $expectedResult, $errorId) - { [SemanticVersion]::new($version) } | ShouldBeErrorId $errorId + { [SemanticVersion]::new($version) } | Should -Throw -ErrorId $errorId if ($version -eq $null) { # PowerShell convert $null to Empty string - { [SemanticVersion]::Parse($version) } | ShouldBeErrorId "FormatException" + { [SemanticVersion]::Parse($version) } | Should -Throw -ErrorId "FormatException" } else { - { [SemanticVersion]::Parse($version) } | ShouldBeErrorId $errorId + { [SemanticVersion]::Parse($version) } | Should -Throw -ErrorId $errorId } $semVer = $null [SemanticVersion]::TryParse($_, [ref]$semVer) | Should -Be $expectedResult @@ -216,15 +216,15 @@ Describe "SemanticVersion api tests" -Tags 'CI' { } It "Negative version arguments" { - { [SemanticVersion]::new(-1, 0) } | ShouldBeErrorId "PSArgumentException" - { [SemanticVersion]::new(1, -1) } | ShouldBeErrorId "PSArgumentException" - { [SemanticVersion]::new(1, 1, -1) } | ShouldBeErrorId "PSArgumentException" + { [SemanticVersion]::new(-1, 0) } | Should -Throw -ErrorId "PSArgumentException" + { [SemanticVersion]::new(1, -1) } | Should -Throw -ErrorId "PSArgumentException" + { [SemanticVersion]::new(1, 1, -1) } | Should -Throw -ErrorId "PSArgumentException" } It "Incompatible 'Version' throws" { # Revision isn't supported - { [SemanticVersion]::new([Version]::new(0, 0, 0, 4)) } | ShouldBeErrorId "PSArgumentException" - { [SemanticVersion]::new([Version]::new("1.2.3.4")) } | ShouldBeErrorId "PSArgumentException" + { [SemanticVersion]::new([Version]::new(0, 0, 0, 4)) } | Should -Throw -ErrorId "PSArgumentException" + { [SemanticVersion]::new([Version]::new("1.2.3.4")) } | Should -Throw -ErrorId "PSArgumentException" } } diff --git a/test/powershell/engine/Basic/ValidateAttributes.Tests.ps1 b/test/powershell/engine/Basic/ValidateAttributes.Tests.ps1 index 471e30ab837..87b9fdf5c1f 100644 --- a/test/powershell/engine/Basic/ValidateAttributes.Tests.ps1 +++ b/test/powershell/engine/Basic/ValidateAttributes.Tests.ps1 @@ -41,7 +41,7 @@ Describe 'Validate Attributes Tests' -Tags 'CI' { It 'Exception: <FullyQualifiedErrorId>:<InnerErrorId>' -TestCases $testCases { param($ScriptBlock, $FullyQualifiedErrorId, $InnerErrorId) - $ScriptBlock | ShouldBeErrorId $FullyQualifiedErrorId + $ScriptBlock | Should -Throw -ErrorId $FullyQualifiedErrorId if ($InnerErrorId) { $error[0].exception.innerexception.errorrecord.FullyQualifiedErrorId | Should -Be $InnerErrorId } @@ -81,7 +81,7 @@ Describe 'Validate Attributes Tests' -Tags 'CI' { It 'Exception: <FullyQualifiedErrorId>:<InnerErrorId>' -TestCases $testCases { param($ScriptBlock, $FullyQualifiedErrorId, $InnerErrorId) - $ScriptBlock | ShouldBeErrorId $FullyQualifiedErrorId + $ScriptBlock | Should -Throw -ErrorId $FullyQualifiedErrorId if ($InnerErrorId) { $error[0].exception.innerexception.errorrecord.FullyQualifiedErrorId | Should -Be $InnerErrorId } @@ -117,7 +117,7 @@ Describe 'Validate Attributes Tests' -Tags 'CI' { It 'Exception: <FullyQualifiedErrorId>:<InnerErrorId>' -TestCases $testCases { param($ScriptBlock, $FullyQualifiedErrorId, $InnerErrorId) - $ScriptBlock | ShouldBeErrorId $FullyQualifiedErrorId + $ScriptBlock | Should -Throw -ErrorId $FullyQualifiedErrorId if ($InnerErrorId) { $error[0].exception.innerexception.errorrecord.FullyQualifiedErrorId | Should -Be $InnerErrorId } @@ -251,7 +251,7 @@ Describe 'Validate Attributes Tests' -Tags 'CI' { It 'Exception: <FullyQualifiedErrorId>:<InnerErrorId>, RangeType: <RangeType>' -TestCases $testCases { param($ScriptBlock, $RangeType, $FullyQualifiedErrorId, $InnerErrorId) - $ScriptBlock | ShouldBeErrorId $FullyQualifiedErrorId + $ScriptBlock | Should -Throw -ErrorId $FullyQualifiedErrorId if ($InnerErrorId) { $error[0].exception.innerexception.errorrecord.FullyQualifiedErrorId | Should -Be $InnerErrorId } diff --git a/test/powershell/engine/Cdxml/Cdxml.Tests.ps1 b/test/powershell/engine/Cdxml/Cdxml.Tests.ps1 index ebd1ec43c95..16061a9e00e 100644 --- a/test/powershell/engine/Cdxml/Cdxml.Tests.ps1 +++ b/test/powershell/engine/Cdxml/Cdxml.Tests.ps1 @@ -138,7 +138,7 @@ Describe "Cdxml cmdlets are supported" -Tag CI,RequireAdminOnWindows { } It "The Get-CimTest cmdlet should return the proper error if the instance does not exist" @ItSkipOrPending { - { Get-CimTest -ea stop -id "ThisIdDoesNotExist" } | ShouldBeErrorId "CmdletizationQuery_NotFound_Id,Get-CimTest" + { Get-CimTest -ea stop -id "ThisIdDoesNotExist" } | Should -Throw -ErrorId "CmdletizationQuery_NotFound_Id,Get-CimTest" } It "The Get-CimTest cmdlet should work as a job" @ItSkipOrPending { @@ -230,7 +230,7 @@ Describe "Cdxml cmdlets are supported" -Tag CI,RequireAdminOnWindows { field1 = "a string" field2 = "a bad string" # this needs to be an int } - { New-CimTest @instanceArgs } | ShouldBeErrorId "ParameterArgumentTransformationError,New-CimTest" + { New-CimTest @instanceArgs } | Should -Throw -ErrorId "ParameterArgumentTransformationError,New-CimTest" # just make sure that it wasn't added Get-CimTest -id $instanceArgs.Id -ea SilentlyContinue | Should -BeNullOrEmpty } diff --git a/test/powershell/engine/Job/Jobs.Tests.ps1 b/test/powershell/engine/Job/Jobs.Tests.ps1 index e2903a2b483..63cbee16f7c 100644 --- a/test/powershell/engine/Job/Jobs.Tests.ps1 +++ b/test/powershell/engine/Job/Jobs.Tests.ps1 @@ -77,7 +77,7 @@ Describe 'Basic Job Tests' -Tags 'CI' { $nativeJob.HasMoreData | Should -BeTrue Receive-Job $nativeJob | Should -BeExactly 2 Remove-Job $nativeJob - { Get-Job $nativeJob -ErrorAction Stop } | ShouldBeErrorId "JobWithSpecifiedNameNotFound,Microsoft.PowerShell.Commands.GetJobCommand" + { Get-Job $nativeJob -ErrorAction Stop } | Should -Throw -ErrorId "JobWithSpecifiedNameNotFound,Microsoft.PowerShell.Commands.GetJobCommand" } finally { Remove-Job $nativeJob -Force -ErrorAction SilentlyContinue @@ -144,7 +144,7 @@ Describe 'Basic Job Tests' -Tags 'CI' { It 'Can Receive-Job and autoremove' { $result = Start-Job -Name 'ReceiveJobAutoRemove' -ScriptBlock { 1 + 1 } | Receive-Job -Wait -AutoRemoveJob $result | Should -Be 2 - { Get-Job -Name 'ReceiveJobAutoRemove' -ErrorAction Stop } | ShouldBeErrorId 'JobWithSpecifiedNameNotFound,Microsoft.PowerShell.Commands.GetJobCommand' + { Get-Job -Name 'ReceiveJobAutoRemove' -ErrorAction Stop } | Should -Throw -ErrorId 'JobWithSpecifiedNameNotFound,Microsoft.PowerShell.Commands.GetJobCommand' } It 'Can Receive-Job and keep results' { diff --git a/test/powershell/engine/Module/NewModuleManifest.Tests.ps1 b/test/powershell/engine/Module/NewModuleManifest.Tests.ps1 index b6bf9d96137..945b90f62a1 100644 --- a/test/powershell/engine/Module/NewModuleManifest.Tests.ps1 +++ b/test/powershell/engine/Module/NewModuleManifest.Tests.ps1 @@ -46,6 +46,6 @@ Describe "New-ModuleManifest tests" -tags "CI" { It "Relative URIs are not allowed" { $testUri = [Uri]"../foo" - { New-ModuleManifest -Path $testModulePath -ProjectUri $testUri -LicenseUri $testUri -IconUri $testUri } | ShouldBeErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.NewModuleManifestCommand" + { New-ModuleManifest -Path $testModulePath -ProjectUri $testUri -LicenseUri $testUri -IconUri $testUri } | Should -Throw -ErrorId "System.InvalidOperationException,Microsoft.PowerShell.Commands.NewModuleManifestCommand" } } diff --git a/test/powershell/engine/Module/TestModuleManifest.Tests.ps1 b/test/powershell/engine/Module/TestModuleManifest.Tests.ps1 index a4e62b15b0b..bbd0093c6c1 100644 --- a/test/powershell/engine/Module/TestModuleManifest.Tests.ps1 +++ b/test/powershell/engine/Module/TestModuleManifest.Tests.ps1 @@ -47,7 +47,7 @@ Describe "Test-ModuleManifest tests" -tags "CI" { New-ModuleManifest -Path $testModulePath @args [string]$errorId = "$error,Microsoft.PowerShell.Commands.TestModuleManifestCommand" - { Test-ModuleManifest -Path $testModulePath -ErrorAction Stop } | ShouldBeErrorId $errorId + { Test-ModuleManifest -Path $testModulePath -ErrorAction Stop } | Should -Throw -ErrorId $errorId } It "module manifest containing valid unprocessed rootmodule file type succeeds: <rootModuleValue>" -TestCases ( @@ -79,7 +79,7 @@ Describe "Test-ModuleManifest tests" -tags "CI" { New-Item -ItemType File -Path testdrive:/module/$rootModuleValue New-ModuleManifest -Path $testModulePath -RootModule $rootModuleValue - { Test-ModuleManifest -Path $testModulePath -ErrorAction Stop } | ShouldBeErrorId "$error,Microsoft.PowerShell.Commands.TestModuleManifestCommand" + { Test-ModuleManifest -Path $testModulePath -ErrorAction Stop } | Should -Throw -ErrorId "$error,Microsoft.PowerShell.Commands.TestModuleManifestCommand" } It "module manifest containing empty rootmodule succeeds: <rootModuleValue>" -TestCases ( @@ -109,7 +109,7 @@ Describe "Test-ModuleManifest tests" -tags "CI" { New-Item -ItemType File -Path testdrive:/module/$rootModuleValue New-ModuleManifest -Path $testModulePath -RootModule $rootModuleValue - { Test-ModuleManifest -Path $testModulePath -ErrorAction Stop } | ShouldBeErrorId "$error,Microsoft.PowerShell.Commands.TestModuleManifestCommand" + { Test-ModuleManifest -Path $testModulePath -ErrorAction Stop } | Should -Throw -ErrorId "$error,Microsoft.PowerShell.Commands.TestModuleManifestCommand" } It "module manifest containing non-existing rootmodule returns error: <rootModuleValue>" -TestCases ( @@ -122,7 +122,7 @@ Describe "Test-ModuleManifest tests" -tags "CI" { New-Item -ItemType Directory -Path testdrive:/module New-ModuleManifest -Path $testModulePath -RootModule $rootModuleValue - { Test-ModuleManifest -Path $testModulePath -ErrorAction Stop } | ShouldBeErrorId "$error,Microsoft.PowerShell.Commands.TestModuleManifestCommand" + { Test-ModuleManifest -Path $testModulePath -ErrorAction Stop } | Should -Throw -ErrorId "$error,Microsoft.PowerShell.Commands.TestModuleManifestCommand" } } @@ -215,7 +215,7 @@ Describe "Tests for circular references in required modules" -tags "CI" { } It "Add a circular reference to RequiredModules and verify error" { - { TestImportModule $false $false $true } | ShouldBeErrorId "Modules_InvalidManifest,Microsoft.PowerShell.Commands.ImportModuleCommand" + { TestImportModule $false $false $true } | Should -Throw -ErrorId "Modules_InvalidManifest,Microsoft.PowerShell.Commands.ImportModuleCommand" } } diff --git a/test/powershell/engine/Remoting/RemoteSession.Basic.Tests.ps1 b/test/powershell/engine/Remoting/RemoteSession.Basic.Tests.ps1 index bad76d962f6..dbf82de1bd6 100644 --- a/test/powershell/engine/Remoting/RemoteSession.Basic.Tests.ps1 +++ b/test/powershell/engine/Remoting/RemoteSession.Basic.Tests.ps1 @@ -220,7 +220,7 @@ Describe "Remoting loopback tests" -Tags @('CI', 'RequireAdminOnWindows') { It "<title>" -TestCases $ParameterError { param($parameters, $expectedError) - { Invoke-Command @parameters } | ShouldBeErrorId $expectedError + { Invoke-Command @parameters } | Should -Throw -ErrorId $expectedError } It 'Can execute command if one of the sessions is available' { diff --git a/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 b/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 index 9af74de0aef..15677636d99 100644 --- a/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 +++ b/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 @@ -21,7 +21,7 @@ Describe "SSH Remoting API Tests" -Tags "Feature" { "UserName", [System.Management.Automation.Internal.AutomationNull]::Value, [System.Management.Automation.Internal.AutomationNull]::Value, - 0) } | ShouldBeErrorId "PSArgumentNullException" + 0) } | Should -Throw -ErrorId "PSArgumentNullException" } It "SSHConnectionInfo should throw file not found exception for invalid key file path" -Skip:$skipTest { From 17cd7ce03e5de0a7bb409515464a4d6879c334e7 Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Tue, 17 Apr 2018 18:34:40 -0700 Subject: [PATCH 34/58] [Feature] try {} catch {} => Should -Throw -ErrorId in engine. --- .../engine/Basic/CommandDiscovery.Tests.ps1 | 26 +------ .../engine/Basic/PropertyAccessor.Tests.ps1 | 8 +-- .../Help/HelpSystem.OnlineHelp.Tests.ps1 | 11 +-- .../ParameterBinding.Tests.ps1 | 72 +++++-------------- 4 files changed, 22 insertions(+), 95 deletions(-) diff --git a/test/powershell/engine/Basic/CommandDiscovery.Tests.ps1 b/test/powershell/engine/Basic/CommandDiscovery.Tests.ps1 index 86f754be0f2..408e6d81e90 100644 --- a/test/powershell/engine/Basic/CommandDiscovery.Tests.ps1 +++ b/test/powershell/engine/Basic/CommandDiscovery.Tests.ps1 @@ -17,15 +17,7 @@ Describe "Command Discovery tests" -Tags "CI" { It "<testName>" -TestCases $TestCasesCommandNotFound { param($command) - try - { - & $command - throw "Should not have found command: '$command'" - } - catch - { - $_.FullyQualifiedErrorId | Should -Be 'CommandNotFoundException' - } + { & $command } | Should -Throw -ErrorId 'CommandNotFoundException' } It "Command lookup with duplicate paths" { @@ -57,32 +49,20 @@ Describe "Command Discovery tests" -Tags "CI" { } It "Cyclic aliases - direct" { - try { Set-Alias CyclicAliasA CyclicAliasB -Force Set-Alias CyclicAliasB CyclicAliasA -Force & CyclicAliasA - throw "Execution should not reach here. '& CyclicAliasA' should have thrown." - } - catch - { - $_.FullyQualifiedErrorId | Should -Be 'CommandNotFoundException' - } + } | Should -Throw -ErrorId 'CommandNotFoundException' } It "Cyclic aliases - indirect" { - try { Set-Alias CyclicAliasA CyclicAliasB -Force Set-Alias CyclicAliasB CyclicAliasC -Force Set-Alias CyclicAliasC CyclicAliasA -Force & CyclicAliasA - throw "Execution should not reach here. '& CyclicAliasA' should have thrown." - } - catch - { - $_.FullyQualifiedErrorId | Should -Be 'CommandNotFoundException' - } + } | Should -Throw -ErrorId 'CommandNotFoundException' } It "Get-Command should return only CmdletInfo, FunctionInfo, AliasInfo or FilterInfo" { diff --git a/test/powershell/engine/Basic/PropertyAccessor.Tests.ps1 b/test/powershell/engine/Basic/PropertyAccessor.Tests.ps1 index eb0c322e0ce..2238166a4ae 100644 --- a/test/powershell/engine/Basic/PropertyAccessor.Tests.ps1 +++ b/test/powershell/engine/Basic/PropertyAccessor.Tests.ps1 @@ -71,13 +71,7 @@ try { Get-ExecutionPolicy -Scope CurrentUser | Should -Be "Undefined" # Verify the file was not created during the test - try { - $propFile = Get-Item $userPropertiesFile -ErrorAction Stop - throw "Properties file genererated during read operation" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" - } + { $propFile = Get-Item $userPropertiesFile -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } It "Verify Queries for Non-Existant Properties Return Default Value" { diff --git a/test/powershell/engine/Help/HelpSystem.OnlineHelp.Tests.ps1 b/test/powershell/engine/Help/HelpSystem.OnlineHelp.Tests.ps1 index 81ad67404bf..ccc68e7be27 100644 --- a/test/powershell/engine/Help/HelpSystem.OnlineHelp.Tests.ps1 +++ b/test/powershell/engine/Help/HelpSystem.OnlineHelp.Tests.ps1 @@ -91,15 +91,6 @@ Describe 'Get-Help -Online is not supported on Nano Server and IoT' -Tags "CI" { $skipTest = -not ([System.Management.Automation.Platform]::IsIoT -or [System.Management.Automation.Platform]::IsNanoServer) It "Get-help -online <cmdletName> throws InvalidOperation." -skip:$skipTest { - - try - { - Get-Help Get-Help -Online - throw "Execution should not have succeeded" - } - catch - { - $_.FullyQualifiedErrorId | Should -Be "InvalidOperation,Microsoft.PowerShell.Commands.GetHelpCommand" - } + { Get-Help Get-Help -Online } | Should -Throw -ErrorId "InvalidOperation,Microsoft.PowerShell.Commands.GetHelpCommand" } } diff --git a/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 b/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 index 299060c6275..975a8b96510 100644 --- a/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 +++ b/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 @@ -14,15 +14,7 @@ Describe "Parameter Binding Tests" -Tags "CI" { } } - try - { - test-PositionalBinding1 1 - throw "No Exception!" - } - catch - { - $_.FullyQualifiedErrorId | should -Be "AmbiguousPositionalParameterNoName,test-PositionalBinding1" - } + { test-PositionalBinding1 1 } | Should -Throw -ErrorId "AmbiguousPositionalParameterNoName,test-PositionalBinding1" } It "a mandatory parameter can't be passed a null if it doesn't have AllowNullAttribute" { @@ -64,17 +56,10 @@ Describe "Parameter Binding Tests" -Tags "CI" { } } - try - { - test-allownullattributes -Parameter2 1 -Parameter3 $null -ShowMe 1 - throw "No Exception!" - } - catch - { - $_.FullyQualifiedErrorId | should -Be "ParameterArgumentValidationErrorEmptyStringNotAllowed,test-allownullattributes" - $_.CategoryInfo | Should -Match "ParameterBindingValidationException" - $_.Exception.Message | should -Match "Parameter3" - } + $e = { test-allownullattributes -Parameter2 1 -Parameter3 $null -ShowMe 1 } | + Should -Throw -ErrorId "ParameterArgumentValidationErrorEmptyStringNotAllowed,test-allownullattributes" -PassThru + $e.CategoryInfo | Should -Match "ParameterBindingValidationException" + $e.Exception.Message | Should -Match "Parameter3" } It "can't pass an argument that looks like a boolean parameter to a named string parameter" { @@ -90,17 +75,9 @@ Describe "Parameter Binding Tests" -Tags "CI" { } } - try - { - test-namedwithboolishargument -Parameter2 -Parameter1 - throw "No Exception!" - } - catch - { - $_.FullyQualifiedErrorId | should -Be "MissingArgument,test-namedwithboolishargument" - $_.CategoryInfo | Should -Match "ParameterBindingException" - $_.Exception.Message | should -Match "Parameter2" - } + $e = { test-namedwithboolishargument -Parameter2 -Parameter1 } | Should -Throw -ErrorId "MissingArgument,test-namedwithboolishargument" -PassThru + $e.CategoryInfo | Should -Match "ParameterBindingException" + $e.Exception.Message | Should -Match "Parameter2" } It "Verify that a SwitchParameter's IsPresent member is false if the parameter is not specified" { @@ -150,18 +127,11 @@ Describe "Parameter Binding Tests" -Tags "CI" { } } - try - { - test-singleintparameter -Parameter1 'exampleInvalidParam' - throw "No Exception!" - } - catch - { - $_.FullyQualifiedErrorId | should -Be "ParameterArgumentTransformationError,test-singleintparameter" - $_.CategoryInfo | Should -Match "ParameterBindingArgumentTransformationException" - $_.Exception.Message | should -Match "Input string was not in a correct format" - $_.Exception.Message | should -Match "Parameter1" - } + $e = { test-singleintparameter -Parameter1 'exampleInvalidParam' } | + Should -Throw -ErrorId "ParameterArgumentTransformationError,test-singleintparameter" -PassThru + $e.CategoryInfo | Should -Match "ParameterBindingArgumentTransformationException" + $e.Exception.Message | Should -Match "Input string was not in a correct format" + $e.Exception.Message | should -Match "Parameter1" } It "Verify that WhatIf is available when SupportShouldProcess is true" { @@ -269,18 +239,10 @@ Describe "Parameter Binding Tests" -Tags "CI" { ) } - try - { - test-nameconflicts6 -Parameter2 1 - throw "No Exception!" - } - catch - { - $_.FullyQualifiedErrorId | should -Be "ParameterNameConflictsWithAlias" - $_.CategoryInfo | Should -Match "MetadataException" - $_.Exception.Message | should -Match "Parameter1" - $_.Exception.Message | should -Match "Parameter2" - } + $e = { test-nameconflicts6 -Parameter2 1 } | Should -Throw -ErrorId "ParameterNameConflictsWithAlias" -PassThru + $e.CategoryInfo | Should -Match "MetadataException" + $e.Exception.Message | should -Match "Parameter1" + $e.Exception.Message | should -Match "Parameter2" } It "PipelineVariable shouldn't cause a NullRef exception when 'DynamicParam' block is present" { From f5c14879165d7a47572e0b78741ddba4e9bd9594 Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Wed, 18 Apr 2018 11:49:45 -0700 Subject: [PATCH 35/58] [Feature] Tests fix --- test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 | 5 ++--- test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 b/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 index 075fbf6f602..aaf5519ec60 100644 --- a/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 +++ b/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 @@ -28,9 +28,8 @@ Try { $instance.GetCimSessionInstanceId() | Should -BeOfType "Guid" } It "should produce an error for a non-existing classname" { - { get-ciminstance -classname thisnameshouldnotexist -ea stop } | - Should -Throw -ErrorId "HRESULT 0x80041010,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstanceCommand" - } + { get-ciminstance -classname thisnameshouldnotexist -ea stop } | + Should -Throw -ErrorId "HRESULT 0x80041010,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstanceCommand" } } } diff --git a/test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 b/test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 index b8af13164da..114a5ff7e80 100644 --- a/test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 +++ b/test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 @@ -15,7 +15,7 @@ try { } It 'produces an error when a non-existent class is used' { - { Get-CimClass -ClassName thisclasstypedoesnotexist -ea stop | + { Get-CimClass -ClassName thisclasstypedoesnotexist -ea stop } | Should -Throw -ErrorId "HRESULT 0x80041002,Microsoft.Management.Infrastructure.CimCmdlets.GetCimClassCommand" } It 'produces an error when an improper namespace is used' { From 0ffb1ed6a0a6da5fb89baa7b07bf0775744db2c5 Mon Sep 17 00:00:00 2001 From: Klaudia Algiz <klalgiz@microsoft.com> Date: Wed, 18 Apr 2018 14:10:23 -0700 Subject: [PATCH 36/58] [Feature] try {} catch {} => Should -Throw -ErrorId in engine. --- .../Remoting/RemoteSession.Basic.Tests.ps1 | 8 ++--- .../Remoting/RoleCapabilityFiles.Tests.ps1 | 35 ++++--------------- .../engine/Remoting/SSHRemotingAPI.Tests.ps1 | 30 ++++------------ .../Remoting/SSHRemotingCmdlets.Tests.ps1 | 21 ++--------- 4 files changed, 17 insertions(+), 77 deletions(-) diff --git a/test/powershell/engine/Remoting/RemoteSession.Basic.Tests.ps1 b/test/powershell/engine/Remoting/RemoteSession.Basic.Tests.ps1 index dbf82de1bd6..7aef5bbe112 100644 --- a/test/powershell/engine/Remoting/RemoteSession.Basic.Tests.ps1 +++ b/test/powershell/engine/Remoting/RemoteSession.Basic.Tests.ps1 @@ -2,12 +2,8 @@ # Licensed under the MIT License. Describe "New-PSSession basic test" -Tag @("CI") { It "New-PSSession should not crash powershell" { - try { - New-PSSession -ComputerName nonexistcomputer -Authentication Basic - throw "New-PSSession should throw" - } catch { - $_.FullyQualifiedErrorId | Should -Be "InvalidOperation,Microsoft.PowerShell.Commands.NewPSSessionCommand" - } + { New-PSSession -ComputerName nonexistcomputer -Authentication Basic } | + Should -Throw -ErrorId "InvalidOperation,Microsoft.PowerShell.Commands.NewPSSessionCommand" } } diff --git a/test/powershell/engine/Remoting/RoleCapabilityFiles.Tests.ps1 b/test/powershell/engine/Remoting/RoleCapabilityFiles.Tests.ps1 index ddc1287ae67..67ca0d1e2b1 100644 --- a/test/powershell/engine/Remoting/RoleCapabilityFiles.Tests.ps1 +++ b/test/powershell/engine/Remoting/RoleCapabilityFiles.Tests.ps1 @@ -42,21 +42,11 @@ Describe "Remote session configuration RoleDefintion RoleCapabilityFiles key tes Administrators = @{ RoleCapabilityFiles = "$RoleCapDirectory\NoFile.psrc" } } - $fullyQualifiedErrorId = "" - try - { + $e = { $iss = [initialsessionstate]::CreateFromSessionConfigurationFile($PSSessionConfigFile, { $true }) - throw 'No Exception!' - } - catch - { - $psioe = [System.Management.Automation.PSInvalidOperationException] ($_.Exception).InnerException - if ($null -ne $psioe) - { - $fullyQualifiedErrorId = $psioe.ErrorRecord.FullyQualifiedErrorId - } - $fullyQualifiedErrorId | Should -Be 'CouldNotFindRoleCapabilityFile' - } + } | Should -Throw -PassThru + + $e.Exception.InnerException.ErrorRecord.FullyQualifiedErrorId | Should -BeExactly 'CouldNotFindRoleCapabilityFile' } It "Verifies incorrect role capability file extenstion error" { @@ -65,21 +55,10 @@ Describe "Remote session configuration RoleDefintion RoleCapabilityFiles key tes Administrators = @{ RoleCapabilityFiles = "$BadRoleCapFile" } } - $fullyQualifiedErrorId = "" - try - { + $e = { $iss = [initialsessionstate]::CreateFromSessionConfigurationFile($PSSessionConfigFile, { $true }) - throw 'No Exception!' - } - catch - { - $psioe = [System.Management.Automation.PSInvalidOperationException] ($_.Exception).InnerException - if ($null -ne $psioe) - { - $fullyQualifiedErrorId = $psioe.ErrorRecord.FullyQualifiedErrorId - } - $fullyQualifiedErrorId | Should -Be 'InvalidRoleCapabilityFileExtension' - } + } | Should -Throw -PassThru + $e.Exception.InnerException.ErrorRecord.FullyQualifiedErrorId | Should -BeExactly 'InvalidRoleCapabilityFileExtension' } It "Verifies restriction on good role capability file" { diff --git a/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 b/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 index 15677636d99..a07a4c9c641 100644 --- a/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 +++ b/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 @@ -26,8 +26,7 @@ Describe "SSH Remoting API Tests" -Tags "Feature" { It "SSHConnectionInfo should throw file not found exception for invalid key file path" -Skip:$skipTest { - try - { + $e = { $sshConnectionInfo = [System.Management.Automation.Runspaces.SSHConnectionInfo]::new( "UserName", "localhost", @@ -36,18 +35,12 @@ Describe "SSH Remoting API Tests" -Tags "Feature" { $rs = [runspacefactory]::CreateRunspace($sshConnectionInfo) $rs.Open() - - throw "No Exception!" - } - catch - { - $_.Exception.InnerException.InnerException | Should -BeOfType "System.IO.FileNotFoundException" - } + } | Should -Throw -PassThru + $e.Exception.InnerException.InnerException | Should -BeOfType "System.IO.FileNotFoundException" } It "SSHConnectionInfo should throw argument exception for invalid port (non 16bit uint)" { - try - { + $e = { $sshConnectionInfo = [System.Management.Automation.Runspaces.SSHConnectionInfo]::new( "UserName", "localhost", @@ -56,19 +49,8 @@ Describe "SSH Remoting API Tests" -Tags "Feature" { $rs = [runspacefactory]::CreateRunspace($sshConnectionInfo) $rs.Open() - - throw "No Exception!" - } - catch - { - $expectedArgumentException = $_.Exception - if ($null -ne $_.Exception.InnerException) - { - $expectedArgumentException = $_.Exception.InnerException - } - - $expectedArgumentException | Should -BeOfType "System.ArgumentException" - } + } | Should -Throw -PassThru + $e.Exception.InnerException | Should -BeOfType "System.ArgumentException" } } } diff --git a/test/powershell/engine/Remoting/SSHRemotingCmdlets.Tests.ps1 b/test/powershell/engine/Remoting/SSHRemotingCmdlets.Tests.ps1 index 312268f6d61..4141ab6c1ba 100644 --- a/test/powershell/engine/Remoting/SSHRemotingCmdlets.Tests.ps1 +++ b/test/powershell/engine/Remoting/SSHRemotingCmdlets.Tests.ps1 @@ -16,17 +16,8 @@ Describe "SSHTransport switch parameter value" -Tags 'Feature' { } It "<testName>" -TestCases $TestCasesSSHTransport { - param($scriptBlock) - try - { - & $scriptBlock - throw "Parameter argument should not be valid" - } - catch - { - $_.FullyQualifiedErrorId | Should -Match "ParameterArgumentValidationError" - } + { & $scriptBlock } | Should -Throw -ErrorId "ParameterArgumentValidationError" } } @@ -46,14 +37,6 @@ Describe "SSHConnection parameter hashtable error conditions" -Tags 'Feature' { It "<testName>" -TestCases $TestCasesSSHConnection { param ($scriptBlock) - try - { - & $scriptBlock - throw "Parameter set should not be valid" - } - catch - { - $_.FullyQualifiedErrorId | Should -Match "Argument,Microsoft.PowerShell.Commands.NewPSSessionCommand" - } + { & $scriptBlock } | Should -Throw -ErrorId "Argument,Microsoft.PowerShell.Commands.NewPSSessionCommand" } } From 472a4af11edec9147a1be37481ea09e9a116208f Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Wed, 18 Apr 2018 14:14:54 -0700 Subject: [PATCH 37/58] [Feature] ShouldBeErrorId => Should -Throw -ErrorId in Host. --- test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index f0270b14778..a0216b84413 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -839,7 +839,7 @@ dir -Recurse ` It "Input '<inputStr>' should throw in tab completion" -TestCases $testCases { param($inputStr, $expected) - $inputStr | ShouldBeErrorId $expected + $inputStr | Should -Throw -ErrorId $expected } } From 6b777381ed46dce69bd9121f20a366eb5769dc3d Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Wed, 18 Apr 2018 14:29:07 -0700 Subject: [PATCH 38/58] [Feature] try {} catch {} => Should -Throw -ErrorId in Host --- test/powershell/Host/ConsoleHost.Tests.ps1 | 50 ++++---------------- test/powershell/Host/HostUtilities.Tests.ps1 | 24 ++-------- 2 files changed, 14 insertions(+), 60 deletions(-) diff --git a/test/powershell/Host/ConsoleHost.Tests.ps1 b/test/powershell/Host/ConsoleHost.Tests.ps1 index 1a633559b2c..34d30d5dabe 100644 --- a/test/powershell/Host/ConsoleHost.Tests.ps1 +++ b/test/powershell/Host/ConsoleHost.Tests.ps1 @@ -93,35 +93,21 @@ Describe "ConsoleHost unit tests" -tags "Feature" { Context "ShellInterop" { It "Verify Parsing Error Output Format Single Shell should throw exception" { - try - { - & $powershell -outp blah -comm { $input } - Throw "Test execution should not reach here!" - } - catch - { - $_.FullyQualifiedErrorId | Should -Be "IncorrectValueForFormatParameter" - } + { & $powershell -outp blah -comm { $input } } | Should -Throw -ErrorId "IncorrectValueForFormatParameter" } It "Verify Validate Dollar Error Populated should throw exception" { $origEA = $ErrorActionPreference $ErrorActionPreference = "Stop" - try - { + $e = { $a = 1,2,3 $a | & $powershell -noprofile -command { wgwg-wrwrhqwrhrh35h3h3} - Throw "Test execution should not reach here!" - } - catch - { - $_.ToString() | Should -Match "wgwg-wrwrhqwrhrh35h3h3" - $_.FullyQualifiedErrorId | Should -Be "CommandNotFoundException" - } - finally - { - $ErrorActionPreference = $origEA - } + } | Should -Throw -PassThru + + $e.ToString() | Should -Match "wgwg-wrwrhqwrhrh35h3h3" + $e.FullyQualifiedErrorId | Should -Be "CommandNotFoundException" + + $ErrorActionPreference = $origEA } It "Verify Validate Output Format As Text Explicitly Child Single Shell does not throw" { @@ -131,15 +117,7 @@ Describe "ConsoleHost unit tests" -tags "Feature" { } It "Verify Parsing Error Input Format Single Shell should throw exception" { - try - { - & $powershell -input blah -comm { $input } - Throw "Test execution should not reach here!" - } - catch - { - $_.FullyQualifiedErrorId | Should -Be "IncorrectValueForFormatParameter" - } + { & $powershell -input blah -comm { $input } } | Should -Throw -ErrorId "IncorrectValueForFormatParameter" } } Context "CommandLine" { @@ -496,15 +474,7 @@ foo recurse $args } - try - { - recurse "args" - Throw "Incorrect exception" - } - catch - { - $_.FullyQualifiedErrorId | Should -Be "CallDepthOverflow" - } + { recurse "args" } | Should -Throw -ErrorId "CallDepthOverflow" } } diff --git a/test/powershell/Host/HostUtilities.Tests.ps1 b/test/powershell/Host/HostUtilities.Tests.ps1 index c2e8cb80867..96145b41ca7 100644 --- a/test/powershell/Host/HostUtilities.Tests.ps1 +++ b/test/powershell/Host/HostUtilities.Tests.ps1 @@ -8,29 +8,13 @@ Describe "InvokeOnRunspace method argument error handling" -tags "Feature" { } It "Null argument exception should be thrown for null PSCommand argument" { - - try - { - [System.Management.Automation.HostUtilities]::InvokeOnRunspace($null, $localRunspace) - throw "InvokeOnRunspace method did not throw expected PSArgumentNullException exception" - } - catch - { - $_.FullyQualifiedErrorId | Should -Be "PSArgumentNullException" - } + { [System.Management.Automation.HostUtilities]::InvokeOnRunspace($null, $localRunspace) } | + Should -Throw -ErrorId "PSArgumentNullException" } It "Null argument exception should be thrown for null Runspace argument" { - - try - { - [System.Management.Automation.HostUtilities]::InvokeOnRunspace($command, $null) - throw "InvokeOnRunspace method did not throw expected PSArgumentNullException exception" - } - catch - { - $_.FullyQualifiedErrorId | Should -Be "PSArgumentNullException" - } + { [System.Management.Automation.HostUtilities]::InvokeOnRunspace($command, $null) } | + Should -Throw -ErrorId "PSArgumentNullException" } } From ee282d6f45b60bbf8034b29764031989d8b549a1 Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Wed, 18 Apr 2018 14:30:49 -0700 Subject: [PATCH 39/58] [Feature] Use new Pester syntax -Parameter in Installer. --- test/powershell/Installer/WindowsInstaller.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/powershell/Installer/WindowsInstaller.Tests.ps1 b/test/powershell/Installer/WindowsInstaller.Tests.ps1 index ac8168a2f82..5b88d653afe 100644 --- a/test/powershell/Installer/WindowsInstaller.Tests.ps1 +++ b/test/powershell/Installer/WindowsInstaller.Tests.ps1 @@ -33,6 +33,6 @@ Describe "Windows Installer" -Tags "Scenario" { } } - $result | Should Not Be $null + $result | Should -Not -Be $null } } From ea6c7f68d38a754456cb917f8e0fd5aedb0650cd Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Wed, 18 Apr 2018 15:12:46 -0700 Subject: [PATCH 40/58] [Feature] ShouldBeErrorId => Should -Throw -ErrorId in Language. --- .../Classes/Scripting.Classes.Attributes.Tests.ps1 | 10 +++++----- .../Language/Operators/ComparisonOperator.Tests.ps1 | 2 +- .../Language/Operators/SplitOperator.Tests.ps1 | 2 +- .../Language/Parser/UsingNamespace.Tests.ps1 | 2 +- .../Language/Scripting/ActionPreference.Tests.ps1 | 2 +- .../NativeExecution/NativeCommandProcessor.Tests.ps1 | 2 +- .../Language/Scripting/ParameterBinding.Tests.ps1 | 8 ++++---- 7 files changed, 14 insertions(+), 14 deletions(-) diff --git a/test/powershell/Language/Classes/Scripting.Classes.Attributes.Tests.ps1 b/test/powershell/Language/Classes/Scripting.Classes.Attributes.Tests.ps1 index b659f8de2dd..c9a17bb54e0 100644 --- a/test/powershell/Language/Classes/Scripting.Classes.Attributes.Tests.ps1 +++ b/test/powershell/Language/Classes/Scripting.Classes.Attributes.Tests.ps1 @@ -260,7 +260,7 @@ Describe 'ValidateSet support a dynamically generated set' -Tag "CI" { } It 'Throw if IValidateSetValuesGenerator is not implemented' { - { Get-TestValidateSet0 -Param1 "TestString" -ErrorAction Stop } | ShouldBeErrorId "Argument" + { Get-TestValidateSet0 -Param1 "TestString" -ErrorAction Stop } | Should -Throw -ErrorId "Argument" } It 'Dynamically generated set works in C# with default (immediate) cache expire' { @@ -270,7 +270,7 @@ Describe 'ValidateSet support a dynamically generated set' -Tag "CI" { It 'Empty dynamically generated set throws in C#' { $exc = { Get-TestValidateSet5 -Param1 "TestString1" -ErrorAction Stop - } | ShouldBeErrorId "ParameterArgumentValidationError,Test.Language.TestValidateSetCommand5" + } | Should -Throw -ErrorId "ParameterArgumentValidationError,Test.Language.TestValidateSetCommand5" -PassThru $exc.Exception.InnerException.ErrorRecord.FullyQualifiedErrorId | Should -BeExactly "ValidateSetGeneratedValidValuesListIsNull" } } @@ -356,20 +356,20 @@ Describe 'ValidateSet support a dynamically generated set' -Tag "CI" { } It 'Get the appropriate error message' { - {Get-TestValidateSetPS4 -Param1 "TestStringWrong" -ErrorAction Stop} | ShouldBeErrorId "ParameterArgumentValidationError,Get-TestValidateSetPS4" + {Get-TestValidateSetPS4 -Param1 "TestStringWrong" -ErrorAction Stop} | Should -Throw -ErrorId "ParameterArgumentValidationError,Get-TestValidateSetPS4" } It 'Empty dynamically generated set throws in PowerShell script' { $exc = { Get-TestValidateSetPS5 -Param1 "TestString1" -ErrorAction Stop - } | ShouldBeErrorId "ParameterArgumentValidationError,Get-TestValidateSetPS5" + } | Should -Throw -ErrorId "ParameterArgumentValidationError,Get-TestValidateSetPS5" -PassThru $exc.Exception.InnerException.ErrorRecord.FullyQualifiedErrorId | Should -BeExactly "ValidateSetGeneratedValidValuesListIsNull" } It 'Unimplemented valid values generator type throws in PowerShell script' { { Get-TestValidateSetPS6 -Param1 "AnyTestString" -ErrorAction Stop - } | ShouldBeErrorId "TypeNotFound" + } | Should -Throw -ErrorId "TypeNotFound" } It 'IValidateSetValuesGenerator works in PowerShell module' { diff --git a/test/powershell/Language/Operators/ComparisonOperator.Tests.ps1 b/test/powershell/Language/Operators/ComparisonOperator.Tests.ps1 index 92c52641943..2c0847dee63 100644 --- a/test/powershell/Language/Operators/ComparisonOperator.Tests.ps1 +++ b/test/powershell/Language/Operators/ComparisonOperator.Tests.ps1 @@ -58,7 +58,7 @@ Describe "ComparisonOperator" -tag "CI" { @{operator = "-isnot"; type = "[foo]"; expectedError='TypeNotFound,Microsoft.PowerShell.Commands.InvokeExpressionCommand'} ) { param($operator, $type, $expectedError) - { Invoke-Expression "'Hello' $operator $type" } | ShouldBeErrorId $expectedError + { Invoke-Expression "'Hello' $operator $type" } | Should -Throw -ErrorId $expectedError } It "Should succeed in comparing type: <lhs> <operator> <rhs>" -TestCases @( diff --git a/test/powershell/Language/Operators/SplitOperator.Tests.ps1 b/test/powershell/Language/Operators/SplitOperator.Tests.ps1 index 25514c9a75a..1e508f4a47a 100644 --- a/test/powershell/Language/Operators/SplitOperator.Tests.ps1 +++ b/test/powershell/Language/Operators/SplitOperator.Tests.ps1 @@ -210,7 +210,7 @@ Describe "Split Operator" -Tags CI { } It "Binary split operator doesn't works with RegexMatch,SimpleMatch" { - { "abc" -split "B", 0, 'RegexMatch,SimpleMatch' } | ShouldBeErrorId "InvalidSplitOptionCombination" + { "abc" -split "B", 0, 'RegexMatch,SimpleMatch' } | Should -Throw -ErrorId "InvalidSplitOptionCombination" } } diff --git a/test/powershell/Language/Parser/UsingNamespace.Tests.ps1 b/test/powershell/Language/Parser/UsingNamespace.Tests.ps1 index caeb570013c..e0b7550636a 100644 --- a/test/powershell/Language/Parser/UsingNamespace.Tests.ps1 +++ b/test/powershell/Language/Parser/UsingNamespace.Tests.ps1 @@ -96,7 +96,7 @@ Describe "Using Namespace" -Tags "CI" { } It "Ambiguous type reference" { - { [ThreadState] } | ShouldBeErrorId AmbiguousTypeReference + { [ThreadState] } | Should -Throw -ErrorId AmbiguousTypeReference } It "Parameters" { diff --git a/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 b/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 index f9fbf3f5e24..3b90565e03b 100644 --- a/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 +++ b/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 @@ -144,7 +144,7 @@ Describe "Tests for (error, warning, etc) action preference" -Tags "CI" { $params += @{$switch=$true} { New-Item @params } | Should -Not -Throw $ErrorActionPreference = "Stop" - { New-Item @params } | ShouldBeErrorId "NewItemIOError,Microsoft.PowerShell.Commands.NewItemCommand" + { New-Item @params } | Should -Throw -ErrorId "NewItemIOError,Microsoft.PowerShell.Commands.NewItemCommand" Remove-Item "$testdrive\test.txt" -Force } } diff --git a/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 b/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 index 4bbef895f82..ef4898ffd75 100644 --- a/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 +++ b/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 @@ -218,6 +218,6 @@ Categories=Application; } It "Opening a file with an unregistered extension on Windows should fail" -Skip:(!$IsWindows) { - { $dllFile = "$PSHOME\System.Management.Automation.dll"; & $dllFile } | ShouldBeErrorId "NativeCommandFailed" + { $dllFile = "$PSHOME\System.Management.Automation.dll"; & $dllFile } | Should -Throw -ErrorId "NativeCommandFailed" } } diff --git a/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 b/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 index a572b74a592..634d75331cb 100644 --- a/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 +++ b/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 @@ -165,7 +165,7 @@ Describe "Tests for parameter binding" -Tags "CI" { $foo } - { get-foo -a a -b b c d } | ShouldBeErrorId 'AmbiguousParameterSet,get-foo' + { get-foo -a a -b b c d } | Should -Throw -ErrorId 'AmbiguousParameterSet,get-foo' ( get-foo -a a b c d ) -join ',' | Should -BeExactly 'b,c,d' ( get-foo -b b a c d ) -join ',' | Should -BeExactly 'a,c,d' } @@ -230,7 +230,7 @@ Describe "Tests for parameter binding" -Tags "CI" { $a } - { get-foo -a $null } | ShouldBeErrorId 'ParameterArgumentValidationErrorNullNotAllowed,get-foo' + { get-foo -a $null } | Should -Throw -ErrorId 'ParameterArgumentValidationErrorNullNotAllowed,get-foo' } @@ -272,7 +272,7 @@ Describe "Tests for parameter binding" -Tags "CI" { $a } - { get-foo -a @() } | ShouldBeErrorId 'ParameterArgumentValidationErrorEmptyArrayNotAllowed,get-foo' + { get-foo -a @() } | Should -Throw -ErrorId 'ParameterArgumentValidationErrorEmptyArrayNotAllowed,get-foo' } It 'Empty collection is allowed when allowEmptyCollection is set' { @@ -315,7 +315,7 @@ Describe "Tests for parameter binding" -Tags "CI" { $Parameter } - { get-foo 'a','b' } | ShouldBeErrorId 'ParameterArgumentTransformationError,get-foo' + { get-foo 'a','b' } | Should -Throw -ErrorId 'ParameterArgumentTransformationError,get-foo' } It "Binding array of string to array of bool should succeed" { From c8c846efcd8a9c165adf5940dfbf1ec11c793454 Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Wed, 18 Apr 2018 17:21:37 -0700 Subject: [PATCH 41/58] [Feature] try {} catch {} => Should -Throw -ErrorId in Language. --- .../Scripting.Classes.Exceptions.Tests.ps1 | 86 ++------- .../LanguageAndParser.TestFollowup.Tests.ps1 | 12 +- .../Language/Parser/Parser.Tests.ps1 | 176 +++--------------- .../Language/Parser/UsingAssembly.Tests.ps1 | 11 +- .../Scripting/ActionPreference.Tests.ps1 | 63 ++----- .../CheckRestrictedlanguage.Tests.ps1 | 45 +---- .../Scripting/CommonParameters.Tests.ps1 | 10 +- .../Debugging/DebuggerScriptTests.Tests.ps1 | 14 +- .../DeserializedTypeConversion.Tests.ps1 | 19 +- .../Scripting/Dynamicparameters.Tests.ps1 | 7 +- .../Language/Scripting/Generics.Tests.ps1 | 10 +- ...htableToPSCustomObjectConversion.Tests.ps1 | 36 ++-- .../Scripting/ParameterBinding.Tests.ps1 | 39 +--- .../Language/Scripting/Requires.Tests.ps1 | 12 +- 14 files changed, 97 insertions(+), 443 deletions(-) diff --git a/test/powershell/Language/Classes/Scripting.Classes.Exceptions.Tests.ps1 b/test/powershell/Language/Classes/Scripting.Classes.Exceptions.Tests.ps1 index f38d2fda1c0..a27f05eefc4 100644 --- a/test/powershell/Language/Classes/Scripting.Classes.Exceptions.Tests.ps1 +++ b/test/powershell/Language/Classes/Scripting.Classes.Exceptions.Tests.ps1 @@ -235,39 +235,23 @@ Describe "Exception error position" -Tags "CI" { } It "Setting a property that doesn't exist" { - try { - [MSFT_3090412]::f1() - throw "f1 should have thrown" - } catch { - $_.InvocationInfo.Line | Should -Match ([regex]::Escape('[MSFT_3090412]::bar = 42')) - } + $e = { [MSFT_3090412]::f1() } | Should -Throw -PassThru -ErrorId 'PropertyAssignmentException' + $e.InvocationInfo.Line | Should -Match ([regex]::Escape('[MSFT_3090412]::bar = 42')) } It "Throwing an exception" { - try { - [MSFT_3090412]::f2() - throw "f2 should have thrown" - } catch { - $_.InvocationInfo.Line | Should -Match ([regex]::Escape('throw "an error in f2"')) - } + $e = { [MSFT_3090412]::f2() } | Should -Throw -PassThru -ErrorId 'an error in f2' + $e.InvocationInfo.Line | Should -Match ([regex]::Escape('throw "an error in f2"')) } It "Calling a .Net method that throws" { - try { - [MSFT_3090412]::f3() - throw "f3 should have thrown" - } catch { - $_.InvocationInfo.Line | Should -Match ([regex]::Escape('"".Substring(0, 10)')) - } + $e = { [MSFT_3090412]::f3() } | Should -Throw -PassThru -ErrorId 'ArgumentOutOfRangeException' + $e.InvocationInfo.Line | Should -Match ([regex]::Escape('"".Substring(0, 10)')) } It "Terminating error" { - try { - [MSFT_3090412]::f4() - throw "f4 should have thrown" - } catch { - $_.InvocationInfo.Line | Should -Match ([regex]::Escape('dir nosuchfile -ea Stop')) - } + $e = { [MSFT_3090412]::f4() } | Should -Throw -PassThru -ErrorId 'PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand' + $e.InvocationInfo.Line | Should -Match ([regex]::Escape('dir nosuchfile -ea Stop')) } } @@ -295,56 +279,26 @@ Describe "Exception from initializer" -Tags "CI" { } It "instance member w/ ctor" { - try { - [MSFT_6397334a]::new() - throw "[MSFT_6397334a]::new() should have thrown" - } - catch - { - $e = $_ - $e.FullyQualifiedErrorId | Should -BeExactly 'InvalidCastFromStringToInteger' - $e.InvocationInfo.Line | Should -Match 'a = "zz"' - } + $e = { [MSFT_6397334a]::new() } | Should -Throw -ErrorId 'InvalidCastFromStringToInteger' -PassThru + $e.InvocationInfo.Line | Should -Match 'a = "zz"' } It "instance member w/o ctor" { - try { - [MSFT_6397334b]::new() - throw "[MSFT_6397334b]::new() should have thrown" - } - catch - { - $e = $_ - $e.FullyQualifiedErrorId | Should -BeExactly 'InvalidCastFromStringToInteger' - $e.InvocationInfo.Line | Should -Match 'a = "zz"' - } + $e = { [MSFT_6397334b]::new() } | Should -Throw -ErrorId 'InvalidCastFromStringToInteger' -PassThru + $e.InvocationInfo.Line | Should -Match 'a = "zz"' } It "static member w/ ctor" { - try { - $null = [MSFT_6397334c]::a - throw "No Exception!" - } - catch - { - $_.Exception | Should -BeOfType System.TypeInitializationException - $e = $_.Exception.InnerException.InnerException.ErrorRecord - $e.FullyQualifiedErrorId | Should -BeExactly 'InvalidCastFromStringToInteger' - $e.InvocationInfo.Line | Should -Match 'a = "zz"' - } + $e = { $null = [MSFT_6397334c]::a } | Should -Throw -PassThru + $e.Exception | Should -BeOfType 'System.TypeInitializationException' + $e.Exception.InnerException.ErrorRecord.FullyQualifiedErrorId | Should -BeExactly 'InvalidCastFromStringToInteger' + $e.Exception.InnerException.InnerException.ErrorRecord.InvocationInfo.Line | Should -Match 'a = "zz"' } It "static member w/o ctor" { - try { - $null = [MSFT_6397334d]::a - throw "No Exception!" - } - catch - { - $_.Exception | Should -BeOfType System.TypeInitializationException - $e = $_.Exception.InnerException.InnerException.ErrorRecord - $e.FullyQualifiedErrorId | Should -BeExactly 'InvalidCastFromStringToInteger' - $e.InvocationInfo.Line | Should -Match 'a = "zz"' - } + $e = { $null = [MSFT_6397334d]::a } | Should -Throw -PassThru + $e.Exception | Should -BeOfType System.TypeInitializationException + $e.Exception.InnerException.InnerException.ErrorRecord.FullyQualifiedErrorId | Should -BeExactly 'InvalidCastFromStringToInteger' + $e.Exception.InnerException.InnerException.ErrorRecord.InvocationInfo.Line | Should -Match 'a = "zz"' } } diff --git a/test/powershell/Language/Parser/LanguageAndParser.TestFollowup.Tests.ps1 b/test/powershell/Language/Parser/LanguageAndParser.TestFollowup.Tests.ps1 index 39d9d23eaac..8860d492c24 100644 --- a/test/powershell/Language/Parser/LanguageAndParser.TestFollowup.Tests.ps1 +++ b/test/powershell/Language/Parser/LanguageAndParser.TestFollowup.Tests.ps1 @@ -172,21 +172,15 @@ Describe "Assign readonly/constant variables" -Tags "CI" { Describe "Attribute error position" -Tags "CI" { It "Ambiguous overloads" { - try - { + $e = { & { param( [ValidateNotNull(1,2,3,4)] $param ) } - throw "Should have thrown" - } - catch - { - $_.InvocationInfo.Line | Should -Match ValidateNotNull - $_.FullyQualifiedErrorId | Should -Be MethodCountCouldNotFindBest - } + } | Should -Throw -PassThru -ErrorId 'MethodCountCouldNotFindBest' + $e.InvocationInfo.Line | Should -Match ValidateNotNull } } diff --git a/test/powershell/Language/Parser/Parser.Tests.ps1 b/test/powershell/Language/Parser/Parser.Tests.ps1 index 0824a6dc870..d9921c63ab3 100644 --- a/test/powershell/Language/Parser/Parser.Tests.ps1 +++ b/test/powershell/Language/Parser/Parser.Tests.ps1 @@ -138,33 +138,15 @@ Describe "ParserTests (admin\monad\tests\monad\src\engine\core\ParserTests.cs)" } It "Throws a syntax error when parsing a string without a closing quote. (line 164)" { - try { - ExecuteCommand '"This is a test' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "IncompleteParseException" - } + { ExecuteCommand '"This is a test' } | Should -Throw -ErrorId "IncompleteParseException" } It "Throws an error if an open parenthesis is not closed (line 176)" { - try { - ExecuteCommand "(" - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "IncompleteParseException" - } + { ExecuteCommand "(" } | Should -Throw -ErrorId "IncompleteParseException" } It "Throws an exception if the the first statement starts with an empty pipe element (line 188)" { - try { - ExecuteCommand "| get-location" - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand "| get-location" } | Should -Throw -ErrorId "ParseException" } It "Throws an CommandNotFoundException exception if using a label in front of an if statement is not allowed. (line 225)"{ @@ -175,51 +157,21 @@ Describe "ParserTests (admin\monad\tests\monad\src\engine\core\ParserTests.cs)" } It "Pipe an expression into a value expression. (line 237)" { - try { - ExecuteCommand "testcmd-parserbvt | 3" - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand "testcmd-parserbvt | 3" } | Should -Throw -ErrorId "ParseException" - try { - ExecuteCommand "testcmd-parserbvt | $(1 + 1)" - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand "testcmd-parserbvt | $(1 + 1)" } | Should -Throw -ErrorId "ParseException" - try { - ExecuteCommand "testcmd-parserbvt | 'abc'" - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand "testcmd-parserbvt | 'abc'" } | Should -Throw -ErrorId "ParseException" } It "Throws when you pipe into a value expression (line 238)" { foreach($command in "1;2;3|3",'1;2;3|$(1+1)',"1;2;3|'abc'") { - try { - ExecuteCommand $command - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand $command } | Should -Throw -ErrorId "ParseException" } } It "Throws an incomplete parse exception when a comma follows an expression (line 247)" { - try { - ExecuteCommand "(1+ 1)," - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "IncompleteParseException" - } + { ExecuteCommand "(1+ 1)," } | Should -Throw -ErrorId "IncompleteParseException" } It "Test that invoke has a higher precedence for a script than for an executable. (line 279)" { @@ -469,83 +421,35 @@ foo``u{2195}abc } It "This test will check that it is a syntax error to use if without a code block. (line 1141)" { - try { - ExecuteCommand 'if ("true")' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "IncompleteParseException" - } + { ExecuteCommand 'if ("true")' } | Should -Throw -ErrorId "IncompleteParseException" } It "This test will check that it is a syntax error if the if condition is not complete. (line 1150)" { - try { - ExecuteCommand 'if (' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "IncompleteParseException" - } + { ExecuteCommand 'if (' } | Should -Throw -ErrorId "IncompleteParseException" } It "This test will check that it is a syntax error to have an if condition without parentheses. (line 1159)" { - try { - ExecuteCommand 'if "true" { 1} else {2}' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand 'if "true" { 1} else {2}' } | Should -Throw -ErrorId "ParseException" } It "This test will check that the parser throws a syntax error when the if condition is missing the closing parentheses. (line 1168)" { - try { - ExecuteCommand 'if ("true" { 1};' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand 'if ("true" { 1};' } | Should -Throw -ErrorId "ParseException" } It "This test will check that it is a syntax error to have an else keyword without the corresponding code block. (line 1177)" { - try { - ExecuteCommand 'if ("true") {1} else' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "IncompleteParseException" - } + { ExecuteCommand 'if ("true") {1} else' } | Should -Throw -ErrorId "IncompleteParseException" } It "This test will check that the parser throws a syntax error when a foreach loop is not complete. (line 1238)" { - try { - ExecuteCommand '$count=0;$files = $(get-childitem / -filter *.txt );foreach ($i ;$count' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand '$count=0;$files = $(get-childitem / -filter *.txt );foreach ($i ;$count' } | Should -Throw -ErrorId "ParseException" } It "This test will check that the parser throws a syntax error if the foreach loop is not complete. (line 1248)" { - try { - ExecuteCommand '$count=0;$files = $(get-childitem / -filter *.txt );foreach ($i in ;$count' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand '$count=0;$files = $(get-childitem / -filter *.txt );foreach ($i in ;$count' } | Should -Throw -ErrorId "ParseException" } It "This will test that the parser throws a syntax error if the foreach loop is missing a closing parentheses. (line 1258)" { - try { - ExecuteCommand '$count=0;$files = $(get-childitem / -filter *.txt );foreach ($i in $files ;$count' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand '$count=0;$files = $(get-childitem / -filter *.txt );foreach ($i in $files ;$count' } | Should -Throw -ErrorId "ParseException" } It "Test that if an exception is thrown from the try block it will be caught in the appropropriate catch block and that the finally block will run regardless of whether an exception is thrown. (line 1317)" { @@ -782,33 +686,15 @@ foo``u{2195}abc } It "Test that an incomplete parse exception is thrown if the array is unfinished. (line 2473)"{ - try { - ExecuteCommand '1,2,' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "IncompleteParseException" - } + { ExecuteCommand '1,2,' } | Should -Throw -ErrorId "IncompleteParseException" } It "Test that the unary comma is not valid in cmdlet parameters. (line 2482)"{ - try { - ExecuteCommand 'write-output 2,,1' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand 'write-output 2,,1' } | Should -Throw -ErrorId "ParseException" } It 'Test that "$var:" will expand to nothing inside a string. (line 2551)'{ - try { - ExecuteCommand '"$var:"' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand '"$var:"' } | Should -Throw -ErrorId "ParseException" } It "Tests the assignment to a read-only property (line 2593)"{ @@ -824,23 +710,11 @@ foo``u{2195}abc } It 'Tests the parser response to ArrayName[. (line 2678)'{ - try { - ExecuteCommand '$A=$(testcmd-parserBVT -returntype array); $A[ ;' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand '$A=$(testcmd-parserBVT -returntype array); $A[ ;' } | Should -Throw -ErrorId "ParseException" } It 'Tests the parser response to ArrayName[]. (line 2687)'{ - try { - ExecuteCommand '$A=$(testcmd-parserBVT -returntype array); $A[] ;' - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand '$A=$(testcmd-parserBVT -returntype array); $A[] ;' } | Should -Throw -ErrorId "ParseException" } #Issue#1430 @@ -902,13 +776,7 @@ foo``u{2195}abc } It "A here string must have one line (line 3266)" { - try { - ExecuteCommand "@`"`"@" - throw "Execution OK" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParseException" - } + { ExecuteCommand "@`"`"@" } | Should -Throw -ErrorId "ParseException" } It "A here string should not throw on '`$herestr=@`"``n'`"'``n`"@'" { diff --git a/test/powershell/Language/Parser/UsingAssembly.Tests.ps1 b/test/powershell/Language/Parser/UsingAssembly.Tests.ps1 index 42b33d9ea29..7eda4785887 100644 --- a/test/powershell/Language/Parser/UsingAssembly.Tests.ps1 +++ b/test/powershell/Language/Parser/UsingAssembly.Tests.ps1 @@ -69,15 +69,8 @@ public class ABC {} } It "reports runtime error about non-existing assembly with relative path" { - $failed = $true - try { - [scriptblock]::Create("using assembly .\NonExistingAssembly.dll") - $failed = $false - } catch { - $_.FullyQualifiedErrorId | Should -Be 'ParseException' - $_.Exception.InnerException.ErrorRecord.FullyQualifiedErrorId | Should -Be 'ErrorLoadingAssembly' - } - $failed | Should -BeTrue + $e = { [scriptblock]::Create("using assembly .\NonExistingAssembly.dll") } | Should -Throw -ErrorId 'ParseException' -PassThru + $e.Exception.InnerException.ErrorRecord.FullyQualifiedErrorId | Should -Be 'ErrorLoadingAssembly' } #> It "Assembly loaded at runtime" -pending { diff --git a/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 b/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 index 3b90565e03b..f4fbcbc0413 100644 --- a/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 +++ b/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 @@ -34,29 +34,23 @@ Describe "Tests for (error, warning, etc) action preference" -Tags "CI" { } It 'action preference of Ignore cannot be set as a preference variable' { - try { + $e = { $GLOBAL:errorActionPreference = "Ignore" Get-Process -Name asdfasdfasdf - Throw "Exception expected, execution should not have reached here" - } catch { - $_.CategoryInfo.Reason | Should -BeExactly 'NotSupportedException' - } finally { - $GLOBAL:errorActionPreference = $orgin - } + } | Should -Throw -ErrorId 'System.NotSupportedException,Microsoft.PowerShell.Commands.GetProcessCommand' -PassThru + $e.CategoryInfo.Reason | Should -BeExactly 'NotSupportedException' + $GLOBAL:errorActionPreference = $orgin } It 'action preference of Suspend cannot be set as a preference variable' { - try { - $GLOBAL:errorActionPreference = "Suspend" - Get-Process -Name asdfasdfasdf - Throw "Exception expected, execution should not have reached here" - } catch { - $_.CategoryInfo.Reason | Should -BeExactly 'ArgumentTransformationMetadataException' - } - finally { - $GLOBAL:errorActionPreference = $orgin - } + $e = { + $GLOBAL:errorActionPreference = "Suspend" + Get-Process -Name asdfasdfasdf + } | Should -Throw -ErrorId 'RuntimeException' -PassThru + $e.CategoryInfo.Reason | Should -BeExactly 'ArgumentTransformationMetadataException' + + $GLOBAL:errorActionPreference = $orgin } It 'enum disambiguation works' { @@ -78,35 +72,15 @@ Describe "Tests for (error, warning, etc) action preference" -Tags "CI" { "Hello" } - try - { - MyHelperFunction -ErrorAction Suspend - Throw "Exception expected, execution should not have reached here" - } catch { - $_.FullyQualifiedErrorId | Should -BeExactly "ParameterBindingFailed,MyHelperFunction" - } + { MyHelperFunction -ErrorAction Suspend } | Should -Throw -ErrorId "ParameterBindingFailed,MyHelperFunction" } It 'ErrorAction = Suspend does not work on cmdlets' { - try - { - Get-Process -ErrorAction Suspend - Throw "Exception expected, execution should not have reached here" - } - catch { - $_.FullyQualifiedErrorId | Should -BeExactly "ParameterBindingFailed,Microsoft.PowerShell.Commands.GetProcessCommand" - } + { Get-Process -ErrorAction Suspend } | Should -Throw -ErrorId "ParameterBindingFailed,Microsoft.PowerShell.Commands.GetProcessCommand" } It 'WarningAction = Suspend does not work' { - try - { - Get-Process -WarningAction Suspend - Throw "Exception expected, execution should not have reached here" - } - catch { - $_.FullyQualifiedErrorId | Should -BeExactly "ParameterBindingFailed,Microsoft.PowerShell.Commands.GetProcessCommand" - } + { Get-Process -WarningAction Suspend } | Should -Throw -ErrorId "ParameterBindingFailed,Microsoft.PowerShell.Commands.GetProcessCommand" } #issue 2076 @@ -118,15 +92,8 @@ Describe "Tests for (error, warning, etc) action preference" -Tags "CI" { $params | ForEach-Object { $input=@{'InputObject' = 'Test';$_='Suspend'} - - try { - Write-Output @input - } catch { - $_.FullyQualifiedErrorId | Should -BeExactly "ParameterBindingFailed,Microsoft.PowerShell.Commands.WriteOutputCommand" - $num++ - } + { Write-Output @input } | Should -Throw -ErrorId "ParameterBindingFailed,Microsoft.PowerShell.Commands.WriteOutputCommand" } - $num | Should -Be 2 } It '<switch> does not take precedence over $ErrorActionPreference' -TestCases @( diff --git a/test/powershell/Language/Scripting/CheckRestrictedlanguage.Tests.ps1 b/test/powershell/Language/Scripting/CheckRestrictedlanguage.Tests.ps1 index 11c988af65f..ab2ab662030 100644 --- a/test/powershell/Language/Scripting/CheckRestrictedlanguage.Tests.ps1 +++ b/test/powershell/Language/Scripting/CheckRestrictedlanguage.Tests.ps1 @@ -25,17 +25,7 @@ Describe "Test restricted language check method on scriptblocks" -Tags "CI" { } It 'Check default variables' { - - try - { - {2+$a}.CheckRestrictedLanguage($null, $null, $false) - Throw "Exception expected, execution should not have reached here" - } - catch - { - $_.FullyQualifiedErrorId | Should -BeExactly 'ParseException' - } - + { {2+$a}.CheckRestrictedLanguage($null, $null, $false) } | Should -Throw -ErrorId 'ParseException' } It 'Check union of default + one allowed variables' { @@ -54,29 +44,11 @@ Describe "Test restricted language check method on scriptblocks" -Tags "CI" { } It 'Check union of default + one disallowed variables' { - - try - { - { $a + $b + $c }.CheckRestrictedLanguage($null, (list a b), $false) # fail - Throw "Exception expected, execution should not have reached here" - } - catch - { - $_.FullyQualifiedErrorId | Should -BeExactly 'ParseException' - } + { { $a + $b + $c }.CheckRestrictedLanguage($null, (list a b), $false) } | Should -Throw -ErrorId 'ParseException' } It 'Check union of default + one allowed variable and but not allow environment variable' { - - try - { - { 2 + $a + $env:foo }.CheckRestrictedLanguage($null, (list a), $false) # fail - Throw "Exception expected, execution should not have reached here" - } - catch - { - $_.FullyQualifiedErrorId | Should -BeExactly 'ParseException' - } + { { 2 + $a + $env:foo }.CheckRestrictedLanguage($null, (list a), $false) } | Should -Throw -ErrorId 'ParseException' } It 'Check union of default + one allowed variable name and allow environment variable ' { @@ -90,16 +62,7 @@ Describe "Test restricted language check method on scriptblocks" -Tags "CI" { } It 'Check for restricted commands' { - - try - { - {get-date}.CheckRestrictedLangauge($null, $null, $false) - Throw "Exception expected, execution should not have reached here" - } - catch - { - $_.FullyQualifiedErrorId | Should -BeExactly 'MethodNotFound' - } + { {get-date}.CheckRestrictedLangauge($null, $null, $false) } | Should -Throw -ErrorId 'MethodNotFound' } It 'Check for allowed commands and variables' { diff --git a/test/powershell/Language/Scripting/CommonParameters.Tests.ps1 b/test/powershell/Language/Scripting/CommonParameters.Tests.ps1 index 955e922786b..dce1c1e3d31 100644 --- a/test/powershell/Language/Scripting/CommonParameters.Tests.ps1 +++ b/test/powershell/Language/Scripting/CommonParameters.Tests.ps1 @@ -137,14 +137,8 @@ Describe "Common parameters support for script cmdlets" -Tags "CI" { [void] $ps.AddScript($script + $command) $asyncResult = $ps.BeginInvoke() - try - { - $ps.EndInvoke($asyncResult) - Throw "Exception expected, execution should not have reached here" - } - catch { - $_.FullyQualifiedErrorId | Should -BeExactly "ActionPreferenceStopException" - } # Exception: "Command execution stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: error foo" + { $ps.EndInvoke($asyncResult) } | Should -Throw -ErrorId "ActionPreferenceStopException" + # Exception: "Command execution stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: error foo" # BUG in runspace api. #$ps.error.count | Should Be 1 diff --git a/test/powershell/Language/Scripting/Debugging/DebuggerScriptTests.Tests.ps1 b/test/powershell/Language/Scripting/Debugging/DebuggerScriptTests.Tests.ps1 index bcac808cee8..2eb919d9a7e 100644 --- a/test/powershell/Language/Scripting/Debugging/DebuggerScriptTests.Tests.ps1 +++ b/test/powershell/Language/Scripting/Debugging/DebuggerScriptTests.Tests.ps1 @@ -278,18 +278,8 @@ Describe "Unit tests for various script breakpoints" -Tags "CI" { # function VerifyException([ScriptBlock] $command, [string] $exception) { - try - { - & $command - - throw "No Exception!" - } - catch - { - It "Script failed expected exception '${command}'" { - $_.Exception.GetType().Name | Should -Be $exception - } - } + $e = { & $command } | Should -Throw -PassThru + $e.Exception.GetType().Name | Should -Be $exception } # diff --git a/test/powershell/Language/Scripting/DeserializedTypeConversion.Tests.ps1 b/test/powershell/Language/Scripting/DeserializedTypeConversion.Tests.ps1 index c848028454b..7960fe2ba4a 100644 --- a/test/powershell/Language/Scripting/DeserializedTypeConversion.Tests.ps1 +++ b/test/powershell/Language/Scripting/DeserializedTypeConversion.Tests.ps1 @@ -144,15 +144,7 @@ Describe "Tests conversion of deserialized types to original type using object p } It 'Type casts should fail.' { - - try - { - $tc3 = [test3]$dst3 - Throw "Exception expected, execution should not have reached here" - } - catch { - $_.FullyQualifiedErrorId | Should -BeExactly 'InvalidCastConstructorException' - } + { $tc3 = [test3]$dst3 } | Should -Throw -ErrorId 'InvalidCastConstructorException' } It 'Parameter bindings should fail.' { @@ -167,14 +159,7 @@ Describe "Tests conversion of deserialized types to original type using object p $test | Format-List | Out-String } - try - { - test-3 $dst3 - Throw "Exception expected, execution should not have reached here" - } - catch { - $_.FullyQualifiedErrorId | Should -BeExactly 'ParameterArgumentTransformationError,test-3' - } + { test-3 $dst3 } | Should -Throw -ErrorId 'ParameterArgumentTransformationError,test-3' } } diff --git a/test/powershell/Language/Scripting/Dynamicparameters.Tests.ps1 b/test/powershell/Language/Scripting/Dynamicparameters.Tests.ps1 index 525dcc7296b..1c17a467ade 100644 --- a/test/powershell/Language/Scripting/Dynamicparameters.Tests.ps1 +++ b/test/powershell/Language/Scripting/Dynamicparameters.Tests.ps1 @@ -64,12 +64,7 @@ Describe "Dynamic parameter support in script cmdlets." -Tags "CI" { } It "When the dynamic parameter is not available, and raises an error when specified" { - try { - foo-bar -path def -dp1 42 - Throw "Exception expected, execution should not have reached here" - } catch { - $_.FullyQualifiedErrorId | Should -BeExactly "NamedParameterNotFound,foo-bar" - } + { foo-bar -path def -dp1 42 } | Should -Throw -ErrorId "NamedParameterNotFound,foo-bar" } It "No dynamic parameter shouldn't cause an errr " { diff --git a/test/powershell/Language/Scripting/Generics.Tests.ps1 b/test/powershell/Language/Scripting/Generics.Tests.ps1 index 42af8395e2e..e3843256953 100644 --- a/test/powershell/Language/Scripting/Generics.Tests.ps1 +++ b/test/powershell/Language/Scripting/Generics.Tests.ps1 @@ -61,14 +61,8 @@ Describe "Generics support" -Tags "CI" { # The error message for a generic that doesn't meet the constraints should mention which # argument failed. - $ex = $null - try { - [nullable[object]] - Throw "Exception expected, execution should not have reached here" - } catch { - $_.FullyQualifiedErrorId | Should -BeExactly 'TypeNotFoundWithMessage' - $_ | Should -Match "\[T\]" - } + $e = { [nullable[object]] } | Should -Throw -ErrorId 'TypeNotFoundWithMessage' -PassThru + $e | Should -Match "\[T\]" } It 'Array type works properly' -skip:$IsCoreCLR{ diff --git a/test/powershell/Language/Scripting/HashtableToPSCustomObjectConversion.Tests.ps1 b/test/powershell/Language/Scripting/HashtableToPSCustomObjectConversion.Tests.ps1 index 745497c4c0d..11fb9004c5e 100644 --- a/test/powershell/Language/Scripting/HashtableToPSCustomObjectConversion.Tests.ps1 +++ b/test/powershell/Language/Scripting/HashtableToPSCustomObjectConversion.Tests.ps1 @@ -99,20 +99,14 @@ Describe "Tests for hashtable to PSCustomObject conversion" -Tags "CI" { It '<Name>' -TestCases:$testData1 { param ($Name, $Cmd, $ErrorID, $InnerException) - try + $e = { Invoke-Expression $Cmd } | Should -Throw -PassThru + + if($InnerException) { - Invoke-Expression $Cmd - Throw "Exception expected, execution should not have reached here" - } catch { - - if($InnerException) - { - $_.Exception.InnerException.ErrorRecord.FullyQualifiedErrorId | Should -BeExactly $ErrorID - } - else { - $_.FullyQualifiedErrorId | Should -BeExactly $ErrorID - } - } + $e.Exception.InnerException.ErrorRecord.FullyQualifiedErrorId | Should -BeExactly $ErrorID + } else { + $e.FullyQualifiedErrorId | Should -BeExactly $ErrorID + } } It 'Creating an object of an existing type from hashtable should succeed' { @@ -139,20 +133,12 @@ Describe "Tests for hashtable to PSCustomObject conversion" -Tags "CI" { $obj.PSTypeNames[0] | Should -BeExactly 'System.Object' } It "new-object should fail to create object for System.Management.Automation.PSCustomObject" { - - $errorObj = $null $obj = $null - $ht = @{one=1;two=2} - try - { - $obj = New-Object System.Management.Automation.PSCustomObject -property $ht - } - catch - { - $errorObj = $_ - } + $ht = @{one=1;two=2} + + { $obj = New-Object System.Management.Automation.PSCustomObject -property $ht } | + Should -Throw -ErrorId "CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand" $obj | Should -BeNullOrEmpty - $errorObj.FullyQualifiedErrorId | Should -BeExactly "CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand" } } diff --git a/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 b/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 index 634d75331cb..a0dc9c1d669 100644 --- a/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 +++ b/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 @@ -420,16 +420,9 @@ Describe "Tests for parameter binding" -Tags "CI" { param([ValidateScript({$_ -gt 2}, ErrorMessage = "Item '{0}' failed '{1}' validation")] $p) $p } - $errMsg = '' - try - { - get-fooi -p 2 - } - catch - { - $errMsg = $_.Exception.Message - } - $errMsg | Should -BeExactly "Cannot validate argument on parameter 'p'. Item '2' failed '`$_ -gt 2' validation" + + $err = { get-fooi -p 2 } | Should -Throw -ErrorId 'ParameterArgumentValidationError,get-fooi' -PassThru + $err.Exception.Message | Should -BeExactly "Cannot validate argument on parameter 'p'. Item '2' failed '`$_ -gt 2' validation" } It "ValidatePattern can use custom ErrorMessage" { @@ -439,16 +432,9 @@ Describe "Tests for parameter binding" -Tags "CI" { param([ValidatePattern("\s+", ErrorMessage = "Item '{0}' failed '{1}' regex")] $p) $p } - $errMsg = '' - try - { - get-fooj -p 2 - } - catch - { - $errMsg = $_.Exception.Message - } - $errMsg | Should -BeExactly "Cannot validate argument on parameter 'p'. Item '2' failed '\s+' regex" + + $err = { get-fooj -p 2 } | Should -Throw -ErrorId 'ParameterArgumentValidationError,get-fooj' -PassThru + $err.Exception.Message | Should -BeExactly "Cannot validate argument on parameter 'p'. Item '2' failed '\s+' regex" } It "ValidateSet can use custom ErrorMessage" { @@ -456,17 +442,10 @@ Describe "Tests for parameter binding" -Tags "CI" { { param([ValidateSet('A', 'B', 'C', IgnoreCase=$false, ErrorMessage="Item '{0}' is not in '{1}'")] $p) } - $errMsg = '' - try - { - get-fook -p 2 - } - catch - { - $errMsg = $_.Exception.Message - } + + $err = { get-fook -p 2 } | Should -Throw -ErrorId 'ParameterArgumentValidationError,get-fook' -PassThru $set = 'A','B','C' -join [Globalization.CultureInfo]::CurrentUICulture.TextInfo.ListSeparator - $errMsg | Should -BeExactly "Cannot validate argument on parameter 'p'. Item '2' is not in '$set'" + $err.Exception.Message | Should -BeExactly "Cannot validate argument on parameter 'p'. Item '2' is not in '$set'" } } diff --git a/test/powershell/Language/Scripting/Requires.Tests.ps1 b/test/powershell/Language/Scripting/Requires.Tests.ps1 index c7bcd051fd6..6d28a1d25d7 100644 --- a/test/powershell/Language/Scripting/Requires.Tests.ps1 +++ b/test/powershell/Language/Scripting/Requires.Tests.ps1 @@ -15,16 +15,8 @@ Describe "Requires tests" -Tags "CI" { It "throws ParserException - <testname>" -TestCases $testcases { param($command) - try - { - [scriptblock]::Create($command) - throw "'$command' should have thrown ParserError" - } - catch - { - $_.FullyQualifiedErrorId | Should -BeExactly "ParseException" - } + { [scriptblock]::Create($command) } | Should -Throw -ErrorId "ParseException" } } +} -} \ No newline at end of file From e3383f0c86194cb7632fc6197626a14dc9d4904d Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Wed, 18 Apr 2018 18:02:44 -0700 Subject: [PATCH 42/58] [Feature] try {} catch {} => Should -Throw -ErrorId in Management. --- .../Clear-Content.Tests.ps1 | 75 +++++-------------- .../Copy.Item.Tests.ps1 | 68 ++++------------- .../FileSystem.Tests.ps1 | 52 +++---------- .../Get-Content.Tests.ps1 | 19 ++--- .../Get-Service.Tests.ps1 | 18 +---- .../Join-Path.Tests.ps1 | 8 +- 6 files changed, 59 insertions(+), 181 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Clear-Content.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Clear-Content.Tests.ps1 index f4e1d02385a..b21a744a057 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Clear-Content.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Clear-Content.Tests.ps1 @@ -97,87 +97,50 @@ Describe "Clear-Content cmdlet tests" -Tags "CI" { } It "the '-Stream' dynamic parameter should not be visible to get-command in the function provider" { - try { - Push-Location -Path function: - Get-Command Clear-Content -Stream $streamName - throw "ExpectedExceptionNotDelivered" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "NamedParameterNotFound,Microsoft.PowerShell.Commands.GetCommandCommand" - } - finally { - Pop-Location - } + Push-Location -Path function: + { Get-Command Clear-Content -Stream $streamName } | + Should -Throw -ErrorId "NamedParameterNotFound,Microsoft.PowerShell.Commands.GetCommandCommand" + Pop-Location } } Context "Proper errors should be delivered when bad locations are specified" { It "should throw `"Cannot bind argument to parameter 'Path'`" when -Path is `$null" { - try { - Clear-Content -Path $null -ErrorAction Stop - throw "expected exception was not delivered" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ClearContentCommand" - } + { Clear-Content -Path $null -ErrorAction Stop } | + Should -Throw -ErrorId "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ClearContentCommand" } #[BugId(BugDatabase.WindowsOutOfBandReleases, 903880)] It "should throw `"Cannot bind argument to parameter 'Path'`" when -Path is `$()" { - try { - Clear-Content -Path $() -ErrorAction Stop - throw "expected exception was not delivered" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ClearContentCommand" - } + { Clear-Content -Path $() -ErrorAction Stop } | + Should -Throw -ErrorId "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ClearContentCommand" } #[DRT][BugId(BugDatabase.WindowsOutOfBandReleases, 906022)] It "should throw 'PSNotSupportedException' when you clear-content to an unsupported provider" { $functionName = Get-NonExistantFunctionName $null = New-Item -Path function:$functionName -Value { 1 } - try { - Clear-Content -Path function:$functionName -ErrorAction Stop - throw "Expected exception was not thrown" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "NotSupported,Microsoft.PowerShell.Commands.ClearContentCommand" - } + { Clear-Content -Path function:$functionName -ErrorAction Stop } | + Should -Throw -ErrorId "NotSupported,Microsoft.PowerShell.Commands.ClearContentCommand" } It "should throw FileNotFound error when referencing a non-existant file" { - try { - $badFile = "TestDrive:/badfilename.txt" - Clear-Content -Path $badFile -ErrorAction Stop - throw "ExpectedExceptionNotDelivered" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "PathNotFound,Microsoft.PowerShell.Commands.ClearContentCommand" - } + $badFile = "TestDrive:/badfilename.txt" + { Clear-Content -Path $badFile -ErrorAction Stop } | + Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.ClearContentCommand" } It "should throw DriveNotFound error when referencing a non-existant drive" { - try { - $badDrive = "{0}:/file.txt" -f (Get-NonExistantDriveName) - Clear-Content -Path $badDrive -ErrorAction Stop - throw "ExpectedExceptionNotDelivered" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "DriveNotFound,Microsoft.PowerShell.Commands.ClearContentCommand" - } + $badDrive = "{0}:/file.txt" -f (Get-NonExistantDriveName) + { Clear-Content -Path $badDrive -ErrorAction Stop } | + Should -Throw -ErrorId "DriveNotFound,Microsoft.PowerShell.Commands.ClearContentCommand" } # we'll use a provider qualified path to produce this error It "should throw ProviderNotFound error when referencing a non-existant provider" { - try { - $badProviderPath = "{0}::C:/file.txt" -f (Get-NonExistantProviderName) - Clear-Content -Path $badProviderPath -ErrorAction Stop - throw "ExpectedExceptionNotDelivered" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ProviderNotFound,Microsoft.PowerShell.Commands.ClearContentCommand" - } + $badProviderPath = "{0}::C:/file.txt" -f (Get-NonExistantProviderName) + { Clear-Content -Path $badProviderPath -ErrorAction Stop } | + Should -Throw -ErrorId "ProviderNotFound,Microsoft.PowerShell.Commands.ClearContentCommand" } } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Copy.Item.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Copy.Item.Tests.ps1 index 0471d1afe8c..ffed38232cc 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Copy.Item.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Copy.Item.Tests.ps1 @@ -322,15 +322,8 @@ Describe "Validate Copy-Item Remotely" -Tags "CI" { $destinationFolderPath = Join-Path $destinationFolderPath "A\B\C\D\E" $expectedFullyQualifiedErrorId = 'RemotePathNotFound,Microsoft.PowerShell.Commands.CopyItemCommand' - try - { - Copy-Item -Path $filePath -ToSession $s -Destination $destinationFolderPath -ErrorAction Stop - throw "CodeExecuted" - } - catch - { - $_.FullyQualifiedErrorId | Should -Be $expectedFullyQualifiedErrorId - } + { Copy-Item -Path $filePath -ToSession $s -Destination $destinationFolderPath -ErrorAction Stop } | + Should -Throw -ErrorId $expectedFullyQualifiedErrorId } It "Copy folder to remote session recursively works even if the target directory does not exist." { @@ -408,20 +401,13 @@ Describe "Validate Copy-Item Remotely" -Tags "CI" { } It "Copy one file from remote session fails when the target directory does not exist." { - $filePath = CreateTestFile $destinationFolderPath = GetDestinationFolderPath $destinationFolderPath = Join-Path $destinationFolderPath "A\B\C\D\E" $expectedFullyQualifiedErrorId = 'CopyItemRemotelyIOError,Microsoft.PowerShell.Commands.CopyItemCommand' - try - { - Copy-Item -Path $filePath -FromSession $s -Destination $destinationFolderPath -ErrorAction Stop - throw "CodeExecuted" - } - catch - { - $_.FullyQualifiedErrorId | Should -Be $expectedFullyQualifiedErrorId - } + + { Copy-Item -Path $filePath -FromSession $s -Destination $destinationFolderPath -ErrorAction Stop } | + Should -Throw -ErrorId $expectedFullyQualifiedErrorId } It "Copy folder from remote session recursively works even if the target directory does not exist." { @@ -565,29 +551,15 @@ Describe "Validate Copy-Item Remotely" -Tags "CI" { if ($fromSession) { It "Copy-Item FromSession -Path '$path' throws $expectedFullyQualifiedErrorId" { - try - { - Copy-Item -Path $path -FromSession $s -Destination $destination -ErrorAction Stop - throw "CodeExecuted" - } - catch - { - $_.FullyQualifiedErrorId | Should -Be $expectedFullyQualifiedErrorId - } + { Copy-Item -Path $path -FromSession $s -Destination $destination -ErrorAction Stop } | + Should -Throw -ErrorId $expectedFullyQualifiedErrorId } } else { It "Copy-Item ToSession -Destination '$path' throws $expectedFullyQualifiedErrorId" { - try - { - Copy-Item -Path $path -ToSession $s -Destination $destination -ErrorAction Stop - throw "CodeExecuted" - } - catch - { - $_.FullyQualifiedErrorId | Should -Be $expectedFullyQualifiedErrorId - } + { Copy-Item -Path $path -ToSession $s -Destination $destination -ErrorAction Stop } | + Should -Throw -ErrorId $expectedFullyQualifiedErrorId } } } @@ -733,26 +705,12 @@ Describe "Validate Copy-Item error for target sessions not in FullLanguageMode." It "Copy-Item throws 'SessionIsNotInFullLanguageMode' error for a session in '$languageMode'" { # FromSession - try - { - Copy-Item -Path $testFilePath -FromSession $session -Destination $destination -Force -Verbose -ErrorAction Stop - throw "CodeExecuted" - } - catch - { - $_.FullyQualifiedErrorId | Should -Be "SessionIsNotInFullLanguageMode,Microsoft.PowerShell.Commands.CopyItemCommand" - } + { Copy-Item -Path $testFilePath -FromSession $session -Destination $destination -Force -Verbose -ErrorAction Stop } | + Should -Throw -ErrorId "SessionIsNotInFullLanguageMode,Microsoft.PowerShell.Commands.CopyItemCommand" # ToSession - try - { - Copy-Item -Path $testFilePath -ToSession $session -Destination $destination -Force -Verbose -ErrorAction Stop - throw "CodeExecuted" - } - catch - { - $_.FullyQualifiedErrorId | Should -Be "SessionIsNotInFullLanguageMode,Microsoft.PowerShell.Commands.CopyItemCommand" - } + { Copy-Item -Path $testFilePath -ToSession $session -Destination $destination -Force -Verbose -ErrorAction Stop } | + Should -Throw -ErrorId "SessionIsNotInFullLanguageMode,Microsoft.PowerShell.Commands.CopyItemCommand" } } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 index 757f614c643..e1f397978d8 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/FileSystem.Tests.ps1 @@ -886,11 +886,8 @@ Describe "Extended FileSystem Item/Content Cmdlet Provider Tests" -Tags "Feature It "Verify Directory + Whatif" { New-Item -Path . -ItemType Directory -Name $testDir -WhatIf > $null - try { - Get-Item -Path $testDir -ErrorAction Stop - throw "Expected exception not thrown" - } - catch { $_.FullyQualifiedErrorId | Should -Be "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } + { Get-Item -Path $testDir -ErrorAction Stop } | + Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } It "Verify Directory + Confirm bypass" { @@ -965,11 +962,8 @@ Describe "Extended FileSystem Item/Content Cmdlet Provider Tests" -Tags "Feature It "Verify WhatIf" { Move-Item -Path $testFile -Destination $altTestFile -WhatIf - try { - Get-Item -Path $altTestFile -ErrorAction Stop - throw "Expected exception not thrown" - } - catch { $_.FullyQualifiedErrorId | Should -Be "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } + { Get-Item -Path $altTestFile -ErrorAction Stop } | + Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } It "Verify Include and Exclude Intersection" { @@ -997,11 +991,8 @@ Describe "Extended FileSystem Item/Content Cmdlet Provider Tests" -Tags "Feature It "Verify WhatIf" { Rename-Item -Path $testFile -NewName $newFile -WhatIf - try { - Get-Item -Path $newFile -ErrorAction Stop - throw "Expected exception not thrown" - } - catch { $_.FullyQualifiedErrorId | Should -Be "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } + { Get-Item -Path $newFile -ErrorAction Stop } | + Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } It "Verify Confirm can be bypassed" { @@ -1022,20 +1013,12 @@ Describe "Extended FileSystem Item/Content Cmdlet Provider Tests" -Tags "Feature It "Verify Confirm can be bypassed" { Remove-Item $testFile -Confirm:$false - try { - Get-Item $testFile -ErrorAction Stop - throw "Expected exception not thrown" - } - catch { $_.FullyQualifiedErrorId | Should -Be "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } + { Get-Item $testFile -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } It "Verify LiteralPath" { Remove-Item -LiteralPath "TestDrive:\$testFile" -Recurse - try { - Get-Item $testFile -ErrorAction Stop - throw "Expected exception not thrown" - } - catch { $_.FullyQualifiedErrorId | Should -Be "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } + { Get-Item $testFile -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } It "Verify Filter" { @@ -1046,11 +1029,7 @@ Describe "Extended FileSystem Item/Content Cmdlet Provider Tests" -Tags "Feature It "Verify Include" { Remove-Item "TestDrive:\*" -Include "*2.txt" - try { - Get-Item $testFile2 -ErrorAction Stop - throw "Expected exception not thrown" - } - catch { $_.FullyQualifiedErrorId | Should -Be "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } + { Get-Item $testFile2 -ErrorAction Stop } | Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand" } It "Verify Include and Exclude Intersection" { @@ -1307,11 +1286,7 @@ Describe "Extended FileSystem Path/Location Cmdlet Provider Tests" -Tags "Featur } It "WhatIf is Not Supported" { - try { - Set-Location $level1_0 -WhatIf - throw "Expected exception not thrown" - } - catch { $_.FullyQualifiedErrorId | Should -Be "NamedParameterNotFound,Microsoft.PowerShell.Commands.SetLocationCommand" } + { Set-Location $level1_0 -WhatIf } | Should -Throw -ErrorId "NamedParameterNotFound,Microsoft.PowerShell.Commands.SetLocationCommand" } } @@ -1359,11 +1334,8 @@ Describe "Extended FileSystem Path/Location Cmdlet Provider Tests" -Tags "Featur } It "Verify Pop + Invalid Stack Name" { - try { - Pop-Location -StackName UnknownStackName -ErrorAction Stop - throw "Expected exception not thrown" - } - catch { $_.FullyQualifiedErrorId | Should -Be "Argument,Microsoft.PowerShell.Commands.PopLocationCommand" } + { Pop-Location -StackName UnknownStackName -ErrorAction Stop } | + Should -Throw -ErrorId "Argument,Microsoft.PowerShell.Commands.PopLocationCommand" } } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 index 68e69060837..dfb389e024f 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 @@ -23,15 +23,10 @@ Describe "Get-Content" -Tags "CI" { Remove-Item -Path $testPath -Force Remove-Item -Path $testPath2 -Force } - + It "Should throw an error on a directory " { - try { - Get-Content . -ErrorAction Stop - throw "No Exception!" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "GetContentReaderUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetContentCommand" - } + { Get-Content . -ErrorAction Stop } | + Should -Throw -ErrorId "GetContentReaderUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetContentCommand" } It "Should return an Object when listing only a single line and the correct information from a file" { @@ -254,7 +249,7 @@ baz param($cmdlet) (Get-Command $cmdlet).Parameters["stream"] | Should -BeNullOrEmpty } - + It "Should return no content when an empty path is used with -Raw switch" { Get-ChildItem $TestDrive -Filter "*.raw" | Get-Content -Raw | Should -BeNullOrEmpty } @@ -264,7 +259,7 @@ baz } It "Should throw TailAndHeadCannotCoexist when both -Tail and -TotalCount are used" { - { + { Get-Content -Path $testPath -Tail 1 -TotalCount 1 -ErrorAction Stop } | Should -Throw -ErrorId "TailAndHeadCannotCoexist,Microsoft.PowerShell.Commands.GetContentCommand" } @@ -347,11 +342,11 @@ baz Describe "Get-Content -Raw test" -Tags "CI" { - It "Reads - <testname> in full" -TestCases @( + It "Reads - <testname> in full" -TestCases @( @{character = "a`nb`n"; testname = "LF-terminated files"; filename = "lf.txt"} @{character = "a`r`nb`r`n"; testname = "CRLF-terminated files"; filename = "crlf.txt"} @{character = "a`nb"; testname = "LF-separated files without trailing newline"; filename = "lf-nt.txt"} - @{character = "a`r`nb"; testname = "CRLF-separated files without trailing newline"; filename = "crlf-nt.txt"} + @{character = "a`r`nb"; testname = "CRLF-separated files without trailing newline"; filename = "crlf-nt.txt"} ) { param ($character, $filename) Set-Content -Encoding Ascii -NoNewline "$TestDrive\$filename" -Value $character diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Service.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Service.Tests.ps1 index 75c7977c9d1..8b9a55308eb 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Service.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Service.Tests.ps1 @@ -21,26 +21,16 @@ Describe "Get-Service cmdlet tests" -Tags "CI" { Context 'Check null or empty value to the -Name parameter' { It 'Should throw if <value> is passed to -Name parameter' -TestCases $testCases { param($data) - try { - $null = Get-Service -Name $data -ErrorAction Stop - throw 'Expected error on previous command' - } - catch { - $_.FullyQualifiedErrorId | Should -Be 'ParameterArgumentValidationError,Microsoft.Powershell.Commands.GetServiceCommand' - } + { $null = Get-Service -Name $data -ErrorAction Stop } | + Should -Throw -ErrorId 'ParameterArgumentValidationError,Microsoft.Powershell.Commands.GetServiceCommand' } } Context 'Check null or empty value to the -Name parameter via pipeline' { It 'Should throw if <value> is passed through pipeline to -Name parameter' -TestCases $testCases { param($data) - try { - $null = Get-Service -Name $data -ErrorAction Stop - throw 'Expected error on previous command' - } - catch { - $_.FullyQualifiedErrorId | Should -Be 'ParameterArgumentValidationError,Microsoft.Powershell.Commands.GetServiceCommand' - } + { $null = Get-Service -Name $data -ErrorAction Stop } | + Should -Throw -ErrorId 'ParameterArgumentValidationError,Microsoft.Powershell.Commands.GetServiceCommand' } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Join-Path.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Join-Path.Tests.ps1 index d56fa7941e3..3c607d6253a 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Join-Path.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Join-Path.Tests.ps1 @@ -13,12 +13,12 @@ Describe "Join-Path cmdlet tests" -Tags "CI" { (Join-Path -Path TestDrive:,$TestDrive -ChildPath "SubDir1" -resolve).Length | Should -Be 2 } It "should throw 'DriveNotFound' when called with -Resolve and drive does not exist" { - try {Join-Path bogusdrive:\\somedir otherdir -resolve -ErrorAction Stop; Throw "Previous statement unexpectedly succeeded..." - } catch {$_.FullyQualifiedErrorId | Should -Be "DriveNotFound,Microsoft.PowerShell.Commands.JoinPathCommand"} + { Join-Path bogusdrive:\\somedir otherdir -resolve -ErrorAction Stop; Throw "Previous statement unexpectedly succeeded..." } | + Should -Throw -ErrorId "DriveNotFound,Microsoft.PowerShell.Commands.JoinPathCommand" } It "should throw 'PathNotFound' when called with -Resolve and item does not exist" { - try {Join-Path "Bogus" "Path" -resolve -ErrorAction Stop; Throw "Previous statement unexpectedly succeeded..." - } catch {$_.FullyQualifiedErrorId | Should -Be "PathNotFound,Microsoft.PowerShell.Commands.JoinPathCommand"} + { Join-Path "Bogus" "Path" -resolve -ErrorAction Stop; Throw "Previous statement unexpectedly succeeded..." } | + Should -Throw -ErrorId "PathNotFound,Microsoft.PowerShell.Commands.JoinPathCommand" } #[BugId(BugDatabase.WindowsOutOfBandReleases, 905237)] Note: Result should be the same on non-Windows platforms too It "should return one object when called with a Windows FileSystem::Redirector" { From 2220ea3536a6c98740444bd174386f637011b357 Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Thu, 19 Apr 2018 09:12:46 -0700 Subject: [PATCH 43/58] [Feature] try {} catch {} => Should -Throw -ErrorId in Security module. --- .../AmsiInterface.Tests.ps1 | 11 +- .../CmsMessage.Tests.ps1 | 32 +- .../ConstrainedLanguageRestriction.Tests.ps1 | 342 +++++------------- .../ExecutionPolicy.Tests.ps1 | 16 +- .../SecureString.Tests.ps1 | 21 +- 5 files changed, 106 insertions(+), 316 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/AmsiInterface.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/AmsiInterface.Tests.ps1 index ef60650054b..f342afcd3fa 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/AmsiInterface.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/AmsiInterface.Tests.ps1 @@ -21,15 +21,8 @@ try $EICAR_STRING_B64 = "awZ8EmMWc3JjaAdvY2lrBgcbY20aBHBwGgROF3Z6cHJhHmBncn13cmF3HnJ9Z3plemFmYB5ndmBnHnV6f3YSF3sYexk= " $bytes = [System.Convert]::FromBase64String($EICAR_STRING_B64) $EICAR_STRING = -join ($bytes | % { [char]($_ -bxor 0x33) }) - try - { - Invoke-Expression -Command "echo '$EICAR_STRING'" - throw "No exception thrown!" - } - catch - { - $_.FullyQualifiedErrorId | Should Be "ScriptContainedMaliciousContent,Microsoft.PowerShell.Commands.InvokeExpressionCommand" - } + { Invoke-Expression -Command "echo '$EICAR_STRING'" } | + Should -Throw -ErrorId "ScriptContainedMaliciousContent,Microsoft.PowerShell.Commands.InvokeExpressionCommand" } } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/CmsMessage.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/CmsMessage.Tests.ps1 index f35c24d9ec7..0865032b85b 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/CmsMessage.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/CmsMessage.Tests.ps1 @@ -223,12 +223,8 @@ Describe "CmsMessage cmdlets thorough tests" -Tags "Feature" { } It "Verify Protect-CmsMessage emits recipient errors" { - try { - "Hello World" | Protect-CmsMessage -To "SomeThumbprintThatDoesNotExist" -ErrorAction Stop - throw "No Exception!" - } catch { - $_.FullyQualifiedErrorId | Should -Be "NoCertificateFound,Microsoft.PowerShell.Commands.ProtectCmsMessageCommand" - } + { "Hello World" | Protect-CmsMessage -To "SomeThumbprintThatDoesNotExist" -ErrorAction Stop } | + Should -Throw -ErrorId "NoCertificateFound,Microsoft.PowerShell.Commands.ProtectCmsMessageCommand" } It "Verify CmsMessage cmdlets works with paths" { @@ -270,30 +266,18 @@ Describe "CmsMessage cmdlets thorough tests" -Tags "Feature" { } It "Verify Unprotect-CmsMessage emits recipient errors" { - try { - "" | Unprotect-CmsMessage -To "SomeThumbprintThatDoesNotExist" -IncludeContext -ErrorAction Stop - throw "No Exception!" - } catch { - $_.FullyQualifiedErrorId | Should -Be "NoCertificateFound,Microsoft.PowerShell.Commands.UnprotectCmsMessageCommand" - } + { "" | Unprotect-CmsMessage -To "SomeThumbprintThatDoesNotExist" -IncludeContext -ErrorAction Stop } | + Should -Throw -ErrorId "NoCertificateFound,Microsoft.PowerShell.Commands.UnprotectCmsMessageCommand" } It "Verify failure to extract Ascii armor generates an error [Unprotect-CmsMessage]" { - try { - "Hello World" | Unprotect-CmsMessage -ErrorAction Stop - throw "No Exception!" - } catch { - $_.FullyQualifiedErrorId | Should -Be "InputContainedNoEncryptedContentIncludeContext,Microsoft.PowerShell.Commands.UnprotectCmsMessageCommand" - } + { "Hello World" | Unprotect-CmsMessage -ErrorAction Stop } | + Should -Throw -ErrorId "InputContainedNoEncryptedContentIncludeContext,Microsoft.PowerShell.Commands.UnprotectCmsMessageCommand" } It "Verify failure to extract Ascii armor generates an error [Get-CmsMessage]" { - try { - "Hello World" | Get-CmsMessage -ErrorAction Stop - throw "No Exception!" - } catch { - $_.FullyQualifiedErrorId | Should -Be "InputContainedNoEncryptedContent,Microsoft.PowerShell.Commands.GetCmsMessageCommand" - } + { "Hello World" | Get-CmsMessage -ErrorAction Stop } | + Should -Throw -ErrorId "InputContainedNoEncryptedContent,Microsoft.PowerShell.Commands.GetCmsMessageCommand" } It "Verify 'Unprotect-CmsMessage -IncludeContext' with no encrypted input" { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/ConstrainedLanguageRestriction.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/ConstrainedLanguageRestriction.Tests.ps1 index 4c5073c4a95..368303b9fde 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/ConstrainedLanguageRestriction.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/ConstrainedLanguageRestriction.Tests.ps1 @@ -155,24 +155,15 @@ try Context "Background jobs within inconsistent mode" { It "Verifies that background job is denied when mode is inconsistent" { - - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" Start-Job { [object]::Equals("A", "B") } - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru - $exception.FullyQualifiedErrorId | Should -Match "CannotStartJobInconsistentLanguageMode" + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode + + $e.FullyQualifiedErrorId | Should -Match "CannotStartJobInconsistentLanguageMode" } } } @@ -180,24 +171,14 @@ try Describe "Add-Type in constrained language" -Tags 'Feature','RequireAdminOnWindows' { It "Verifies Add-Type fails in constrained language mode" { - - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" Add-Type -TypeDefinition 'public class ConstrainedLanguageTest { public static string Hello = "HelloConstrained"; }' - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - $exception.FullyQualifiedErrorId | Should -Match "CannotDefineNewType" + $e.FullyQualifiedErrorId | Should -Match "CannotDefineNewType" } It "Verifies Add-Type works back in full language mode again" { @@ -228,23 +209,15 @@ try It "Verifies New-Object throws error in constrained language for disallowed IntPtr type" { - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" New-Object System.IntPtr 1234 - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru - $exception.FullyQualifiedErrorId | Should -Match "CannotCreateTypeConstrainedLanguage" + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode + + $e.FullyQualifiedErrorId | Should -Match "CannotCreateTypeConstrainedLanguage" } It "Verifies New-Object works for IntPtr type back in full language mode again" { @@ -257,24 +230,16 @@ try It "Verifies New-Object with COM types is disallowed in system lock down" { - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" Invoke-LanguageModeTestingSupportCmdlet -SetLockdownMode New-Object -Com ADODB.Parameter - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -RevertLockdownMode -EnableFullLanguageMode - } + } | Should -Throw -PassThru + + Invoke-LanguageModeTestingSupportCmdlet -RevertLockdownMode -EnableFullLanguageMode - $exception.FullyQualifiedErrorId | Should -Match "CannotCreateComTypeConstrainedLanguage" + $e.FullyQualifiedErrorId | Should -Match "CannotCreateComTypeConstrainedLanguage" } It "Verifies New-Object with COM types works back in full language mode again" { @@ -288,49 +253,29 @@ try Describe "New-Item command on function drive in constrained language" -Tags 'Feature','RequireAdminOnWindows' { It "Verifies New-Item directory on function drive is not allowed in constrained language mode" { - - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" $null = New-Item -Path function:\SomeEvilFunction -ItemType Directory -Value SomeBadScriptBlock -ErrorAction Stop - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } - - $exception.FullyQualifiedErrorId | Should -Match "NotSupported" + } | Should -Throw -PassThru + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode + $e.FullyQualifiedErrorId | Should -Match "NotSupported" } } Describe "Script debugging in constrained language" -Tags 'Feature','RequireAdminOnWindows' { It "Verifies that a debugging breakpoint cannot be set in constrained language and no system lockdown" { - - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" function MyDebuggerFunction {} Set-PSBreakpoint -Command MyDebuggerFunction - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru - $exception.FullyQualifiedErrorId | Should -Match "CannotSetBreakpointInconsistentLanguageMode" + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode + + $e.FullyQualifiedErrorId | Should -Match "CannotSetBreakpointInconsistentLanguageMode" } It "Verifies that a debugging breakpoint can be set in constrained language with system lockdown" { @@ -354,9 +299,7 @@ try } It "Verifies that debugger commands do not run in full language mode when system is locked down" { - - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" function MyDebuggerFunction3 {} @@ -365,19 +308,12 @@ try $restoreEAPreference = $ErrorActionPreference $ErrorActionPreference = "Stop" MyDebuggerFunction3 - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - if ($restoreEAPreference -ne $null) { $ErrorActionPreference = $restoreEAPreference } - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru + + if ($restoreEAPreference -ne $null) { $ErrorActionPreference = $restoreEAPreference } + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - $exception.FullyQualifiedErrorId | Should Match "CannotSetBreakpointInconsistentLanguageMode" + $e.FullyQualifiedErrorId | Should Match "CannotSetBreakpointInconsistentLanguageMode" } It "Verifies that debugger command injection is blocked in system lock down" { @@ -445,23 +381,14 @@ try Import-Module PSDiagnostics $module = Get-Module PSDiagnostics - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - & $module { [object]::Equals("A", "B") } - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru + + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - $exception.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" + $e.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" } } @@ -475,21 +402,11 @@ try $rs.Open() $pl = $rs.CreatePipeline("switch -file $testDrive/foo.txt { 'A' { 'B' } }") - try - { - $pl.Invoke() - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - $rs.Dispose() - } + $e = { $pl.Invoke() } | Should -Throw -PassThru + + $rs.Dispose() - $exception.FullyQualifiedErrorId | Should -Match "DriveNotFoundException" + $e.FullyQualifiedErrorId | Should -Match "DriveNotFoundException" } } @@ -521,21 +438,11 @@ try $rs.Open() $pl = $rs.CreatePipeline('"Hello" > c:\temp\foo.txt') - try - { - $pl.Invoke() - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - $rs.Dispose() - } + $e = { $pl.Invoke() } | Should -Throw -PassThru + + $rs.Dispose() - $exception.FullyQualifiedErrorId | Should -Match "CmdletInvocationException" + $e.FullyQualifiedErrorId | Should -Match "CmdletInvocationException" } } @@ -557,23 +464,15 @@ try param ($scriptblock) - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" & $scriptblock - throw 'No Exception!' - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru + + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - $exception.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" + $e.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" } } @@ -581,48 +480,33 @@ try It "Verifies dynamic method invocation does not bypass constrained language mode" { - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" $type = [IO.Path] $method = "GetRandomFileName" $type::$method() throw 'No Exception!' - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru + + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - $exception.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" + $e.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" } It "Verifies dynamic methods invocation does not bypass constrained language mode" { - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" $type = [IO.Path] $methods = "GetRandomFileName","GetTempPath" $type::($methods[0])() - throw 'No Exception!' - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru + + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - $exception.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" + $e.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" } } @@ -649,44 +533,28 @@ try It "Verifies Set-Variable cannot create AllScope in constrained language" { - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" Set-Variable -Name SetVariableAllScopeNotSupported -Value bar -Option AllScope - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru + + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - $exception.FullyQualifiedErrorId | Should -Match "NotSupported" + $e.FullyQualifiedErrorId | Should -Match "NotSupported" } It "Verifies New-Variable cannot create AllScope in constrained language" { - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" New-Variable -Name NewVarialbeAllScopeNotSupported -Value bar -Option AllScope - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru - $exception.FullyQualifiedErrorId | Should -Match "NotSupported" + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode + + $e.FullyQualifiedErrorId | Should -Match "NotSupported" } } @@ -694,17 +562,9 @@ try function InvokeDataSectionConstrained { - try - { - Invoke-Expression 'data foo -SupportedCommand Add-Type { Add-Type }' - throw "No Exception!" - } - catch - { - $exception = $_ - } + $e = { Invoke-Expression 'data foo -SupportedCommand Add-Type { Add-Type }' } | Should -Throw -PassThru - return $exception + return $e } It "Verifies data section Add-Type additional command is disallowed in constrained language" { @@ -728,24 +588,16 @@ try It "Verifies data section with no-constant expression Add-Type additional command is disallowed in constrained language" { - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" $addedCommand = "Add-Type" Invoke-Expression 'data foo -SupportedCommand $addedCommand { Add-Type }' - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru - $exception.FullyQualifiedErrorId | Should -Match "DataSectionAllowedCommandDisallowed" + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode + + $e.FullyQualifiedErrorId | Should -Match "DataSectionAllowedCommandDisallowed" } } @@ -753,25 +605,17 @@ try It "Verifies Import-LocalizedData disallows Add-Type in constrained language" { - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" $localizedDataFileName = Join-Path $TestDrive ImportLocalizedDataAdditionalCommandsNotSupported.psd1 $null = New-Item -ItemType File -Path $localizedDataFileName -Force Import-LocalizedData -SupportedCommand Add-Type -BaseDirectory $TestDrive -FileName ImportLocalizedDataAdditionalCommandsNotSupported - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru + + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - $exception.FullyQualifiedErrorId | Should -Match "CannotDefineSupportedCommand" + $e.FullyQualifiedErrorId | Should -Match "CannotDefineSupportedCommand" } } @@ -861,25 +705,17 @@ try [string] $script ) - try - { + $e = { $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" # Scriptblock must be created inside constrained language. $sb = [scriptblock]::Create($script) & sb - throw "No Exception!" - } - catch - { - $exception = $_ - } - finally - { - Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - } + } | Should -Throw -PassThru + + Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - $exception.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" + $e.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 index f26f55a8a91..e5f71072759 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 @@ -559,21 +559,9 @@ ZoneId=$FileType $scriptName = $testScript - $exception = $null - try { - & $scriptName - } - catch - { - $exception = $_ - } - - $exception.Exception | Should -Not -BeNullOrEmpty - - $exceptionType = $exception.Exception.getType() - $result = $exceptionType + $exception = { & $scriptName } | Should -Throw -PassThru - $result | Should -Be "System.Management.Automation.PSSecurityException" + $exception.Exception | Should -BeOfType "System.Management.Automation.PSSecurityException" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/SecureString.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/SecureString.Tests.ps1 index 9f49c94f2d9..a97c32a1080 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/SecureString.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/SecureString.Tests.ps1 @@ -14,25 +14,14 @@ Describe "SecureString conversion tests" -Tags "CI" { } It "using null arguments to ConvertFrom-SecureString produces an exception" { - try { - ConvertFrom-SecureString -secureString $null -key $null - throw "No Exception!" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertFromSecureStringCommand" - } - + { ConvertFrom-SecureString -secureString $null -key $null } | + Should -Throw -ErrorId "ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertFromSecureStringCommand" } It "using a bad key produces an exception" { - try { - $badkey = [byte[]]@(1,2) - ConvertFrom-SecureString -securestring $secureString -key $badkey - throw "Command did not throw exception" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "Argument,Microsoft.PowerShell.Commands.ConvertFromSecureStringCommand" - } + $badkey = [byte[]]@(1,2) + { ConvertFrom-SecureString -securestring $secureString -key $badkey } | + Should -Throw -ErrorId "Argument,Microsoft.PowerShell.Commands.ConvertFromSecureStringCommand" } It "Can convert to a secure string" { From fe00e85689d9bc94006a96e50e9da199907008b2 Mon Sep 17 00:00:00 2001 From: Klaudia Algiz <klalgiz@microsoft.com> Date: Thu, 19 Apr 2018 10:52:31 -0700 Subject: [PATCH 44/58] [Feature] ConstrainedLanguageRestriction tests fixes. --- .../ConstrainedLanguageRestriction.Tests.ps1 | 172 +++++------------- 1 file changed, 49 insertions(+), 123 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/ConstrainedLanguageRestriction.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/ConstrainedLanguageRestriction.Tests.ps1 index 368303b9fde..512f8dbedea 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/ConstrainedLanguageRestriction.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/ConstrainedLanguageRestriction.Tests.ps1 @@ -155,15 +155,10 @@ try Context "Background jobs within inconsistent mode" { It "Verifies that background job is denied when mode is inconsistent" { - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - - Start-Job { [object]::Equals("A", "B") } - } | Should -Throw -PassThru + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + { Start-Job { [object]::Equals("A", "B") } } | Should -Throw -ErrorId "CannotStartJobInconsistentLanguageMode" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "CannotStartJobInconsistentLanguageMode" } } } @@ -171,14 +166,10 @@ try Describe "Add-Type in constrained language" -Tags 'Feature','RequireAdminOnWindows' { It "Verifies Add-Type fails in constrained language mode" { - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - - Add-Type -TypeDefinition 'public class ConstrainedLanguageTest { public static string Hello = "HelloConstrained"; }' - } | Should -Throw -PassThru + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + { Add-Type -TypeDefinition 'public class ConstrainedLanguageTest { public static string Hello = "HelloConstrained"; }' } | + Should -Throw -ErrorId "CannotDefineNewType" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "CannotDefineNewType" } It "Verifies Add-Type works back in full language mode again" { @@ -208,16 +199,10 @@ try } It "Verifies New-Object throws error in constrained language for disallowed IntPtr type" { - - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - - New-Object System.IntPtr 1234 - } | Should -Throw -PassThru + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + { New-Object System.IntPtr 1234 } | Should -Throw -ErrorId "CannotCreateTypeConstrainedLanguage" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "CannotCreateTypeConstrainedLanguage" } It "Verifies New-Object works for IntPtr type back in full language mode again" { @@ -229,17 +214,12 @@ try Context "New-Object with COM types" { It "Verifies New-Object with COM types is disallowed in system lock down" { + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + Invoke-LanguageModeTestingSupportCmdlet -SetLockdownMode - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - Invoke-LanguageModeTestingSupportCmdlet -SetLockdownMode - - New-Object -Com ADODB.Parameter - } | Should -Throw -PassThru + { New-Object -Com ADODB.Parameter } | Should -Throw -ErrorId "CannotCreateComTypeConstrainedLanguage" Invoke-LanguageModeTestingSupportCmdlet -RevertLockdownMode -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "CannotCreateComTypeConstrainedLanguage" } It "Verifies New-Object with COM types works back in full language mode again" { @@ -253,29 +233,22 @@ try Describe "New-Item command on function drive in constrained language" -Tags 'Feature','RequireAdminOnWindows' { It "Verifies New-Item directory on function drive is not allowed in constrained language mode" { - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - - $null = New-Item -Path function:\SomeEvilFunction -ItemType Directory -Value SomeBadScriptBlock -ErrorAction Stop - } | Should -Throw -PassThru + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + { $null = New-Item -Path function:\SomeEvilFunction -ItemType Directory -Value SomeBadScriptBlock -ErrorAction Stop } | + Should -Throw -ErrorId "NotSupported" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - $e.FullyQualifiedErrorId | Should -Match "NotSupported" } } Describe "Script debugging in constrained language" -Tags 'Feature','RequireAdminOnWindows' { It "Verifies that a debugging breakpoint cannot be set in constrained language and no system lockdown" { - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + function MyDebuggerFunction {} - function MyDebuggerFunction {} - Set-PSBreakpoint -Command MyDebuggerFunction - } | Should -Throw -PassThru + { Set-PSBreakpoint -Command MyDebuggerFunction } | Should -Throw -ErrorId "CannotSetBreakpointInconsistentLanguageMode" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "CannotSetBreakpointInconsistentLanguageMode" } It "Verifies that a debugging breakpoint can be set in constrained language with system lockdown" { @@ -299,21 +272,19 @@ try } It "Verifies that debugger commands do not run in full language mode when system is locked down" { - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - function MyDebuggerFunction3 {} - $null = Set-PSBreakpoint -Command MyDebuggerFunction3 -Action { $Global:dbgResult = [object]::Equals("A", "B") } + function MyDebuggerFunction3 {} + { + $null = Set-PSBreakpoint -Command MyDebuggerFunction3 -Action { $Global:dbgResult = [object]::Equals("A", "B") } $restoreEAPreference = $ErrorActionPreference $ErrorActionPreference = "Stop" MyDebuggerFunction3 - } | Should -Throw -PassThru + } | Should -Throw -ErrorId "CannotSetBreakpointInconsistentLanguageMode" if ($restoreEAPreference -ne $null) { $ErrorActionPreference = $restoreEAPreference } Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should Match "CannotSetBreakpointInconsistentLanguageMode" } It "Verifies that debugger command injection is blocked in system lock down" { @@ -381,14 +352,10 @@ try Import-Module PSDiagnostics $module = Get-Module PSDiagnostics - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - & $module { [object]::Equals("A", "B") } - } | Should -Throw -PassThru + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + { & $module { [object]::Equals("A", "B") } } | Should -Throw -ErrorId "MethodInvocationNotSupportedInConstrainedLanguage" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" } } @@ -402,11 +369,9 @@ try $rs.Open() $pl = $rs.CreatePipeline("switch -file $testDrive/foo.txt { 'A' { 'B' } }") - $e = { $pl.Invoke() } | Should -Throw -PassThru + $e = { $pl.Invoke() } | Should -Throw -ErrorId "DriveNotFoundException" $rs.Dispose() - - $e.FullyQualifiedErrorId | Should -Match "DriveNotFoundException" } } @@ -438,11 +403,9 @@ try $rs.Open() $pl = $rs.CreatePipeline('"Hello" > c:\temp\foo.txt') - $e = { $pl.Invoke() } | Should -Throw -PassThru + $e = { $pl.Invoke() } | Should -Throw -ErrorId "CmdletInvocationException" $rs.Dispose() - - $e.FullyQualifiedErrorId | Should -Match "CmdletInvocationException" } } @@ -464,49 +427,35 @@ try param ($scriptblock) - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - - & $scriptblock - } | Should -Throw -PassThru + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + { & $scriptblock } | Should -Throw -ErrorId "MethodInvocationNotSupportedInConstrainedLanguage" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" } } Describe "Dynamic method invocation in constrained language mode" -Tags 'Feature','RequireAdminOnWindows' { It "Verifies dynamic method invocation does not bypass constrained language mode" { - - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + { $type = [IO.Path] $method = "GetRandomFileName" $type::$method() - throw 'No Exception!' - } | Should -Throw -PassThru + } | Should -Throw -ErrorId "MethodInvocationNotSupportedInConstrainedLanguage" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" } It "Verifies dynamic methods invocation does not bypass constrained language mode" { - - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + { $type = [IO.Path] $methods = "GetRandomFileName","GetTempPath" $type::($methods[0])() - } | Should -Throw -PassThru + } | Should -Throw -ErrorId "MethodInvocationNotSupportedInConstrainedLanguage" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" } } @@ -532,29 +481,19 @@ try Describe "Variable AllScope in constrained language mode" -Tags 'Feature','RequireAdminOnWindows' { It "Verifies Set-Variable cannot create AllScope in constrained language" { - - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - - Set-Variable -Name SetVariableAllScopeNotSupported -Value bar -Option AllScope - } | Should -Throw -PassThru + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + { Set-Variable -Name SetVariableAllScopeNotSupported -Value bar -Option AllScope } | + Should -Throw -ErrorId "NotSupported" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "NotSupported" } It "Verifies New-Variable cannot create AllScope in constrained language" { - - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - - New-Variable -Name NewVarialbeAllScopeNotSupported -Value bar -Option AllScope - } | Should -Throw -PassThru + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + { New-Variable -Name NewVarialbeAllScopeNotSupported -Value bar -Option AllScope } | + Should -Throw -ErrorId "NotSupported" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "NotSupported" } } @@ -587,35 +526,26 @@ try } It "Verifies data section with no-constant expression Add-Type additional command is disallowed in constrained language" { - - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - - $addedCommand = "Add-Type" - Invoke-Expression 'data foo -SupportedCommand $addedCommand { Add-Type }' - } | Should -Throw -PassThru + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + $addedCommand = "Add-Type" + { Invoke-Expression 'data foo -SupportedCommand $addedCommand { Add-Type }' } | + Should -Throw -ErrorId "DataSectionAllowedCommandDisallowed" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "DataSectionAllowedCommandDisallowed" } } Describe "Import-LocalizedData additional commands in constrained language" -Tags 'Feature','RequireAdminOnWindows' { It "Verifies Import-LocalizedData disallows Add-Type in constrained language" { - - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + { $localizedDataFileName = Join-Path $TestDrive ImportLocalizedDataAdditionalCommandsNotSupported.psd1 $null = New-Item -ItemType File -Path $localizedDataFileName -Force Import-LocalizedData -SupportedCommand Add-Type -BaseDirectory $TestDrive -FileName ImportLocalizedDataAdditionalCommandsNotSupported - } | Should -Throw -PassThru + } | Should -Throw -ErrorId "CannotDefineSupportedCommand" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "CannotDefineSupportedCommand" } } @@ -704,18 +634,14 @@ try param ( [string] $script ) - - $e = { - $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" - + $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" + { # Scriptblock must be created inside constrained language. $sb = [scriptblock]::Create($script) & sb - } | Should -Throw -PassThru + } | Should -Throw -ErrorId "MethodInvocationNotSupportedInConstrainedLanguage" Invoke-LanguageModeTestingSupportCmdlet -EnableFullLanguageMode - - $e.FullyQualifiedErrorId | Should -Match "MethodInvocationNotSupportedInConstrainedLanguage" } } From ad427f0479bc20018acb47a07223b2afcbf80b04 Mon Sep 17 00:00:00 2001 From: Klaudia Algiz <klalgiz@microsoft.com> Date: Thu, 19 Apr 2018 11:08:09 -0700 Subject: [PATCH 45/58] [Feature] try {} catch {} => Should -Throw -ErrorId in Security module continued. --- .../ExecutionPolicy.Tests.ps1 | 20 +++++-------------- 1 file changed, 5 insertions(+), 15 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 index e5f71072759..d1a704bb56d 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 @@ -1032,13 +1032,8 @@ ZoneId=$FileType [string] $policyScope ) - try { - Set-ExecutionPolicy -Scope $policyScope -ExecutionPolicy Restricted - throw "No Exception!" - } - catch { - $_.FullyQualifiedErrorId | Should -Be "CantSetGroupPolicy,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand" - } + { Set-ExecutionPolicy -Scope $policyScope -ExecutionPolicy Restricted } | + Should -Throw -ErrorId "CantSetGroupPolicy,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand" } function RestoreExecutionPolicy @@ -1152,14 +1147,9 @@ ZoneId=$FileType Set-ExecutionPolicy -Scope Process -ExecutionPolicy Undefined Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Restricted - try - { - Set-ExecutionPolicy -Scope LocalMachine -ExecutionPolicy ByPass - throw "Expected exception: ExecutionPolicyOverride" - } - catch [System.Security.SecurityException] { - $_.FullyQualifiedErrorId | Should -Be 'ExecutionPolicyOverride,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand' - } + + { Set-ExecutionPolicy -Scope LocalMachine -ExecutionPolicy ByPass } | + Should -Throw -ErrorId 'ExecutionPolicyOverride,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand' Get-ExecutionPolicy -Scope LocalMachine | Should -Be "ByPass" } From 70b2bfa24cb88095dc1e5e2eb9bce9eb6971eae0 Mon Sep 17 00:00:00 2001 From: Klaudia Algiz <klalgiz@microsoft.com> Date: Thu, 19 Apr 2018 11:30:26 -0700 Subject: [PATCH 46/58] [Feature] try {} catch {} => Should -Throw -ErrorId in Utility module. --- .../Implicit.Remoting.Tests.ps1 | 29 ++++++++----------- .../Unblock-File.Tests.ps1 | 16 +++------- 2 files changed, 16 insertions(+), 29 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Implicit.Remoting.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Implicit.Remoting.Tests.ps1 index 16d772a98e6..abe47d5dae0 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Implicit.Remoting.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Implicit.Remoting.Tests.ps1 @@ -340,13 +340,12 @@ try } It "Verifies that Export-PSSession fails when a module directory already exists" { - try { - Export-PSSession -Session $session -CommandName Get-Variable -AllowClobber -ModuleName $file -EA SilentlyContinue -ErrorVariable expectedError - } catch { } + $e = { Export-PSSession -Session $session -CommandName Get-Variable -AllowClobber -ModuleName $file -ErrorAction Stop } | + Should -Throw -PassThru - $expectedError | Should -Not -BeNullOrEmpty + $e | Should -Not -BeNullOrEmpty # Error contains reference to the directory that already exists - ([string]($expectedError[0]) -like "*$file*") | Should -BeTrue + ([string]($e[0]) -like "*$file*") | Should -BeTrue } It "Verifies that overwriting an existing directory succeeds with -Force" { @@ -1686,19 +1685,15 @@ try } It "Get-Command returns something that is not CommandInfo" { - try { - Invoke-Command $session { $oldGetCommand = ${function:Get-Command} } - Invoke-Command $session { function Get-Command { Microsoft.PowerShell.Utility\Get-Variable } } + Invoke-Command $session { $oldGetCommand = ${function:Get-Command} } + Invoke-Command $session { function Get-Command { Microsoft.PowerShell.Utility\Get-Variable } } + $e = { $module = Import-PSSession -Session $session -AllowClobber } | Should -Throw -PassThru - $module = Import-PSSession -Session $session -AllowClobber - throw "Import-PSSession should throw" - } catch { - $msg = [string]($_) - $msg.Contains("Get-Command") | Should -BeTrue - } finally { - if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } - Invoke-Command $session { ${function:Get-Command} = $oldGetCommand } - } + $msg = [string]($e) + $msg.Contains("Get-Command") | Should -BeTrue + + if ($null -ne $module) { Remove-Module $module -Force -ErrorAction SilentlyContinue } + Invoke-Command $session { ${function:Get-Command} = $oldGetCommand } } # Test order of remote commands (alias > function > cmdlet > external script) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 index c615191d22a..b85cb1156f0 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 @@ -1,16 +1,8 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. function Test-UnblockFile { - try { - Get-Content -Path $testfilepath -Stream Zone.Identifier -ErrorAction Stop | Out-Null - } - catch { - if ($_.FullyQualifiedErrorId -eq "GetContentReaderFileNotFoundError,Microsoft.PowerShell.Commands.GetContentCommand") { - return $true - } - } - - return $false + { Get-Content -Path $testfilepath -Stream Zone.Identifier -ErrorAction Stop | Out-Null } | + Should -Throw -ErrorId "GetContentReaderFileNotFoundError,Microsoft.PowerShell.Commands.GetContentCommand" } Describe "Unblock-File" -Tags "CI" { @@ -48,7 +40,7 @@ Describe "Unblock-File" -Tags "CI" { It "With '-Path': file exist" { Unblock-File -Path $testfilepath - Test-UnblockFile | Should -BeTrue + Test-UnblockFile # If a file is not blocked we silently return without an error. { Unblock-File -Path $testfilepath -ErrorAction Stop } | Should -Not -Throw @@ -56,7 +48,7 @@ Describe "Unblock-File" -Tags "CI" { It "With '-LiteralPath': file exist" { Unblock-File -LiteralPath $testfilepath - Test-UnblockFile | Should -BeTrue + Test-UnblockFile } It "Write an error if a file is read only" { From 7202c93f4f8fe7835413fc622d55f962beee36bf Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Thu, 19 Apr 2018 13:08:15 -0700 Subject: [PATCH 47/58] [Feature] Tests fixes. --- .../Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 index 50ff168743e..2b994a5dc8d 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 @@ -14,7 +14,7 @@ Describe "Clear-Variable DRT Unit Tests" -Tags "CI" { It "Clear-Variable ReadOnly variable Name should throw exception and force Clear-Variable should works"{ Set-Variable foo bar -Option ReadOnly - $e = { Clear-Variable -Name foo -Scope 1 -EA Stop } | Should -Throw -ErrorId "VariableNotWritable,Microsoft.PowerShell.Commands.ClearVariableCommand" + $e = { Clear-Variable -Name foo -Scope 1 -EA Stop } | Should -Throw -ErrorId "VariableNotWritable,Microsoft.PowerShell.Commands.ClearVariableCommand" -PassThru $e.CategoryInfo | Should -Match "SessionStateUnauthorizedAccessException" Clear-Variable -Name foo -Force @@ -50,7 +50,7 @@ Describe "Clear-Variable DRT Unit Tests" -Tags "CI" { Set-Variable foo bar -Option Private &{ $e = { Get-Variable -Name foo -Scope local -EA Stop } | - Should -Throw -ErrorId "VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand" + Should -Throw -ErrorId "VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand" -PassThru $e.CategoryInfo | Should -Match "ItemNotFoundException" } From 8886ea8896fce6394936a19217d4cbdbd653c6cd Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Fri, 20 Apr 2018 09:07:18 -0700 Subject: [PATCH 48/58] [Feature] Tests fixes. --- test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 | 2 +- .../Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 | 6 +++--- .../Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 b/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 index aaf5519ec60..e5d6fecf29a 100644 --- a/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 +++ b/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 @@ -28,7 +28,7 @@ Try { $instance.GetCimSessionInstanceId() | Should -BeOfType "Guid" } It "should produce an error for a non-existing classname" { - { get-ciminstance -classname thisnameshouldnotexist -ea stop } | + { get-ciminstance -classname thisnameshouldnotexist -ErrorAction stop } | Should -Throw -ErrorId "HRESULT 0x80041010,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstanceCommand" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 index 2b994a5dc8d..52922bce7ce 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Clear-Variable.Tests.ps1 @@ -14,7 +14,7 @@ Describe "Clear-Variable DRT Unit Tests" -Tags "CI" { It "Clear-Variable ReadOnly variable Name should throw exception and force Clear-Variable should works"{ Set-Variable foo bar -Option ReadOnly - $e = { Clear-Variable -Name foo -Scope 1 -EA Stop } | Should -Throw -ErrorId "VariableNotWritable,Microsoft.PowerShell.Commands.ClearVariableCommand" -PassThru + $e = { Clear-Variable -Name foo -Scope 1 -ErrorAction Stop } | Should -Throw -ErrorId "VariableNotWritable,Microsoft.PowerShell.Commands.ClearVariableCommand" -PassThru $e.CategoryInfo | Should -Match "SessionStateUnauthorizedAccessException" Clear-Variable -Name foo -Force @@ -49,7 +49,7 @@ Describe "Clear-Variable DRT Unit Tests" -Tags "CI" { It "Clear-Variable Private variable Name should works and Get-Variable with local scope should throw exception"{ Set-Variable foo bar -Option Private &{ - $e = { Get-Variable -Name foo -Scope local -EA Stop } | + $e = { Get-Variable -Name foo -Scope local -ErrorAction Stop } | Should -Throw -ErrorId "VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand" -PassThru $e.CategoryInfo | Should -Match "ItemNotFoundException" } @@ -176,7 +176,7 @@ Describe "Clear-Variable" -Tags "CI" { It "Should throw error when trying to clear variable that is read-only without using the Force parameter" { New-Variable -Name var2 -Option ReadOnly -Value 100 - { Clear-Variable -Name var2 -Scope 1 -ea stop } | Should -Throw -ErrorId "VariableNotWritable,Microsoft.PowerShell.Commands.ClearVariableCommand" + { Clear-Variable -Name var2 -Scope 1 -ErrorAction stop } | Should -Throw -ErrorId "VariableNotWritable,Microsoft.PowerShell.Commands.ClearVariableCommand" $var2 | Should -Not -BeNullOrEmpty diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 index b85cb1156f0..1b3a3e69d7d 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 @@ -40,7 +40,7 @@ Describe "Unblock-File" -Tags "CI" { It "With '-Path': file exist" { Unblock-File -Path $testfilepath - Test-UnblockFile + Test-UnblockFile | Should -BeTrue # If a file is not blocked we silently return without an error. { Unblock-File -Path $testfilepath -ErrorAction Stop } | Should -Not -Throw @@ -48,7 +48,7 @@ Describe "Unblock-File" -Tags "CI" { It "With '-LiteralPath': file exist" { Unblock-File -LiteralPath $testfilepath - Test-UnblockFile + Test-UnblockFile | Should -BeTrue } It "Write an error if a file is read only" { From e95bf34ade506223ad2250fda14942d1dc662f1d Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Mon, 23 Apr 2018 13:55:33 -0700 Subject: [PATCH 49/58] [Feature] -ea => -ErrorAction --- .../Scripting.Classes.BasicParsing.Tests.ps1 | 2 +- .../Scripting.Classes.Exceptions.Tests.ps1 | 4 +-- .../Scripting/ActionPreference.Tests.ps1 | 2 +- .../Debugging/DebuggerScriptTests.Tests.ps1 | 2 +- .../Language/Scripting/I18n.Tests.ps1 | 2 +- .../Language/Scripting/ScriptHelp.Tests.ps1 | 16 +++++----- .../Modules/CimCmdlets/Get-CimClass.Tests.ps1 | 4 +-- .../PSSessionConfiguration.Tests.ps1 | 4 +-- .../Get-WinEvent.Tests.ps1 | 32 +++++++++---------- .../Clear-EventLog.Tests.ps1 | 2 +- .../Copy.Item.Tests.ps1 | 18 +++++------ .../New-EventLog.Tests.ps1 | 2 +- .../Remove-EventLog.Tests.ps1 | 2 +- .../ConstrainedLanguageRestriction.Tests.ps1 | 2 +- .../ExecutionPolicy.Tests.ps1 | 10 +++--- .../Debug-Runspace.Tests.ps1 | 8 ++--- .../Format-Table.Tests.ps1 | 2 +- .../Get-Variable.Tests.ps1 | 4 +-- .../ImportExportCSV.Delimiter.Tests.ps1 | 2 +- .../New-Object.Tests.ps1 | 12 +++---- .../New-Variable.Tests.ps1 | 10 +++--- .../Remove-Variable.Tests.ps1 | 14 ++++---- .../Select-Object.Tests.ps1 | 2 +- .../Set-Variable.Tests.ps1 | 8 ++--- .../WebCmdlets.Tests.ps1 | 4 +-- .../Write-Stream.Tests.ps1 | 2 +- .../clixml.tests.ps1 | 2 +- .../object.tests.ps1 | 4 +-- test/powershell/engine/Cdxml/Cdxml.Tests.ps1 | 8 ++--- .../Help/HelpSystem.OnlineHelp.Tests.ps1 | 4 +-- .../engine/Help/UpdatableHelpSystem.Tests.ps1 | 4 +-- .../engine/ResourceValidation/TestRunner.ps1 | 2 +- 32 files changed, 98 insertions(+), 98 deletions(-) diff --git a/test/powershell/Language/Classes/Scripting.Classes.BasicParsing.Tests.ps1 b/test/powershell/Language/Classes/Scripting.Classes.BasicParsing.Tests.ps1 index 1d017ce11a1..748f1225f63 100644 --- a/test/powershell/Language/Classes/Scripting.Classes.BasicParsing.Tests.ps1 +++ b/test/powershell/Language/Classes/Scripting.Classes.BasicParsing.Tests.ps1 @@ -637,7 +637,7 @@ function test-it([EE]$ee){$ee} } finally { - Remove-Module -ea ignore MSFT_2081529 + Remove-Module -ErrorAction ignore MSFT_2081529 } } diff --git a/test/powershell/Language/Classes/Scripting.Classes.Exceptions.Tests.ps1 b/test/powershell/Language/Classes/Scripting.Classes.Exceptions.Tests.ps1 index a27f05eefc4..3188c5993be 100644 --- a/test/powershell/Language/Classes/Scripting.Classes.Exceptions.Tests.ps1 +++ b/test/powershell/Language/Classes/Scripting.Classes.Exceptions.Tests.ps1 @@ -231,7 +231,7 @@ Describe "Exception error position" -Tags "CI" { static f1() { [MSFT_3090412]::bar = 42 } static f2() { throw "an error in f2" } static f3() { "".Substring(0, 10) } - static f4() { dir nosuchfile -ea Stop } + static f4() { dir nosuchfile -ErrorAction Stop } } It "Setting a property that doesn't exist" { @@ -251,7 +251,7 @@ Describe "Exception error position" -Tags "CI" { It "Terminating error" { $e = { [MSFT_3090412]::f4() } | Should -Throw -PassThru -ErrorId 'PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand' - $e.InvocationInfo.Line | Should -Match ([regex]::Escape('dir nosuchfile -ea Stop')) + $e.InvocationInfo.Line | Should -Match ([regex]::Escape('dir nosuchfile -ErrorAction Stop')) } } diff --git a/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 b/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 index f4fbcbc0413..7e2e8401567 100644 --- a/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 +++ b/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 @@ -15,7 +15,7 @@ Describe "Tests for (error, warning, etc) action preference" -Tags "CI" { $err = $null try { - get-childitem nosuchfile.nosuchextension -ea stop -ev err + get-childitem nosuchfile.nosuchextension -ErrorAction stop -ev err } catch {} diff --git a/test/powershell/Language/Scripting/Debugging/DebuggerScriptTests.Tests.ps1 b/test/powershell/Language/Scripting/Debugging/DebuggerScriptTests.Tests.ps1 index 2eb919d9a7e..51d8fc52cee 100644 --- a/test/powershell/Language/Scripting/Debugging/DebuggerScriptTests.Tests.ps1 +++ b/test/powershell/Language/Scripting/Debugging/DebuggerScriptTests.Tests.ps1 @@ -580,7 +580,7 @@ Describe "Unit tests for line breakpoints on modules" -Tags "CI" { if ($null -ne $breakpoint3) { Remove-PSBreakpoint $breakpoint3 } if ($null -ne $breakpoint4) { Remove-PSBreakpoint $breakpoint4 } get-module $moduleName | remove-module - if (Test-Path $moduleDirectory) { Remove-Item $moduleDirectory -r -force -ea silentlycontinue } + if (Test-Path $moduleDirectory) { Remove-Item $moduleDirectory -r -force -ErrorAction silentlycontinue } } } diff --git a/test/powershell/Language/Scripting/I18n.Tests.ps1 b/test/powershell/Language/Scripting/I18n.Tests.ps1 index 144afdf199e..9ca0fbf4227 100644 --- a/test/powershell/Language/Scripting/I18n.Tests.ps1 +++ b/test/powershell/Language/Scripting/I18n.Tests.ps1 @@ -51,7 +51,7 @@ Describe 'Testing of script internationalization' -Tags "CI" { It 'Import non existing culture is done correctly' { - import-localizedData mydata -uiculture nl-NL -ea SilentlyContinue -ev ev + import-localizedData mydata -uiculture nl-NL -ErrorAction SilentlyContinue -ev ev $ev | Should -Not -BeNullOrEmpty $ev[0].Exception | Should -BeOfType "System.Management.Automation.PSInvalidOperationException" diff --git a/test/powershell/Language/Scripting/ScriptHelp.Tests.ps1 b/test/powershell/Language/Scripting/ScriptHelp.Tests.ps1 index a870b50a397..a301a487106 100644 --- a/test/powershell/Language/Scripting/ScriptHelp.Tests.ps1 +++ b/test/powershell/Language/Scripting/ScriptHelp.Tests.ps1 @@ -88,34 +88,34 @@ Describe 'get-help HelpFunc1' -Tags "Feature" { } Context 'get-help helpFunc1 -component blah' { - $x = get-help helpFunc1 -component blah -ea SilentlyContinue -ev e + $x = get-help helpFunc1 -component blah -ErrorAction SilentlyContinue -ev e TestHelpError $x $e 'HelpNotFound,Microsoft.PowerShell.Commands.GetHelpCommand' } Context 'get-help helpFunc1 -component Something' { - $x = get-help helpFunc1 -component Something -ea SilentlyContinue -ev e + $x = get-help helpFunc1 -component Something -ErrorAction SilentlyContinue -ev e TestHelpFunc1 $x It '$e should be empty' { $e.Count | Should -Be 0 } } Context 'get-help helpFunc1 -role blah' { - $x = get-help helpFunc1 -component blah -ea SilentlyContinue -ev e + $x = get-help helpFunc1 -component blah -ErrorAction SilentlyContinue -ev e TestHelpError $x $e 'HelpNotFound,Microsoft.PowerShell.Commands.GetHelpCommand' } Context 'get-help helpFunc1 -role CrazyUser' { - $x = get-help helpFunc1 -role CrazyUser -ea SilentlyContinue -ev e + $x = get-help helpFunc1 -role CrazyUser -ErrorAction SilentlyContinue -ev e TestHelpFunc1 $x It '$e should be empty' { $e.Count | Should -Be 0 } } Context '$x = get-help helpFunc1 -functionality blah' { - $x = get-help helpFunc1 -functionality blah -ea SilentlyContinue -ev e + $x = get-help helpFunc1 -functionality blah -ErrorAction SilentlyContinue -ev e TestHelpError $x $e 'HelpNotFound,Microsoft.PowerShell.Commands.GetHelpCommand' } Context '$x = get-help helpFunc1 -functionality Useless' { - $x = get-help helpFunc1 -functionality Useless -ea SilentlyContinue -ev e + $x = get-help helpFunc1 -functionality Useless -ErrorAction SilentlyContinue -ev e TestHelpFunc1 $x It '$e should be empty' { $e.Count | Should -Be 0 } } @@ -131,7 +131,7 @@ Describe 'get-help file' -Tags "CI" { } AfterAll { - remove-item $tmpfile -Force -ea silentlycontinue + remove-item $tmpfile -Force -ErrorAction silentlycontinue } Context 'get-help file1' { @@ -184,7 +184,7 @@ Describe 'get-help other tests' -Tags "CI" { } AfterAll { - remove-item $tempFile -Force -ea silentlycontinue + remove-item $tempFile -Force -ErrorAction silentlycontinue } Context 'get-help missingHelp' { diff --git a/test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 b/test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 index 114a5ff7e80..73975f940cc 100644 --- a/test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 +++ b/test/powershell/Modules/CimCmdlets/Get-CimClass.Tests.ps1 @@ -15,11 +15,11 @@ try { } It 'produces an error when a non-existent class is used' { - { Get-CimClass -ClassName thisclasstypedoesnotexist -ea stop } | + { Get-CimClass -ClassName thisclasstypedoesnotexist -ErrorAction stop } | Should -Throw -ErrorId "HRESULT 0x80041002,Microsoft.Management.Infrastructure.CimCmdlets.GetCimClassCommand" } It 'produces an error when an improper namespace is used' { - { Get-CimClass -ClassName CIM_OperatingSystem -Namespace badnamespace -ea stop } | + { Get-CimClass -ClassName CIM_OperatingSystem -Namespace badnamespace -ErrorAction stop } | Should -Throw -ErrorId "HRESULT 0x8004100e,Microsoft.Management.Infrastructure.CimCmdlets.GetCimClassCommand" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Core/PSSessionConfiguration.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Core/PSSessionConfiguration.Tests.ps1 index 3a2b42f366a..beb597f9f3e 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Core/PSSessionConfiguration.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Core/PSSessionConfiguration.Tests.ps1 @@ -481,7 +481,7 @@ namespace PowershellTestConfigNamespace $UseSharedProcess = $true Register-PSSessionConfiguration -Name $TestSessionConfigName -path $LocalConfigFilePath -MaximumReceivedObjectSizeMB $psmaximumreceivedobjectsizemb -MaximumReceivedDataSizePerCommandMB $psmaximumreceiveddatasizepercommandmb -UseSharedProcess:$UseSharedProcess -ThreadOptions $pssessionthreadoptions - $Result = [PSObject]@{Session = Get-PSSessionConfiguration -Name $TestSessionConfigName; Culture = (Get-Item WSMan:\localhost\Plugin\$endpointName\lang -ea SilentlyContinue).value} + $Result = [PSObject]@{Session = Get-PSSessionConfiguration -Name $TestSessionConfigName; Culture = (Get-Item WSMan:\localhost\Plugin\$endpointName\lang -ErrorAction SilentlyContinue).value} $Result.Session.Name | Should -Be $TestSessionConfigName $Result.Session.SessionType | Should -Be "Default" @@ -558,7 +558,7 @@ namespace PowershellTestConfigNamespace $UseSharedProcess = $true Set-PSSessionConfiguration -Name $TestSessionConfigName -MaximumReceivedObjectSizeMB $psmaximumreceivedobjectsizemb -MaximumReceivedDataSizePerCommandMB $psmaximumreceiveddatasizepercommandmb -UseSharedProcess:$UseSharedProcess -ThreadOptions $pssessionthreadoptions -NoServiceRestart - $Result = [PSObject]@{Session = (Get-PSSessionConfiguration -Name $TestSessionConfigName) ; Culture = (Get-Item WSMan:\localhost\Plugin\microsoft.powershell\lang -ea SilentlyContinue).value} + $Result = [PSObject]@{Session = (Get-PSSessionConfiguration -Name $TestSessionConfigName) ; Culture = (Get-Item WSMan:\localhost\Plugin\microsoft.powershell\lang -ErrorAction SilentlyContinue).value} $Result.Session.Name | Should -Be $TestSessionConfigName $Result.Session.PSVersion | Should -BeExactly $expectedPSVersion diff --git a/test/powershell/Modules/Microsoft.PowerShell.Diagnostics/Get-WinEvent.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Diagnostics/Get-WinEvent.Tests.ps1 index f7946512261..f5b5929bda5 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Diagnostics/Get-WinEvent.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Diagnostics/Get-WinEvent.Tests.ps1 @@ -80,48 +80,48 @@ Describe 'Get-WinEvent' -Tags "CI" { Context "Get-WinEvent UserData Queries" { It 'Get-WinEvent can retrieve events with UserData queries using FilterXml' { # this relies on apriori knowledge about the log file - # the provided log file has been edited to remove MS PII, so we must use -ea silentlycontinue + # the provided log file has been edited to remove MS PII, so we must use -ErrorAction silentlycontinue $eventLogFile = [io.path]::Combine($PSScriptRoot, "assets", "Saved-Events.evtx") $filter = "<QueryList><Query><Select Path='file://$eventLogFile'>*[UserData/*/Param2='Windows x64']</Select></Query></QueryList>" - $results = Get-WinEvent -FilterXml $filter -ea silentlycontinue + $results = Get-WinEvent -FilterXml $filter -ErrorAction silentlycontinue @($results).Count | Should -Be 1 $results.RecordId | Should -Be 10 } It 'Get-WinEvent can retrieve events with UserData queries using FilterHashtable (one value)' { # this relies on apriori knowledge about the log file - # the provided log file has been edited to remove MS PII, so we must use -ea silentlycontinue + # the provided log file has been edited to remove MS PII, so we must use -ErrorAction silentlycontinue $eventLogFile = [io.path]::Combine($PSScriptRoot, "assets", "Saved-Events.evtx") $filter = @{ path = "$eventLogFile"; Param2 = "Windows x64"} - $results = Get-WinEvent -filterHashtable $filter -ea silentlycontinue + $results = Get-WinEvent -filterHashtable $filter -ErrorAction silentlycontinue @($results).Count | Should -Be 1 $results.RecordId | Should -Be 10 } It 'Get-WinEvent can retrieve events with UserData queries using FilterHashtable (array of values)' { # this relies on apriori knowledge about the log file - # the provided log file has been edited to remove MS PII, so we must use -ea silentlycontinue + # the provided log file has been edited to remove MS PII, so we must use -ErrorAction silentlycontinue $eventLogFile = [io.path]::Combine($PSScriptRoot, "assets", "Saved-Events.evtx") $filter = @{ path = "$eventLogFile"; DriverName = "Remote Desktop Easy Print", "Microsoft enhanced Point and Print compatibility driver" } - $results = Get-WinEvent -filterHashtable $filter -ea silentlycontinue + $results = Get-WinEvent -filterHashtable $filter -ErrorAction silentlycontinue @($results).Count | Should -Be 2 ($results.RecordId -contains 9) | Should -BeTrue ($results.RecordId -contains 11) | Should -BeTrue } It 'Get-WinEvent can retrieve events with UserData queries using FilterHashtable (multiple named params)' { # this relies on apriori knowledge about the log file - # the provided log file has been edited to remove MS PII, so we must use -ea silentlycontinue + # the provided log file has been edited to remove MS PII, so we must use -ErrorAction silentlycontinue $eventLogFile = [io.path]::Combine($PSScriptRoot, "assets", "Saved-Events.evtx") $filter = @{ path = "$eventLogFile"; PackageAware="Not package aware"; DriverName = "Remote Desktop Easy Print", "Microsoft enhanced Point and Print compatibility driver" } - $results = Get-WinEvent -filterHashtable $filter -ea silentlycontinue + $results = Get-WinEvent -filterHashtable $filter -ErrorAction silentlycontinue @($results).Count | Should -Be 2 ($results.RecordId -contains 9) | Should -BeTrue ($results.RecordId -contains 11) | Should -BeTrue } It 'Get-WinEvent can retrieve events with UserData queries using FilterXPath' { # this relies on apriori knowledge about the log file - # the provided log file has been edited to remove MS PII, so we must use -ea silentlycontinue + # the provided log file has been edited to remove MS PII, so we must use -ErrorAction silentlycontinue $eventLogFile = [io.path]::Combine($PSScriptRoot, "assets", "Saved-Events.evtx") $filter = "*/UserData/*/Param2='Windows x64'" - $results = Get-WinEvent -path $eventLogFile -filterXPath $filter -ea silentlycontinue + $results = Get-WinEvent -path $eventLogFile -filterXPath $filter -ErrorAction silentlycontinue @($results).Count | Should -Be 1 $results.RecordId | Should -Be 10 } @@ -129,23 +129,23 @@ Describe 'Get-WinEvent' -Tags "CI" { Context "Get-WinEvent Queries with SuppressHashFilter" { It 'Get-WinEvent can suppress events by Id' { # this relies on apriori knowledge about the log file - # the provided log file has been edited to remove MS PII, so we must use -ea silentlycontinue + # the provided log file has been edited to remove MS PII, so we must use -ErrorAction silentlycontinue $eventLogFile = [io.path]::Combine($PSScriptRoot, "assets", "Saved-Events.evtx") $filter = @{ path = "$eventLogFile"} - $results = Get-WinEvent -filterHashtable $filter -ea silentlycontinue + $results = Get-WinEvent -filterHashtable $filter -ErrorAction silentlycontinue $filterSuppress = @{ path = "$eventLogFile"; SuppressHashFilter=@{Id=370}} - $resultsSuppress = Get-WinEvent -filterHashtable $filterSuppress -ea silentlycontinue + $resultsSuppress = Get-WinEvent -filterHashtable $filterSuppress -ErrorAction silentlycontinue @($results).Count | Should -Be 3 @($resultsSuppress).Count | Should -Be 2 } It 'Get-WinEvent can suppress events by UserData' { # this relies on apriori knowledge about the log file - # the provided log file has been edited to remove MS PII, so we must use -ea silentlycontinue + # the provided log file has been edited to remove MS PII, so we must use -ErrorAction silentlycontinue $eventLogFile = [io.path]::Combine($PSScriptRoot, "assets", "Saved-Events.evtx") $filter = @{ path = "$eventLogFile"} - $results = Get-WinEvent -filterHashtable $filter -ea silentlycontinue + $results = Get-WinEvent -filterHashtable $filter -ErrorAction silentlycontinue $filterSuppress = @{ path = "$eventLogFile"; SuppressHashFilter=@{Param2 = "Windows x64"}} - $resultsSuppress = Get-WinEvent -filterHashtable $filterSuppress -ea silentlycontinue + $resultsSuppress = Get-WinEvent -filterHashtable $filterSuppress -ErrorAction silentlycontinue @($results).Count | Should -Be 3 @($resultsSuppress).Count | Should -Be 2 } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Clear-EventLog.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Clear-EventLog.Tests.ps1 index df5407f1677..28a9e374f03 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Clear-EventLog.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Clear-EventLog.Tests.ps1 @@ -12,7 +12,7 @@ Describe "Clear-EventLog cmdlet tests" -Tags @('CI', 'RequireAdminOnWindows') { } It "should be able to Clear-EventLog" -Pending:($True) { - Remove-EventLog -LogName TestLog -ea Ignore + Remove-EventLog -LogName TestLog -ErrorAction Ignore { New-EventLog -LogName TestLog -Source TestSource -ErrorAction Stop } | Should -Not -Throw { Write-EventLog -LogName TestLog -Source TestSource -Message "Test" -EventID 1 -ErrorAction Stop } | Should -Not -Throw { Get-EventLog -LogName TestLog } | Should -Not -Throw diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Copy.Item.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Copy.Item.Tests.ps1 index ffed38232cc..bb71e8adec9 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Copy.Item.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Copy.Item.Tests.ps1 @@ -455,7 +455,7 @@ Describe "Validate Copy-Item Remotely" -Tags "CI" { } finally { - Remove-Module $testAssembly.ModuleName -Force -ea SilentlyContinue + Remove-Module $testAssembly.ModuleName -Force -ErrorAction SilentlyContinue } } @@ -539,7 +539,7 @@ Describe "Validate Copy-Item Remotely" -Tags "CI" { $testFilePath = Join-Path "TestDrive:" "testfile.txt" if (test-path $testFilePath) { - Remove-Item $testFilePath -Force -ea SilentlyContinue + Remove-Item $testFilePath -Force -ErrorAction SilentlyContinue } "File test content" | Out-File $testFilePath -Force } @@ -685,16 +685,16 @@ Describe "Validate Copy-Item error for target sessions not in FullLanguageMode." $testSessions[$languageMode] = $testSession # Remove the pssc file. - Remove-Item $configFilePath -Force -ea SilentlyContinue + Remove-Item $configFilePath -Force -ErrorAction SilentlyContinue } } AfterAll { - $testSessions.Values | Remove-PSSession -ea SilentlyContinue + $testSessions.Values | Remove-PSSession -ErrorAction SilentlyContinue $sessionToUnregister | ForEach-Object { - Unregister-PSSessionConfiguration -Name $_ -Force -ea SilentlyContinue + Unregister-PSSessionConfiguration -Name $_ -Force -ErrorAction SilentlyContinue } } @@ -720,7 +720,7 @@ Describe "Copy-Item can use Recurse and Exclude together" -Tags "Feature" { Context "Local and Remote Tests" { BeforeAll { - $s = New-PSSession -ComputerName . -ea SilentlyContinue + $s = New-PSSession -ComputerName . -ErrorAction SilentlyContinue if (-not $s) { throw "Failed to create PSSession for remote copy operations." @@ -801,7 +801,7 @@ Describe "Copy-Item remotely bug fixes" -Tags "Feature" { Copy-Item -Path "TestDrive:\Source\testFile1.txt" -Destination "$TestDrive\Destination\testFile1.txt" -ToSession $s # Validate the the file was overwritten - $fileContent = Get-Content "TestDrive:\Destination\testFile1.txt" -ea SilentlyContinue -Raw + $fileContent = Get-Content "TestDrive:\Destination\testFile1.txt" -ErrorAction SilentlyContinue -Raw $fileContent | Should -Match $newContent } @@ -811,7 +811,7 @@ Describe "Copy-Item remotely bug fixes" -Tags "Feature" { Copy-Item -Path "$TestDrive\Source\testFile1.txt" -Destination "TestDrive:\Destination\testFile1.txt" -FromSession $s # Validate the the file was overwritten - $fileContent = Get-Content "TestDrive:\Destination\testFile1.txt" -ea SilentlyContinue -Raw + $fileContent = Get-Content "TestDrive:\Destination\testFile1.txt" -ErrorAction SilentlyContinue -Raw $fileContent | Should -Match $newContent } } @@ -822,7 +822,7 @@ Describe "Copy-Item remotely bug fixes" -Tags "Feature" { if (Test-Path "TestDrive:\AnotherDestination") { - Remove-Item "TestDrive:\AnotherDestination" -Force -Recurse -ea SilentlyContinue + Remove-Item "TestDrive:\AnotherDestination" -Force -Recurse -ErrorAction SilentlyContinue } $null = New-Item -ItemType Directory -Path "TestDrive:\AnotherDestination" diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/New-EventLog.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/New-EventLog.Tests.ps1 index e9d84e6af65..c0af78122c2 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/New-EventLog.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/New-EventLog.Tests.ps1 @@ -14,7 +14,7 @@ Describe "New-EventLog cmdlet tests" -Tags @('CI', 'RequireAdminOnWindows') { BeforeEach { if ($IsNotSkipped) { - Remove-EventLog -LogName TestLog -ea Ignore + Remove-EventLog -LogName TestLog -ErrorAction Ignore } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Remove-EventLog.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Remove-EventLog.Tests.ps1 index e289cf362a1..92ef62f931a 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Remove-EventLog.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Remove-EventLog.Tests.ps1 @@ -14,7 +14,7 @@ Describe "New-EventLog cmdlet tests" -Tags @('CI', 'RequireAdminOnWindows') { BeforeEach { if ($IsNotSkipped) { - Remove-EventLog -LogName TestLog -ea Ignore + Remove-EventLog -LogName TestLog -ErrorAction Ignore {New-EventLog -LogName TestLog -Source TestSource -ErrorAction Stop} | Should -Not -Throw {Write-EventLog -LogName TestLog -Source TestSource -Message "Test" -EventID 1 -ErrorAction Stop} | Should -Not -Throw } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/ConstrainedLanguageRestriction.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/ConstrainedLanguageRestriction.Tests.ps1 index 512f8dbedea..3660606284f 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/ConstrainedLanguageRestriction.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/ConstrainedLanguageRestriction.Tests.ps1 @@ -78,7 +78,7 @@ if ($IsWindows) } '@ - if (-not (Get-Command Invoke-LanguageModeTestingSupportCmdlet -ea Ignore)) + if (-not (Get-Command Invoke-LanguageModeTestingSupportCmdlet -ErrorAction Ignore)) { $moduleName = Get-RandomFileName $moduleDirectory = join-path $TestDrive\Modules $moduleName diff --git a/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 index d1a704bb56d..86842457eb2 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Security/ExecutionPolicy.Tests.ps1 @@ -84,7 +84,7 @@ try { $testDirectory = Join-Path $drive ("MultiMachineTestData\Commands\Cmdlets\Security_TestData\ExecutionPolicyTestData") if(Test-Path $testDirectory) { - Remove-Item -Force -Recurse $testDirectory -ea SilentlyContinue + Remove-Item -Force -Recurse $testDirectory -ErrorAction SilentlyContinue } $null = New-Item $testDirectory -ItemType Directory -Force $remoteTestDirectory = $testDirectory @@ -521,8 +521,8 @@ ZoneId=$FileType #Clean up $testDirectory = $remoteTestDirectory - Remove-Item $testDirectory -Recurse -Force -ea SilentlyContinue - Remove-Item function:createTestFile -ea SilentlyContinue + Remove-Item $testDirectory -Recurse -Force -ErrorAction SilentlyContinue + Remove-Item function:createTestFile -ErrorAction SilentlyContinue } } @@ -597,8 +597,8 @@ ZoneId=$FileType # Clean up $testDirectory = $remoteTestDirectory - Remove-Item $testDirectory -Recurse -Force -ea SilentlyContinue - Remove-Item function:createTestFile -ea SilentlyContinue + Remove-Item $testDirectory -Recurse -Force -ErrorAction SilentlyContinue + Remove-Item function:createTestFile -ErrorAction SilentlyContinue } } Context "Validate that 'Unrestricted' execution policy works on OneCore powershell" { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Debug-Runspace.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Debug-Runspace.Tests.ps1 index abf6d286172..681cafd18bd 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Debug-Runspace.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Debug-Runspace.Tests.ps1 @@ -15,21 +15,21 @@ Describe "Debug-Runspace" -tag "CI" { } It "Debugging a runspace should fail if the name is ambiguous" { - { Debug-Runspace -Name "My*" -ea stop } | Should -Throw -ErrorId "DebugRunspaceTooManyRunspaceFound,Microsoft.PowerShell.Commands.DebugRunspaceCommand" + { Debug-Runspace -Name "My*" -ErrorAction stop } | Should -Throw -ErrorId "DebugRunspaceTooManyRunspaceFound,Microsoft.PowerShell.Commands.DebugRunspaceCommand" } It "Debugging a runspace should fail if the name is not found" { - { Debug-Runspace -Name "dflkjsdkfjldkjssldfj" -ea stop } | Should -Throw -ErrorId "DebugRunspaceNoRunspaceFound,Microsoft.PowerShell.Commands.DebugRunspaceCommand" + { Debug-Runspace -Name "dflkjsdkfjldkjssldfj" -ErrorAction stop } | Should -Throw -ErrorId "DebugRunspaceNoRunspaceFound,Microsoft.PowerShell.Commands.DebugRunspaceCommand" } It "Debugging a runspace should fail if the runspace is not open" { $rs2.Close() - { Debug-Runspace -runspace $rs2 -ea stop } | Should -Throw -ErrorId "InvalidOperation,Microsoft.PowerShell.Commands.DebugRunspaceCommand" + { Debug-Runspace -runspace $rs2 -ErrorAction stop } | Should -Throw -ErrorId "InvalidOperation,Microsoft.PowerShell.Commands.DebugRunspaceCommand" } It "Debugging a runspace should fail if the runspace has no debugger" { $rs1.Debugger.SetDebugMode("None") - { Debug-Runspace -runspace $rs1 -ea stop } | Should -Throw -ErrorId "InvalidOperation,Microsoft.PowerShell.Commands.DebugRunspaceCommand" + { Debug-Runspace -runspace $rs1 -ErrorAction stop } | Should -Throw -ErrorId "InvalidOperation,Microsoft.PowerShell.Commands.DebugRunspaceCommand" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 index 3f79b0a380d..e3e9bb70f7d 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Format-Table.Tests.ps1 @@ -21,7 +21,7 @@ Describe "Format-Table" -Tags "CI" { It "Format-Table with not existing table with force should throw PipelineStoppedException"{ $obj = New-Object -typename PSObject - $e = { $obj | Format-Table -view bar -force -EA Stop } | + $e = { $obj | Format-Table -view bar -force -ErrorAction Stop } | Should -Throw -ErrorId "FormatViewNotFound,Microsoft.PowerShell.Commands.FormatTableCommand" -PassThru $e.CategoryInfo | Should -Match "PipelineStoppedException" } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Variable.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Variable.Tests.ps1 index 6dba5a18bea..e509f199750 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Variable.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Variable.Tests.ps1 @@ -3,7 +3,7 @@ Describe "Get-Variable DRT Unit Tests" -Tags "CI" { It "Get-Variable of not existing variable Name should throw ItemNotFoundException"{ - { Get-Variable -EA Stop -Name nonexistingVariableName } | + { Get-Variable -ErrorAction Stop -Name nonexistingVariableName } | Should -Throw -ErrorId "VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand" } @@ -39,7 +39,7 @@ Describe "Get-Variable DRT Unit Tests" -Tags "CI" { It "Get-Variable of existing private variable Name should throw ItemNotFoundException"{ Set-Variable newVar testing -Option Private - {Get-Variable -Name newVar -EA Stop} | + {Get-Variable -Name newVar -ErrorAction Stop} | Should -Throw -ErrorId "VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/ImportExportCSV.Delimiter.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/ImportExportCSV.Delimiter.Tests.ps1 index 9400c97ed9e..3d840120e2a 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/ImportExportCSV.Delimiter.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/ImportExportCSV.Delimiter.Tests.ps1 @@ -37,7 +37,7 @@ Describe "Using delimiters with Export-CSV and Import-CSV behave correctly" -tag else { [System.Globalization.CultureInfo]::CurrentCulture.TextInfo.ListSeparator = $defaultDelimiter } - remove-item -force -ea silentlycontinue TESTDRIVE:/file.csv + remove-item -force -ErrorAction silentlycontinue TESTDRIVE:/file.csv } It "Disallow use of null delimiter" { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/New-Object.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/New-Object.Tests.ps1 index 2046ab829ca..a66854d071b 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/New-Object.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/New-Object.Tests.ps1 @@ -84,19 +84,19 @@ Describe "New-Object DRT basic functionality" -Tags "CI" { } It "New-Object with invalid type should throw Exception"{ - $e = { New-Object -TypeName LiarType -EA Stop } | Should -Throw -ErrorId "TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand" -PassThru + $e = { New-Object -TypeName LiarType -ErrorAction Stop } | Should -Throw -ErrorId "TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand" -PassThru $e.CategoryInfo | Should -Match "PSArgumentException" } It "New-Object with invalid argument should throw Exception"{ - $e = { New-Object -TypeName System.Management.Automation.PSVariable -ArgumentList "A", 1, None, "asd" -EA Stop } | + $e = { New-Object -TypeName System.Management.Automation.PSVariable -ArgumentList "A", 1, None, "asd" -ErrorAction Stop } | Should -Throw -ErrorId "ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand" -PassThru $e.CategoryInfo | Should -Match "MethodException" } It "New-Object with abstract class should throw Exception"{ Add-Type -TypeDefinition "public abstract class AbstractEmployee{public AbstractEmployee(){}}" - $e = { New-Object -TypeName AbstractEmployee -EA Stop } | + $e = { New-Object -TypeName AbstractEmployee -ErrorAction Stop } | Should -Throw -ErrorId "ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand" -PassThru $e.CategoryInfo | Should -Match "MethodInvocationException" } @@ -106,7 +106,7 @@ Describe "New-Object DRT basic functionality" -Tags "CI" { { Add-Type -TypeDefinition "public class Employee{public Employee(string firstName,string lastName,int yearsInMS){FirstName = firstName;LastName=lastName;YearsInMS = yearsInMS;}public string FirstName;public string LastName;public int YearsInMS;}" } - $e = { New-Object -TypeName Employee -ArgumentList 11 -EA Stop } | Should -Throw -ErrorId "ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand" -PassThru + $e = { New-Object -TypeName Employee -ArgumentList 11 -ErrorAction Stop } | Should -Throw -ErrorId "ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand" -PassThru $e.CategoryInfo | Should -Match "MethodException" } @@ -116,12 +116,12 @@ Describe "New-Object DRT basic functionality" -Tags "CI" { { Add-Type -TypeDefinition "public class Employee{public Employee(string firstName,string lastName,int yearsInMS){FirstName = firstName;LastName=lastName;YearsInMS = yearsInMS;}public string FirstName;public string LastName;public int YearsInMS;}" } - { New-Object -TypeName Employee -EA Stop } | Should -Throw -ErrorId "CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand" + { New-Object -TypeName Employee -ErrorAction Stop } | Should -Throw -ErrorId "CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand" } It "New-Object with Private Nested class should throw Exception"{ Add-Type -TypeDefinition "public class WeirdEmployee{public WeirdEmployee(){}private class PrivateNestedWeirdEmployee{public PrivateNestedWeirdEmployee(){}}}" - $e = { New-Object -TypeName WeirdEmployee+PrivateNestedWeirdEmployee -EA Stop } | Should -Throw -ErrorId "TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand" -PassThru + $e = { New-Object -TypeName WeirdEmployee+PrivateNestedWeirdEmployee -ErrorAction Stop } | Should -Throw -ErrorId "TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand" -PassThru $e.CategoryInfo | Should -Match "PSArgumentException" } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/New-Variable.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/New-Variable.Tests.ps1 index af487e989f2..ae7af5dddc3 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/New-Variable.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/New-Variable.Tests.ps1 @@ -23,7 +23,7 @@ Describe "New-Variable DRT Unit Tests" -Tags "CI" { It "New-Variable variable twice should throw Exception"{ New-Variable foo bogus - $e = { New-Variable foo bar -Scope 1 -EA Stop } | + $e = { New-Variable foo bar -Scope 1 -ErrorAction Stop } | Should -Throw -ErrorId "VariableAlreadyExists,Microsoft.PowerShell.Commands.NewVariableCommand" -PassThru $e.CategoryInfo | Should -Match "SessionStateException" @@ -38,7 +38,7 @@ Describe "New-Variable DRT Unit Tests" -Tags "CI" { It "New-Variable ReadOnly variable twice should throw Exception"{ New-Variable foo bogus -option ReadOnly - $e = { New-Variable foo bar -Scope 1 -EA Stop } | + $e = { New-Variable foo bar -Scope 1 -ErrorAction Stop } | Should -Throw -ErrorId "VariableAlreadyExists,Microsoft.PowerShell.Commands.NewVariableCommand" -PassThru $e.CategoryInfo | Should -Match "SessionStateException" @@ -197,11 +197,11 @@ Describe "New-Variable" -Tags "CI" { Context "Scope Tests" { BeforeAll { - if ( get-variable -scope global -name globalVar1 -ea SilentlyContinue ) + if ( get-variable -scope global -name globalVar1 -ErrorAction SilentlyContinue ) { Remove-Variable -scope global -name globalVar1 } - if ( get-variable -scope script -name scriptvar -ea SilentlyContinue ) + if ( get-variable -scope script -name scriptvar -ErrorAction SilentlyContinue ) { remove-variable -scope script -name scriptvar } @@ -222,7 +222,7 @@ Describe "New-Variable" -Tags "CI" { get-variable -Scope global -name globalVar1 -ValueOnly | Should -Be 1 } It "Should be able to create a local scope variable using the local switch" { - Get-Variable -scope local -name localvar -ValueOnly -ea silentlycontinue | Should -BeNullOrEmpty + Get-Variable -scope local -name localvar -ValueOnly -ErrorAction silentlycontinue | Should -BeNullOrEmpty New-Variable -Scope local -Name localVar -value 10 get-variable -scope local -name localvar -ValueOnly | Should -Be 10 } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Remove-Variable.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Remove-Variable.Tests.ps1 index af57bbcaaea..f631450de1b 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Remove-Variable.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Remove-Variable.Tests.ps1 @@ -207,34 +207,34 @@ Describe "Remove-Variable basic functionality" -Tags "CI" { It "Remove-Variable variable should works"{ New-Variable foo bar Remove-Variable foo - $var1 = Get-Variable -Name foo -EA SilentlyContinue + $var1 = Get-Variable -Name foo -ErrorAction SilentlyContinue $var1 | Should -BeNullOrEmpty } It "Remove-Variable Constant variable should throw SessionStateUnauthorizedAccessException"{ New-Variable foo bar -Option Constant - $e = { Remove-Variable foo -Scope 1 -EA Stop } | + $e = { Remove-Variable foo -Scope 1 -ErrorAction Stop } | Should -Throw -ErrorId "VariableNotRemovable,Microsoft.PowerShell.Commands.RemoveVariableCommand" -PassThru $e.CategoryInfo | Should -Match "SessionStateUnauthorizedAccessException" } It "Remove-Variable ReadOnly variable should throw SessionStateUnauthorizedAccessException and force remove should work"{ New-Variable foo bar -Option ReadOnly - $e = { Remove-Variable foo -Scope 1 -EA Stop } | + $e = { Remove-Variable foo -Scope 1 -ErrorAction Stop } | Should -Throw -ErrorId "VariableNotRemovable,Microsoft.PowerShell.Commands.RemoveVariableCommand" -PassThru $e.CategoryInfo | Should -Match "SessionStateUnauthorizedAccessException" Remove-Variable foo -Force - $var1 = Get-Variable -Name foo -EA SilentlyContinue + $var1 = Get-Variable -Name foo -ErrorAction SilentlyContinue $var1 | Should -BeNullOrEmpty } It "Remove-Variable Constant variable should throw SessionStateUnauthorizedAccessException and force remove should also throw exception"{ New-Variable foo bar -Option Constant - $e = { Remove-Variable foo -Scope 1 -EA Stop } | + $e = { Remove-Variable foo -Scope 1 -ErrorAction Stop } | Should -Throw -ErrorId "VariableNotRemovable,Microsoft.PowerShell.Commands.RemoveVariableCommand" -PassThru $e.CategoryInfo | Should -Match "SessionStateUnauthorizedAccessException" - { Remove-Variable foo -Force -Scope 1 -EA Stop } | + { Remove-Variable foo -Force -Scope 1 -ErrorAction Stop } | Should -Throw -ErrorId "VariableNotRemovable,Microsoft.PowerShell.Commands.RemoveVariableCommand" -PassThru $e.CategoryInfo | Should -Match "SessionStateUnauthorizedAccessException" } @@ -244,7 +244,7 @@ Describe "Remove-Variable basic functionality" -Tags "CI" { &{ Clear-Variable foo Remove-Variable foo - $e = { Get-Variable -Name foo -Scope local -EA Stop } | + $e = { Get-Variable -Name foo -Scope local -ErrorAction Stop } | Should -Throw -ErrorId "VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand" -PassThru $e.CategoryInfo | Should -Match "ItemNotFoundException" } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Select-Object.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Select-Object.Tests.ps1 index b1d44da530f..ffcc08bacef 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Select-Object.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Select-Object.Tests.ps1 @@ -124,7 +124,7 @@ Describe "Select-Object DRT basic functionality" -Tags "CI" { } It "Select-Object with empty script block property should throw"{ - $e = { "bar" | select-object -Prop {} -EA Stop } | + $e = { "bar" | select-object -Prop {} -ErrorAction Stop } | Should -Throw -ErrorId "EmptyScriptBlockAndNoName,Microsoft.PowerShell.Commands.SelectObjectCommand" -PassThru $e.CategoryInfo | Should -Match "PSArgumentException" } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Set-Variable.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Set-Variable.Tests.ps1 index b2a46790e1d..f6afcd44acf 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Set-Variable.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Set-Variable.Tests.ps1 @@ -91,7 +91,7 @@ Describe "Set-Variable DRT Unit Tests" -Tags "CI" { It "Set-Variable overwrite Constant Option should throw SessionStateUnauthorizedAccessException"{ Set-Variable -Name abcaVar bar -Option Constant -Scope "local" - { Set-Variable -Name abcaVar new -Scope 1 -EA Stop } | Should -Throw -ErrorId "VariableNotWritable,Microsoft.PowerShell.Commands.SetVariableCommand" + { Set-Variable -Name abcaVar new -Scope 1 -ErrorAction Stop } | Should -Throw -ErrorId "VariableNotWritable,Microsoft.PowerShell.Commands.SetVariableCommand" } It "Set-Variable of existing Private variable without force should throw Exception"{ @@ -111,8 +111,8 @@ Describe "Set-Variable DRT Unit Tests" -Tags "CI" { } It "Set-Variable with Exclude, then Get-Variable it should throw ItemNotFoundException"{ - Set-Variable -Name foo1,foo2 hello -Exclude foo2 -EA Stop - { Get-Variable -Name foo2 -EA Stop } | Should -Throw -ErrorId "VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand" + Set-Variable -Name foo1,foo2 hello -Exclude foo2 -ErrorAction Stop + { Get-Variable -Name foo2 -ErrorAction Stop } | Should -Throw -ErrorId "VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand" } It "Set-Variable of existing ReadOnly variable without force should throw Exception"{ @@ -122,7 +122,7 @@ Describe "Set-Variable DRT Unit Tests" -Tags "CI" { $var1.Value|Should -BeExactly "bar" $var1.Options|Should -BeExactly "ReadOnly" $var1.Description|Should -BeExactly "new description" - { Set-Variable abcaVar -Option None -Scope 1 -EA Stop } | Should -Throw -ErrorId "VariableNotWritable,Microsoft.PowerShell.Commands.SetVariableCommand" + { Set-Variable abcaVar -Option None -Scope 1 -ErrorAction Stop } | Should -Throw -ErrorId "VariableNotWritable,Microsoft.PowerShell.Commands.SetVariableCommand" } It "Set-Variable of ReadOnly variable with private scope should work"{ diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index e6f341bee81..87de03650b5 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -48,12 +48,12 @@ function ExecuteRequestWithOutFile { } else { Invoke-RestMethod -Uri $uri -OutFile $filePath } - $result.Output = Get-Content $filePath -Raw -ea SilentlyContinue + $result.Output = Get-Content $filePath -Raw -ErrorAction SilentlyContinue } catch { $result.Error = $_ } finally { if (Test-Path $filePath) { - Remove-Item $filePath -Force -ea SilentlyContinue + Remove-Item $filePath -Force -ErrorAction SilentlyContinue } } return $result diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Stream.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Stream.Tests.ps1 index 99e822adde0..f04a87c8c0e 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Stream.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Stream.Tests.ps1 @@ -34,7 +34,7 @@ Describe "Stream writer tests" -Tags "CI" { } It "Should write debug messages to the debug stream" { - Write-Messages -Debug -EA SilentlyContinue 5>&1 > $targetfile + Write-Messages -Debug -ErrorAction SilentlyContinue 5>&1 > $targetfile # The contents of the debug stream should contain the expected text $targetfile | Should -FileContentMatch "Debug Message" } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/clixml.tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/clixml.tests.ps1 index d6b12600a4e..334b4c52936 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/clixml.tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/clixml.tests.ps1 @@ -181,7 +181,7 @@ Describe "Deserializing corrupted Cim classes should not instantiate non-Cim typ # Only run on Windows platform. # Ensure calc.exe is avaiable for test. - $shouldRunTest = $IsWindows -and ((Get-Command calc.exe -ea SilentlyContinue) -ne $null) + $shouldRunTest = $IsWindows -and ((Get-Command calc.exe -ErrorAction SilentlyContinue) -ne $null) $skipNotWindows = ! $shouldRunTest if ( $shouldRunTest ) { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/object.tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/object.tests.ps1 index c4f24590b30..f329e90cdf6 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/object.tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/object.tests.ps1 @@ -90,12 +90,12 @@ Describe "Object cmdlets" -Tags "CI" { } It 'should return correct error for non-numeric input' { - $gmi = "abc",[Datetime]::Now | measure -sum -max -ev err -ea silentlycontinue + $gmi = "abc",[Datetime]::Now | measure -sum -max -ev err -ErrorAction silentlycontinue $err | ForEach-Object { $_.FullyQualifiedErrorId | Should -Be 'NonNumericInputObject,Microsoft.PowerShell.Commands.MeasureObjectCommand' } } It 'should have the correct count' { - $gmi = "abc",[Datetime]::Now | measure -sum -max -ev err -ea silentlycontinue + $gmi = "abc",[Datetime]::Now | measure -sum -max -ev err -ErrorAction silentlycontinue $gmi.Count | Should -Be 2 } } diff --git a/test/powershell/engine/Cdxml/Cdxml.Tests.ps1 b/test/powershell/engine/Cdxml/Cdxml.Tests.ps1 index 16061a9e00e..0cda7b25af8 100644 --- a/test/powershell/engine/Cdxml/Cdxml.Tests.ps1 +++ b/test/powershell/engine/Cdxml/Cdxml.Tests.ps1 @@ -34,7 +34,7 @@ Describe "Cdxml cmdlets are supported" -Tag CI,RequireAdminOnWindows { # there is a possibility that we could be on Windows, but MofComp # isn't present, in any event we will mark these tests as skipped # since the environment won't support loading the test classes - if ( (Get-Command -ea SilentlyContinue Mofcomp.exe) -eq $null ) { + if ( (Get-Command -ErrorAction SilentlyContinue Mofcomp.exe) -eq $null ) { $script:ItSkipOrPending = @{ Skip = $true } return } @@ -138,7 +138,7 @@ Describe "Cdxml cmdlets are supported" -Tag CI,RequireAdminOnWindows { } It "The Get-CimTest cmdlet should return the proper error if the instance does not exist" @ItSkipOrPending { - { Get-CimTest -ea stop -id "ThisIdDoesNotExist" } | Should -Throw -ErrorId "CmdletizationQuery_NotFound_Id,Get-CimTest" + { Get-CimTest -ErrorAction stop -id "ThisIdDoesNotExist" } | Should -Throw -ErrorId "CmdletizationQuery_NotFound_Id,Get-CimTest" } It "The Get-CimTest cmdlet should work as a job" @ItSkipOrPending { @@ -232,7 +232,7 @@ Describe "Cdxml cmdlets are supported" -Tag CI,RequireAdminOnWindows { } { New-CimTest @instanceArgs } | Should -Throw -ErrorId "ParameterArgumentTransformationError,New-CimTest" # just make sure that it wasn't added - Get-CimTest -id $instanceArgs.Id -ea SilentlyContinue | Should -BeNullOrEmpty + Get-CimTest -id $instanceArgs.Id -ErrorAction SilentlyContinue | Should -BeNullOrEmpty } It "Should support -whatif" @ItSkipOrPending { @@ -243,7 +243,7 @@ Describe "Cdxml cmdlets are supported" -Tag CI,RequireAdminOnWindows { Whatif = $true } New-CimTest @instanceArgs - Get-CimTest -id $instanceArgs.Id -ea SilentlyContinue | Should -BeNullOrEmpty + Get-CimTest -id $instanceArgs.Id -ErrorAction SilentlyContinue | Should -BeNullOrEmpty } } diff --git a/test/powershell/engine/Help/HelpSystem.OnlineHelp.Tests.ps1 b/test/powershell/engine/Help/HelpSystem.OnlineHelp.Tests.ps1 index ccc68e7be27..c14ef99ff04 100644 --- a/test/powershell/engine/Help/HelpSystem.OnlineHelp.Tests.ps1 +++ b/test/powershell/engine/Help/HelpSystem.OnlineHelp.Tests.ps1 @@ -26,12 +26,12 @@ Describe 'Online help tests for PowerShell Core Cmdlets' -Tags "CI" { foreach ($filePath in @("$PSScriptRoot\assets\HelpURI\V2Cmdlets.csv", "$PSScriptRoot\assets\HelpURI\V3Cmdlets.csv")) { - $cmdletList = Import-Csv $filePath -ea Stop + $cmdletList = Import-Csv $filePath -ErrorAction Stop foreach ($cmdlet in $cmdletList) { # If the cmdlet is not preset in CoreCLR, skip it. - $skipTest = $null -eq (Get-Command $cmdlet.TopicTitle -ea SilentlyContinue) + $skipTest = $null -eq (Get-Command $cmdlet.TopicTitle -ErrorAction SilentlyContinue) # TopicTitle - is the cmdlet name in the csv file # HelpURI - is the expected help URI in the csv file diff --git a/test/powershell/engine/Help/UpdatableHelpSystem.Tests.ps1 b/test/powershell/engine/Help/UpdatableHelpSystem.Tests.ps1 index 39af4273f38..07f14c4ec0e 100644 --- a/test/powershell/engine/Help/UpdatableHelpSystem.Tests.ps1 +++ b/test/powershell/engine/Help/UpdatableHelpSystem.Tests.ps1 @@ -166,7 +166,7 @@ function GetFiles [string]$path ) - Get-ChildItem $path -Include $fileType -Recurse -ea SilentlyContinue | Select-Object -ExpandProperty FullName + Get-ChildItem $path -Include $fileType -Recurse -ErrorAction SilentlyContinue | Select-Object -ExpandProperty FullName } function ValidateInstalledHelpContent @@ -325,7 +325,7 @@ function RunSaveHelpTests } finally { - Remove-Item $saveHelpFolder -Force -ea SilentlyContinue -Recurse + Remove-Item $saveHelpFolder -Force -ErrorAction SilentlyContinue -Recurse } } } diff --git a/test/powershell/engine/ResourceValidation/TestRunner.ps1 b/test/powershell/engine/ResourceValidation/TestRunner.ps1 index 85b9447c515..01e3db38dcb 100644 --- a/test/powershell/engine/ResourceValidation/TestRunner.ps1 +++ b/test/powershell/engine/ResourceValidation/TestRunner.ps1 @@ -9,7 +9,7 @@ function Test-ResourceStrings $repoBase = (Resolve-Path (Join-Path $psScriptRoot ../../../..)).Path $asmBase = Join-Path $repoBase "src/$AssemblyName" $resourceDir = Join-Path $asmBase resources - $resourceFiles = Get-ChildItem $resourceDir -Filter *.resx -ea stop | + $resourceFiles = Get-ChildItem $resourceDir -Filter *.resx -ErrorAction stop | Where-Object { $excludeList -notcontains $_.Name } $bindingFlags = [reflection.bindingflags]"NonPublic,Static" From bc0ddc1123fe774b54c7e78b93ba392208191156 Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Tue, 24 Apr 2018 14:19:11 -0700 Subject: [PATCH 50/58] [Feature] Unblock-File tests fixes. --- .../Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 index 1b3a3e69d7d..b85cb1156f0 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Unblock-File.Tests.ps1 @@ -40,7 +40,7 @@ Describe "Unblock-File" -Tags "CI" { It "With '-Path': file exist" { Unblock-File -Path $testfilepath - Test-UnblockFile | Should -BeTrue + Test-UnblockFile # If a file is not blocked we silently return without an error. { Unblock-File -Path $testfilepath -ErrorAction Stop } | Should -Not -Throw @@ -48,7 +48,7 @@ Describe "Unblock-File" -Tags "CI" { It "With '-LiteralPath': file exist" { Unblock-File -LiteralPath $testfilepath - Test-UnblockFile | Should -BeTrue + Test-UnblockFile } It "Write an error if a file is read only" { From b588fbad33c9bf11dd834405063afe9160e58298 Mon Sep 17 00:00:00 2001 From: Klaudia Algiz <klalgiz@microsoft.com> Date: Wed, 25 Apr 2018 10:07:25 -0700 Subject: [PATCH 51/58] [Feautre] Test fix. --- .../engine/Remoting/SSHRemotingAPI.Tests.ps1 | 34 ++++++++----------- 1 file changed, 15 insertions(+), 19 deletions(-) diff --git a/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 b/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 index a07a4c9c641..c3fb0951682 100644 --- a/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 +++ b/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 @@ -25,31 +25,27 @@ Describe "SSH Remoting API Tests" -Tags "Feature" { } It "SSHConnectionInfo should throw file not found exception for invalid key file path" -Skip:$skipTest { + $sshConnectionInfo = [System.Management.Automation.Runspaces.SSHConnectionInfo]::new( + "UserName", + "localhost", + "NoValidKeyFilePath", + 22) - $e = { - $sshConnectionInfo = [System.Management.Automation.Runspaces.SSHConnectionInfo]::new( - "UserName", - "localhost", - "NoValidKeyFilePath", - 22) + $rs = [runspacefactory]::CreateRunspace($sshConnectionInfo) - $rs = [runspacefactory]::CreateRunspace($sshConnectionInfo) - $rs.Open() - } | Should -Throw -PassThru + $e = { $rs.Open() } | Should -Throw -PassThru $e.Exception.InnerException.InnerException | Should -BeOfType "System.IO.FileNotFoundException" } It "SSHConnectionInfo should throw argument exception for invalid port (non 16bit uint)" { - $e = { - $sshConnectionInfo = [System.Management.Automation.Runspaces.SSHConnectionInfo]::new( - "UserName", - "localhost", - "ValidKeyFilePath", - 99999) - - $rs = [runspacefactory]::CreateRunspace($sshConnectionInfo) - $rs.Open() - } | Should -Throw -PassThru + $sshConnectionInfo = [System.Management.Automation.Runspaces.SSHConnectionInfo]::new( + "UserName", + "localhost", + "ValidKeyFilePath", + 99999) + + $rs = [runspacefactory]::CreateRunspace($sshConnectionInfo) + $e = { $rs.Open() } | Should -Throw -PassThru $e.Exception.InnerException | Should -BeOfType "System.ArgumentException" } } From e6bdde95a34206371d592cc5a1c2cf3f21ef2600 Mon Sep 17 00:00:00 2001 From: Klaudia Algiz <klalgiz@microsoft.com> Date: Wed, 25 Apr 2018 10:34:04 -0700 Subject: [PATCH 52/58] [Feature] Test in ConsoleHost.Tests.ps1 clean up. --- test/powershell/Host/ConsoleHost.Tests.ps1 | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/test/powershell/Host/ConsoleHost.Tests.ps1 b/test/powershell/Host/ConsoleHost.Tests.ps1 index e3e41669b95..7edd8cc697d 100644 --- a/test/powershell/Host/ConsoleHost.Tests.ps1 +++ b/test/powershell/Host/ConsoleHost.Tests.ps1 @@ -99,13 +99,12 @@ Describe "ConsoleHost unit tests" -tags "Feature" { It "Verify Validate Dollar Error Populated should throw exception" { $origEA = $ErrorActionPreference $ErrorActionPreference = "Stop" + $a = 1,2,3 $e = { - $a = 1,2,3 $a | & $powershell -noprofile -command { wgwg-wrwrhqwrhrh35h3h3} - } | Should -Throw -PassThru + } | Should -Throw -ErrorId "CommandNotFoundException" -PassThru $e.ToString() | Should -Match "wgwg-wrwrhqwrhrh35h3h3" - $e.FullyQualifiedErrorId | Should -Be "CommandNotFoundException" $ErrorActionPreference = $origEA } From fc53623633a7e6f60442af0a4e190662988b40cd Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Wed, 25 Apr 2018 12:03:26 -0700 Subject: [PATCH 53/58] [Feature] Test fix --- .../Microsoft.PowerShell.Management/New-Item.Tests.ps1 | 3 ++- test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 | 9 +++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/New-Item.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/New-Item.Tests.ps1 index 5ec37f99cfa..7f05603d74d 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/New-Item.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/New-Item.Tests.ps1 @@ -180,13 +180,14 @@ Describe "New-Item with links" -Tags @('CI', 'RequireAdminOnWindows') { } It "Should error correctly when failing to create a symbolic link" -Skip:($IsWindows -or $IsElevated) { + Write-Host "Iselevated: $IsElevated" # This test expects that /sbin exists but is not writable by the user { New-Item -ItemType SymbolicLink -Path "/sbin/powershell-test" -Target $FullyQualifiedFolder -ErrorAction Stop } | Should -Throw -ErrorId "NewItemSymbolicLinkElevationRequired,Microsoft.PowerShell.Commands.NewItemCommand" } It "New-Item -ItemType SymbolicLink should understand directory path ending with slash" { - $folderName = [System.IO.Path]::GetRandomFileName() + $folderName = [System.IO.Path]::GetRandomFileName() $symbolicLinkPath = New-Item -ItemType SymbolicLink -Path "$tmpDirectory/$folderName/" -Value "/bar/" $symbolicLinkPath | Should -Not -BeNullOrEmpty } diff --git a/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 b/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 index c3fb0951682..9c9a0aa7e5f 100644 --- a/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 +++ b/test/powershell/engine/Remoting/SSHRemotingAPI.Tests.ps1 @@ -38,15 +38,16 @@ Describe "SSH Remoting API Tests" -Tags "Feature" { } It "SSHConnectionInfo should throw argument exception for invalid port (non 16bit uint)" { - $sshConnectionInfo = [System.Management.Automation.Runspaces.SSHConnectionInfo]::new( + { + $sshConnectionInfo = [System.Management.Automation.Runspaces.SSHConnectionInfo]::new( "UserName", "localhost", "ValidKeyFilePath", 99999) - $rs = [runspacefactory]::CreateRunspace($sshConnectionInfo) - $e = { $rs.Open() } | Should -Throw -PassThru - $e.Exception.InnerException | Should -BeOfType "System.ArgumentException" + $rs = [runspacefactory]::CreateRunspace($sshConnectionInfo) + $rs.Open() + } | Should -Throw -ErrorId "ArgumentException" -PassThru } } } From 262a572f4fa8c8b6808caab5146c5ff9d8cbb5af Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Thu, 26 Apr 2018 15:45:27 -0700 Subject: [PATCH 54/58] [Feature] -ev => -ErrorVariable --- .../Language/Scripting/ActionPreference.Tests.ps1 | 2 +- test/powershell/Language/Scripting/I18n.Tests.ps1 | 2 +- .../Language/Scripting/OutErrorVariable.Tests.ps1 | 10 +++++----- .../Language/Scripting/ScriptHelp.Tests.ps1 | 12 ++++++------ .../Microsoft.PowerShell.Utility/FormatHex.Tests.ps1 | 6 +++--- .../Microsoft.PowerShell.Utility/object.tests.ps1 | 4 ++-- 6 files changed, 18 insertions(+), 18 deletions(-) diff --git a/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 b/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 index 7e2e8401567..ecb0eafea01 100644 --- a/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 +++ b/test/powershell/Language/Scripting/ActionPreference.Tests.ps1 @@ -15,7 +15,7 @@ Describe "Tests for (error, warning, etc) action preference" -Tags "CI" { $err = $null try { - get-childitem nosuchfile.nosuchextension -ErrorAction stop -ev err + get-childitem nosuchfile.nosuchextension -ErrorAction stop -ErrorVariable err } catch {} diff --git a/test/powershell/Language/Scripting/I18n.Tests.ps1 b/test/powershell/Language/Scripting/I18n.Tests.ps1 index 9ca0fbf4227..5dbac9cb4d6 100644 --- a/test/powershell/Language/Scripting/I18n.Tests.ps1 +++ b/test/powershell/Language/Scripting/I18n.Tests.ps1 @@ -51,7 +51,7 @@ Describe 'Testing of script internationalization' -Tags "CI" { It 'Import non existing culture is done correctly' { - import-localizedData mydata -uiculture nl-NL -ErrorAction SilentlyContinue -ev ev + import-localizedData mydata -uiculture nl-NL -ErrorAction SilentlyContinue -ErrorVariable ev $ev | Should -Not -BeNullOrEmpty $ev[0].Exception | Should -BeOfType "System.Management.Automation.PSInvalidOperationException" diff --git a/test/powershell/Language/Scripting/OutErrorVariable.Tests.ps1 b/test/powershell/Language/Scripting/OutErrorVariable.Tests.ps1 index 149dcd15a54..78289b9cac8 100644 --- a/test/powershell/Language/Scripting/OutErrorVariable.Tests.ps1 +++ b/test/powershell/Language/Scripting/OutErrorVariable.Tests.ps1 @@ -280,7 +280,7 @@ Describe "Update both OutVariable and ErrorVariable" -Tags "CI" { } } - (get-foo5 "foo-message" -ev foo_err1 -ov foo_out1 | get-foo5 -ev foo_err2 -ov foo_out2 | get-foo5 -ev foo_err3 -ov foo_out3) 2>&1 > $null + (get-foo5 "foo-message" -ErrorVariable foo_err1 -ov foo_out1 | get-foo5 -ErrorVariable foo_err2 -ov foo_out2 | get-foo5 -ErrorVariable foo_err3 -ov foo_out3) 2>&1 > $null $foo_out1 | Should -BeExactly "foo-message" $foo_out2 | Should -BeExactly "foo-message" @@ -293,7 +293,7 @@ Describe "Update both OutVariable and ErrorVariable" -Tags "CI" { Context 'Error variable in multi-command pipeline (with native cmdlet)' { BeforeAll { - (get-foo -ev foo_err | get-item -ev get_item_err ) 2>&1 > $null + (get-foo -ErrorVariable foo_err | get-item -ErrorVariable get_item_err ) 2>&1 > $null } It '$foo_err should be "foo-error"' { @@ -369,11 +369,11 @@ Describe "Update both OutVariable and ErrorVariable" -Tags "CI" { "bar-output" write-error "bar-error" - get-foo7 "foo-output" -ev script:foo_err1 -ov script:foo_out1 | get-foo7 -ev script:foo_err2 -ov script:foo_out2 - get-foo7 "foo-output" -ev script:foo_err3 -ov script:foo_out3 | get-foo7 -ev script:foo_err4 -ov script:foo_out4 + get-foo7 "foo-output" -ErrorVariable script:foo_err1 -ov script:foo_out1 | get-foo7 -ErrorVariable script:foo_err2 -ov script:foo_out2 + get-foo7 "foo-output" -ErrorVariable script:foo_err3 -ov script:foo_out3 | get-foo7 -ErrorVariable script:foo_err4 -ov script:foo_out4 } - get-bar5 -ev script:bar_err -ov script:bar_out 2>&1 > $null + get-bar5 -ErrorVariable script:bar_err -ov script:bar_out 2>&1 > $null $script:foo_out1 | Should -BeExactly "foo-output" $script:foo_err1 | Should -BeExactly "foo-error" diff --git a/test/powershell/Language/Scripting/ScriptHelp.Tests.ps1 b/test/powershell/Language/Scripting/ScriptHelp.Tests.ps1 index a301a487106..bf854960fb8 100644 --- a/test/powershell/Language/Scripting/ScriptHelp.Tests.ps1 +++ b/test/powershell/Language/Scripting/ScriptHelp.Tests.ps1 @@ -88,34 +88,34 @@ Describe 'get-help HelpFunc1' -Tags "Feature" { } Context 'get-help helpFunc1 -component blah' { - $x = get-help helpFunc1 -component blah -ErrorAction SilentlyContinue -ev e + $x = get-help helpFunc1 -component blah -ErrorAction SilentlyContinue -ErrorVariable e TestHelpError $x $e 'HelpNotFound,Microsoft.PowerShell.Commands.GetHelpCommand' } Context 'get-help helpFunc1 -component Something' { - $x = get-help helpFunc1 -component Something -ErrorAction SilentlyContinue -ev e + $x = get-help helpFunc1 -component Something -ErrorAction SilentlyContinue -ErrorVariable e TestHelpFunc1 $x It '$e should be empty' { $e.Count | Should -Be 0 } } Context 'get-help helpFunc1 -role blah' { - $x = get-help helpFunc1 -component blah -ErrorAction SilentlyContinue -ev e + $x = get-help helpFunc1 -component blah -ErrorAction SilentlyContinue -ErrorVariable e TestHelpError $x $e 'HelpNotFound,Microsoft.PowerShell.Commands.GetHelpCommand' } Context 'get-help helpFunc1 -role CrazyUser' { - $x = get-help helpFunc1 -role CrazyUser -ErrorAction SilentlyContinue -ev e + $x = get-help helpFunc1 -role CrazyUser -ErrorAction SilentlyContinue -ErrorVariable e TestHelpFunc1 $x It '$e should be empty' { $e.Count | Should -Be 0 } } Context '$x = get-help helpFunc1 -functionality blah' { - $x = get-help helpFunc1 -functionality blah -ErrorAction SilentlyContinue -ev e + $x = get-help helpFunc1 -functionality blah -ErrorAction SilentlyContinue -ErrorVariable e TestHelpError $x $e 'HelpNotFound,Microsoft.PowerShell.Commands.GetHelpCommand' } Context '$x = get-help helpFunc1 -functionality Useless' { - $x = get-help helpFunc1 -functionality Useless -ErrorAction SilentlyContinue -ev e + $x = get-help helpFunc1 -functionality Useless -ErrorAction SilentlyContinue -ErrorVariable e TestHelpFunc1 $x It '$e should be empty' { $e.Count | Should -Be 0 } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/FormatHex.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/FormatHex.Tests.ps1 index c50088cfa42..b1d23abe370 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/FormatHex.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/FormatHex.Tests.ps1 @@ -349,19 +349,19 @@ Describe "FormatHex" -tags "CI" { $testCases = @( @{ - Name = "If given invalid path in array, continues to process valid paths 'fhx -Path `$invalidPath, `$inputFile1 -ev e -ErrorAction SilentlyContinue'" + Name = "If given invalid path in array, continues to process valid paths 'fhx -Path `$invalidPath, `$inputFile1 -ErrorVariable e -ErrorAction SilentlyContinue'" PathCase = $true InvalidPath = "$($inputFile1.DirectoryName)\fakefile8888845345345348709.txt" ExpectedFullyQualifiedErrorId = "FileNotFound,Microsoft.PowerShell.Commands.FormatHex" } @{ - Name = "If given a non FileSystem path in array, continues to process valid paths 'fhx -Path `$invalidPath, `$inputFile1 -ev e -ErrorAction SilentlyContinue'" + Name = "If given a non FileSystem path in array, continues to process valid paths 'fhx -Path `$invalidPath, `$inputFile1 -ErrorVariable e -ErrorAction SilentlyContinue'" PathCase = $true InvalidPath = "Cert:\CurrentUser\My\$thumbprint" ExpectedFullyQualifiedErrorId = "FormatHexOnlySupportsFileSystemPaths,Microsoft.PowerShell.Commands.FormatHex" } @{ - Name = "If given a non FileSystem path in array (with LiteralPath), continues to process valid paths 'fhx -Path `$invalidPath, `$inputFile1 -ev e -ErrorAction SilentlyContinue'" + Name = "If given a non FileSystem path in array (with LiteralPath), continues to process valid paths 'fhx -Path `$invalidPath, `$inputFile1 -ErrorVariable e -ErrorAction SilentlyContinue'" InvalidPath = "Cert:\CurrentUser\My\$thumbprint" ExpectedFullyQualifiedErrorId = "FormatHexOnlySupportsFileSystemPaths,Microsoft.PowerShell.Commands.FormatHex" } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/object.tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/object.tests.ps1 index f329e90cdf6..a69807c95c4 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/object.tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/object.tests.ps1 @@ -90,12 +90,12 @@ Describe "Object cmdlets" -Tags "CI" { } It 'should return correct error for non-numeric input' { - $gmi = "abc",[Datetime]::Now | measure -sum -max -ev err -ErrorAction silentlycontinue + $gmi = "abc",[Datetime]::Now | measure -sum -max -ErrorVariable err -ErrorAction silentlycontinue $err | ForEach-Object { $_.FullyQualifiedErrorId | Should -Be 'NonNumericInputObject,Microsoft.PowerShell.Commands.MeasureObjectCommand' } } It 'should have the correct count' { - $gmi = "abc",[Datetime]::Now | measure -sum -max -ev err -ErrorAction silentlycontinue + $gmi = "abc",[Datetime]::Now | measure -sum -max -ErrorVariable err -ErrorAction silentlycontinue $gmi.Count | Should -Be 2 } } From 2441c49a554a54bab7ab4acc7303340d76ceaad0 Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Thu, 26 Apr 2018 15:48:36 -0700 Subject: [PATCH 55/58] [Feature] -r => -Recurse --- .../Language/Scripting/Debugging/DebuggerScriptTests.Tests.ps1 | 2 +- .../Modules/Microsoft.PowerShell.Utility/Export-Alias.Tests.ps1 | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/test/powershell/Language/Scripting/Debugging/DebuggerScriptTests.Tests.ps1 b/test/powershell/Language/Scripting/Debugging/DebuggerScriptTests.Tests.ps1 index 51d8fc52cee..226bc32b6e4 100644 --- a/test/powershell/Language/Scripting/Debugging/DebuggerScriptTests.Tests.ps1 +++ b/test/powershell/Language/Scripting/Debugging/DebuggerScriptTests.Tests.ps1 @@ -580,7 +580,7 @@ Describe "Unit tests for line breakpoints on modules" -Tags "CI" { if ($null -ne $breakpoint3) { Remove-PSBreakpoint $breakpoint3 } if ($null -ne $breakpoint4) { Remove-PSBreakpoint $breakpoint4 } get-module $moduleName | remove-module - if (Test-Path $moduleDirectory) { Remove-Item $moduleDirectory -r -force -ErrorAction silentlycontinue } + if (Test-Path $moduleDirectory) { Remove-Item $moduleDirectory -Recurse -force -ErrorAction silentlycontinue } } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Alias.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Alias.Tests.ps1 index b15ac09ee8d..7e10e99c247 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Alias.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Alias.Tests.ps1 @@ -113,7 +113,7 @@ Describe "Export-Alias DRT Unit Tests" -Tags "CI" { if ( $IsWindows ) { - attrib -r $fulltestpath + attrib -Recurse $fulltestpath } else { From 41093fb9b857557a7aa659a4459dac65b86be193 Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Fri, 4 May 2018 15:10:41 -0800 Subject: [PATCH 56/58] Fix tests for Requires.Tests.ps1 --- test/powershell/Language/Scripting/Requires.Tests.ps1 | 1 - 1 file changed, 1 deletion(-) diff --git a/test/powershell/Language/Scripting/Requires.Tests.ps1 b/test/powershell/Language/Scripting/Requires.Tests.ps1 index 2f257aa6047..70586a578c9 100644 --- a/test/powershell/Language/Scripting/Requires.Tests.ps1 +++ b/test/powershell/Language/Scripting/Requires.Tests.ps1 @@ -18,7 +18,6 @@ Describe "Requires tests" -Tags "CI" { { [scriptblock]::Create($command) } | Should -Throw -ErrorId "ParseException" } } -} Context "Interactive requires" { From bb7f6fa13fafdd958f57973f87b6302f98fe89b8 Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Mon, 14 May 2018 18:14:58 -0700 Subject: [PATCH 57/58] [Feature] Tests fixes. --- test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 | 4 ---- .../Microsoft.PowerShell.Utility/Export-Csv.Tests.ps1 | 6 +----- 2 files changed, 1 insertion(+), 9 deletions(-) diff --git a/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 b/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 index 26a85f18f71..0442de20061 100644 --- a/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 +++ b/test/powershell/Modules/CimCmdlets/CimInstance.Tests.ps1 @@ -33,11 +33,7 @@ try { } It "should produce an error for a non-existing classname" { -<<<<<<< HEAD - { get-ciminstance -classname thisnameshouldnotexist -ErrorAction stop } | -======= { Get-CimInstance -ClassName thisnameshouldnotexist -ErrorAction Stop } | ->>>>>>> 500c8535507a723951462ec2d465b78aac36b3d8 Should -Throw -ErrorId "HRESULT 0x80041010,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstanceCommand" } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Csv.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Csv.Tests.ps1 index fb0fbf3ad27..0536424ae6e 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Csv.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Export-Csv.Tests.ps1 @@ -73,12 +73,8 @@ Describe "Export-Csv" -Tags "CI" { } It "Does not support -IncludeTypeInformation and -NoTypeInformation at the same time" { -<<<<<<< HEAD - { $testObject | Export-Csv -Path $testCsv -IncludeTypeInformation -NoTypeInformation } | + { $testObject | Export-Csv -Path $testCsv -IncludeTypeInformation -NoTypeInformation } | Should -Throw -ErrorId "CannotSpecifyIncludeTypeInformationAndNoTypeInformation,Microsoft.PowerShell.Commands.ExportCsvCommand" -======= - { $testObject | Export-Csv -Path $testCsv -IncludeTypeInformation -NoTypeInformation } | Should -Throw -ErrorId "CannotSpecifyIncludeTypeInformationAndNoTypeInformation,Microsoft.PowerShell.Commands.ExportCsvCommand" ->>>>>>> 67b1dc3059f5b80a95c0e7cff07c41fea9f636a6 } It "Should support -LiteralPath parameter" { From b5c07515dc9a333a14f7f45c14cbdf5723c6d39b Mon Sep 17 00:00:00 2001 From: kalgiz <klalgiz@microsoft.com> Date: Wed, 16 May 2018 09:41:53 -0700 Subject: [PATCH 58/58] [Feature]