diff --git a/tst/Format2.Tests.ps1 b/tst/Format2.Tests.ps1 index 0ff6432d4..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 @@ -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..5c9044241 100644 --- a/tst/Help.Tests.ps1 +++ b/tst/Help.Tests.ps1 @@ -12,36 +12,37 @@ 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-BeString $_.Name + $help.Category | Should-Be $_.CommandType + $help.ModuleName | Should-BeString $moduleName } 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 -Not -Match "^\s*$($_.Name)((\s+\[+?-\w+)|$)" + $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 } $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' { - $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 | 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' { @@ -53,7 +54,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 +75,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..eb281758c 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-BeString 'Pester' } 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)) { @@ -39,12 +39,12 @@ 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" { - $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" { @@ -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-BeTrue } } 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-BeNull } } } @@ -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 @() } } @@ -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-BeString '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-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' { $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-BeTrue + ($paths -contains (Join-Path $testDrive "SomeOtherFile.Tests.ps1")) | Should-BeTrue } 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..8a53b7646 100644 --- a/tst/PesterConfiguration.Tests.ps1 +++ b/tst/PesterConfiguration.Tests.ps1 @@ -12,17 +12,17 @@ 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.FormatViewDefinition.Count | Should -Be 1 - $formatData.FormatViewDefinition[0].Name | Should -BeExactly $section.FullName - $formatData.FormatViewDefinition[0].Control | Should -BeOfType ([System.Management.Automation.ListControl]) + $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]) } 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 @() } } @@ -32,22 +32,22 @@ 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.FormatViewDefinition.Count | Should -Be 1 - $formatData.FormatViewDefinition[0].Name | Should -BeExactly 'Pester.Option' - $formatData.FormatViewDefinition[0].Control | Should -BeOfType ([System.Management.Automation.TableControl]) + $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]) } 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..1449c2868 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,58 +219,58 @@ 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-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' { - $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-BeString "'I am the nested function.'" } 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' - $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 -BeNullOrEmpty - $coverageReport.MissedCommands[2].Class | Should -BeNullOrEmpty + $coverageReport.HitCommands[9].Class | Should-BeNull + $coverageReport.MissedCommands[2].Class | Should-BeNull } } 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' { @@ -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-BeString '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-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" } } } @@ -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 + $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-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' { @@ -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-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' } } @@ -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,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-BeNull } 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-BeNull } } @@ -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' } } @@ -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-BeString '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-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' } } @@ -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-BeString '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-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' } } } @@ -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-BeString "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-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 } @@ -2662,7 +2662,7 @@ Describe "Mock definition output" { function a () {} $output = Mock a { } - $output | Should -Be $null + $output | Should-BeNull } } @@ -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' } } @@ -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-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" } } } @@ -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-BeString "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-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 -Color 'zzz' } | Should -Throw -ErrorId '*ParameterArgumentValidationError*' + 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" { @@ -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-BeNull -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-BeNull -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-BeString "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-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' - { Should -InvokeVerifiable } | Should -Throw + 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' { @@ -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-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' { @@ -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-BeString '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-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-Fixture.Tests.ps1 b/tst/functions/New-Fixture.Tests.ps1 index 459dd6908..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" { @@ -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..8826722e3 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-BeString 'Jakub' + $mockObject.GetName() | Should-BeString '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-BeString 'MyInternalClass' + $mock.GetName() | Should-BeString '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-BeString "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-BeString "killed" + $mockObject._Kill[-1].Call | Should-Be 1 + $mockObject._Kill[-1].Arguments | Should-BeNull + $mockObject.Kill($true) | Should-BeString "killed" + $mockObject._Kill[-1].Call | Should-Be 2 + $mockObject._Kill[-1].Arguments | Should-BeTrue } 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-BeString "connect" + $mockObject.Close() | Should-BeString "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..d03dea2d1 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-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' } } } - 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-BeString 'RuntimeException: message' + $r.Message.Count | Should-Be 1 } It 'failed should produces correct message lines.' { try { - 'One' | Should -be 'Two' -ErrorAction Stop + 'One' | Should-BeString '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-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 -match "'One' | Should -be 'Two'" - $r.Trace.Count | Should -be 1 + $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... # 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-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.Count | Should -be 4 + $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 } } } 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-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 } } } 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-BeString "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-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.Count | Should -be 2 + $r.Trace[0] | Should-BeString "at , $testPath`:10" + $r.Trace[1] | Should-BeString "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-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.Count | Should -be 1 + $r.Trace[0] | Should-BeString "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 } } } @@ -684,9 +684,9 @@ 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 - if ($param.Aliases) { $param.Aliases | Should -BeIn $WritePesterHostMessageParam[$param.Name].Aliases } + $WritePesterHostMessageParam.Keys | Should-ContainCollection $param.Name + $WritePesterHostMessageParam[$param.Name].ParameterType | Should-Be $param.ParameterType + if ($param.Aliases) { $WritePesterHostMessageParam[$param.Name].Aliases | Sort-Object | Should-ContainCollection ($param.Aliases | Sort-Object) } } } } diff --git a/tst/functions/Set-ItResult.Tests.ps1 b/tst/functions/Set-ItResult.Tests.ps1 index 91622e4be..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,16 +33,16 @@ Describe "Testing Set-ItResult" { Set-ItResult -Skipped } catch { - $_.FullyQualifiedErrorID | Should -Be "PesterTestSkipped" + $_.FullyQualifiedErrorID | Should-BeString "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..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' } } } @@ -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..b405d4347 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,15 +195,15 @@ 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' - { 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 - $TestDrive | Should -BeNullOrEmpty + $TestDrive | Should-BeNull } } @@ -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,33 +236,33 @@ 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' { # 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 + Get-ChildItem -Path 'TestDrive:/' | Should-BeNull } } } $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-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.FullName | 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 94ff38b50..04fb8a39a 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,29 +87,29 @@ 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' { - (Get-Item -Path 'TestRegistry:/').Property | Should -BeNullOrEmpty + (Get-Item -Path 'TestRegistry:/').Property | Should-BeNull } } } $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-BeString '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..adeeb150e 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-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 } - 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 + $powershellPath | Should-NotBeEmptyString - GetFullPath $powershellPath | Should -Be $powershellPath + GetFullPath $powershellPath | Should-BeString $powershellPath } Pop-Location @@ -99,15 +99,15 @@ 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['os-version'] | Should -Not -BeNullOrEmpty - $result['platform'] | Should -Not -BeNullOrEmpty + $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-NotBeEmptyString + $result['platform'] | Should-NotBeEmptyString } It "Falls back to Unknown OS info when Get-CimInstance returns null (access denied)" -Skip:(-not $IsWindows) { @@ -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 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 } }