diff --git a/src/functions/assert/String/Should-BeString.ps1 b/src/functions/assert/String/Should-BeString.ps1 index 1d05bbfbe..c6e2eaa73 100644 --- a/src/functions/assert/String/Should-BeString.ps1 +++ b/src/functions/assert/String/Should-BeString.ps1 @@ -3,7 +3,8 @@ [String]$Expected, $Actual, [switch]$CaseSensitive, - [switch]$IgnoreWhitespace + [switch]$IgnoreWhitespace, + [switch]$TrimWhitespace ) if ($Actual -isnot [string]) { @@ -15,6 +16,11 @@ $Actual = $Actual -replace '\s' } + if ($TrimWhitespace) { + $Expected = $Expected -replace '^\s+|\s+$' + $Actual = $Actual -replace '^\s+|\s+$' + } + if (-not $CaseSensitive) { $Expected -eq $Actual } @@ -43,6 +49,9 @@ function Should-BeString { .PARAMETER IgnoreWhitespace Indicates that the comparison should ignore whitespace. + .PARAMETER TrimWhitespace + Trims whitespace at the start and end of the string. + .PARAMETER Because The reason why the actual value should be equal to the expected value. @@ -77,13 +86,14 @@ function Should-BeString { [String]$Expected, [String]$Because, [switch]$CaseSensitive, - [switch]$IgnoreWhitespace + [switch]$IgnoreWhitespace, + [switch]$TrimWhitespace ) $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput $Actual = $collectedInput.Actual - $stringsAreEqual = Test-StringEqual -Expected $Expected -Actual $Actual -CaseSensitive:$CaseSensitive -IgnoreWhitespace:$IgnoreWhiteSpace + $stringsAreEqual = Test-StringEqual -Expected $Expected -Actual $Actual -CaseSensitive:$CaseSensitive -IgnoreWhitespace:$IgnoreWhiteSpace -TrimWhitespace:$TrimWhitespace if (-not ($stringsAreEqual)) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected , but got ." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) diff --git a/tst/functions/assert/String/Should-BeString.Tests.ps1 b/tst/functions/assert/String/Should-BeString.Tests.ps1 index f90ca04ce..db9e702fe 100644 --- a/tst/functions/assert/String/Should-BeString.Tests.ps1 +++ b/tst/functions/assert/String/Should-BeString.Tests.ps1 @@ -97,6 +97,19 @@ Describe "Should-BeString" { It "Can compare strings without whitespace" { Should-BeString -Expected " a b c " -Actual "abc" -IgnoreWhitespace } + + It "Can compare strings without whitespace at the start or end" -ForEach @( + @{ Value = " abc" } + @{ Value = "abc " } + @{ Value = "abc`t" } + @{ Value = "`tabc" } + ) { + " abc " | Should-BeString -Expected "abc" -TrimWhitespace + } + + It "Trimming whitespace does not remove it from inside of the string" { + { "a bc" | Should-BeString -Expected "abc" -TrimWhitespace } | Verify-AssertionFailed + } } It "Can be called with positional parameters" {