From ae0915e4068b0e3e8334307d8bb453795abaa7a9 Mon Sep 17 00:00:00 2001 From: Frode Flaten <3436158+fflaten@users.noreply.github.com> Date: Wed, 15 Jul 2026 19:34:43 +0000 Subject: [PATCH 1/6] Initial migration of non-assertion tests to v6 assertions --- tst/Format2.Tests.ps1 | 2 +- tst/Help.Tests.ps1 | 16 +- tst/Pester.Tests.ps1 | 56 +-- tst/PesterConfiguration.Tests.ps1 | 22 +- tst/functions/Context.Tests.ps1 | 6 +- tst/functions/Coverage.Tests.ps1 | 206 ++++----- tst/functions/Describe.Tests.ps1 | 18 +- tst/functions/Environment.Tests.ps1 | 20 +- tst/functions/GlobalMock-A.Tests.ps1 | 2 +- tst/functions/GlobalMock-B.Tests.ps1 | 4 +- tst/functions/InModuleScope.Tests.ps1 | 98 ++-- tst/functions/It.Tests.ps1 | 6 +- tst/functions/Mock.Global.Tests.ps1 | 66 +-- tst/functions/Mock.Tests.ps1 | 420 +++++++++--------- tst/functions/New-Fixture.Tests.ps1 | 6 +- tst/functions/New-MockObject.Tests.ps1 | 48 +- tst/functions/Output.Tests.ps1 | 256 +++++------ tst/functions/Set-ItResult.Tests.ps1 | 12 +- tst/functions/SetupTeardown.Tests.ps1 | 68 +-- tst/functions/TestDrive.Tests.ps1 | 22 +- tst/functions/TestRegistry.Tests.ps1 | 18 +- tst/functions/TestResults.Tests.ps1 | 36 +- .../BasicTests/folder1/file1.Tests.ps1 | 6 +- 23 files changed, 707 insertions(+), 707 deletions(-) diff --git a/tst/Format2.Tests.ps1 b/tst/Format2.Tests.ps1 index 0ff6432d4..776af3bfe 100644 --- a/tst/Format2.Tests.ps1 +++ b/tst/Format2.Tests.ps1 @@ -354,7 +354,7 @@ InPesterModuleScope { $result = Format-String2 -Value $value # The result should not contain any of the original control characters # (C0 0x00-0x1F, DEL 0x7F, or C1 0x80-0x9F). - $result | Should -Not -Match '[\x00-\x1F\x7F-\x9F]' + $result | Should-NotMatchString '[\x00-\x1F\x7F-\x9F]' } } } diff --git a/tst/Help.Tests.ps1 b/tst/Help.Tests.ps1 index 7580ff715..69ad473e5 100644 --- a/tst/Help.Tests.ps1 +++ b/tst/Help.Tests.ps1 @@ -12,15 +12,15 @@ Describe "Testing module help" -Tag 'Help' -ForEach @{ exportedFunctions = $expo } It 'Help is found' { - $help.Name | Should -Be $_.Name - $help.Category | Should -Be $_.CommandType - $help.ModuleName | Should -Be $moduleName + $help.Name | Should-Be $_.Name + $help.Category | Should-Be $_.CommandType + $help.ModuleName | Should-Be $moduleName } It 'Synopsis is defined' { $help.Synopsis | Should -Not -BeNullOrEmpty # Syntax is used as synopsis when none is defined in help. - $help.Synopsis | Should -Not -Match "^\s*$($_.Name)((\s+\[+?-\w+)|$)" + $help.Synopsis | Should-NotMatchString "^\s*$($_.Name)((\s+\[+?-\w+)|$)" } It 'Description is defined' { @@ -36,12 +36,12 @@ Describe "Testing module help" -Tag 'Help' -ForEach @{ exportedFunctions = $expo $helpName = if ($alias) { $alias.Name } else { $help.Name } $firstUri = $help.relatedLinks.navigationLink | Where-Object uri | Select-Object -First 1 -ExpandProperty uri - $firstUri | Should -Be "https://pester.dev/docs/commands/$helpName" -Because 'first uri-link should be to online version of this help topic' + $firstUri | Should-Be "https://pester.dev/docs/commands/$helpName" -Because 'first uri-link should be to online version of this help topic' } It 'Has at least one example' { $help.Examples | Should -Not -BeNullOrEmpty - $help.Examples.example | Where-Object { -not $_.Code.Trim() } | Foreach-Object { $_.title.Trim("- ") } | Should -Be @() -Because 'no examples should be empty' + $help.Examples.example | Where-Object { -not $_.Code.Trim() } | ForEach-Object { $_.title.Trim('- ') } | Should-BeCollection @() -Because 'no examples should be empty' } It 'All static parameters have description' { @@ -53,7 +53,7 @@ Describe "Testing module help" -Tag 'Help' -ForEach @{ exportedFunctions = $expo Where-Object { $_.psobject.properties.name -notcontains 'description' } | ForEach-Object name) - $parametersMissingHelp | Should -Be @() + $parametersMissingHelp | Should-BeCollection @() } else { Set-ItResult -Skipped -Because 'no static parameters to test' @@ -74,7 +74,7 @@ Describe "Testing module help" -Tag 'Help' -ForEach @{ exportedFunctions = $expo $null -eq $attr -or $attr.HelpMessage -eq $null } | ForEach-Object Name) - $parametersMissingHelp | Should -Be @() -Because "it it's required for Should's online docs" + $parametersMissingHelp | Should-BeCollection @() -Because "it it's required for Should's online docs" } } } diff --git a/tst/Pester.Tests.ps1 b/tst/Pester.Tests.ps1 index a01ff5aa9..79b27c4f2 100644 --- a/tst/Pester.Tests.ps1 +++ b/tst/Pester.Tests.ps1 @@ -22,11 +22,11 @@ Describe -Tags 'VersionChecks' "Pester manifest and changelog" { } It "has a valid name in the manifest" { - $script:manifest.Name | Should -Be Pester + $script:manifest.Name | Should-Be Pester } It "has a valid guid in the manifest" { - $script:manifest.Guid | Should -Be 'a699dea5-2c73-4616-a270-1f7abb777e71' + $script:manifest.Guid | Should-Be 'a699dea5-2c73-4616-a270-1f7abb777e71' } if ((Get-Command -Name git -ErrorAction SilentlyContinue) -and (Get-Item ".git" -ErrorAction Ignore)) { @@ -44,7 +44,7 @@ Describe -Tags 'VersionChecks' "Pester manifest and changelog" { } It "has valid release notes in the manifest" { - $script:manifest.PrivateData.PSData.ReleaseNotes | Should -Be "https://github.com/pester/Pester/releases/tag/$script:tagVersion" + $script:manifest.PrivateData.PSData.ReleaseNotes | Should-Be "https://github.com/pester/Pester/releases/tag/$script:tagVersion" } It "tag and changelog versions are the same" { @@ -57,17 +57,17 @@ Describe -Tags 'VersionChecks' "Pester manifest and changelog" { } } - $script:changelogVersion | Should -Be $script:tagVersion - $script:changelogVersionShort | Should -Be $script:tagVersionShort + $script:changelogVersion | Should-Be $script:tagVersion + $script:changelogVersionShort | Should-Be $script:tagVersionShort } It "tag and changelog versions are the same" { - $script:changelogVersion | Should -Be $script:tagVersion + $script:changelogVersion | Should-Be $script:tagVersion } It "all short versions are the same" { - $script:changelogVersionShort -as [Version] | Should -Be ( $script:manifest.Version -as [Version] ) - $script:manifest.Version -as [Version] | Should -Be ( $script:tagVersionShort -as [Version] ) + $script:changelogVersionShort -as [Version] | Should-Be ( $script:manifest.Version -as [Version] ) + $script:manifest.Version -as [Version] | Should-Be ( $script:tagVersionShort -as [Version] ) } } } @@ -75,7 +75,7 @@ Describe -Tags 'VersionChecks' "Pester manifest and changelog" { It "has valid pre-release suffix in manifest (empty for stable version)" { # might be empty or null, as well as the tagPrerelase. we need empty string to eq $null but not to eq any other value $prereleaseFromManifest = $script:manifest.PrivateData.PSData.Prerelease | where { $_ } - $prereleaseFromManifest | Should -Be $script:tagPrerelease + $prereleaseFromManifest | Should-Be $script:tagPrerelease } } @@ -86,12 +86,12 @@ if ($PSVersionTable.PSVersion.Major -ge 3) { } Context 'A Context' { It 'Performs a successful test' { - $true | Should -Be $true + $true | Should-Be $true } } It 'Did not add anything to the $error variable' { - $error.Count | Should -Be 0 + $error.Count | Should-Be 0 } } @@ -127,7 +127,7 @@ if ($PSVersionTable.PSVersion.Major -ge 3) { } It 'The SafeCommands table contains all commands that are called from the module' { - $missingSafeCommands | Should -Be $null + $missingSafeCommands | Should-Be $null } } } @@ -237,34 +237,34 @@ InPesterModuleScope { It 'Resolves non-wildcarded file paths regardless of whether the file ends with Tests.ps1' { $result = @(Find-File 'TestDrive:\SomeOtherFile.ps1' -Extension ".Tests.ps1") - $result.Count | Should -Be 1 - $result[0].UnresolvedPath | Should -Be 'TestDrive:\SomeOtherFile.ps1' + $result.Count | Should-Be 1 + $result[0].UnresolvedPath | Should-Be 'TestDrive:\SomeOtherFile.ps1' } It 'Finds only *.Tests.ps1 files when the path contains wildcards' { $result = @(Find-File 'TestDrive:\*.ps1' -Extension ".Tests.ps1") - $result.Count | Should -Be 2 + $result.Count | Should-Be 2 $paths = $result | Select-Object -ExpandProperty FullName $testDrive = (Get-PSDrive TestDrive).Root - ($paths -contains (Join-Path $testDrive "SomeFile.Tests.ps1")) | Should -Be $true - ($paths -contains (Join-Path $testDrive "SomeOtherFile.Tests.ps1")) | Should -Be $true + ($paths -contains (Join-Path $testDrive "SomeFile.Tests.ps1")) | Should-Be $true + ($paths -contains (Join-Path $testDrive "SomeOtherFile.Tests.ps1")) | Should-Be $true } It 'Finds only *.Tests.ps1 files when the path refers to a directory and does not contain wildcards' { $result = @(Find-File 'TestDrive:\' -Extension ".Tests.ps1") - $result.Count | Should -Be 2 + $result.Count | Should-Be 2 $paths = $result | Select-Object -ExpandProperty FullName $testDrive = (Get-PSDrive TestDrive).Root - ($paths -contains (Join-Path $testDrive "SomeFile.Tests.ps1")) | Should -Be $true - ($paths -contains (Join-Path $testDrive "SomeOtherFile.Tests.ps1")) | Should -Be $true + ($paths -contains (Join-Path $testDrive "SomeFile.Tests.ps1")) | Should-Be $true + ($paths -contains (Join-Path $testDrive "SomeOtherFile.Tests.ps1")) | Should-Be $true } It 'Deduplicates filepaths when the provided paths overlaps' { $result = @(Find-File 'TestDrive:\*.ps1','TestDrive:\*.ps1' -Extension '.Tests.ps1') - $result.Count | Should -Be 2 + $result.Count | Should-Be 2 } Context 'Hidden folders and VCS metadata' { @@ -306,12 +306,12 @@ InPesterModuleScope { It 'discovers test files inside dot-prefixed (hidden) folders' { $names = @(Find-File -Path 'TestDrive:\' -Extension '.Tests.ps1' | Select-Object -ExpandProperty Name) - $names | Should -Contain 'InHidden.Tests.ps1' + $names | Should-ContainCollection 'InHidden.Tests.ps1' } It 'discovers test files in nested hidden folders' { $names = @(Find-File -Path 'TestDrive:\' -Extension '.Tests.ps1' | Select-Object -ExpandProperty Name) - $names | Should -Contain 'NestedHidden.Tests.ps1' + $names | Should-ContainCollection 'NestedHidden.Tests.ps1' } It 'does not descend into .git directories' { @@ -319,8 +319,8 @@ InPesterModuleScope { # appear in the result, proving the walker stops at .git without # opening its contents. $names = @(Find-File -Path 'TestDrive:\' -Extension '.Tests.ps1' | Select-Object -ExpandProperty Name) - $names | Should -Not -Contain 'HeadLevel.Tests.ps1' - $names | Should -Not -Contain 'DeepInGit.Tests.ps1' + $names | Should-NotContainCollection 'HeadLevel.Tests.ps1' + $names | Should-NotContainCollection 'DeepInGit.Tests.ps1' } It 'returns the same set as Get-ChildItem -Recurse -Force minus VCS folders' { @@ -331,7 +331,7 @@ InPesterModuleScope { Select-Object -ExpandProperty FullName | Sort-Object ) - $found | Should -Be $expected + $found | Should-BeCollection $expected } } @@ -476,7 +476,7 @@ InModuleScope -ModuleName Pester { @{ Filter = "*Unit*"; Collection = "Low", "Medium", "High" } ) { Contain-AnyStringLike -Filter $Filter -Collection $Collection | - Should -BeFalse + Should-BeFalse } It 'Given a filter that matches one or more items in collection it returns $true' -TestCases @( @@ -488,7 +488,7 @@ InModuleScope -ModuleName Pester { @{ Filter = "l*"; Collection = "Low", "Medium", "High" } ) { Contain-AnyStringLike -Filter $Filter -Collection $Collection | - Should -BeTrue + Should-BeTrue } } } diff --git a/tst/PesterConfiguration.Tests.ps1 b/tst/PesterConfiguration.Tests.ps1 index f45f5db2f..6d8f00fd5 100644 --- a/tst/PesterConfiguration.Tests.ps1 +++ b/tst/PesterConfiguration.Tests.ps1 @@ -13,16 +13,16 @@ Describe "PesterConfiguration.Format.ps1xml" { } It 'Has a single view defined of type ListControl' { $formatData | Should -Not -BeNullOrEmpty - $formatData.FormatViewDefinition.Count | Should -Be 1 - $formatData.FormatViewDefinition[0].Name | Should -BeExactly $section.FullName - $formatData.FormatViewDefinition[0].Control | Should -BeOfType ([System.Management.Automation.ListControl]) + $formatData.FormatViewDefinition.Count | Should-Be 1 + $formatData.FormatViewDefinition[0].Name | Should-BeString $section.FullName -CaseSensitive + $formatData.FormatViewDefinition[0].Control | Should-HaveType ([System.Management.Automation.ListControl]) } It 'View includes all options' { $propertiesInView = @($formatData.FormatViewDefinition[0].Control.Entries.Items.DisplayEntry | Where-Object ValueType -eq 'Property') - $propertiesInView.Count | Should -Be $options.Count + $propertiesInView.Count | Should-Be $options.Count $missingOptions = $options.Name | Where-Object { $propertiesInView.Value -notcontains $_ } - $missingOptions | Should -Be @() + $missingOptions | Should-BeCollection @() } } @@ -33,21 +33,21 @@ Describe "PesterConfiguration.Format.ps1xml" { } It 'Has a single view defined of type TableControl' { $formatData | Should -Not -BeNullOrEmpty - $formatData.FormatViewDefinition.Count | Should -Be 1 - $formatData.FormatViewDefinition[0].Name | Should -BeExactly 'Pester.Option' - $formatData.FormatViewDefinition[0].Control | Should -BeOfType ([System.Management.Automation.TableControl]) + $formatData.FormatViewDefinition.Count | Should-Be 1 + $formatData.FormatViewDefinition[0].Name | Should-BeString 'Pester.Option' -CaseSensitive + $formatData.FormatViewDefinition[0].Control | Should-HaveType ([System.Management.Automation.TableControl]) } It 'View includes all options' { $propertiesInView = @($formatData.FormatViewDefinition[0].Control.Rows.Columns.DisplayEntry | Where-Object ValueType -EQ 'Property') - $propertiesInView.Count | Should -Be $options.Count + $propertiesInView.Count | Should-Be $options.Count $missingOptions = $options.Name | Where-Object { $propertiesInView.Value -notcontains $_ } - $missingOptions | Should -Be @() + $missingOptions | Should-BeCollection @() } It 'View does not include IsModified' { $propertiesInView = @($formatData.FormatViewDefinition[0].Control.Rows.Columns.DisplayEntry | Where-Object ValueType -EQ 'Property') - $propertiesInView.Value | Should -Not -Contain 'IsModified' + $propertiesInView.Value | Should-NotContainCollection 'IsModified' } } } diff --git a/tst/functions/Context.Tests.ps1 b/tst/functions/Context.Tests.ps1 index c962c322a..62d034d24 100644 --- a/tst/functions/Context.Tests.ps1 +++ b/tst/functions/Context.Tests.ps1 @@ -7,7 +7,7 @@ Describe 'Testing Context' { } } - } | Should -Throw 'Test fixture name has multiple lines and no test fixture is provided. (Have you provided a name for the test group?)' + } | Should-Throw -ExceptionMessage 'Test fixture name has multiple lines and no test fixture is provided. (Have you provided a name for the test group?)' } It "Has a name that looks like a script block" { @@ -17,11 +17,11 @@ Describe 'Testing Context' { } } - } | Should -Throw 'No test fixture is provided. (Have you put the open curly brace on the next line?)' + } | Should-Throw -ExceptionMessage 'No test fixture is provided. (Have you put the open curly brace on the next line?)' } It 'Throws when provided unbound scriptblock' { # Unbound scriptblocks would execute in Pester's internal module state - { Context 'c' -Fixture ([scriptblock]::Create('')) } | Should -Throw -ExpectedMessage 'Unbound scriptblock*' + { Context 'c' -Fixture ([scriptblock]::Create('')) } | Should-Throw -ExceptionMessage 'Unbound scriptblock*' } } diff --git a/tst/functions/Coverage.Tests.ps1 b/tst/functions/Coverage.Tests.ps1 index b7397a725..d4f782b39 100644 --- a/tst/functions/Coverage.Tests.ps1 +++ b/tst/functions/Coverage.Tests.ps1 @@ -195,7 +195,7 @@ InPesterModuleScope { # Path deliberately duplicated to make sure the code doesn't produce multiple breakpoints for the same commands $breakpoints = Enter-CoverageAnalysis -CodeCoverage $testScriptPath, $testScriptPath, $testScript2Path, $testScript3Path, $testScriptStatementsPath, $testScriptExitPath -UseBreakpoints $UseBreakpoints - @($breakpoints).Count | Should -Be 40 -Because 'it has the proper number of breakpoints defined' + @($breakpoints).Count | Should-Be 40 -Because 'it has the proper number of breakpoints defined' $sb = { $null = & $testScriptPath @@ -219,45 +219,45 @@ InPesterModuleScope { } It 'Reports the proper number of executed commands' { - $coverageReport.NumberOfCommandsExecuted | Should -Be 34 + $coverageReport.NumberOfCommandsExecuted | Should-Be 34 } It 'Reports the proper number of analyzed commands' { - $coverageReport.NumberOfCommandsAnalyzed | Should -Be 40 + $coverageReport.NumberOfCommandsAnalyzed | Should-Be 40 } It 'Reports the proper number of analyzed files' { - $coverageReport.NumberOfFilesAnalyzed | Should -Be 5 + $coverageReport.NumberOfFilesAnalyzed | Should-Be 5 } It 'Reports the proper number of missed commands' { - $coverageReport.MissedCommands.Count | Should -Be 6 + $coverageReport.MissedCommands.Count | Should-Be 6 } It 'Reports the correct missed command' { - $coverageReport.MissedCommands[0].Command | Should -Be "'I cannot get called.'" - $coverageReport.MissedCommands[1].Command | Should -Be "'I am function two. I never get called.'" - $coverageReport.MissedCommands[2].Command | Should -Be "'I am method two. I never get called.'" - $coverageReport.MissedCommands[3].Command | Should -Be "'I was skipped because 2 called break in switch.'" - $coverageReport.MissedCommands[4].Command | Should -Be "'I was skipped by a labeled break.'" - $coverageReport.MissedCommands[5].Command | Should -Be "'I was skipped by a labeled contiune.'" + $coverageReport.MissedCommands[0].Command | Should-Be "'I cannot get called.'" + $coverageReport.MissedCommands[1].Command | Should-Be "'I am function two. I never get called.'" + $coverageReport.MissedCommands[2].Command | Should-Be "'I am method two. I never get called.'" + $coverageReport.MissedCommands[3].Command | Should-Be "'I was skipped because 2 called break in switch.'" + $coverageReport.MissedCommands[4].Command | Should-Be "'I was skipped by a labeled break.'" + $coverageReport.MissedCommands[5].Command | Should-Be "'I was skipped by a labeled contiune.'" } It 'Reports the proper number of hit commands' { - $coverageReport.HitCommands.Count | Should -Be 34 + $coverageReport.HitCommands.Count | Should-Be 34 } It 'Reports the correct hit command' { - $coverageReport.HitCommands[0].Command | Should -Be "'I am the nested function.'" + $coverageReport.HitCommands[0].Command | Should-Be "'I am the nested function.'" } It 'Reports the correct class names' { $coverageReport.HitCommands[0].Class | Should -BeNullOrEmpty # Classes have been introduced in PowerShell 5.0 if ($PSVersionTable.PSVersion.Major -ge 5) { - $coverageReport.HitCommands[9].Class | Should -Be 'MyBaseClass' - $coverageReport.HitCommands[10].Class | Should -Be 'MyClass' - $coverageReport.MissedCommands[2].Class | Should -Be 'MyClass' + $coverageReport.HitCommands[9].Class | Should-Be 'MyBaseClass' + $coverageReport.HitCommands[10].Class | Should-Be 'MyClass' + $coverageReport.MissedCommands[2].Class | Should-Be 'MyClass' } else { $coverageReport.HitCommands[9].Class | Should -BeNullOrEmpty @@ -266,11 +266,11 @@ InPesterModuleScope { } It 'Reports the correct function names' { - $coverageReport.HitCommands[0].Function | Should -Be 'NestedFunction' - $coverageReport.HitCommands[2].Function | Should -Be 'FunctionOne' - $coverageReport.HitCommands[9].Function | Should -Be 'MyBaseClass' - $coverageReport.HitCommands[10].Function | Should -Be 'MyClass' - $coverageReport.MissedCommands[2].Function | Should -Be 'MethodTwo' + $coverageReport.HitCommands[0].Function | Should-Be 'NestedFunction' + $coverageReport.HitCommands[2].Function | Should-Be 'FunctionOne' + $coverageReport.HitCommands[9].Function | Should-Be 'MyBaseClass' + $coverageReport.HitCommands[10].Function | Should-Be 'MyClass' + $coverageReport.MissedCommands[2].Function | Should-Be 'MethodTwo' } It 'JaCoCo report must be correct' { @@ -281,7 +281,7 @@ InPesterModuleScope { $jaCoCoReportXml = $jaCoCoReportXml -replace "$([System.Environment]::NewLine)", '' $jaCoCoReportXml = $jaCoCoReportXml -replace "$(Split-Path -Path $root -Leaf)", 'CommonRoot' $jaCoCoReportXml = $jaCoCoReportXml.Replace($root.Replace('\', '/'), '') - (Clear-WhiteSpace $jaCoCoReportXml) | Should -Be (Clear-WhiteSpace ' + (Clear-WhiteSpace $jaCoCoReportXml) | Should-Be (Clear-WhiteSpace ' @@ -467,7 +467,7 @@ InPesterModuleScope { $coberturaReportXml = $coberturaReportXml -replace "$([System.Environment]::NewLine)", '' $coberturaReportXml = $coberturaReportXml.Replace($root, 'CommonRoot') $coberturaReportXml = $coberturaReportXml.Replace($root.Replace('\', '/'), 'CommonRoot') - (Clear-WhiteSpace $coberturaReportXml) | Should -Be (Clear-WhiteSpace ' + (Clear-WhiteSpace $coberturaReportXml) | Should-Be (Clear-WhiteSpace ' ' -replace "`r`n", "`n") } @@ -1060,7 +1060,7 @@ Describe "When Calling Should -Not -Invoke -ExclusiveFilter" { It "Should throw an error" { $scriptBlock = { Should -Not -Invoke FunctionUnderTest -ExclusiveFilter { $param1 -eq 'one' } -Scope Describe } - $scriptBlock | Should -Throw 'Cannot use -ExclusiveFilter when -Not is specified. Use -ParameterFilter instead.' + $scriptBlock | Should-Throw -ExceptionMessage 'Cannot use -ExclusiveFilter when -Not is specified. Use -ParameterFilter instead.' } } @@ -1077,18 +1077,18 @@ Describe 'When Calling Should -Invoke with invalid -Scope' { } } It 'Should throw' { - $result.Exception.Message | Should -Be 'Assertion is placed outside of an It block, but -Scope It is specified.' + $result.Exception.Message | Should-Be 'Assertion is placed outside of an It block, but -Scope It is specified.' } } It 'Should throw when negative number' { $scriptBlock = { Should -Not -Invoke FunctionUnderTest -Scope -1 } - $scriptBlock | Should -Throw "Parameter Scope must be one of 'Describe', 'Context', 'It' or a non-negative number." + $scriptBlock | Should-Throw -ExceptionMessage "Parameter Scope must be one of 'Describe', 'Context', 'It' or a non-negative number." } It 'Should throw when unknown named block' { $scriptBlock = { Should -Not -Invoke FunctionUnderTest -Scope SomethingElse } - $scriptBlock | Should -Throw "Parameter Scope must be one of 'Describe', 'Context', 'It' or a non-negative number." + $scriptBlock | Should-Throw -ExceptionMessage "Parameter Scope must be one of 'Describe', 'Context', 'It' or a non-negative number." } } @@ -1098,7 +1098,7 @@ Context 'When Calling Should -Invoke -Scope Describe while not inside Describe' } It 'Should throw' { $scriptBlock = { Should -Not -Invoke FunctionUnderTest -Scope Describe } - $scriptBlock | Should -Throw 'Assertion is not placed directly nor nested inside a Describe block, but -Scope Describe is specified.' + $scriptBlock | Should-Throw -ExceptionMessage 'Assertion is not placed directly nor nested inside a Describe block, but -Scope Describe is specified.' } } @@ -1108,19 +1108,19 @@ Describe 'When Calling Should -Invoke -Scope Context while not inside Context' { } It 'Should throw' { $scriptBlock = { Should -Not -Invoke FunctionUnderTest -Scope Context } - $scriptBlock | Should -Throw 'Assertion is not placed directly nor nested inside a Context block, but -Scope Context is specified.' + $scriptBlock | Should-Throw -ExceptionMessage 'Assertion is not placed directly nor nested inside a Context block, but -Scope Context is specified.' } } Describe "When Calling Should -Invoke with pipeline-input or -ActualValue" { It "Should throw an error on pipeline-input" { $scriptBlock = { "value" | Should -Invoke -CommandName "ABC" -Scope Describe } - $scriptBlock | Should -Throw 'Should -Invoke does not take pipeline input or ActualValue.' + $scriptBlock | Should-Throw -ExceptionMessage 'Should -Invoke does not take pipeline input or ActualValue.' } It "Should throw an error on ActualInput-value" { $scriptBlock = { Should -Invoke -CommandName "ABC" -ActualValue "value" -Scope Describe } - $scriptBlock | Should -Throw 'Should -Invoke does not take pipeline input or ActualValue.' + $scriptBlock | Should-Throw -ExceptionMessage 'Should -Invoke does not take pipeline input or ActualValue.' } } @@ -1132,19 +1132,19 @@ Describe "Using Pester Scopes (Describe,Context,It)" { Context "When in the first context" { It "should mock Describe scoped paramless mock" { - FunctionUnderTest | should -be "I am the paramless mock test" + FunctionUnderTest | Should-Be "I am the paramless mock test" } It "should mock Describe scoped single param mock" { - FunctionUnderTest "one" | should -be "I am the first mock test" + FunctionUnderTest "one" | Should-Be "I am the first mock test" } } Context "When in the second context" { It "should mock Describe scoped paramless mock again" { - FunctionUnderTest | should -be "I am the paramless mock test" + FunctionUnderTest | Should-Be "I am the paramless mock test" } It "should mock Describe scoped single param mock again" { - FunctionUnderTest "one" | should -be "I am the first mock test" + FunctionUnderTest "one" | Should-Be "I am the first mock test" } } @@ -1154,10 +1154,10 @@ Describe "Using Pester Scopes (Describe,Context,It)" { } It "should mock Describe scoped mock." { - FunctionUnderTest | should -be "I am the paramless mock test" + FunctionUnderTest | Should-Be "I am the paramless mock test" } It "should mock Context scoped mock." { - FunctionUnderTestWithoutParams | should -be "I am the other function" + FunctionUnderTestWithoutParams | Should-Be "I am the other function" } } @@ -1168,20 +1168,20 @@ Describe "Using Pester Scopes (Describe,Context,It)" { } It "should use the context paramless mock" { - FunctionUnderTest | should -be "I am the context mock" + FunctionUnderTest | Should-Be "I am the context mock" } It "should use the context parameterized mock" { - FunctionUnderTest "one" | should -be "I am the parameterized context mock" + FunctionUnderTest "one" | Should-Be "I am the parameterized context mock" } } Context "When context no longer hides a describe mock" { It "should use the describe mock" { - FunctionUnderTest | should -be "I am the paramless mock test" + FunctionUnderTest | Should-Be "I am the paramless mock test" } It "should use the describe parameterized mock" { - FunctionUnderTest "one" | should -be "I am the first mock test" + FunctionUnderTest "one" | Should-Be "I am the first mock test" } } @@ -1195,7 +1195,7 @@ Describe "Using Pester Scopes (Describe,Context,It)" { } It 'Does not leave the mock active in the parent scope' { - FunctionUnderTest | Should -Be 'I am the context mock' + FunctionUnderTest | Should-Be 'I am the context mock' } } } @@ -1212,7 +1212,7 @@ Describe 'Testing mock history behavior from each scope' { } It 'Calls the describe mock' { - MockHistoryChecker | Should -Be 'I am the describe mock.' + MockHistoryChecker | Should-Be 'I am the describe mock.' } It "Reports that zero calls have been made in an It block, after a context-scoped call" { @@ -1244,7 +1244,7 @@ Describe 'Testing mock history behavior from each scope' { } It 'Calls the context mock' { - MockHistoryChecker | Should -Be 'I am the context mock.' + MockHistoryChecker | Should-Be 'I am the context mock.' } It 'Reports one context-scoped call' { @@ -1257,7 +1257,7 @@ Describe 'Testing mock history behavior from each scope' { It 'Calls an It-scoped mock' { Mock MockHistoryChecker { 'I am the It mock.' } - MockHistoryChecker | Should -Be 'I am the It mock.' + MockHistoryChecker | Should-Be 'I am the It mock.' } It 'Reports 2 context-scoped calls' { @@ -1285,7 +1285,7 @@ Describe "Using a single no param Describe" { } It "Should use the context mock" { - FunctionUnderTest | should -be "I am the context mock test" + FunctionUnderTest | Should-Be "I am the context mock test" } } } @@ -1361,8 +1361,8 @@ Describe 'Mocking Cmdlets with typed provider dynamic parameters' { # the mock we get a type-conversion binding error; when it is missing (the #1137 bug) we get # a NamedParameterNotFound error instead. We assert the former to prove the parameter exists. $splat = @{ Path = 'TestDrive:\a'; Destination = 'TestDrive:\b'; $Name = 'not-a-session' } - $err = { Copy-Item @splat } | Should -Throw -PassThru - $err.FullyQualifiedErrorId | Should -Not -BeLike 'NamedParameterNotFound*' -Because "the $Name dynamic parameter should be available on the mocked Copy-Item (#1137)" + $err = { Copy-Item @splat } | Should-Throw -PassThru + $err.FullyQualifiedErrorId | Should-NotBeLikeString 'NamedParameterNotFound*' -Because "the $Name dynamic parameter should be available on the mocked Copy-Item (#1137)" } } } @@ -1549,7 +1549,7 @@ Describe 'Mocking functions with dynamic parameters' { It 'Should successfully call the mock and generate the dynamic parameters' { $scriptBlock | Should -Not -Throw - $hash.Result | Should -Be 'Mocked' + $hash.Result | Should-Be 'Mocked' } } @@ -1607,7 +1607,7 @@ Describe 'Mocking functions with dynamic parameters' { It 'Should successfully call the mock and generate the dynamic parameters' { $scriptBlock | Should -Not -Throw - $hash.Result | Should -Be 'Mocked' + $hash.Result | Should-Be 'Mocked' } } @@ -1659,7 +1659,7 @@ Describe 'Mocking functions with dynamic parameters' { It 'Should successfully call the mock and generate the dynamic parameters' { $scriptBlock | Should -Not -Throw - $hash.Result | Should -Be 'Mocked' + $hash.Result | Should-Be 'Mocked' } } @@ -1714,7 +1714,7 @@ Describe 'Mocking functions with dynamic parameters' { It 'Should successfully call the mock and generate the dynamic parameters' { $scriptBlock | Should -Not -Throw - $hash.Result | Should -Be 'Mocked' + $hash.Result | Should-Be 'Mocked' } } @@ -1731,7 +1731,7 @@ Describe 'Mocking functions with dynamic parameters' { Mock Get-ThingWithFailingDynamicParam { 'mocked' } { Get-ThingWithFailingDynamicParam } | Should -Not -Throw - Get-ThingWithFailingDynamicParam | Should -Be 'mocked' + Get-ThingWithFailingDynamicParam | Should-Be 'mocked' } } @@ -1765,19 +1765,19 @@ Describe 'Mocking functions with dynamic parameters' { It 'matches the parameter filter using the alias of a dynamic parameter' { Mock Get-DynamicAliasThing { 'mocked' } -ParameterFilter { $Location -eq 'Here' } - Get-DynamicAliasThing -Location 'Here' | Should -Be 'mocked' + Get-DynamicAliasThing -Location 'Here' | Should-Be 'mocked' } It 'matches the parameter filter using the name of a dynamic parameter' { Mock Get-DynamicAliasThing { 'mocked' } -ParameterFilter { $Path -eq 'Here' } - Get-DynamicAliasThing -Location 'Here' | Should -Be 'mocked' + Get-DynamicAliasThing -Location 'Here' | Should-Be 'mocked' } It 'uses the dynamic-parameter alias to choose between behaviors' { Mock Get-DynamicAliasThing { 'default' } Mock Get-DynamicAliasThing { 'matched' } -ParameterFilter { $Location -eq 'Here' } - Get-DynamicAliasThing -Location 'Here' | Should -Be 'matched' - Get-DynamicAliasThing -Location 'There' | Should -Be 'default' + Get-DynamicAliasThing -Location 'Here' | Should-Be 'matched' + Get-DynamicAliasThing -Location 'There' | Should-Be 'default' } It 'matches Should -Invoke -ParameterFilter using the alias of a dynamic parameter' { @@ -1930,7 +1930,7 @@ Describe 'DynamicParam blocks in other scopes' { } It 'Properly evaluates dynamic parameters when called from another scope' { - CallingFunction | Should -Be 'I am the mocked function' + CallingFunction | Should-Be 'I am the mocked function' } It 'Properly evaluates dynamic parameters when called from another scope when the call is from a ValidateScript block' { @@ -1971,7 +1971,7 @@ Describe "Mocking Get-ItemProperty" { } It "Does not fail with NotImplementedException" { - Get-ItemProperty -Path "HKLM:\Software\Key\" -Name "Property" | Select-Object -ExpandProperty Name | Should -Be fakeName + Get-ItemProperty -Path "HKLM:\Software\Key\" -Name "Property" | Select-Object -ExpandProperty Name | Should-Be fakeName } } @@ -1992,7 +1992,7 @@ Describe 'When mocking a command with parameters that match internal variable na It 'Should execute the mocked command successfully' { { Test-Function } | Should -Not -Throw - Test-Function | Should -Be 'Mocked!' + Test-Function | Should-Be 'Mocked!' } } @@ -2037,7 +2037,7 @@ Describe 'When mocking a command that has an ArgumentList parameter with validat $scriptBlock = { $hash.Result = Start-Process -FilePath cmd.exe -ArgumentList '/c dir c:\' } $scriptBlock | Should -Not -Throw - $hash.Result | Should -Be 'mocked' + $hash.Result | Should-Be 'mocked' } } @@ -2051,7 +2051,7 @@ Describe 'Mocking New-Object' { Mock New-Object $result = New-Object -TypeName Object - $result | Should -Be $null + $result | Should-Be $null Should -Invoke New-Object } } @@ -2069,24 +2069,24 @@ Describe 'Mocking module-qualified calls' { } It 'Mock alias should not exist before the mock is defined' { - $alias | Should -Be $null + $alias | Should-Be $null } It 'Creates the alias while the mock is in effect' { $alias = Get-Alias -Name 'Microsoft.PowerShell.Management\Get-Content' -ErrorAction SilentlyContinue - $alias | Should -Not -Be $null + $alias | Should-NotBe $null } It 'Calls the mock properly even if the call is module-qualified' { $result = Microsoft.PowerShell.Management\Get-Content -Path $mockFile - $result | Should -Be $mockResult + $result | Should-Be $mockResult } } Describe 'After a mock goes out of scope' { It 'Removes the alias after the mock goes out of scope' { $alias = Get-Alias -Name 'Microsoft.PowerShell.Management\Get-Content' -ErrorAction SilentlyContinue - $alias | Should -Be $null + $alias | Should-Be $null } } @@ -2134,8 +2134,8 @@ Describe 'Mocks with closures' { } It 'Resolves variables in the closure rather than Pester''s current scope' { - TestClosure | Should -Be 'Variable resolved from script' - TestClosure -Closure | Should -Be 'Variable resolved from closure' + TestClosure | Should-Be 'Variable resolved from script' + TestClosure -Closure | Should-Be 'Variable resolved from closure' } } @@ -2175,13 +2175,13 @@ Describe '$args handling' { } It 'Advanced function mock should be callable with dot operator' { - SimpleFunction garbage | Should -Be mock + SimpleFunction garbage | Should-Be mock } It 'Advanced function with Args parameter should be mockable' { - AdvancedFunctionWithArgs -Args garbage | Should -Be mock + AdvancedFunctionWithArgs -Args garbage | Should-Be mock } It 'Cmdlet with Args parameter should be mockable' { - Invoke-CmdletWithArgs -Args garbage | Should -Be mock + Invoke-CmdletWithArgs -Args garbage | Should-Be mock } AfterAll { @@ -2212,7 +2212,7 @@ Describe 'Mocking advanced function' { return $MyParam1 } - Get-Something -MyParam1 'SomeValue' | Should -Be 'SomeValue' + Get-Something -MyParam1 'SomeValue' | Should-Be 'SomeValue' } } @@ -2234,12 +2234,12 @@ Describe 'Single quote in command/module name' { It 'Command with single quote in module name should be mockable' { Mock NormalCommandName { 'mock' } - NormalCommandName | Should -Be mock + NormalCommandName | Should-Be mock } It 'Command with single quote in name should be mockable' { Mock "Command '‘’‚‛" { 'mock' } - & "Command '‘’‚‛" | Should -Be mock + & "Command '‘’‚‛" | Should-Be mock } } @@ -2283,20 +2283,20 @@ Describe 'Mocking cmdlet without positional parameters' { } It 'Original cmdlet does not have positional parameters' { - { Invoke-CmdletWithoutPositionalParameters garbage } | Should -Throw + { Invoke-CmdletWithoutPositionalParameters garbage } | Should-Throw } It 'Mock of cmdlet should not make parameters to be positional' { Mock Invoke-CmdletWithoutPositionalParameters - { Invoke-CmdletWithoutPositionalParameters garbage } | Should -Throw + { Invoke-CmdletWithoutPositionalParameters garbage } | Should-Throw } It 'Original cmdlet bind all to Remainings' { - Invoke-CmdletWithValueFromRemainingArguments asd fgh jkl | Should -Be '; asd, fgh, jkl' + Invoke-CmdletWithValueFromRemainingArguments asd fgh jkl | Should-Be '; asd, fgh, jkl' } It 'Mock of cmdlet should bind all to Remainings' { Mock Invoke-CmdletWithValueFromRemainingArguments { -join ($Parameter, '; ', ($Remainings -join ', ')) } - Invoke-CmdletWithValueFromRemainingArguments asd fgh jkl | Should -Be '; asd, fgh, jkl' + Invoke-CmdletWithValueFromRemainingArguments asd fgh jkl | Should-Be '; asd, fgh, jkl' } } @@ -2315,8 +2315,8 @@ Describe 'Nested Mock calls' { It 'Properly handles nested mocks' { $result = @(Get-Date) - $result.Count | Should -Be 1 - $result[0] | Should -Be '2012-06-13T00:00:00.0000000' + $result.Count | Should-Be 1 + $result[0] | Should-Be '2012-06-13T00:00:00.0000000' } } @@ -2340,10 +2340,10 @@ Describe 'Globbing characters in command name' { Mock f[f]f { 'mock1' } Mock f?f { 'mock2' } Mock f*f { 'mock3' } - f[f]f | Should -Be mock1 - f?f | Should -Be mock2 - f*f | Should -Be mock3 - fff | Should -Be orig4 + f[f]f | Should-Be mock1 + f?f | Should-Be mock2 + f*f | Should-Be mock3 + fff | Should-Be orig4 } } @@ -2362,7 +2362,7 @@ Describe 'Naming conflicts in mocked functions' { } It 'Works with commands with parameter named Metadata' { - Wrapper | Should -Be 'mocked' + Wrapper | Should-Be 'mocked' } } Context 'parameter named Keys' { @@ -2379,7 +2379,7 @@ Describe 'Naming conflicts in mocked functions' { It 'Works with command with parameter named Keys' { $r = Wrapper - $r | Should -be 'value' + $r | Should-Be 'value' } } } @@ -2394,7 +2394,7 @@ Describe 'Passing unbound script blocks as mocks' { $scriptBlock = [scriptblock]::Create('"Mocked"') { Mock TestMe $scriptBlock } | Should -Not -Throw - TestMe | Should -Be Mocked + TestMe | Should-Be Mocked } It 'Should not execute in Pester internal state' { @@ -2402,7 +2402,7 @@ Describe 'Passing unbound script blocks as mocks' { $scriptBlock = [scriptblock]::Create('if ("pester" -eq $ExecutionContext.SessionState.Module) { throw "executed mock in internal state" } else { "Mocked" }') { Mock -CommandName TestMe -ParameterFilter $filter -MockWith $scriptBlock } | Should -Not -Throw - TestMe -SomeParam | Should -Be Mocked + TestMe -SomeParam | Should-Be Mocked } } @@ -2422,14 +2422,14 @@ Describe 'Should -Invoke when mock called outside of It block' { } It 'Should log the correct number of calls' { - TestMe | Should -Be Mocked + TestMe | Should-Be Mocked Should -Invoke TestMe -Scope It -Exactly -Times 1 Should -Invoke TestMe -Scope Context -Exactly -Times 2 Should -Invoke TestMe -Scope Describe -Exactly -Times 3 } It 'Should log the correct number of calls (second test)' { - TestMe | Should -Be Mocked + TestMe | Should-Be Mocked Should -Invoke TestMe -Scope It -Exactly -Times 1 Should -Invoke TestMe -Scope Context -Exactly -Times 3 Should -Invoke TestMe -Scope Describe -Exactly -Times 4 @@ -2449,11 +2449,11 @@ Describe "Restoring original commands when mock scopes exit" { # Deliberately not using "Should Exist" here because that executes in # Pester's module scope, where function:\a does not exist It "original function exists" { - $function:a | Should -Not -Be $null + $function:a | Should-NotBe $null } It "passes in first context" { - a | Should -Be "mock" + a | Should-Be "mock" } } @@ -2463,11 +2463,11 @@ Describe "Restoring original commands when mock scopes exit" { } It "original function exists" { - $function:a | Should -Not -Be $null + $function:a | Should-NotBe $null } It "passes in second context" { - a | Should -Be "mock" + a | Should-Be "mock" } } } @@ -2493,11 +2493,11 @@ Describe "Mocking functions with conflicting parameters" { } It 'executes the mock' { - Get-ExampleTest -ParamToAvoid "Hello" | Should -Be "World" + Get-ExampleTest -ParamToAvoid "Hello" | Should-Be "World" } It 'falls back to the default mock when no parameter filter matches' { - Get-ExampleTest -ParamToAvoid "Bye" | Should -Be "default mock" + Get-ExampleTest -ParamToAvoid "Bye" | Should-Be "default mock" } Context "Should -Invoke" { @@ -2544,15 +2544,15 @@ if ($PSVersionTable.PSVersion.Major -ge 3) { } It "returns mock that matches parameter filter block when using alias in the call" { - Get-Content -Path "c:\temp.txt" -Last 100 | Should -Be "aliased-parameter-name" + Get-Content -Path "c:\temp.txt" -Last 100 | Should-Be "aliased-parameter-name" } It "returns mock that matches parameter filter block when using the real parameter name in call" { - Get-Content -Path "c:\temp.txt" -Tail 100 | Should -Be "aliased-parameter-name" + Get-Content -Path "c:\temp.txt" -Tail 100 | Should-Be "aliased-parameter-name" } It 'returns default mock' { - Get-Content -Path "c:\temp.txt" | Should -Be "default-get-content" + Get-Content -Path "c:\temp.txt" | Should-Be "default-get-content" } } @@ -2561,7 +2561,7 @@ if ($PSVersionTable.PSVersion.Major -ge 3) { It 'calls the mock' { Mock New-Item { throw "default mock should not run" } Mock New-Item { return "nic" } -ParameterFilter { $Type -ne $null -and $Type.StartsWith("nic") } - New-Item -Path 'Hello' -Type "nic" | Should -Be "nic" + New-Item -Path 'Hello' -Type "nic" | Should-Be "nic" } } @@ -2611,7 +2611,7 @@ InPesterModuleScope { It 'mocks command' -TestCases $case { Mock $Command { 'I am being mocked' } - & $Command | Should -Be 'I am being mocked' + & $Command | Should-Be 'I am being mocked' Should -Invoke $Command -Scope It -Exactly 1 } @@ -2622,7 +2622,7 @@ InPesterModuleScope { It 'mocks notepad command with extension' { Mock notepad.exe { 'I am being mocked' } - notepad.exe | Should -Be 'I am being mocked' + notepad.exe | Should-Be 'I am being mocked' Should -Invoke notepad.exe -Scope It -Exactly 1 } @@ -2632,7 +2632,7 @@ InPesterModuleScope { It 'mocks with extension and calls it without ext' { Mock notepad.exe { 'I am being mocked' } - notepad | Should -Be 'I am being mocked' + notepad | Should-Be 'I am being mocked' Should -Invoke notepad.exe -Scope It -Exactly 1 } @@ -2640,7 +2640,7 @@ InPesterModuleScope { It 'mocks without extension and calls with extension' { Mock notepad { 'I am being mocked' } - notepad.exe | Should -Be 'I am being mocked' + notepad.exe | Should-Be 'I am being mocked' } It 'assert that alias to mock works' { @@ -2648,7 +2648,7 @@ InPesterModuleScope { Mock notepad.exe { 'I am being mocked' } - notepad | Should -Be 'I am being mocked' + notepad | Should-Be 'I am being mocked' Should -Invoke note -Scope It -Exactly 1 } @@ -2662,7 +2662,7 @@ Describe "Mock definition output" { function a () {} $output = Mock a { } - $output | Should -Be $null + $output | Should-Be $null } } @@ -2678,7 +2678,7 @@ Describe 'Mocking using ParameterFilter' { Mock Get-MockFilterValue { 'fallback' } Mock Get-MockFilterValue { 'mocked' } -ParameterFilter { $Name | Should-Be 'foo' } - Get-MockFilterValue -Name 'foo' | Should -Be 'mocked' + Get-MockFilterValue -Name 'foo' | Should-Be 'mocked' } It 'matches a filter that uses Should-BeString' { @@ -2691,7 +2691,7 @@ Describe 'Mocking using ParameterFilter' { Mock Get-MockFilterText { 'fallback' } Mock Get-MockFilterText { 'mocked' } -ParameterFilter { $Name | Should-BeString 'foo' } - Get-MockFilterText -Name 'foo' | Should -Be 'mocked' + Get-MockFilterText -Name 'foo' | Should-Be 'mocked' } } @@ -2703,11 +2703,11 @@ Describe 'Mocking using ParameterFilter' { } It "Returns default mock" { - Test-Path -Path C:\AwesomePath | Should -Be $True + Test-Path -Path C:\AwesomePath | Should-BeTrue } It "returns mock that matches parameter filter block" { - Test-Path -Path C:\Windows | Should -Be $false + Test-Path -Path C:\Windows | Should-BeFalse } } @@ -2719,11 +2719,11 @@ Describe 'Mocking using ParameterFilter' { } It "Returns default mock" { - Test-Path -Path C:\AwesomePath | Should -Be $True + Test-Path -Path C:\AwesomePath | Should-BeTrue } It "returns mock that matches parameter filter block" { - Test-Path -Path C:\Windows | Should -Be $false + Test-Path -Path C:\Windows | Should-BeFalse } } @@ -2734,11 +2734,11 @@ Describe 'Mocking using ParameterFilter' { } It "Returns default mock" { - Test-Path -Path C:\AwesomePath | Should -Be $True + Test-Path -Path C:\AwesomePath | Should-BeTrue } It "returns mock that matches parameter filter block" { - Test-Path -Path C:\Windows | Should -Be $false + Test-Path -Path C:\Windows | Should-BeFalse } } Context 'Scriptblock {} passed to ParameterFilter as var' { @@ -2751,11 +2751,11 @@ Describe 'Mocking using ParameterFilter' { } It "Returns default mock" { - Test-Path -Path C:\AwesomePath | Should -Be $True + Test-Path -Path C:\AwesomePath | Should-BeTrue } It "returns mock that matches parameter filter block" { - Test-Path -Path C:\Windows | Should -Be $false + Test-Path -Path C:\Windows | Should-BeFalse } } @@ -2769,11 +2769,11 @@ Describe 'Mocking using ParameterFilter' { } It "Returns default mock" { - Test-Path -Path C:\AwesomePath | Should -Be $True + Test-Path -Path C:\AwesomePath | Should-BeTrue } It "returns mock that matches parameter filter block" { - Test-Path -Path C:\Windows | Should -Be $false + Test-Path -Path C:\Windows | Should-BeFalse } } } @@ -2790,8 +2790,8 @@ if ($PSVersionTable.PSVersion.Major -ge 3) { Mock f { "result" } -RemoveParameterType 'Count' [Diagnostics.Process] $currentProcess = Get-Process -id $pid - $currentProcess -as [int] -eq $null | Should -BeTrue -Because "Process is not convertible to int" - f -Name 'Hello' -Count $currentProcess | Should -Be "result" -Because "we successfuly provided a process to parameter defined as int" + $currentProcess -as [int] -eq $null | Should-BeTrue -Because "Process is not convertible to int" + f -Name 'Hello' -Count $currentProcess | Should-Be "result" -Because "we successfuly provided a process to parameter defined as int" } if ($PSVersionTable.PSVersion.Major -eq 5) { @@ -2810,7 +2810,7 @@ if ($PSVersionTable.PSVersion.Major -ge 3) { Context "Get-PhysicalDisk example" { It "should return 'hello'" { Mock Get-PhysicalDisk -RemoveParameterType Usage, HealthStatus { return "hello" } - Get-PhysicalDisk | Should -Be "hello" + Get-PhysicalDisk | Should-Be "hello" } } } @@ -2831,13 +2831,13 @@ Describe 'RemoveParameterValidation' { } It 'throws when number is not in the valid range' { - { Test-Validation -Count -1 } | Should -Throw -ErrorId '*ParameterArgumentValidationError*' + { Test-Validation -Count -1 } | Should-Throw -FullyQualifiedErrorId '*ParameterArgumentValidationError*' } It 'passes when mock removes the validation' { Mock Test-Validation -RemoveParameterValidation Count { "mock" } - Test-Validation -Count -1 | Should -Be "mock" + Test-Validation -Count -1 | Should-Be "mock" } Context 'When the validated parameter is a dynamic parameter (#1557)' { @@ -2868,18 +2868,18 @@ Describe 'RemoveParameterValidation' { It 'still validates the dynamic parameter when validation is not removed' { Mock Test-DynamicValidation { 'mock' } - { Test-DynamicValidation -Name 'zzz' } | Should -Throw -ErrorId '*ParameterArgumentValidationError*' + { Test-DynamicValidation -Name 'zzz' } | Should-Throw -FullyQualifiedErrorId '*ParameterArgumentValidationError*' } It 'passes when mock removes the validation from the dynamic parameter' { Mock Test-DynamicValidation { 'mock' } -RemoveParameterValidation Name - Test-DynamicValidation -Name 'zzz' | Should -Be 'mock' + Test-DynamicValidation -Name 'zzz' | Should-Be 'mock' } It 'only removes validation from the named dynamic parameter' { Mock Test-DynamicValidation { 'mock' } -RemoveParameterValidation Name - Test-DynamicValidation -Name 'zzz' | Should -Be 'mock' - { Test-DynamicValidation -Color 'zzz' } | Should -Throw -ErrorId '*ParameterArgumentValidationError*' + Test-DynamicValidation -Name 'zzz' | Should-Be 'mock' + { Test-DynamicValidation -Color 'zzz' } | Should-Throw -FullyQualifiedErrorId '*ParameterArgumentValidationError*' } } } @@ -2941,7 +2941,7 @@ Describe 'Mocking command with ValidateRange-attributes' { Set-Item -Path 'function:Test-EnumValidation' -Value ('param ( {0}{1} )' -f $Attribute, $Parameter) Mock -CommandName 'Test-EnumValidation' -MockWith { 'mock' } - Test-EnumValidation | Should -Be 'mock' + Test-EnumValidation | Should-Be 'mock' } if ($PSVersionTable.PSVersion.Major -ge '7') { @@ -2954,7 +2954,7 @@ Describe 'Mocking command with ValidateRange-attributes' { Set-Item -Path 'function:Test-EnumValidation' -Value ('param ( {0}{1} )' -f $Attribute, $Parameter) Mock -CommandName 'Test-EnumValidation' -MockWith { 'mock' } - Test-EnumValidation | Should -Be 'mock' + Test-EnumValidation | Should-Be 'mock' } } @@ -2962,7 +2962,7 @@ Describe 'Mocking command with ValidateRange-attributes' { if ((Get-Module BitsTransfer -ErrorAction SilentlyContinue)) { It 'mocked cmdlet does not throw' { Mock -CommandName 'Start-BitsTransfer' -MockWith { 'mock' } - Start-BitsTransfer -Source "/nonexistingpath" | Should -Be 'mock' + Start-BitsTransfer -Source "/nonexistingpath" | Should-Be 'mock' } } } @@ -2985,7 +2985,7 @@ Describe "Running Mock with ModuleName in test scope" { It "can mock internal function of the module" { Mock -ModuleName test a { "mock" } - f | Should -Be "mock" + f | Should-Be "mock" } It "runs the body in the current scope" { @@ -2993,8 +2993,8 @@ Describe "Running Mock with ModuleName in test scope" { $ExecutionContext.SessionState } $actual = f - $actual | Should -BeOfType ([Management.Automation.SessionState]) - $actual.Module | Should -Be $null -Because "we are not running inside of the 'test' module" + $actual | Should-HaveType ([Management.Automation.SessionState]) + $actual.Module | Should-Be $null -Because "we are not running inside of the 'test' module" } It "runs the parameter filter in the current scope" { @@ -3002,8 +3002,8 @@ Describe "Running Mock with ModuleName in test scope" { Mock -ModuleName test a { } -ParameterFilter { $script:ss = $ExecutionContext.SessionState ; $true } $null = f - $script:ss | Should -BeOfType ([Management.Automation.SessionState]) - $script:ss.Module | Should -Be $null -Because "we are not running inside of the 'test' module" + $script:ss | Should-HaveType ([Management.Automation.SessionState]) + $script:ss.Module | Should-Be $null -Because "we are not running inside of the 'test' module" } } @@ -3016,7 +3016,7 @@ Describe "Mocks can be defined outside of BeforeAll" { } It "Finds the mock" { - a | Should -Be "mock" + a | Should-Be "mock" } } @@ -3043,9 +3043,9 @@ Describe "Debugging mocks" { $Name -eq "Jakub" } - $sb[0].HitCount | Should -Be 1 -Because "breakpoint on line $($sb[0].Line) is hit" - $sb[1].HitCount | Should -Be 1 -Because "breakpoint on line $($sb[1].Line) is hit" - $sb[2].HitCount | Should -Be 1 -Because "breakpoint on line $($sb[2].Line) is hit" + $sb[0].HitCount | Should-Be 1 -Because "breakpoint on line $($sb[0].Line) is hit" + $sb[1].HitCount | Should-Be 1 -Because "breakpoint on line $($sb[1].Line) is hit" + $sb[2].HitCount | Should-Be 1 -Because "breakpoint on line $($sb[2].Line) is hit" } finally { $sb | Remove-PSBreakpoint @@ -3061,21 +3061,21 @@ Describe "When inherited variables conflicts with parameters" { It "parameterized mock should not be called due to inherited variable" { $param1 = 'abc' - FunctionUnderTest | Should -Be 'default' + FunctionUnderTest | Should-Be 'default' } It "InvokeVerifiable should not pass due to test variable" { # Uses same logic as mock execution, so should not be tricked $param1 = 'abc' - FunctionUnderTest | Should -Be 'default' - { Should -InvokeVerifiable } | Should -Throw + FunctionUnderTest | Should-Be 'default' + { Should -InvokeVerifiable } | Should-Throw } It "Should Invoke ParameterFilter will count false positive for the first FunctionUnderTest call" { # https://github.com/pester/Pester/issues/1873 # this will pass the parameter filter because we define a variable param1 with the same name and value as the expected parameter value - FunctionUnderTest | Should -Be 'default' - FunctionUnderTest -param1 'abc' | Should -Be 'filtered' + FunctionUnderTest | Should-Be 'default' + FunctionUnderTest -param1 'abc' | Should-Be 'filtered' $param1 = 'abc' # This should show warning about conflict when in Diagnostic output (Mock debug message) @@ -3085,8 +3085,8 @@ Describe "When inherited variables conflicts with parameters" { It "Invoke ParameterFilter works as expected when PesterBoundParamters is used" { # Workaround mentioned in debug message warning mentioned in previous test - FunctionUnderTest | Should -Be 'default' - FunctionUnderTest -param1 'abc' | Should -Be 'filtered' + FunctionUnderTest | Should-Be 'default' + FunctionUnderTest -param1 'abc' | Should-Be 'filtered' $param1 = 'abc' # No warning will be shown in debug as there's no conflict @@ -3094,7 +3094,7 @@ Describe "When inherited variables conflicts with parameters" { } It "Calling mock with parameter overrides inherited variable in filter" { - FunctionUnderTest -param1 '123' | Should -Be 'default' + FunctionUnderTest -param1 '123' | Should-Be 'default' $param1 = 'abc' # This should show warning about conflict when in Diagnostic output (Mock debug message) @@ -3128,13 +3128,13 @@ Describe 'Mocking in manifest modules' { It 'Should be able to mock public function' { Mock -CommandName 'myManifestPublicFunction' -MockWith { 'mocked public' } - myManifestPublicFunction | Should -Be 'mocked public' + myManifestPublicFunction | Should-Be 'mocked public' Should -Invoke -CommandName 'myManifestPublicFunction' -Exactly -Times 1 } It 'Should be able to mock private function' { Mock -CommandName 'myManifestPrivateFunction' -ModuleName $moduleName -MockWith { 'mocked private' } - myManifestPublicFunction | Should -Be 'mocked private' + myManifestPublicFunction | Should-Be 'mocked private' Should -Invoke -CommandName 'myManifestPrivateFunction' -ModuleName $moduleName -Exactly -Times 1 } } @@ -3170,7 +3170,7 @@ Describe "Mocking using 'RootModule/NestedModule' slash notation" { It 'Should mock an internal command in the nested module using slash notation' { Mock -CommandName 'Get-InternalData' -ModuleName "$rootName/$nestedName" -MockWith { 'mocked' } $result = Get-PublicData - $result | Should -Be 'mocked' + $result | Should-Be 'mocked' } It 'Should-Invoke matches call history when using slash notation' { @@ -3193,7 +3193,7 @@ Describe "Mocking using 'RootModule/NestedModule' slash notation" { It 'Mock cleanup removes the bootstrap function from the nested module session state' { # After the It block completes the mock is torn down; calling the real function returns 'real'. - Get-PublicData | Should -Be 'real' + Get-PublicData | Should-Be 'real' } } @@ -3230,7 +3230,7 @@ Describe "Mocking using deep module path notation 'Root/Mid/Leaf'" { It 'Should mock an internal command in the deeply nested module using slash notation' { Mock -CommandName 'Get-DeepInternalData' -ModuleName "$rootName/$midName/$leafName" -MockWith { 'mocked-deep' } $result = InModuleScope "$rootName/$midName/$leafName" { Get-DeepPublicData } - $result | Should -Be 'mocked-deep' + $result | Should-Be 'mocked-deep' } It 'Should-Invoke matches call history when using deep slash notation' { @@ -3281,14 +3281,14 @@ Describe "Disambiguating nested modules with the same name across two root modul It 'loads both nested modules under the same name, so a plain name is ambiguous' { # Guard: confirms the scenario genuinely exercises disambiguation. - @(Get-Module $sharedName -All).Count | Should -BeGreaterThan 1 + @(Get-Module $sharedName -All).Count | Should-BeGreaterThan 1 } It 'mocks Get-Data in the ClientA copy, leaving the identically-named ClientB copy untouched' { Mock -CommandName 'Get-Data' -ModuleName "$rootA/$sharedName" -MockWith { 'mockedA' } - InModuleScope "$rootA/$sharedName" { Invoke-Api } | Should -Be 'mockedA' + InModuleScope "$rootA/$sharedName" { Invoke-Api } | Should-Be 'mockedA' # the mock must not bleed into the same-named nested module under ClientB - InModuleScope "$rootB/$sharedName" { Invoke-Api } | Should -Be 'dataB' + InModuleScope "$rootB/$sharedName" { Invoke-Api } | Should-Be 'dataB' } It 'Should-Invoke uses slash notation to check the ClientA copy call history' { @@ -3306,7 +3306,7 @@ Describe 'Mocking in nested Invoke-Pester runs' { Describe 'inner' { It 'local mock works' { Mock Get-Command { 2 } - Get-Command | Should -Be 2 + Get-Command | Should-Be 2 } It 'outer mock bootstrap leaks but throws instead of falling through' { @@ -3314,7 +3314,7 @@ Describe 'Mocking in nested Invoke-Pester runs' { # session state that is visible to this nested Invoke-Pester run. # Pester 6 never falls through to the original command, so calling # Get-Date here without mocking it locally throws with a clear message. - { Get-Date } | Should -Throw "*No mock for command 'Get-Date' is defined in this scope*" + { Get-Date } | Should-Throw -ExceptionMessage "*No mock for command 'Get-Date' is defined in this scope*" } } }) -Output None -PassThru @@ -3322,18 +3322,18 @@ Describe 'Mocking in nested Invoke-Pester runs' { It 'Mocks in outer run works after nested Invoke-Pester' { # https://github.com/pester/Pester/issues/2074 - Get-Date | Should -Be 1 + Get-Date | Should-Be 1 # Outer mock should not have been called from nested run Should -Invoke Get-Date -Exactly -Times 1 } It 'Mocking works in nested run' { - $innerRun.Result | Should -Be 'Passed' - $innerRun.PassedCount | Should -Be 2 + $innerRun.Result | Should-Be 'Passed' + $innerRun.PassedCount | Should-Be 2 } It 'Mocks in nested run do not leak to outside' { - Get-Command Get-ChildItem | Should -Not -Be 2 + Get-Command Get-ChildItem | Should-NotBe 2 } } @@ -3385,7 +3385,7 @@ Describe 'Usage of Alias in DynamicParams' { It 'Mocks Test-DynamicParam with PSEdition set to Desktop' { Mock Test-DynamicParam { "World" } -ParameterFilter { $_PSEdition -eq 'Desktop' } - Test-DynamicParam -Name "Hello" -PSEdition 'Desktop' | Should -Be 'World' + Test-DynamicParam -Name "Hello" -PSEdition 'Desktop' | Should-Be 'World' } } @@ -3393,7 +3393,7 @@ Describe 'Usage of Alias in DynamicParams' { It 'Invokes Test-DynamicParam with correct parameters' { Mock Test-DynamicParam { "World" } - Test-DynamicParam -Name "Hello" -PSEdition 'Desktop' | Should -Be 'World' + Test-DynamicParam -Name "Hello" -PSEdition 'Desktop' | Should-Be 'World' Should -Invoke Test-DynamicParam -Exactly 1 -Scope It } diff --git a/tst/functions/New-Fixture.Tests.ps1 b/tst/functions/New-Fixture.Tests.ps1 index 459dd6908..832f7d19f 100644 --- a/tst/functions/New-Fixture.Tests.ps1 +++ b/tst/functions/New-Fixture.Tests.ps1 @@ -2,7 +2,7 @@ Describe "New-Fixture" { It "Name parameter is mandatory" { - (Get-Command New-Fixture).Parameters.Name.ParameterSets.__AllParameterSets.IsMandatory | Should -Be $true + (Get-Command New-Fixture).Parameters.Name.ParameterSets.__AllParameterSets.IsMandatory | Should-Be $true } Context "Only Name parameter is specified" { @@ -108,14 +108,14 @@ Describe "New-Fixture" { New-Fixture -Name $name -Path $path | Out-Null New-Fixture -Name $name -Path $path -WarningVariable warnings -WarningAction SilentlyContinue | Out-Null - Should -InvokeVerifiable + Should-Invoke -Verifiable } It "Throws on whitespace in Name" { $name = "Test Fixture" $path = "TestDrive:\" - { New-Fixture -Name $name -Path $path } | Should -Throw -Because "whitespace is not allowed in fixture name" + { New-Fixture -Name $name -Path $path } | Should-Throw -Because "whitespace is not allowed in fixture name" } } } diff --git a/tst/functions/New-MockObject.Tests.ps1 b/tst/functions/New-MockObject.Tests.ps1 index fd15d2fcc..578f5ce78 100644 --- a/tst/functions/New-MockObject.Tests.ps1 +++ b/tst/functions/New-MockObject.Tests.ps1 @@ -4,15 +4,15 @@ Describe 'New-MockObject' { It 'instantiates an object from a class with no public constructors' { $type = 'Microsoft.PowerShell.Commands.Language' - New-MockObject -Type $type | Should -BeOfType $type + New-MockObject -Type $type | Should-HaveType $type } It 'Add a property to existing object' { $o = New-Object -TypeName 'System.Diagnostics.Process' $mockObject = New-MockObject -InputObject $o -Properties @{ Id = 123 } - $mockObject | Should -Be $o - $mockObject.Id | Should -Be 123 + $mockObject | Should-Be $o + $mockObject.Id | Should-Be 123 } It 'User scriptblock can use $this to reference to itself' { @@ -25,9 +25,9 @@ Describe 'New-MockObject' { } } - $mockObject | Should -Be $o - $mockObject.Name | Should -Be 'Jakub' - $mockObject.GetName() | Should -Be 'Jakub' + $mockObject | Should-Be $o + $mockObject.Name | Should-Be 'Jakub' + $mockObject.GetName() | Should-Be 'Jakub' } It 'Default parameter set is Type for backwards compatibility' { @@ -36,7 +36,7 @@ Describe 'New-MockObject' { } It 'Mock using type input' { - New-MockObject -Type ([System.Diagnostics.Process]) | Should -BeOfType ([System.Diagnostics.Process]) + New-MockObject -Type ([System.Diagnostics.Process]) | Should-HaveType ([System.Diagnostics.Process]) } if ($PSVersionTable.PSVersion.Major -ge 5) { @@ -54,10 +54,10 @@ Describe 'New-MockObject' { $obj } - { [MyInternalClass] } | Should -Throw -ErrorId 'TypeNotFound' + { [MyInternalClass] } | Should-Throw -FullyQualifiedErrorId 'TypeNotFound' $mock = New-MockObject -Type $someObj.GetType() -Properties @{ Name = 'Mocked' } - $mock.GetType().Name | Should -Be 'MyInternalClass' - $mock.GetName() | Should -Be 'Mocked' + $mock.GetType().Name | Should-Be 'MyInternalClass' + $mock.GetName() | Should-Be 'Mocked' } } @@ -66,21 +66,21 @@ Describe 'New-MockObject' { $o = New-Object -TypeName 'System.Diagnostics.Process' $mockObject = New-MockObject -InputObject $o -Methods @{ Kill = { param() "killed" } } - $mockObject | Should -Be $o - $mockObject.Kill() | Should -Be "killed" + $mockObject | Should-Be $o + $mockObject.Kill() | Should-Be "killed" } It "Counts history of the invocation" { $o = New-Object -TypeName 'System.Diagnostics.Process' $mockObject = New-MockObject -InputObject $o -Methods @{ Kill = { param($entireProcessTree) "killed" } } - $mockObject | Should -Be $o - $mockObject.Kill() | Should -Be "killed" - $mockObject._Kill[-1].Call | Should -Be 1 - $mockObject._Kill[-1].Arguments | Should -Be $null - $mockObject.Kill($true) | Should -Be "killed" - $mockObject._Kill[-1].Call | Should -Be 2 - $mockObject._Kill[-1].Arguments | Should -Be $true + $mockObject | Should-Be $o + $mockObject.Kill() | Should-Be "killed" + $mockObject._Kill[-1].Call | Should-Be 1 + $mockObject._Kill[-1].Arguments | Should-Be $null + $mockObject.Kill($true) | Should-Be "killed" + $mockObject._Kill[-1].Call | Should-Be 2 + $mockObject._Kill[-1].Arguments | Should-Be $true } It "Adds 2 methods to the object" { @@ -89,8 +89,8 @@ Describe 'New-MockObject' { Close = { param($Server, $Port)"close" } } - $mockObject.Connect() | Should -Be "connect" - $mockObject.Close() | Should -Be "close" + $mockObject.Connect() | Should-Be "connect" + $mockObject.Close() | Should-Be "close" } } @@ -101,18 +101,18 @@ Describe 'New-MockObject' { it 'Fails with just a normal mock' { $mockedProcess = New-MockObject -Type 'System.Diagnostics.Process' - { $mockedProcess.Id = 123 } | Should -Throw + { $mockedProcess.Id = 123 } | Should-Throw } it 'Works when you mock the property' { $mockedProcess = New-MockObject -Type 'System.Diagnostics.Process' -Properties @{ Id = 123 } - $mockedProcess.Id | Should -Be 123 + $mockedProcess.Id | Should-Be 123 } it 'Should preserve types' { $mockedProcess = New-MockObject -Type 'System.Diagnostics.Process' -Properties @{Id = 123 } - $mockedProcess.Id | Should -BeOfType ([int]) + $mockedProcess.Id | Should-HaveType ([int]) } } } diff --git a/tst/functions/Output.Tests.ps1 b/tst/functions/Output.Tests.ps1 index a998303cf..f718ffb6d 100644 --- a/tst/functions/Output.Tests.ps1 +++ b/tst/functions/Output.Tests.ps1 @@ -87,49 +87,49 @@ InModuleScope -ModuleName Pester -ScriptBlock { Describe "Format-PesterPath" { It "Writes path correctly when it is given `$null" { - Format-PesterPath -Path $null | Should -Be $null + Format-PesterPath -Path $null | Should-BeNull } if ((GetPesterOS) -ne 'Windows') { It "Writes path correctly when it is provided as string" { - Format-PesterPath -Path "/home/username/folder1" | Should -Be "/home/username/folder1" + Format-PesterPath -Path '/home/username/folder1' | Should-Be '/home/username/folder1' } It "Writes path correctly when it is provided as string[]" { - Format-PesterPath -Path @("/home/username/folder1", "/home/username/folder2") -Delimiter ', ' | Should -Be "/home/username/folder1, /home/username/folder2" + Format-PesterPath -Path @('/home/username/folder1', '/home/username/folder2') -Delimiter ', ' | Should-Be '/home/username/folder1, /home/username/folder2' } It "Writes path correctly when provided through hashtable" { - Format-PesterPath -Path @{ Path = "/home/username/folder1" } | Should -Be "/home/username/folder1" + Format-PesterPath -Path @{ Path = '/home/username/folder1' } | Should-Be '/home/username/folder1' } It "Writes path correctly when provided through array of hashtable" { - Format-PesterPath -Path @{ Path = "/home/username/folder1" }, @{ Path = "/home/username/folder2" } -Delimiter ', ' | Should -Be "/home/username/folder1, /home/username/folder2" + Format-PesterPath -Path @{ Path = '/home/username/folder1' }, @{ Path = '/home/username/folder2' } -Delimiter ', ' | Should-Be '/home/username/folder1, /home/username/folder2' } } else { It "Writes path correctly when it is provided as string" { - Format-PesterPath -Path "C:\path" | Should -Be "C:\path" + Format-PesterPath -Path 'C:\path' | Should-Be 'C:\path' } It "Writes path correctly when it is provided as string[]" { - Format-PesterPath -Path @("C:\path1", "C:\path2") -Delimiter ', ' | Should -Be "C:\path1, C:\path2" + Format-PesterPath -Path @('C:\path1', 'C:\path2') -Delimiter ', ' | Should-Be 'C:\path1, C:\path2' } It "Writes path correctly when provided through hashtable" { - Format-PesterPath -Path @{ Path = "C:\path" } | Should -Be "C:\path" + Format-PesterPath -Path @{ Path = 'C:\path' } | Should-Be 'C:\path' } It "Writes path correctly when provided through array of hashtable" { - Format-PesterPath -Path @{ Path = "C:\path1" }, @{ Path = "C:\path2" } -Delimiter ', ' | Should -Be "C:\path1, C:\path2" + Format-PesterPath -Path @{ Path = 'C:\path1' }, @{ Path = 'C:\path2' } -Delimiter ', ' | Should-Be 'C:\path1, C:\path2' } } } - Describe ConvertTo-FailureLines { + Describe "ConvertTo-FailureLines" { BeforeAll { $showFullErrors = & (Get-Module Pester) { @@ -160,13 +160,13 @@ InModuleScope -ModuleName Pester -ScriptBlock { $r = $e | ConvertTo-FailureLines - $r.Message[0] | Should -be 'RuntimeException: message' - $r.Message.Count | Should -be 1 + $r.Message[0] | Should-Be 'RuntimeException: message' + $r.Message.Count | Should-Be 1 } It 'failed should produces correct message lines.' { try { - 'One' | Should -be 'Two' -ErrorAction Stop + 'One' | Should -Be 'Two' -ErrorAction Stop } catch { $e = $_ @@ -174,16 +174,16 @@ InModuleScope -ModuleName Pester -ScriptBlock { $r = $e | ConvertTo-FailureLines - $r.Message[0] | Should -be 'Expected strings to be the same, but they were different.' - $r.message[1] | Should -be 'String lengths are both 3.' - $r.message[2] | Should -be 'Strings differ at index 0.' - $r.Message[3] | Should -be "Expected: 'Two'" - $r.Message[4] | Should -be "But was: 'One'" - $r.Message[5] | Should -be " ^" - $r.Message.Count | Should -be 6 + $r.Message[0] | Should-Be 'Expected strings to be the same, but they were different.' + $r.message[1] | Should-Be 'String lengths are both 3.' + $r.message[2] | Should-Be 'Strings differ at index 0.' + $r.Message[3] | Should-Be "Expected: 'Two'" + $r.Message[4] | Should-Be "But was: 'One'" + $r.Message[5] | Should-Be ' ^' + $r.Message.Count | Should-Be 6 - $r.Trace[0] | Should -match "'One' | Should -be 'Two'" - $r.Trace.Count | Should -be 1 + $r.Trace[0] | Should-MatchString "'One' | Should -be 'Two'" + $r.Trace.Count | Should-Be 1 } # TODO: should fails with a very weird error, probably has something to do with dynamic params... # Context 'Should fails in file' { @@ -252,36 +252,36 @@ InModuleScope -ModuleName Pester -ScriptBlock { } It 'produces correct message lines.' { - $r.Message[0] | Should -be 'RuntimeException: f1 message' + $r.Message[0] | Should-Be 'RuntimeException: f1 message' } if ((GetPesterOS) -ne 'Windows') { It 'produces correct trace lines.' { if ($hasStackTrace) { - $r.Trace[0] | Should -be "at f1, ${testPath}:2" - $r.Trace[1] | Should -be "at f2, ${testPath}:5" - $r.Trace[2] | Should -be "at , ${testPath}:7" - $r.Trace[3] | Should -be "at , ${PSCommandPath}:244" - $r.Trace.Count | Should -be 4 + $r.Trace[0] | Should-Be "at f1, ${testPath}:2" + $r.Trace[1] | Should-Be "at f2, ${testPath}:5" + $r.Trace[2] | Should-Be "at , ${testPath}:7" + $r.Trace[3] | Should-Be "at , ${PSCommandPath}:244" + $r.Trace.Count | Should-Be 4 } } } else { It 'produces correct trace lines.' { if ($hasStackTrace) { - $r.Trace[0] | Should -be "at f1, ${testPath}:2" - $r.Trace[1] | Should -be "at f2, ${testPath}:5" - $r.Trace[2] | Should -be "at , ${testPath}:7" - $r.Trace[3] | Should -be "at , ${PSCommandPath}:244" - $r.Trace.Count | Should -be 4 + $r.Trace[0] | Should-Be "at f1, ${testPath}:2" + $r.Trace[1] | Should-Be "at f2, ${testPath}:5" + $r.Trace[2] | Should-Be "at , ${testPath}:7" + $r.Trace[3] | Should-Be "at , ${PSCommandPath}:244" + $r.Trace.Count | Should-Be 4 } } } It 'produces correct trace lines.' { if (-not $hasStackTrace) { - $r.Trace[0] | Should -be "at line: 2 in $testPath" - $r.Trace.Count | Should -be 1 + $r.Trace[0] | Should-Be "at line: 2 in $testPath" + $r.Trace.Count | Should-Be 1 } } } @@ -319,38 +319,38 @@ InModuleScope -ModuleName Pester -ScriptBlock { It 'produces correct message lines.' { if (6 -ge $PSVersionTable.PSVersion.Major) { - $r.Message[0] | Should -be 'ArgumentException: inner message' - $r.Message[1] | Should -be 'Parameter name: param_name' - $r.Message[2] | Should -be 'FormatException: outer message' + $r.Message[0] | Should-Be 'ArgumentException: inner message' + $r.Message[1] | Should-Be 'Parameter name: param_name' + $r.Message[2] | Should-Be 'FormatException: outer message' } else { - $r.Message[0] | Should -be "ArgumentException: inner message (Parameter 'param_name')" - $r.Message[1] | Should -be 'FormatException: outer message' + $r.Message[0] | Should-Be "ArgumentException: inner message (Parameter 'param_name')" + $r.Message[1] | Should-Be 'FormatException: outer message' } } if ((GetPesterOS) -ne 'Windows') { It 'produces correct trace line.' { if ($hasStackTrace) { - $r.Trace[0] | Should -be "at , $testPath`:10" - $r.Trace[1] | Should -be "at , $PSCommandPath`:310" - $r.Trace.Count | Should -be 2 + $r.Trace[0] | Should-Be "at , $testPath`:10" + $r.Trace[1] | Should-Be "at , $PSCommandPath`:310" + $r.Trace.Count | Should-Be 2 } } } else { It 'produces correct trace line.' { if ($hasStackTrace) { - $r.Trace[0] | Should -be "at , $testPath`:10" - $r.Trace[1] | Should -be "at , $PSCommandPath`:310" - $r.Trace.Count | Should -be 2 + $r.Trace[0] | Should-Be "at , $testPath`:10" + $r.Trace[1] | Should-Be "at , $PSCommandPath`:310" + $r.Trace.Count | Should-Be 2 } } } It 'produces correct trace line.' { if (-not $hasStackTrace) { - $r.Trace[0] | Should -be "at line: 10 in $testPath" - $r.Trace.Count | Should -be 1 + $r.Trace[0] | Should-Be "at line: 10 in $testPath" + $r.Trace.Count | Should-Be 1 } } } @@ -358,7 +358,7 @@ InModuleScope -ModuleName Pester -ScriptBlock { Context 'Exceptions with no error message property set' { BeforeAll { try { - $exceptionWithNullMessage = New-Object -TypeName "System.Management.Automation.ParentContainsErrorRecordException" + $exceptionWithNullMessage = New-Object -TypeName 'System.Management.Automation.ParentContainsErrorRecordException' throw $exceptionWithNullMessage } catch { @@ -369,17 +369,17 @@ InModuleScope -ModuleName Pester -ScriptBlock { It 'produces correct message lines' { - $r.Message.Length | Should -Be 0 + $r.Message.Length | Should-Be 0 } It 'produces correct trace line' { - $r.Trace.Count | Should -Be 1 + $r.Trace.Count | Should-Be 1 } } } Describe Format-ErrorMessage { - Context "Formats error messages for one error" { + Context 'Formats error messages for one error' { BeforeEach { try { 1 / 0 @@ -387,64 +387,64 @@ InModuleScope -ModuleName Pester -ScriptBlock { catch [System.DivideByZeroException] { $errorRecord = $_ } - $errorRecord | Add-Member -Name "DisplayErrorMessage" -MemberType NoteProperty -Value "Failed to divide 1/0" + $errorRecord | Add-Member -Name 'DisplayErrorMessage' -MemberType NoteProperty -Value 'Failed to divide 1/0' $stackTraceText = $errorRecord.Exception.ToString() + "$([Environment]::NewLine)at , ${PSCommandPath}:230" - $errorRecord | Add-Member -Name "DisplayStackTrace" -MemberType NoteProperty -Value $stackTraceText + $errorRecord | Add-Member -Name 'DisplayStackTrace' -MemberType NoteProperty -Value $stackTraceText } - It "When StackTraceVerbosity is None, it has only one error message in output" { - $errorMessage = Format-ErrorMessage -Err $errorRecord -StackTraceVerbosity "None" + It 'When StackTraceVerbosity is None, it has only one error message in output' { + $errorMessage = Format-ErrorMessage -Err $errorRecord -StackTraceVerbosity 'None' $messages = $errorMessage -split [Environment]::NewLine - $messages[0] | Should -BeExactly "Failed to divide 1/0" - $messages | Should -HaveCount 1 + $messages[0] | Should-BeString 'Failed to divide 1/0' -CaseSensitive + $messages | Should-BeCollection -Count 1 } - It "When StackTraceVerbosity is FirstLine, it has error message and first line of stack trace in output" { - $errorMessage = Format-ErrorMessage -Err $errorRecord -StackTraceVerbosity "FirstLine" + It 'When StackTraceVerbosity is FirstLine, it has error message and first line of stack trace in output' { + $errorMessage = Format-ErrorMessage -Err $errorRecord -StackTraceVerbosity 'FirstLine' $messages = $errorMessage -split [Environment]::NewLine - $messages[0] | Should -BeExactly "Failed to divide 1/0" - $messages[1] | Should -BeExactly "System.DivideByZeroException: Attempted to divide by zero." - $messages | Should -HaveCount 2 + $messages[0] | Should-BeString 'Failed to divide 1/0' -CaseSensitive + $messages[1] | Should-BeString 'System.DivideByZeroException: Attempted to divide by zero.' -CaseSensitive + $messages | Should-BeCollection -Count 2 } - It "When StackTraceVerbosity is Filtered, it has error message and two lines of stacktrace output" { - $errorMessage = Format-ErrorMessage -Err $errorRecord -StackTraceVerbosity "Filtered" + It 'When StackTraceVerbosity is Filtered, it has error message and two lines of stacktrace output' { + $errorMessage = Format-ErrorMessage -Err $errorRecord -StackTraceVerbosity 'Filtered' $messages = $errorMessage -split [Environment]::NewLine - $messages[0] | Should -BeExactly "Failed to divide 1/0" - $messages[1] | Should -BeExactly "System.DivideByZeroException: Attempted to divide by zero." - $messages[2] | Should -BeExactly "at , ${PSCommandPath}:230" - $messages.Count | Should -BeGreaterThan 2 + $messages[0] | Should-BeString 'Failed to divide 1/0' -CaseSensitive + $messages[1] | Should-BeString 'System.DivideByZeroException: Attempted to divide by zero.' -CaseSensitive + $messages[2] | Should-BeString "at , ${PSCommandPath}:230" -CaseSensitive + $messages.Count | Should-BeGreaterThan 2 } - It "When StackTraceVerbosity is Full, it has error message and two lines of stacktrace output" { - $errorMessage = Format-ErrorMessage -Err $errorRecord -StackTraceVerbosity "Full" + It 'When StackTraceVerbosity is Full, it has error message and two lines of stacktrace output' { + $errorMessage = Format-ErrorMessage -Err $errorRecord -StackTraceVerbosity 'Full' $messages = $errorMessage -split [Environment]::NewLine - $messages[0] | Should -BeExactly "Failed to divide 1/0" - $messages[1] | Should -BeExactly "System.DivideByZeroException: Attempted to divide by zero." - $messages[2] | Should -BeExactly "at , ${PSCommandPath}:230" - $messages.Count | Should -BeGreaterThan 2 + $messages[0] | Should-BeString 'Failed to divide 1/0' -CaseSensitive + $messages[1] | Should-BeString 'System.DivideByZeroException: Attempted to divide by zero.' -CaseSensitive + $messages[2] | Should-BeString "at , ${PSCommandPath}:230" -CaseSensitive + $messages.Count | Should-BeGreaterThan 2 } It "When StackTraceVerbosity is '<_>' and DisplayErrorMessage is `$null, it has execption message with script stack trace" -ForEach @('None', 'FirstLine', 'Filtered', 'Full') { $errorRecord.DisplayErrorMessage = $null $errorMessage = Format-ErrorMessage -Err $errorRecord -StackTraceVerbosity $_ $messages = $errorMessage -split [Environment]::NewLine - $messages[0] | Should -BeExactly "System.DivideByZeroException: Attempted to divide by zero." - $messages[1] | Should -BeExactly "at , ${PSCommandPath}: line 385" - $messages.Count | Should -BeGreaterThan 1 + $messages[0] | Should-BeString 'System.DivideByZeroException: Attempted to divide by zero.' -CaseSensitive + $messages[1] | Should-BeString "at , ${PSCommandPath}: line 385" -CaseSensitive + $messages.Count | Should-BeGreaterThan 1 } It "When StackTraceVerbosity is '<_>' and DisplayStackTrace is `$null, it has only one error message in output" -ForEach @('None', 'FirstLine', 'Filtered', 'Full') { $errorRecord.DisplayStackTrace = $null $errorMessage = Format-ErrorMessage -Err $errorRecord -StackTraceVerbosity $_ $messages = $errorMessage -split [Environment]::NewLine - $messages[0] | Should -BeExactly "Failed to divide 1/0" - $messages | Should -HaveCount 1 + $messages[0] | Should-BeString 'Failed to divide 1/0' -CaseSensitive + $messages | Should-BeCollection -Count 1 } } - Context "Formats error messages for multiple errors" { + Context 'Formats error messages for multiple errors' { BeforeEach { $errorRecords = @() for ($i = 1; $i -lt 3; $i++) { @@ -454,53 +454,53 @@ InModuleScope -ModuleName Pester -ScriptBlock { catch [System.DivideByZeroException] { $errorRecord = $_ } - $errorRecord | Add-Member -Name "DisplayErrorMessage" -MemberType NoteProperty -Value "Failed to divide $i/0" + $errorRecord | Add-Member -Name 'DisplayErrorMessage' -MemberType NoteProperty -Value "Failed to divide $i/0" $stackTraceText = $errorRecord.Exception.ToString() + "$([Environment]::NewLine)at , ${PSCommandPath}:230" - $errorRecord | Add-Member -Name "DisplayStackTrace" -MemberType NoteProperty -Value $stackTraceText + $errorRecord | Add-Member -Name 'DisplayStackTrace' -MemberType NoteProperty -Value $stackTraceText $errorRecords += $errorRecord } } - It "When StackTraceVerbosity is None, it has only one error message in output" { - $errorMessage = Format-ErrorMessage -Err $errorRecords -StackTraceVerbosity "None" + It 'When StackTraceVerbosity is None, it has only one error message in output' { + $errorMessage = Format-ErrorMessage -Err $errorRecords -StackTraceVerbosity 'None' $messages = $errorMessage -split [Environment]::NewLine - $messages[0] | Should -BeExactly "[0] Failed to divide 1/0" - $messages[1] | Should -BeExactly "[1] Failed to divide 2/0" - $messages | Should -HaveCount 2 + $messages[0] | Should-BeString '[0] Failed to divide 1/0' -CaseSensitive + $messages[1] | Should-BeString '[1] Failed to divide 2/0' -CaseSensitive + $messages | Should-BeCollection -Count 2 } - It "When StackTraceVerbosity is FirstLine, it has error message and first line of stack trace in output" { - $errorMessage = Format-ErrorMessage -Err $errorRecords -StackTraceVerbosity "FirstLine" + It 'When StackTraceVerbosity is FirstLine, it has error message and first line of stack trace in output' { + $errorMessage = Format-ErrorMessage -Err $errorRecords -StackTraceVerbosity 'FirstLine' $messages = $errorMessage -split [Environment]::NewLine - $messages[0] | Should -BeExactly "[0] Failed to divide 1/0" - $messages[1] | Should -BeExactly "System.DivideByZeroException: Attempted to divide by zero." - $messages[2] | Should -BeExactly "[1] Failed to divide 2/0" - $messages[3] | Should -BeExactly "System.DivideByZeroException: Attempted to divide by zero." - $messages | Should -HaveCount 4 + $messages[0] | Should-BeString '[0] Failed to divide 1/0' -CaseSensitive + $messages[1] | Should-BeString 'System.DivideByZeroException: Attempted to divide by zero.' -CaseSensitive + $messages[2] | Should-BeString '[1] Failed to divide 2/0' -CaseSensitive + $messages[3] | Should-BeString 'System.DivideByZeroException: Attempted to divide by zero.' -CaseSensitive + $messages | Should-BeCollection -Count 4 } - It "When StackTraceVerbosity is Filtered, it has two error messages and four lines stacktrace output" { - $errorMessage = Format-ErrorMessage -Err $errorRecords -StackTraceVerbosity "Filtered" + It 'When StackTraceVerbosity is Filtered, it has two error messages and four lines stacktrace output' { + $errorMessage = Format-ErrorMessage -Err $errorRecords -StackTraceVerbosity 'Filtered' $messages = $errorMessage -split [Environment]::NewLine - $messages[0] | Should -BeExactly "[0] Failed to divide 1/0" - $messages[1] | Should -BeExactly "System.DivideByZeroException: Attempted to divide by zero." - $messages[2] | Should -BeExactly "at , ${PSCommandPath}:230" - $messages[3] | Should -BeExactly "[1] Failed to divide 2/0" - $messages[4] | Should -BeExactly "System.DivideByZeroException: Attempted to divide by zero." - $messages[5] | Should -BeExactly "at , ${PSCommandPath}:230" - $messages.Count | Should -BeGreaterThan 4 + $messages[0] | Should-BeString '[0] Failed to divide 1/0' -CaseSensitive + $messages[1] | Should-BeString 'System.DivideByZeroException: Attempted to divide by zero.' -CaseSensitive + $messages[2] | Should-BeString "at , ${PSCommandPath}:230" -CaseSensitive + $messages[3] | Should-BeString '[1] Failed to divide 2/0' -CaseSensitive + $messages[4] | Should-BeString 'System.DivideByZeroException: Attempted to divide by zero.' -CaseSensitive + $messages[5] | Should-BeString "at , ${PSCommandPath}:230" -CaseSensitive + $messages.Count | Should-BeGreaterThan 4 } - It "When StackTraceVerbosity is Full, it has two error messages and four lines stacktrace output" { - $errorMessage = Format-ErrorMessage -Err $errorRecords -StackTraceVerbosity "Full" + It 'When StackTraceVerbosity is Full, it has two error messages and four lines stacktrace output' { + $errorMessage = Format-ErrorMessage -Err $errorRecords -StackTraceVerbosity 'Full' $messages = $errorMessage -split [Environment]::NewLine - $messages[0] | Should -BeExactly "[0] Failed to divide 1/0" - $messages[1] | Should -BeExactly "System.DivideByZeroException: Attempted to divide by zero." - $messages[2] | Should -BeExactly "at , ${PSCommandPath}:230" - $messages[3] | Should -BeExactly "[1] Failed to divide 2/0" - $messages[4] | Should -BeExactly "System.DivideByZeroException: Attempted to divide by zero." - $messages[5] | Should -BeExactly "at , ${PSCommandPath}:230" - $messages.Count | Should -BeGreaterThan 4 + $messages[0] | Should-BeString '[0] Failed to divide 1/0' -CaseSensitive + $messages[1] | Should-BeString 'System.DivideByZeroException: Attempted to divide by zero.' -CaseSensitive + $messages[2] | Should-BeString "at , ${PSCommandPath}:230" -CaseSensitive + $messages[3] | Should-BeString '[1] Failed to divide 2/0' -CaseSensitive + $messages[4] | Should-BeString 'System.DivideByZeroException: Attempted to divide by zero.' -CaseSensitive + $messages[5] | Should-BeString "at , ${PSCommandPath}:230" -CaseSensitive + $messages.Count | Should-BeGreaterThan 4 } It "When StackTraceVerbosity is '<_>' and DisplayErrorMessage is `$null, it has execption message with script stack trace" -ForEach @('None', 'FirstLine', 'Filtered', 'Full') { @@ -508,8 +508,8 @@ InModuleScope -ModuleName Pester -ScriptBlock { $errorRecord.DisplayErrorMessage = $null $errorMessage = Format-ErrorMessage -Err $errorRecord -StackTraceVerbosity $_ $messages = $errorMessage -split [Environment]::NewLine - $messages[0] | Should -BeExactly "System.DivideByZeroException: Attempted to divide by zero." - $messages | Should -BeGreaterThan 1 + $messages[0] | Should-BeString 'System.DivideByZeroException: Attempted to divide by zero.' -CaseSensitive + $messages.Count | Should-BeGreaterThan 1 } } @@ -518,8 +518,8 @@ InModuleScope -ModuleName Pester -ScriptBlock { $errorRecords[$i].DisplayStackTrace = $null $errorMessage = Format-ErrorMessage -Err $errorRecords[$i] -StackTraceVerbosity $_ $messages = $errorMessage -split [Environment]::NewLine - $messages[0] | Should -BeExactly "Failed to divide $($i + 1)/0" - $messages | Should -HaveCount 1 + $messages[0] | Should-BeString "Failed to divide $($i + 1)/0" -CaseSensitive + $messages | Should-BeCollection -Count 1 } } } @@ -533,16 +533,16 @@ InModuleScope -ModuleName Pester -ScriptBlock { catch [System.DivideByZeroException] { $errorRecord = $_ } - $errorRecord | Add-Member -Name "DisplayErrorMessage" -MemberType NoteProperty -Value "Failed to divide 1/0" - $errorRecord | Add-Member -Name "DisplayStackTrace" -MemberType NoteProperty -Value $errorRecord.Exception.ToString() + $errorRecord | Add-Member -Name 'DisplayErrorMessage' -MemberType NoteProperty -Value 'Failed to divide 1/0' + $errorRecord | Add-Member -Name 'DisplayStackTrace' -MemberType NoteProperty -Value $errorRecord.Exception.ToString() } - It "Throw error message" { - { Write-ErrorToScreen -Err $errorRecord -Throw } | Should -Throw + It 'Throw error message' { + { Write-ErrorToScreen -Err $errorRecord -Throw } | Should-Throw } } Describe Format-CIErrorMessage { - Context "Azure Devops Error Format" { + Context 'Azure Devops Error Format' { It "Header '
' and Message '' returns ''" -TestCases @( @{ Header = 'header' @@ -562,11 +562,11 @@ InModuleScope -ModuleName Pester -ScriptBlock { ) } ) { - Format-CIErrorMessage -CIFormat 'AzureDevops' -CILogLevel 'Error' -Header $Header -Message $Message | Should -Be $Expected + Format-CIErrorMessage -CIFormat 'AzureDevops' -CILogLevel 'Error' -Header $Header -Message $Message | Should-BeCollection $Expected } } - Context "Azure Devops Warning Format" { + Context 'Azure Devops Warning Format' { It "Header '
' and Message '' returns ''" -TestCases @( @{ Header = 'header' @@ -586,7 +586,7 @@ InModuleScope -ModuleName Pester -ScriptBlock { ) } ) { - Format-CIErrorMessage -CIFormat 'AzureDevops' -CILogLevel 'Warning' -Header $Header -Message $Message | Should -Be $Expected + Format-CIErrorMessage -CIFormat 'AzureDevops' -CILogLevel 'Warning' -Header $Header -Message $Message | Should-BeCollection $Expected } } @@ -625,7 +625,7 @@ InModuleScope -ModuleName Pester -ScriptBlock { ) } ) { - Format-CIErrorMessage -CIFormat 'GithubActions' -CILogLevel 'Error' -Header $Header -Message $Message | Should -Be $Expected + Format-CIErrorMessage -CIFormat 'GithubActions' -CILogLevel 'Error' -Header $Header -Message $Message | Should-BeCollection $Expected } } @@ -664,7 +664,7 @@ InModuleScope -ModuleName Pester -ScriptBlock { ) } ) { - Format-CIErrorMessage -CIFormat 'GithubActions' -CILogLevel 'Warning' -Header $Header -Message $Message | Should -Be $Expected + Format-CIErrorMessage -CIFormat 'GithubActions' -CILogLevel 'Warning' -Header $Header -Message $Message | Should-BeCollection $Expected } } } @@ -685,7 +685,7 @@ Describe 'Write-PesterHostMessage' { It 'Parameter <_.Name> is equal' -TestCases $WriteHostParam { $param = $_ $param.Name | Should -BeIn $WritePesterHostMessageParam.Keys - $WritePesterHostMessageParam[$param.Name].ParameterType | Should -Be $param.ParameterType + $WritePesterHostMessageParam[$param.Name].ParameterType | Should-Be $param.ParameterType if ($param.Aliases) { $param.Aliases | Should -BeIn $WritePesterHostMessageParam[$param.Name].Aliases } } } diff --git a/tst/functions/Set-ItResult.Tests.ps1 b/tst/functions/Set-ItResult.Tests.ps1 index 91622e4be..4750e8081 100644 --- a/tst/functions/Set-ItResult.Tests.ps1 +++ b/tst/functions/Set-ItResult.Tests.ps1 @@ -6,7 +6,7 @@ Describe "Testing Set-ItResult" { Set-ItResult -Inconclusive -Because "we are setting it to inconclusive" } catch { - $_.FullyQualifiedErrorID | Should -Be "PesterTestInconclusive" + $_.FullyQualifiedErrorID | Should-Be "PesterTestInconclusive" } } @@ -15,7 +15,7 @@ Describe "Testing Set-ItResult" { Set-ItResult -Skipped -Because "we are forcing it to skip" } catch { - $_.FullyQualifiedErrorID | Should -Be "PesterTestSkipped" + $_.FullyQualifiedErrorID | Should-Be "PesterTestSkipped" } } @@ -24,7 +24,7 @@ Describe "Testing Set-ItResult" { Set-ItResult -Skipped -Because "we are forcing it to skip" } catch { - $_.Exception.Message | Should -Be "is skipped, because we are forcing it to skip" + $_.Exception.Message | Should-Be "is skipped, because we are forcing it to skip" } } @@ -33,16 +33,16 @@ Describe "Testing Set-ItResult" { Set-ItResult -Skipped } catch { - $_.FullyQualifiedErrorID | Should -Be "PesterTestSkipped" + $_.FullyQualifiedErrorID | Should-Be "PesterTestSkipped" } } It "Set-ItResult has to have a switch indicating what to set it to" { - { Set-ItResult -Because "testing with no switch" } | Should -Throw -Because "the expected state is not selected" + { Set-ItResult -Because "testing with no switch" } | Should-Throw -Because "the expected state is not selected" } It "Set-ItResult cannot be called with two states requested" { - { Set-ItResult -Inconclusive -Skipped } | Should -Throw -Because "two states are requested" + { Set-ItResult -Inconclusive -Skipped } | Should-Throw -Because "two states are requested" } } diff --git a/tst/functions/SetupTeardown.Tests.ps1 b/tst/functions/SetupTeardown.Tests.ps1 index 71d0347be..515b6a53e 100644 --- a/tst/functions/SetupTeardown.Tests.ps1 +++ b/tst/functions/SetupTeardown.Tests.ps1 @@ -8,12 +8,12 @@ Describe 'Describe-Scoped Test Case setup' { $testVariable = 'Set in Describe' It 'Assigns the correct value in first test' { - $testVariable | Should -Be 'From BeforeEach' + $testVariable | Should-Be 'From BeforeEach' $testVariable = 'Set in It' } It 'Assigns the correct value in subsequent tests' { - $testVariable | Should -Be 'From BeforeEach' + $testVariable | Should-Be 'From BeforeEach' } } @@ -25,12 +25,12 @@ Describe 'Describe-Scoped Test Case setup using named ScriptBlock-parameter' { $testVariable = 'Set in Describe' It 'Assigns the correct value in first test' { - $testVariable | Should -Be 'From BeforeEach' + $testVariable | Should-Be 'From BeforeEach' $testVariable = 'Set in It' } It 'Assigns the correct value in subsequent tests' { - $testVariable | Should -Be 'From BeforeEach' + $testVariable | Should-Be 'From BeforeEach' } } @@ -44,12 +44,12 @@ Describe 'Context-scoped Test Case setup' { } It 'Assigns the correct value inside the context' { - $testVariable | Should -Be 'From BeforeEach' + $testVariable | Should-Be 'From BeforeEach' } } It 'Reports the original value after the Context' { - $testVariable | Should -Be 'Set in Describe' + $testVariable | Should-Be 'Set in Describe' } } @@ -64,7 +64,7 @@ Describe 'Multiple Test Case setup blocks' { Context 'The context' { It 'Executes Describe setup blocks first, then Context block' { - $testVariable | Should -Be 'Set in Context BeforeEach' + $testVariable | Should-Be 'Set in Context BeforeEach' } BeforeEach { @@ -73,7 +73,7 @@ Describe 'Multiple Test Case setup blocks' { } It 'Continues to execute Describe setup blocks after the Context' { - $testVariable | Should -Be 'Set in Describe BeforeEach' + $testVariable | Should-Be 'Set in Describe BeforeEach' } } @@ -87,11 +87,11 @@ Describe 'Describe-scoped Test Case teardown' { } It 'Does not modify the variable before the first test' { - $testVariable | Should -Be 'Set in Describe' + $testVariable | Should-Be 'Set in Describe' } It 'Keeps the describe variable after the first test' { - $testVariable | Should -Be 'Set in Describe' + $testVariable | Should-Be 'Set in Describe' } } @@ -115,7 +115,7 @@ Describe 'Multiple Test Case teardown blocks' { It 'Performs a test in Context' { "some output" } It 'Executes Describe teardown blocks after Context teardown blocks' { - $container.Value | Should -Be 'Set in Describe AfterEach' + $container.Value | Should-Be 'Set in Describe AfterEach' } } } @@ -131,13 +131,13 @@ BeforeAll { Describe 'Test Group Setup and Teardown' { It 'Executed the Describe BeforeAll regardless of definition order' { - $container.DescribeBeforeAllCounter | Should -Be 1 + $container.DescribeBeforeAllCounter | Should-Be 1 } It 'Did not execute any other block yet' { - $container.DescribeAfterAllCounter | Should -Be 0 - $container.ContextBeforeAllCounter | Should -Be 0 - $container.ContextAfterAllCounter | Should -Be 0 + $container.DescribeAfterAllCounter | Should-Be 0 + $container.ContextBeforeAllCounter | Should-Be 0 + $container.ContextAfterAllCounter | Should-Be 0 } BeforeAll { @@ -158,27 +158,27 @@ Describe 'Test Group Setup and Teardown' { } It 'Executed the Context BeforeAll block' { - $container.ContextBeforeAllCounter | Should -Be 1 + $container.ContextBeforeAllCounter | Should-Be 1 } It 'Has not executed any other blocks yet' { - $container.DescribeBeforeAllCounter | Should -Be 1 - $container.DescribeAfterAllCounter | Should -Be 0 - $container.ContextAfterAllCounter | Should -Be 0 + $container.DescribeBeforeAllCounter | Should-Be 1 + $container.DescribeAfterAllCounter | Should-Be 0 + $container.ContextAfterAllCounter | Should-Be 0 } } It 'Executed the Context AfterAll block' { - $container.ContextAfterAllCounter | Should -Be 1 + $container.ContextAfterAllCounter | Should-Be 1 } } Describe 'Finishing TestGroup Setup and Teardown tests' { It 'Executed each Describe and Context group block once' { - $container.DescribeBeforeAllCounter | Should -Be 1 - $container.DescribeAfterAllCounter | Should -Be 1 - $container.ContextBeforeAllCounter | Should -Be 1 - $container.ContextAfterAllCounter | Should -Be 1 + $container.DescribeBeforeAllCounter | Should-Be 1 + $container.DescribeAfterAllCounter | Should-Be 1 + $container.ContextBeforeAllCounter | Should-Be 1 + $container.ContextAfterAllCounter | Should-Be 1 } } @@ -189,16 +189,16 @@ Describe 'Unbound scriptsblocks as input' { $expectedMessage = 'Unbound scriptblock*' } It 'Throws when provided to BeforeAll' { - { BeforeAll -Scriptblock $sb } | Should -Throw -ExpectedMessage $expectedMessage + { BeforeAll -Scriptblock $sb } | Should-Throw -ExceptionMessage $expectedMessage } It 'Throws when provided to AfterAll' { - { AfterAll -Scriptblock $sb } | Should -Throw -ExpectedMessage $expectedMessage + { AfterAll -Scriptblock $sb } | Should-Throw -ExceptionMessage $expectedMessage } It 'Throws when provided to BeforeEach' { - { BeforeEach -Scriptblock $sb } | Should -Throw -ExpectedMessage $expectedMessage + { BeforeEach -Scriptblock $sb } | Should-Throw -ExceptionMessage $expectedMessage } It 'Throws when provided to AfterEach' { - { AfterEach -Scriptblock $sb } | Should -Throw -ExpectedMessage $expectedMessage + { AfterEach -Scriptblock $sb } | Should-Throw -ExceptionMessage $expectedMessage } } @@ -216,7 +216,7 @@ Describe 'Duplicate setup and teardown blocks throw' { $c.Run.PassThru = $true $c.Output.Verbosity = 'None' $r = Invoke-Pester -Configuration $c - $r.Containers[0].ErrorRecord[0].Exception.Message | Should -BeLike '*BeforeAll is already defined*' + $r.Containers[0].ErrorRecord[0].Exception.Message | Should-BeLikeString '*BeforeAll is already defined*' } It 'Throws when two AfterAll are defined in the same block' { @@ -232,7 +232,7 @@ Describe 'Duplicate setup and teardown blocks throw' { $c.Run.PassThru = $true $c.Output.Verbosity = 'None' $r = Invoke-Pester -Configuration $c - $r.Containers[0].ErrorRecord[0].Exception.Message | Should -BeLike '*AfterAll is already defined*' + $r.Containers[0].ErrorRecord[0].Exception.Message | Should-BeLikeString '*AfterAll is already defined*' } It 'Throws when two BeforeEach are defined in the same block' { @@ -248,7 +248,7 @@ Describe 'Duplicate setup and teardown blocks throw' { $c.Run.PassThru = $true $c.Output.Verbosity = 'None' $r = Invoke-Pester -Configuration $c - $r.Containers[0].ErrorRecord[0].Exception.Message | Should -BeLike '*BeforeEach is already defined*' + $r.Containers[0].ErrorRecord[0].Exception.Message | Should-BeLikeString '*BeforeEach is already defined*' } It 'Throws when two AfterEach are defined in the same block' { @@ -264,7 +264,7 @@ Describe 'Duplicate setup and teardown blocks throw' { $c.Run.PassThru = $true $c.Output.Verbosity = 'None' $r = Invoke-Pester -Configuration $c - $r.Containers[0].ErrorRecord[0].Exception.Message | Should -BeLike '*AfterEach is already defined*' + $r.Containers[0].ErrorRecord[0].Exception.Message | Should-BeLikeString '*AfterEach is already defined*' } It 'Allows same hook type in different blocks' { @@ -273,7 +273,7 @@ Describe 'Duplicate setup and teardown blocks throw' { BeforeAll { $script:x = 1 } Context 'c' { BeforeAll { $script:y = 2 } - It 'i' { $script:x + $script:y | Should -Be 3 } + It 'i' { $script:x + $script:y | Should-Be 3 } } } } @@ -282,7 +282,7 @@ Describe 'Duplicate setup and teardown blocks throw' { $c.Run.PassThru = $true $c.Output.Verbosity = 'None' $r = Invoke-Pester -Configuration $c - $r.FailedCount | Should -Be 0 + $r.FailedCount | Should-Be 0 } } # # TODO: this depends on the old pester internals it would be easier to test in P diff --git a/tst/functions/TestDrive.Tests.ps1 b/tst/functions/TestDrive.Tests.ps1 index 521026561..fd271cefe 100644 --- a/tst/functions/TestDrive.Tests.ps1 +++ b/tst/functions/TestDrive.Tests.ps1 @@ -96,7 +96,7 @@ InPesterModuleScope { $first | Remove-Item -Force $second | Remove-Item -Force - $first | Should -Not -Be $second + $first | Should-NotBe $second } } @@ -195,11 +195,11 @@ Describe 'Repair missing TestDrive' { Context 'Broken' { It 'Removes TestDrive' { Should -Exist -ActualValue $tempFilePath - Get-Content -Path $tempFilePath | Should -Be 'Hello' + Get-Content -Path $tempFilePath | Should-Be 'Hello' # Remove PSDrive Remove-PSDrive -Name 'TestDrive' - { Get-PSDrive -Name 'TestDrive' -ErrorAction Stop } | Should -Throw -ExpectedMessage 'Cannot find drive*' + { Get-PSDrive -Name 'TestDrive' -ErrorAction Stop } | Should-Throw -ExceptionMessage 'Cannot find drive*' # Remove variable Set-Variable -Name TestDrive -Scope Global -Value $null @@ -214,7 +214,7 @@ Describe 'Repair missing TestDrive' { Should -Exist -ActualValue $tempFilePath # Verify PSDrive - Get-Content -Path "TestDrive:/$tempFileName" | Should -Be 'Hello' + Get-Content -Path "TestDrive:/$tempFileName" | Should-Be 'Hello' } } } @@ -228,7 +228,7 @@ Describe 'Running Pester in Pester' { It 'File exists before' { Should -Exist -ActualValue $tempFilePath - Get-Content -Path $tempFilePath | Should -Be 'Hello' + Get-Content -Path $tempFilePath | Should-Be 'Hello' } It 'Works in nested run' { @@ -236,13 +236,13 @@ Describe 'Running Pester in Pester' { Describe 'Nested' { It 'Files created in outer run are available using absolute path' { Should -Exist -ActualValue $TempFilePath - Get-Content -Path $TempFilePath | Should -Be 'Hello' + Get-Content -Path $TempFilePath | Should-Be 'Hello' } It 'TestDrive PSDrive and $TestDrive points to clean location' { # Variable should point to new drive $outerTestDrive = Split-Path $tempFilePath - $TestDrive | Should -Not -Be $outerTestDrive + $TestDrive | Should-NotBe $outerTestDrive # TestDrive should be clean in inner run Get-ChildItem -Path 'TestDrive:/' | Should -BeNullOrEmpty @@ -252,17 +252,17 @@ Describe 'Running Pester in Pester' { $c = New-PesterContainer -ScriptBlock $sb -Data @{ TempFilePath = $tempFilePath } $innerRun = Invoke-Pester -Container $c -PassThru -Output None - $innerRun.Result | Should -Be 'Passed' - $innerRun.PassedCount | Should -Be 2 + $innerRun.Result | Should-Be 'Passed' + $innerRun.PassedCount | Should-Be 2 } It 'TestDrive PSDrive and $TestDrive point to original location' { $originalTestDrive = Split-Path $tempFilePath - $TestDrive | Should -Be $originalTestDrive + $TestDrive | Should-Be $originalTestDrive $tempFilePath2 = Join-Path -Path 'TestDrive:/' -ChildPath $tempFileName Should -Exist -ActualValue $tempFilePath2 - Get-Content -Path $tempFilePath2 | Should -Be 'Hello' + Get-Content -Path $tempFilePath2 | Should-Be 'Hello' } } diff --git a/tst/functions/TestRegistry.Tests.ps1 b/tst/functions/TestRegistry.Tests.ps1 index 94ff38b50..b7eb5b518 100644 --- a/tst/functions/TestRegistry.Tests.ps1 +++ b/tst/functions/TestRegistry.Tests.ps1 @@ -13,7 +13,7 @@ Describe "General" { It "is located in Pester key in HKCU" { $testRegistryPath = (Get-PSDrive TestRegistry).Root - $testRegistryPath | Should -BeLike "HKEY_CURRENT_USER\Software\Pester*" + $testRegistryPath | Should-BeLikeString "HKEY_CURRENT_USER\Software\Pester*" } } @@ -67,15 +67,15 @@ Describe 'Repair missing TestRegistry' { Context 'Broken' { It 'Removes TestRegistry' { - (Get-ItemProperty -Path 'TestRegistry:/' -Name $tempValueName).$tempValueName | Should -Be 1 + (Get-ItemProperty -Path 'TestRegistry:/' -Name $tempValueName).$tempValueName | Should-Be 1 Remove-PSDrive -Name 'TestRegistry' - { Get-PSDrive -Name 'TestRegistry' -ErrorAction Stop } | Should -Throw -ExpectedMessage 'Cannot find drive*' + { Get-PSDrive -Name 'TestRegistry' -ErrorAction Stop } | Should-Throw -ExceptionMessage 'Cannot find drive*' } } Context 'Fixed' { It 'TestRegistry exists again' { - (Get-ItemProperty -Path 'TestRegistry:/' -Name $tempValueName).$tempValueName | Should -Be 1 + (Get-ItemProperty -Path 'TestRegistry:/' -Name $tempValueName).$tempValueName | Should-Be 1 } } } @@ -87,14 +87,14 @@ Describe 'Running Pester in Invoke-Pester' { } It 'Value exists before' { - (Get-ItemProperty -Path 'TestRegistry:/' -Name $tempValueName).$tempValueName | Should -Be 1 + (Get-ItemProperty -Path 'TestRegistry:/' -Name $tempValueName).$tempValueName | Should-Be 1 } It 'Works in nested run' { $sb = { Describe 'Nested' { It 'Value created in outer run are available using absolute path' { - (Get-ItemProperty -Path $TempKeyPath -Name $TempValueName).$TempValueName | Should -Be 1 + (Get-ItemProperty -Path $TempKeyPath -Name $TempValueName).$TempValueName | Should-Be 1 } It 'TestRegistry PSDrive points to clean location' { @@ -105,11 +105,11 @@ Describe 'Running Pester in Invoke-Pester' { $c = New-PesterContainer -ScriptBlock $sb -Data @{ TempKeyPath = $tempValue.PSPath; TempValueName = $tempValueName } $innerRun = Invoke-Pester -Container $c -PassThru -Output None - $innerRun.Result | Should -Be 'Passed' - $innerRun.PassedCount | Should -Be 2 + $innerRun.Result | Should-Be 'Passed' + $innerRun.PassedCount | Should-Be 2 } It 'Value still exists after nested run' { - (Get-ItemProperty -Path 'TestRegistry:/' -Name $tempValueName).$tempValueName | Should -Be 1 + (Get-ItemProperty -Path 'TestRegistry:/' -Name $tempValueName).$tempValueName | Should-Be 1 } } diff --git a/tst/functions/TestResults.Tests.ps1 b/tst/functions/TestResults.Tests.ps1 index 6c09165dd..07d2ff607 100644 --- a/tst/functions/TestResults.Tests.ps1 +++ b/tst/functions/TestResults.Tests.ps1 @@ -29,15 +29,15 @@ InPesterModuleScope { #using the string formatter here to know how the string will be output to screen $Result = { Get-TestTime -Tests $TestResult | Out-String -Stream } | Using-Culture -Culture de-DE - $Result | Should -Be "3.5" + $Result | Should-Be "3.5" } It "Time is measured in seconds with 0,1 millisecond as lowest value" { $TestResult = New-Object -TypeName psObject -Property @{ Time = [timespan]1000 } - Get-TestTime -Tests $TestResult | Should -Be 0.0001 + Get-TestTime -Tests $TestResult | Should-Be 0.0001 $TestResult = New-Object -TypeName psObject -Property @{ Time = [timespan]100 } - Get-TestTime -Tests $TestResult | Should -Be 0 + Get-TestTime -Tests $TestResult | Should-Be 0 $TestResult = New-Object -TypeName psObject -Property @{ Time = [timespan]1234567 } - Get-TestTime -Tests $TestResult | Should -Be 0.1235 + Get-TestTime -Tests $TestResult | Should-Be 0.1235 } } @@ -55,14 +55,14 @@ InPesterModuleScope { Push-Location -Path TestDrive:\ $p = GetFullPath notexistingfile.txt Pop-Location - $p | Should -Be (Join-Path $TestDrive notexistingfile.txt) + $p | Should-Be (Join-Path $TestDrive notexistingfile.txt) } It "Resolves non existing path correctly - PSDrive" { Push-Location -Path TestDrive:\ $p = GetFullPath TestDrive:\notexistingfile.txt Pop-Location - $p | Should -Be (Join-Path $TestDrive notexistingfile.txt) + $p | Should-Be (Join-Path $TestDrive notexistingfile.txt) } It "Resolves existing path correctly" { @@ -70,7 +70,7 @@ InPesterModuleScope { New-Item -ItemType File -Name existingfile1.txt $p = GetFullPath existingfile1.txt Pop-Location - $p | Should -Be (Join-Path $TestDrive existingfile1.txt) + $p | Should-Be (Join-Path $TestDrive existingfile1.txt) } It "Resolves existing path correctly - PSDrive" { @@ -78,14 +78,14 @@ InPesterModuleScope { New-Item -ItemType File -Name existingfile2.txt $p = GetFullPath existingfile2.txt Pop-Location - $p | Should -Be (Join-Path $TestDrive existingfile2.txt) + $p | Should-Be (Join-Path $TestDrive existingfile2.txt) } It "Resolves full path correctly" { $powershellPath = Get-Command -Name $CommandToTest | Select-Object -ExpandProperty 'Definition' $powershellPath | Should -Not -BeNullOrEmpty - GetFullPath $powershellPath | Should -Be $powershellPath + GetFullPath $powershellPath | Should-Be $powershellPath } Pop-Location @@ -99,13 +99,13 @@ InPesterModuleScope { Describe "Get-RunTimeEnvironment" { It "Returns a hashtable with expected keys without throwing" { $result = Get-RunTimeEnvironment - $result | Should -BeOfType [hashtable] - $result.Keys | Should -Contain 'os-version' - $result.Keys | Should -Contain 'platform' - $result.Keys | Should -Contain 'machine-name' - $result.Keys | Should -Contain 'user' - $result.Keys | Should -Contain 'cwd' - $result.Keys | Should -Contain 'clr-version' + $result | Should-HaveType ([hashtable]) + $result.Keys | Should-ContainCollection 'os-version' + $result.Keys | Should-ContainCollection 'platform' + $result.Keys | Should-ContainCollection 'machine-name' + $result.Keys | Should-ContainCollection 'user' + $result.Keys | Should-ContainCollection 'cwd' + $result.Keys | Should-ContainCollection 'clr-version' $result['os-version'] | Should -Not -BeNullOrEmpty $result['platform'] | Should -Not -BeNullOrEmpty } @@ -125,8 +125,8 @@ InPesterModuleScope { $result = Get-RunTimeEnvironment - $result['platform'] | Should -Be 'Unknown' - $result['os-version'] | Should -Be '0.0.0.0' + $result['platform'] | Should-Be 'Unknown' + $result['os-version'] | Should-Be '0.0.0.0' } finally { $SafeCommands['Get-CimInstance'] = $originalCim diff --git a/tst/testProjects/BasicTests/folder1/file1.Tests.ps1 b/tst/testProjects/BasicTests/folder1/file1.Tests.ps1 index a0108d406..ba20ec012 100644 --- a/tst/testProjects/BasicTests/folder1/file1.Tests.ps1 +++ b/tst/testProjects/BasicTests/folder1/file1.Tests.ps1 @@ -2,17 +2,17 @@ Describe "describe state tests" { It "passing" { - 1 | Should -Be 1 + 1 | Should-Be 1 } It "fails" { - 1 | Should -Be 2 + 1 | Should-Be 2 } It "passing with testcases" -TestCases @( @{ Value = 1 } @{ Value = 2 } ) { - 1 | Should -Be 1 + 1 | Should-Be 1 } } From 49554639fc8614fd0505fddabfdd8603aad5e2c1 Mon Sep 17 00:00:00 2001 From: Frode Flaten <3436158+fflaten@users.noreply.github.com> Date: Thu, 16 Jul 2026 12:18:26 +0000 Subject: [PATCH 2/6] Use type assertions --- tst/Format2.Tests.ps1 | 2 +- tst/Help.Tests.ps1 | 11 +++++---- tst/Pester.Tests.ps1 | 6 ++--- tst/PesterConfiguration.Tests.ps1 | 4 ++-- tst/functions/Coverage.Tests.ps1 | 16 ++++++------- tst/functions/Describe.Tests.ps1 | 4 ++-- tst/functions/Get-ShouldOperator.Tests.ps1 | 27 +++++++++++----------- tst/functions/GlobalMock-B.Tests.ps1 | 2 +- tst/functions/InModuleScope.Tests.ps1 | 18 +++++++-------- tst/functions/Mock.Global.Tests.ps1 | 2 +- tst/functions/Mock.Tests.ps1 | 14 +++++------ tst/functions/New-Fixture.Tests.ps1 | 2 +- tst/functions/New-MockObject.Tests.ps1 | 4 ++-- tst/functions/Output.Tests.ps1 | 10 ++++---- tst/functions/TestDrive.Tests.ps1 | 4 ++-- tst/functions/TestRegistry.Tests.ps1 | 2 +- tst/functions/TestResults.Tests.ps1 | 6 ++--- 17 files changed, 68 insertions(+), 66 deletions(-) diff --git a/tst/Format2.Tests.ps1 b/tst/Format2.Tests.ps1 index 776af3bfe..7cc04a886 100644 --- a/tst/Format2.Tests.ps1 +++ b/tst/Format2.Tests.ps1 @@ -191,7 +191,7 @@ InPesterModuleScope { } -ArgumentList (Get-Module Pester).Path, $TestDrive $result = $job | Wait-Job -Timeout 10 | Receive-Job $job | Remove-Job -Force - $result | Should -Not -BeNullOrEmpty + $result | Verify-NotNull } # Regression test for https://github.com/pester/Pester/issues/2828 diff --git a/tst/Help.Tests.ps1 b/tst/Help.Tests.ps1 index 69ad473e5..f4092b97e 100644 --- a/tst/Help.Tests.ps1 +++ b/tst/Help.Tests.ps1 @@ -18,18 +18,19 @@ Describe "Testing module help" -Tag 'Help' -ForEach @{ exportedFunctions = $expo } It 'Synopsis is defined' { - $help.Synopsis | Should -Not -BeNullOrEmpty + $help.Synopsis | Should-NotBeEmptyString # Syntax is used as synopsis when none is defined in help. $help.Synopsis | Should-NotMatchString "^\s*$($_.Name)((\s+\[+?-\w+)|$)" } It 'Description is defined' { # Property is missing if undefined - $help.description | Should -Not -BeNullOrEmpty + $help.description | Should-NotBeNull + $help.description.Count | Should-BeGreaterThan 0 } It 'Has link sections' { - $help.psobject.properties.name -match 'relatedLinks' | Should -Not -BeNullOrEmpty -Because 'all exported functions should at least have link to online version as first Uri' + $help.psobject.properties.name -match 'relatedLinks' | Should-NotBeNull -Because 'all exported functions should at least have link to online version as first Uri' $functionName = $_.Name $alias = Get-Alias -Name Should* | Where-Object { $_.Definition -eq $functionName } @@ -40,8 +41,8 @@ Describe "Testing module help" -Tag 'Help' -ForEach @{ exportedFunctions = $expo } It 'Has at least one example' { - $help.Examples | Should -Not -BeNullOrEmpty - $help.Examples.example | Where-Object { -not $_.Code.Trim() } | ForEach-Object { $_.title.Trim('- ') } | Should-BeCollection @() -Because 'no examples should be empty' + $help.Examples | Should-NotBeNull + $help.Examples.example | Where-Object { -not $_.Code.Trim() } | Foreach-Object { $_.title.Trim("- ") } | Should-BeCollection @() -Because 'no examples should be empty' } It 'All static parameters have description' { diff --git a/tst/Pester.Tests.ps1 b/tst/Pester.Tests.ps1 index 79b27c4f2..05992a6d2 100644 --- a/tst/Pester.Tests.ps1 +++ b/tst/Pester.Tests.ps1 @@ -39,8 +39,8 @@ Describe -Tags 'VersionChecks' "Pester manifest and changelog" { $script:tagVersionShort, $script:tagPrerelease = $script:tagVersion -split "-", 2 } - $script:tagVersion | Should -Not -BeNullOrEmpty - $script:tagVersionShort -as [Version] | Should -Not -BeNullOrEmpty + $script:tagVersion | Should-NotBeNull + $script:tagVersionShort -as [Version] | Should-NotBeNull } It "has valid release notes in the manifest" { @@ -139,7 +139,7 @@ Describe 'Public API' { ? { $_.CommandType -ne 'Alias' } | # Get-Command outputs aliases in PowerShell 2 ? { -not $_.CmdletBinding } | % { $_.Name } - $r | Should -beNullOrEmpty + $r | Should-BeCollection @() } } diff --git a/tst/PesterConfiguration.Tests.ps1 b/tst/PesterConfiguration.Tests.ps1 index 6d8f00fd5..8a53b7646 100644 --- a/tst/PesterConfiguration.Tests.ps1 +++ b/tst/PesterConfiguration.Tests.ps1 @@ -12,7 +12,7 @@ Describe "PesterConfiguration.Format.ps1xml" { $options = @($section.GetProperties() | Where-Object { $_.PropertyType.IsSubclassOf([Pester.Option]) }) } It 'Has a single view defined of type ListControl' { - $formatData | Should -Not -BeNullOrEmpty + $formatData | Should-NotBeNull $formatData.FormatViewDefinition.Count | Should-Be 1 $formatData.FormatViewDefinition[0].Name | Should-BeString $section.FullName -CaseSensitive $formatData.FormatViewDefinition[0].Control | Should-HaveType ([System.Management.Automation.ListControl]) @@ -32,7 +32,7 @@ Describe "PesterConfiguration.Format.ps1xml" { $options = [Pester.Option[bool]].GetProperties() | Where-Object Name -notin 'IsModified' } It 'Has a single view defined of type TableControl' { - $formatData | Should -Not -BeNullOrEmpty + $formatData | Should-NotBeNull $formatData.FormatViewDefinition.Count | Should-Be 1 $formatData.FormatViewDefinition[0].Name | Should-BeString 'Pester.Option' -CaseSensitive $formatData.FormatViewDefinition[0].Control | Should-HaveType ([System.Management.Automation.TableControl]) diff --git a/tst/functions/Coverage.Tests.ps1 b/tst/functions/Coverage.Tests.ps1 index d4f782b39..207c7b0d9 100644 --- a/tst/functions/Coverage.Tests.ps1 +++ b/tst/functions/Coverage.Tests.ps1 @@ -252,7 +252,7 @@ InPesterModuleScope { } It 'Reports the correct class names' { - $coverageReport.HitCommands[0].Class | Should -BeNullOrEmpty + $coverageReport.HitCommands[0].Class | Should-BeEmptyString # Classes have been introduced in PowerShell 5.0 if ($PSVersionTable.PSVersion.Major -ge 5) { $coverageReport.HitCommands[9].Class | Should-Be 'MyBaseClass' @@ -260,8 +260,8 @@ InPesterModuleScope { $coverageReport.MissedCommands[2].Class | Should-Be 'MyClass' } else { - $coverageReport.HitCommands[9].Class | Should -BeNullOrEmpty - $coverageReport.MissedCommands[2].Class | Should -BeNullOrEmpty + $coverageReport.HitCommands[9].Class | Should-BeNull + $coverageReport.MissedCommands[2].Class | Should-BeNull } } @@ -599,14 +599,14 @@ InPesterModuleScope { $coverageReport = [PSCustomObject] @{ NumberOfCommandsAnalyzed = 0 } [String]$jaCoCoReportXml = Get-JaCoCoReportXml -CommandCoverage @{} -TotalMilliseconds 10000 -CoverageReport $coverageReport -ReportRoot $TestDrive $jaCoCoReportXml | Should-NotBe $null - $jaCoCoReportXml | Should-Be ([String]::Empty) + $jaCoCoReportXml | Should-BeEmptyString } It 'Cobertura returns empty string when there are 0 analyzed commands' { $coverageReport = [PSCustomObject] @{ NumberOfCommandsAnalyzed = 0 } [String]$coberturaReportXml = Get-CoberturaReportXml -CoverageReport $coverageReport -TotalMilliseconds 10000 -ReportRoot $TestDrive $coberturaReportXml | Should-NotBe $null - $coberturaReportXml | Should-Be ([String]::Empty) + $coberturaReportXml | Should-BeEmptyString } It 'Reports the right line numbers' { @@ -1109,7 +1109,7 @@ InPesterModuleScope { $PesterTests = @($coverageInfo | Select-Object -ExpandProperty Path | Where-Object { $_ -match '\.tests.ps1$' }) - $PesterTests | Should -BeNullOrEmpty + $PesterTests | Should-BeNull } It 'Includes test files when specified in wildcard path' { $coverageInfo = Get-CoverageInfoFromUserInput "$(Join-Path -Path $root -ChildPath *.tests.ps1)" @@ -1131,12 +1131,12 @@ InPesterModuleScope { It 'Excludes test files when IncludeTests is not specified' { $coverageInfo = Get-CoverageInfoFromUserInput @{ Path = "$(Join-Path -Path $root -ChildPath TestScript.tests.ps1)" } $PesterTests = $coverageInfo | Select-Object -ExpandProperty Path - $PesterTests | Should -BeNullOrEmpty + $PesterTests | Should-BeNull } It 'Excludes test files when IncludeTests is false' { $coverageInfo = Get-CoverageInfoFromUserInput @{ Path = "$(Join-Path -Path $root -ChildPath TestScript.tests.ps1)"; IncludeTests = $false } $PesterTests = $coverageInfo | Select-Object -ExpandProperty Path - $PesterTests | Should -BeNullOrEmpty + $PesterTests | Should-BeNull } It 'Includes test files when IncludeTests is true' { $path = Join-Path -Path $root -ChildPath TestScript.tests.ps1 diff --git a/tst/functions/Describe.Tests.ps1 b/tst/functions/Describe.Tests.ps1 index 6eeb2627e..b7e81e9d8 100644 --- a/tst/functions/Describe.Tests.ps1 +++ b/tst/functions/Describe.Tests.ps1 @@ -12,7 +12,7 @@ Describe 'Testing Describe' { $attribute = $parameter.Attributes | Where-Object { $_ -is [System.Management.Automation.ParameterAttribute] } $isMandatory = $null -ne $attribute -and $attribute.Mandatory - $isMandatory | Should-Be $false + $isMandatory | Should-BeFalse { Describe Bogus } | Should-Throw -ExceptionMessage 'No test fixture is provided. (Have you put the open curly brace on the next line?)' } @@ -28,7 +28,7 @@ Describe 'Testing Describe' { $attribute = $parameter.Attributes | Where-Object { $_ -is [System.Management.Automation.ParameterAttribute] } $isMandatory = $null -ne $attribute -and $attribute.Mandatory - $isMandatory | Should-Be $false + $isMandatory | Should-BeFalse { Describe { diff --git a/tst/functions/Get-ShouldOperator.Tests.ps1 b/tst/functions/Get-ShouldOperator.Tests.ps1 index af914eefd..2288055b2 100644 --- a/tst/functions/Get-ShouldOperator.Tests.ps1 +++ b/tst/functions/Get-ShouldOperator.Tests.ps1 @@ -14,15 +14,15 @@ InPesterModuleScope { } It 'Returns all registered operators' { - $get1.Count | Should -Be $OpCount - $get2.Count | Should -Be ($OpCount + 1) + $get1.Count | Should-Be $OpCount + $get2.Count | Should-Be ($OpCount + 1) } It 'Returns Name and Alias properties' { $get1[0].PSObject.Properties | Select-Object -ExpandProperty Name | Sort-Object | - Should -Be 'Alias', 'Name' + Should-ContainCollection @('Alias', 'Name') } AfterAll { @@ -36,24 +36,25 @@ InPesterModuleScope { } It 'Should return a PesterAssertionOperatorHelp-object' { - $BGT.Name | Should -BeExactly 'BeGreaterThan' - $BGT.Aliases | Should -BeExactly @('GT') - # BeOfType doesn't currently work with PSCustomObject typenames - $BGT.PSTypeNames[0] | Should -BeExactly 'PesterAssertionOperatorHelp' - $BGT.Help.PSTypeNames[0] | Should -BeExactly 'MamlCommandHelpInfo#ExamplesView' - $BGT.Help.syntax.syntaxItem[0].name | Should -Be 'Should -BeGreaterThan' - $BGT.Help.syntax.syntaxItem[0].DisplayParameterSet | Should -BeOfType ([string]) - $BGT.Help.syntax.syntaxItem[0].DisplayParameterSet | Should -BeLike '*-ActualValue*' + $BGT.Name | Should-BeString 'BeGreaterThan' -CaseSensitive + $BGT.Aliases | Should-BeCollection @('GT') + $BGT.Aliases[0] | Should-BeString 'GT' -CaseSensitive + # Should-HaveType doesn't currently work with PSCustomObject typenames + $BGT.PSTypeNames[0] | Should-BeString 'PesterAssertionOperatorHelp' -CaseSensitive + $BGT.Help.PSTypeNames[0] | Should-BeString 'MamlCommandHelpInfo#ExamplesView' -CaseSensitive + $BGT.Help.syntax.syntaxItem[0].Name | Should-BeString 'Should -BeGreaterThan' -CaseSensitive + $BGT.Help.syntax.syntaxItem[0].DisplayParameterSet | Should-HaveType ([string]) + $BGT.Help.syntax.syntaxItem[0].DisplayParameterSet | Should-BeLikeString '*-ActualValue*' } It 'Returns help for all internal Pester assertion operators' { $AssertionOperators.Keys | ForEach-Object { - Get-ShouldOperator -Name $_ | Should -Not -BeNullOrEmpty -Because "$_ should have help" + Get-ShouldOperator -Name $_ | Should-NotBeNull -Because "$_ should have help" } } It 'Throws on invalid assertion-name' { - { Get-ShouldOperator BeHorrible } | Should -Throw -ExceptionType ([System.Management.Automation.ParameterBindingException]) -ErrorId 'ParameterArgumentValidationError,Get-ShouldOperator' -ExpectedMessage "*on parameter 'Name'*does not belong to the set*" + { Get-ShouldOperator BeHorrible } | Should-Throw -FullyQualifiedErrorId 'ParameterArgumentValidationError,Get-ShouldOperator' -ExceptionMessage "*on parameter 'Name'*does not belong to the set*" } It 'Supports positional value' { diff --git a/tst/functions/GlobalMock-B.Tests.ps1 b/tst/functions/GlobalMock-B.Tests.ps1 index 659bb1780..ae53c25dd 100644 --- a/tst/functions/GlobalMock-B.Tests.ps1 +++ b/tst/functions/GlobalMock-B.Tests.ps1 @@ -8,7 +8,7 @@ Describe 'Mocking Global Functions - Part Two' { It 'Restored the global function properly' { $functionName = '01c1a57716fe4005ac1a7bf216f38ad0' $globalFunctionExists = Test-Path Function:\global:$functionName - $globalFunctionExists | Should-Be $true + $globalFunctionExists | Should-BeTrue & $functionName | Should-Be 'Original Function' } diff --git a/tst/functions/InModuleScope.Tests.ps1 b/tst/functions/InModuleScope.Tests.ps1 index 0de0536bd..70ef3b4c2 100644 --- a/tst/functions/InModuleScope.Tests.ps1 +++ b/tst/functions/InModuleScope.Tests.ps1 @@ -16,7 +16,7 @@ Describe "Module scope separation" { # TODO: : come up with a better way of verifying that only the desired commands from the Pester # module are visible to the SUT. - (Get-Item function:\ConvertTo-PesterResult -ErrorAction SilentlyContinue) | Should-Be $null + (Get-Item function:\ConvertTo-PesterResult -ErrorAction SilentlyContinue) | Should-BeNull } } @@ -72,7 +72,7 @@ Describe 'Get-CompatibleModule' { Context 'when module name matches imported script module' { It 'should return a single ModuleInfo object' { $moduleInfo = InPesterModuleScope { Get-CompatibleModule -ModuleName Pester } - $moduleInfo | Should -Not -BeNullOrEmpty + $moduleInfo | Should-NotBeNull @($moduleInfo).Count | Should-Be 1 $moduleInfo.Name | Should-Be 'Pester' $moduleInfo.ModuleType | Should-Be 'Script' @@ -94,7 +94,7 @@ Describe 'Get-CompatibleModule' { It 'should return a single ModuleInfo object' { $moduleInfo = InPesterModuleScope { Get-CompatibleModule -ModuleName testManifestModule } - $moduleInfo | Should -Not -BeNullOrEmpty + $moduleInfo | Should-NotBeNull @($moduleInfo).Count | Should-Be 1 $moduleInfo.Name | Should-Be 'testManifestModule' $moduleInfo.ModuleType | Should-Be 'Manifest' @@ -142,7 +142,7 @@ Describe 'Get-CompatibleModule' { It 'should return the nested module via forward-slash delimiter' { $moduleInfo = InPesterModuleScope { Get-CompatibleModule -ModuleName 'RootWithNestedModule/NestedModule' } - $moduleInfo | Should -Not -BeNullOrEmpty + $moduleInfo | Should-NotBeNull @($moduleInfo).Count | Should-Be 1 $moduleInfo.Name | Should-Be 'NestedModule' $moduleInfo.ModuleType | Should-Be 'Script' @@ -150,7 +150,7 @@ Describe 'Get-CompatibleModule' { It 'should return the nested module via backslash delimiter' { $moduleInfo = InPesterModuleScope { Get-CompatibleModule -ModuleName 'RootWithNestedModule\NestedModule' } - $moduleInfo | Should -Not -BeNullOrEmpty + $moduleInfo | Should-NotBeNull @($moduleInfo).Count | Should-Be 1 $moduleInfo.Name | Should-Be 'NestedModule' $moduleInfo.ModuleType | Should-Be 'Script' @@ -203,14 +203,14 @@ Describe 'Get-CompatibleModule' { It 'should resolve the leaf module via forward-slash deep path' { $moduleInfo = InPesterModuleScope { Get-CompatibleModule -ModuleName 'DeepRootModule/DeepMidModule/DeepLeafModule' } - $moduleInfo | Should -Not -BeNullOrEmpty + $moduleInfo | Should-NotBeNull $moduleInfo.Name | Should-Be 'DeepLeafModule' $moduleInfo.ModuleType | Should-Be 'Script' } It 'should resolve the leaf module via mixed slash and backslash deep path' { $moduleInfo = InPesterModuleScope { Get-CompatibleModule -ModuleName 'DeepRootModule\DeepMidModule/DeepLeafModule' } - $moduleInfo | Should -Not -BeNullOrEmpty + $moduleInfo | Should-NotBeNull $moduleInfo.Name | Should-Be 'DeepLeafModule' $moduleInfo.ModuleType | Should-Be 'Script' } @@ -425,7 +425,7 @@ Describe 'InModuleScope arguments and parameter binding' { } InModuleScope -ModuleName TestModule2 -ScriptBlock $sb -Parameters $inModuleScopeParameters | Should-Be $inModuleScopeParameters.SomeParam2 - InModuleScope -ModuleName TestModule2 -ScriptBlock $sb2 | Should -BeNullOrEmpty + InModuleScope -ModuleName TestModule2 -ScriptBlock $sb2 | Should-BeEmptyString } AfterAll { @@ -447,7 +447,7 @@ Describe "Using variables within module scope" { InModuleScope -ModuleName TestModule2 -ScriptBlock $setup InModuleScope -ModuleName TestModule2 -ScriptBlock { $script:myVar } | Should-Be 'bar' - InModuleScope -ModuleName TestModule2 -ScriptBlock { $myVar2 } | Should -BeNullOrEmpty + InModuleScope -ModuleName TestModule2 -ScriptBlock { $myVar2 } | Should-BeNull } AfterAll { diff --git a/tst/functions/Mock.Global.Tests.ps1 b/tst/functions/Mock.Global.Tests.ps1 index 4478d213a..e53bd2eea 100644 --- a/tst/functions/Mock.Global.Tests.ps1 +++ b/tst/functions/Mock.Global.Tests.ps1 @@ -215,7 +215,7 @@ Describe 'Global mock hook lifecycle' { # be observed at the top level (a nested run snapshots/restores instead), so we use a child process: # arm the hook by hand, run a trivial top-level Pester run, and confirm the hook was cleared. $modulePath = (Get-Module -Name Pester | Select-Object -First 1).Path - $modulePath | Should -Not -BeNullOrEmpty + $modulePath | Should-NotBeEmptyString $childScript = { Import-Module $env:PESTER_MODULE_PATH_FOR_TEST -Force diff --git a/tst/functions/Mock.Tests.ps1 b/tst/functions/Mock.Tests.ps1 index cf4f144b1..95bf70579 100644 --- a/tst/functions/Mock.Tests.ps1 +++ b/tst/functions/Mock.Tests.ps1 @@ -325,7 +325,7 @@ Describe 'When calling Mock, StrictMode is enabled, and variables are used in th } It 'Does not throw an error when testing the parameter filter' { - $result | Should-Be $null + $result | Should-BeNull } It 'Calls the mock properly' { @@ -2051,7 +2051,7 @@ Describe 'Mocking New-Object' { Mock New-Object $result = New-Object -TypeName Object - $result | Should-Be $null + $result | Should-BeNull Should -Invoke New-Object } } @@ -2069,7 +2069,7 @@ Describe 'Mocking module-qualified calls' { } It 'Mock alias should not exist before the mock is defined' { - $alias | Should-Be $null + $alias | Should-BeNull } It 'Creates the alias while the mock is in effect' { @@ -2086,7 +2086,7 @@ Describe 'Mocking module-qualified calls' { Describe 'After a mock goes out of scope' { It 'Removes the alias after the mock goes out of scope' { $alias = Get-Alias -Name 'Microsoft.PowerShell.Management\Get-Content' -ErrorAction SilentlyContinue - $alias | Should-Be $null + $alias | Should-BeNull } } @@ -2662,7 +2662,7 @@ Describe "Mock definition output" { function a () {} $output = Mock a { } - $output | Should-Be $null + $output | Should-BeNull } } @@ -2994,7 +2994,7 @@ Describe "Running Mock with ModuleName in test scope" { } $actual = f $actual | Should-HaveType ([Management.Automation.SessionState]) - $actual.Module | Should-Be $null -Because "we are not running inside of the 'test' module" + $actual.Module | Should-BeNull -Because "we are not running inside of the 'test' module" } It "runs the parameter filter in the current scope" { @@ -3003,7 +3003,7 @@ Describe "Running Mock with ModuleName in test scope" { $null = f $script:ss | Should-HaveType ([Management.Automation.SessionState]) - $script:ss.Module | Should-Be $null -Because "we are not running inside of the 'test' module" + $script:ss.Module | Should-BeNull -Because "we are not running inside of the 'test' module" } } diff --git a/tst/functions/New-Fixture.Tests.ps1 b/tst/functions/New-Fixture.Tests.ps1 index 832f7d19f..0bb451163 100644 --- a/tst/functions/New-Fixture.Tests.ps1 +++ b/tst/functions/New-Fixture.Tests.ps1 @@ -2,7 +2,7 @@ Describe "New-Fixture" { It "Name parameter is mandatory" { - (Get-Command New-Fixture).Parameters.Name.ParameterSets.__AllParameterSets.IsMandatory | Should-Be $true + (Get-Command New-Fixture).Parameters.Name.ParameterSets.__AllParameterSets.IsMandatory | Should-BeTrue } Context "Only Name parameter is specified" { diff --git a/tst/functions/New-MockObject.Tests.ps1 b/tst/functions/New-MockObject.Tests.ps1 index 578f5ce78..e0306dcb2 100644 --- a/tst/functions/New-MockObject.Tests.ps1 +++ b/tst/functions/New-MockObject.Tests.ps1 @@ -77,10 +77,10 @@ Describe 'New-MockObject' { $mockObject | Should-Be $o $mockObject.Kill() | Should-Be "killed" $mockObject._Kill[-1].Call | Should-Be 1 - $mockObject._Kill[-1].Arguments | Should-Be $null + $mockObject._Kill[-1].Arguments | Should-BeNull $mockObject.Kill($true) | Should-Be "killed" $mockObject._Kill[-1].Call | Should-Be 2 - $mockObject._Kill[-1].Arguments | Should-Be $true + $mockObject._Kill[-1].Arguments | Should-BeTrue } It "Adds 2 methods to the object" { diff --git a/tst/functions/Output.Tests.ps1 b/tst/functions/Output.Tests.ps1 index f718ffb6d..15d732c9e 100644 --- a/tst/functions/Output.Tests.ps1 +++ b/tst/functions/Output.Tests.ps1 @@ -166,7 +166,7 @@ InModuleScope -ModuleName Pester -ScriptBlock { It 'failed should produces correct message lines.' { try { - 'One' | Should -Be 'Two' -ErrorAction Stop + 'One' | Should-BeString 'Two' -ErrorAction Stop } catch { $e = $_ @@ -179,10 +179,10 @@ InModuleScope -ModuleName Pester -ScriptBlock { $r.message[2] | Should-Be 'Strings differ at index 0.' $r.Message[3] | Should-Be "Expected: 'Two'" $r.Message[4] | Should-Be "But was: 'One'" - $r.Message[5] | Should-Be ' ^' + $r.Message[5] | Should-Be ' ^' $r.Message.Count | Should-Be 6 - $r.Trace[0] | Should-MatchString "'One' | Should -be 'Two'" + $r.Trace[0] | Should-MatchString "'One' | Should-BeString 'Two'" $r.Trace.Count | Should-Be 1 } # TODO: should fails with a very weird error, probably has something to do with dynamic params... @@ -684,9 +684,9 @@ Describe 'Write-PesterHostMessage' { } It 'Parameter <_.Name> is equal' -TestCases $WriteHostParam { $param = $_ - $param.Name | Should -BeIn $WritePesterHostMessageParam.Keys + $WritePesterHostMessageParam.Keys | Should-ContainCollection $param.Name $WritePesterHostMessageParam[$param.Name].ParameterType | Should-Be $param.ParameterType - if ($param.Aliases) { $param.Aliases | Should -BeIn $WritePesterHostMessageParam[$param.Name].Aliases } + if ($param.Aliases) { $WritePesterHostMessageParam[$param.Name].Aliases | Sort-Object | Should-ContainCollection ($param.Aliases | Sort-Object) } } } } diff --git a/tst/functions/TestDrive.Tests.ps1 b/tst/functions/TestDrive.Tests.ps1 index fd271cefe..25fedefbc 100644 --- a/tst/functions/TestDrive.Tests.ps1 +++ b/tst/functions/TestDrive.Tests.ps1 @@ -203,7 +203,7 @@ Describe 'Repair missing TestDrive' { # Remove variable Set-Variable -Name TestDrive -Scope Global -Value $null - $TestDrive | Should -BeNullOrEmpty + $TestDrive | Should-BeNull } } @@ -245,7 +245,7 @@ Describe 'Running Pester in Pester' { $TestDrive | Should-NotBe $outerTestDrive # TestDrive should be clean in inner run - Get-ChildItem -Path 'TestDrive:/' | Should -BeNullOrEmpty + Get-ChildItem -Path 'TestDrive:/' | Should-BeNull } } } diff --git a/tst/functions/TestRegistry.Tests.ps1 b/tst/functions/TestRegistry.Tests.ps1 index b7eb5b518..99d7b57d7 100644 --- a/tst/functions/TestRegistry.Tests.ps1 +++ b/tst/functions/TestRegistry.Tests.ps1 @@ -98,7 +98,7 @@ Describe 'Running Pester in Invoke-Pester' { } It 'TestRegistry PSDrive points to clean location' { - (Get-Item -Path 'TestRegistry:/').Property | Should -BeNullOrEmpty + (Get-Item -Path 'TestRegistry:/').Property | Should-BeNull } } } diff --git a/tst/functions/TestResults.Tests.ps1 b/tst/functions/TestResults.Tests.ps1 index 07d2ff607..28677ac61 100644 --- a/tst/functions/TestResults.Tests.ps1 +++ b/tst/functions/TestResults.Tests.ps1 @@ -83,7 +83,7 @@ InPesterModuleScope { It "Resolves full path correctly" { $powershellPath = Get-Command -Name $CommandToTest | Select-Object -ExpandProperty 'Definition' - $powershellPath | Should -Not -BeNullOrEmpty + $powershellPath | Should-NotBeEmptyString GetFullPath $powershellPath | Should-Be $powershellPath } @@ -106,8 +106,8 @@ InPesterModuleScope { $result.Keys | Should-ContainCollection 'user' $result.Keys | Should-ContainCollection 'cwd' $result.Keys | Should-ContainCollection 'clr-version' - $result['os-version'] | Should -Not -BeNullOrEmpty - $result['platform'] | Should -Not -BeNullOrEmpty + $result['os-version'] | Should-NotBeEmptyString + $result['platform'] | Should-NotBeEmptyString } It "Falls back to Unknown OS info when Get-CimInstance returns null (access denied)" -Skip:(-not $IsWindows) { From 152ae519fa8ed0dda5e6a61fa96a1b3bfa728d19 Mon Sep 17 00:00:00 2001 From: Frode Flaten <3436158+fflaten@users.noreply.github.com> Date: Thu, 16 Jul 2026 14:27:33 +0000 Subject: [PATCH 3/6] Convert Should-Be to Should-BeString --- tst/Help.Tests.ps1 | 6 +- tst/Pester.Tests.ps1 | 6 +- tst/functions/Coverage.Tests.ps1 | 52 +++--- tst/functions/Environment.Tests.ps1 | 12 +- tst/functions/GlobalMock-A.Tests.ps1 | 2 +- tst/functions/GlobalMock-B.Tests.ps1 | 2 +- tst/functions/InModuleScope.Tests.ps1 | 34 ++-- tst/functions/Mock.Global.Tests.ps1 | 10 +- tst/functions/Mock.Tests.ps1 | 230 ++++++++++++------------- tst/functions/New-MockObject.Tests.ps1 | 18 +- tst/functions/Output.Tests.ps1 | 70 ++++---- tst/functions/Set-ItResult.Tests.ps1 | 8 +- tst/functions/SetupTeardown.Tests.ps1 | 22 +-- tst/functions/TestDrive.Tests.ps1 | 14 +- tst/functions/TestRegistry.Tests.ps1 | 2 +- tst/functions/TestResults.Tests.ps1 | 8 +- 16 files changed, 248 insertions(+), 248 deletions(-) diff --git a/tst/Help.Tests.ps1 b/tst/Help.Tests.ps1 index f4092b97e..5c9044241 100644 --- a/tst/Help.Tests.ps1 +++ b/tst/Help.Tests.ps1 @@ -12,9 +12,9 @@ Describe "Testing module help" -Tag 'Help' -ForEach @{ exportedFunctions = $expo } It 'Help is found' { - $help.Name | Should-Be $_.Name + $help.Name | Should-BeString $_.Name $help.Category | Should-Be $_.CommandType - $help.ModuleName | Should-Be $moduleName + $help.ModuleName | Should-BeString $moduleName } It 'Synopsis is defined' { @@ -37,7 +37,7 @@ Describe "Testing module help" -Tag 'Help' -ForEach @{ exportedFunctions = $expo $helpName = if ($alias) { $alias.Name } else { $help.Name } $firstUri = $help.relatedLinks.navigationLink | Where-Object uri | Select-Object -First 1 -ExpandProperty uri - $firstUri | Should-Be "https://pester.dev/docs/commands/$helpName" -Because 'first uri-link should be to online version of this help topic' + $firstUri | Should-BeString "https://pester.dev/docs/commands/$helpName" -Because 'first uri-link should be to online version of this help topic' } It 'Has at least one example' { diff --git a/tst/Pester.Tests.ps1 b/tst/Pester.Tests.ps1 index 05992a6d2..1490a84b8 100644 --- a/tst/Pester.Tests.ps1 +++ b/tst/Pester.Tests.ps1 @@ -26,7 +26,7 @@ Describe -Tags 'VersionChecks' "Pester manifest and changelog" { } It "has a valid guid in the manifest" { - $script:manifest.Guid | Should-Be 'a699dea5-2c73-4616-a270-1f7abb777e71' + $script:manifest.Guid | Should-BeString 'a699dea5-2c73-4616-a270-1f7abb777e71' } if ((Get-Command -Name git -ErrorAction SilentlyContinue) -and (Get-Item ".git" -ErrorAction Ignore)) { @@ -44,7 +44,7 @@ Describe -Tags 'VersionChecks' "Pester manifest and changelog" { } It "has valid release notes in the manifest" { - $script:manifest.PrivateData.PSData.ReleaseNotes | Should-Be "https://github.com/pester/Pester/releases/tag/$script:tagVersion" + $script:manifest.PrivateData.PSData.ReleaseNotes | Should-BeString "https://github.com/pester/Pester/releases/tag/$script:tagVersion" } It "tag and changelog versions are the same" { @@ -238,7 +238,7 @@ InPesterModuleScope { It 'Resolves non-wildcarded file paths regardless of whether the file ends with Tests.ps1' { $result = @(Find-File 'TestDrive:\SomeOtherFile.ps1' -Extension ".Tests.ps1") $result.Count | Should-Be 1 - $result[0].UnresolvedPath | Should-Be 'TestDrive:\SomeOtherFile.ps1' + $result[0].UnresolvedPath | Should-BeString 'TestDrive:\SomeOtherFile.ps1' } It 'Finds only *.Tests.ps1 files when the path contains wildcards' { diff --git a/tst/functions/Coverage.Tests.ps1 b/tst/functions/Coverage.Tests.ps1 index 207c7b0d9..1449c2868 100644 --- a/tst/functions/Coverage.Tests.ps1 +++ b/tst/functions/Coverage.Tests.ps1 @@ -235,12 +235,12 @@ InPesterModuleScope { } It 'Reports the correct missed command' { - $coverageReport.MissedCommands[0].Command | Should-Be "'I cannot get called.'" - $coverageReport.MissedCommands[1].Command | Should-Be "'I am function two. I never get called.'" - $coverageReport.MissedCommands[2].Command | Should-Be "'I am method two. I never get called.'" - $coverageReport.MissedCommands[3].Command | Should-Be "'I was skipped because 2 called break in switch.'" - $coverageReport.MissedCommands[4].Command | Should-Be "'I was skipped by a labeled break.'" - $coverageReport.MissedCommands[5].Command | Should-Be "'I was skipped by a labeled contiune.'" + $coverageReport.MissedCommands[0].Command | Should-BeString "'I cannot get called.'" + $coverageReport.MissedCommands[1].Command | Should-BeString "'I am function two. I never get called.'" + $coverageReport.MissedCommands[2].Command | Should-BeString "'I am method two. I never get called.'" + $coverageReport.MissedCommands[3].Command | Should-BeString "'I was skipped because 2 called break in switch.'" + $coverageReport.MissedCommands[4].Command | Should-BeString "'I was skipped by a labeled break.'" + $coverageReport.MissedCommands[5].Command | Should-BeString "'I was skipped by a labeled contiune.'" } It 'Reports the proper number of hit commands' { @@ -248,16 +248,16 @@ InPesterModuleScope { } It 'Reports the correct hit command' { - $coverageReport.HitCommands[0].Command | Should-Be "'I am the nested function.'" + $coverageReport.HitCommands[0].Command | Should-BeString "'I am the nested function.'" } It 'Reports the correct class names' { $coverageReport.HitCommands[0].Class | Should-BeEmptyString # Classes have been introduced in PowerShell 5.0 if ($PSVersionTable.PSVersion.Major -ge 5) { - $coverageReport.HitCommands[9].Class | Should-Be 'MyBaseClass' - $coverageReport.HitCommands[10].Class | Should-Be 'MyClass' - $coverageReport.MissedCommands[2].Class | Should-Be 'MyClass' + $coverageReport.HitCommands[9].Class | Should-BeString 'MyBaseClass' + $coverageReport.HitCommands[10].Class | Should-BeString 'MyClass' + $coverageReport.MissedCommands[2].Class | Should-BeString 'MyClass' } else { $coverageReport.HitCommands[9].Class | Should-BeNull @@ -266,11 +266,11 @@ InPesterModuleScope { } It 'Reports the correct function names' { - $coverageReport.HitCommands[0].Function | Should-Be 'NestedFunction' - $coverageReport.HitCommands[2].Function | Should-Be 'FunctionOne' - $coverageReport.HitCommands[9].Function | Should-Be 'MyBaseClass' - $coverageReport.HitCommands[10].Function | Should-Be 'MyClass' - $coverageReport.MissedCommands[2].Function | Should-Be 'MethodTwo' + $coverageReport.HitCommands[0].Function | Should-BeString 'NestedFunction' + $coverageReport.HitCommands[2].Function | Should-BeString 'FunctionOne' + $coverageReport.HitCommands[9].Function | Should-BeString 'MyBaseClass' + $coverageReport.HitCommands[10].Function | Should-BeString 'MyClass' + $coverageReport.MissedCommands[2].Function | Should-BeString 'MethodTwo' } It 'JaCoCo report must be correct' { @@ -660,7 +660,7 @@ InPesterModuleScope { } It 'Reports the correct missed command' { - $coverageReport.MissedCommands[0].Command | Should-Be "'I am function two. I never get called.'" + $coverageReport.MissedCommands[0].Command | Should-BeString "'I am function two. I never get called.'" } It 'Reports the proper number of hit commands' { @@ -713,7 +713,7 @@ InPesterModuleScope { } It 'Reports the correct hit command' { - $coverageReport.HitCommands[0].Command | Should-Be "'I am the nested function.'" + $coverageReport.HitCommands[0].Command | Should-BeString "'I am the nested function.'" } AfterAll { @@ -762,7 +762,7 @@ InPesterModuleScope { } It 'Reports the correct hit command' { - $coverageReport.HitCommands[0].Command | Should-Be "'I am functionOne'" + $coverageReport.HitCommands[0].Command | Should-BeString "'I am functionOne'" } AfterAll { @@ -810,8 +810,8 @@ InPesterModuleScope { } It 'Reports the correct missed command' { - $coverageReport.MissedCommands[0].Command | Should-Be "'I cannot get called.'" - $coverageReport.MissedCommands[1].Command | Should-Be "'I am function two. I never get called.'" + $coverageReport.MissedCommands[0].Command | Should-BeString "'I cannot get called.'" + $coverageReport.MissedCommands[1].Command | Should-BeString "'I am function two. I never get called.'" } It 'Reports the proper number of hit commands' { @@ -819,7 +819,7 @@ InPesterModuleScope { } It 'Reports the correct hit command' { - $coverageReport.HitCommands[0].Command | Should-Be "'I am the nested function.'" + $coverageReport.HitCommands[0].Command | Should-BeString "'I am the nested function.'" } AfterAll { @@ -1050,7 +1050,7 @@ InPesterModuleScope { $breakpoints = Enter-CoverageAnalysis -CodeCoverage @{ Path = $proxyScriptPath; Function = 'Test-Proxy' } -UseBreakpoints $UseBreakpoints - @($breakpoints).Count | Should -Be 5 -Because 'the & $wrappedCmd call and the scriptblock literal wrapping it are ignored' + @($breakpoints).Count | Should-Be 5 -Because 'the & $wrappedCmd call and the scriptblock literal wrapping it are ignored' if ($UseBreakpoints) { & $proxyScriptPath | Out-Null @@ -1065,11 +1065,11 @@ InPesterModuleScope { } It 'Reports no missed commands for the steppable-pipeline proxy' { - $coverageReport.MissedCommands.Count | Should -Be 0 + $coverageReport.MissedCommands.Count | Should-Be 0 } It 'Reports every analyzed command as executed' { - $coverageReport.NumberOfCommandsExecuted | Should -Be $coverageReport.NumberOfCommandsAnalyzed + $coverageReport.NumberOfCommandsExecuted | Should-Be $coverageReport.NumberOfCommandsAnalyzed } AfterAll { @@ -1124,7 +1124,7 @@ InPesterModuleScope { $path = Join-Path -Path $root -ChildPath TestScript.tests.ps1 $coverageInfo = Get-CoverageInfoFromUserInput $path $PesterTests = $coverageInfo | Select-Object -ExpandProperty Path - $PesterTests | Should-Be $path + $PesterTests | Should-BeString $path } } Context 'Using object-input' { @@ -1142,7 +1142,7 @@ InPesterModuleScope { $path = Join-Path -Path $root -ChildPath TestScript.tests.ps1 $coverageInfo = Get-CoverageInfoFromUserInput @{ Path = $path; IncludeTests = $true } $PesterTests = $coverageInfo | Select-Object -ExpandProperty Path - $PesterTests | Should-Be $path + $PesterTests | Should-BeString $path } It 'Includes test files when IncludeTests is true and using wildcard path' { $coverageInfo = Get-CoverageInfoFromUserInput @{ Path = "$(Join-Path -Path $root -ChildPath *)"; IncludeTests = $true } diff --git a/tst/functions/Environment.Tests.ps1 b/tst/functions/Environment.Tests.ps1 index 1f5aee191..0485aa186 100644 --- a/tst/functions/Environment.Tests.ps1 +++ b/tst/functions/Environment.Tests.ps1 @@ -53,25 +53,25 @@ InModuleScope -ModuleName Pester { # Pester 6 supports Windows PowerShell 5.1 and PowerShell 7+. PowerShell 6 is # EOL and is treated as Windows-only, so any version below 7 reports 'Windows'. Invoke-WithFakedEnvironment -Version 5 -Test { - GetPesterOs | Should-Be 'Windows' + GetPesterOs | Should-BeString 'Windows' } } It "Returns 'Windows' when `$IsWindows is `$true on PowerShell 7+" { Invoke-WithFakedEnvironment -Version 7 -Variable @{ IsWindows = $true } -Test { - GetPesterOs | Should-Be 'Windows' + GetPesterOs | Should-BeString 'Windows' } } It "Returns 'macOS' when `$IsMacOS is `$true on PowerShell 7+" { Invoke-WithFakedEnvironment -Version 7 -Variable @{ IsMacOS = $true } -Test { - GetPesterOs | Should-Be 'macOS' + GetPesterOs | Should-BeString 'macOS' } } It "Returns 'Linux' when `$IsLinux is `$true on PowerShell 7+" { Invoke-WithFakedEnvironment -Version 7 -Variable @{ IsLinux = $true } -Test { - GetPesterOs | Should-Be 'Linux' + GetPesterOs | Should-BeString 'Linux' } } @@ -85,7 +85,7 @@ InModuleScope -ModuleName Pester { Describe 'Get-TempDirectory' { It "Returns '/private/tmp' on macOS" { Mock GetPesterOs { 'macOS' } - Get-TempDirectory | Should-Be '/private/tmp' + Get-TempDirectory | Should-BeString '/private/tmp' } It 'Returns the system temp path on Windows' { @@ -102,7 +102,7 @@ InModuleScope -ModuleName Pester { Describe 'Get-TempRegistry' -Skip:((GetPesterOs) -ne 'Windows') { # Get-TempRegistry uses the Windows registry provider, which only exists on Windows. It 'Returns the Pester registry root path' { - Get-TempRegistry | Should-Be 'Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\Software\Pester' + Get-TempRegistry | Should-BeString 'Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\Software\Pester' } } } diff --git a/tst/functions/GlobalMock-A.Tests.ps1 b/tst/functions/GlobalMock-A.Tests.ps1 index cbdad7adb..140fd192a 100644 --- a/tst/functions/GlobalMock-A.Tests.ps1 +++ b/tst/functions/GlobalMock-A.Tests.ps1 @@ -27,6 +27,6 @@ Describe 'Mocking Global Functions - Part One' { } It 'Mocks the global function' { - & $functionName | Should-Be 'Mocked' + & $functionName | Should-BeString 'Mocked' } } diff --git a/tst/functions/GlobalMock-B.Tests.ps1 b/tst/functions/GlobalMock-B.Tests.ps1 index ae53c25dd..3c121e413 100644 --- a/tst/functions/GlobalMock-B.Tests.ps1 +++ b/tst/functions/GlobalMock-B.Tests.ps1 @@ -9,7 +9,7 @@ Describe 'Mocking Global Functions - Part Two' { $functionName = '01c1a57716fe4005ac1a7bf216f38ad0' $globalFunctionExists = Test-Path Function:\global:$functionName $globalFunctionExists | Should-BeTrue - & $functionName | Should-Be 'Original Function' + & $functionName | Should-BeString 'Original Function' } AfterAll { diff --git a/tst/functions/InModuleScope.Tests.ps1 b/tst/functions/InModuleScope.Tests.ps1 index 70ef3b4c2..6577cdc86 100644 --- a/tst/functions/InModuleScope.Tests.ps1 +++ b/tst/functions/InModuleScope.Tests.ps1 @@ -7,7 +7,7 @@ Describe "Module scope separation" { } It "does not hide user variables" { - $test | Should-Be 'This is a test.' + $test | Should-BeString 'This is a test.' } } @@ -40,12 +40,12 @@ Describe "Executing test code inside a module" { InModuleScope TestModule { It "Can call module internal functions using InModuleScope" { - InternalFunction | Should-Be 'I am the internal function' + InternalFunction | Should-BeString 'I am the internal function' } It "Can mock functions inside the module without using Mock -ModuleName" { Mock InternalFunction { 'I am the mock function.' } - InternalFunction | Should-Be 'I am the mock function.' + InternalFunction | Should-BeString 'I am the mock function.' } } @@ -74,7 +74,7 @@ Describe 'Get-CompatibleModule' { $moduleInfo = InPesterModuleScope { Get-CompatibleModule -ModuleName Pester } $moduleInfo | Should-NotBeNull @($moduleInfo).Count | Should-Be 1 - $moduleInfo.Name | Should-Be 'Pester' + $moduleInfo.Name | Should-BeString 'Pester' $moduleInfo.ModuleType | Should-Be 'Script' } } @@ -96,7 +96,7 @@ Describe 'Get-CompatibleModule' { $moduleInfo = InPesterModuleScope { Get-CompatibleModule -ModuleName testManifestModule } $moduleInfo | Should-NotBeNull @($moduleInfo).Count | Should-Be 1 - $moduleInfo.Name | Should-Be 'testManifestModule' + $moduleInfo.Name | Should-BeString 'testManifestModule' $moduleInfo.ModuleType | Should-Be 'Manifest' } } @@ -144,7 +144,7 @@ Describe 'Get-CompatibleModule' { $moduleInfo = InPesterModuleScope { Get-CompatibleModule -ModuleName 'RootWithNestedModule/NestedModule' } $moduleInfo | Should-NotBeNull @($moduleInfo).Count | Should-Be 1 - $moduleInfo.Name | Should-Be 'NestedModule' + $moduleInfo.Name | Should-BeString 'NestedModule' $moduleInfo.ModuleType | Should-Be 'Script' } @@ -152,7 +152,7 @@ Describe 'Get-CompatibleModule' { $moduleInfo = InPesterModuleScope { Get-CompatibleModule -ModuleName 'RootWithNestedModule\NestedModule' } $moduleInfo | Should-NotBeNull @($moduleInfo).Count | Should-Be 1 - $moduleInfo.Name | Should-Be 'NestedModule' + $moduleInfo.Name | Should-BeString 'NestedModule' $moduleInfo.ModuleType | Should-Be 'Script' } @@ -160,12 +160,12 @@ Describe 'Get-CompatibleModule' { $name = InModuleScope -ModuleName 'RootWithNestedModule/NestedModule' -ScriptBlock { $ExecutionContext.SessionState.Module.Name } - $name | Should-Be 'NestedModule' + $name | Should-BeString 'NestedModule' } It 'should read a variable defined in the nested module' { InModuleScope -ModuleName 'RootWithNestedModule/NestedModule' -ScriptBlock { - $Script:NestedVar | Should-Be 'NestedValue' + $Script:NestedVar | Should-BeString 'NestedValue' } } @@ -204,14 +204,14 @@ Describe 'Get-CompatibleModule' { It 'should resolve the leaf module via forward-slash deep path' { $moduleInfo = InPesterModuleScope { Get-CompatibleModule -ModuleName 'DeepRootModule/DeepMidModule/DeepLeafModule' } $moduleInfo | Should-NotBeNull - $moduleInfo.Name | Should-Be 'DeepLeafModule' + $moduleInfo.Name | Should-BeString 'DeepLeafModule' $moduleInfo.ModuleType | Should-Be 'Script' } It 'should resolve the leaf module via mixed slash and backslash deep path' { $moduleInfo = InPesterModuleScope { Get-CompatibleModule -ModuleName 'DeepRootModule\DeepMidModule/DeepLeafModule' } $moduleInfo | Should-NotBeNull - $moduleInfo.Name | Should-Be 'DeepLeafModule' + $moduleInfo.Name | Should-BeString 'DeepLeafModule' $moduleInfo.ModuleType | Should-Be 'Script' } @@ -219,12 +219,12 @@ Describe 'Get-CompatibleModule' { $name = InModuleScope -ModuleName 'DeepRootModule/DeepMidModule/DeepLeafModule' -ScriptBlock { $ExecutionContext.SessionState.Module.Name } - $name | Should-Be 'DeepLeafModule' + $name | Should-BeString 'DeepLeafModule' } It 'should read a variable defined in the deeply nested module' { InModuleScope -ModuleName 'DeepRootModule/DeepMidModule/DeepLeafModule' -ScriptBlock { - $Script:DeepNestedVar | Should-Be 'DeepNestedValue' + $Script:DeepNestedVar | Should-BeString 'DeepNestedValue' } } @@ -266,12 +266,12 @@ Describe 'Get-CompatibleModule' { It 'resolves to the ClientA copy via slash notation (verified by content)' { $repoId = InModuleScope -ModuleName "$rootA/$sharedNestedName" -ScriptBlock { $Script:RepoId } - $repoId | Should-Be 'RepoA' + $repoId | Should-BeString 'RepoA' } It 'resolves to the ClientB copy via slash notation (verified by content)' { $repoId = InModuleScope -ModuleName "$rootB/$sharedNestedName" -ScriptBlock { $Script:RepoId } - $repoId | Should-Be 'RepoB' + $repoId | Should-BeString 'RepoB' } } } @@ -446,7 +446,7 @@ Describe "Using variables within module scope" { } InModuleScope -ModuleName TestModule2 -ScriptBlock $setup - InModuleScope -ModuleName TestModule2 -ScriptBlock { $script:myVar } | Should-Be 'bar' + InModuleScope -ModuleName TestModule2 -ScriptBlock { $script:myVar } | Should-BeString 'bar' InModuleScope -ModuleName TestModule2 -ScriptBlock { $myVar2 } | Should-BeNull } @@ -487,6 +487,6 @@ Describe 'Working with manifest modules' { It 'Should be able to invoke private functions' { $res = InModuleScope -ModuleName $moduleName -ScriptBlock { myPrivateFunction } - $res | Should-Be 'real' + $res | Should-BeString 'real' } } diff --git a/tst/functions/Mock.Global.Tests.ps1 b/tst/functions/Mock.Global.Tests.ps1 index e53bd2eea..51cc971c9 100644 --- a/tst/functions/Mock.Global.Tests.ps1 +++ b/tst/functions/Mock.Global.Tests.ps1 @@ -65,7 +65,7 @@ Describe 'Mock.Global configuration option' { Mock Get-Content { 'allowed-content' } -ParameterFilter { $Path -like '*allowed*' } Mock Get-Content { throw 'blocked' } -ParameterFilter { $Path -notlike '*allowed*' } - Read-Path -Path 'C:\allowed\file.txt' | Should-Be 'allowed-content' + Read-Path -Path 'C:\allowed\file.txt' | Should-BeString 'allowed-content' { Read-Path -Path 'C:\secret\file.txt' } | Should-Throw -ExceptionMessage '*blocked*' } @@ -73,7 +73,7 @@ Describe 'Mock.Global configuration option' { # Get-ChildItem -Hidden relies on the FileSystem provider's dynamic parameters. The # global hook must not hide them when resolving the command to build the mock. Mock Get-ChildItem { 'mocked' } - Get-HiddenItems | Should-Be 'mocked' + Get-HiddenItems | Should-BeString 'mocked' } It 'does not affect commands Pester calls internally through SafeCommands' { @@ -112,7 +112,7 @@ Describe 'Mock.Global configuration option' { $configuration.Mock.Global = $true $result = Invoke-Pester -Configuration $configuration - $result.Result | Should-Be 'Passed' + $result.Result | Should-BeString 'Passed' $result.FailedCount | Should-Be 0 $result.PassedCount | Should-BeGreaterThan 0 } @@ -160,7 +160,7 @@ Describe 'Global mock hook lifecycle' { $configuration.Mock.Global = $true $result = Invoke-Pester -Configuration $configuration - $result.Result | Should-Be 'Passed' + $result.Result | Should-BeString 'Passed' $result.FailedCount | Should-Be 0 } @@ -205,7 +205,7 @@ Describe 'Global mock hook lifecycle' { $configuration.Mock.Global = $true $result = Invoke-Pester -Configuration $configuration - $result.Result | Should-Be 'Passed' + $result.Result | Should-BeString 'Passed' $result.FailedCount | Should-Be 0 } diff --git a/tst/functions/Mock.Tests.ps1 b/tst/functions/Mock.Tests.ps1 index 95bf70579..8bac9bad7 100644 --- a/tst/functions/Mock.Tests.ps1 +++ b/tst/functions/Mock.Tests.ps1 @@ -66,7 +66,7 @@ Describe "When calling Mock on existing cmdlet" { } It "Should Invoke the mocked script" { - $result | Should-Be "I am not Get-Process" + $result | Should-BeString "I am not Get-Process" } It 'Should not resolve $args to the parent scope' { @@ -100,7 +100,7 @@ Describe 'When calling Mock on an alias' { } It 'Should Invoke the mocked script' { - $result | Should-Be 'I am not dir' + $result | Should-BeString 'I am not dir' } AfterAll { @@ -116,11 +116,11 @@ Describe 'When calling Mock on an alias that refers to a function Pester can''t } New-Alias 'ali' orig - ali | Should-Be 'orig' + ali | Should-BeString 'orig' { mock ali { 'mck' } } | Should -Not -Throw - ali | Should-Be 'mck' + ali | Should-BeString 'mck' } } @@ -131,7 +131,7 @@ Describe 'When calling Mock on a filter' { } It 'Should Invoke the mocked script' { - $result | Should-Be 'I am not FilterUnderTest' + $result | Should-BeString 'I am not FilterUnderTest' } } @@ -167,7 +167,7 @@ Describe 'When calling Mock on an external script' { } It 'Should Invoke the mocked script using just the script name' { - $result | Should-Be 'I am not tempExternalScript.ps1' + $result | Should-BeString 'I am not tempExternalScript.ps1' } @@ -175,13 +175,13 @@ Describe 'When calling Mock on an external script' { #the command invocation operator is (&). Moved this to comment because it breaks the continuous builds. #there is issue for this on GH $result = & tempExternalScript.ps1 - $result | Should-Be 'I am not tempExternalScript.ps1' + $result | Should-BeString 'I am not tempExternalScript.ps1' } It 'Should Invoke the mocked script using dot source notation' { $result = . tempExternalScript.ps1 - $result | Should-Be 'I am not tempExternalScript.ps1' + $result | Should-BeString 'I am not tempExternalScript.ps1' } <# @@ -207,7 +207,7 @@ InModuleScope -ModuleName Pester { It 'Should Invoke the mocked script' { Mock id { return "I am not 'id'" } $result = id - $result | Should-Be "I am not 'id'" + $result | Should-BeString "I am not 'id'" } } @@ -215,7 +215,7 @@ InModuleScope -ModuleName Pester { It 'Should Invoke the mocked script' { Mock schtasks.exe { return 'I am not schtasks.exe' } $result = schtasks.exe - $result | Should-Be 'I am not schtasks.exe' + $result | Should-BeString 'I am not schtasks.exe' } } } @@ -225,7 +225,7 @@ Describe "When calling Mock in the Describe block" { It "Should mock Out-File successfully" { Mock Out-File { return "I am not Out-File" } $outfile = "test" | Out-File "TestDrive:\testfile.txt" - $outfile | Should-Be "I am not Out-File" + $outfile | Should-BeString "I am not Out-File" } } @@ -243,7 +243,7 @@ Describe "When calling Mock on existing cmdlet to handle pipelined input" { $result = '' "a", "b" | Get-ChildItem | ForEach { $result += $_ } - $result | Should-Be "AABB" + $result | Should-BeString "AABB" } } @@ -292,7 +292,7 @@ Describe "When calling Mock on non-existing function" { catch { $result = $_ } - $result.Exception.Message | Should-Be "Could not find command NotFunctionUnderTest" + $result.Exception.Message | Should-BeString "Could not find command NotFunctionUnderTest" } } @@ -329,7 +329,7 @@ Describe 'When calling Mock, StrictMode is enabled, and variables are used in th } It 'Calls the mock properly' { - FunctionUnderTest $testValue | Should-Be 'I am the mock' + FunctionUnderTest $testValue | Should-BeString 'I am the mock' } It 'Properly asserts the mock was called when there is a variable in the parameter filter' { @@ -348,7 +348,7 @@ Describe "When calling Mock on existing function with matching bound params" { It "Should return mocked result" { Mock FunctionUnderTest { return "fake results" } -parameterFilter { $param1 -eq "badTest" } $result = FunctionUnderTest "badTest" - $result | Should-Be "fake results" + $result | Should-BeString "fake results" } } @@ -363,7 +363,7 @@ Describe "When calling Mock on existing function with matching unbound arguments It "Should return mocked result" { Mock FunctionUnderTestWithoutParams { return "fake results" } -parameterFilter { $param1 -eq "badTest" -and $args[0] -eq 'arg0' } $result = FunctionUnderTestWithoutParams "badTest" "arg0" - $result | Should-Be "fake results" + $result | Should-BeString "fake results" } } @@ -391,7 +391,7 @@ Describe "When calling Mock on cmdlet Used by Mock" { Mock Set-Item { return "I am not Set-Item" } $result = Set-Item "mypath" -value "value" - $result | Should-Be "I am not Set-Item" + $result | Should-BeString "I am not Set-Item" } } @@ -405,10 +405,10 @@ Describe "When calling Mock on More than one command" { } It "Should Invoke the mocked script for the first Mock" { - $result | Should-Be "I am not Invoke-Command" + $result | Should-BeString "I am not Invoke-Command" } It "Should Invoke the mocked script for the second Mock" { - $result2 | Should-Be "I am the mock test" + $result2 | Should-BeString "I am the mock test" } } @@ -474,7 +474,7 @@ Describe 'When calling Mock on a module-internal function.' { } It 'Should call the actual internal module function from the public function' { - TestModule\PublicFunction | Should-Be 'I am the internal function' + TestModule\PublicFunction | Should-BeString 'I am the internal function' } Context 'Using Mock -ModuleName "ModuleName" "CommandName" syntax' { @@ -485,7 +485,7 @@ Describe 'When calling Mock on a module-internal function.' { } It 'Should call the mocked InternalFunction' { - TestModule\PublicFunction | Should-Be 'I am the mock test' + TestModule\PublicFunction | Should-BeString 'I am the mock test' } It 'Should be able to count the call to the InternalFunction' { @@ -503,12 +503,12 @@ Describe 'When calling Mock on a module-internal function.' { } It 'Should only call mocks within the same module' { - TestModule2\PublicFunction | Should-Be 'I am the second module internal function' + TestModule2\PublicFunction | Should-BeString 'I am the second module internal function' } It 'Should work even if the function is weird and steps on the automatic $ExecutionContext variable.' { - TestModule2\FuncThatOverwritesExecutionContext | Should-Be 'I am the second module internal function' - TestModule\FuncThatOverwritesExecutionContext | Should-Be 'I am the mock test' + TestModule2\FuncThatOverwritesExecutionContext | Should-BeString 'I am the second module internal function' + TestModule\FuncThatOverwritesExecutionContext | Should-BeString 'I am the mock test' } It 'Does not trigger the mocked Get-Content from Pester internals' { @@ -532,10 +532,10 @@ Describe "When Applying multiple Mocks on a single command" { } It "Should Invoke the mocked script for the first Mock" { - $result | Should-Be "I am the first mock test" + $result | Should-BeString "I am the first mock test" } It "Should Invoke the mocked script for the second Mock" { - $result2 | Should-Be "I am the Second mock test" + $result2 | Should-BeString "I am the Second mock test" } } @@ -548,7 +548,7 @@ Describe "When Applying multiple Mocks with filters on a single command where bo } It "The last Mock should win" { - $result | Should-Be "I am the Second mock test" + $result | Should-BeString "I am the Second mock test" } } @@ -563,11 +563,11 @@ Describe "When Applying multiple Mocks on a single command where one has no filt } It "The parameterless mock is evaluated last" { - $result | Should-Be "I am the first mock test" + $result | Should-BeString "I am the first mock test" } It "The parameterless mock will be applied if no other wins" { - $result2 | Should-Be "I am the paramless mock test" + $result2 | Should-BeString "I am the paramless mock test" } } @@ -585,7 +585,7 @@ Describe "When Creating Verifiable Mock that is not called" { $result = $_ } - $result.Exception.Message | Should-Be "$([System.Environment]::NewLine)Expected all verifiable mocks to be called, but these were not:$([System.Environment]::NewLine) Command FunctionUnderTest with { `$param1 -eq `"one`" }" + $result.Exception.Message | Should-BeString "$([System.Environment]::NewLine)Expected all verifiable mocks to be called, but these were not:$([System.Environment]::NewLine) Command FunctionUnderTest with { `$param1 -eq `"one`" }" } } @@ -610,7 +610,7 @@ Describe "When Creating Verifiable Mock that is not called" { } It "Should throw" { - $result.Exception.Message | Should-Be "$([System.Environment]::NewLine)Expected all verifiable mocks to be called, but these were not:$([System.Environment]::NewLine) Command ModuleFunctionUnderTest from inside module TestModule with { `$param1 -eq `"one`" }" + $result.Exception.Message | Should-BeString "$([System.Environment]::NewLine)Expected all verifiable mocks to be called, but these were not:$([System.Environment]::NewLine) Command ModuleFunctionUnderTest from inside module TestModule with { `$param1 -eq `"one`" }" } AfterAll { @@ -635,7 +635,7 @@ Describe "When Creating multiple Verifiable Mocks that are not called" { } It "Should throw and list all commands" { - $result.Exception.Message | Should-Be "$([System.Environment]::NewLine)Expected all verifiable mocks to be called, but these were not:$([System.Environment]::NewLine) Command FunctionUnderTest with { `$param1 -eq `"one`" }$([System.Environment]::NewLine) Command FunctionUnderTest with { `$param1 -eq `"two`" }" + $result.Exception.Message | Should-BeString "$([System.Environment]::NewLine)Expected all verifiable mocks to be called, but these were not:$([System.Environment]::NewLine) Command FunctionUnderTest with { `$param1 -eq `"one`" }$([System.Environment]::NewLine) Command FunctionUnderTest with { `$param1 -eq `"two`" }" } It 'Should include reason when -Because is used' { @@ -645,7 +645,7 @@ Describe "When Creating multiple Verifiable Mocks that are not called" { Catch { $failure = $_ } - $failure.Exception.Message | Should-Be "$([System.Environment]::NewLine)Expected all verifiable mocks to be called, because of reasons, but these were not:$([System.Environment]::NewLine) Command FunctionUnderTest with { `$param1 -eq `"one`" }$([System.Environment]::NewLine) Command FunctionUnderTest with { `$param1 -eq `"two`" }" + $failure.Exception.Message | Should-BeString "$([System.Environment]::NewLine)Expected all verifiable mocks to be called, because of reasons, but these were not:$([System.Environment]::NewLine) Command FunctionUnderTest with { `$param1 -eq `"one`" }$([System.Environment]::NewLine) Command FunctionUnderTest with { `$param1 -eq `"two`" }" } } @@ -675,7 +675,7 @@ Describe "When calling Should -Not -InvokeVerifiable" { } It "Should throw" { - $result.Exception.Message | Should-Be "$([System.Environment]::NewLine)Expected no verifiable mocks to be called, but these were:$([System.Environment]::NewLine) Command FunctionUnderTest with { `$param1 -eq `"one`" }" + $result.Exception.Message | Should-BeString "$([System.Environment]::NewLine)Expected no verifiable mocks to be called, but these were:$([System.Environment]::NewLine) Command FunctionUnderTest with { `$param1 -eq `"one`" }" } It 'Should include reason when -Because is used' { @@ -685,7 +685,7 @@ Describe "When calling Should -Not -InvokeVerifiable" { Catch { $failure = $_ } - $failure.Exception.Message | Should-Be "$([System.Environment]::NewLine)Expected no verifiable mocks to be called, because of reasons, but these were:$([System.Environment]::NewLine) Command FunctionUnderTest with { `$param1 -eq `"one`" }" + $failure.Exception.Message | Should-BeString "$([System.Environment]::NewLine)Expected no verifiable mocks to be called, because of reasons, but these were:$([System.Environment]::NewLine) Command FunctionUnderTest with { `$param1 -eq `"one`" }" } } @@ -704,7 +704,7 @@ Describe "When calling Should -Not -InvokeVerifiable" { } It "Should throw" { - $result.Exception.Message | Should-Be "$([System.Environment]::NewLine)Expected no verifiable mocks to be called, but these were:$([System.Environment]::NewLine) Command FunctionUnderTest with { `$param1 -eq `"one`" }" + $result.Exception.Message | Should-BeString "$([System.Environment]::NewLine)Expected no verifiable mocks to be called, but these were:$([System.Environment]::NewLine) Command FunctionUnderTest with { `$param1 -eq `"one`" }" } } @@ -1077,7 +1077,7 @@ Describe 'When Calling Should -Invoke with invalid -Scope' { } } It 'Should throw' { - $result.Exception.Message | Should-Be 'Assertion is placed outside of an It block, but -Scope It is specified.' + $result.Exception.Message | Should-BeString 'Assertion is placed outside of an It block, but -Scope It is specified.' } } @@ -1132,19 +1132,19 @@ Describe "Using Pester Scopes (Describe,Context,It)" { Context "When in the first context" { It "should mock Describe scoped paramless mock" { - FunctionUnderTest | Should-Be "I am the paramless mock test" + FunctionUnderTest | Should-BeString "I am the paramless mock test" } It "should mock Describe scoped single param mock" { - FunctionUnderTest "one" | Should-Be "I am the first mock test" + FunctionUnderTest "one" | Should-BeString "I am the first mock test" } } Context "When in the second context" { It "should mock Describe scoped paramless mock again" { - FunctionUnderTest | Should-Be "I am the paramless mock test" + FunctionUnderTest | Should-BeString "I am the paramless mock test" } It "should mock Describe scoped single param mock again" { - FunctionUnderTest "one" | Should-Be "I am the first mock test" + FunctionUnderTest "one" | Should-BeString "I am the first mock test" } } @@ -1154,10 +1154,10 @@ Describe "Using Pester Scopes (Describe,Context,It)" { } It "should mock Describe scoped mock." { - FunctionUnderTest | Should-Be "I am the paramless mock test" + FunctionUnderTest | Should-BeString "I am the paramless mock test" } It "should mock Context scoped mock." { - FunctionUnderTestWithoutParams | Should-Be "I am the other function" + FunctionUnderTestWithoutParams | Should-BeString "I am the other function" } } @@ -1168,20 +1168,20 @@ Describe "Using Pester Scopes (Describe,Context,It)" { } It "should use the context paramless mock" { - FunctionUnderTest | Should-Be "I am the context mock" + FunctionUnderTest | Should-BeString "I am the context mock" } It "should use the context parameterized mock" { - FunctionUnderTest "one" | Should-Be "I am the parameterized context mock" + FunctionUnderTest "one" | Should-BeString "I am the parameterized context mock" } } Context "When context no longer hides a describe mock" { It "should use the describe mock" { - FunctionUnderTest | Should-Be "I am the paramless mock test" + FunctionUnderTest | Should-BeString "I am the paramless mock test" } It "should use the describe parameterized mock" { - FunctionUnderTest "one" | Should-Be "I am the first mock test" + FunctionUnderTest "one" | Should-BeString "I am the first mock test" } } @@ -1195,7 +1195,7 @@ Describe "Using Pester Scopes (Describe,Context,It)" { } It 'Does not leave the mock active in the parent scope' { - FunctionUnderTest | Should-Be 'I am the context mock' + FunctionUnderTest | Should-BeString 'I am the context mock' } } } @@ -1212,7 +1212,7 @@ Describe 'Testing mock history behavior from each scope' { } It 'Calls the describe mock' { - MockHistoryChecker | Should-Be 'I am the describe mock.' + MockHistoryChecker | Should-BeString 'I am the describe mock.' } It "Reports that zero calls have been made in an It block, after a context-scoped call" { @@ -1244,7 +1244,7 @@ Describe 'Testing mock history behavior from each scope' { } It 'Calls the context mock' { - MockHistoryChecker | Should-Be 'I am the context mock.' + MockHistoryChecker | Should-BeString 'I am the context mock.' } It 'Reports one context-scoped call' { @@ -1257,7 +1257,7 @@ Describe 'Testing mock history behavior from each scope' { It 'Calls an It-scoped mock' { Mock MockHistoryChecker { 'I am the It mock.' } - MockHistoryChecker | Should-Be 'I am the It mock.' + MockHistoryChecker | Should-BeString 'I am the It mock.' } It 'Reports 2 context-scoped calls' { @@ -1285,7 +1285,7 @@ Describe "Using a single no param Describe" { } It "Should use the context mock" { - FunctionUnderTest | Should-Be "I am the context mock test" + FunctionUnderTest | Should-BeString "I am the context mock test" } } } @@ -1549,7 +1549,7 @@ Describe 'Mocking functions with dynamic parameters' { It 'Should successfully call the mock and generate the dynamic parameters' { $scriptBlock | Should -Not -Throw - $hash.Result | Should-Be 'Mocked' + $hash.Result | Should-BeString 'Mocked' } } @@ -1607,7 +1607,7 @@ Describe 'Mocking functions with dynamic parameters' { It 'Should successfully call the mock and generate the dynamic parameters' { $scriptBlock | Should -Not -Throw - $hash.Result | Should-Be 'Mocked' + $hash.Result | Should-BeString 'Mocked' } } @@ -1659,7 +1659,7 @@ Describe 'Mocking functions with dynamic parameters' { It 'Should successfully call the mock and generate the dynamic parameters' { $scriptBlock | Should -Not -Throw - $hash.Result | Should-Be 'Mocked' + $hash.Result | Should-BeString 'Mocked' } } @@ -1714,7 +1714,7 @@ Describe 'Mocking functions with dynamic parameters' { It 'Should successfully call the mock and generate the dynamic parameters' { $scriptBlock | Should -Not -Throw - $hash.Result | Should-Be 'Mocked' + $hash.Result | Should-BeString 'Mocked' } } @@ -1731,7 +1731,7 @@ Describe 'Mocking functions with dynamic parameters' { Mock Get-ThingWithFailingDynamicParam { 'mocked' } { Get-ThingWithFailingDynamicParam } | Should -Not -Throw - Get-ThingWithFailingDynamicParam | Should-Be 'mocked' + Get-ThingWithFailingDynamicParam | Should-BeString 'mocked' } } @@ -1765,19 +1765,19 @@ Describe 'Mocking functions with dynamic parameters' { It 'matches the parameter filter using the alias of a dynamic parameter' { Mock Get-DynamicAliasThing { 'mocked' } -ParameterFilter { $Location -eq 'Here' } - Get-DynamicAliasThing -Location 'Here' | Should-Be 'mocked' + Get-DynamicAliasThing -Location 'Here' | Should-BeString 'mocked' } It 'matches the parameter filter using the name of a dynamic parameter' { Mock Get-DynamicAliasThing { 'mocked' } -ParameterFilter { $Path -eq 'Here' } - Get-DynamicAliasThing -Location 'Here' | Should-Be 'mocked' + Get-DynamicAliasThing -Location 'Here' | Should-BeString 'mocked' } It 'uses the dynamic-parameter alias to choose between behaviors' { Mock Get-DynamicAliasThing { 'default' } Mock Get-DynamicAliasThing { 'matched' } -ParameterFilter { $Location -eq 'Here' } - Get-DynamicAliasThing -Location 'Here' | Should-Be 'matched' - Get-DynamicAliasThing -Location 'There' | Should-Be 'default' + Get-DynamicAliasThing -Location 'Here' | Should-BeString 'matched' + Get-DynamicAliasThing -Location 'There' | Should-BeString 'default' } It 'matches Should -Invoke -ParameterFilter using the alias of a dynamic parameter' { @@ -1930,7 +1930,7 @@ Describe 'DynamicParam blocks in other scopes' { } It 'Properly evaluates dynamic parameters when called from another scope' { - CallingFunction | Should-Be 'I am the mocked function' + CallingFunction | Should-BeString 'I am the mocked function' } It 'Properly evaluates dynamic parameters when called from another scope when the call is from a ValidateScript block' { @@ -1992,7 +1992,7 @@ Describe 'When mocking a command with parameters that match internal variable na It 'Should execute the mocked command successfully' { { Test-Function } | Should -Not -Throw - Test-Function | Should-Be 'Mocked!' + Test-Function | Should-BeString 'Mocked!' } } @@ -2037,7 +2037,7 @@ Describe 'When mocking a command that has an ArgumentList parameter with validat $scriptBlock = { $hash.Result = Start-Process -FilePath cmd.exe -ArgumentList '/c dir c:\' } $scriptBlock | Should -Not -Throw - $hash.Result | Should-Be 'mocked' + $hash.Result | Should-BeString 'mocked' } } @@ -2134,8 +2134,8 @@ Describe 'Mocks with closures' { } It 'Resolves variables in the closure rather than Pester''s current scope' { - TestClosure | Should-Be 'Variable resolved from script' - TestClosure -Closure | Should-Be 'Variable resolved from closure' + TestClosure | Should-BeString 'Variable resolved from script' + TestClosure -Closure | Should-BeString 'Variable resolved from closure' } } @@ -2212,7 +2212,7 @@ Describe 'Mocking advanced function' { return $MyParam1 } - Get-Something -MyParam1 'SomeValue' | Should-Be 'SomeValue' + Get-Something -MyParam1 'SomeValue' | Should-BeString 'SomeValue' } } @@ -2292,11 +2292,11 @@ Describe 'Mocking cmdlet without positional parameters' { } It 'Original cmdlet bind all to Remainings' { - Invoke-CmdletWithValueFromRemainingArguments asd fgh jkl | Should-Be '; asd, fgh, jkl' + Invoke-CmdletWithValueFromRemainingArguments asd fgh jkl | Should-BeString '; asd, fgh, jkl' } It 'Mock of cmdlet should bind all to Remainings' { Mock Invoke-CmdletWithValueFromRemainingArguments { -join ($Parameter, '; ', ($Remainings -join ', ')) } - Invoke-CmdletWithValueFromRemainingArguments asd fgh jkl | Should-Be '; asd, fgh, jkl' + Invoke-CmdletWithValueFromRemainingArguments asd fgh jkl | Should-BeString '; asd, fgh, jkl' } } @@ -2316,7 +2316,7 @@ Describe 'Nested Mock calls' { It 'Properly handles nested mocks' { $result = @(Get-Date) $result.Count | Should-Be 1 - $result[0] | Should-Be '2012-06-13T00:00:00.0000000' + $result[0] | Should-BeString '2012-06-13T00:00:00.0000000' } } @@ -2362,7 +2362,7 @@ Describe 'Naming conflicts in mocked functions' { } It 'Works with commands with parameter named Metadata' { - Wrapper | Should-Be 'mocked' + Wrapper | Should-BeString 'mocked' } } Context 'parameter named Keys' { @@ -2379,7 +2379,7 @@ Describe 'Naming conflicts in mocked functions' { It 'Works with command with parameter named Keys' { $r = Wrapper - $r | Should-Be 'value' + $r | Should-BeString 'value' } } } @@ -2453,7 +2453,7 @@ Describe "Restoring original commands when mock scopes exit" { } It "passes in first context" { - a | Should-Be "mock" + a | Should-BeString "mock" } } @@ -2467,7 +2467,7 @@ Describe "Restoring original commands when mock scopes exit" { } It "passes in second context" { - a | Should-Be "mock" + a | Should-BeString "mock" } } } @@ -2493,11 +2493,11 @@ Describe "Mocking functions with conflicting parameters" { } It 'executes the mock' { - Get-ExampleTest -ParamToAvoid "Hello" | Should-Be "World" + Get-ExampleTest -ParamToAvoid "Hello" | Should-BeString "World" } It 'falls back to the default mock when no parameter filter matches' { - Get-ExampleTest -ParamToAvoid "Bye" | Should-Be "default mock" + Get-ExampleTest -ParamToAvoid "Bye" | Should-BeString "default mock" } Context "Should -Invoke" { @@ -2544,15 +2544,15 @@ if ($PSVersionTable.PSVersion.Major -ge 3) { } It "returns mock that matches parameter filter block when using alias in the call" { - Get-Content -Path "c:\temp.txt" -Last 100 | Should-Be "aliased-parameter-name" + Get-Content -Path "c:\temp.txt" -Last 100 | Should-BeString "aliased-parameter-name" } It "returns mock that matches parameter filter block when using the real parameter name in call" { - Get-Content -Path "c:\temp.txt" -Tail 100 | Should-Be "aliased-parameter-name" + Get-Content -Path "c:\temp.txt" -Tail 100 | Should-BeString "aliased-parameter-name" } It 'returns default mock' { - Get-Content -Path "c:\temp.txt" | Should-Be "default-get-content" + Get-Content -Path "c:\temp.txt" | Should-BeString "default-get-content" } } @@ -2561,7 +2561,7 @@ if ($PSVersionTable.PSVersion.Major -ge 3) { It 'calls the mock' { Mock New-Item { throw "default mock should not run" } Mock New-Item { return "nic" } -ParameterFilter { $Type -ne $null -and $Type.StartsWith("nic") } - New-Item -Path 'Hello' -Type "nic" | Should-Be "nic" + New-Item -Path 'Hello' -Type "nic" | Should-BeString "nic" } } @@ -2611,7 +2611,7 @@ InPesterModuleScope { It 'mocks command' -TestCases $case { Mock $Command { 'I am being mocked' } - & $Command | Should-Be 'I am being mocked' + & $Command | Should-BeString 'I am being mocked' Should -Invoke $Command -Scope It -Exactly 1 } @@ -2622,7 +2622,7 @@ InPesterModuleScope { It 'mocks notepad command with extension' { Mock notepad.exe { 'I am being mocked' } - notepad.exe | Should-Be 'I am being mocked' + notepad.exe | Should-BeString 'I am being mocked' Should -Invoke notepad.exe -Scope It -Exactly 1 } @@ -2632,7 +2632,7 @@ InPesterModuleScope { It 'mocks with extension and calls it without ext' { Mock notepad.exe { 'I am being mocked' } - notepad | Should-Be 'I am being mocked' + notepad | Should-BeString 'I am being mocked' Should -Invoke notepad.exe -Scope It -Exactly 1 } @@ -2640,7 +2640,7 @@ InPesterModuleScope { It 'mocks without extension and calls with extension' { Mock notepad { 'I am being mocked' } - notepad.exe | Should-Be 'I am being mocked' + notepad.exe | Should-BeString 'I am being mocked' } It 'assert that alias to mock works' { @@ -2648,7 +2648,7 @@ InPesterModuleScope { Mock notepad.exe { 'I am being mocked' } - notepad | Should-Be 'I am being mocked' + notepad | Should-BeString 'I am being mocked' Should -Invoke note -Scope It -Exactly 1 } @@ -2676,9 +2676,9 @@ Describe 'Mocking using ParameterFilter' { } Mock Get-MockFilterValue { 'fallback' } - Mock Get-MockFilterValue { 'mocked' } -ParameterFilter { $Name | Should-Be 'foo' } + Mock Get-MockFilterValue { 'mocked' } -ParameterFilter { $Name | Should-BeString 'foo' } - Get-MockFilterValue -Name 'foo' | Should-Be 'mocked' + Get-MockFilterValue -Name 'foo' | Should-BeString 'mocked' } It 'matches a filter that uses Should-BeString' { @@ -2691,7 +2691,7 @@ Describe 'Mocking using ParameterFilter' { Mock Get-MockFilterText { 'fallback' } Mock Get-MockFilterText { 'mocked' } -ParameterFilter { $Name | Should-BeString 'foo' } - Get-MockFilterText -Name 'foo' | Should-Be 'mocked' + Get-MockFilterText -Name 'foo' | Should-BeString 'mocked' } } @@ -2791,7 +2791,7 @@ if ($PSVersionTable.PSVersion.Major -ge 3) { [Diagnostics.Process] $currentProcess = Get-Process -id $pid $currentProcess -as [int] -eq $null | Should-BeTrue -Because "Process is not convertible to int" - f -Name 'Hello' -Count $currentProcess | Should-Be "result" -Because "we successfuly provided a process to parameter defined as int" + f -Name 'Hello' -Count $currentProcess | Should-BeString "result" -Because "we successfuly provided a process to parameter defined as int" } if ($PSVersionTable.PSVersion.Major -eq 5) { @@ -2810,7 +2810,7 @@ if ($PSVersionTable.PSVersion.Major -ge 3) { Context "Get-PhysicalDisk example" { It "should return 'hello'" { Mock Get-PhysicalDisk -RemoveParameterType Usage, HealthStatus { return "hello" } - Get-PhysicalDisk | Should-Be "hello" + Get-PhysicalDisk | Should-BeString "hello" } } } @@ -2837,7 +2837,7 @@ Describe 'RemoveParameterValidation' { It 'passes when mock removes the validation' { Mock Test-Validation -RemoveParameterValidation Count { "mock" } - Test-Validation -Count -1 | Should-Be "mock" + Test-Validation -Count -1 | Should-BeString "mock" } Context 'When the validated parameter is a dynamic parameter (#1557)' { @@ -2873,12 +2873,12 @@ Describe 'RemoveParameterValidation' { It 'passes when mock removes the validation from the dynamic parameter' { Mock Test-DynamicValidation { 'mock' } -RemoveParameterValidation Name - Test-DynamicValidation -Name 'zzz' | Should-Be 'mock' + Test-DynamicValidation -Name 'zzz' | Should-BeString 'mock' } It 'only removes validation from the named dynamic parameter' { Mock Test-DynamicValidation { 'mock' } -RemoveParameterValidation Name - Test-DynamicValidation -Name 'zzz' | Should-Be 'mock' + Test-DynamicValidation -Name 'zzz' | Should-BeString 'mock' { Test-DynamicValidation -Color 'zzz' } | Should-Throw -FullyQualifiedErrorId '*ParameterArgumentValidationError*' } } @@ -2941,7 +2941,7 @@ Describe 'Mocking command with ValidateRange-attributes' { Set-Item -Path 'function:Test-EnumValidation' -Value ('param ( {0}{1} )' -f $Attribute, $Parameter) Mock -CommandName 'Test-EnumValidation' -MockWith { 'mock' } - Test-EnumValidation | Should-Be 'mock' + Test-EnumValidation | Should-BeString 'mock' } if ($PSVersionTable.PSVersion.Major -ge '7') { @@ -2954,7 +2954,7 @@ Describe 'Mocking command with ValidateRange-attributes' { Set-Item -Path 'function:Test-EnumValidation' -Value ('param ( {0}{1} )' -f $Attribute, $Parameter) Mock -CommandName 'Test-EnumValidation' -MockWith { 'mock' } - Test-EnumValidation | Should-Be 'mock' + Test-EnumValidation | Should-BeString 'mock' } } @@ -2962,7 +2962,7 @@ Describe 'Mocking command with ValidateRange-attributes' { if ((Get-Module BitsTransfer -ErrorAction SilentlyContinue)) { It 'mocked cmdlet does not throw' { Mock -CommandName 'Start-BitsTransfer' -MockWith { 'mock' } - Start-BitsTransfer -Source "/nonexistingpath" | Should-Be 'mock' + Start-BitsTransfer -Source "/nonexistingpath" | Should-BeString 'mock' } } } @@ -2985,7 +2985,7 @@ Describe "Running Mock with ModuleName in test scope" { It "can mock internal function of the module" { Mock -ModuleName test a { "mock" } - f | Should-Be "mock" + f | Should-BeString "mock" } It "runs the body in the current scope" { @@ -3016,7 +3016,7 @@ Describe "Mocks can be defined outside of BeforeAll" { } It "Finds the mock" { - a | Should-Be "mock" + a | Should-BeString "mock" } } @@ -3061,21 +3061,21 @@ Describe "When inherited variables conflicts with parameters" { It "parameterized mock should not be called due to inherited variable" { $param1 = 'abc' - FunctionUnderTest | Should-Be 'default' + FunctionUnderTest | Should-BeString 'default' } It "InvokeVerifiable should not pass due to test variable" { # Uses same logic as mock execution, so should not be tricked $param1 = 'abc' - FunctionUnderTest | Should-Be 'default' + FunctionUnderTest | Should-BeString 'default' { Should -InvokeVerifiable } | Should-Throw } It "Should Invoke ParameterFilter will count false positive for the first FunctionUnderTest call" { # https://github.com/pester/Pester/issues/1873 # this will pass the parameter filter because we define a variable param1 with the same name and value as the expected parameter value - FunctionUnderTest | Should-Be 'default' - FunctionUnderTest -param1 'abc' | Should-Be 'filtered' + FunctionUnderTest | Should-BeString 'default' + FunctionUnderTest -param1 'abc' | Should-BeString 'filtered' $param1 = 'abc' # This should show warning about conflict when in Diagnostic output (Mock debug message) @@ -3085,8 +3085,8 @@ Describe "When inherited variables conflicts with parameters" { It "Invoke ParameterFilter works as expected when PesterBoundParamters is used" { # Workaround mentioned in debug message warning mentioned in previous test - FunctionUnderTest | Should-Be 'default' - FunctionUnderTest -param1 'abc' | Should-Be 'filtered' + FunctionUnderTest | Should-BeString 'default' + FunctionUnderTest -param1 'abc' | Should-BeString 'filtered' $param1 = 'abc' # No warning will be shown in debug as there's no conflict @@ -3094,7 +3094,7 @@ Describe "When inherited variables conflicts with parameters" { } It "Calling mock with parameter overrides inherited variable in filter" { - FunctionUnderTest -param1 '123' | Should-Be 'default' + FunctionUnderTest -param1 '123' | Should-BeString 'default' $param1 = 'abc' # This should show warning about conflict when in Diagnostic output (Mock debug message) @@ -3128,13 +3128,13 @@ Describe 'Mocking in manifest modules' { It 'Should be able to mock public function' { Mock -CommandName 'myManifestPublicFunction' -MockWith { 'mocked public' } - myManifestPublicFunction | Should-Be 'mocked public' + myManifestPublicFunction | Should-BeString 'mocked public' Should -Invoke -CommandName 'myManifestPublicFunction' -Exactly -Times 1 } It 'Should be able to mock private function' { Mock -CommandName 'myManifestPrivateFunction' -ModuleName $moduleName -MockWith { 'mocked private' } - myManifestPublicFunction | Should-Be 'mocked private' + myManifestPublicFunction | Should-BeString 'mocked private' Should -Invoke -CommandName 'myManifestPrivateFunction' -ModuleName $moduleName -Exactly -Times 1 } } @@ -3170,7 +3170,7 @@ Describe "Mocking using 'RootModule/NestedModule' slash notation" { It 'Should mock an internal command in the nested module using slash notation' { Mock -CommandName 'Get-InternalData' -ModuleName "$rootName/$nestedName" -MockWith { 'mocked' } $result = Get-PublicData - $result | Should-Be 'mocked' + $result | Should-BeString 'mocked' } It 'Should-Invoke matches call history when using slash notation' { @@ -3193,7 +3193,7 @@ Describe "Mocking using 'RootModule/NestedModule' slash notation" { It 'Mock cleanup removes the bootstrap function from the nested module session state' { # After the It block completes the mock is torn down; calling the real function returns 'real'. - Get-PublicData | Should-Be 'real' + Get-PublicData | Should-BeString 'real' } } @@ -3230,7 +3230,7 @@ Describe "Mocking using deep module path notation 'Root/Mid/Leaf'" { It 'Should mock an internal command in the deeply nested module using slash notation' { Mock -CommandName 'Get-DeepInternalData' -ModuleName "$rootName/$midName/$leafName" -MockWith { 'mocked-deep' } $result = InModuleScope "$rootName/$midName/$leafName" { Get-DeepPublicData } - $result | Should-Be 'mocked-deep' + $result | Should-BeString 'mocked-deep' } It 'Should-Invoke matches call history when using deep slash notation' { @@ -3286,9 +3286,9 @@ Describe "Disambiguating nested modules with the same name across two root modul It 'mocks Get-Data in the ClientA copy, leaving the identically-named ClientB copy untouched' { Mock -CommandName 'Get-Data' -ModuleName "$rootA/$sharedName" -MockWith { 'mockedA' } - InModuleScope "$rootA/$sharedName" { Invoke-Api } | Should-Be 'mockedA' + InModuleScope "$rootA/$sharedName" { Invoke-Api } | Should-BeString 'mockedA' # the mock must not bleed into the same-named nested module under ClientB - InModuleScope "$rootB/$sharedName" { Invoke-Api } | Should-Be 'dataB' + InModuleScope "$rootB/$sharedName" { Invoke-Api } | Should-BeString 'dataB' } It 'Should-Invoke uses slash notation to check the ClientA copy call history' { @@ -3328,7 +3328,7 @@ Describe 'Mocking in nested Invoke-Pester runs' { } It 'Mocking works in nested run' { - $innerRun.Result | Should-Be 'Passed' + $innerRun.Result | Should-BeString 'Passed' $innerRun.PassedCount | Should-Be 2 } @@ -3385,7 +3385,7 @@ Describe 'Usage of Alias in DynamicParams' { It 'Mocks Test-DynamicParam with PSEdition set to Desktop' { Mock Test-DynamicParam { "World" } -ParameterFilter { $_PSEdition -eq 'Desktop' } - Test-DynamicParam -Name "Hello" -PSEdition 'Desktop' | Should-Be 'World' + Test-DynamicParam -Name "Hello" -PSEdition 'Desktop' | Should-BeString 'World' } } @@ -3393,7 +3393,7 @@ Describe 'Usage of Alias in DynamicParams' { It 'Invokes Test-DynamicParam with correct parameters' { Mock Test-DynamicParam { "World" } - Test-DynamicParam -Name "Hello" -PSEdition 'Desktop' | Should-Be 'World' + Test-DynamicParam -Name "Hello" -PSEdition 'Desktop' | Should-BeString 'World' Should -Invoke Test-DynamicParam -Exactly 1 -Scope It } diff --git a/tst/functions/New-MockObject.Tests.ps1 b/tst/functions/New-MockObject.Tests.ps1 index e0306dcb2..8826722e3 100644 --- a/tst/functions/New-MockObject.Tests.ps1 +++ b/tst/functions/New-MockObject.Tests.ps1 @@ -26,8 +26,8 @@ Describe 'New-MockObject' { } $mockObject | Should-Be $o - $mockObject.Name | Should-Be 'Jakub' - $mockObject.GetName() | Should-Be 'Jakub' + $mockObject.Name | Should-BeString 'Jakub' + $mockObject.GetName() | Should-BeString 'Jakub' } It 'Default parameter set is Type for backwards compatibility' { @@ -56,8 +56,8 @@ Describe 'New-MockObject' { { [MyInternalClass] } | Should-Throw -FullyQualifiedErrorId 'TypeNotFound' $mock = New-MockObject -Type $someObj.GetType() -Properties @{ Name = 'Mocked' } - $mock.GetType().Name | Should-Be 'MyInternalClass' - $mock.GetName() | Should-Be 'Mocked' + $mock.GetType().Name | Should-BeString 'MyInternalClass' + $mock.GetName() | Should-BeString 'Mocked' } } @@ -67,7 +67,7 @@ Describe 'New-MockObject' { $mockObject = New-MockObject -InputObject $o -Methods @{ Kill = { param() "killed" } } $mockObject | Should-Be $o - $mockObject.Kill() | Should-Be "killed" + $mockObject.Kill() | Should-BeString "killed" } It "Counts history of the invocation" { @@ -75,10 +75,10 @@ Describe 'New-MockObject' { $mockObject = New-MockObject -InputObject $o -Methods @{ Kill = { param($entireProcessTree) "killed" } } $mockObject | Should-Be $o - $mockObject.Kill() | Should-Be "killed" + $mockObject.Kill() | Should-BeString "killed" $mockObject._Kill[-1].Call | Should-Be 1 $mockObject._Kill[-1].Arguments | Should-BeNull - $mockObject.Kill($true) | Should-Be "killed" + $mockObject.Kill($true) | Should-BeString "killed" $mockObject._Kill[-1].Call | Should-Be 2 $mockObject._Kill[-1].Arguments | Should-BeTrue } @@ -89,8 +89,8 @@ Describe 'New-MockObject' { Close = { param($Server, $Port)"close" } } - $mockObject.Connect() | Should-Be "connect" - $mockObject.Close() | Should-Be "close" + $mockObject.Connect() | Should-BeString "connect" + $mockObject.Close() | Should-BeString "close" } } diff --git a/tst/functions/Output.Tests.ps1 b/tst/functions/Output.Tests.ps1 index 15d732c9e..d03dea2d1 100644 --- a/tst/functions/Output.Tests.ps1 +++ b/tst/functions/Output.Tests.ps1 @@ -93,37 +93,37 @@ InModuleScope -ModuleName Pester -ScriptBlock { if ((GetPesterOS) -ne 'Windows') { It "Writes path correctly when it is provided as string" { - Format-PesterPath -Path '/home/username/folder1' | Should-Be '/home/username/folder1' + Format-PesterPath -Path '/home/username/folder1' | Should-BeString '/home/username/folder1' } It "Writes path correctly when it is provided as string[]" { - Format-PesterPath -Path @('/home/username/folder1', '/home/username/folder2') -Delimiter ', ' | Should-Be '/home/username/folder1, /home/username/folder2' + Format-PesterPath -Path @('/home/username/folder1', '/home/username/folder2') -Delimiter ', ' | Should-BeString '/home/username/folder1, /home/username/folder2' } It "Writes path correctly when provided through hashtable" { - Format-PesterPath -Path @{ Path = '/home/username/folder1' } | Should-Be '/home/username/folder1' + Format-PesterPath -Path @{ Path = '/home/username/folder1' } | Should-BeString '/home/username/folder1' } It "Writes path correctly when provided through array of hashtable" { - Format-PesterPath -Path @{ Path = '/home/username/folder1' }, @{ Path = '/home/username/folder2' } -Delimiter ', ' | Should-Be '/home/username/folder1, /home/username/folder2' + Format-PesterPath -Path @{ Path = '/home/username/folder1' }, @{ Path = '/home/username/folder2' } -Delimiter ', ' | Should-BeString '/home/username/folder1, /home/username/folder2' } } else { It "Writes path correctly when it is provided as string" { - Format-PesterPath -Path 'C:\path' | Should-Be 'C:\path' + Format-PesterPath -Path 'C:\path' | Should-BeString 'C:\path' } It "Writes path correctly when it is provided as string[]" { - Format-PesterPath -Path @('C:\path1', 'C:\path2') -Delimiter ', ' | Should-Be 'C:\path1, C:\path2' + Format-PesterPath -Path @('C:\path1', 'C:\path2') -Delimiter ', ' | Should-BeString 'C:\path1, C:\path2' } It "Writes path correctly when provided through hashtable" { - Format-PesterPath -Path @{ Path = 'C:\path' } | Should-Be 'C:\path' + Format-PesterPath -Path @{ Path = 'C:\path' } | Should-BeString 'C:\path' } It "Writes path correctly when provided through array of hashtable" { - Format-PesterPath -Path @{ Path = 'C:\path1' }, @{ Path = 'C:\path2' } -Delimiter ', ' | Should-Be 'C:\path1, C:\path2' + Format-PesterPath -Path @{ Path = 'C:\path1' }, @{ Path = 'C:\path2' } -Delimiter ', ' | Should-BeString 'C:\path1, C:\path2' } } @@ -160,7 +160,7 @@ InModuleScope -ModuleName Pester -ScriptBlock { $r = $e | ConvertTo-FailureLines - $r.Message[0] | Should-Be 'RuntimeException: message' + $r.Message[0] | Should-BeString 'RuntimeException: message' $r.Message.Count | Should-Be 1 } @@ -174,12 +174,12 @@ InModuleScope -ModuleName Pester -ScriptBlock { $r = $e | ConvertTo-FailureLines - $r.Message[0] | Should-Be 'Expected strings to be the same, but they were different.' - $r.message[1] | Should-Be 'String lengths are both 3.' - $r.message[2] | Should-Be 'Strings differ at index 0.' - $r.Message[3] | Should-Be "Expected: 'Two'" - $r.Message[4] | Should-Be "But was: 'One'" - $r.Message[5] | Should-Be ' ^' + $r.Message[0] | Should-BeString 'Expected strings to be the same, but they were different.' + $r.message[1] | Should-BeString 'String lengths are both 3.' + $r.message[2] | Should-BeString 'Strings differ at index 0.' + $r.Message[3] | Should-BeString "Expected: 'Two'" + $r.Message[4] | Should-BeString "But was: 'One'" + $r.Message[5] | Should-BeString ' ^' $r.Message.Count | Should-Be 6 $r.Trace[0] | Should-MatchString "'One' | Should-BeString 'Two'" @@ -252,16 +252,16 @@ InModuleScope -ModuleName Pester -ScriptBlock { } It 'produces correct message lines.' { - $r.Message[0] | Should-Be 'RuntimeException: f1 message' + $r.Message[0] | Should-BeString 'RuntimeException: f1 message' } if ((GetPesterOS) -ne 'Windows') { It 'produces correct trace lines.' { if ($hasStackTrace) { - $r.Trace[0] | Should-Be "at f1, ${testPath}:2" - $r.Trace[1] | Should-Be "at f2, ${testPath}:5" - $r.Trace[2] | Should-Be "at , ${testPath}:7" - $r.Trace[3] | Should-Be "at , ${PSCommandPath}:244" + $r.Trace[0] | Should-BeString "at f1, ${testPath}:2" + $r.Trace[1] | Should-BeString "at f2, ${testPath}:5" + $r.Trace[2] | Should-BeString "at , ${testPath}:7" + $r.Trace[3] | Should-BeString "at , ${PSCommandPath}:244" $r.Trace.Count | Should-Be 4 } } @@ -269,10 +269,10 @@ InModuleScope -ModuleName Pester -ScriptBlock { else { It 'produces correct trace lines.' { if ($hasStackTrace) { - $r.Trace[0] | Should-Be "at f1, ${testPath}:2" - $r.Trace[1] | Should-Be "at f2, ${testPath}:5" - $r.Trace[2] | Should-Be "at , ${testPath}:7" - $r.Trace[3] | Should-Be "at , ${PSCommandPath}:244" + $r.Trace[0] | Should-BeString "at f1, ${testPath}:2" + $r.Trace[1] | Should-BeString "at f2, ${testPath}:5" + $r.Trace[2] | Should-BeString "at , ${testPath}:7" + $r.Trace[3] | Should-BeString "at , ${PSCommandPath}:244" $r.Trace.Count | Should-Be 4 } } @@ -280,7 +280,7 @@ InModuleScope -ModuleName Pester -ScriptBlock { It 'produces correct trace lines.' { if (-not $hasStackTrace) { - $r.Trace[0] | Should-Be "at line: 2 in $testPath" + $r.Trace[0] | Should-BeString "at line: 2 in $testPath" $r.Trace.Count | Should-Be 1 } } @@ -319,21 +319,21 @@ InModuleScope -ModuleName Pester -ScriptBlock { It 'produces correct message lines.' { if (6 -ge $PSVersionTable.PSVersion.Major) { - $r.Message[0] | Should-Be 'ArgumentException: inner message' - $r.Message[1] | Should-Be 'Parameter name: param_name' - $r.Message[2] | Should-Be 'FormatException: outer message' + $r.Message[0] | Should-BeString 'ArgumentException: inner message' + $r.Message[1] | Should-BeString 'Parameter name: param_name' + $r.Message[2] | Should-BeString 'FormatException: outer message' } else { - $r.Message[0] | Should-Be "ArgumentException: inner message (Parameter 'param_name')" - $r.Message[1] | Should-Be 'FormatException: outer message' + $r.Message[0] | Should-BeString "ArgumentException: inner message (Parameter 'param_name')" + $r.Message[1] | Should-BeString 'FormatException: outer message' } } if ((GetPesterOS) -ne 'Windows') { It 'produces correct trace line.' { if ($hasStackTrace) { - $r.Trace[0] | Should-Be "at , $testPath`:10" - $r.Trace[1] | Should-Be "at , $PSCommandPath`:310" + $r.Trace[0] | Should-BeString "at , $testPath`:10" + $r.Trace[1] | Should-BeString "at , $PSCommandPath`:310" $r.Trace.Count | Should-Be 2 } } @@ -341,15 +341,15 @@ InModuleScope -ModuleName Pester -ScriptBlock { else { It 'produces correct trace line.' { if ($hasStackTrace) { - $r.Trace[0] | Should-Be "at , $testPath`:10" - $r.Trace[1] | Should-Be "at , $PSCommandPath`:310" + $r.Trace[0] | Should-BeString "at , $testPath`:10" + $r.Trace[1] | Should-BeString "at , $PSCommandPath`:310" $r.Trace.Count | Should-Be 2 } } } It 'produces correct trace line.' { if (-not $hasStackTrace) { - $r.Trace[0] | Should-Be "at line: 10 in $testPath" + $r.Trace[0] | Should-BeString "at line: 10 in $testPath" $r.Trace.Count | Should-Be 1 } } diff --git a/tst/functions/Set-ItResult.Tests.ps1 b/tst/functions/Set-ItResult.Tests.ps1 index 4750e8081..6a7fd6753 100644 --- a/tst/functions/Set-ItResult.Tests.ps1 +++ b/tst/functions/Set-ItResult.Tests.ps1 @@ -6,7 +6,7 @@ Describe "Testing Set-ItResult" { Set-ItResult -Inconclusive -Because "we are setting it to inconclusive" } catch { - $_.FullyQualifiedErrorID | Should-Be "PesterTestInconclusive" + $_.FullyQualifiedErrorID | Should-BeString "PesterTestInconclusive" } } @@ -15,7 +15,7 @@ Describe "Testing Set-ItResult" { Set-ItResult -Skipped -Because "we are forcing it to skip" } catch { - $_.FullyQualifiedErrorID | Should-Be "PesterTestSkipped" + $_.FullyQualifiedErrorID | Should-BeString "PesterTestSkipped" } } @@ -24,7 +24,7 @@ Describe "Testing Set-ItResult" { Set-ItResult -Skipped -Because "we are forcing it to skip" } catch { - $_.Exception.Message | Should-Be "is skipped, because we are forcing it to skip" + $_.Exception.Message | Should-BeString "is skipped, because we are forcing it to skip" } } @@ -33,7 +33,7 @@ Describe "Testing Set-ItResult" { Set-ItResult -Skipped } catch { - $_.FullyQualifiedErrorID | Should-Be "PesterTestSkipped" + $_.FullyQualifiedErrorID | Should-BeString "PesterTestSkipped" } } diff --git a/tst/functions/SetupTeardown.Tests.ps1 b/tst/functions/SetupTeardown.Tests.ps1 index 515b6a53e..c7e3dfb77 100644 --- a/tst/functions/SetupTeardown.Tests.ps1 +++ b/tst/functions/SetupTeardown.Tests.ps1 @@ -8,12 +8,12 @@ Describe 'Describe-Scoped Test Case setup' { $testVariable = 'Set in Describe' It 'Assigns the correct value in first test' { - $testVariable | Should-Be 'From BeforeEach' + $testVariable | Should-BeString 'From BeforeEach' $testVariable = 'Set in It' } It 'Assigns the correct value in subsequent tests' { - $testVariable | Should-Be 'From BeforeEach' + $testVariable | Should-BeString 'From BeforeEach' } } @@ -25,12 +25,12 @@ Describe 'Describe-Scoped Test Case setup using named ScriptBlock-parameter' { $testVariable = 'Set in Describe' It 'Assigns the correct value in first test' { - $testVariable | Should-Be 'From BeforeEach' + $testVariable | Should-BeString 'From BeforeEach' $testVariable = 'Set in It' } It 'Assigns the correct value in subsequent tests' { - $testVariable | Should-Be 'From BeforeEach' + $testVariable | Should-BeString 'From BeforeEach' } } @@ -44,12 +44,12 @@ Describe 'Context-scoped Test Case setup' { } It 'Assigns the correct value inside the context' { - $testVariable | Should-Be 'From BeforeEach' + $testVariable | Should-BeString 'From BeforeEach' } } It 'Reports the original value after the Context' { - $testVariable | Should-Be 'Set in Describe' + $testVariable | Should-BeString 'Set in Describe' } } @@ -64,7 +64,7 @@ Describe 'Multiple Test Case setup blocks' { Context 'The context' { It 'Executes Describe setup blocks first, then Context block' { - $testVariable | Should-Be 'Set in Context BeforeEach' + $testVariable | Should-BeString 'Set in Context BeforeEach' } BeforeEach { @@ -73,7 +73,7 @@ Describe 'Multiple Test Case setup blocks' { } It 'Continues to execute Describe setup blocks after the Context' { - $testVariable | Should-Be 'Set in Describe BeforeEach' + $testVariable | Should-BeString 'Set in Describe BeforeEach' } } @@ -87,11 +87,11 @@ Describe 'Describe-scoped Test Case teardown' { } It 'Does not modify the variable before the first test' { - $testVariable | Should-Be 'Set in Describe' + $testVariable | Should-BeString 'Set in Describe' } It 'Keeps the describe variable after the first test' { - $testVariable | Should-Be 'Set in Describe' + $testVariable | Should-BeString 'Set in Describe' } } @@ -115,7 +115,7 @@ Describe 'Multiple Test Case teardown blocks' { It 'Performs a test in Context' { "some output" } It 'Executes Describe teardown blocks after Context teardown blocks' { - $container.Value | Should-Be 'Set in Describe AfterEach' + $container.Value | Should-BeString 'Set in Describe AfterEach' } } } diff --git a/tst/functions/TestDrive.Tests.ps1 b/tst/functions/TestDrive.Tests.ps1 index 25fedefbc..93ae72a79 100644 --- a/tst/functions/TestDrive.Tests.ps1 +++ b/tst/functions/TestDrive.Tests.ps1 @@ -195,7 +195,7 @@ Describe 'Repair missing TestDrive' { Context 'Broken' { It 'Removes TestDrive' { Should -Exist -ActualValue $tempFilePath - Get-Content -Path $tempFilePath | Should-Be 'Hello' + Get-Content -Path $tempFilePath | Should-BeString 'Hello' # Remove PSDrive Remove-PSDrive -Name 'TestDrive' @@ -214,7 +214,7 @@ Describe 'Repair missing TestDrive' { Should -Exist -ActualValue $tempFilePath # Verify PSDrive - Get-Content -Path "TestDrive:/$tempFileName" | Should-Be 'Hello' + Get-Content -Path "TestDrive:/$tempFileName" | Should-BeString 'Hello' } } } @@ -228,7 +228,7 @@ Describe 'Running Pester in Pester' { It 'File exists before' { Should -Exist -ActualValue $tempFilePath - Get-Content -Path $tempFilePath | Should-Be 'Hello' + Get-Content -Path $tempFilePath | Should-BeString 'Hello' } It 'Works in nested run' { @@ -236,7 +236,7 @@ Describe 'Running Pester in Pester' { Describe 'Nested' { It 'Files created in outer run are available using absolute path' { Should -Exist -ActualValue $TempFilePath - Get-Content -Path $TempFilePath | Should-Be 'Hello' + Get-Content -Path $TempFilePath | Should-BeString 'Hello' } It 'TestDrive PSDrive and $TestDrive points to clean location' { @@ -252,17 +252,17 @@ Describe 'Running Pester in Pester' { $c = New-PesterContainer -ScriptBlock $sb -Data @{ TempFilePath = $tempFilePath } $innerRun = Invoke-Pester -Container $c -PassThru -Output None - $innerRun.Result | Should-Be 'Passed' + $innerRun.Result | Should-BeString 'Passed' $innerRun.PassedCount | Should-Be 2 } It 'TestDrive PSDrive and $TestDrive point to original location' { $originalTestDrive = Split-Path $tempFilePath - $TestDrive | Should-Be $originalTestDrive + $TestDrive | Should-BeString $originalTestDrive $tempFilePath2 = Join-Path -Path 'TestDrive:/' -ChildPath $tempFileName Should -Exist -ActualValue $tempFilePath2 - Get-Content -Path $tempFilePath2 | Should-Be 'Hello' + Get-Content -Path $tempFilePath2 | Should-BeString 'Hello' } } diff --git a/tst/functions/TestRegistry.Tests.ps1 b/tst/functions/TestRegistry.Tests.ps1 index 99d7b57d7..04fb8a39a 100644 --- a/tst/functions/TestRegistry.Tests.ps1 +++ b/tst/functions/TestRegistry.Tests.ps1 @@ -105,7 +105,7 @@ Describe 'Running Pester in Invoke-Pester' { $c = New-PesterContainer -ScriptBlock $sb -Data @{ TempKeyPath = $tempValue.PSPath; TempValueName = $tempValueName } $innerRun = Invoke-Pester -Container $c -PassThru -Output None - $innerRun.Result | Should-Be 'Passed' + $innerRun.Result | Should-BeString 'Passed' $innerRun.PassedCount | Should-Be 2 } diff --git a/tst/functions/TestResults.Tests.ps1 b/tst/functions/TestResults.Tests.ps1 index 28677ac61..adeeb150e 100644 --- a/tst/functions/TestResults.Tests.ps1 +++ b/tst/functions/TestResults.Tests.ps1 @@ -29,7 +29,7 @@ InPesterModuleScope { #using the string formatter here to know how the string will be output to screen $Result = { Get-TestTime -Tests $TestResult | Out-String -Stream } | Using-Culture -Culture de-DE - $Result | Should-Be "3.5" + $Result | Should-BeString "3.5" } It "Time is measured in seconds with 0,1 millisecond as lowest value" { $TestResult = New-Object -TypeName psObject -Property @{ Time = [timespan]1000 } @@ -85,7 +85,7 @@ InPesterModuleScope { $powershellPath = Get-Command -Name $CommandToTest | Select-Object -ExpandProperty 'Definition' $powershellPath | Should-NotBeEmptyString - GetFullPath $powershellPath | Should-Be $powershellPath + GetFullPath $powershellPath | Should-BeString $powershellPath } Pop-Location @@ -125,8 +125,8 @@ InPesterModuleScope { $result = Get-RunTimeEnvironment - $result['platform'] | Should-Be 'Unknown' - $result['os-version'] | Should-Be '0.0.0.0' + $result['platform'] | Should-BeString 'Unknown' + $result['os-version'] | Should-BeString '0.0.0.0' } finally { $SafeCommands['Get-CimInstance'] = $originalCim From 84afeec02540e8100b62f254f692ff599e0bd91b Mon Sep 17 00:00:00 2001 From: Frode Flaten <3436158+fflaten@users.noreply.github.com> Date: Thu, 16 Jul 2026 14:45:34 +0000 Subject: [PATCH 4/6] Fix remaining in Pester.Tests.ps1 --- tst/Pester.Tests.ps1 | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/tst/Pester.Tests.ps1 b/tst/Pester.Tests.ps1 index 1490a84b8..eb281758c 100644 --- a/tst/Pester.Tests.ps1 +++ b/tst/Pester.Tests.ps1 @@ -22,7 +22,7 @@ Describe -Tags 'VersionChecks' "Pester manifest and changelog" { } It "has a valid name in the manifest" { - $script:manifest.Name | Should-Be Pester + $script:manifest.Name | Should-BeString 'Pester' } It "has a valid guid in the manifest" { @@ -86,7 +86,7 @@ if ($PSVersionTable.PSVersion.Major -ge 3) { } Context 'A Context' { It 'Performs a successful test' { - $true | Should-Be $true + $true | Should-BeTrue } } @@ -127,7 +127,7 @@ if ($PSVersionTable.PSVersion.Major -ge 3) { } It 'The SafeCommands table contains all commands that are called from the module' { - $missingSafeCommands | Should-Be $null + $missingSafeCommands | Should-BeNull } } } @@ -247,8 +247,8 @@ InPesterModuleScope { $paths = $result | Select-Object -ExpandProperty FullName $testDrive = (Get-PSDrive TestDrive).Root - ($paths -contains (Join-Path $testDrive "SomeFile.Tests.ps1")) | Should-Be $true - ($paths -contains (Join-Path $testDrive "SomeOtherFile.Tests.ps1")) | Should-Be $true + ($paths -contains (Join-Path $testDrive "SomeFile.Tests.ps1")) | Should-BeTrue + ($paths -contains (Join-Path $testDrive "SomeOtherFile.Tests.ps1")) | Should-BeTrue } It 'Finds only *.Tests.ps1 files when the path refers to a directory and does not contain wildcards' { @@ -258,8 +258,8 @@ InPesterModuleScope { $paths = $result | Select-Object -ExpandProperty FullName $testDrive = (Get-PSDrive TestDrive).Root - ($paths -contains (Join-Path $testDrive "SomeFile.Tests.ps1")) | Should-Be $true - ($paths -contains (Join-Path $testDrive "SomeOtherFile.Tests.ps1")) | Should-Be $true + ($paths -contains (Join-Path $testDrive "SomeFile.Tests.ps1")) | Should-BeTrue + ($paths -contains (Join-Path $testDrive "SomeOtherFile.Tests.ps1")) | Should-BeTrue } It 'Deduplicates filepaths when the provided paths overlaps' { From aea1105ec973e4dbef8a2f6f4f24457880345e1f Mon Sep 17 00:00:00 2001 From: Frode Flaten <3436158+fflaten@users.noreply.github.com> Date: Thu, 16 Jul 2026 14:48:39 +0000 Subject: [PATCH 5/6] Fix TestDrive test --- tst/functions/TestDrive.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tst/functions/TestDrive.Tests.ps1 b/tst/functions/TestDrive.Tests.ps1 index 93ae72a79..b405d4347 100644 --- a/tst/functions/TestDrive.Tests.ps1 +++ b/tst/functions/TestDrive.Tests.ps1 @@ -258,7 +258,7 @@ Describe 'Running Pester in Pester' { It 'TestDrive PSDrive and $TestDrive point to original location' { $originalTestDrive = Split-Path $tempFilePath - $TestDrive | Should-BeString $originalTestDrive + $TestDrive.FullName | Should-BeString $originalTestDrive $tempFilePath2 = Join-Path -Path 'TestDrive:/' -ChildPath $tempFileName Should -Exist -ActualValue $tempFilePath2 From 9ae311c8f5639627002ba9fb9e832d61d67a111b Mon Sep 17 00:00:00 2001 From: Frode Flaten <3436158+fflaten@users.noreply.github.com> Date: Thu, 16 Jul 2026 15:56:01 +0000 Subject: [PATCH 6/6] Fix test on Windows --- tst/functions/Mock.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tst/functions/Mock.Tests.ps1 b/tst/functions/Mock.Tests.ps1 index 8bac9bad7..5b05d654e 100644 --- a/tst/functions/Mock.Tests.ps1 +++ b/tst/functions/Mock.Tests.ps1 @@ -1361,7 +1361,7 @@ Describe 'Mocking Cmdlets with typed provider dynamic parameters' { # the mock we get a type-conversion binding error; when it is missing (the #1137 bug) we get # a NamedParameterNotFound error instead. We assert the former to prove the parameter exists. $splat = @{ Path = 'TestDrive:\a'; Destination = 'TestDrive:\b'; $Name = 'not-a-session' } - $err = { Copy-Item @splat } | Should-Throw -PassThru + $err = { Copy-Item @splat } | Should-Throw $err.FullyQualifiedErrorId | Should-NotBeLikeString 'NamedParameterNotFound*' -Because "the $Name dynamic parameter should be available on the mocked Copy-Item (#1137)" } }