From 567549c56175668af3b5700dbc323b8a06f1f26d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Mon, 1 Apr 2024 22:41:43 +0200 Subject: [PATCH 01/55] Copy paste assert --- src/TypeClass.ps1 | 4 + src/functions/assert/Boolean/Assert-False.ps1 | 16 + src/functions/assert/Boolean/Assert-True.ps1 | 16 + .../assert/Collection/Assert-All.ps1 | 41 + .../assert/Collection/Assert-Any.ps1 | 19 + .../assert/Collection/Assert-Contain.ps1 | 19 + .../assert/Collection/Assert-NotContain.ps1 | 19 + .../assert/Common/Add-AssertionException.ps1 | 2 + .../assert/Common/AssertionException.cs | 27 + src/functions/assert/Common/Collect-Input.ps1 | 14 + .../Common/Ensure-ExpectedIsNotCollection.ps1 | 12 + .../assert/Common/Get-AssertionMessage.ps1 | 43 + .../Common/Get-CustomFailureMessage.ps1 | 6 + .../assert/Equivalence/Assert-Equivalent.ps1 | 758 ++++++++++++++++++ .../assert/Exception/Assert-Throw.ps1 | 121 +++ src/functions/assert/General/Assert-Equal.ps1 | 19 + .../assert/General/Assert-GreaterThan.ps1 | 18 + .../General/Assert-GreaterThanOrEqual.ps1 | 18 + .../assert/General/Assert-LessThan.ps1 | 18 + .../assert/General/Assert-LessThanOrEqual.ps1 | 18 + .../assert/General/Assert-NotEqual.ps1 | 18 + .../assert/General/Assert-NotNull.ps1 | 16 + .../assert/General/Assert-NotSame.ps1 | 18 + .../assert/General/Assert-NotType.ps1 | 19 + src/functions/assert/General/Assert-Null.ps1 | 16 + src/functions/assert/General/Assert-Same.ps1 | 23 + src/functions/assert/General/Assert-Type.ps1 | 19 + src/functions/assert/String/Assert-Like.ps1 | 60 ++ .../assert/String/Assert-NotLike.ps1 | 61 ++ .../assert/String/Assert-StringEqual.ps1 | 59 ++ .../assert/String/Assert-StringNotEqual.ps1 | 31 + .../assert/Boolean/Assert-False.Tests.ps1 | 44 + .../assert/Boolean/Assert-True.Tests.ps1 | 40 + .../assert/Collection/Assert-All.Tests.ps1 | 43 + .../assert/Collection/Assert-Any.Tests.ps1 | 40 + .../Collection/Assert-Contain.Tests.ps1 | 25 + .../Collection/Assert-NotContain.Tests.ps1 | 25 + .../Ensure-ExpectedIsNotCollection.Tests.ps1 | 18 + .../Common/Get-AssertionMessage.Tests.ps1 | 51 ++ .../Assert-Equivalent.Options.Tests.ps1 | 380 +++++++++ .../Equivalence/Assert-Equivalent.Tests.ps1 | 483 +++++++++++ .../assert/Exception/Assert-Throw.Tests.ps1 | 233 ++++++ .../assert/General/Assert-Equal.Tests.ps1 | 91 +++ .../General/Assert-GreaterThan.Tests.ps1 | 109 +++ .../Assert-GreaterThanOrEqual.Tests.ps1 | 109 +++ .../assert/General/Assert-LessThan.Tests.ps1 | 107 +++ .../General/Assert-LessThanOrEqual.Tests.ps1 | 107 +++ .../assert/General/Assert-NotEqual.Tests.ps1 | 89 ++ .../assert/General/Assert-NotNull.Tests.ps1 | 19 + .../assert/General/Assert-NotSame.Tests.ps1 | 45 ++ .../assert/General/Assert-NotType.Tests.ps1 | 19 + .../assert/General/Assert-Null.Tests.ps1 | 19 + .../assert/General/Assert-Same.Tests.ps1 | 59 ++ .../assert/General/Assert-Type.Tests.ps1 | 19 + .../assert/Get-CustomFailureMessage.Tests.ps1 | 27 + .../assert/String/Assert-Like.Tests.ps1 | 137 ++++ .../assert/String/Assert-NotLike.Tests.ps1 | 137 ++++ .../String/Assert-StringEqual.Tests.ps1 | 124 +++ .../String/Assert-StringNotEqual.Tests.ps1 | 58 ++ tst/functions/assert/TestHelpers.psm1 | 11 + 60 files changed, 4216 insertions(+) create mode 100644 src/functions/assert/Boolean/Assert-False.ps1 create mode 100644 src/functions/assert/Boolean/Assert-True.ps1 create mode 100644 src/functions/assert/Collection/Assert-All.ps1 create mode 100644 src/functions/assert/Collection/Assert-Any.ps1 create mode 100644 src/functions/assert/Collection/Assert-Contain.ps1 create mode 100644 src/functions/assert/Collection/Assert-NotContain.ps1 create mode 100644 src/functions/assert/Common/Add-AssertionException.ps1 create mode 100644 src/functions/assert/Common/AssertionException.cs create mode 100644 src/functions/assert/Common/Collect-Input.ps1 create mode 100644 src/functions/assert/Common/Ensure-ExpectedIsNotCollection.ps1 create mode 100644 src/functions/assert/Common/Get-AssertionMessage.ps1 create mode 100644 src/functions/assert/Common/Get-CustomFailureMessage.ps1 create mode 100644 src/functions/assert/Equivalence/Assert-Equivalent.ps1 create mode 100644 src/functions/assert/Exception/Assert-Throw.ps1 create mode 100644 src/functions/assert/General/Assert-Equal.ps1 create mode 100644 src/functions/assert/General/Assert-GreaterThan.ps1 create mode 100644 src/functions/assert/General/Assert-GreaterThanOrEqual.ps1 create mode 100644 src/functions/assert/General/Assert-LessThan.ps1 create mode 100644 src/functions/assert/General/Assert-LessThanOrEqual.ps1 create mode 100644 src/functions/assert/General/Assert-NotEqual.ps1 create mode 100644 src/functions/assert/General/Assert-NotNull.ps1 create mode 100644 src/functions/assert/General/Assert-NotSame.ps1 create mode 100644 src/functions/assert/General/Assert-NotType.ps1 create mode 100644 src/functions/assert/General/Assert-Null.ps1 create mode 100644 src/functions/assert/General/Assert-Same.ps1 create mode 100644 src/functions/assert/General/Assert-Type.ps1 create mode 100644 src/functions/assert/String/Assert-Like.ps1 create mode 100644 src/functions/assert/String/Assert-NotLike.ps1 create mode 100644 src/functions/assert/String/Assert-StringEqual.ps1 create mode 100644 src/functions/assert/String/Assert-StringNotEqual.ps1 create mode 100644 tst/functions/assert/Boolean/Assert-False.Tests.ps1 create mode 100644 tst/functions/assert/Boolean/Assert-True.Tests.ps1 create mode 100644 tst/functions/assert/Collection/Assert-All.Tests.ps1 create mode 100644 tst/functions/assert/Collection/Assert-Any.Tests.ps1 create mode 100644 tst/functions/assert/Collection/Assert-Contain.Tests.ps1 create mode 100644 tst/functions/assert/Collection/Assert-NotContain.Tests.ps1 create mode 100644 tst/functions/assert/Common/Ensure-ExpectedIsNotCollection.Tests.ps1 create mode 100644 tst/functions/assert/Common/Get-AssertionMessage.Tests.ps1 create mode 100644 tst/functions/assert/Equivalence/Assert-Equivalent.Options.Tests.ps1 create mode 100644 tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 create mode 100644 tst/functions/assert/Exception/Assert-Throw.Tests.ps1 create mode 100644 tst/functions/assert/General/Assert-Equal.Tests.ps1 create mode 100644 tst/functions/assert/General/Assert-GreaterThan.Tests.ps1 create mode 100644 tst/functions/assert/General/Assert-GreaterThanOrEqual.Tests.ps1 create mode 100644 tst/functions/assert/General/Assert-LessThan.Tests.ps1 create mode 100644 tst/functions/assert/General/Assert-LessThanOrEqual.Tests.ps1 create mode 100644 tst/functions/assert/General/Assert-NotEqual.Tests.ps1 create mode 100644 tst/functions/assert/General/Assert-NotNull.Tests.ps1 create mode 100644 tst/functions/assert/General/Assert-NotSame.Tests.ps1 create mode 100644 tst/functions/assert/General/Assert-NotType.Tests.ps1 create mode 100644 tst/functions/assert/General/Assert-Null.Tests.ps1 create mode 100644 tst/functions/assert/General/Assert-Same.Tests.ps1 create mode 100644 tst/functions/assert/General/Assert-Type.Tests.ps1 create mode 100644 tst/functions/assert/Get-CustomFailureMessage.Tests.ps1 create mode 100644 tst/functions/assert/String/Assert-Like.Tests.ps1 create mode 100644 tst/functions/assert/String/Assert-NotLike.Tests.ps1 create mode 100644 tst/functions/assert/String/Assert-StringEqual.Tests.ps1 create mode 100644 tst/functions/assert/String/Assert-StringNotEqual.Tests.ps1 create mode 100644 tst/functions/assert/TestHelpers.psm1 diff --git a/src/TypeClass.ps1 b/src/TypeClass.ps1 index 9319cdd64..4c3f6f79e 100644 --- a/src/TypeClass.ps1 +++ b/src/TypeClass.ps1 @@ -39,3 +39,7 @@ function Is-Object ($Value) { -not ($null -eq $Value -or (Is-Value -Value $Value) -or (Is-Collection -Value $Value)) } + +function Is-DataRow ($Value) { + $Value -is [Data.DataRow] -or $Value.Psobject.TypeNames[0] -like '*System.Data.DataRow' +} diff --git a/src/functions/assert/Boolean/Assert-False.ps1 b/src/functions/assert/Boolean/Assert-False.ps1 new file mode 100644 index 000000000..4743659f2 --- /dev/null +++ b/src/functions/assert/Boolean/Assert-False.ps1 @@ -0,0 +1,16 @@ +function Assert-False { + param ( + [Parameter(ValueFromPipeline=$true)] + $Actual, + [String]$CustomMessage + ) + + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + if ($Actual) + { + $Message = Get-AssertionMessage -Expected $false -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be '' or falsy value 0, """", `$null, @()." + throw [Assertions.AssertionException]$Message + } + + $Actual +} \ No newline at end of file diff --git a/src/functions/assert/Boolean/Assert-True.ps1 b/src/functions/assert/Boolean/Assert-True.ps1 new file mode 100644 index 000000000..e1615a0eb --- /dev/null +++ b/src/functions/assert/Boolean/Assert-True.ps1 @@ -0,0 +1,16 @@ +function Assert-True{ + param ( + [Parameter(ValueFromPipeline=$true)] + $Actual, + [String]$CustomMessage + ) + + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + if (-not $Actual) + { + $Message = Get-AssertionMessage -Expected $true -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be '' or truthy value." + throw [Assertions.AssertionException]$Message + } + + $Actual +} \ No newline at end of file diff --git a/src/functions/assert/Collection/Assert-All.ps1 b/src/functions/assert/Collection/Assert-All.ps1 new file mode 100644 index 000000000..fe6ac1731 --- /dev/null +++ b/src/functions/assert/Collection/Assert-All.ps1 @@ -0,0 +1,41 @@ +function Assert-All { + [CmdletBinding()] + param ( + [Parameter(ValueFromPipeline=$true, Position=1)] + $Actual, + [Parameter(Position=0, Mandatory=$true)] + [scriptblock]$FilterScript, + [String]$CustomMessage + ) + + + $Expected = $FilterScript + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + # we are jumping between modules so I need to explicitly pass the _ variable + # simply using '&' won't work + # see: https://blogs.msdn.microsoft.com/sergey_babkins_blog/2014/10/30/calling-the-script-blocks-in-powershell/ + $actualFiltered = $Actual | ForEach-Object { + # powershell v4 code where we have InvokeWithContext available + # $underscore = Get-Variable _ + # $pass = $FilterScript.InvokeWithContext($null, $underscore, $null) + + # polyfill for PowerShell v2 + $PSCmdlet.SessionState.PSVariable.Set("_", $_) + $pass = & $FilterScript + + + if (-not $pass) { $_ } + } + + if ($actualFiltered) + { + $data = @{ + actualFiltered = $actualFiltered + actualFilteredCount = @($actualFiltered).Count + } + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Data $data -CustomMessage $CustomMessage -DefaultMessage "Expected all items in collection '' to pass filter '', but of them '' did not pass the filter." + throw [Assertions.AssertionException]$Message + } + + $Actual +} \ No newline at end of file diff --git a/src/functions/assert/Collection/Assert-Any.ps1 b/src/functions/assert/Collection/Assert-Any.ps1 new file mode 100644 index 000000000..0c24088d8 --- /dev/null +++ b/src/functions/assert/Collection/Assert-Any.ps1 @@ -0,0 +1,19 @@ +function Assert-Any { + param ( + [Parameter(ValueFromPipeline=$true, Position=1)] + $Actual, + [Parameter(Position=0, Mandatory=$true)] + [scriptblock]$FilterScript, + [String]$CustomMessage + ) + + $Expected = $FilterScript + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + if (-not ($Actual | Where-Object -FilterScript $FilterScript)) + { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected at least one item in collection '' to pass filter '', but none of the items passed the filter." + throw [Assertions.AssertionException]$Message + } + + $Actual +} \ No newline at end of file diff --git a/src/functions/assert/Collection/Assert-Contain.ps1 b/src/functions/assert/Collection/Assert-Contain.ps1 new file mode 100644 index 000000000..7b43635b1 --- /dev/null +++ b/src/functions/assert/Collection/Assert-Contain.ps1 @@ -0,0 +1,19 @@ +function Assert-Contain { + param ( + [Parameter(Position=1, ValueFromPipeline=$true)] + $Actual, + [Parameter(Position=0)] + $Expected, + [String]$CustomMessage + ) + + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + if ($Actual -notcontains $Expected) + { + $type = [string]$Expected + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be present in collection '', but it was not there." + throw [Assertions.AssertionException]$Message + } + + $Actual +} \ No newline at end of file diff --git a/src/functions/assert/Collection/Assert-NotContain.ps1 b/src/functions/assert/Collection/Assert-NotContain.ps1 new file mode 100644 index 000000000..dedd9845f --- /dev/null +++ b/src/functions/assert/Collection/Assert-NotContain.ps1 @@ -0,0 +1,19 @@ +function Assert-NotContain { + param ( + [Parameter(Position=1, ValueFromPipeline=$true)] + $Actual, + [Parameter(Position=0)] + $Expected, + [String]$CustomMessage + ) + + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + if ($Actual -contains $Expected) + { + $type = [string]$Expected + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to not be present in collection '', but it was there." + throw [Assertions.AssertionException]$Message + } + + $Actual +} \ No newline at end of file diff --git a/src/functions/assert/Common/Add-AssertionException.ps1 b/src/functions/assert/Common/Add-AssertionException.ps1 new file mode 100644 index 000000000..2ff593098 --- /dev/null +++ b/src/functions/assert/Common/Add-AssertionException.ps1 @@ -0,0 +1,2 @@ +$typeDefinition = Get-Content $PSScriptRoot/AssertionException.cs | Out-String +Add-Type -TypeDefinition $typeDefinition -WarningAction SilentlyContinue \ No newline at end of file diff --git a/src/functions/assert/Common/AssertionException.cs b/src/functions/assert/Common/AssertionException.cs new file mode 100644 index 000000000..3d82a1bdf --- /dev/null +++ b/src/functions/assert/Common/AssertionException.cs @@ -0,0 +1,27 @@ +using System; +using System.Runtime.Serialization; + +namespace Assertions +{ + [Serializable] + public class AssertionException : Exception + { + public AssertionException() + { + } + + public AssertionException(string message) : base(message) + { + } + + public AssertionException(string message, Exception inner) : base(message, inner) + { + } + + // protected AssertionException( + // SerializationInfo info, + // StreamingContext context) : base(info, context) + // { + // } + } +} \ No newline at end of file diff --git a/src/functions/assert/Common/Collect-Input.ps1 b/src/functions/assert/Common/Collect-Input.ps1 new file mode 100644 index 000000000..c25e8651e --- /dev/null +++ b/src/functions/assert/Common/Collect-Input.ps1 @@ -0,0 +1,14 @@ +function Collect-Input ($ParameterInput, $PipelineInput) +{ + #source: http://www.powertheshell.com/input_psv3/ + $collectedInput = @($PipelineInput) + + $isInPipeline = $collectedInput.Count -gt 0 + if ($isInPipeline) { + $collectedInput + } + else + { + $ParameterInput + } +} \ No newline at end of file diff --git a/src/functions/assert/Common/Ensure-ExpectedIsNotCollection.ps1 b/src/functions/assert/Common/Ensure-ExpectedIsNotCollection.ps1 new file mode 100644 index 000000000..98d9a3028 --- /dev/null +++ b/src/functions/assert/Common/Ensure-ExpectedIsNotCollection.ps1 @@ -0,0 +1,12 @@ +function Ensure-ExpectedIsNotCollection { + param( + $InputObject + ) + + if (Is-Collection $InputObject) + { + throw [ArgumentException]'You provided a collection to the -Expected parameter. Using a collection on the -Expected side is not allowed by this assertion, because it leads to unexpected behavior. Please use Assert-Any, Assert-All or some other specialized collection assertion.' + } + + $InputObject +} \ No newline at end of file diff --git a/src/functions/assert/Common/Get-AssertionMessage.ps1 b/src/functions/assert/Common/Get-AssertionMessage.ps1 new file mode 100644 index 000000000..8514ae7c7 --- /dev/null +++ b/src/functions/assert/Common/Get-AssertionMessage.ps1 @@ -0,0 +1,43 @@ +function Get-AssertionMessage ($Expected, $Actual, $Option, [hashtable]$Data = @{}, $CustomMessage, $DefaultMessage, [switch]$Pretty) +{ + if (-not $CustomMessage) + { + $CustomMessage = $DefaultMessage + } + + $expectedFormatted = Format-Nicely -Value $Expected -Pretty:$Pretty + $actualFormatted = Format-Nicely -Value $Actual -Pretty:$Pretty + + $optionMessage = $null; + if ($null -ne $Option -and $option.Length -gt 0) + { + if (-not $Pretty) { + $optionMessage = "Used options: $($Option -join ", ")." + } + else { + if ($Pretty) { + $optionMessage = "Used options:$($Option | ForEach-Object { "`n$_" })." + } + } + } + + + $CustomMessage = $CustomMessage.Replace('', $expectedFormatted) + $CustomMessage = $CustomMessage.Replace('', $actualFormatted) + $CustomMessage = $CustomMessage.Replace('', (Get-ShortType -Value $Expected)) + $CustomMessage = $CustomMessage.Replace('', (Get-ShortType -Value $Actual)) + $CustomMessage = $CustomMessage.Replace('', $optionMessage) + + foreach ($pair in $Data.GetEnumerator()) + { + $CustomMessage = $CustomMessage.Replace("<$($pair.Key)>", (Format-Nicely -Value $pair.Value)) + } + + if (-not $Pretty) { + $CustomMessage + } + else + { + $CustomMessage + "`n`n" + } +} \ No newline at end of file diff --git a/src/functions/assert/Common/Get-CustomFailureMessage.ps1 b/src/functions/assert/Common/Get-CustomFailureMessage.ps1 new file mode 100644 index 000000000..f2b5f179a --- /dev/null +++ b/src/functions/assert/Common/Get-CustomFailureMessage.ps1 @@ -0,0 +1,6 @@ +function Get-CustomFailureMessage ($CustomMessage, $Expected, $Actual) +{ + $formatted = $CustomMessage -f $Expected, $Actual + $tokensReplaced = $formatted -replace '', $Expected -replace '', $Actual + $tokensReplaced -replace '', $Expected -replace '', $Actual +} \ No newline at end of file diff --git a/src/functions/assert/Equivalence/Assert-Equivalent.ps1 b/src/functions/assert/Equivalence/Assert-Equivalent.ps1 new file mode 100644 index 000000000..f1221af60 --- /dev/null +++ b/src/functions/assert/Equivalence/Assert-Equivalent.ps1 @@ -0,0 +1,758 @@ +function Test-Same ($Expected, $Actual) { + [object]::ReferenceEquals($Expected, $Actual) +} + +function Is-CollectionSize ($Expected, $Actual) { + if ($Expected.Length -is [Int] -and $Actual.Length -is [Int]) { + return $Expected.Length -eq $Actual.Length + } + else { + return $Expected.Count -eq $Actual.Count + } +} + +function Is-DataTableSize ($Expected, $Actual) { + return $Expected.Rows.Count -eq $Actual.Rows.Count +} + +function Get-ValueNotEquivalentMessage ($Expected, $Actual, $Property, $Options) { + $Expected = Format-Nicely -Value $Expected + $Actual = Format-Nicely -Value $Actual + $propertyInfo = if ($Property) { " property $Property with value" } + $comparison = if ("Equality" -eq $Options.Comparator) { 'equal' } else { 'equivalent' } + "Expected$propertyInfo '$Expected' to be $comparison to the actual value, but got '$Actual'." +} + + +function Get-CollectionSizeNotTheSameMessage ($Actual, $Expected, $Property) { + $expectedLength = if ($Expected.Length -is [int]) {$Expected.Length} else {$Expected.Count} + $actualLength = if ($Actual.Length -is [int]) {$Actual.Length} else {$Actual.Count} + $Expected = Format-Collection -Value $Expected + $Actual = Format-Collection -Value $Actual + + $propertyMessage = $null + if ($property) { + $propertyMessage = " in property $Property with values" + } + "Expected collection$propertyMessage '$Expected' with length '$expectedLength' to be the same size as the actual collection, but got '$Actual' with length '$actualLength'." +} + +function Get-DataTableSizeNotTheSameMessage ($Actual, $Expected, $Property) { + $expectedLength = $Expected.Rows.Count + $actualLength = $Actual.Rows.Count + $Expected = Format-Collection -Value $Expected + $Actual = Format-Collection -Value $Actual + + $propertyMessage = $null + if ($property) { + $propertyMessage = " in property $Property with values" + } + "Expected DataTable$propertyMessage '$Expected' with length '$expectedLength' to be the same size as the actual DataTable, but got '$Actual' with length '$actualLength'." +} + +function Compare-CollectionEquivalent ($Expected, $Actual, $Property, $Options) { + if (-not (Is-Collection -Value $Expected)) + { + throw [ArgumentException]"Expected must be a collection." + } + + if (-not (Is-Collection -Value $Actual)) + { + v -Difference "`$Actual is not a collection it is a $(Format-Nicely (Get-Type $Actual)), so they are not equivalent." + $expectedFormatted = Format-Collection -Value $Expected + $expectedLength = $expected.Length + $actualFormatted = Format-Nicely -Value $actual + return "Expected collection '$expectedFormatted' with length '$expectedLength', but got '$actualFormatted'." + } + + if (-not (Is-CollectionSize -Expected $Expected -Actual $Actual)) { + v -Difference "`$Actual does not have the same size ($($Actual.Length)) as `$Expected ($($Expected.Length)) so they are not equivalent." + return Get-CollectionSizeNotTheSameMessage -Expected $Expected -Actual $Actual -Property $Property + } + + $eEnd = if ($Expected.Length -is [int]) {$Expected.Length} else {$Expected.Count} + $aEnd = if ($Actual.Length -is [int]) {$Actual.Length} else {$Actual.Count} + v "Comparing items in collection, `$Expected has lenght $eEnd, `$Actual has length $aEnd." + $taken = @() + $notFound = @() + $anyDifferent = $false + for ($e=0; $e -lt $eEnd; $e++) { + # todo: retest strict order + v "`nSearching for `$Expected[$e]:" + $currentExpected = $Expected[$e] + $found = $false + if ($StrictOrder) { + $currentActual = $Actual[$e] + if ($taken -notcontains $e -and (-not (Compare-Equivalent -Expected $currentExpected -Actual $currentActual -Path $Property -Options $Options))) + { + $taken += $e + $found = $true + v -Equivalence "`Found `$Expected[$e]." + } + } + else { + for ($a=0; $a -lt $aEnd; $a++) { + # we already took this item as equivalent to an item + # in the expected collection, skip it + if ($taken -contains $a) { + v "Skipping `$Actual[$a] because it is already taken." + continue } + $currentActual = $Actual[$a] + # -not, because $null means no differences, and some strings means there are differences + v "Comparing `$Actual[$a] to `$Expected[$e] to see if they are equivalent." + if (-not (Compare-Equivalent -Expected $currentExpected -Actual $currentActual -Path $Property -Options $Options)) + { + # add the index to the list of taken items so we can skip it + # in the search, this way we can compare collections with + # arrays multiple same items + $taken += $a + $found = $true + v -Equivalence "`Found equivalent item for `$Expected[$e] at `$Actual[$a]." + # we already found the item we + # can move on to the next item in Exected array + break + } + } + } + if (-not $found) + { + v -Difference "`$Actual does not contain `$Expected[$e]." + $anyDifferent = $true + $notFound += $currentExpected + } + } + + # do not depend on $notFound collection here + # failing to find a single $null, will return + # @($null) which evaluates to false, even though + # there was a single item that we did not find + if ($anyDifferent) { + v -Difference "`$Actual and `$Expected arrays are not equivalent." + $Expected = Format-Nicely -Value $Expected + $Actual = Format-Nicely -Value $Actual + $notFoundFormatted = Format-Nicely -Value ( $notFound | ForEach-Object { Format-Nicely -Value $_ } ) + + $propertyMessage = if ($Property) {" in property $Property which is"} + return "Expected collection$propertyMessage '$Expected' to be equivalent to '$Actual' but some values were missing: '$notFoundFormatted'." + } + v -Equivalence "`$Actual and `$Expected arrays are equivalent." +} + +function Compare-DataTableEquivalent ($Expected, $Actual, $Property, $Options) { + if (-not (Is-DataTable -Value $Expected)) { + throw [ArgumentException]"Expected must be a DataTable." + } + + if (-not (Is-DataTable -Value $Actual)) { + $expectedFormatted = Format-Collection -Value $Expected + $expectedLength = $expected.Rows.Count + $actualFormatted = Format-Nicely -Value $actual + return "Expected DataTable '$expectedFormatted' with length '$expectedLength', but got '$actualFormatted'." + } + + if (-not (Is-DataTableSize -Expected $Expected -Actual $Actual)) { + return Get-DataTableSizeNotTheSameMessage -Expected $Expected -Actual $Actual -Property $Property + } + + $eEnd = $Expected.Rows.Count + $aEnd = $Actual.Rows.Count + $taken = @() + $notFound = @() + for ($e = 0; $e -lt $eEnd; $e++) { + $currentExpected = $Expected.Rows[$e] + $found = $false + if ($StrictOrder) { + $currentActual = $Actual.Rows[$e] + if ((-not (Compare-Equivalent -Expected $currentExpected -Actual $currentActual -Path $Property -Options $Options)) -and $taken -notcontains $e) { + $taken += $e + $found = $true + } + } + else { + for ($a = 0; $a -lt $aEnd; $a++) { + $currentActual = $Actual.Rows[$a] + if ((-not (Compare-Equivalent -Expected $currentExpected -Actual $currentActual -Path $Property -Options $Options)) -and $taken -notcontains $a) { + $taken += $a + $found = $true + } + } + } + if (-not $found) { + $notFound += $currentExpected + } + } + $Expected = Format-Nicely -Value $Expected + $Actual = Format-Nicely -Value $Actual + $notFoundFormatted = Format-Nicely -Value ( $notFound | ForEach-Object { Format-Nicely -Value $_ } ) + + if ($notFound) { + $propertyMessage = if ($Property) {" in property $Property which is"} + return "Expected DataTable$propertyMessage '$Expected' to be equivalent to '$Actual' but some values were missing: '$notFoundFormatted'." + } +} + +function Compare-ValueEquivalent ($Actual, $Expected, $Property, $Options) { + $Expected = $($Expected) + if (-not (Is-Value -Value $Expected)) + { + throw [ArgumentException]"Expected must be a Value." + } + + # we don't specify the options in some tests so here we make + # sure that equivalency is used as the default + # not ideal but better than rewriting 100 tests + if (($null -eq $Options) -or + ($null -eq $Options.Comparator) -or + ("Equivalency" -eq $Options.Comparator)) { + v "Equivalency comparator is used, values will be compared for equivalency." + # fix that string 'false' becomes $true boolean + if ($Actual -is [Bool] -and $Expected -is [string] -and "$Expected" -eq 'False') + { + v "`$Actual is a boolean, and `$Expected is a 'False' string, which we consider equivalent to boolean `$false. Setting `$Expected to `$false." + $Expected = $false + if ($Expected -ne $Actual) + { + v -Difference "`$Actual is not equivalent to $(Format-Nicely $Expected) because it is $(Format-Nicely $Actual)." + return Get-ValueNotEquivalentMessage -Expected $Expected -Actual $Actual -Property $Property -Options $Options + } + v -Equivalence "`$Actual is equivalent to $(Format-Nicely $Expected) because it is $(Format-Nicely $Actual)." + return + } + + if ($Expected -is [Bool] -and $Actual -is [string] -and "$Actual" -eq 'False') + { + v "`$Actual is a 'False' string, which we consider equivalent to boolean `$false. `$Expected is a boolean. Setting `$Actual to `$false." + $Actual = $false + if ($Expected -ne $Actual) + { + v -Difference "`$Actual is not equivalent to $(Format-Nicely $Expected) because it is $(Format-Nicely $Actual)." + return Get-ValueNotEquivalentMessage -Expected $Expected -Actual $Actual -Property $Property -Options $Options + } + v -Equivalence "`$Actual is equivalent to $(Format-Nicely $Expected) because it is $(Format-Nicely $Actual)." + return + } + + #fix that scriptblocks are compared by reference + if (Is-ScriptBlock -Value $Expected) + { + # todo: compare by equivalency like strings? + v "`$Expected is a ScriptBlock, scriptblocks are considered equivalent when their content is equal. Converting `$Expected to string." + #forcing scriptblock to serialize to string and then comparing that + if ("$Expected" -ne $Actual) + { + # todo: difference on index? + v -Difference "`$Actual is not equivalent to `$Expected because their contents differ." + return Get-ValueNotEquivalentMessage -Expected $Expected -Actual $Actual -Property $Path -Options $Options + } + v -Equivalence "`$Actual is equivalent to `$Expected because their contents are equal." + return + } + } + else + { + v "Equality comparator is used, values will be compared for equality." + } + + v "Comparing values as $(Format-Nicely (Get-Type $Expected)) because `$Expected has that type." + # todo: shorter messages when both sides have the same type (do not compare by using -is, instead query the type and compare it) because -is is true even for parent types + $type = Get-Type $Expected + $coalescedActual = $Actual -as $type + if ($Expected -ne $Actual) + { + v -Difference "`$Actual is not equivalent to $(Format-Nicely $Expected) because it is $(Format-Nicely $Actual), and $(Format-Nicely $Actual) coalesced to $(Format-Nicely $type) is $(Format-Nicely $coalescedActual)." + return Get-ValueNotEquivalentMessage -Expected $Expected -Actual $Actual -Property $Property -Options $Options + } + v -Equivalence "`$Actual is equivalent to $(Format-Nicely $Expected) because it is $(Format-Nicely $Actual), and $(Format-Nicely $Actual) coalesced to $(Format-Nicely $type) is $(Format-Nicely $coalescedActual)." +} + +function Compare-HashtableEquivalent ($Actual, $Expected, $Property, $Options) { + if (-not (Is-Hashtable -Value $Expected)) + { + throw [ArgumentException]"Expected must be a hashtable." + } + + if (-not (Is-Hashtable -Value $Actual)) + { + v -Difference "`$Actual is not a hashtable it is a $(Format-Nicely (Get-Type $Actual)), so they are not equivalent." + $expectedFormatted = Format-Nicely -Value $Expected + $actualFormatted = Format-Nicely -Value $Actual + return "Expected hashtable '$expectedFormatted', but got '$actualFormatted'." + } + + # todo: if either side or both sides are empty hashtable make the verbose output shorter and nicer + + $actualKeys = $Actual.Keys + $expectedKeys = $Expected.Keys + + v "`Comparing all ($($expectedKeys.Count)) keys from `$Expected to keys in `$Actual." + $result = @() + foreach ($k in $expectedKeys) + { + if (-not (Test-IncludedPath -PathSelector Hashtable -Path $Property -Options $Options -InputObject $k)) { + continue + } + + $actualHasKey = $actualKeys -contains $k + if (-not $actualHasKey) + { + v -Difference "`$Actual is missing key '$k'." + $result += "Expected has key '$k' that the other object does not have." + continue + } + + $expectedValue = $Expected[$k] + $actualValue = $Actual[$k] + v "Both `$Actual and `$Expected have key '$k', comparing thier contents." + $result += Compare-Equivalent -Expected $expectedValue -Actual $actualValue -Path "$Property.$k" -Options $Options + } + + if (!$Options.ExcludePathsNotOnExpected) { + # fix for powershell 2 where the array needs to be explicit + $keysNotInExpected = @( $actualKeys | Where-Object { $expectedKeys -notcontains $_ }) + + $filteredKeysNotInExpected = @( $keysNotInExpected | Test-IncludedPath -PathSelector Hashtable -Path $Property -Options $Options) + + # fix for powershell v2 where foreach goes once over null + if ($filteredKeysNotInExpected | Where-Object { $_ }) { + v -Difference "`$Actual has $($filteredKeysNotInExpected.Count) keys that were not found on `$Expected: $(Format-Nicely @($filteredKeysNotInExpected))." + } + else { + v "`$Actual has no keys that we did not find on `$Expected." + } + + foreach ($k in $filteredKeysNotInExpected | Where-Object { $_ }) + { + $result += "Expected is missing key '$k' that the other object has." + } + } + + if ($result | Where-Object { $_ }) + { + v -Difference "Hashtables `$Actual and `$Expected are not equivalent." + $expectedFormatted = Format-Nicely -Value $Expected + $actualFormatted = Format-Nicely -Value $Actual + return "Expected hashtable '$expectedFormatted', but got '$actualFormatted'.`n$($result -join "`n")" + } + + v -Equivalence "Hastables `$Actual and `$Expected are equivalent." +} + +function Compare-DictionaryEquivalent ($Actual, $Expected, $Property, $Options) { + if (-not (Is-Dictionary -Value $Expected)) + { + throw [ArgumentException]"Expected must be a dictionary." + } + + if (-not (Is-Dictionary -Value $Actual)) + { + v -Difference "`$Actual is not a dictionary it is a $(Format-Nicely (Get-Type $Actual)), so they are not equivalent." + $expectedFormatted = Format-Nicely -Value $Expected + $actualFormatted = Format-Nicely -Value $Actual + return "Expected dictionary '$expectedFormatted', but got '$actualFormatted'." + } + + # todo: if either side or both sides are empty dictionary make the verbose output shorter and nicer + + $actualKeys = $Actual.Keys + $expectedKeys = $Expected.Keys + + v "`Comparing all ($($expectedKeys.Count)) keys from `$Expected to keys in `$Actual." + $result = @() + foreach ($k in $expectedKeys) + { + if (-not (Test-IncludedPath -PathSelector Hashtable -Path $Property -Options $Options -InputObject $k)) { + continue + } + + $actualHasKey = $actualKeys -contains $k + if (-not $actualHasKey) + { + v -Difference "`$Actual is missing key '$k'." + $result += "Expected has key '$k' that the other object does not have." + continue + } + + $expectedValue = $Expected[$k] + $actualValue = $Actual[$k] + v "Both `$Actual and `$Expected have key '$k', comparing thier contents." + $result += Compare-Equivalent -Expected $expectedValue -Actual $actualValue -Path "$Property.$k" -Options $Options + } + if (!$Options.ExcludePathsNotOnExpected) { + # fix for powershell 2 where the array needs to be explicit + $keysNotInExpected = @( $actualKeys | Where-Object { $expectedKeys -notcontains $_ } ) + $filteredKeysNotInExpected = @( $keysNotInExpected | Test-IncludedPath -PathSelector Hashtable -Path $Property -Options $Options ) + + # fix for powershell v2 where foreach goes once over null + if ($filteredKeysNotInExpected | Where-Object { $_ }) { + v -Difference "`$Actual has $($filteredKeysNotInExpected.Count) keys that were not found on `$Expected: $(Format-Nicely @($filteredKeysNotInExpected))." + } + else { + v "`$Actual has no keys that we did not find on `$Expected." + } + + foreach ($k in $filteredKeysNotInExpected | Where-Object { $_ }) + { + $result += "Expected is missing key '$k' that the other object has." + } + } + + if ($result) + { + v -Difference "Dictionaries `$Actual and `$Expected are not equivalent." + $expectedFormatted = Format-Nicely -Value $Expected + $actualFormatted = Format-Nicely -Value $Actual + return "Expected dictionary '$expectedFormatted', but got '$actualFormatted'.`n$($result -join "`n")" + } + v -Equivalence "Dictionaries `$Actual and `$Expected are equivalent." +} + +function Compare-ObjectEquivalent ($Actual, $Expected, $Property, $Options) { + + if (-not (Is-Object -Value $Expected)) + { + throw [ArgumentException]"Expected must be an object." + } + + if (-not (Is-Object -Value $Actual)) { + v -Difference "`$Actual is not an object it is a $(Format-Nicely (Get-Type $Actual)), so they are not equivalent." + $expectedFormatted = Format-Nicely -Value $Expected + $actualFormatted = Format-Nicely -Value $Actual + return "Expected object '$expectedFormatted', but got '$actualFormatted'." + } + + $actualProperties = $Actual.PsObject.Properties + $expectedProperties = $Expected.PsObject.Properties + + v "Comparing ($(@($expectedProperties).Count)) properties of `$Expected to `$Actual." + foreach ($p in $expectedProperties) + { + if (-not (Test-IncludedPath -PathSelector Property -InputObject $p -Options $Options -Path $Property)) + { + continue + } + + $propertyName = $p.Name + $actualProperty = $actualProperties | Where-Object { $_.Name -eq $propertyName} + if (-not $actualProperty) + { + v -Difference "Property '$propertyName' was not found on `$Actual." + "Expected has property '$PropertyName' that the other object does not have." + continue + } + v "Property '$propertyName` was found on `$Actual, comparing them for equivalence." + $differences = Compare-Equivalent -Expected $p.Value -Actual $actualProperty.Value -Path "$Property.$propertyName" -Options $Options + if (-not $differences) { + v -Equivalence "Property '$propertyName` is equivalent." + } + else { + v -Difference "Property '$propertyName` is not equivalent." + } + $differences + } + + if (!$Options.ExcludePathsNotOnExpected) { + #check if there are any extra actual object props + $expectedPropertyNames = $expectedProperties | Select-Object -ExpandProperty Name + + $propertiesNotInExpected = @( $actualProperties | Where-Object { $expectedPropertyNames -notcontains $_.name }) + + # fix for powershell v2 we need to make the array explicit + $filteredPropertiesNotInExpected = $propertiesNotInExpected | + Test-IncludedPath -PathSelector Property -Options $Options -Path $Property + + if ($filteredPropertiesNotInExpected) { + v -Difference "`$Actual has ($(@($filteredPropertiesNotInExpected).Count)) properties that `$Expected does not have: $(Format-Nicely @($filteredPropertiesNotInExpected))." + } + else { + v -Equivalence "`$Actual has no extra properties that `$Expected does not have." + } + + # fix for powershell v2 where foreach goes once over null + foreach ($p in $filteredPropertiesNotInExpected | Where-Object { $_ }) + { + "Expected is missing property '$($p.Name)' that the other object has." + } + } +} + +function Compare-DataRowEquivalent ($Actual, $Expected, $Property, $Options) { + + if (-not (Is-DataRow -Value $Expected)) + { + throw [ArgumentException]"Expected must be a DataRow." + } + + if (-not (Is-DataRow -Value $Actual)) { + $expectedFormatted = Format-Nicely -Value $Expected + $actualFormatted = Format-Nicely -Value $Actual + return "Expected DataRow '$expectedFormatted', but got '$actualFormatted'." + } + + $actualProperties = $Actual.PsObject.Properties | Where-Object {'RowError','RowState','Table','ItemArray','HasErrors' -notcontains $_.Name } + $expectedProperties = $Expected.PsObject.Properties | Where-Object {'RowError','RowState','Table','ItemArray','HasErrors' -notcontains $_.Name } + + foreach ($p in $expectedProperties) + { + $propertyName = $p.Name + $actualProperty = $actualProperties | Where-Object { $_.Name -eq $propertyName} + if (-not $actualProperty) + { + "Expected has property '$PropertyName' that the other object does not have." + continue + } + + Compare-Equivalent -Expected $p.Value -Actual $actualProperty.Value -Path "$Property.$propertyName" -Options $Options + } + + #check if there are any extra actual object props + $expectedPropertyNames = $expectedProperties | Select-Object -ExpandProperty Name + + $propertiesNotInExpected = @($actualProperties | Where-Object {$expectedPropertyNames -notcontains $_.name }) + + # fix for powershell v2 where foreach goes once over null + foreach ($p in $propertiesNotInExpected | Where-Object { $_ }) + { + "Expected is missing property '$($p.Name)' that the other object has." + } +} + +function v { + [CmdletBinding()] + param( + [String] $String, + [Switch] $Difference, + [Switch] $Equivalence, + [Switch] $Skip + ) + + # we are using implict variable $Path + # from the parent scope, this is ugly + # and bad practice, but saves us ton of + # coding and boilerplate code + + $p = "" + $p += if ($null -ne $Path) { + "($Path)" + } + + $p += if ($Difference) { + " DIFFERENCE" + } + + $p += if ($Equivalence) { + " EQUIVALENCE" + } + + $p += if ($Skip) { + " SKIP" + } + + $p += if (""-ne $p) { + " - " + } + + Write-Verbose ("$p$String".Trim() + " ") +} + +# compares two objects for equivalency and returns $null when they are equivalent +# or a string message when they are not +function Compare-Equivalent { + [CmdletBinding()] + param( + $Actual, + $Expected, + $Path, + $Options = (&{ + Write-Warning "Getting default equivalency options, this should never be seen. If you see this and you are not developing Assert, please file issue at https://github.com/nohwnd/Assert/issues" + Get-EquivalencyOption + }) + ) + + if ($null -ne $Options.ExludedPaths -and $Options.ExcludedPaths -contains $Path) { + v -Skip "Current path '$Path' is excluded from the comparison." + return + } + + #start by null checks to avoid implementing null handling + #logic in the functions that follow + if ($null -eq $Expected) + { + v "`$Expected is `$null, so we are expecting `$null." + if ($Expected -ne $Actual) + { + v -Difference "`$Actual is not equivalent to $(Format-Nicely $Expected), because it has a value of type $(Format-Nicely $Actual.GetType())." + return Get-ValueNotEquivalentMessage -Expected $Expected -Actual $Actual -Property $Path -Options $Options + } + # we terminate here, either we passed the test and return nothing, or we did not + # and the previous statement returned message + v -Equivalence "`$Actual is equivalent to `$null, because it is `$null." + return + } + + if ($null -eq $Actual) + { + v -Difference "`$Actual is $(Format-Nicely), but `$Expected has value of type $(Format-Nicely Get-Type $Expected), so they are not equivalent." + return Get-ValueNotEquivalentMessage -Expected $Expected -Actual $Actual -Property $Path + } + + v "`$Expected has type $(Get-Type $Expected), `$Actual has type $(Get-Type $Actual), they are both non-null." + + #test value types, strings, and single item arrays with values in them as values + #expand the single item array to get to the value in it + if (Is-Value -Value $Expected) + { + v "`$Expected is a value (value type, string, single value array, or a scriptblock), we will be comparing `$Actual to value types." + Compare-ValueEquivalent -Actual $Actual -Expected $Expected -Property $Path -Options $Options + return + } + + #are the same instance + if (Test-Same -Expected $Expected -Actual $Actual) + { + v -Equivalence "`$Expected and `$Actual are equivalent because they are the same object (by reference)." + return + } + + if (Is-Hashtable -Value $Expected) + { + v "`$Expected is a hashtable, we will be comparing `$Actual to hashtables." + Compare-HashtableEquivalent -Expected $Expected -Actual $Actual -Property $Path -Options $Options + return + } + + # dictionaries? (they are IEnumerable so they must go before collections) + if (Is-Dictionary -Value $Expected) + { + v "`$Expected is a dictionary, we will be comparing `$Actual to dictionaries." + Compare-DictionaryEquivalent -Expected $Expected -Actual $Actual -Property $Path -Options $Options + return + } + + #compare DataTable + if (Is-DataTable -Value $Expected) { + # todo add verbose output to data table + v "`$Expected is a datatable, we will be comparing `$Actual to datatables." + Compare-DataTableEquivalent -Expected $Expected -Actual $Actual -Property $Path -Options $Options + return + } + + #compare collection + if (Is-Collection -Value $Expected) { + v "`$Expected is a collection, we will be comparing `$Actual to collections." + Compare-CollectionEquivalent -Expected $Expected -Actual $Actual -Property $Path -Options $Options + return + } + + #compare DataRow + if (Is-DataRow -Value $Expected) { + # todo add verbose output to data row + v "`$Expected is a datarow, we will be comparing `$Actual to datarows." + Compare-DataRowEquivalent -Expected $Expected -Actual $Actual -Property $Path -Options $Options + return + } + + v "`$Expected is an object of type $(Get-Type $Expected), we will be comparing `$Actual to objects." + Compare-ObjectEquivalent -Expected $Expected -Actual $Actual -Property $Path -Options $Options +} + +function Assert-Equivalent { + [CmdletBinding()] + param( + $Actual, + $Expected, + $Options = (Get-EquivalencyOption), + [Switch] $StrictOrder + ) + + $areDifferent = Compare-Equivalent -Actual $Actual -Expected $Expected -Options $Options | Out-String + + if ($areDifferent) + { + $optionsFormatted = Format-EquivalencyOptions -Options $Options + # the paremeter is -Option not -Options + $message = Get-AssertionMessage -Actual $actual -Expected $Expected -Option $optionsFormatted -Pretty -CustomMessage "Expected and actual are not equivalent!`nExpected:`n`n`nActual:`n`n`nSummary:`n$areDifferent`n" + throw [Assertions.AssertionException]$message + } + + v -Equivalence "`$Actual and `$Expected are equivalent." +} + +function Get-EquivalencyOption { + param( + [string[]] $ExcludePath = @(), + [switch] $ExcludePathsNotOnExpected, + [ValidateSet('Equivalency', 'Equality')] + [string] $Comparator = 'Equivalency' + ) + + [PSCustomObject]@{ + ExcludedPaths = [string[]] $ExcludePath + ExcludePathsNotOnExpected = [bool] $ExcludePathsNotOnExpected + Comparator = [string] $Comparator + } +} + +function Test-IncludedPath { + param( + [Parameter(Mandatory=$true, ValueFromPipeline=$true)] + $InputObject, + [String] + $Path, + $Options, + [Parameter(Mandatory=$true)] + [ValidateSet("Property", "Hashtable")] + $PathSelector + ) + + begin { + $selector = switch ($PathSelector) { + "Property" { { param($InputObject) $InputObject.Name } } + "Hashtable" { { param($InputObject) $InputObject } } + Default {throw "Unsupported path selector."} + } + } + + process { + if ($null -eq $Options.ExcludedPaths) + { + return $InputObject + } + + $subPath = &$selector $InputObject + $fullPath = "$Path.$subPath".Trim('.') + + + if ($fullPath | Like-Any $Options.ExcludedPaths) + { + v -Skip "Current path $fullPath is excluded from the comparison." + } + else + { + $InputObject + } + } +} + +function Format-EquivalencyOptions ($Options) { + $Options.ExcludedPaths | ForEach-Object { "Exclude path '$_'" } + if ($Options.ExcludePathsNotOnExpected) { "Excluding all paths not found on Expected" } +} + +function Like-Any { + param( + [String[]] $PathFilters, + [Parameter(Mandatory = $true, ValueFromPipeline = $true)] + [String] $Path + ) + process { + foreach ($pathFilter in $PathFilters | Where-Object { $_ }) { + $r = $Path -like $pathFilter + if ($r) { + v -Skip "Path '$Path' matches filter '$pathFilter'." + return $true + } + } + + return $false + } +} \ No newline at end of file diff --git a/src/functions/assert/Exception/Assert-Throw.ps1 b/src/functions/assert/Exception/Assert-Throw.ps1 new file mode 100644 index 000000000..a35f27608 --- /dev/null +++ b/src/functions/assert/Exception/Assert-Throw.ps1 @@ -0,0 +1,121 @@ +function Assert-Throw { + param ( + [Parameter(ValueFromPipeline=$true, Mandatory = $true)] + [ScriptBlock]$ScriptBlock, + [Type]$ExceptionType, + [String]$ExceptionMessage, + [String]$FullyQualifiedErrorId, + [Switch]$AllowNonTerminatingError, + [String]$CustomMessage + ) + + $ScriptBlock = Collect-Input -ParameterInput $ScriptBlock -PipelineInput $local:Input + + $errorThrown = $false + $err = $null + try { + $p = 'stop' + if ($AllowNonTerminatingError) + { + $p = 'continue' + } + # compatibility fix for powershell v2 + # $eap = New-Object -TypeName psvariable "erroractionpreference", $p + # $null = $ScriptBlock.InvokeWithContext($null, $eap, $null) 2>&1 + + $null = (Invoke-WithContext -ScriptBlock $ScriptBlock -Variables @{ ErrorActionPreference = $p }) 2>&1 + } + catch + { + $errorThrown = $true + $err = Get-Error $_ + } + + $buts = @() + $filters = @() + + $filterOnExceptionType = $null -ne $ExceptionType + if ($filterOnExceptionType) { + $exceptionFilterTypeFormatted = Format-Type $ExceptionType + + $filters += "of type $exceptionFilterTypeFormatted" + + $exceptionTypeFilterMatches = $err.Exception -is $ExceptionType + if (-not $exceptionTypeFilterMatches) { + $exceptionTypeFormatted = Get-ShortType $err.Exception + $buts += "the exception type was '$exceptionTypeFormatted'" + } + } + + $filterOnMessage = -not (Test-NullOrWhiteSpace $ExceptionMessage) + if ($filterOnMessage) { + $filters += "with message '$ExceptionMessage'" + if ($err.ExceptionMessage -notlike $ExceptionMessage) { + $buts += "the message was '$($err.ExceptionMessage)'" + } + } + + $filterOnId = -not (Test-NullOrWhiteSpace $FullyQualifiedErrorId) + if ($filterOnId) { + $filters += "with FullyQualifiedErrorId '$FullyQualifiedErrorId'" + if ($err.FullyQualifiedErrorId -notlike $FullyQualifiedErrorId) { + $buts += "the FullyQualifiedErrorId was '$($err.FullyQualifiedErrorId)'" + } + } + + if (-not $errorThrown) + { + $buts += "no exception was thrown" + } + + if ($buts.Count -ne 0) { + $filter = Add-SpaceToNonEmptyString ( Join-And $filters -Threshold 3 ) + $but = Join-And $buts + $defaultMessage = "Expected an exception,$filter to be thrown, but $but." + + $Message = Get-AssertionMessage -Expected $Expected -Actual $ScriptBlock -CustomMessage $CustomMessage ` + -DefaultMessage $defaultMessage + throw [Assertions.AssertionException]$Message + } + + $err.ErrorRecord +} + +function Get-Error ($ErrorRecord) { + + if ($ErrorRecord.Exception -like '*"InvokeWithContext"*') + { + $e = $ErrorRecord.Exception.InnerException.ErrorRecord + } + else + { + $e = $ErrorRecord + } + New-Object -TypeName PSObject -Property @{ + ErrorRecord = $e + ExceptionMessage = $e.Exception.Message + Exception = $e.Exception + ExceptionType = $e.Exception.GetType() + FullyQualifiedErrorId = $e.FullyQualifiedErrorId + } +} + +function Join-And ($Items, $Threshold=2) { + + if ($null -eq $items -or $items.count -lt $Threshold) + { + $items -join ', ' + } + else + { + $c = $items.count + ($items[0..($c-2)] -join ', ') + ' and ' + $items[-1] + } +} + +function Add-SpaceToNonEmptyString ([string]$Value) { + if ($Value) + { + " $Value" + } +} \ No newline at end of file diff --git a/src/functions/assert/General/Assert-Equal.ps1 b/src/functions/assert/General/Assert-Equal.ps1 new file mode 100644 index 000000000..5a5f96fad --- /dev/null +++ b/src/functions/assert/General/Assert-Equal.ps1 @@ -0,0 +1,19 @@ +function Assert-Equal { + param ( + [Parameter(Position=1, ValueFromPipeline=$true)] + $Actual, + [Parameter(Position=0)] + $Expected, + [String]$CustomMessage + ) + + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + + if ((Ensure-ExpectedIsNotCollection $Expected) -ne $Actual) + { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '', but got ''." + throw [Assertions.AssertionException]$Message + } + + $Actual +} \ No newline at end of file diff --git a/src/functions/assert/General/Assert-GreaterThan.ps1 b/src/functions/assert/General/Assert-GreaterThan.ps1 new file mode 100644 index 000000000..1fe3643a4 --- /dev/null +++ b/src/functions/assert/General/Assert-GreaterThan.ps1 @@ -0,0 +1,18 @@ +function Assert-GreaterThan { + param ( + [Parameter(Position=1, ValueFromPipeline=$true)] + $Actual, + [Parameter(Position=0)] + $Expected, + [String]$CustomMessage + ) + + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + if ((Ensure-ExpectedIsNotCollection $Expected) -ge $Actual) + { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be greater than '', but it was not." + throw [Assertions.AssertionException]$Message + } + + $Actual +} \ No newline at end of file diff --git a/src/functions/assert/General/Assert-GreaterThanOrEqual.ps1 b/src/functions/assert/General/Assert-GreaterThanOrEqual.ps1 new file mode 100644 index 000000000..4d0b89489 --- /dev/null +++ b/src/functions/assert/General/Assert-GreaterThanOrEqual.ps1 @@ -0,0 +1,18 @@ +function Assert-GreaterThanOrEqual { + param ( + [Parameter(Position=1, ValueFromPipeline=$true)] + $Actual, + [Parameter(Position=0)] + $Expected, + [String]$CustomMessage + ) + + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + if ((Ensure-ExpectedIsNotCollection $Expected) -gt $Actual) + { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be greater than or equal to '', but it was not." + throw [Assertions.AssertionException]$Message + } + + $Actual +} \ No newline at end of file diff --git a/src/functions/assert/General/Assert-LessThan.ps1 b/src/functions/assert/General/Assert-LessThan.ps1 new file mode 100644 index 000000000..a1b41afbf --- /dev/null +++ b/src/functions/assert/General/Assert-LessThan.ps1 @@ -0,0 +1,18 @@ +function Assert-LessThan { + param ( + [Parameter(Position=1, ValueFromPipeline=$true)] + $Actual, + [Parameter(Position=0)] + $Expected, + [String]$CustomMessage + ) + + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + if ((Ensure-ExpectedIsNotCollection $Expected) -le $Actual) + { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be less than '', but it was not." + throw [Assertions.AssertionException]$Message + } + + $Actual +} \ No newline at end of file diff --git a/src/functions/assert/General/Assert-LessThanOrEqual.ps1 b/src/functions/assert/General/Assert-LessThanOrEqual.ps1 new file mode 100644 index 000000000..43ec5ea06 --- /dev/null +++ b/src/functions/assert/General/Assert-LessThanOrEqual.ps1 @@ -0,0 +1,18 @@ +function Assert-LessThanOrEqual { + param ( + [Parameter(Position=1, ValueFromPipeline=$true)] + $Actual, + [Parameter(Position=0)] + $Expected, + [String]$CustomMessage + ) + + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + if ((Ensure-ExpectedIsNotCollection $Expected) -lt $Actual) + { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be less than or equal to '', but it was not." + throw [Assertions.AssertionException]$Message + } + + $Actual +} \ No newline at end of file diff --git a/src/functions/assert/General/Assert-NotEqual.ps1 b/src/functions/assert/General/Assert-NotEqual.ps1 new file mode 100644 index 000000000..b02f1dade --- /dev/null +++ b/src/functions/assert/General/Assert-NotEqual.ps1 @@ -0,0 +1,18 @@ +function Assert-NotEqual { + param ( + [Parameter(Position=1, ValueFromPipeline=$true)] + $Actual, + [Parameter(Position=0)] + $Expected, + [String]$CustomMessage + ) + + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + if ((Ensure-ExpectedIsNotCollection $Expected) -eq $Actual) + { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '', to be different than the actual value, but they were the same." + throw [Assertions.AssertionException]$Message + } + + $Actual +} \ No newline at end of file diff --git a/src/functions/assert/General/Assert-NotNull.ps1 b/src/functions/assert/General/Assert-NotNull.ps1 new file mode 100644 index 000000000..18b071481 --- /dev/null +++ b/src/functions/assert/General/Assert-NotNull.ps1 @@ -0,0 +1,16 @@ +function Assert-NotNull { + param ( + [Parameter(Position=1, ValueFromPipeline=$true)] + $Actual, + [String]$CustomMessage + ) + + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + if ($null -eq $Actual) + { + $Message = Get-AssertionMessage -Expected $null -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected not `$null, but got `$null." + throw [Assertions.AssertionException]$Message + } + + $Actual +} \ No newline at end of file diff --git a/src/functions/assert/General/Assert-NotSame.ps1 b/src/functions/assert/General/Assert-NotSame.ps1 new file mode 100644 index 000000000..535ca1d11 --- /dev/null +++ b/src/functions/assert/General/Assert-NotSame.ps1 @@ -0,0 +1,18 @@ +function Assert-NotSame { + param ( + [Parameter(Position=1, ValueFromPipeline=$true)] + $Actual, + [Parameter(Position=0)] + $Expected, + [String]$CustomMessage + ) + + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + if ([object]::ReferenceEquals($Expected, $Actual)) + { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '', to not be the same instance." + throw [Assertions.AssertionException]$Message + } + + $Actual +} \ No newline at end of file diff --git a/src/functions/assert/General/Assert-NotType.ps1 b/src/functions/assert/General/Assert-NotType.ps1 new file mode 100644 index 000000000..3198fcc94 --- /dev/null +++ b/src/functions/assert/General/Assert-NotType.ps1 @@ -0,0 +1,19 @@ +function Assert-NotType { + param ( + [Parameter(Position=1, ValueFromPipeline=$true)] + $Actual, + [Parameter(Position=0)] + [Type]$Expected, + [String]$CustomMessage + ) + + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + if ($Actual -is $Expected) + { + $type = [string]$Expected + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected value to be of different type than '$type', but got '' of type ''." + throw [Assertions.AssertionException]$Message + } + + $Actual +} \ No newline at end of file diff --git a/src/functions/assert/General/Assert-Null.ps1 b/src/functions/assert/General/Assert-Null.ps1 new file mode 100644 index 000000000..ba9773db8 --- /dev/null +++ b/src/functions/assert/General/Assert-Null.ps1 @@ -0,0 +1,16 @@ +function Assert-Null { + param ( + [Parameter(Position=1, ValueFromPipeline=$true)] + $Actual, + [String]$CustomMessage + ) + + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + if ($null -ne $Actual) + { + $Message = Get-AssertionMessage -Expected $null -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected `$null, but got ''." + throw [Assertions.AssertionException]$Message + } + + $Actual +} \ No newline at end of file diff --git a/src/functions/assert/General/Assert-Same.ps1 b/src/functions/assert/General/Assert-Same.ps1 new file mode 100644 index 000000000..5cbff9125 --- /dev/null +++ b/src/functions/assert/General/Assert-Same.ps1 @@ -0,0 +1,23 @@ +function Assert-Same { + param ( + [Parameter(Position=1, ValueFromPipeline=$true)] + $Actual, + [Parameter(Position=0)] + $Expected, + [String]$CustomMessage + ) + + if ($Expected -is [ValueType] -or $Expected -is [string]) + { + throw [ArgumentException]"Assert-Same compares objects by reference. You provided a value type or a string, those are not reference types and you most likely don't need to compare them by reference, see https://github.com/nohwnd/Assert/issues/6.`n`nAre you trying to compare two values to see if they are equal? Use Assert-Equal instead." + } + + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + if (-not ([object]::ReferenceEquals($Expected, $Actual))) + { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '', to be the same instance but it was not." + throw [Assertions.AssertionException]$Message + } + + $Actual +} \ No newline at end of file diff --git a/src/functions/assert/General/Assert-Type.ps1 b/src/functions/assert/General/Assert-Type.ps1 new file mode 100644 index 000000000..14c920c6e --- /dev/null +++ b/src/functions/assert/General/Assert-Type.ps1 @@ -0,0 +1,19 @@ +function Assert-Type { + param ( + [Parameter(Position=1, ValueFromPipeline=$true)] + $Actual, + [Parameter(Position=0)] + [Type]$Expected, + [String]$CustomMessage + ) + + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + if ($Actual -isnot $Expected) + { + $type = [string]$Expected + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected value to be of type '$type', but got '' of type ''." + throw [Assertions.AssertionException]$Message + } + + $Actual +} \ No newline at end of file diff --git a/src/functions/assert/String/Assert-Like.ps1 b/src/functions/assert/String/Assert-Like.ps1 new file mode 100644 index 000000000..d7c75ad81 --- /dev/null +++ b/src/functions/assert/String/Assert-Like.ps1 @@ -0,0 +1,60 @@ +function Test-Like +{ + param ( + [String]$Expected, + $Actual, + [switch]$CaseSensitive + ) + + if (-not $CaseSensitive) + { + $Actual -like $Expected + } + else + { + $Actual -clike $Expected + } +} + +function Get-LikeDefaultFailureMessage ([String]$Expected, $Actual, [switch]$CaseSensitive) +{ + $caseSensitiveMessage = "" + if ($CaseSensitive) + { + $caseSensitiveMessage = " case sensitively" + } + "Expected the string '$Actual' to$caseSensitiveMessage match '$Expected' but it did not." +} + +function Assert-Like +{ + param ( + [Parameter(Position=1, ValueFromPipeline=$true)] + $Actual, + [Parameter(Position=0, Mandatory=$true)] + [String]$Expected, + [Switch]$CaseSensitive, + [String]$CustomMessage + ) + + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + + if ($Actual -isnot [string]) + { + throw [ArgumentException]"Actual is expected to be string, to avoid confusing behavior that -like operator exhibits with collections. To assert on collections use Assert-Any, Assert-All or some other collection assertion." + } + + $stringsAreAlike = Test-Like -Expected $Expected -Actual $Actual -CaseSensitive:$CaseSensitive -IgnoreWhitespace:$IgnoreWhiteSpace + if (-not ($stringsAreAlike)) + { + if (-not $CustomMessage) + { + $formattedMessage = Get-LikeDefaultFailureMessage -Expected $Expected -Actual $Actual -CaseSensitive:$CaseSensitive + } + else + { + $formattedMessage = Get-CustomFailureMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -CaseSensitive:$CaseSensitive + } + throw [Assertions.AssertionException]$formattedMessage + } +} \ No newline at end of file diff --git a/src/functions/assert/String/Assert-NotLike.ps1 b/src/functions/assert/String/Assert-NotLike.ps1 new file mode 100644 index 000000000..960a49e4b --- /dev/null +++ b/src/functions/assert/String/Assert-NotLike.ps1 @@ -0,0 +1,61 @@ +function Test-NotLike +{ + param ( + [String]$Expected, + $Actual, + [switch]$CaseSensitive + ) + + if (-not $CaseSensitive) + { + $Actual -NotLike $Expected + } + else + { + $actual -cNotLike $Expected + } +} + +function Get-NotLikeDefaultFailureMessage ([String]$Expected, $Actual, [switch]$CaseSensitive) +{ + $caseSensitiveMessage = "" + if ($CaseSensitive) + { + $caseSensitiveMessage = " case sensitively" + } + "Expected the string '$Actual' to$caseSensitiveMessage not match '$Expected' but it matched it." +} + +function Assert-NotLike +{ + param ( + [Parameter(Position=1, ValueFromPipeline=$true)] + $Actual, + [Parameter(Position=0, Mandatory=$true)] + [String]$Expected, + [Switch]$CaseSensitive, + [String]$CustomMessage + ) + + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + + if ($Actual -isnot [string]) + { + throw [ArgumentException]"Actual is expected to be string, to avoid confusing behavior that -like operator exhibits with collections. To assert on collections use Assert-Any, Assert-All or some other collection assertion." + } + + $stringsAreANotLike = Test-NotLike -Expected $Expected -Actual $Actual -CaseSensitive:$CaseSensitive -IgnoreWhitespace:$IgnoreWhiteSpace + if (-not ($stringsAreANotLike)) + { + if (-not $CustomMessage) + { + $formattedMessage = Get-NotLikeDefaultFailureMessage -Expected $Expected -Actual $Actual -CaseSensitive:$CaseSensitive + } + else + { + $formattedMessage = Get-CustomFailureMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -CaseSensitive:$CaseSensitive + } + + throw [Assertions.AssertionException]$formattedMessage + } +} \ No newline at end of file diff --git a/src/functions/assert/String/Assert-StringEqual.ps1 b/src/functions/assert/String/Assert-StringEqual.ps1 new file mode 100644 index 000000000..3807ae688 --- /dev/null +++ b/src/functions/assert/String/Assert-StringEqual.ps1 @@ -0,0 +1,59 @@ +function Test-StringEqual +{ + param ( + [String]$Expected, + $Actual, + [switch]$CaseSensitive, + [switch]$IgnoreWhitespace + ) + + if ($IgnoreWhitespace) + { + $Expected = $Expected -replace '\s' + $Actual = $Actual -replace '\s' + } + + if (-not $CaseSensitive) + { + $Expected -eq $Actual + } + else + { + $Expected -ceq $Actual + } +} + +function Get-StringEqualDefaultFailureMessage ([String]$Expected, $Actual) +{ + "Expected the string to be '$Expected' but got '$Actual'." +} + +function Assert-StringEqual +{ + param ( + [Parameter(Position=1, ValueFromPipeline=$true)] + $Actual, + [Parameter(Position=0)] + [String]$Expected, + [String]$CustomMessage, + [switch]$CaseSensitive, + [switch]$IgnoreWhitespace + ) + + $_actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + + if (-not $CustomMessage) + { + $formattedMessage = Get-StringEqualDefaultFailureMessage -Expected $Expected -Actual $_actual + } + else + { + $formattedMessage = Get-CustomFailureMessage -Expected $Expected -Actual $_actual -CustomMessage $CustomMessage + } + + $stringsAreEqual = Test-StringEqual -Expected $Expected -Actual $_actual -CaseSensitive:$CaseSensitive -IgnoreWhitespace:$IgnoreWhiteSpace + if (-not ($stringsAreEqual)) + { + throw [Assertions.AssertionException]$formattedMessage + } +} \ No newline at end of file diff --git a/src/functions/assert/String/Assert-StringNotEqual.ps1 b/src/functions/assert/String/Assert-StringNotEqual.ps1 new file mode 100644 index 000000000..29ef52d8f --- /dev/null +++ b/src/functions/assert/String/Assert-StringNotEqual.ps1 @@ -0,0 +1,31 @@ +function Get-StringNotEqualDefaultFailureMessage ([String]$Expected, $Actual) +{ + "Expected the strings to be different but they were the same '$Expected'." +} + +function Assert-StringNotEqual +{ + param ( + [Parameter(Position=1, ValueFromPipeline=$true)] + $Actual, + [Parameter(Position=0)] + [String]$Expected, + [String]$CustomMessage, + [switch]$CaseSensitive, + [switch]$IgnoreWhitespace + ) + + if (Test-StringEqual -Expected $Expected -Actual $Actual -CaseSensitive:$CaseSensitive -IgnoreWhitespace:$IgnoreWhiteSpace) + { + if (-not $CustomMessage) + { + $formattedMessage = Get-StringNotEqualDefaultFailureMessage -Expected $Expected -Actual $Actual + } + else + { + $formattedMessage = Get-CustomFailureMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage + } + + throw [Assertions.AssertionException]$formattedMessage + } +} \ No newline at end of file diff --git a/tst/functions/assert/Boolean/Assert-False.Tests.ps1 b/tst/functions/assert/Boolean/Assert-False.Tests.ps1 new file mode 100644 index 000000000..53ac8bd47 --- /dev/null +++ b/tst/functions/assert/Boolean/Assert-False.Tests.ps1 @@ -0,0 +1,44 @@ +Describe "Assert-False" { + It "Passes when given `$false" { + $false | Assert-False + } + + It "Passes when given falsy value ''" -TestCases @( + @{ Actual = 0 } + @{ Actual = "" } + @{ Actual = $null } + @{ Actual = @() } + ) { + param($Actual) + Assert-False -Actual $Actual + } + + It "Fails for array input even if the last item is `$false" { + { $true,$true,$false | Assert-False } | Verify-AssertionFailed + } + + It "Fails with custom message" { + $error = { 9 | Assert-False -CustomMessage " is not false" } | Verify-AssertionFailed + $error.Exception.Message | Verify-Equal "9 is not false" + } + + Context "Validate messages" { + It "Given value '' that is not `$false it returns expected message ''" -TestCases @( + @{ Actual = $true ; Message = "Expected bool '`$true' to be bool '`$false' or falsy value 0, """", `$null, @()."}, + @{ Actual = 10 ; Message = "Expected int '10' to be bool '`$false' or falsy value 0, """", `$null, @()."} + ) { + param($Actual, $Message) + $error = { Assert-False -Actual $Actual } | Verify-AssertionFailed + $error.Exception.Message | Verify-Equal $Message + } + } + + It "Returns the value on output" { + $expected = $false + $expected | Assert-False | Verify-Equal $expected + } + + It "Can be called with positional parameters" { + { Assert-False $true } | Verify-AssertionFailed + } +} \ No newline at end of file diff --git a/tst/functions/assert/Boolean/Assert-True.Tests.ps1 b/tst/functions/assert/Boolean/Assert-True.Tests.ps1 new file mode 100644 index 000000000..3f0fb4286 --- /dev/null +++ b/tst/functions/assert/Boolean/Assert-True.Tests.ps1 @@ -0,0 +1,40 @@ +Describe "Assert-True" { + It "Passes when given `$true" { + $true | Assert-True + } + + It "Passes when given truthy" -TestCases @( + @{ Actual = 1 } + @{ Actual = "text" } + @{ Actual = New-Object -TypeName PSObject } + @{ Actual = 1,2 } + ) { + param($Actual) + Assert-True -Actual $Actual + } + + It "Fails with custom message" { + $error = { $null | Assert-True -CustomMessage " is not true" } | Verify-AssertionFailed + $error.Exception.Message | Verify-Equal "`$null is not true" + } + + Context "Validate messages" { + It "Given value that is not `$true it returns expected message ''" -TestCases @( + @{ Actual = $false ; Message = "Expected bool '`$false' to be bool '`$true' or truthy value."}, + @{ Actual = 0 ; Message = "Expected int '0' to be bool '`$true' or truthy value."} + ) { + param($Actual, $Message) + $error = { Assert-True -Actual $Actual } | Verify-AssertionFailed + $error.Exception.Message | Verify-Equal $Message + } + } + + It "Returns the value on output" { + $expected = $true + $expected | Assert-True | Verify-Equal $expected + } + + It "Can be called with positional parameters" { + { Assert-True $false } | Verify-AssertionFailed + } +} \ No newline at end of file diff --git a/tst/functions/assert/Collection/Assert-All.Tests.ps1 b/tst/functions/assert/Collection/Assert-All.Tests.ps1 new file mode 100644 index 000000000..14aff00a3 --- /dev/null +++ b/tst/functions/assert/Collection/Assert-All.Tests.ps1 @@ -0,0 +1,43 @@ +Describe "Assert-All" { + It "Passes when all items in the given collection pass the predicate" -TestCases @( + @{ Actual = 1,1,1,1 } + @{ Actual = @(1) } + @{ Actual = 1 } + ) { + param($Actual) + $Actual | Assert-All -FilterScript { $_ -eq 1 } + } + + It "Fails when any item in the given collection does not pass the predicate" -TestCases @( + @{ Actual = 1,1,2,1 } + @{ Actual = @(2) } + @{ Actual = 2 } + ) { + param($Actual) + { $Actual | Assert-All -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed + } + + It "Validate messages" -TestCases @( + @{ Actual = @(3,4,5); Message = "Expected all items in collection '3, 4, 5' to pass filter '{ `$_ -eq 1 }', but 3 of them '3, 4, 5' did not pass the filter." } + ) { + param($Actual, $Message) + $err = { $Actual | Assert-All -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $Message + } + + It "Returns the value on output" { + $expected = "a","b" + $v = $expected | Assert-All { $true } + $v[0] | Verify-Equal $expected[0] + $v[1] | Verify-Equal $expected[1] + } + + It "Can filter using variables from the sorrounding context" { + $f = 1 + 2,4 | Assert-All { $_ / $f } + } + + It "Accepts FilterScript and Actual by position" { + Assert-All { $true } 1,2 + } +} \ No newline at end of file diff --git a/tst/functions/assert/Collection/Assert-Any.Tests.ps1 b/tst/functions/assert/Collection/Assert-Any.Tests.ps1 new file mode 100644 index 000000000..4c7c973e9 --- /dev/null +++ b/tst/functions/assert/Collection/Assert-Any.Tests.ps1 @@ -0,0 +1,40 @@ +Describe "Assert-Any" { + It "Passes when at least one item in the given collection passes the predicate" -TestCases @( + @{ Actual = @(1,2,3) } + @{ Actual = @(1) } + @{ Actual = 1 } + ) { + param($Actual) + $Actual | Assert-Any -FilterScript { $_ -eq 1 } + } + + It "Fails when none of the items passes the predicate" -TestCases @( + @{ Actual = @(1,2,3) } + @{ Actual = @(1) } + @{ Actual = 1 } + ) { + param($Actual) + { $Actual | Assert-Any -FilterScript { $_ -eq 0 } } | Verify-AssertionFailed + } + + It "Validate messages" -TestCases @( + @{ Actual = @(3,4,5); Message = "Expected at least one item in collection '3, 4, 5' to pass filter '{ `$_ -eq 1 }', but none of the items passed the filter." } + @{ Actual = @(3); Message = "Expected at least one item in collection '3' to pass filter '{ `$_ -eq 1 }', but none of the items passed the filter." } + @{ Actual = 3; Message = "Expected at least one item in collection '3' to pass filter '{ `$_ -eq 1 }', but none of the items passed the filter." } + ) { + param($Actual, $Message) + $err = { $Actual | Assert-Any -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $Message + } + + It "Returns the value on output" { + $expected = "a","b" + $v = $expected | Assert-Any { $true } + $v[0] | Verify-Equal $expected[0] + $v[1] | Verify-Equal $expected[1] + } + + It "Accepts FilterScript and Actual by position" { + Assert-Any { $true } 1,2 + } +} \ No newline at end of file diff --git a/tst/functions/assert/Collection/Assert-Contain.Tests.ps1 b/tst/functions/assert/Collection/Assert-Contain.Tests.ps1 new file mode 100644 index 000000000..bde14dc50 --- /dev/null +++ b/tst/functions/assert/Collection/Assert-Contain.Tests.ps1 @@ -0,0 +1,25 @@ +InModuleScope -ModuleName Assert { + Describe "Assert-Contain" { + It "Passes when collection of single item contains the expected item" { + @(1) | Assert-Contain 1 + } + + It "Fails when collection of single item does not contain the expected item" { + $error = { @(5) | Assert-Contain 1 } | Verify-AssertionFailed + $error.Exception.Message | Verify-Equal "Expected int '1' to be present in collection '5', but it was not there." + } + + It "Passes when collection of multiple items contains the expected item" { + @(1,2,3) | Assert-Contain 1 + } + + It "Fails when collection of multiple items does not contain the expected item" { + $error = { @(5,6,7) | Assert-Contain 1 } | Verify-AssertionFailed + $error.Exception.Message | Verify-Equal "Expected int '1' to be present in collection '5, 6, 7', but it was not there." + } + + It "Can be called with positional parameters" { + { Assert-Contain 1 3,4,5 } | Verify-AssertionFailed + } + } +} \ No newline at end of file diff --git a/tst/functions/assert/Collection/Assert-NotContain.Tests.ps1 b/tst/functions/assert/Collection/Assert-NotContain.Tests.ps1 new file mode 100644 index 000000000..ded3dec65 --- /dev/null +++ b/tst/functions/assert/Collection/Assert-NotContain.Tests.ps1 @@ -0,0 +1,25 @@ +InModuleScope -ModuleName Assert { + Describe "Assert-NotContain" { + It "Fails when collection of single item contains the expected item" { + $error = { @(1) | Assert-NotContain 1 } | Verify-AssertionFailed + $error.Exception.Message | Verify-Equal "Expected int '1' to not be present in collection '1', but it was there." + } + + It "Passes when collection of single item does not contain the expected item" { + @(5) | Assert-NotContain 1 + } + + It "Fails when collection of multiple items contains the expected item" { + $error = { @(1,2,3) | Assert-NotContain 1 } | Verify-AssertionFailed + $error.Exception.Message | Verify-Equal "Expected int '1' to not be present in collection '1, 2, 3', but it was there." + } + + It "Passes when collection of multiple items does not contain the expected item" { + @(5,6,7) | Assert-NotContain 1 + } + + It "Can be called with positional parameters" { + { Assert-NotContain 1 1,2,3 } | Verify-AssertionFailed + } + } +} \ No newline at end of file diff --git a/tst/functions/assert/Common/Ensure-ExpectedIsNotCollection.Tests.ps1 b/tst/functions/assert/Common/Ensure-ExpectedIsNotCollection.Tests.ps1 new file mode 100644 index 000000000..99fa2112f --- /dev/null +++ b/tst/functions/assert/Common/Ensure-ExpectedIsNotCollection.Tests.ps1 @@ -0,0 +1,18 @@ +InModuleScope -ModuleName Assert { + Describe "Ensure-ExpectedIsNotCollection" { + It "Given a collection it throws ArgumentException" { + $error = { Ensure-ExpectedIsNotCollection -InputObject @() } | Verify-Throw + $error.Exception | Verify-Type ([ArgumentException]) + } + + It "Given a collection it throws correct message" { + $error = { Ensure-ExpectedIsNotCollection -InputObject @() } | Verify-Throw + $error.Exception.Message | Verify-Equal 'You provided a collection to the -Expected parameter. Using a collection on the -Expected side is not allowed by this assertion, because it leads to unexpected behavior. Please use Assert-Any, Assert-All or some other specialized collection assertion.' + } + + + It "Given a value it passes it to output when it is not a collection" { + Ensure-ExpectedIsNotCollection -InputObject 'a' | Verify-Equal 'a' + } + } +} \ No newline at end of file diff --git a/tst/functions/assert/Common/Get-AssertionMessage.Tests.ps1 b/tst/functions/assert/Common/Get-AssertionMessage.Tests.ps1 new file mode 100644 index 000000000..ce4f88df0 --- /dev/null +++ b/tst/functions/assert/Common/Get-AssertionMessage.Tests.ps1 @@ -0,0 +1,51 @@ +InModuleScope -ModuleName Assert { + Describe "Get-AssertionMessage" { + It "returns correct message when no tokens are provided" { + $expected = "Static failure message." + $customMessage = "Static failure message." + Get-AssertionMessage -CustomMessage $customMessage -Expected 1 -Actual 2 | Verify-Equal $expected + } + + It "returns correct message when named tokens are provided" { + $expected = "We expected string to be 1, but got 2." + $customMessage = "We expected string to be , but got ." + Get-AssertionMessage -CustomMessage $customMessage -Expected 1 -Actual 2 | Verify-Equal $expected + } + + It "returns correct message when complex objects are provided" { + $expected = "We expected string to be PSObject{Age=28; Name=Jakub}, but got 2." + $customMessage = "We expected string to be , but got ." + Get-AssertionMessage -CustomMessage $customMessage -Expected (New-PSObject @{Name='Jakub';Age=28}) -Actual 2 | Verify-Equal $expected + } + + It "returns correct message when type tokens are provided" { + $expected = "We expected string to be PSObject, but got int." + $customMessage = "We expected string to be , but got ." + Get-AssertionMessage -CustomMessage $customMessage -Expected (New-PSObject @{Name='Jakub';Age=28}) -Actual 2 | Verify-Equal $expected + } + + It "returns correct type message when `$null is provided" { + $expected = "Expected type is , and actual type is ." + $customMessage = "Expected type is , and actual type is ." + Get-AssertionMessage -CustomMessage $customMessage -Expected $null -Actual $null | Verify-Equal $expected + } + + It "returns correct message when option is provided" { + $expected = "Expected 'a', but got 'b'. Used options: CaseSensitive, IgnoreWhitespace." + $customMessage = "Expected 'a', but got 'b'. " + Get-AssertionMessage -CustomMessage $customMessage -Expected 'a' -Actual 'b' -Option "CaseSensitive","IgnoreWhitespace" | Verify-Equal $expected + } + + It "returns correct message when additional data are provided" { + $expected = "but 3 of them '1, 2, 3' did not pass the filter." + + $customMessage = "but of them '' did not pass the filter." + $data = @{ + actualFilteredCount = 3 + actualFiltered = 1, 2, 3 + } + + Get-AssertionMessage -CustomMessage $customMessage -Data $data | Verify-Equal $expected + } + } +} \ No newline at end of file diff --git a/tst/functions/assert/Equivalence/Assert-Equivalent.Options.Tests.ps1 b/tst/functions/assert/Equivalence/Assert-Equivalent.Options.Tests.ps1 new file mode 100644 index 000000000..632b1d31e --- /dev/null +++ b/tst/functions/assert/Equivalence/Assert-Equivalent.Options.Tests.ps1 @@ -0,0 +1,380 @@ +InModuleScope -ModuleName Assert { + Describe "Compare-Equivalent - Exclude path options" { + Context "Full excluded paths" { + + It "Given a full path to a property it ignores it on the Expected object" -TestCases @( + @{ Path = $null } + @{ Path = "ParentProperty1" } + @{ Path = "ParentProperty1.ParentProperty2" } + ) { + param ($Path) + + $expected = New-PSObject @{ + Name = "Jakub" + Age = 30 + } + + $actual = New-PSObject @{ + Name = "Jakub" + } + + $options = Get-EquivalencyOption -ExcludePath ("$Path.Age".Trim('.')) + Compare-Equivalent -Actual $actual -Expected $expected -Path $Path -Options $options | Verify-Null + } + + It "Given a full path to a property it ignores it on the Actual object" -TestCases @( + @{ Path = $null } + @{ Path = "ParentProperty1" } + @{ Path = "ParentProperty1.ParentProperty2" } + ) { + param ($Path) + $expected = New-PSObject @{ + Name = "Jakub" + } + + $actual = New-PSObject @{ + Name = "Jakub" + Age = 30 + } + + $options = Get-EquivalencyOption -ExcludePath ("$Path.Age".Trim('.')) + Compare-Equivalent -Actual $actual -Expected $expected -Path $Path -Options $options | Verify-Null + } + + + It "Given a full path to a property on object that is in collection it ignores it on the Expected object" { + $expected = New-PSObject @{ + ProgrammingLanguages = @( + (New-PSObject @{ + Name = "C#" + Type = "OO" + }), + (New-PSObject @{ + Name = "PowerShell" + }) + ) + } + + $actual = New-PSObject @{ + ProgrammingLanguages = @( + (New-PSObject @{ + Name = "C#" + }), + (New-PSObject @{ + Name = "PowerShell" + }) + ) + } + + + $options = Get-EquivalencyOption -ExcludePath "ProgrammingLanguages.Type" + Compare-Equivalent -Actual $actual -Expected $expected -Options $options | Verify-Null + } + + It "Given a full path to a property on object that is in collection it ignores it on the Actual object" { + $expected = New-PSObject @{ + ProgrammingLanguages = @( + (New-PSObject @{ + Name = "C#" + }), + (New-PSObject @{ + Name = "PowerShell" + }) + ) + } + + $actual = New-PSObject @{ + ProgrammingLanguages = @( + (New-PSObject @{ + Name = "C#" + Type = "OO" + }), + (New-PSObject @{ + Name = "PowerShell" + }) + ) + } + + + $options = Get-EquivalencyOption -ExcludePath "ProgrammingLanguages.Type" + Compare-Equivalent -Actual $actual -Expected $expected -Options $options | Verify-Null + } + + It "Given a full path to a property on object that is in hashtable it ignores it on the Expected object" { + $expected = New-PSObject @{ + ProgrammingLanguages = @{ + Language1 = (New-PSObject @{ + Name = "C#" + Type = "OO" + }); + Language2 = (New-PSObject @{ + Name = "PowerShell" + }) + } + } + + $actual = New-PSObject @{ + ProgrammingLanguages = @{ + Language1 = (New-PSObject @{ + Name = "C#" + }); + Language2 = (New-PSObject @{ + Name = "PowerShell" + }) + } + } + + $options = Get-EquivalencyOption -ExcludePath "ProgrammingLanguages.Language1.Type" + Compare-Equivalent -Actual $actual -Expected $expected -Options $options | Verify-Null + } + + # in the above tests we are not testing all the possible options of skippin in all possible + # emumerable objects, but this many tests should still be enough. The Path unifies how different + # collections are handled, and we filter out based on the path on the start of Compare-Equivalent + # so the same rules should apply transitively no matter the collection type + + + It "Given a full path to a key on a hashtable it ignores it on the Expected hashtable" { + $expected = @{ + Name = "C#" + Type = "OO" + } + + $actual = @{ + Name = "C#" + } + + $options = Get-EquivalencyOption -ExcludePath "Type" + Compare-Equivalent -Actual $actual -Expected $expected -Options $options | Verify-Null + } + + It "Given a full path to a key on a hashtable it ignores it on the Actual hashtable" { + $expected = @{ + Name = "C#" + } + + $actual = @{ + Name = "C#" + Type = "OO" + } + + $options = Get-EquivalencyOption -ExcludePath "Type" + Compare-Equivalent -Actual $actual -Expected $expected -Options $options | Verify-Null + } + + It "Given a full path to a key on a dictionary it ignores it on the Expected dictionary" { + $expected = New-Dictionary @{ + Name = "C#" + Type = "OO" + } + + $actual = New-Dictionary @{ + Name = "C#" + } + + $options = Get-EquivalencyOption -ExcludePath "Type" + Compare-Equivalent -Actual $actual -Expected $expected -Options $options | Verify-Null + } + + It "Given a full path to a key on a dictionary it ignores it on the Actual dictionary" { + $expected = New-Dictionary @{ + Name = "C#" + } + + $actual = New-Dictionary @{ + Name = "C#" + Type = "OO" + } + + $options = Get-EquivalencyOption -ExcludePath "Type" + Compare-Equivalent -Actual $actual -Expected $expected -Options $options | Verify-Null + } + + It "Given options it passes them correctly from Assert-Equivalent" { + $expected = New-PSObject @{ + Name = "Jakub" + Location = "Prague" + Age = 30 + } + + $actual = New-PSObject @{ + Name = "Jakub" + } + + $options = Get-EquivalencyOption -ExcludePath "Age", "NonExisting" + $err = { Assert-Equivalent -Actual $actual -Expected $expected -Options $options } | Verify-AssertionFailed + + $err.Exception.Message | Verify-Like "*Expected has property 'Location'*" + $err.Exception.Message | Verify-Like "*Exclude path 'Age'*" + } + } + + Context "Wildcard path exclusions" { + It "Given wildcarded path it ignores it on the expected object" { + $expected = [PSCustomObject] @{ + Name = "Jakub" + Location = "Prague" + } + + $actual = [PSCustomObject] @{ + Name = "Jakub" + } + + $options = Get-EquivalencyOption -ExcludePath Loc* + Assert-Equivalent -Actual $actual -Expected $expected -Options $Options + } + + It "Given wildcarded path it ignores it on the actual object" { + $expected = [PSCustomObject] @{ + Name = "Jakub" + } + + $actual = [PSCustomObject] @{ + Name = "Jakub" + Location = "Prague" + } + + $options = Get-EquivalencyOption -ExcludePath Loc* + Assert-Equivalent -Actual $actual -Expected $expected -Options $Options + } + + It "Given wildcarded path it ignores it on the expected hashtable" { + $expected = @{ + Name = "Jakub" + Location = "Prague" + } + + $actual = @{ + Name = "Jakub" + } + + $options = Get-EquivalencyOption -ExcludePath Loc* + Assert-Equivalent -Actual $actual -Expected $expected -Options $Options + } + + It "Given wildcarded path it ignores it on the actual hashtable" { + $expected = @{ + Name = "Jakub" + } + + $actual = @{ + Name = "Jakub" + Location = "Prague" + } + + $options = Get-EquivalencyOption -ExcludePath Loc* + Assert-Equivalent -Actual $actual -Expected $expected -Options $Options + } + + It "Given wildcarded path it ignores it on the expected dictionary" { + $expected = New-Dictionary @{ + Name = "Jakub" + Location = "Prague" + } + + $actual = New-Dictionary @{ + Name = "Jakub" + } + + $options = Get-EquivalencyOption -ExcludePath Loc* + Assert-Equivalent -Actual $actual -Expected $expected -Options $Options + } + + It "Given wildcarded path it ignores it on the actual dictionary" { + $expected = New-Dictionary @{ + Name = "Jakub" + } + + $actual = New-Dictionary @{ + Name = "Jakub" + Location = "Prague" + } + + $options = Get-EquivalencyOption -ExcludePath Loc* + Assert-Equivalent -Actual $actual -Expected $expected -Options $Options + } + } + + Context "-ExcludePathsNotOnExpected" { + It "Given actual object that has more properties that expected it skips them" { + $expected = [PSCustomObject] @{ + Name = "Jakub" + } + + $actual = [PSCustomObject] @{ + Name = "Jakub" + Location = "Prague" + Age = 30 + } + + $options = Get-EquivalencyOption -ExcludePathsNotOnExpected + Assert-Equivalent -Actual $actual -Expected $expected -Options $Options + } + + It "Given actual hashtable that has more keys that expected it skips them" { + $expected = @{ + Name = "Jakub" + } + + $actual = @{ + Name = "Jakub" + Location = "Prague" + Age = 30 + } + + $options = Get-EquivalencyOption -ExcludePathsNotOnExpected + Assert-Equivalent -Actual $actual -Expected $expected -Options $Options + } + + It "Given actual dictionary that has more keys that expected it skips them" { + $expected = New-Dictionary @{ + Name = "Jakub" + } + + $actual = New-Dictionary @{ + Name = "Jakub" + Location = "Prague" + Age = 30 + } + + $options = Get-EquivalencyOption -ExcludePathsNotOnExpected + Assert-Equivalent -Actual $actual -Expected $expected -Options $Options + } + } + } + + Describe "Compare-Equiavlent - equality comparison options" { + It "Given objects that are equivalent and -Comparator Equality option it compares them as different" { + $expected = New-PsObject @{ + LikesIfsInMocks = $false + } + + $actual = New-PsObject @{ + LikesIfsInMocks = "False" + } + + $options = Get-EquivalencyOption -Comparator Equality + { Assert-Equivalent -Actual $actual -Expected $expected -Options $options } | Verify-AssertionFailed + } + } + + + Describe "Printing Options into difference report" { + + It "Given options that exclude property it shows up in the difference report correctly" { + $options = Get-EquivalencyOption -ExcludePath "Age", "Name", "Person.Age", "Person.Created*" + Clear-WhiteSpace (Format-EquivalencyOptions -Options $options) | Verify-Equal (Clear-WhiteSpace " + Exclude path 'Age' + Exclude path 'Name' + Exclude path 'Person.Age' + Exclude path 'Person.Created*'") + } + + It "Given options that exclude property it shows up in the difference report correctly" { + $options = Get-EquivalencyOption -ExcludePathsNotOnExpected + Clear-WhiteSpace (Format-EquivalencyOptions -Options $options) | Verify-Equal (Clear-WhiteSpace " + Excluding all paths not found on Expected") + } + } + +} \ No newline at end of file diff --git a/tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 b/tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 new file mode 100644 index 000000000..6a4426744 --- /dev/null +++ b/tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 @@ -0,0 +1,483 @@ +BeforeDiscovery { + Add-Type -TypeDefinition 'namespace Assertions.TestType { + public class Person2 { + // powershell v2 mandates fully implemented properties + string _name; + int _age; + public string Name { get { return _name; } set { _name = value; } } + public int Age { get { return _age; } set { _age = value; } } + } + }' +} + +InModuleScope -ModuleName Assert { + BeforeAll { + function Get-TestCase ($Value) { + #let's see if this is useful, it's nice for values, but sucks for + #types that serialize to just the type name (most of them) + if ($null -ne $Value) + { + @{ + Value = $Value + Type = $Value.GetType() + } + } + else + { + @{ + Value = $null + Type = '' + } + } + } + } + + Describe "Test-Same" { + It "Given the same instance of a reference type it returns `$true" -TestCases @( + @{ Value = $null }, + @{ Value = @() }, + @{ Value = [Type] }, + @{ Value = (New-Object -TypeName Diagnostics.Process) } + ) { + param($Value) + Test-Same -Expected $Value -Actual $Value | Verify-True + } + + It "Given different instances of a reference type it returns `$false" -TestCases @( + @{ Actual = @(); Expected = @() }, + @{ Actual = (New-Object -TypeName Diagnostics.Process) ; Expected = (New-Object -TypeName Diagnostics.Process) } + ) { + param($Expected, $Actual) + Test-Same -Expected $Expected -Actual $Actual | Verify-False + } + } + + Describe "Get-TestCase" { + It "Given a value it returns the value and its type in a hashtable" { + $expected = @{ + Value = 1 + Type = [Int] + } + + $actual = Get-TestCase -Value $expected.Value + + $actual.GetType().Name | Verify-Equal 'hashtable' + $actual.Value | Verify-Equal $expected.Value + $actual.Type | Verify-Equal $expected.Type + } + + It "Given `$null it returns as the name of the type" { + $expected = @{ + Value = $null + Type = 'none' + } + + $actual = Get-TestCase -Value $expected.Value + + $actual.GetType().Name | Verify-Equal 'hashtable' + $actual.Value | Verify-Null + $actual.Type | Verify-Equal '' + } + } + + Describe "Get-ValueNotEquivalentMessage" { + It "Returns correct message when comparing value to an object" { + $e = 'abc' + $a = New-PSObject @{ Name = 'Jakub'; Age = 28 } + Get-ValueNotEquivalentMessage -Actual $a -Expected $e | + Verify-Equal "Expected 'abc' to be equivalent to the actual value, but got 'PSObject{Age=28; Name=Jakub}'." + } + + It "Returns correct message when comparing object to a value" { + $e = New-PSObject @{ Name = 'Jakub'; Age = 28 } + $a = 'abc' + Get-ValueNotEquivalentMessage -Actual $a -Expected $e | + Verify-Equal "Expected 'PSObject{Age=28; Name=Jakub}' to be equivalent to the actual value, but got 'abc'." + } + + It "Returns correct message when comparing value to an array" { + $e = 'abc' + $a = 1,2,3 + Get-ValueNotEquivalentMessage -Actual $a -Expected $e | + Verify-Equal "Expected 'abc' to be equivalent to the actual value, but got '1, 2, 3'." + } + + It "Returns correct message when comparing value to null" { + $e = 'abc' + $a = $null + Get-ValueNotEquivalentMessage -Actual $a -Expected $e | + Verify-Equal "Expected 'abc' to be equivalent to the actual value, but got '`$null'." + } + + It "Returns correct message for given property" { + $e = 1 + $a = 2 + Get-ValueNotEquivalentMessage -Actual 1 -Expected 2 -Property ".Age" | + Verify-Equal "Expected property .Age with value '2' to be equivalent to the actual value, but got '1'." + } + + It "Changes wording to 'equal' when options specify Equality comparator" { + $e = 1 + $a = 2 + $options = Get-EquivalencyOption -Comparator Equality + Get-ValueNotEquivalentMessage -Actual 1 -Expected 2 -Options $options | + Verify-Equal "Expected '2' to be equal to the actual value, but got '1'." + } + } + + Describe "Is-CollectionSize" { + It "Given two collections '' '' of the same size it returns `$true" -TestCases @( + @{ Actual = (1,2,3); Expected = (1,2,3)}, + @{ Actual = (1,2,3); Expected = (3,2,1)} + ) { + param ($Actual, $Expected) + Is-CollectionSize -Actual $Actual -Expected $Expected | Verify-True + } + + It "Given two collections '' '' of different sizes it returns `$false" -TestCases @( + @{ Actual = (1,2,3); Expected = (1,2,3,4)}, + @{ Actual = (1,2,3); Expected = (1,2)} + @{ Actual = (1,2,3); Expected = @()} + ) { + param ($Actual, $Expected) + Is-CollectionSize -Actual $Actual -Expected $Expected | Verify-False + } + } + + Describe "Get-CollectionSizeNotTheSameMessage" { + It "Given two collections of differrent sizes it returns the correct message" { + Get-CollectionSizeNotTheSameMessage -Expected (1,2,3) -Actual (1,2) | Verify-Equal "Expected collection '1, 2, 3' with length '3' to be the same size as the actual collection, but got '1, 2' with length '2'." + } + } + + Describe "Compare-ValueEquivalent" { + It "Given expected that is not a value it throws ArgumentException" { + $err = { Compare-ValueEquivalent -Actual "dummy" -Expected (Get-Process -Id $PID) } | Verify-Throw + $err.Exception -is [ArgumentException] | Verify-True + } + + It "Given values '' and '' that are not equivalent it returns message ''." -TestCases @( + @{ Actual = $null; Expected = 1; Message = "Expected '1' to be equivalent to the actual value, but got '`$null'." }, + @{ Actual = $null; Expected = ""; Message = "Expected '' to be equivalent to the actual value, but got '`$null'." }, + @{ Actual = $true; Expected = $false; Message = "Expected '`$false' to be equivalent to the actual value, but got '`$true'." }, + @{ Actual = $true; Expected = 'False'; Message = "Expected '`$false' to be equivalent to the actual value, but got '`$true'." }, + @{ Actual = 1; Expected = -1; Message = "Expected '-1' to be equivalent to the actual value, but got '1'." }, + @{ Actual = "1"; Expected = 1.01; Message = "Expected '1.01' to be equivalent to the actual value, but got '1'." }, + @{ Actual = "abc"; Expected = "a b c"; Message = "Expected 'a b c' to be equivalent to the actual value, but got 'abc'." }, + @{ Actual = @("abc", "bde"); Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got 'abc, bde'." }, + @{ Actual = {def}; Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got '{def}'." }, + @{ Actual = (New-PSObject @{ Name = 'Jakub' }); Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got 'PSObject{Name=Jakub}'." }, + @{ Actual = (1,2,3); Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got '1, 2, 3'." } + ) { + param($Actual, $Expected, $Message) + Compare-ValueEquivalent -Actual $Actual -Expected $Expected | Verify-Equal $Message + } + } + + Describe "Compare-CollectionEquivalent" { + It "Given expected that is not a collection it throws ArgumentException" { + $err = { Compare-CollectionEquivalent -Actual "dummy" -Expected 1 } | Verify-Throw + $err.Exception -is [ArgumentException] | Verify-True + } + + It "Given two collections '' '' of different sizes it returns message ''" -TestCases @( + @{ Actual = (1,2,3); Expected = (1,2,3,4); Message = "Expected collection '1, 2, 3, 4' with length '4' to be the same size as the actual collection, but got '1, 2, 3' with length '3'."}, + @{ Actual = (1,2,3); Expected = (3,1); Message = "Expected collection '3, 1' with length '2' to be the same size as the actual collection, but got '1, 2, 3' with length '3'." } + ) { + param ($Actual, $Expected, $Message) + Compare-CollectionEquivalent -Actual $Actual -Expected $Expected | Verify-Equal $Message + } + + It "Given collection '' on the expected side and non-collection '' on the actual side it prints the correct message ''" -TestCases @( + @{ Actual = 3; Expected = (1,2,3,4); Message = "Expected collection '1, 2, 3, 4' with length '4', but got '3'."}, + @{ Actual = (New-PSObject @{ Name = 'Jakub' }); Expected = (1,2,3,4); Message = "Expected collection '1, 2, 3, 4' with length '4', but got 'PSObject{Name=Jakub}'."} + ) { + param ($Actual, $Expected, $Message) + Compare-CollectionEquivalent -Actual $Actual -Expected $Expected | Verify-Equal $Message + } + + It "Given two collections '' '' it compares each value with each value and returns `$null if all of them are equivalent" -TestCases @( + @{ Actual = (1,2,3); Expected = (1,2,3)} + @{ Actual = (1,2,3); Expected = (3,2,1)} + + # issue https://github.com/nohwnd/Assert/issues/31 + @{ Actual = ($null, $null); Expected = ($null, $null) } + @{ Actual = ($null, $null, $null); Expected = ($null, $null, $null) } + @{ Actual = (1, 1, 1, 1); Expected = (1, 1, 1, 1) } + @{ Actual = (1, 2, 2, 1); Expected = (2, 1, 2, 1) } + ## + + ) { + param ($Actual, $Expected) + Compare-CollectionEquivalent -Actual $Actual -Expected $Expected | Verify-Null + } + + It "Given two collections '' '' it compares each value with each value and returns message ' if any of them are not equivalent" -TestCases @( + @{ Actual = (1,2,3); Expected = (4,5,6); Message = "Expected collection '4, 5, 6' to be equivalent to '1, 2, 3' but some values were missing: '4, 5, 6'."}, + @{ Actual = (1,2,3); Expected = (1,2,2); Message = "Expected collection '1, 2, 2' to be equivalent to '1, 2, 3' but some values were missing: '2'."} + ) { + param ($Actual, $Expected, $Message) + Compare-CollectionEquivalent -Actual $Actual -Expected $Expected | Verify-Equal $Message + } + } + + Describe "Compare-ObjectEquivalent" { + It "Given expected '' that is not an object it throws ArgumentException" -TestCases @( + @{ Expected = "a" }, + @{ Expected = "1" }, + @{ Expected = { abc } }, + @{ Expected = (1,2,3) } + ) { + param($Expected) {} + $err = { Compare-ObjectEquivalent -Actual "dummy" -Expected $Expected } | Verify-Throw + $err.Exception -is [ArgumentException] | Verify-True + } + + It "Given values '' and '' that are not equivalent it returns message ''." -TestCases @( + @{ Actual = 'a'; Expected = (New-PSObject @{ Name = 'Jakub' }); Message = "Expected object 'PSObject{Name=Jakub}', but got 'a'."} + ) { + param ($Actual, $Expected, $Message) + Compare-ObjectEquivalent -Expected $Expected -Actual $Actual | Verify-Equal $Message + } + } + + Describe "Compare-HashtableEquivalent" { + It "Given expected '' that is not a hashtable it throws ArgumentException" -TestCases @( + @{ Expected = "a" } + ) { + param($Expected) {} + $err = { Compare-HashtableEquivalent -Actual "dummy" -Expected $Expected } | Verify-Throw + $err.Exception -is [ArgumentException] | Verify-True + } + + It "Given values '' and '' that are not equivalent it returns message ''." -TestCases @( + @{ Actual = 'a'; Expected = @{ Name = 'Jakub' }; Message = "Expected hashtable '@{Name=Jakub}', but got 'a'." } + @{ Actual = @{ }; Expected = @{ Name = 'Jakub' }; Message = "Expected hashtable '@{Name=Jakub}', but got '@{}'.`nExpected has key 'Name' that the other object does not have." } + @{ Actual = @{ Name = 'Tomas' }; Expected = @{ Name = 'Jakub' }; Message = "Expected hashtable '@{Name=Jakub}', but got '@{Name=Tomas}'.`nExpected property .Name with value 'Jakub' to be equivalent to the actual value, but got 'Tomas'." } + @{ Actual = @{ Name = 'Tomas'; Value = 10 }; Expected = @{ Name = 'Jakub' }; Message = "Expected hashtable '@{Name=Jakub}', but got '@{Name=Tomas; Value=10}'.`nExpected property .Name with value 'Jakub' to be equivalent to the actual value, but got 'Tomas'.`nExpected is missing key 'Value' that the other object has." } + ) { + param ($Actual, $Expected, $Message) + + Compare-HashtableEquivalent -Expected $Expected -Actual $Actual | Verify-Equal $Message + } + } + + Describe "Compare-DictionaryEquivalent" { + It "Given expected '' that is not a dictionary it throws ArgumentException" -TestCases @( + @{ Expected = "a" } + ) { + param($Expected) {} + $err = { Compare-DictionaryEquivalent -Actual "dummy" -Expected $Expected } | Verify-Throw + $err.Exception -is [ArgumentException] | Verify-True + } + + It "Given values '' and '' that are not equivalent it returns message ''." -TestCases @( + @{ Actual = 'a'; Expected = New-Dictionary @{ Name = 'Jakub' }; Message = "Expected dictionary 'Dictionary{Name=Jakub}', but got 'a'." } + @{ Actual = New-Dictionary @{ }; Expected = New-Dictionary @{ Name = 'Jakub' }; Message = "Expected dictionary 'Dictionary{Name=Jakub}', but got 'Dictionary{}'.`nExpected has key 'Name' that the other object does not have." } + @{ Actual = New-Dictionary @{ Name = 'Tomas' }; Expected = New-Dictionary @{ Name = 'Jakub' }; Message = "Expected dictionary 'Dictionary{Name=Jakub}', but got 'Dictionary{Name=Tomas}'.`nExpected property .Name with value 'Jakub' to be equivalent to the actual value, but got 'Tomas'." } + @{ Actual = New-Dictionary @{ Name = 'Tomas'; Value = 10 }; Expected = New-Dictionary @{ Name = 'Jakub' }; Message = "Expected dictionary 'Dictionary{Name=Jakub}', but got 'Dictionary{Name=Tomas; Value=10}'.`nExpected property .Name with value 'Jakub' to be equivalent to the actual value, but got 'Tomas'.`nExpected is missing key 'Value' that the other object has." } + ) { + param ($Actual, $Expected, $Message) + + Compare-DictionaryEquivalent -Expected $Expected -Actual $Actual | Verify-Equal $Message + } + } + + Describe "Compare-Equivalent" { + It "Given values '' and '' that are equivalent returns report with Equivalent set to `$true" -TestCases @( + @{ Actual = $null; Expected = $null }, + @{ Actual = ""; Expected = "" }, + @{ Actual = $true; Expected = $true }, + @{ Actual = $true; Expected = 'True' }, + @{ Actual = 'True'; Expected = $true }, + @{ Actual = $false; Expected = 'False' }, + @{ Actual = 'False'; Expected = $false}, + @{ Actual = 1; Expected = 1 }, + @{ Actual = "1"; Expected = 1 }, + @{ Actual = "abc"; Expected = "abc" }, + @{ Actual = @("abc"); Expected = "abc" }, + @{ Actual = "abc"; Expected = @("abc") }, + @{ Actual = {abc}; Expected = "abc" }, + @{ Actual = "abc"; Expected = {abc} }, + @{ Actual = {abc}; Expected = {abc} } + ) { + param ($Actual, $Expected) + Compare-Equivalent -Expected $Expected -Actual $Actual | Verify-Null + } + + It "Given values '' and '' that are not equivalent it returns message ''." -TestCases @( + @{ Actual = $null; Expected = 1; Message = "Expected '1' to be equivalent to the actual value, but got '`$null'." }, + @{ Actual = $null; Expected = ""; Message = "Expected '' to be equivalent to the actual value, but got '`$null'." }, + @{ Actual = $true; Expected = $false; Message = "Expected '`$false' to be equivalent to the actual value, but got '`$true'." }, + @{ Actual = $true; Expected = 'False'; Message = "Expected '`$false' to be equivalent to the actual value, but got '`$true'." }, + @{ Actual = 1; Expected = -1; Message = "Expected '-1' to be equivalent to the actual value, but got '1'." }, + @{ Actual = "1"; Expected = 1.01; Message = "Expected '1.01' to be equivalent to the actual value, but got '1'." }, + @{ Actual = "abc"; Expected = "a b c"; Message = "Expected 'a b c' to be equivalent to the actual value, but got 'abc'." }, + @{ Actual = @("abc", "bde"); Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got 'abc, bde'." }, + @{ Actual = {def}; Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got '{def}'." }, + @{ Actual = "def"; Expected = {abc}; Message = "Expected '{abc}' to be equivalent to the actual value, but got 'def'." }, + @{ Actual = {abc}; Expected = {def}; Message = "Expected '{def}' to be equivalent to the actual value, but got '{abc}'." }, + @{ Actual = (1,2,3); Expected = (1,2,3,4); Message = "Expected collection '1, 2, 3, 4' with length '4' to be the same size as the actual collection, but got '1, 2, 3' with length '3'."}, + @{ Actual = 3; Expected = (1,2,3,4); Message = "Expected collection '1, 2, 3, 4' with length '4', but got '3'."}, + @{ Actual = (New-PSObject @{ Name = 'Jakub' }); Expected = (1,2,3,4); Message = "Expected collection '1, 2, 3, 4' with length '4', but got 'PSObject{Name=Jakub}'."}, + @{ Actual = (New-PSObject @{ Name = 'Jakub' }); Expected = "a"; Message = "Expected 'a' to be equivalent to the actual value, but got 'PSObject{Name=Jakub}'." }, + @{ Actual = 'a'; Expected = (New-PSObject @{ Name = 'Jakub' }); Message = "Expected object 'PSObject{Name=Jakub}', but got 'a'."} + @{ Actual = 'a'; Expected = @{ Name = 'Jakub' }; Message = "Expected hashtable '@{Name=Jakub}', but got 'a'." } + @{ Actual = 'a'; Expected = New-Dictionary @{ Name = 'Jakub' }; Message = "Expected dictionary 'Dictionary{Name=Jakub}', but got 'a'." } + ) { + param ($Actual, $Expected, $Message) + Compare-Equivalent -Expected $Expected -Actual $Actual | Verify-Equal $Message + } + + It "Comparing the same instance of a psObject returns null"{ + $actual = $expected = New-PSObject @{ Name = 'Jakub' } + Verify-Same -Expected $expected -Actual $actual + + Compare-Equivalent -Expected $expected -Actual $actual | Verify-Null + } + + It "Given PSObjects '' and ' that are different instances but have the same values it returns report with Equivalent set to `$true" -TestCases @( + @{ + Expected = New-PSObject @{ Name = 'Jakub' } + Actual = New-PSObject @{ Name = 'Jakub' } + }, + @{ + Expected = New-PSObject @{ Name = 'Jakub' } + Actual = New-PSObject @{ Name = 'Jakub' } + }, + @{ + Expected = New-PSObject @{ Age = 28 } + Actual = New-PSObject @{ Age = '28' } + } + ) { + param ($Expected, $Actual) + Verify-NotSame -Expected $Expected -Actual $Actual + + Compare-Equivalent -Expected $Expected -Actual $Actual | Verify-Null + } + + It "Given PSObjects '' and ' that have different values in some of the properties it returns message ''" -TestCases @( + @{ + Expected = New-PSObject @{ Name = 'Jakub'; Age = 28 } + Actual = New-PSObject @{ Name = 'Jakub'; Age = 19 } + Message = "Expected property .Age with value '28' to be equivalent to the actual value, but got '19'." + }, + @{ + Expected = New-PSObject @{ Name = 'Jakub'; Age = 28 } + Actual = New-PSObject @{ Name = 'Jakub'} + Message = "Expected has property 'Age' that the other object does not have." + }, + @{ + Expected = New-PSObject @{ Name = 'Jakub'} + Actual = New-PSObject @{ Name = 'Jakub'; Age = 28 } + Message = "Expected is missing property 'Age' that the other object has." + } + ) { + param ($Expected, $Actual, $Message) + Verify-NotSame -Expected $Expected -Actual $Actual + + Compare-Equivalent -Expected $Expected -Actual $Actual | Verify-Equal $Message + } + + It "Given PSObject '' and object ' that have the same values it returns `$null" -TestCases @( + @{ + Expected = New-Object -TypeName Assertions.TestType.Person2 -Property @{ Name = 'Jakub'; Age = 28} + Actual = New-PSObject @{ Name = 'Jakub'; Age = 28 } + } + ) { + param ($Expected, $Actual) + Compare-Equivalent -Expected $Expected -Actual $Actual | Verify-Null + } + + + It "Given PSObjects '' and ' that contain different arrays in the same property returns the correct message" -TestCases @( + @{ + Expected = New-PSObject @{ Numbers = 1,2,3 } + Actual = New-PSObject @{ Numbers = 3,4,5 } + } + ) { + param ($Expected, $Actual) + + Compare-Equivalent -Expected $Expected -Actual $Actual | Verify-Equal "Expected collection in property .Numbers which is '1, 2, 3' to be equivalent to '3, 4, 5' but some values were missing: '1, 2'." + } + + It "Comparing psObjects that have collections of objects returns `$null when the objects have the same value" -TestCases @( + @{ + Expected = New-PSObject @{ Objects = (New-PSObject @{ Name = "Jan" }), (New-PSObject @{ Name = "Tomas" }) } + Actual = New-PSObject @{ Objects = (New-PSObject @{ Name = "Tomas" }), (New-PSObject @{ Name = "Jan" }) } + } + ) { + param ($Expected, $Actual) + Compare-Equivalent -Expected $Expected -Actual $Actual | Verify-Null + } + + It "Comparing psObjects that have collections of objects returns the correct message when the items in the collection differ" -TestCases @( + @{ + Expected = New-PSObject @{ Objects = (New-PSObject @{ Name = "Jan" }), (New-PSObject @{ Name = "Petr" }) } + Actual = New-PSObject @{ Objects = (New-PSObject @{ Name = "Jan" }), (New-PSObject @{ Name = "Tomas" }) } + } + ) { + param ($Expected, $Actual) + Compare-Equivalent -Expected $Expected -Actual $Actual | Verify-Equal "Expected collection in property .Objects which is 'PSObject{Name=Jan}, PSObject{Name=Petr}' to be equivalent to 'PSObject{Name=Jan}, PSObject{Name=Tomas}' but some values were missing: 'PSObject{Name=Petr}'." + } + + It "Comparing DataTable" { + # todo: move this to it's own describe, split the tests to smaller parts, and make them use Verify-* axioms + $Expected = New-Object Data.DataTable 'Test' + $null = $Expected.Columns.Add('IDD', [System.Int32]) + $null = $Expected.Columns.Add('Name') + $null = $Expected.Columns.Add('Junk') + $null = $Expected.Columns.Add('IntT', [System.Int32]) + $null = $Expected.Rows.Add(1, 'A', 'AAA', 5) + $null = $Expected.Rows.Add(3, 'C', $null, $null) + + $Actual = New-Object Data.DataTable 'Test' + $null = $Actual.Columns.Add('IDD', [System.Int32]) + $null = $Actual.Columns.Add('Name') + $null = $Actual.Columns.Add('Junk') + $null = $Actual.Columns.Add('IntT', [System.Int32]) + $null = $Actual.Rows.Add(3, 'C', $null, $null) + $null = $Actual.Rows.Add(1, 'A', 'AAA', 5) + + Assert-Equivalent -Actual $Actual -Expected $Expected + + function SerializeDeserialize ($InputObject) { + # psv2 compatibility + # $ExpectedDeserialized = [System.Management.Automation.PSSerializer]::Deserialize([System.Management.Automation.PSSerializer]::Serialize($Expected)) + # Alternatively this could be done in memory via https://github.com/Jaykul/Reflection/blob/master/CliXml.psm1, but I don't want to fiddle with more + # relfection right now + try { + $path = [IO.Path]::GetTempFileName() + + Export-Clixml -Path $path -InputObject $InputObject -Force | Out-Null + Import-Clixml -Path $path + } + finally { + if ($null -ne $path -and (Test-Path $path)) { + Remove-Item -Path $path -Force + } + } + } + + + $ExpectedDeserialized = SerializeDeserialize $Expected + $ActualDeserialized = SerializeDeserialize $Actual + Assert-Equivalent -Actual $ActualDeserialized -Expected $ExpectedDeserialized + Assert-Equivalent -Actual $Actual -Expected $ExpectedDeserialized + + {Assert-Equivalent -Actual $Actual -Expected $Expected -StrictOrder} | Should -Throw + + $Actual.Rows[1].Name = 'D' + {Assert-Equivalent -Actual $Actual -Expected $Expected} | Should -Throw + + $ExpectedDeserialized = SerializeDeserialize $Expected + $ActualDeserialized = SerializeDeserialize $Actual + {Assert-Equivalent -Actual $ActualDeserialized -Expected $ExpectedDeserialized} | Should -Throw + {Assert-Equivalent -Actual $Actual -Expected $ExpectedDeserialized} | Should -Throw + } + + It "Can be called with positional parameters" { + { Assert-Equivalent 1 2 } | Verify-AssertionFailed + } + } +} \ No newline at end of file diff --git a/tst/functions/assert/Exception/Assert-Throw.Tests.ps1 b/tst/functions/assert/Exception/Assert-Throw.Tests.ps1 new file mode 100644 index 000000000..6523dfba3 --- /dev/null +++ b/tst/functions/assert/Exception/Assert-Throw.Tests.ps1 @@ -0,0 +1,233 @@ +Describe "Assert-Throw" { + It "Passes when exception is thrown" { + { throw } | Assert-Throw + } + + It "Fails when no exception is thrown" { + { { } | Assert-Throw } | Verify-AssertionFailed + } + + It "Passes when non-terminating exception is thrown" { + + { Write-Error "fail!" } | Assert-Throw + } + + It "Fails when non-terminating exception is thrown and -AllowNonTerminatingError switch is specified" { + { { Write-Error "fail!" } | Assert-Throw -AllowNonTerminatingError } | Verify-AssertionFailed + } + + Context "Filtering with exception type" { + It "Passes when exception has the expected type" { + { throw [ArgumentException]"A is null!" } | Assert-Throw -ExceptionType ([ArgumentException]) + } + + It "Passes when exception has type that inherits from the expected type" { + { throw [ArgumentNullException]"A is null!" } | Assert-Throw -ExceptionType ([ArgumentException]) + } + + It "Fails when exception is thrown, but is not the expected type nor iheriting form the expected type" { + { { throw [InvalidOperationException]"This operation is invalid!" } | Assert-Throw -ExceptionType ([ArgumentException]) } | Verify-AssertionFailed + } + } + + Context "Filtering with exception message" { + It "Passes when exception has the expected message" { + { throw [ArgumentException]"A is null!" } | Assert-Throw -ExceptionMessage 'A is null!' + } + + It "Fails when exception does not have the expected message" { + { { throw [ArgumentException]"A is null!" } | Assert-Throw -ExceptionMessage 'flabbergasted' } | Verify-AssertionFailed + } + + It "Passes when exception has message that matches based on wildcards" { + { throw [ArgumentNullException]"A is null!" } | Assert-Throw -ExceptionMessage '*null*' + } + + It "Fails when exception does not match the message with wildcard" { + { { throw [ArgumentException]"A is null!" } | Assert-Throw -ExceptionMessage '*flabbergasted*' } | Verify-AssertionFailed + } + } + + Context "Filtering with FullyQualifiedErrorId" { + It "Passes when exception has the FullyQualifiedErrorId" { + { throw [ArgumentException]"A is null!" } | Assert-Throw -FullyQualifiedErrorId 'A is null!' + } + + It "Fails when exception does not have the FullyQualifiedErrorId" { + { { throw [ArgumentException]"A is null!" } | Assert-Throw -FullyQualifiedErrorId 'flabbergasted' } | Verify-AssertionFailed + } + + It "Passes when exception has FullyQualifiedErrorId that matches based on wildcards" { + { throw [ArgumentNullException]"A is null!" } | Assert-Throw -FullyQualifiedErrorId '*null*' + } + + It "Fails when exception does not match the FullyQualifiedErrorId with wildcard" { + { { throw [ArgumentException]"A is null!" } | Assert-Throw -FullyQualifiedErrorId '*flabbergasted*' } | Verify-AssertionFailed + } + } + + Context "Verify messages" { + It "Given no exception it returns the correct message" { + $err = { { } | Assert-Throw } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal 'Expected an exception, to be thrown, but no exception was thrown.' + } + + It "Given exception that does not match on type it returns the correct message" { + $err = { { throw [ArgumentException]"" } | Assert-Throw -ExceptionType ([System.InvalidOperationException]) } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "Expected an exception, of type InvalidOperationException to be thrown, but the exception type was 'ArgumentException'." + } + + It "Given exception that does not match on message it returns the correct message" { + $err = { { throw [ArgumentException]"fail!" } | Assert-Throw -ExceptionMessage 'halt!' } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "Expected an exception, with message 'halt!' to be thrown, but the message was 'fail!'." + } + + It "Given exception that does not match on FullyQualifiedErrorId it returns the correct message" { + $err = { { throw [ArgumentException]"SomeId" } | Assert-Throw -FullyQualifiedErrorId 'DifferentId' } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "Expected an exception, with FullyQualifiedErrorId 'DifferentId' to be thrown, but the FullyQualifiedErrorId was 'SomeId'." + } + + It "Given exception that does not match on type and message it returns the correct message" { + $err = { { throw [ArgumentException]"fail!" } | Assert-Throw -ExceptionType ([System.InvalidOperationException]) -ExceptionMessage 'halt!' } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "Expected an exception, of type InvalidOperationException, with message 'halt!' to be thrown, but the exception type was 'ArgumentException' and the message was 'fail!'." + } + + It "Given exception that does not match on type and FullyQualifiedErrorId it returns the correct message" { + $err = { { throw [ArgumentException]"SomeId!" } | Assert-Throw -ExceptionType ([System.InvalidOperationException]) -FullyQualifiedErrorId 'DifferentId!' } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "Expected an exception, of type InvalidOperationException, with FullyQualifiedErrorId 'DifferentId!' to be thrown, but the exception type was 'ArgumentException' and the FullyQualifiedErrorId was 'SomeId!'." + } + + It "Given exception that does not match on message and FullyQualifiedErrorId it returns the correct message" { + $err = { { throw [ArgumentException]"halt!" } | Assert-Throw -ExceptionMessage 'fail!' -FullyQualifiedErrorId 'fail!' } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "Expected an exception, with message 'fail!', with FullyQualifiedErrorId 'fail!' to be thrown, but the message was 'halt!' and the FullyQualifiedErrorId was 'halt!'." + } + + It "Given exception that does not match on type, message and FullyQualifiedErrorId it returns the correct message" { + $err = { { throw [ArgumentException]"halt!" } | Assert-Throw -ExceptionType ([System.InvalidOperationException]) -ExceptionMessage 'fail!' -FullyQualifiedErrorId 'fail!' } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "Expected an exception, of type InvalidOperationException, with message 'fail!' and with FullyQualifiedErrorId 'fail!' to be thrown, but the exception type was 'ArgumentException', the message was 'halt!' and the FullyQualifiedErrorId was 'halt!'." + } + } + + Context "Unwrapping exception from different sources" { + It 'Exception is thrown by throw keyword' { + { throw "fail!" } | Assert-Throw + } + + It 'Exception is thrown by static .net method' { + { [io.directory]::delete("non-existing") } | Assert-Throw + } + + It 'Exception is thrown by failed constructor' { + { New-Object DateTime "incorrect parameter" } | Assert-Throw + } + + # division by zero circumvents try catch in pwsh v2 + # so we divide by $null to trigger the same exception + It 'Exception is thrown by division by zero' { + { 1/$null } | Assert-Throw + } + + It 'Terminating error is thrown by cmdlet failing to bind paramaters' { + { Get-Item "non-existing" } | Assert-Throw + } + + It 'Terminating error is thrown by cmdlet with -ErrorAction Stop' { + { Get-Item "non-existing" -ErrorAction 'stop' } | Assert-Throw + } + + It 'Non-terminating error is thrown by cmdlet and converted to terminating error by the assertion' { + { Get-Item "non-existing" } | Assert-Throw + } + } + + It "Given scriptblock that throws it returns ErrorRecord to the output" { + $error = { throw [InvalidOperationException]"error" } | Assert-Throw + $error | Verify-Type ([Management.Automation.ErrorRecord]) + $error.Exception | Verify-Type ([System.InvalidOperationException]) + $error.Exception.Message | Verify-Equal "error" + } +} + +Describe "General try catch behavior" { + It 'Gets error record when exception is thrown by throw keyword' { + try + { + &{ throw "fail!" } + } + catch + { + $err = $_ + } + + $err | Verify-NotNull + $err | Verify-Type ([Management.Automation.ErrorRecord]) + } + + It 'Gets error record when exception is thrown from .net' { + try + { + &{ [io.directory]::delete("non-existing"); } + } + catch + { + $err = $_ + } + + $err | Verify-NotNull + $err | Verify-Type ([Management.Automation.ErrorRecord]) + } + + It 'Gets error record when non-terminating error is translated to terminating error' { + try + { + &{ Get-Item "non-existing" -ErrorAction 'stop' } + } + catch + { + $err = $_ + } + + $err | Verify-NotNull + $err | Verify-Type ([Management.Automation.ErrorRecord]) + } + + + It 'Gets error record when non-terminating error is translated to terminating error' { + try + { + $ErrorActionPreference = 'stop' + &{ Get-Item "non-existing" } + } + catch + { + $err = $_ + } + + $err | Verify-NotNull + $err | Verify-Type ([Management.Automation.ErrorRecord]) + } +} + +InModuleScope -ModuleName "Assert" { + Describe "Get-Error" { + It 'Unwraps error from invoke with context' { + $ErrorActionPreference = 'stop' + try + { + $sb = { + Get-Item "/non-existing" + } + Invoke-WithContext $sb -Variables @{ ErrorActionPreference = "Stop" } + } + catch + { + $e = $_ + } + + $err = Get-Error $e + $err.ExceptionMessage | Verify-Like "Cannot find path*because it does not exist." + $err.ExceptionType | Verify-Equal ([Management.Automation.ItemNotFoundException]) + $err.FullyQualifiedErrorId | Verify-Equal 'PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand' + } + } +} \ No newline at end of file diff --git a/tst/functions/assert/General/Assert-Equal.Tests.ps1 b/tst/functions/assert/General/Assert-Equal.Tests.ps1 new file mode 100644 index 000000000..627fe06e3 --- /dev/null +++ b/tst/functions/assert/General/Assert-Equal.Tests.ps1 @@ -0,0 +1,91 @@ +InModuleScope -ModuleName Assert { + Describe "Assert-Equal" { + Context "Comparing strings" { + It "Passes when two strings are equal" { + "abc" | Assert-Equal "abc" + } + + It "Fails when two strings are different" { + { "abc" | Assert-Equal "bde" } | Verify-AssertionFailed + } + } + + Context "Comparing integers" { + It "Passes when two numbers are equal" { + 1 | Assert-Equal 1 + } + + It "Fails when two numbers are different" { + { 1 | Assert-Equal 9 } | Verify-AssertionFailed + } + } + + Context "Comparing doubles" { + It "Passes when two numbers are equal" { + .1 | Assert-Equal .1 + } + + It "Fails when two numbers are different" { + { .1 | Assert-Equal .9 } | Verify-AssertionFailed + } + } + + Context "Comparing decimals" { + It "Passes when two numbers are equal" { + .1D | Assert-Equal .1D + } + + It "Fails when two numbers are different" { + { .1D | Assert-Equal .9D } | Verify-AssertionFailed + } + } + + Context "Comparing objects" { + It "Passes when two objects are the same" { + $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + $object | Assert-Equal $object + } + + It "Fails when two objects are different" { + $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + $object1 = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + { $object | Assert-Equal $object1 } | Verify-AssertionFailed + } + } + + It "Fails for array input even if the last item is the same as expected" { + { 1,2,3 | Assert-Equal 3 } | Verify-AssertionFailed + } + + It "Fails with custom message" { + $error = { 9 | Assert-Equal 3 -CustomMessage " is not " } | Verify-AssertionFailed + $error.Exception.Message | Verify-Equal "3 is not 9" + } + + Context "Validate messages" { + It "Given two values that are not the same '' and '' it returns expected message ''" -TestCases @( + @{ Expected = "a" ; Actual = 10 ; Message = "Expected string 'a', but got int '10'."}, + @{ Expected = "a" ; Actual = 10.1 ; Message = "Expected string 'a', but got double '10.1'."}, + @{ Expected = "a" ; Actual = 10.1D ; Message = "Expected string 'a', but got decimal '10.1'."} + ) { + param($Expected, $Actual, $Message) + $error = { Assert-Equal -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + $error.Exception.Message | Verify-Equal $Message + } + } + + It "Returns the value on output" { + $expected = 1 + $expected | Assert-Equal 1 | Verify-Equal $expected + } + + It "Can be called with positional parameters" { + { Assert-Equal 1 2 } | Verify-AssertionFailed + } + + It "Given collection to Expected it throws" { + $error = { "dummy" | Assert-Equal @() } | Verify-Throw + $error.Exception | Verify-Type ([ArgumentException]) + } + } +} \ No newline at end of file diff --git a/tst/functions/assert/General/Assert-GreaterThan.Tests.ps1 b/tst/functions/assert/General/Assert-GreaterThan.Tests.ps1 new file mode 100644 index 000000000..669110a27 --- /dev/null +++ b/tst/functions/assert/General/Assert-GreaterThan.Tests.ps1 @@ -0,0 +1,109 @@ +InModuleScope -ModuleName Assert { + Describe "Assert-GreaterThan" { + Context "Comparing strings" { + It "Passes when actual is greater than expected" { + "z" | Assert-GreaterThan "a" + } + + It "Fails when actual is equal to expected" { + { "a" | Assert-GreaterThan "a" } | Verify-AssertionFailed + } + + It "Fails when actual is lower than expected" { + { "a" | Assert-GreaterThan "z" } | Verify-AssertionFailed + } + } + + Context "Comparing integers" { + It "Passes when expected is greater than actual" { + 2 | Assert-GreaterThan 1 + } + + It "Fails when actual is equal to expected" { + { 1 | Assert-GreaterThan 1 } | Verify-AssertionFailed + } + + It "Fails when actual is lower than expected" { + { 1 | Assert-GreaterThan 9 } | Verify-AssertionFailed + } + } + + Context "Comparing doubles" { + It "Passes when expected is greater than actual" { + .2 | Assert-GreaterThan .1 + } + + It "Fails when actual is equal to expected" { + { .1 | Assert-GreaterThan .1 } | Verify-AssertionFailed + } + + It "Fails when actual is lower than expected" { + { .1 | Assert-GreaterThan .9 } | Verify-AssertionFailed + } + } + + Context "Comparing decimals" { + It "Passes when expected is greater than actual" { + 2D | Assert-GreaterThan 1D + } + + It "Fails when actual is equal to expected" { + { 1D | Assert-GreaterThan 1D } | Verify-AssertionFailed + } + + It "Fails when actual is lower than expected" { + { 1D | Assert-GreaterThan 9D } | Verify-AssertionFailed + } + } + + Context "Comparing objects" { + It "Fails when two objects are the same" { + $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + { $object | Assert-GreaterThan $object } | Verify-AssertionFailed + } + + It "Fails when two objects are not comparable" { + $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + $object1 = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + $err = { $object | Assert-GreaterThan $object1 } | Verify-Throw + $err.Exception | Verify-Type ([System.Management.Automation.ExtendedTypeSystemException]) + } + } + + It "Fails for array input even if the last item is greater than then expected value" { + $err = { 1,2,3,4 | Assert-GreaterThan 3 } | Verify-Throw + $err.Exception | Verify-Type ([System.Management.Automation.RuntimeException]) + } + + It "Fails with custom message" { + $err = { 2 | Assert-GreaterThan 3 -CustomMessage " is not greater than " } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "2 is not greater than 3" + } + + Context "Validate messages" { + It "Given two values '' and '' it returns expected message ''" -TestCases @( + @{ Expected = "z" ; Actual = "a" ; Message = "Expected string 'a' to be greater than string 'z', but it was not."}, + @{ Expected = 10.1 ; Actual = 1.1 ; Message = "Expected double '1.1' to be greater than double '10.1', but it was not."}, + @{ Expected = 10.1D ; Actual = 1.1D ; Message = "Expected decimal '1.1' to be greater than decimal '10.1', but it was not."} + ) { + param($Expected, $Actual, $Message) + $error = { Assert-GreaterThan -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + $error.Exception.Message | Verify-Equal $Message + } + } + + It "Returns the value on output" { + $expected = 1 + $expected | Assert-GreaterThan 0 | Verify-Equal $expected + } + + It "Can be called with positional parameters" { + { Assert-GreaterThan 2 1 } | Verify-AssertionFailed + } + + It "Given collection to Expected it throws" { + $error = { "dummy" | Assert-GreaterThan @() } | Verify-Throw + $error.Exception | Verify-Type ([ArgumentException]) + } + } +} \ No newline at end of file diff --git a/tst/functions/assert/General/Assert-GreaterThanOrEqual.Tests.ps1 b/tst/functions/assert/General/Assert-GreaterThanOrEqual.Tests.ps1 new file mode 100644 index 000000000..08ebf8e6c --- /dev/null +++ b/tst/functions/assert/General/Assert-GreaterThanOrEqual.Tests.ps1 @@ -0,0 +1,109 @@ +InModuleScope -ModuleName Assert { + Describe "Assert-GreaterThanOrEqual" { + Context "Comparing strings" { + It "Passes when actual is greater than expected" { + "z" | Assert-GreaterThanOrEqual "a" + } + + It "Passes when actual is equal to expected" { + "a" | Assert-GreaterThanOrEqual "a" + } + + It "Fails when actual is lower than expected" { + { "a" | Assert-GreaterThanOrEqual "z" } | Verify-AssertionFailed + } + } + + Context "Comparing integers" { + It "Passes when expected is greater than actual" { + 2 | Assert-GreaterThanOrEqual 1 + } + + It "Passes when actual is equal to expected" { + 1 | Assert-GreaterThanOrEqual 1 + } + + It "Fails when actual is lower than expected" { + { 1 | Assert-GreaterThanOrEqual 9 } | Verify-AssertionFailed + } + } + + Context "Comparing doubles" { + It "Passes when expected is greater than actual" { + .2 | Assert-GreaterThanOrEqual .1 + } + + It "Passes when actual is equal to expected" { + .1 | Assert-GreaterThanOrEqual .1 + } + + It "Fails when actual is lower than expected" { + { .1 | Assert-GreaterThanOrEqual .9 } | Verify-AssertionFailed + } + } + + Context "Comparing decimals" { + It "Passes when expected is greater than actual" { + 2D | Assert-GreaterThanOrEqual 1D + } + + It "Passes when actual is equal to expected" { + 1D | Assert-GreaterThanOrEqual 1D + } + + It "Fails when actual is lower than expected" { + { 1D | Assert-GreaterThanOrEqual 9D } | Verify-AssertionFailed + } + } + + Context "Comparing objects" { + It "Passes when two objects are the same" { + $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + $object | Assert-GreaterThanOrEqual $object + } + + It "Fails when two objects are not comparable" { + $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + $object1 = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + $err = { $object | Assert-GreaterThanOrEqual $object1 } | Verify-Throw + $err.Exception | Verify-Type ([System.Management.Automation.ExtendedTypeSystemException]) + } + } + + It "Fails for array input even if the last item is greater than then expected value" { + $err = { 1,2,3,4 | Assert-GreaterThanOrEqual 3 } | Verify-Throw + $err.Exception | Verify-Type ([System.Management.Automation.RuntimeException]) + } + + It "Fails with custom message" { + $err = { 2 | Assert-GreaterThanOrEqual 3 -CustomMessage " is not greater than " } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "2 is not greater than 3" + } + + Context "Validate messages" { + It "Given two values '' and '' it returns expected message ''" -TestCases @( + @{ Expected = "z" ; Actual = "a" ; Message = "Expected string 'a' to be greater than or equal to string 'z', but it was not."}, + @{ Expected = 10.1 ; Actual = 1.1 ; Message = "Expected double '1.1' to be greater than or equal to double '10.1', but it was not."}, + @{ Expected = 10.1D ; Actual = 1.1D ; Message = "Expected decimal '1.1' to be greater than or equal to decimal '10.1', but it was not."} + ) { + param($Expected, $Actual, $Message) + $error = { Assert-GreaterThanOrEqual -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + $error.Exception.Message | Verify-Equal $Message + } + } + + It "Returns the value on output" { + $expected = 1 + $expected | Assert-GreaterThanOrEqual 0 | Verify-Equal $expected + } + + It "Can be called with positional parameters" { + { Assert-GreaterThanOrEqual 2 1 } | Verify-AssertionFailed + } + + It "Given collection to Expected it throws" { + $error = { "dummy" | Assert-GreaterThanOrEqual @() } | Verify-Throw + $error.Exception | Verify-Type ([ArgumentException]) + } + } +} \ No newline at end of file diff --git a/tst/functions/assert/General/Assert-LessThan.Tests.ps1 b/tst/functions/assert/General/Assert-LessThan.Tests.ps1 new file mode 100644 index 000000000..5e4c96087 --- /dev/null +++ b/tst/functions/assert/General/Assert-LessThan.Tests.ps1 @@ -0,0 +1,107 @@ +Describe "Assert-LessThan" { + Context "Comparing strings" { + It "Passes when actual is less than expected" { + "a" | Assert-LessThan "z" + } + + It "Fails when actual is equal to expected" { + { "z" | Assert-LessThan "z" } | Verify-AssertionFailed + } + + It "Fails when actual is greater than expected" { + { "z" | Assert-LessThan "a" } | Verify-AssertionFailed + } + } + + Context "Comparing integers" { + It "Passes when expected is less than actual" { + 1 | Assert-LessThan 2 + } + + It "Fails when actual is equal to expected" { + { 1 | Assert-LessThan 1 } | Verify-AssertionFailed + } + + It "Fails when actual is greater than expected" { + { 9 | Assert-LessThan 1 } | Verify-AssertionFailed + } + } + + Context "Comparing doubles" { + It "Passes when expected is less than actual" { + .1 | Assert-LessThan .2 + } + + It "Fails when actual is equal to expected" { + { .1 | Assert-LessThan .1 } | Verify-AssertionFailed + } + + It "Fails when actual is greater than expected" { + { .9 | Assert-LessThan .1 } | Verify-AssertionFailed + } + } + + Context "Comparing decimals" { + It "Passes when expected is less than actual" { + 1D | Assert-LessThan 2D + } + + It "Fails when actual is equal to expected" { + { 1D | Assert-LessThan 1D } | Verify-AssertionFailed + } + + It "Fails when actual is greater than expected" { + { 9D | Assert-LessThan 1D } | Verify-AssertionFailed + } + } + + Context "Comparing objects" { + It "Fails when two objects are the same" { + $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + { $object | Assert-LessThan $object } | Verify-AssertionFailed + } + + It "Fails when two objects are not comparable" { + $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + $object1 = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + $err = { $object | Assert-LessThan $object1 } | Verify-Throw + $err.Exception | Verify-Type ([System.Management.Automation.ExtendedTypeSystemException]) + } + } + + It "Fails for array input even if the last item is less than the expected value" { + $err = { 4,3,2,1 | Assert-LessThan 3 } | Verify-Throw + $err.Exception | Verify-Type ([System.Management.Automation.RuntimeException]) + } + + It "Fails with custom message" { + $err = { 3 | Assert-LessThan 2 -CustomMessage " is not less than " } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "3 is not less than 2" + } + + Context "Validate messages" { + It "Given two values '' and '' it returns expected message ''" -TestCases @( + @{ Expected = "a" ; Actual = "z" ; Message = "Expected string 'z' to be less than string 'a', but it was not."}, + @{ Expected = 1.1 ; Actual = 10.1 ; Message = "Expected double '10.1' to be less than double '1.1', but it was not."}, + @{ Expected = 1.1D ; Actual = 10.1D ; Message = "Expected decimal '10.1' to be less than decimal '1.1', but it was not."} + ) { + param($Expected, $Actual, $Message) + $error = { Assert-LessThan -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + $error.Exception.Message | Verify-Equal $Message + } + } + + It "Returns the value on output" { + $expected = 0 + $expected | Assert-LessThan 1 | Verify-Equal $expected + } + + It "Can be called with positional parameters" { + { Assert-LessThan 1 2 } | Verify-AssertionFailed + } + + It "Given collection to Expected it throws" { + $error = { "dummy" | Assert-LessThan @() } | Verify-Throw + $error.Exception | Verify-Type ([ArgumentException]) + } +} \ No newline at end of file diff --git a/tst/functions/assert/General/Assert-LessThanOrEqual.Tests.ps1 b/tst/functions/assert/General/Assert-LessThanOrEqual.Tests.ps1 new file mode 100644 index 000000000..960dfb707 --- /dev/null +++ b/tst/functions/assert/General/Assert-LessThanOrEqual.Tests.ps1 @@ -0,0 +1,107 @@ +Describe "Assert-LessThanOrEqual" { + Context "Comparing strings" { + It "Passes when actual is less than expected" { + "a" | Assert-LessThanOrEqual "z" + } + + It "Passes when actual is equal to expected" { + "a" | Assert-LessThanOrEqual "a" + } + + It "Fails when actual is greater than expected" { + { "z" | Assert-LessThanOrEqual "a" } | Verify-AssertionFailed + } + } + + Context "Comparing integers" { + It "Passes when expected is less than actual" { + 1 | Assert-LessThanOrEqual 2 + } + + It "Passes when actual is equal to expected" { + 1 | Assert-LessThanOrEqual 1 + } + + It "Fails when actual is greater than expected" { + { 9 | Assert-LessThanOrEqual 1 } | Verify-AssertionFailed + } + } + + Context "Comparing doubles" { + It "Passes when expected is less than actual" { + .1 | Assert-LessThanOrEqual .2 + } + + It "Passes when actual is equal to expected" { + .1 | Assert-LessThanOrEqual .1 + } + + It "Fails when actual is greater than expected" { + { .9 | Assert-LessThanOrEqual .1 } | Verify-AssertionFailed + } + } + + Context "Comparing decimals" { + It "Passes when expected is less than actual" { + 1D | Assert-LessThanOrEqual 2D + } + + It "Passes when actual is equal to expected" { + 1D | Assert-LessThanOrEqual 1D + } + + It "Fails when actual is greater than expected" { + { 9D | Assert-LessThanOrEqual 1D } | Verify-AssertionFailed + } + } + + Context "Comparing objects" { + It "Passes when two objects are the same" { + $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + $object | Assert-LessThanOrEqual $object + } + + It "Fails when two objects are not comparable" { + $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + $object1 = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + $err = { $object | Assert-LessThanOrEqual $object1 } | Verify-Throw + $err.Exception | Verify-Type ([System.Management.Automation.ExtendedTypeSystemException]) + } + } + + It "Fails for array input even if the last item is less than then expected value" { + $err = { 4,3,2,1 | Assert-LessThanOrEqual 3 } | Verify-Throw + $err.Exception | Verify-Type ([System.Management.Automation.RuntimeException]) + } + + It "Fails with custom message" { + $err = { 3 | Assert-LessThanOrEqual 2 -CustomMessage " is not less than " } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "3 is not less than 2" + } + + Context "Validate messages" { + It "Given two values '' and '' it returns expected message ''" -TestCases @( + @{ Expected = "a" ; Actual = "z" ; Message = "Expected string 'z' to be less than or equal to string 'a', but it was not."}, + @{ Expected = 1.1 ; Actual = 10.1 ; Message = "Expected double '10.1' to be less than or equal to double '1.1', but it was not."}, + @{ Expected = 1.1D ; Actual = 10.1D ; Message = "Expected decimal '10.1' to be less than or equal to decimal '1.1', but it was not."} + ) { + param($Expected, $Actual, $Message) + $error = { Assert-LessThanOrEqual -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + $error.Exception.Message | Verify-Equal $Message + } + } + + It "Returns the value on output" { + $expected = 0 + $expected | Assert-LessThanOrEqual 1 | Verify-Equal $expected + } + + It "Can be called with positional parameters" { + { Assert-LessThanOrEqual 1 2 } | Verify-AssertionFailed + } + + It "Given collection to Expected it throws" { + $error = { "dummy" | Assert-LessThanOrEqual @() } | Verify-Throw + $error.Exception | Verify-Type ([ArgumentException]) + } +} \ No newline at end of file diff --git a/tst/functions/assert/General/Assert-NotEqual.Tests.ps1 b/tst/functions/assert/General/Assert-NotEqual.Tests.ps1 new file mode 100644 index 000000000..c7931672f --- /dev/null +++ b/tst/functions/assert/General/Assert-NotEqual.Tests.ps1 @@ -0,0 +1,89 @@ +InModuleScope -ModuleName Assert { + Describe "Assert-NotEqual" { + Context "Comparing strings" { + It "Fails when two strings are equal" { + { "abc" | Assert-NotEqual "abc" } | Verify-AssertionFailed + } + + It "Passes when two strings are different" { + "abc" | Assert-NotEqual "bde" + } + } + + Context "Comparing integers" { + It "Fails when two numbers are equal" { + { 1 | Assert-NotEqual 1 } | Verify-AssertionFailed + } + + It "Passes when two numbers are different" { + 1 | Assert-NotEqual 9 + } + } + + Context "Comparing doubles" { + It "Fails when two numbers are equal" { + { .1 | Assert-NotEqual .1 } | Verify-AssertionFailed + } + + It "Passes when two numbers are different" { + .1 | Assert-NotEqual .9 + } + } + + Context "Comparing decimals" { + It "Fails when two numbers are equal" { + { .1D | Assert-NotEqual .1D } | Verify-AssertionFailed + } + + It "Passes when two numbers are different" { + .1D | Assert-NotEqual .9D + } + } + + Context "Comparing objects" { + It "Fails when two objects are the same" { + $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + { $object | Assert-NotEqual $object } | Verify-AssertionFailed + } + + It "Passes when two objects are different" { + $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + $object1 = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + $object | Assert-NotEqual $object1 + } + } + + It "Passes for array input even if the last item is the same as expected" { + 1,2,3 | Assert-NotEqual 3 + } + + It "Fails with custom message" { + $error = { 3 | Assert-NotEqual 3 -CustomMessage " is " } | Verify-AssertionFailed + $error.Exception.Message | Verify-Equal "3 is 3" + } + + Context "Validate messages" { + It "Given two values that are the same '' it returns expected message ''" -TestCases @( + @{ Value = 1; Message = "Expected int '1', to be different than the actual value, but they were the same."} + ) { + param($Value, $Message) + $error = { Assert-NotEqual -Actual $Value -Expected $Value } | Verify-AssertionFailed + $error.Exception.Message | Verify-Equal $Message + } + } + + It "Returns the value on output" { + $expected = 1 + $expected | Assert-NotEqual 9 | Verify-Equal $expected + } + + It "Can be called with positional parameters" { + { Assert-NotEqual 1 1 } | Verify-AssertionFailed + } + + It "Given collection to Expected it throws" { + $error = { "dummy" | Assert-NotEqual @() } | Verify-Throw + $error.Exception | Verify-Type ([ArgumentException]) + } + } +} \ No newline at end of file diff --git a/tst/functions/assert/General/Assert-NotNull.Tests.ps1 b/tst/functions/assert/General/Assert-NotNull.Tests.ps1 new file mode 100644 index 000000000..581345eaa --- /dev/null +++ b/tst/functions/assert/General/Assert-NotNull.Tests.ps1 @@ -0,0 +1,19 @@ +InModuleScope -ModuleName Assert { + Describe "Assert-NotNull" { + It "Given a value it passes" { + 1 | Assert-NotNull + } + + It "Given `$null it fails" { + { $null | Assert-NotNull } | Verify-AssertionFailed + } + + It "Returns the given value" { + 1 | Assert-NotNull | Verify-NotNull + } + + It "Can be called with positional parameters" { + { Assert-NotNull $null } | Verify-AssertionFailed + } + } +} \ No newline at end of file diff --git a/tst/functions/assert/General/Assert-NotSame.Tests.ps1 b/tst/functions/assert/General/Assert-NotSame.Tests.ps1 new file mode 100644 index 000000000..fe5441bb4 --- /dev/null +++ b/tst/functions/assert/General/Assert-NotSame.Tests.ps1 @@ -0,0 +1,45 @@ +InModuleScope -ModuleName Assert { + Describe "Assert-NotSame" { + It "Fails when two objects are the same instance" { + $object = New-Object Diagnostics.Process + { $object | Assert-NotSame $object } | Verify-AssertionFailed + } + + It "Passes when two objects are different instance" { + $object = New-Object Diagnostics.Process + $object1 = New-Object Diagnostics.Process + $object | Assert-NotSame $object1 + } + + It "Passes for array input even if the last item is the same as expected" { + $object = New-Object Diagnostics.Process + 1,2, $object | Assert-NotSame $object + } + + It "Fails with custom message" { + $object = 1 + $error = { $object | Assert-NotSame $object -CustomMessage " is " } | Verify-AssertionFailed + $error.Exception.Message | Verify-Equal "1 is 1" + } + + It "Given two values that are the same instance it returns expected message ''" -TestCases @( + @{ Value = "a"; Message = "Expected string 'a', to not be the same instance."} + ) { + param($Value, $Message) + $error = { Assert-NotSame -Actual $Value -Expected $Value } | Verify-AssertionFailed + $error.Exception.Message | Verify-Equal $Message + } + + It "Returns the value on output" { + $expected = 1 + $expected | Assert-NotSame 7 | Verify-Equal $expected + } + + It "Can be called with positional parameters" { + { + $obj = New-Object -TypeName PSObject + Assert-NotSame $obj $obj + } | Verify-AssertionFailed + } + } +} \ No newline at end of file diff --git a/tst/functions/assert/General/Assert-NotType.Tests.ps1 b/tst/functions/assert/General/Assert-NotType.Tests.ps1 new file mode 100644 index 000000000..e8b762d78 --- /dev/null +++ b/tst/functions/assert/General/Assert-NotType.Tests.ps1 @@ -0,0 +1,19 @@ +InModuleScope -ModuleName Assert { + Describe "Assert-NotType" { + It "Given value of expected type it fails" { + { 1 | Assert-NotType ([int]) } | Verify-AssertionFailed + } + + It "Given an object of different type it passes" { + 1 | Assert-NotType ([string]) + } + + It "Returns the given value" { + 'b' | Assert-NotType ([int]) | Verify-Equal 'b' + } + + It "Can be called with positional parameters" { + { Assert-NotType ([int]) 1 } | Verify-AssertionFailed + } + } +} \ No newline at end of file diff --git a/tst/functions/assert/General/Assert-Null.Tests.ps1 b/tst/functions/assert/General/Assert-Null.Tests.ps1 new file mode 100644 index 000000000..54b02594d --- /dev/null +++ b/tst/functions/assert/General/Assert-Null.Tests.ps1 @@ -0,0 +1,19 @@ +InModuleScope -ModuleName Assert { + Describe "Assert-Null" { + It "Given `$null it passes" { + $null | Assert-Null + } + + It "Given an objects it fails" { + { 1 | Assert-Null } | Verify-AssertionFailed + } + + It "Returns the given value" { + $null | Assert-Null | Verify-Null + } + + It "Can be called with positional parameters" { + { Assert-Null 1 } | Verify-AssertionFailed + } + } +} \ No newline at end of file diff --git a/tst/functions/assert/General/Assert-Same.Tests.ps1 b/tst/functions/assert/General/Assert-Same.Tests.ps1 new file mode 100644 index 000000000..3a8c1b482 --- /dev/null +++ b/tst/functions/assert/General/Assert-Same.Tests.ps1 @@ -0,0 +1,59 @@ +InModuleScope -ModuleName Assert { + Describe "Assert-Same" { + It "Passes when two objects are the same instance" { + $object = New-Object Diagnostics.Process + $object | Assert-Same $object + } + + It "Fails when two objects are different instance" { + $object = New-Object Diagnostics.Process + $object1 = New-Object Diagnostics.Process + { $object | Assert-Same $object1 } | Verify-AssertionFailed + } + + It "Fails for array input even if the last item is the same as expected" { + $object = New-Object Diagnostics.Process + { 1,2, $object | Assert-Same $object } | Verify-AssertionFailed + } + + It "Fails with custom message" { + $object = New-Object Diagnostics.Process + $error = { "text" | Assert-Same $object -CustomMessage "'' is not ''" } | Verify-AssertionFailed + $error.Exception.Message | Verify-Equal "'Diagnostics.Process{Id=; Name=}' is not 'text'" + } + + It "Given two values that are not the same instance '' and '' it returns expected message ''" -TestCases @( + @{ Expected = New-Object -TypeName PSObject ; Actual = New-Object -TypeName PSObject ; Message = "Expected PSObject '', to be the same instance but it was not."} + ) { + param($Expected, $Actual, $Message) + $error = { Assert-Same -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + $error.Exception.Message | Verify-Equal $Message + } + + It "Returns the value on output" { + $expected = New-Object Diagnostics.Process + $expected | Assert-Same $expected | Verify-Equal $expected + } + + Context "Throws when `$expected is a value type or string to warn user about unexpected behavior" { + It "throws for value " -TestCases @( + @{ Value = 1 } + @{ Value = 1.0D } + @{ Value = 1.0 } + @{ Value = 'c' } + @{ Value = "abc" } + ) { + param($Value) + + $err = { "dummy" | Assert-Same -Expected $Value } | Verify-Throw + $err.Exception | Verify-Type ([ArgumentException]) + $err.Exception.Message | Verify-Equal "Assert-Same compares objects by reference. You provided a value type or a string, those are not reference types and you most likely don't need to compare them by reference, see https://github.com/nohwnd/Assert/issues/6.`n`nAre you trying to compare two values to see if they are equal? Use Assert-Equal instead." + } + } + + It "Can be called with positional parameters" { + $object = New-Object Diagnostics.Process + { Assert-Same $object "abc" } | Verify-AssertionFailed + } + } +} \ No newline at end of file diff --git a/tst/functions/assert/General/Assert-Type.Tests.ps1 b/tst/functions/assert/General/Assert-Type.Tests.ps1 new file mode 100644 index 000000000..08374ab66 --- /dev/null +++ b/tst/functions/assert/General/Assert-Type.Tests.ps1 @@ -0,0 +1,19 @@ +InModuleScope -ModuleName Assert { + Describe "Assert-Type" { + It "Given value of expected type it passes" { + 1| Assert-Type ([int]) + } + + It "Given an object of different type it fails" { + { 1 | Assert-Type ([string]) } | Verify-AssertionFailed + } + + It "Returns the given value" { + 'b' | Assert-Type ([string]) | Verify-Equal 'b' + } + + It "Can be called with positional parameters" { + { Assert-Type ([string]) 1 } | Verify-AssertionFailed + } + } +} \ No newline at end of file diff --git a/tst/functions/assert/Get-CustomFailureMessage.Tests.ps1 b/tst/functions/assert/Get-CustomFailureMessage.Tests.ps1 new file mode 100644 index 000000000..10b4d379c --- /dev/null +++ b/tst/functions/assert/Get-CustomFailureMessage.Tests.ps1 @@ -0,0 +1,27 @@ +InModuleScope -ModuleName Assert { + Describe "Get-CustomFailureMessage" { + It "returns correct custom message when no tokens are provided" { + $expected = "Static failure message." + $customMessage = "Static failure message." + Get-CustomFailureMessage -CustomMessage $customMessage -Expected 1 -Actual 2 | Verify-Equal $expected + } + + It "returns correct custom message when positional tokens are provided" { + $expected = "We expected string to be 1, because that is the default value, but got 2." + $customMessage = "We expected string to be {0}, because that is the default value, but got {1}." + Get-CustomFailureMessage -CustomMessage $customMessage -Expected 1 -Actual 2 | Verify-Equal $expected + } + + It "returns correct custom message when named tokens are provided" { + $expected = "We expected string to be 1, because that is the default value, but got 2." + $customMessage = "We expected string to be , because that is the default value, but got ." + Get-CustomFailureMessage -CustomMessage $customMessage -Expected 1 -Actual 2 | Verify-Equal $expected + } + + It "returns correct custom message when shortened named tokens are provided" { + $expected = "We expected string to be 1, because that is the default value, but got 2." + $customMessage = "We expected string to be , because that is the default value, but got ." + Get-CustomFailureMessage -CustomMessage $customMessage -Expected 1 -Actual 2 | Verify-Equal $expected + } + } +} \ No newline at end of file diff --git a/tst/functions/assert/String/Assert-Like.Tests.ps1 b/tst/functions/assert/String/Assert-Like.Tests.ps1 new file mode 100644 index 000000000..daef3dc2d --- /dev/null +++ b/tst/functions/assert/String/Assert-Like.Tests.ps1 @@ -0,0 +1,137 @@ +Describe "Assert-Like" { + Context "Case insensitive matching" { + It "Passes give strings that have the same value" { + Assert-Like -Expected "abc" -Actual "abc" + } + + It "Passes given strings with different case and same values. comparing '':''" -TestCases @( + @{ Actual = "ABc"; Expected = "abc" }, + @{ Actual = "aBc"; Expected = "abc" }, + @{ Actual = "ABC"; Expected = "abc" } + ) { + param ($Actual, $Expected) + Assert-Like -Actual $Actual -Expected $Expected + } + + It "Fails given strings with different values" { + { Assert-Like -Expected "abc" -Actual "def" } | Verify-AssertionFailed + } + + It "Fails given strings with different case and different values. comparing '':''" -TestCases @( + @{ Actual = "ABc"; Expected = "def" }, + @{ Actual = "aBc"; Expected = "def" }, + @{ Actual = "ABC"; Expected = "def" } + ) { + param ($Actual, $Expected) + { Assert-Like -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + } + + It "Fails given strings from which one is sorrounded by whitespace. comparing '':''" -TestCases @( + @{ Actual = "abc "; Expected = "abc" }, + @{ Actual = "abc "; Expected = "abc" }, + @{ Actual = "ab c"; Expected = "abc" } + ) { + param ($Actual, $Expected) + { Assert-Like -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + } + + It "Passes given strings with different case that start with a given pattern. comparing '':''" -TestCases @( + @{ Actual = "ABcdef"; Expected = "abc*" }, + @{ Actual = "aBcdef"; Expected = "abc*" }, + @{ Actual = "ABCDEF"; Expected = "abc*" } + ) { + param ($Actual, $Expected) + Assert-Like -Actual $Actual -Expected $Expected + } + + It "Fails given strings with different case that start with a different pattern. comparing '':''" -TestCases @( + @{ Actual = "ABcdef"; Expected = "ghi*" }, + @{ Actual = "aBcdef"; Expected = "ghi*" }, + @{ Actual = "ABCDEF"; Expected = "ghi*" } + ) { + param ($Actual, $Expected) + { Assert-Like -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + } + + It "Passes given strings with different case that contain a given pattern. comparing '':''" -TestCases @( + @{ Actual = "ABcdef"; Expected = "*cd*" }, + @{ Actual = "aBcdef"; Expected = "*cd*" }, + @{ Actual = "ABCDEF"; Expected = "*CD*" } + ) { + param ($Actual, $Expected) + Assert-Like -Actual $Actual -Expected $Expected + } + + It "Fails given strings with different case that contain a different pattern. comparing '':''" -TestCases @( + @{ Actual = "ABcdef"; Expected = "*gh*" }, + @{ Actual = "aBcdef"; Expected = "*gh*" }, + @{ Actual = "ABCDEF"; Expected = "*GH*" } + ) { + param ($Actual, $Expected) + { Assert-Like -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + } + } + + Context "Case sensitive matching" { + It "Fails given strings with different case but same values. comparing '':''" -TestCases @( + @{ Actual = "ABc"; Expected = "abc" }, + @{ Actual = "aBc"; Expected = "abc" }, + @{ Actual = "ABC"; Expected = "abc" } + ) { + param ($Actual, $Expected) + { Assert-Like -Actual $Actual -Expected $Expected -CaseSensitive } | Verify-AssertionFailed + } + } + + Context "Case sensitive matching" { + It "Fails given strings with different case that contain the given pattern. comparing '':''" -TestCases @( + @{ Actual = "ABCDEF"; Expected = "*cd*" } + ) { + param ($Actual, $Expected) + { Assert-Like -Actual $Actual -Expected $Expected -CaseSensitive } | Verify-AssertionFailed + } + } + + It "Allows actual to be passed from pipeline" { + "abc" | Assert-Like -Expected "abc" + } + + It "Allows expected to be passed by position" { + Assert-Like "abc" -Actual "abc" + } + + It "Allows actual to be passed by pipeline and expected by position" { + "abc" | Assert-Like "abc" + } + + It "Throws when given a collection to avoid confusing matches of the last item only" { + $err = { "bde", "abc" | Assert-Like -Expected "abc" } | Verify-Throw + $err.Exception.Message | Verify-Equal "Actual is expected to be string, to avoid confusing behavior that -like operator exhibits with collections. To assert on collections use Assert-Any, Assert-All or some other collection assertion." + } + + It "Can be called with positional parameters" { + { Assert-Like "a" "b" } | Verify-AssertionFailed + } + + Context "Verify messages" { + It "Given two values that are not alike '' and '' it returns the correct message ''" -TestCases @( + @{ Actual = 'a'; Expected = 'b'; Message = "Expected the string 'a' to match 'b' but it did not." } + @{ Actual = 'ab'; Expected = 'd*'; Message = "Expected the string 'ab' to match 'd*' but it did not." } + @{ Actual = 'something'; Expected = '*abc*'; Message = "Expected the string 'something' to match '*abc*' but it did not." } + ) { + param ($Actual, $Expected, $Message) + $err = { Assert-Like -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $Message + } + + It "Given two values that are not alike becuase of case '' and '' it returns the correct message ''" -TestCases @( + @{ Actual = 'a'; Expected = 'B'; Message = "Expected the string 'a' to case sensitively match 'B' but it did not." } + @{ Actual = 'ab'; Expected = 'B*'; Message = "Expected the string 'ab' to case sensitively match 'B*' but it did not." } + @{ Actual = 'something'; Expected = '*SOME*'; Message = "Expected the string 'something' to case sensitively match '*SOME*' but it did not." } + ) { + param ($Actual, $Expected, $Message) + $err = { Assert-Like -Actual $Actual -Expected $Expected -CaseSensitive } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $Message + } + } +} \ No newline at end of file diff --git a/tst/functions/assert/String/Assert-NotLike.Tests.ps1 b/tst/functions/assert/String/Assert-NotLike.Tests.ps1 new file mode 100644 index 000000000..ea56807e2 --- /dev/null +++ b/tst/functions/assert/String/Assert-NotLike.Tests.ps1 @@ -0,0 +1,137 @@ +Describe "Assert-NotLike" { + Context "Case insensitive matching" { + It "Fails give strings that have the same value" { + { Assert-NotLike -Expected "abc" -Actual "abc" } | Verify-AssertionFailed + } + + It "Fails given strings with different case and same values. comparing '':''" -TestCases @( + @{ Actual = "ABc"; Expected = "abc" }, + @{ Actual = "aBc"; Expected = "abc" }, + @{ Actual = "ABC"; Expected = "abc" } + ) { + param ($Actual, $Expected) + { Assert-NotLike -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + } + + It "Passes given strings with different values" { + Assert-NotLike -Expected "abc" -Actual "def" + } + + It "Passes given strings with different case and different values. comparing '':''" -TestCases @( + @{ Actual = "ABc"; Expected = "def" }, + @{ Actual = "aBc"; Expected = "def" }, + @{ Actual = "ABC"; Expected = "def" } + ) { + param ($Actual, $Expected) + Assert-NotLike -Actual $Actual -Expected $Expected + } + + It "Passes given strings from which one is sorrounded by whitespace. comparing '':''" -TestCases @( + @{ Actual = "abc "; Expected = "abc" }, + @{ Actual = "abc "; Expected = "abc" }, + @{ Actual = "ab c"; Expected = "abc" } + ) { + param ($Actual, $Expected) + Assert-NotLike -Actual $Actual -Expected $Expected + } + + It "Fails given strings with different case that start with a given pattern. comparing '':''" -TestCases @( + @{ Actual = "ABcdef"; Expected = "abc*" }, + @{ Actual = "aBcdef"; Expected = "abc*" }, + @{ Actual = "ABCDEF"; Expected = "abc*" } + ) { + param ($Actual, $Expected) + { Assert-NotLike -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + } + + It "Passes given strings with different case that start with a different pattern. comparing '':''" -TestCases @( + @{ Actual = "ABcdef"; Expected = "ghi*" }, + @{ Actual = "aBcdef"; Expected = "ghi*" }, + @{ Actual = "ABCDEF"; Expected = "ghi*" } + ) { + param ($Actual, $Expected) + Assert-NotLike -Actual $Actual -Expected $Expected + } + + It "Fails given strings with different case that contain a given pattern. comparing '':''" -TestCases @( + @{ Actual = "ABcdef"; Expected = "*cd*" }, + @{ Actual = "aBcdef"; Expected = "*cd*" }, + @{ Actual = "ABCDEF"; Expected = "*CD*" } + ) { + param ($Actual, $Expected) + { Assert-NotLike -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + } + + It "Passes given strings with different case that contain a different pattern. comparing '':''" -TestCases @( + @{ Actual = "ABcdef"; Expected = "*gh*" }, + @{ Actual = "aBcdef"; Expected = "*gh*" }, + @{ Actual = "ABCDEF"; Expected = "*GH*" } + ) { + param ($Actual, $Expected) + Assert-NotLike -Actual $Actual -Expected $Expected + } + } + + Context "Case sensitive matching" { + It "Passes given strings with different case but same values. comparing '':''" -TestCases @( + @{ Actual = "ABc"; Expected = "abc" }, + @{ Actual = "aBc"; Expected = "abc" }, + @{ Actual = "ABC"; Expected = "abc" } + ) { + param ($Actual, $Expected) + Assert-NotLike -Actual $Actual -Expected $Expected -CaseSensitive + } + } + + Context "Case sensitive matching" { + It "Passes given strings with different case that contain the given pattern. comparing '':''" -TestCases @( + @{ Actual = "ABCDEF"; Expected = "*cd*" } + ) { + param ($Actual, $Expected) + Assert-NotLike -Actual $Actual -Expected $Expected -CaseSensitive + } + } + + It "Allows actual to be passed from pipeline" { + "efg" | Assert-NotLike -Expected "abc" + } + + It "Allows expected to be passed by position" { + Assert-NotLike "efg" -Actual "abc" + } + + It "Allows actual to be passed by pipeline and expected by position" { + "efg" | Assert-NotLike "abc" + } + + It "Can be called with positional parameters" { + { Assert-NotLike "a" "a" } | Verify-AssertionFailed + } + + It "Throws when given a collection to avoid confusing matches of the last item only" { + $err = { "bde", "abc" | Assert-NotLike -Expected "abc" } | Verify-Throw + $err.Exception.Message | Verify-Equal "Actual is expected to be string, to avoid confusing behavior that -like operator exhibits with collections. To assert on collections use Assert-Any, Assert-All or some other collection assertion." + } + + Context "Verify messages" { + It "Given two values that are alike '' and '' it returns the correct message ''" -TestCases @( + @{ Actual = 'a'; Expected = 'A'; Message = "Expected the string 'a' to not match 'A' but it matched it." } + @{ Actual = 'ab'; Expected = 'a*'; Message = "Expected the string 'ab' to not match 'a*' but it matched it." } + @{ Actual = 'something'; Expected = 'SOME*'; Message = "Expected the string 'something' to not match 'SOME*' but it matched it." } + ) { + param ($Actual, $Expected, $Message) + $err = { Assert-NotLike -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $Message + } + + It "Given two values that are alike becuase of case '' and '' it returns the correct message ''" -TestCases @( + @{ Actual = 'a'; Expected = 'a'; Message = "Expected the string 'a' to case sensitively not match 'a' but it matched it." } + @{ Actual = 'AB'; Expected = 'A*'; Message = "Expected the string 'AB' to case sensitively not match 'A*' but it matched it." } + @{ Actual = 'SOMETHING'; Expected = '*SOME*'; Message = "Expected the string 'SOMETHING' to case sensitively not match '*SOME*' but it matched it." } + ) { + param ($Actual, $Expected, $Message) + $err = { Assert-NotLike -Actual $Actual -Expected $Expected -CaseSensitive } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $Message + } + } +} \ No newline at end of file diff --git a/tst/functions/assert/String/Assert-StringEqual.Tests.ps1 b/tst/functions/assert/String/Assert-StringEqual.Tests.ps1 new file mode 100644 index 000000000..63898f193 --- /dev/null +++ b/tst/functions/assert/String/Assert-StringEqual.Tests.ps1 @@ -0,0 +1,124 @@ +InModuleScope -ModuleName Assert { + Describe "Test-StringEqual" { + Context "Case insensitive matching" { + It "strings with the same values are equal" { + Test-StringEqual -Expected "abc" -Actual "abc" | Verify-True + } + + It "strings with different case and same values are equal. comparing '':''" -TestCases @( + @{l = "ABc"; r = "abc" }, + @{l = "aBc"; r = "abc" }, + @{l = "ABC"; r = "abc" } + ) { + param ($l, $r) + Test-StringEqual -Expected $l -Actual $r | Verify-True + } + + It "strings with different values are not equal" { + Test-StringEqual -Expected "abc" -Actual "def" | Verify-False + } + + It "strings with different case and different values are not equal. comparing '':''" -TestCases @( + @{l = "ABc"; r = "def" }, + @{l = "aBc"; r = "def" }, + @{l = "ABC"; r = "def" } + ) { + param ($l, $r) + Test-StringEqual -Expected $l -Actual $r | Verify-False + } + + It "strings from which one is sorrounded by whitespace are not equal. comparing '':''" -TestCases @( + @{l = "abc "; r = "abc" }, + @{l = "abc "; r = "abc" }, + @{l = "ab c"; r = "abc" } + ) { + param ($l, $r) + Test-StringEqual -Expected $l -Actual $r | Verify-False + } + } + + Context "Case sensitive matching" { + It "strings with different case but same values are not equal. comparing '':''" -TestCases @( + @{l = "ABc"; r = "abc" }, + @{l = "aBc"; r = "abc" }, + @{l = "ABC"; r = "abc" } + ) { + param ($l, $r) + Test-StringEqual -Expected $l -Actual $r -CaseSensitive | Verify-False + } + } + + Context "Case insensitive matching with ingoring whitespace" { + It "strings sorrounded or containing whitespace are equal. comparing '':''" -TestCases @( + @{l = "abc "; r = "abc" }, + @{l = "abc "; r = "abc" }, + @{l = "ab c"; r = "abc" }, + @{l = "ab c"; r = "a b c" } + ) { + param ($l, $r) + Test-StringEqual -Expected $l -Actual $r -IgnoreWhiteSpace | Verify-True + } + } + } + + Describe "Get-StringEqualDefaultFailureMessage" { + It "returns correct default message" { + $expected = "Expected the string to be 'abc' but got 'bde'." + $actual = Get-StringEqualDefaultFailureMessage -Expected "abc" -Actual "bde" + $actual | Verify-Equal $expected + } + } + + Describe "Assert-StringEqual" { + It "Does nothing when string are the same" { + Assert-StringEqual -Expected "abc" -Actual "abc" + } + + It "Throws when strings are different" { + { Assert-StringEqual -Expected "abc" -Actual "bde" } | Verify-AssertionFailed + } + + It "Throws with default message when test fails" { + $expected = Get-StringEqualDefaultFailureMessage -Expected "abc" -Actual "bde" + $exception = { Assert-StringEqual -Expected "abc" -Actual "bde" } | Verify-AssertionFailed + "$exception" | Verify-Equal $expected + } + + It "Throws with custom message when test fails" { + $customMessage = "Test failed becasue it expected '' but got ''. What a shame!" + $expected = Get-CustomFailureMessage -CustomMessage $customMessage -Expected "abc" -Actual "bde" + $exception = { Assert-StringEqual -Expected "abc" -Actual "bde" -CustomMessage $customMessage } | Verify-AssertionFailed + "$exception" | Verify-Equal $expected + } + + It "Allows actual to be passed from pipeline" { + "abc" | Assert-StringEqual -Expected "abc" + } + + It "Allows expected to be passed by position" { + Assert-StringEqual "abc" -Actual "abc" + } + + It "Allows actual to be passed by pipeline and expected by position" { + "abc" | Assert-StringEqual "abc" + } + + It "Fails when collection of strings is passed in by pipeline, even if the last string is the same as the expected string" { + { "bde", "abc" | Assert-StringEqual -Expected "abc" } | Verify-AssertionFailed + } + + Context "String specific features" { + It "Can compare strings in CaseSensitive mode" { + { Assert-StringEqual -Expected "ABC" -Actual "abc" -CaseSensitive } | Verify-AssertionFailed + } + + It "Can compare strings without whitespace" { + Assert-StringEqual -Expected " a b c " -Actual "abc" -IgnoreWhitespace + } + } + + It "Can be called with positional parameters" { + { Assert-StringEqual "a" "b" } | Verify-AssertionFailed + } + } +} \ No newline at end of file diff --git a/tst/functions/assert/String/Assert-StringNotEqual.Tests.ps1 b/tst/functions/assert/String/Assert-StringNotEqual.Tests.ps1 new file mode 100644 index 000000000..76f3f4e70 --- /dev/null +++ b/tst/functions/assert/String/Assert-StringNotEqual.Tests.ps1 @@ -0,0 +1,58 @@ +InModuleScope -ModuleName Assert { + Describe "Get-StringNotEqualDefaultFailureMessage" { + It "returns correct default message" { + $expected = "Expected the strings to be different but they were the same 'abc'." + $actual = Get-StringNotEqualDefaultFailureMessage -Expected "abc" -Actual "abc" + $actual | Verify-Equal $expected + } + } + + Describe "Assert-StringNotEqual" { + It "Does nothing when string are different" { + Assert-StringNotEqual -Expected "abc" -Actual "bde" + } + + It "Throws when strings are the same" { + { Assert-StringNotEqual -Expected "abc" -Actual "abc" } | Verify-AssertionFailed + } + + It "Throws with default message when test fails" { + $expected = Get-StringNotEqualDefaultFailureMessage -Expected "abc" -Actual "abc" + $exception = { Assert-StringNotEqual -Expected "abc" -Actual "abc" } | Verify-AssertionFailed + "$exception" | Verify-Equal $expected + } + + It "Throws with custom message when test fails" { + $customMessage = "Test failed becasue it expected '' but got ''. What a shame!" + $expected = Get-CustomFailureMessage -CustomMessage $customMessage -Expected "abc" -Actual "abc" + $exception = { Assert-StringNotEqual -Expected "abc" -Actual "abc" -CustomMessage $customMessage } | Verify-AssertionFailed + "$exception" | Verify-Equal $expected + } + + It "Allows actual to be passed from pipeline" { + "abc" | Assert-StringNotEqual -Expected "bde" + } + + It "Allows expected to be passed by position" { + Assert-StringNotEqual "abc" -Actual "bde" + } + + It "Allows actual to be passed by pipeline and expected by position" { + "abc" | Assert-StringNotEqual "bde" + } + + Context "String specific features" { + It "Can compare strings in CaseSensitive mode" { + Assert-StringNotEqual -Expected "ABC" -Actual "abc" -CaseSensitive + } + + It "Can compare strings without whitespace" { + { Assert-StringNotEqual -Expected " a b c " -Actual "abc" -IgnoreWhitespace } | Verify-AssertionFailed + } + } + + It "Can be called with positional parameters" { + { Assert-StringNotEqual "a" "a" } | Verify-AssertionFailed + } + } +} \ No newline at end of file diff --git a/tst/functions/assert/TestHelpers.psm1 b/tst/functions/assert/TestHelpers.psm1 new file mode 100644 index 000000000..30f584578 --- /dev/null +++ b/tst/functions/assert/TestHelpers.psm1 @@ -0,0 +1,11 @@ +function New-Dictionary ([hashtable]$Hashtable) { + $d = new-object "Collections.Generic.Dictionary[string,object]" + + $Hashtable.GetEnumerator() | ForEach-Object { $d.Add($_.Key, $_.Value) } + + $d +} + +function Clear-WhiteSpace ($Text) { + "$($Text -replace "(`t|`n|`r)"," " -replace "\s+"," ")".Trim() +} \ No newline at end of file From 28761e6cc31724de9d2c7d9ef4e4af6cc02d1d5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Mon, 1 Apr 2024 23:55:49 +0200 Subject: [PATCH 02/55] Before adding format nicely2 --- build.ps1 | 6 +- src/Format2.ps1 | 156 +++++++++++++++ src/Module.ps1 | 27 +++ src/Pester.psd1 | 28 +++ src/functions/assert/Boolean/Assert-False.ps1 | 4 +- src/functions/assert/Boolean/Assert-True.ps1 | 4 +- .../assert/Collection/Assert-All.ps1 | 13 +- .../assert/Collection/Assert-Any.ps1 | 4 +- .../assert/Collection/Assert-Contain.ps1 | 4 +- .../assert/Collection/Assert-NotContain.ps1 | 4 +- src/functions/assert/Compatibility.ps1 | 76 +++++++ .../assert/Equivalence/Assert-Equivalent.ps1 | 4 +- .../assert/Exception/Assert-Throw.ps1 | 4 +- src/functions/assert/General/Assert-Equal.ps1 | 4 +- .../assert/General/Assert-GreaterThan.ps1 | 4 +- .../General/Assert-GreaterThanOrEqual.ps1 | 4 +- .../assert/General/Assert-LessThan.ps1 | 4 +- .../assert/General/Assert-LessThanOrEqual.ps1 | 4 +- .../assert/General/Assert-NotEqual.ps1 | 4 +- .../assert/General/Assert-NotNull.ps1 | 4 +- .../assert/General/Assert-NotSame.ps1 | 4 +- .../assert/General/Assert-NotType.ps1 | 11 +- src/functions/assert/General/Assert-Null.ps1 | 4 +- src/functions/assert/General/Assert-Same.ps1 | 4 +- src/functions/assert/General/Assert-Type.ps1 | 11 +- src/functions/assert/String/Assert-Like.ps1 | 38 ++-- .../assert/String/Assert-NotLike.ps1 | 38 ++-- .../assert/String/Assert-StringEqual.ps1 | 35 ++-- .../assert/String/Assert-StringNotEqual.ps1 | 23 +-- src/functions/assertions/Should.ps1 | 10 - test.ps1 | 11 + tst/Format2.Tests.ps1 | 188 ++++++++++++++++++ .../Collection/Assert-Contain.Tests.ps1 | 6 +- .../Collection/Assert-NotContain.Tests.ps1 | 6 +- .../Ensure-ExpectedIsNotCollection.Tests.ps1 | 6 +- .../Common/Get-AssertionMessage.Tests.ps1 | 6 +- .../Assert-Equivalent.Options.Tests.ps1 | 6 +- .../Equivalence/Assert-Equivalent.Tests.ps1 | 148 +++++++------- .../assert/General/Assert-Equal.Tests.ps1 | 6 +- .../General/Assert-GreaterThan.Tests.ps1 | 6 +- .../Assert-GreaterThanOrEqual.Tests.ps1 | 6 +- .../assert/General/Assert-NotEqual.Tests.ps1 | 6 +- .../assert/General/Assert-NotNull.Tests.ps1 | 6 +- .../assert/General/Assert-NotSame.Tests.ps1 | 6 +- .../assert/General/Assert-NotType.Tests.ps1 | 6 +- .../assert/General/Assert-Null.Tests.ps1 | 6 +- .../assert/General/Assert-Same.Tests.ps1 | 6 +- .../assert/General/Assert-Type.Tests.ps1 | 6 +- .../assert/Get-CustomFailureMessage.Tests.ps1 | 6 +- .../String/Assert-StringEqual.Tests.ps1 | 6 +- .../String/Assert-StringNotEqual.Tests.ps1 | 6 +- tst/functions/assert/TestHelpers.psm1 | 11 - 52 files changed, 737 insertions(+), 269 deletions(-) create mode 100644 src/Format2.ps1 create mode 100644 src/functions/assert/Compatibility.ps1 create mode 100644 tst/Format2.Tests.ps1 delete mode 100644 tst/functions/assert/TestHelpers.psm1 diff --git a/build.ps1 b/build.ps1 index 6bb6dac0d..318898fc0 100644 --- a/build.ps1 +++ b/build.ps1 @@ -282,6 +282,9 @@ $script = @( "$PSScriptRoot/src/Pester.RSpec.ps1" "$PSScriptRoot/src/Main.ps1" + # TODO: Imports Compatibility.ps1, remove the code that is there, because it is for PowerShell 2.0 compatibility! + "$PSScriptRoot/src/functions/assert/*" + "$PSScriptRoot/src/functions/assert/*/*" "$PSScriptRoot/src/functions/assertions/*" "$PSScriptRoot/src/functions/*" @@ -326,7 +329,8 @@ foreach ($f in $files) { else { # when not inlining just dot-source the file if ($f.FullName -notlike "*.ps1") { - throw "$($f.FullName) is not a ps1 file" + Write-Warning "$($f.FullName) is not a ps1 file" + # throw "$($f.FullName) is not a ps1 file" } $null = $sb.AppendLine(". '$($f.FullName)'") } diff --git a/src/Format2.ps1 b/src/Format2.ps1 new file mode 100644 index 000000000..31515e7c0 --- /dev/null +++ b/src/Format2.ps1 @@ -0,0 +1,156 @@ +function Format-Collection2 ($Value, [switch]$Pretty) { + $separator = ', ' + if ($Pretty) { + $separator = ",`n" + } + ($Value | ForEach-Object { Format-Nicely2 -Value $_ -Pretty:$Pretty }) -join $separator +} + +function Format-Object2 ($Value, $Property, [switch]$Pretty) { + if ($null -eq $Property) { + $Property = $Value.PSObject.Properties | Select-Object -ExpandProperty Name + } + $orderedProperty = $Property | + Sort-Object | + # force the values to be strings for powershell v2 + ForEach-Object { "$_" } + + $valueType = Get-ShortType $Value + $valueFormatted = [string]([PSObject]$Value | Select-Object -Property $orderedProperty) + + if ($Pretty) { + $margin = " " + $valueFormatted = $valueFormatted ` + -replace '^@{', "@{`n$margin" ` + -replace '; ', ";`n$margin" ` + -replace '}$', "`n}" ` + + } + + $valueFormatted -replace "^@", $valueType +} + +function Format-Null2 { + '$null' +} + +function Format-Boolean2 ($Value) { + '$' + $Value.ToString().ToLower() +} + +function Format-ScriptBlock2 ($Value) { + '{' + $Value + '}' +} + +function Format-Number2 ($Value) { + [string]$Value +} + +function Format-Hashtable2 ($Value) { + $head = '@{' + $tail = '}' + + $entries = $Value.Keys | Sort-Object | ForEach-Object { + $formattedValue = Format-Nicely $Value.$_ + "$_=$formattedValue" } + + $head + ( $entries -join '; ') + $tail +} + +function Format-Dictionary2 ($Value) { + $head = 'Dictionary{' + $tail = '}' + + $entries = $Value.Keys | Sort-Object | ForEach-Object { + $formattedValue = Format-Nicely $Value.$_ + "$_=$formattedValue" } + + $head + ( $entries -join '; ') + $tail +} + +function Format-Nicely2 ($Value, [switch]$Pretty) { + if ($null -eq $Value) { + return Format-Null2 -Value $Value + } + + if ($Value -is [bool]) { + return Format-Boolean2 -Value $Value + } + + if ($value -is [type]) { + return Format-Type2 -Value $Value + } + + if (Is-DecimalNumber -Value $Value) { + return Format-Number2 -Value $Value + } + + if (Is-ScriptBlock -Value $Value) { + return Format-ScriptBlock2 -Value $Value + } + + if (Is-Value -Value $Value) { + return $Value + } + + if (Is-Hashtable -Value $Value) { + return Format-Hashtable2 -Value $Value + } + + if (Is-Dictionary -Value $Value) { + return Format-Dictionary2 -Value $Value + } + + if (Is-Collection -Value $Value) { + return Format-Collection2 -Value $Value -Pretty:$Pretty + } + + Format-Object2 -Value $Value -Property (Get-DisplayProperty2 (Get-Type $Value)) -Pretty:$Pretty +} + +function Get-DisplayProperty2 ([Type]$Type) { + # rename to Get-DisplayProperty? + + <# some objects are simply too big to show all of their properties, + so we can create a list of properties to show from an object + maybe the default info from Get-FormatData could be utilized here somehow + so we show only stuff that would normally show in format-table view + leveraging the work PS team already did #> + + # this will become more advanced, basically something along the lines of: + # foreach type, try constructing the type, and if it exists then check if the + # incoming type is assignable to the current type, if so then return the properties, + # this way I can specify the map from the most concrete type to the least concrete type + # and for types that do not exist + + $propertyMap = @{ + 'System.Diagnostics.Process' = 'Id', 'Name' + } + + $propertyMap[$Type.FullName] +} + +function Get-ShortType2 ($Value) { + if ($null -ne $value) { + Format-Type2 (Get-Type $Value) + } + else { + Format-Type2 $null + } +} + +function Format-Type2 ([Type]$Value) { + if ($null -eq $Value) { + return '' + } + + $type = [string]$Value + + $type ` + -replace "^System\." ` + -replace "^Management\.Automation\.PSCustomObject$", "PSObject" ` + -replace "^PSCustomObject$", "PSObject" ` + -replace "^Object\[\]$", "collection" ` + +} + diff --git a/src/Module.ps1 b/src/Module.ps1 index cf9eef142..7a68b0c45 100644 --- a/src/Module.ps1 +++ b/src/Module.ps1 @@ -39,6 +39,33 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session 'New-PesterContainer' 'New-PesterConfiguration' + # assert + 'Assert-False' + 'Assert-True' + 'Assert-All' + 'Assert-Any' + 'Assert-Contain' + 'Assert-NotContain' + 'AssertionException' + 'Assert-Equivalent' + 'Assert-Throw' + 'Assert-Equal' + 'Assert-GreaterThan' + 'Assert-GreaterThanOrEqual' + 'Assert-LessThan' + 'Assert-LessThanOrEqual' + 'Assert-NotEqual' + 'Assert-NotNull' + 'Assert-NotSame' + 'Assert-NotType' + 'Assert-Null' + 'Assert-Same' + 'Assert-Type' + 'Assert-Like' + 'Assert-NotLike' + 'Assert-StringEqual' + 'Assert-StringNotEqual' + # export 'Export-NUnitReport' 'ConvertTo-NUnitReport' diff --git a/src/Pester.psd1 b/src/Pester.psd1 index f916a4c25..a24296df9 100644 --- a/src/Pester.psd1 +++ b/src/Pester.psd1 @@ -66,6 +66,34 @@ 'New-PesterContainer' 'New-PesterConfiguration' + # assert + 'Assert-False' + 'Assert-True' + 'Assert-All' + 'Assert-Any' + 'Assert-Contain' + 'Assert-NotContain' + 'AssertionException' + 'Assert-Equivalent' + 'Assert-Throw' + 'Assert-Equal' + 'Assert-GreaterThan' + 'Assert-GreaterThanOrEqual' + 'Assert-LessThan' + 'Assert-LessThanOrEqual' + 'Assert-NotEqual' + 'Assert-NotNull' + 'Assert-NotSame' + 'Assert-NotType' + 'Assert-Null' + 'Assert-Same' + 'Assert-Type' + 'Assert-Like' + 'Assert-NotLike' + 'Assert-StringEqual' + 'Assert-StringNotEqual' + + # legacy 'Assert-VerifiableMock' 'Assert-MockCalled' diff --git a/src/functions/assert/Boolean/Assert-False.ps1 b/src/functions/assert/Boolean/Assert-False.ps1 index 4743659f2..bd3ee1423 100644 --- a/src/functions/assert/Boolean/Assert-False.ps1 +++ b/src/functions/assert/Boolean/Assert-False.ps1 @@ -9,8 +9,8 @@ if ($Actual) { $Message = Get-AssertionMessage -Expected $false -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be '' or falsy value 0, """", `$null, @()." - throw [Assertions.AssertionException]$Message + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } $Actual -} \ No newline at end of file +} diff --git a/src/functions/assert/Boolean/Assert-True.ps1 b/src/functions/assert/Boolean/Assert-True.ps1 index e1615a0eb..9dad238d5 100644 --- a/src/functions/assert/Boolean/Assert-True.ps1 +++ b/src/functions/assert/Boolean/Assert-True.ps1 @@ -9,8 +9,8 @@ if (-not $Actual) { $Message = Get-AssertionMessage -Expected $true -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be '' or truthy value." - throw [Assertions.AssertionException]$Message + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } $Actual -} \ No newline at end of file +} diff --git a/src/functions/assert/Collection/Assert-All.ps1 b/src/functions/assert/Collection/Assert-All.ps1 index fe6ac1731..9f6d57bd0 100644 --- a/src/functions/assert/Collection/Assert-All.ps1 +++ b/src/functions/assert/Collection/Assert-All.ps1 @@ -1,9 +1,9 @@ function Assert-All { [CmdletBinding()] param ( - [Parameter(ValueFromPipeline=$true, Position=1)] + [Parameter(ValueFromPipeline = $true, Position = 1)] $Actual, - [Parameter(Position=0, Mandatory=$true)] + [Parameter(Position = 0, Mandatory = $true)] [scriptblock]$FilterScript, [String]$CustomMessage ) @@ -27,15 +27,14 @@ if (-not $pass) { $_ } } - if ($actualFiltered) - { + if ($actualFiltered) { $data = @{ - actualFiltered = $actualFiltered + actualFiltered = $actualFiltered actualFilteredCount = @($actualFiltered).Count } $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Data $data -CustomMessage $CustomMessage -DefaultMessage "Expected all items in collection '' to pass filter '', but of them '' did not pass the filter." - throw [Assertions.AssertionException]$Message + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } $Actual -} \ No newline at end of file +} diff --git a/src/functions/assert/Collection/Assert-Any.ps1 b/src/functions/assert/Collection/Assert-Any.ps1 index 0c24088d8..1fe85e8c6 100644 --- a/src/functions/assert/Collection/Assert-Any.ps1 +++ b/src/functions/assert/Collection/Assert-Any.ps1 @@ -12,8 +12,8 @@ if (-not ($Actual | Where-Object -FilterScript $FilterScript)) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected at least one item in collection '' to pass filter '', but none of the items passed the filter." - throw [Assertions.AssertionException]$Message + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } $Actual -} \ No newline at end of file +} diff --git a/src/functions/assert/Collection/Assert-Contain.ps1 b/src/functions/assert/Collection/Assert-Contain.ps1 index 7b43635b1..60bb4e02a 100644 --- a/src/functions/assert/Collection/Assert-Contain.ps1 +++ b/src/functions/assert/Collection/Assert-Contain.ps1 @@ -12,8 +12,8 @@ { $type = [string]$Expected $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be present in collection '', but it was not there." - throw [Assertions.AssertionException]$Message + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } $Actual -} \ No newline at end of file +} diff --git a/src/functions/assert/Collection/Assert-NotContain.ps1 b/src/functions/assert/Collection/Assert-NotContain.ps1 index dedd9845f..27eb5e031 100644 --- a/src/functions/assert/Collection/Assert-NotContain.ps1 +++ b/src/functions/assert/Collection/Assert-NotContain.ps1 @@ -12,8 +12,8 @@ { $type = [string]$Expected $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to not be present in collection '', but it was there." - throw [Assertions.AssertionException]$Message + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } $Actual -} \ No newline at end of file +} diff --git a/src/functions/assert/Compatibility.ps1 b/src/functions/assert/Compatibility.ps1 new file mode 100644 index 000000000..03caf8fa3 --- /dev/null +++ b/src/functions/assert/Compatibility.ps1 @@ -0,0 +1,76 @@ +function New-PSObject ([hashtable]$Property) { + New-Object -Type PSObject -Property $Property +} + +function Invoke-WithContext { + param( + [Parameter(Mandatory = $true )] + [ScriptBlock] $ScriptBlock, + [Parameter(Mandatory = $true)] + [hashtable] $Variables) + + # this functions is a psv2 compatible version of + # ScriptBlock InvokeWithContext that is not available + # in that version of PowerShell + + # this is what the code below does + # which in effect sets the context without detaching the + # scriptblock from the original scope + # & { + # # context + # $a = 10 + # $b = 20 + # # invoking our original scriptblock + # & $sb + # } + + # a similar solution was $SessionState.PSVariable.Set('a', 10) + # but that sets the variable for all "scopes" in the current + # scope so the value persist after the original has run which + # is not correct, + + $scriptBlockWithContext = { + param($context) + + foreach ($pair in $context.Variables.GetEnumerator()) { + New-Variable -Name $pair.Key -Value $pair.Value + } + + # this cleans up the variable from the session + # the subexpression outputs the value of the variable + # and then deletes the variable, so the value is still passed + # but the variable no longer exists when the scriptblock executes + & $($context.ScriptBlock; Remove-Variable -Name 'context' -Scope Local) + } + + $flags = [System.Reflection.BindingFlags]'Instance,NonPublic' + $SessionState = $ScriptBlock.GetType().GetProperty("SessionState", $flags).GetValue($ScriptBlock, $null) + $SessionStateInternal = $SessionState.GetType().GetProperty('Internal', $flags).GetValue($SessionState, $null) + + # attach the original session state to the wrapper scriptblock + # making it invoke in the same scope as $ScriptBlock + $scriptBlockWithContext.GetType().GetProperty('SessionStateInternal', $flags).SetValue($scriptBlockWithContext, $SessionStateInternal, $null) + + & $scriptBlockWithContext @{ ScriptBlock = $ScriptBlock; Variables = $Variables } +} + +function Test-NullOrWhiteSpace ($Value) { + # psv2 compatibility, on newer .net we would simply use + # [string]::isnullorwhitespace + $null -eq $Value -or $Value -match "^\s*$" +} + +function Get-Type ($InputObject) { + try { + $ErrorActionPreference = 'Stop' + # normally this would not ever throw + # but in psv2 when datatable is deserialized then + # [Deserialized.System.Data.DataTable] does not contain + # .GetType() + $InputObject.GetType() + } + catch [Exception] { + return [Object] + } + +} \ No newline at end of file diff --git a/src/functions/assert/Equivalence/Assert-Equivalent.ps1 b/src/functions/assert/Equivalence/Assert-Equivalent.ps1 index f1221af60..cbe73f72a 100644 --- a/src/functions/assert/Equivalence/Assert-Equivalent.ps1 +++ b/src/functions/assert/Equivalence/Assert-Equivalent.ps1 @@ -671,7 +671,7 @@ function Assert-Equivalent { $optionsFormatted = Format-EquivalencyOptions -Options $Options # the paremeter is -Option not -Options $message = Get-AssertionMessage -Actual $actual -Expected $Expected -Option $optionsFormatted -Pretty -CustomMessage "Expected and actual are not equivalent!`nExpected:`n`n`nActual:`n`n`nSummary:`n$areDifferent`n" - throw [Assertions.AssertionException]$message + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } v -Equivalence "`$Actual and `$Expected are equivalent." @@ -755,4 +755,4 @@ function Like-Any { return $false } -} \ No newline at end of file +} diff --git a/src/functions/assert/Exception/Assert-Throw.ps1 b/src/functions/assert/Exception/Assert-Throw.ps1 index a35f27608..effbbd31c 100644 --- a/src/functions/assert/Exception/Assert-Throw.ps1 +++ b/src/functions/assert/Exception/Assert-Throw.ps1 @@ -75,7 +75,7 @@ function Assert-Throw { $Message = Get-AssertionMessage -Expected $Expected -Actual $ScriptBlock -CustomMessage $CustomMessage ` -DefaultMessage $defaultMessage - throw [Assertions.AssertionException]$Message + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } $err.ErrorRecord @@ -118,4 +118,4 @@ function Add-SpaceToNonEmptyString ([string]$Value) { { " $Value" } -} \ No newline at end of file +} diff --git a/src/functions/assert/General/Assert-Equal.ps1 b/src/functions/assert/General/Assert-Equal.ps1 index 5a5f96fad..56af6d6f5 100644 --- a/src/functions/assert/General/Assert-Equal.ps1 +++ b/src/functions/assert/General/Assert-Equal.ps1 @@ -12,8 +12,8 @@ if ((Ensure-ExpectedIsNotCollection $Expected) -ne $Actual) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '', but got ''." - throw [Assertions.AssertionException]$Message + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } $Actual -} \ No newline at end of file +} diff --git a/src/functions/assert/General/Assert-GreaterThan.ps1 b/src/functions/assert/General/Assert-GreaterThan.ps1 index 1fe3643a4..b4d3d4b78 100644 --- a/src/functions/assert/General/Assert-GreaterThan.ps1 +++ b/src/functions/assert/General/Assert-GreaterThan.ps1 @@ -11,8 +11,8 @@ if ((Ensure-ExpectedIsNotCollection $Expected) -ge $Actual) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be greater than '', but it was not." - throw [Assertions.AssertionException]$Message + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } $Actual -} \ No newline at end of file +} diff --git a/src/functions/assert/General/Assert-GreaterThanOrEqual.ps1 b/src/functions/assert/General/Assert-GreaterThanOrEqual.ps1 index 4d0b89489..fec78007c 100644 --- a/src/functions/assert/General/Assert-GreaterThanOrEqual.ps1 +++ b/src/functions/assert/General/Assert-GreaterThanOrEqual.ps1 @@ -11,8 +11,8 @@ if ((Ensure-ExpectedIsNotCollection $Expected) -gt $Actual) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be greater than or equal to '', but it was not." - throw [Assertions.AssertionException]$Message + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } $Actual -} \ No newline at end of file +} diff --git a/src/functions/assert/General/Assert-LessThan.ps1 b/src/functions/assert/General/Assert-LessThan.ps1 index a1b41afbf..f0696fff2 100644 --- a/src/functions/assert/General/Assert-LessThan.ps1 +++ b/src/functions/assert/General/Assert-LessThan.ps1 @@ -11,8 +11,8 @@ if ((Ensure-ExpectedIsNotCollection $Expected) -le $Actual) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be less than '', but it was not." - throw [Assertions.AssertionException]$Message + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } $Actual -} \ No newline at end of file +} diff --git a/src/functions/assert/General/Assert-LessThanOrEqual.ps1 b/src/functions/assert/General/Assert-LessThanOrEqual.ps1 index 43ec5ea06..1806e4a72 100644 --- a/src/functions/assert/General/Assert-LessThanOrEqual.ps1 +++ b/src/functions/assert/General/Assert-LessThanOrEqual.ps1 @@ -11,8 +11,8 @@ if ((Ensure-ExpectedIsNotCollection $Expected) -lt $Actual) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be less than or equal to '', but it was not." - throw [Assertions.AssertionException]$Message + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } $Actual -} \ No newline at end of file +} diff --git a/src/functions/assert/General/Assert-NotEqual.ps1 b/src/functions/assert/General/Assert-NotEqual.ps1 index b02f1dade..137d3e5ad 100644 --- a/src/functions/assert/General/Assert-NotEqual.ps1 +++ b/src/functions/assert/General/Assert-NotEqual.ps1 @@ -11,8 +11,8 @@ if ((Ensure-ExpectedIsNotCollection $Expected) -eq $Actual) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '', to be different than the actual value, but they were the same." - throw [Assertions.AssertionException]$Message + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } $Actual -} \ No newline at end of file +} diff --git a/src/functions/assert/General/Assert-NotNull.ps1 b/src/functions/assert/General/Assert-NotNull.ps1 index 18b071481..f714b299e 100644 --- a/src/functions/assert/General/Assert-NotNull.ps1 +++ b/src/functions/assert/General/Assert-NotNull.ps1 @@ -9,8 +9,8 @@ if ($null -eq $Actual) { $Message = Get-AssertionMessage -Expected $null -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected not `$null, but got `$null." - throw [Assertions.AssertionException]$Message + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } $Actual -} \ No newline at end of file +} diff --git a/src/functions/assert/General/Assert-NotSame.ps1 b/src/functions/assert/General/Assert-NotSame.ps1 index 535ca1d11..0ff518c96 100644 --- a/src/functions/assert/General/Assert-NotSame.ps1 +++ b/src/functions/assert/General/Assert-NotSame.ps1 @@ -11,8 +11,8 @@ if ([object]::ReferenceEquals($Expected, $Actual)) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '', to not be the same instance." - throw [Assertions.AssertionException]$Message + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } $Actual -} \ No newline at end of file +} diff --git a/src/functions/assert/General/Assert-NotType.ps1 b/src/functions/assert/General/Assert-NotType.ps1 index 3198fcc94..1ac387cd2 100644 --- a/src/functions/assert/General/Assert-NotType.ps1 +++ b/src/functions/assert/General/Assert-NotType.ps1 @@ -1,19 +1,18 @@ function Assert-NotType { param ( - [Parameter(Position=1, ValueFromPipeline=$true)] + [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position=0)] + [Parameter(Position = 0)] [Type]$Expected, [String]$CustomMessage ) $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input - if ($Actual -is $Expected) - { + if ($Actual -is $Expected) { $type = [string]$Expected $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected value to be of different type than '$type', but got '' of type ''." - throw [Assertions.AssertionException]$Message + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } $Actual -} \ No newline at end of file +} diff --git a/src/functions/assert/General/Assert-Null.ps1 b/src/functions/assert/General/Assert-Null.ps1 index ba9773db8..033b3f3ff 100644 --- a/src/functions/assert/General/Assert-Null.ps1 +++ b/src/functions/assert/General/Assert-Null.ps1 @@ -9,8 +9,8 @@ if ($null -ne $Actual) { $Message = Get-AssertionMessage -Expected $null -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected `$null, but got ''." - throw [Assertions.AssertionException]$Message + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } $Actual -} \ No newline at end of file +} diff --git a/src/functions/assert/General/Assert-Same.ps1 b/src/functions/assert/General/Assert-Same.ps1 index 5cbff9125..4dc699a29 100644 --- a/src/functions/assert/General/Assert-Same.ps1 +++ b/src/functions/assert/General/Assert-Same.ps1 @@ -16,8 +16,8 @@ if (-not ([object]::ReferenceEquals($Expected, $Actual))) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '', to be the same instance but it was not." - throw [Assertions.AssertionException]$Message + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } $Actual -} \ No newline at end of file +} diff --git a/src/functions/assert/General/Assert-Type.ps1 b/src/functions/assert/General/Assert-Type.ps1 index 14c920c6e..81f9543ff 100644 --- a/src/functions/assert/General/Assert-Type.ps1 +++ b/src/functions/assert/General/Assert-Type.ps1 @@ -1,19 +1,18 @@ function Assert-Type { param ( - [Parameter(Position=1, ValueFromPipeline=$true)] + [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position=0)] + [Parameter(Position = 0)] [Type]$Expected, [String]$CustomMessage ) $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input - if ($Actual -isnot $Expected) - { + if ($Actual -isnot $Expected) { $type = [string]$Expected $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected value to be of type '$type', but got '' of type ''." - throw [Assertions.AssertionException]$Message + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } $Actual -} \ No newline at end of file +} diff --git a/src/functions/assert/String/Assert-Like.ps1 b/src/functions/assert/String/Assert-Like.ps1 index d7c75ad81..b21571956 100644 --- a/src/functions/assert/String/Assert-Like.ps1 +++ b/src/functions/assert/String/Assert-Like.ps1 @@ -1,37 +1,31 @@ -function Test-Like -{ +function Test-Like { param ( [String]$Expected, $Actual, [switch]$CaseSensitive ) - if (-not $CaseSensitive) - { + if (-not $CaseSensitive) { $Actual -like $Expected } - else - { + else { $Actual -clike $Expected } } -function Get-LikeDefaultFailureMessage ([String]$Expected, $Actual, [switch]$CaseSensitive) -{ +function Get-LikeDefaultFailureMessage ([String]$Expected, $Actual, [switch]$CaseSensitive) { $caseSensitiveMessage = "" - if ($CaseSensitive) - { + if ($CaseSensitive) { $caseSensitiveMessage = " case sensitively" } "Expected the string '$Actual' to$caseSensitiveMessage match '$Expected' but it did not." } -function Assert-Like -{ +function Assert-Like { param ( - [Parameter(Position=1, ValueFromPipeline=$true)] + [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position=0, Mandatory=$true)] + [Parameter(Position = 0, Mandatory = $true)] [String]$Expected, [Switch]$CaseSensitive, [String]$CustomMessage @@ -39,22 +33,18 @@ function Assert-Like $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input - if ($Actual -isnot [string]) - { + if ($Actual -isnot [string]) { throw [ArgumentException]"Actual is expected to be string, to avoid confusing behavior that -like operator exhibits with collections. To assert on collections use Assert-Any, Assert-All or some other collection assertion." } $stringsAreAlike = Test-Like -Expected $Expected -Actual $Actual -CaseSensitive:$CaseSensitive -IgnoreWhitespace:$IgnoreWhiteSpace - if (-not ($stringsAreAlike)) - { - if (-not $CustomMessage) - { + if (-not ($stringsAreAlike)) { + if (-not $CustomMessage) { $formattedMessage = Get-LikeDefaultFailureMessage -Expected $Expected -Actual $Actual -CaseSensitive:$CaseSensitive } - else - { + else { $formattedMessage = Get-CustomFailureMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -CaseSensitive:$CaseSensitive } - throw [Assertions.AssertionException]$formattedMessage + throw [Pester.Factory]::CreateShouldErrorRecord($formattedMessage, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } -} \ No newline at end of file +} diff --git a/src/functions/assert/String/Assert-NotLike.ps1 b/src/functions/assert/String/Assert-NotLike.ps1 index 960a49e4b..804de4187 100644 --- a/src/functions/assert/String/Assert-NotLike.ps1 +++ b/src/functions/assert/String/Assert-NotLike.ps1 @@ -1,37 +1,31 @@ -function Test-NotLike -{ +function Test-NotLike { param ( [String]$Expected, $Actual, [switch]$CaseSensitive ) - if (-not $CaseSensitive) - { + if (-not $CaseSensitive) { $Actual -NotLike $Expected } - else - { + else { $actual -cNotLike $Expected } } -function Get-NotLikeDefaultFailureMessage ([String]$Expected, $Actual, [switch]$CaseSensitive) -{ +function Get-NotLikeDefaultFailureMessage ([String]$Expected, $Actual, [switch]$CaseSensitive) { $caseSensitiveMessage = "" - if ($CaseSensitive) - { + if ($CaseSensitive) { $caseSensitiveMessage = " case sensitively" } "Expected the string '$Actual' to$caseSensitiveMessage not match '$Expected' but it matched it." } -function Assert-NotLike -{ +function Assert-NotLike { param ( - [Parameter(Position=1, ValueFromPipeline=$true)] + [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position=0, Mandatory=$true)] + [Parameter(Position = 0, Mandatory = $true)] [String]$Expected, [Switch]$CaseSensitive, [String]$CustomMessage @@ -39,23 +33,19 @@ function Assert-NotLike $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input - if ($Actual -isnot [string]) - { + if ($Actual -isnot [string]) { throw [ArgumentException]"Actual is expected to be string, to avoid confusing behavior that -like operator exhibits with collections. To assert on collections use Assert-Any, Assert-All or some other collection assertion." } $stringsAreANotLike = Test-NotLike -Expected $Expected -Actual $Actual -CaseSensitive:$CaseSensitive -IgnoreWhitespace:$IgnoreWhiteSpace - if (-not ($stringsAreANotLike)) - { - if (-not $CustomMessage) - { + if (-not ($stringsAreANotLike)) { + if (-not $CustomMessage) { $formattedMessage = Get-NotLikeDefaultFailureMessage -Expected $Expected -Actual $Actual -CaseSensitive:$CaseSensitive } - else - { + else { $formattedMessage = Get-CustomFailureMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -CaseSensitive:$CaseSensitive } - throw [Assertions.AssertionException]$formattedMessage + throw [Pester.Factory]::CreateShouldErrorRecord($formattedMessage, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } -} \ No newline at end of file +} diff --git a/src/functions/assert/String/Assert-StringEqual.ps1 b/src/functions/assert/String/Assert-StringEqual.ps1 index 3807ae688..73996fd80 100644 --- a/src/functions/assert/String/Assert-StringEqual.ps1 +++ b/src/functions/assert/String/Assert-StringEqual.ps1 @@ -1,5 +1,4 @@ -function Test-StringEqual -{ +function Test-StringEqual { param ( [String]$Expected, $Actual, @@ -7,33 +6,28 @@ [switch]$IgnoreWhitespace ) - if ($IgnoreWhitespace) - { + if ($IgnoreWhitespace) { $Expected = $Expected -replace '\s' $Actual = $Actual -replace '\s' } - if (-not $CaseSensitive) - { + if (-not $CaseSensitive) { $Expected -eq $Actual } - else - { + else { $Expected -ceq $Actual } } -function Get-StringEqualDefaultFailureMessage ([String]$Expected, $Actual) -{ +function Get-StringEqualDefaultFailureMessage ([String]$Expected, $Actual) { "Expected the string to be '$Expected' but got '$Actual'." } -function Assert-StringEqual -{ +function Assert-StringEqual { param ( - [Parameter(Position=1, ValueFromPipeline=$true)] + [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position=0)] + [Parameter(Position = 0)] [String]$Expected, [String]$CustomMessage, [switch]$CaseSensitive, @@ -42,18 +36,15 @@ function Assert-StringEqual $_actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input - if (-not $CustomMessage) - { + if (-not $CustomMessage) { $formattedMessage = Get-StringEqualDefaultFailureMessage -Expected $Expected -Actual $_actual } - else - { + else { $formattedMessage = Get-CustomFailureMessage -Expected $Expected -Actual $_actual -CustomMessage $CustomMessage } $stringsAreEqual = Test-StringEqual -Expected $Expected -Actual $_actual -CaseSensitive:$CaseSensitive -IgnoreWhitespace:$IgnoreWhiteSpace - if (-not ($stringsAreEqual)) - { - throw [Assertions.AssertionException]$formattedMessage + if (-not ($stringsAreEqual)) { + throw [Pester.Factory]::CreateShouldErrorRecord($formattedMessage, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } -} \ No newline at end of file +} diff --git a/src/functions/assert/String/Assert-StringNotEqual.ps1 b/src/functions/assert/String/Assert-StringNotEqual.ps1 index 29ef52d8f..277c667f7 100644 --- a/src/functions/assert/String/Assert-StringNotEqual.ps1 +++ b/src/functions/assert/String/Assert-StringNotEqual.ps1 @@ -1,31 +1,26 @@ -function Get-StringNotEqualDefaultFailureMessage ([String]$Expected, $Actual) -{ +function Get-StringNotEqualDefaultFailureMessage ([String]$Expected, $Actual) { "Expected the strings to be different but they were the same '$Expected'." } -function Assert-StringNotEqual -{ +function Assert-StringNotEqual { param ( - [Parameter(Position=1, ValueFromPipeline=$true)] + [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position=0)] + [Parameter(Position = 0)] [String]$Expected, [String]$CustomMessage, [switch]$CaseSensitive, [switch]$IgnoreWhitespace ) - if (Test-StringEqual -Expected $Expected -Actual $Actual -CaseSensitive:$CaseSensitive -IgnoreWhitespace:$IgnoreWhiteSpace) - { - if (-not $CustomMessage) - { + if (Test-StringEqual -Expected $Expected -Actual $Actual -CaseSensitive:$CaseSensitive -IgnoreWhitespace:$IgnoreWhiteSpace) { + if (-not $CustomMessage) { $formattedMessage = Get-StringNotEqualDefaultFailureMessage -Expected $Expected -Actual $Actual } - else - { + else { $formattedMessage = Get-CustomFailureMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage } - throw [Assertions.AssertionException]$formattedMessage + throw [Pester.Factory]::CreateShouldErrorRecord($formattedMessage, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } -} \ No newline at end of file +} diff --git a/src/functions/assertions/Should.ps1 b/src/functions/assertions/Should.ps1 index 38a7a43cb..32873b383 100644 --- a/src/functions/assertions/Should.ps1 +++ b/src/functions/assertions/Should.ps1 @@ -9,16 +9,6 @@ return (& $failureMessageFunction $value $expected) } -function New-ShouldErrorRecord ([string] $Message, [string] $File, [string] $Line, [string] $LineText, $Terminating) { - $exception = [Exception] $Message - $errorID = 'PesterAssertionFailed' - $errorCategory = [Management.Automation.ErrorCategory]::InvalidResult - # we use ErrorRecord.TargetObject to pass structured information about the error to a reporting system. - $targetObject = @{ Message = $Message; File = $File; Line = $Line; LineText = $LineText; Terminating = $Terminating } - $errorRecord = & $SafeCommands['New-Object'] Management.Automation.ErrorRecord $exception, $errorID, $errorCategory, $targetObject - return $errorRecord -} - function Should { <# .SYNOPSIS diff --git a/test.ps1 b/test.ps1 index 6a905b6ab..dc47f6f65 100644 --- a/test.ps1 +++ b/test.ps1 @@ -116,6 +116,17 @@ New-Module -Name TestHelpers -ScriptBlock { $module = Get-Module -Name Pester -ErrorAction Stop . $module $ScriptBlock } + + function New-Dictionary ([hashtable]$Hashtable) { + $d = new-object "Collections.Generic.Dictionary[string,object]" + $Hashtable.GetEnumerator() | ForEach-Object { $d.Add($_.Key, $_.Value) } + + $d + } + + function Clear-WhiteSpace ($Text) { + "$($Text -replace "(`t|`n|`r)"," " -replace "\s+"," ")".Trim() + } } | Out-Null diff --git a/tst/Format2.Tests.ps1 b/tst/Format2.Tests.ps1 new file mode 100644 index 000000000..5a9a0a1b1 --- /dev/null +++ b/tst/Format2.Tests.ps1 @@ -0,0 +1,188 @@ +BeforeDiscovery { + Add-Type -TypeDefinition ' + namespace Assertions.TestType { + public class Person { + // powershell v2 mandates fully implemented properties + string _name; + int _age; + public string Name { get { return _name; } set { _name = value; } } + public int Age { get { return _age; } set { _age = value; } } + } + }' +} + + +Describe "Format-Collection2" { + It "Formats collection of values '' to '' using the default separator" -TestCases @( + @{ Value = (1, 2, 3); Expected = "1, 2, 3" } + ) { + param ($Value, $Expected) + Format-Collection2 -Value $Value | Verify-Equal $Expected + } + + It "Formats collection of values '' to '' using the default separator" -TestCases @( + @{ Value = (1, 2, 3); Expected = "1, 2, 3" } + ) { + param ($Value, $Expected) + Format-Collection2 -Value $Value | Verify-Equal $Expected + } +} + +Describe "Format-Number" { + It "Formats number to use . separator (tests anything only on non-english systems --todo)" -TestCases @( + @{ Value = 1.1; }, + @{ Value = [double] 1.1; }, + @{ Value = [float] 1.1; }, + @{ Value = [single] 1.1; }, + @{ Value = [decimal] 1.1; } + ) { + param ($Value) + Format-Number -Value $Value | Verify-Equal "1.1" + } +} + +Describe "Format-Object2" { + It "Formats object '' to ''" -TestCases @( + @{ Value = (New-PSObject @{Name = 'Jakub'; Age = 28 }); Expected = "PSObject{Age=28; Name=Jakub}" }, + @{ Value = (New-Object -Type Assertions.TestType.Person -Property @{Name = 'Jakub'; Age = 28 }); Expected = "Assertions.TestType.Person{Age=28; Name=Jakub}" } + ) { + param ($Value, $Expected) + Format-Object2 -Value $Value | Verify-Equal $Expected + } + + It "Formats object '' with selected properties '' to ''" -TestCases @( + @{ Value = (New-PSObject @{Name = 'Jakub'; Age = 28 }); SelectedProperties = "Age"; Expected = "PSObject{Age=28}" }, + @{ + Value = (New-Object -Type Assertions.TestType.Person -Property @{Name = 'Jakub'; Age = 28 }) + SelectedProperties = 'Name' + Expected = "Assertions.TestType.Person{Name=Jakub}" + } + ) { + param ($Value, $SelectedProperties, $Expected) + Format-Object2 -Value $Value -Property $SelectedProperties | Verify-Equal $Expected + } + + It "Formats current process with selected properties Name and Id correctly" { + # this used to be a normal unit test but Idle process does not exist + # cross platform so we use the current process, which can also have + # different names among powershell versions + $process = Get-Process -PID $PID + $name = $process.Name + $id = $process.Id + $SelectedProperties = "Name", "Id" + $expected = "Diagnostics.Process{Id=$id; Name=$name}" + + Format-Object2 -Value $process -Property $selectedProperties | Verify-Equal $Expected + } +} + +Describe "Format-Boolean2" { + It "Formats boolean '' to ''" -TestCases @( + @{ Value = $true; Expected = '$true' }, + @{ Value = $false; Expected = '$false' } + ) { + param($Value, $Expected) + Format-Boolean2 -Value $Value | Verify-Equal $Expected + } +} + +Describe "Format-Null2" { + It "Formats null to '`$null'" { + Format-Null2 | Verify-Equal '$null' + } +} + +Describe "Format-ScriptBlock2" { + It "Formats scriptblock as string with curly braces" { + Format-ScriptBlock2 -Value { abc } | Verify-Equal '{abc}' + } +} + +Describe "Format-Hashtable2" { + It "Formats empty hashtable as @{}" { + Format-Hashtable2 @{} | Verify-Equal '@{}' + } + + It "Formats hashtable as ''" -TestCases @( + @{ Value = @{Age = 28; Name = 'Jakub' }; Expected = '@{Age=28; Name=Jakub}' } + @{ Value = @{Z = 1; H = 1; A = 1 }; Expected = '@{A=1; H=1; Z=1}' } + @{ Value = @{Hash = @{Hash = 'Value' } }; Expected = '@{Hash=@{Hash=Value}}' } + ) { + param ($Value, $Expected) + Format-Hashtable2 $Value | Verify-Equal $Expected + } +} + +Describe "Format-Dictionary2" { + It "Formats empty dictionary as @{}" { + Format-Dictionary2 (New-Dictionary @{}) | Verify-Equal 'Dictionary{}' + } + + It "Formats dictionary as ''" -TestCases @( + @{ Value = New-Dictionary @{Age = 28; Name = 'Jakub' }; Expected = 'Dictionary{Age=28; Name=Jakub}' } + @{ Value = New-Dictionary @{Z = 1; H = 1; A = 1 }; Expected = 'Dictionary{A=1; H=1; Z=1}' } + @{ Value = New-Dictionary @{Dict = ( New-Dictionary @{Dict = 'Value' }) }; Expected = 'Dictionary{Dict=Dictionary{Dict=Value}}' } + ) { + param ($Value, $Expected) + Format-Dictionary2 $Value | Verify-Equal $Expected + } +} + +Describe "Format-Nicely2" { + It "Formats value '' correctly to ''" -TestCases @( + @{ Value = $null; Expected = '$null' } + @{ Value = $true; Expected = '$true' } + @{ Value = $false; Expected = '$false' } + @{ Value = 'a' ; Expected = 'a' }, + @{ Value = 1; Expected = '1' }, + @{ Value = (1, 2, 3); Expected = '1, 2, 3' }, + @{ Value = 1.1; Expected = '1.1' }, + @{ Value = [int]; Expected = 'int' } + @{ Value = New-PSObject @{ Name = "Jakub" }; Expected = 'PSObject{Name=Jakub}' }, + @{ Value = (New-Object -Type Assertions.TestType.Person -Property @{Name = 'Jakub'; Age = 28 }); Expected = "Assertions.TestType.Person{Age=28; Name=Jakub}" } + @{ Value = @{Name = 'Jakub'; Age = 28 }; Expected = '@{Age=28; Name=Jakub}' } + @{ Value = New-Dictionary @{Age = 28; Name = 'Jakub' }; Expected = 'Dictionary{Age=28; Name=Jakub}' } + ) { + param($Value, $Expected) + Format-Nicely2 -Value $Value | Verify-Equal $Expected + } +} + +Describe "Get-DisplayProperty2" { + It "Returns '' for ''" -TestCases @( + @{ Type = "Diagnostics.Process"; Expected = ("Id", "Name") } + ) { + param ($Type, $Expected) + $Actual = Get-DisplayProperty2 -Type $Type + "$Actual" | Verify-Equal "$Expected" + } +} + +Describe "Format-Type2" { + It "Given '' it returns the correct shortened type name ''" -TestCases @( + @{ Value = [int]; Expected = 'int' }, + @{ Value = [double]; Expected = 'double' }, + @{ Value = [string]; Expected = 'string' }, + @{ Value = $null; Expected = '' }, + @{ Value = [Management.Automation.PSObject]; Expected = 'PSObject' }, + @{ Value = [Object[]]; Expected = 'collection' } + ) { + param($Value, $Expected) + Format-Type2 -Value $Value | Verify-Equal $Expected + } +} + + +Describe "Get-ShortType2" { + It "Given '' it returns the correct shortened type name ''" -TestCases @( + @{ Value = 1; Expected = 'int' }, + @{ Value = 1.1; Expected = 'double' }, + @{ Value = 'a' ; Expected = 'string' }, + @{ Value = $null ; Expected = '' }, + @{ Value = New-PSObject @{Name = 'Jakub' } ; Expected = 'PSObject' }, + @{ Value = [Object[]]1, 2, 3 ; Expected = 'collection' } + ) { + param($Value, $Expected) + Get-ShortType2 -Value $Value | Verify-Equal $Expected + } +} diff --git a/tst/functions/assert/Collection/Assert-Contain.Tests.ps1 b/tst/functions/assert/Collection/Assert-Contain.Tests.ps1 index bde14dc50..e5a949da8 100644 --- a/tst/functions/assert/Collection/Assert-Contain.Tests.ps1 +++ b/tst/functions/assert/Collection/Assert-Contain.Tests.ps1 @@ -1,4 +1,6 @@ -InModuleScope -ModuleName Assert { +Set-StrictMode -Version Latest + +InPesterModuleScope { Describe "Assert-Contain" { It "Passes when collection of single item contains the expected item" { @(1) | Assert-Contain 1 @@ -22,4 +24,4 @@ { Assert-Contain 1 3,4,5 } | Verify-AssertionFailed } } -} \ No newline at end of file +} diff --git a/tst/functions/assert/Collection/Assert-NotContain.Tests.ps1 b/tst/functions/assert/Collection/Assert-NotContain.Tests.ps1 index ded3dec65..545efac26 100644 --- a/tst/functions/assert/Collection/Assert-NotContain.Tests.ps1 +++ b/tst/functions/assert/Collection/Assert-NotContain.Tests.ps1 @@ -1,4 +1,6 @@ -InModuleScope -ModuleName Assert { +Set-StrictMode -Version Latest + +InPesterModuleScope { Describe "Assert-NotContain" { It "Fails when collection of single item contains the expected item" { $error = { @(1) | Assert-NotContain 1 } | Verify-AssertionFailed @@ -22,4 +24,4 @@ InModuleScope -ModuleName Assert { { Assert-NotContain 1 1,2,3 } | Verify-AssertionFailed } } -} \ No newline at end of file +} diff --git a/tst/functions/assert/Common/Ensure-ExpectedIsNotCollection.Tests.ps1 b/tst/functions/assert/Common/Ensure-ExpectedIsNotCollection.Tests.ps1 index 99fa2112f..ae907c926 100644 --- a/tst/functions/assert/Common/Ensure-ExpectedIsNotCollection.Tests.ps1 +++ b/tst/functions/assert/Common/Ensure-ExpectedIsNotCollection.Tests.ps1 @@ -1,4 +1,6 @@ -InModuleScope -ModuleName Assert { +Set-StrictMode -Version Latest + +InPesterModuleScope { Describe "Ensure-ExpectedIsNotCollection" { It "Given a collection it throws ArgumentException" { $error = { Ensure-ExpectedIsNotCollection -InputObject @() } | Verify-Throw @@ -15,4 +17,4 @@ Ensure-ExpectedIsNotCollection -InputObject 'a' | Verify-Equal 'a' } } -} \ No newline at end of file +} diff --git a/tst/functions/assert/Common/Get-AssertionMessage.Tests.ps1 b/tst/functions/assert/Common/Get-AssertionMessage.Tests.ps1 index ce4f88df0..b6f5a8b73 100644 --- a/tst/functions/assert/Common/Get-AssertionMessage.Tests.ps1 +++ b/tst/functions/assert/Common/Get-AssertionMessage.Tests.ps1 @@ -1,4 +1,6 @@ -InModuleScope -ModuleName Assert { +Set-StrictMode -Version Latest + +InPesterModuleScope { Describe "Get-AssertionMessage" { It "returns correct message when no tokens are provided" { $expected = "Static failure message." @@ -48,4 +50,4 @@ Get-AssertionMessage -CustomMessage $customMessage -Data $data | Verify-Equal $expected } } -} \ No newline at end of file +} diff --git a/tst/functions/assert/Equivalence/Assert-Equivalent.Options.Tests.ps1 b/tst/functions/assert/Equivalence/Assert-Equivalent.Options.Tests.ps1 index 632b1d31e..cb4a7c521 100644 --- a/tst/functions/assert/Equivalence/Assert-Equivalent.Options.Tests.ps1 +++ b/tst/functions/assert/Equivalence/Assert-Equivalent.Options.Tests.ps1 @@ -1,4 +1,6 @@ -InModuleScope -ModuleName Assert { +Set-StrictMode -Version Latest + +InPesterModuleScope { Describe "Compare-Equivalent - Exclude path options" { Context "Full excluded paths" { @@ -377,4 +379,4 @@ } } -} \ No newline at end of file +} diff --git a/tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 b/tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 index 6a4426744..42f3ad956 100644 --- a/tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 +++ b/tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 @@ -1,32 +1,32 @@ -BeforeDiscovery { - Add-Type -TypeDefinition 'namespace Assertions.TestType { - public class Person2 { - // powershell v2 mandates fully implemented properties - string _name; - int _age; - public string Name { get { return _name; } set { _name = value; } } - public int Age { get { return _age; } set { _age = value; } } - } - }' -} +Set-StrictMode -Version Latest + +InPesterModuleScope { + BeforeDiscovery { + Add-Type -TypeDefinition 'namespace Assertions.TestType { + public class Person2 { + // powershell v2 mandates fully implemented properties + string _name; + int _age; + public string Name { get { return _name; } set { _name = value; } } + public int Age { get { return _age; } set { _age = value; } } + } + }' + } -InModuleScope -ModuleName Assert { - BeforeAll { + BeforeAll { function Get-TestCase ($Value) { #let's see if this is useful, it's nice for values, but sucks for #types that serialize to just the type name (most of them) - if ($null -ne $Value) - { + if ($null -ne $Value) { @{ Value = $Value - Type = $Value.GetType() + Type = $Value.GetType() } } - else - { + else { @{ Value = $null - Type = '' + Type = '' } } } @@ -56,7 +56,7 @@ InModuleScope -ModuleName Assert { It "Given a value it returns the value and its type in a hashtable" { $expected = @{ Value = 1 - Type = [Int] + Type = [Int] } $actual = Get-TestCase -Value $expected.Value @@ -69,7 +69,7 @@ InModuleScope -ModuleName Assert { It "Given `$null it returns as the name of the type" { $expected = @{ Value = $null - Type = 'none' + Type = 'none' } $actual = Get-TestCase -Value $expected.Value @@ -97,7 +97,7 @@ InModuleScope -ModuleName Assert { It "Returns correct message when comparing value to an array" { $e = 'abc' - $a = 1,2,3 + $a = 1, 2, 3 Get-ValueNotEquivalentMessage -Actual $a -Expected $e | Verify-Equal "Expected 'abc' to be equivalent to the actual value, but got '1, 2, 3'." } @@ -127,17 +127,17 @@ InModuleScope -ModuleName Assert { Describe "Is-CollectionSize" { It "Given two collections '' '' of the same size it returns `$true" -TestCases @( - @{ Actual = (1,2,3); Expected = (1,2,3)}, - @{ Actual = (1,2,3); Expected = (3,2,1)} + @{ Actual = (1, 2, 3); Expected = (1, 2, 3) }, + @{ Actual = (1, 2, 3); Expected = (3, 2, 1) } ) { param ($Actual, $Expected) Is-CollectionSize -Actual $Actual -Expected $Expected | Verify-True } It "Given two collections '' '' of different sizes it returns `$false" -TestCases @( - @{ Actual = (1,2,3); Expected = (1,2,3,4)}, - @{ Actual = (1,2,3); Expected = (1,2)} - @{ Actual = (1,2,3); Expected = @()} + @{ Actual = (1, 2, 3); Expected = (1, 2, 3, 4) }, + @{ Actual = (1, 2, 3); Expected = (1, 2) } + @{ Actual = (1, 2, 3); Expected = @() } ) { param ($Actual, $Expected) Is-CollectionSize -Actual $Actual -Expected $Expected | Verify-False @@ -146,7 +146,7 @@ InModuleScope -ModuleName Assert { Describe "Get-CollectionSizeNotTheSameMessage" { It "Given two collections of differrent sizes it returns the correct message" { - Get-CollectionSizeNotTheSameMessage -Expected (1,2,3) -Actual (1,2) | Verify-Equal "Expected collection '1, 2, 3' with length '3' to be the same size as the actual collection, but got '1, 2' with length '2'." + Get-CollectionSizeNotTheSameMessage -Expected (1, 2, 3) -Actual (1, 2) | Verify-Equal "Expected collection '1, 2, 3' with length '3' to be the same size as the actual collection, but got '1, 2' with length '2'." } } @@ -165,9 +165,9 @@ InModuleScope -ModuleName Assert { @{ Actual = "1"; Expected = 1.01; Message = "Expected '1.01' to be equivalent to the actual value, but got '1'." }, @{ Actual = "abc"; Expected = "a b c"; Message = "Expected 'a b c' to be equivalent to the actual value, but got 'abc'." }, @{ Actual = @("abc", "bde"); Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got 'abc, bde'." }, - @{ Actual = {def}; Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got '{def}'." }, + @{ Actual = { def }; Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got '{def}'." }, @{ Actual = (New-PSObject @{ Name = 'Jakub' }); Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got 'PSObject{Name=Jakub}'." }, - @{ Actual = (1,2,3); Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got '1, 2, 3'." } + @{ Actual = (1, 2, 3); Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got '1, 2, 3'." } ) { param($Actual, $Expected, $Message) Compare-ValueEquivalent -Actual $Actual -Expected $Expected | Verify-Equal $Message @@ -181,24 +181,24 @@ InModuleScope -ModuleName Assert { } It "Given two collections '' '' of different sizes it returns message ''" -TestCases @( - @{ Actual = (1,2,3); Expected = (1,2,3,4); Message = "Expected collection '1, 2, 3, 4' with length '4' to be the same size as the actual collection, but got '1, 2, 3' with length '3'."}, - @{ Actual = (1,2,3); Expected = (3,1); Message = "Expected collection '3, 1' with length '2' to be the same size as the actual collection, but got '1, 2, 3' with length '3'." } + @{ Actual = (1, 2, 3); Expected = (1, 2, 3, 4); Message = "Expected collection '1, 2, 3, 4' with length '4' to be the same size as the actual collection, but got '1, 2, 3' with length '3'." }, + @{ Actual = (1, 2, 3); Expected = (3, 1); Message = "Expected collection '3, 1' with length '2' to be the same size as the actual collection, but got '1, 2, 3' with length '3'." } ) { param ($Actual, $Expected, $Message) Compare-CollectionEquivalent -Actual $Actual -Expected $Expected | Verify-Equal $Message } It "Given collection '' on the expected side and non-collection '' on the actual side it prints the correct message ''" -TestCases @( - @{ Actual = 3; Expected = (1,2,3,4); Message = "Expected collection '1, 2, 3, 4' with length '4', but got '3'."}, - @{ Actual = (New-PSObject @{ Name = 'Jakub' }); Expected = (1,2,3,4); Message = "Expected collection '1, 2, 3, 4' with length '4', but got 'PSObject{Name=Jakub}'."} + @{ Actual = 3; Expected = (1, 2, 3, 4); Message = "Expected collection '1, 2, 3, 4' with length '4', but got '3'." }, + @{ Actual = (New-PSObject @{ Name = 'Jakub' }); Expected = (1, 2, 3, 4); Message = "Expected collection '1, 2, 3, 4' with length '4', but got 'PSObject{Name=Jakub}'." } ) { param ($Actual, $Expected, $Message) Compare-CollectionEquivalent -Actual $Actual -Expected $Expected | Verify-Equal $Message } It "Given two collections '' '' it compares each value with each value and returns `$null if all of them are equivalent" -TestCases @( - @{ Actual = (1,2,3); Expected = (1,2,3)} - @{ Actual = (1,2,3); Expected = (3,2,1)} + @{ Actual = (1, 2, 3); Expected = (1, 2, 3) } + @{ Actual = (1, 2, 3); Expected = (3, 2, 1) } # issue https://github.com/nohwnd/Assert/issues/31 @{ Actual = ($null, $null); Expected = ($null, $null) } @@ -213,8 +213,8 @@ InModuleScope -ModuleName Assert { } It "Given two collections '' '' it compares each value with each value and returns message ' if any of them are not equivalent" -TestCases @( - @{ Actual = (1,2,3); Expected = (4,5,6); Message = "Expected collection '4, 5, 6' to be equivalent to '1, 2, 3' but some values were missing: '4, 5, 6'."}, - @{ Actual = (1,2,3); Expected = (1,2,2); Message = "Expected collection '1, 2, 2' to be equivalent to '1, 2, 3' but some values were missing: '2'."} + @{ Actual = (1, 2, 3); Expected = (4, 5, 6); Message = "Expected collection '4, 5, 6' to be equivalent to '1, 2, 3' but some values were missing: '4, 5, 6'." }, + @{ Actual = (1, 2, 3); Expected = (1, 2, 2); Message = "Expected collection '1, 2, 2' to be equivalent to '1, 2, 3' but some values were missing: '2'." } ) { param ($Actual, $Expected, $Message) Compare-CollectionEquivalent -Actual $Actual -Expected $Expected | Verify-Equal $Message @@ -226,7 +226,7 @@ InModuleScope -ModuleName Assert { @{ Expected = "a" }, @{ Expected = "1" }, @{ Expected = { abc } }, - @{ Expected = (1,2,3) } + @{ Expected = (1, 2, 3) } ) { param($Expected) {} $err = { Compare-ObjectEquivalent -Actual "dummy" -Expected $Expected } | Verify-Throw @@ -234,7 +234,7 @@ InModuleScope -ModuleName Assert { } It "Given values '' and '' that are not equivalent it returns message ''." -TestCases @( - @{ Actual = 'a'; Expected = (New-PSObject @{ Name = 'Jakub' }); Message = "Expected object 'PSObject{Name=Jakub}', but got 'a'."} + @{ Actual = 'a'; Expected = (New-PSObject @{ Name = 'Jakub' }); Message = "Expected object 'PSObject{Name=Jakub}', but got 'a'." } ) { param ($Actual, $Expected, $Message) Compare-ObjectEquivalent -Expected $Expected -Actual $Actual | Verify-Equal $Message @@ -291,15 +291,15 @@ InModuleScope -ModuleName Assert { @{ Actual = $true; Expected = 'True' }, @{ Actual = 'True'; Expected = $true }, @{ Actual = $false; Expected = 'False' }, - @{ Actual = 'False'; Expected = $false}, + @{ Actual = 'False'; Expected = $false }, @{ Actual = 1; Expected = 1 }, @{ Actual = "1"; Expected = 1 }, @{ Actual = "abc"; Expected = "abc" }, @{ Actual = @("abc"); Expected = "abc" }, @{ Actual = "abc"; Expected = @("abc") }, - @{ Actual = {abc}; Expected = "abc" }, - @{ Actual = "abc"; Expected = {abc} }, - @{ Actual = {abc}; Expected = {abc} } + @{ Actual = { abc }; Expected = "abc" }, + @{ Actual = "abc"; Expected = { abc } }, + @{ Actual = { abc }; Expected = { abc } } ) { param ($Actual, $Expected) Compare-Equivalent -Expected $Expected -Actual $Actual | Verify-Null @@ -314,22 +314,22 @@ InModuleScope -ModuleName Assert { @{ Actual = "1"; Expected = 1.01; Message = "Expected '1.01' to be equivalent to the actual value, but got '1'." }, @{ Actual = "abc"; Expected = "a b c"; Message = "Expected 'a b c' to be equivalent to the actual value, but got 'abc'." }, @{ Actual = @("abc", "bde"); Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got 'abc, bde'." }, - @{ Actual = {def}; Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got '{def}'." }, - @{ Actual = "def"; Expected = {abc}; Message = "Expected '{abc}' to be equivalent to the actual value, but got 'def'." }, - @{ Actual = {abc}; Expected = {def}; Message = "Expected '{def}' to be equivalent to the actual value, but got '{abc}'." }, - @{ Actual = (1,2,3); Expected = (1,2,3,4); Message = "Expected collection '1, 2, 3, 4' with length '4' to be the same size as the actual collection, but got '1, 2, 3' with length '3'."}, - @{ Actual = 3; Expected = (1,2,3,4); Message = "Expected collection '1, 2, 3, 4' with length '4', but got '3'."}, - @{ Actual = (New-PSObject @{ Name = 'Jakub' }); Expected = (1,2,3,4); Message = "Expected collection '1, 2, 3, 4' with length '4', but got 'PSObject{Name=Jakub}'."}, + @{ Actual = { def }; Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got '{def}'." }, + @{ Actual = "def"; Expected = { abc }; Message = "Expected '{abc}' to be equivalent to the actual value, but got 'def'." }, + @{ Actual = { abc }; Expected = { def }; Message = "Expected '{def}' to be equivalent to the actual value, but got '{abc}'." }, + @{ Actual = (1, 2, 3); Expected = (1, 2, 3, 4); Message = "Expected collection '1, 2, 3, 4' with length '4' to be the same size as the actual collection, but got '1, 2, 3' with length '3'." }, + @{ Actual = 3; Expected = (1, 2, 3, 4); Message = "Expected collection '1, 2, 3, 4' with length '4', but got '3'." }, + @{ Actual = (New-PSObject @{ Name = 'Jakub' }); Expected = (1, 2, 3, 4); Message = "Expected collection '1, 2, 3, 4' with length '4', but got 'PSObject{Name=Jakub}'." }, @{ Actual = (New-PSObject @{ Name = 'Jakub' }); Expected = "a"; Message = "Expected 'a' to be equivalent to the actual value, but got 'PSObject{Name=Jakub}'." }, - @{ Actual = 'a'; Expected = (New-PSObject @{ Name = 'Jakub' }); Message = "Expected object 'PSObject{Name=Jakub}', but got 'a'."} + @{ Actual = 'a'; Expected = (New-PSObject @{ Name = 'Jakub' }); Message = "Expected object 'PSObject{Name=Jakub}', but got 'a'." } @{ Actual = 'a'; Expected = @{ Name = 'Jakub' }; Message = "Expected hashtable '@{Name=Jakub}', but got 'a'." } - @{ Actual = 'a'; Expected = New-Dictionary @{ Name = 'Jakub' }; Message = "Expected dictionary 'Dictionary{Name=Jakub}', but got 'a'." } + @{ Actual = 'a'; Expected = New-Dictionary @{ Name = 'Jakub' }; Message = "Expected dictionary 'Dictionary{Name=Jakub}', but got 'a'." } ) { param ($Actual, $Expected, $Message) Compare-Equivalent -Expected $Expected -Actual $Actual | Verify-Equal $Message } - It "Comparing the same instance of a psObject returns null"{ + It "Comparing the same instance of a psObject returns null" { $actual = $expected = New-PSObject @{ Name = 'Jakub' } Verify-Same -Expected $expected -Actual $actual @@ -339,15 +339,15 @@ InModuleScope -ModuleName Assert { It "Given PSObjects '' and ' that are different instances but have the same values it returns report with Equivalent set to `$true" -TestCases @( @{ Expected = New-PSObject @{ Name = 'Jakub' } - Actual = New-PSObject @{ Name = 'Jakub' } + Actual = New-PSObject @{ Name = 'Jakub' } }, @{ Expected = New-PSObject @{ Name = 'Jakub' } - Actual = New-PSObject @{ Name = 'Jakub' } + Actual = New-PSObject @{ Name = 'Jakub' } }, @{ Expected = New-PSObject @{ Age = 28 } - Actual = New-PSObject @{ Age = '28' } + Actual = New-PSObject @{ Age = '28' } } ) { param ($Expected, $Actual) @@ -359,18 +359,18 @@ InModuleScope -ModuleName Assert { It "Given PSObjects '' and ' that have different values in some of the properties it returns message ''" -TestCases @( @{ Expected = New-PSObject @{ Name = 'Jakub'; Age = 28 } - Actual = New-PSObject @{ Name = 'Jakub'; Age = 19 } - Message = "Expected property .Age with value '28' to be equivalent to the actual value, but got '19'." + Actual = New-PSObject @{ Name = 'Jakub'; Age = 19 } + Message = "Expected property .Age with value '28' to be equivalent to the actual value, but got '19'." }, @{ Expected = New-PSObject @{ Name = 'Jakub'; Age = 28 } - Actual = New-PSObject @{ Name = 'Jakub'} - Message = "Expected has property 'Age' that the other object does not have." + Actual = New-PSObject @{ Name = 'Jakub' } + Message = "Expected has property 'Age' that the other object does not have." }, @{ - Expected = New-PSObject @{ Name = 'Jakub'} - Actual = New-PSObject @{ Name = 'Jakub'; Age = 28 } - Message = "Expected is missing property 'Age' that the other object has." + Expected = New-PSObject @{ Name = 'Jakub' } + Actual = New-PSObject @{ Name = 'Jakub'; Age = 28 } + Message = "Expected is missing property 'Age' that the other object has." } ) { param ($Expected, $Actual, $Message) @@ -381,8 +381,8 @@ InModuleScope -ModuleName Assert { It "Given PSObject '' and object ' that have the same values it returns `$null" -TestCases @( @{ - Expected = New-Object -TypeName Assertions.TestType.Person2 -Property @{ Name = 'Jakub'; Age = 28} - Actual = New-PSObject @{ Name = 'Jakub'; Age = 28 } + Expected = New-Object -TypeName Assertions.TestType.Person2 -Property @{ Name = 'Jakub'; Age = 28 } + Actual = New-PSObject @{ Name = 'Jakub'; Age = 28 } } ) { param ($Expected, $Actual) @@ -392,8 +392,8 @@ InModuleScope -ModuleName Assert { It "Given PSObjects '' and ' that contain different arrays in the same property returns the correct message" -TestCases @( @{ - Expected = New-PSObject @{ Numbers = 1,2,3 } - Actual = New-PSObject @{ Numbers = 3,4,5 } + Expected = New-PSObject @{ Numbers = 1, 2, 3 } + Actual = New-PSObject @{ Numbers = 3, 4, 5 } } ) { param ($Expected, $Actual) @@ -404,7 +404,7 @@ InModuleScope -ModuleName Assert { It "Comparing psObjects that have collections of objects returns `$null when the objects have the same value" -TestCases @( @{ Expected = New-PSObject @{ Objects = (New-PSObject @{ Name = "Jan" }), (New-PSObject @{ Name = "Tomas" }) } - Actual = New-PSObject @{ Objects = (New-PSObject @{ Name = "Tomas" }), (New-PSObject @{ Name = "Jan" }) } + Actual = New-PSObject @{ Objects = (New-PSObject @{ Name = "Tomas" }), (New-PSObject @{ Name = "Jan" }) } } ) { param ($Expected, $Actual) @@ -414,7 +414,7 @@ InModuleScope -ModuleName Assert { It "Comparing psObjects that have collections of objects returns the correct message when the items in the collection differ" -TestCases @( @{ Expected = New-PSObject @{ Objects = (New-PSObject @{ Name = "Jan" }), (New-PSObject @{ Name = "Petr" }) } - Actual = New-PSObject @{ Objects = (New-PSObject @{ Name = "Jan" }), (New-PSObject @{ Name = "Tomas" }) } + Actual = New-PSObject @{ Objects = (New-PSObject @{ Name = "Jan" }), (New-PSObject @{ Name = "Tomas" }) } } ) { param ($Expected, $Actual) @@ -465,19 +465,19 @@ InModuleScope -ModuleName Assert { Assert-Equivalent -Actual $ActualDeserialized -Expected $ExpectedDeserialized Assert-Equivalent -Actual $Actual -Expected $ExpectedDeserialized - {Assert-Equivalent -Actual $Actual -Expected $Expected -StrictOrder} | Should -Throw + { Assert-Equivalent -Actual $Actual -Expected $Expected -StrictOrder } | Should -Throw $Actual.Rows[1].Name = 'D' - {Assert-Equivalent -Actual $Actual -Expected $Expected} | Should -Throw + { Assert-Equivalent -Actual $Actual -Expected $Expected } | Should -Throw $ExpectedDeserialized = SerializeDeserialize $Expected $ActualDeserialized = SerializeDeserialize $Actual - {Assert-Equivalent -Actual $ActualDeserialized -Expected $ExpectedDeserialized} | Should -Throw - {Assert-Equivalent -Actual $Actual -Expected $ExpectedDeserialized} | Should -Throw + { Assert-Equivalent -Actual $ActualDeserialized -Expected $ExpectedDeserialized } | Should -Throw + { Assert-Equivalent -Actual $Actual -Expected $ExpectedDeserialized } | Should -Throw } It "Can be called with positional parameters" { { Assert-Equivalent 1 2 } | Verify-AssertionFailed } } -} \ No newline at end of file +} diff --git a/tst/functions/assert/General/Assert-Equal.Tests.ps1 b/tst/functions/assert/General/Assert-Equal.Tests.ps1 index 627fe06e3..6ec43dba4 100644 --- a/tst/functions/assert/General/Assert-Equal.Tests.ps1 +++ b/tst/functions/assert/General/Assert-Equal.Tests.ps1 @@ -1,4 +1,6 @@ -InModuleScope -ModuleName Assert { +Set-StrictMode -Version Latest + +InPesterModuleScope { Describe "Assert-Equal" { Context "Comparing strings" { It "Passes when two strings are equal" { @@ -88,4 +90,4 @@ $error.Exception | Verify-Type ([ArgumentException]) } } -} \ No newline at end of file +} diff --git a/tst/functions/assert/General/Assert-GreaterThan.Tests.ps1 b/tst/functions/assert/General/Assert-GreaterThan.Tests.ps1 index 669110a27..0851eaa01 100644 --- a/tst/functions/assert/General/Assert-GreaterThan.Tests.ps1 +++ b/tst/functions/assert/General/Assert-GreaterThan.Tests.ps1 @@ -1,4 +1,6 @@ -InModuleScope -ModuleName Assert { +Set-StrictMode -Version Latest + +InPesterModuleScope { Describe "Assert-GreaterThan" { Context "Comparing strings" { It "Passes when actual is greater than expected" { @@ -106,4 +108,4 @@ $error.Exception | Verify-Type ([ArgumentException]) } } -} \ No newline at end of file +} diff --git a/tst/functions/assert/General/Assert-GreaterThanOrEqual.Tests.ps1 b/tst/functions/assert/General/Assert-GreaterThanOrEqual.Tests.ps1 index 08ebf8e6c..0e634f861 100644 --- a/tst/functions/assert/General/Assert-GreaterThanOrEqual.Tests.ps1 +++ b/tst/functions/assert/General/Assert-GreaterThanOrEqual.Tests.ps1 @@ -1,4 +1,6 @@ -InModuleScope -ModuleName Assert { +Set-StrictMode -Version Latest + +InPesterModuleScope { Describe "Assert-GreaterThanOrEqual" { Context "Comparing strings" { It "Passes when actual is greater than expected" { @@ -106,4 +108,4 @@ $error.Exception | Verify-Type ([ArgumentException]) } } -} \ No newline at end of file +} diff --git a/tst/functions/assert/General/Assert-NotEqual.Tests.ps1 b/tst/functions/assert/General/Assert-NotEqual.Tests.ps1 index c7931672f..c5cc4b73c 100644 --- a/tst/functions/assert/General/Assert-NotEqual.Tests.ps1 +++ b/tst/functions/assert/General/Assert-NotEqual.Tests.ps1 @@ -1,4 +1,6 @@ -InModuleScope -ModuleName Assert { +Set-StrictMode -Version Latest + +InPesterModuleScope { Describe "Assert-NotEqual" { Context "Comparing strings" { It "Fails when two strings are equal" { @@ -86,4 +88,4 @@ $error.Exception | Verify-Type ([ArgumentException]) } } -} \ No newline at end of file +} diff --git a/tst/functions/assert/General/Assert-NotNull.Tests.ps1 b/tst/functions/assert/General/Assert-NotNull.Tests.ps1 index 581345eaa..16d053ba3 100644 --- a/tst/functions/assert/General/Assert-NotNull.Tests.ps1 +++ b/tst/functions/assert/General/Assert-NotNull.Tests.ps1 @@ -1,4 +1,6 @@ -InModuleScope -ModuleName Assert { +Set-StrictMode -Version Latest + +InPesterModuleScope { Describe "Assert-NotNull" { It "Given a value it passes" { 1 | Assert-NotNull @@ -16,4 +18,4 @@ { Assert-NotNull $null } | Verify-AssertionFailed } } -} \ No newline at end of file +} diff --git a/tst/functions/assert/General/Assert-NotSame.Tests.ps1 b/tst/functions/assert/General/Assert-NotSame.Tests.ps1 index fe5441bb4..23b78431f 100644 --- a/tst/functions/assert/General/Assert-NotSame.Tests.ps1 +++ b/tst/functions/assert/General/Assert-NotSame.Tests.ps1 @@ -1,4 +1,6 @@ -InModuleScope -ModuleName Assert { +Set-StrictMode -Version Latest + +InPesterModuleScope { Describe "Assert-NotSame" { It "Fails when two objects are the same instance" { $object = New-Object Diagnostics.Process @@ -42,4 +44,4 @@ } | Verify-AssertionFailed } } -} \ No newline at end of file +} diff --git a/tst/functions/assert/General/Assert-NotType.Tests.ps1 b/tst/functions/assert/General/Assert-NotType.Tests.ps1 index e8b762d78..2a0409c66 100644 --- a/tst/functions/assert/General/Assert-NotType.Tests.ps1 +++ b/tst/functions/assert/General/Assert-NotType.Tests.ps1 @@ -1,4 +1,6 @@ -InModuleScope -ModuleName Assert { +Set-StrictMode -Version Latest + +InPesterModuleScope { Describe "Assert-NotType" { It "Given value of expected type it fails" { { 1 | Assert-NotType ([int]) } | Verify-AssertionFailed @@ -16,4 +18,4 @@ { Assert-NotType ([int]) 1 } | Verify-AssertionFailed } } -} \ No newline at end of file +} diff --git a/tst/functions/assert/General/Assert-Null.Tests.ps1 b/tst/functions/assert/General/Assert-Null.Tests.ps1 index 54b02594d..32bf7f3ee 100644 --- a/tst/functions/assert/General/Assert-Null.Tests.ps1 +++ b/tst/functions/assert/General/Assert-Null.Tests.ps1 @@ -1,4 +1,6 @@ -InModuleScope -ModuleName Assert { +Set-StrictMode -Version Latest + +InPesterModuleScope { Describe "Assert-Null" { It "Given `$null it passes" { $null | Assert-Null @@ -16,4 +18,4 @@ { Assert-Null 1 } | Verify-AssertionFailed } } -} \ No newline at end of file +} diff --git a/tst/functions/assert/General/Assert-Same.Tests.ps1 b/tst/functions/assert/General/Assert-Same.Tests.ps1 index 3a8c1b482..dc119abed 100644 --- a/tst/functions/assert/General/Assert-Same.Tests.ps1 +++ b/tst/functions/assert/General/Assert-Same.Tests.ps1 @@ -1,4 +1,6 @@ -InModuleScope -ModuleName Assert { +Set-StrictMode -Version Latest + +InPesterModuleScope { Describe "Assert-Same" { It "Passes when two objects are the same instance" { $object = New-Object Diagnostics.Process @@ -56,4 +58,4 @@ { Assert-Same $object "abc" } | Verify-AssertionFailed } } -} \ No newline at end of file +} diff --git a/tst/functions/assert/General/Assert-Type.Tests.ps1 b/tst/functions/assert/General/Assert-Type.Tests.ps1 index 08374ab66..7748c2439 100644 --- a/tst/functions/assert/General/Assert-Type.Tests.ps1 +++ b/tst/functions/assert/General/Assert-Type.Tests.ps1 @@ -1,4 +1,6 @@ -InModuleScope -ModuleName Assert { +Set-StrictMode -Version Latest + +InPesterModuleScope { Describe "Assert-Type" { It "Given value of expected type it passes" { 1| Assert-Type ([int]) @@ -16,4 +18,4 @@ { Assert-Type ([string]) 1 } | Verify-AssertionFailed } } -} \ No newline at end of file +} diff --git a/tst/functions/assert/Get-CustomFailureMessage.Tests.ps1 b/tst/functions/assert/Get-CustomFailureMessage.Tests.ps1 index 10b4d379c..f89b75178 100644 --- a/tst/functions/assert/Get-CustomFailureMessage.Tests.ps1 +++ b/tst/functions/assert/Get-CustomFailureMessage.Tests.ps1 @@ -1,4 +1,6 @@ -InModuleScope -ModuleName Assert { +Set-StrictMode -Version Latest + +InPesterModuleScope { Describe "Get-CustomFailureMessage" { It "returns correct custom message when no tokens are provided" { $expected = "Static failure message." @@ -24,4 +26,4 @@ InModuleScope -ModuleName Assert { Get-CustomFailureMessage -CustomMessage $customMessage -Expected 1 -Actual 2 | Verify-Equal $expected } } -} \ No newline at end of file +} diff --git a/tst/functions/assert/String/Assert-StringEqual.Tests.ps1 b/tst/functions/assert/String/Assert-StringEqual.Tests.ps1 index 63898f193..92a2d8cd0 100644 --- a/tst/functions/assert/String/Assert-StringEqual.Tests.ps1 +++ b/tst/functions/assert/String/Assert-StringEqual.Tests.ps1 @@ -1,4 +1,6 @@ -InModuleScope -ModuleName Assert { +Set-StrictMode -Version Latest + +InPesterModuleScope { Describe "Test-StringEqual" { Context "Case insensitive matching" { It "strings with the same values are equal" { @@ -121,4 +123,4 @@ { Assert-StringEqual "a" "b" } | Verify-AssertionFailed } } -} \ No newline at end of file +} diff --git a/tst/functions/assert/String/Assert-StringNotEqual.Tests.ps1 b/tst/functions/assert/String/Assert-StringNotEqual.Tests.ps1 index 76f3f4e70..8ebd42828 100644 --- a/tst/functions/assert/String/Assert-StringNotEqual.Tests.ps1 +++ b/tst/functions/assert/String/Assert-StringNotEqual.Tests.ps1 @@ -1,4 +1,6 @@ -InModuleScope -ModuleName Assert { +Set-StrictMode -Version Latest + +InPesterModuleScope { Describe "Get-StringNotEqualDefaultFailureMessage" { It "returns correct default message" { $expected = "Expected the strings to be different but they were the same 'abc'." @@ -55,4 +57,4 @@ { Assert-StringNotEqual "a" "a" } | Verify-AssertionFailed } } -} \ No newline at end of file +} diff --git a/tst/functions/assert/TestHelpers.psm1 b/tst/functions/assert/TestHelpers.psm1 deleted file mode 100644 index 30f584578..000000000 --- a/tst/functions/assert/TestHelpers.psm1 +++ /dev/null @@ -1,11 +0,0 @@ -function New-Dictionary ([hashtable]$Hashtable) { - $d = new-object "Collections.Generic.Dictionary[string,object]" - - $Hashtable.GetEnumerator() | ForEach-Object { $d.Add($_.Key, $_.Value) } - - $d -} - -function Clear-WhiteSpace ($Text) { - "$($Text -replace "(`t|`n|`r)"," " -replace "\s+"," ")".Trim() -} \ No newline at end of file From 079d374c319ad6d9c1ff474da7c34407317d500f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Tue, 2 Apr 2024 00:23:39 +0200 Subject: [PATCH 03/55] Few more tests --- build.ps1 | 2 + src/Format2.ps1 | 4 +- src/TypeClass.ps1 | 4 + .../assert/Common/Get-AssertionMessage.ps1 | 12 +- .../assert/Equivalence/Assert-Equivalent.ps1 | 283 ++++++++---------- .../assert/Exception/Assert-Throw.ps1 | 44 ++- tst/axiom/Axiom.psm1 | 2 + tst/axiom/Verify-Like.ps1 | 19 ++ .../Equivalence/Assert-Equivalent.Tests.ps1 | 2 +- .../assert/Exception/Assert-Throw.Tests.ps1 | 44 ++- 10 files changed, 190 insertions(+), 226 deletions(-) create mode 100644 tst/axiom/Verify-Like.ps1 diff --git a/build.ps1 b/build.ps1 index 318898fc0..1a29c0dc4 100644 --- a/build.ps1 +++ b/build.ps1 @@ -279,6 +279,8 @@ $script = @( "$PSScriptRoot/src/Pester.Runtime.ps1" "$PSScriptRoot/src/TypeClass.ps1" "$PSScriptRoot/src/Format.ps1" + # TODO: the original version of Format2 from assert, because it does not format strings and other stuff in Pester specific way. I've used this regex (Format-Collection|Format-Object|Format-Null|Format-Boolean|Format-ScriptBlock|Format-Number|Format-Hashtable|Format-Dictionary|Format-Nicely|Get-DisplayProperty|Get-ShortType|Format-Type), '$12' to replace in VS Code. + "$PSScriptRoot/src/Format2.ps1" "$PSScriptRoot/src/Pester.RSpec.ps1" "$PSScriptRoot/src/Main.ps1" diff --git a/src/Format2.ps1 b/src/Format2.ps1 index 31515e7c0..7a2282e5b 100644 --- a/src/Format2.ps1 +++ b/src/Format2.ps1 @@ -51,7 +51,7 @@ function Format-Hashtable2 ($Value) { $tail = '}' $entries = $Value.Keys | Sort-Object | ForEach-Object { - $formattedValue = Format-Nicely $Value.$_ + $formattedValue = Format-Nicely2 $Value.$_ "$_=$formattedValue" } $head + ( $entries -join '; ') + $tail @@ -62,7 +62,7 @@ function Format-Dictionary2 ($Value) { $tail = '}' $entries = $Value.Keys | Sort-Object | ForEach-Object { - $formattedValue = Format-Nicely $Value.$_ + $formattedValue = Format-Nicely2 $Value.$_ "$_=$formattedValue" } $head + ( $entries -join '; ') + $tail diff --git a/src/TypeClass.ps1 b/src/TypeClass.ps1 index 4c3f6f79e..c097d5f3a 100644 --- a/src/TypeClass.ps1 +++ b/src/TypeClass.ps1 @@ -43,3 +43,7 @@ function Is-Object ($Value) { function Is-DataRow ($Value) { $Value -is [Data.DataRow] -or $Value.Psobject.TypeNames[0] -like '*System.Data.DataRow' } + +function Is-DataTable ($Value) { + $Value -is [Data.DataTable] -or $Value.Psobject.TypeNames[0] -like '*System.Data.DataTable' +} diff --git a/src/functions/assert/Common/Get-AssertionMessage.ps1 b/src/functions/assert/Common/Get-AssertionMessage.ps1 index 8514ae7c7..05b081cd2 100644 --- a/src/functions/assert/Common/Get-AssertionMessage.ps1 +++ b/src/functions/assert/Common/Get-AssertionMessage.ps1 @@ -5,8 +5,8 @@ $CustomMessage = $DefaultMessage } - $expectedFormatted = Format-Nicely -Value $Expected -Pretty:$Pretty - $actualFormatted = Format-Nicely -Value $Actual -Pretty:$Pretty + $expectedFormatted = Format-Nicely2 -Value $Expected -Pretty:$Pretty + $actualFormatted = Format-Nicely2 -Value $Actual -Pretty:$Pretty $optionMessage = $null; if ($null -ne $Option -and $option.Length -gt 0) @@ -24,13 +24,13 @@ $CustomMessage = $CustomMessage.Replace('', $expectedFormatted) $CustomMessage = $CustomMessage.Replace('', $actualFormatted) - $CustomMessage = $CustomMessage.Replace('', (Get-ShortType -Value $Expected)) - $CustomMessage = $CustomMessage.Replace('', (Get-ShortType -Value $Actual)) + $CustomMessage = $CustomMessage.Replace('', (Get-ShortType2 -Value $Expected)) + $CustomMessage = $CustomMessage.Replace('', (Get-ShortType2 -Value $Actual)) $CustomMessage = $CustomMessage.Replace('', $optionMessage) foreach ($pair in $Data.GetEnumerator()) { - $CustomMessage = $CustomMessage.Replace("<$($pair.Key)>", (Format-Nicely -Value $pair.Value)) + $CustomMessage = $CustomMessage.Replace("<$($pair.Key)>", (Format-Nicely2 -Value $pair.Value)) } if (-not $Pretty) { @@ -40,4 +40,4 @@ { $CustomMessage + "`n`n" } -} \ No newline at end of file +} diff --git a/src/functions/assert/Equivalence/Assert-Equivalent.ps1 b/src/functions/assert/Equivalence/Assert-Equivalent.ps1 index cbe73f72a..be33c4f10 100644 --- a/src/functions/assert/Equivalence/Assert-Equivalent.ps1 +++ b/src/functions/assert/Equivalence/Assert-Equivalent.ps1 @@ -12,12 +12,12 @@ function Is-CollectionSize ($Expected, $Actual) { } function Is-DataTableSize ($Expected, $Actual) { - return $Expected.Rows.Count -eq $Actual.Rows.Count + return $Expected.Rows.Count -eq $Actual.Rows.Count } function Get-ValueNotEquivalentMessage ($Expected, $Actual, $Property, $Options) { - $Expected = Format-Nicely -Value $Expected - $Actual = Format-Nicely -Value $Actual + $Expected = Format-Nicely2 -Value $Expected + $Actual = Format-Nicely2 -Value $Actual $propertyInfo = if ($Property) { " property $Property with value" } $comparison = if ("Equality" -eq $Options.Comparator) { 'equal' } else { 'equivalent' } "Expected$propertyInfo '$Expected' to be $comparison to the actual value, but got '$Actual'." @@ -25,10 +25,10 @@ function Get-ValueNotEquivalentMessage ($Expected, $Actual, $Property, $Options) function Get-CollectionSizeNotTheSameMessage ($Actual, $Expected, $Property) { - $expectedLength = if ($Expected.Length -is [int]) {$Expected.Length} else {$Expected.Count} - $actualLength = if ($Actual.Length -is [int]) {$Actual.Length} else {$Actual.Count} - $Expected = Format-Collection -Value $Expected - $Actual = Format-Collection -Value $Actual + $expectedLength = if ($Expected.Length -is [int]) { $Expected.Length } else { $Expected.Count } + $actualLength = if ($Actual.Length -is [int]) { $Actual.Length } else { $Actual.Count } + $Expected = Format-Collection2 -Value $Expected + $Actual = Format-Collection2 -Value $Actual $propertyMessage = $null if ($property) { @@ -40,8 +40,8 @@ function Get-CollectionSizeNotTheSameMessage ($Actual, $Expected, $Property) { function Get-DataTableSizeNotTheSameMessage ($Actual, $Expected, $Property) { $expectedLength = $Expected.Rows.Count $actualLength = $Actual.Rows.Count - $Expected = Format-Collection -Value $Expected - $Actual = Format-Collection -Value $Actual + $Expected = Format-Collection2 -Value $Expected + $Actual = Format-Collection2 -Value $Actual $propertyMessage = $null if ($property) { @@ -51,17 +51,15 @@ function Get-DataTableSizeNotTheSameMessage ($Actual, $Expected, $Property) { } function Compare-CollectionEquivalent ($Expected, $Actual, $Property, $Options) { - if (-not (Is-Collection -Value $Expected)) - { + if (-not (Is-Collection -Value $Expected)) { throw [ArgumentException]"Expected must be a collection." } - if (-not (Is-Collection -Value $Actual)) - { - v -Difference "`$Actual is not a collection it is a $(Format-Nicely (Get-Type $Actual)), so they are not equivalent." - $expectedFormatted = Format-Collection -Value $Expected + if (-not (Is-Collection -Value $Actual)) { + v -Difference "`$Actual is not a collection it is a $(Format-Nicely2 (Get-Type $Actual)), so they are not equivalent." + $expectedFormatted = Format-Collection2 -Value $Expected $expectedLength = $expected.Length - $actualFormatted = Format-Nicely -Value $actual + $actualFormatted = Format-Nicely2 -Value $actual return "Expected collection '$expectedFormatted' with length '$expectedLength', but got '$actualFormatted'." } @@ -70,38 +68,37 @@ function Compare-CollectionEquivalent ($Expected, $Actual, $Property, $Options) return Get-CollectionSizeNotTheSameMessage -Expected $Expected -Actual $Actual -Property $Property } - $eEnd = if ($Expected.Length -is [int]) {$Expected.Length} else {$Expected.Count} - $aEnd = if ($Actual.Length -is [int]) {$Actual.Length} else {$Actual.Count} + $eEnd = if ($Expected.Length -is [int]) { $Expected.Length } else { $Expected.Count } + $aEnd = if ($Actual.Length -is [int]) { $Actual.Length } else { $Actual.Count } v "Comparing items in collection, `$Expected has lenght $eEnd, `$Actual has length $aEnd." $taken = @() $notFound = @() $anyDifferent = $false - for ($e=0; $e -lt $eEnd; $e++) { + for ($e = 0; $e -lt $eEnd; $e++) { # todo: retest strict order v "`nSearching for `$Expected[$e]:" $currentExpected = $Expected[$e] $found = $false if ($StrictOrder) { $currentActual = $Actual[$e] - if ($taken -notcontains $e -and (-not (Compare-Equivalent -Expected $currentExpected -Actual $currentActual -Path $Property -Options $Options))) - { + if ($taken -notcontains $e -and (-not (Compare-Equivalent -Expected $currentExpected -Actual $currentActual -Path $Property -Options $Options))) { $taken += $e $found = $true v -Equivalence "`Found `$Expected[$e]." } } else { - for ($a=0; $a -lt $aEnd; $a++) { + for ($a = 0; $a -lt $aEnd; $a++) { # we already took this item as equivalent to an item # in the expected collection, skip it if ($taken -contains $a) { v "Skipping `$Actual[$a] because it is already taken." - continue } + continue + } $currentActual = $Actual[$a] # -not, because $null means no differences, and some strings means there are differences v "Comparing `$Actual[$a] to `$Expected[$e] to see if they are equivalent." - if (-not (Compare-Equivalent -Expected $currentExpected -Actual $currentActual -Path $Property -Options $Options)) - { + if (-not (Compare-Equivalent -Expected $currentExpected -Actual $currentActual -Path $Property -Options $Options)) { # add the index to the list of taken items so we can skip it # in the search, this way we can compare collections with # arrays multiple same items @@ -114,8 +111,7 @@ function Compare-CollectionEquivalent ($Expected, $Actual, $Property, $Options) } } } - if (-not $found) - { + if (-not $found) { v -Difference "`$Actual does not contain `$Expected[$e]." $anyDifferent = $true $notFound += $currentExpected @@ -128,11 +124,11 @@ function Compare-CollectionEquivalent ($Expected, $Actual, $Property, $Options) # there was a single item that we did not find if ($anyDifferent) { v -Difference "`$Actual and `$Expected arrays are not equivalent." - $Expected = Format-Nicely -Value $Expected - $Actual = Format-Nicely -Value $Actual - $notFoundFormatted = Format-Nicely -Value ( $notFound | ForEach-Object { Format-Nicely -Value $_ } ) + $Expected = Format-Nicely2 -Value $Expected + $Actual = Format-Nicely2 -Value $Actual + $notFoundFormatted = Format-Nicely2 -Value ( $notFound | ForEach-Object { Format-Nicely2 -Value $_ } ) - $propertyMessage = if ($Property) {" in property $Property which is"} + $propertyMessage = if ($Property) { " in property $Property which is" } return "Expected collection$propertyMessage '$Expected' to be equivalent to '$Actual' but some values were missing: '$notFoundFormatted'." } v -Equivalence "`$Actual and `$Expected arrays are equivalent." @@ -144,9 +140,9 @@ function Compare-DataTableEquivalent ($Expected, $Actual, $Property, $Options) { } if (-not (Is-DataTable -Value $Actual)) { - $expectedFormatted = Format-Collection -Value $Expected + $expectedFormatted = Format-Collection2 -Value $Expected $expectedLength = $expected.Rows.Count - $actualFormatted = Format-Nicely -Value $actual + $actualFormatted = Format-Nicely2 -Value $actual return "Expected DataTable '$expectedFormatted' with length '$expectedLength', but got '$actualFormatted'." } @@ -181,20 +177,19 @@ function Compare-DataTableEquivalent ($Expected, $Actual, $Property, $Options) { $notFound += $currentExpected } } - $Expected = Format-Nicely -Value $Expected - $Actual = Format-Nicely -Value $Actual - $notFoundFormatted = Format-Nicely -Value ( $notFound | ForEach-Object { Format-Nicely -Value $_ } ) + $Expected = Format-Nicely2 -Value $Expected + $Actual = Format-Nicely2 -Value $Actual + $notFoundFormatted = Format-Nicely2 -Value ( $notFound | ForEach-Object { Format-Nicely2 -Value $_ } ) if ($notFound) { - $propertyMessage = if ($Property) {" in property $Property which is"} + $propertyMessage = if ($Property) { " in property $Property which is" } return "Expected DataTable$propertyMessage '$Expected' to be equivalent to '$Actual' but some values were missing: '$notFoundFormatted'." } } function Compare-ValueEquivalent ($Actual, $Expected, $Property, $Options) { $Expected = $($Expected) - if (-not (Is-Value -Value $Expected)) - { + if (-not (Is-Value -Value $Expected)) { throw [ArgumentException]"Expected must be a Value." } @@ -206,40 +201,34 @@ function Compare-ValueEquivalent ($Actual, $Expected, $Property, $Options) { ("Equivalency" -eq $Options.Comparator)) { v "Equivalency comparator is used, values will be compared for equivalency." # fix that string 'false' becomes $true boolean - if ($Actual -is [Bool] -and $Expected -is [string] -and "$Expected" -eq 'False') - { + if ($Actual -is [Bool] -and $Expected -is [string] -and "$Expected" -eq 'False') { v "`$Actual is a boolean, and `$Expected is a 'False' string, which we consider equivalent to boolean `$false. Setting `$Expected to `$false." $Expected = $false - if ($Expected -ne $Actual) - { - v -Difference "`$Actual is not equivalent to $(Format-Nicely $Expected) because it is $(Format-Nicely $Actual)." + if ($Expected -ne $Actual) { + v -Difference "`$Actual is not equivalent to $(Format-Nicely2 $Expected) because it is $(Format-Nicely2 $Actual)." return Get-ValueNotEquivalentMessage -Expected $Expected -Actual $Actual -Property $Property -Options $Options } - v -Equivalence "`$Actual is equivalent to $(Format-Nicely $Expected) because it is $(Format-Nicely $Actual)." + v -Equivalence "`$Actual is equivalent to $(Format-Nicely2 $Expected) because it is $(Format-Nicely2 $Actual)." return } - if ($Expected -is [Bool] -and $Actual -is [string] -and "$Actual" -eq 'False') - { + if ($Expected -is [Bool] -and $Actual -is [string] -and "$Actual" -eq 'False') { v "`$Actual is a 'False' string, which we consider equivalent to boolean `$false. `$Expected is a boolean. Setting `$Actual to `$false." $Actual = $false - if ($Expected -ne $Actual) - { - v -Difference "`$Actual is not equivalent to $(Format-Nicely $Expected) because it is $(Format-Nicely $Actual)." + if ($Expected -ne $Actual) { + v -Difference "`$Actual is not equivalent to $(Format-Nicely2 $Expected) because it is $(Format-Nicely2 $Actual)." return Get-ValueNotEquivalentMessage -Expected $Expected -Actual $Actual -Property $Property -Options $Options } - v -Equivalence "`$Actual is equivalent to $(Format-Nicely $Expected) because it is $(Format-Nicely $Actual)." + v -Equivalence "`$Actual is equivalent to $(Format-Nicely2 $Expected) because it is $(Format-Nicely2 $Actual)." return } #fix that scriptblocks are compared by reference - if (Is-ScriptBlock -Value $Expected) - { + if (Is-ScriptBlock -Value $Expected) { # todo: compare by equivalency like strings? v "`$Expected is a ScriptBlock, scriptblocks are considered equivalent when their content is equal. Converting `$Expected to string." #forcing scriptblock to serialize to string and then comparing that - if ("$Expected" -ne $Actual) - { + if ("$Expected" -ne $Actual) { # todo: difference on index? v -Difference "`$Actual is not equivalent to `$Expected because their contents differ." return Get-ValueNotEquivalentMessage -Expected $Expected -Actual $Actual -Property $Path -Options $Options @@ -248,34 +237,30 @@ function Compare-ValueEquivalent ($Actual, $Expected, $Property, $Options) { return } } - else - { + else { v "Equality comparator is used, values will be compared for equality." } - v "Comparing values as $(Format-Nicely (Get-Type $Expected)) because `$Expected has that type." + v "Comparing values as $(Format-Nicely2 (Get-Type $Expected)) because `$Expected has that type." # todo: shorter messages when both sides have the same type (do not compare by using -is, instead query the type and compare it) because -is is true even for parent types $type = Get-Type $Expected $coalescedActual = $Actual -as $type - if ($Expected -ne $Actual) - { - v -Difference "`$Actual is not equivalent to $(Format-Nicely $Expected) because it is $(Format-Nicely $Actual), and $(Format-Nicely $Actual) coalesced to $(Format-Nicely $type) is $(Format-Nicely $coalescedActual)." + if ($Expected -ne $Actual) { + v -Difference "`$Actual is not equivalent to $(Format-Nicely2 $Expected) because it is $(Format-Nicely2 $Actual), and $(Format-Nicely2 $Actual) coalesced to $(Format-Nicely2 $type) is $(Format-Nicely2 $coalescedActual)." return Get-ValueNotEquivalentMessage -Expected $Expected -Actual $Actual -Property $Property -Options $Options } - v -Equivalence "`$Actual is equivalent to $(Format-Nicely $Expected) because it is $(Format-Nicely $Actual), and $(Format-Nicely $Actual) coalesced to $(Format-Nicely $type) is $(Format-Nicely $coalescedActual)." + v -Equivalence "`$Actual is equivalent to $(Format-Nicely2 $Expected) because it is $(Format-Nicely2 $Actual), and $(Format-Nicely2 $Actual) coalesced to $(Format-Nicely2 $type) is $(Format-Nicely2 $coalescedActual)." } function Compare-HashtableEquivalent ($Actual, $Expected, $Property, $Options) { - if (-not (Is-Hashtable -Value $Expected)) - { + if (-not (Is-Hashtable -Value $Expected)) { throw [ArgumentException]"Expected must be a hashtable." } - if (-not (Is-Hashtable -Value $Actual)) - { - v -Difference "`$Actual is not a hashtable it is a $(Format-Nicely (Get-Type $Actual)), so they are not equivalent." - $expectedFormatted = Format-Nicely -Value $Expected - $actualFormatted = Format-Nicely -Value $Actual + if (-not (Is-Hashtable -Value $Actual)) { + v -Difference "`$Actual is not a hashtable it is a $(Format-Nicely2 (Get-Type $Actual)), so they are not equivalent." + $expectedFormatted = Format-Nicely2 -Value $Expected + $actualFormatted = Format-Nicely2 -Value $Actual return "Expected hashtable '$expectedFormatted', but got '$actualFormatted'." } @@ -286,15 +271,13 @@ function Compare-HashtableEquivalent ($Actual, $Expected, $Property, $Options) { v "`Comparing all ($($expectedKeys.Count)) keys from `$Expected to keys in `$Actual." $result = @() - foreach ($k in $expectedKeys) - { + foreach ($k in $expectedKeys) { if (-not (Test-IncludedPath -PathSelector Hashtable -Path $Property -Options $Options -InputObject $k)) { continue } $actualHasKey = $actualKeys -contains $k - if (-not $actualHasKey) - { + if (-not $actualHasKey) { v -Difference "`$Actual is missing key '$k'." $result += "Expected has key '$k' that the other object does not have." continue @@ -314,23 +297,21 @@ function Compare-HashtableEquivalent ($Actual, $Expected, $Property, $Options) { # fix for powershell v2 where foreach goes once over null if ($filteredKeysNotInExpected | Where-Object { $_ }) { - v -Difference "`$Actual has $($filteredKeysNotInExpected.Count) keys that were not found on `$Expected: $(Format-Nicely @($filteredKeysNotInExpected))." + v -Difference "`$Actual has $($filteredKeysNotInExpected.Count) keys that were not found on `$Expected: $(Format-Nicely2 @($filteredKeysNotInExpected))." } else { v "`$Actual has no keys that we did not find on `$Expected." } - foreach ($k in $filteredKeysNotInExpected | Where-Object { $_ }) - { + foreach ($k in $filteredKeysNotInExpected | Where-Object { $_ }) { $result += "Expected is missing key '$k' that the other object has." } } - if ($result | Where-Object { $_ }) - { + if ($result | Where-Object { $_ }) { v -Difference "Hashtables `$Actual and `$Expected are not equivalent." - $expectedFormatted = Format-Nicely -Value $Expected - $actualFormatted = Format-Nicely -Value $Actual + $expectedFormatted = Format-Nicely2 -Value $Expected + $actualFormatted = Format-Nicely2 -Value $Actual return "Expected hashtable '$expectedFormatted', but got '$actualFormatted'.`n$($result -join "`n")" } @@ -338,16 +319,14 @@ function Compare-HashtableEquivalent ($Actual, $Expected, $Property, $Options) { } function Compare-DictionaryEquivalent ($Actual, $Expected, $Property, $Options) { - if (-not (Is-Dictionary -Value $Expected)) - { + if (-not (Is-Dictionary -Value $Expected)) { throw [ArgumentException]"Expected must be a dictionary." } - if (-not (Is-Dictionary -Value $Actual)) - { - v -Difference "`$Actual is not a dictionary it is a $(Format-Nicely (Get-Type $Actual)), so they are not equivalent." - $expectedFormatted = Format-Nicely -Value $Expected - $actualFormatted = Format-Nicely -Value $Actual + if (-not (Is-Dictionary -Value $Actual)) { + v -Difference "`$Actual is not a dictionary it is a $(Format-Nicely2 (Get-Type $Actual)), so they are not equivalent." + $expectedFormatted = Format-Nicely2 -Value $Expected + $actualFormatted = Format-Nicely2 -Value $Actual return "Expected dictionary '$expectedFormatted', but got '$actualFormatted'." } @@ -358,15 +337,13 @@ function Compare-DictionaryEquivalent ($Actual, $Expected, $Property, $Options) v "`Comparing all ($($expectedKeys.Count)) keys from `$Expected to keys in `$Actual." $result = @() - foreach ($k in $expectedKeys) - { + foreach ($k in $expectedKeys) { if (-not (Test-IncludedPath -PathSelector Hashtable -Path $Property -Options $Options -InputObject $k)) { continue } $actualHasKey = $actualKeys -contains $k - if (-not $actualHasKey) - { + if (-not $actualHasKey) { v -Difference "`$Actual is missing key '$k'." $result += "Expected has key '$k' that the other object does not have." continue @@ -384,23 +361,21 @@ function Compare-DictionaryEquivalent ($Actual, $Expected, $Property, $Options) # fix for powershell v2 where foreach goes once over null if ($filteredKeysNotInExpected | Where-Object { $_ }) { - v -Difference "`$Actual has $($filteredKeysNotInExpected.Count) keys that were not found on `$Expected: $(Format-Nicely @($filteredKeysNotInExpected))." + v -Difference "`$Actual has $($filteredKeysNotInExpected.Count) keys that were not found on `$Expected: $(Format-Nicely2 @($filteredKeysNotInExpected))." } else { v "`$Actual has no keys that we did not find on `$Expected." } - foreach ($k in $filteredKeysNotInExpected | Where-Object { $_ }) - { + foreach ($k in $filteredKeysNotInExpected | Where-Object { $_ }) { $result += "Expected is missing key '$k' that the other object has." } } - if ($result) - { + if ($result) { v -Difference "Dictionaries `$Actual and `$Expected are not equivalent." - $expectedFormatted = Format-Nicely -Value $Expected - $actualFormatted = Format-Nicely -Value $Actual + $expectedFormatted = Format-Nicely2 -Value $Expected + $actualFormatted = Format-Nicely2 -Value $Actual return "Expected dictionary '$expectedFormatted', but got '$actualFormatted'.`n$($result -join "`n")" } v -Equivalence "Dictionaries `$Actual and `$Expected are equivalent." @@ -408,15 +383,14 @@ function Compare-DictionaryEquivalent ($Actual, $Expected, $Property, $Options) function Compare-ObjectEquivalent ($Actual, $Expected, $Property, $Options) { - if (-not (Is-Object -Value $Expected)) - { + if (-not (Is-Object -Value $Expected)) { throw [ArgumentException]"Expected must be an object." } if (-not (Is-Object -Value $Actual)) { - v -Difference "`$Actual is not an object it is a $(Format-Nicely (Get-Type $Actual)), so they are not equivalent." - $expectedFormatted = Format-Nicely -Value $Expected - $actualFormatted = Format-Nicely -Value $Actual + v -Difference "`$Actual is not an object it is a $(Format-Nicely2 (Get-Type $Actual)), so they are not equivalent." + $expectedFormatted = Format-Nicely2 -Value $Expected + $actualFormatted = Format-Nicely2 -Value $Actual return "Expected object '$expectedFormatted', but got '$actualFormatted'." } @@ -424,17 +398,14 @@ function Compare-ObjectEquivalent ($Actual, $Expected, $Property, $Options) { $expectedProperties = $Expected.PsObject.Properties v "Comparing ($(@($expectedProperties).Count)) properties of `$Expected to `$Actual." - foreach ($p in $expectedProperties) - { - if (-not (Test-IncludedPath -PathSelector Property -InputObject $p -Options $Options -Path $Property)) - { + foreach ($p in $expectedProperties) { + if (-not (Test-IncludedPath -PathSelector Property -InputObject $p -Options $Options -Path $Property)) { continue } $propertyName = $p.Name - $actualProperty = $actualProperties | Where-Object { $_.Name -eq $propertyName} - if (-not $actualProperty) - { + $actualProperty = $actualProperties | Where-Object { $_.Name -eq $propertyName } + if (-not $actualProperty) { v -Difference "Property '$propertyName' was not found on `$Actual." "Expected has property '$PropertyName' that the other object does not have." continue @@ -454,22 +425,21 @@ function Compare-ObjectEquivalent ($Actual, $Expected, $Property, $Options) { #check if there are any extra actual object props $expectedPropertyNames = $expectedProperties | Select-Object -ExpandProperty Name - $propertiesNotInExpected = @( $actualProperties | Where-Object { $expectedPropertyNames -notcontains $_.name }) + $propertiesNotInExpected = @( $actualProperties | Where-Object { $expectedPropertyNames -notcontains $_.name }) # fix for powershell v2 we need to make the array explicit $filteredPropertiesNotInExpected = $propertiesNotInExpected | Test-IncludedPath -PathSelector Property -Options $Options -Path $Property if ($filteredPropertiesNotInExpected) { - v -Difference "`$Actual has ($(@($filteredPropertiesNotInExpected).Count)) properties that `$Expected does not have: $(Format-Nicely @($filteredPropertiesNotInExpected))." + v -Difference "`$Actual has ($(@($filteredPropertiesNotInExpected).Count)) properties that `$Expected does not have: $(Format-Nicely2 @($filteredPropertiesNotInExpected))." } else { v -Equivalence "`$Actual has no extra properties that `$Expected does not have." } # fix for powershell v2 where foreach goes once over null - foreach ($p in $filteredPropertiesNotInExpected | Where-Object { $_ }) - { + foreach ($p in $filteredPropertiesNotInExpected | Where-Object { $_ }) { "Expected is missing property '$($p.Name)' that the other object has." } } @@ -477,26 +447,23 @@ function Compare-ObjectEquivalent ($Actual, $Expected, $Property, $Options) { function Compare-DataRowEquivalent ($Actual, $Expected, $Property, $Options) { - if (-not (Is-DataRow -Value $Expected)) - { + if (-not (Is-DataRow -Value $Expected)) { throw [ArgumentException]"Expected must be a DataRow." } if (-not (Is-DataRow -Value $Actual)) { - $expectedFormatted = Format-Nicely -Value $Expected - $actualFormatted = Format-Nicely -Value $Actual + $expectedFormatted = Format-Nicely2 -Value $Expected + $actualFormatted = Format-Nicely2 -Value $Actual return "Expected DataRow '$expectedFormatted', but got '$actualFormatted'." } - $actualProperties = $Actual.PsObject.Properties | Where-Object {'RowError','RowState','Table','ItemArray','HasErrors' -notcontains $_.Name } - $expectedProperties = $Expected.PsObject.Properties | Where-Object {'RowError','RowState','Table','ItemArray','HasErrors' -notcontains $_.Name } + $actualProperties = $Actual.PsObject.Properties | Where-Object { 'RowError', 'RowState', 'Table', 'ItemArray', 'HasErrors' -notcontains $_.Name } + $expectedProperties = $Expected.PsObject.Properties | Where-Object { 'RowError', 'RowState', 'Table', 'ItemArray', 'HasErrors' -notcontains $_.Name } - foreach ($p in $expectedProperties) - { + foreach ($p in $expectedProperties) { $propertyName = $p.Name - $actualProperty = $actualProperties | Where-Object { $_.Name -eq $propertyName} - if (-not $actualProperty) - { + $actualProperty = $actualProperties | Where-Object { $_.Name -eq $propertyName } + if (-not $actualProperty) { "Expected has property '$PropertyName' that the other object does not have." continue } @@ -507,11 +474,10 @@ function Compare-DataRowEquivalent ($Actual, $Expected, $Property, $Options) { #check if there are any extra actual object props $expectedPropertyNames = $expectedProperties | Select-Object -ExpandProperty Name - $propertiesNotInExpected = @($actualProperties | Where-Object {$expectedPropertyNames -notcontains $_.name }) + $propertiesNotInExpected = @($actualProperties | Where-Object { $expectedPropertyNames -notcontains $_.name }) # fix for powershell v2 where foreach goes once over null - foreach ($p in $propertiesNotInExpected | Where-Object { $_ }) - { + foreach ($p in $propertiesNotInExpected | Where-Object { $_ }) { "Expected is missing property '$($p.Name)' that the other object has." } } @@ -547,7 +513,7 @@ function v { " SKIP" } - $p += if (""-ne $p) { + $p += if ("" -ne $p) { " - " } @@ -562,10 +528,10 @@ function Compare-Equivalent { $Actual, $Expected, $Path, - $Options = (&{ - Write-Warning "Getting default equivalency options, this should never be seen. If you see this and you are not developing Assert, please file issue at https://github.com/nohwnd/Assert/issues" - Get-EquivalencyOption - }) + $Options = (& { + Write-Warning "Getting default equivalency options, this should never be seen. If you see this and you are not developing Assert, please file issue at https://github.com/nohwnd/Assert/issues" + Get-EquivalencyOption + }) ) if ($null -ne $Options.ExludedPaths -and $Options.ExcludedPaths -contains $Path) { @@ -575,12 +541,10 @@ function Compare-Equivalent { #start by null checks to avoid implementing null handling #logic in the functions that follow - if ($null -eq $Expected) - { + if ($null -eq $Expected) { v "`$Expected is `$null, so we are expecting `$null." - if ($Expected -ne $Actual) - { - v -Difference "`$Actual is not equivalent to $(Format-Nicely $Expected), because it has a value of type $(Format-Nicely $Actual.GetType())." + if ($Expected -ne $Actual) { + v -Difference "`$Actual is not equivalent to $(Format-Nicely2 $Expected), because it has a value of type $(Format-Nicely2 $Actual.GetType())." return Get-ValueNotEquivalentMessage -Expected $Expected -Actual $Actual -Property $Path -Options $Options } # we terminate here, either we passed the test and return nothing, or we did not @@ -589,9 +553,8 @@ function Compare-Equivalent { return } - if ($null -eq $Actual) - { - v -Difference "`$Actual is $(Format-Nicely), but `$Expected has value of type $(Format-Nicely Get-Type $Expected), so they are not equivalent." + if ($null -eq $Actual) { + v -Difference "`$Actual is $(Format-Nicely2), but `$Expected has value of type $(Format-Nicely2 Get-Type $Expected), so they are not equivalent." return Get-ValueNotEquivalentMessage -Expected $Expected -Actual $Actual -Property $Path } @@ -599,30 +562,26 @@ function Compare-Equivalent { #test value types, strings, and single item arrays with values in them as values #expand the single item array to get to the value in it - if (Is-Value -Value $Expected) - { + if (Is-Value -Value $Expected) { v "`$Expected is a value (value type, string, single value array, or a scriptblock), we will be comparing `$Actual to value types." Compare-ValueEquivalent -Actual $Actual -Expected $Expected -Property $Path -Options $Options return } #are the same instance - if (Test-Same -Expected $Expected -Actual $Actual) - { + if (Test-Same -Expected $Expected -Actual $Actual) { v -Equivalence "`$Expected and `$Actual are equivalent because they are the same object (by reference)." return } - if (Is-Hashtable -Value $Expected) - { + if (Is-Hashtable -Value $Expected) { v "`$Expected is a hashtable, we will be comparing `$Actual to hashtables." Compare-HashtableEquivalent -Expected $Expected -Actual $Actual -Property $Path -Options $Options return } # dictionaries? (they are IEnumerable so they must go before collections) - if (Is-Dictionary -Value $Expected) - { + if (Is-Dictionary -Value $Expected) { v "`$Expected is a dictionary, we will be comparing `$Actual to dictionaries." Compare-DictionaryEquivalent -Expected $Expected -Actual $Actual -Property $Path -Options $Options return @@ -666,12 +625,11 @@ function Assert-Equivalent { $areDifferent = Compare-Equivalent -Actual $Actual -Expected $Expected -Options $Options | Out-String - if ($areDifferent) - { + if ($areDifferent) { $optionsFormatted = Format-EquivalencyOptions -Options $Options # the paremeter is -Option not -Options $message = Get-AssertionMessage -Actual $actual -Expected $Expected -Option $optionsFormatted -Pretty -CustomMessage "Expected and actual are not equivalent!`nExpected:`n`n`nActual:`n`n`nSummary:`n$areDifferent`n" - throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) + throw [Pester.Factory]::CreateShouldErrorRecord($message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } v -Equivalence "`$Actual and `$Expected are equivalent." @@ -686,20 +644,20 @@ function Get-EquivalencyOption { ) [PSCustomObject]@{ - ExcludedPaths = [string[]] $ExcludePath + ExcludedPaths = [string[]] $ExcludePath ExcludePathsNotOnExpected = [bool] $ExcludePathsNotOnExpected - Comparator = [string] $Comparator + Comparator = [string] $Comparator } } function Test-IncludedPath { param( - [Parameter(Mandatory=$true, ValueFromPipeline=$true)] + [Parameter(Mandatory = $true, ValueFromPipeline = $true)] $InputObject, [String] $Path, $Options, - [Parameter(Mandatory=$true)] + [Parameter(Mandatory = $true)] [ValidateSet("Property", "Hashtable")] $PathSelector ) @@ -708,26 +666,23 @@ function Test-IncludedPath { $selector = switch ($PathSelector) { "Property" { { param($InputObject) $InputObject.Name } } "Hashtable" { { param($InputObject) $InputObject } } - Default {throw "Unsupported path selector."} + Default { throw "Unsupported path selector." } } } process { - if ($null -eq $Options.ExcludedPaths) - { + if ($null -eq $Options.ExcludedPaths) { return $InputObject } - $subPath = &$selector $InputObject + $subPath = &$selector $InputObject $fullPath = "$Path.$subPath".Trim('.') - if ($fullPath | Like-Any $Options.ExcludedPaths) - { + if ($fullPath | Like-Any $Options.ExcludedPaths) { v -Skip "Current path $fullPath is excluded from the comparison." } - else - { + else { $InputObject } } diff --git a/src/functions/assert/Exception/Assert-Throw.ps1 b/src/functions/assert/Exception/Assert-Throw.ps1 index effbbd31c..e3819e4cf 100644 --- a/src/functions/assert/Exception/Assert-Throw.ps1 +++ b/src/functions/assert/Exception/Assert-Throw.ps1 @@ -1,6 +1,6 @@ function Assert-Throw { param ( - [Parameter(ValueFromPipeline=$true, Mandatory = $true)] + [Parameter(ValueFromPipeline = $true, Mandatory = $true)] [ScriptBlock]$ScriptBlock, [Type]$ExceptionType, [String]$ExceptionMessage, @@ -15,8 +15,7 @@ function Assert-Throw { $err = $null try { $p = 'stop' - if ($AllowNonTerminatingError) - { + if ($AllowNonTerminatingError) { $p = 'continue' } # compatibility fix for powershell v2 @@ -25,8 +24,7 @@ function Assert-Throw { $null = (Invoke-WithContext -ScriptBlock $ScriptBlock -Variables @{ ErrorActionPreference = $p }) 2>&1 } - catch - { + catch { $errorThrown = $true $err = Get-Error $_ } @@ -36,13 +34,13 @@ function Assert-Throw { $filterOnExceptionType = $null -ne $ExceptionType if ($filterOnExceptionType) { - $exceptionFilterTypeFormatted = Format-Type $ExceptionType + $exceptionFilterTypeFormatted = Format-Type2 $ExceptionType $filters += "of type $exceptionFilterTypeFormatted" $exceptionTypeFilterMatches = $err.Exception -is $ExceptionType if (-not $exceptionTypeFilterMatches) { - $exceptionTypeFormatted = Get-ShortType $err.Exception + $exceptionTypeFormatted = Get-ShortType2 $err.Exception $buts += "the exception type was '$exceptionTypeFormatted'" } } @@ -63,8 +61,7 @@ function Assert-Throw { } } - if (-not $errorThrown) - { + if (-not $errorThrown) { $buts += "no exception was thrown" } @@ -74,7 +71,7 @@ function Assert-Throw { $defaultMessage = "Expected an exception,$filter to be thrown, but $but." $Message = Get-AssertionMessage -Expected $Expected -Actual $ScriptBlock -CustomMessage $CustomMessage ` - -DefaultMessage $defaultMessage + -DefaultMessage $defaultMessage throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } @@ -83,39 +80,34 @@ function Assert-Throw { function Get-Error ($ErrorRecord) { - if ($ErrorRecord.Exception -like '*"InvokeWithContext"*') - { + if ($ErrorRecord.Exception -like '*"InvokeWithContext"*') { $e = $ErrorRecord.Exception.InnerException.ErrorRecord } - else - { + else { $e = $ErrorRecord } New-Object -TypeName PSObject -Property @{ - ErrorRecord = $e - ExceptionMessage = $e.Exception.Message - Exception = $e.Exception - ExceptionType = $e.Exception.GetType() + ErrorRecord = $e + ExceptionMessage = $e.Exception.Message + Exception = $e.Exception + ExceptionType = $e.Exception.GetType() FullyQualifiedErrorId = $e.FullyQualifiedErrorId } } -function Join-And ($Items, $Threshold=2) { +function Join-And ($Items, $Threshold = 2) { - if ($null -eq $items -or $items.count -lt $Threshold) - { + if ($null -eq $items -or $items.count -lt $Threshold) { $items -join ', ' } - else - { + else { $c = $items.count - ($items[0..($c-2)] -join ', ') + ' and ' + $items[-1] + ($items[0..($c - 2)] -join ', ') + ' and ' + $items[-1] } } function Add-SpaceToNonEmptyString ([string]$Value) { - if ($Value) - { + if ($Value) { " $Value" } } diff --git a/tst/axiom/Axiom.psm1 b/tst/axiom/Axiom.psm1 index 1d6c03703..7afe23178 100644 --- a/tst/axiom/Axiom.psm1 +++ b/tst/axiom/Axiom.psm1 @@ -13,4 +13,6 @@ . $PSScriptRoot\Verify-Type.ps1 +. $PSScriptRoot\Verify-Like.ps1 + . $PSScriptRoot\Verify-AssertionFailed.ps1 diff --git a/tst/axiom/Verify-Like.ps1 b/tst/axiom/Verify-Like.ps1 new file mode 100644 index 000000000..ef014230c --- /dev/null +++ b/tst/axiom/Verify-Like.ps1 @@ -0,0 +1,19 @@ + +function Verify-Like { + param ( + [Parameter(ValueFromPipeline = $true)] + $Actual, + [Parameter(Mandatory = $true, Position = 0)] + $Expected + ) + + if ($Actual -notlike $Expected) { + $message = "Expected is not present in Actual!`n" + + "Expected: '$Expected'`n" + + "Actual : '$Actual'" + + throw [Exception]$message + } + + $Actual +} diff --git a/tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 b/tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 index 42f3ad956..4ed36beb6 100644 --- a/tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 +++ b/tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 @@ -165,7 +165,7 @@ InPesterModuleScope { @{ Actual = "1"; Expected = 1.01; Message = "Expected '1.01' to be equivalent to the actual value, but got '1'." }, @{ Actual = "abc"; Expected = "a b c"; Message = "Expected 'a b c' to be equivalent to the actual value, but got 'abc'." }, @{ Actual = @("abc", "bde"); Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got 'abc, bde'." }, - @{ Actual = { def }; Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got '{def}'." }, + @{ Actual = { def }; Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got '{ def }'." }, @{ Actual = (New-PSObject @{ Name = 'Jakub' }); Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got 'PSObject{Name=Jakub}'." }, @{ Actual = (1, 2, 3); Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got '1, 2, 3'." } ) { diff --git a/tst/functions/assert/Exception/Assert-Throw.Tests.ps1 b/tst/functions/assert/Exception/Assert-Throw.Tests.ps1 index 6523dfba3..f3d5f404d 100644 --- a/tst/functions/assert/Exception/Assert-Throw.Tests.ps1 +++ b/tst/functions/assert/Exception/Assert-Throw.Tests.ps1 @@ -124,7 +124,7 @@ # division by zero circumvents try catch in pwsh v2 # so we divide by $null to trigger the same exception It 'Exception is thrown by division by zero' { - { 1/$null } | Assert-Throw + { 1 / $null } | Assert-Throw } It 'Terminating error is thrown by cmdlet failing to bind paramaters' { @@ -150,12 +150,10 @@ Describe "General try catch behavior" { It 'Gets error record when exception is thrown by throw keyword' { - try - { - &{ throw "fail!" } + try { + & { throw "fail!" } } - catch - { + catch { $err = $_ } @@ -164,12 +162,10 @@ Describe "General try catch behavior" { } It 'Gets error record when exception is thrown from .net' { - try - { - &{ [io.directory]::delete("non-existing"); } + try { + & { [io.directory]::delete("non-existing"); } } - catch - { + catch { $err = $_ } @@ -178,12 +174,10 @@ Describe "General try catch behavior" { } It 'Gets error record when non-terminating error is translated to terminating error' { - try - { - &{ Get-Item "non-existing" -ErrorAction 'stop' } + try { + & { Get-Item "non-existing" -ErrorAction 'stop' } } - catch - { + catch { $err = $_ } @@ -193,13 +187,11 @@ Describe "General try catch behavior" { It 'Gets error record when non-terminating error is translated to terminating error' { - try - { + try { $ErrorActionPreference = 'stop' - &{ Get-Item "non-existing" } + & { Get-Item "non-existing" } } - catch - { + catch { $err = $_ } @@ -208,19 +200,17 @@ Describe "General try catch behavior" { } } -InModuleScope -ModuleName "Assert" { +InPesterModuleScope { Describe "Get-Error" { It 'Unwraps error from invoke with context' { $ErrorActionPreference = 'stop' - try - { + try { $sb = { Get-Item "/non-existing" } Invoke-WithContext $sb -Variables @{ ErrorActionPreference = "Stop" } } - catch - { + catch { $e = $_ } @@ -230,4 +220,4 @@ InModuleScope -ModuleName "Assert" { $err.FullyQualifiedErrorId | Verify-Equal 'PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand' } } -} \ No newline at end of file +} From cfaa9655ba113e286db1d247cafada7747ea9170 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Tue, 2 Apr 2024 22:00:57 +0200 Subject: [PATCH 04/55] Add code, did not fix help yet --- build.ps1 | 3 +- src/Module.ps1 | 1 - src/Pester.psd1 | 1 - .../assert/Common/Add-AssertionException.ps1 | 2 - .../assert/Common/AssertionException.cs | 27 -- src/functions/assert/Compatibility.ps1 | 6 +- .../assert/Equivalence/Assert-Equivalent.ps1 | 19 +- test.ps1 | 4 + tst/Format2.Tests.ps1 | 319 +++++++++--------- tst/Help.Tests.ps1 | 4 +- .../assert/Boolean/Assert-False.Tests.ps1 | 40 +-- .../assert/Boolean/Assert-True.Tests.ps1 | 38 ++- .../assert/Collection/Assert-All.Tests.ps1 | 18 +- .../assert/Collection/Assert-Any.Tests.ps1 | 16 +- .../Equivalence/Assert-Equivalent.Tests.ps1 | 10 +- .../assert/Exception/Assert-Throw.Tests.ps1 | 4 +- .../assert/General/Assert-LessThan.Tests.ps1 | 20 +- .../General/Assert-LessThanOrEqual.Tests.ps1 | 20 +- .../assert/String/Assert-Like.Tests.ps1 | 6 +- .../assert/String/Assert-NotLike.Tests.ps1 | 6 +- 20 files changed, 278 insertions(+), 286 deletions(-) delete mode 100644 src/functions/assert/Common/Add-AssertionException.ps1 delete mode 100644 src/functions/assert/Common/AssertionException.cs diff --git a/build.ps1 b/build.ps1 index 1a29c0dc4..04ba8d3e4 100644 --- a/build.ps1 +++ b/build.ps1 @@ -331,8 +331,7 @@ foreach ($f in $files) { else { # when not inlining just dot-source the file if ($f.FullName -notlike "*.ps1") { - Write-Warning "$($f.FullName) is not a ps1 file" - # throw "$($f.FullName) is not a ps1 file" + throw "$($f.FullName) is not a ps1 file" } $null = $sb.AppendLine(". '$($f.FullName)'") } diff --git a/src/Module.ps1 b/src/Module.ps1 index 7a68b0c45..c0cf869c0 100644 --- a/src/Module.ps1 +++ b/src/Module.ps1 @@ -46,7 +46,6 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session 'Assert-Any' 'Assert-Contain' 'Assert-NotContain' - 'AssertionException' 'Assert-Equivalent' 'Assert-Throw' 'Assert-Equal' diff --git a/src/Pester.psd1 b/src/Pester.psd1 index a24296df9..557f3fa97 100644 --- a/src/Pester.psd1 +++ b/src/Pester.psd1 @@ -73,7 +73,6 @@ 'Assert-Any' 'Assert-Contain' 'Assert-NotContain' - 'AssertionException' 'Assert-Equivalent' 'Assert-Throw' 'Assert-Equal' diff --git a/src/functions/assert/Common/Add-AssertionException.ps1 b/src/functions/assert/Common/Add-AssertionException.ps1 deleted file mode 100644 index 2ff593098..000000000 --- a/src/functions/assert/Common/Add-AssertionException.ps1 +++ /dev/null @@ -1,2 +0,0 @@ -$typeDefinition = Get-Content $PSScriptRoot/AssertionException.cs | Out-String -Add-Type -TypeDefinition $typeDefinition -WarningAction SilentlyContinue \ No newline at end of file diff --git a/src/functions/assert/Common/AssertionException.cs b/src/functions/assert/Common/AssertionException.cs deleted file mode 100644 index 3d82a1bdf..000000000 --- a/src/functions/assert/Common/AssertionException.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using System.Runtime.Serialization; - -namespace Assertions -{ - [Serializable] - public class AssertionException : Exception - { - public AssertionException() - { - } - - public AssertionException(string message) : base(message) - { - } - - public AssertionException(string message, Exception inner) : base(message, inner) - { - } - - // protected AssertionException( - // SerializationInfo info, - // StreamingContext context) : base(info, context) - // { - // } - } -} \ No newline at end of file diff --git a/src/functions/assert/Compatibility.ps1 b/src/functions/assert/Compatibility.ps1 index 03caf8fa3..4e79ca958 100644 --- a/src/functions/assert/Compatibility.ps1 +++ b/src/functions/assert/Compatibility.ps1 @@ -1,6 +1,4 @@ -function New-PSObject ([hashtable]$Property) { - New-Object -Type PSObject -Property $Property -} + function Invoke-WithContext { param( @@ -73,4 +71,4 @@ function Get-Type ($InputObject) { return [Object] } -} \ No newline at end of file +} diff --git a/src/functions/assert/Equivalence/Assert-Equivalent.ps1 b/src/functions/assert/Equivalence/Assert-Equivalent.ps1 index be33c4f10..e03d4db24 100644 --- a/src/functions/assert/Equivalence/Assert-Equivalent.ps1 +++ b/src/functions/assert/Equivalence/Assert-Equivalent.ps1 @@ -223,11 +223,10 @@ function Compare-ValueEquivalent ($Actual, $Expected, $Property, $Options) { return } - #fix that scriptblocks are compared by reference + # fix that scriptblocks are compared by reference if (Is-ScriptBlock -Value $Expected) { - # todo: compare by equivalency like strings? v "`$Expected is a ScriptBlock, scriptblocks are considered equivalent when their content is equal. Converting `$Expected to string." - #forcing scriptblock to serialize to string and then comparing that + # forcing scriptblock to serialize to string and then comparing that if ("$Expected" -ne $Actual) { # todo: difference on index? v -Difference "`$Actual is not equivalent to `$Expected because their contents differ." @@ -529,7 +528,7 @@ function Compare-Equivalent { $Expected, $Path, $Options = (& { - Write-Warning "Getting default equivalency options, this should never be seen. If you see this and you are not developing Assert, please file issue at https://github.com/nohwnd/Assert/issues" + Write-Warning "Getting default equivalency options, this should never be seen. If you see this and you are not developing Pester, please file issue at https://github.com/pester/Pester/issues" Get-EquivalencyOption }) ) @@ -539,8 +538,8 @@ function Compare-Equivalent { return } - #start by null checks to avoid implementing null handling - #logic in the functions that follow + # start by null checks to avoid implementing null handling + # logic in the functions that follow if ($null -eq $Expected) { v "`$Expected is `$null, so we are expecting `$null." if ($Expected -ne $Actual) { @@ -554,21 +553,21 @@ function Compare-Equivalent { } if ($null -eq $Actual) { - v -Difference "`$Actual is $(Format-Nicely2), but `$Expected has value of type $(Format-Nicely2 Get-Type $Expected), so they are not equivalent." + v -Difference "`$Actual is $(Format-Nicely2), but `$Expected has value of type $(Format-Nicely2 (Get-Type $Expected)), so they are not equivalent." return Get-ValueNotEquivalentMessage -Expected $Expected -Actual $Actual -Property $Path } v "`$Expected has type $(Get-Type $Expected), `$Actual has type $(Get-Type $Actual), they are both non-null." - #test value types, strings, and single item arrays with values in them as values - #expand the single item array to get to the value in it + # test value types, strings, and single item arrays with values in them as values + # expand the single item array to get to the value in it if (Is-Value -Value $Expected) { v "`$Expected is a value (value type, string, single value array, or a scriptblock), we will be comparing `$Actual to value types." Compare-ValueEquivalent -Actual $Actual -Expected $Expected -Property $Path -Options $Options return } - #are the same instance + # are the same instance if (Test-Same -Expected $Expected -Actual $Actual) { v -Equivalence "`$Expected and `$Actual are equivalent because they are the same object (by reference)." return diff --git a/test.ps1 b/test.ps1 index dc47f6f65..51ce50255 100644 --- a/test.ps1 +++ b/test.ps1 @@ -127,6 +127,10 @@ New-Module -Name TestHelpers -ScriptBlock { function Clear-WhiteSpace ($Text) { "$($Text -replace "(`t|`n|`r)"," " -replace "\s+"," ")".Trim() } + + function New-PSObject ([hashtable]$Property) { + New-Object -Type PSObject -Property $Property + } } | Out-Null diff --git a/tst/Format2.Tests.ps1 b/tst/Format2.Tests.ps1 index 5a9a0a1b1..11a926a67 100644 --- a/tst/Format2.Tests.ps1 +++ b/tst/Format2.Tests.ps1 @@ -1,188 +1,193 @@ -BeforeDiscovery { - Add-Type -TypeDefinition ' - namespace Assertions.TestType { - public class Person { - // powershell v2 mandates fully implemented properties - string _name; - int _age; - public string Name { get { return _name; } set { _name = value; } } - public int Age { get { return _age; } set { _age = value; } } - } - }' -} - - -Describe "Format-Collection2" { - It "Formats collection of values '' to '' using the default separator" -TestCases @( - @{ Value = (1, 2, 3); Expected = "1, 2, 3" } - ) { - param ($Value, $Expected) - Format-Collection2 -Value $Value | Verify-Equal $Expected - } +Set-StrictMode -Version Latest + +InPesterModuleScope { + + BeforeDiscovery { + Add-Type -TypeDefinition ' + namespace Assertions.TestType { + public class Person { + // powershell v2 mandates fully implemented properties + string _name; + int _age; + public string Name { get { return _name; } set { _name = value; } } + public int Age { get { return _age; } set { _age = value; } } + } + }' + } + + + Describe "Format-Collection2" { + It "Formats collection of values '' to '' using the default separator" -TestCases @( + @{ Value = (1, 2, 3); Expected = "1, 2, 3" } + ) { + param ($Value, $Expected) + Format-Collection2 -Value $Value | Verify-Equal $Expected + } - It "Formats collection of values '' to '' using the default separator" -TestCases @( - @{ Value = (1, 2, 3); Expected = "1, 2, 3" } - ) { - param ($Value, $Expected) - Format-Collection2 -Value $Value | Verify-Equal $Expected + It "Formats collection of values '' to '' using the default separator" -TestCases @( + @{ Value = (1, 2, 3); Expected = "1, 2, 3" } + ) { + param ($Value, $Expected) + Format-Collection2 -Value $Value | Verify-Equal $Expected + } } -} -Describe "Format-Number" { - It "Formats number to use . separator (tests anything only on non-english systems --todo)" -TestCases @( - @{ Value = 1.1; }, - @{ Value = [double] 1.1; }, - @{ Value = [float] 1.1; }, - @{ Value = [single] 1.1; }, - @{ Value = [decimal] 1.1; } - ) { - param ($Value) - Format-Number -Value $Value | Verify-Equal "1.1" + Describe "Format-Number" { + It "Formats number to use . separator (tests anything only on non-english systems --todo)" -TestCases @( + @{ Value = 1.1; }, + @{ Value = [double] 1.1; }, + @{ Value = [float] 1.1; }, + @{ Value = [single] 1.1; }, + @{ Value = [decimal] 1.1; } + ) { + param ($Value) + Format-Number -Value $Value | Verify-Equal "1.1" + } } -} -Describe "Format-Object2" { - It "Formats object '' to ''" -TestCases @( - @{ Value = (New-PSObject @{Name = 'Jakub'; Age = 28 }); Expected = "PSObject{Age=28; Name=Jakub}" }, - @{ Value = (New-Object -Type Assertions.TestType.Person -Property @{Name = 'Jakub'; Age = 28 }); Expected = "Assertions.TestType.Person{Age=28; Name=Jakub}" } - ) { - param ($Value, $Expected) - Format-Object2 -Value $Value | Verify-Equal $Expected - } + Describe "Format-Object2" { + It "Formats object '' to ''" -TestCases @( + @{ Value = (New-PSObject @{Name = 'Jakub'; Age = 28 }); Expected = "PSObject{Age=28; Name=Jakub}" }, + @{ Value = (New-Object -Type Assertions.TestType.Person -Property @{Name = 'Jakub'; Age = 28 }); Expected = "Assertions.TestType.Person{Age=28; Name=Jakub}" } + ) { + param ($Value, $Expected) + Format-Object2 -Value $Value | Verify-Equal $Expected + } - It "Formats object '' with selected properties '' to ''" -TestCases @( - @{ Value = (New-PSObject @{Name = 'Jakub'; Age = 28 }); SelectedProperties = "Age"; Expected = "PSObject{Age=28}" }, - @{ - Value = (New-Object -Type Assertions.TestType.Person -Property @{Name = 'Jakub'; Age = 28 }) - SelectedProperties = 'Name' - Expected = "Assertions.TestType.Person{Name=Jakub}" + It "Formats object '' with selected properties '' to ''" -TestCases @( + @{ Value = (New-PSObject @{Name = 'Jakub'; Age = 28 }); SelectedProperties = "Age"; Expected = "PSObject{Age=28}" }, + @{ + Value = (New-Object -Type Assertions.TestType.Person -Property @{Name = 'Jakub'; Age = 28 }) + SelectedProperties = 'Name' + Expected = "Assertions.TestType.Person{Name=Jakub}" + } + ) { + param ($Value, $SelectedProperties, $Expected) + Format-Object2 -Value $Value -Property $SelectedProperties | Verify-Equal $Expected } - ) { - param ($Value, $SelectedProperties, $Expected) - Format-Object2 -Value $Value -Property $SelectedProperties | Verify-Equal $Expected - } - It "Formats current process with selected properties Name and Id correctly" { - # this used to be a normal unit test but Idle process does not exist - # cross platform so we use the current process, which can also have - # different names among powershell versions - $process = Get-Process -PID $PID - $name = $process.Name - $id = $process.Id - $SelectedProperties = "Name", "Id" - $expected = "Diagnostics.Process{Id=$id; Name=$name}" - - Format-Object2 -Value $process -Property $selectedProperties | Verify-Equal $Expected + It "Formats current process with selected properties Name and Id correctly" { + # this used to be a normal unit test but Idle process does not exist + # cross platform so we use the current process, which can also have + # different names among powershell versions + $process = Get-Process -PID $PID + $name = $process.Name + $id = $process.Id + $SelectedProperties = "Name", "Id" + $expected = "Diagnostics.Process{Id=$id; Name=$name}" + + Format-Object2 -Value $process -Property $selectedProperties | Verify-Equal $Expected + } } -} -Describe "Format-Boolean2" { - It "Formats boolean '' to ''" -TestCases @( - @{ Value = $true; Expected = '$true' }, - @{ Value = $false; Expected = '$false' } - ) { - param($Value, $Expected) - Format-Boolean2 -Value $Value | Verify-Equal $Expected + Describe "Format-Boolean2" { + It "Formats boolean '' to ''" -TestCases @( + @{ Value = $true; Expected = '$true' }, + @{ Value = $false; Expected = '$false' } + ) { + param($Value, $Expected) + Format-Boolean2 -Value $Value | Verify-Equal $Expected + } } -} -Describe "Format-Null2" { - It "Formats null to '`$null'" { - Format-Null2 | Verify-Equal '$null' + Describe "Format-Null2" { + It "Formats null to '`$null'" { + Format-Null2 | Verify-Equal '$null' + } } -} -Describe "Format-ScriptBlock2" { - It "Formats scriptblock as string with curly braces" { - Format-ScriptBlock2 -Value { abc } | Verify-Equal '{abc}' + Describe "Format-ScriptBlock2" { + It "Formats scriptblock as string with curly braces" { + Format-ScriptBlock2 -Value { abc } | Verify-Equal '{ abc }' + } } -} -Describe "Format-Hashtable2" { - It "Formats empty hashtable as @{}" { - Format-Hashtable2 @{} | Verify-Equal '@{}' - } + Describe "Format-Hashtable2" { + It "Formats empty hashtable as @{}" { + Format-Hashtable2 @{} | Verify-Equal '@{}' + } - It "Formats hashtable as ''" -TestCases @( - @{ Value = @{Age = 28; Name = 'Jakub' }; Expected = '@{Age=28; Name=Jakub}' } - @{ Value = @{Z = 1; H = 1; A = 1 }; Expected = '@{A=1; H=1; Z=1}' } - @{ Value = @{Hash = @{Hash = 'Value' } }; Expected = '@{Hash=@{Hash=Value}}' } - ) { - param ($Value, $Expected) - Format-Hashtable2 $Value | Verify-Equal $Expected + It "Formats hashtable as ''" -TestCases @( + @{ Value = @{Age = 28; Name = 'Jakub' }; Expected = '@{Age=28; Name=Jakub}' } + @{ Value = @{Z = 1; H = 1; A = 1 }; Expected = '@{A=1; H=1; Z=1}' } + @{ Value = @{Hash = @{Hash = 'Value' } }; Expected = '@{Hash=@{Hash=Value}}' } + ) { + param ($Value, $Expected) + Format-Hashtable2 $Value | Verify-Equal $Expected + } } -} -Describe "Format-Dictionary2" { - It "Formats empty dictionary as @{}" { - Format-Dictionary2 (New-Dictionary @{}) | Verify-Equal 'Dictionary{}' - } + Describe "Format-Dictionary2" { + It "Formats empty dictionary as @{}" { + Format-Dictionary2 (New-Dictionary @{}) | Verify-Equal 'Dictionary{}' + } - It "Formats dictionary as ''" -TestCases @( - @{ Value = New-Dictionary @{Age = 28; Name = 'Jakub' }; Expected = 'Dictionary{Age=28; Name=Jakub}' } - @{ Value = New-Dictionary @{Z = 1; H = 1; A = 1 }; Expected = 'Dictionary{A=1; H=1; Z=1}' } - @{ Value = New-Dictionary @{Dict = ( New-Dictionary @{Dict = 'Value' }) }; Expected = 'Dictionary{Dict=Dictionary{Dict=Value}}' } - ) { - param ($Value, $Expected) - Format-Dictionary2 $Value | Verify-Equal $Expected + It "Formats dictionary as ''" -TestCases @( + @{ Value = New-Dictionary @{Age = 28; Name = 'Jakub' }; Expected = 'Dictionary{Age=28; Name=Jakub}' } + @{ Value = New-Dictionary @{Z = 1; H = 1; A = 1 }; Expected = 'Dictionary{A=1; H=1; Z=1}' } + @{ Value = New-Dictionary @{Dict = ( New-Dictionary @{Dict = 'Value' }) }; Expected = 'Dictionary{Dict=Dictionary{Dict=Value}}' } + ) { + param ($Value, $Expected) + Format-Dictionary2 $Value | Verify-Equal $Expected + } } -} -Describe "Format-Nicely2" { - It "Formats value '' correctly to ''" -TestCases @( - @{ Value = $null; Expected = '$null' } - @{ Value = $true; Expected = '$true' } - @{ Value = $false; Expected = '$false' } - @{ Value = 'a' ; Expected = 'a' }, - @{ Value = 1; Expected = '1' }, - @{ Value = (1, 2, 3); Expected = '1, 2, 3' }, - @{ Value = 1.1; Expected = '1.1' }, - @{ Value = [int]; Expected = 'int' } - @{ Value = New-PSObject @{ Name = "Jakub" }; Expected = 'PSObject{Name=Jakub}' }, - @{ Value = (New-Object -Type Assertions.TestType.Person -Property @{Name = 'Jakub'; Age = 28 }); Expected = "Assertions.TestType.Person{Age=28; Name=Jakub}" } - @{ Value = @{Name = 'Jakub'; Age = 28 }; Expected = '@{Age=28; Name=Jakub}' } - @{ Value = New-Dictionary @{Age = 28; Name = 'Jakub' }; Expected = 'Dictionary{Age=28; Name=Jakub}' } - ) { - param($Value, $Expected) - Format-Nicely2 -Value $Value | Verify-Equal $Expected + Describe "Format-Nicely2" { + It "Formats value '' correctly to ''" -TestCases @( + @{ Value = $null; Expected = '$null' } + @{ Value = $true; Expected = '$true' } + @{ Value = $false; Expected = '$false' } + @{ Value = 'a' ; Expected = 'a' }, + @{ Value = 1; Expected = '1' }, + @{ Value = (1, 2, 3); Expected = '1, 2, 3' }, + @{ Value = 1.1; Expected = '1.1' }, + @{ Value = [int]; Expected = 'int' } + @{ Value = New-PSObject @{ Name = "Jakub" }; Expected = 'PSObject{Name=Jakub}' }, + @{ Value = (New-Object -Type Assertions.TestType.Person -Property @{Name = 'Jakub'; Age = 28 }); Expected = "Assertions.TestType.Person{Age=28; Name=Jakub}" } + @{ Value = @{Name = 'Jakub'; Age = 28 }; Expected = '@{Age=28; Name=Jakub}' } + @{ Value = New-Dictionary @{Age = 28; Name = 'Jakub' }; Expected = 'Dictionary{Age=28; Name=Jakub}' } + ) { + param($Value, $Expected) + Format-Nicely2 -Value $Value | Verify-Equal $Expected + } } -} -Describe "Get-DisplayProperty2" { - It "Returns '' for ''" -TestCases @( - @{ Type = "Diagnostics.Process"; Expected = ("Id", "Name") } - ) { - param ($Type, $Expected) - $Actual = Get-DisplayProperty2 -Type $Type - "$Actual" | Verify-Equal "$Expected" + Describe "Get-DisplayProperty2" { + It "Returns '' for ''" -TestCases @( + @{ Type = "Diagnostics.Process"; Expected = ("Id", "Name") } + ) { + param ($Type, $Expected) + $Actual = Get-DisplayProperty2 -Type $Type + "$Actual" | Verify-Equal "$Expected" + } } -} -Describe "Format-Type2" { - It "Given '' it returns the correct shortened type name ''" -TestCases @( - @{ Value = [int]; Expected = 'int' }, - @{ Value = [double]; Expected = 'double' }, - @{ Value = [string]; Expected = 'string' }, - @{ Value = $null; Expected = '' }, - @{ Value = [Management.Automation.PSObject]; Expected = 'PSObject' }, - @{ Value = [Object[]]; Expected = 'collection' } - ) { - param($Value, $Expected) - Format-Type2 -Value $Value | Verify-Equal $Expected + Describe "Format-Type2" { + It "Given '' it returns the correct shortened type name ''" -TestCases @( + @{ Value = [int]; Expected = 'int' }, + @{ Value = [double]; Expected = 'double' }, + @{ Value = [string]; Expected = 'string' }, + @{ Value = $null; Expected = '' }, + @{ Value = [Management.Automation.PSObject]; Expected = 'PSObject' }, + @{ Value = [Object[]]; Expected = 'collection' } + ) { + param($Value, $Expected) + Format-Type2 -Value $Value | Verify-Equal $Expected + } } -} -Describe "Get-ShortType2" { - It "Given '' it returns the correct shortened type name ''" -TestCases @( - @{ Value = 1; Expected = 'int' }, - @{ Value = 1.1; Expected = 'double' }, - @{ Value = 'a' ; Expected = 'string' }, - @{ Value = $null ; Expected = '' }, - @{ Value = New-PSObject @{Name = 'Jakub' } ; Expected = 'PSObject' }, - @{ Value = [Object[]]1, 2, 3 ; Expected = 'collection' } - ) { - param($Value, $Expected) - Get-ShortType2 -Value $Value | Verify-Equal $Expected + Describe "Get-ShortType2" { + It "Given '' it returns the correct shortened type name ''" -TestCases @( + @{ Value = 1; Expected = 'int' }, + @{ Value = 1.1; Expected = 'double' }, + @{ Value = 'a' ; Expected = 'string' }, + @{ Value = $null ; Expected = '' }, + @{ Value = New-PSObject @{Name = 'Jakub' } ; Expected = 'PSObject' }, + @{ Value = [Object[]]1, 2, 3 ; Expected = 'collection' } + ) { + param($Value, $Expected) + Get-ShortType2 -Value $Value | Verify-Equal $Expected + } } } diff --git a/tst/Help.Tests.ps1 b/tst/Help.Tests.ps1 index 1864d37a5..6ed6347ad 100644 --- a/tst/Help.Tests.ps1 +++ b/tst/Help.Tests.ps1 @@ -2,7 +2,7 @@ BeforeDiscovery { $moduleName = 'Pester' - $exportedFunctions = Get-Command -CommandType Cmdlet, Function -Module $moduleName + $exportedFunctions = Get-Command -CommandType Cmdlet, Function -Module $moduleName | Where-Object { $_.Name -notlike "Assert-*" } } Describe "Testing module help" -Tag 'Help' -ForEach @{ exportedFunctions = $exportedFunctions; moduleName = $moduleName } { @@ -68,7 +68,7 @@ Describe "Testing module help" -Tag 'Help' -ForEach @{ exportedFunctions = $expo (Get-AssertionDynamicParams).Values | Where-Object name -in $operators } - $parametersMissingHelp = @($operatorParams |Where-Object { + $parametersMissingHelp = @($operatorParams | Where-Object { $attr = $_.Attributes | Where-Object { $_ -is [System.Management.Automation.ParameterAttribute] } $null -eq $attr -or $attr.HelpMessage -eq $null } | ForEach-Object Name) diff --git a/tst/functions/assert/Boolean/Assert-False.Tests.ps1 b/tst/functions/assert/Boolean/Assert-False.Tests.ps1 index 53ac8bd47..8b5c35f03 100644 --- a/tst/functions/assert/Boolean/Assert-False.Tests.ps1 +++ b/tst/functions/assert/Boolean/Assert-False.Tests.ps1 @@ -1,31 +1,33 @@ -Describe "Assert-False" { - It "Passes when given `$false" { - $false | Assert-False - } +Set-StrictMode -Version Latest - It "Passes when given falsy value ''" -TestCases @( - @{ Actual = 0 } - @{ Actual = "" } - @{ Actual = $null } - @{ Actual = @() } - ) { - param($Actual) - Assert-False -Actual $Actual - } +Describe "Assert-False" { + It "Passes when given `$false" { + $false | Assert-False + } + + It "Passes when given falsy value ''" -TestCases @( + @{ Actual = 0 } + @{ Actual = "" } + @{ Actual = $null } + @{ Actual = @() } + ) { + param($Actual) + Assert-False -Actual $Actual + } It "Fails for array input even if the last item is `$false" { - { $true,$true,$false | Assert-False } | Verify-AssertionFailed + { $true, $true, $false | Assert-False } | Verify-AssertionFailed } It "Fails with custom message" { - $error = { 9 | Assert-False -CustomMessage " is not false" } | Verify-AssertionFailed - $error.Exception.Message | Verify-Equal "9 is not false" + $error = { 9 | Assert-False -CustomMessage " is not false" } | Verify-AssertionFailed + $error.Exception.Message | Verify-Equal "9 is not false" } Context "Validate messages" { It "Given value '' that is not `$false it returns expected message ''" -TestCases @( - @{ Actual = $true ; Message = "Expected bool '`$true' to be bool '`$false' or falsy value 0, """", `$null, @()."}, - @{ Actual = 10 ; Message = "Expected int '10' to be bool '`$false' or falsy value 0, """", `$null, @()."} + @{ Actual = $true ; Message = "Expected bool '`$true' to be bool '`$false' or falsy value 0, """", `$null, @()." }, + @{ Actual = 10 ; Message = "Expected int '10' to be bool '`$false' or falsy value 0, """", `$null, @()." } ) { param($Actual, $Message) $error = { Assert-False -Actual $Actual } | Verify-AssertionFailed @@ -41,4 +43,4 @@ It "Can be called with positional parameters" { { Assert-False $true } | Verify-AssertionFailed } -} \ No newline at end of file +} diff --git a/tst/functions/assert/Boolean/Assert-True.Tests.ps1 b/tst/functions/assert/Boolean/Assert-True.Tests.ps1 index 3f0fb4286..7e3070d10 100644 --- a/tst/functions/assert/Boolean/Assert-True.Tests.ps1 +++ b/tst/functions/assert/Boolean/Assert-True.Tests.ps1 @@ -1,27 +1,29 @@ -Describe "Assert-True" { - It "Passes when given `$true" { - $true | Assert-True - } +Set-StrictMode -Version Latest - It "Passes when given truthy" -TestCases @( - @{ Actual = 1 } - @{ Actual = "text" } - @{ Actual = New-Object -TypeName PSObject } - @{ Actual = 1,2 } - ) { - param($Actual) - Assert-True -Actual $Actual - } +Describe "Assert-True" { + It "Passes when given `$true" { + $true | Assert-True + } + + It "Passes when given truthy" -TestCases @( + @{ Actual = 1 } + @{ Actual = "text" } + @{ Actual = New-Object -TypeName PSObject } + @{ Actual = 1, 2 } + ) { + param($Actual) + Assert-True -Actual $Actual + } It "Fails with custom message" { - $error = { $null | Assert-True -CustomMessage " is not true" } | Verify-AssertionFailed - $error.Exception.Message | Verify-Equal "`$null is not true" + $error = { $null | Assert-True -CustomMessage " is not true" } | Verify-AssertionFailed + $error.Exception.Message | Verify-Equal "`$null is not true" } Context "Validate messages" { It "Given value that is not `$true it returns expected message ''" -TestCases @( - @{ Actual = $false ; Message = "Expected bool '`$false' to be bool '`$true' or truthy value."}, - @{ Actual = 0 ; Message = "Expected int '0' to be bool '`$true' or truthy value."} + @{ Actual = $false ; Message = "Expected bool '`$false' to be bool '`$true' or truthy value." }, + @{ Actual = 0 ; Message = "Expected int '0' to be bool '`$true' or truthy value." } ) { param($Actual, $Message) $error = { Assert-True -Actual $Actual } | Verify-AssertionFailed @@ -37,4 +39,4 @@ It "Can be called with positional parameters" { { Assert-True $false } | Verify-AssertionFailed } -} \ No newline at end of file +} diff --git a/tst/functions/assert/Collection/Assert-All.Tests.ps1 b/tst/functions/assert/Collection/Assert-All.Tests.ps1 index 14aff00a3..4c2dd7364 100644 --- a/tst/functions/assert/Collection/Assert-All.Tests.ps1 +++ b/tst/functions/assert/Collection/Assert-All.Tests.ps1 @@ -1,6 +1,8 @@ -Describe "Assert-All" { +Set-StrictMode -Version Latest + +Describe "Assert-All" { It "Passes when all items in the given collection pass the predicate" -TestCases @( - @{ Actual = 1,1,1,1 } + @{ Actual = 1, 1, 1, 1 } @{ Actual = @(1) } @{ Actual = 1 } ) { @@ -9,7 +11,7 @@ } It "Fails when any item in the given collection does not pass the predicate" -TestCases @( - @{ Actual = 1,1,2,1 } + @{ Actual = 1, 1, 2, 1 } @{ Actual = @(2) } @{ Actual = 2 } ) { @@ -18,7 +20,7 @@ } It "Validate messages" -TestCases @( - @{ Actual = @(3,4,5); Message = "Expected all items in collection '3, 4, 5' to pass filter '{ `$_ -eq 1 }', but 3 of them '3, 4, 5' did not pass the filter." } + @{ Actual = @(3, 4, 5); Message = "Expected all items in collection '3, 4, 5' to pass filter '{ `$_ -eq 1 }', but 3 of them '3, 4, 5' did not pass the filter." } ) { param($Actual, $Message) $err = { $Actual | Assert-All -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed @@ -26,7 +28,7 @@ } It "Returns the value on output" { - $expected = "a","b" + $expected = "a", "b" $v = $expected | Assert-All { $true } $v[0] | Verify-Equal $expected[0] $v[1] | Verify-Equal $expected[1] @@ -34,10 +36,10 @@ It "Can filter using variables from the sorrounding context" { $f = 1 - 2,4 | Assert-All { $_ / $f } + 2, 4 | Assert-All { $_ / $f } } It "Accepts FilterScript and Actual by position" { - Assert-All { $true } 1,2 + Assert-All { $true } 1, 2 } -} \ No newline at end of file +} diff --git a/tst/functions/assert/Collection/Assert-Any.Tests.ps1 b/tst/functions/assert/Collection/Assert-Any.Tests.ps1 index 4c7c973e9..7624bbb7e 100644 --- a/tst/functions/assert/Collection/Assert-Any.Tests.ps1 +++ b/tst/functions/assert/Collection/Assert-Any.Tests.ps1 @@ -1,6 +1,8 @@ -Describe "Assert-Any" { +Set-StrictMode -Version Latest + +Describe "Assert-Any" { It "Passes when at least one item in the given collection passes the predicate" -TestCases @( - @{ Actual = @(1,2,3) } + @{ Actual = @(1, 2, 3) } @{ Actual = @(1) } @{ Actual = 1 } ) { @@ -9,7 +11,7 @@ } It "Fails when none of the items passes the predicate" -TestCases @( - @{ Actual = @(1,2,3) } + @{ Actual = @(1, 2, 3) } @{ Actual = @(1) } @{ Actual = 1 } ) { @@ -18,7 +20,7 @@ } It "Validate messages" -TestCases @( - @{ Actual = @(3,4,5); Message = "Expected at least one item in collection '3, 4, 5' to pass filter '{ `$_ -eq 1 }', but none of the items passed the filter." } + @{ Actual = @(3, 4, 5); Message = "Expected at least one item in collection '3, 4, 5' to pass filter '{ `$_ -eq 1 }', but none of the items passed the filter." } @{ Actual = @(3); Message = "Expected at least one item in collection '3' to pass filter '{ `$_ -eq 1 }', but none of the items passed the filter." } @{ Actual = 3; Message = "Expected at least one item in collection '3' to pass filter '{ `$_ -eq 1 }', but none of the items passed the filter." } ) { @@ -28,13 +30,13 @@ } It "Returns the value on output" { - $expected = "a","b" + $expected = "a", "b" $v = $expected | Assert-Any { $true } $v[0] | Verify-Equal $expected[0] $v[1] | Verify-Equal $expected[1] } It "Accepts FilterScript and Actual by position" { - Assert-Any { $true } 1,2 + Assert-Any { $true } 1, 2 } -} \ No newline at end of file +} diff --git a/tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 b/tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 index 4ed36beb6..94bf85f8f 100644 --- a/tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 +++ b/tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 @@ -297,8 +297,8 @@ InPesterModuleScope { @{ Actual = "abc"; Expected = "abc" }, @{ Actual = @("abc"); Expected = "abc" }, @{ Actual = "abc"; Expected = @("abc") }, - @{ Actual = { abc }; Expected = "abc" }, - @{ Actual = "abc"; Expected = { abc } }, + @{ Actual = { abc }; Expected = " abc " }, + @{ Actual = " abc "; Expected = { abc } }, @{ Actual = { abc }; Expected = { abc } } ) { param ($Actual, $Expected) @@ -314,9 +314,9 @@ InPesterModuleScope { @{ Actual = "1"; Expected = 1.01; Message = "Expected '1.01' to be equivalent to the actual value, but got '1'." }, @{ Actual = "abc"; Expected = "a b c"; Message = "Expected 'a b c' to be equivalent to the actual value, but got 'abc'." }, @{ Actual = @("abc", "bde"); Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got 'abc, bde'." }, - @{ Actual = { def }; Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got '{def}'." }, - @{ Actual = "def"; Expected = { abc }; Message = "Expected '{abc}' to be equivalent to the actual value, but got 'def'." }, - @{ Actual = { abc }; Expected = { def }; Message = "Expected '{def}' to be equivalent to the actual value, but got '{abc}'." }, + @{ Actual = { def }; Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got '{ def }'." }, + @{ Actual = "def"; Expected = { abc }; Message = "Expected '{ abc }' to be equivalent to the actual value, but got 'def'." }, + @{ Actual = { abc }; Expected = { def }; Message = "Expected '{ def }' to be equivalent to the actual value, but got '{ abc }'." }, @{ Actual = (1, 2, 3); Expected = (1, 2, 3, 4); Message = "Expected collection '1, 2, 3, 4' with length '4' to be the same size as the actual collection, but got '1, 2, 3' with length '3'." }, @{ Actual = 3; Expected = (1, 2, 3, 4); Message = "Expected collection '1, 2, 3, 4' with length '4', but got '3'." }, @{ Actual = (New-PSObject @{ Name = 'Jakub' }); Expected = (1, 2, 3, 4); Message = "Expected collection '1, 2, 3, 4' with length '4', but got 'PSObject{Name=Jakub}'." }, diff --git a/tst/functions/assert/Exception/Assert-Throw.Tests.ps1 b/tst/functions/assert/Exception/Assert-Throw.Tests.ps1 index f3d5f404d..531fabb6c 100644 --- a/tst/functions/assert/Exception/Assert-Throw.Tests.ps1 +++ b/tst/functions/assert/Exception/Assert-Throw.Tests.ps1 @@ -1,4 +1,6 @@ -Describe "Assert-Throw" { +Set-StrictMode -Version Latest + +Describe "Assert-Throw" { It "Passes when exception is thrown" { { throw } | Assert-Throw } diff --git a/tst/functions/assert/General/Assert-LessThan.Tests.ps1 b/tst/functions/assert/General/Assert-LessThan.Tests.ps1 index 5e4c96087..31143c6f3 100644 --- a/tst/functions/assert/General/Assert-LessThan.Tests.ps1 +++ b/tst/functions/assert/General/Assert-LessThan.Tests.ps1 @@ -1,4 +1,6 @@ -Describe "Assert-LessThan" { +Set-StrictMode -Version Latest + +Describe "Assert-LessThan" { Context "Comparing strings" { It "Passes when actual is less than expected" { "a" | Assert-LessThan "z" @@ -70,20 +72,20 @@ } It "Fails for array input even if the last item is less than the expected value" { - $err = { 4,3,2,1 | Assert-LessThan 3 } | Verify-Throw - $err.Exception | Verify-Type ([System.Management.Automation.RuntimeException]) + $err = { 4, 3, 2, 1 | Assert-LessThan 3 } | Verify-Throw + $err.Exception | Verify-Type ([System.Management.Automation.RuntimeException]) } It "Fails with custom message" { - $err = { 3 | Assert-LessThan 2 -CustomMessage " is not less than " } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "3 is not less than 2" + $err = { 3 | Assert-LessThan 2 -CustomMessage " is not less than " } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "3 is not less than 2" } Context "Validate messages" { It "Given two values '' and '' it returns expected message ''" -TestCases @( - @{ Expected = "a" ; Actual = "z" ; Message = "Expected string 'z' to be less than string 'a', but it was not."}, - @{ Expected = 1.1 ; Actual = 10.1 ; Message = "Expected double '10.1' to be less than double '1.1', but it was not."}, - @{ Expected = 1.1D ; Actual = 10.1D ; Message = "Expected decimal '10.1' to be less than decimal '1.1', but it was not."} + @{ Expected = "a" ; Actual = "z" ; Message = "Expected string 'z' to be less than string 'a', but it was not." }, + @{ Expected = 1.1 ; Actual = 10.1 ; Message = "Expected double '10.1' to be less than double '1.1', but it was not." }, + @{ Expected = 1.1D ; Actual = 10.1D ; Message = "Expected decimal '10.1' to be less than decimal '1.1', but it was not." } ) { param($Expected, $Actual, $Message) $error = { Assert-LessThan -Actual $Actual -Expected $Expected } | Verify-AssertionFailed @@ -104,4 +106,4 @@ $error = { "dummy" | Assert-LessThan @() } | Verify-Throw $error.Exception | Verify-Type ([ArgumentException]) } -} \ No newline at end of file +} diff --git a/tst/functions/assert/General/Assert-LessThanOrEqual.Tests.ps1 b/tst/functions/assert/General/Assert-LessThanOrEqual.Tests.ps1 index 960dfb707..fabf0a16f 100644 --- a/tst/functions/assert/General/Assert-LessThanOrEqual.Tests.ps1 +++ b/tst/functions/assert/General/Assert-LessThanOrEqual.Tests.ps1 @@ -1,4 +1,6 @@ -Describe "Assert-LessThanOrEqual" { +Set-StrictMode -Version Latest + +Describe "Assert-LessThanOrEqual" { Context "Comparing strings" { It "Passes when actual is less than expected" { "a" | Assert-LessThanOrEqual "z" @@ -70,20 +72,20 @@ } It "Fails for array input even if the last item is less than then expected value" { - $err = { 4,3,2,1 | Assert-LessThanOrEqual 3 } | Verify-Throw - $err.Exception | Verify-Type ([System.Management.Automation.RuntimeException]) + $err = { 4, 3, 2, 1 | Assert-LessThanOrEqual 3 } | Verify-Throw + $err.Exception | Verify-Type ([System.Management.Automation.RuntimeException]) } It "Fails with custom message" { - $err = { 3 | Assert-LessThanOrEqual 2 -CustomMessage " is not less than " } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "3 is not less than 2" + $err = { 3 | Assert-LessThanOrEqual 2 -CustomMessage " is not less than " } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "3 is not less than 2" } Context "Validate messages" { It "Given two values '' and '' it returns expected message ''" -TestCases @( - @{ Expected = "a" ; Actual = "z" ; Message = "Expected string 'z' to be less than or equal to string 'a', but it was not."}, - @{ Expected = 1.1 ; Actual = 10.1 ; Message = "Expected double '10.1' to be less than or equal to double '1.1', but it was not."}, - @{ Expected = 1.1D ; Actual = 10.1D ; Message = "Expected decimal '10.1' to be less than or equal to decimal '1.1', but it was not."} + @{ Expected = "a" ; Actual = "z" ; Message = "Expected string 'z' to be less than or equal to string 'a', but it was not." }, + @{ Expected = 1.1 ; Actual = 10.1 ; Message = "Expected double '10.1' to be less than or equal to double '1.1', but it was not." }, + @{ Expected = 1.1D ; Actual = 10.1D ; Message = "Expected decimal '10.1' to be less than or equal to decimal '1.1', but it was not." } ) { param($Expected, $Actual, $Message) $error = { Assert-LessThanOrEqual -Actual $Actual -Expected $Expected } | Verify-AssertionFailed @@ -104,4 +106,4 @@ $error = { "dummy" | Assert-LessThanOrEqual @() } | Verify-Throw $error.Exception | Verify-Type ([ArgumentException]) } -} \ No newline at end of file +} diff --git a/tst/functions/assert/String/Assert-Like.Tests.ps1 b/tst/functions/assert/String/Assert-Like.Tests.ps1 index daef3dc2d..f6ec2e68e 100644 --- a/tst/functions/assert/String/Assert-Like.Tests.ps1 +++ b/tst/functions/assert/String/Assert-Like.Tests.ps1 @@ -1,4 +1,6 @@ -Describe "Assert-Like" { +Set-StrictMode -Version Latest + +Describe "Assert-Like" { Context "Case insensitive matching" { It "Passes give strings that have the same value" { Assert-Like -Expected "abc" -Actual "abc" @@ -134,4 +136,4 @@ $err.Exception.Message | Verify-Equal $Message } } -} \ No newline at end of file +} diff --git a/tst/functions/assert/String/Assert-NotLike.Tests.ps1 b/tst/functions/assert/String/Assert-NotLike.Tests.ps1 index ea56807e2..fb71d193f 100644 --- a/tst/functions/assert/String/Assert-NotLike.Tests.ps1 +++ b/tst/functions/assert/String/Assert-NotLike.Tests.ps1 @@ -1,4 +1,6 @@ -Describe "Assert-NotLike" { +Set-StrictMode -Version Latest + +Describe "Assert-NotLike" { Context "Case insensitive matching" { It "Fails give strings that have the same value" { { Assert-NotLike -Expected "abc" -Actual "abc" } | Verify-AssertionFailed @@ -134,4 +136,4 @@ $err.Exception.Message | Verify-Equal $Message } } -} \ No newline at end of file +} From 911a4650619fb13c49dd35ac105c3af142e9e900 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Sat, 6 Apr 2024 21:12:45 +0200 Subject: [PATCH 05/55] Fix $error --- tst/functions/assert/Boolean/Assert-False.Tests.ps1 | 8 ++++---- tst/functions/assert/Boolean/Assert-True.Tests.ps1 | 8 ++++---- .../assert/Collection/Assert-Contain.Tests.ps1 | 8 ++++---- .../assert/Collection/Assert-NotContain.Tests.ps1 | 8 ++++---- .../Common/Ensure-ExpectedIsNotCollection.Tests.ps1 | 8 ++++---- .../assert/Exception/Assert-Throw.Tests.ps1 | 8 ++++---- tst/functions/assert/General/Assert-Equal.Tests.ps1 | 12 ++++++------ .../assert/General/Assert-GreaterThan.Tests.ps1 | 8 ++++---- .../General/Assert-GreaterThanOrEqual.Tests.ps1 | 8 ++++---- .../assert/General/Assert-LessThan.Tests.ps1 | 8 ++++---- .../assert/General/Assert-LessThanOrEqual.Tests.ps1 | 8 ++++---- .../assert/General/Assert-NotEqual.Tests.ps1 | 12 ++++++------ .../assert/General/Assert-NotSame.Tests.ps1 | 8 ++++---- tst/functions/assert/General/Assert-Same.Tests.ps1 | 12 ++++++------ 14 files changed, 62 insertions(+), 62 deletions(-) diff --git a/tst/functions/assert/Boolean/Assert-False.Tests.ps1 b/tst/functions/assert/Boolean/Assert-False.Tests.ps1 index 8b5c35f03..5ac36c378 100644 --- a/tst/functions/assert/Boolean/Assert-False.Tests.ps1 +++ b/tst/functions/assert/Boolean/Assert-False.Tests.ps1 @@ -20,8 +20,8 @@ Describe "Assert-False" { } It "Fails with custom message" { - $error = { 9 | Assert-False -CustomMessage " is not false" } | Verify-AssertionFailed - $error.Exception.Message | Verify-Equal "9 is not false" + $err = { 9 | Assert-False -CustomMessage " is not false" } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "9 is not false" } Context "Validate messages" { @@ -30,8 +30,8 @@ Describe "Assert-False" { @{ Actual = 10 ; Message = "Expected int '10' to be bool '`$false' or falsy value 0, """", `$null, @()." } ) { param($Actual, $Message) - $error = { Assert-False -Actual $Actual } | Verify-AssertionFailed - $error.Exception.Message | Verify-Equal $Message + $err = { Assert-False -Actual $Actual } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $Message } } diff --git a/tst/functions/assert/Boolean/Assert-True.Tests.ps1 b/tst/functions/assert/Boolean/Assert-True.Tests.ps1 index 7e3070d10..e7c214102 100644 --- a/tst/functions/assert/Boolean/Assert-True.Tests.ps1 +++ b/tst/functions/assert/Boolean/Assert-True.Tests.ps1 @@ -16,8 +16,8 @@ Describe "Assert-True" { } It "Fails with custom message" { - $error = { $null | Assert-True -CustomMessage " is not true" } | Verify-AssertionFailed - $error.Exception.Message | Verify-Equal "`$null is not true" + $err = { $null | Assert-True -CustomMessage " is not true" } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "`$null is not true" } Context "Validate messages" { @@ -26,8 +26,8 @@ Describe "Assert-True" { @{ Actual = 0 ; Message = "Expected int '0' to be bool '`$true' or truthy value." } ) { param($Actual, $Message) - $error = { Assert-True -Actual $Actual } | Verify-AssertionFailed - $error.Exception.Message | Verify-Equal $Message + $err = { Assert-True -Actual $Actual } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $Message } } diff --git a/tst/functions/assert/Collection/Assert-Contain.Tests.ps1 b/tst/functions/assert/Collection/Assert-Contain.Tests.ps1 index e5a949da8..bbcea6265 100644 --- a/tst/functions/assert/Collection/Assert-Contain.Tests.ps1 +++ b/tst/functions/assert/Collection/Assert-Contain.Tests.ps1 @@ -7,8 +7,8 @@ InPesterModuleScope { } It "Fails when collection of single item does not contain the expected item" { - $error = { @(5) | Assert-Contain 1 } | Verify-AssertionFailed - $error.Exception.Message | Verify-Equal "Expected int '1' to be present in collection '5', but it was not there." + $err = { @(5) | Assert-Contain 1 } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "Expected int '1' to be present in collection '5', but it was not there." } It "Passes when collection of multiple items contains the expected item" { @@ -16,8 +16,8 @@ InPesterModuleScope { } It "Fails when collection of multiple items does not contain the expected item" { - $error = { @(5,6,7) | Assert-Contain 1 } | Verify-AssertionFailed - $error.Exception.Message | Verify-Equal "Expected int '1' to be present in collection '5, 6, 7', but it was not there." + $err = { @(5,6,7) | Assert-Contain 1 } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "Expected int '1' to be present in collection '5, 6, 7', but it was not there." } It "Can be called with positional parameters" { diff --git a/tst/functions/assert/Collection/Assert-NotContain.Tests.ps1 b/tst/functions/assert/Collection/Assert-NotContain.Tests.ps1 index 545efac26..1dbb44062 100644 --- a/tst/functions/assert/Collection/Assert-NotContain.Tests.ps1 +++ b/tst/functions/assert/Collection/Assert-NotContain.Tests.ps1 @@ -3,8 +3,8 @@ Set-StrictMode -Version Latest InPesterModuleScope { Describe "Assert-NotContain" { It "Fails when collection of single item contains the expected item" { - $error = { @(1) | Assert-NotContain 1 } | Verify-AssertionFailed - $error.Exception.Message | Verify-Equal "Expected int '1' to not be present in collection '1', but it was there." + $err = { @(1) | Assert-NotContain 1 } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "Expected int '1' to not be present in collection '1', but it was there." } It "Passes when collection of single item does not contain the expected item" { @@ -12,8 +12,8 @@ InPesterModuleScope { } It "Fails when collection of multiple items contains the expected item" { - $error = { @(1,2,3) | Assert-NotContain 1 } | Verify-AssertionFailed - $error.Exception.Message | Verify-Equal "Expected int '1' to not be present in collection '1, 2, 3', but it was there." + $err = { @(1,2,3) | Assert-NotContain 1 } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "Expected int '1' to not be present in collection '1, 2, 3', but it was there." } It "Passes when collection of multiple items does not contain the expected item" { diff --git a/tst/functions/assert/Common/Ensure-ExpectedIsNotCollection.Tests.ps1 b/tst/functions/assert/Common/Ensure-ExpectedIsNotCollection.Tests.ps1 index ae907c926..4edea0e02 100644 --- a/tst/functions/assert/Common/Ensure-ExpectedIsNotCollection.Tests.ps1 +++ b/tst/functions/assert/Common/Ensure-ExpectedIsNotCollection.Tests.ps1 @@ -3,13 +3,13 @@ InPesterModuleScope { Describe "Ensure-ExpectedIsNotCollection" { It "Given a collection it throws ArgumentException" { - $error = { Ensure-ExpectedIsNotCollection -InputObject @() } | Verify-Throw - $error.Exception | Verify-Type ([ArgumentException]) + $err = { Ensure-ExpectedIsNotCollection -InputObject @() } | Verify-Throw + $err.Exception | Verify-Type ([ArgumentException]) } It "Given a collection it throws correct message" { - $error = { Ensure-ExpectedIsNotCollection -InputObject @() } | Verify-Throw - $error.Exception.Message | Verify-Equal 'You provided a collection to the -Expected parameter. Using a collection on the -Expected side is not allowed by this assertion, because it leads to unexpected behavior. Please use Assert-Any, Assert-All or some other specialized collection assertion.' + $err = { Ensure-ExpectedIsNotCollection -InputObject @() } | Verify-Throw + $err.Exception.Message | Verify-Equal 'You provided a collection to the -Expected parameter. Using a collection on the -Expected side is not allowed by this assertion, because it leads to unexpected behavior. Please use Assert-Any, Assert-All or some other specialized collection assertion.' } diff --git a/tst/functions/assert/Exception/Assert-Throw.Tests.ps1 b/tst/functions/assert/Exception/Assert-Throw.Tests.ps1 index 531fabb6c..22040f857 100644 --- a/tst/functions/assert/Exception/Assert-Throw.Tests.ps1 +++ b/tst/functions/assert/Exception/Assert-Throw.Tests.ps1 @@ -143,10 +143,10 @@ Describe "Assert-Throw" { } It "Given scriptblock that throws it returns ErrorRecord to the output" { - $error = { throw [InvalidOperationException]"error" } | Assert-Throw - $error | Verify-Type ([Management.Automation.ErrorRecord]) - $error.Exception | Verify-Type ([System.InvalidOperationException]) - $error.Exception.Message | Verify-Equal "error" + $err = { throw [InvalidOperationException]"error" } | Assert-Throw + $err | Verify-Type ([Management.Automation.ErrorRecord]) + $err.Exception | Verify-Type ([System.InvalidOperationException]) + $err.Exception.Message | Verify-Equal "error" } } diff --git a/tst/functions/assert/General/Assert-Equal.Tests.ps1 b/tst/functions/assert/General/Assert-Equal.Tests.ps1 index 6ec43dba4..0d86adce1 100644 --- a/tst/functions/assert/General/Assert-Equal.Tests.ps1 +++ b/tst/functions/assert/General/Assert-Equal.Tests.ps1 @@ -60,8 +60,8 @@ InPesterModuleScope { } It "Fails with custom message" { - $error = { 9 | Assert-Equal 3 -CustomMessage " is not " } | Verify-AssertionFailed - $error.Exception.Message | Verify-Equal "3 is not 9" + $err = { 9 | Assert-Equal 3 -CustomMessage " is not " } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "3 is not 9" } Context "Validate messages" { @@ -71,8 +71,8 @@ InPesterModuleScope { @{ Expected = "a" ; Actual = 10.1D ; Message = "Expected string 'a', but got decimal '10.1'."} ) { param($Expected, $Actual, $Message) - $error = { Assert-Equal -Actual $Actual -Expected $Expected } | Verify-AssertionFailed - $error.Exception.Message | Verify-Equal $Message + $err = { Assert-Equal -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $Message } } @@ -86,8 +86,8 @@ InPesterModuleScope { } It "Given collection to Expected it throws" { - $error = { "dummy" | Assert-Equal @() } | Verify-Throw - $error.Exception | Verify-Type ([ArgumentException]) + $err = { "dummy" | Assert-Equal @() } | Verify-Throw + $err.Exception | Verify-Type ([ArgumentException]) } } } diff --git a/tst/functions/assert/General/Assert-GreaterThan.Tests.ps1 b/tst/functions/assert/General/Assert-GreaterThan.Tests.ps1 index 0851eaa01..45eb42fbb 100644 --- a/tst/functions/assert/General/Assert-GreaterThan.Tests.ps1 +++ b/tst/functions/assert/General/Assert-GreaterThan.Tests.ps1 @@ -89,8 +89,8 @@ InPesterModuleScope { @{ Expected = 10.1D ; Actual = 1.1D ; Message = "Expected decimal '1.1' to be greater than decimal '10.1', but it was not."} ) { param($Expected, $Actual, $Message) - $error = { Assert-GreaterThan -Actual $Actual -Expected $Expected } | Verify-AssertionFailed - $error.Exception.Message | Verify-Equal $Message + $err = { Assert-GreaterThan -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $Message } } @@ -104,8 +104,8 @@ InPesterModuleScope { } It "Given collection to Expected it throws" { - $error = { "dummy" | Assert-GreaterThan @() } | Verify-Throw - $error.Exception | Verify-Type ([ArgumentException]) + $err = { "dummy" | Assert-GreaterThan @() } | Verify-Throw + $err.Exception | Verify-Type ([ArgumentException]) } } } diff --git a/tst/functions/assert/General/Assert-GreaterThanOrEqual.Tests.ps1 b/tst/functions/assert/General/Assert-GreaterThanOrEqual.Tests.ps1 index 0e634f861..5d5a88cdc 100644 --- a/tst/functions/assert/General/Assert-GreaterThanOrEqual.Tests.ps1 +++ b/tst/functions/assert/General/Assert-GreaterThanOrEqual.Tests.ps1 @@ -89,8 +89,8 @@ InPesterModuleScope { @{ Expected = 10.1D ; Actual = 1.1D ; Message = "Expected decimal '1.1' to be greater than or equal to decimal '10.1', but it was not."} ) { param($Expected, $Actual, $Message) - $error = { Assert-GreaterThanOrEqual -Actual $Actual -Expected $Expected } | Verify-AssertionFailed - $error.Exception.Message | Verify-Equal $Message + $err = { Assert-GreaterThanOrEqual -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $Message } } @@ -104,8 +104,8 @@ InPesterModuleScope { } It "Given collection to Expected it throws" { - $error = { "dummy" | Assert-GreaterThanOrEqual @() } | Verify-Throw - $error.Exception | Verify-Type ([ArgumentException]) + $err = { "dummy" | Assert-GreaterThanOrEqual @() } | Verify-Throw + $err.Exception | Verify-Type ([ArgumentException]) } } } diff --git a/tst/functions/assert/General/Assert-LessThan.Tests.ps1 b/tst/functions/assert/General/Assert-LessThan.Tests.ps1 index 31143c6f3..01ba0a12e 100644 --- a/tst/functions/assert/General/Assert-LessThan.Tests.ps1 +++ b/tst/functions/assert/General/Assert-LessThan.Tests.ps1 @@ -88,8 +88,8 @@ Describe "Assert-LessThan" { @{ Expected = 1.1D ; Actual = 10.1D ; Message = "Expected decimal '10.1' to be less than decimal '1.1', but it was not." } ) { param($Expected, $Actual, $Message) - $error = { Assert-LessThan -Actual $Actual -Expected $Expected } | Verify-AssertionFailed - $error.Exception.Message | Verify-Equal $Message + $err = { Assert-LessThan -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $Message } } @@ -103,7 +103,7 @@ Describe "Assert-LessThan" { } It "Given collection to Expected it throws" { - $error = { "dummy" | Assert-LessThan @() } | Verify-Throw - $error.Exception | Verify-Type ([ArgumentException]) + $err = { "dummy" | Assert-LessThan @() } | Verify-Throw + $err.Exception | Verify-Type ([ArgumentException]) } } diff --git a/tst/functions/assert/General/Assert-LessThanOrEqual.Tests.ps1 b/tst/functions/assert/General/Assert-LessThanOrEqual.Tests.ps1 index fabf0a16f..88ff611d4 100644 --- a/tst/functions/assert/General/Assert-LessThanOrEqual.Tests.ps1 +++ b/tst/functions/assert/General/Assert-LessThanOrEqual.Tests.ps1 @@ -88,8 +88,8 @@ Describe "Assert-LessThanOrEqual" { @{ Expected = 1.1D ; Actual = 10.1D ; Message = "Expected decimal '10.1' to be less than or equal to decimal '1.1', but it was not." } ) { param($Expected, $Actual, $Message) - $error = { Assert-LessThanOrEqual -Actual $Actual -Expected $Expected } | Verify-AssertionFailed - $error.Exception.Message | Verify-Equal $Message + $err = { Assert-LessThanOrEqual -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $Message } } @@ -103,7 +103,7 @@ Describe "Assert-LessThanOrEqual" { } It "Given collection to Expected it throws" { - $error = { "dummy" | Assert-LessThanOrEqual @() } | Verify-Throw - $error.Exception | Verify-Type ([ArgumentException]) + $err = { "dummy" | Assert-LessThanOrEqual @() } | Verify-Throw + $err.Exception | Verify-Type ([ArgumentException]) } } diff --git a/tst/functions/assert/General/Assert-NotEqual.Tests.ps1 b/tst/functions/assert/General/Assert-NotEqual.Tests.ps1 index c5cc4b73c..4aad56d23 100644 --- a/tst/functions/assert/General/Assert-NotEqual.Tests.ps1 +++ b/tst/functions/assert/General/Assert-NotEqual.Tests.ps1 @@ -60,8 +60,8 @@ InPesterModuleScope { } It "Fails with custom message" { - $error = { 3 | Assert-NotEqual 3 -CustomMessage " is " } | Verify-AssertionFailed - $error.Exception.Message | Verify-Equal "3 is 3" + $err = { 3 | Assert-NotEqual 3 -CustomMessage " is " } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "3 is 3" } Context "Validate messages" { @@ -69,8 +69,8 @@ InPesterModuleScope { @{ Value = 1; Message = "Expected int '1', to be different than the actual value, but they were the same."} ) { param($Value, $Message) - $error = { Assert-NotEqual -Actual $Value -Expected $Value } | Verify-AssertionFailed - $error.Exception.Message | Verify-Equal $Message + $err = { Assert-NotEqual -Actual $Value -Expected $Value } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $Message } } @@ -84,8 +84,8 @@ InPesterModuleScope { } It "Given collection to Expected it throws" { - $error = { "dummy" | Assert-NotEqual @() } | Verify-Throw - $error.Exception | Verify-Type ([ArgumentException]) + $err = { "dummy" | Assert-NotEqual @() } | Verify-Throw + $err.Exception | Verify-Type ([ArgumentException]) } } } diff --git a/tst/functions/assert/General/Assert-NotSame.Tests.ps1 b/tst/functions/assert/General/Assert-NotSame.Tests.ps1 index 23b78431f..f83a69afa 100644 --- a/tst/functions/assert/General/Assert-NotSame.Tests.ps1 +++ b/tst/functions/assert/General/Assert-NotSame.Tests.ps1 @@ -20,16 +20,16 @@ InPesterModuleScope { It "Fails with custom message" { $object = 1 - $error = { $object | Assert-NotSame $object -CustomMessage " is " } | Verify-AssertionFailed - $error.Exception.Message | Verify-Equal "1 is 1" + $err = { $object | Assert-NotSame $object -CustomMessage " is " } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "1 is 1" } It "Given two values that are the same instance it returns expected message ''" -TestCases @( @{ Value = "a"; Message = "Expected string 'a', to not be the same instance."} ) { param($Value, $Message) - $error = { Assert-NotSame -Actual $Value -Expected $Value } | Verify-AssertionFailed - $error.Exception.Message | Verify-Equal $Message + $err = { Assert-NotSame -Actual $Value -Expected $Value } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $Message } It "Returns the value on output" { diff --git a/tst/functions/assert/General/Assert-Same.Tests.ps1 b/tst/functions/assert/General/Assert-Same.Tests.ps1 index dc119abed..2eb89eb03 100644 --- a/tst/functions/assert/General/Assert-Same.Tests.ps1 +++ b/tst/functions/assert/General/Assert-Same.Tests.ps1 @@ -15,21 +15,21 @@ InPesterModuleScope { It "Fails for array input even if the last item is the same as expected" { $object = New-Object Diagnostics.Process - { 1,2, $object | Assert-Same $object } | Verify-AssertionFailed + { 1, 2, $object | Assert-Same $object } | Verify-AssertionFailed } It "Fails with custom message" { $object = New-Object Diagnostics.Process - $error = { "text" | Assert-Same $object -CustomMessage "'' is not ''" } | Verify-AssertionFailed - $error.Exception.Message | Verify-Equal "'Diagnostics.Process{Id=; Name=}' is not 'text'" + $err = { "text" | Assert-Same $object -CustomMessage "'' is not ''" } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "'Diagnostics.Process{Id=; Name=}' is not 'text'" } It "Given two values that are not the same instance '' and '' it returns expected message ''" -TestCases @( - @{ Expected = New-Object -TypeName PSObject ; Actual = New-Object -TypeName PSObject ; Message = "Expected PSObject '', to be the same instance but it was not."} + @{ Expected = New-Object -TypeName PSObject ; Actual = New-Object -TypeName PSObject ; Message = "Expected PSObject '', to be the same instance but it was not." } ) { param($Expected, $Actual, $Message) - $error = { Assert-Same -Actual $Actual -Expected $Expected } | Verify-AssertionFailed - $error.Exception.Message | Verify-Equal $Message + $err = { Assert-Same -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $Message } It "Returns the value on output" { From 0bf4752b8a60370ddee15888e7b79d4283f132bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Sat, 6 Apr 2024 22:19:23 +0200 Subject: [PATCH 06/55] Fix warnings --- src/Format2.ps1 | 31 ++++++++++++------- .../assert/Collection/Assert-All.ps1 | 15 ++++----- .../assert/Collection/Assert-Any.ps1 | 7 ++--- .../assert/Common/Get-AssertionMessage.ps1 | 17 ++++------ src/functions/assert/Compatibility.ps1 | 2 +- .../assert/Exception/Assert-Throw.ps1 | 8 ++--- .../assert/Exception/Assert-Throw.Tests.ps1 | 4 ++- 7 files changed, 43 insertions(+), 41 deletions(-) diff --git a/src/Format2.ps1 b/src/Format2.ps1 index 7a2282e5b..0c8c08197 100644 --- a/src/Format2.ps1 +++ b/src/Format2.ps1 @@ -3,20 +3,25 @@ if ($Pretty) { $separator = ",`n" } - ($Value | ForEach-Object { Format-Nicely2 -Value $_ -Pretty:$Pretty }) -join $separator + + $o = foreach ($v in $Value) { + Format-Nicely2 -Value $v -Pretty:$Pretty + } + + $o -join $separator } function Format-Object2 ($Value, $Property, [switch]$Pretty) { if ($null -eq $Property) { - $Property = $Value.PSObject.Properties | Select-Object -ExpandProperty Name + $Property = foreach ($p in $Value.PSObject.Properties) { $p.Name } } - $orderedProperty = $Property | - Sort-Object | + $orderedProperty = foreach ($p in $Property | & $SafeCommands['Sort-Object']) { # force the values to be strings for powershell v2 - ForEach-Object { "$_" } + "$p" + } $valueType = Get-ShortType $Value - $valueFormatted = [string]([PSObject]$Value | Select-Object -Property $orderedProperty) + $valueFormatted = [string]([PSObject]$Value | & $SafeCommands['Select-Object'] -Property $orderedProperty) if ($Pretty) { $margin = " " @@ -50,9 +55,10 @@ function Format-Hashtable2 ($Value) { $head = '@{' $tail = '}' - $entries = $Value.Keys | Sort-Object | ForEach-Object { - $formattedValue = Format-Nicely2 $Value.$_ - "$_=$formattedValue" } + $entries = foreach ($v in $Value.Keys | & $SafeCommands['Sort-Object']) { + $formattedValue = Format-Nicely2 $Value.$v + "$v=$formattedValue" + } $head + ( $entries -join '; ') + $tail } @@ -61,9 +67,10 @@ function Format-Dictionary2 ($Value) { $head = 'Dictionary{' $tail = '}' - $entries = $Value.Keys | Sort-Object | ForEach-Object { - $formattedValue = Format-Nicely2 $Value.$_ - "$_=$formattedValue" } + $entries = foreach ($v in $Value.Keys | & $SafeCommands['Sort-Object'] ) { + $formattedValue = Format-Nicely2 $Value.$v + "$v=$formattedValue" + } $head + ( $entries -join '; ') + $tail } diff --git a/src/functions/assert/Collection/Assert-All.ps1 b/src/functions/assert/Collection/Assert-All.ps1 index 9f6d57bd0..0995cc3dd 100644 --- a/src/functions/assert/Collection/Assert-All.ps1 +++ b/src/functions/assert/Collection/Assert-All.ps1 @@ -14,15 +14,16 @@ # we are jumping between modules so I need to explicitly pass the _ variable # simply using '&' won't work # see: https://blogs.msdn.microsoft.com/sergey_babkins_blog/2014/10/30/calling-the-script-blocks-in-powershell/ - $actualFiltered = $Actual | ForEach-Object { + # + # Do NOT replace this Foreach-Object with foreach keyword, you will break the $_ variable. + $actualFiltered = $Actual | & $SafeCommands['ForEach-Object'] { # powershell v4 code where we have InvokeWithContext available - # $underscore = Get-Variable _ - # $pass = $FilterScript.InvokeWithContext($null, $underscore, $null) - - # polyfill for PowerShell v2 - $PSCmdlet.SessionState.PSVariable.Set("_", $_) - $pass = & $FilterScript + $underscore = Get-Variable _ + $pass = $FilterScript.InvokeWithContext($null, $underscore, $null) + # # polyfill for PowerShell v2 + # $PSCmdlet.SessionState.PSVariable.Set("_", $_) + # $pass = & $FilterScript if (-not $pass) { $_ } } diff --git a/src/functions/assert/Collection/Assert-Any.ps1 b/src/functions/assert/Collection/Assert-Any.ps1 index 1fe85e8c6..15c523d2a 100644 --- a/src/functions/assert/Collection/Assert-Any.ps1 +++ b/src/functions/assert/Collection/Assert-Any.ps1 @@ -1,16 +1,15 @@ function Assert-Any { param ( - [Parameter(ValueFromPipeline=$true, Position=1)] + [Parameter(ValueFromPipeline = $true, Position = 1)] $Actual, - [Parameter(Position=0, Mandatory=$true)] + [Parameter(Position = 0, Mandatory = $true)] [scriptblock]$FilterScript, [String]$CustomMessage ) $Expected = $FilterScript $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input - if (-not ($Actual | Where-Object -FilterScript $FilterScript)) - { + if (-not ($Actual | & $SafeCommands['Where-Object'] -FilterScript $FilterScript)) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected at least one item in collection '' to pass filter '', but none of the items passed the filter." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/Common/Get-AssertionMessage.ps1 b/src/functions/assert/Common/Get-AssertionMessage.ps1 index 05b081cd2..49e01420a 100644 --- a/src/functions/assert/Common/Get-AssertionMessage.ps1 +++ b/src/functions/assert/Common/Get-AssertionMessage.ps1 @@ -1,7 +1,5 @@ -function Get-AssertionMessage ($Expected, $Actual, $Option, [hashtable]$Data = @{}, $CustomMessage, $DefaultMessage, [switch]$Pretty) -{ - if (-not $CustomMessage) - { +function Get-AssertionMessage ($Expected, $Actual, $Option, [hashtable]$Data = @{}, $CustomMessage, $DefaultMessage, [switch]$Pretty) { + if (-not $CustomMessage) { $CustomMessage = $DefaultMessage } @@ -9,14 +7,13 @@ $actualFormatted = Format-Nicely2 -Value $Actual -Pretty:$Pretty $optionMessage = $null; - if ($null -ne $Option -and $option.Length -gt 0) - { + if ($null -ne $Option -and $option.Length -gt 0) { if (-not $Pretty) { $optionMessage = "Used options: $($Option -join ", ")." } else { if ($Pretty) { - $optionMessage = "Used options:$($Option | ForEach-Object { "`n$_" })." + $optionMessage = "Used options:$(foreach ($o in $Option) { "`n$o" })." } } } @@ -28,16 +25,14 @@ $CustomMessage = $CustomMessage.Replace('', (Get-ShortType2 -Value $Actual)) $CustomMessage = $CustomMessage.Replace('', $optionMessage) - foreach ($pair in $Data.GetEnumerator()) - { + foreach ($pair in $Data.GetEnumerator()) { $CustomMessage = $CustomMessage.Replace("<$($pair.Key)>", (Format-Nicely2 -Value $pair.Value)) } if (-not $Pretty) { $CustomMessage } - else - { + else { $CustomMessage + "`n`n" } } diff --git a/src/functions/assert/Compatibility.ps1 b/src/functions/assert/Compatibility.ps1 index 4e79ca958..e6cc7d63b 100644 --- a/src/functions/assert/Compatibility.ps1 +++ b/src/functions/assert/Compatibility.ps1 @@ -49,7 +49,7 @@ function Invoke-WithContext { # making it invoke in the same scope as $ScriptBlock $scriptBlockWithContext.GetType().GetProperty('SessionStateInternal', $flags).SetValue($scriptBlockWithContext, $SessionStateInternal, $null) - & $scriptBlockWithContext @{ ScriptBlock = $ScriptBlock; Variables = $Variables } + & $scriptBlockWithContext @{ ScriptBlock = $ScriptBlock; Variables = $Variables } } function Test-NullOrWhiteSpace ($Value) { diff --git a/src/functions/assert/Exception/Assert-Throw.ps1 b/src/functions/assert/Exception/Assert-Throw.ps1 index e3819e4cf..b3ee83db8 100644 --- a/src/functions/assert/Exception/Assert-Throw.ps1 +++ b/src/functions/assert/Exception/Assert-Throw.ps1 @@ -18,11 +18,9 @@ function Assert-Throw { if ($AllowNonTerminatingError) { $p = 'continue' } - # compatibility fix for powershell v2 - # $eap = New-Object -TypeName psvariable "erroractionpreference", $p - # $null = $ScriptBlock.InvokeWithContext($null, $eap, $null) 2>&1 - $null = (Invoke-WithContext -ScriptBlock $ScriptBlock -Variables @{ ErrorActionPreference = $p }) 2>&1 + $eap = [PSVariable]::new("erroractionpreference", $p) + $null = $ScriptBlock.InvokeWithContext($null, $eap, $null) 2>&1 } catch { $errorThrown = $true @@ -86,7 +84,7 @@ function Get-Error ($ErrorRecord) { else { $e = $ErrorRecord } - New-Object -TypeName PSObject -Property @{ + [PSCustomObject] @{ ErrorRecord = $e ExceptionMessage = $e.Exception.Message Exception = $e.Exception diff --git a/tst/functions/assert/Exception/Assert-Throw.Tests.ps1 b/tst/functions/assert/Exception/Assert-Throw.Tests.ps1 index 22040f857..1f6e1b39c 100644 --- a/tst/functions/assert/Exception/Assert-Throw.Tests.ps1 +++ b/tst/functions/assert/Exception/Assert-Throw.Tests.ps1 @@ -210,7 +210,9 @@ InPesterModuleScope { $sb = { Get-Item "/non-existing" } - Invoke-WithContext $sb -Variables @{ ErrorActionPreference = "Stop" } + + $eap = [PSVariable]::new("erroractionpreference", 'Stop') + $null = $sb.InvokeWithContext($null, $eap, $null) 2>&1 } catch { $e = $_ From b54b003a61c104f9ea3e3369a7cdcafff3f00147 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Sat, 6 Apr 2024 23:17:08 +0200 Subject: [PATCH 07/55] Fix collecting from pipeline --- src/functions/assert/Boolean/Assert-False.ps1 | 3 +- src/functions/assert/Boolean/Assert-True.ps1 | 10 ++-- .../assert/Collection/Assert-All.ps1 | 3 +- .../assert/Collection/Assert-Any.ps1 | 3 +- .../assert/Collection/Assert-Contain.ps1 | 3 +- .../assert/Collection/Assert-NotContain.ps1 | 3 +- src/functions/assert/Common/Collect-Input.ps1 | 16 ++---- src/functions/assert/Compatibility.ps1 | 53 ------------------- .../assert/Exception/Assert-Throw.ps1 | 3 +- src/functions/assert/General/Assert-Equal.ps1 | 10 ++-- .../assert/General/Assert-GreaterThan.ps1 | 3 +- .../General/Assert-GreaterThanOrEqual.ps1 | 3 +- .../assert/General/Assert-LessThan.ps1 | 3 +- .../assert/General/Assert-LessThanOrEqual.ps1 | 3 +- .../assert/General/Assert-NotEqual.ps1 | 3 +- .../assert/General/Assert-NotNull.ps1 | 3 +- .../assert/General/Assert-NotSame.ps1 | 10 ++-- .../assert/General/Assert-NotType.ps1 | 3 +- src/functions/assert/General/Assert-Null.ps1 | 8 +-- src/functions/assert/General/Assert-Same.ps1 | 13 +++-- src/functions/assert/General/Assert-Type.ps1 | 3 +- src/functions/assert/String/Assert-Like.ps1 | 3 +- .../assert/String/Assert-NotLike.ps1 | 3 +- .../assert/String/Assert-StringEqual.ps1 | 3 +- .../assert/String/Assert-StringNotEqual.ps1 | 1 + 25 files changed, 65 insertions(+), 107 deletions(-) diff --git a/src/functions/assert/Boolean/Assert-False.ps1 b/src/functions/assert/Boolean/Assert-False.ps1 index bd3ee1423..27a84c884 100644 --- a/src/functions/assert/Boolean/Assert-False.ps1 +++ b/src/functions/assert/Boolean/Assert-False.ps1 @@ -1,11 +1,12 @@ function Assert-False { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(ValueFromPipeline=$true)] $Actual, [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput if ($Actual) { $Message = Get-AssertionMessage -Expected $false -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be '' or falsy value 0, """", `$null, @()." diff --git a/src/functions/assert/Boolean/Assert-True.ps1 b/src/functions/assert/Boolean/Assert-True.ps1 index 9dad238d5..5080ab2b5 100644 --- a/src/functions/assert/Boolean/Assert-True.ps1 +++ b/src/functions/assert/Boolean/Assert-True.ps1 @@ -1,13 +1,13 @@ -function Assert-True{ +function Assert-True { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( - [Parameter(ValueFromPipeline=$true)] + [Parameter(ValueFromPipeline = $true)] $Actual, [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input - if (-not $Actual) - { + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + if (-not $Actual) { $Message = Get-AssertionMessage -Expected $true -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be '' or truthy value." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/Collection/Assert-All.ps1 b/src/functions/assert/Collection/Assert-All.ps1 index 0995cc3dd..8b14f136e 100644 --- a/src/functions/assert/Collection/Assert-All.ps1 +++ b/src/functions/assert/Collection/Assert-All.ps1 @@ -1,4 +1,5 @@ function Assert-All { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] [CmdletBinding()] param ( [Parameter(ValueFromPipeline = $true, Position = 1)] @@ -10,7 +11,7 @@ $Expected = $FilterScript - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput # we are jumping between modules so I need to explicitly pass the _ variable # simply using '&' won't work # see: https://blogs.msdn.microsoft.com/sergey_babkins_blog/2014/10/30/calling-the-script-blocks-in-powershell/ diff --git a/src/functions/assert/Collection/Assert-Any.ps1 b/src/functions/assert/Collection/Assert-Any.ps1 index 15c523d2a..8f0512c7f 100644 --- a/src/functions/assert/Collection/Assert-Any.ps1 +++ b/src/functions/assert/Collection/Assert-Any.ps1 @@ -1,4 +1,5 @@ function Assert-Any { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(ValueFromPipeline = $true, Position = 1)] $Actual, @@ -8,7 +9,7 @@ ) $Expected = $FilterScript - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput if (-not ($Actual | & $SafeCommands['Where-Object'] -FilterScript $FilterScript)) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected at least one item in collection '' to pass filter '', but none of the items passed the filter." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) diff --git a/src/functions/assert/Collection/Assert-Contain.ps1 b/src/functions/assert/Collection/Assert-Contain.ps1 index 60bb4e02a..616263c36 100644 --- a/src/functions/assert/Collection/Assert-Contain.ps1 +++ b/src/functions/assert/Collection/Assert-Contain.ps1 @@ -1,4 +1,5 @@ function Assert-Contain { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position=1, ValueFromPipeline=$true)] $Actual, @@ -7,7 +8,7 @@ [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput if ($Actual -notcontains $Expected) { $type = [string]$Expected diff --git a/src/functions/assert/Collection/Assert-NotContain.ps1 b/src/functions/assert/Collection/Assert-NotContain.ps1 index 27eb5e031..d62721589 100644 --- a/src/functions/assert/Collection/Assert-NotContain.ps1 +++ b/src/functions/assert/Collection/Assert-NotContain.ps1 @@ -1,4 +1,5 @@ function Assert-NotContain { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position=1, ValueFromPipeline=$true)] $Actual, @@ -7,7 +8,7 @@ [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput if ($Actual -contains $Expected) { $type = [string]$Expected diff --git a/src/functions/assert/Common/Collect-Input.ps1 b/src/functions/assert/Common/Collect-Input.ps1 index c25e8651e..ab2facc29 100644 --- a/src/functions/assert/Common/Collect-Input.ps1 +++ b/src/functions/assert/Common/Collect-Input.ps1 @@ -1,14 +1,8 @@ -function Collect-Input ($ParameterInput, $PipelineInput) -{ - #source: http://www.powertheshell.com/input_psv3/ - $collectedInput = @($PipelineInput) - - $isInPipeline = $collectedInput.Count -gt 0 - if ($isInPipeline) { - $collectedInput +function Collect-Input ($ParameterInput, $PipelineInput, $IsInPipeline) { + if ($IsInPipeline) { + $PipelineInput } - else - { + else { $ParameterInput } -} \ No newline at end of file +} diff --git a/src/functions/assert/Compatibility.ps1 b/src/functions/assert/Compatibility.ps1 index e6cc7d63b..9b03aaf45 100644 --- a/src/functions/assert/Compatibility.ps1 +++ b/src/functions/assert/Compatibility.ps1 @@ -1,57 +1,4 @@  - -function Invoke-WithContext { - param( - [Parameter(Mandatory = $true )] - [ScriptBlock] $ScriptBlock, - [Parameter(Mandatory = $true)] - [hashtable] $Variables) - - # this functions is a psv2 compatible version of - # ScriptBlock InvokeWithContext that is not available - # in that version of PowerShell - - # this is what the code below does - # which in effect sets the context without detaching the - # scriptblock from the original scope - # & { - # # context - # $a = 10 - # $b = 20 - # # invoking our original scriptblock - # & $sb - # } - - # a similar solution was $SessionState.PSVariable.Set('a', 10) - # but that sets the variable for all "scopes" in the current - # scope so the value persist after the original has run which - # is not correct, - - $scriptBlockWithContext = { - param($context) - - foreach ($pair in $context.Variables.GetEnumerator()) { - New-Variable -Name $pair.Key -Value $pair.Value - } - - # this cleans up the variable from the session - # the subexpression outputs the value of the variable - # and then deletes the variable, so the value is still passed - # but the variable no longer exists when the scriptblock executes - & $($context.ScriptBlock; Remove-Variable -Name 'context' -Scope Local) - } - - $flags = [System.Reflection.BindingFlags]'Instance,NonPublic' - $SessionState = $ScriptBlock.GetType().GetProperty("SessionState", $flags).GetValue($ScriptBlock, $null) - $SessionStateInternal = $SessionState.GetType().GetProperty('Internal', $flags).GetValue($SessionState, $null) - - # attach the original session state to the wrapper scriptblock - # making it invoke in the same scope as $ScriptBlock - $scriptBlockWithContext.GetType().GetProperty('SessionStateInternal', $flags).SetValue($scriptBlockWithContext, $SessionStateInternal, $null) - - & $scriptBlockWithContext @{ ScriptBlock = $ScriptBlock; Variables = $Variables } -} - function Test-NullOrWhiteSpace ($Value) { # psv2 compatibility, on newer .net we would simply use # [string]::isnullorwhitespace diff --git a/src/functions/assert/Exception/Assert-Throw.ps1 b/src/functions/assert/Exception/Assert-Throw.ps1 index b3ee83db8..7043748f2 100644 --- a/src/functions/assert/Exception/Assert-Throw.ps1 +++ b/src/functions/assert/Exception/Assert-Throw.ps1 @@ -1,4 +1,5 @@ function Assert-Throw { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(ValueFromPipeline = $true, Mandatory = $true)] [ScriptBlock]$ScriptBlock, @@ -9,7 +10,7 @@ function Assert-Throw { [String]$CustomMessage ) - $ScriptBlock = Collect-Input -ParameterInput $ScriptBlock -PipelineInput $local:Input + $ScriptBlock = Collect-Input -ParameterInput $ScriptBlock -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput $errorThrown = $false $err = $null diff --git a/src/functions/assert/General/Assert-Equal.ps1 b/src/functions/assert/General/Assert-Equal.ps1 index 56af6d6f5..62a63ba48 100644 --- a/src/functions/assert/General/Assert-Equal.ps1 +++ b/src/functions/assert/General/Assert-Equal.ps1 @@ -1,16 +1,16 @@ function Assert-Equal { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( - [Parameter(Position=1, ValueFromPipeline=$true)] + [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position=0)] + [Parameter(Position = 0)] $Expected, [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput - if ((Ensure-ExpectedIsNotCollection $Expected) -ne $Actual) - { + if ((Ensure-ExpectedIsNotCollection $Expected) -ne $Actual) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '', but got ''." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Assert-GreaterThan.ps1 b/src/functions/assert/General/Assert-GreaterThan.ps1 index b4d3d4b78..dd85c2685 100644 --- a/src/functions/assert/General/Assert-GreaterThan.ps1 +++ b/src/functions/assert/General/Assert-GreaterThan.ps1 @@ -1,4 +1,5 @@ function Assert-GreaterThan { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position=1, ValueFromPipeline=$true)] $Actual, @@ -7,7 +8,7 @@ [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput if ((Ensure-ExpectedIsNotCollection $Expected) -ge $Actual) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be greater than '', but it was not." diff --git a/src/functions/assert/General/Assert-GreaterThanOrEqual.ps1 b/src/functions/assert/General/Assert-GreaterThanOrEqual.ps1 index fec78007c..b6979c417 100644 --- a/src/functions/assert/General/Assert-GreaterThanOrEqual.ps1 +++ b/src/functions/assert/General/Assert-GreaterThanOrEqual.ps1 @@ -1,4 +1,5 @@ function Assert-GreaterThanOrEqual { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position=1, ValueFromPipeline=$true)] $Actual, @@ -7,7 +8,7 @@ [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput if ((Ensure-ExpectedIsNotCollection $Expected) -gt $Actual) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be greater than or equal to '', but it was not." diff --git a/src/functions/assert/General/Assert-LessThan.ps1 b/src/functions/assert/General/Assert-LessThan.ps1 index f0696fff2..414a71a07 100644 --- a/src/functions/assert/General/Assert-LessThan.ps1 +++ b/src/functions/assert/General/Assert-LessThan.ps1 @@ -1,4 +1,5 @@ function Assert-LessThan { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position=1, ValueFromPipeline=$true)] $Actual, @@ -7,7 +8,7 @@ [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput if ((Ensure-ExpectedIsNotCollection $Expected) -le $Actual) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be less than '', but it was not." diff --git a/src/functions/assert/General/Assert-LessThanOrEqual.ps1 b/src/functions/assert/General/Assert-LessThanOrEqual.ps1 index 1806e4a72..c9e9c8066 100644 --- a/src/functions/assert/General/Assert-LessThanOrEqual.ps1 +++ b/src/functions/assert/General/Assert-LessThanOrEqual.ps1 @@ -1,4 +1,5 @@ function Assert-LessThanOrEqual { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position=1, ValueFromPipeline=$true)] $Actual, @@ -7,7 +8,7 @@ [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput if ((Ensure-ExpectedIsNotCollection $Expected) -lt $Actual) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be less than or equal to '', but it was not." diff --git a/src/functions/assert/General/Assert-NotEqual.ps1 b/src/functions/assert/General/Assert-NotEqual.ps1 index 137d3e5ad..c2280e702 100644 --- a/src/functions/assert/General/Assert-NotEqual.ps1 +++ b/src/functions/assert/General/Assert-NotEqual.ps1 @@ -1,4 +1,5 @@ function Assert-NotEqual { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position=1, ValueFromPipeline=$true)] $Actual, @@ -7,7 +8,7 @@ [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput if ((Ensure-ExpectedIsNotCollection $Expected) -eq $Actual) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '', to be different than the actual value, but they were the same." diff --git a/src/functions/assert/General/Assert-NotNull.ps1 b/src/functions/assert/General/Assert-NotNull.ps1 index f714b299e..ba0936d58 100644 --- a/src/functions/assert/General/Assert-NotNull.ps1 +++ b/src/functions/assert/General/Assert-NotNull.ps1 @@ -1,11 +1,12 @@ function Assert-NotNull { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position=1, ValueFromPipeline=$true)] $Actual, [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput if ($null -eq $Actual) { $Message = Get-AssertionMessage -Expected $null -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected not `$null, but got `$null." diff --git a/src/functions/assert/General/Assert-NotSame.ps1 b/src/functions/assert/General/Assert-NotSame.ps1 index 0ff518c96..15a0eeb1c 100644 --- a/src/functions/assert/General/Assert-NotSame.ps1 +++ b/src/functions/assert/General/Assert-NotSame.ps1 @@ -1,15 +1,15 @@ function Assert-NotSame { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( - [Parameter(Position=1, ValueFromPipeline=$true)] + [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position=0)] + [Parameter(Position = 0)] $Expected, [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input - if ([object]::ReferenceEquals($Expected, $Actual)) - { + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + if ([object]::ReferenceEquals($Expected, $Actual)) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '', to not be the same instance." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Assert-NotType.ps1 b/src/functions/assert/General/Assert-NotType.ps1 index 1ac387cd2..c8be106c6 100644 --- a/src/functions/assert/General/Assert-NotType.ps1 +++ b/src/functions/assert/General/Assert-NotType.ps1 @@ -1,4 +1,5 @@ function Assert-NotType { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, @@ -7,7 +8,7 @@ [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput if ($Actual -is $Expected) { $type = [string]$Expected $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected value to be of different type than '$type', but got '' of type ''." diff --git a/src/functions/assert/General/Assert-Null.ps1 b/src/functions/assert/General/Assert-Null.ps1 index 033b3f3ff..1622d3c47 100644 --- a/src/functions/assert/General/Assert-Null.ps1 +++ b/src/functions/assert/General/Assert-Null.ps1 @@ -1,13 +1,13 @@ function Assert-Null { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( - [Parameter(Position=1, ValueFromPipeline=$true)] + [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input - if ($null -ne $Actual) - { + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + if ($null -ne $Actual) { $Message = Get-AssertionMessage -Expected $null -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected `$null, but got ''." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Assert-Same.ps1 b/src/functions/assert/General/Assert-Same.ps1 index 4dc699a29..1312f0924 100644 --- a/src/functions/assert/General/Assert-Same.ps1 +++ b/src/functions/assert/General/Assert-Same.ps1 @@ -1,20 +1,19 @@ function Assert-Same { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( - [Parameter(Position=1, ValueFromPipeline=$true)] + [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position=0)] + [Parameter(Position = 0)] $Expected, [String]$CustomMessage ) - if ($Expected -is [ValueType] -or $Expected -is [string]) - { + if ($Expected -is [ValueType] -or $Expected -is [string]) { throw [ArgumentException]"Assert-Same compares objects by reference. You provided a value type or a string, those are not reference types and you most likely don't need to compare them by reference, see https://github.com/nohwnd/Assert/issues/6.`n`nAre you trying to compare two values to see if they are equal? Use Assert-Equal instead." } - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input - if (-not ([object]::ReferenceEquals($Expected, $Actual))) - { + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + if (-not ([object]::ReferenceEquals($Expected, $Actual))) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '', to be the same instance but it was not." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Assert-Type.ps1 b/src/functions/assert/General/Assert-Type.ps1 index 81f9543ff..4827a7a44 100644 --- a/src/functions/assert/General/Assert-Type.ps1 +++ b/src/functions/assert/General/Assert-Type.ps1 @@ -1,4 +1,5 @@ function Assert-Type { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, @@ -7,7 +8,7 @@ [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput if ($Actual -isnot $Expected) { $type = [string]$Expected $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected value to be of type '$type', but got '' of type ''." diff --git a/src/functions/assert/String/Assert-Like.ps1 b/src/functions/assert/String/Assert-Like.ps1 index b21571956..e5cfb7a02 100644 --- a/src/functions/assert/String/Assert-Like.ps1 +++ b/src/functions/assert/String/Assert-Like.ps1 @@ -22,6 +22,7 @@ function Get-LikeDefaultFailureMessage ([String]$Expected, $Actual, [switch]$Cas } function Assert-Like { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, @@ -31,7 +32,7 @@ function Assert-Like { [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput if ($Actual -isnot [string]) { throw [ArgumentException]"Actual is expected to be string, to avoid confusing behavior that -like operator exhibits with collections. To assert on collections use Assert-Any, Assert-All or some other collection assertion." diff --git a/src/functions/assert/String/Assert-NotLike.ps1 b/src/functions/assert/String/Assert-NotLike.ps1 index 804de4187..9214117ef 100644 --- a/src/functions/assert/String/Assert-NotLike.ps1 +++ b/src/functions/assert/String/Assert-NotLike.ps1 @@ -22,6 +22,7 @@ function Get-NotLikeDefaultFailureMessage ([String]$Expected, $Actual, [switch]$ } function Assert-NotLike { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, @@ -31,7 +32,7 @@ function Assert-NotLike { [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput if ($Actual -isnot [string]) { throw [ArgumentException]"Actual is expected to be string, to avoid confusing behavior that -like operator exhibits with collections. To assert on collections use Assert-Any, Assert-All or some other collection assertion." diff --git a/src/functions/assert/String/Assert-StringEqual.ps1 b/src/functions/assert/String/Assert-StringEqual.ps1 index 73996fd80..72850209b 100644 --- a/src/functions/assert/String/Assert-StringEqual.ps1 +++ b/src/functions/assert/String/Assert-StringEqual.ps1 @@ -24,6 +24,7 @@ function Get-StringEqualDefaultFailureMessage ([String]$Expected, $Actual) { } function Assert-StringEqual { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, @@ -34,7 +35,7 @@ function Assert-StringEqual { [switch]$IgnoreWhitespace ) - $_actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input + $_actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput if (-not $CustomMessage) { $formattedMessage = Get-StringEqualDefaultFailureMessage -Expected $Expected -Actual $_actual diff --git a/src/functions/assert/String/Assert-StringNotEqual.ps1 b/src/functions/assert/String/Assert-StringNotEqual.ps1 index 277c667f7..a47c83b6e 100644 --- a/src/functions/assert/String/Assert-StringNotEqual.ps1 +++ b/src/functions/assert/String/Assert-StringNotEqual.ps1 @@ -3,6 +3,7 @@ } function Assert-StringNotEqual { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, From 50182d9d7c3ffd3c515f50af7b051a5f4f8d08cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Sun, 7 Apr 2024 21:07:08 +0200 Subject: [PATCH 08/55] wip --- src/functions/assert/Common/Collect-Input.ps1 | 15 ++++- .../assert/Common/Collect-Input.Tests.ps1 | 62 +++++++++++++++++++ 2 files changed, 75 insertions(+), 2 deletions(-) create mode 100644 tst/functions/assert/Common/Collect-Input.Tests.ps1 diff --git a/src/functions/assert/Common/Collect-Input.ps1 b/src/functions/assert/Common/Collect-Input.ps1 index ab2facc29..d10433d85 100644 --- a/src/functions/assert/Common/Collect-Input.ps1 +++ b/src/functions/assert/Common/Collect-Input.ps1 @@ -1,8 +1,19 @@ function Collect-Input ($ParameterInput, $PipelineInput, $IsInPipeline) { if ($IsInPipeline) { - $PipelineInput + # We are called like this: 1 | Assert-Equal -Expected 1, we will get $local:Input in $PipelineInput and $true in $IsInPipeline (coming from $MyInvocation.ExpectingInput). + + if ($PipelineInput.Count -eq 0) { + # When calling @() | Assert-Equal -Expected 1, the engine will special case it, and we will get empty array $local:Input, fix that + # by returning empty array wrapped in array. + , @() + } + else { + # This is array of all the input, when we output it, the function will unwrap it. So we get the raw input on the output. + $PipelineInput + } } else { - $ParameterInput + # This is exactly what was provided to the ActualParmeter, wrap it in array so the function return can unwrap it. + , $ParameterInput } } diff --git a/tst/functions/assert/Common/Collect-Input.Tests.ps1 b/tst/functions/assert/Common/Collect-Input.Tests.ps1 new file mode 100644 index 000000000..1cccba7ed --- /dev/null +++ b/tst/functions/assert/Common/Collect-Input.Tests.ps1 @@ -0,0 +1,62 @@ +Set-StrictMode -Version Latest + +InPesterModuleScope { + Describe "Collect-Input" { + BeforeAll { + function Assert-PassThru { + # This is how all Assert-* functions look inside, here we just collect $Actual and return it. + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] + param ( + [Parameter(ValueFromPipeline = $true)] + $Actual + ) + + + $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + + $Actual + } + } + + It "Given `$null through pipeline it returns `$null" { + $in = $null | Assert-PassThru + + Verify-True ($null -eq $in) + } + + It "Given @() through pipeline it returns array with 0 items" { + $in = @() | Assert-PassThru + + Verify-True ($in.GetType().Name -eq 'Object[]') + Verify-True ($in.Count -eq 0) + } + + It "Given @() through pipeline it returns array with 0 items" { + $in = Assert-PassThru -Actual @() + + Verify-True ($in.GetType().Name -eq 'Object[]') + Verify-True ($in.Count -eq 0) + } + + It "Given @() through pipeline it returns array with 0 items" { + $in = Assert-PassThru -Actual $null + + Verify-True ($in.GetType().Name -eq 'Object[]') + Verify-True ($in.Count -eq 0) + } + + It "Given @() through pipeline it returns array with 0 items" { + $in = Assert-PassThru -Actual 1, 2 + + Verify-True ($in.GetType().Name -eq 'Object[]') + Verify-True ($in.Count -eq 0) + } + + It "Given @() through pipeline it returns array with 0 items" { + $in = 1, 2 | Assert-PassThru + + Verify-True ($in.GetType().Name -eq 'Object[]') + Verify-True ($in.Count -eq 0) + } + } +} From 333417c90a12688343f362a384dea921978f5b9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Sun, 7 Apr 2024 22:48:01 +0200 Subject: [PATCH 09/55] Fix input collecting --- src/functions/assert/Boolean/Assert-False.ps1 | 8 +- src/functions/assert/Boolean/Assert-True.ps1 | 3 +- .../assert/Collection/Assert-All.ps1 | 3 +- .../assert/Collection/Assert-Any.ps1 | 3 +- .../assert/Collection/Assert-Contain.ps1 | 3 +- .../assert/Collection/Assert-NotContain.ps1 | 3 +- src/functions/assert/Common/Collect-Input.ps1 | 25 +++-- .../assert/Exception/Assert-Throw.ps1 | 3 +- src/functions/assert/General/Assert-Equal.ps1 | 3 +- .../assert/General/Assert-GreaterThan.ps1 | 3 +- .../General/Assert-GreaterThanOrEqual.ps1 | 3 +- .../assert/General/Assert-LessThan.ps1 | 3 +- .../assert/General/Assert-LessThanOrEqual.ps1 | 3 +- .../assert/General/Assert-NotEqual.ps1 | 3 +- .../assert/General/Assert-NotNull.ps1 | 3 +- .../assert/General/Assert-NotSame.ps1 | 3 +- .../assert/General/Assert-NotType.ps1 | 3 +- src/functions/assert/General/Assert-Null.ps1 | 3 +- src/functions/assert/General/Assert-Same.ps1 | 3 +- src/functions/assert/General/Assert-Type.ps1 | 3 +- src/functions/assert/String/Assert-Like.ps1 | 3 +- .../assert/String/Assert-NotLike.ps1 | 3 +- .../assert/String/Assert-StringEqual.ps1 | 9 +- .../assert/Common/Collect-Input.Tests.ps1 | 99 +++++++++++++------ .../assert/General/Assert-Null.Tests.ps1 | 10 +- 25 files changed, 142 insertions(+), 69 deletions(-) diff --git a/src/functions/assert/Boolean/Assert-False.ps1 b/src/functions/assert/Boolean/Assert-False.ps1 index 27a84c884..fb5230d19 100644 --- a/src/functions/assert/Boolean/Assert-False.ps1 +++ b/src/functions/assert/Boolean/Assert-False.ps1 @@ -1,14 +1,14 @@ function Assert-False { [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( - [Parameter(ValueFromPipeline=$true)] + [Parameter(ValueFromPipeline = $true)] $Actual, [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput - if ($Actual) - { + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual + if ($Actual) { $Message = Get-AssertionMessage -Expected $false -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be '' or falsy value 0, """", `$null, @()." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/Boolean/Assert-True.ps1 b/src/functions/assert/Boolean/Assert-True.ps1 index 5080ab2b5..bae30fc50 100644 --- a/src/functions/assert/Boolean/Assert-True.ps1 +++ b/src/functions/assert/Boolean/Assert-True.ps1 @@ -6,7 +6,8 @@ [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual if (-not $Actual) { $Message = Get-AssertionMessage -Expected $true -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be '' or truthy value." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) diff --git a/src/functions/assert/Collection/Assert-All.ps1 b/src/functions/assert/Collection/Assert-All.ps1 index 8b14f136e..8f7dcb22f 100644 --- a/src/functions/assert/Collection/Assert-All.ps1 +++ b/src/functions/assert/Collection/Assert-All.ps1 @@ -11,7 +11,8 @@ $Expected = $FilterScript - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual # we are jumping between modules so I need to explicitly pass the _ variable # simply using '&' won't work # see: https://blogs.msdn.microsoft.com/sergey_babkins_blog/2014/10/30/calling-the-script-blocks-in-powershell/ diff --git a/src/functions/assert/Collection/Assert-Any.ps1 b/src/functions/assert/Collection/Assert-Any.ps1 index 8f0512c7f..90b37d342 100644 --- a/src/functions/assert/Collection/Assert-Any.ps1 +++ b/src/functions/assert/Collection/Assert-Any.ps1 @@ -9,7 +9,8 @@ ) $Expected = $FilterScript - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual if (-not ($Actual | & $SafeCommands['Where-Object'] -FilterScript $FilterScript)) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected at least one item in collection '' to pass filter '', but none of the items passed the filter." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) diff --git a/src/functions/assert/Collection/Assert-Contain.ps1 b/src/functions/assert/Collection/Assert-Contain.ps1 index 616263c36..233e365cd 100644 --- a/src/functions/assert/Collection/Assert-Contain.ps1 +++ b/src/functions/assert/Collection/Assert-Contain.ps1 @@ -8,7 +8,8 @@ [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual if ($Actual -notcontains $Expected) { $type = [string]$Expected diff --git a/src/functions/assert/Collection/Assert-NotContain.ps1 b/src/functions/assert/Collection/Assert-NotContain.ps1 index d62721589..f582d310f 100644 --- a/src/functions/assert/Collection/Assert-NotContain.ps1 +++ b/src/functions/assert/Collection/Assert-NotContain.ps1 @@ -8,7 +8,8 @@ [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual if ($Actual -contains $Expected) { $type = [string]$Expected diff --git a/src/functions/assert/Common/Collect-Input.ps1 b/src/functions/assert/Common/Collect-Input.ps1 index d10433d85..8f7880e89 100644 --- a/src/functions/assert/Common/Collect-Input.ps1 +++ b/src/functions/assert/Common/Collect-Input.ps1 @@ -1,19 +1,24 @@ -function Collect-Input ($ParameterInput, $PipelineInput, $IsInPipeline) { - if ($IsInPipeline) { - # We are called like this: 1 | Assert-Equal -Expected 1, we will get $local:Input in $PipelineInput and $true in $IsInPipeline (coming from $MyInvocation.ExpectingInput). +function Collect-Input ($ParameterInput, $PipelineInput, $IsPipelineInput) { + if ($IsPipelineInput) { + # We are called like this: 1 | Assert-Equal -Expected 1, we will get $local:Input in $PipelineInput and $true in $IsPipelineInput (coming from $MyInvocation.ExpectingInput). if ($PipelineInput.Count -eq 0) { - # When calling @() | Assert-Equal -Expected 1, the engine will special case it, and we will get empty array $local:Input, fix that - # by returning empty array wrapped in array. - , @() + # When calling @() | Assert-Equal -Expected 1, the engine will special case it, and we will get empty array in $local:Input + $collectedInput = @() } else { - # This is array of all the input, when we output it, the function will unwrap it. So we get the raw input on the output. - $PipelineInput + # This is array of all the input, unwrap it. + $collectedInput = foreach ($item in $PipelineInput) { $item } } } else { - # This is exactly what was provided to the ActualParmeter, wrap it in array so the function return can unwrap it. - , $ParameterInput + # This is exactly what was provided to the ActualParmeter. + $collectedInput = $ParameterInput + } + + @{ + Actual = $collectedInput + # We can use this to determine if collections are comparable. Pipeline input will unwind the collection, so pipeline input collection type is not comparable. + IsPipelineInput = $IsPipelineInput } } diff --git a/src/functions/assert/Exception/Assert-Throw.ps1 b/src/functions/assert/Exception/Assert-Throw.ps1 index 7043748f2..023e74329 100644 --- a/src/functions/assert/Exception/Assert-Throw.ps1 +++ b/src/functions/assert/Exception/Assert-Throw.ps1 @@ -10,7 +10,8 @@ function Assert-Throw { [String]$CustomMessage ) - $ScriptBlock = Collect-Input -ParameterInput $ScriptBlock -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $ScriptBlock -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $ScriptBlock = $collectedInput.Actual $errorThrown = $false $err = $null diff --git a/src/functions/assert/General/Assert-Equal.ps1 b/src/functions/assert/General/Assert-Equal.ps1 index 62a63ba48..afbd8948f 100644 --- a/src/functions/assert/General/Assert-Equal.ps1 +++ b/src/functions/assert/General/Assert-Equal.ps1 @@ -8,7 +8,8 @@ [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual if ((Ensure-ExpectedIsNotCollection $Expected) -ne $Actual) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '', but got ''." diff --git a/src/functions/assert/General/Assert-GreaterThan.ps1 b/src/functions/assert/General/Assert-GreaterThan.ps1 index dd85c2685..5d3f8fbbd 100644 --- a/src/functions/assert/General/Assert-GreaterThan.ps1 +++ b/src/functions/assert/General/Assert-GreaterThan.ps1 @@ -8,7 +8,8 @@ [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual if ((Ensure-ExpectedIsNotCollection $Expected) -ge $Actual) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be greater than '', but it was not." diff --git a/src/functions/assert/General/Assert-GreaterThanOrEqual.ps1 b/src/functions/assert/General/Assert-GreaterThanOrEqual.ps1 index b6979c417..2cbafa627 100644 --- a/src/functions/assert/General/Assert-GreaterThanOrEqual.ps1 +++ b/src/functions/assert/General/Assert-GreaterThanOrEqual.ps1 @@ -8,7 +8,8 @@ [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual if ((Ensure-ExpectedIsNotCollection $Expected) -gt $Actual) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be greater than or equal to '', but it was not." diff --git a/src/functions/assert/General/Assert-LessThan.ps1 b/src/functions/assert/General/Assert-LessThan.ps1 index 414a71a07..336f29dbf 100644 --- a/src/functions/assert/General/Assert-LessThan.ps1 +++ b/src/functions/assert/General/Assert-LessThan.ps1 @@ -8,7 +8,8 @@ [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual if ((Ensure-ExpectedIsNotCollection $Expected) -le $Actual) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be less than '', but it was not." diff --git a/src/functions/assert/General/Assert-LessThanOrEqual.ps1 b/src/functions/assert/General/Assert-LessThanOrEqual.ps1 index c9e9c8066..7a3f00bdb 100644 --- a/src/functions/assert/General/Assert-LessThanOrEqual.ps1 +++ b/src/functions/assert/General/Assert-LessThanOrEqual.ps1 @@ -8,7 +8,8 @@ [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual if ((Ensure-ExpectedIsNotCollection $Expected) -lt $Actual) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be less than or equal to '', but it was not." diff --git a/src/functions/assert/General/Assert-NotEqual.ps1 b/src/functions/assert/General/Assert-NotEqual.ps1 index c2280e702..60400a07a 100644 --- a/src/functions/assert/General/Assert-NotEqual.ps1 +++ b/src/functions/assert/General/Assert-NotEqual.ps1 @@ -8,7 +8,8 @@ [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual if ((Ensure-ExpectedIsNotCollection $Expected) -eq $Actual) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '', to be different than the actual value, but they were the same." diff --git a/src/functions/assert/General/Assert-NotNull.ps1 b/src/functions/assert/General/Assert-NotNull.ps1 index ba0936d58..5b9605a97 100644 --- a/src/functions/assert/General/Assert-NotNull.ps1 +++ b/src/functions/assert/General/Assert-NotNull.ps1 @@ -6,7 +6,8 @@ [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual if ($null -eq $Actual) { $Message = Get-AssertionMessage -Expected $null -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected not `$null, but got `$null." diff --git a/src/functions/assert/General/Assert-NotSame.ps1 b/src/functions/assert/General/Assert-NotSame.ps1 index 15a0eeb1c..e83b90446 100644 --- a/src/functions/assert/General/Assert-NotSame.ps1 +++ b/src/functions/assert/General/Assert-NotSame.ps1 @@ -8,7 +8,8 @@ [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual if ([object]::ReferenceEquals($Expected, $Actual)) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '', to not be the same instance." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) diff --git a/src/functions/assert/General/Assert-NotType.ps1 b/src/functions/assert/General/Assert-NotType.ps1 index c8be106c6..de4858d94 100644 --- a/src/functions/assert/General/Assert-NotType.ps1 +++ b/src/functions/assert/General/Assert-NotType.ps1 @@ -8,7 +8,8 @@ [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual if ($Actual -is $Expected) { $type = [string]$Expected $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected value to be of different type than '$type', but got '' of type ''." diff --git a/src/functions/assert/General/Assert-Null.ps1 b/src/functions/assert/General/Assert-Null.ps1 index 1622d3c47..20c914690 100644 --- a/src/functions/assert/General/Assert-Null.ps1 +++ b/src/functions/assert/General/Assert-Null.ps1 @@ -6,7 +6,8 @@ [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual if ($null -ne $Actual) { $Message = Get-AssertionMessage -Expected $null -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected `$null, but got ''." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) diff --git a/src/functions/assert/General/Assert-Same.ps1 b/src/functions/assert/General/Assert-Same.ps1 index 1312f0924..c64cd6a27 100644 --- a/src/functions/assert/General/Assert-Same.ps1 +++ b/src/functions/assert/General/Assert-Same.ps1 @@ -12,7 +12,8 @@ throw [ArgumentException]"Assert-Same compares objects by reference. You provided a value type or a string, those are not reference types and you most likely don't need to compare them by reference, see https://github.com/nohwnd/Assert/issues/6.`n`nAre you trying to compare two values to see if they are equal? Use Assert-Equal instead." } - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual if (-not ([object]::ReferenceEquals($Expected, $Actual))) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '', to be the same instance but it was not." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) diff --git a/src/functions/assert/General/Assert-Type.ps1 b/src/functions/assert/General/Assert-Type.ps1 index 4827a7a44..4581d359c 100644 --- a/src/functions/assert/General/Assert-Type.ps1 +++ b/src/functions/assert/General/Assert-Type.ps1 @@ -8,7 +8,8 @@ [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual if ($Actual -isnot $Expected) { $type = [string]$Expected $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected value to be of type '$type', but got '' of type ''." diff --git a/src/functions/assert/String/Assert-Like.ps1 b/src/functions/assert/String/Assert-Like.ps1 index e5cfb7a02..9e8e0a59f 100644 --- a/src/functions/assert/String/Assert-Like.ps1 +++ b/src/functions/assert/String/Assert-Like.ps1 @@ -32,7 +32,8 @@ function Assert-Like { [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual if ($Actual -isnot [string]) { throw [ArgumentException]"Actual is expected to be string, to avoid confusing behavior that -like operator exhibits with collections. To assert on collections use Assert-Any, Assert-All or some other collection assertion." diff --git a/src/functions/assert/String/Assert-NotLike.ps1 b/src/functions/assert/String/Assert-NotLike.ps1 index 9214117ef..50a770b01 100644 --- a/src/functions/assert/String/Assert-NotLike.ps1 +++ b/src/functions/assert/String/Assert-NotLike.ps1 @@ -32,7 +32,8 @@ function Assert-NotLike { [String]$CustomMessage ) - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual if ($Actual -isnot [string]) { throw [ArgumentException]"Actual is expected to be string, to avoid confusing behavior that -like operator exhibits with collections. To assert on collections use Assert-Any, Assert-All or some other collection assertion." diff --git a/src/functions/assert/String/Assert-StringEqual.ps1 b/src/functions/assert/String/Assert-StringEqual.ps1 index 72850209b..04d37a92e 100644 --- a/src/functions/assert/String/Assert-StringEqual.ps1 +++ b/src/functions/assert/String/Assert-StringEqual.ps1 @@ -35,16 +35,17 @@ function Assert-StringEqual { [switch]$IgnoreWhitespace ) - $_actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual if (-not $CustomMessage) { - $formattedMessage = Get-StringEqualDefaultFailureMessage -Expected $Expected -Actual $_actual + $formattedMessage = Get-StringEqualDefaultFailureMessage -Expected $Expected -Actual $Actual } else { - $formattedMessage = Get-CustomFailureMessage -Expected $Expected -Actual $_actual -CustomMessage $CustomMessage + $formattedMessage = Get-CustomFailureMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage } - $stringsAreEqual = Test-StringEqual -Expected $Expected -Actual $_actual -CaseSensitive:$CaseSensitive -IgnoreWhitespace:$IgnoreWhiteSpace + $stringsAreEqual = Test-StringEqual -Expected $Expected -Actual $Actual -CaseSensitive:$CaseSensitive -IgnoreWhitespace:$IgnoreWhiteSpace if (-not ($stringsAreEqual)) { throw [Pester.Factory]::CreateShouldErrorRecord($formattedMessage, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/tst/functions/assert/Common/Collect-Input.Tests.ps1 b/tst/functions/assert/Common/Collect-Input.Tests.ps1 index 1cccba7ed..287a21c0f 100644 --- a/tst/functions/assert/Common/Collect-Input.Tests.ps1 +++ b/tst/functions/assert/Common/Collect-Input.Tests.ps1 @@ -11,52 +11,91 @@ InPesterModuleScope { $Actual ) + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $collectedInput + } + } - $Actual = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsInPipeline $MyInvocation.ExpectingInput + Describe "Pipeline input" { + It "Given `$null through pipeline it captures `$null" { + $collectedInput = $null | Assert-PassThru - $Actual + Verify-True $collectedInput.IsPipelineInput + if ($null -ne $collectedInput.Actual) { + throw "Expected `$null, but got $(Format-Nicely2 $collectedInput.Actual)." + } } - } - It "Given `$null through pipeline it returns `$null" { - $in = $null | Assert-PassThru + It "Given @() through pipeline it captures @()" { + $collectedInput = @() | Assert-PassThru - Verify-True ($null -eq $in) - } + Verify-True $collectedInput.IsPipelineInput + Verify-Type -Actual $collectedInput.Actual -Expected ([Object[]]) + if (@() -ne $collectedInput.Actual) { + throw "Expected @(), but got $(Format-Nicely2 $collectedInput.Actual)." + } + } - It "Given @() through pipeline it returns array with 0 items" { - $in = @() | Assert-PassThru + It "Given List[int] through pipeline it captures the items in Object[]" { + $collectedInput = [Collections.Generic.List[int]]@(1, 2) | Assert-PassThru - Verify-True ($in.GetType().Name -eq 'Object[]') - Verify-True ($in.Count -eq 0) - } + Verify-True $collectedInput.IsPipelineInput + Verify-Type -Actual $collectedInput.Actual -Expected ([Object[]]) + if (1 -ne $collectedInput.Actual[0] -or 2 -ne $collectedInput.Actual[1]) { + throw "Expected @(1, 2), but got $(Format-Nicely2 $collectedInput.Actual)." + } + } - It "Given @() through pipeline it returns array with 0 items" { - $in = Assert-PassThru -Actual @() + It "Given 1,2 through pipeline it captures the items" { + $collectedInput = 1, 2 | Assert-PassThru - Verify-True ($in.GetType().Name -eq 'Object[]') - Verify-True ($in.Count -eq 0) + Verify-True $collectedInput.IsPipelineInput + Verify-Type -Actual $collectedInput.Actual -Expected ([Object[]]) + if (1 -ne $collectedInput.Actual[0] -or 2 -ne $collectedInput.Actual[1]) { + throw "Expected @(1, 2), but got $(Format-Nicely2 $collectedInput.Actual)." + } + } } - It "Given @() through pipeline it returns array with 0 items" { - $in = Assert-PassThru -Actual $null + Describe "Parameter input" { + It "Given `$null through parameter it captures `$null" { + $collectedInput = Assert-PassThru -Actual $null - Verify-True ($in.GetType().Name -eq 'Object[]') - Verify-True ($in.Count -eq 0) - } + Verify-False $collectedInput.IsPipelineInput + if ($null -ne $collectedInput.Actual) { + throw "Expected `$null, but got $(Format-Nicely2 $collectedInput.Actual)." + } + } - It "Given @() through pipeline it returns array with 0 items" { - $in = Assert-PassThru -Actual 1, 2 + It "Given @() through parameter it captures @()" { + $collectedInput = Assert-PassThru -Actual @() - Verify-True ($in.GetType().Name -eq 'Object[]') - Verify-True ($in.Count -eq 0) - } + Verify-False $collectedInput.IsPipelineInput + Verify-Type -Actual $collectedInput.Actual -Expected ([Object[]]) + if (@() -ne $collectedInput.Actual) { + throw "Expected @(), but got $(Format-Nicely2 $collectedInput.Actual)." + } + } - It "Given @() through pipeline it returns array with 0 items" { - $in = 1, 2 | Assert-PassThru + It "Given List[int] through parameter it captures the List" { + $collectedInput = Assert-PassThru -Actual ([Collections.Generic.List[int]]@(1, 2)) - Verify-True ($in.GetType().Name -eq 'Object[]') - Verify-True ($in.Count -eq 0) + Verify-False $collectedInput.IsPipelineInput + Verify-Type -Actual $collectedInput.Actual -Expected ([Collections.Generic.List[int]]) + if (1 -ne $collectedInput.Actual[0] -or 2 -ne $collectedInput.Actual[1]) { + throw "Expected List(1, 2), but got $(Format-Nicely2 $collectedInput.Actual)." + } + } + + It "Given 1,2 through parameter it captures the items" { + $collectedInput = Assert-PassThru -Actual 1, 2 + + Verify-False $collectedInput.IsPipelineInput + Verify-Type -Actual $collectedInput.Actual -Expected ([Object[]]) + if (1 -ne $collectedInput.Actual[0] -or 2 -ne $collectedInput.Actual[1]) { + throw "Expected @(1, 2), but got $(Format-Nicely2 $collectedInput.Actual)." + } + } } } } diff --git a/tst/functions/assert/General/Assert-Null.Tests.ps1 b/tst/functions/assert/General/Assert-Null.Tests.ps1 index 32bf7f3ee..7343aeb2a 100644 --- a/tst/functions/assert/General/Assert-Null.Tests.ps1 +++ b/tst/functions/assert/General/Assert-Null.Tests.ps1 @@ -10,12 +10,20 @@ InPesterModuleScope { { 1 | Assert-Null } | Verify-AssertionFailed } + It "Given empty array it fails" { + { @() | Assert-Null } | Verify-AssertionFailed + } + It "Returns the given value" { $null | Assert-Null | Verify-Null } - It "Can be called with positional parameters" { + It "Can be called with positional parameters (1)" { { Assert-Null 1 } | Verify-AssertionFailed } + + It "Can be called with positional parameters (@())" { + { Assert-Null @() } | Verify-AssertionFailed + } } } From 0230d8cfda6537dfb2e5fb7bf943c8929f399b2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Sun, 7 Apr 2024 22:58:47 +0200 Subject: [PATCH 10/55] Remove Compatibility.ps1 --- build.ps1 | 2 -- src/Format2.ps1 | 4 ++-- src/functions/assert/Compatibility.ps1 | 21 ------------------- .../assert/Equivalence/Assert-Equivalent.ps1 | 18 ++++++++-------- .../assert/Exception/Assert-Throw.ps1 | 4 ++-- 5 files changed, 13 insertions(+), 36 deletions(-) delete mode 100644 src/functions/assert/Compatibility.ps1 diff --git a/build.ps1 b/build.ps1 index 0f48d5791..19743608f 100644 --- a/build.ps1 +++ b/build.ps1 @@ -282,8 +282,6 @@ $script = @( "$PSScriptRoot/src/Pester.RSpec.ps1" "$PSScriptRoot/src/Main.ps1" - # TODO: Imports Compatibility.ps1, remove the code that is there, because it is for PowerShell 2.0 compatibility! - "$PSScriptRoot/src/functions/assert/*" "$PSScriptRoot/src/functions/assert/*/*" "$PSScriptRoot/src/functions/assertions/*" "$PSScriptRoot/src/functions/*" diff --git a/src/Format2.ps1 b/src/Format2.ps1 index 0c8c08197..a6cfa50fd 100644 --- a/src/Format2.ps1 +++ b/src/Format2.ps1 @@ -112,7 +112,7 @@ function Format-Nicely2 ($Value, [switch]$Pretty) { return Format-Collection2 -Value $Value -Pretty:$Pretty } - Format-Object2 -Value $Value -Property (Get-DisplayProperty2 (Get-Type $Value)) -Pretty:$Pretty + Format-Object2 -Value $Value -Property (Get-DisplayProperty2 $Value.GetType()) -Pretty:$Pretty } function Get-DisplayProperty2 ([Type]$Type) { @@ -139,7 +139,7 @@ function Get-DisplayProperty2 ([Type]$Type) { function Get-ShortType2 ($Value) { if ($null -ne $value) { - Format-Type2 (Get-Type $Value) + Format-Type2 $Value.GetType() } else { Format-Type2 $null diff --git a/src/functions/assert/Compatibility.ps1 b/src/functions/assert/Compatibility.ps1 deleted file mode 100644 index 9b03aaf45..000000000 --- a/src/functions/assert/Compatibility.ps1 +++ /dev/null @@ -1,21 +0,0 @@ - -function Test-NullOrWhiteSpace ($Value) { - # psv2 compatibility, on newer .net we would simply use - # [string]::isnullorwhitespace - $null -eq $Value -or $Value -match "^\s*$" -} - -function Get-Type ($InputObject) { - try { - $ErrorActionPreference = 'Stop' - # normally this would not ever throw - # but in psv2 when datatable is deserialized then - # [Deserialized.System.Data.DataTable] does not contain - # .GetType() - $InputObject.GetType() - } - catch [Exception] { - return [Object] - } - -} diff --git a/src/functions/assert/Equivalence/Assert-Equivalent.ps1 b/src/functions/assert/Equivalence/Assert-Equivalent.ps1 index e03d4db24..a3b2f39f5 100644 --- a/src/functions/assert/Equivalence/Assert-Equivalent.ps1 +++ b/src/functions/assert/Equivalence/Assert-Equivalent.ps1 @@ -56,7 +56,7 @@ function Compare-CollectionEquivalent ($Expected, $Actual, $Property, $Options) } if (-not (Is-Collection -Value $Actual)) { - v -Difference "`$Actual is not a collection it is a $(Format-Nicely2 (Get-Type $Actual)), so they are not equivalent." + v -Difference "`$Actual is not a collection it is a $(Format-Nicely2 $Actual.GetType()), so they are not equivalent." $expectedFormatted = Format-Collection2 -Value $Expected $expectedLength = $expected.Length $actualFormatted = Format-Nicely2 -Value $actual @@ -240,9 +240,9 @@ function Compare-ValueEquivalent ($Actual, $Expected, $Property, $Options) { v "Equality comparator is used, values will be compared for equality." } - v "Comparing values as $(Format-Nicely2 (Get-Type $Expected)) because `$Expected has that type." + v "Comparing values as $(Format-Nicely2 $Expected.GetType()) because `$Expected has that type." # todo: shorter messages when both sides have the same type (do not compare by using -is, instead query the type and compare it) because -is is true even for parent types - $type = Get-Type $Expected + $type = $Expected.GetType() $coalescedActual = $Actual -as $type if ($Expected -ne $Actual) { v -Difference "`$Actual is not equivalent to $(Format-Nicely2 $Expected) because it is $(Format-Nicely2 $Actual), and $(Format-Nicely2 $Actual) coalesced to $(Format-Nicely2 $type) is $(Format-Nicely2 $coalescedActual)." @@ -257,7 +257,7 @@ function Compare-HashtableEquivalent ($Actual, $Expected, $Property, $Options) { } if (-not (Is-Hashtable -Value $Actual)) { - v -Difference "`$Actual is not a hashtable it is a $(Format-Nicely2 (Get-Type $Actual)), so they are not equivalent." + v -Difference "`$Actual is not a hashtable it is a $(Format-Nicely2 $Actual.GetType()), so they are not equivalent." $expectedFormatted = Format-Nicely2 -Value $Expected $actualFormatted = Format-Nicely2 -Value $Actual return "Expected hashtable '$expectedFormatted', but got '$actualFormatted'." @@ -323,7 +323,7 @@ function Compare-DictionaryEquivalent ($Actual, $Expected, $Property, $Options) } if (-not (Is-Dictionary -Value $Actual)) { - v -Difference "`$Actual is not a dictionary it is a $(Format-Nicely2 (Get-Type $Actual)), so they are not equivalent." + v -Difference "`$Actual is not a dictionary it is a $(Format-Nicely2 $Actual.GetType()), so they are not equivalent." $expectedFormatted = Format-Nicely2 -Value $Expected $actualFormatted = Format-Nicely2 -Value $Actual return "Expected dictionary '$expectedFormatted', but got '$actualFormatted'." @@ -387,7 +387,7 @@ function Compare-ObjectEquivalent ($Actual, $Expected, $Property, $Options) { } if (-not (Is-Object -Value $Actual)) { - v -Difference "`$Actual is not an object it is a $(Format-Nicely2 (Get-Type $Actual)), so they are not equivalent." + v -Difference "`$Actual is not an object it is a $(Format-Nicely2 $Actual.GetType()), so they are not equivalent." $expectedFormatted = Format-Nicely2 -Value $Expected $actualFormatted = Format-Nicely2 -Value $Actual return "Expected object '$expectedFormatted', but got '$actualFormatted'." @@ -553,11 +553,11 @@ function Compare-Equivalent { } if ($null -eq $Actual) { - v -Difference "`$Actual is $(Format-Nicely2), but `$Expected has value of type $(Format-Nicely2 (Get-Type $Expected)), so they are not equivalent." + v -Difference "`$Actual is $(Format-Nicely2), but `$Expected has value of type $(Format-Nicely2 $Expected.GetType()), so they are not equivalent." return Get-ValueNotEquivalentMessage -Expected $Expected -Actual $Actual -Property $Path } - v "`$Expected has type $(Get-Type $Expected), `$Actual has type $(Get-Type $Actual), they are both non-null." + v "`$Expected has type $$Expected.GetType(), `$Actual has type $$Actual.GetType(), they are both non-null." # test value types, strings, and single item arrays with values in them as values # expand the single item array to get to the value in it @@ -609,7 +609,7 @@ function Compare-Equivalent { return } - v "`$Expected is an object of type $(Get-Type $Expected), we will be comparing `$Actual to objects." + v "`$Expected is an object of type $$Expected.GetType(), we will be comparing `$Actual to objects." Compare-ObjectEquivalent -Expected $Expected -Actual $Actual -Property $Path -Options $Options } diff --git a/src/functions/assert/Exception/Assert-Throw.ps1 b/src/functions/assert/Exception/Assert-Throw.ps1 index 023e74329..438900903 100644 --- a/src/functions/assert/Exception/Assert-Throw.ps1 +++ b/src/functions/assert/Exception/Assert-Throw.ps1 @@ -45,7 +45,7 @@ function Assert-Throw { } } - $filterOnMessage = -not (Test-NullOrWhiteSpace $ExceptionMessage) + $filterOnMessage = -not ([string]::IsNullOrWhiteSpace($ExceptionMessage)) if ($filterOnMessage) { $filters += "with message '$ExceptionMessage'" if ($err.ExceptionMessage -notlike $ExceptionMessage) { @@ -53,7 +53,7 @@ function Assert-Throw { } } - $filterOnId = -not (Test-NullOrWhiteSpace $FullyQualifiedErrorId) + $filterOnId = -not ([string]::IsNullOrWhiteSpace($FullyQualifiedErrorId)) if ($filterOnId) { $filters += "with FullyQualifiedErrorId '$FullyQualifiedErrorId'" if ($err.FullyQualifiedErrorId -notlike $FullyQualifiedErrorId) { From 3d1d89643bae536ed10b3ad85e6b1cb634042674 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Sun, 7 Apr 2024 23:16:23 +0200 Subject: [PATCH 11/55] Add Should-* aliases --- src/Module.ps1 | 55 +++++++++++++++++++++++++++++++++++++++++++++++-- src/Pester.psd1 | 27 +++++++++++++++++++++++- 2 files changed, 79 insertions(+), 3 deletions(-) diff --git a/src/Module.ps1 b/src/Module.ps1 index c0cf869c0..ee55b8b44 100644 --- a/src/Module.ps1 +++ b/src/Module.ps1 @@ -5,8 +5,33 @@ $script:SafeCommands['Get-MockDynamicParameter'] = $ExecutionContext.SessionStat $script:SafeCommands['Write-PesterDebugMessage'] = $ExecutionContext.SessionState.InvokeCommand.GetCommand('Write-PesterDebugMessage', 'function') $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.SessionState.InvokeCommand.GetCommand('Set-DynamicParameterVariable', 'function') -& $SafeCommands['Set-Alias'] 'Add-AssertionOperator' 'Add-ShouldOperator' -& $SafeCommands['Set-Alias'] 'Get-AssertionOperator' 'Get-ShouldOperator' +& $SafeCommands['Set-Alias'] 'Add-AssertionOperator' 'Add-ShouldOperator' +& $SafeCommands['Set-Alias'] 'Get-AssertionOperator' 'Get-ShouldOperator' + +& $SafeCommands['Set-Alias'] 'Should-BeFalse' 'Assert-False' +& $SafeCommands['Set-Alias'] 'Should-BeTrue' 'Assert-True' +& $SafeCommands['Set-Alias'] 'Should-All' 'Assert-All' +& $SafeCommands['Set-Alias'] 'Should-Any' 'Assert-Any' +& $SafeCommands['Set-Alias'] 'Should-Contain' 'Assert-Contain' +& $SafeCommands['Set-Alias'] 'Should-NotContain' 'Assert-NotContain' +& $SafeCommands['Set-Alias'] 'Should-BeEquivalent' 'Assert-Equivalent' +& $SafeCommands['Set-Alias'] 'Should-Throw' 'Assert-Throw' +& $SafeCommands['Set-Alias'] 'Should-BeEqual' 'Assert-Equal' +& $SafeCommands['Set-Alias'] 'Should-BeGreaterThan' 'Assert-GreaterThan' +& $SafeCommands['Set-Alias'] 'Should-BeGreaterThanOrEqual' 'Assert-GreaterThanOrEqual' +& $SafeCommands['Set-Alias'] 'Should-BeLessThan' 'Assert-LessThan' +& $SafeCommands['Set-Alias'] 'Shoulde-BeLessThanOrEqual' 'Assert-LessThanOrEqual' +& $SafeCommands['Set-Alias'] 'Should-NotBeEqual' 'Assert-NotEqual' +& $SafeCommands['Set-Alias'] 'Should-NotBeNull' 'Assert-NotNull' +& $SafeCommands['Set-Alias'] 'Should-NotBeSame' 'Assert-NotSame' +& $SafeCommands['Set-Alias'] 'Should-NotBeType' 'Assert-NotType' +& $SafeCommands['Set-Alias'] 'Should-BeNull' 'Assert-Null' +& $SafeCommands['Set-Alias'] 'Should-BeSame' 'Assert-Same' +& $SafeCommands['Set-Alias'] 'Should-BeType' 'Assert-Type' +& $SafeCommands['Set-Alias'] 'Should-BeLike' 'Assert-Like' +& $SafeCommands['Set-Alias'] 'Should-NotBeLike' 'Assert-NotLike' + + & $SafeCommands['Update-TypeData'] -TypeName PesterConfiguration -TypeConverter 'PesterConfigurationDeserializer' -SerializationDepth 5 -Force & $SafeCommands['Update-TypeData'] -TypeName 'Deserialized.PesterConfiguration' -TargetTypeForDeserialization PesterConfiguration -Force @@ -82,4 +107,30 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session ) -Alias @( 'Add-AssertionOperator' 'Get-AssertionOperator' + + # assert + 'Should-BeFalse' + 'Should-BeTrue' + 'Should-All' + 'Should-Any' + 'Should-Contain' + 'Should-NotContain' + 'Should-BeEquivalent' + 'Should-Throw' + 'Should-BeEqual' + 'Should-BeGreaterThan' + 'Should-BeGreaterThanOrEqual' + 'Should-BeLessThan' + 'Shoulde-BeLessThanOrEqual' + 'Should-NotBeEqual' + 'Should-NotBeNull' + 'Should-NotBeSame' + 'Should-NotBeType' + 'Should-BeNull' + 'Should-BeSame' + 'Should-BeType' + 'Should-BeLike' + 'Should-NotBeLike' + 'Should-StringBeEqual' + 'Should-StringNotBeEqual' ) diff --git a/src/Pester.psd1 b/src/Pester.psd1 index 4a42f5149..2e84e6a46 100644 --- a/src/Pester.psd1 +++ b/src/Pester.psd1 @@ -92,7 +92,6 @@ 'Assert-StringEqual' 'Assert-StringNotEqual' - # legacy 'Assert-VerifiableMock' 'Assert-MockCalled' @@ -112,6 +111,32 @@ AliasesToExport = @( 'Add-AssertionOperator' 'Get-AssertionOperator' + + # assert + 'Should-BeFalse' + 'Should-BeTrue' + 'Should-All' + 'Should-Any' + 'Should-Contain' + 'Should-NotContain' + 'Should-BeEquivalent' + 'Should-Throw' + 'Should-BeEqual' + 'Should-BeGreaterThan' + 'Should-BeGreaterThanOrEqual' + 'Should-BeLessThan' + 'Shoulde-BeLessThanOrEqual' + 'Should-NotBeEqual' + 'Should-NotBeNull' + 'Should-NotBeSame' + 'Should-NotBeType' + 'Should-BeNull' + 'Should-BeSame' + 'Should-BeType' + 'Should-BeLike' + 'Should-NotBeLike' + 'Should-StringBeEqual' + 'Should-StringNotBeEqual' ) From b0ffc38bb8a115422c15ffc8634685dd6d9df82d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Sun, 7 Apr 2024 23:41:23 +0200 Subject: [PATCH 12/55] Rename internal Should-* functions to Should-*Assertion to avoid conflict with nnew aliases --- src/functions/assertions/Be.ps1 | 12 ++++++------ src/functions/assertions/BeGreaterThan.ps1 | 8 ++++---- src/functions/assertions/BeIn.ps1 | 6 +++--- src/functions/assertions/BeLessThan.ps1 | 8 ++++---- src/functions/assertions/BeLike.ps1 | 6 +++--- src/functions/assertions/BeLikeExactly.ps1 | 6 +++--- src/functions/assertions/BeNullOrEmpty.ps1 | 6 +++--- src/functions/assertions/BeOfType.ps1 | 6 +++--- src/functions/assertions/BeTrueOrFalse.ps1 | 16 ++++++++-------- src/functions/assertions/Contain.ps1 | 6 +++--- src/functions/assertions/Exist.ps1 | 6 +++--- src/functions/assertions/FileContentMatch.ps1 | 6 +++--- .../assertions/FileContentMatchMultiline.ps1 | 6 +++--- .../FileContentMatchMultilineExactly.ps1 | 6 +++--- src/functions/assertions/HaveCount.ps1 | 6 +++--- src/functions/assertions/HaveParameter.ps1 | 6 +++--- src/functions/assertions/Match.ps1 | 6 +++--- src/functions/assertions/MatchExactly.ps1 | 6 +++--- src/functions/assertions/PesterThrow.ps1 | 6 +++--- 19 files changed, 67 insertions(+), 67 deletions(-) diff --git a/src/functions/assertions/Be.ps1 b/src/functions/assertions/Be.ps1 index 748a9475f..4bc3ff7b4 100644 --- a/src/functions/assertions/Be.ps1 +++ b/src/functions/assertions/Be.ps1 @@ -1,5 +1,5 @@ #Be -function Should-Be ($ActualValue, $ExpectedValue, [switch] $Negate, [string] $Because) { +function Should-BeAssertion ($ActualValue, $ExpectedValue, [switch] $Negate, [string] $Because) { <# .SYNOPSIS Compares one object with another for equality @@ -64,8 +64,8 @@ function NotShouldBeFailureMessage($ActualValue, $ExpectedValue, $Because) { } & $script:SafeCommands['Add-ShouldOperator'] -Name Be ` - -InternalName Should-Be ` - -Test ${function:Should-Be} ` + -InternalName Should-BeAssertion ` + -Test ${function:Should-BeAssertion} ` -Alias 'EQ' ` -SupportsArrayInput @@ -73,7 +73,7 @@ Set-ShouldOperatorHelpMessage -OperatorName Be ` -HelpMessage 'Compares one object with another for equality and throws if the two objects are not the same.' #BeExactly -function Should-BeExactly($ActualValue, $ExpectedValue, $Because) { +function Should-BeAssertionExactly($ActualValue, $ExpectedValue, $Because) { <# .SYNOPSIS Compares one object with another for equality and throws if the @@ -137,8 +137,8 @@ function NotShouldBeExactlyFailureMessage($ActualValue, $ExpectedValue, $Because } & $script:SafeCommands['Add-ShouldOperator'] -Name BeExactly ` - -InternalName Should-BeExactly ` - -Test ${function:Should-BeExactly} ` + -InternalName Should-BeAssertionExactly ` + -Test ${function:Should-BeAssertionExactly} ` -Alias 'CEQ' ` -SupportsArrayInput diff --git a/src/functions/assertions/BeGreaterThan.ps1 b/src/functions/assertions/BeGreaterThan.ps1 index 00aafc167..c74c23f9f 100644 --- a/src/functions/assertions/BeGreaterThan.ps1 +++ b/src/functions/assertions/BeGreaterThan.ps1 @@ -1,4 +1,4 @@ -function Should-BeGreaterThan($ActualValue, $ExpectedValue, [switch] $Negate, [string] $Because) { +function Should-BeGreaterThanAssertion($ActualValue, $ExpectedValue, [switch] $Negate, [string] $Because) { <# .SYNOPSIS Asserts that a number (or other comparable value) is greater than an expected value. @@ -43,7 +43,7 @@ function Should-BeLessOrEqual($ActualValue, $ExpectedValue, [switch] $Negate, [s This test also passes, as PowerShell evaluates `10 -le 10` as true. #> if ($Negate) { - return Should-BeGreaterThan -ActualValue $ActualValue -ExpectedValue $ExpectedValue -Negate:$false -Because $Because + return Should-BeGreaterThanAssertion -ActualValue $ActualValue -ExpectedValue $ExpectedValue -Negate:$false -Because $Because } if ($ActualValue -gt $ExpectedValue) { @@ -59,8 +59,8 @@ function Should-BeLessOrEqual($ActualValue, $ExpectedValue, [switch] $Negate, [s } & $script:SafeCommands['Add-ShouldOperator'] -Name BeGreaterThan ` - -InternalName Should-BeGreaterThan ` - -Test ${function:Should-BeGreaterThan} ` + -InternalName Should-BeGreaterThanAssertion ` + -Test ${function:Should-BeGreaterThanAssertion} ` -Alias 'GT' Set-ShouldOperatorHelpMessage -OperatorName BeGreaterThan ` diff --git a/src/functions/assertions/BeIn.ps1 b/src/functions/assertions/BeIn.ps1 index dbad24a8e..cf9ad8f7b 100644 --- a/src/functions/assertions/BeIn.ps1 +++ b/src/functions/assertions/BeIn.ps1 @@ -1,4 +1,4 @@ -function Should-BeIn($ActualValue, $ExpectedValue, [switch] $Negate, [string] $Because) { +function Should-BeInAssertion($ActualValue, $ExpectedValue, [switch] $Negate, [string] $Because) { <# .SYNOPSIS Asserts that a collection of values contain a specific value. @@ -35,8 +35,8 @@ } & $script:SafeCommands['Add-ShouldOperator'] -Name BeIn ` - -InternalName Should-BeIn ` - -Test ${function:Should-BeIn} + -InternalName Should-BeInAssertion ` + -Test ${function:Should-BeInAssertion} Set-ShouldOperatorHelpMessage -OperatorName BeIn ` -HelpMessage "Asserts that a collection of values contain a specific value. Uses PowerShell's -contains operator to confirm." diff --git a/src/functions/assertions/BeLessThan.ps1 b/src/functions/assertions/BeLessThan.ps1 index 2ba09e5e0..8109c12b1 100644 --- a/src/functions/assertions/BeLessThan.ps1 +++ b/src/functions/assertions/BeLessThan.ps1 @@ -1,4 +1,4 @@ -function Should-BeLessThan($ActualValue, $ExpectedValue, [switch] $Negate, [string] $Because) { +function Should-BeLessThanAssertion($ActualValue, $ExpectedValue, [switch] $Negate, [string] $Because) { <# .SYNOPSIS Asserts that a number (or other comparable value) is lower than an expected value. @@ -43,7 +43,7 @@ function Should-BeGreaterOrEqual($ActualValue, $ExpectedValue, [switch] $Negate, This test also passes, as PowerShell evaluates `2 -ge 2` as true. #> if ($Negate) { - return Should-BeLessThan -ActualValue $ActualValue -ExpectedValue $ExpectedValue -Negate:$false -Because $Because + return Should-BeLessThanAssertion -ActualValue $ActualValue -ExpectedValue $ExpectedValue -Negate:$false -Because $Because } if ($ActualValue -lt $ExpectedValue) { @@ -59,8 +59,8 @@ function Should-BeGreaterOrEqual($ActualValue, $ExpectedValue, [switch] $Negate, } & $script:SafeCommands['Add-ShouldOperator'] -Name BeLessThan ` - -InternalName Should-BeLessThan ` - -Test ${function:Should-BeLessThan} ` + -InternalName Should-BeLessThanAssertion ` + -Test ${function:Should-BeLessThanAssertion} ` -Alias 'LT' Set-ShouldOperatorHelpMessage -OperatorName BeLessThan ` diff --git a/src/functions/assertions/BeLike.ps1 b/src/functions/assertions/BeLike.ps1 index 132712546..904e7edd0 100644 --- a/src/functions/assertions/BeLike.ps1 +++ b/src/functions/assertions/BeLike.ps1 @@ -1,4 +1,4 @@ -function Should-BeLike($ActualValue, $ExpectedValue, [switch] $Negate, [String] $Because) { +function Should-BeLikeAssertion($ActualValue, $ExpectedValue, [switch] $Negate, [String] $Because) { <# .SYNOPSIS Asserts that the actual value matches a wildcard pattern using PowerShell's -like operator. @@ -43,8 +43,8 @@ } & $script:SafeCommands['Add-ShouldOperator'] -Name BeLike ` - -InternalName Should-BeLike ` - -Test ${function:Should-BeLike} + -InternalName Should-BeLikeAssertion ` + -Test ${function:Should-BeLikeAssertion} Set-ShouldOperatorHelpMessage -OperatorName BeLike ` -HelpMessage "Asserts that the actual value matches a wildcard pattern using PowerShell's -like operator. This comparison is not case-sensitive." diff --git a/src/functions/assertions/BeLikeExactly.ps1 b/src/functions/assertions/BeLikeExactly.ps1 index 36242bbbf..c05417478 100644 --- a/src/functions/assertions/BeLikeExactly.ps1 +++ b/src/functions/assertions/BeLikeExactly.ps1 @@ -1,4 +1,4 @@ -function Should-BeLikeExactly($ActualValue, $ExpectedValue, [switch] $Negate, [String] $Because) { +function Should-BeLikeExactlyAssertion($ActualValue, $ExpectedValue, [switch] $Negate, [String] $Because) { <# .SYNOPSIS Asserts that the actual value matches a wildcard pattern using PowerShell's -like operator. @@ -42,8 +42,8 @@ } & $script:SafeCommands['Add-ShouldOperator'] -Name BeLikeExactly ` - -InternalName Should-BeLikeExactly ` - -Test ${function:Should-BeLikeExactly} + -InternalName Should-BeLikeExactlyAssertion ` + -Test ${function:Should-BeLikeExactlyAssertion} Set-ShouldOperatorHelpMessage -OperatorName BeLikeExactly ` -HelpMessage "Asserts that the actual value matches a wildcard pattern using PowerShell's -like operator. This comparison is case-sensitive." diff --git a/src/functions/assertions/BeNullOrEmpty.ps1 b/src/functions/assertions/BeNullOrEmpty.ps1 index 3c29198ef..8af19c08a 100644 --- a/src/functions/assertions/BeNullOrEmpty.ps1 +++ b/src/functions/assertions/BeNullOrEmpty.ps1 @@ -1,5 +1,5 @@  -function Should-BeNullOrEmpty($ActualValue, [switch] $Negate, [string] $Because) { +function Should-BeNullOrEmptyAssertion($ActualValue, [switch] $Negate, [string] $Because) { <# .SYNOPSIS Checks values for null or empty (strings). @@ -73,8 +73,8 @@ function NotShouldBeNullOrEmptyFailureMessage ($Because) { } & $script:SafeCommands['Add-ShouldOperator'] -Name BeNullOrEmpty ` - -InternalName Should-BeNullOrEmpty ` - -Test ${function:Should-BeNullOrEmpty} ` + -InternalName Should-BeNullOrEmptyAssertion ` + -Test ${function:Should-BeNullOrEmptyAssertion} ` -SupportsArrayInput Set-ShouldOperatorHelpMessage -OperatorName BeNullOrEmpty ` diff --git a/src/functions/assertions/BeOfType.ps1 b/src/functions/assertions/BeOfType.ps1 index 1b58343c7..5a7a110ef 100644 --- a/src/functions/assertions/BeOfType.ps1 +++ b/src/functions/assertions/BeOfType.ps1 @@ -1,5 +1,5 @@  -function Should-BeOfType($ActualValue, $ExpectedType, [switch] $Negate, [string]$Because) { +function Should-BeOfTypeAssertion($ActualValue, $ExpectedType, [switch] $Negate, [string]$Because) { <# .SYNOPSIS Asserts that the actual value should be an object of a specified type @@ -68,8 +68,8 @@ function Should-BeOfType($ActualValue, $ExpectedType, [switch] $Negate, [string] & $script:SafeCommands['Add-ShouldOperator'] -Name BeOfType ` - -InternalName Should-BeOfType ` - -Test ${function:Should-BeOfType} ` + -InternalName Should-BeOfTypeAssertion ` + -Test ${function:Should-BeOfTypeAssertion} ` -Alias 'HaveType' Set-ShouldOperatorHelpMessage -OperatorName BeOfType ` diff --git a/src/functions/assertions/BeTrueOrFalse.ps1 b/src/functions/assertions/BeTrueOrFalse.ps1 index 99e81f5e2..b05c3ad0d 100644 --- a/src/functions/assertions/BeTrueOrFalse.ps1 +++ b/src/functions/assertions/BeTrueOrFalse.ps1 @@ -1,4 +1,4 @@ -function Should-BeTrue($ActualValue, [switch] $Negate, [string] $Because) { +function Should-BeTrueAssertion($ActualValue, [switch] $Negate, [string] $Because) { <# .SYNOPSIS Asserts that the value is true, or truthy. @@ -20,7 +20,7 @@ This test passes as a "truthy" result. #> if ($Negate) { - return Should-BeFalse -ActualValue $ActualValue -Negate:$false -Because $Because + return Should-BeFalseAssertion -ActualValue $ActualValue -Negate:$false -Because $Because } if (-not $ActualValue) { @@ -36,7 +36,7 @@ } } -function Should-BeFalse($ActualValue, [switch] $Negate, $Because) { +function Should-BeFalseAssertion($ActualValue, [switch] $Negate, $Because) { <# .SYNOPSIS Asserts that the value is false, or falsy. @@ -58,7 +58,7 @@ function Should-BeFalse($ActualValue, [switch] $Negate, $Because) { This test passes as a "falsy" result. #> if ($Negate) { - return Should-BeTrue -ActualValue $ActualValue -Negate:$false -Because $Because + return Should-BeTrueAssertion -ActualValue $ActualValue -Negate:$false -Because $Because } if ($ActualValue) { @@ -76,15 +76,15 @@ function Should-BeFalse($ActualValue, [switch] $Negate, $Because) { & $script:SafeCommands['Add-ShouldOperator'] -Name BeTrue ` - -InternalName Should-BeTrue ` - -Test ${function:Should-BeTrue} + -InternalName Should-BeTrueAssertion ` + -Test ${function:Should-BeTrueAssertion} Set-ShouldOperatorHelpMessage -OperatorName BeTrue ` -HelpMessage "Asserts that the value is true, or truthy." & $script:SafeCommands['Add-ShouldOperator'] -Name BeFalse ` - -InternalName Should-BeFalse ` - -Test ${function:Should-BeFalse} + -InternalName Should-BeFalseAssertion ` + -Test ${function:Should-BeFalseAssertion} Set-ShouldOperatorHelpMessage -OperatorName BeFalse ` -HelpMessage "Asserts that the value is false, or falsy." diff --git a/src/functions/assertions/Contain.ps1 b/src/functions/assertions/Contain.ps1 index e2624e4ed..a7bce41ba 100644 --- a/src/functions/assertions/Contain.ps1 +++ b/src/functions/assertions/Contain.ps1 @@ -1,4 +1,4 @@ -function Should-Contain($ActualValue, $ExpectedValue, [switch] $Negate, [string] $Because) { +function Should-ContainAssertion($ActualValue, $ExpectedValue, [switch] $Negate, [string] $Because) { <# .SYNOPSIS Asserts that collection contains a specific value. @@ -35,8 +35,8 @@ } & $script:SafeCommands['Add-ShouldOperator'] -Name Contain ` - -InternalName Should-Contain ` - -Test ${function:Should-Contain} ` + -InternalName Should-ContainAssertion ` + -Test ${function:Should-ContainAssertion} ` -SupportsArrayInput Set-ShouldOperatorHelpMessage -OperatorName Contain ` diff --git a/src/functions/assertions/Exist.ps1 b/src/functions/assertions/Exist.ps1 index ae79a7cfc..a89398a04 100644 --- a/src/functions/assertions/Exist.ps1 +++ b/src/functions/assertions/Exist.ps1 @@ -1,4 +1,4 @@ -function Should-Exist($ActualValue, [switch] $Negate, [string] $Because) { +function Should-ExistAssertion($ActualValue, [switch] $Negate, [string] $Because) { <# .SYNOPSIS Does not perform any comparison, but checks if the object calling Exist is present in a PS Provider. @@ -36,8 +36,8 @@ } & $script:SafeCommands['Add-ShouldOperator'] -Name Exist ` - -InternalName Should-Exist ` - -Test ${function:Should-Exist} + -InternalName Should-ExistAssertion ` + -Test ${function:Should-ExistAssertion} Set-ShouldOperatorHelpMessage -OperatorName Exist ` -HelpMessage "Does not perform any comparison, but checks if the object calling Exist is present in a PS Provider. The object must have valid path syntax. It essentially must pass a Test-Path call." diff --git a/src/functions/assertions/FileContentMatch.ps1 b/src/functions/assertions/FileContentMatch.ps1 index 27dac43b7..7c81c74e9 100644 --- a/src/functions/assertions/FileContentMatch.ps1 +++ b/src/functions/assertions/FileContentMatch.ps1 @@ -1,4 +1,4 @@ -function Should-FileContentMatch($ActualValue, $ExpectedContent, [switch] $Negate, $Because) { +function Should-FileContentMatchAssertion($ActualValue, $ExpectedContent, [switch] $Negate, $Because) { <# .SYNOPSIS Checks to see if a file contains the specified text. @@ -66,8 +66,8 @@ function NotShouldFileContentMatchFailureMessage($ActualValue, $ExpectedContent, } & $script:SafeCommands['Add-ShouldOperator'] -Name FileContentMatch ` - -InternalName Should-FileContentMatch ` - -Test ${function:Should-FileContentMatch} + -InternalName Should-FileContentMatchAssertion ` + -Test ${function:Should-FileContentMatchAssertion} Set-ShouldOperatorHelpMessage -OperatorName FileContentMatch ` -HelpMessage 'Checks to see if a file contains the specified text. This search is not case sensitive and uses regular expressions.' diff --git a/src/functions/assertions/FileContentMatchMultiline.ps1 b/src/functions/assertions/FileContentMatchMultiline.ps1 index 0410d61e9..10188c4a6 100644 --- a/src/functions/assertions/FileContentMatchMultiline.ps1 +++ b/src/functions/assertions/FileContentMatchMultiline.ps1 @@ -1,4 +1,4 @@ -function Should-FileContentMatchMultiline($ActualValue, $ExpectedContent, [switch] $Negate, [String] $Because) { +function Should-FileContentMatchMultilineAssertion($ActualValue, $ExpectedContent, [switch] $Negate, [String] $Because) { <# .SYNOPSIS As opposed to FileContentMatch and FileContentMatchExactly operators, @@ -58,8 +58,8 @@ function NotShouldFileContentMatchMultilineFailureMessage($ActualValue, $Expecte } & $script:SafeCommands['Add-ShouldOperator'] -Name FileContentMatchMultiline ` - -InternalName Should-FileContentMatchMultiline ` - -Test ${function:Should-FileContentMatchMultiline} + -InternalName Should-FileContentMatchMultilineAssertion ` + -Test ${function:Should-FileContentMatchMultilineAssertion} Set-ShouldOperatorHelpMessage -OperatorName FileContentMatchMultiline ` -HelpMessage 'As opposed to FileContentMatch and FileContentMatchExactly operators, FileContentMatchMultiline presents content of the file being tested as one string object, so that the expression you are comparing it to can consist of several lines.' diff --git a/src/functions/assertions/FileContentMatchMultilineExactly.ps1 b/src/functions/assertions/FileContentMatchMultilineExactly.ps1 index 174733353..9f87a7729 100644 --- a/src/functions/assertions/FileContentMatchMultilineExactly.ps1 +++ b/src/functions/assertions/FileContentMatchMultilineExactly.ps1 @@ -1,4 +1,4 @@ -function Should-FileContentMatchMultilineExactly($ActualValue, $ExpectedContent, [switch] $Negate, [String] $Because) { +function Should-FileContentMatchMultilineExactlyAssertion($ActualValue, $ExpectedContent, [switch] $Negate, [String] $Because) { <# .SYNOPSIS As opposed to FileContentMatch and FileContentMatchExactly operators, @@ -75,8 +75,8 @@ function NotShouldFileContentMatchMultilineExactlyFailureMessage($ActualValue, $ } & $script:SafeCommands['Add-ShouldOperator'] -Name FileContentMatchMultilineExactly ` - -InternalName Should-FileContentMatchMultilineExactly ` - -Test ${function:Should-FileContentMatchMultilineExactly} + -InternalName Should-FileContentMatchMultilineExactlyAssertion ` + -Test ${function:Should-FileContentMatchMultilineExactlyAssertion} Set-ShouldOperatorHelpMessage -OperatorName FileContentMatchMultilineExactly ` -HelpMessage 'As opposed to FileContentMatch and FileContentMatchExactly operators, FileContentMatchMultilineExactly presents content of the file being tested as one string object, so that the case sensitive expression you are comparing it to can consist of several lines.' diff --git a/src/functions/assertions/HaveCount.ps1 b/src/functions/assertions/HaveCount.ps1 index a4a943f4d..9f9155810 100644 --- a/src/functions/assertions/HaveCount.ps1 +++ b/src/functions/assertions/HaveCount.ps1 @@ -1,4 +1,4 @@ -function Should-HaveCount($ActualValue, [int] $ExpectedValue, [switch] $Negate, [string] $Because) { +function Should-HaveCountAssertion($ActualValue, [int] $ExpectedValue, [switch] $Negate, [string] $Because) { <# .SYNOPSIS Asserts that a collection has the expected amount of items. @@ -71,8 +71,8 @@ } & $script:SafeCommands['Add-ShouldOperator'] -Name HaveCount ` - -InternalName Should-HaveCount ` - -Test ${function:Should-HaveCount} ` + -InternalName Should-HaveCountAssertion ` + -Test ${function:Should-HaveCountAssertion} ` -SupportsArrayInput Set-ShouldOperatorHelpMessage -OperatorName HaveCount ` diff --git a/src/functions/assertions/HaveParameter.ps1 b/src/functions/assertions/HaveParameter.ps1 index 4d5f8811f..d3bfaac4b 100644 --- a/src/functions/assertions/HaveParameter.ps1 +++ b/src/functions/assertions/HaveParameter.ps1 @@ -1,4 +1,4 @@ -function Should-HaveParameter ( +function Should-HaveParameterAssertion ( $ActualValue, [String] $ParameterName, $Type, @@ -376,8 +376,8 @@ } & $script:SafeCommands['Add-ShouldOperator'] -Name HaveParameter ` - -InternalName Should-HaveParameter ` - -Test ${function:Should-HaveParameter} + -InternalName Should-HaveParameterAssertion ` + -Test ${function:Should-HaveParameterAssertion} Set-ShouldOperatorHelpMessage -OperatorName HaveParameter ` -HelpMessage 'Asserts that a command has the expected parameter.' diff --git a/src/functions/assertions/Match.ps1 b/src/functions/assertions/Match.ps1 index 42c6b4cfc..d5c0e1742 100644 --- a/src/functions/assertions/Match.ps1 +++ b/src/functions/assertions/Match.ps1 @@ -1,4 +1,4 @@ -function Should-Match($ActualValue, $RegularExpression, [switch] $Negate, [string] $Because) { +function Should-MatchAssertion($ActualValue, $RegularExpression, [switch] $Negate, [string] $Because) { <# .SYNOPSIS Uses a regular expression to compare two objects. @@ -55,8 +55,8 @@ function NotShouldMatchFailureMessage($ActualValue, $RegularExpression, $Because } & $script:SafeCommands['Add-ShouldOperator'] -Name Match ` - -InternalName Should-Match ` - -Test ${function:Should-Match} + -InternalName Should-MatchAssertion ` + -Test ${function:Should-MatchAssertion} Set-ShouldOperatorHelpMessage -OperatorName Match ` -HelpMessage 'Uses a regular expression to compare two objects. This comparison is not case sensitive.' diff --git a/src/functions/assertions/MatchExactly.ps1 b/src/functions/assertions/MatchExactly.ps1 index 6f26dc0f4..6dd412c85 100644 --- a/src/functions/assertions/MatchExactly.ps1 +++ b/src/functions/assertions/MatchExactly.ps1 @@ -1,4 +1,4 @@ -function Should-MatchExactly($ActualValue, $RegularExpression, [switch] $Negate, [string] $Because) { +function Should-MatchExactlyAssertion($ActualValue, $RegularExpression, [switch] $Negate, [string] $Because) { <# .SYNOPSIS Uses a regular expression to compare two objects. @@ -48,8 +48,8 @@ function NotShouldMatchExactlyFailureMessage($ActualValue, $RegularExpression) { } & $script:SafeCommands['Add-ShouldOperator'] -Name MatchExactly ` - -InternalName Should-MatchExactly ` - -Test ${function:Should-MatchExactly} ` + -InternalName Should-MatchExactlyAssertion ` + -Test ${function:Should-MatchExactlyAssertion} ` -Alias 'CMATCH' Set-ShouldOperatorHelpMessage -OperatorName MatchExactly ` diff --git a/src/functions/assertions/PesterThrow.ps1 b/src/functions/assertions/PesterThrow.ps1 index 9ac8b9a03..57bd5c254 100644 --- a/src/functions/assertions/PesterThrow.ps1 +++ b/src/functions/assertions/PesterThrow.ps1 @@ -1,4 +1,4 @@ -function Should-Throw { +function Should-ThrowAssertion { <# .SYNOPSIS Checks if an exception was thrown. Enclose input in a script block. @@ -165,8 +165,8 @@ function NotShouldThrowFailureMessage { } & $script:SafeCommands['Add-ShouldOperator'] -Name Throw ` - -InternalName Should-Throw ` - -Test ${function:Should-Throw} + -InternalName Should-ThrowAssertion ` + -Test ${function:Should-ThrowAssertion} Set-ShouldOperatorHelpMessage -OperatorName Throw ` -HelpMessage 'Checks if an exception was thrown. Enclose input in a scriptblock.' From d60f53559473ecc24b4d0cdf048b099129ed3a1b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Fri, 12 Apr 2024 23:03:41 +0200 Subject: [PATCH 13/55] Fix raw get-variable --- src/functions/assert/Collection/Assert-All.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/functions/assert/Collection/Assert-All.ps1 b/src/functions/assert/Collection/Assert-All.ps1 index 8f7dcb22f..6fa4883d3 100644 --- a/src/functions/assert/Collection/Assert-All.ps1 +++ b/src/functions/assert/Collection/Assert-All.ps1 @@ -20,7 +20,7 @@ # Do NOT replace this Foreach-Object with foreach keyword, you will break the $_ variable. $actualFiltered = $Actual | & $SafeCommands['ForEach-Object'] { # powershell v4 code where we have InvokeWithContext available - $underscore = Get-Variable _ + $underscore = & $SafeCommands['Get-Variable'] _ $pass = $FilterScript.InvokeWithContext($null, $underscore, $null) # # polyfill for PowerShell v2 From 36f36c917feefd2d9c739ad437f9df4692ac5679 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Fri, 12 Apr 2024 23:07:06 +0200 Subject: [PATCH 14/55] No SDK pre-release --- global.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/global.json b/global.json index 869f89528..2d566bd8c 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,7 @@ { "sdk": { "rollForward": "latestFeature", - "version": "8.0.100" + "version": "8.0.100", + "allowPrerelease": false } } \ No newline at end of file From 9829ae11b81ae89a031099f11dc49213a4330af2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Fri, 19 Apr 2024 21:05:35 +0200 Subject: [PATCH 15/55] Fixes --- long list of stuff to do.md | 40 +++++++++++++++++++ src/Module.ps1 | 16 ++++---- src/Pester.psd1 | 10 ++--- .../assert/Collection/Assert-All.ps1 | 10 ++--- .../assert/Collection/Assert-Collection.ps1 | 35 ++++++++++++++++ test.ps1 | 8 ++++ .../assert/Collection/Assert-All.Tests.ps1 | 4 ++ .../Collection/Assert-Collection.Tests.ps1 | 33 +++++++++++++++ .../Collection/Assert-NotCollection.Tests.ps1 | 1 + 9 files changed, 138 insertions(+), 19 deletions(-) create mode 100644 long list of stuff to do.md create mode 100644 src/functions/assert/Collection/Assert-Collection.ps1 create mode 100644 tst/functions/assert/Collection/Assert-Collection.Tests.ps1 create mode 100644 tst/functions/assert/Collection/Assert-NotCollection.Tests.ps1 diff --git a/long list of stuff to do.md b/long list of stuff to do.md new file mode 100644 index 000000000..2616942c8 --- /dev/null +++ b/long list of stuff to do.md @@ -0,0 +1,40 @@ +- [ ] Should-BeNull +- [ ] Should-BeType +- [ ] Should-BeOneOf +- [ ] Should-BeSame +- [ ] Should-MatchString +- [ ] Should-BeLikeString +- [ ] Should-StartWithString +- [ ] Should-EndWithString +- [ ] +- [ ] Should-BeCollection +- [ ] Should-BeInCollection +- [ ] Should-BeSame +- [ ] Should-BeTrue +- [ ] Should-BeFalse +- [ ] Should-MatchString +- [ ] Should-ContainString +- [ ] Should-BeEmptyString +- [ ] Should-BeWhitespaceString +- [ ] Should-BeEquivalentToString +- [ ] Should-StartWithString +- [ ] Should-EndWithString +- [ ] Should-BeLikeString +- [ ] Should-BeGreaterThanOrEqual +- [ ] Should-BeGreaterThan +- [ ] Should-BeLessThanOrEqual +- [ ] Should-BeLessThan +- [ ] Should-BeInRange +- [ ] Should-Be +- [ ] Should-HaveCount +- [ ] Should-BeCollection +- [ ] Should-HaveCountGreaterThan +- [ ] Should-HaveCountGreaterThanOrEqual +- [ ] Should-HaveCountLessThan +- [ ] Should-HaveCountLessThanOrEqual +- [ ] +- [ ] +- [ ] +- [ ] +- [ ] +- [ ] Should-BeCollection 1,2,3 diff --git a/src/Module.ps1 b/src/Module.ps1 index ee55b8b44..0c2cacda1 100644 --- a/src/Module.ps1 +++ b/src/Module.ps1 @@ -20,7 +20,7 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session & $SafeCommands['Set-Alias'] 'Should-BeGreaterThan' 'Assert-GreaterThan' & $SafeCommands['Set-Alias'] 'Should-BeGreaterThanOrEqual' 'Assert-GreaterThanOrEqual' & $SafeCommands['Set-Alias'] 'Should-BeLessThan' 'Assert-LessThan' -& $SafeCommands['Set-Alias'] 'Shoulde-BeLessThanOrEqual' 'Assert-LessThanOrEqual' +& $SafeCommands['Set-Alias'] 'Should-BeLessThanOrEqual' 'Assert-LessThanOrEqual' & $SafeCommands['Set-Alias'] 'Should-NotBeEqual' 'Assert-NotEqual' & $SafeCommands['Set-Alias'] 'Should-NotBeNull' 'Assert-NotNull' & $SafeCommands['Set-Alias'] 'Should-NotBeSame' 'Assert-NotSame' @@ -28,8 +28,8 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session & $SafeCommands['Set-Alias'] 'Should-BeNull' 'Assert-Null' & $SafeCommands['Set-Alias'] 'Should-BeSame' 'Assert-Same' & $SafeCommands['Set-Alias'] 'Should-BeType' 'Assert-Type' -& $SafeCommands['Set-Alias'] 'Should-BeLike' 'Assert-Like' -& $SafeCommands['Set-Alias'] 'Should-NotBeLike' 'Assert-NotLike' +& $SafeCommands['Set-Alias'] 'Should-BeLikeString' 'Assert-Like' +& $SafeCommands['Set-Alias'] 'Should-NotBeLikeString' 'Assert-NotLike' @@ -121,7 +121,7 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session 'Should-BeGreaterThan' 'Should-BeGreaterThanOrEqual' 'Should-BeLessThan' - 'Shoulde-BeLessThanOrEqual' + 'Should-BeLessThanOrEqual' 'Should-NotBeEqual' 'Should-NotBeNull' 'Should-NotBeSame' @@ -129,8 +129,8 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session 'Should-BeNull' 'Should-BeSame' 'Should-BeType' - 'Should-BeLike' - 'Should-NotBeLike' - 'Should-StringBeEqual' - 'Should-StringNotBeEqual' + 'Should-BeLikeString' + 'Should-NotBeLikeString' + 'Should-BeString' + 'Should-NotBeString' ) diff --git a/src/Pester.psd1 b/src/Pester.psd1 index 2e84e6a46..2da875b17 100644 --- a/src/Pester.psd1 +++ b/src/Pester.psd1 @@ -125,7 +125,7 @@ 'Should-BeGreaterThan' 'Should-BeGreaterThanOrEqual' 'Should-BeLessThan' - 'Shoulde-BeLessThanOrEqual' + 'Should-BeLessThanOrEqual' 'Should-NotBeEqual' 'Should-NotBeNull' 'Should-NotBeSame' @@ -133,10 +133,10 @@ 'Should-BeNull' 'Should-BeSame' 'Should-BeType' - 'Should-BeLike' - 'Should-NotBeLike' - 'Should-StringBeEqual' - 'Should-StringNotBeEqual' + 'Should-BeLikeString' + 'Should-NotBeLikeString' + 'Should-BeString' + 'Should-NotBeString' ) diff --git a/src/functions/assert/Collection/Assert-All.ps1 b/src/functions/assert/Collection/Assert-All.ps1 index 6fa4883d3..849453ba7 100644 --- a/src/functions/assert/Collection/Assert-All.ps1 +++ b/src/functions/assert/Collection/Assert-All.ps1 @@ -23,17 +23,15 @@ $underscore = & $SafeCommands['Get-Variable'] _ $pass = $FilterScript.InvokeWithContext($null, $underscore, $null) - # # polyfill for PowerShell v2 - # $PSCmdlet.SessionState.PSVariable.Set("_", $_) - # $pass = & $FilterScript - if (-not $pass) { $_ } } - if ($actualFiltered) { + # Make sure are checking the count of the filtered items, not just a single item. + $actualFiltered = @($actualFiltered) + if (0 -lt $actualFiltered.Count) { $data = @{ actualFiltered = $actualFiltered - actualFilteredCount = @($actualFiltered).Count + actualFilteredCount = $actualFiltered.Count } $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Data $data -CustomMessage $CustomMessage -DefaultMessage "Expected all items in collection '' to pass filter '', but of them '' did not pass the filter." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) diff --git a/src/functions/assert/Collection/Assert-Collection.ps1 b/src/functions/assert/Collection/Assert-Collection.ps1 new file mode 100644 index 000000000..be77a1cea --- /dev/null +++ b/src/functions/assert/Collection/Assert-Collection.ps1 @@ -0,0 +1,35 @@ +function Assert-Collection { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] + param ( + [Parameter(Position = 1, ValueFromPipeline = $true)] + $Actual, + [Parameter(Position = 0)] + $Expected, + [String]$CustomMessage + ) + + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual + + if (-not (Is-Collection -Value $Expected)) { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' is not a collection." + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) + } + + if (-not (Is-Collection -Value $Actual)) { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Actual '' is not a collection." + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) + } + + if (-not (Is-CollectionSize -Expected $Expected -Actual $Actual)) { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be equal to collection '' but they don't have the same number of items." + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) + } + + if ($Actual) { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be present in collection '', but it was not there." + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) + } + + $Actual +} diff --git a/test.ps1 b/test.ps1 index 51ce50255..a06a2eaad 100644 --- a/test.ps1 +++ b/test.ps1 @@ -36,6 +36,7 @@ param ( # force P to fail when I leave `dt` in the tests [switch] $CI, [switch] $SkipPTests, + [switch] $SkipPesterTests, [switch] $NoBuild, [switch] $Inline, [string[]] $File @@ -48,6 +49,10 @@ $ErrorView = "NormalView" "Using PS: $($PsVersionTable.PSVersion)" "In path: $($pwd.Path)" +if ($CI -and ($SkipPTests -or $SkipPesterTests)) { + throw "Cannot skip tests in CI mode!" +} + if (-not $NoBuild) { if ($CI) { & "$PSScriptRoot/build.ps1" -Inline @@ -133,6 +138,9 @@ New-Module -Name TestHelpers -ScriptBlock { } } | Out-Null +if ($SkipPesterTests) { + return +} $configuration = [PesterConfiguration]::Default diff --git a/tst/functions/assert/Collection/Assert-All.Tests.ps1 b/tst/functions/assert/Collection/Assert-All.Tests.ps1 index 4c2dd7364..5816c37e0 100644 --- a/tst/functions/assert/Collection/Assert-All.Tests.ps1 +++ b/tst/functions/assert/Collection/Assert-All.Tests.ps1 @@ -42,4 +42,8 @@ Describe "Assert-All" { It "Accepts FilterScript and Actual by position" { Assert-All { $true } 1, 2 } + + It 'It fails when the only item not matching the filter is 0' { + { 0 | Assert-All -FilterScript { $_ -gt 0 } } | Verify-AssertionFailed + } } diff --git a/tst/functions/assert/Collection/Assert-Collection.Tests.ps1 b/tst/functions/assert/Collection/Assert-Collection.Tests.ps1 new file mode 100644 index 000000000..58a4756e3 --- /dev/null +++ b/tst/functions/assert/Collection/Assert-Collection.Tests.ps1 @@ -0,0 +1,33 @@ +Set-StrictMode -Version Latest + +InPesterModuleScope { + Describe "Assert-Collection" { + It "Passes when collections have the same count and items" -ForEach @( + @{ Actual = @(1); Expected = @(1) } + @{ Actual = @(1, 2); Expected = @(1, 2) } + ) { + $actual | Assert-Collection $expected + } + + It "Fails when collections don't have the same count" -ForEach @( + @{ Actual = @(1); Expected = @(1, 2) } + @{ Actual = @(1, 2); Expected = @(1) } + ) { + $err = { $actual | Assert-Collection $expected } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "Expected int '1' to be present in collection '5', but it was not there." + } + + # It "Passes when collection of multiple items contains the expected item" { + # @(1,2,3) | Assert-Contain 1 + # } + + # It "Fails when collection of multiple items does not contain the expected item" { + # $err = { @(5,6,7) | Assert-Contain 1 } | Verify-AssertionFailed + # $err.Exception.Message | Verify-Equal "Expected int '1' to be present in collection '5, 6, 7', but it was not there." + # } + + # It "Can be called with positional parameters" { + # { Assert-Contain 1 3,4,5 } | Verify-AssertionFailed + # } + } +} diff --git a/tst/functions/assert/Collection/Assert-NotCollection.Tests.ps1 b/tst/functions/assert/Collection/Assert-NotCollection.Tests.ps1 new file mode 100644 index 000000000..5f282702b --- /dev/null +++ b/tst/functions/assert/Collection/Assert-NotCollection.Tests.ps1 @@ -0,0 +1 @@ + \ No newline at end of file From 914303045b2896ada827985058fa48773df1c308 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Sat, 20 Apr 2024 00:07:47 +0200 Subject: [PATCH 16/55] Add Should-BeEmptyString and fix formatting --- src/Format2.ps1 | 50 ++++++---- src/Module.ps1 | 25 +++-- src/Pester.psd1 | 15 ++- .../assert/Common/Get-AssertionMessage.ps1 | 4 +- .../assert/String/Should-BeEmptyString.ps1 | 66 +++++++++++++ tst/Format2.Tests.ps1 | 99 ++++++++++++------- .../assert/Collection/Assert-All.Tests.ps1 | 3 - .../Collection/Assert-Collection.Tests.ps1 | 3 + .../assert/Common/Collect-Input.Tests.ps1 | 11 +++ .../String/Should-BeEmptyString.Tests.ps1 | 80 +++++++++++++++ 10 files changed, 290 insertions(+), 66 deletions(-) create mode 100644 src/functions/assert/String/Should-BeEmptyString.ps1 create mode 100644 tst/functions/assert/String/Should-BeEmptyString.Tests.ps1 diff --git a/src/Format2.ps1 b/src/Format2.ps1 index a6cfa50fd..dbe31bbff 100644 --- a/src/Format2.ps1 +++ b/src/Format2.ps1 @@ -1,14 +1,19 @@ function Format-Collection2 ($Value, [switch]$Pretty) { - $separator = ', ' - if ($Pretty) { - $separator = ",`n" - } - + $length = 0 $o = foreach ($v in $Value) { - Format-Nicely2 -Value $v -Pretty:$Pretty + $formatted = Format-Nicely2 -Value $v -Pretty:$Pretty + $length += $formatted.Length + 1 # 1 is for the separator + $formatted } - $o -join $separator + $prettyLimit = 50 + if ($Pretty -and ($length + 3) -gt $prettyLimit) { + # 3 is for the '@()' + "@(`n $($o -join ",`n ")`n)" + } + else { + "@($($o -join ', '))" + } } function Format-Object2 ($Value, $Property, [switch]$Pretty) { @@ -21,18 +26,24 @@ function Format-Object2 ($Value, $Property, [switch]$Pretty) { } $valueType = Get-ShortType $Value - $valueFormatted = [string]([PSObject]$Value | & $SafeCommands['Select-Object'] -Property $orderedProperty) + $margin = " " + $items = foreach ($p in $orderedProperty) { + if ($Pretty) { "`n$margin" } + $v = ([PSObject]$Value.$p) + $f = Format-Nicely2 -Value $v -Pretty:$Pretty + "$separator$p=$f" + } + $o = "$valueType{$($items -join '; ')}" - if ($Pretty) { - $margin = " " - $valueFormatted = $valueFormatted ` - -replace '^@{', "@{`n$margin" ` - -replace '; ', ";`n$margin" ` - -replace '}$', "`n}" ` + $o +} +function Format-String2 ($Value) { + if ('' -eq $Value) { + return '' } - $valueFormatted -replace "^@", $valueType + "'$Value'" } function Format-Null2 { @@ -84,6 +95,10 @@ function Format-Nicely2 ($Value, [switch]$Pretty) { return Format-Boolean2 -Value $Value } + if ($Value -is [string]) { + return Format-String2 -Value $Value + } + if ($value -is [type]) { return Format-Type2 -Value $Value } @@ -148,16 +163,17 @@ function Get-ShortType2 ($Value) { function Format-Type2 ([Type]$Value) { if ($null -eq $Value) { - return '' + return '[null]' } $type = [string]$Value - $type ` + $typeFormatted = $type ` -replace "^System\." ` -replace "^Management\.Automation\.PSCustomObject$", "PSObject" ` -replace "^PSCustomObject$", "PSObject" ` -replace "^Object\[\]$", "collection" ` + "[$($typeFormatted)]" } diff --git a/src/Module.ps1 b/src/Module.ps1 index 0c2cacda1..383c306a3 100644 --- a/src/Module.ps1 +++ b/src/Module.ps1 @@ -20,7 +20,7 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session & $SafeCommands['Set-Alias'] 'Should-BeGreaterThan' 'Assert-GreaterThan' & $SafeCommands['Set-Alias'] 'Should-BeGreaterThanOrEqual' 'Assert-GreaterThanOrEqual' & $SafeCommands['Set-Alias'] 'Should-BeLessThan' 'Assert-LessThan' -& $SafeCommands['Set-Alias'] 'Should-BeLessThanOrEqual' 'Assert-LessThanOrEqual' +& $SafeCommands['Set-Alias'] 'Should-BeLessThanOrEqual' 'Assert-LessThanOrEqual' & $SafeCommands['Set-Alias'] 'Should-NotBeEqual' 'Assert-NotEqual' & $SafeCommands['Set-Alias'] 'Should-NotBeNull' 'Assert-NotNull' & $SafeCommands['Set-Alias'] 'Should-NotBeSame' 'Assert-NotSame' @@ -28,8 +28,10 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session & $SafeCommands['Set-Alias'] 'Should-BeNull' 'Assert-Null' & $SafeCommands['Set-Alias'] 'Should-BeSame' 'Assert-Same' & $SafeCommands['Set-Alias'] 'Should-BeType' 'Assert-Type' -& $SafeCommands['Set-Alias'] 'Should-BeLikeString' 'Assert-Like' -& $SafeCommands['Set-Alias'] 'Should-NotBeLikeString' 'Assert-NotLike' +& $SafeCommands['Set-Alias'] 'Should-BeLikeString' 'Assert-Like' +& $SafeCommands['Set-Alias'] 'Should-NotBeLikeString' 'Assert-NotLike' + +& $SafeCommands['Set-Alias'] 'Should-BeEmptyString' 'Assert-StringEmpty' @@ -85,11 +87,14 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session 'Assert-Null' 'Assert-Same' 'Assert-Type' + 'Assert-Like' 'Assert-NotLike' 'Assert-StringEqual' 'Assert-StringNotEqual' + 'Assert-StringEmpty' + # export 'Export-NUnitReport' 'ConvertTo-NUnitReport' @@ -108,9 +113,12 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session 'Add-AssertionOperator' 'Get-AssertionOperator' - # assert + # assertion functions + # bool 'Should-BeFalse' 'Should-BeTrue' + + # collection 'Should-All' 'Should-Any' 'Should-Contain' @@ -129,8 +137,13 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session 'Should-BeNull' 'Should-BeSame' 'Should-BeType' - 'Should-BeLikeString' - 'Should-NotBeLikeString' + + # string 'Should-BeString' 'Should-NotBeString' + + 'Should-BeEmptyString' + + 'Should-BeLikeString' + 'Should-NotBeLikeString' ) diff --git a/src/Pester.psd1 b/src/Pester.psd1 index 2da875b17..ec1eaf57c 100644 --- a/src/Pester.psd1 +++ b/src/Pester.psd1 @@ -91,6 +91,7 @@ 'Assert-NotLike' 'Assert-StringEqual' 'Assert-StringNotEqual' + 'Assert-StringEmpty' # legacy 'Assert-VerifiableMock' @@ -112,9 +113,12 @@ 'Add-AssertionOperator' 'Get-AssertionOperator' - # assert + # assertion functions + # bool 'Should-BeFalse' 'Should-BeTrue' + + # collection 'Should-All' 'Should-Any' 'Should-Contain' @@ -133,10 +137,15 @@ 'Should-BeNull' 'Should-BeSame' 'Should-BeType' - 'Should-BeLikeString' - 'Should-NotBeLikeString' + + # string 'Should-BeString' 'Should-NotBeString' + + 'Should-BeEmptyString' + + 'Should-BeLikeString' + 'Should-NotBeLikeString' ) diff --git a/src/functions/assert/Common/Get-AssertionMessage.ps1 b/src/functions/assert/Common/Get-AssertionMessage.ps1 index 49e01420a..ba25a5b52 100644 --- a/src/functions/assert/Common/Get-AssertionMessage.ps1 +++ b/src/functions/assert/Common/Get-AssertionMessage.ps1 @@ -1,10 +1,11 @@ -function Get-AssertionMessage ($Expected, $Actual, $Option, [hashtable]$Data = @{}, $CustomMessage, $DefaultMessage, [switch]$Pretty) { +function Get-AssertionMessage ($Expected, $Actual, $Because, $Option, [hashtable]$Data = @{}, $CustomMessage, $DefaultMessage, [switch]$Pretty) { if (-not $CustomMessage) { $CustomMessage = $DefaultMessage } $expectedFormatted = Format-Nicely2 -Value $Expected -Pretty:$Pretty $actualFormatted = Format-Nicely2 -Value $Actual -Pretty:$Pretty + $becauseFormatted = Format-Because -Because $Because $optionMessage = $null; if ($null -ne $Option -and $option.Length -gt 0) { @@ -24,6 +25,7 @@ $CustomMessage = $CustomMessage.Replace('', (Get-ShortType2 -Value $Expected)) $CustomMessage = $CustomMessage.Replace('', (Get-ShortType2 -Value $Actual)) $CustomMessage = $CustomMessage.Replace('', $optionMessage) + $CustomMessage = $CustomMessage.Replace('', $becauseFormatted) foreach ($pair in $Data.GetEnumerator()) { $CustomMessage = $CustomMessage.Replace("<$($pair.Key)>", (Format-Nicely2 -Value $pair.Value)) diff --git a/src/functions/assert/String/Should-BeEmptyString.ps1 b/src/functions/assert/String/Should-BeEmptyString.ps1 new file mode 100644 index 000000000..344acb683 --- /dev/null +++ b/src/functions/assert/String/Should-BeEmptyString.ps1 @@ -0,0 +1,66 @@ +function Test-StringEmpty { + param ( + $Actual + ) + + + $Actual -is [string] -and [string]::Empty -eq $Actual +} + +function Get-StringEmptyDefaultFailureMessage ($Actual, $Because) { + Get-AssertionMessage -Actual $Actual -Because $Because -DefaultMessage "Expected an empty string, but got : " -Pretty +} + +function Assert-StringEmpty { + <# + .SYNOPSIS + Ensures that input is an empty string. + + .PARAMETER Actual + The actual value that will be compared to an empty string. + + .PARAMETER Because + The reason why the input should be an empty string. + + .EXAMPLE + ```powershell + $actual = "" + $actual | Should-BeEmptyString + ``` + + This test will pass. + + .EXAMPLE + ```powershell + $actual = "hello" + $actual | Should-BeEmptyString + ``` + + This test will fail, the input is not an empty string. + + .EXAMPLE + ``` + $null | Should-BeEmptyString + @() | Should-BeEmptyString + $() | Should-BeEmptyString + $false | Should-BeEmptyString + ``` + + All the tests above will fail, the input is not a string. + #> + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] + param ( + [Parameter(Position = 0, ValueFromPipeline = $true)] + $Actual, + [String]$Because + ) + + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual + + $stringsAreEqual = Test-StringEmpty -Actual $Actual + if (-not ($stringsAreEqual)) { + $formattedMessage = Get-StringEmptyDefaultFailureMessage -Actual $Actual -Because $Because + throw [Pester.Factory]::CreateShouldErrorRecord($formattedMessage, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) + } +} diff --git a/tst/Format2.Tests.ps1 b/tst/Format2.Tests.ps1 index 11a926a67..2fe8dddd9 100644 --- a/tst/Format2.Tests.ps1 +++ b/tst/Format2.Tests.ps1 @@ -17,19 +17,36 @@ InPesterModuleScope { Describe "Format-Collection2" { + It "Formats empty collection to @()" -TestCases @( + ) { + Format-Collection2 -Value @() | Verify-Equal "@()" + } + It "Formats collection of values '' to '' using the default separator" -TestCases @( - @{ Value = (1, 2, 3); Expected = "1, 2, 3" } + @{ Value = (1, 2, 3); Expected = "@(1, 2, 3)" } ) { - param ($Value, $Expected) Format-Collection2 -Value $Value | Verify-Equal $Expected } It "Formats collection of values '' to '' using the default separator" -TestCases @( - @{ Value = (1, 2, 3); Expected = "1, 2, 3" } + @{ Value = (1, 2, 3); Expected = "@(1, 2, 3)" } ) { - param ($Value, $Expected) Format-Collection2 -Value $Value | Verify-Equal $Expected } + + It "Formats collection on single line when it is shorter than 50 characters" -TestCases @( + @{ Value = (1, 2, 3); Expected = "@(1, 2, 3)" } + @{ Value = @([string]::new("*", 44)); Expected = "@('$([string]::new("*", 44))')" } + ) { + Format-Collection2 -Value $Value -Pretty | Verify-Equal $Expected + } + + It "Formats collection on multiple lines when it is longer than 50 characters" -TestCases @( + @{ Value = ([string]::new("*", 25), [string]::new("-", 25)); Expected = "@(`n '$([string]::new("*", 25))',`n '$([string]::new("-", 25))'`n)" } + @{ Value = @([string]::new("*", 60)); Expected = "@(`n '$([string]::new("*", 60))'`n)" } + ) { + Format-Collection2 -Value $Value -Pretty | Verify-Equal $Expected + } } Describe "Format-Number" { @@ -47,8 +64,8 @@ InPesterModuleScope { Describe "Format-Object2" { It "Formats object '' to ''" -TestCases @( - @{ Value = (New-PSObject @{Name = 'Jakub'; Age = 28 }); Expected = "PSObject{Age=28; Name=Jakub}" }, - @{ Value = (New-Object -Type Assertions.TestType.Person -Property @{Name = 'Jakub'; Age = 28 }); Expected = "Assertions.TestType.Person{Age=28; Name=Jakub}" } + @{ Value = (New-PSObject @{Name = 'Jakub'; Age = 28 }); Expected = "PSObject{Age=28; Name='Jakub'}" }, + @{ Value = (New-Object -Type Assertions.TestType.Person -Property @{Name = 'Jakub'; Age = 28 }); Expected = "Assertions.TestType.Person{Age=28; Name='Jakub'}" } ) { param ($Value, $Expected) Format-Object2 -Value $Value | Verify-Equal $Expected @@ -59,7 +76,7 @@ InPesterModuleScope { @{ Value = (New-Object -Type Assertions.TestType.Person -Property @{Name = 'Jakub'; Age = 28 }) SelectedProperties = 'Name' - Expected = "Assertions.TestType.Person{Name=Jakub}" + Expected = "Assertions.TestType.Person{Name='Jakub'}" } ) { param ($Value, $SelectedProperties, $Expected) @@ -74,7 +91,7 @@ InPesterModuleScope { $name = $process.Name $id = $process.Id $SelectedProperties = "Name", "Id" - $expected = "Diagnostics.Process{Id=$id; Name=$name}" + $expected = "Diagnostics.Process{Id=$id; Name='$name'}" Format-Object2 -Value $process -Property $selectedProperties | Verify-Equal $Expected } @@ -108,9 +125,9 @@ InPesterModuleScope { } It "Formats hashtable as ''" -TestCases @( - @{ Value = @{Age = 28; Name = 'Jakub' }; Expected = '@{Age=28; Name=Jakub}' } + @{ Value = @{Age = 28; Name = 'Jakub' }; Expected = "@{Age=28; Name='Jakub'}" } @{ Value = @{Z = 1; H = 1; A = 1 }; Expected = '@{A=1; H=1; Z=1}' } - @{ Value = @{Hash = @{Hash = 'Value' } }; Expected = '@{Hash=@{Hash=Value}}' } + @{ Value = @{Hash = @{Hash = 'Value' } }; Expected = "@{Hash=@{Hash='Value'}}" } ) { param ($Value, $Expected) Format-Hashtable2 $Value | Verify-Equal $Expected @@ -123,9 +140,9 @@ InPesterModuleScope { } It "Formats dictionary as ''" -TestCases @( - @{ Value = New-Dictionary @{Age = 28; Name = 'Jakub' }; Expected = 'Dictionary{Age=28; Name=Jakub}' } + @{ Value = New-Dictionary @{Age = 28; Name = 'Jakub' }; Expected = "Dictionary{Age=28; Name='Jakub'}" } @{ Value = New-Dictionary @{Z = 1; H = 1; A = 1 }; Expected = 'Dictionary{A=1; H=1; Z=1}' } - @{ Value = New-Dictionary @{Dict = ( New-Dictionary @{Dict = 'Value' }) }; Expected = 'Dictionary{Dict=Dictionary{Dict=Value}}' } + @{ Value = New-Dictionary @{Dict = ( New-Dictionary @{Dict = 'Value' }) }; Expected = "Dictionary{Dict=Dictionary{Dict='Value'}}" } ) { param ($Value, $Expected) Format-Dictionary2 $Value | Verify-Equal $Expected @@ -134,18 +151,18 @@ InPesterModuleScope { Describe "Format-Nicely2" { It "Formats value '' correctly to ''" -TestCases @( - @{ Value = $null; Expected = '$null' } - @{ Value = $true; Expected = '$true' } - @{ Value = $false; Expected = '$false' } - @{ Value = 'a' ; Expected = 'a' }, - @{ Value = 1; Expected = '1' }, - @{ Value = (1, 2, 3); Expected = '1, 2, 3' }, - @{ Value = 1.1; Expected = '1.1' }, - @{ Value = [int]; Expected = 'int' } - @{ Value = New-PSObject @{ Name = "Jakub" }; Expected = 'PSObject{Name=Jakub}' }, - @{ Value = (New-Object -Type Assertions.TestType.Person -Property @{Name = 'Jakub'; Age = 28 }); Expected = "Assertions.TestType.Person{Age=28; Name=Jakub}" } - @{ Value = @{Name = 'Jakub'; Age = 28 }; Expected = '@{Age=28; Name=Jakub}' } - @{ Value = New-Dictionary @{Age = 28; Name = 'Jakub' }; Expected = 'Dictionary{Age=28; Name=Jakub}' } + # @{ Value = $null; Expected = '$null' } + # @{ Value = $true; Expected = '$true' } + # @{ Value = $false; Expected = '$false' } + # @{ Value = 'a' ; Expected = "'a'" }, + # @{ Value = 1; Expected = '1' }, + # @{ Value = (1, 2, 3); Expected = '@(1, 2, 3)' }, + # @{ Value = 1.1; Expected = '1.1' }, + # @{ Value = [int]; Expected = 'int' } + @{ Value = New-PSObject @{ Name = "Jakub" }; Expected = "PSObject{Name='Jakub'}" }, + @{ Value = (New-Object -Type Assertions.TestType.Person -Property @{Name = 'Jakub'; Age = 28 }); Expected = "Assertions.TestType.Person{Age=28; Name='Jakub'}" } + @{ Value = @{Name = 'Jakub'; Age = 28 }; Expected = "@{Age=28; Name='Jakub'}" } + @{ Value = New-Dictionary @{Age = 28; Name = 'Jakub' }; Expected = "Dictionary{Age=28; Name='Jakub'}" } ) { param($Value, $Expected) Format-Nicely2 -Value $Value | Verify-Equal $Expected @@ -164,12 +181,12 @@ InPesterModuleScope { Describe "Format-Type2" { It "Given '' it returns the correct shortened type name ''" -TestCases @( - @{ Value = [int]; Expected = 'int' }, - @{ Value = [double]; Expected = 'double' }, - @{ Value = [string]; Expected = 'string' }, - @{ Value = $null; Expected = '' }, - @{ Value = [Management.Automation.PSObject]; Expected = 'PSObject' }, - @{ Value = [Object[]]; Expected = 'collection' } + @{ Value = [int]; Expected = '[int]' }, + @{ Value = [double]; Expected = '[double]' }, + @{ Value = [string]; Expected = '[string]' }, + @{ Value = $null; Expected = '[null]' }, + @{ Value = [Management.Automation.PSObject]; Expected = '[PSObject]' }, + @{ Value = [Object[]]; Expected = '[collection]' } ) { param($Value, $Expected) Format-Type2 -Value $Value | Verify-Equal $Expected @@ -179,15 +196,25 @@ InPesterModuleScope { Describe "Get-ShortType2" { It "Given '' it returns the correct shortened type name ''" -TestCases @( - @{ Value = 1; Expected = 'int' }, - @{ Value = 1.1; Expected = 'double' }, - @{ Value = 'a' ; Expected = 'string' }, - @{ Value = $null ; Expected = '' }, - @{ Value = New-PSObject @{Name = 'Jakub' } ; Expected = 'PSObject' }, - @{ Value = [Object[]]1, 2, 3 ; Expected = 'collection' } + @{ Value = 1; Expected = '[int]' }, + @{ Value = 1.1; Expected = '[double]' }, + @{ Value = 'a' ; Expected = '[string]' }, + @{ Value = $null ; Expected = '[null]' }, + @{ Value = New-PSObject @{Name = 'Jakub' } ; Expected = '[PSObject]' }, + @{ Value = [Object[]]1, 2, 3 ; Expected = '[collection]' } ) { param($Value, $Expected) Get-ShortType2 -Value $Value | Verify-Equal $Expected } } + + Describe "Format-String2" { + It "Formats empty string to `` (no quotes)" { + Format-String2 -Value "" | Verify-Equal '' + } + + It "Formats string to be sorrounded by quotes" { + Format-String2 -Value "abc" | Verify-Equal "'abc'" + } + } } diff --git a/tst/functions/assert/Collection/Assert-All.Tests.ps1 b/tst/functions/assert/Collection/Assert-All.Tests.ps1 index 5816c37e0..5d5c71edc 100644 --- a/tst/functions/assert/Collection/Assert-All.Tests.ps1 +++ b/tst/functions/assert/Collection/Assert-All.Tests.ps1 @@ -6,7 +6,6 @@ Describe "Assert-All" { @{ Actual = @(1) } @{ Actual = 1 } ) { - param($Actual) $Actual | Assert-All -FilterScript { $_ -eq 1 } } @@ -15,14 +14,12 @@ Describe "Assert-All" { @{ Actual = @(2) } @{ Actual = 2 } ) { - param($Actual) { $Actual | Assert-All -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed } It "Validate messages" -TestCases @( @{ Actual = @(3, 4, 5); Message = "Expected all items in collection '3, 4, 5' to pass filter '{ `$_ -eq 1 }', but 3 of them '3, 4, 5' did not pass the filter." } ) { - param($Actual, $Message) $err = { $Actual | Assert-All -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message } diff --git a/tst/functions/assert/Collection/Assert-Collection.Tests.ps1 b/tst/functions/assert/Collection/Assert-Collection.Tests.ps1 index 58a4756e3..fe1196b38 100644 --- a/tst/functions/assert/Collection/Assert-Collection.Tests.ps1 +++ b/tst/functions/assert/Collection/Assert-Collection.Tests.ps1 @@ -1,5 +1,8 @@ Set-StrictMode -Version Latest +# TODO: Add tests. +return + InPesterModuleScope { Describe "Assert-Collection" { It "Passes when collections have the same count and items" -ForEach @( diff --git a/tst/functions/assert/Common/Collect-Input.Tests.ps1 b/tst/functions/assert/Common/Collect-Input.Tests.ps1 index 287a21c0f..b06c8e069 100644 --- a/tst/functions/assert/Common/Collect-Input.Tests.ps1 +++ b/tst/functions/assert/Common/Collect-Input.Tests.ps1 @@ -36,6 +36,17 @@ InPesterModuleScope { } } + It "Given @("""") through pipeline it captures @("""")" { + $collectedInput = @($null) | Assert-PassThru + $collectedInput2 = "" | Assert-PassThru + + Verify-True $collectedInput.IsPipelineInput + Verify-Type -Actual $collectedInput.Actual -Expected ([Object[]]) + if (@("") -ne $collectedInput.Actual) { + throw "Expected @(), but got $(Format-Nicely2 $collectedInput.Actual)." + } + } + It "Given List[int] through pipeline it captures the items in Object[]" { $collectedInput = [Collections.Generic.List[int]]@(1, 2) | Assert-PassThru diff --git a/tst/functions/assert/String/Should-BeEmptyString.Tests.ps1 b/tst/functions/assert/String/Should-BeEmptyString.Tests.ps1 new file mode 100644 index 000000000..5a6f43d44 --- /dev/null +++ b/tst/functions/assert/String/Should-BeEmptyString.Tests.ps1 @@ -0,0 +1,80 @@ +Set-StrictMode -Version Latest + +InPesterModuleScope { + Describe "Test-StringEmpty" { + It "empty string returns `$true" -ForEach @( + @{ Actual = "" } + @{ Actual = [String]::Empty } + ) { + Test-StringEmpty -Actual $Actual | Verify-True + } + + It "non-empty string, whitespace, or null returns `$false" -ForEach @( + @{ Actual = "a" } + @{ Actual = " " } + @{ Actual = $null } + ) { + Test-StringEmpty -Actual $Actual | Verify-False + } + + It "Object with a type that is not a string, returns `$false" -ForEach @( + @{ Actual = $bool } + @{ Actual = 1 } + @{ Actual = @() } + @{ Actual = $null } + ) { + Test-StringEmpty -Actual $Actual | Verify-False + } + + It "returns `$false when type serializes to empty string" { + Add-type -TypeDefinition " + public class TypeThatSerializesToEmptyString { public override string ToString() { return string.Empty; } } + " + Test-StringEmpty -Actual ([TypeThatSerializesToEmptyString]::new()) | Verify-False + } + } + + Describe "Get-StringEmptyDefaultFailureMessage" { + It "Throws with default message when test fails" { + $expected = Get-StringEmptyDefaultFailureMessage -Actual "bde" + $exception = { Should-BeEmptyString -Actual "bde" } | Verify-AssertionFailed + "$exception" | Verify-Equal $expected + } + + It "Throws with default message and because when test fails" { + $expected = Get-StringEmptyDefaultFailureMessage -Actual "bde" -Because "abc" + $exception = { Should-BeEmptyString -Actual "bde" -Because "abc" } | Verify-AssertionFailed + "$exception" | Verify-Equal $expected + } + } +} + +Describe "Should-BeEmptyString" { + It "Does not throw when string is empty" { + Should-BeEmptyString -Actual "" + } + + It "EDGE CASE: Does not throw when string is empty" { + @("") | Should-BeEmptyString + } + + It "Throws when string is not empty" { + { Should-BeEmptyString -Actual "bde" } | Verify-AssertionFailed + } + + It "Allows actual to be passed from pipeline" { + "" | Should-BeEmptyString + } + + It "Allows actual to be passed by position" { + Should-BeEmptyString "" + } + + It "Fails when empty collection is passed in by pipeline" { + { @() | Should-BeEmptyString } | Verify-AssertionFailed + } + + It "Fails when `$null collection is passed in by pipeline" { + { $null | Should-BeEmptyString } | Verify-AssertionFailed + } +} From 6e79b45bdea5262b4c59c42c4a0eb1590ee5ed4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Sat, 20 Apr 2024 21:08:37 +0200 Subject: [PATCH 17/55] Build on dev/* --- azure-pipelines.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 789b0a5d0..8b9ca74f9 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -3,6 +3,7 @@ trigger: include: - main - rel/* + - dev/* paths: exclude: - .devcontainer From e5a4446358b4f363b3e9cb1b79ec93b4bf58acba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Sat, 20 Apr 2024 22:22:07 +0200 Subject: [PATCH 18/55] Add not be null or empty, and not be null or whitespace string assertions --- src/Module.ps1 | 7 ++ src/Pester.psd1 | 5 ++ .../String/Should-BeNullOrEmptyString.ps1 | 3 + .../Should-BeNullOrWhiteSpaceString.ps1 | 3 + .../String/Should-NotBeNullOrEmptyString.ps1 | 57 ++++++++++++++ .../Should-NotBeNullOrWhitespaceString.ps1 | 57 ++++++++++++++ .../Should-NotBeNullOrEmptyString.Tests.ps1 | 74 ++++++++++++++++++ ...ould-NotBeNullOrWhiteSpaceString.Tests.ps1 | 78 +++++++++++++++++++ 8 files changed, 284 insertions(+) create mode 100644 src/functions/assert/String/Should-BeNullOrEmptyString.ps1 create mode 100644 src/functions/assert/String/Should-BeNullOrWhiteSpaceString.ps1 create mode 100644 src/functions/assert/String/Should-NotBeNullOrEmptyString.ps1 create mode 100644 src/functions/assert/String/Should-NotBeNullOrWhitespaceString.ps1 create mode 100644 tst/functions/assert/String/Should-NotBeNullOrEmptyString.Tests.ps1 create mode 100644 tst/functions/assert/String/Should-NotBeNullOrWhiteSpaceString.Tests.ps1 diff --git a/src/Module.ps1 b/src/Module.ps1 index 383c306a3..bb3ba665e 100644 --- a/src/Module.ps1 +++ b/src/Module.ps1 @@ -32,6 +32,9 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session & $SafeCommands['Set-Alias'] 'Should-NotBeLikeString' 'Assert-NotLike' & $SafeCommands['Set-Alias'] 'Should-BeEmptyString' 'Assert-StringEmpty' +& $SafeCommands['Set-Alias'] 'Should-NotBeNullOrWhiteSpaceString' 'Assert-StringNotNullOrWhiteSpace' +& $SafeCommands['Set-Alias'] 'Should-NotBeNullOrEmptyString' 'Assert-StringNotNullOrEmpty' + @@ -94,6 +97,8 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session 'Assert-StringNotEqual' 'Assert-StringEmpty' + 'Assert-StringNotNullOrWhiteSpace' + 'Assert-StringNotNullOrEmpty' # export 'Export-NUnitReport' @@ -143,6 +148,8 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session 'Should-NotBeString' 'Should-BeEmptyString' + 'Should-NotBeNullOrWhiteSpaceString' + 'Should-NotBeNullOrEmptyString' 'Should-BeLikeString' 'Should-NotBeLikeString' diff --git a/src/Pester.psd1 b/src/Pester.psd1 index ec1eaf57c..30a7cc3a7 100644 --- a/src/Pester.psd1 +++ b/src/Pester.psd1 @@ -92,6 +92,8 @@ 'Assert-StringEqual' 'Assert-StringNotEqual' 'Assert-StringEmpty' + 'Assert-StringNotNullOrWhiteSpace' + 'Assert-StringNotNullOrEmpty' # legacy 'Assert-VerifiableMock' @@ -144,6 +146,9 @@ 'Should-BeEmptyString' + 'Should-NotBeNullOrWhiteSpaceString' + 'Should-NotBeNullOrEmptyString' + 'Should-BeLikeString' 'Should-NotBeLikeString' ) diff --git a/src/functions/assert/String/Should-BeNullOrEmptyString.ps1 b/src/functions/assert/String/Should-BeNullOrEmptyString.ps1 new file mode 100644 index 000000000..58a964ad5 --- /dev/null +++ b/src/functions/assert/String/Should-BeNullOrEmptyString.ps1 @@ -0,0 +1,3 @@ +function Test-StringNullOrEmpty ($Actual) { + $Actual -is [string] -and -not ([string]::IsNullOrEmpty($Actual)) +} diff --git a/src/functions/assert/String/Should-BeNullOrWhiteSpaceString.ps1 b/src/functions/assert/String/Should-BeNullOrWhiteSpaceString.ps1 new file mode 100644 index 000000000..9f78c6be8 --- /dev/null +++ b/src/functions/assert/String/Should-BeNullOrWhiteSpaceString.ps1 @@ -0,0 +1,3 @@ +function Test-StringNullOrWhiteSpace ($Actual) { + $Actual -is [string] -and -not ([string]::IsNullOrWhiteSpace($Actual)) +} diff --git a/src/functions/assert/String/Should-NotBeNullOrEmptyString.ps1 b/src/functions/assert/String/Should-NotBeNullOrEmptyString.ps1 new file mode 100644 index 000000000..b44a09137 --- /dev/null +++ b/src/functions/assert/String/Should-NotBeNullOrEmptyString.ps1 @@ -0,0 +1,57 @@ +function Get-StringNotNullOrEmptyDefaultFailureMessage ($Actual, $Because) { + Get-AssertionMessage -Actual $Actual -Because $Because -DefaultMessage "Expected a [string] that is not `$null or empty, but got : " -Pretty +} + +function Assert-StringNotNullOrEmpty { + <# + .SYNOPSIS + Ensures that the input is a string, and that the input is not $null, empty, or whitespace only string. + + .PARAMETER Actual + The actual value that will be compared. + + .PARAMETER Because + The reason why the input should be a string that is not $null, empty, or whitespace only string. + + .EXAMPLE + ```powershell + $actual = "hello" + $actual | Should-NotBeNullOrEmptyString + ``` + + This test will pass. + + .EXAMPLE + ```powershell + $actual = " " + $actual | Should-NotBeNullOrEmptyString + ``` + + This test will fail, the input is a whitespace only string. + + .EXAMPLE + ``` + $null | Should-NotBeNullOrEmptyString + "" | Should-NotBeNullOrEmptyString + $() | Should-NotBeNullOrEmptyString + $false | Should-NotBeNullOrEmptyString + 1 | Should-NotBeNullOrEmptyString + ``` + + All the tests above will fail, the input is not a string. + #> + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] + param ( + [Parameter(Position = 0, ValueFromPipeline = $true)] + $Actual, + [String]$Because + ) + + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual + + if (-not (Test-StringNullOrEmpty -Actual $Actual)) { + $formattedMessage = Get-StringNotNullOrEmptyDefaultFailureMessage -Actual $Actual -Because $Because + throw [Pester.Factory]::CreateShouldErrorRecord($formattedMessage, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) + } +} diff --git a/src/functions/assert/String/Should-NotBeNullOrWhitespaceString.ps1 b/src/functions/assert/String/Should-NotBeNullOrWhitespaceString.ps1 new file mode 100644 index 000000000..eab633039 --- /dev/null +++ b/src/functions/assert/String/Should-NotBeNullOrWhitespaceString.ps1 @@ -0,0 +1,57 @@ +function Get-StringNotNullOrWhiteSpaceDefaultFailureMessage ($Actual, $Because) { + Get-AssertionMessage -Actual $Actual -Because $Because -DefaultMessage "Expected a [string] that is not `$null, empty or whitespace, but got : " -Pretty +} + +function Assert-StringNotNullOrWhiteSpace { + <# + .SYNOPSIS + Ensures that the input is a string, and that the input is not $null, empty, or whitespace only string. + + .PARAMETER Actual + The actual value that will be compared. + + .PARAMETER Because + The reason why the input should be a string that is not $null, empty, or whitespace only string. + + .EXAMPLE + ```powershell + $actual = "hello" + $actual | Should-NotBeNullOrWhiteSpaceString + ``` + + This test will pass. + + .EXAMPLE + ```powershell + $actual = " " + $actual | Should-NotBeNullOrWhiteSpaceString + ``` + + This test will fail, the input is a whitespace only string. + + .EXAMPLE + ``` + $null | Should-NotBeNullOrWhiteSpaceString + "" | Should-NotBeNullOrWhiteSpaceString + $() | Should-NotBeNullOrWhiteSpaceString + $false | Should-NotBeNullOrWhiteSpaceString + 1 | Should-NotBeNullOrWhiteSpaceString + ``` + + All the tests above will fail, the input is not a string. + #> + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] + param ( + [Parameter(Position = 0, ValueFromPipeline = $true)] + $Actual, + [String]$Because + ) + + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual + + if (-not (Test-StringNullOrWhiteSpace -Actual $Actual)) { + $formattedMessage = Get-StringNotNullOrWhiteSpaceDefaultFailureMessage -Actual $Actual -Because $Because + throw [Pester.Factory]::CreateShouldErrorRecord($formattedMessage, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) + } +} diff --git a/tst/functions/assert/String/Should-NotBeNullOrEmptyString.Tests.ps1 b/tst/functions/assert/String/Should-NotBeNullOrEmptyString.Tests.ps1 new file mode 100644 index 000000000..9e9a9184b --- /dev/null +++ b/tst/functions/assert/String/Should-NotBeNullOrEmptyString.Tests.ps1 @@ -0,0 +1,74 @@ +Set-StrictMode -Version Latest + +InPesterModuleScope { + Describe "Test-StringNullOrEmpty" { + It "non-empty string, or whitespace returns `$false" -ForEach @( + @{ Actual = "1" } + @{ Actual = " " } + @{ Actual = "`t" } + @{ Actual = "`n" } + @{ Actual = "`r" } + ) { + Test-StringNullOrEmpty -Actual $Actual | Verify-True + } + + It "empty string, or null returns `$true" -ForEach @( + @{ Actual = "" } + @{ Actual = $null } + ) { + Test-StringNullOrEmpty -Actual $Actual | Verify-False + } + } + + Describe "Get-StringNotNullOrEmptyDefaultFailureMessage" { + It "Throws with default message when test fails" { + $expected = Get-StringNotNullOrEmptyDefaultFailureMessage -Actual "" + $exception = { Should-NotBeNullOrEmptyString -Actual "" } | Verify-AssertionFailed + "$exception" | Verify-Equal $expected + } + + It "Throws with default message and because when test fails" { + $expected = Get-StringNotNullOrEmptyDefaultFailureMessage -Actual "" -Because "abc" + $exception = { Should-NotBeNullOrEmptyString -Actual "" -Because "abc" } | Verify-AssertionFailed + "$exception" | Verify-Equal $expected + } + } +} + +Describe "Should-NotBeNullOrEmptyString" { + It "Does not throw when string has value" { + "bde" | Should-NotBeNullOrEmptyString + } + + It "Throws when string is `$null or empty" -ForEach @( + @{ Actual = "" } + @{ Actual = $null } + ) { + { $Actual | Should-NotBeNullOrEmptyString } | Verify-AssertionFailed + } + + It "Throws when value is not string" -ForEach @( + @{ Actual = 1 } + @{ Actual = @() } + @{ Actual = $true } + ) { + { $Actual | Should-NotBeNullOrEmptyString } | Verify-AssertionFailed + } + + + It "Allows actual to be passed from pipeline" { + "abc" | Should-NotBeNullOrEmptyString + } + + It "Allows actual to be passed by position" { + Should-NotBeNullOrEmptyString "abc" + } + + It "Fails when empty collection is passed in by pipeline" { + { @() | Should-NotBeNullOrEmptyString } | Verify-AssertionFailed + } + + It "Fails when `$null collection is passed in by pipeline" { + { $null | Should-NotBeNullOrEmptyString } | Verify-AssertionFailed + } +} diff --git a/tst/functions/assert/String/Should-NotBeNullOrWhiteSpaceString.Tests.ps1 b/tst/functions/assert/String/Should-NotBeNullOrWhiteSpaceString.Tests.ps1 new file mode 100644 index 000000000..21496a11c --- /dev/null +++ b/tst/functions/assert/String/Should-NotBeNullOrWhiteSpaceString.Tests.ps1 @@ -0,0 +1,78 @@ +Set-StrictMode -Version Latest + +InPesterModuleScope { + Describe "Test-StringNullOrWhiteSpace" { + It "non-empty string returns `$false" -ForEach @( + @{ Actual = "1" } + ) { + Test-StringNullOrWhiteSpace -Actual $Actual | Verify-True + } + + It "empty string, whitespace, or null returns `$true" -ForEach @( + @{ Actual = "" } + @{ Actual = " " } + @{ Actual = "`t" } + @{ Actual = "`n" } + @{ Actual = "`r" } + @{ Actual = $null } + ) { + Test-StringNullOrWhiteSpace -Actual $Actual | Verify-False + } + } + + Describe "Get-StringNotNullOrWhiteSpaceDefaultFailureMessage" { + It "Throws with default message when test fails" { + $expected = Get-StringNotNullOrWhiteSpaceDefaultFailureMessage -Actual "" + $exception = { Should-NotBeNullOrWhiteSpaceString -Actual "" } | Verify-AssertionFailed + "$exception" | Verify-Equal $expected + } + + It "Throws with default message and because when test fails" { + $expected = Get-StringNotNullOrWhiteSpaceDefaultFailureMessage -Actual "" -Because "abc" + $exception = { Should-NotBeNullOrWhiteSpaceString -Actual "" -Because "abc" } | Verify-AssertionFailed + "$exception" | Verify-Equal $expected + } + } +} + +Describe "Should-NotBeNullOrWhiteSpaceString" { + It "Does not throw when string has value" { + "bde" | Should-NotBeNullOrWhiteSpaceString + } + + It "Throws when string is emptyish" -ForEach @( + @{ Actual = "" } + @{ Actual = " " } + @{ Actual = "`t" } + @{ Actual = "`n" } + @{ Actual = "`r" } + @{ Actual = $null } + ) { + { $Actual | Should-NotBeNullOrWhiteSpaceString } | Verify-AssertionFailed + } + + It "Throws when value is not string" -ForEach @( + @{ Actual = 1 } + @{ Actual = @() } + @{ Actual = $true } + ) { + { $Actual | Should-NotBeNullOrWhiteSpaceString } | Verify-AssertionFailed + } + + + It "Allows actual to be passed from pipeline" { + "abc" | Should-NotBeNullOrWhiteSpaceString + } + + It "Allows actual to be passed by position" { + Should-NotBeNullOrWhiteSpaceString "abc" + } + + It "Fails when empty collection is passed in by pipeline" { + { @() | Should-NotBeNullOrWhiteSpaceString } | Verify-AssertionFailed + } + + It "Fails when `$null collection is passed in by pipeline" { + { $null | Should-NotBeNullOrWhiteSpaceString } | Verify-AssertionFailed + } +} From 0560d77d5ece5dd11932bffa5e2e0cd9cc6fe90d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Sun, 21 Apr 2024 00:25:57 +0200 Subject: [PATCH 19/55] formatting almost fixed --- src/Module.ps1 | 11 +- src/Pester.psd1 | 4 +- src/functions/assert/Boolean/Assert-False.ps1 | 2 +- src/functions/assert/Boolean/Assert-True.ps1 | 2 +- .../assert/Collection/Assert-All.ps1 | 2 +- .../assert/Collection/Assert-Any.ps1 | 2 +- .../assert/Collection/Assert-Contain.ps1 | 2 +- .../assert/Collection/Assert-NotContain.ps1 | 9 +- .../assert/Equivalence/Assert-Equivalent.ps1 | 22 ++-- .../assert/String/Should-BeEmptyString.ps1 | 20 +--- .../String/Should-BeNullOrEmptyString.ps1 | 3 - ...ring.ps1 => Should-BeWhiteSpaceString.ps1} | 2 +- ...String.ps1 => Should-NotBeEmptyString.ps1} | 19 ++-- ...g.ps1 => Should-NotBeWhiteSpaceString.ps1} | 10 +- .../assert/Boolean/Assert-False.Tests.ps1 | 4 +- .../assert/Boolean/Assert-True.Tests.ps1 | 4 +- .../assert/Collection/Assert-All.Tests.ps1 | 2 +- .../assert/Collection/Assert-Any.Tests.ps1 | 9 +- .../Collection/Assert-Contain.Tests.ps1 | 12 +- .../Collection/Assert-NotContain.Tests.ps1 | 10 +- .../assert/Common/Collect-Input.Tests.ps1 | 11 -- .../Common/Get-AssertionMessage.Tests.ps1 | 20 ++-- .../Equivalence/Assert-Equivalent.Tests.ps1 | 104 +++++++++--------- .../General/Assert-LessThanOrEqual.Tests.ps1 | 6 +- .../assert/General/Assert-NotEqual.Tests.ps1 | 4 +- .../assert/General/Assert-NotSame.Tests.ps1 | 4 +- .../assert/General/Assert-Same.Tests.ps1 | 4 +- .../String/Should-BeEmptyString.Tests.ps1 | 85 ++++++-------- .../Should-NotBeNullOrEmptyString.Tests.ps1 | 56 ++++------ ...ould-NotBeNullOrWhiteSpaceString.Tests.ps1 | 48 ++------ 30 files changed, 197 insertions(+), 296 deletions(-) delete mode 100644 src/functions/assert/String/Should-BeNullOrEmptyString.ps1 rename src/functions/assert/String/{Should-BeNullOrWhiteSpaceString.ps1 => Should-BeWhiteSpaceString.ps1} (59%) rename src/functions/assert/String/{Should-NotBeNullOrEmptyString.ps1 => Should-NotBeEmptyString.ps1} (66%) rename src/functions/assert/String/{Should-NotBeNullOrWhitespaceString.ps1 => Should-NotBeWhiteSpaceString.ps1} (76%) diff --git a/src/Module.ps1 b/src/Module.ps1 index bb3ba665e..5e9e16f9e 100644 --- a/src/Module.ps1 +++ b/src/Module.ps1 @@ -28,12 +28,15 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session & $SafeCommands['Set-Alias'] 'Should-BeNull' 'Assert-Null' & $SafeCommands['Set-Alias'] 'Should-BeSame' 'Assert-Same' & $SafeCommands['Set-Alias'] 'Should-BeType' 'Assert-Type' + +& $SafeCommands['Set-Alias'] 'Should-BeString' 'Assert-StringEqual' +& $SafeCommands['Set-Alias'] 'Should-NotBeString' 'Assert-StringNotEqual' & $SafeCommands['Set-Alias'] 'Should-BeLikeString' 'Assert-Like' & $SafeCommands['Set-Alias'] 'Should-NotBeLikeString' 'Assert-NotLike' & $SafeCommands['Set-Alias'] 'Should-BeEmptyString' 'Assert-StringEmpty' -& $SafeCommands['Set-Alias'] 'Should-NotBeNullOrWhiteSpaceString' 'Assert-StringNotNullOrWhiteSpace' -& $SafeCommands['Set-Alias'] 'Should-NotBeNullOrEmptyString' 'Assert-StringNotNullOrEmpty' +& $SafeCommands['Set-Alias'] 'Should-NotBeNullOrWhiteSpaceString' 'Assert-StringNotWhiteSpace' +& $SafeCommands['Set-Alias'] 'Should-NotBeNullOrEmptyString' 'Assert-StringNotEmpty' @@ -97,8 +100,8 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session 'Assert-StringNotEqual' 'Assert-StringEmpty' - 'Assert-StringNotNullOrWhiteSpace' - 'Assert-StringNotNullOrEmpty' + 'Assert-StringNotWhiteSpace' + 'Assert-StringNotEmpty' # export 'Export-NUnitReport' diff --git a/src/Pester.psd1 b/src/Pester.psd1 index 30a7cc3a7..90cb808e9 100644 --- a/src/Pester.psd1 +++ b/src/Pester.psd1 @@ -92,8 +92,8 @@ 'Assert-StringEqual' 'Assert-StringNotEqual' 'Assert-StringEmpty' - 'Assert-StringNotNullOrWhiteSpace' - 'Assert-StringNotNullOrEmpty' + 'Assert-StringNotWhiteSpace' + 'Assert-StringNotEmpty' # legacy 'Assert-VerifiableMock' diff --git a/src/functions/assert/Boolean/Assert-False.ps1 b/src/functions/assert/Boolean/Assert-False.ps1 index fb5230d19..c25903f0b 100644 --- a/src/functions/assert/Boolean/Assert-False.ps1 +++ b/src/functions/assert/Boolean/Assert-False.ps1 @@ -9,7 +9,7 @@ $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if ($Actual) { - $Message = Get-AssertionMessage -Expected $false -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be '' or falsy value 0, """", `$null, @()." + $Message = Get-AssertionMessage -Expected $false -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected to be or falsy value 0, """", `$null, @()." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/Boolean/Assert-True.ps1 b/src/functions/assert/Boolean/Assert-True.ps1 index bae30fc50..987c06c1c 100644 --- a/src/functions/assert/Boolean/Assert-True.ps1 +++ b/src/functions/assert/Boolean/Assert-True.ps1 @@ -9,7 +9,7 @@ $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if (-not $Actual) { - $Message = Get-AssertionMessage -Expected $true -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be '' or truthy value." + $Message = Get-AssertionMessage -Expected $true -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected to be or truthy value." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/Collection/Assert-All.ps1 b/src/functions/assert/Collection/Assert-All.ps1 index 849453ba7..91ee1bf6d 100644 --- a/src/functions/assert/Collection/Assert-All.ps1 +++ b/src/functions/assert/Collection/Assert-All.ps1 @@ -33,7 +33,7 @@ actualFiltered = $actualFiltered actualFilteredCount = $actualFiltered.Count } - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Data $data -CustomMessage $CustomMessage -DefaultMessage "Expected all items in collection '' to pass filter '', but of them '' did not pass the filter." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Data $data -CustomMessage $CustomMessage -DefaultMessage "Expected all items in collection to pass filter , but of them did not pass the filter." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/Collection/Assert-Any.ps1 b/src/functions/assert/Collection/Assert-Any.ps1 index 90b37d342..dc32e5542 100644 --- a/src/functions/assert/Collection/Assert-Any.ps1 +++ b/src/functions/assert/Collection/Assert-Any.ps1 @@ -12,7 +12,7 @@ $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if (-not ($Actual | & $SafeCommands['Where-Object'] -FilterScript $FilterScript)) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected at least one item in collection '' to pass filter '', but none of the items passed the filter." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected at least one item in collection to pass filter , but none of the items passed the filter." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/Collection/Assert-Contain.ps1 b/src/functions/assert/Collection/Assert-Contain.ps1 index 233e365cd..e4eed57b5 100644 --- a/src/functions/assert/Collection/Assert-Contain.ps1 +++ b/src/functions/assert/Collection/Assert-Contain.ps1 @@ -13,7 +13,7 @@ if ($Actual -notcontains $Expected) { $type = [string]$Expected - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be present in collection '', but it was not there." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected to be present in collection , but it was not there." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/Collection/Assert-NotContain.ps1 b/src/functions/assert/Collection/Assert-NotContain.ps1 index f582d310f..65463de12 100644 --- a/src/functions/assert/Collection/Assert-NotContain.ps1 +++ b/src/functions/assert/Collection/Assert-NotContain.ps1 @@ -1,19 +1,18 @@ function Assert-NotContain { [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( - [Parameter(Position=1, ValueFromPipeline=$true)] + [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position=0)] + [Parameter(Position = 0)] $Expected, [String]$CustomMessage ) $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual - if ($Actual -contains $Expected) - { + if ($Actual -contains $Expected) { $type = [string]$Expected - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to not be present in collection '', but it was there." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected to not be present in collection , but it was there." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/Equivalence/Assert-Equivalent.ps1 b/src/functions/assert/Equivalence/Assert-Equivalent.ps1 index a3b2f39f5..a4b966ad2 100644 --- a/src/functions/assert/Equivalence/Assert-Equivalent.ps1 +++ b/src/functions/assert/Equivalence/Assert-Equivalent.ps1 @@ -20,7 +20,7 @@ function Get-ValueNotEquivalentMessage ($Expected, $Actual, $Property, $Options) $Actual = Format-Nicely2 -Value $Actual $propertyInfo = if ($Property) { " property $Property with value" } $comparison = if ("Equality" -eq $Options.Comparator) { 'equal' } else { 'equivalent' } - "Expected$propertyInfo '$Expected' to be $comparison to the actual value, but got '$Actual'." + "Expected$propertyInfo $Expected to be $comparison to the actual value, but got $Actual." } @@ -34,7 +34,7 @@ function Get-CollectionSizeNotTheSameMessage ($Actual, $Expected, $Property) { if ($property) { $propertyMessage = " in property $Property with values" } - "Expected collection$propertyMessage '$Expected' with length '$expectedLength' to be the same size as the actual collection, but got '$Actual' with length '$actualLength'." + "Expected collection$propertyMessage $Expected with length $expectedLength to be the same size as the actual collection, but got $Actual with length $actualLength." } function Get-DataTableSizeNotTheSameMessage ($Actual, $Expected, $Property) { @@ -47,7 +47,7 @@ function Get-DataTableSizeNotTheSameMessage ($Actual, $Expected, $Property) { if ($property) { $propertyMessage = " in property $Property with values" } - "Expected DataTable$propertyMessage '$Expected' with length '$expectedLength' to be the same size as the actual DataTable, but got '$Actual' with length '$actualLength'." + "Expected DataTable$propertyMessage $Expected with length $expectedLength to be the same size as the actual DataTable, but got $Actual with length $actualLength." } function Compare-CollectionEquivalent ($Expected, $Actual, $Property, $Options) { @@ -60,7 +60,7 @@ function Compare-CollectionEquivalent ($Expected, $Actual, $Property, $Options) $expectedFormatted = Format-Collection2 -Value $Expected $expectedLength = $expected.Length $actualFormatted = Format-Nicely2 -Value $actual - return "Expected collection '$expectedFormatted' with length '$expectedLength', but got '$actualFormatted'." + return "Expected collection $expectedFormatted with length $expectedLength, but got $actualFormatted." } if (-not (Is-CollectionSize -Expected $Expected -Actual $Actual)) { @@ -129,7 +129,7 @@ function Compare-CollectionEquivalent ($Expected, $Actual, $Property, $Options) $notFoundFormatted = Format-Nicely2 -Value ( $notFound | ForEach-Object { Format-Nicely2 -Value $_ } ) $propertyMessage = if ($Property) { " in property $Property which is" } - return "Expected collection$propertyMessage '$Expected' to be equivalent to '$Actual' but some values were missing: '$notFoundFormatted'." + return "Expected collection$propertyMessage $Expected to be equivalent to $Actual but some values were missing: $notFoundFormatted." } v -Equivalence "`$Actual and `$Expected arrays are equivalent." } @@ -143,7 +143,7 @@ function Compare-DataTableEquivalent ($Expected, $Actual, $Property, $Options) { $expectedFormatted = Format-Collection2 -Value $Expected $expectedLength = $expected.Rows.Count $actualFormatted = Format-Nicely2 -Value $actual - return "Expected DataTable '$expectedFormatted' with length '$expectedLength', but got '$actualFormatted'." + return "Expected DataTable $expectedFormatted with length $expectedLength, but got $actualFormatted." } if (-not (Is-DataTableSize -Expected $Expected -Actual $Actual)) { @@ -260,7 +260,7 @@ function Compare-HashtableEquivalent ($Actual, $Expected, $Property, $Options) { v -Difference "`$Actual is not a hashtable it is a $(Format-Nicely2 $Actual.GetType()), so they are not equivalent." $expectedFormatted = Format-Nicely2 -Value $Expected $actualFormatted = Format-Nicely2 -Value $Actual - return "Expected hashtable '$expectedFormatted', but got '$actualFormatted'." + return "Expected hashtable $expectedFormatted, but got $actualFormatted." } # todo: if either side or both sides are empty hashtable make the verbose output shorter and nicer @@ -311,7 +311,7 @@ function Compare-HashtableEquivalent ($Actual, $Expected, $Property, $Options) { v -Difference "Hashtables `$Actual and `$Expected are not equivalent." $expectedFormatted = Format-Nicely2 -Value $Expected $actualFormatted = Format-Nicely2 -Value $Actual - return "Expected hashtable '$expectedFormatted', but got '$actualFormatted'.`n$($result -join "`n")" + return "Expected hashtable $expectedFormatted, but got $actualFormatted.`n$($result -join "`n")" } v -Equivalence "Hastables `$Actual and `$Expected are equivalent." @@ -326,7 +326,7 @@ function Compare-DictionaryEquivalent ($Actual, $Expected, $Property, $Options) v -Difference "`$Actual is not a dictionary it is a $(Format-Nicely2 $Actual.GetType()), so they are not equivalent." $expectedFormatted = Format-Nicely2 -Value $Expected $actualFormatted = Format-Nicely2 -Value $Actual - return "Expected dictionary '$expectedFormatted', but got '$actualFormatted'." + return "Expected dictionary $expectedFormatted, but got $actualFormatted." } # todo: if either side or both sides are empty dictionary make the verbose output shorter and nicer @@ -375,7 +375,7 @@ function Compare-DictionaryEquivalent ($Actual, $Expected, $Property, $Options) v -Difference "Dictionaries `$Actual and `$Expected are not equivalent." $expectedFormatted = Format-Nicely2 -Value $Expected $actualFormatted = Format-Nicely2 -Value $Actual - return "Expected dictionary '$expectedFormatted', but got '$actualFormatted'.`n$($result -join "`n")" + return "Expected dictionary $expectedFormatted, but got $actualFormatted.`n$($result -join "`n")" } v -Equivalence "Dictionaries `$Actual and `$Expected are equivalent." } @@ -390,7 +390,7 @@ function Compare-ObjectEquivalent ($Actual, $Expected, $Property, $Options) { v -Difference "`$Actual is not an object it is a $(Format-Nicely2 $Actual.GetType()), so they are not equivalent." $expectedFormatted = Format-Nicely2 -Value $Expected $actualFormatted = Format-Nicely2 -Value $Actual - return "Expected object '$expectedFormatted', but got '$actualFormatted'." + return "Expected object $expectedFormatted, but got $actualFormatted." } $actualProperties = $Actual.PsObject.Properties diff --git a/src/functions/assert/String/Should-BeEmptyString.ps1 b/src/functions/assert/String/Should-BeEmptyString.ps1 index 344acb683..6bcf3570e 100644 --- a/src/functions/assert/String/Should-BeEmptyString.ps1 +++ b/src/functions/assert/String/Should-BeEmptyString.ps1 @@ -1,17 +1,4 @@ -function Test-StringEmpty { - param ( - $Actual - ) - - - $Actual -is [string] -and [string]::Empty -eq $Actual -} - -function Get-StringEmptyDefaultFailureMessage ($Actual, $Because) { - Get-AssertionMessage -Actual $Actual -Because $Because -DefaultMessage "Expected an empty string, but got : " -Pretty -} - -function Assert-StringEmpty { +function Assert-StringEmpty { <# .SYNOPSIS Ensures that input is an empty string. @@ -58,9 +45,8 @@ function Assert-StringEmpty { $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual - $stringsAreEqual = Test-StringEmpty -Actual $Actual - if (-not ($stringsAreEqual)) { - $formattedMessage = Get-StringEmptyDefaultFailureMessage -Actual $Actual -Because $Because + if ($Actual -isnot [String] -or -not [String]::IsNullOrEmpty( $Actual)) { + $formattedMessage = Get-AssertionMessage -Actual $Actual -Because $Because -DefaultMessage "Expected a [string] that is empty, but got : " -Pretty throw [Pester.Factory]::CreateShouldErrorRecord($formattedMessage, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } } diff --git a/src/functions/assert/String/Should-BeNullOrEmptyString.ps1 b/src/functions/assert/String/Should-BeNullOrEmptyString.ps1 deleted file mode 100644 index 58a964ad5..000000000 --- a/src/functions/assert/String/Should-BeNullOrEmptyString.ps1 +++ /dev/null @@ -1,3 +0,0 @@ -function Test-StringNullOrEmpty ($Actual) { - $Actual -is [string] -and -not ([string]::IsNullOrEmpty($Actual)) -} diff --git a/src/functions/assert/String/Should-BeNullOrWhiteSpaceString.ps1 b/src/functions/assert/String/Should-BeWhiteSpaceString.ps1 similarity index 59% rename from src/functions/assert/String/Should-BeNullOrWhiteSpaceString.ps1 rename to src/functions/assert/String/Should-BeWhiteSpaceString.ps1 index 9f78c6be8..b465823dd 100644 --- a/src/functions/assert/String/Should-BeNullOrWhiteSpaceString.ps1 +++ b/src/functions/assert/String/Should-BeWhiteSpaceString.ps1 @@ -1,3 +1,3 @@ -function Test-StringNullOrWhiteSpace ($Actual) { +function Test-StringNotWhiteSpace ($Actual) { $Actual -is [string] -and -not ([string]::IsNullOrWhiteSpace($Actual)) } diff --git a/src/functions/assert/String/Should-NotBeNullOrEmptyString.ps1 b/src/functions/assert/String/Should-NotBeEmptyString.ps1 similarity index 66% rename from src/functions/assert/String/Should-NotBeNullOrEmptyString.ps1 rename to src/functions/assert/String/Should-NotBeEmptyString.ps1 index b44a09137..84288b231 100644 --- a/src/functions/assert/String/Should-NotBeNullOrEmptyString.ps1 +++ b/src/functions/assert/String/Should-NotBeEmptyString.ps1 @@ -1,17 +1,13 @@ -function Get-StringNotNullOrEmptyDefaultFailureMessage ($Actual, $Because) { - Get-AssertionMessage -Actual $Actual -Because $Because -DefaultMessage "Expected a [string] that is not `$null or empty, but got : " -Pretty -} - -function Assert-StringNotNullOrEmpty { +function Assert-StringNotEmpty { <# .SYNOPSIS - Ensures that the input is a string, and that the input is not $null, empty, or whitespace only string. + Ensures that the input is a string, and that the input is not $null or empty string. .PARAMETER Actual The actual value that will be compared. .PARAMETER Because - The reason why the input should be a string that is not $null, empty, or whitespace only string. + The reason why the input should be a string that is not $null or empty. .EXAMPLE ```powershell @@ -23,16 +19,15 @@ function Assert-StringNotNullOrEmpty { .EXAMPLE ```powershell - $actual = " " + $actual = "" $actual | Should-NotBeNullOrEmptyString ``` - This test will fail, the input is a whitespace only string. + This test will fail, the input is an empty string. .EXAMPLE ``` $null | Should-NotBeNullOrEmptyString - "" | Should-NotBeNullOrEmptyString $() | Should-NotBeNullOrEmptyString $false | Should-NotBeNullOrEmptyString 1 | Should-NotBeNullOrEmptyString @@ -50,8 +45,8 @@ function Assert-StringNotNullOrEmpty { $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual - if (-not (Test-StringNullOrEmpty -Actual $Actual)) { - $formattedMessage = Get-StringNotNullOrEmptyDefaultFailureMessage -Actual $Actual -Because $Because + if ($Actual -isnot [String] -or [String]::IsNullOrEmpty($Actual)) { + $formattedMessage = Get-AssertionMessage -Actual $Actual -Because $Because -DefaultMessage "Expected a [string] that is not `$null or empty, but got : " -Pretty throw [Pester.Factory]::CreateShouldErrorRecord($formattedMessage, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } } diff --git a/src/functions/assert/String/Should-NotBeNullOrWhitespaceString.ps1 b/src/functions/assert/String/Should-NotBeWhiteSpaceString.ps1 similarity index 76% rename from src/functions/assert/String/Should-NotBeNullOrWhitespaceString.ps1 rename to src/functions/assert/String/Should-NotBeWhiteSpaceString.ps1 index eab633039..878b17a62 100644 --- a/src/functions/assert/String/Should-NotBeNullOrWhitespaceString.ps1 +++ b/src/functions/assert/String/Should-NotBeWhiteSpaceString.ps1 @@ -1,8 +1,4 @@ -function Get-StringNotNullOrWhiteSpaceDefaultFailureMessage ($Actual, $Because) { - Get-AssertionMessage -Actual $Actual -Because $Because -DefaultMessage "Expected a [string] that is not `$null, empty or whitespace, but got : " -Pretty -} - -function Assert-StringNotNullOrWhiteSpace { +function Assert-StringNotWhiteSpace { <# .SYNOPSIS Ensures that the input is a string, and that the input is not $null, empty, or whitespace only string. @@ -50,8 +46,8 @@ function Assert-StringNotNullOrWhiteSpace { $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual - if (-not (Test-StringNullOrWhiteSpace -Actual $Actual)) { - $formattedMessage = Get-StringNotNullOrWhiteSpaceDefaultFailureMessage -Actual $Actual -Because $Because + if ($Actual -isnot [string] -or [string]::IsNullOrWhiteSpace($Actual)) { + $formattedMessage = Get-AssertionMessage -Actual $Actual -Because $Because -DefaultMessage "Expected a [string] that is not `$null, empty or whitespace, but got : " -Pretty throw [Pester.Factory]::CreateShouldErrorRecord($formattedMessage, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } } diff --git a/tst/functions/assert/Boolean/Assert-False.Tests.ps1 b/tst/functions/assert/Boolean/Assert-False.Tests.ps1 index 5ac36c378..456c41ffa 100644 --- a/tst/functions/assert/Boolean/Assert-False.Tests.ps1 +++ b/tst/functions/assert/Boolean/Assert-False.Tests.ps1 @@ -26,8 +26,8 @@ Describe "Assert-False" { Context "Validate messages" { It "Given value '' that is not `$false it returns expected message ''" -TestCases @( - @{ Actual = $true ; Message = "Expected bool '`$true' to be bool '`$false' or falsy value 0, """", `$null, @()." }, - @{ Actual = 10 ; Message = "Expected int '10' to be bool '`$false' or falsy value 0, """", `$null, @()." } + @{ Actual = $true ; Message = "Expected [bool] `$true to be [bool] `$false or falsy value 0, """", `$null, @()." }, + @{ Actual = 10 ; Message = "Expected [int] 10 to be [bool] `$false or falsy value 0, """", `$null, @()." } ) { param($Actual, $Message) $err = { Assert-False -Actual $Actual } | Verify-AssertionFailed diff --git a/tst/functions/assert/Boolean/Assert-True.Tests.ps1 b/tst/functions/assert/Boolean/Assert-True.Tests.ps1 index e7c214102..a3559abf0 100644 --- a/tst/functions/assert/Boolean/Assert-True.Tests.ps1 +++ b/tst/functions/assert/Boolean/Assert-True.Tests.ps1 @@ -22,8 +22,8 @@ Describe "Assert-True" { Context "Validate messages" { It "Given value that is not `$true it returns expected message ''" -TestCases @( - @{ Actual = $false ; Message = "Expected bool '`$false' to be bool '`$true' or truthy value." }, - @{ Actual = 0 ; Message = "Expected int '0' to be bool '`$true' or truthy value." } + @{ Actual = $false ; Message = "Expected [bool] `$false to be [bool] `$true or truthy value." }, + @{ Actual = 0 ; Message = "Expected [int] 0 to be [bool] `$true or truthy value." } ) { param($Actual, $Message) $err = { Assert-True -Actual $Actual } | Verify-AssertionFailed diff --git a/tst/functions/assert/Collection/Assert-All.Tests.ps1 b/tst/functions/assert/Collection/Assert-All.Tests.ps1 index 5d5c71edc..d2459c3c1 100644 --- a/tst/functions/assert/Collection/Assert-All.Tests.ps1 +++ b/tst/functions/assert/Collection/Assert-All.Tests.ps1 @@ -18,7 +18,7 @@ Describe "Assert-All" { } It "Validate messages" -TestCases @( - @{ Actual = @(3, 4, 5); Message = "Expected all items in collection '3, 4, 5' to pass filter '{ `$_ -eq 1 }', but 3 of them '3, 4, 5' did not pass the filter." } + @{ Actual = @(3, 4, 5); Message = "Expected all items in collection @(3, 4, 5) to pass filter { `$_ -eq 1 }, but 3 of them @(3, 4, 5) did not pass the filter." } ) { $err = { $Actual | Assert-All -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message diff --git a/tst/functions/assert/Collection/Assert-Any.Tests.ps1 b/tst/functions/assert/Collection/Assert-Any.Tests.ps1 index 7624bbb7e..3b644eff6 100644 --- a/tst/functions/assert/Collection/Assert-Any.Tests.ps1 +++ b/tst/functions/assert/Collection/Assert-Any.Tests.ps1 @@ -6,7 +6,6 @@ Describe "Assert-Any" { @{ Actual = @(1) } @{ Actual = 1 } ) { - param($Actual) $Actual | Assert-Any -FilterScript { $_ -eq 1 } } @@ -15,16 +14,14 @@ Describe "Assert-Any" { @{ Actual = @(1) } @{ Actual = 1 } ) { - param($Actual) { $Actual | Assert-Any -FilterScript { $_ -eq 0 } } | Verify-AssertionFailed } It "Validate messages" -TestCases @( - @{ Actual = @(3, 4, 5); Message = "Expected at least one item in collection '3, 4, 5' to pass filter '{ `$_ -eq 1 }', but none of the items passed the filter." } - @{ Actual = @(3); Message = "Expected at least one item in collection '3' to pass filter '{ `$_ -eq 1 }', but none of the items passed the filter." } - @{ Actual = 3; Message = "Expected at least one item in collection '3' to pass filter '{ `$_ -eq 1 }', but none of the items passed the filter." } + @{ Actual = @(3, 4, 5); Message = "Expected at least one item in collection @(3, 4, 5) to pass filter { `$_ -eq 1 }, but none of the items passed the filter." } + @{ Actual = 3; Message = "Expected at least one item in collection 3 to pass filter { `$_ -eq 1 }, but none of the items passed the filter." } + @{ Actual = 3; Message = "Expected at least one item in collection 3 to pass filter { `$_ -eq 1 }, but none of the items passed the filter." } ) { - param($Actual, $Message) $err = { $Actual | Assert-Any -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message } diff --git a/tst/functions/assert/Collection/Assert-Contain.Tests.ps1 b/tst/functions/assert/Collection/Assert-Contain.Tests.ps1 index bbcea6265..d425d64c8 100644 --- a/tst/functions/assert/Collection/Assert-Contain.Tests.ps1 +++ b/tst/functions/assert/Collection/Assert-Contain.Tests.ps1 @@ -8,20 +8,20 @@ InPesterModuleScope { It "Fails when collection of single item does not contain the expected item" { $err = { @(5) | Assert-Contain 1 } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "Expected int '1' to be present in collection '5', but it was not there." + $err.Exception.Message | Verify-Equal "Expected [int] 1 to be present in collection 5, but it was not there." } It "Passes when collection of multiple items contains the expected item" { - @(1,2,3) | Assert-Contain 1 + @(1, 2, 3) | Assert-Contain 1 } It "Fails when collection of multiple items does not contain the expected item" { - $err = { @(5,6,7) | Assert-Contain 1 } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "Expected int '1' to be present in collection '5, 6, 7', but it was not there." + $err = { @(5, 6, 7) | Assert-Contain 1 } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "Expected [int] 1 to be present in collection @(5, 6, 7), but it was not there." } - It "Can be called with positional parameters" { - { Assert-Contain 1 3,4,5 } | Verify-AssertionFailed + It "Can be called with positional parameters" { + { Assert-Contain 1 3, 4, 5 } | Verify-AssertionFailed } } } diff --git a/tst/functions/assert/Collection/Assert-NotContain.Tests.ps1 b/tst/functions/assert/Collection/Assert-NotContain.Tests.ps1 index 1dbb44062..21a987c4c 100644 --- a/tst/functions/assert/Collection/Assert-NotContain.Tests.ps1 +++ b/tst/functions/assert/Collection/Assert-NotContain.Tests.ps1 @@ -4,7 +4,7 @@ InPesterModuleScope { Describe "Assert-NotContain" { It "Fails when collection of single item contains the expected item" { $err = { @(1) | Assert-NotContain 1 } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "Expected int '1' to not be present in collection '1', but it was there." + $err.Exception.Message | Verify-Equal "Expected [int] 1 to not be present in collection 1, but it was there." } It "Passes when collection of single item does not contain the expected item" { @@ -12,16 +12,16 @@ InPesterModuleScope { } It "Fails when collection of multiple items contains the expected item" { - $err = { @(1,2,3) | Assert-NotContain 1 } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "Expected int '1' to not be present in collection '1, 2, 3', but it was there." + $err = { @(1, 2, 3) | Assert-NotContain 1 } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "Expected [int] 1 to not be present in collection @(1, 2, 3), but it was there." } It "Passes when collection of multiple items does not contain the expected item" { - @(5,6,7) | Assert-NotContain 1 + @(5, 6, 7) | Assert-NotContain 1 } It "Can be called with positional parameters" { - { Assert-NotContain 1 1,2,3 } | Verify-AssertionFailed + { Assert-NotContain 1 1, 2, 3 } | Verify-AssertionFailed } } } diff --git a/tst/functions/assert/Common/Collect-Input.Tests.ps1 b/tst/functions/assert/Common/Collect-Input.Tests.ps1 index b06c8e069..287a21c0f 100644 --- a/tst/functions/assert/Common/Collect-Input.Tests.ps1 +++ b/tst/functions/assert/Common/Collect-Input.Tests.ps1 @@ -36,17 +36,6 @@ InPesterModuleScope { } } - It "Given @("""") through pipeline it captures @("""")" { - $collectedInput = @($null) | Assert-PassThru - $collectedInput2 = "" | Assert-PassThru - - Verify-True $collectedInput.IsPipelineInput - Verify-Type -Actual $collectedInput.Actual -Expected ([Object[]]) - if (@("") -ne $collectedInput.Actual) { - throw "Expected @(), but got $(Format-Nicely2 $collectedInput.Actual)." - } - } - It "Given List[int] through pipeline it captures the items in Object[]" { $collectedInput = [Collections.Generic.List[int]]@(1, 2) | Assert-PassThru diff --git a/tst/functions/assert/Common/Get-AssertionMessage.Tests.ps1 b/tst/functions/assert/Common/Get-AssertionMessage.Tests.ps1 index b6f5a8b73..a65c5d650 100644 --- a/tst/functions/assert/Common/Get-AssertionMessage.Tests.ps1 +++ b/tst/functions/assert/Common/Get-AssertionMessage.Tests.ps1 @@ -15,36 +15,36 @@ InPesterModuleScope { } It "returns correct message when complex objects are provided" { - $expected = "We expected string to be PSObject{Age=28; Name=Jakub}, but got 2." + $expected = "We expected string to be PSObject{Age=28; Name='Jakub'}, but got 2." $customMessage = "We expected string to be , but got ." - Get-AssertionMessage -CustomMessage $customMessage -Expected (New-PSObject @{Name='Jakub';Age=28}) -Actual 2 | Verify-Equal $expected + Get-AssertionMessage -CustomMessage $customMessage -Expected (New-PSObject @{Name = 'Jakub'; Age = 28 }) -Actual 2 | Verify-Equal $expected } It "returns correct message when type tokens are provided" { - $expected = "We expected string to be PSObject, but got int." + $expected = "We expected string to be [PSObject], but got [int]." $customMessage = "We expected string to be , but got ." - Get-AssertionMessage -CustomMessage $customMessage -Expected (New-PSObject @{Name='Jakub';Age=28}) -Actual 2 | Verify-Equal $expected + Get-AssertionMessage -CustomMessage $customMessage -Expected (New-PSObject @{Name = 'Jakub'; Age = 28 }) -Actual 2 | Verify-Equal $expected } - It "returns correct type message when `$null is provided" { - $expected = "Expected type is , and actual type is ." + It "returns correct type message when `$null is provided" { + $expected = "Expected type is [null], and actual type is [null]." $customMessage = "Expected type is , and actual type is ." Get-AssertionMessage -CustomMessage $customMessage -Expected $null -Actual $null | Verify-Equal $expected } - It "returns correct message when option is provided" { + It "returns correct message when option is provided" { $expected = "Expected 'a', but got 'b'. Used options: CaseSensitive, IgnoreWhitespace." $customMessage = "Expected 'a', but got 'b'. " - Get-AssertionMessage -CustomMessage $customMessage -Expected 'a' -Actual 'b' -Option "CaseSensitive","IgnoreWhitespace" | Verify-Equal $expected + Get-AssertionMessage -CustomMessage $customMessage -Expected 'a' -Actual 'b' -Option "CaseSensitive", "IgnoreWhitespace" | Verify-Equal $expected } It "returns correct message when additional data are provided" { - $expected = "but 3 of them '1, 2, 3' did not pass the filter." + $expected = "but 3 of them '@(1, 2, 3)' did not pass the filter." $customMessage = "but of them '' did not pass the filter." $data = @{ actualFilteredCount = 3 - actualFiltered = 1, 2, 3 + actualFiltered = 1, 2, 3 } Get-AssertionMessage -CustomMessage $customMessage -Data $data | Verify-Equal $expected diff --git a/tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 b/tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 index 94bf85f8f..334c2231a 100644 --- a/tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 +++ b/tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 @@ -85,35 +85,35 @@ InPesterModuleScope { $e = 'abc' $a = New-PSObject @{ Name = 'Jakub'; Age = 28 } Get-ValueNotEquivalentMessage -Actual $a -Expected $e | - Verify-Equal "Expected 'abc' to be equivalent to the actual value, but got 'PSObject{Age=28; Name=Jakub}'." + Verify-Equal "Expected 'abc' to be equivalent to the actual value, but got PSObject{Age=28; Name='Jakub'}." } It "Returns correct message when comparing object to a value" { $e = New-PSObject @{ Name = 'Jakub'; Age = 28 } $a = 'abc' Get-ValueNotEquivalentMessage -Actual $a -Expected $e | - Verify-Equal "Expected 'PSObject{Age=28; Name=Jakub}' to be equivalent to the actual value, but got 'abc'." + Verify-Equal "Expected PSObject{Age=28; Name='Jakub'} to be equivalent to the actual value, but got 'abc'." } It "Returns correct message when comparing value to an array" { $e = 'abc' $a = 1, 2, 3 Get-ValueNotEquivalentMessage -Actual $a -Expected $e | - Verify-Equal "Expected 'abc' to be equivalent to the actual value, but got '1, 2, 3'." + Verify-Equal "Expected 'abc' to be equivalent to the actual value, but got @(1, 2, 3)." } It "Returns correct message when comparing value to null" { $e = 'abc' $a = $null Get-ValueNotEquivalentMessage -Actual $a -Expected $e | - Verify-Equal "Expected 'abc' to be equivalent to the actual value, but got '`$null'." + Verify-Equal "Expected 'abc' to be equivalent to the actual value, but got `$null." } It "Returns correct message for given property" { $e = 1 $a = 2 Get-ValueNotEquivalentMessage -Actual 1 -Expected 2 -Property ".Age" | - Verify-Equal "Expected property .Age with value '2' to be equivalent to the actual value, but got '1'." + Verify-Equal "Expected property .Age with value 2 to be equivalent to the actual value, but got 1." } It "Changes wording to 'equal' when options specify Equality comparator" { @@ -121,7 +121,7 @@ InPesterModuleScope { $a = 2 $options = Get-EquivalencyOption -Comparator Equality Get-ValueNotEquivalentMessage -Actual 1 -Expected 2 -Options $options | - Verify-Equal "Expected '2' to be equal to the actual value, but got '1'." + Verify-Equal "Expected 2 to be equal to the actual value, but got 1." } } @@ -146,7 +146,7 @@ InPesterModuleScope { Describe "Get-CollectionSizeNotTheSameMessage" { It "Given two collections of differrent sizes it returns the correct message" { - Get-CollectionSizeNotTheSameMessage -Expected (1, 2, 3) -Actual (1, 2) | Verify-Equal "Expected collection '1, 2, 3' with length '3' to be the same size as the actual collection, but got '1, 2' with length '2'." + Get-CollectionSizeNotTheSameMessage -Expected (1, 2, 3) -Actual (1, 2) | Verify-Equal "Expected collection @(1, 2, 3) with length 3 to be the same size as the actual collection, but got @(1, 2) with length 2." } } @@ -157,17 +157,17 @@ InPesterModuleScope { } It "Given values '' and '' that are not equivalent it returns message ''." -TestCases @( - @{ Actual = $null; Expected = 1; Message = "Expected '1' to be equivalent to the actual value, but got '`$null'." }, - @{ Actual = $null; Expected = ""; Message = "Expected '' to be equivalent to the actual value, but got '`$null'." }, - @{ Actual = $true; Expected = $false; Message = "Expected '`$false' to be equivalent to the actual value, but got '`$true'." }, - @{ Actual = $true; Expected = 'False'; Message = "Expected '`$false' to be equivalent to the actual value, but got '`$true'." }, - @{ Actual = 1; Expected = -1; Message = "Expected '-1' to be equivalent to the actual value, but got '1'." }, - @{ Actual = "1"; Expected = 1.01; Message = "Expected '1.01' to be equivalent to the actual value, but got '1'." }, + @{ Actual = $null; Expected = 1; Message = "Expected 1 to be equivalent to the actual value, but got `$null." }, + @{ Actual = $null; Expected = ""; Message = "Expected to be equivalent to the actual value, but got `$null." }, + @{ Actual = $true; Expected = $false; Message = "Expected `$false to be equivalent to the actual value, but got `$true." }, + @{ Actual = $true; Expected = 'False'; Message = "Expected `$false to be equivalent to the actual value, but got `$true." }, + @{ Actual = 1; Expected = -1; Message = "Expected -1 to be equivalent to the actual value, but got 1." }, + @{ Actual = "1"; Expected = 1.01; Message = "Expected 1.01 to be equivalent to the actual value, but got '1'." }, @{ Actual = "abc"; Expected = "a b c"; Message = "Expected 'a b c' to be equivalent to the actual value, but got 'abc'." }, - @{ Actual = @("abc", "bde"); Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got 'abc, bde'." }, - @{ Actual = { def }; Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got '{ def }'." }, - @{ Actual = (New-PSObject @{ Name = 'Jakub' }); Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got 'PSObject{Name=Jakub}'." }, - @{ Actual = (1, 2, 3); Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got '1, 2, 3'." } + @{ Actual = @("abc", "bde"); Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got @('abc', 'bde')." }, + @{ Actual = { def }; Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got { def }." }, + @{ Actual = (New-PSObject @{ Name = 'Jakub' }); Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got PSObject{Name='Jakub'}." }, + @{ Actual = (1, 2, 3); Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got @(1, 2, 3)." } ) { param($Actual, $Expected, $Message) Compare-ValueEquivalent -Actual $Actual -Expected $Expected | Verify-Equal $Message @@ -181,16 +181,16 @@ InPesterModuleScope { } It "Given two collections '' '' of different sizes it returns message ''" -TestCases @( - @{ Actual = (1, 2, 3); Expected = (1, 2, 3, 4); Message = "Expected collection '1, 2, 3, 4' with length '4' to be the same size as the actual collection, but got '1, 2, 3' with length '3'." }, - @{ Actual = (1, 2, 3); Expected = (3, 1); Message = "Expected collection '3, 1' with length '2' to be the same size as the actual collection, but got '1, 2, 3' with length '3'." } + @{ Actual = (1, 2, 3); Expected = (1, 2, 3, 4); Message = "Expected collection @(1, 2, 3, 4) with length 4 to be the same size as the actual collection, but got @(1, 2, 3) with length 3." }, + @{ Actual = (1, 2, 3); Expected = (3, 1); Message = "Expected collection @(3, 1) with length 2 to be the same size as the actual collection, but got @(1, 2, 3) with length 3." } ) { param ($Actual, $Expected, $Message) Compare-CollectionEquivalent -Actual $Actual -Expected $Expected | Verify-Equal $Message } It "Given collection '' on the expected side and non-collection '' on the actual side it prints the correct message ''" -TestCases @( - @{ Actual = 3; Expected = (1, 2, 3, 4); Message = "Expected collection '1, 2, 3, 4' with length '4', but got '3'." }, - @{ Actual = (New-PSObject @{ Name = 'Jakub' }); Expected = (1, 2, 3, 4); Message = "Expected collection '1, 2, 3, 4' with length '4', but got 'PSObject{Name=Jakub}'." } + @{ Actual = 3; Expected = (1, 2, 3, 4); Message = "Expected collection @(1, 2, 3, 4) with length 4, but got 3." }, + @{ Actual = (New-PSObject @{ Name = 'Jakub' }); Expected = (1, 2, 3, 4); Message = "Expected collection @(1, 2, 3, 4) with length 4, but got PSObject{Name='Jakub'}." } ) { param ($Actual, $Expected, $Message) Compare-CollectionEquivalent -Actual $Actual -Expected $Expected | Verify-Equal $Message @@ -213,8 +213,8 @@ InPesterModuleScope { } It "Given two collections '' '' it compares each value with each value and returns message ' if any of them are not equivalent" -TestCases @( - @{ Actual = (1, 2, 3); Expected = (4, 5, 6); Message = "Expected collection '4, 5, 6' to be equivalent to '1, 2, 3' but some values were missing: '4, 5, 6'." }, - @{ Actual = (1, 2, 3); Expected = (1, 2, 2); Message = "Expected collection '1, 2, 2' to be equivalent to '1, 2, 3' but some values were missing: '2'." } + @{ Actual = (1, 2, 3); Expected = (4, 5, 6); Message = "Expected collection @(4, 5, 6) to be equivalent to @(1, 2, 3) but some values were missing: @(4, 5, 6)." }, + @{ Actual = (1, 2, 3); Expected = (1, 2, 2); Message = "Expected collection @(1, 2, 2) to be equivalent to @(1, 2, 3) but some values were missing: 2." } ) { param ($Actual, $Expected, $Message) Compare-CollectionEquivalent -Actual $Actual -Expected $Expected | Verify-Equal $Message @@ -234,7 +234,7 @@ InPesterModuleScope { } It "Given values '' and '' that are not equivalent it returns message ''." -TestCases @( - @{ Actual = 'a'; Expected = (New-PSObject @{ Name = 'Jakub' }); Message = "Expected object 'PSObject{Name=Jakub}', but got 'a'." } + @{ Actual = 'a'; Expected = (New-PSObject @{ Name = 'Jakub' }); Message = "Expected object PSObject{Name='Jakub'}, but got 'a'." } ) { param ($Actual, $Expected, $Message) Compare-ObjectEquivalent -Expected $Expected -Actual $Actual | Verify-Equal $Message @@ -251,10 +251,10 @@ InPesterModuleScope { } It "Given values '' and '' that are not equivalent it returns message ''." -TestCases @( - @{ Actual = 'a'; Expected = @{ Name = 'Jakub' }; Message = "Expected hashtable '@{Name=Jakub}', but got 'a'." } - @{ Actual = @{ }; Expected = @{ Name = 'Jakub' }; Message = "Expected hashtable '@{Name=Jakub}', but got '@{}'.`nExpected has key 'Name' that the other object does not have." } - @{ Actual = @{ Name = 'Tomas' }; Expected = @{ Name = 'Jakub' }; Message = "Expected hashtable '@{Name=Jakub}', but got '@{Name=Tomas}'.`nExpected property .Name with value 'Jakub' to be equivalent to the actual value, but got 'Tomas'." } - @{ Actual = @{ Name = 'Tomas'; Value = 10 }; Expected = @{ Name = 'Jakub' }; Message = "Expected hashtable '@{Name=Jakub}', but got '@{Name=Tomas; Value=10}'.`nExpected property .Name with value 'Jakub' to be equivalent to the actual value, but got 'Tomas'.`nExpected is missing key 'Value' that the other object has." } + @{ Actual = 'a'; Expected = @{ Name = 'Jakub' }; Message = "Expected hashtable @{Name='Jakub'}, but got 'a'." } + @{ Actual = @{ }; Expected = @{ Name = 'Jakub' }; Message = "Expected hashtable @{Name='Jakub'}, but got @{}.`nExpected has key 'Name' that the other object does not have." } + @{ Actual = @{ Name = 'Tomas' }; Expected = @{ Name = 'Jakub' }; Message = "Expected hashtable @{Name='Jakub'}, but got @{Name='Tomas'}.`nExpected property .Name with value 'Jakub' to be equivalent to the actual value, but got 'Tomas'." } + @{ Actual = @{ Name = 'Tomas'; Value = 10 }; Expected = @{ Name = 'Jakub' }; Message = "Expected hashtable @{Name='Jakub'}, but got @{Name='Tomas'; Value=10}.`nExpected property .Name with value 'Jakub' to be equivalent to the actual value, but got 'Tomas'.`nExpected is missing key 'Value' that the other object has." } ) { param ($Actual, $Expected, $Message) @@ -272,10 +272,10 @@ InPesterModuleScope { } It "Given values '' and '' that are not equivalent it returns message ''." -TestCases @( - @{ Actual = 'a'; Expected = New-Dictionary @{ Name = 'Jakub' }; Message = "Expected dictionary 'Dictionary{Name=Jakub}', but got 'a'." } - @{ Actual = New-Dictionary @{ }; Expected = New-Dictionary @{ Name = 'Jakub' }; Message = "Expected dictionary 'Dictionary{Name=Jakub}', but got 'Dictionary{}'.`nExpected has key 'Name' that the other object does not have." } - @{ Actual = New-Dictionary @{ Name = 'Tomas' }; Expected = New-Dictionary @{ Name = 'Jakub' }; Message = "Expected dictionary 'Dictionary{Name=Jakub}', but got 'Dictionary{Name=Tomas}'.`nExpected property .Name with value 'Jakub' to be equivalent to the actual value, but got 'Tomas'." } - @{ Actual = New-Dictionary @{ Name = 'Tomas'; Value = 10 }; Expected = New-Dictionary @{ Name = 'Jakub' }; Message = "Expected dictionary 'Dictionary{Name=Jakub}', but got 'Dictionary{Name=Tomas; Value=10}'.`nExpected property .Name with value 'Jakub' to be equivalent to the actual value, but got 'Tomas'.`nExpected is missing key 'Value' that the other object has." } + @{ Actual = 'a'; Expected = New-Dictionary @{ Name = 'Jakub' }; Message = "Expected dictionary Dictionary{Name='Jakub'}, but got 'a'." } + @{ Actual = New-Dictionary @{ }; Expected = New-Dictionary @{ Name = 'Jakub' }; Message = "Expected dictionary Dictionary{Name='Jakub'}, but got Dictionary{}.`nExpected has key 'Name' that the other object does not have." } + @{ Actual = New-Dictionary @{ Name = 'Tomas' }; Expected = New-Dictionary @{ Name = 'Jakub' }; Message = "Expected dictionary Dictionary{Name='Jakub'}, but got Dictionary{Name='Tomas'}.`nExpected property .Name with value 'Jakub' to be equivalent to the actual value, but got 'Tomas'." } + @{ Actual = New-Dictionary @{ Name = 'Tomas'; Value = 10 }; Expected = New-Dictionary @{ Name = 'Jakub' }; Message = "Expected dictionary Dictionary{Name='Jakub'}, but got Dictionary{Name='Tomas'; Value=10}.`nExpected property .Name with value 'Jakub' to be equivalent to the actual value, but got 'Tomas'.`nExpected is missing key 'Value' that the other object has." } ) { param ($Actual, $Expected, $Message) @@ -306,24 +306,24 @@ InPesterModuleScope { } It "Given values '' and '' that are not equivalent it returns message ''." -TestCases @( - @{ Actual = $null; Expected = 1; Message = "Expected '1' to be equivalent to the actual value, but got '`$null'." }, - @{ Actual = $null; Expected = ""; Message = "Expected '' to be equivalent to the actual value, but got '`$null'." }, - @{ Actual = $true; Expected = $false; Message = "Expected '`$false' to be equivalent to the actual value, but got '`$true'." }, - @{ Actual = $true; Expected = 'False'; Message = "Expected '`$false' to be equivalent to the actual value, but got '`$true'." }, - @{ Actual = 1; Expected = -1; Message = "Expected '-1' to be equivalent to the actual value, but got '1'." }, - @{ Actual = "1"; Expected = 1.01; Message = "Expected '1.01' to be equivalent to the actual value, but got '1'." }, + @{ Actual = $null; Expected = 1; Message = "Expected 1 to be equivalent to the actual value, but got `$null." }, + @{ Actual = $null; Expected = ""; Message = "Expected to be equivalent to the actual value, but got `$null." }, + @{ Actual = $true; Expected = $false; Message = "Expected `$false to be equivalent to the actual value, but got `$true." }, + @{ Actual = $true; Expected = 'False'; Message = "Expected `$false to be equivalent to the actual value, but got `$true." }, + @{ Actual = 1; Expected = -1; Message = "Expected -1 to be equivalent to the actual value, but got 1." }, + @{ Actual = "1"; Expected = 1.01; Message = "Expected 1.01 to be equivalent to the actual value, but got '1'." }, @{ Actual = "abc"; Expected = "a b c"; Message = "Expected 'a b c' to be equivalent to the actual value, but got 'abc'." }, - @{ Actual = @("abc", "bde"); Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got 'abc, bde'." }, - @{ Actual = { def }; Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got '{ def }'." }, - @{ Actual = "def"; Expected = { abc }; Message = "Expected '{ abc }' to be equivalent to the actual value, but got 'def'." }, - @{ Actual = { abc }; Expected = { def }; Message = "Expected '{ def }' to be equivalent to the actual value, but got '{ abc }'." }, - @{ Actual = (1, 2, 3); Expected = (1, 2, 3, 4); Message = "Expected collection '1, 2, 3, 4' with length '4' to be the same size as the actual collection, but got '1, 2, 3' with length '3'." }, - @{ Actual = 3; Expected = (1, 2, 3, 4); Message = "Expected collection '1, 2, 3, 4' with length '4', but got '3'." }, - @{ Actual = (New-PSObject @{ Name = 'Jakub' }); Expected = (1, 2, 3, 4); Message = "Expected collection '1, 2, 3, 4' with length '4', but got 'PSObject{Name=Jakub}'." }, - @{ Actual = (New-PSObject @{ Name = 'Jakub' }); Expected = "a"; Message = "Expected 'a' to be equivalent to the actual value, but got 'PSObject{Name=Jakub}'." }, - @{ Actual = 'a'; Expected = (New-PSObject @{ Name = 'Jakub' }); Message = "Expected object 'PSObject{Name=Jakub}', but got 'a'." } - @{ Actual = 'a'; Expected = @{ Name = 'Jakub' }; Message = "Expected hashtable '@{Name=Jakub}', but got 'a'." } - @{ Actual = 'a'; Expected = New-Dictionary @{ Name = 'Jakub' }; Message = "Expected dictionary 'Dictionary{Name=Jakub}', but got 'a'." } + @{ Actual = @("abc", "bde"); Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got @('abc', 'bde')." }, + @{ Actual = { def }; Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got { def }." }, + @{ Actual = "def"; Expected = { abc }; Message = "Expected { abc } to be equivalent to the actual value, but got 'def'." }, + @{ Actual = { abc }; Expected = { def }; Message = "Expected { def } to be equivalent to the actual value, but got { abc }." }, + @{ Actual = (1, 2, 3); Expected = (1, 2, 3, 4); Message = "Expected collection @(1, 2, 3, 4) with length 4 to be the same size as the actual collection, but got @(1, 2, 3) with length 3." }, + @{ Actual = 3; Expected = (1, 2, 3, 4); Message = "Expected collection @(1, 2, 3, 4) with length 4, but got 3." }, + @{ Actual = (New-PSObject @{ Name = 'Jakub' }); Expected = (1, 2, 3, 4); Message = "Expected collection @(1, 2, 3, 4) with length 4, but got PSObject{Name='Jakub'}." }, + @{ Actual = (New-PSObject @{ Name = 'Jakub' }); Expected = "a"; Message = "Expected 'a' to be equivalent to the actual value, but got PSObject{Name='Jakub'}." }, + @{ Actual = 'a'; Expected = (New-PSObject @{ Name = 'Jakub' }); Message = "Expected object PSObject{Name='Jakub'}, but got 'a'." } + @{ Actual = 'a'; Expected = @{ Name = 'Jakub' }; Message = "Expected hashtable @{Name='Jakub'}, but got 'a'." } + @{ Actual = 'a'; Expected = New-Dictionary @{ Name = 'Jakub' }; Message = "Expected dictionary Dictionary{Name='Jakub'}, but got 'a'." } ) { param ($Actual, $Expected, $Message) Compare-Equivalent -Expected $Expected -Actual $Actual | Verify-Equal $Message @@ -360,7 +360,7 @@ InPesterModuleScope { @{ Expected = New-PSObject @{ Name = 'Jakub'; Age = 28 } Actual = New-PSObject @{ Name = 'Jakub'; Age = 19 } - Message = "Expected property .Age with value '28' to be equivalent to the actual value, but got '19'." + Message = "Expected property .Age with value 28 to be equivalent to the actual value, but got 19." }, @{ Expected = New-PSObject @{ Name = 'Jakub'; Age = 28 } @@ -398,7 +398,7 @@ InPesterModuleScope { ) { param ($Expected, $Actual) - Compare-Equivalent -Expected $Expected -Actual $Actual | Verify-Equal "Expected collection in property .Numbers which is '1, 2, 3' to be equivalent to '3, 4, 5' but some values were missing: '1, 2'." + Compare-Equivalent -Expected $Expected -Actual $Actual | Verify-Equal "Expected collection in property .Numbers which is @(1, 2, 3) to be equivalent to @(3, 4, 5) but some values were missing: @(1, 2)." } It "Comparing psObjects that have collections of objects returns `$null when the objects have the same value" -TestCases @( @@ -418,7 +418,7 @@ InPesterModuleScope { } ) { param ($Expected, $Actual) - Compare-Equivalent -Expected $Expected -Actual $Actual | Verify-Equal "Expected collection in property .Objects which is 'PSObject{Name=Jan}, PSObject{Name=Petr}' to be equivalent to 'PSObject{Name=Jan}, PSObject{Name=Tomas}' but some values were missing: 'PSObject{Name=Petr}'." + Compare-Equivalent -Expected $Expected -Actual $Actual | Verify-Equal "Expected collection in property .Objects which is @(PSObject{Name='Jan'}, PSObject{Name='Petr'}) to be equivalent to @(PSObject{Name='Jan'}, PSObject{Name='Tomas'}) but some values were missing: PSObject{Name='Petr'}." } It "Comparing DataTable" { diff --git a/tst/functions/assert/General/Assert-LessThanOrEqual.Tests.ps1 b/tst/functions/assert/General/Assert-LessThanOrEqual.Tests.ps1 index 88ff611d4..6e2396e33 100644 --- a/tst/functions/assert/General/Assert-LessThanOrEqual.Tests.ps1 +++ b/tst/functions/assert/General/Assert-LessThanOrEqual.Tests.ps1 @@ -83,9 +83,9 @@ Describe "Assert-LessThanOrEqual" { Context "Validate messages" { It "Given two values '' and '' it returns expected message ''" -TestCases @( - @{ Expected = "a" ; Actual = "z" ; Message = "Expected string 'z' to be less than or equal to string 'a', but it was not." }, - @{ Expected = 1.1 ; Actual = 10.1 ; Message = "Expected double '10.1' to be less than or equal to double '1.1', but it was not." }, - @{ Expected = 1.1D ; Actual = 10.1D ; Message = "Expected decimal '10.1' to be less than or equal to decimal '1.1', but it was not." } + @{ Expected = "a" ; Actual = "z" ; Message = "Expected [string] ''z'' to be less than or equal to [string] ''a'', but it was not." }, + @{ Expected = 1.1 ; Actual = 10.1 ; Message = "Expected [double] '10.1' to be less than or equal to [double] '1.1', but it was not." }, + @{ Expected = 1.1D ; Actual = 10.1D ; Message = "Expected [decimal] '10.1' to be less than or equal to [decimal] '1.1', but it was not." } ) { param($Expected, $Actual, $Message) $err = { Assert-LessThanOrEqual -Actual $Actual -Expected $Expected } | Verify-AssertionFailed diff --git a/tst/functions/assert/General/Assert-NotEqual.Tests.ps1 b/tst/functions/assert/General/Assert-NotEqual.Tests.ps1 index 4aad56d23..c5d443ec8 100644 --- a/tst/functions/assert/General/Assert-NotEqual.Tests.ps1 +++ b/tst/functions/assert/General/Assert-NotEqual.Tests.ps1 @@ -56,7 +56,7 @@ InPesterModuleScope { } It "Passes for array input even if the last item is the same as expected" { - 1,2,3 | Assert-NotEqual 3 + 1, 2, 3 | Assert-NotEqual 3 } It "Fails with custom message" { @@ -66,7 +66,7 @@ InPesterModuleScope { Context "Validate messages" { It "Given two values that are the same '' it returns expected message ''" -TestCases @( - @{ Value = 1; Message = "Expected int '1', to be different than the actual value, but they were the same."} + @{ Value = 1; Message = "Expected [int] 1, to be different than the actual value, but they were the same." } ) { param($Value, $Message) $err = { Assert-NotEqual -Actual $Value -Expected $Value } | Verify-AssertionFailed diff --git a/tst/functions/assert/General/Assert-NotSame.Tests.ps1 b/tst/functions/assert/General/Assert-NotSame.Tests.ps1 index f83a69afa..01b6c3924 100644 --- a/tst/functions/assert/General/Assert-NotSame.Tests.ps1 +++ b/tst/functions/assert/General/Assert-NotSame.Tests.ps1 @@ -15,7 +15,7 @@ InPesterModuleScope { It "Passes for array input even if the last item is the same as expected" { $object = New-Object Diagnostics.Process - 1,2, $object | Assert-NotSame $object + 1, 2, $object | Assert-NotSame $object } It "Fails with custom message" { @@ -25,7 +25,7 @@ InPesterModuleScope { } It "Given two values that are the same instance it returns expected message ''" -TestCases @( - @{ Value = "a"; Message = "Expected string 'a', to not be the same instance."} + @{ Value = "a"; Message = "Expected [string] ''a'', to not be the same instance." } ) { param($Value, $Message) $err = { Assert-NotSame -Actual $Value -Expected $Value } | Verify-AssertionFailed diff --git a/tst/functions/assert/General/Assert-Same.Tests.ps1 b/tst/functions/assert/General/Assert-Same.Tests.ps1 index 2eb89eb03..32a7efc20 100644 --- a/tst/functions/assert/General/Assert-Same.Tests.ps1 +++ b/tst/functions/assert/General/Assert-Same.Tests.ps1 @@ -21,11 +21,11 @@ InPesterModuleScope { It "Fails with custom message" { $object = New-Object Diagnostics.Process $err = { "text" | Assert-Same $object -CustomMessage "'' is not ''" } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "'Diagnostics.Process{Id=; Name=}' is not 'text'" + $err.Exception.Message | Verify-Equal "'Diagnostics.Process{Id=`$null; Name=`$null}' is not ''text''" } It "Given two values that are not the same instance '' and '' it returns expected message ''" -TestCases @( - @{ Expected = New-Object -TypeName PSObject ; Actual = New-Object -TypeName PSObject ; Message = "Expected PSObject '', to be the same instance but it was not." } + @{ Expected = New-Object -TypeName PSObject ; Actual = New-Object -TypeName PSObject ; Message = "Expected [PSObject] 'PSObject{}', to be the same instance but it was not." } ) { param($Expected, $Actual, $Message) $err = { Assert-Same -Actual $Actual -Expected $Expected } | Verify-AssertionFailed diff --git a/tst/functions/assert/String/Should-BeEmptyString.Tests.ps1 b/tst/functions/assert/String/Should-BeEmptyString.Tests.ps1 index 5a6f43d44..7005c20df 100644 --- a/tst/functions/assert/String/Should-BeEmptyString.Tests.ps1 +++ b/tst/functions/assert/String/Should-BeEmptyString.Tests.ps1 @@ -1,65 +1,35 @@ Set-StrictMode -Version Latest -InPesterModuleScope { - Describe "Test-StringEmpty" { - It "empty string returns `$true" -ForEach @( - @{ Actual = "" } - @{ Actual = [String]::Empty } - ) { - Test-StringEmpty -Actual $Actual | Verify-True - } - - It "non-empty string, whitespace, or null returns `$false" -ForEach @( - @{ Actual = "a" } - @{ Actual = " " } - @{ Actual = $null } - ) { - Test-StringEmpty -Actual $Actual | Verify-False - } - - It "Object with a type that is not a string, returns `$false" -ForEach @( - @{ Actual = $bool } - @{ Actual = 1 } - @{ Actual = @() } - @{ Actual = $null } - ) { - Test-StringEmpty -Actual $Actual | Verify-False - } - - It "returns `$false when type serializes to empty string" { - Add-type -TypeDefinition " - public class TypeThatSerializesToEmptyString { public override string ToString() { return string.Empty; } } - " - Test-StringEmpty -Actual ([TypeThatSerializesToEmptyString]::new()) | Verify-False - } - } - - Describe "Get-StringEmptyDefaultFailureMessage" { - It "Throws with default message when test fails" { - $expected = Get-StringEmptyDefaultFailureMessage -Actual "bde" - $exception = { Should-BeEmptyString -Actual "bde" } | Verify-AssertionFailed - "$exception" | Verify-Equal $expected - } - - It "Throws with default message and because when test fails" { - $expected = Get-StringEmptyDefaultFailureMessage -Actual "bde" -Because "abc" - $exception = { Should-BeEmptyString -Actual "bde" -Because "abc" } | Verify-AssertionFailed - "$exception" | Verify-Equal $expected - } - } -} - Describe "Should-BeEmptyString" { It "Does not throw when string is empty" { Should-BeEmptyString -Actual "" } - It "EDGE CASE: Does not throw when string is empty" { + It "EDGE CASE: Does not throw when string is single item collection of empty string" { @("") | Should-BeEmptyString } - It "Throws when string is not empty" { - { Should-BeEmptyString -Actual "bde" } | Verify-AssertionFailed + It "Throws when string is not empty" -ForEach @( + @{ Actual = "a" } + @{ Actual = " " } + ) { + { Should-BeEmptyString -Actual $Actual } | Verify-AssertionFailed + } + + It "Throws when `$Actual is not a string" -ForEach @( + @{ Actual = $true } + @{ Actual = 1 } + @{ Actual = @() } + @{ Actual = $null } + ) { + { Should-BeEmptyString -Actual $Actual } | Verify-AssertionFailed + } + + It "Throws when type serializes to empty string" { + Add-type -TypeDefinition " + public class TypeThatSerializesToEmptyString { public override string ToString() { return string.Empty; } } + " + { Should-BeEmptyString -Actual ([TypeThatSerializesToEmptyString]::new()) } | Verify-AssertionFailed } It "Allows actual to be passed from pipeline" { @@ -77,4 +47,15 @@ Describe "Should-BeEmptyString" { It "Fails when `$null collection is passed in by pipeline" { { $null | Should-BeEmptyString } | Verify-AssertionFailed } + + It "Fails with the expected message" -ForEach @( + @{ Actual = "a"; Because = $null; ExpectedMessage = "Expected a [string] that is empty, but got [string]: 'a'`n`n" } + @{ Actual = "a"; Because = 'reason'; ExpectedMessage = "Expected a [string] that is empty, because reason, but got [string]: 'a'`n`n" } + @{ Actual = 3; Because = $null; ExpectedMessage = "Expected a [string] that is empty, but got [int]: 3`n`n" } + ) { + $actual = $Actual + $expectedMessage = $ExpectedMessage + $err = { Should-BeEmptyString -Actual $actual -Because $Because } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $ExpectedMessage + } } diff --git a/tst/functions/assert/String/Should-NotBeNullOrEmptyString.Tests.ps1 b/tst/functions/assert/String/Should-NotBeNullOrEmptyString.Tests.ps1 index 9e9a9184b..8bcd9e22c 100644 --- a/tst/functions/assert/String/Should-NotBeNullOrEmptyString.Tests.ps1 +++ b/tst/functions/assert/String/Should-NotBeNullOrEmptyString.Tests.ps1 @@ -1,43 +1,14 @@ Set-StrictMode -Version Latest -InPesterModuleScope { - Describe "Test-StringNullOrEmpty" { - It "non-empty string, or whitespace returns `$false" -ForEach @( - @{ Actual = "1" } - @{ Actual = " " } - @{ Actual = "`t" } - @{ Actual = "`n" } - @{ Actual = "`r" } - ) { - Test-StringNullOrEmpty -Actual $Actual | Verify-True - } - - It "empty string, or null returns `$true" -ForEach @( - @{ Actual = "" } - @{ Actual = $null } - ) { - Test-StringNullOrEmpty -Actual $Actual | Verify-False - } - } - - Describe "Get-StringNotNullOrEmptyDefaultFailureMessage" { - It "Throws with default message when test fails" { - $expected = Get-StringNotNullOrEmptyDefaultFailureMessage -Actual "" - $exception = { Should-NotBeNullOrEmptyString -Actual "" } | Verify-AssertionFailed - "$exception" | Verify-Equal $expected - } - - It "Throws with default message and because when test fails" { - $expected = Get-StringNotNullOrEmptyDefaultFailureMessage -Actual "" -Because "abc" - $exception = { Should-NotBeNullOrEmptyString -Actual "" -Because "abc" } | Verify-AssertionFailed - "$exception" | Verify-Equal $expected - } - } -} - Describe "Should-NotBeNullOrEmptyString" { - It "Does not throw when string has value" { - "bde" | Should-NotBeNullOrEmptyString + It "Does not throw when string has value" -ForEach @( + @{ Actual = "1" } + @{ Actual = " " } + @{ Actual = "`t" } + @{ Actual = "`n" } + @{ Actual = "`r" } + ) { + $Actual | Should-NotBeNullOrEmptyString } It "Throws when string is `$null or empty" -ForEach @( @@ -71,4 +42,15 @@ Describe "Should-NotBeNullOrEmptyString" { It "Fails when `$null collection is passed in by pipeline" { { $null | Should-NotBeNullOrEmptyString } | Verify-AssertionFailed } + + It "Fails with the expected message" -ForEach @( + @{ Actual = ""; Because = $null; ExpectedMessage = "Expected a [string] that is not `$null or empty, but got [string]: `n`n" } + @{ Actual = ""; Because = 'reason'; ExpectedMessage = "Expected a [string] that is not `$null or empty, because reason, but got [string]: `n`n" } + @{ Actual = 3; Because = $null; ExpectedMessage = "Expected a [string] that is not `$null or empty, but got [int]: 3`n`n" } + ) { + $actual = $Actual + $expectedMessage = $ExpectedMessage + $err = { Should-NotBeNullOrEmptyString -Actual $actual -Because $Because } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $ExpectedMessage + } } diff --git a/tst/functions/assert/String/Should-NotBeNullOrWhiteSpaceString.Tests.ps1 b/tst/functions/assert/String/Should-NotBeNullOrWhiteSpaceString.Tests.ps1 index 21496a11c..0a9dc12e4 100644 --- a/tst/functions/assert/String/Should-NotBeNullOrWhiteSpaceString.Tests.ps1 +++ b/tst/functions/assert/String/Should-NotBeNullOrWhiteSpaceString.Tests.ps1 @@ -1,40 +1,5 @@ Set-StrictMode -Version Latest -InPesterModuleScope { - Describe "Test-StringNullOrWhiteSpace" { - It "non-empty string returns `$false" -ForEach @( - @{ Actual = "1" } - ) { - Test-StringNullOrWhiteSpace -Actual $Actual | Verify-True - } - - It "empty string, whitespace, or null returns `$true" -ForEach @( - @{ Actual = "" } - @{ Actual = " " } - @{ Actual = "`t" } - @{ Actual = "`n" } - @{ Actual = "`r" } - @{ Actual = $null } - ) { - Test-StringNullOrWhiteSpace -Actual $Actual | Verify-False - } - } - - Describe "Get-StringNotNullOrWhiteSpaceDefaultFailureMessage" { - It "Throws with default message when test fails" { - $expected = Get-StringNotNullOrWhiteSpaceDefaultFailureMessage -Actual "" - $exception = { Should-NotBeNullOrWhiteSpaceString -Actual "" } | Verify-AssertionFailed - "$exception" | Verify-Equal $expected - } - - It "Throws with default message and because when test fails" { - $expected = Get-StringNotNullOrWhiteSpaceDefaultFailureMessage -Actual "" -Because "abc" - $exception = { Should-NotBeNullOrWhiteSpaceString -Actual "" -Because "abc" } | Verify-AssertionFailed - "$exception" | Verify-Equal $expected - } - } -} - Describe "Should-NotBeNullOrWhiteSpaceString" { It "Does not throw when string has value" { "bde" | Should-NotBeNullOrWhiteSpaceString @@ -46,7 +11,6 @@ Describe "Should-NotBeNullOrWhiteSpaceString" { @{ Actual = "`t" } @{ Actual = "`n" } @{ Actual = "`r" } - @{ Actual = $null } ) { { $Actual | Should-NotBeNullOrWhiteSpaceString } | Verify-AssertionFailed } @@ -55,6 +19,7 @@ Describe "Should-NotBeNullOrWhiteSpaceString" { @{ Actual = 1 } @{ Actual = @() } @{ Actual = $true } + @{ Actual = $null } ) { { $Actual | Should-NotBeNullOrWhiteSpaceString } | Verify-AssertionFailed } @@ -75,4 +40,15 @@ Describe "Should-NotBeNullOrWhiteSpaceString" { It "Fails when `$null collection is passed in by pipeline" { { $null | Should-NotBeNullOrWhiteSpaceString } | Verify-AssertionFailed } + + It "Fails with the expected message" -ForEach @( + @{ Actual = ""; Because = $null; ExpectedMessage = "Expected a [string] that is not `$null, empty or whitespace, but got [string]: `n`n" } + @{ Actual = ""; Because = 'reason'; ExpectedMessage = "Expected a [string] that is not `$null, empty or whitespace, because reason, but got [string]: `n`n" } + @{ Actual = 3; Because = $null; ExpectedMessage = "Expected a [string] that is not `$null, empty or whitespace, but got [int]: 3`n`n" } + ) { + $actual = $Actual + $expectedMessage = $ExpectedMessage + $err = { Should-NotBeNullOrWhiteSpaceString -Actual $actual -Because $Because } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $ExpectedMessage + } } From 5b1ebd47ace9c18fcc9450221d36281b065313a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Sun, 21 Apr 2024 20:30:50 +0200 Subject: [PATCH 20/55] Change formats, fix all tests --- src/Format2.ps1 | 13 +++++++++++++ .../assert/Equivalence/Assert-Equivalent.ps1 | 4 ++-- src/functions/assert/Exception/Assert-Throw.ps1 | 2 +- src/functions/assert/General/Assert-Equal.ps1 | 2 +- .../assert/General/Assert-GreaterThan.ps1 | 9 ++++----- .../assert/General/Assert-GreaterThanOrEqual.ps1 | 9 ++++----- src/functions/assert/General/Assert-LessThan.ps1 | 9 ++++----- .../assert/General/Assert-LessThanOrEqual.ps1 | 9 ++++----- src/functions/assert/General/Assert-NotEqual.ps1 | 9 ++++----- .../Equivalence/Assert-Equivalent.Tests.ps1 | 2 +- .../assert/Exception/Assert-Throw.Tests.ps1 | 8 ++++---- .../assert/General/Assert-Equal.Tests.ps1 | 13 ++++++------- .../assert/General/Assert-GreaterThan.Tests.ps1 | 15 +++++++-------- .../General/Assert-GreaterThanOrEqual.Tests.ps1 | 15 +++++++-------- .../assert/General/Assert-LessThan.Tests.ps1 | 7 +++---- .../General/Assert-LessThanOrEqual.Tests.ps1 | 7 +++---- 16 files changed, 68 insertions(+), 65 deletions(-) diff --git a/src/Format2.ps1 b/src/Format2.ps1 index dbe31bbff..9823b1caa 100644 --- a/src/Format2.ps1 +++ b/src/Format2.ps1 @@ -123,6 +123,15 @@ function Format-Nicely2 ($Value, [switch]$Pretty) { return Format-Dictionary2 -Value $Value } + if ((Is-DataTable -Value $Value) -or (Is-DataRow -Value $Value)) { + try { + return Format-DataTable2 -Value $Value -Pretty:$Pretty + } + catch { + $a = 18 + } + } + if (Is-Collection -Value $Value) { return Format-Collection2 -Value $Value -Pretty:$Pretty } @@ -177,3 +186,7 @@ function Format-Type2 ([Type]$Value) { "[$($typeFormatted)]" } +function Format-DataTable2 ($Value) { + return "$Value" +} + diff --git a/src/functions/assert/Equivalence/Assert-Equivalent.ps1 b/src/functions/assert/Equivalence/Assert-Equivalent.ps1 index a4b966ad2..b163e43f5 100644 --- a/src/functions/assert/Equivalence/Assert-Equivalent.ps1 +++ b/src/functions/assert/Equivalence/Assert-Equivalent.ps1 @@ -126,7 +126,7 @@ function Compare-CollectionEquivalent ($Expected, $Actual, $Property, $Options) v -Difference "`$Actual and `$Expected arrays are not equivalent." $Expected = Format-Nicely2 -Value $Expected $Actual = Format-Nicely2 -Value $Actual - $notFoundFormatted = Format-Nicely2 -Value ( $notFound | ForEach-Object { Format-Nicely2 -Value $_ } ) + $notFoundFormatted = Format-Nicely2 -Value $notFound $propertyMessage = if ($Property) { " in property $Property which is" } return "Expected collection$propertyMessage $Expected to be equivalent to $Actual but some values were missing: $notFoundFormatted." @@ -183,7 +183,7 @@ function Compare-DataTableEquivalent ($Expected, $Actual, $Property, $Options) { if ($notFound) { $propertyMessage = if ($Property) { " in property $Property which is" } - return "Expected DataTable$propertyMessage '$Expected' to be equivalent to '$Actual' but some values were missing: '$notFoundFormatted'." + return "Expected DataTable$propertyMessage $Expected to be equivalent to $Actual but some values were missing: $notFoundFormatted." } } diff --git a/src/functions/assert/Exception/Assert-Throw.ps1 b/src/functions/assert/Exception/Assert-Throw.ps1 index 438900903..3b6d5a9b3 100644 --- a/src/functions/assert/Exception/Assert-Throw.ps1 +++ b/src/functions/assert/Exception/Assert-Throw.ps1 @@ -41,7 +41,7 @@ function Assert-Throw { $exceptionTypeFilterMatches = $err.Exception -is $ExceptionType if (-not $exceptionTypeFilterMatches) { $exceptionTypeFormatted = Get-ShortType2 $err.Exception - $buts += "the exception type was '$exceptionTypeFormatted'" + $buts += "the exception type was $exceptionTypeFormatted" } } diff --git a/src/functions/assert/General/Assert-Equal.ps1 b/src/functions/assert/General/Assert-Equal.ps1 index afbd8948f..1aa37066f 100644 --- a/src/functions/assert/General/Assert-Equal.ps1 +++ b/src/functions/assert/General/Assert-Equal.ps1 @@ -12,7 +12,7 @@ $Actual = $collectedInput.Actual if ((Ensure-ExpectedIsNotCollection $Expected) -ne $Actual) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '', but got ''." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected , but got ." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Assert-GreaterThan.ps1 b/src/functions/assert/General/Assert-GreaterThan.ps1 index 5d3f8fbbd..53462bd1b 100644 --- a/src/functions/assert/General/Assert-GreaterThan.ps1 +++ b/src/functions/assert/General/Assert-GreaterThan.ps1 @@ -1,18 +1,17 @@ function Assert-GreaterThan { [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( - [Parameter(Position=1, ValueFromPipeline=$true)] + [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position=0)] + [Parameter(Position = 0)] $Expected, [String]$CustomMessage ) $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual - if ((Ensure-ExpectedIsNotCollection $Expected) -ge $Actual) - { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be greater than '', but it was not." + if ((Ensure-ExpectedIsNotCollection $Expected) -ge $Actual) { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected to be greater than , but it was not." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Assert-GreaterThanOrEqual.ps1 b/src/functions/assert/General/Assert-GreaterThanOrEqual.ps1 index 2cbafa627..452e5749c 100644 --- a/src/functions/assert/General/Assert-GreaterThanOrEqual.ps1 +++ b/src/functions/assert/General/Assert-GreaterThanOrEqual.ps1 @@ -1,18 +1,17 @@ function Assert-GreaterThanOrEqual { [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( - [Parameter(Position=1, ValueFromPipeline=$true)] + [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position=0)] + [Parameter(Position = 0)] $Expected, [String]$CustomMessage ) $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual - if ((Ensure-ExpectedIsNotCollection $Expected) -gt $Actual) - { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be greater than or equal to '', but it was not." + if ((Ensure-ExpectedIsNotCollection $Expected) -gt $Actual) { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected to be greater than or equal to , but it was not." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Assert-LessThan.ps1 b/src/functions/assert/General/Assert-LessThan.ps1 index 336f29dbf..b0d7dc83b 100644 --- a/src/functions/assert/General/Assert-LessThan.ps1 +++ b/src/functions/assert/General/Assert-LessThan.ps1 @@ -1,18 +1,17 @@ function Assert-LessThan { [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( - [Parameter(Position=1, ValueFromPipeline=$true)] + [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position=0)] + [Parameter(Position = 0)] $Expected, [String]$CustomMessage ) $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual - if ((Ensure-ExpectedIsNotCollection $Expected) -le $Actual) - { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be less than '', but it was not." + if ((Ensure-ExpectedIsNotCollection $Expected) -le $Actual) { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected to be less than , but it was not." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Assert-LessThanOrEqual.ps1 b/src/functions/assert/General/Assert-LessThanOrEqual.ps1 index 7a3f00bdb..1c8c8d292 100644 --- a/src/functions/assert/General/Assert-LessThanOrEqual.ps1 +++ b/src/functions/assert/General/Assert-LessThanOrEqual.ps1 @@ -1,18 +1,17 @@ function Assert-LessThanOrEqual { [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( - [Parameter(Position=1, ValueFromPipeline=$true)] + [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position=0)] + [Parameter(Position = 0)] $Expected, [String]$CustomMessage ) $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual - if ((Ensure-ExpectedIsNotCollection $Expected) -lt $Actual) - { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be less than or equal to '', but it was not." + if ((Ensure-ExpectedIsNotCollection $Expected) -lt $Actual) { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected to be less than or equal to , but it was not." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Assert-NotEqual.ps1 b/src/functions/assert/General/Assert-NotEqual.ps1 index 60400a07a..0c7e525b0 100644 --- a/src/functions/assert/General/Assert-NotEqual.ps1 +++ b/src/functions/assert/General/Assert-NotEqual.ps1 @@ -1,18 +1,17 @@ function Assert-NotEqual { [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( - [Parameter(Position=1, ValueFromPipeline=$true)] + [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position=0)] + [Parameter(Position = 0)] $Expected, [String]$CustomMessage ) $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual - if ((Ensure-ExpectedIsNotCollection $Expected) -eq $Actual) - { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '', to be different than the actual value, but they were the same." + if ((Ensure-ExpectedIsNotCollection $Expected) -eq $Actual) { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected , to be different than the actual value, but they were the same." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 b/tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 index 334c2231a..60d69877a 100644 --- a/tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 +++ b/tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 @@ -418,7 +418,7 @@ InPesterModuleScope { } ) { param ($Expected, $Actual) - Compare-Equivalent -Expected $Expected -Actual $Actual | Verify-Equal "Expected collection in property .Objects which is @(PSObject{Name='Jan'}, PSObject{Name='Petr'}) to be equivalent to @(PSObject{Name='Jan'}, PSObject{Name='Tomas'}) but some values were missing: PSObject{Name='Petr'}." + Compare-Equivalent -Expected $Expected -Actual $Actual | Verify-Equal "Expected collection in property .Objects which is @(PSObject{Name='Jan'}, PSObject{Name='Petr'}) to be equivalent to @(PSObject{Name='Jan'}, PSObject{Name='Tomas'}) but some values were missing: @(PSObject{Name='Petr'})." } It "Comparing DataTable" { diff --git a/tst/functions/assert/Exception/Assert-Throw.Tests.ps1 b/tst/functions/assert/Exception/Assert-Throw.Tests.ps1 index 1f6e1b39c..84a777f4a 100644 --- a/tst/functions/assert/Exception/Assert-Throw.Tests.ps1 +++ b/tst/functions/assert/Exception/Assert-Throw.Tests.ps1 @@ -76,7 +76,7 @@ Describe "Assert-Throw" { It "Given exception that does not match on type it returns the correct message" { $err = { { throw [ArgumentException]"" } | Assert-Throw -ExceptionType ([System.InvalidOperationException]) } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "Expected an exception, of type InvalidOperationException to be thrown, but the exception type was 'ArgumentException'." + $err.Exception.Message | Verify-Equal "Expected an exception, of type [InvalidOperationException] to be thrown, but the exception type was [ArgumentException]." } It "Given exception that does not match on message it returns the correct message" { @@ -91,12 +91,12 @@ Describe "Assert-Throw" { It "Given exception that does not match on type and message it returns the correct message" { $err = { { throw [ArgumentException]"fail!" } | Assert-Throw -ExceptionType ([System.InvalidOperationException]) -ExceptionMessage 'halt!' } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "Expected an exception, of type InvalidOperationException, with message 'halt!' to be thrown, but the exception type was 'ArgumentException' and the message was 'fail!'." + $err.Exception.Message | Verify-Equal "Expected an exception, of type [InvalidOperationException], with message 'halt!' to be thrown, but the exception type was [ArgumentException] and the message was 'fail!'." } It "Given exception that does not match on type and FullyQualifiedErrorId it returns the correct message" { $err = { { throw [ArgumentException]"SomeId!" } | Assert-Throw -ExceptionType ([System.InvalidOperationException]) -FullyQualifiedErrorId 'DifferentId!' } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "Expected an exception, of type InvalidOperationException, with FullyQualifiedErrorId 'DifferentId!' to be thrown, but the exception type was 'ArgumentException' and the FullyQualifiedErrorId was 'SomeId!'." + $err.Exception.Message | Verify-Equal "Expected an exception, of type [InvalidOperationException], with FullyQualifiedErrorId 'DifferentId!' to be thrown, but the exception type was [ArgumentException] and the FullyQualifiedErrorId was 'SomeId!'." } It "Given exception that does not match on message and FullyQualifiedErrorId it returns the correct message" { @@ -106,7 +106,7 @@ Describe "Assert-Throw" { It "Given exception that does not match on type, message and FullyQualifiedErrorId it returns the correct message" { $err = { { throw [ArgumentException]"halt!" } | Assert-Throw -ExceptionType ([System.InvalidOperationException]) -ExceptionMessage 'fail!' -FullyQualifiedErrorId 'fail!' } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "Expected an exception, of type InvalidOperationException, with message 'fail!' and with FullyQualifiedErrorId 'fail!' to be thrown, but the exception type was 'ArgumentException', the message was 'halt!' and the FullyQualifiedErrorId was 'halt!'." + $err.Exception.Message | Verify-Equal "Expected an exception, of type [InvalidOperationException], with message 'fail!' and with FullyQualifiedErrorId 'fail!' to be thrown, but the exception type was [ArgumentException], the message was 'halt!' and the FullyQualifiedErrorId was 'halt!'." } } diff --git a/tst/functions/assert/General/Assert-Equal.Tests.ps1 b/tst/functions/assert/General/Assert-Equal.Tests.ps1 index 0d86adce1..76a09ff65 100644 --- a/tst/functions/assert/General/Assert-Equal.Tests.ps1 +++ b/tst/functions/assert/General/Assert-Equal.Tests.ps1 @@ -56,21 +56,20 @@ InPesterModuleScope { } It "Fails for array input even if the last item is the same as expected" { - { 1,2,3 | Assert-Equal 3 } | Verify-AssertionFailed + { 1, 2, 3 | Assert-Equal 3 } | Verify-AssertionFailed } It "Fails with custom message" { - $err = { 9 | Assert-Equal 3 -CustomMessage " is not " } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "3 is not 9" + $err = { 9 | Assert-Equal 3 -CustomMessage " is not " } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "3 is not 9" } Context "Validate messages" { It "Given two values that are not the same '' and '' it returns expected message ''" -TestCases @( - @{ Expected = "a" ; Actual = 10 ; Message = "Expected string 'a', but got int '10'."}, - @{ Expected = "a" ; Actual = 10.1 ; Message = "Expected string 'a', but got double '10.1'."}, - @{ Expected = "a" ; Actual = 10.1D ; Message = "Expected string 'a', but got decimal '10.1'."} + @{ Expected = "a" ; Actual = 10 ; Message = "Expected [string] 'a', but got [int] 10." }, + @{ Expected = "a" ; Actual = 10.1 ; Message = "Expected [string] 'a', but got [double] 10.1." }, + @{ Expected = "a" ; Actual = 10.1D ; Message = "Expected [string] 'a', but got [decimal] 10.1." } ) { - param($Expected, $Actual, $Message) $err = { Assert-Equal -Actual $Actual -Expected $Expected } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message } diff --git a/tst/functions/assert/General/Assert-GreaterThan.Tests.ps1 b/tst/functions/assert/General/Assert-GreaterThan.Tests.ps1 index 45eb42fbb..5d1f0b9bb 100644 --- a/tst/functions/assert/General/Assert-GreaterThan.Tests.ps1 +++ b/tst/functions/assert/General/Assert-GreaterThan.Tests.ps1 @@ -73,22 +73,21 @@ InPesterModuleScope { } It "Fails for array input even if the last item is greater than then expected value" { - $err = { 1,2,3,4 | Assert-GreaterThan 3 } | Verify-Throw - $err.Exception | Verify-Type ([System.Management.Automation.RuntimeException]) + $err = { 1, 2, 3, 4 | Assert-GreaterThan 3 } | Verify-Throw + $err.Exception | Verify-Type ([System.Management.Automation.RuntimeException]) } It "Fails with custom message" { - $err = { 2 | Assert-GreaterThan 3 -CustomMessage " is not greater than " } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "2 is not greater than 3" + $err = { 2 | Assert-GreaterThan 3 -CustomMessage " is not greater than " } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "2 is not greater than 3" } Context "Validate messages" { It "Given two values '' and '' it returns expected message ''" -TestCases @( - @{ Expected = "z" ; Actual = "a" ; Message = "Expected string 'a' to be greater than string 'z', but it was not."}, - @{ Expected = 10.1 ; Actual = 1.1 ; Message = "Expected double '1.1' to be greater than double '10.1', but it was not."}, - @{ Expected = 10.1D ; Actual = 1.1D ; Message = "Expected decimal '1.1' to be greater than decimal '10.1', but it was not."} + @{ Expected = "z" ; Actual = "a" ; Message = "Expected [string] 'a' to be greater than [string] 'z', but it was not." }, + @{ Expected = 10.1 ; Actual = 1.1 ; Message = "Expected [double] 1.1 to be greater than [double] 10.1, but it was not." }, + @{ Expected = 10.1D ; Actual = 1.1D ; Message = "Expected [decimal] 1.1 to be greater than [decimal] 10.1, but it was not." } ) { - param($Expected, $Actual, $Message) $err = { Assert-GreaterThan -Actual $Actual -Expected $Expected } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message } diff --git a/tst/functions/assert/General/Assert-GreaterThanOrEqual.Tests.ps1 b/tst/functions/assert/General/Assert-GreaterThanOrEqual.Tests.ps1 index 5d5a88cdc..293d378c8 100644 --- a/tst/functions/assert/General/Assert-GreaterThanOrEqual.Tests.ps1 +++ b/tst/functions/assert/General/Assert-GreaterThanOrEqual.Tests.ps1 @@ -73,22 +73,21 @@ InPesterModuleScope { } It "Fails for array input even if the last item is greater than then expected value" { - $err = { 1,2,3,4 | Assert-GreaterThanOrEqual 3 } | Verify-Throw - $err.Exception | Verify-Type ([System.Management.Automation.RuntimeException]) + $err = { 1, 2, 3, 4 | Assert-GreaterThanOrEqual 3 } | Verify-Throw + $err.Exception | Verify-Type ([System.Management.Automation.RuntimeException]) } It "Fails with custom message" { - $err = { 2 | Assert-GreaterThanOrEqual 3 -CustomMessage " is not greater than " } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "2 is not greater than 3" + $err = { 2 | Assert-GreaterThanOrEqual 3 -CustomMessage " is not greater than " } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "2 is not greater than 3" } Context "Validate messages" { It "Given two values '' and '' it returns expected message ''" -TestCases @( - @{ Expected = "z" ; Actual = "a" ; Message = "Expected string 'a' to be greater than or equal to string 'z', but it was not."}, - @{ Expected = 10.1 ; Actual = 1.1 ; Message = "Expected double '1.1' to be greater than or equal to double '10.1', but it was not."}, - @{ Expected = 10.1D ; Actual = 1.1D ; Message = "Expected decimal '1.1' to be greater than or equal to decimal '10.1', but it was not."} + @{ Expected = "z" ; Actual = "a" ; Message = "Expected [string] 'a' to be greater than or equal to [string] 'z', but it was not." }, + @{ Expected = 10.1 ; Actual = 1.1 ; Message = "Expected [double] 1.1 to be greater than or equal to [double] 10.1, but it was not." }, + @{ Expected = 10.1D ; Actual = 1.1D ; Message = "Expected [decimal] 1.1 to be greater than or equal to [decimal] 10.1, but it was not." } ) { - param($Expected, $Actual, $Message) $err = { Assert-GreaterThanOrEqual -Actual $Actual -Expected $Expected } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message } diff --git a/tst/functions/assert/General/Assert-LessThan.Tests.ps1 b/tst/functions/assert/General/Assert-LessThan.Tests.ps1 index 01ba0a12e..b739bf2bc 100644 --- a/tst/functions/assert/General/Assert-LessThan.Tests.ps1 +++ b/tst/functions/assert/General/Assert-LessThan.Tests.ps1 @@ -83,11 +83,10 @@ Describe "Assert-LessThan" { Context "Validate messages" { It "Given two values '' and '' it returns expected message ''" -TestCases @( - @{ Expected = "a" ; Actual = "z" ; Message = "Expected string 'z' to be less than string 'a', but it was not." }, - @{ Expected = 1.1 ; Actual = 10.1 ; Message = "Expected double '10.1' to be less than double '1.1', but it was not." }, - @{ Expected = 1.1D ; Actual = 10.1D ; Message = "Expected decimal '10.1' to be less than decimal '1.1', but it was not." } + @{ Expected = "a" ; Actual = "z" ; Message = "Expected [string] 'z' to be less than [string] 'a', but it was not." }, + @{ Expected = 1.1 ; Actual = 10.1 ; Message = "Expected [double] 10.1 to be less than [double] 1.1, but it was not." }, + @{ Expected = 1.1D ; Actual = 10.1D ; Message = "Expected [decimal] 10.1 to be less than [decimal] 1.1, but it was not." } ) { - param($Expected, $Actual, $Message) $err = { Assert-LessThan -Actual $Actual -Expected $Expected } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message } diff --git a/tst/functions/assert/General/Assert-LessThanOrEqual.Tests.ps1 b/tst/functions/assert/General/Assert-LessThanOrEqual.Tests.ps1 index 6e2396e33..63c095618 100644 --- a/tst/functions/assert/General/Assert-LessThanOrEqual.Tests.ps1 +++ b/tst/functions/assert/General/Assert-LessThanOrEqual.Tests.ps1 @@ -83,11 +83,10 @@ Describe "Assert-LessThanOrEqual" { Context "Validate messages" { It "Given two values '' and '' it returns expected message ''" -TestCases @( - @{ Expected = "a" ; Actual = "z" ; Message = "Expected [string] ''z'' to be less than or equal to [string] ''a'', but it was not." }, - @{ Expected = 1.1 ; Actual = 10.1 ; Message = "Expected [double] '10.1' to be less than or equal to [double] '1.1', but it was not." }, - @{ Expected = 1.1D ; Actual = 10.1D ; Message = "Expected [decimal] '10.1' to be less than or equal to [decimal] '1.1', but it was not." } + @{ Expected = "a" ; Actual = "z" ; Message = "Expected [string] 'z' to be less than or equal to [string] 'a', but it was not." }, + @{ Expected = 1.1 ; Actual = 10.1 ; Message = "Expected [double] 10.1 to be less than or equal to [double] 1.1, but it was not." }, + @{ Expected = 1.1D ; Actual = 10.1D ; Message = "Expected [decimal] 10.1 to be less than or equal to [decimal] 1.1, but it was not." } ) { - param($Expected, $Actual, $Message) $err = { Assert-LessThanOrEqual -Actual $Actual -Expected $Expected } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message } From 5b54c22324e9562df2b13303d04143d29d605474 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Sun, 21 Apr 2024 20:37:58 +0200 Subject: [PATCH 21/55] Update azure-pipelines.yml --- azure-pipelines.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 8b9ca74f9..9e3f8f1a1 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -3,7 +3,6 @@ trigger: include: - main - rel/* - - dev/* paths: exclude: - .devcontainer @@ -22,6 +21,7 @@ pr: include: - main - rel/* + - dev/* paths: exclude: - .devcontainer From 60c3a1272d606aaa282f3dcd08ffd16a7bee2f4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Sun, 21 Apr 2024 23:37:13 +0200 Subject: [PATCH 22/55] Add faster and before date time --- src/Module.ps1 | 12 ++++ src/Pester.psd1 | 7 +++ .../Pester/TimeSpanOrStringWithTimeUnit.cs | 18 ++++++ src/functions/assert/Time/Assert-Before.ps1 | 41 ++++++++++++++ src/functions/assert/Time/Assert-Faster.ps1 | 55 +++++++++++++++++++ src/functions/assert/Time/Assert-Slower.ps1 | 36 ++++++++++++ .../assert/Time/Should-BeAfter.Tests.ps1 | 15 +++++ .../assert/Time/Should-BeBefore.Tests.ps1 | 31 +++++++++++ .../assert/Time/Should-BeFasterThan.Tests.ps1 | 50 +++++++++++++++++ .../assert/Time/Should-BeSlowerThan.Tests.ps1 | 27 +++++++++ 10 files changed, 292 insertions(+) create mode 100644 src/csharp/Pester/TimeSpanOrStringWithTimeUnit.cs create mode 100644 src/functions/assert/Time/Assert-Before.ps1 create mode 100644 src/functions/assert/Time/Assert-Faster.ps1 create mode 100644 src/functions/assert/Time/Assert-Slower.ps1 create mode 100644 tst/functions/assert/Time/Should-BeAfter.Tests.ps1 create mode 100644 tst/functions/assert/Time/Should-BeBefore.Tests.ps1 create mode 100644 tst/functions/assert/Time/Should-BeFasterThan.Tests.ps1 create mode 100644 tst/functions/assert/Time/Should-BeSlowerThan.Tests.ps1 diff --git a/src/Module.ps1 b/src/Module.ps1 index 5e9e16f9e..10eafca6e 100644 --- a/src/Module.ps1 +++ b/src/Module.ps1 @@ -38,6 +38,9 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session & $SafeCommands['Set-Alias'] 'Should-NotBeNullOrWhiteSpaceString' 'Assert-StringNotWhiteSpace' & $SafeCommands['Set-Alias'] 'Should-NotBeNullOrEmptyString' 'Assert-StringNotEmpty' +& $SafeCommands['Set-Alias'] 'Should-BeFasterThan' 'Assert-Faster' +& $SafeCommands['Set-Alias'] 'Should-BeSlowerThan' 'Assert-Slower' +& $SafeCommands['Set-Alias'] 'Should-BeBefore' 'Assert-Before' @@ -103,6 +106,10 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session 'Assert-StringNotWhiteSpace' 'Assert-StringNotEmpty' + 'Assert-Faster' + 'Assert-Slower' + 'Assert-Before' + # export 'Export-NUnitReport' 'ConvertTo-NUnitReport' @@ -156,4 +163,9 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session 'Should-BeLikeString' 'Should-NotBeLikeString' + + # time + 'Should-BeFasterThan' + 'Should-BeSlowerThan' + 'Should-BeBefore' ) diff --git a/src/Pester.psd1 b/src/Pester.psd1 index 90cb808e9..af8277d2e 100644 --- a/src/Pester.psd1 +++ b/src/Pester.psd1 @@ -94,6 +94,9 @@ 'Assert-StringEmpty' 'Assert-StringNotWhiteSpace' 'Assert-StringNotEmpty' + 'Assert-Faster' + 'Assert-Slower' + 'Assert-Before' # legacy 'Assert-VerifiableMock' @@ -151,6 +154,10 @@ 'Should-BeLikeString' 'Should-NotBeLikeString' + + 'Should-BeFasterThan' + 'Should-BeSlowerThan' + 'Should-BeBefore' ) diff --git a/src/csharp/Pester/TimeSpanOrStringWithTimeUnit.cs b/src/csharp/Pester/TimeSpanOrStringWithTimeUnit.cs new file mode 100644 index 000000000..ed8271572 --- /dev/null +++ b/src/csharp/Pester/TimeSpanOrStringWithTimeUnit.cs @@ -0,0 +1,18 @@ +using System; + +namespace Pester +{ + public class TimeSpanOrStringWithTimeUnit + { + public TimeSpan DurationTimeSpan { get; private set; } + public string DurationString { get; private set; } + public static implicit operator TimeSpanOrStringWithTimeUnit(TimeSpan durationTimeSpan) + { + return new TimeSpanOrStringWithTimeUnit() { DurationTimeSpan = durationTimeSpan }; + } + public static implicit operator TimeSpanOrStringWithTimeUnit(string durationTimeSpan) + { + return new TimeSpanOrStringWithTimeUnit() { DurationString = durationTimeSpan }; + } + } +} diff --git a/src/functions/assert/Time/Assert-Before.ps1 b/src/functions/assert/Time/Assert-Before.ps1 new file mode 100644 index 000000000..a8f169c7e --- /dev/null +++ b/src/functions/assert/Time/Assert-Before.ps1 @@ -0,0 +1,41 @@ +function Assert-Before { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] + param ( + [Parameter(Position = 1, ValueFromPipeline = $true)] + $Actual, + [Parameter(Position = 0, ParameterSetName = "Expected")] + [DateTime] $Expected, + + [Parameter(Position = 0, ParameterSetName = "Ago")] + $TimeAgo, + + [Parameter(Position = 0, ParameterSetName = "FromNow")] + $TimeFromNow + ) + + $now = [datetime]::UtcNow.ToLocalTime() + if ($PSCmdlet.ParameterSetName -eq "Expected") { + if ($Actual -ge $Expected) { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "The provided [datetime] should be before , but it was after: " + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) + } + return + } + + if ($PSCmdlet.ParameterSetName -eq "Ago") { + $Expected = $now - (Get-TimeSpanFromStringWithUnits -Value $TimeAgo) + if ($Actual -ge $Expected) { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -Data @{ ago = $TimeAgo } -DefaultMessage "The provided [datetime] should be before ( ago), but it was after: " + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) + } + return + } + else { + $Expected = $now - (Get-TimeSpanFromStringWithUnits -Value $TimeFromNow) + if ($Actual -ge $Expected) { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -Data @{ fromNow = $TimeFromNow } -DefaultMessage "The provided [datetime] should be before ( from now), but it was after: " + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) + } + return + } +} diff --git a/src/functions/assert/Time/Assert-Faster.ps1 b/src/functions/assert/Time/Assert-Faster.ps1 new file mode 100644 index 000000000..9421bd451 --- /dev/null +++ b/src/functions/assert/Time/Assert-Faster.ps1 @@ -0,0 +1,55 @@ +function Get-TimeSpanFromStringWithUnits ([string] $Value) { + if ($Value -notmatch "(?^\d+(?:\.\d+)?)\s*(?ms|mil|m|h|d|s|w)") { + throw "String '$Value' is not a valid timespan string. It should be a number followed by a unit in short or long format (e.g. '1ms', '1s', '1m', '1h', '1d', '1w', '1sec', '1second', '1.5hours' etc.)." + } + + $suffix = $Matches['suffix'] + $valueFromRegex = $Matches['value'] + switch ($suffix) { + ms { [timespan]::FromMilliseconds($valueFromRegex) } + mil { [timespan]::FromMilliseconds($valueFromRegex) } + s { [timespan]::FromSeconds($valueFromRegex) } + m { [timespan]::FromMinutes($valueFromRegex) } + h { [timespan]::FromHours($valueFromRegex) } + d { [timespan]::FromDays($valueFromRegex) } + w { [timespan]::FromDays([double]$valueFromRegex * 7) } + default { throw "Time unit '$suffix' in '$Value' is not supported." } + } +} + +function Assert-Faster { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] + param ( + [Parameter(Position = 1, ValueFromPipeline = $true)] + $Actual, + [Parameter(Position = 0)] + $Expected + ) + + if ($Expected -isnot [timespan]) { + $Expected = Get-TimeSpanFromStringWithUnits -Value $Expected + } + + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual + + if ($Actual -is [scriptblock]) { + $sw = [System.Diagnostics.Stopwatch]::StartNew() + & $Actual + $sw.Stop() + + if ($sw.Elapsed -ge $Expected) { + $Message = Get-AssertionMessage -Expected $Expected -Actual $sw.Elapsed -CustomMessage $CustomMessage -Data @{ scriptblock = $Actual } -DefaultMessage "The provided [scriptblock] should execute faster than , but it took to run.`nActual: " + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) + } + return + } + + if ($Actual -is [timespan]) { + if ($Actual -ge $Expected) { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "The provided [timespan] should be shorter than , but it was longer: " + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) + } + return + } +} diff --git a/src/functions/assert/Time/Assert-Slower.ps1 b/src/functions/assert/Time/Assert-Slower.ps1 new file mode 100644 index 000000000..14da5b484 --- /dev/null +++ b/src/functions/assert/Time/Assert-Slower.ps1 @@ -0,0 +1,36 @@ +function Assert-Slower { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] + param ( + [Parameter(Position = 1, ValueFromPipeline = $true)] + $Actual, + [Parameter(Position = 0)] + $Expected + ) + + if ($Expected -isnot [timespan]) { + $Expected = Get-TimeSpanFromStringWithUnits -Value $Expected + } + + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual + + if ($Actual -is [scriptblock]) { + $sw = [System.Diagnostics.Stopwatch]::StartNew() + & $Actual + $sw.Stop() + + if ($sw.Elapsed -le $Expected) { + $Message = Get-AssertionMessage -Expected $Expected -Actual $sw.Elapsed -CustomMessage $CustomMessage -Data @{ scriptblock = $Actual } -DefaultMessage "The provided [scriptblock] should execute slower than , but it took to run.`nActual: " + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) + } + return + } + + if ($Actual -is [timespan]) { + if ($Actual -le $Expected) { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "The provided [timespan] should be longer than , but it was shorter: " + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) + } + return + } +} diff --git a/tst/functions/assert/Time/Should-BeAfter.Tests.ps1 b/tst/functions/assert/Time/Should-BeAfter.Tests.ps1 new file mode 100644 index 000000000..11784ff19 --- /dev/null +++ b/tst/functions/assert/Time/Should-BeAfter.Tests.ps1 @@ -0,0 +1,15 @@ +Set-StrictMode -Version Latest + +Describe "Should-BeSlowerThan" { + It "Does not throw when actual is slower than expected" -ForEach @( + @{ Actual = { Start-Sleep -Milliseconds 10 }; Expected = "1ms" } + ) { + $Actual | Should-BeSlowerThan -Expected $Expected + } + + It "Does not throw when actual is slower than expected taking TimeSpan" -ForEach @( + @{ Actual = [timespan]::FromMilliseconds(999); Expected = "1ms" } + ) { + $Actual | Should-BeSlowerThan -Expected $Expected + } +} diff --git a/tst/functions/assert/Time/Should-BeBefore.Tests.ps1 b/tst/functions/assert/Time/Should-BeBefore.Tests.ps1 new file mode 100644 index 000000000..bf0ae60f8 --- /dev/null +++ b/tst/functions/assert/Time/Should-BeBefore.Tests.ps1 @@ -0,0 +1,31 @@ +Set-StrictMode -Version Latest + +Describe "Should-BeBefore" { + It "Does not throw when actual date is before expected date" -ForEach @( + @{ Actual = [DateTime]::Now.AddDays(-1); Expected = [DateTime]::Now } + ) { + $Actual | Should-BeBefore -Expected $Expected + } + + It "Does not throw when actual date is before expected date using ago" { + [DateTime]::Now.AddMinutes(-11) | Should-BeBefore -TimeAgo 10minutes + } + + It "Does not throw when actual date is before expected date using fromNow" { + [datetime]::now.Add([timespan]::FromMinutes(-20)) | Should-BeBefore -TimeFromNow 10minutes + } + + It "Throws when actual date is after expected date" -ForEach @( + @{ Actual = [DateTime]::Now.AddDays(1); Expected = [DateTime]::Now } + ) { + { $Actual | Should-BeBefore -Expected $Expected } | Verify-AssertionFailed + } + + It "Throw when actual date is after expected date using ago" { + { [DateTime]::Now.AddMinutes(-9) | Should-BeBefore -TimeAgo 10minutes } | Verify-AssertionFailed + } + + It "Throws when actual date is after expected date using fromNow" { + { [datetime]::now.Add([timespan]::FromMinutes(11)) | Should-BeBefore -TimeFromNow 10minutes } | Verify-AssertionFailed + } +} diff --git a/tst/functions/assert/Time/Should-BeFasterThan.Tests.ps1 b/tst/functions/assert/Time/Should-BeFasterThan.Tests.ps1 new file mode 100644 index 000000000..9a4ec8115 --- /dev/null +++ b/tst/functions/assert/Time/Should-BeFasterThan.Tests.ps1 @@ -0,0 +1,50 @@ +Set-StrictMode -Version Latest + +InPesterModuleScope { + Describe "Get-TimeSpanFromStringWithUnits" { + It "Throws when string is not a valid timespan string" { + { Get-TimeSpanFromStringWithUnits 1f } | Verify-Throw + } + + It "Parses string with units correctly" -ForEach @( + @{ Value = "1ms"; Expected = [timespan]::FromMilliseconds(1) } + @{ Value = "1mil"; Expected = [timespan]::FromMilliseconds(1) } + @{ Value = "1s"; Expected = [timespan]::FromSeconds(1) } + @{ Value = "1m"; Expected = [timespan]::FromMinutes(1) } + @{ Value = "1h"; Expected = [timespan]::FromHours(1) } + @{ Value = "1d"; Expected = [timespan]::FromDays(1) } + @{ Value = "1w"; Expected = [timespan]::FromDays(7) } + @{ Value = "1sec"; Expected = [timespan]::FromSeconds(1) } + @{ Value = "1second"; Expected = [timespan]::FromSeconds(1) } + @{ Value = "1.5hours"; Expected = [timespan]::FromHours(1.5) } + ) { + Get-TimeSpanFromStringWithUnits -Value $Value | Verify-Equal -Expected $Expected + } + } +} + +Describe "Should-BeFasterThan" { + It "Does not throw when actual is faster than expected" -ForEach @( + @{ Actual = { Start-Sleep -Milliseconds 10 }; Expected = "100ms" } + ) { + $Actual | Should-BeFasterThan -Expected $Expected + } + + It "Does not throw when actual is faster than expected taking TimeSpan" -ForEach @( + @{ Actual = [timespan]::FromMilliseconds(999); Expected = "1s" } + ) { + $Actual | Should-BeFasterThan -Expected $Expected + } + + It "Throws when scriptblock is slower than expected" -ForEach @( + @{ Actual = { Start-Sleep -Milliseconds 10 }; Expected = "1ms" } + ) { + { $Actual | Should-BeFasterThan -Expected $Expected } | Verify-AssertionFailed + } + + It "Throw timespan is longer than expected" -ForEach @( + @{ Actual = [timespan]::FromMilliseconds(999); Expected = "1ms" } + ) { + { $Actual | Should-BeFasterThan -Expected $Expected } | Verify-AssertionFailed + } +} diff --git a/tst/functions/assert/Time/Should-BeSlowerThan.Tests.ps1 b/tst/functions/assert/Time/Should-BeSlowerThan.Tests.ps1 new file mode 100644 index 000000000..1f2179d72 --- /dev/null +++ b/tst/functions/assert/Time/Should-BeSlowerThan.Tests.ps1 @@ -0,0 +1,27 @@ +Set-StrictMode -Version Latest + +Describe "Should-BeSlowerThan" { + It "Does not throw when actual is slower than expected" -ForEach @( + @{ Actual = { Start-Sleep -Milliseconds 10 }; Expected = "1ms" } + ) { + $Actual | Should-BeSlowerThan -Expected $Expected + } + + It "Does not throw when actual is slower than expected taking TimeSpan" -ForEach @( + @{ Actual = [timespan]::FromMilliseconds(999); Expected = "1ms" } + ) { + $Actual | Should-BeSlowerThan -Expected $Expected + } + + It "Throws when scriptblock is faster than expected" -ForEach @( + @{ Actual = { Start-Sleep -Milliseconds 10 }; Expected = "1000ms" } + ) { + { $Actual | Should-BeSlowerThan -Expected $Expected } | Verify-AssertionFailed + } + + It "Throw timespan is shorter than expected" -ForEach @( + @{ Actual = [timespan]::FromMilliseconds(10); Expected = "1000ms" } + ) { + { $Actual | Should-BeSlowerThan -Expected $Expected } | Verify-AssertionFailed + } +} From 9e43582ba6bc01fc083d5c8b0f2d75032638a96c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Tue, 23 Apr 2024 21:23:01 +0200 Subject: [PATCH 23/55] Faster, slower, before, after --- test.ps1 | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/test.ps1 b/test.ps1 index a06a2eaad..968b51c6e 100644 --- a/test.ps1 +++ b/test.ps1 @@ -49,8 +49,18 @@ $ErrorView = "NormalView" "Using PS: $($PsVersionTable.PSVersion)" "In path: $($pwd.Path)" -if ($CI -and ($SkipPTests -or $SkipPesterTests)) { - throw "Cannot skip tests in CI mode!" +# Detect which tests to skip from the filenames. +$anyPesterTests = [bool]@($File | Where-Object { $_ -like "*.Tests.ps1" }) +$anyPTests = [bool]@($File | Where-Object { $_ -like "*.ts.ps1" }) + +if ($anyPTests -and $anyPesterTests) { + # Don't skip P or Pester tests, use the parameters user provided. +} +elseif (-not $SkipPTests.IsPresent -and (-not $anyPTests)) { + $SkipPTests = $true +} +elseif (-not $SkipPesterTests.IsPresent -and (-not $anyPesterTests)) { + $SkipPesterTests = $true } if (-not $NoBuild) { @@ -62,6 +72,10 @@ if (-not $NoBuild) { } } +if ($CI -and ($SkipPTests -or $SkipPesterTests)) { + throw "Cannot skip tests in CI mode!" +} + # remove pester because we will be reimporting it in multiple other places Get-Module Pester | Remove-Module From 0e5c07379582c353dd0af804da99a258e1517145 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Tue, 23 Apr 2024 21:24:17 +0200 Subject: [PATCH 24/55] before, after, faster, slower --- .gitignore | 1 + .vscode/launch.json | 32 ++++++++++ src/Module.ps1 | 3 + src/Pester.psd1 | 2 + src/functions/assert/Time/Assert-After.ps1 | 51 +++++++++++++++ src/functions/assert/Time/Assert-Before.ps1 | 62 +++++++++++-------- src/functions/assert/Time/Assert-Faster.ps1 | 2 +- src/functions/assert/Time/Assert-Slower.ps1 | 2 +- .../assert/Time/Should-BeAfter.Tests.ps1 | 58 ++++++++++++++--- .../assert/Time/Should-BeBefore.Tests.ps1 | 38 ++++++++++-- 10 files changed, 211 insertions(+), 40 deletions(-) create mode 100644 .vscode/launch.json create mode 100644 src/functions/assert/Time/Assert-After.ps1 diff --git a/.gitignore b/.gitignore index e02bf5456..28591e1ea 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ vendor/packages/ .vscode/ # But don't exclude settings.json !.vscode/settings.json +!.vscode/launch.json coverage.xml testResults.xml diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 000000000..ad1914f88 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,32 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "PowerShell: Launch Current File", + "type": "PowerShell", + "request": "launch", + "script": "${file}", + "args": [] + }, + { + "name": "Pester: Tests from current file", + "type": "PowerShell", + "request": "launch", + "script": "${workspaceFolder}/test.ps1", + "args": [ + "-File", + "${file}" + ] + }, + { + "name": "Pester: All tests", + "type": "PowerShell", + "request": "launch", + "script": "${workspaceFolder}/test.ps1", + "args": [] + } + ] +} diff --git a/src/Module.ps1 b/src/Module.ps1 index 10eafca6e..05bef7def 100644 --- a/src/Module.ps1 +++ b/src/Module.ps1 @@ -41,6 +41,7 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session & $SafeCommands['Set-Alias'] 'Should-BeFasterThan' 'Assert-Faster' & $SafeCommands['Set-Alias'] 'Should-BeSlowerThan' 'Assert-Slower' & $SafeCommands['Set-Alias'] 'Should-BeBefore' 'Assert-Before' +& $SafeCommands['Set-Alias'] 'Should-BeAfter' 'Assert-After' @@ -109,6 +110,7 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session 'Assert-Faster' 'Assert-Slower' 'Assert-Before' + 'Assert-After' # export 'Export-NUnitReport' @@ -168,4 +170,5 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session 'Should-BeFasterThan' 'Should-BeSlowerThan' 'Should-BeBefore' + 'Should-BeAfter' ) diff --git a/src/Pester.psd1 b/src/Pester.psd1 index af8277d2e..928610bb9 100644 --- a/src/Pester.psd1 +++ b/src/Pester.psd1 @@ -97,6 +97,7 @@ 'Assert-Faster' 'Assert-Slower' 'Assert-Before' + 'Assert-After' # legacy 'Assert-VerifiableMock' @@ -158,6 +159,7 @@ 'Should-BeFasterThan' 'Should-BeSlowerThan' 'Should-BeBefore' + 'Should-BeAfter' ) diff --git a/src/functions/assert/Time/Assert-After.ps1 b/src/functions/assert/Time/Assert-After.ps1 new file mode 100644 index 000000000..6e238226b --- /dev/null +++ b/src/functions/assert/Time/Assert-After.ps1 @@ -0,0 +1,51 @@ +function Assert-After { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] + [CmdletBinding(DefaultParameterSetName = "Now")] + param ( + [Parameter(Position = 2, ValueFromPipeline = $true)] + $Actual, + + [Parameter(Position = 0, ParameterSetName = "Now")] + [switch] $Now, + + [Parameter(Position = 0, ParameterSetName = "Fluent")] + $Time, + + [Parameter(Position = 1, ParameterSetName = "Fluent")] + [switch] $Ago, + + [Parameter(Position = 1, ParameterSetName = "Fluent")] + [switch] $FromNow, + + [Parameter(Position = 0, ParameterSetName = "Expected")] + [DateTime] $Expected + ) + + # Now is just a syntax marker, we don't need to do anything with it. + $Now = $Now + + $currentTime = [datetime]::UtcNow.ToLocalTime() + if ($PSCmdlet.ParameterSetName -eq "Expected") { + # do nothing we already have expected value + } + elseif ($PSCmdlet.ParameterSetName -eq "Now") { + $Expected = $currentTime + } + else { + if ($Ago -and $FromNow -or (-not $Ago -and -not $FromNow)) { + throw "You must provide either -Ago or -FromNow switch, but not both or none." + } + + if ($Ago) { + $Expected = $currentTime - (Get-TimeSpanFromStringWithUnits -Value $Time) + } + else { + $Expected = $currentTime + (Get-TimeSpanFromStringWithUnits -Value $Time) + } + } + + if ($Actual -le $Expected) { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -Data @{ ago = $Ago } -DefaultMessage "Expected the provided [datetime] to be after ( ago), but it was before: " + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) + } +} diff --git a/src/functions/assert/Time/Assert-Before.ps1 b/src/functions/assert/Time/Assert-Before.ps1 index a8f169c7e..1881b333b 100644 --- a/src/functions/assert/Time/Assert-Before.ps1 +++ b/src/functions/assert/Time/Assert-Before.ps1 @@ -1,41 +1,51 @@ function Assert-Before { [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] + [CmdletBinding(DefaultParameterSetName = "Now")] param ( - [Parameter(Position = 1, ValueFromPipeline = $true)] + [Parameter(Position = 2, ValueFromPipeline = $true)] $Actual, - [Parameter(Position = 0, ParameterSetName = "Expected")] - [DateTime] $Expected, - [Parameter(Position = 0, ParameterSetName = "Ago")] - $TimeAgo, + [Parameter(Position = 0, ParameterSetName = "Now")] + [switch] $Now, + + [Parameter(Position = 0, ParameterSetName = "Fluent")] + $Time, + + [Parameter(Position = 1, ParameterSetName = "Fluent")] + [switch] $Ago, + + [Parameter(Position = 1, ParameterSetName = "Fluent")] + [switch] $FromNow, - [Parameter(Position = 0, ParameterSetName = "FromNow")] - $TimeFromNow + [Parameter(Position = 0, ParameterSetName = "Expected")] + [DateTime] $Expected ) - $now = [datetime]::UtcNow.ToLocalTime() + # Now is just a syntax marker, we don't need to do anything with it. + $Now = $Now + + $currentTime = [datetime]::UtcNow.ToLocalTime() if ($PSCmdlet.ParameterSetName -eq "Expected") { - if ($Actual -ge $Expected) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "The provided [datetime] should be before , but it was after: " - throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) - } - return + # do nothing we already have expected value } - - if ($PSCmdlet.ParameterSetName -eq "Ago") { - $Expected = $now - (Get-TimeSpanFromStringWithUnits -Value $TimeAgo) - if ($Actual -ge $Expected) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -Data @{ ago = $TimeAgo } -DefaultMessage "The provided [datetime] should be before ( ago), but it was after: " - throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) - } - return + elseif ($PSCmdlet.ParameterSetName -eq "Now") { + $Expected = $currentTime } else { - $Expected = $now - (Get-TimeSpanFromStringWithUnits -Value $TimeFromNow) - if ($Actual -ge $Expected) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -Data @{ fromNow = $TimeFromNow } -DefaultMessage "The provided [datetime] should be before ( from now), but it was after: " - throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) + if ($Ago -and $FromNow -or (-not $Ago -and -not $FromNow)) { + throw "You must provide either -Ago or -FromNow switch, but not both or none." + } + + if ($Ago) { + $Expected = $currentTime - (Get-TimeSpanFromStringWithUnits -Value $Time) } - return + else { + $Expected = $currentTime + (Get-TimeSpanFromStringWithUnits -Value $Time) + } + } + + if ($Actual -ge $Expected) { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -Data @{ ago = $Ago } -DefaultMessage "Expected the provided [datetime] to be before ( ago), but it was after: " + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } } diff --git a/src/functions/assert/Time/Assert-Faster.ps1 b/src/functions/assert/Time/Assert-Faster.ps1 index 9421bd451..89e518bf7 100644 --- a/src/functions/assert/Time/Assert-Faster.ps1 +++ b/src/functions/assert/Time/Assert-Faster.ps1 @@ -39,7 +39,7 @@ function Assert-Faster { $sw.Stop() if ($sw.Elapsed -ge $Expected) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $sw.Elapsed -CustomMessage $CustomMessage -Data @{ scriptblock = $Actual } -DefaultMessage "The provided [scriptblock] should execute faster than , but it took to run.`nActual: " + $Message = Get-AssertionMessage -Expected $Expected -Actual $sw.Elapsed -CustomMessage $CustomMessage -Data @{ scriptblock = $Actual } -DefaultMessage "Expected the provided [scriptblock] to execute faster than , but it took to run.`nScriptBlock: " throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } return diff --git a/src/functions/assert/Time/Assert-Slower.ps1 b/src/functions/assert/Time/Assert-Slower.ps1 index 14da5b484..b801f2fa0 100644 --- a/src/functions/assert/Time/Assert-Slower.ps1 +++ b/src/functions/assert/Time/Assert-Slower.ps1 @@ -20,7 +20,7 @@ $sw.Stop() if ($sw.Elapsed -le $Expected) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $sw.Elapsed -CustomMessage $CustomMessage -Data @{ scriptblock = $Actual } -DefaultMessage "The provided [scriptblock] should execute slower than , but it took to run.`nActual: " + $Message = Get-AssertionMessage -Expected $Expected -Actual $sw.Elapsed -CustomMessage $CustomMessage -Data @{ scriptblock = $Actual } -DefaultMessage "The provided [scriptblock] should execute slower than , but it took to run.`nScriptBlock: " throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } return diff --git a/tst/functions/assert/Time/Should-BeAfter.Tests.ps1 b/tst/functions/assert/Time/Should-BeAfter.Tests.ps1 index 11784ff19..83466511b 100644 --- a/tst/functions/assert/Time/Should-BeAfter.Tests.ps1 +++ b/tst/functions/assert/Time/Should-BeAfter.Tests.ps1 @@ -1,15 +1,59 @@ Set-StrictMode -Version Latest -Describe "Should-BeSlowerThan" { - It "Does not throw when actual is slower than expected" -ForEach @( - @{ Actual = { Start-Sleep -Milliseconds 10 }; Expected = "1ms" } +Describe "Should-BeAfter" { + It "Does not throw when actual date is before expected date" -ForEach @( + @{ Actual = [DateTime]::Now.AddDays(1); Expected = [DateTime]::Now } ) { - $Actual | Should-BeSlowerThan -Expected $Expected + $Actual | Should-BeAfter -Expected $Expected } - It "Does not throw when actual is slower than expected taking TimeSpan" -ForEach @( - @{ Actual = [timespan]::FromMilliseconds(999); Expected = "1ms" } + It "Does not throw when actual date is before expected date using ago" { + [DateTime]::Now.AddMinutes(11) | Should-BeAfter 10minutes -Ago + } + + It "Does not throw when actual date is before expected date using fromNow" { + [DateTime]::Now.Add([timespan]::FromMinutes(20)) | Should-BeAfter 10minutes -FromNow + } + + It "Does not throw when actual date is before expected date using Now" { + [DateTime]::Now.Add([timespan]::FromMinutes(20)) | Should-BeAfter -Now + } + + It "Does not throw when actual date is before expected date using Now parameter set but not providing any switch" { + [DateTime]::Now.Add([timespan]::FromMinutes(20)) | Should-BeAfter + } + + It "Throws when actual date is before expected date" -ForEach @( + @{ Actual = [DateTime]::Now.AddDays(-1); Expected = [DateTime]::Now } ) { - $Actual | Should-BeSlowerThan -Expected $Expected + { $Actual | Should-BeAfter -Expected $Expected } | Verify-AssertionFailed + } + + It "Throws when actual date is before expected date using ago" { + { [DateTime]::Now.AddMinutes(-11) | Should-BeAfter 10minutes -Ago } | Verify-AssertionFailed + } + + It "Throws when actual date is before expected date using fromNow" { + { [DateTime]::Now.Add([timespan]::FromMinutes(9)) | Should-BeAfter 10minutes -FromNow } | Verify-AssertionFailed + } + + It "Throws when actual date is before expected date using Now" { + { [DateTime]::Now.Add([timespan]::FromMinutes(-1)) | Should-BeAfter -Now } | Verify-AssertionFailed + } + + It "Throws when actual date is before expected date using Now parameter set but not providing any switch" { + { [DateTime]::Now.Add([timespan]::FromMinutes(-1)) | Should-BeAfter } | Verify-AssertionFailed + } + + It "Throws when both -Ago and -FromNow are used" -ForEach @( + ) { + { $Actual | Should-BeAfter 10minutes -Ago -FromNow } | Verify-Throw + } + + It "Can check file creation date" { + New-Item -ItemType Directory -Path "TestDrive:\MyFolder" -Force | Out-Null + $path = "TestDrive:\MyFolder\test.txt" + "hello" | Set-Content $path + (Get-Item $path).CreationTime | Should-BeAfter 1s -Ago } } diff --git a/tst/functions/assert/Time/Should-BeBefore.Tests.ps1 b/tst/functions/assert/Time/Should-BeBefore.Tests.ps1 index bf0ae60f8..d9574de3c 100644 --- a/tst/functions/assert/Time/Should-BeBefore.Tests.ps1 +++ b/tst/functions/assert/Time/Should-BeBefore.Tests.ps1 @@ -8,11 +8,19 @@ Describe "Should-BeBefore" { } It "Does not throw when actual date is before expected date using ago" { - [DateTime]::Now.AddMinutes(-11) | Should-BeBefore -TimeAgo 10minutes + [DateTime]::Now.AddMinutes(-11) | Should-BeBefore 10minutes -Ago } It "Does not throw when actual date is before expected date using fromNow" { - [datetime]::now.Add([timespan]::FromMinutes(-20)) | Should-BeBefore -TimeFromNow 10minutes + [DateTime]::Now.Add([timespan]::FromMinutes(-20)) | Should-BeBefore 10minutes -FromNow + } + + It "Does not throw when actual date is before expected date using Now" { + [DateTime]::Now.Add([timespan]::FromMinutes(-20)) | Should-BeBefore -Now + } + + It "Does not throw when actual date is before expected date using Now parameter set but not providing any switch" { + [DateTime]::Now.Add([timespan]::FromMinutes(-20)) | Should-BeBefore } It "Throws when actual date is after expected date" -ForEach @( @@ -21,11 +29,31 @@ Describe "Should-BeBefore" { { $Actual | Should-BeBefore -Expected $Expected } | Verify-AssertionFailed } - It "Throw when actual date is after expected date using ago" { - { [DateTime]::Now.AddMinutes(-9) | Should-BeBefore -TimeAgo 10minutes } | Verify-AssertionFailed + It "Throws when actual date is after expected date using ago" { + { [DateTime]::Now.AddMinutes(-9) | Should-BeBefore 10minutes -Ago } | Verify-AssertionFailed } It "Throws when actual date is after expected date using fromNow" { - { [datetime]::now.Add([timespan]::FromMinutes(11)) | Should-BeBefore -TimeFromNow 10minutes } | Verify-AssertionFailed + { [DateTime]::Now.Add([timespan]::FromMinutes(11)) | Should-BeBefore 10minutes -FromNow } | Verify-AssertionFailed + } + + It "Throws when actual date is after expected date using Now" { + { [DateTime]::Now.Add([timespan]::FromMinutes(20)) | Should-BeBefore -Now } | Verify-AssertionFailed + } + + It "Throws when actual date is after expected date using Now parameter set but not providing any switch" { + { [DateTime]::Now.Add([timespan]::FromMinutes(20)) | Should-BeBefore } | Verify-AssertionFailed + } + + It "Throws when both -Ago and -FromNow are used" -ForEach @( + ) { + { $Actual | Should-BeBefore 10minutes -Ago -FromNow } | Verify-Throw + } + + It "Can check file creation date" { + New-Item -ItemType Directory -Path "TestDrive:\MyFolder" -Force | Out-Null + $path = "TestDrive:\MyFolder\test.txt" + "hello" | Set-Content $path + (Get-Item $path).CreationTime | Should-BeBefore -Now } } From 1565699c5715bf8bb02c95a2a45e4e31d9501421 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Tue, 23 Apr 2024 21:25:12 +0200 Subject: [PATCH 25/55] Strict mode --- tst/functions/assert/Collection/Assert-NotCollection.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tst/functions/assert/Collection/Assert-NotCollection.Tests.ps1 b/tst/functions/assert/Collection/Assert-NotCollection.Tests.ps1 index 5f282702b..0013d9112 100644 --- a/tst/functions/assert/Collection/Assert-NotCollection.Tests.ps1 +++ b/tst/functions/assert/Collection/Assert-NotCollection.Tests.ps1 @@ -1 +1 @@ - \ No newline at end of file +Set-StrictMode -Version Latest From d80c7ef1e6ac04b053ffaec2a2b1449ec6303a88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Tue, 23 Apr 2024 21:52:48 +0200 Subject: [PATCH 26/55] Fix running tests --- test.ps1 | 12 ++++++------ tst/functions/New-Fixture.ts.ps1 | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/test.ps1 b/test.ps1 index 968b51c6e..ee9506828 100644 --- a/test.ps1 +++ b/test.ps1 @@ -32,6 +32,7 @@ .NOTES Tests are excluded with Tags VersionChecks, StyleRules, Help. #> +[CmdletBinding()] param ( # force P to fail when I leave `dt` in the tests [switch] $CI, @@ -39,7 +40,7 @@ param ( [switch] $SkipPesterTests, [switch] $NoBuild, [switch] $Inline, - [string[]] $File + [string[]] $File = @() ) Set-StrictMode -Version Latest @@ -50,16 +51,15 @@ $ErrorView = "NormalView" "In path: $($pwd.Path)" # Detect which tests to skip from the filenames. +$anyFile = 0 -lt $File.Count $anyPesterTests = [bool]@($File | Where-Object { $_ -like "*.Tests.ps1" }) $anyPTests = [bool]@($File | Where-Object { $_ -like "*.ts.ps1" }) -if ($anyPTests -and $anyPesterTests) { - # Don't skip P or Pester tests, use the parameters user provided. -} -elseif (-not $SkipPTests.IsPresent -and (-not $anyPTests)) { +if ($SkipPTests -or ($anyFile -and -not $anyPTests)) { $SkipPTests = $true } -elseif (-not $SkipPesterTests.IsPresent -and (-not $anyPesterTests)) { + +if ($SkipPesterTests -or ($anyFile -and -not $anyPesterTests)) { $SkipPesterTests = $true } diff --git a/tst/functions/New-Fixture.ts.ps1 b/tst/functions/New-Fixture.ts.ps1 index 49d2688dc..7799c2563 100644 --- a/tst/functions/New-Fixture.ts.ps1 +++ b/tst/functions/New-Fixture.ts.ps1 @@ -29,7 +29,7 @@ i -PassThru:$PassThru { try { New-Fixture -Path $tempFolder -Name $name - $r = Invoke-Pester -Path $testsPath -PassThru + $r = Invoke-Pester -Path $testsPath -PassThru -Output None $r.Containers[0].Blocks[0].Tests[0].Result | Verify-Equal "Failed" $r.Containers[0].Blocks[0].Tests[0].ErrorRecord.Exception | Verify-Type ([System.NotImplementedException]) } From caaffae03aa8aca4c0987d91c355e3d95c51ce78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Tue, 23 Apr 2024 23:10:22 +0200 Subject: [PATCH 27/55] all and any --- src/Module.ps1 | 4 +- src/Pester.psd1 | 2 +- .../assert/Collection/Assert-All.ps1 | 40 +++++++++++++++---- .../assert/Collection/Assert-Any.ps1 | 35 +++++++++++++++- .../assert/Collection/Assert-All.Tests.ps1 | 9 +++++ .../assert/Collection/Assert-Any.Tests.ps1 | 14 +++++++ 6 files changed, 93 insertions(+), 11 deletions(-) diff --git a/src/Module.ps1 b/src/Module.ps1 index 05bef7def..4457fe616 100644 --- a/src/Module.ps1 +++ b/src/Module.ps1 @@ -16,7 +16,7 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session & $SafeCommands['Set-Alias'] 'Should-NotContain' 'Assert-NotContain' & $SafeCommands['Set-Alias'] 'Should-BeEquivalent' 'Assert-Equivalent' & $SafeCommands['Set-Alias'] 'Should-Throw' 'Assert-Throw' -& $SafeCommands['Set-Alias'] 'Should-BeEqual' 'Assert-Equal' +& $SafeCommands['Set-Alias'] 'Should-Be' 'Assert-Equal' & $SafeCommands['Set-Alias'] 'Should-BeGreaterThan' 'Assert-GreaterThan' & $SafeCommands['Set-Alias'] 'Should-BeGreaterThanOrEqual' 'Assert-GreaterThanOrEqual' & $SafeCommands['Set-Alias'] 'Should-BeLessThan' 'Assert-LessThan' @@ -142,7 +142,7 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session 'Should-NotContain' 'Should-BeEquivalent' 'Should-Throw' - 'Should-BeEqual' + 'Should-Be' 'Should-BeGreaterThan' 'Should-BeGreaterThanOrEqual' 'Should-BeLessThan' diff --git a/src/Pester.psd1 b/src/Pester.psd1 index 928610bb9..6eb2d35de 100644 --- a/src/Pester.psd1 +++ b/src/Pester.psd1 @@ -131,7 +131,7 @@ 'Should-NotContain' 'Should-BeEquivalent' 'Should-Throw' - 'Should-BeEqual' + 'Should-Be' 'Should-BeGreaterThan' 'Should-BeGreaterThanOrEqual' 'Should-BeLessThan' diff --git a/src/functions/assert/Collection/Assert-All.ps1 b/src/functions/assert/Collection/Assert-All.ps1 index 91ee1bf6d..d775ec9cd 100644 --- a/src/functions/assert/Collection/Assert-All.ps1 +++ b/src/functions/assert/Collection/Assert-All.ps1 @@ -13,19 +13,38 @@ $Expected = $FilterScript $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual - # we are jumping between modules so I need to explicitly pass the _ variable - # simply using '&' won't work - # see: https://blogs.msdn.microsoft.com/sergey_babkins_blog/2014/10/30/calling-the-script-blocks-in-powershell/ - # - # Do NOT replace this Foreach-Object with foreach keyword, you will break the $_ variable. - $actualFiltered = $Actual | & $SafeCommands['ForEach-Object'] { + + $failReasons = $null + $appendMore = $false + $predicate = { # powershell v4 code where we have InvokeWithContext available $underscore = & $SafeCommands['Get-Variable'] _ - $pass = $FilterScript.InvokeWithContext($null, $underscore, $null) + try { + $pass = $FilterScript.InvokeWithContext($null, $underscore, $null) + } + catch { + if ($null -eq $failReasons) { + $failReasons = [System.Collections.Generic.List[string]]::new(10) + } + if ($failReasons.Count -lt 10) { + $failReasons.Add($_.Exception.InnerException.Message) + } + else { + $appendMore = $true + } + $pass = $false + } if (-not $pass) { $_ } } + # we are jumping between modules so I need to explicitly pass the _ variable + # simply using '&' won't work + # see: https://blogs.msdn.microsoft.com/sergey_babkins_blog/2014/10/30/calling-the-script-blocks-in-powershell/ + # + # Do NOT replace this Foreach-Object with foreach keyword, you will break the $_ variable. + $actualFiltered = $Actual | & $SafeCommands['ForEach-Object'] $predicate + # Make sure are checking the count of the filtered items, not just a single item. $actualFiltered = @($actualFiltered) if (0 -lt $actualFiltered.Count) { @@ -34,6 +53,13 @@ actualFilteredCount = $actualFiltered.Count } $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Data $data -CustomMessage $CustomMessage -DefaultMessage "Expected all items in collection to pass filter , but of them did not pass the filter." + if ($null -ne $failReasons) { + $failReasons = $failReasons -join "`n" + if ($appendMore) { + $failReasons += "`nand more..." + } + $Message += "`nReasons :`n$failReasons" + } throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/Collection/Assert-Any.ps1 b/src/functions/assert/Collection/Assert-Any.ps1 index dc32e5542..f566d7c98 100644 --- a/src/functions/assert/Collection/Assert-Any.ps1 +++ b/src/functions/assert/Collection/Assert-Any.ps1 @@ -11,8 +11,41 @@ $Expected = $FilterScript $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual - if (-not ($Actual | & $SafeCommands['Where-Object'] -FilterScript $FilterScript)) { + + $failReasons = $null + $appendMore = $false + $pass = $false + foreach ($item in $Actual) { + # powershell v4 code where we have InvokeWithContext available + $underscore = [PSVariable]::new('_', $item) + try { + $pass = $FilterScript.InvokeWithContext($null, $underscore, $null) + } + catch { + if ($null -eq $failReasons) { + $failReasons = [System.Collections.Generic.List[string]]::new(10) + } + if ($failReasons.Count -lt 10) { + $failReasons.Add($_.Exception.InnerException.Message) + } + else { + $appendMore = $true + } + + $pass = $false + } + if ($pass) { break } + } + + if (-not $pass) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected at least one item in collection to pass filter , but none of the items passed the filter." + if ($null -ne $failReasons) { + $failReasons = $failReasons -join "`n" + if ($appendMore) { + $failReasons += "`nand more..." + } + $Message += "`nReasons :`n$failReasons" + } throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/tst/functions/assert/Collection/Assert-All.Tests.ps1 b/tst/functions/assert/Collection/Assert-All.Tests.ps1 index d2459c3c1..124f66666 100644 --- a/tst/functions/assert/Collection/Assert-All.Tests.ps1 +++ b/tst/functions/assert/Collection/Assert-All.Tests.ps1 @@ -17,6 +17,15 @@ Describe "Assert-All" { { $Actual | Assert-All -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed } + It "Can be failed by other assertion" { + $err = { 1, 1, 1 | Should-All -FilterScript { $_ | Should-Be 2 } } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal ("Expected all items in collection @(1, 1, 1) to pass filter { `$_ | Should-Be 2 }, but 3 of them @(1, 1, 1) did not pass the filter. +Reasons : +Expected [int] 2, but got [int] 1. +Expected [int] 2, but got [int] 1. +Expected [int] 2, but got [int] 1." -replace "`r`n", "`n") + } + It "Validate messages" -TestCases @( @{ Actual = @(3, 4, 5); Message = "Expected all items in collection @(3, 4, 5) to pass filter { `$_ -eq 1 }, but 3 of them @(3, 4, 5) did not pass the filter." } ) { diff --git a/tst/functions/assert/Collection/Assert-Any.Tests.ps1 b/tst/functions/assert/Collection/Assert-Any.Tests.ps1 index 3b644eff6..161f11cf9 100644 --- a/tst/functions/assert/Collection/Assert-Any.Tests.ps1 +++ b/tst/functions/assert/Collection/Assert-Any.Tests.ps1 @@ -17,6 +17,20 @@ Describe "Assert-Any" { { $Actual | Assert-Any -FilterScript { $_ -eq 0 } } | Verify-AssertionFailed } + It "Can be failed by other assertion" { + $err = { 1, 1, 1 | Should-Any -FilterScript { $_ | Should-Be 2 } } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal ("Expected at least one item in collection @(1, 1, 1) to pass filter { `$_ | Should-Be 2 }, but none of the items passed the filter. +Reasons : +Expected [int] 2, but got [int] 1. +Expected [int] 2, but got [int] 1. +Expected [int] 2, but got [int] 1." -replace "`r`n", "`n") + } + + It "Can filter using variables from the sorrounding context" { + $f = 1 + 2, 4 | Assert-Any { $_ / $f } + } + It "Validate messages" -TestCases @( @{ Actual = @(3, 4, 5); Message = "Expected at least one item in collection @(3, 4, 5) to pass filter { `$_ -eq 1 }, but none of the items passed the filter." } @{ Actual = 3; Message = "Expected at least one item in collection 3 to pass filter { `$_ -eq 1 }, but none of the items passed the filter." } From cc03bf4bc649133cbd447fa7a9d6895fe58ae7af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Tue, 23 Apr 2024 23:10:38 +0200 Subject: [PATCH 28/55] all and any --- .../assert/Collection/Assert-All.ps1 | 24 +++++++++---------- .../assert/Collection/Assert-Any.ps1 | 6 ++++- .../assert/Collection/Assert-All.Tests.ps1 | 12 ++++++++++ .../assert/Collection/Assert-Any.Tests.ps1 | 12 ++++++++++ 4 files changed, 41 insertions(+), 13 deletions(-) diff --git a/src/functions/assert/Collection/Assert-All.ps1 b/src/functions/assert/Collection/Assert-All.ps1 index d775ec9cd..a4742720b 100644 --- a/src/functions/assert/Collection/Assert-All.ps1 +++ b/src/functions/assert/Collection/Assert-All.ps1 @@ -14,11 +14,18 @@ $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual + if ($null -eq $Actual -or 0 -eq @($Actual).Count) { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Data $data -CustomMessage $CustomMessage -DefaultMessage "Expected all items in collection to pass filter , but contains no items to compare." + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) + } + $failReasons = $null $appendMore = $false - $predicate = { - # powershell v4 code where we have InvokeWithContext available - $underscore = & $SafeCommands['Get-Variable'] _ + # we are jumping between modules so I need to explicitly pass the _ variable + # simply using '&' won't work + # see: https://blogs.msdn.microsoft.com/sergey_babkins_blog/2014/10/30/calling-the-script-blocks-in-powershell/ + $actualFiltered = foreach ($item in $Actual) { + $underscore = [PSVariable]::new('_', $item) try { $pass = $FilterScript.InvokeWithContext($null, $underscore, $null) } @@ -35,17 +42,10 @@ $pass = $false } - if (-not $pass) { $_ } + if (-not $pass) { $item } } - # we are jumping between modules so I need to explicitly pass the _ variable - # simply using '&' won't work - # see: https://blogs.msdn.microsoft.com/sergey_babkins_blog/2014/10/30/calling-the-script-blocks-in-powershell/ - # - # Do NOT replace this Foreach-Object with foreach keyword, you will break the $_ variable. - $actualFiltered = $Actual | & $SafeCommands['ForEach-Object'] $predicate - - # Make sure are checking the count of the filtered items, not just a single item. + # Make sure are checking the count of the filtered items, not just truthiness of a single item. $actualFiltered = @($actualFiltered) if (0 -lt $actualFiltered.Count) { $data = @{ diff --git a/src/functions/assert/Collection/Assert-Any.ps1 b/src/functions/assert/Collection/Assert-Any.ps1 index f566d7c98..6eb3275b6 100644 --- a/src/functions/assert/Collection/Assert-Any.ps1 +++ b/src/functions/assert/Collection/Assert-Any.ps1 @@ -12,11 +12,15 @@ $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual + if ($null -eq $Actual -or 0 -eq @($Actual).Count) { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Data $data -CustomMessage $CustomMessage -DefaultMessage "Expected at least one item in collection to pass filter , but contains no items to compare." + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) + } + $failReasons = $null $appendMore = $false $pass = $false foreach ($item in $Actual) { - # powershell v4 code where we have InvokeWithContext available $underscore = [PSVariable]::new('_', $item) try { $pass = $FilterScript.InvokeWithContext($null, $underscore, $null) diff --git a/tst/functions/assert/Collection/Assert-All.Tests.ps1 b/tst/functions/assert/Collection/Assert-All.Tests.ps1 index 124f66666..ccbbb4715 100644 --- a/tst/functions/assert/Collection/Assert-All.Tests.ps1 +++ b/tst/functions/assert/Collection/Assert-All.Tests.ps1 @@ -26,6 +26,18 @@ Expected [int] 2, but got [int] 1. Expected [int] 2, but got [int] 1." -replace "`r`n", "`n") } + It "Fails when no items are passed" -TestCases @( + @{ Actual = $null; Expected = "Expected all items in collection to pass filter { `$_ -eq 1 }, but [null] `$null contains no items to compare." } + @{ Actual = @(); Expected = "Expected all items in collection to pass filter { `$_ -eq 1 }, but [collection] @() contains no items to compare." } + ) { + $err = { $Actual | Assert-All -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $Expected + } + + It "Fails when no items are passed" { + { Assert-All -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed + } + It "Validate messages" -TestCases @( @{ Actual = @(3, 4, 5); Message = "Expected all items in collection @(3, 4, 5) to pass filter { `$_ -eq 1 }, but 3 of them @(3, 4, 5) did not pass the filter." } ) { diff --git a/tst/functions/assert/Collection/Assert-Any.Tests.ps1 b/tst/functions/assert/Collection/Assert-Any.Tests.ps1 index 161f11cf9..6118310b3 100644 --- a/tst/functions/assert/Collection/Assert-Any.Tests.ps1 +++ b/tst/functions/assert/Collection/Assert-Any.Tests.ps1 @@ -26,6 +26,18 @@ Expected [int] 2, but got [int] 1. Expected [int] 2, but got [int] 1." -replace "`r`n", "`n") } + It "Fails when no items are passed" -TestCases @( + @{ Actual = $null; Expected = "Expected at least one item in collection to pass filter { `$_ -eq 1 }, but [null] `$null contains no items to compare." } + @{ Actual = @(); Expected = "Expected at least one item in collection to pass filter { `$_ -eq 1 }, but [collection] @() contains no items to compare." } + ) { + $err = { $Actual | Assert-Any -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $Expected + } + + It "Fails when no items are passed" { + { Assert-Any -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed + } + It "Can filter using variables from the sorrounding context" { $f = 1 2, 4 | Assert-Any { $_ / $f } From bdc7fcfa9f854fd54e3f37ee249490262897102d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Tue, 23 Apr 2024 23:29:34 +0200 Subject: [PATCH 29/55] Why did pass thru failing now? :/ --- azure-pipelines.yml | 2 +- test.ps1 | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 9e3f8f1a1..72162aff1 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -112,7 +112,7 @@ stages: targetType: inline pwsh: $(pwsh) script: | - & ./test.ps1 -CI -PassThru -NoBuild + & ./test.ps1 -CI -NoBuild workingDirectory: '$(Build.SourcesDirectory)' - task: PublishCodeCoverageResults@2 inputs: diff --git a/test.ps1 b/test.ps1 index ee9506828..dcf295be2 100644 --- a/test.ps1 +++ b/test.ps1 @@ -12,9 +12,12 @@ so leaving it in code would run only one test from the file on the server. .PARAMETER SkipPTests - Skips Passthrough P tests. Skip the tests written using the P module, Unit + Skips P tests. Skip the tests written using the P module, Unit Tests for the Runtime, and Acceptance Tests for Pester + .PARAMETER SkipPesterTests + Skips Pester tests, but not P tests. + .PARAMETER NoBuild Skips running build.ps1. Do not build the underlying csharp components. Used in CI pipeline since a clean build has already been run prior to Test. From 28ae51f18c7a2a4f5177af720e69eb000ff8d6ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Thu, 25 Apr 2024 08:24:20 +0200 Subject: [PATCH 30/55] Rename assertion files --- long list of stuff to do.md | 2 +- src/Module.ps1 | 10 ++++++---- src/Pester.psd1 | 6 ++++-- .../Boolean/{Assert-False.ps1 => Should-BeFalse.ps1} | 0 .../Boolean/{Assert-True.ps1 => Should-BeTrue.ps1} | 0 .../Collection/{Assert-All.ps1 => Should-All.ps1} | 0 .../Collection/{Assert-Any.ps1 => Should-Any.ps1} | 0 .../{Assert-Equivalent.ps1 => Should-BeEquivalent.ps1} | 0 .../Exception/{Assert-Throw.ps1 => Should-Throw.ps1} | 0 .../assert/General/{Assert-Equal.ps1 => Should-Be.ps1} | 0 ...ThanOrEqual.ps1 => Should-BeGreaterThanOrEqual.ps1} | 0 .../{Assert-LessThan.ps1 => Should-BeLessThan.ps1} | 0 ...essThanOrEqual.ps1 => Should-BeLessThanOrEqual.ps1} | 0 .../General/{Assert-Null.ps1 => Should-BeNull.ps1} | 0 .../General/{Assert-Same.ps1 => Should-BeSame.ps1} | 0 .../General/{Assert-Type.ps1 => Should-BeType.ps1} | 0 .../General/{Assert-NotEqual.ps1 => Should-NotBe.ps1} | 0 .../{Assert-NotNull.ps1 => Should-NotBeNull.ps1} | 0 .../{Assert-NotSame.ps1 => Should-NotBeSame.ps1} | 0 .../{Assert-NotType.ps1 => Should-NotBeType.ps1} | 0 ...Assert-GreaterThan.ps1 => ShouldBe-GreaterThan.ps1} | 0 .../Time/{Assert-After.ps1 => Should-BeAfter.ps1} | 0 .../Time/{Assert-Before.ps1 => Should-BeBefore.ps1} | 0 .../{Assert-Faster.ps1 => Should-BeFasterThan.ps1} | 0 .../{Assert-Slower.ps1 => Should-BeSlowerThan.ps1} | 0 .../String/Should-NotBeNullOrEmptyString.Tests.ps1 | 2 +- 26 files changed, 12 insertions(+), 8 deletions(-) rename src/functions/assert/Boolean/{Assert-False.ps1 => Should-BeFalse.ps1} (100%) rename src/functions/assert/Boolean/{Assert-True.ps1 => Should-BeTrue.ps1} (100%) rename src/functions/assert/Collection/{Assert-All.ps1 => Should-All.ps1} (100%) rename src/functions/assert/Collection/{Assert-Any.ps1 => Should-Any.ps1} (100%) rename src/functions/assert/Equivalence/{Assert-Equivalent.ps1 => Should-BeEquivalent.ps1} (100%) rename src/functions/assert/Exception/{Assert-Throw.ps1 => Should-Throw.ps1} (100%) rename src/functions/assert/General/{Assert-Equal.ps1 => Should-Be.ps1} (100%) rename src/functions/assert/General/{Assert-GreaterThanOrEqual.ps1 => Should-BeGreaterThanOrEqual.ps1} (100%) rename src/functions/assert/General/{Assert-LessThan.ps1 => Should-BeLessThan.ps1} (100%) rename src/functions/assert/General/{Assert-LessThanOrEqual.ps1 => Should-BeLessThanOrEqual.ps1} (100%) rename src/functions/assert/General/{Assert-Null.ps1 => Should-BeNull.ps1} (100%) rename src/functions/assert/General/{Assert-Same.ps1 => Should-BeSame.ps1} (100%) rename src/functions/assert/General/{Assert-Type.ps1 => Should-BeType.ps1} (100%) rename src/functions/assert/General/{Assert-NotEqual.ps1 => Should-NotBe.ps1} (100%) rename src/functions/assert/General/{Assert-NotNull.ps1 => Should-NotBeNull.ps1} (100%) rename src/functions/assert/General/{Assert-NotSame.ps1 => Should-NotBeSame.ps1} (100%) rename src/functions/assert/General/{Assert-NotType.ps1 => Should-NotBeType.ps1} (100%) rename src/functions/assert/General/{Assert-GreaterThan.ps1 => ShouldBe-GreaterThan.ps1} (100%) rename src/functions/assert/Time/{Assert-After.ps1 => Should-BeAfter.ps1} (100%) rename src/functions/assert/Time/{Assert-Before.ps1 => Should-BeBefore.ps1} (100%) rename src/functions/assert/Time/{Assert-Faster.ps1 => Should-BeFasterThan.ps1} (100%) rename src/functions/assert/Time/{Assert-Slower.ps1 => Should-BeSlowerThan.ps1} (100%) diff --git a/long list of stuff to do.md b/long list of stuff to do.md index 2616942c8..0bfa2a0bc 100644 --- a/long list of stuff to do.md +++ b/long list of stuff to do.md @@ -13,7 +13,7 @@ - [ ] Should-BeTrue - [ ] Should-BeFalse - [ ] Should-MatchString -- [ ] Should-ContainString +- [ ] Should-ContainCollectionString - [ ] Should-BeEmptyString - [ ] Should-BeWhitespaceString - [ ] Should-BeEquivalentToString diff --git a/src/Module.ps1 b/src/Module.ps1 index 4457fe616..667f5c4cc 100644 --- a/src/Module.ps1 +++ b/src/Module.ps1 @@ -12,8 +12,8 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session & $SafeCommands['Set-Alias'] 'Should-BeTrue' 'Assert-True' & $SafeCommands['Set-Alias'] 'Should-All' 'Assert-All' & $SafeCommands['Set-Alias'] 'Should-Any' 'Assert-Any' -& $SafeCommands['Set-Alias'] 'Should-Contain' 'Assert-Contain' -& $SafeCommands['Set-Alias'] 'Should-NotContain' 'Assert-NotContain' +& $SafeCommands['Set-Alias'] 'Should-ContainCollection' 'Assert-Contain' +& $SafeCommands['Set-Alias'] 'Should-NotContainCollection' 'Assert-NotContain' & $SafeCommands['Set-Alias'] 'Should-BeEquivalent' 'Assert-Equivalent' & $SafeCommands['Set-Alias'] 'Should-Throw' 'Assert-Throw' & $SafeCommands['Set-Alias'] 'Should-Be' 'Assert-Equal' @@ -83,6 +83,7 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session 'Assert-Any' 'Assert-Contain' 'Assert-NotContain' + 'Assert-Collection' 'Assert-Equivalent' 'Assert-Throw' 'Assert-Equal' @@ -138,8 +139,9 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session # collection 'Should-All' 'Should-Any' - 'Should-Contain' - 'Should-NotContain' + 'Should-BeCollection' + 'Should-ContainCollection' + 'Should-NotContainCollection' 'Should-BeEquivalent' 'Should-Throw' 'Should-Be' diff --git a/src/Pester.psd1 b/src/Pester.psd1 index 6eb2d35de..e32453511 100644 --- a/src/Pester.psd1 +++ b/src/Pester.psd1 @@ -73,6 +73,7 @@ 'Assert-Any' 'Assert-Contain' 'Assert-NotContain' + 'Assert-Collection' 'Assert-Equivalent' 'Assert-Throw' 'Assert-Equal' @@ -127,8 +128,9 @@ # collection 'Should-All' 'Should-Any' - 'Should-Contain' - 'Should-NotContain' + 'Should-ContainCollection' + 'Should-NotContainCollection' + 'Should-BeCollection' 'Should-BeEquivalent' 'Should-Throw' 'Should-Be' diff --git a/src/functions/assert/Boolean/Assert-False.ps1 b/src/functions/assert/Boolean/Should-BeFalse.ps1 similarity index 100% rename from src/functions/assert/Boolean/Assert-False.ps1 rename to src/functions/assert/Boolean/Should-BeFalse.ps1 diff --git a/src/functions/assert/Boolean/Assert-True.ps1 b/src/functions/assert/Boolean/Should-BeTrue.ps1 similarity index 100% rename from src/functions/assert/Boolean/Assert-True.ps1 rename to src/functions/assert/Boolean/Should-BeTrue.ps1 diff --git a/src/functions/assert/Collection/Assert-All.ps1 b/src/functions/assert/Collection/Should-All.ps1 similarity index 100% rename from src/functions/assert/Collection/Assert-All.ps1 rename to src/functions/assert/Collection/Should-All.ps1 diff --git a/src/functions/assert/Collection/Assert-Any.ps1 b/src/functions/assert/Collection/Should-Any.ps1 similarity index 100% rename from src/functions/assert/Collection/Assert-Any.ps1 rename to src/functions/assert/Collection/Should-Any.ps1 diff --git a/src/functions/assert/Equivalence/Assert-Equivalent.ps1 b/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 similarity index 100% rename from src/functions/assert/Equivalence/Assert-Equivalent.ps1 rename to src/functions/assert/Equivalence/Should-BeEquivalent.ps1 diff --git a/src/functions/assert/Exception/Assert-Throw.ps1 b/src/functions/assert/Exception/Should-Throw.ps1 similarity index 100% rename from src/functions/assert/Exception/Assert-Throw.ps1 rename to src/functions/assert/Exception/Should-Throw.ps1 diff --git a/src/functions/assert/General/Assert-Equal.ps1 b/src/functions/assert/General/Should-Be.ps1 similarity index 100% rename from src/functions/assert/General/Assert-Equal.ps1 rename to src/functions/assert/General/Should-Be.ps1 diff --git a/src/functions/assert/General/Assert-GreaterThanOrEqual.ps1 b/src/functions/assert/General/Should-BeGreaterThanOrEqual.ps1 similarity index 100% rename from src/functions/assert/General/Assert-GreaterThanOrEqual.ps1 rename to src/functions/assert/General/Should-BeGreaterThanOrEqual.ps1 diff --git a/src/functions/assert/General/Assert-LessThan.ps1 b/src/functions/assert/General/Should-BeLessThan.ps1 similarity index 100% rename from src/functions/assert/General/Assert-LessThan.ps1 rename to src/functions/assert/General/Should-BeLessThan.ps1 diff --git a/src/functions/assert/General/Assert-LessThanOrEqual.ps1 b/src/functions/assert/General/Should-BeLessThanOrEqual.ps1 similarity index 100% rename from src/functions/assert/General/Assert-LessThanOrEqual.ps1 rename to src/functions/assert/General/Should-BeLessThanOrEqual.ps1 diff --git a/src/functions/assert/General/Assert-Null.ps1 b/src/functions/assert/General/Should-BeNull.ps1 similarity index 100% rename from src/functions/assert/General/Assert-Null.ps1 rename to src/functions/assert/General/Should-BeNull.ps1 diff --git a/src/functions/assert/General/Assert-Same.ps1 b/src/functions/assert/General/Should-BeSame.ps1 similarity index 100% rename from src/functions/assert/General/Assert-Same.ps1 rename to src/functions/assert/General/Should-BeSame.ps1 diff --git a/src/functions/assert/General/Assert-Type.ps1 b/src/functions/assert/General/Should-BeType.ps1 similarity index 100% rename from src/functions/assert/General/Assert-Type.ps1 rename to src/functions/assert/General/Should-BeType.ps1 diff --git a/src/functions/assert/General/Assert-NotEqual.ps1 b/src/functions/assert/General/Should-NotBe.ps1 similarity index 100% rename from src/functions/assert/General/Assert-NotEqual.ps1 rename to src/functions/assert/General/Should-NotBe.ps1 diff --git a/src/functions/assert/General/Assert-NotNull.ps1 b/src/functions/assert/General/Should-NotBeNull.ps1 similarity index 100% rename from src/functions/assert/General/Assert-NotNull.ps1 rename to src/functions/assert/General/Should-NotBeNull.ps1 diff --git a/src/functions/assert/General/Assert-NotSame.ps1 b/src/functions/assert/General/Should-NotBeSame.ps1 similarity index 100% rename from src/functions/assert/General/Assert-NotSame.ps1 rename to src/functions/assert/General/Should-NotBeSame.ps1 diff --git a/src/functions/assert/General/Assert-NotType.ps1 b/src/functions/assert/General/Should-NotBeType.ps1 similarity index 100% rename from src/functions/assert/General/Assert-NotType.ps1 rename to src/functions/assert/General/Should-NotBeType.ps1 diff --git a/src/functions/assert/General/Assert-GreaterThan.ps1 b/src/functions/assert/General/ShouldBe-GreaterThan.ps1 similarity index 100% rename from src/functions/assert/General/Assert-GreaterThan.ps1 rename to src/functions/assert/General/ShouldBe-GreaterThan.ps1 diff --git a/src/functions/assert/Time/Assert-After.ps1 b/src/functions/assert/Time/Should-BeAfter.ps1 similarity index 100% rename from src/functions/assert/Time/Assert-After.ps1 rename to src/functions/assert/Time/Should-BeAfter.ps1 diff --git a/src/functions/assert/Time/Assert-Before.ps1 b/src/functions/assert/Time/Should-BeBefore.ps1 similarity index 100% rename from src/functions/assert/Time/Assert-Before.ps1 rename to src/functions/assert/Time/Should-BeBefore.ps1 diff --git a/src/functions/assert/Time/Assert-Faster.ps1 b/src/functions/assert/Time/Should-BeFasterThan.ps1 similarity index 100% rename from src/functions/assert/Time/Assert-Faster.ps1 rename to src/functions/assert/Time/Should-BeFasterThan.ps1 diff --git a/src/functions/assert/Time/Assert-Slower.ps1 b/src/functions/assert/Time/Should-BeSlowerThan.ps1 similarity index 100% rename from src/functions/assert/Time/Assert-Slower.ps1 rename to src/functions/assert/Time/Should-BeSlowerThan.ps1 diff --git a/tst/functions/assert/String/Should-NotBeNullOrEmptyString.Tests.ps1 b/tst/functions/assert/String/Should-NotBeNullOrEmptyString.Tests.ps1 index 8bcd9e22c..8f00564cc 100644 --- a/tst/functions/assert/String/Should-NotBeNullOrEmptyString.Tests.ps1 +++ b/tst/functions/assert/String/Should-NotBeNullOrEmptyString.Tests.ps1 @@ -6,7 +6,7 @@ Describe "Should-NotBeNullOrEmptyString" { @{ Actual = " " } @{ Actual = "`t" } @{ Actual = "`n" } - @{ Actual = "`r" } + @{ Actual = "" } ) { $Actual | Should-NotBeNullOrEmptyString } From c70bdd2f1c4b735a2686d3e166f94dbc5cdb2951 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Thu, 25 Apr 2024 23:31:29 +0200 Subject: [PATCH 31/55] rename some files --- src/Module.ps1 | 1 + ...Collection.ps1 => Should-BeCollection.ps1} | 0 ...ntain.ps1 => Should-ContainCollection.ps1} | 0 ...in.ps1 => Should-NotContainCollection.ps1} | 0 ...lse.Tests.ps1 => Should-BeFalse.Tests.ps1} | 17 ++++++++-------- ...True.Tests.ps1 => Should-BeTrue.Tests.ps1} | 14 ++++++------- .../Collection/Assert-NotCollection.Tests.ps1 | 1 - ...ert-All.Tests.ps1 => Should-All.Tests.ps1} | 20 +++++++++---------- ...ert-Any.Tests.ps1 => Should-Any.Tests.ps1} | 18 ++++++++--------- ...ests.ps1 => Should-BeCollection.Tests.ps1} | 6 +++--- ...ps1 => Should-ContainCollection.Tests.ps1} | 12 +++++------ ... => Should-NotContainCollection.Tests.ps1} | 12 +++++------ 12 files changed, 50 insertions(+), 51 deletions(-) rename src/functions/assert/Collection/{Assert-Collection.ps1 => Should-BeCollection.ps1} (100%) rename src/functions/assert/Collection/{Assert-Contain.ps1 => Should-ContainCollection.ps1} (100%) rename src/functions/assert/Collection/{Assert-NotContain.ps1 => Should-NotContainCollection.ps1} (100%) rename tst/functions/assert/Boolean/{Assert-False.Tests.ps1 => Should-BeFalse.Tests.ps1} (68%) rename tst/functions/assert/Boolean/{Assert-True.Tests.ps1 => Should-BeTrue.Tests.ps1} (71%) delete mode 100644 tst/functions/assert/Collection/Assert-NotCollection.Tests.ps1 rename tst/functions/assert/Collection/{Assert-All.Tests.ps1 => Should-All.Tests.ps1} (80%) rename tst/functions/assert/Collection/{Assert-Any.Tests.ps1 => Should-Any.Tests.ps1} (83%) rename tst/functions/assert/Collection/{Assert-Collection.Tests.ps1 => Should-BeCollection.Tests.ps1} (87%) rename tst/functions/assert/Collection/{Assert-Contain.Tests.ps1 => Should-ContainCollection.Tests.ps1} (66%) rename tst/functions/assert/Collection/{Assert-NotContain.Tests.ps1 => Should-NotContainCollection.Tests.ps1} (65%) diff --git a/src/Module.ps1 b/src/Module.ps1 index 667f5c4cc..f10012083 100644 --- a/src/Module.ps1 +++ b/src/Module.ps1 @@ -12,6 +12,7 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session & $SafeCommands['Set-Alias'] 'Should-BeTrue' 'Assert-True' & $SafeCommands['Set-Alias'] 'Should-All' 'Assert-All' & $SafeCommands['Set-Alias'] 'Should-Any' 'Assert-Any' +& $SafeCommands['Set-Alias'] 'Should-BeCollection' 'Assert-Contain' & $SafeCommands['Set-Alias'] 'Should-ContainCollection' 'Assert-Contain' & $SafeCommands['Set-Alias'] 'Should-NotContainCollection' 'Assert-NotContain' & $SafeCommands['Set-Alias'] 'Should-BeEquivalent' 'Assert-Equivalent' diff --git a/src/functions/assert/Collection/Assert-Collection.ps1 b/src/functions/assert/Collection/Should-BeCollection.ps1 similarity index 100% rename from src/functions/assert/Collection/Assert-Collection.ps1 rename to src/functions/assert/Collection/Should-BeCollection.ps1 diff --git a/src/functions/assert/Collection/Assert-Contain.ps1 b/src/functions/assert/Collection/Should-ContainCollection.ps1 similarity index 100% rename from src/functions/assert/Collection/Assert-Contain.ps1 rename to src/functions/assert/Collection/Should-ContainCollection.ps1 diff --git a/src/functions/assert/Collection/Assert-NotContain.ps1 b/src/functions/assert/Collection/Should-NotContainCollection.ps1 similarity index 100% rename from src/functions/assert/Collection/Assert-NotContain.ps1 rename to src/functions/assert/Collection/Should-NotContainCollection.ps1 diff --git a/tst/functions/assert/Boolean/Assert-False.Tests.ps1 b/tst/functions/assert/Boolean/Should-BeFalse.Tests.ps1 similarity index 68% rename from tst/functions/assert/Boolean/Assert-False.Tests.ps1 rename to tst/functions/assert/Boolean/Should-BeFalse.Tests.ps1 index 456c41ffa..1366ec290 100644 --- a/tst/functions/assert/Boolean/Assert-False.Tests.ps1 +++ b/tst/functions/assert/Boolean/Should-BeFalse.Tests.ps1 @@ -1,8 +1,8 @@ Set-StrictMode -Version Latest -Describe "Assert-False" { +Describe "Should-BeFalse" { It "Passes when given `$false" { - $false | Assert-False + $false | Should-BeFalse } It "Passes when given falsy value ''" -TestCases @( @@ -12,15 +12,15 @@ Describe "Assert-False" { @{ Actual = @() } ) { param($Actual) - Assert-False -Actual $Actual + Should-BeFalse -Actual $Actual } It "Fails for array input even if the last item is `$false" { - { $true, $true, $false | Assert-False } | Verify-AssertionFailed + { $true, $true, $false | Should-BeFalse } | Verify-AssertionFailed } It "Fails with custom message" { - $err = { 9 | Assert-False -CustomMessage " is not false" } | Verify-AssertionFailed + $err = { 9 | Should-BeFalse -CustomMessage " is not false" } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal "9 is not false" } @@ -29,18 +29,17 @@ Describe "Assert-False" { @{ Actual = $true ; Message = "Expected [bool] `$true to be [bool] `$false or falsy value 0, """", `$null, @()." }, @{ Actual = 10 ; Message = "Expected [int] 10 to be [bool] `$false or falsy value 0, """", `$null, @()." } ) { - param($Actual, $Message) - $err = { Assert-False -Actual $Actual } | Verify-AssertionFailed + $err = { Should-BeFalse -Actual $Actual } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message } } It "Returns the value on output" { $expected = $false - $expected | Assert-False | Verify-Equal $expected + $expected | Should-BeFalse | Verify-Equal $expected } It "Can be called with positional parameters" { - { Assert-False $true } | Verify-AssertionFailed + { Should-BeFalse $true } | Verify-AssertionFailed } } diff --git a/tst/functions/assert/Boolean/Assert-True.Tests.ps1 b/tst/functions/assert/Boolean/Should-BeTrue.Tests.ps1 similarity index 71% rename from tst/functions/assert/Boolean/Assert-True.Tests.ps1 rename to tst/functions/assert/Boolean/Should-BeTrue.Tests.ps1 index a3559abf0..1f2c2f94b 100644 --- a/tst/functions/assert/Boolean/Assert-True.Tests.ps1 +++ b/tst/functions/assert/Boolean/Should-BeTrue.Tests.ps1 @@ -1,8 +1,8 @@ Set-StrictMode -Version Latest -Describe "Assert-True" { +Describe "Should-BeTrue" { It "Passes when given `$true" { - $true | Assert-True + $true | Should-BeTrue } It "Passes when given truthy" -TestCases @( @@ -12,11 +12,11 @@ Describe "Assert-True" { @{ Actual = 1, 2 } ) { param($Actual) - Assert-True -Actual $Actual + Should-BeTrue -Actual $Actual } It "Fails with custom message" { - $err = { $null | Assert-True -CustomMessage " is not true" } | Verify-AssertionFailed + $err = { $null | Should-BeTrue -CustomMessage " is not true" } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal "`$null is not true" } @@ -26,17 +26,17 @@ Describe "Assert-True" { @{ Actual = 0 ; Message = "Expected [int] 0 to be [bool] `$true or truthy value." } ) { param($Actual, $Message) - $err = { Assert-True -Actual $Actual } | Verify-AssertionFailed + $err = { Should-BeTrue -Actual $Actual } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message } } It "Returns the value on output" { $expected = $true - $expected | Assert-True | Verify-Equal $expected + $expected | Should-BeTrue | Verify-Equal $expected } It "Can be called with positional parameters" { - { Assert-True $false } | Verify-AssertionFailed + { Should-BeTrue $false } | Verify-AssertionFailed } } diff --git a/tst/functions/assert/Collection/Assert-NotCollection.Tests.ps1 b/tst/functions/assert/Collection/Assert-NotCollection.Tests.ps1 deleted file mode 100644 index 0013d9112..000000000 --- a/tst/functions/assert/Collection/Assert-NotCollection.Tests.ps1 +++ /dev/null @@ -1 +0,0 @@ -Set-StrictMode -Version Latest diff --git a/tst/functions/assert/Collection/Assert-All.Tests.ps1 b/tst/functions/assert/Collection/Should-All.Tests.ps1 similarity index 80% rename from tst/functions/assert/Collection/Assert-All.Tests.ps1 rename to tst/functions/assert/Collection/Should-All.Tests.ps1 index ccbbb4715..fb47ac240 100644 --- a/tst/functions/assert/Collection/Assert-All.Tests.ps1 +++ b/tst/functions/assert/Collection/Should-All.Tests.ps1 @@ -1,12 +1,12 @@ Set-StrictMode -Version Latest -Describe "Assert-All" { +Describe "Should-All" { It "Passes when all items in the given collection pass the predicate" -TestCases @( @{ Actual = 1, 1, 1, 1 } @{ Actual = @(1) } @{ Actual = 1 } ) { - $Actual | Assert-All -FilterScript { $_ -eq 1 } + $Actual | Should-All -FilterScript { $_ -eq 1 } } It "Fails when any item in the given collection does not pass the predicate" -TestCases @( @@ -14,7 +14,7 @@ Describe "Assert-All" { @{ Actual = @(2) } @{ Actual = 2 } ) { - { $Actual | Assert-All -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed + { $Actual | Should-All -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed } It "Can be failed by other assertion" { @@ -30,38 +30,38 @@ Expected [int] 2, but got [int] 1." -replace "`r`n", "`n") @{ Actual = $null; Expected = "Expected all items in collection to pass filter { `$_ -eq 1 }, but [null] `$null contains no items to compare." } @{ Actual = @(); Expected = "Expected all items in collection to pass filter { `$_ -eq 1 }, but [collection] @() contains no items to compare." } ) { - $err = { $Actual | Assert-All -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed + $err = { $Actual | Should-All -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Expected } It "Fails when no items are passed" { - { Assert-All -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed + { Should-All -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed } It "Validate messages" -TestCases @( @{ Actual = @(3, 4, 5); Message = "Expected all items in collection @(3, 4, 5) to pass filter { `$_ -eq 1 }, but 3 of them @(3, 4, 5) did not pass the filter." } ) { - $err = { $Actual | Assert-All -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed + $err = { $Actual | Should-All -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message } It "Returns the value on output" { $expected = "a", "b" - $v = $expected | Assert-All { $true } + $v = $expected | Should-All { $true } $v[0] | Verify-Equal $expected[0] $v[1] | Verify-Equal $expected[1] } It "Can filter using variables from the sorrounding context" { $f = 1 - 2, 4 | Assert-All { $_ / $f } + 2, 4 | Should-All { $_ / $f } } It "Accepts FilterScript and Actual by position" { - Assert-All { $true } 1, 2 + Should-All { $true } 1, 2 } It 'It fails when the only item not matching the filter is 0' { - { 0 | Assert-All -FilterScript { $_ -gt 0 } } | Verify-AssertionFailed + { 0 | Should-All -FilterScript { $_ -gt 0 } } | Verify-AssertionFailed } } diff --git a/tst/functions/assert/Collection/Assert-Any.Tests.ps1 b/tst/functions/assert/Collection/Should-Any.Tests.ps1 similarity index 83% rename from tst/functions/assert/Collection/Assert-Any.Tests.ps1 rename to tst/functions/assert/Collection/Should-Any.Tests.ps1 index 6118310b3..c4a2f54c7 100644 --- a/tst/functions/assert/Collection/Assert-Any.Tests.ps1 +++ b/tst/functions/assert/Collection/Should-Any.Tests.ps1 @@ -1,12 +1,12 @@ Set-StrictMode -Version Latest -Describe "Assert-Any" { +Describe "Should-Any" { It "Passes when at least one item in the given collection passes the predicate" -TestCases @( @{ Actual = @(1, 2, 3) } @{ Actual = @(1) } @{ Actual = 1 } ) { - $Actual | Assert-Any -FilterScript { $_ -eq 1 } + $Actual | Should-Any -FilterScript { $_ -eq 1 } } It "Fails when none of the items passes the predicate" -TestCases @( @@ -14,7 +14,7 @@ Describe "Assert-Any" { @{ Actual = @(1) } @{ Actual = 1 } ) { - { $Actual | Assert-Any -FilterScript { $_ -eq 0 } } | Verify-AssertionFailed + { $Actual | Should-Any -FilterScript { $_ -eq 0 } } | Verify-AssertionFailed } It "Can be failed by other assertion" { @@ -30,17 +30,17 @@ Expected [int] 2, but got [int] 1." -replace "`r`n", "`n") @{ Actual = $null; Expected = "Expected at least one item in collection to pass filter { `$_ -eq 1 }, but [null] `$null contains no items to compare." } @{ Actual = @(); Expected = "Expected at least one item in collection to pass filter { `$_ -eq 1 }, but [collection] @() contains no items to compare." } ) { - $err = { $Actual | Assert-Any -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed + $err = { $Actual | Should-Any -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Expected } It "Fails when no items are passed" { - { Assert-Any -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed + { Should-Any -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed } It "Can filter using variables from the sorrounding context" { $f = 1 - 2, 4 | Assert-Any { $_ / $f } + 2, 4 | Should-Any { $_ / $f } } It "Validate messages" -TestCases @( @@ -48,18 +48,18 @@ Expected [int] 2, but got [int] 1." -replace "`r`n", "`n") @{ Actual = 3; Message = "Expected at least one item in collection 3 to pass filter { `$_ -eq 1 }, but none of the items passed the filter." } @{ Actual = 3; Message = "Expected at least one item in collection 3 to pass filter { `$_ -eq 1 }, but none of the items passed the filter." } ) { - $err = { $Actual | Assert-Any -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed + $err = { $Actual | Should-Any -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message } It "Returns the value on output" { $expected = "a", "b" - $v = $expected | Assert-Any { $true } + $v = $expected | Should-Any { $true } $v[0] | Verify-Equal $expected[0] $v[1] | Verify-Equal $expected[1] } It "Accepts FilterScript and Actual by position" { - Assert-Any { $true } 1, 2 + Should-Any { $true } 1, 2 } } diff --git a/tst/functions/assert/Collection/Assert-Collection.Tests.ps1 b/tst/functions/assert/Collection/Should-BeCollection.Tests.ps1 similarity index 87% rename from tst/functions/assert/Collection/Assert-Collection.Tests.ps1 rename to tst/functions/assert/Collection/Should-BeCollection.Tests.ps1 index fe1196b38..f46b53fc9 100644 --- a/tst/functions/assert/Collection/Assert-Collection.Tests.ps1 +++ b/tst/functions/assert/Collection/Should-BeCollection.Tests.ps1 @@ -4,19 +4,19 @@ return InPesterModuleScope { - Describe "Assert-Collection" { + Describe "Should-BeCollection" { It "Passes when collections have the same count and items" -ForEach @( @{ Actual = @(1); Expected = @(1) } @{ Actual = @(1, 2); Expected = @(1, 2) } ) { - $actual | Assert-Collection $expected + $actual | Should-BeCollection $expected } It "Fails when collections don't have the same count" -ForEach @( @{ Actual = @(1); Expected = @(1, 2) } @{ Actual = @(1, 2); Expected = @(1) } ) { - $err = { $actual | Assert-Collection $expected } | Verify-AssertionFailed + $err = { $actual | Should-BeCollection $expected } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal "Expected int '1' to be present in collection '5', but it was not there." } diff --git a/tst/functions/assert/Collection/Assert-Contain.Tests.ps1 b/tst/functions/assert/Collection/Should-ContainCollection.Tests.ps1 similarity index 66% rename from tst/functions/assert/Collection/Assert-Contain.Tests.ps1 rename to tst/functions/assert/Collection/Should-ContainCollection.Tests.ps1 index d425d64c8..6061a868b 100644 --- a/tst/functions/assert/Collection/Assert-Contain.Tests.ps1 +++ b/tst/functions/assert/Collection/Should-ContainCollection.Tests.ps1 @@ -1,27 +1,27 @@ Set-StrictMode -Version Latest InPesterModuleScope { - Describe "Assert-Contain" { + Describe "Should-ContainCollection" { It "Passes when collection of single item contains the expected item" { - @(1) | Assert-Contain 1 + @(1) | Should-ContainCollection 1 } It "Fails when collection of single item does not contain the expected item" { - $err = { @(5) | Assert-Contain 1 } | Verify-AssertionFailed + $err = { @(5) | Should-ContainCollection 1 } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal "Expected [int] 1 to be present in collection 5, but it was not there." } It "Passes when collection of multiple items contains the expected item" { - @(1, 2, 3) | Assert-Contain 1 + @(1, 2, 3) | Should-ContainCollection 1 } It "Fails when collection of multiple items does not contain the expected item" { - $err = { @(5, 6, 7) | Assert-Contain 1 } | Verify-AssertionFailed + $err = { @(5, 6, 7) | Should-ContainCollection 1 } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal "Expected [int] 1 to be present in collection @(5, 6, 7), but it was not there." } It "Can be called with positional parameters" { - { Assert-Contain 1 3, 4, 5 } | Verify-AssertionFailed + { Should-ContainCollection 1 3, 4, 5 } | Verify-AssertionFailed } } } diff --git a/tst/functions/assert/Collection/Assert-NotContain.Tests.ps1 b/tst/functions/assert/Collection/Should-NotContainCollection.Tests.ps1 similarity index 65% rename from tst/functions/assert/Collection/Assert-NotContain.Tests.ps1 rename to tst/functions/assert/Collection/Should-NotContainCollection.Tests.ps1 index 21a987c4c..1ab0f9255 100644 --- a/tst/functions/assert/Collection/Assert-NotContain.Tests.ps1 +++ b/tst/functions/assert/Collection/Should-NotContainCollection.Tests.ps1 @@ -1,27 +1,27 @@ Set-StrictMode -Version Latest InPesterModuleScope { - Describe "Assert-NotContain" { + Describe "Should-NotContainCollection" { It "Fails when collection of single item contains the expected item" { - $err = { @(1) | Assert-NotContain 1 } | Verify-AssertionFailed + $err = { @(1) | Should-NotContainCollection 1 } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal "Expected [int] 1 to not be present in collection 1, but it was there." } It "Passes when collection of single item does not contain the expected item" { - @(5) | Assert-NotContain 1 + @(5) | Should-NotContainCollection 1 } It "Fails when collection of multiple items contains the expected item" { - $err = { @(1, 2, 3) | Assert-NotContain 1 } | Verify-AssertionFailed + $err = { @(1, 2, 3) | Should-NotContainCollection 1 } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal "Expected [int] 1 to not be present in collection @(1, 2, 3), but it was there." } It "Passes when collection of multiple items does not contain the expected item" { - @(5, 6, 7) | Assert-NotContain 1 + @(5, 6, 7) | Should-NotContainCollection 1 } It "Can be called with positional parameters" { - { Assert-NotContain 1 1, 2, 3 } | Verify-AssertionFailed + { Should-NotContainCollection 1 1, 2, 3 } | Verify-AssertionFailed } } } From 6dd68d61f09401ddaf0fa857a4b271e882cfbc76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Fri, 26 Apr 2024 09:08:13 +0200 Subject: [PATCH 32/55] Continue on renaming and using Should-* in tests --- src/Module.ps1 | 12 +- src/Pester.psd1 | 6 +- src/functions/assert/Common/Collect-Input.ps1 | 21 +- .../assert/General/Should-BeSame.ps1 | 2 +- ...{Should-BeType.ps1 => Should-HaveType.ps1} | 0 ...d-NotBeType.ps1 => Should-NotHaveType.ps1} | 0 ...ssert-Like.ps1 => Should-BeLikeString.ps1} | 0 ...rt-StringEqual.ps1 => Should-BeString.ps1} | 0 ...NotLike.ps1 => Should-NotBeLikeString.ps1} | 0 ...ingNotEqual.ps1 => Should-NotBeString.ps1} | 0 ... => Should-BeEquivalent.Options.Tests.ps1} | 220 +++++++++--------- ...ests.ps1 => Should-BeEquivalent.Tests.ps1} | 16 +- ...Throw.Tests.ps1 => Should-Throw.Tests.ps1} | 64 ++--- .../assert/General/Assert-Equal.Tests.ps1 | 92 -------- .../General/Assert-GreaterThan.Tests.ps1 | 110 --------- .../Assert-GreaterThanOrEqual.Tests.ps1 | 110 --------- .../assert/General/Assert-NotEqual.Tests.ps1 | 91 -------- .../assert/General/Assert-NotSame.Tests.ps1 | 47 ---- .../assert/General/Assert-NotType.Tests.ps1 | 21 -- .../assert/General/Assert-Null.Tests.ps1 | 29 --- .../assert/General/Assert-Same.Tests.ps1 | 61 ----- .../assert/General/Assert-Type.Tests.ps1 | 21 -- .../assert/General/Should-Be.Tests.ps1 | 90 +++++++ .../General/Should-BeGreaterThan.Tests.ps1 | 108 +++++++++ .../Should-BeGreaterThanOrEqual.Tests.ps1 | 108 +++++++++ ....Tests.ps1 => Should-BeLessThan.Tests.ps1} | 42 ++-- ...ps1 => Should-BeLessThanOrEqual.Tests.ps1} | 42 ++-- .../assert/General/Should-BeNull.Tests.ps1 | 27 +++ .../assert/General/Should-BeSame.Tests.ps1 | 56 +++++ .../assert/General/Should-HaveType.Tests.ps1 | 19 ++ .../assert/General/Should-NotBe.Tests.ps1 | 90 +++++++ ...l.Tests.ps1 => Should-NotBeNull.Tests.ps1} | 10 +- .../assert/General/Should-NotBeSame.Tests.ps1 | 46 ++++ .../General/Should-NotHaveType.Tests.ps1 | 19 ++ .../String/Assert-StringNotEqual.Tests.ps1 | 60 ----- ...ests.ps1 => Should-BeLikeString.Tests.ps1} | 88 +++---- ...s.ps1 => Should-NotBeLikeString.Tests.ps1} | 99 ++++---- .../String/Should-NotBeString.Tests.ps1 | 61 +++++ 38 files changed, 939 insertions(+), 949 deletions(-) rename src/functions/assert/General/{Should-BeType.ps1 => Should-HaveType.ps1} (100%) rename src/functions/assert/General/{Should-NotBeType.ps1 => Should-NotHaveType.ps1} (100%) rename src/functions/assert/String/{Assert-Like.ps1 => Should-BeLikeString.ps1} (100%) rename src/functions/assert/String/{Assert-StringEqual.ps1 => Should-BeString.ps1} (100%) rename src/functions/assert/String/{Assert-NotLike.ps1 => Should-NotBeLikeString.ps1} (100%) rename src/functions/assert/String/{Assert-StringNotEqual.ps1 => Should-NotBeString.ps1} (100%) rename tst/functions/assert/Equivalence/{Assert-Equivalent.Options.Tests.ps1 => Should-BeEquivalent.Options.Tests.ps1} (65%) rename tst/functions/assert/Equivalence/{Assert-Equivalent.Tests.ps1 => Should-BeEquivalent.Tests.ps1} (97%) rename tst/functions/assert/Exception/{Assert-Throw.Tests.ps1 => Should-Throw.Tests.ps1} (76%) delete mode 100644 tst/functions/assert/General/Assert-Equal.Tests.ps1 delete mode 100644 tst/functions/assert/General/Assert-GreaterThan.Tests.ps1 delete mode 100644 tst/functions/assert/General/Assert-GreaterThanOrEqual.Tests.ps1 delete mode 100644 tst/functions/assert/General/Assert-NotEqual.Tests.ps1 delete mode 100644 tst/functions/assert/General/Assert-NotSame.Tests.ps1 delete mode 100644 tst/functions/assert/General/Assert-NotType.Tests.ps1 delete mode 100644 tst/functions/assert/General/Assert-Null.Tests.ps1 delete mode 100644 tst/functions/assert/General/Assert-Same.Tests.ps1 delete mode 100644 tst/functions/assert/General/Assert-Type.Tests.ps1 create mode 100644 tst/functions/assert/General/Should-Be.Tests.ps1 create mode 100644 tst/functions/assert/General/Should-BeGreaterThan.Tests.ps1 create mode 100644 tst/functions/assert/General/Should-BeGreaterThanOrEqual.Tests.ps1 rename tst/functions/assert/General/{Assert-LessThan.Tests.ps1 => Should-BeLessThan.Tests.ps1} (66%) rename tst/functions/assert/General/{Assert-LessThanOrEqual.Tests.ps1 => Should-BeLessThanOrEqual.Tests.ps1} (67%) create mode 100644 tst/functions/assert/General/Should-BeNull.Tests.ps1 create mode 100644 tst/functions/assert/General/Should-BeSame.Tests.ps1 create mode 100644 tst/functions/assert/General/Should-HaveType.Tests.ps1 create mode 100644 tst/functions/assert/General/Should-NotBe.Tests.ps1 rename tst/functions/assert/General/{Assert-NotNull.Tests.ps1 => Should-NotBeNull.Tests.ps1} (53%) create mode 100644 tst/functions/assert/General/Should-NotBeSame.Tests.ps1 create mode 100644 tst/functions/assert/General/Should-NotHaveType.Tests.ps1 delete mode 100644 tst/functions/assert/String/Assert-StringNotEqual.Tests.ps1 rename tst/functions/assert/String/{Assert-Like.Tests.ps1 => Should-BeLikeString.Tests.ps1} (59%) rename tst/functions/assert/String/{Assert-NotLike.Tests.ps1 => Should-NotBeLikeString.Tests.ps1} (53%) create mode 100644 tst/functions/assert/String/Should-NotBeString.Tests.ps1 diff --git a/src/Module.ps1 b/src/Module.ps1 index f10012083..ff77951d5 100644 --- a/src/Module.ps1 +++ b/src/Module.ps1 @@ -22,13 +22,13 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session & $SafeCommands['Set-Alias'] 'Should-BeGreaterThanOrEqual' 'Assert-GreaterThanOrEqual' & $SafeCommands['Set-Alias'] 'Should-BeLessThan' 'Assert-LessThan' & $SafeCommands['Set-Alias'] 'Should-BeLessThanOrEqual' 'Assert-LessThanOrEqual' -& $SafeCommands['Set-Alias'] 'Should-NotBeEqual' 'Assert-NotEqual' +& $SafeCommands['Set-Alias'] 'Should-NotBe' 'Assert-NotEqual' & $SafeCommands['Set-Alias'] 'Should-NotBeNull' 'Assert-NotNull' & $SafeCommands['Set-Alias'] 'Should-NotBeSame' 'Assert-NotSame' -& $SafeCommands['Set-Alias'] 'Should-NotBeType' 'Assert-NotType' +& $SafeCommands['Set-Alias'] 'Should-NotHaveType' 'Assert-NotType' & $SafeCommands['Set-Alias'] 'Should-BeNull' 'Assert-Null' & $SafeCommands['Set-Alias'] 'Should-BeSame' 'Assert-Same' -& $SafeCommands['Set-Alias'] 'Should-BeType' 'Assert-Type' +& $SafeCommands['Set-Alias'] 'Should-HaveType' 'Assert-Type' & $SafeCommands['Set-Alias'] 'Should-BeString' 'Assert-StringEqual' & $SafeCommands['Set-Alias'] 'Should-NotBeString' 'Assert-StringNotEqual' @@ -150,13 +150,13 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session 'Should-BeGreaterThanOrEqual' 'Should-BeLessThan' 'Should-BeLessThanOrEqual' - 'Should-NotBeEqual' + 'Should-NotBe' 'Should-NotBeNull' 'Should-NotBeSame' - 'Should-NotBeType' + 'Should-NotHaveType' 'Should-BeNull' 'Should-BeSame' - 'Should-BeType' + 'Should-HaveType' # string 'Should-BeString' diff --git a/src/Pester.psd1 b/src/Pester.psd1 index e32453511..597ef48e1 100644 --- a/src/Pester.psd1 +++ b/src/Pester.psd1 @@ -138,13 +138,13 @@ 'Should-BeGreaterThanOrEqual' 'Should-BeLessThan' 'Should-BeLessThanOrEqual' - 'Should-NotBeEqual' + 'Should-NotBe' 'Should-NotBeNull' 'Should-NotBeSame' - 'Should-NotBeType' + 'Should-NotHaveType' 'Should-BeNull' 'Should-BeSame' - 'Should-BeType' + 'Should-HaveType' # string 'Should-BeString' diff --git a/src/functions/assert/Common/Collect-Input.ps1 b/src/functions/assert/Common/Collect-Input.ps1 index 8f7880e89..e1c4eca07 100644 --- a/src/functions/assert/Common/Collect-Input.ps1 +++ b/src/functions/assert/Common/Collect-Input.ps1 @@ -1,4 +1,23 @@ -function Collect-Input ($ParameterInput, $PipelineInput, $IsPipelineInput) { +function Collect-Input { + param ( + # This is input when called without pipeline syntax e.g. Should-Be -Actual 1 + # In that case -ParameterInput $Actual will be 1 + $ParameterInput, + # This is $local:input, which is the input that powershell collected from pipeline. + # It is always $null or object[] containing all the received items. + $PipelineInput, + # This tell us if we were called by | syntax or not. Caller needs to pass in $MyInvocation.ExpectingInput. + $IsPipelineInput + # This unwraps input provided by |. The effect of this is that we get single item input directly, + # and not wrapped in array. E.g. 1 | Should-Be -> 1, and not 1 | Should-Be -> @(1). + # + # Single item assertions should always provide this parameter. Collection assertions should never + # provide this parameter, because they should handle collections consistenly. + # + # This parameter does not apply to input provided by parameter sytax Should-Be -Actual 1 + # TODO: will apply this, but not yet. [switch] $UnrollInput + ) + if ($IsPipelineInput) { # We are called like this: 1 | Assert-Equal -Expected 1, we will get $local:Input in $PipelineInput and $true in $IsPipelineInput (coming from $MyInvocation.ExpectingInput). diff --git a/src/functions/assert/General/Should-BeSame.ps1 b/src/functions/assert/General/Should-BeSame.ps1 index c64cd6a27..4db2e2ff4 100644 --- a/src/functions/assert/General/Should-BeSame.ps1 +++ b/src/functions/assert/General/Should-BeSame.ps1 @@ -9,7 +9,7 @@ ) if ($Expected -is [ValueType] -or $Expected -is [string]) { - throw [ArgumentException]"Assert-Same compares objects by reference. You provided a value type or a string, those are not reference types and you most likely don't need to compare them by reference, see https://github.com/nohwnd/Assert/issues/6.`n`nAre you trying to compare two values to see if they are equal? Use Assert-Equal instead." + throw [ArgumentException]"Should-BeSame compares objects by reference. You provided a value type or a string, those are not reference types and you most likely don't need to compare them by reference, see https://github.com/nohwnd/Assert/issues/6.`n`nAre you trying to compare two values to see if they are equal? Use Should-BeEqual instead." } $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput diff --git a/src/functions/assert/General/Should-BeType.ps1 b/src/functions/assert/General/Should-HaveType.ps1 similarity index 100% rename from src/functions/assert/General/Should-BeType.ps1 rename to src/functions/assert/General/Should-HaveType.ps1 diff --git a/src/functions/assert/General/Should-NotBeType.ps1 b/src/functions/assert/General/Should-NotHaveType.ps1 similarity index 100% rename from src/functions/assert/General/Should-NotBeType.ps1 rename to src/functions/assert/General/Should-NotHaveType.ps1 diff --git a/src/functions/assert/String/Assert-Like.ps1 b/src/functions/assert/String/Should-BeLikeString.ps1 similarity index 100% rename from src/functions/assert/String/Assert-Like.ps1 rename to src/functions/assert/String/Should-BeLikeString.ps1 diff --git a/src/functions/assert/String/Assert-StringEqual.ps1 b/src/functions/assert/String/Should-BeString.ps1 similarity index 100% rename from src/functions/assert/String/Assert-StringEqual.ps1 rename to src/functions/assert/String/Should-BeString.ps1 diff --git a/src/functions/assert/String/Assert-NotLike.ps1 b/src/functions/assert/String/Should-NotBeLikeString.ps1 similarity index 100% rename from src/functions/assert/String/Assert-NotLike.ps1 rename to src/functions/assert/String/Should-NotBeLikeString.ps1 diff --git a/src/functions/assert/String/Assert-StringNotEqual.ps1 b/src/functions/assert/String/Should-NotBeString.ps1 similarity index 100% rename from src/functions/assert/String/Assert-StringNotEqual.ps1 rename to src/functions/assert/String/Should-NotBeString.ps1 diff --git a/tst/functions/assert/Equivalence/Assert-Equivalent.Options.Tests.ps1 b/tst/functions/assert/Equivalence/Should-BeEquivalent.Options.Tests.ps1 similarity index 65% rename from tst/functions/assert/Equivalence/Assert-Equivalent.Options.Tests.ps1 rename to tst/functions/assert/Equivalence/Should-BeEquivalent.Options.Tests.ps1 index cb4a7c521..2f0520180 100644 --- a/tst/functions/assert/Equivalence/Assert-Equivalent.Options.Tests.ps1 +++ b/tst/functions/assert/Equivalence/Should-BeEquivalent.Options.Tests.ps1 @@ -11,120 +11,120 @@ InPesterModuleScope { ) { param ($Path) - $expected = New-PSObject @{ - Name = "Jakub" - Age = 30 - } + $expected = New-PSObject @{ + Name = "Jakub" + Age = 30 + } - $actual = New-PSObject @{ - Name = "Jakub" - } + $actual = New-PSObject @{ + Name = "Jakub" + } $options = Get-EquivalencyOption -ExcludePath ("$Path.Age".Trim('.')) Compare-Equivalent -Actual $actual -Expected $expected -Path $Path -Options $options | Verify-Null } - It "Given a full path to a property it ignores it on the Actual object" -TestCases @( - @{ Path = $null } - @{ Path = "ParentProperty1" } - @{ Path = "ParentProperty1.ParentProperty2" } - ) { - param ($Path) - $expected = New-PSObject @{ - Name = "Jakub" - } + It "Given a full path to a property it ignores it on the Actual object" -TestCases @( + @{ Path = $null } + @{ Path = "ParentProperty1" } + @{ Path = "ParentProperty1.ParentProperty2" } + ) { + param ($Path) + $expected = New-PSObject @{ + Name = "Jakub" + } - $actual = New-PSObject @{ - Name = "Jakub" - Age = 30 - } + $actual = New-PSObject @{ + Name = "Jakub" + Age = 30 + } $options = Get-EquivalencyOption -ExcludePath ("$Path.Age".Trim('.')) Compare-Equivalent -Actual $actual -Expected $expected -Path $Path -Options $options | Verify-Null } - It "Given a full path to a property on object that is in collection it ignores it on the Expected object" { - $expected = New-PSObject @{ - ProgrammingLanguages = @( + It "Given a full path to a property on object that is in collection it ignores it on the Expected object" { + $expected = New-PSObject @{ + ProgrammingLanguages = @( (New-PSObject @{ - Name = "C#" - Type = "OO" - }), + Name = "C#" + Type = "OO" + }), (New-PSObject @{ - Name = "PowerShell" - }) - ) - } + Name = "PowerShell" + }) + ) + } - $actual = New-PSObject @{ - ProgrammingLanguages = @( + $actual = New-PSObject @{ + ProgrammingLanguages = @( (New-PSObject @{ - Name = "C#" - }), + Name = "C#" + }), (New-PSObject @{ - Name = "PowerShell" - }) - ) - } + Name = "PowerShell" + }) + ) + } $options = Get-EquivalencyOption -ExcludePath "ProgrammingLanguages.Type" Compare-Equivalent -Actual $actual -Expected $expected -Options $options | Verify-Null } - It "Given a full path to a property on object that is in collection it ignores it on the Actual object" { - $expected = New-PSObject @{ - ProgrammingLanguages = @( + It "Given a full path to a property on object that is in collection it ignores it on the Actual object" { + $expected = New-PSObject @{ + ProgrammingLanguages = @( (New-PSObject @{ - Name = "C#" - }), + Name = "C#" + }), (New-PSObject @{ - Name = "PowerShell" - }) - ) - } + Name = "PowerShell" + }) + ) + } - $actual = New-PSObject @{ - ProgrammingLanguages = @( + $actual = New-PSObject @{ + ProgrammingLanguages = @( (New-PSObject @{ - Name = "C#" - Type = "OO" - }), + Name = "C#" + Type = "OO" + }), (New-PSObject @{ - Name = "PowerShell" - }) - ) - } + Name = "PowerShell" + }) + ) + } $options = Get-EquivalencyOption -ExcludePath "ProgrammingLanguages.Type" Compare-Equivalent -Actual $actual -Expected $expected -Options $options | Verify-Null } - It "Given a full path to a property on object that is in hashtable it ignores it on the Expected object" { - $expected = New-PSObject @{ - ProgrammingLanguages = @{ - Language1 = (New-PSObject @{ - Name = "C#" - Type = "OO" - }); - Language2 = (New-PSObject @{ - Name = "PowerShell" - }) + It "Given a full path to a property on object that is in hashtable it ignores it on the Expected object" { + $expected = New-PSObject @{ + ProgrammingLanguages = @{ + Language1 = (New-PSObject @{ + Name = "C#" + Type = "OO" + }); + Language2 = (New-PSObject @{ + Name = "PowerShell" + }) + } } - } - $actual = New-PSObject @{ - ProgrammingLanguages = @{ - Language1 = (New-PSObject @{ - Name = "C#" - }); - Language2 = (New-PSObject @{ - Name = "PowerShell" - }) + $actual = New-PSObject @{ + ProgrammingLanguages = @{ + Language1 = (New-PSObject @{ + Name = "C#" + }); + Language2 = (New-PSObject @{ + Name = "PowerShell" + }) + } } - } $options = Get-EquivalencyOption -ExcludePath "ProgrammingLanguages.Language1.Type" Compare-Equivalent -Actual $actual -Expected $expected -Options $options | Verify-Null @@ -192,19 +192,19 @@ InPesterModuleScope { Compare-Equivalent -Actual $actual -Expected $expected -Options $options | Verify-Null } - It "Given options it passes them correctly from Assert-Equivalent" { - $expected = New-PSObject @{ - Name = "Jakub" - Location = "Prague" - Age = 30 - } + It "Given options it passes them correctly from Should-BeEquivalent" { + $expected = New-PSObject @{ + Name = "Jakub" + Location = "Prague" + Age = 30 + } - $actual = New-PSObject @{ - Name = "Jakub" - } + $actual = New-PSObject @{ + Name = "Jakub" + } $options = Get-EquivalencyOption -ExcludePath "Age", "NonExisting" - $err = { Assert-Equivalent -Actual $actual -Expected $expected -Options $options } | Verify-AssertionFailed + $err = { Should-BeEquivalent -Actual $actual -Expected $expected -Options $options } | Verify-AssertionFailed $err.Exception.Message | Verify-Like "*Expected has property 'Location'*" $err.Exception.Message | Verify-Like "*Exclude path 'Age'*" @@ -214,7 +214,7 @@ InPesterModuleScope { Context "Wildcard path exclusions" { It "Given wildcarded path it ignores it on the expected object" { $expected = [PSCustomObject] @{ - Name = "Jakub" + Name = "Jakub" Location = "Prague" } @@ -223,7 +223,7 @@ InPesterModuleScope { } $options = Get-EquivalencyOption -ExcludePath Loc* - Assert-Equivalent -Actual $actual -Expected $expected -Options $Options + Should-BeEquivalent -Actual $actual -Expected $expected -Options $Options } It "Given wildcarded path it ignores it on the actual object" { @@ -232,17 +232,17 @@ InPesterModuleScope { } $actual = [PSCustomObject] @{ - Name = "Jakub" + Name = "Jakub" Location = "Prague" } $options = Get-EquivalencyOption -ExcludePath Loc* - Assert-Equivalent -Actual $actual -Expected $expected -Options $Options + Should-BeEquivalent -Actual $actual -Expected $expected -Options $Options } It "Given wildcarded path it ignores it on the expected hashtable" { $expected = @{ - Name = "Jakub" + Name = "Jakub" Location = "Prague" } @@ -251,7 +251,7 @@ InPesterModuleScope { } $options = Get-EquivalencyOption -ExcludePath Loc* - Assert-Equivalent -Actual $actual -Expected $expected -Options $Options + Should-BeEquivalent -Actual $actual -Expected $expected -Options $Options } It "Given wildcarded path it ignores it on the actual hashtable" { @@ -260,17 +260,17 @@ InPesterModuleScope { } $actual = @{ - Name = "Jakub" + Name = "Jakub" Location = "Prague" } $options = Get-EquivalencyOption -ExcludePath Loc* - Assert-Equivalent -Actual $actual -Expected $expected -Options $Options + Should-BeEquivalent -Actual $actual -Expected $expected -Options $Options } It "Given wildcarded path it ignores it on the expected dictionary" { $expected = New-Dictionary @{ - Name = "Jakub" + Name = "Jakub" Location = "Prague" } @@ -279,7 +279,7 @@ InPesterModuleScope { } $options = Get-EquivalencyOption -ExcludePath Loc* - Assert-Equivalent -Actual $actual -Expected $expected -Options $Options + Should-BeEquivalent -Actual $actual -Expected $expected -Options $Options } It "Given wildcarded path it ignores it on the actual dictionary" { @@ -288,12 +288,12 @@ InPesterModuleScope { } $actual = New-Dictionary @{ - Name = "Jakub" + Name = "Jakub" Location = "Prague" } $options = Get-EquivalencyOption -ExcludePath Loc* - Assert-Equivalent -Actual $actual -Expected $expected -Options $Options + Should-BeEquivalent -Actual $actual -Expected $expected -Options $Options } } @@ -304,13 +304,13 @@ InPesterModuleScope { } $actual = [PSCustomObject] @{ - Name = "Jakub" + Name = "Jakub" Location = "Prague" - Age = 30 + Age = 30 } $options = Get-EquivalencyOption -ExcludePathsNotOnExpected - Assert-Equivalent -Actual $actual -Expected $expected -Options $Options + Should-BeEquivalent -Actual $actual -Expected $expected -Options $Options } It "Given actual hashtable that has more keys that expected it skips them" { @@ -319,13 +319,13 @@ InPesterModuleScope { } $actual = @{ - Name = "Jakub" + Name = "Jakub" Location = "Prague" - Age = 30 + Age = 30 } $options = Get-EquivalencyOption -ExcludePathsNotOnExpected - Assert-Equivalent -Actual $actual -Expected $expected -Options $Options + Should-BeEquivalent -Actual $actual -Expected $expected -Options $Options } It "Given actual dictionary that has more keys that expected it skips them" { @@ -334,13 +334,13 @@ InPesterModuleScope { } $actual = New-Dictionary @{ - Name = "Jakub" + Name = "Jakub" Location = "Prague" - Age = 30 + Age = 30 } $options = Get-EquivalencyOption -ExcludePathsNotOnExpected - Assert-Equivalent -Actual $actual -Expected $expected -Options $Options + Should-BeEquivalent -Actual $actual -Expected $expected -Options $Options } } } @@ -356,7 +356,7 @@ InPesterModuleScope { } $options = Get-EquivalencyOption -Comparator Equality - { Assert-Equivalent -Actual $actual -Expected $expected -Options $options } | Verify-AssertionFailed + { Should-BeEquivalent -Actual $actual -Expected $expected -Options $options } | Verify-AssertionFailed } } @@ -364,8 +364,8 @@ InPesterModuleScope { Describe "Printing Options into difference report" { It "Given options that exclude property it shows up in the difference report correctly" { - $options = Get-EquivalencyOption -ExcludePath "Age", "Name", "Person.Age", "Person.Created*" - Clear-WhiteSpace (Format-EquivalencyOptions -Options $options) | Verify-Equal (Clear-WhiteSpace " + $options = Get-EquivalencyOption -ExcludePath "Age", "Name", "Person.Age", "Person.Created*" + Clear-WhiteSpace (Format-EquivalencyOptions -Options $options) | Verify-Equal (Clear-WhiteSpace " Exclude path 'Age' Exclude path 'Name' Exclude path 'Person.Age' diff --git a/tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 b/tst/functions/assert/Equivalence/Should-BeEquivalent.Tests.ps1 similarity index 97% rename from tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 rename to tst/functions/assert/Equivalence/Should-BeEquivalent.Tests.ps1 index 60d69877a..ef65365d4 100644 --- a/tst/functions/assert/Equivalence/Assert-Equivalent.Tests.ps1 +++ b/tst/functions/assert/Equivalence/Should-BeEquivalent.Tests.ps1 @@ -439,7 +439,7 @@ InPesterModuleScope { $null = $Actual.Rows.Add(3, 'C', $null, $null) $null = $Actual.Rows.Add(1, 'A', 'AAA', 5) - Assert-Equivalent -Actual $Actual -Expected $Expected + Should-BeEquivalent -Actual $Actual -Expected $Expected function SerializeDeserialize ($InputObject) { # psv2 compatibility @@ -462,22 +462,22 @@ InPesterModuleScope { $ExpectedDeserialized = SerializeDeserialize $Expected $ActualDeserialized = SerializeDeserialize $Actual - Assert-Equivalent -Actual $ActualDeserialized -Expected $ExpectedDeserialized - Assert-Equivalent -Actual $Actual -Expected $ExpectedDeserialized + Should-BeEquivalent -Actual $ActualDeserialized -Expected $ExpectedDeserialized + Should-BeEquivalent -Actual $Actual -Expected $ExpectedDeserialized - { Assert-Equivalent -Actual $Actual -Expected $Expected -StrictOrder } | Should -Throw + { Should-BeEquivalent -Actual $Actual -Expected $Expected -StrictOrder } | Should -Throw $Actual.Rows[1].Name = 'D' - { Assert-Equivalent -Actual $Actual -Expected $Expected } | Should -Throw + { Should-BeEquivalent -Actual $Actual -Expected $Expected } | Should -Throw $ExpectedDeserialized = SerializeDeserialize $Expected $ActualDeserialized = SerializeDeserialize $Actual - { Assert-Equivalent -Actual $ActualDeserialized -Expected $ExpectedDeserialized } | Should -Throw - { Assert-Equivalent -Actual $Actual -Expected $ExpectedDeserialized } | Should -Throw + { Should-BeEquivalent -Actual $ActualDeserialized -Expected $ExpectedDeserialized } | Should -Throw + { Should-BeEquivalent -Actual $Actual -Expected $ExpectedDeserialized } | Should -Throw } It "Can be called with positional parameters" { - { Assert-Equivalent 1 2 } | Verify-AssertionFailed + { Should-BeEquivalent 1 2 } | Verify-AssertionFailed } } } diff --git a/tst/functions/assert/Exception/Assert-Throw.Tests.ps1 b/tst/functions/assert/Exception/Should-Throw.Tests.ps1 similarity index 76% rename from tst/functions/assert/Exception/Assert-Throw.Tests.ps1 rename to tst/functions/assert/Exception/Should-Throw.Tests.ps1 index 84a777f4a..ea8b192e6 100644 --- a/tst/functions/assert/Exception/Assert-Throw.Tests.ps1 +++ b/tst/functions/assert/Exception/Should-Throw.Tests.ps1 @@ -1,149 +1,149 @@ Set-StrictMode -Version Latest -Describe "Assert-Throw" { +Describe "Should-Throw" { It "Passes when exception is thrown" { - { throw } | Assert-Throw + { throw } | Should-Throw } It "Fails when no exception is thrown" { - { { } | Assert-Throw } | Verify-AssertionFailed + { { } | Should-Throw } | Verify-AssertionFailed } It "Passes when non-terminating exception is thrown" { - { Write-Error "fail!" } | Assert-Throw + { Write-Error "fail!" } | Should-Throw } It "Fails when non-terminating exception is thrown and -AllowNonTerminatingError switch is specified" { - { { Write-Error "fail!" } | Assert-Throw -AllowNonTerminatingError } | Verify-AssertionFailed + { { Write-Error "fail!" } | Should-Throw -AllowNonTerminatingError } | Verify-AssertionFailed } Context "Filtering with exception type" { It "Passes when exception has the expected type" { - { throw [ArgumentException]"A is null!" } | Assert-Throw -ExceptionType ([ArgumentException]) + { throw [ArgumentException]"A is null!" } | Should-Throw -ExceptionType ([ArgumentException]) } It "Passes when exception has type that inherits from the expected type" { - { throw [ArgumentNullException]"A is null!" } | Assert-Throw -ExceptionType ([ArgumentException]) + { throw [ArgumentNullException]"A is null!" } | Should-Throw -ExceptionType ([ArgumentException]) } It "Fails when exception is thrown, but is not the expected type nor iheriting form the expected type" { - { { throw [InvalidOperationException]"This operation is invalid!" } | Assert-Throw -ExceptionType ([ArgumentException]) } | Verify-AssertionFailed + { { throw [InvalidOperationException]"This operation is invalid!" } | Should-Throw -ExceptionType ([ArgumentException]) } | Verify-AssertionFailed } } Context "Filtering with exception message" { It "Passes when exception has the expected message" { - { throw [ArgumentException]"A is null!" } | Assert-Throw -ExceptionMessage 'A is null!' + { throw [ArgumentException]"A is null!" } | Should-Throw -ExceptionMessage 'A is null!' } It "Fails when exception does not have the expected message" { - { { throw [ArgumentException]"A is null!" } | Assert-Throw -ExceptionMessage 'flabbergasted' } | Verify-AssertionFailed + { { throw [ArgumentException]"A is null!" } | Should-Throw -ExceptionMessage 'flabbergasted' } | Verify-AssertionFailed } It "Passes when exception has message that matches based on wildcards" { - { throw [ArgumentNullException]"A is null!" } | Assert-Throw -ExceptionMessage '*null*' + { throw [ArgumentNullException]"A is null!" } | Should-Throw -ExceptionMessage '*null*' } It "Fails when exception does not match the message with wildcard" { - { { throw [ArgumentException]"A is null!" } | Assert-Throw -ExceptionMessage '*flabbergasted*' } | Verify-AssertionFailed + { { throw [ArgumentException]"A is null!" } | Should-Throw -ExceptionMessage '*flabbergasted*' } | Verify-AssertionFailed } } Context "Filtering with FullyQualifiedErrorId" { It "Passes when exception has the FullyQualifiedErrorId" { - { throw [ArgumentException]"A is null!" } | Assert-Throw -FullyQualifiedErrorId 'A is null!' + { throw [ArgumentException]"A is null!" } | Should-Throw -FullyQualifiedErrorId 'A is null!' } It "Fails when exception does not have the FullyQualifiedErrorId" { - { { throw [ArgumentException]"A is null!" } | Assert-Throw -FullyQualifiedErrorId 'flabbergasted' } | Verify-AssertionFailed + { { throw [ArgumentException]"A is null!" } | Should-Throw -FullyQualifiedErrorId 'flabbergasted' } | Verify-AssertionFailed } It "Passes when exception has FullyQualifiedErrorId that matches based on wildcards" { - { throw [ArgumentNullException]"A is null!" } | Assert-Throw -FullyQualifiedErrorId '*null*' + { throw [ArgumentNullException]"A is null!" } | Should-Throw -FullyQualifiedErrorId '*null*' } It "Fails when exception does not match the FullyQualifiedErrorId with wildcard" { - { { throw [ArgumentException]"A is null!" } | Assert-Throw -FullyQualifiedErrorId '*flabbergasted*' } | Verify-AssertionFailed + { { throw [ArgumentException]"A is null!" } | Should-Throw -FullyQualifiedErrorId '*flabbergasted*' } | Verify-AssertionFailed } } Context "Verify messages" { It "Given no exception it returns the correct message" { - $err = { { } | Assert-Throw } | Verify-AssertionFailed + $err = { { } | Should-Throw } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal 'Expected an exception, to be thrown, but no exception was thrown.' } It "Given exception that does not match on type it returns the correct message" { - $err = { { throw [ArgumentException]"" } | Assert-Throw -ExceptionType ([System.InvalidOperationException]) } | Verify-AssertionFailed + $err = { { throw [ArgumentException]"" } | Should-Throw -ExceptionType ([System.InvalidOperationException]) } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal "Expected an exception, of type [InvalidOperationException] to be thrown, but the exception type was [ArgumentException]." } It "Given exception that does not match on message it returns the correct message" { - $err = { { throw [ArgumentException]"fail!" } | Assert-Throw -ExceptionMessage 'halt!' } | Verify-AssertionFailed + $err = { { throw [ArgumentException]"fail!" } | Should-Throw -ExceptionMessage 'halt!' } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal "Expected an exception, with message 'halt!' to be thrown, but the message was 'fail!'." } It "Given exception that does not match on FullyQualifiedErrorId it returns the correct message" { - $err = { { throw [ArgumentException]"SomeId" } | Assert-Throw -FullyQualifiedErrorId 'DifferentId' } | Verify-AssertionFailed + $err = { { throw [ArgumentException]"SomeId" } | Should-Throw -FullyQualifiedErrorId 'DifferentId' } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal "Expected an exception, with FullyQualifiedErrorId 'DifferentId' to be thrown, but the FullyQualifiedErrorId was 'SomeId'." } It "Given exception that does not match on type and message it returns the correct message" { - $err = { { throw [ArgumentException]"fail!" } | Assert-Throw -ExceptionType ([System.InvalidOperationException]) -ExceptionMessage 'halt!' } | Verify-AssertionFailed + $err = { { throw [ArgumentException]"fail!" } | Should-Throw -ExceptionType ([System.InvalidOperationException]) -ExceptionMessage 'halt!' } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal "Expected an exception, of type [InvalidOperationException], with message 'halt!' to be thrown, but the exception type was [ArgumentException] and the message was 'fail!'." } It "Given exception that does not match on type and FullyQualifiedErrorId it returns the correct message" { - $err = { { throw [ArgumentException]"SomeId!" } | Assert-Throw -ExceptionType ([System.InvalidOperationException]) -FullyQualifiedErrorId 'DifferentId!' } | Verify-AssertionFailed + $err = { { throw [ArgumentException]"SomeId!" } | Should-Throw -ExceptionType ([System.InvalidOperationException]) -FullyQualifiedErrorId 'DifferentId!' } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal "Expected an exception, of type [InvalidOperationException], with FullyQualifiedErrorId 'DifferentId!' to be thrown, but the exception type was [ArgumentException] and the FullyQualifiedErrorId was 'SomeId!'." } It "Given exception that does not match on message and FullyQualifiedErrorId it returns the correct message" { - $err = { { throw [ArgumentException]"halt!" } | Assert-Throw -ExceptionMessage 'fail!' -FullyQualifiedErrorId 'fail!' } | Verify-AssertionFailed + $err = { { throw [ArgumentException]"halt!" } | Should-Throw -ExceptionMessage 'fail!' -FullyQualifiedErrorId 'fail!' } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal "Expected an exception, with message 'fail!', with FullyQualifiedErrorId 'fail!' to be thrown, but the message was 'halt!' and the FullyQualifiedErrorId was 'halt!'." } It "Given exception that does not match on type, message and FullyQualifiedErrorId it returns the correct message" { - $err = { { throw [ArgumentException]"halt!" } | Assert-Throw -ExceptionType ([System.InvalidOperationException]) -ExceptionMessage 'fail!' -FullyQualifiedErrorId 'fail!' } | Verify-AssertionFailed + $err = { { throw [ArgumentException]"halt!" } | Should-Throw -ExceptionType ([System.InvalidOperationException]) -ExceptionMessage 'fail!' -FullyQualifiedErrorId 'fail!' } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal "Expected an exception, of type [InvalidOperationException], with message 'fail!' and with FullyQualifiedErrorId 'fail!' to be thrown, but the exception type was [ArgumentException], the message was 'halt!' and the FullyQualifiedErrorId was 'halt!'." } } Context "Unwrapping exception from different sources" { It 'Exception is thrown by throw keyword' { - { throw "fail!" } | Assert-Throw + { throw "fail!" } | Should-Throw } It 'Exception is thrown by static .net method' { - { [io.directory]::delete("non-existing") } | Assert-Throw + { [io.directory]::delete("non-existing") } | Should-Throw } It 'Exception is thrown by failed constructor' { - { New-Object DateTime "incorrect parameter" } | Assert-Throw + { New-Object DateTime "incorrect parameter" } | Should-Throw } # division by zero circumvents try catch in pwsh v2 # so we divide by $null to trigger the same exception It 'Exception is thrown by division by zero' { - { 1 / $null } | Assert-Throw + { 1 / $null } | Should-Throw } It 'Terminating error is thrown by cmdlet failing to bind paramaters' { - { Get-Item "non-existing" } | Assert-Throw + { Get-Item "non-existing" } | Should-Throw } It 'Terminating error is thrown by cmdlet with -ErrorAction Stop' { - { Get-Item "non-existing" -ErrorAction 'stop' } | Assert-Throw + { Get-Item "non-existing" -ErrorAction 'stop' } | Should-Throw } It 'Non-terminating error is thrown by cmdlet and converted to terminating error by the assertion' { - { Get-Item "non-existing" } | Assert-Throw + { Get-Item "non-existing" } | Should-Throw } } It "Given scriptblock that throws it returns ErrorRecord to the output" { - $err = { throw [InvalidOperationException]"error" } | Assert-Throw + $err = { throw [InvalidOperationException]"error" } | Should-Throw $err | Verify-Type ([Management.Automation.ErrorRecord]) $err.Exception | Verify-Type ([System.InvalidOperationException]) $err.Exception.Message | Verify-Equal "error" diff --git a/tst/functions/assert/General/Assert-Equal.Tests.ps1 b/tst/functions/assert/General/Assert-Equal.Tests.ps1 deleted file mode 100644 index 76a09ff65..000000000 --- a/tst/functions/assert/General/Assert-Equal.Tests.ps1 +++ /dev/null @@ -1,92 +0,0 @@ -Set-StrictMode -Version Latest - -InPesterModuleScope { - Describe "Assert-Equal" { - Context "Comparing strings" { - It "Passes when two strings are equal" { - "abc" | Assert-Equal "abc" - } - - It "Fails when two strings are different" { - { "abc" | Assert-Equal "bde" } | Verify-AssertionFailed - } - } - - Context "Comparing integers" { - It "Passes when two numbers are equal" { - 1 | Assert-Equal 1 - } - - It "Fails when two numbers are different" { - { 1 | Assert-Equal 9 } | Verify-AssertionFailed - } - } - - Context "Comparing doubles" { - It "Passes when two numbers are equal" { - .1 | Assert-Equal .1 - } - - It "Fails when two numbers are different" { - { .1 | Assert-Equal .9 } | Verify-AssertionFailed - } - } - - Context "Comparing decimals" { - It "Passes when two numbers are equal" { - .1D | Assert-Equal .1D - } - - It "Fails when two numbers are different" { - { .1D | Assert-Equal .9D } | Verify-AssertionFailed - } - } - - Context "Comparing objects" { - It "Passes when two objects are the same" { - $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } - $object | Assert-Equal $object - } - - It "Fails when two objects are different" { - $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } - $object1 = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } - { $object | Assert-Equal $object1 } | Verify-AssertionFailed - } - } - - It "Fails for array input even if the last item is the same as expected" { - { 1, 2, 3 | Assert-Equal 3 } | Verify-AssertionFailed - } - - It "Fails with custom message" { - $err = { 9 | Assert-Equal 3 -CustomMessage " is not " } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "3 is not 9" - } - - Context "Validate messages" { - It "Given two values that are not the same '' and '' it returns expected message ''" -TestCases @( - @{ Expected = "a" ; Actual = 10 ; Message = "Expected [string] 'a', but got [int] 10." }, - @{ Expected = "a" ; Actual = 10.1 ; Message = "Expected [string] 'a', but got [double] 10.1." }, - @{ Expected = "a" ; Actual = 10.1D ; Message = "Expected [string] 'a', but got [decimal] 10.1." } - ) { - $err = { Assert-Equal -Actual $Actual -Expected $Expected } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal $Message - } - } - - It "Returns the value on output" { - $expected = 1 - $expected | Assert-Equal 1 | Verify-Equal $expected - } - - It "Can be called with positional parameters" { - { Assert-Equal 1 2 } | Verify-AssertionFailed - } - - It "Given collection to Expected it throws" { - $err = { "dummy" | Assert-Equal @() } | Verify-Throw - $err.Exception | Verify-Type ([ArgumentException]) - } - } -} diff --git a/tst/functions/assert/General/Assert-GreaterThan.Tests.ps1 b/tst/functions/assert/General/Assert-GreaterThan.Tests.ps1 deleted file mode 100644 index 5d1f0b9bb..000000000 --- a/tst/functions/assert/General/Assert-GreaterThan.Tests.ps1 +++ /dev/null @@ -1,110 +0,0 @@ -Set-StrictMode -Version Latest - -InPesterModuleScope { - Describe "Assert-GreaterThan" { - Context "Comparing strings" { - It "Passes when actual is greater than expected" { - "z" | Assert-GreaterThan "a" - } - - It "Fails when actual is equal to expected" { - { "a" | Assert-GreaterThan "a" } | Verify-AssertionFailed - } - - It "Fails when actual is lower than expected" { - { "a" | Assert-GreaterThan "z" } | Verify-AssertionFailed - } - } - - Context "Comparing integers" { - It "Passes when expected is greater than actual" { - 2 | Assert-GreaterThan 1 - } - - It "Fails when actual is equal to expected" { - { 1 | Assert-GreaterThan 1 } | Verify-AssertionFailed - } - - It "Fails when actual is lower than expected" { - { 1 | Assert-GreaterThan 9 } | Verify-AssertionFailed - } - } - - Context "Comparing doubles" { - It "Passes when expected is greater than actual" { - .2 | Assert-GreaterThan .1 - } - - It "Fails when actual is equal to expected" { - { .1 | Assert-GreaterThan .1 } | Verify-AssertionFailed - } - - It "Fails when actual is lower than expected" { - { .1 | Assert-GreaterThan .9 } | Verify-AssertionFailed - } - } - - Context "Comparing decimals" { - It "Passes when expected is greater than actual" { - 2D | Assert-GreaterThan 1D - } - - It "Fails when actual is equal to expected" { - { 1D | Assert-GreaterThan 1D } | Verify-AssertionFailed - } - - It "Fails when actual is lower than expected" { - { 1D | Assert-GreaterThan 9D } | Verify-AssertionFailed - } - } - - Context "Comparing objects" { - It "Fails when two objects are the same" { - $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } - { $object | Assert-GreaterThan $object } | Verify-AssertionFailed - } - - It "Fails when two objects are not comparable" { - $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } - $object1 = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } - $err = { $object | Assert-GreaterThan $object1 } | Verify-Throw - $err.Exception | Verify-Type ([System.Management.Automation.ExtendedTypeSystemException]) - } - } - - It "Fails for array input even if the last item is greater than then expected value" { - $err = { 1, 2, 3, 4 | Assert-GreaterThan 3 } | Verify-Throw - $err.Exception | Verify-Type ([System.Management.Automation.RuntimeException]) - } - - It "Fails with custom message" { - $err = { 2 | Assert-GreaterThan 3 -CustomMessage " is not greater than " } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "2 is not greater than 3" - } - - Context "Validate messages" { - It "Given two values '' and '' it returns expected message ''" -TestCases @( - @{ Expected = "z" ; Actual = "a" ; Message = "Expected [string] 'a' to be greater than [string] 'z', but it was not." }, - @{ Expected = 10.1 ; Actual = 1.1 ; Message = "Expected [double] 1.1 to be greater than [double] 10.1, but it was not." }, - @{ Expected = 10.1D ; Actual = 1.1D ; Message = "Expected [decimal] 1.1 to be greater than [decimal] 10.1, but it was not." } - ) { - $err = { Assert-GreaterThan -Actual $Actual -Expected $Expected } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal $Message - } - } - - It "Returns the value on output" { - $expected = 1 - $expected | Assert-GreaterThan 0 | Verify-Equal $expected - } - - It "Can be called with positional parameters" { - { Assert-GreaterThan 2 1 } | Verify-AssertionFailed - } - - It "Given collection to Expected it throws" { - $err = { "dummy" | Assert-GreaterThan @() } | Verify-Throw - $err.Exception | Verify-Type ([ArgumentException]) - } - } -} diff --git a/tst/functions/assert/General/Assert-GreaterThanOrEqual.Tests.ps1 b/tst/functions/assert/General/Assert-GreaterThanOrEqual.Tests.ps1 deleted file mode 100644 index 293d378c8..000000000 --- a/tst/functions/assert/General/Assert-GreaterThanOrEqual.Tests.ps1 +++ /dev/null @@ -1,110 +0,0 @@ -Set-StrictMode -Version Latest - -InPesterModuleScope { - Describe "Assert-GreaterThanOrEqual" { - Context "Comparing strings" { - It "Passes when actual is greater than expected" { - "z" | Assert-GreaterThanOrEqual "a" - } - - It "Passes when actual is equal to expected" { - "a" | Assert-GreaterThanOrEqual "a" - } - - It "Fails when actual is lower than expected" { - { "a" | Assert-GreaterThanOrEqual "z" } | Verify-AssertionFailed - } - } - - Context "Comparing integers" { - It "Passes when expected is greater than actual" { - 2 | Assert-GreaterThanOrEqual 1 - } - - It "Passes when actual is equal to expected" { - 1 | Assert-GreaterThanOrEqual 1 - } - - It "Fails when actual is lower than expected" { - { 1 | Assert-GreaterThanOrEqual 9 } | Verify-AssertionFailed - } - } - - Context "Comparing doubles" { - It "Passes when expected is greater than actual" { - .2 | Assert-GreaterThanOrEqual .1 - } - - It "Passes when actual is equal to expected" { - .1 | Assert-GreaterThanOrEqual .1 - } - - It "Fails when actual is lower than expected" { - { .1 | Assert-GreaterThanOrEqual .9 } | Verify-AssertionFailed - } - } - - Context "Comparing decimals" { - It "Passes when expected is greater than actual" { - 2D | Assert-GreaterThanOrEqual 1D - } - - It "Passes when actual is equal to expected" { - 1D | Assert-GreaterThanOrEqual 1D - } - - It "Fails when actual is lower than expected" { - { 1D | Assert-GreaterThanOrEqual 9D } | Verify-AssertionFailed - } - } - - Context "Comparing objects" { - It "Passes when two objects are the same" { - $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } - $object | Assert-GreaterThanOrEqual $object - } - - It "Fails when two objects are not comparable" { - $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } - $object1 = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } - $err = { $object | Assert-GreaterThanOrEqual $object1 } | Verify-Throw - $err.Exception | Verify-Type ([System.Management.Automation.ExtendedTypeSystemException]) - } - } - - It "Fails for array input even if the last item is greater than then expected value" { - $err = { 1, 2, 3, 4 | Assert-GreaterThanOrEqual 3 } | Verify-Throw - $err.Exception | Verify-Type ([System.Management.Automation.RuntimeException]) - } - - It "Fails with custom message" { - $err = { 2 | Assert-GreaterThanOrEqual 3 -CustomMessage " is not greater than " } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "2 is not greater than 3" - } - - Context "Validate messages" { - It "Given two values '' and '' it returns expected message ''" -TestCases @( - @{ Expected = "z" ; Actual = "a" ; Message = "Expected [string] 'a' to be greater than or equal to [string] 'z', but it was not." }, - @{ Expected = 10.1 ; Actual = 1.1 ; Message = "Expected [double] 1.1 to be greater than or equal to [double] 10.1, but it was not." }, - @{ Expected = 10.1D ; Actual = 1.1D ; Message = "Expected [decimal] 1.1 to be greater than or equal to [decimal] 10.1, but it was not." } - ) { - $err = { Assert-GreaterThanOrEqual -Actual $Actual -Expected $Expected } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal $Message - } - } - - It "Returns the value on output" { - $expected = 1 - $expected | Assert-GreaterThanOrEqual 0 | Verify-Equal $expected - } - - It "Can be called with positional parameters" { - { Assert-GreaterThanOrEqual 2 1 } | Verify-AssertionFailed - } - - It "Given collection to Expected it throws" { - $err = { "dummy" | Assert-GreaterThanOrEqual @() } | Verify-Throw - $err.Exception | Verify-Type ([ArgumentException]) - } - } -} diff --git a/tst/functions/assert/General/Assert-NotEqual.Tests.ps1 b/tst/functions/assert/General/Assert-NotEqual.Tests.ps1 deleted file mode 100644 index c5d443ec8..000000000 --- a/tst/functions/assert/General/Assert-NotEqual.Tests.ps1 +++ /dev/null @@ -1,91 +0,0 @@ -Set-StrictMode -Version Latest - -InPesterModuleScope { - Describe "Assert-NotEqual" { - Context "Comparing strings" { - It "Fails when two strings are equal" { - { "abc" | Assert-NotEqual "abc" } | Verify-AssertionFailed - } - - It "Passes when two strings are different" { - "abc" | Assert-NotEqual "bde" - } - } - - Context "Comparing integers" { - It "Fails when two numbers are equal" { - { 1 | Assert-NotEqual 1 } | Verify-AssertionFailed - } - - It "Passes when two numbers are different" { - 1 | Assert-NotEqual 9 - } - } - - Context "Comparing doubles" { - It "Fails when two numbers are equal" { - { .1 | Assert-NotEqual .1 } | Verify-AssertionFailed - } - - It "Passes when two numbers are different" { - .1 | Assert-NotEqual .9 - } - } - - Context "Comparing decimals" { - It "Fails when two numbers are equal" { - { .1D | Assert-NotEqual .1D } | Verify-AssertionFailed - } - - It "Passes when two numbers are different" { - .1D | Assert-NotEqual .9D - } - } - - Context "Comparing objects" { - It "Fails when two objects are the same" { - $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } - { $object | Assert-NotEqual $object } | Verify-AssertionFailed - } - - It "Passes when two objects are different" { - $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } - $object1 = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } - $object | Assert-NotEqual $object1 - } - } - - It "Passes for array input even if the last item is the same as expected" { - 1, 2, 3 | Assert-NotEqual 3 - } - - It "Fails with custom message" { - $err = { 3 | Assert-NotEqual 3 -CustomMessage " is " } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "3 is 3" - } - - Context "Validate messages" { - It "Given two values that are the same '' it returns expected message ''" -TestCases @( - @{ Value = 1; Message = "Expected [int] 1, to be different than the actual value, but they were the same." } - ) { - param($Value, $Message) - $err = { Assert-NotEqual -Actual $Value -Expected $Value } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal $Message - } - } - - It "Returns the value on output" { - $expected = 1 - $expected | Assert-NotEqual 9 | Verify-Equal $expected - } - - It "Can be called with positional parameters" { - { Assert-NotEqual 1 1 } | Verify-AssertionFailed - } - - It "Given collection to Expected it throws" { - $err = { "dummy" | Assert-NotEqual @() } | Verify-Throw - $err.Exception | Verify-Type ([ArgumentException]) - } - } -} diff --git a/tst/functions/assert/General/Assert-NotSame.Tests.ps1 b/tst/functions/assert/General/Assert-NotSame.Tests.ps1 deleted file mode 100644 index 01b6c3924..000000000 --- a/tst/functions/assert/General/Assert-NotSame.Tests.ps1 +++ /dev/null @@ -1,47 +0,0 @@ -Set-StrictMode -Version Latest - -InPesterModuleScope { - Describe "Assert-NotSame" { - It "Fails when two objects are the same instance" { - $object = New-Object Diagnostics.Process - { $object | Assert-NotSame $object } | Verify-AssertionFailed - } - - It "Passes when two objects are different instance" { - $object = New-Object Diagnostics.Process - $object1 = New-Object Diagnostics.Process - $object | Assert-NotSame $object1 - } - - It "Passes for array input even if the last item is the same as expected" { - $object = New-Object Diagnostics.Process - 1, 2, $object | Assert-NotSame $object - } - - It "Fails with custom message" { - $object = 1 - $err = { $object | Assert-NotSame $object -CustomMessage " is " } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "1 is 1" - } - - It "Given two values that are the same instance it returns expected message ''" -TestCases @( - @{ Value = "a"; Message = "Expected [string] ''a'', to not be the same instance." } - ) { - param($Value, $Message) - $err = { Assert-NotSame -Actual $Value -Expected $Value } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal $Message - } - - It "Returns the value on output" { - $expected = 1 - $expected | Assert-NotSame 7 | Verify-Equal $expected - } - - It "Can be called with positional parameters" { - { - $obj = New-Object -TypeName PSObject - Assert-NotSame $obj $obj - } | Verify-AssertionFailed - } - } -} diff --git a/tst/functions/assert/General/Assert-NotType.Tests.ps1 b/tst/functions/assert/General/Assert-NotType.Tests.ps1 deleted file mode 100644 index 2a0409c66..000000000 --- a/tst/functions/assert/General/Assert-NotType.Tests.ps1 +++ /dev/null @@ -1,21 +0,0 @@ -Set-StrictMode -Version Latest - -InPesterModuleScope { - Describe "Assert-NotType" { - It "Given value of expected type it fails" { - { 1 | Assert-NotType ([int]) } | Verify-AssertionFailed - } - - It "Given an object of different type it passes" { - 1 | Assert-NotType ([string]) - } - - It "Returns the given value" { - 'b' | Assert-NotType ([int]) | Verify-Equal 'b' - } - - It "Can be called with positional parameters" { - { Assert-NotType ([int]) 1 } | Verify-AssertionFailed - } - } -} diff --git a/tst/functions/assert/General/Assert-Null.Tests.ps1 b/tst/functions/assert/General/Assert-Null.Tests.ps1 deleted file mode 100644 index 7343aeb2a..000000000 --- a/tst/functions/assert/General/Assert-Null.Tests.ps1 +++ /dev/null @@ -1,29 +0,0 @@ -Set-StrictMode -Version Latest - -InPesterModuleScope { - Describe "Assert-Null" { - It "Given `$null it passes" { - $null | Assert-Null - } - - It "Given an objects it fails" { - { 1 | Assert-Null } | Verify-AssertionFailed - } - - It "Given empty array it fails" { - { @() | Assert-Null } | Verify-AssertionFailed - } - - It "Returns the given value" { - $null | Assert-Null | Verify-Null - } - - It "Can be called with positional parameters (1)" { - { Assert-Null 1 } | Verify-AssertionFailed - } - - It "Can be called with positional parameters (@())" { - { Assert-Null @() } | Verify-AssertionFailed - } - } -} diff --git a/tst/functions/assert/General/Assert-Same.Tests.ps1 b/tst/functions/assert/General/Assert-Same.Tests.ps1 deleted file mode 100644 index 32a7efc20..000000000 --- a/tst/functions/assert/General/Assert-Same.Tests.ps1 +++ /dev/null @@ -1,61 +0,0 @@ -Set-StrictMode -Version Latest - -InPesterModuleScope { - Describe "Assert-Same" { - It "Passes when two objects are the same instance" { - $object = New-Object Diagnostics.Process - $object | Assert-Same $object - } - - It "Fails when two objects are different instance" { - $object = New-Object Diagnostics.Process - $object1 = New-Object Diagnostics.Process - { $object | Assert-Same $object1 } | Verify-AssertionFailed - } - - It "Fails for array input even if the last item is the same as expected" { - $object = New-Object Diagnostics.Process - { 1, 2, $object | Assert-Same $object } | Verify-AssertionFailed - } - - It "Fails with custom message" { - $object = New-Object Diagnostics.Process - $err = { "text" | Assert-Same $object -CustomMessage "'' is not ''" } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "'Diagnostics.Process{Id=`$null; Name=`$null}' is not ''text''" - } - - It "Given two values that are not the same instance '' and '' it returns expected message ''" -TestCases @( - @{ Expected = New-Object -TypeName PSObject ; Actual = New-Object -TypeName PSObject ; Message = "Expected [PSObject] 'PSObject{}', to be the same instance but it was not." } - ) { - param($Expected, $Actual, $Message) - $err = { Assert-Same -Actual $Actual -Expected $Expected } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal $Message - } - - It "Returns the value on output" { - $expected = New-Object Diagnostics.Process - $expected | Assert-Same $expected | Verify-Equal $expected - } - - Context "Throws when `$expected is a value type or string to warn user about unexpected behavior" { - It "throws for value " -TestCases @( - @{ Value = 1 } - @{ Value = 1.0D } - @{ Value = 1.0 } - @{ Value = 'c' } - @{ Value = "abc" } - ) { - param($Value) - - $err = { "dummy" | Assert-Same -Expected $Value } | Verify-Throw - $err.Exception | Verify-Type ([ArgumentException]) - $err.Exception.Message | Verify-Equal "Assert-Same compares objects by reference. You provided a value type or a string, those are not reference types and you most likely don't need to compare them by reference, see https://github.com/nohwnd/Assert/issues/6.`n`nAre you trying to compare two values to see if they are equal? Use Assert-Equal instead." - } - } - - It "Can be called with positional parameters" { - $object = New-Object Diagnostics.Process - { Assert-Same $object "abc" } | Verify-AssertionFailed - } - } -} diff --git a/tst/functions/assert/General/Assert-Type.Tests.ps1 b/tst/functions/assert/General/Assert-Type.Tests.ps1 deleted file mode 100644 index 7748c2439..000000000 --- a/tst/functions/assert/General/Assert-Type.Tests.ps1 +++ /dev/null @@ -1,21 +0,0 @@ -Set-StrictMode -Version Latest - -InPesterModuleScope { - Describe "Assert-Type" { - It "Given value of expected type it passes" { - 1| Assert-Type ([int]) - } - - It "Given an object of different type it fails" { - { 1 | Assert-Type ([string]) } | Verify-AssertionFailed - } - - It "Returns the given value" { - 'b' | Assert-Type ([string]) | Verify-Equal 'b' - } - - It "Can be called with positional parameters" { - { Assert-Type ([string]) 1 } | Verify-AssertionFailed - } - } -} diff --git a/tst/functions/assert/General/Should-Be.Tests.ps1 b/tst/functions/assert/General/Should-Be.Tests.ps1 new file mode 100644 index 000000000..cd00ba2a3 --- /dev/null +++ b/tst/functions/assert/General/Should-Be.Tests.ps1 @@ -0,0 +1,90 @@ +Set-StrictMode -Version Latest + +Describe "Should-Be" { + Context "Comparing strings" { + It "Passes when two strings are equal" { + "abc" | Should-Be "abc" + } + + It "Fails when two strings are different" { + { "abc" | Should-Be "bde" } | Verify-AssertionFailed + } + } + + Context "Comparing integers" { + It "Passes when two numbers are equal" { + 1 | Should-Be 1 + } + + It "Fails when two numbers are different" { + { 1 | Should-Be 9 } | Verify-AssertionFailed + } + } + + Context "Comparing doubles" { + It "Passes when two numbers are equal" { + .1 | Should-Be .1 + } + + It "Fails when two numbers are different" { + { .1 | Should-Be .9 } | Verify-AssertionFailed + } + } + + Context "Comparing decimals" { + It "Passes when two numbers are equal" { + .1D | Should-Be .1D + } + + It "Fails when two numbers are different" { + { .1D | Should-Be .9D } | Verify-AssertionFailed + } + } + + Context "Comparing objects" { + It "Passes when two objects are the same" { + $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + $object | Should-Be $object + } + + It "Fails when two objects are different" { + $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + $object1 = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + { $object | Should-Be $object1 } | Verify-AssertionFailed + } + } + + It "Fails for array input even if the last item is the same as expected" { + { 1, 2, 3 | Should-Be 3 } | Verify-AssertionFailed + } + + It "Fails with custom message" { + $err = { 9 | Should-Be 3 -CustomMessage " is not " } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "3 is not 9" + } + + Context "Validate messages" { + It "Given two values that are not the same '' and '' it returns expected message ''" -TestCases @( + @{ Expected = "a" ; Actual = 10 ; Message = "Expected [string] 'a', but got [int] 10." }, + @{ Expected = "a" ; Actual = 10.1 ; Message = "Expected [string] 'a', but got [double] 10.1." }, + @{ Expected = "a" ; Actual = 10.1D ; Message = "Expected [string] 'a', but got [decimal] 10.1." } + ) { + $err = { Should-Be -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $Message + } + } + + It "Returns the value on output" { + $expected = 1 + $expected | Should-Be 1 | Verify-Equal $expected + } + + It "Can be called with positional parameters" { + { Should-Be 1 2 } | Verify-AssertionFailed + } + + It "Given collection to Expected it throws" { + $err = { "dummy" | Should-Be @() } | Verify-Throw + $err.Exception | Verify-Type ([ArgumentException]) + } +} diff --git a/tst/functions/assert/General/Should-BeGreaterThan.Tests.ps1 b/tst/functions/assert/General/Should-BeGreaterThan.Tests.ps1 new file mode 100644 index 000000000..18b8024eb --- /dev/null +++ b/tst/functions/assert/General/Should-BeGreaterThan.Tests.ps1 @@ -0,0 +1,108 @@ +Set-StrictMode -Version Latest + +Describe "Should-BeGreaterThan" { + Context "Comparing strings" { + It "Passes when actual is greater than expected" { + "z" | Should-BeGreaterThan "a" + } + + It "Fails when actual is equal to expected" { + { "a" | Should-BeGreaterThan "a" } | Verify-AssertionFailed + } + + It "Fails when actual is lower than expected" { + { "a" | Should-BeGreaterThan "z" } | Verify-AssertionFailed + } + } + + Context "Comparing integers" { + It "Passes when expected is greater than actual" { + 2 | Should-BeGreaterThan 1 + } + + It "Fails when actual is equal to expected" { + { 1 | Should-BeGreaterThan 1 } | Verify-AssertionFailed + } + + It "Fails when actual is lower than expected" { + { 1 | Should-BeGreaterThan 9 } | Verify-AssertionFailed + } + } + + Context "Comparing doubles" { + It "Passes when expected is greater than actual" { + .2 | Should-BeGreaterThan .1 + } + + It "Fails when actual is equal to expected" { + { .1 | Should-BeGreaterThan .1 } | Verify-AssertionFailed + } + + It "Fails when actual is lower than expected" { + { .1 | Should-BeGreaterThan .9 } | Verify-AssertionFailed + } + } + + Context "Comparing decimals" { + It "Passes when expected is greater than actual" { + 2D | Should-BeGreaterThan 1D + } + + It "Fails when actual is equal to expected" { + { 1D | Should-BeGreaterThan 1D } | Verify-AssertionFailed + } + + It "Fails when actual is lower than expected" { + { 1D | Should-BeGreaterThan 9D } | Verify-AssertionFailed + } + } + + Context "Comparing objects" { + It "Fails when two objects are the same" { + $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + { $object | Should-BeGreaterThan $object } | Verify-AssertionFailed + } + + It "Fails when two objects are not comparable" { + $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + $object1 = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + $err = { $object | Should-BeGreaterThan $object1 } | Verify-Throw + $err.Exception | Verify-Type ([System.Management.Automation.ExtendedTypeSystemException]) + } + } + + It "Fails for array input even if the last item is greater than then expected value" { + $err = { 1, 2, 3, 4 | Should-BeGreaterThan 3 } | Verify-Throw + $err.Exception | Verify-Type ([System.Management.Automation.RuntimeException]) + } + + It "Fails with custom message" { + $err = { 2 | Should-BeGreaterThan 3 -CustomMessage " is not greater than " } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "2 is not greater than 3" + } + + Context "Validate messages" { + It "Given two values '' and '' it returns expected message ''" -TestCases @( + @{ Expected = "z" ; Actual = "a" ; Message = "Expected [string] 'a' to be greater than [string] 'z', but it was not." }, + @{ Expected = 10.1 ; Actual = 1.1 ; Message = "Expected [double] 1.1 to be greater than [double] 10.1, but it was not." }, + @{ Expected = 10.1D ; Actual = 1.1D ; Message = "Expected [decimal] 1.1 to be greater than [decimal] 10.1, but it was not." } + ) { + $err = { Should-BeGreaterThan -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $Message + } + } + + It "Returns the value on output" { + $expected = 1 + $expected | Should-BeGreaterThan 0 | Verify-Equal $expected + } + + It "Can be called with positional parameters" { + { Should-BeGreaterThan 2 1 } | Verify-AssertionFailed + } + + It "Given collection to Expected it throws" { + $err = { "dummy" | Should-BeGreaterThan @() } | Verify-Throw + $err.Exception | Verify-Type ([ArgumentException]) + } +} diff --git a/tst/functions/assert/General/Should-BeGreaterThanOrEqual.Tests.ps1 b/tst/functions/assert/General/Should-BeGreaterThanOrEqual.Tests.ps1 new file mode 100644 index 000000000..e5d917782 --- /dev/null +++ b/tst/functions/assert/General/Should-BeGreaterThanOrEqual.Tests.ps1 @@ -0,0 +1,108 @@ +Set-StrictMode -Version Latest + +Describe "Should-BeGreaterThanOrEqual" { + Context "Comparing strings" { + It "Passes when actual is greater than expected" { + "z" | Should-BeGreaterThanOrEqual "a" + } + + It "Passes when actual is equal to expected" { + "a" | Should-BeGreaterThanOrEqual "a" + } + + It "Fails when actual is lower than expected" { + { "a" | Should-BeGreaterThanOrEqual "z" } | Verify-AssertionFailed + } + } + + Context "Comparing integers" { + It "Passes when expected is greater than actual" { + 2 | Should-BeGreaterThanOrEqual 1 + } + + It "Passes when actual is equal to expected" { + 1 | Should-BeGreaterThanOrEqual 1 + } + + It "Fails when actual is lower than expected" { + { 1 | Should-BeGreaterThanOrEqual 9 } | Verify-AssertionFailed + } + } + + Context "Comparing doubles" { + It "Passes when expected is greater than actual" { + .2 | Should-BeGreaterThanOrEqual .1 + } + + It "Passes when actual is equal to expected" { + .1 | Should-BeGreaterThanOrEqual .1 + } + + It "Fails when actual is lower than expected" { + { .1 | Should-BeGreaterThanOrEqual .9 } | Verify-AssertionFailed + } + } + + Context "Comparing decimals" { + It "Passes when expected is greater than actual" { + 2D | Should-BeGreaterThanOrEqual 1D + } + + It "Passes when actual is equal to expected" { + 1D | Should-BeGreaterThanOrEqual 1D + } + + It "Fails when actual is lower than expected" { + { 1D | Should-BeGreaterThanOrEqual 9D } | Verify-AssertionFailed + } + } + + Context "Comparing objects" { + It "Passes when two objects are the same" { + $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + $object | Should-BeGreaterThanOrEqual $object + } + + It "Fails when two objects are not comparable" { + $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + $object1 = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + $err = { $object | Should-BeGreaterThanOrEqual $object1 } | Verify-Throw + $err.Exception | Verify-Type ([System.Management.Automation.ExtendedTypeSystemException]) + } + } + + It "Fails for array input even if the last item is greater than then expected value" { + $err = { 1, 2, 3, 4 | Should-BeGreaterThanOrEqual 3 } | Verify-Throw + $err.Exception | Verify-Type ([System.Management.Automation.RuntimeException]) + } + + It "Fails with custom message" { + $err = { 2 | Should-BeGreaterThanOrEqual 3 -CustomMessage " is not greater than " } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "2 is not greater than 3" + } + + Context "Validate messages" { + It "Given two values '' and '' it returns expected message ''" -TestCases @( + @{ Expected = "z" ; Actual = "a" ; Message = "Expected [string] 'a' to be greater than or equal to [string] 'z', but it was not." }, + @{ Expected = 10.1 ; Actual = 1.1 ; Message = "Expected [double] 1.1 to be greater than or equal to [double] 10.1, but it was not." }, + @{ Expected = 10.1D ; Actual = 1.1D ; Message = "Expected [decimal] 1.1 to be greater than or equal to [decimal] 10.1, but it was not." } + ) { + $err = { Should-BeGreaterThanOrEqual -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $Message + } + } + + It "Returns the value on output" { + $expected = 1 + $expected | Should-BeGreaterThanOrEqual 0 | Verify-Equal $expected + } + + It "Can be called with positional parameters" { + { Should-BeGreaterThanOrEqual 2 1 } | Verify-AssertionFailed + } + + It "Given collection to Expected it throws" { + $err = { "dummy" | Should-BeGreaterThanOrEqual @() } | Verify-Throw + $err.Exception | Verify-Type ([ArgumentException]) + } +} diff --git a/tst/functions/assert/General/Assert-LessThan.Tests.ps1 b/tst/functions/assert/General/Should-BeLessThan.Tests.ps1 similarity index 66% rename from tst/functions/assert/General/Assert-LessThan.Tests.ps1 rename to tst/functions/assert/General/Should-BeLessThan.Tests.ps1 index b739bf2bc..f193c35d5 100644 --- a/tst/functions/assert/General/Assert-LessThan.Tests.ps1 +++ b/tst/functions/assert/General/Should-BeLessThan.Tests.ps1 @@ -1,83 +1,83 @@ Set-StrictMode -Version Latest -Describe "Assert-LessThan" { +Describe "Should-BeLessThan" { Context "Comparing strings" { It "Passes when actual is less than expected" { - "a" | Assert-LessThan "z" + "a" | Should-BeLessThan "z" } It "Fails when actual is equal to expected" { - { "z" | Assert-LessThan "z" } | Verify-AssertionFailed + { "z" | Should-BeLessThan "z" } | Verify-AssertionFailed } It "Fails when actual is greater than expected" { - { "z" | Assert-LessThan "a" } | Verify-AssertionFailed + { "z" | Should-BeLessThan "a" } | Verify-AssertionFailed } } Context "Comparing integers" { It "Passes when expected is less than actual" { - 1 | Assert-LessThan 2 + 1 | Should-BeLessThan 2 } It "Fails when actual is equal to expected" { - { 1 | Assert-LessThan 1 } | Verify-AssertionFailed + { 1 | Should-BeLessThan 1 } | Verify-AssertionFailed } It "Fails when actual is greater than expected" { - { 9 | Assert-LessThan 1 } | Verify-AssertionFailed + { 9 | Should-BeLessThan 1 } | Verify-AssertionFailed } } Context "Comparing doubles" { It "Passes when expected is less than actual" { - .1 | Assert-LessThan .2 + .1 | Should-BeLessThan .2 } It "Fails when actual is equal to expected" { - { .1 | Assert-LessThan .1 } | Verify-AssertionFailed + { .1 | Should-BeLessThan .1 } | Verify-AssertionFailed } It "Fails when actual is greater than expected" { - { .9 | Assert-LessThan .1 } | Verify-AssertionFailed + { .9 | Should-BeLessThan .1 } | Verify-AssertionFailed } } Context "Comparing decimals" { It "Passes when expected is less than actual" { - 1D | Assert-LessThan 2D + 1D | Should-BeLessThan 2D } It "Fails when actual is equal to expected" { - { 1D | Assert-LessThan 1D } | Verify-AssertionFailed + { 1D | Should-BeLessThan 1D } | Verify-AssertionFailed } It "Fails when actual is greater than expected" { - { 9D | Assert-LessThan 1D } | Verify-AssertionFailed + { 9D | Should-BeLessThan 1D } | Verify-AssertionFailed } } Context "Comparing objects" { It "Fails when two objects are the same" { $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } - { $object | Assert-LessThan $object } | Verify-AssertionFailed + { $object | Should-BeLessThan $object } | Verify-AssertionFailed } It "Fails when two objects are not comparable" { $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } $object1 = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } - $err = { $object | Assert-LessThan $object1 } | Verify-Throw + $err = { $object | Should-BeLessThan $object1 } | Verify-Throw $err.Exception | Verify-Type ([System.Management.Automation.ExtendedTypeSystemException]) } } It "Fails for array input even if the last item is less than the expected value" { - $err = { 4, 3, 2, 1 | Assert-LessThan 3 } | Verify-Throw + $err = { 4, 3, 2, 1 | Should-BeLessThan 3 } | Verify-Throw $err.Exception | Verify-Type ([System.Management.Automation.RuntimeException]) } It "Fails with custom message" { - $err = { 3 | Assert-LessThan 2 -CustomMessage " is not less than " } | Verify-AssertionFailed + $err = { 3 | Should-BeLessThan 2 -CustomMessage " is not less than " } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal "3 is not less than 2" } @@ -87,22 +87,22 @@ Describe "Assert-LessThan" { @{ Expected = 1.1 ; Actual = 10.1 ; Message = "Expected [double] 10.1 to be less than [double] 1.1, but it was not." }, @{ Expected = 1.1D ; Actual = 10.1D ; Message = "Expected [decimal] 10.1 to be less than [decimal] 1.1, but it was not." } ) { - $err = { Assert-LessThan -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + $err = { Should-BeLessThan -Actual $Actual -Expected $Expected } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message } } It "Returns the value on output" { $expected = 0 - $expected | Assert-LessThan 1 | Verify-Equal $expected + $expected | Should-BeLessThan 1 | Verify-Equal $expected } It "Can be called with positional parameters" { - { Assert-LessThan 1 2 } | Verify-AssertionFailed + { Should-BeLessThan 1 2 } | Verify-AssertionFailed } It "Given collection to Expected it throws" { - $err = { "dummy" | Assert-LessThan @() } | Verify-Throw + $err = { "dummy" | Should-BeLessThan @() } | Verify-Throw $err.Exception | Verify-Type ([ArgumentException]) } } diff --git a/tst/functions/assert/General/Assert-LessThanOrEqual.Tests.ps1 b/tst/functions/assert/General/Should-BeLessThanOrEqual.Tests.ps1 similarity index 67% rename from tst/functions/assert/General/Assert-LessThanOrEqual.Tests.ps1 rename to tst/functions/assert/General/Should-BeLessThanOrEqual.Tests.ps1 index 63c095618..fabb29417 100644 --- a/tst/functions/assert/General/Assert-LessThanOrEqual.Tests.ps1 +++ b/tst/functions/assert/General/Should-BeLessThanOrEqual.Tests.ps1 @@ -1,83 +1,83 @@ Set-StrictMode -Version Latest -Describe "Assert-LessThanOrEqual" { +Describe "Should-BeLessThanOrEqual" { Context "Comparing strings" { It "Passes when actual is less than expected" { - "a" | Assert-LessThanOrEqual "z" + "a" | Should-BeLessThanOrEqual "z" } It "Passes when actual is equal to expected" { - "a" | Assert-LessThanOrEqual "a" + "a" | Should-BeLessThanOrEqual "a" } It "Fails when actual is greater than expected" { - { "z" | Assert-LessThanOrEqual "a" } | Verify-AssertionFailed + { "z" | Should-BeLessThanOrEqual "a" } | Verify-AssertionFailed } } Context "Comparing integers" { It "Passes when expected is less than actual" { - 1 | Assert-LessThanOrEqual 2 + 1 | Should-BeLessThanOrEqual 2 } It "Passes when actual is equal to expected" { - 1 | Assert-LessThanOrEqual 1 + 1 | Should-BeLessThanOrEqual 1 } It "Fails when actual is greater than expected" { - { 9 | Assert-LessThanOrEqual 1 } | Verify-AssertionFailed + { 9 | Should-BeLessThanOrEqual 1 } | Verify-AssertionFailed } } Context "Comparing doubles" { It "Passes when expected is less than actual" { - .1 | Assert-LessThanOrEqual .2 + .1 | Should-BeLessThanOrEqual .2 } It "Passes when actual is equal to expected" { - .1 | Assert-LessThanOrEqual .1 + .1 | Should-BeLessThanOrEqual .1 } It "Fails when actual is greater than expected" { - { .9 | Assert-LessThanOrEqual .1 } | Verify-AssertionFailed + { .9 | Should-BeLessThanOrEqual .1 } | Verify-AssertionFailed } } Context "Comparing decimals" { It "Passes when expected is less than actual" { - 1D | Assert-LessThanOrEqual 2D + 1D | Should-BeLessThanOrEqual 2D } It "Passes when actual is equal to expected" { - 1D | Assert-LessThanOrEqual 1D + 1D | Should-BeLessThanOrEqual 1D } It "Fails when actual is greater than expected" { - { 9D | Assert-LessThanOrEqual 1D } | Verify-AssertionFailed + { 9D | Should-BeLessThanOrEqual 1D } | Verify-AssertionFailed } } Context "Comparing objects" { It "Passes when two objects are the same" { $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } - $object | Assert-LessThanOrEqual $object + $object | Should-BeLessThanOrEqual $object } It "Fails when two objects are not comparable" { $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } $object1 = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } - $err = { $object | Assert-LessThanOrEqual $object1 } | Verify-Throw + $err = { $object | Should-BeLessThanOrEqual $object1 } | Verify-Throw $err.Exception | Verify-Type ([System.Management.Automation.ExtendedTypeSystemException]) } } It "Fails for array input even if the last item is less than then expected value" { - $err = { 4, 3, 2, 1 | Assert-LessThanOrEqual 3 } | Verify-Throw + $err = { 4, 3, 2, 1 | Should-BeLessThanOrEqual 3 } | Verify-Throw $err.Exception | Verify-Type ([System.Management.Automation.RuntimeException]) } It "Fails with custom message" { - $err = { 3 | Assert-LessThanOrEqual 2 -CustomMessage " is not less than " } | Verify-AssertionFailed + $err = { 3 | Should-BeLessThanOrEqual 2 -CustomMessage " is not less than " } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal "3 is not less than 2" } @@ -87,22 +87,22 @@ Describe "Assert-LessThanOrEqual" { @{ Expected = 1.1 ; Actual = 10.1 ; Message = "Expected [double] 10.1 to be less than or equal to [double] 1.1, but it was not." }, @{ Expected = 1.1D ; Actual = 10.1D ; Message = "Expected [decimal] 10.1 to be less than or equal to [decimal] 1.1, but it was not." } ) { - $err = { Assert-LessThanOrEqual -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + $err = { Should-BeLessThanOrEqual -Actual $Actual -Expected $Expected } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message } } It "Returns the value on output" { $expected = 0 - $expected | Assert-LessThanOrEqual 1 | Verify-Equal $expected + $expected | Should-BeLessThanOrEqual 1 | Verify-Equal $expected } It "Can be called with positional parameters" { - { Assert-LessThanOrEqual 1 2 } | Verify-AssertionFailed + { Should-BeLessThanOrEqual 1 2 } | Verify-AssertionFailed } It "Given collection to Expected it throws" { - $err = { "dummy" | Assert-LessThanOrEqual @() } | Verify-Throw + $err = { "dummy" | Should-BeLessThanOrEqual @() } | Verify-Throw $err.Exception | Verify-Type ([ArgumentException]) } } diff --git a/tst/functions/assert/General/Should-BeNull.Tests.ps1 b/tst/functions/assert/General/Should-BeNull.Tests.ps1 new file mode 100644 index 000000000..7398ae333 --- /dev/null +++ b/tst/functions/assert/General/Should-BeNull.Tests.ps1 @@ -0,0 +1,27 @@ +Set-StrictMode -Version Latest + +Describe "Should-BeNull" { + It "Given `$null it passes" { + $null | Should-BeNull + } + + It "Given an objects it fails" { + { 1 | Should-BeNull } | Verify-AssertionFailed + } + + It "Given empty array it fails" { + { @() | Should-BeNull } | Verify-AssertionFailed + } + + It "Returns the given value" { + $null | Should-BeNull | Verify-Null + } + + It "Can be called with positional parameters (1)" { + { Should-BeNull 1 } | Verify-AssertionFailed + } + + It "Can be called with positional parameters (@())" { + { Should-BeNull @() } | Verify-AssertionFailed + } +} diff --git a/tst/functions/assert/General/Should-BeSame.Tests.ps1 b/tst/functions/assert/General/Should-BeSame.Tests.ps1 new file mode 100644 index 000000000..00cbcc1a2 --- /dev/null +++ b/tst/functions/assert/General/Should-BeSame.Tests.ps1 @@ -0,0 +1,56 @@ +Set-StrictMode -Version Latest + +Describe "Should-BeSame" { + It "Passes when two objects are the same instance" { + $object = New-Object Diagnostics.Process + $object | Should-BeSame $object + } + + It "Fails when two objects are different instance" { + $object = New-Object Diagnostics.Process + $object1 = New-Object Diagnostics.Process + { $object | Should-BeSame $object1 } | Verify-AssertionFailed + } + + It "Fails for array input even if the last item is the same as expected" { + $object = New-Object Diagnostics.Process + { 1, 2, $object | Should-BeSame $object } | Verify-AssertionFailed + } + + It "Fails with custom message" { + $object = New-Object Diagnostics.Process + $err = { "text" | Should-BeSame $object -CustomMessage "'' is not ''" } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "'Diagnostics.Process{Id=`$null; Name=`$null}' is not ''text''" + } + + It "Given two values that are not the same instance '' and '' it returns expected message ''" -TestCases @( + @{ Expected = New-Object -TypeName PSObject ; Actual = New-Object -TypeName PSObject ; Message = "Expected [PSObject] 'PSObject{}', to be the same instance but it was not." } + ) { + $err = { Should-BeSame -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $Message + } + + It "Returns the value on output" { + $expected = New-Object Diagnostics.Process + $expected | Should-BeSame $expected | Verify-Equal $expected + } + + Context "Throws when `$expected is a value type or string to warn user about unexpected behavior" { + It "throws for value " -TestCases @( + @{ Value = 1 } + @{ Value = 1.0D } + @{ Value = 1.0 } + @{ Value = 'c' } + @{ Value = "abc" } + ) { + $err = { "dummy" | Should-BeSame -Expected $Value } | Verify-Throw + $err.Exception | Verify-Type ([ArgumentException]) + $err.Exception.Message | Verify-Equal "Should-BeSame compares objects by reference. You provided a value type or a string, those are not reference types and you most likely don't need to compare them by reference, see https://github.com/nohwnd/Assert/issues/6.`n`nAre you trying to compare two values to see if they are equal? Use Should-BeEqual instead." + } + } + + It "Can be called with positional parameters" { + $object = New-Object Diagnostics.Process + { Should-BeSame $object "abc" } | Verify-AssertionFailed + } +} diff --git a/tst/functions/assert/General/Should-HaveType.Tests.ps1 b/tst/functions/assert/General/Should-HaveType.Tests.ps1 new file mode 100644 index 000000000..ba064cb3d --- /dev/null +++ b/tst/functions/assert/General/Should-HaveType.Tests.ps1 @@ -0,0 +1,19 @@ +Set-StrictMode -Version Latest + +Describe "Should-HaveType" { + It "Given value of expected type it passes" { + 1 | Should-HaveType ([int]) + } + + It "Given an object of different type it fails" { + { 1 | Should-HaveType ([string]) } | Verify-AssertionFailed + } + + It "Returns the given value" { + 'b' | Should-HaveType ([string]) | Verify-Equal 'b' + } + + It "Can be called with positional parameters" { + { Should-HaveType ([string]) 1 } | Verify-AssertionFailed + } +} diff --git a/tst/functions/assert/General/Should-NotBe.Tests.ps1 b/tst/functions/assert/General/Should-NotBe.Tests.ps1 new file mode 100644 index 000000000..804f29c10 --- /dev/null +++ b/tst/functions/assert/General/Should-NotBe.Tests.ps1 @@ -0,0 +1,90 @@ +Set-StrictMode -Version Latest + +Describe "Should-NotBe" { + Context "Comparing strings" { + It "Fails when two strings are equal" { + { "abc" | Should-NotBe "abc" } | Verify-AssertionFailed + } + + It "Passes when two strings are different" { + "abc" | Should-NotBe "bde" + } + } + + Context "Comparing integers" { + It "Fails when two numbers are equal" { + { 1 | Should-NotBe 1 } | Verify-AssertionFailed + } + + It "Passes when two numbers are different" { + 1 | Should-NotBe 9 + } + } + + Context "Comparing doubles" { + It "Fails when two numbers are equal" { + { .1 | Should-NotBe .1 } | Verify-AssertionFailed + } + + It "Passes when two numbers are different" { + .1 | Should-NotBe .9 + } + } + + Context "Comparing decimals" { + It "Fails when two numbers are equal" { + { .1D | Should-NotBe .1D } | Verify-AssertionFailed + } + + It "Passes when two numbers are different" { + .1D | Should-NotBe .9D + } + } + + Context "Comparing objects" { + It "Fails when two objects are the same" { + $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + { $object | Should-NotBe $object } | Verify-AssertionFailed + } + + It "Passes when two objects are different" { + $object = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + $object1 = New-Object -TypeName PsObject -Property @{ Name = "Jakub" } + $object | Should-NotBe $object1 + } + } + + It "Passes for array input even if the last item is the same as expected" { + 1, 2, 3 | Should-NotBe 3 + } + + It "Fails with custom message" { + $err = { 3 | Should-NotBe 3 -CustomMessage " is " } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "3 is 3" + } + + Context "Validate messages" { + It "Given two values that are the same '' it returns expected message ''" -TestCases @( + @{ Value = 1; Message = "Expected [int] 1, to be different than the actual value, but they were the same." } + ) { + param($Value, $Message) + $err = { Should-NotBe -Actual $Value -Expected $Value } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $Message + } + } + + It "Returns the value on output" { + $expected = 1 + $expected | Should-NotBe 9 | Verify-Equal $expected + } + + It "Can be called with positional parameters" { + { Should-NotBe 1 1 } | Verify-AssertionFailed + } + + It "Given collection to Expected it throws" { + $err = { "dummy" | Should-NotBe @() } | Verify-Throw + $err.Exception | Verify-Type ([ArgumentException]) + } +} + diff --git a/tst/functions/assert/General/Assert-NotNull.Tests.ps1 b/tst/functions/assert/General/Should-NotBeNull.Tests.ps1 similarity index 53% rename from tst/functions/assert/General/Assert-NotNull.Tests.ps1 rename to tst/functions/assert/General/Should-NotBeNull.Tests.ps1 index 16d053ba3..203dd44b1 100644 --- a/tst/functions/assert/General/Assert-NotNull.Tests.ps1 +++ b/tst/functions/assert/General/Should-NotBeNull.Tests.ps1 @@ -1,21 +1,21 @@ Set-StrictMode -Version Latest InPesterModuleScope { - Describe "Assert-NotNull" { + Describe "Should-NotBeNull" { It "Given a value it passes" { - 1 | Assert-NotNull + 1 | Should-NotBeNull } It "Given `$null it fails" { - { $null | Assert-NotNull } | Verify-AssertionFailed + { $null | Should-NotBeNull } | Verify-AssertionFailed } It "Returns the given value" { - 1 | Assert-NotNull | Verify-NotNull + 1 | Should-NotBeNull | Verify-NotNull } It "Can be called with positional parameters" { - { Assert-NotNull $null } | Verify-AssertionFailed + { Should-NotBeNull $null } | Verify-AssertionFailed } } } diff --git a/tst/functions/assert/General/Should-NotBeSame.Tests.ps1 b/tst/functions/assert/General/Should-NotBeSame.Tests.ps1 new file mode 100644 index 000000000..da93e44e8 --- /dev/null +++ b/tst/functions/assert/General/Should-NotBeSame.Tests.ps1 @@ -0,0 +1,46 @@ +Set-StrictMode -Version Latest + +Describe "Should-NotBeSame" { + It "Fails when two objects are the same instance" { + $object = New-Object Diagnostics.Process + { $object | Should-NotBeSame $object } | Verify-AssertionFailed + } + + It "Passes when two objects are different instance" { + $object = New-Object Diagnostics.Process + $object1 = New-Object Diagnostics.Process + $object | Should-NotBeSame $object1 + } + + It "Passes for array input even if the last item is the same as expected" { + $object = New-Object Diagnostics.Process + 1, 2, $object | Should-NotBeSame $object + } + + It "Fails with custom message" { + $object = 1 + $err = { $object | Should-NotBeSame $object -CustomMessage " is " } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "1 is 1" + } + + It "Given two values that are the same instance it returns expected message ''" -TestCases @( + @{ Value = "a"; Message = "Expected [string] ''a'', to not be the same instance." } + ) { + param($Value, $Message) + $err = { Should-NotBeSame -Actual $Value -Expected $Value } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $Message + } + + It "Returns the value on output" { + $expected = 1 + $expected | Should-NotBeSame 7 | Verify-Equal $expected + } + + It "Can be called with positional parameters" { + { + $obj = New-Object -TypeName PSObject + Should-NotBeSame $obj $obj + } | Verify-AssertionFailed + } +} + diff --git a/tst/functions/assert/General/Should-NotHaveType.Tests.ps1 b/tst/functions/assert/General/Should-NotHaveType.Tests.ps1 new file mode 100644 index 000000000..00b598dd0 --- /dev/null +++ b/tst/functions/assert/General/Should-NotHaveType.Tests.ps1 @@ -0,0 +1,19 @@ +Set-StrictMode -Version Latest + +Describe "Should-NotHaveType" { + It "Given value of expected type it fails" { + { 1 | Should-NotHaveType ([int]) } | Verify-AssertionFailed + } + + It "Given an object of different type it passes" { + 1 | Should-NotHaveType ([string]) + } + + It "Returns the given value" { + 'b' | Should-NotHaveType ([int]) | Verify-Equal 'b' + } + + It "Can be called with positional parameters" { + { Should-NotHaveType ([int]) 1 } | Verify-AssertionFailed + } +} diff --git a/tst/functions/assert/String/Assert-StringNotEqual.Tests.ps1 b/tst/functions/assert/String/Assert-StringNotEqual.Tests.ps1 deleted file mode 100644 index 8ebd42828..000000000 --- a/tst/functions/assert/String/Assert-StringNotEqual.Tests.ps1 +++ /dev/null @@ -1,60 +0,0 @@ -Set-StrictMode -Version Latest - -InPesterModuleScope { - Describe "Get-StringNotEqualDefaultFailureMessage" { - It "returns correct default message" { - $expected = "Expected the strings to be different but they were the same 'abc'." - $actual = Get-StringNotEqualDefaultFailureMessage -Expected "abc" -Actual "abc" - $actual | Verify-Equal $expected - } - } - - Describe "Assert-StringNotEqual" { - It "Does nothing when string are different" { - Assert-StringNotEqual -Expected "abc" -Actual "bde" - } - - It "Throws when strings are the same" { - { Assert-StringNotEqual -Expected "abc" -Actual "abc" } | Verify-AssertionFailed - } - - It "Throws with default message when test fails" { - $expected = Get-StringNotEqualDefaultFailureMessage -Expected "abc" -Actual "abc" - $exception = { Assert-StringNotEqual -Expected "abc" -Actual "abc" } | Verify-AssertionFailed - "$exception" | Verify-Equal $expected - } - - It "Throws with custom message when test fails" { - $customMessage = "Test failed becasue it expected '' but got ''. What a shame!" - $expected = Get-CustomFailureMessage -CustomMessage $customMessage -Expected "abc" -Actual "abc" - $exception = { Assert-StringNotEqual -Expected "abc" -Actual "abc" -CustomMessage $customMessage } | Verify-AssertionFailed - "$exception" | Verify-Equal $expected - } - - It "Allows actual to be passed from pipeline" { - "abc" | Assert-StringNotEqual -Expected "bde" - } - - It "Allows expected to be passed by position" { - Assert-StringNotEqual "abc" -Actual "bde" - } - - It "Allows actual to be passed by pipeline and expected by position" { - "abc" | Assert-StringNotEqual "bde" - } - - Context "String specific features" { - It "Can compare strings in CaseSensitive mode" { - Assert-StringNotEqual -Expected "ABC" -Actual "abc" -CaseSensitive - } - - It "Can compare strings without whitespace" { - { Assert-StringNotEqual -Expected " a b c " -Actual "abc" -IgnoreWhitespace } | Verify-AssertionFailed - } - } - - It "Can be called with positional parameters" { - { Assert-StringNotEqual "a" "a" } | Verify-AssertionFailed - } - } -} diff --git a/tst/functions/assert/String/Assert-Like.Tests.ps1 b/tst/functions/assert/String/Should-BeLikeString.Tests.ps1 similarity index 59% rename from tst/functions/assert/String/Assert-Like.Tests.ps1 rename to tst/functions/assert/String/Should-BeLikeString.Tests.ps1 index f6ec2e68e..c59617ac9 100644 --- a/tst/functions/assert/String/Assert-Like.Tests.ps1 +++ b/tst/functions/assert/String/Should-BeLikeString.Tests.ps1 @@ -1,118 +1,118 @@ Set-StrictMode -Version Latest -Describe "Assert-Like" { +Describe "Should-BeLikeString" { Context "Case insensitive matching" { It "Passes give strings that have the same value" { - Assert-Like -Expected "abc" -Actual "abc" + Should-BeLikeString -Expected "abc" -Actual "abc" } It "Passes given strings with different case and same values. comparing '':''" -TestCases @( - @{ Actual = "ABc"; Expected = "abc" }, - @{ Actual = "aBc"; Expected = "abc" }, - @{ Actual = "ABC"; Expected = "abc" } + @{ Actual = "ABc"; Expected = "abc" }, + @{ Actual = "aBc"; Expected = "abc" }, + @{ Actual = "ABC"; Expected = "abc" } ) { param ($Actual, $Expected) - Assert-Like -Actual $Actual -Expected $Expected + Should-BeLikeString -Actual $Actual -Expected $Expected } It "Fails given strings with different values" { - { Assert-Like -Expected "abc" -Actual "def" } | Verify-AssertionFailed + { Should-BeLikeString -Expected "abc" -Actual "def" } | Verify-AssertionFailed } It "Fails given strings with different case and different values. comparing '':''" -TestCases @( - @{ Actual = "ABc"; Expected = "def" }, - @{ Actual = "aBc"; Expected = "def" }, - @{ Actual = "ABC"; Expected = "def" } + @{ Actual = "ABc"; Expected = "def" }, + @{ Actual = "aBc"; Expected = "def" }, + @{ Actual = "ABC"; Expected = "def" } ) { param ($Actual, $Expected) - { Assert-Like -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + { Should-BeLikeString -Actual $Actual -Expected $Expected } | Verify-AssertionFailed } It "Fails given strings from which one is sorrounded by whitespace. comparing '':''" -TestCases @( - @{ Actual = "abc "; Expected = "abc" }, - @{ Actual = "abc "; Expected = "abc" }, - @{ Actual = "ab c"; Expected = "abc" } + @{ Actual = "abc "; Expected = "abc" }, + @{ Actual = "abc "; Expected = "abc" }, + @{ Actual = "ab c"; Expected = "abc" } ) { param ($Actual, $Expected) - { Assert-Like -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + { Should-BeLikeString -Actual $Actual -Expected $Expected } | Verify-AssertionFailed } It "Passes given strings with different case that start with a given pattern. comparing '':''" -TestCases @( - @{ Actual = "ABcdef"; Expected = "abc*" }, - @{ Actual = "aBcdef"; Expected = "abc*" }, - @{ Actual = "ABCDEF"; Expected = "abc*" } + @{ Actual = "ABcdef"; Expected = "abc*" }, + @{ Actual = "aBcdef"; Expected = "abc*" }, + @{ Actual = "ABCDEF"; Expected = "abc*" } ) { param ($Actual, $Expected) - Assert-Like -Actual $Actual -Expected $Expected + Should-BeLikeString -Actual $Actual -Expected $Expected } It "Fails given strings with different case that start with a different pattern. comparing '':''" -TestCases @( - @{ Actual = "ABcdef"; Expected = "ghi*" }, - @{ Actual = "aBcdef"; Expected = "ghi*" }, - @{ Actual = "ABCDEF"; Expected = "ghi*" } + @{ Actual = "ABcdef"; Expected = "ghi*" }, + @{ Actual = "aBcdef"; Expected = "ghi*" }, + @{ Actual = "ABCDEF"; Expected = "ghi*" } ) { param ($Actual, $Expected) - { Assert-Like -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + { Should-BeLikeString -Actual $Actual -Expected $Expected } | Verify-AssertionFailed } It "Passes given strings with different case that contain a given pattern. comparing '':''" -TestCases @( - @{ Actual = "ABcdef"; Expected = "*cd*" }, - @{ Actual = "aBcdef"; Expected = "*cd*" }, - @{ Actual = "ABCDEF"; Expected = "*CD*" } + @{ Actual = "ABcdef"; Expected = "*cd*" }, + @{ Actual = "aBcdef"; Expected = "*cd*" }, + @{ Actual = "ABCDEF"; Expected = "*CD*" } ) { param ($Actual, $Expected) - Assert-Like -Actual $Actual -Expected $Expected + Should-BeLikeString -Actual $Actual -Expected $Expected } It "Fails given strings with different case that contain a different pattern. comparing '':''" -TestCases @( - @{ Actual = "ABcdef"; Expected = "*gh*" }, - @{ Actual = "aBcdef"; Expected = "*gh*" }, - @{ Actual = "ABCDEF"; Expected = "*GH*" } + @{ Actual = "ABcdef"; Expected = "*gh*" }, + @{ Actual = "aBcdef"; Expected = "*gh*" }, + @{ Actual = "ABCDEF"; Expected = "*GH*" } ) { param ($Actual, $Expected) - { Assert-Like -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + { Should-BeLikeString -Actual $Actual -Expected $Expected } | Verify-AssertionFailed } } Context "Case sensitive matching" { It "Fails given strings with different case but same values. comparing '':''" -TestCases @( - @{ Actual = "ABc"; Expected = "abc" }, - @{ Actual = "aBc"; Expected = "abc" }, - @{ Actual = "ABC"; Expected = "abc" } + @{ Actual = "ABc"; Expected = "abc" }, + @{ Actual = "aBc"; Expected = "abc" }, + @{ Actual = "ABC"; Expected = "abc" } ) { param ($Actual, $Expected) - { Assert-Like -Actual $Actual -Expected $Expected -CaseSensitive } | Verify-AssertionFailed + { Should-BeLikeString -Actual $Actual -Expected $Expected -CaseSensitive } | Verify-AssertionFailed } } Context "Case sensitive matching" { It "Fails given strings with different case that contain the given pattern. comparing '':''" -TestCases @( - @{ Actual = "ABCDEF"; Expected = "*cd*" } + @{ Actual = "ABCDEF"; Expected = "*cd*" } ) { param ($Actual, $Expected) - { Assert-Like -Actual $Actual -Expected $Expected -CaseSensitive } | Verify-AssertionFailed + { Should-BeLikeString -Actual $Actual -Expected $Expected -CaseSensitive } | Verify-AssertionFailed } } It "Allows actual to be passed from pipeline" { - "abc" | Assert-Like -Expected "abc" + "abc" | Should-BeLikeString -Expected "abc" } It "Allows expected to be passed by position" { - Assert-Like "abc" -Actual "abc" + Should-BeLikeString "abc" -Actual "abc" } It "Allows actual to be passed by pipeline and expected by position" { - "abc" | Assert-Like "abc" + "abc" | Should-BeLikeString "abc" } It "Throws when given a collection to avoid confusing matches of the last item only" { - $err = { "bde", "abc" | Assert-Like -Expected "abc" } | Verify-Throw + $err = { "bde", "abc" | Should-BeLikeString -Expected "abc" } | Verify-Throw $err.Exception.Message | Verify-Equal "Actual is expected to be string, to avoid confusing behavior that -like operator exhibits with collections. To assert on collections use Assert-Any, Assert-All or some other collection assertion." } It "Can be called with positional parameters" { - { Assert-Like "a" "b" } | Verify-AssertionFailed + { Should-BeLikeString "a" "b" } | Verify-AssertionFailed } Context "Verify messages" { @@ -122,7 +122,7 @@ Describe "Assert-Like" { @{ Actual = 'something'; Expected = '*abc*'; Message = "Expected the string 'something' to match '*abc*' but it did not." } ) { param ($Actual, $Expected, $Message) - $err = { Assert-Like -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + $err = { Should-BeLikeString -Actual $Actual -Expected $Expected } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message } @@ -132,7 +132,7 @@ Describe "Assert-Like" { @{ Actual = 'something'; Expected = '*SOME*'; Message = "Expected the string 'something' to case sensitively match '*SOME*' but it did not." } ) { param ($Actual, $Expected, $Message) - $err = { Assert-Like -Actual $Actual -Expected $Expected -CaseSensitive } | Verify-AssertionFailed + $err = { Should-BeLikeString -Actual $Actual -Expected $Expected -CaseSensitive } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message } } diff --git a/tst/functions/assert/String/Assert-NotLike.Tests.ps1 b/tst/functions/assert/String/Should-NotBeLikeString.Tests.ps1 similarity index 53% rename from tst/functions/assert/String/Assert-NotLike.Tests.ps1 rename to tst/functions/assert/String/Should-NotBeLikeString.Tests.ps1 index fb71d193f..e0c3e6f69 100644 --- a/tst/functions/assert/String/Assert-NotLike.Tests.ps1 +++ b/tst/functions/assert/String/Should-NotBeLikeString.Tests.ps1 @@ -1,117 +1,108 @@ Set-StrictMode -Version Latest -Describe "Assert-NotLike" { +Describe "Should-NotBeLikeString" { Context "Case insensitive matching" { It "Fails give strings that have the same value" { - { Assert-NotLike -Expected "abc" -Actual "abc" } | Verify-AssertionFailed + { Should-NotBeLikeString -Expected "abc" -Actual "abc" } | Verify-AssertionFailed } It "Fails given strings with different case and same values. comparing '':''" -TestCases @( - @{ Actual = "ABc"; Expected = "abc" }, - @{ Actual = "aBc"; Expected = "abc" }, - @{ Actual = "ABC"; Expected = "abc" } + @{ Actual = "ABc"; Expected = "abc" }, + @{ Actual = "aBc"; Expected = "abc" }, + @{ Actual = "ABC"; Expected = "abc" } ) { - param ($Actual, $Expected) - { Assert-NotLike -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + { Should-NotBeLikeString -Actual $Actual -Expected $Expected } | Verify-AssertionFailed } It "Passes given strings with different values" { - Assert-NotLike -Expected "abc" -Actual "def" + Should-NotBeLikeString -Expected "abc" -Actual "def" } It "Passes given strings with different case and different values. comparing '':''" -TestCases @( - @{ Actual = "ABc"; Expected = "def" }, - @{ Actual = "aBc"; Expected = "def" }, - @{ Actual = "ABC"; Expected = "def" } + @{ Actual = "ABc"; Expected = "def" }, + @{ Actual = "aBc"; Expected = "def" }, + @{ Actual = "ABC"; Expected = "def" } ) { - param ($Actual, $Expected) - Assert-NotLike -Actual $Actual -Expected $Expected + Should-NotBeLikeString -Actual $Actual -Expected $Expected } It "Passes given strings from which one is sorrounded by whitespace. comparing '':''" -TestCases @( - @{ Actual = "abc "; Expected = "abc" }, - @{ Actual = "abc "; Expected = "abc" }, - @{ Actual = "ab c"; Expected = "abc" } + @{ Actual = "abc "; Expected = "abc" }, + @{ Actual = "abc "; Expected = "abc" }, + @{ Actual = "ab c"; Expected = "abc" } ) { - param ($Actual, $Expected) - Assert-NotLike -Actual $Actual -Expected $Expected + Should-NotBeLikeString -Actual $Actual -Expected $Expected } It "Fails given strings with different case that start with a given pattern. comparing '':''" -TestCases @( - @{ Actual = "ABcdef"; Expected = "abc*" }, - @{ Actual = "aBcdef"; Expected = "abc*" }, - @{ Actual = "ABCDEF"; Expected = "abc*" } + @{ Actual = "ABcdef"; Expected = "abc*" }, + @{ Actual = "aBcdef"; Expected = "abc*" }, + @{ Actual = "ABCDEF"; Expected = "abc*" } ) { - param ($Actual, $Expected) - { Assert-NotLike -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + { Should-NotBeLikeString -Actual $Actual -Expected $Expected } | Verify-AssertionFailed } It "Passes given strings with different case that start with a different pattern. comparing '':''" -TestCases @( - @{ Actual = "ABcdef"; Expected = "ghi*" }, - @{ Actual = "aBcdef"; Expected = "ghi*" }, - @{ Actual = "ABCDEF"; Expected = "ghi*" } + @{ Actual = "ABcdef"; Expected = "ghi*" }, + @{ Actual = "aBcdef"; Expected = "ghi*" }, + @{ Actual = "ABCDEF"; Expected = "ghi*" } ) { - param ($Actual, $Expected) - Assert-NotLike -Actual $Actual -Expected $Expected + Should-NotBeLikeString -Actual $Actual -Expected $Expected } It "Fails given strings with different case that contain a given pattern. comparing '':''" -TestCases @( - @{ Actual = "ABcdef"; Expected = "*cd*" }, - @{ Actual = "aBcdef"; Expected = "*cd*" }, - @{ Actual = "ABCDEF"; Expected = "*CD*" } + @{ Actual = "ABcdef"; Expected = "*cd*" }, + @{ Actual = "aBcdef"; Expected = "*cd*" }, + @{ Actual = "ABCDEF"; Expected = "*CD*" } ) { - param ($Actual, $Expected) - { Assert-NotLike -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + { Should-NotBeLikeString -Actual $Actual -Expected $Expected } | Verify-AssertionFailed } It "Passes given strings with different case that contain a different pattern. comparing '':''" -TestCases @( - @{ Actual = "ABcdef"; Expected = "*gh*" }, - @{ Actual = "aBcdef"; Expected = "*gh*" }, - @{ Actual = "ABCDEF"; Expected = "*GH*" } + @{ Actual = "ABcdef"; Expected = "*gh*" }, + @{ Actual = "aBcdef"; Expected = "*gh*" }, + @{ Actual = "ABCDEF"; Expected = "*GH*" } ) { - param ($Actual, $Expected) - Assert-NotLike -Actual $Actual -Expected $Expected + Should-NotBeLikeString -Actual $Actual -Expected $Expected } } Context "Case sensitive matching" { It "Passes given strings with different case but same values. comparing '':''" -TestCases @( - @{ Actual = "ABc"; Expected = "abc" }, - @{ Actual = "aBc"; Expected = "abc" }, - @{ Actual = "ABC"; Expected = "abc" } + @{ Actual = "ABc"; Expected = "abc" }, + @{ Actual = "aBc"; Expected = "abc" }, + @{ Actual = "ABC"; Expected = "abc" } ) { - param ($Actual, $Expected) - Assert-NotLike -Actual $Actual -Expected $Expected -CaseSensitive + Should-NotBeLikeString -Actual $Actual -Expected $Expected -CaseSensitive } } Context "Case sensitive matching" { It "Passes given strings with different case that contain the given pattern. comparing '':''" -TestCases @( - @{ Actual = "ABCDEF"; Expected = "*cd*" } + @{ Actual = "ABCDEF"; Expected = "*cd*" } ) { - param ($Actual, $Expected) - Assert-NotLike -Actual $Actual -Expected $Expected -CaseSensitive + Should-NotBeLikeString -Actual $Actual -Expected $Expected -CaseSensitive } } It "Allows actual to be passed from pipeline" { - "efg" | Assert-NotLike -Expected "abc" + "efg" | Should-NotBeLikeString -Expected "abc" } It "Allows expected to be passed by position" { - Assert-NotLike "efg" -Actual "abc" + Should-NotBeLikeString "efg" -Actual "abc" } It "Allows actual to be passed by pipeline and expected by position" { - "efg" | Assert-NotLike "abc" + "efg" | Should-NotBeLikeString "abc" } It "Can be called with positional parameters" { - { Assert-NotLike "a" "a" } | Verify-AssertionFailed + { Should-NotBeLikeString "a" "a" } | Verify-AssertionFailed } It "Throws when given a collection to avoid confusing matches of the last item only" { - $err = { "bde", "abc" | Assert-NotLike -Expected "abc" } | Verify-Throw + $err = { "bde", "abc" | Should-NotBeLikeString -Expected "abc" } | Verify-Throw $err.Exception.Message | Verify-Equal "Actual is expected to be string, to avoid confusing behavior that -like operator exhibits with collections. To assert on collections use Assert-Any, Assert-All or some other collection assertion." } @@ -121,8 +112,7 @@ Describe "Assert-NotLike" { @{ Actual = 'ab'; Expected = 'a*'; Message = "Expected the string 'ab' to not match 'a*' but it matched it." } @{ Actual = 'something'; Expected = 'SOME*'; Message = "Expected the string 'something' to not match 'SOME*' but it matched it." } ) { - param ($Actual, $Expected, $Message) - $err = { Assert-NotLike -Actual $Actual -Expected $Expected } | Verify-AssertionFailed + $err = { Should-NotBeLikeString -Actual $Actual -Expected $Expected } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message } @@ -131,8 +121,7 @@ Describe "Assert-NotLike" { @{ Actual = 'AB'; Expected = 'A*'; Message = "Expected the string 'AB' to case sensitively not match 'A*' but it matched it." } @{ Actual = 'SOMETHING'; Expected = '*SOME*'; Message = "Expected the string 'SOMETHING' to case sensitively not match '*SOME*' but it matched it." } ) { - param ($Actual, $Expected, $Message) - $err = { Assert-NotLike -Actual $Actual -Expected $Expected -CaseSensitive } | Verify-AssertionFailed + $err = { Should-NotBeLikeString -Actual $Actual -Expected $Expected -CaseSensitive } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message } } diff --git a/tst/functions/assert/String/Should-NotBeString.Tests.ps1 b/tst/functions/assert/String/Should-NotBeString.Tests.ps1 new file mode 100644 index 000000000..81a033108 --- /dev/null +++ b/tst/functions/assert/String/Should-NotBeString.Tests.ps1 @@ -0,0 +1,61 @@ +Set-StrictMode -Version Latest + +InPesterModuleScope { + Describe "Get-StringNotEqualDefaultFailureMessage" { + It "returns correct default message" { + $expected = "Expected the strings to be different but they were the same 'abc'." + $actual = Get-StringNotEqualDefaultFailureMessage -Expected "abc" -Actual "abc" + $actual | Verify-Equal $expected + } + + It "Throws with default message when test fails" { + $expected = Get-StringNotEqualDefaultFailureMessage -Expected "abc" -Actual "abc" + $exception = { Should-NotBeString -Expected "abc" -Actual "abc" } | Verify-AssertionFailed + "$exception" | Verify-Equal $expected + } + + It "Throws with custom message when test fails" { + $customMessage = "Test failed becasue it expected '' but got ''. What a shame!" + $expected = Get-CustomFailureMessage -CustomMessage $customMessage -Expected "abc" -Actual "abc" + $exception = { Should-NotBeString -Expected "abc" -Actual "abc" -CustomMessage $customMessage } | Verify-AssertionFailed + "$exception" | Verify-Equal $expected + } + } +} + +Describe "Should-NotBeString" { + It "Does nothing when string are different" { + Should-NotBeString -Expected "abc" -Actual "bde" + } + + It "Throws when strings are the same" { + { Should-NotBeString -Expected "abc" -Actual "abc" } | Verify-AssertionFailed + } + + It "Allows actual to be passed from pipeline" { + "abc" | Should-NotBeString -Expected "bde" + } + + It "Allows expected to be passed by position" { + Should-NotBeString "abc" -Actual "bde" + } + + It "Allows actual to be passed by pipeline and expected by position" { + "abc" | Should-NotBeString "bde" + } + + Context "String specific features" { + It "Can compare strings in CaseSensitive mode" { + Should-NotBeString -Expected "ABC" -Actual "abc" -CaseSensitive + } + + It "Can compare strings without whitespace" { + { Should-NotBeString -Expected " a b c " -Actual "abc" -IgnoreWhitespace } | Verify-AssertionFailed + } + } + + It "Can be called with positional parameters" { + { Should-NotBeString "a" "a" } | Verify-AssertionFailed + } +} + From 432e02d008783d528526f00c78189863a283f3a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Fri, 26 Apr 2024 17:34:59 +0200 Subject: [PATCH 33/55] Rename assertions and tests, and use assertion functions so we are sure they are exported --- .../assert/String/Should-NotBeNullOrEmptyString.Tests.ps1 | 1 - 1 file changed, 1 deletion(-) diff --git a/tst/functions/assert/String/Should-NotBeNullOrEmptyString.Tests.ps1 b/tst/functions/assert/String/Should-NotBeNullOrEmptyString.Tests.ps1 index 8f00564cc..7dd692ae8 100644 --- a/tst/functions/assert/String/Should-NotBeNullOrEmptyString.Tests.ps1 +++ b/tst/functions/assert/String/Should-NotBeNullOrEmptyString.Tests.ps1 @@ -6,7 +6,6 @@ Describe "Should-NotBeNullOrEmptyString" { @{ Actual = " " } @{ Actual = "`t" } @{ Actual = "`n" } - @{ Actual = "" } ) { $Actual | Should-NotBeNullOrEmptyString } From b5f8da425153b34eaf3eca9c625b49a7ea6aad71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Wed, 1 May 2024 19:43:31 +0200 Subject: [PATCH 34/55] Fix tests --- .../Common/Ensure-ExpectedIsNotCollection.ps1 | 4 ++-- .../assert/String/Should-BeLikeString.ps1 | 2 +- .../assert/String/Should-NotBeLikeString.ps1 | 2 +- src/functions/assert/Time/Should-BeAfter.ps1 | 2 +- tst/Format2.Tests.ps1 | 17 ++++++++--------- .../Ensure-ExpectedIsNotCollection.Tests.ps1 | 2 +- .../assert/String/Should-BeLikeString.Tests.ps1 | 2 +- .../String/Should-NotBeLikeString.Tests.ps1 | 2 +- .../assert/Time/Should-BeBefore.Tests.ps1 | 2 ++ 9 files changed, 18 insertions(+), 17 deletions(-) diff --git a/src/functions/assert/Common/Ensure-ExpectedIsNotCollection.ps1 b/src/functions/assert/Common/Ensure-ExpectedIsNotCollection.ps1 index 98d9a3028..83d174ab0 100644 --- a/src/functions/assert/Common/Ensure-ExpectedIsNotCollection.ps1 +++ b/src/functions/assert/Common/Ensure-ExpectedIsNotCollection.ps1 @@ -5,8 +5,8 @@ function Ensure-ExpectedIsNotCollection { if (Is-Collection $InputObject) { - throw [ArgumentException]'You provided a collection to the -Expected parameter. Using a collection on the -Expected side is not allowed by this assertion, because it leads to unexpected behavior. Please use Assert-Any, Assert-All or some other specialized collection assertion.' + throw [ArgumentException]'You provided a collection to the -Expected parameter. Using a collection on the -Expected side is not allowed by this assertion, because it leads to unexpected behavior. Please use Should-Any, Should-All or some other specialized collection assertion.' } $InputObject -} \ No newline at end of file +} diff --git a/src/functions/assert/String/Should-BeLikeString.ps1 b/src/functions/assert/String/Should-BeLikeString.ps1 index 9e8e0a59f..6e4c74fd9 100644 --- a/src/functions/assert/String/Should-BeLikeString.ps1 +++ b/src/functions/assert/String/Should-BeLikeString.ps1 @@ -36,7 +36,7 @@ function Assert-Like { $Actual = $collectedInput.Actual if ($Actual -isnot [string]) { - throw [ArgumentException]"Actual is expected to be string, to avoid confusing behavior that -like operator exhibits with collections. To assert on collections use Assert-Any, Assert-All or some other collection assertion." + throw [ArgumentException]"Actual is expected to be string, to avoid confusing behavior that -like operator exhibits with collections. To assert on collections use Should-Any, Should-All or some other collection assertion." } $stringsAreAlike = Test-Like -Expected $Expected -Actual $Actual -CaseSensitive:$CaseSensitive -IgnoreWhitespace:$IgnoreWhiteSpace diff --git a/src/functions/assert/String/Should-NotBeLikeString.ps1 b/src/functions/assert/String/Should-NotBeLikeString.ps1 index 50a770b01..daaa61d51 100644 --- a/src/functions/assert/String/Should-NotBeLikeString.ps1 +++ b/src/functions/assert/String/Should-NotBeLikeString.ps1 @@ -36,7 +36,7 @@ function Assert-NotLike { $Actual = $collectedInput.Actual if ($Actual -isnot [string]) { - throw [ArgumentException]"Actual is expected to be string, to avoid confusing behavior that -like operator exhibits with collections. To assert on collections use Assert-Any, Assert-All or some other collection assertion." + throw [ArgumentException]"Actual is expected to be string, to avoid confusing behavior that -like operator exhibits with collections. To assert on collections use Should-Any, Should-All or some other collection assertion." } $stringsAreANotLike = Test-NotLike -Expected $Expected -Actual $Actual -CaseSensitive:$CaseSensitive -IgnoreWhitespace:$IgnoreWhiteSpace diff --git a/src/functions/assert/Time/Should-BeAfter.ps1 b/src/functions/assert/Time/Should-BeAfter.ps1 index 6e238226b..577338c20 100644 --- a/src/functions/assert/Time/Should-BeAfter.ps1 +++ b/src/functions/assert/Time/Should-BeAfter.ps1 @@ -45,7 +45,7 @@ } if ($Actual -le $Expected) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -Data @{ ago = $Ago } -DefaultMessage "Expected the provided [datetime] to be after ( ago), but it was before: " + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected the provided [datetime] to be after , but it was before: " throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } } diff --git a/tst/Format2.Tests.ps1 b/tst/Format2.Tests.ps1 index 2fe8dddd9..35c0065be 100644 --- a/tst/Format2.Tests.ps1 +++ b/tst/Format2.Tests.ps1 @@ -151,20 +151,19 @@ InPesterModuleScope { Describe "Format-Nicely2" { It "Formats value '' correctly to ''" -TestCases @( - # @{ Value = $null; Expected = '$null' } - # @{ Value = $true; Expected = '$true' } - # @{ Value = $false; Expected = '$false' } - # @{ Value = 'a' ; Expected = "'a'" }, - # @{ Value = 1; Expected = '1' }, - # @{ Value = (1, 2, 3); Expected = '@(1, 2, 3)' }, - # @{ Value = 1.1; Expected = '1.1' }, - # @{ Value = [int]; Expected = 'int' } + @{ Value = $null; Expected = '$null' } + @{ Value = $true; Expected = '$true' } + @{ Value = $false; Expected = '$false' } + @{ Value = 'a' ; Expected = "'a'" }, + @{ Value = 1; Expected = '1' }, + @{ Value = (1, 2, 3); Expected = '@(1, 2, 3)' }, + @{ Value = 1.1; Expected = '1.1' }, + @{ Value = [int]; Expected = '[int]' } @{ Value = New-PSObject @{ Name = "Jakub" }; Expected = "PSObject{Name='Jakub'}" }, @{ Value = (New-Object -Type Assertions.TestType.Person -Property @{Name = 'Jakub'; Age = 28 }); Expected = "Assertions.TestType.Person{Age=28; Name='Jakub'}" } @{ Value = @{Name = 'Jakub'; Age = 28 }; Expected = "@{Age=28; Name='Jakub'}" } @{ Value = New-Dictionary @{Age = 28; Name = 'Jakub' }; Expected = "Dictionary{Age=28; Name='Jakub'}" } ) { - param($Value, $Expected) Format-Nicely2 -Value $Value | Verify-Equal $Expected } } diff --git a/tst/functions/assert/Common/Ensure-ExpectedIsNotCollection.Tests.ps1 b/tst/functions/assert/Common/Ensure-ExpectedIsNotCollection.Tests.ps1 index 4edea0e02..93ee5ecd5 100644 --- a/tst/functions/assert/Common/Ensure-ExpectedIsNotCollection.Tests.ps1 +++ b/tst/functions/assert/Common/Ensure-ExpectedIsNotCollection.Tests.ps1 @@ -9,7 +9,7 @@ InPesterModuleScope { It "Given a collection it throws correct message" { $err = { Ensure-ExpectedIsNotCollection -InputObject @() } | Verify-Throw - $err.Exception.Message | Verify-Equal 'You provided a collection to the -Expected parameter. Using a collection on the -Expected side is not allowed by this assertion, because it leads to unexpected behavior. Please use Assert-Any, Assert-All or some other specialized collection assertion.' + $err.Exception.Message | Verify-Equal 'You provided a collection to the -Expected parameter. Using a collection on the -Expected side is not allowed by this assertion, because it leads to unexpected behavior. Please use Should-Any, Should-All or some other specialized collection assertion.' } diff --git a/tst/functions/assert/String/Should-BeLikeString.Tests.ps1 b/tst/functions/assert/String/Should-BeLikeString.Tests.ps1 index c59617ac9..2bd962312 100644 --- a/tst/functions/assert/String/Should-BeLikeString.Tests.ps1 +++ b/tst/functions/assert/String/Should-BeLikeString.Tests.ps1 @@ -108,7 +108,7 @@ Describe "Should-BeLikeString" { It "Throws when given a collection to avoid confusing matches of the last item only" { $err = { "bde", "abc" | Should-BeLikeString -Expected "abc" } | Verify-Throw - $err.Exception.Message | Verify-Equal "Actual is expected to be string, to avoid confusing behavior that -like operator exhibits with collections. To assert on collections use Assert-Any, Assert-All or some other collection assertion." + $err.Exception.Message | Verify-Equal "Actual is expected to be string, to avoid confusing behavior that -like operator exhibits with collections. To assert on collections use Should-Any, Should-All or some other collection assertion." } It "Can be called with positional parameters" { diff --git a/tst/functions/assert/String/Should-NotBeLikeString.Tests.ps1 b/tst/functions/assert/String/Should-NotBeLikeString.Tests.ps1 index e0c3e6f69..7d0ca265e 100644 --- a/tst/functions/assert/String/Should-NotBeLikeString.Tests.ps1 +++ b/tst/functions/assert/String/Should-NotBeLikeString.Tests.ps1 @@ -103,7 +103,7 @@ Describe "Should-NotBeLikeString" { It "Throws when given a collection to avoid confusing matches of the last item only" { $err = { "bde", "abc" | Should-NotBeLikeString -Expected "abc" } | Verify-Throw - $err.Exception.Message | Verify-Equal "Actual is expected to be string, to avoid confusing behavior that -like operator exhibits with collections. To assert on collections use Assert-Any, Assert-All or some other collection assertion." + $err.Exception.Message | Verify-Equal "Actual is expected to be string, to avoid confusing behavior that -like operator exhibits with collections. To assert on collections use Should-Any, Should-All or some other collection assertion." } Context "Verify messages" { diff --git a/tst/functions/assert/Time/Should-BeBefore.Tests.ps1 b/tst/functions/assert/Time/Should-BeBefore.Tests.ps1 index d9574de3c..561ce734b 100644 --- a/tst/functions/assert/Time/Should-BeBefore.Tests.ps1 +++ b/tst/functions/assert/Time/Should-BeBefore.Tests.ps1 @@ -54,6 +54,8 @@ Describe "Should-BeBefore" { New-Item -ItemType Directory -Path "TestDrive:\MyFolder" -Force | Out-Null $path = "TestDrive:\MyFolder\test.txt" "hello" | Set-Content $path + # DateTime.Now is not precise in Windows Powershell. We need to wait a bit. + Start-Sleep -Milliseconds 15 (Get-Item $path).CreationTime | Should-BeBefore -Now } } From 2f262f352731750c0417a54bc464ddfc820000fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Wed, 1 May 2024 21:10:18 +0200 Subject: [PATCH 35/55] Change messages,tests are broken --- src/Module.ps1 | 6 + src/Pester.psd1 | 4 + .../assert/Boolean/Should-BeFalse.ps1 | 6 +- .../assert/Boolean/Should-BeFalsy.ps1 | 17 +++ .../assert/Boolean/Should-BeTrue.ps1 | 6 +- .../assert/Boolean/Should-BeTruthy.ps1 | 17 +++ .../assert/Collection/Should-All.ps1 | 6 +- .../assert/Collection/Should-Any.ps1 | 6 +- .../assert/Collection/Should-BeCollection.ps1 | 10 +- .../Collection/Should-ContainCollection.ps1 | 12 +- .../Should-NotContainCollection.ps1 | 5 +- .../assert/Exception/Should-Throw.ps1 | 4 +- src/functions/assert/General/Should-Be.ps1 | 4 +- .../General/Should-BeGreaterThanOrEqual.ps1 | 4 +- .../assert/General/Should-BeLessThan.ps1 | 4 +- .../General/Should-BeLessThanOrEqual.ps1 | 4 +- .../assert/General/Should-BeNull.ps1 | 4 +- .../assert/General/Should-BeSame.ps1 | 4 +- .../assert/General/Should-HaveType.ps1 | 5 +- src/functions/assert/General/Should-NotBe.ps1 | 4 +- .../assert/General/Should-NotBeNull.ps1 | 9 +- .../assert/General/Should-NotBeSame.ps1 | 4 +- .../assert/General/Should-NotHaveType.ps1 | 5 +- .../assert/General/ShouldBe-GreaterThan.ps1 | 4 +- .../assert/String/Should-BeLikeString.ps1 | 4 +- .../assert/String/Should-BeString.ps1 | 20 +-- .../assert/String/Should-NotBeLikeString.ps1 | 4 +- .../assert/String/Should-NotBeString.ps1 | 4 +- src/functions/assert/Time/Should-BeAfter.ps1 | 2 +- src/functions/assert/Time/Should-BeBefore.ps1 | 2 +- .../assert/Time/Should-BeFasterThan.ps1 | 4 +- .../assert/Time/Should-BeSlowerThan.ps1 | 4 +- test.ps1 | 10 +- .../assert/Boolean/Should-BeFalse.Tests.ps1 | 14 +- .../assert/Boolean/Should-BeFalsy.Tests.ps1 | 40 ++++++ .../assert/Boolean/Should-BeTrue.Tests.ps1 | 16 +-- .../assert/Boolean/Should-BeTruthy.Tests.ps1 | 35 +++++ .../assert/General/Should-Be.Tests.ps1 | 5 - .../General/Should-BeGreaterThan.Tests.ps1 | 5 - .../Should-BeGreaterThanOrEqual.Tests.ps1 | 5 - .../General/Should-BeLessThan.Tests.ps1 | 5 - .../Should-BeLessThanOrEqual.Tests.ps1 | 5 - .../assert/General/Should-BeSame.Tests.ps1 | 6 - .../assert/General/Should-NotBe.Tests.ps1 | 5 - .../assert/General/Should-NotBeSame.Tests.ps1 | 6 - .../String/Assert-StringEqual.Tests.ps1 | 126 ------------------ .../assert/String/Should-BeString.Tests.ps1 | 110 +++++++++++++++ .../String/Should-NotBeString.Tests.ps1 | 7 - 48 files changed, 314 insertions(+), 284 deletions(-) create mode 100644 src/functions/assert/Boolean/Should-BeFalsy.ps1 create mode 100644 src/functions/assert/Boolean/Should-BeTruthy.ps1 create mode 100644 tst/functions/assert/Boolean/Should-BeFalsy.Tests.ps1 create mode 100644 tst/functions/assert/Boolean/Should-BeTruthy.Tests.ps1 delete mode 100644 tst/functions/assert/String/Assert-StringEqual.Tests.ps1 create mode 100644 tst/functions/assert/String/Should-BeString.Tests.ps1 diff --git a/src/Module.ps1 b/src/Module.ps1 index ff77951d5..04c0ae01b 100644 --- a/src/Module.ps1 +++ b/src/Module.ps1 @@ -10,6 +10,8 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session & $SafeCommands['Set-Alias'] 'Should-BeFalse' 'Assert-False' & $SafeCommands['Set-Alias'] 'Should-BeTrue' 'Assert-True' +& $SafeCommands['Set-Alias'] 'Should-BeFalsy' 'Assert-Falsy' +& $SafeCommands['Set-Alias'] 'Should-BeTruthy' 'Assert-Truthy' & $SafeCommands['Set-Alias'] 'Should-All' 'Assert-All' & $SafeCommands['Set-Alias'] 'Should-Any' 'Assert-Any' & $SafeCommands['Set-Alias'] 'Should-BeCollection' 'Assert-Contain' @@ -80,6 +82,8 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session # assert 'Assert-False' 'Assert-True' + 'Assert-Falsy' + 'Assert-Truthy' 'Assert-All' 'Assert-Any' 'Assert-Contain' @@ -136,6 +140,8 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session # bool 'Should-BeFalse' 'Should-BeTrue' + 'Should-BeFalsy' + 'Should-BeTruthy' # collection 'Should-All' diff --git a/src/Pester.psd1 b/src/Pester.psd1 index 597ef48e1..d3fe835ea 100644 --- a/src/Pester.psd1 +++ b/src/Pester.psd1 @@ -69,6 +69,8 @@ # assert 'Assert-False' 'Assert-True' + 'Assert-Falsy' + 'Assert-Truthy' 'Assert-All' 'Assert-Any' 'Assert-Contain' @@ -124,6 +126,8 @@ # bool 'Should-BeFalse' 'Should-BeTrue' + 'Should-BeFalsy' + 'Should-BeTruthy' # collection 'Should-All' diff --git a/src/functions/assert/Boolean/Should-BeFalse.ps1 b/src/functions/assert/Boolean/Should-BeFalse.ps1 index c25903f0b..37ee2f8f1 100644 --- a/src/functions/assert/Boolean/Should-BeFalse.ps1 +++ b/src/functions/assert/Boolean/Should-BeFalse.ps1 @@ -3,13 +3,13 @@ param ( [Parameter(ValueFromPipeline = $true)] $Actual, - [String]$CustomMessage + [String]$Because ) $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual - if ($Actual) { - $Message = Get-AssertionMessage -Expected $false -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected to be or falsy value 0, """", `$null, @()." + if ($Actual -isnot [bool] -or $Actual) { + $Message = Get-AssertionMessage -Expected $false -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/src/functions/assert/Boolean/Should-BeFalsy.ps1 b/src/functions/assert/Boolean/Should-BeFalsy.ps1 new file mode 100644 index 000000000..974d3885f --- /dev/null +++ b/src/functions/assert/Boolean/Should-BeFalsy.ps1 @@ -0,0 +1,17 @@ +function Assert-Falsy { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] + param ( + [Parameter(ValueFromPipeline = $true)] + $Actual, + [String]$Because + ) + + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual + if ($Actual) { + $Message = Get-AssertionMessage -Expected $false -Actual $Actual -Because $Because -DefaultMessage 'Expected or a falsy value: 0, "", $null or @(), but got: .' + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) + } + + $Actual +} diff --git a/src/functions/assert/Boolean/Should-BeTrue.ps1 b/src/functions/assert/Boolean/Should-BeTrue.ps1 index 987c06c1c..7eeaf84b1 100644 --- a/src/functions/assert/Boolean/Should-BeTrue.ps1 +++ b/src/functions/assert/Boolean/Should-BeTrue.ps1 @@ -3,13 +3,13 @@ param ( [Parameter(ValueFromPipeline = $true)] $Actual, - [String]$CustomMessage + [String]$Because ) $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual - if (-not $Actual) { - $Message = Get-AssertionMessage -Expected $true -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected to be or truthy value." + if ($Actual -isnot [bool] -or -not $Actual) { + $Message = Get-AssertionMessage -Expected $true -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/src/functions/assert/Boolean/Should-BeTruthy.ps1 b/src/functions/assert/Boolean/Should-BeTruthy.ps1 new file mode 100644 index 000000000..71232122c --- /dev/null +++ b/src/functions/assert/Boolean/Should-BeTruthy.ps1 @@ -0,0 +1,17 @@ +function Assert-Truthy { + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] + param ( + [Parameter(ValueFromPipeline = $true)] + $Actual, + [String]$Because + ) + + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $Actual = $collectedInput.Actual + if (-not $Actual) { + $Message = Get-AssertionMessage -Expected $true -Actual $Actual -Because $Because -DefaultMessage "Expected or a truthy value, but got: ." + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) + } + + $Actual +} diff --git a/src/functions/assert/Collection/Should-All.ps1 b/src/functions/assert/Collection/Should-All.ps1 index a4742720b..bb54d6ef6 100644 --- a/src/functions/assert/Collection/Should-All.ps1 +++ b/src/functions/assert/Collection/Should-All.ps1 @@ -6,7 +6,7 @@ $Actual, [Parameter(Position = 0, Mandatory = $true)] [scriptblock]$FilterScript, - [String]$CustomMessage + [String]$Because ) @@ -15,7 +15,7 @@ $Actual = $collectedInput.Actual if ($null -eq $Actual -or 0 -eq @($Actual).Count) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Data $data -CustomMessage $CustomMessage -DefaultMessage "Expected all items in collection to pass filter , but contains no items to compare." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Data $data -Because $Because -DefaultMessage "Expected all items in collection to pass filter , but contains no items to compare." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } @@ -52,7 +52,7 @@ actualFiltered = $actualFiltered actualFilteredCount = $actualFiltered.Count } - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Data $data -CustomMessage $CustomMessage -DefaultMessage "Expected all items in collection to pass filter , but of them did not pass the filter." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Data $data -Because $Because -DefaultMessage "Expected all items in collection to pass filter , but of them did not pass the filter." if ($null -ne $failReasons) { $failReasons = $failReasons -join "`n" if ($appendMore) { diff --git a/src/functions/assert/Collection/Should-Any.ps1 b/src/functions/assert/Collection/Should-Any.ps1 index 6eb3275b6..31986f979 100644 --- a/src/functions/assert/Collection/Should-Any.ps1 +++ b/src/functions/assert/Collection/Should-Any.ps1 @@ -5,7 +5,7 @@ $Actual, [Parameter(Position = 0, Mandatory = $true)] [scriptblock]$FilterScript, - [String]$CustomMessage + [String]$Because ) $Expected = $FilterScript @@ -13,7 +13,7 @@ $Actual = $collectedInput.Actual if ($null -eq $Actual -or 0 -eq @($Actual).Count) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Data $data -CustomMessage $CustomMessage -DefaultMessage "Expected at least one item in collection to pass filter , but contains no items to compare." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Data $data -Because $Because -DefaultMessage "Expected at least one item in collection to pass filter , but contains no items to compare." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } @@ -42,7 +42,7 @@ } if (-not $pass) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected at least one item in collection to pass filter , but none of the items passed the filter." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected at least one item in collection to pass filter , but none of the items passed the filter." if ($null -ne $failReasons) { $failReasons = $failReasons -join "`n" if ($appendMore) { diff --git a/src/functions/assert/Collection/Should-BeCollection.ps1 b/src/functions/assert/Collection/Should-BeCollection.ps1 index be77a1cea..7eaa3adad 100644 --- a/src/functions/assert/Collection/Should-BeCollection.ps1 +++ b/src/functions/assert/Collection/Should-BeCollection.ps1 @@ -5,29 +5,29 @@ $Actual, [Parameter(Position = 0)] $Expected, - [String]$CustomMessage + [String]$Because ) $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if (-not (Is-Collection -Value $Expected)) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' is not a collection." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected '' is not a collection." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } if (-not (Is-Collection -Value $Actual)) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Actual '' is not a collection." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Actual '' is not a collection." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } if (-not (Is-CollectionSize -Expected $Expected -Actual $Actual)) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be equal to collection '' but they don't have the same number of items." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected '' to be equal to collection '' but they don't have the same number of items." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } if ($Actual) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '' to be present in collection '', but it was not there." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected '' to be present in collection '', but it was not there." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/Collection/Should-ContainCollection.ps1 b/src/functions/assert/Collection/Should-ContainCollection.ps1 index e4eed57b5..d1d353532 100644 --- a/src/functions/assert/Collection/Should-ContainCollection.ps1 +++ b/src/functions/assert/Collection/Should-ContainCollection.ps1 @@ -1,19 +1,17 @@ function Assert-Contain { [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( - [Parameter(Position=1, ValueFromPipeline=$true)] + [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position=0)] + [Parameter(Position = 0)] $Expected, - [String]$CustomMessage + [String]$Because ) $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual - if ($Actual -notcontains $Expected) - { - $type = [string]$Expected - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected to be present in collection , but it was not there." + if ($Actual -notcontains $Expected) { + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected to be present in collection , but it was not there." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/Collection/Should-NotContainCollection.ps1 b/src/functions/assert/Collection/Should-NotContainCollection.ps1 index 65463de12..54ef69b9e 100644 --- a/src/functions/assert/Collection/Should-NotContainCollection.ps1 +++ b/src/functions/assert/Collection/Should-NotContainCollection.ps1 @@ -5,14 +5,13 @@ $Actual, [Parameter(Position = 0)] $Expected, - [String]$CustomMessage + [String]$Because ) $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if ($Actual -contains $Expected) { - $type = [string]$Expected - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected to not be present in collection , but it was there." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected to not be present in collection , but it was there." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/Exception/Should-Throw.ps1 b/src/functions/assert/Exception/Should-Throw.ps1 index 3b6d5a9b3..0a08a9103 100644 --- a/src/functions/assert/Exception/Should-Throw.ps1 +++ b/src/functions/assert/Exception/Should-Throw.ps1 @@ -7,7 +7,7 @@ function Assert-Throw { [String]$ExceptionMessage, [String]$FullyQualifiedErrorId, [Switch]$AllowNonTerminatingError, - [String]$CustomMessage + [String]$Because ) $collectedInput = Collect-Input -ParameterInput $ScriptBlock -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput @@ -70,7 +70,7 @@ function Assert-Throw { $but = Join-And $buts $defaultMessage = "Expected an exception,$filter to be thrown, but $but." - $Message = Get-AssertionMessage -Expected $Expected -Actual $ScriptBlock -CustomMessage $CustomMessage ` + $Message = Get-AssertionMessage -Expected $Expected -Actual $ScriptBlock -Because $Because ` -DefaultMessage $defaultMessage throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Should-Be.ps1 b/src/functions/assert/General/Should-Be.ps1 index 1aa37066f..dbeb9324b 100644 --- a/src/functions/assert/General/Should-Be.ps1 +++ b/src/functions/assert/General/Should-Be.ps1 @@ -5,14 +5,14 @@ $Actual, [Parameter(Position = 0)] $Expected, - [String]$CustomMessage + [String]$Because ) $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if ((Ensure-ExpectedIsNotCollection $Expected) -ne $Actual) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected , but got ." + $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/src/functions/assert/General/Should-BeGreaterThanOrEqual.ps1 b/src/functions/assert/General/Should-BeGreaterThanOrEqual.ps1 index 452e5749c..bb70b4fa2 100644 --- a/src/functions/assert/General/Should-BeGreaterThanOrEqual.ps1 +++ b/src/functions/assert/General/Should-BeGreaterThanOrEqual.ps1 @@ -5,13 +5,13 @@ $Actual, [Parameter(Position = 0)] $Expected, - [String]$CustomMessage + [String]$Because ) $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if ((Ensure-ExpectedIsNotCollection $Expected) -gt $Actual) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected to be greater than or equal to , but it was not." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected actual value to be greater than or equal to , but it was not. Actual: " throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Should-BeLessThan.ps1 b/src/functions/assert/General/Should-BeLessThan.ps1 index b0d7dc83b..f30c29d84 100644 --- a/src/functions/assert/General/Should-BeLessThan.ps1 +++ b/src/functions/assert/General/Should-BeLessThan.ps1 @@ -5,13 +5,13 @@ $Actual, [Parameter(Position = 0)] $Expected, - [String]$CustomMessage + [String]$Because ) $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if ((Ensure-ExpectedIsNotCollection $Expected) -le $Actual) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected to be less than , but it was not." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected the actual value to be less than , but it was not. Actual: " throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Should-BeLessThanOrEqual.ps1 b/src/functions/assert/General/Should-BeLessThanOrEqual.ps1 index 1c8c8d292..81d2f5d79 100644 --- a/src/functions/assert/General/Should-BeLessThanOrEqual.ps1 +++ b/src/functions/assert/General/Should-BeLessThanOrEqual.ps1 @@ -5,13 +5,13 @@ $Actual, [Parameter(Position = 0)] $Expected, - [String]$CustomMessage + [String]$Because ) $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if ((Ensure-ExpectedIsNotCollection $Expected) -lt $Actual) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected to be less than or equal to , but it was not." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected the actual value to be less than or equal to , but it was not. Actual: " throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Should-BeNull.ps1 b/src/functions/assert/General/Should-BeNull.ps1 index 20c914690..c2b460c4b 100644 --- a/src/functions/assert/General/Should-BeNull.ps1 +++ b/src/functions/assert/General/Should-BeNull.ps1 @@ -3,13 +3,13 @@ param ( [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [String]$CustomMessage + [String]$Because ) $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if ($null -ne $Actual) { - $Message = Get-AssertionMessage -Expected $null -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected `$null, but got ''." + $Message = Get-AssertionMessage -Expected $null -Actual $Actual -Because $Because -DefaultMessage "Expected `$null, but got ''." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Should-BeSame.ps1 b/src/functions/assert/General/Should-BeSame.ps1 index 4db2e2ff4..a203af333 100644 --- a/src/functions/assert/General/Should-BeSame.ps1 +++ b/src/functions/assert/General/Should-BeSame.ps1 @@ -5,7 +5,7 @@ $Actual, [Parameter(Position = 0)] $Expected, - [String]$CustomMessage + [String]$Because ) if ($Expected -is [ValueType] -or $Expected -is [string]) { @@ -15,7 +15,7 @@ $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if (-not ([object]::ReferenceEquals($Expected, $Actual))) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '', to be the same instance but it was not." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected , to be the same instance but it was not. Actual: " throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Should-HaveType.ps1 b/src/functions/assert/General/Should-HaveType.ps1 index 4581d359c..6f2bec046 100644 --- a/src/functions/assert/General/Should-HaveType.ps1 +++ b/src/functions/assert/General/Should-HaveType.ps1 @@ -5,14 +5,13 @@ $Actual, [Parameter(Position = 0)] [Type]$Expected, - [String]$CustomMessage + [String]$Because ) $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if ($Actual -isnot $Expected) { - $type = [string]$Expected - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected value to be of type '$type', but got '' of type ''." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected value to have type , but got ." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Should-NotBe.ps1 b/src/functions/assert/General/Should-NotBe.ps1 index 0c7e525b0..174de0650 100644 --- a/src/functions/assert/General/Should-NotBe.ps1 +++ b/src/functions/assert/General/Should-NotBe.ps1 @@ -5,13 +5,13 @@ $Actual, [Parameter(Position = 0)] $Expected, - [String]$CustomMessage + [String]$Because ) $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if ((Ensure-ExpectedIsNotCollection $Expected) -eq $Actual) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected , to be different than the actual value, but they were the same." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected , to be different than the actual value, but they were equal." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Should-NotBeNull.ps1 b/src/functions/assert/General/Should-NotBeNull.ps1 index 5b9605a97..26288c6e9 100644 --- a/src/functions/assert/General/Should-NotBeNull.ps1 +++ b/src/functions/assert/General/Should-NotBeNull.ps1 @@ -1,16 +1,15 @@ function Assert-NotNull { [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( - [Parameter(Position=1, ValueFromPipeline=$true)] + [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [String]$CustomMessage + [String]$Because ) $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual - if ($null -eq $Actual) - { - $Message = Get-AssertionMessage -Expected $null -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected not `$null, but got `$null." + if ($null -eq $Actual) { + $Message = Get-AssertionMessage -Expected $null -Actual $Actual -Because $Because -DefaultMessage "Expected not `$null, but got `$null." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Should-NotBeSame.ps1 b/src/functions/assert/General/Should-NotBeSame.ps1 index e83b90446..d50fb9e37 100644 --- a/src/functions/assert/General/Should-NotBeSame.ps1 +++ b/src/functions/assert/General/Should-NotBeSame.ps1 @@ -5,13 +5,13 @@ $Actual, [Parameter(Position = 0)] $Expected, - [String]$CustomMessage + [String]$Because ) $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if ([object]::ReferenceEquals($Expected, $Actual)) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected '', to not be the same instance." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected , to not be the same instance." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Should-NotHaveType.ps1 b/src/functions/assert/General/Should-NotHaveType.ps1 index de4858d94..494a229db 100644 --- a/src/functions/assert/General/Should-NotHaveType.ps1 +++ b/src/functions/assert/General/Should-NotHaveType.ps1 @@ -5,14 +5,13 @@ $Actual, [Parameter(Position = 0)] [Type]$Expected, - [String]$CustomMessage + [String]$Because ) $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if ($Actual -is $Expected) { - $type = [string]$Expected - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected value to be of different type than '$type', but got '' of type ''." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected value to be of different type than , but got ." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/ShouldBe-GreaterThan.ps1 b/src/functions/assert/General/ShouldBe-GreaterThan.ps1 index 53462bd1b..544d46bf6 100644 --- a/src/functions/assert/General/ShouldBe-GreaterThan.ps1 +++ b/src/functions/assert/General/ShouldBe-GreaterThan.ps1 @@ -5,13 +5,13 @@ $Actual, [Parameter(Position = 0)] $Expected, - [String]$CustomMessage + [String]$Because ) $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if ((Ensure-ExpectedIsNotCollection $Expected) -ge $Actual) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected to be greater than , but it was not." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected the actual value to be greater than , but it was not. Actual: " throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/String/Should-BeLikeString.ps1 b/src/functions/assert/String/Should-BeLikeString.ps1 index 6e4c74fd9..dddea4374 100644 --- a/src/functions/assert/String/Should-BeLikeString.ps1 +++ b/src/functions/assert/String/Should-BeLikeString.ps1 @@ -29,7 +29,7 @@ function Assert-Like { [Parameter(Position = 0, Mandatory = $true)] [String]$Expected, [Switch]$CaseSensitive, - [String]$CustomMessage + [String]$Because ) $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput @@ -45,7 +45,7 @@ function Assert-Like { $formattedMessage = Get-LikeDefaultFailureMessage -Expected $Expected -Actual $Actual -CaseSensitive:$CaseSensitive } else { - $formattedMessage = Get-CustomFailureMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -CaseSensitive:$CaseSensitive + $formattedMessage = Get-CustomFailureMessage -Expected $Expected -Actual $Actual -Because $Because -CaseSensitive:$CaseSensitive } throw [Pester.Factory]::CreateShouldErrorRecord($formattedMessage, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/String/Should-BeString.ps1 b/src/functions/assert/String/Should-BeString.ps1 index 04d37a92e..f12394b33 100644 --- a/src/functions/assert/String/Should-BeString.ps1 +++ b/src/functions/assert/String/Should-BeString.ps1 @@ -6,6 +6,10 @@ [switch]$IgnoreWhitespace ) + if ($Actual -isnot [string]) { + return $false + } + if ($IgnoreWhitespace) { $Expected = $Expected -replace '\s' $Actual = $Actual -replace '\s' @@ -19,10 +23,6 @@ } } -function Get-StringEqualDefaultFailureMessage ([String]$Expected, $Actual) { - "Expected the string to be '$Expected' but got '$Actual'." -} - function Assert-StringEqual { [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( @@ -30,7 +30,7 @@ function Assert-StringEqual { $Actual, [Parameter(Position = 0)] [String]$Expected, - [String]$CustomMessage, + [String]$Because, [switch]$CaseSensitive, [switch]$IgnoreWhitespace ) @@ -38,15 +38,9 @@ function Assert-StringEqual { $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual - if (-not $CustomMessage) { - $formattedMessage = Get-StringEqualDefaultFailureMessage -Expected $Expected -Actual $Actual - } - else { - $formattedMessage = Get-CustomFailureMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage - } - $stringsAreEqual = Test-StringEqual -Expected $Expected -Actual $Actual -CaseSensitive:$CaseSensitive -IgnoreWhitespace:$IgnoreWhiteSpace if (-not ($stringsAreEqual)) { - throw [Pester.Factory]::CreateShouldErrorRecord($formattedMessage, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) + $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/src/functions/assert/String/Should-NotBeLikeString.ps1 b/src/functions/assert/String/Should-NotBeLikeString.ps1 index daaa61d51..46e819e13 100644 --- a/src/functions/assert/String/Should-NotBeLikeString.ps1 +++ b/src/functions/assert/String/Should-NotBeLikeString.ps1 @@ -29,7 +29,7 @@ function Assert-NotLike { [Parameter(Position = 0, Mandatory = $true)] [String]$Expected, [Switch]$CaseSensitive, - [String]$CustomMessage + [String]$Because ) $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput @@ -45,7 +45,7 @@ function Assert-NotLike { $formattedMessage = Get-NotLikeDefaultFailureMessage -Expected $Expected -Actual $Actual -CaseSensitive:$CaseSensitive } else { - $formattedMessage = Get-CustomFailureMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -CaseSensitive:$CaseSensitive + $formattedMessage = Get-CustomFailureMessage -Expected $Expected -Actual $Actual -Because $Because -CaseSensitive:$CaseSensitive } throw [Pester.Factory]::CreateShouldErrorRecord($formattedMessage, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) diff --git a/src/functions/assert/String/Should-NotBeString.ps1 b/src/functions/assert/String/Should-NotBeString.ps1 index a47c83b6e..13f39a56a 100644 --- a/src/functions/assert/String/Should-NotBeString.ps1 +++ b/src/functions/assert/String/Should-NotBeString.ps1 @@ -9,7 +9,7 @@ function Assert-StringNotEqual { $Actual, [Parameter(Position = 0)] [String]$Expected, - [String]$CustomMessage, + [String]$Because, [switch]$CaseSensitive, [switch]$IgnoreWhitespace ) @@ -19,7 +19,7 @@ function Assert-StringNotEqual { $formattedMessage = Get-StringNotEqualDefaultFailureMessage -Expected $Expected -Actual $Actual } else { - $formattedMessage = Get-CustomFailureMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage + $formattedMessage = Get-CustomFailureMessage -Expected $Expected -Actual $Actual -Because $Because } throw [Pester.Factory]::CreateShouldErrorRecord($formattedMessage, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) diff --git a/src/functions/assert/Time/Should-BeAfter.ps1 b/src/functions/assert/Time/Should-BeAfter.ps1 index 577338c20..174b4d463 100644 --- a/src/functions/assert/Time/Should-BeAfter.ps1 +++ b/src/functions/assert/Time/Should-BeAfter.ps1 @@ -45,7 +45,7 @@ } if ($Actual -le $Expected) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "Expected the provided [datetime] to be after , but it was before: " + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected the provided [datetime] to be after , but it was before: " throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } } diff --git a/src/functions/assert/Time/Should-BeBefore.ps1 b/src/functions/assert/Time/Should-BeBefore.ps1 index 1881b333b..452bd71cd 100644 --- a/src/functions/assert/Time/Should-BeBefore.ps1 +++ b/src/functions/assert/Time/Should-BeBefore.ps1 @@ -45,7 +45,7 @@ } if ($Actual -ge $Expected) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -Data @{ ago = $Ago } -DefaultMessage "Expected the provided [datetime] to be before ( ago), but it was after: " + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -Data @{ ago = $Ago } -DefaultMessage "Expected the provided [datetime] to be before ( ago), but it was after: " throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } } diff --git a/src/functions/assert/Time/Should-BeFasterThan.ps1 b/src/functions/assert/Time/Should-BeFasterThan.ps1 index 89e518bf7..87418c4e1 100644 --- a/src/functions/assert/Time/Should-BeFasterThan.ps1 +++ b/src/functions/assert/Time/Should-BeFasterThan.ps1 @@ -39,7 +39,7 @@ function Assert-Faster { $sw.Stop() if ($sw.Elapsed -ge $Expected) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $sw.Elapsed -CustomMessage $CustomMessage -Data @{ scriptblock = $Actual } -DefaultMessage "Expected the provided [scriptblock] to execute faster than , but it took to run.`nScriptBlock: " + $Message = Get-AssertionMessage -Expected $Expected -Actual $sw.Elapsed -Because $Because -Data @{ scriptblock = $Actual } -DefaultMessage "Expected the provided [scriptblock] to execute faster than , but it took to run.`nScriptBlock: " throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } return @@ -47,7 +47,7 @@ function Assert-Faster { if ($Actual -is [timespan]) { if ($Actual -ge $Expected) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "The provided [timespan] should be shorter than , but it was longer: " + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "The provided [timespan] should be shorter than , but it was longer: " throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } return diff --git a/src/functions/assert/Time/Should-BeSlowerThan.ps1 b/src/functions/assert/Time/Should-BeSlowerThan.ps1 index b801f2fa0..df9cb8ed3 100644 --- a/src/functions/assert/Time/Should-BeSlowerThan.ps1 +++ b/src/functions/assert/Time/Should-BeSlowerThan.ps1 @@ -20,7 +20,7 @@ $sw.Stop() if ($sw.Elapsed -le $Expected) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $sw.Elapsed -CustomMessage $CustomMessage -Data @{ scriptblock = $Actual } -DefaultMessage "The provided [scriptblock] should execute slower than , but it took to run.`nScriptBlock: " + $Message = Get-AssertionMessage -Expected $Expected -Actual $sw.Elapsed -Because $Because -Data @{ scriptblock = $Actual } -DefaultMessage "The provided [scriptblock] should execute slower than , but it took to run.`nScriptBlock: " throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } return @@ -28,7 +28,7 @@ if ($Actual -is [timespan]) { if ($Actual -le $Expected) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -CustomMessage $CustomMessage -DefaultMessage "The provided [timespan] should be longer than , but it was shorter: " + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "The provided [timespan] should be longer than , but it was shorter: " throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } return diff --git a/test.ps1 b/test.ps1 index dcf295be2..989264ceb 100644 --- a/test.ps1 +++ b/test.ps1 @@ -75,9 +75,9 @@ if (-not $NoBuild) { } } -if ($CI -and ($SkipPTests -or $SkipPesterTests)) { - throw "Cannot skip tests in CI mode!" -} +# if ($CI -and ($SkipPTests -or $SkipPesterTests)) { +# throw "Cannot skip tests in CI mode!" +# } # remove pester because we will be reimporting it in multiple other places Get-Module Pester | Remove-Module @@ -183,8 +183,8 @@ if ($CI) { $configuration.Run.Exit = $true # not using code coverage, it is still very slow - $configuration.CodeCoverage.Enabled = $false - $configuration.CodeCoverage.Path = "$PSScriptRoot/src/*" + $configuration.CodeCoverage.Enabled = $true + $configuration.CodeCoverage.Path = "$PSScriptRoot/bin/*" # experimental, uses the Profiler based tracer to do code coverage without using breakpoints $configuration.CodeCoverage.UseBreakpoints = $false diff --git a/tst/functions/assert/Boolean/Should-BeFalse.Tests.ps1 b/tst/functions/assert/Boolean/Should-BeFalse.Tests.ps1 index 1366ec290..cb0f5b1c8 100644 --- a/tst/functions/assert/Boolean/Should-BeFalse.Tests.ps1 +++ b/tst/functions/assert/Boolean/Should-BeFalse.Tests.ps1 @@ -5,29 +5,23 @@ Describe "Should-BeFalse" { $false | Should-BeFalse } - It "Passes when given falsy value ''" -TestCases @( + It "Falis when given falsy value ''" -TestCases @( @{ Actual = 0 } @{ Actual = "" } @{ Actual = $null } @{ Actual = @() } ) { - param($Actual) - Should-BeFalse -Actual $Actual + { Should-BeFalse -Actual $Actual } | Verify-AssertionFailed } It "Fails for array input even if the last item is `$false" { { $true, $true, $false | Should-BeFalse } | Verify-AssertionFailed } - It "Fails with custom message" { - $err = { 9 | Should-BeFalse -CustomMessage " is not false" } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "9 is not false" - } - Context "Validate messages" { It "Given value '' that is not `$false it returns expected message ''" -TestCases @( - @{ Actual = $true ; Message = "Expected [bool] `$true to be [bool] `$false or falsy value 0, """", `$null, @()." }, - @{ Actual = 10 ; Message = "Expected [int] 10 to be [bool] `$false or falsy value 0, """", `$null, @()." } + @{ Actual = $true ; Message = "Expected [bool] `$false, but got: [bool] `$true." }, + @{ Actual = 10 ; Message = "Expected [bool] `$false, but got: [int] 10." } ) { $err = { Should-BeFalse -Actual $Actual } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message diff --git a/tst/functions/assert/Boolean/Should-BeFalsy.Tests.ps1 b/tst/functions/assert/Boolean/Should-BeFalsy.Tests.ps1 new file mode 100644 index 000000000..01f30533b --- /dev/null +++ b/tst/functions/assert/Boolean/Should-BeFalsy.Tests.ps1 @@ -0,0 +1,40 @@ +Set-StrictMode -Version Latest + +Describe "Should-BeFalsy" { + It "Passes when given `$false" { + $false | Should-BeFalsy + } + + It "Passes when given falsy value ''" -TestCases @( + @{ Actual = 0 } + @{ Actual = "" } + @{ Actual = $null } + @{ Actual = @() } + ) { + param($Actual) + Should-BeFalsy -Actual $Actual + } + + It "Fails for array input even if the last item is `$false" { + { $true, $true, $false | Should-BeFalsy } | Verify-AssertionFailed + } + + Context "Validate messages" { + It "Given value '' that is not `$false it returns expected message ''" -TestCases @( + @{ Actual = $true ; Message = "Expected [bool] `$false or a falsy value: 0, """", `$null or @(), but got: [bool] `$true." }, + @{ Actual = 10 ; Message = "Expected [bool] `$false or a falsy value: 0, """", `$null or @(), but got: [int] 10." } + ) { + $err = { Should-BeFalsy -Actual $Actual } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $Message + } + } + + It "Returns the value on output" { + $expected = $false + $expected | Should-BeFalsy | Verify-Equal $expected + } + + It "Can be called with positional parameters" { + { Should-BeFalsy $true } | Verify-AssertionFailed + } +} diff --git a/tst/functions/assert/Boolean/Should-BeTrue.Tests.ps1 b/tst/functions/assert/Boolean/Should-BeTrue.Tests.ps1 index 1f2c2f94b..3852bb318 100644 --- a/tst/functions/assert/Boolean/Should-BeTrue.Tests.ps1 +++ b/tst/functions/assert/Boolean/Should-BeTrue.Tests.ps1 @@ -5,27 +5,21 @@ Describe "Should-BeTrue" { $true | Should-BeTrue } - It "Passes when given truthy" -TestCases @( + It "Fails when given truthy value" -TestCases @( @{ Actual = 1 } @{ Actual = "text" } @{ Actual = New-Object -TypeName PSObject } @{ Actual = 1, 2 } + @{ Actual = "false" } ) { - param($Actual) - Should-BeTrue -Actual $Actual - } - - It "Fails with custom message" { - $err = { $null | Should-BeTrue -CustomMessage " is not true" } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "`$null is not true" + { Should-BeTrue -Actual $Actual } | Verify-AssertionFailed } Context "Validate messages" { It "Given value that is not `$true it returns expected message ''" -TestCases @( - @{ Actual = $false ; Message = "Expected [bool] `$false to be [bool] `$true or truthy value." }, - @{ Actual = 0 ; Message = "Expected [int] 0 to be [bool] `$true or truthy value." } + @{ Actual = $false ; Message = "Expected [bool] `$true, but got: [bool] `$false." }, + @{ Actual = 0 ; Message = "Expected [bool] `$true, but got: [int] 0." } ) { - param($Actual, $Message) $err = { Should-BeTrue -Actual $Actual } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message } diff --git a/tst/functions/assert/Boolean/Should-BeTruthy.Tests.ps1 b/tst/functions/assert/Boolean/Should-BeTruthy.Tests.ps1 new file mode 100644 index 000000000..446cf4fe2 --- /dev/null +++ b/tst/functions/assert/Boolean/Should-BeTruthy.Tests.ps1 @@ -0,0 +1,35 @@ +Set-StrictMode -Version Latest + +Describe "Should-BeTruthy" { + It "Passes when given `$true" { + $true | Should-BeTruthy + } + + It "Passes when given truthy" -TestCases @( + @{ Actual = 1 } + @{ Actual = "text" } + @{ Actual = New-Object -TypeName PSObject } + @{ Actual = 1, 2 } + ) { + Should-BeTruthy -Actual $Actual + } + + Context "Validate messages" { + It "Given value that is not `$true it returns expected message ''" -TestCases @( + @{ Actual = $false ; Message = "Expected [bool] `$true or a truthy value, but got: [bool] `$false." }, + @{ Actual = 0 ; Message = "Expected [bool] `$true or a truthy value, but got: [int] 0." } + ) { + $err = { Should-BeTruthy -Actual $Actual } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal $Message + } + } + + It "Returns the value on output" { + $expected = $true + $expected | Should-BeTruthy | Verify-Equal $expected + } + + It "Can be called with positional parameters" { + { Should-BeTruthy $false } | Verify-AssertionFailed + } +} diff --git a/tst/functions/assert/General/Should-Be.Tests.ps1 b/tst/functions/assert/General/Should-Be.Tests.ps1 index cd00ba2a3..7213dc8c0 100644 --- a/tst/functions/assert/General/Should-Be.Tests.ps1 +++ b/tst/functions/assert/General/Should-Be.Tests.ps1 @@ -58,11 +58,6 @@ Describe "Should-Be" { { 1, 2, 3 | Should-Be 3 } | Verify-AssertionFailed } - It "Fails with custom message" { - $err = { 9 | Should-Be 3 -CustomMessage " is not " } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "3 is not 9" - } - Context "Validate messages" { It "Given two values that are not the same '' and '' it returns expected message ''" -TestCases @( @{ Expected = "a" ; Actual = 10 ; Message = "Expected [string] 'a', but got [int] 10." }, diff --git a/tst/functions/assert/General/Should-BeGreaterThan.Tests.ps1 b/tst/functions/assert/General/Should-BeGreaterThan.Tests.ps1 index 18b8024eb..dfa1206e4 100644 --- a/tst/functions/assert/General/Should-BeGreaterThan.Tests.ps1 +++ b/tst/functions/assert/General/Should-BeGreaterThan.Tests.ps1 @@ -76,11 +76,6 @@ Describe "Should-BeGreaterThan" { $err.Exception | Verify-Type ([System.Management.Automation.RuntimeException]) } - It "Fails with custom message" { - $err = { 2 | Should-BeGreaterThan 3 -CustomMessage " is not greater than " } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "2 is not greater than 3" - } - Context "Validate messages" { It "Given two values '' and '' it returns expected message ''" -TestCases @( @{ Expected = "z" ; Actual = "a" ; Message = "Expected [string] 'a' to be greater than [string] 'z', but it was not." }, diff --git a/tst/functions/assert/General/Should-BeGreaterThanOrEqual.Tests.ps1 b/tst/functions/assert/General/Should-BeGreaterThanOrEqual.Tests.ps1 index e5d917782..ac37097f5 100644 --- a/tst/functions/assert/General/Should-BeGreaterThanOrEqual.Tests.ps1 +++ b/tst/functions/assert/General/Should-BeGreaterThanOrEqual.Tests.ps1 @@ -76,11 +76,6 @@ Describe "Should-BeGreaterThanOrEqual" { $err.Exception | Verify-Type ([System.Management.Automation.RuntimeException]) } - It "Fails with custom message" { - $err = { 2 | Should-BeGreaterThanOrEqual 3 -CustomMessage " is not greater than " } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "2 is not greater than 3" - } - Context "Validate messages" { It "Given two values '' and '' it returns expected message ''" -TestCases @( @{ Expected = "z" ; Actual = "a" ; Message = "Expected [string] 'a' to be greater than or equal to [string] 'z', but it was not." }, diff --git a/tst/functions/assert/General/Should-BeLessThan.Tests.ps1 b/tst/functions/assert/General/Should-BeLessThan.Tests.ps1 index f193c35d5..ec851a0ce 100644 --- a/tst/functions/assert/General/Should-BeLessThan.Tests.ps1 +++ b/tst/functions/assert/General/Should-BeLessThan.Tests.ps1 @@ -76,11 +76,6 @@ Describe "Should-BeLessThan" { $err.Exception | Verify-Type ([System.Management.Automation.RuntimeException]) } - It "Fails with custom message" { - $err = { 3 | Should-BeLessThan 2 -CustomMessage " is not less than " } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "3 is not less than 2" - } - Context "Validate messages" { It "Given two values '' and '' it returns expected message ''" -TestCases @( @{ Expected = "a" ; Actual = "z" ; Message = "Expected [string] 'z' to be less than [string] 'a', but it was not." }, diff --git a/tst/functions/assert/General/Should-BeLessThanOrEqual.Tests.ps1 b/tst/functions/assert/General/Should-BeLessThanOrEqual.Tests.ps1 index fabb29417..955d05e37 100644 --- a/tst/functions/assert/General/Should-BeLessThanOrEqual.Tests.ps1 +++ b/tst/functions/assert/General/Should-BeLessThanOrEqual.Tests.ps1 @@ -76,11 +76,6 @@ Describe "Should-BeLessThanOrEqual" { $err.Exception | Verify-Type ([System.Management.Automation.RuntimeException]) } - It "Fails with custom message" { - $err = { 3 | Should-BeLessThanOrEqual 2 -CustomMessage " is not less than " } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "3 is not less than 2" - } - Context "Validate messages" { It "Given two values '' and '' it returns expected message ''" -TestCases @( @{ Expected = "a" ; Actual = "z" ; Message = "Expected [string] 'z' to be less than or equal to [string] 'a', but it was not." }, diff --git a/tst/functions/assert/General/Should-BeSame.Tests.ps1 b/tst/functions/assert/General/Should-BeSame.Tests.ps1 index 00cbcc1a2..3e5e05d66 100644 --- a/tst/functions/assert/General/Should-BeSame.Tests.ps1 +++ b/tst/functions/assert/General/Should-BeSame.Tests.ps1 @@ -17,12 +17,6 @@ Describe "Should-BeSame" { { 1, 2, $object | Should-BeSame $object } | Verify-AssertionFailed } - It "Fails with custom message" { - $object = New-Object Diagnostics.Process - $err = { "text" | Should-BeSame $object -CustomMessage "'' is not ''" } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "'Diagnostics.Process{Id=`$null; Name=`$null}' is not ''text''" - } - It "Given two values that are not the same instance '' and '' it returns expected message ''" -TestCases @( @{ Expected = New-Object -TypeName PSObject ; Actual = New-Object -TypeName PSObject ; Message = "Expected [PSObject] 'PSObject{}', to be the same instance but it was not." } ) { diff --git a/tst/functions/assert/General/Should-NotBe.Tests.ps1 b/tst/functions/assert/General/Should-NotBe.Tests.ps1 index 804f29c10..0fcbe7313 100644 --- a/tst/functions/assert/General/Should-NotBe.Tests.ps1 +++ b/tst/functions/assert/General/Should-NotBe.Tests.ps1 @@ -58,11 +58,6 @@ Describe "Should-NotBe" { 1, 2, 3 | Should-NotBe 3 } - It "Fails with custom message" { - $err = { 3 | Should-NotBe 3 -CustomMessage " is " } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "3 is 3" - } - Context "Validate messages" { It "Given two values that are the same '' it returns expected message ''" -TestCases @( @{ Value = 1; Message = "Expected [int] 1, to be different than the actual value, but they were the same." } diff --git a/tst/functions/assert/General/Should-NotBeSame.Tests.ps1 b/tst/functions/assert/General/Should-NotBeSame.Tests.ps1 index da93e44e8..9ddd12ed8 100644 --- a/tst/functions/assert/General/Should-NotBeSame.Tests.ps1 +++ b/tst/functions/assert/General/Should-NotBeSame.Tests.ps1 @@ -17,12 +17,6 @@ Describe "Should-NotBeSame" { 1, 2, $object | Should-NotBeSame $object } - It "Fails with custom message" { - $object = 1 - $err = { $object | Should-NotBeSame $object -CustomMessage " is " } | Verify-AssertionFailed - $err.Exception.Message | Verify-Equal "1 is 1" - } - It "Given two values that are the same instance it returns expected message ''" -TestCases @( @{ Value = "a"; Message = "Expected [string] ''a'', to not be the same instance." } ) { diff --git a/tst/functions/assert/String/Assert-StringEqual.Tests.ps1 b/tst/functions/assert/String/Assert-StringEqual.Tests.ps1 deleted file mode 100644 index 92a2d8cd0..000000000 --- a/tst/functions/assert/String/Assert-StringEqual.Tests.ps1 +++ /dev/null @@ -1,126 +0,0 @@ -Set-StrictMode -Version Latest - -InPesterModuleScope { - Describe "Test-StringEqual" { - Context "Case insensitive matching" { - It "strings with the same values are equal" { - Test-StringEqual -Expected "abc" -Actual "abc" | Verify-True - } - - It "strings with different case and same values are equal. comparing '':''" -TestCases @( - @{l = "ABc"; r = "abc" }, - @{l = "aBc"; r = "abc" }, - @{l = "ABC"; r = "abc" } - ) { - param ($l, $r) - Test-StringEqual -Expected $l -Actual $r | Verify-True - } - - It "strings with different values are not equal" { - Test-StringEqual -Expected "abc" -Actual "def" | Verify-False - } - - It "strings with different case and different values are not equal. comparing '':''" -TestCases @( - @{l = "ABc"; r = "def" }, - @{l = "aBc"; r = "def" }, - @{l = "ABC"; r = "def" } - ) { - param ($l, $r) - Test-StringEqual -Expected $l -Actual $r | Verify-False - } - - It "strings from which one is sorrounded by whitespace are not equal. comparing '':''" -TestCases @( - @{l = "abc "; r = "abc" }, - @{l = "abc "; r = "abc" }, - @{l = "ab c"; r = "abc" } - ) { - param ($l, $r) - Test-StringEqual -Expected $l -Actual $r | Verify-False - } - } - - Context "Case sensitive matching" { - It "strings with different case but same values are not equal. comparing '':''" -TestCases @( - @{l = "ABc"; r = "abc" }, - @{l = "aBc"; r = "abc" }, - @{l = "ABC"; r = "abc" } - ) { - param ($l, $r) - Test-StringEqual -Expected $l -Actual $r -CaseSensitive | Verify-False - } - } - - Context "Case insensitive matching with ingoring whitespace" { - It "strings sorrounded or containing whitespace are equal. comparing '':''" -TestCases @( - @{l = "abc "; r = "abc" }, - @{l = "abc "; r = "abc" }, - @{l = "ab c"; r = "abc" }, - @{l = "ab c"; r = "a b c" } - ) { - param ($l, $r) - Test-StringEqual -Expected $l -Actual $r -IgnoreWhiteSpace | Verify-True - } - } - } - - Describe "Get-StringEqualDefaultFailureMessage" { - It "returns correct default message" { - $expected = "Expected the string to be 'abc' but got 'bde'." - $actual = Get-StringEqualDefaultFailureMessage -Expected "abc" -Actual "bde" - $actual | Verify-Equal $expected - } - } - - Describe "Assert-StringEqual" { - It "Does nothing when string are the same" { - Assert-StringEqual -Expected "abc" -Actual "abc" - } - - It "Throws when strings are different" { - { Assert-StringEqual -Expected "abc" -Actual "bde" } | Verify-AssertionFailed - } - - It "Throws with default message when test fails" { - $expected = Get-StringEqualDefaultFailureMessage -Expected "abc" -Actual "bde" - $exception = { Assert-StringEqual -Expected "abc" -Actual "bde" } | Verify-AssertionFailed - "$exception" | Verify-Equal $expected - } - - It "Throws with custom message when test fails" { - $customMessage = "Test failed becasue it expected '' but got ''. What a shame!" - $expected = Get-CustomFailureMessage -CustomMessage $customMessage -Expected "abc" -Actual "bde" - $exception = { Assert-StringEqual -Expected "abc" -Actual "bde" -CustomMessage $customMessage } | Verify-AssertionFailed - "$exception" | Verify-Equal $expected - } - - It "Allows actual to be passed from pipeline" { - "abc" | Assert-StringEqual -Expected "abc" - } - - It "Allows expected to be passed by position" { - Assert-StringEqual "abc" -Actual "abc" - } - - It "Allows actual to be passed by pipeline and expected by position" { - "abc" | Assert-StringEqual "abc" - } - - It "Fails when collection of strings is passed in by pipeline, even if the last string is the same as the expected string" { - { "bde", "abc" | Assert-StringEqual -Expected "abc" } | Verify-AssertionFailed - } - - Context "String specific features" { - It "Can compare strings in CaseSensitive mode" { - { Assert-StringEqual -Expected "ABC" -Actual "abc" -CaseSensitive } | Verify-AssertionFailed - } - - It "Can compare strings without whitespace" { - Assert-StringEqual -Expected " a b c " -Actual "abc" -IgnoreWhitespace - } - } - - It "Can be called with positional parameters" { - { Assert-StringEqual "a" "b" } | Verify-AssertionFailed - } - } -} diff --git a/tst/functions/assert/String/Should-BeString.Tests.ps1 b/tst/functions/assert/String/Should-BeString.Tests.ps1 new file mode 100644 index 000000000..f90ca04ce --- /dev/null +++ b/tst/functions/assert/String/Should-BeString.Tests.ps1 @@ -0,0 +1,110 @@ +Set-StrictMode -Version Latest + +InPesterModuleScope { + Describe "Test-StringEqual" { + Context "Type matching" { + It "Returns false for non-string" { + Test-StringEqual -Expected "1" -Actual 1 | Verify-False + } + } + Context "Case insensitive matching" { + It "strings with the same values are equal" { + Test-StringEqual -Expected "abc" -Actual "abc" | Verify-True + } + + It "strings with different case and same values are equal. comparing '':''" -TestCases @( + @{l = "ABc"; r = "abc" }, + @{l = "aBc"; r = "abc" }, + @{l = "ABC"; r = "abc" } + ) { + Test-StringEqual -Expected $l -Actual $r | Verify-True + } + + It "strings with different values are not equal" { + Test-StringEqual -Expected "abc" -Actual "def" | Verify-False + } + + It "strings with different case and different values are not equal. comparing '':''" -TestCases @( + @{l = "ABc"; r = "def" }, + @{l = "aBc"; r = "def" }, + @{l = "ABC"; r = "def" } + ) { + Test-StringEqual -Expected $l -Actual $r | Verify-False + } + + It "strings from which one is sorrounded by whitespace are not equal. comparing '':''" -TestCases @( + @{l = "abc "; r = "abc" }, + @{l = "abc "; r = "abc" }, + @{l = "ab c"; r = "abc" } + ) { + Test-StringEqual -Expected $l -Actual $r | Verify-False + } + } + + Context "Case sensitive matching" { + It "strings with different case but same values are not equal. comparing '':''" -TestCases @( + @{l = "ABc"; r = "abc" }, + @{l = "aBc"; r = "abc" }, + @{l = "ABC"; r = "abc" } + ) { + Test-StringEqual -Expected $l -Actual $r -CaseSensitive | Verify-False + } + } + + Context "Case insensitive matching with ingoring whitespace" { + It "strings sorrounded or containing whitespace are equal. comparing '':''" -TestCases @( + @{l = "abc "; r = "abc" }, + @{l = "abc "; r = "abc" }, + @{l = "ab c"; r = "abc" }, + @{l = "ab c"; r = "a b c" } + ) { + Test-StringEqual -Expected $l -Actual $r -IgnoreWhiteSpace | Verify-True + } + } + } +} + +Describe "Should-BeString" { + It "Does nothing when string are the same" { + Should-BeString -Expected "abc" -Actual "abc" + } + + It "Throws when strings are different" { + { Should-BeString -Expected "abc" -Actual "bde" } | Verify-AssertionFailed + } + + It "Allows actual to be passed from pipeline" { + "abc" | Should-BeString -Expected "abc" + } + + It "Allows expected to be passed by position" { + Should-BeString "abc" -Actual "abc" + } + + It "Allows actual to be passed by pipeline and expected by position" { + "abc" | Should-BeString "abc" + } + + It "Fails when collection of strings is passed in by pipeline, even if the last string is the same as the expected string" { + { "bde", "abc" | Should-BeString -Expected "abc" } | Verify-AssertionFailed + } + + Context "String specific features" { + It "Can compare strings in CaseSensitive mode" { + { Should-BeString -Expected "ABC" -Actual "abc" -CaseSensitive } | Verify-AssertionFailed + } + + It "Can compare strings without whitespace" { + Should-BeString -Expected " a b c " -Actual "abc" -IgnoreWhitespace + } + } + + It "Can be called with positional parameters" { + { Should-BeString "a" "b" } | Verify-AssertionFailed + } + + It "Throws with default message when test fails" { + $err = { Should-BeString -Expected "abc" -Actual "bde" } | Verify-AssertionFailed + $err.Exception.Message | Verify-Equal "Expected [string] 'abc', but got [string] 'bde'." + } +} diff --git a/tst/functions/assert/String/Should-NotBeString.Tests.ps1 b/tst/functions/assert/String/Should-NotBeString.Tests.ps1 index 81a033108..fe0bf97de 100644 --- a/tst/functions/assert/String/Should-NotBeString.Tests.ps1 +++ b/tst/functions/assert/String/Should-NotBeString.Tests.ps1 @@ -13,13 +13,6 @@ InPesterModuleScope { $exception = { Should-NotBeString -Expected "abc" -Actual "abc" } | Verify-AssertionFailed "$exception" | Verify-Equal $expected } - - It "Throws with custom message when test fails" { - $customMessage = "Test failed becasue it expected '' but got ''. What a shame!" - $expected = Get-CustomFailureMessage -CustomMessage $customMessage -Expected "abc" -Actual "abc" - $exception = { Should-NotBeString -Expected "abc" -Actual "abc" -CustomMessage $customMessage } | Verify-AssertionFailed - "$exception" | Verify-Equal $expected - } } } From 13307ca9cab3c37a5bd7415cd3149840711d74d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Fri, 3 May 2024 19:49:13 +0200 Subject: [PATCH 36/55] Fix messages --- .vscode/launch.json | 3 ++- .../General/Should-BeGreaterThanOrEqual.ps1 | 2 +- test.ps1 | 24 ++++++++++++------- .../General/Should-BeGreaterThan.Tests.ps1 | 6 ++--- .../Should-BeGreaterThanOrEqual.Tests.ps1 | 6 ++--- .../General/Should-BeLessThan.Tests.ps1 | 6 ++--- .../Should-BeLessThanOrEqual.Tests.ps1 | 6 ++--- .../assert/General/Should-BeSame.Tests.ps1 | 2 +- .../assert/General/Should-NotBe.Tests.ps1 | 2 +- .../assert/General/Should-NotBeSame.Tests.ps1 | 3 +-- 10 files changed, 33 insertions(+), 27 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index ad1914f88..4730820e1 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -18,7 +18,8 @@ "script": "${workspaceFolder}/test.ps1", "args": [ "-File", - "${file}" + "${file}", + "-VSCode" ] }, { diff --git a/src/functions/assert/General/Should-BeGreaterThanOrEqual.ps1 b/src/functions/assert/General/Should-BeGreaterThanOrEqual.ps1 index bb70b4fa2..6d6f4f73c 100644 --- a/src/functions/assert/General/Should-BeGreaterThanOrEqual.ps1 +++ b/src/functions/assert/General/Should-BeGreaterThanOrEqual.ps1 @@ -11,7 +11,7 @@ $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if ((Ensure-ExpectedIsNotCollection $Expected) -gt $Actual) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected actual value to be greater than or equal to , but it was not. Actual: " + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected the actual value to be greater than or equal to , but it was not. Actual: " throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/test.ps1 b/test.ps1 index 989264ceb..be831ffb5 100644 --- a/test.ps1 +++ b/test.ps1 @@ -32,6 +32,9 @@ done, but makes local debugging difficult. When -CI is used, inlining is forced. + .PARAMETER VSCode + Set when calling from VSCode laucher file so we automatically figure out + what to run or what to skip. .NOTES Tests are excluded with Tags VersionChecks, StyleRules, Help. #> @@ -43,6 +46,7 @@ param ( [switch] $SkipPesterTests, [switch] $NoBuild, [switch] $Inline, + [switch] $VSCode, [string[]] $File = @() ) @@ -53,17 +57,19 @@ $ErrorView = "NormalView" "Using PS: $($PsVersionTable.PSVersion)" "In path: $($pwd.Path)" -# Detect which tests to skip from the filenames. -$anyFile = 0 -lt $File.Count -$anyPesterTests = [bool]@($File | Where-Object { $_ -like "*.Tests.ps1" }) -$anyPTests = [bool]@($File | Where-Object { $_ -like "*.ts.ps1" }) +if ($VSCode) { + # Detect which tests to skip from the filenames. + $anyFile = 0 -lt $File.Count + $anyPesterTests = [bool]@($File | Where-Object { $_ -like "*.Tests.ps1" }) + $anyPTests = [bool]@($File | Where-Object { $_ -like "*.ts.ps1" }) -if ($SkipPTests -or ($anyFile -and -not $anyPTests)) { - $SkipPTests = $true -} + if ($SkipPTests -or ($anyFile -and -not $anyPTests)) { + $SkipPTests = $true + } -if ($SkipPesterTests -or ($anyFile -and -not $anyPesterTests)) { - $SkipPesterTests = $true + if ($SkipPesterTests -or ($anyFile -and -not $anyPesterTests)) { + $SkipPesterTests = $true + } } if (-not $NoBuild) { diff --git a/tst/functions/assert/General/Should-BeGreaterThan.Tests.ps1 b/tst/functions/assert/General/Should-BeGreaterThan.Tests.ps1 index dfa1206e4..f260644fe 100644 --- a/tst/functions/assert/General/Should-BeGreaterThan.Tests.ps1 +++ b/tst/functions/assert/General/Should-BeGreaterThan.Tests.ps1 @@ -78,9 +78,9 @@ Describe "Should-BeGreaterThan" { Context "Validate messages" { It "Given two values '' and '' it returns expected message ''" -TestCases @( - @{ Expected = "z" ; Actual = "a" ; Message = "Expected [string] 'a' to be greater than [string] 'z', but it was not." }, - @{ Expected = 10.1 ; Actual = 1.1 ; Message = "Expected [double] 1.1 to be greater than [double] 10.1, but it was not." }, - @{ Expected = 10.1D ; Actual = 1.1D ; Message = "Expected [decimal] 1.1 to be greater than [decimal] 10.1, but it was not." } + @{ Expected = "z" ; Actual = "a" ; Message = "Expected the actual value to be greater than [string] 'z', but it was not. Actual: [string] 'a'" }, + @{ Expected = 10.1 ; Actual = 1.1 ; Message = "Expected the actual value to be greater than [double] 10.1, but it was not. Actual: [double] 1.1" }, + @{ Expected = 10.1D ; Actual = 1.1D ; Message = "Expected the actual value to be greater than [decimal] 10.1, but it was not. Actual: [decimal] 1.1" } ) { $err = { Should-BeGreaterThan -Actual $Actual -Expected $Expected } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message diff --git a/tst/functions/assert/General/Should-BeGreaterThanOrEqual.Tests.ps1 b/tst/functions/assert/General/Should-BeGreaterThanOrEqual.Tests.ps1 index ac37097f5..6868c0dbd 100644 --- a/tst/functions/assert/General/Should-BeGreaterThanOrEqual.Tests.ps1 +++ b/tst/functions/assert/General/Should-BeGreaterThanOrEqual.Tests.ps1 @@ -78,9 +78,9 @@ Describe "Should-BeGreaterThanOrEqual" { Context "Validate messages" { It "Given two values '' and '' it returns expected message ''" -TestCases @( - @{ Expected = "z" ; Actual = "a" ; Message = "Expected [string] 'a' to be greater than or equal to [string] 'z', but it was not." }, - @{ Expected = 10.1 ; Actual = 1.1 ; Message = "Expected [double] 1.1 to be greater than or equal to [double] 10.1, but it was not." }, - @{ Expected = 10.1D ; Actual = 1.1D ; Message = "Expected [decimal] 1.1 to be greater than or equal to [decimal] 10.1, but it was not." } + @{ Expected = "z" ; Actual = "a" ; Message = "Expected the actual value to be greater than or equal to [string] 'z', but it was not. Actual: [string] 'a'" }, + @{ Expected = 10.1 ; Actual = 1.1 ; Message = "Expected the actual value to be greater than or equal to [double] 10.1, but it was not. Actual: [double] 1.1" }, + @{ Expected = 10.1D ; Actual = 1.1D ; Message = "Expected the actual value to be greater than or equal to [decimal] 10.1, but it was not. Actual: [decimal] 1.1" } ) { $err = { Should-BeGreaterThanOrEqual -Actual $Actual -Expected $Expected } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message diff --git a/tst/functions/assert/General/Should-BeLessThan.Tests.ps1 b/tst/functions/assert/General/Should-BeLessThan.Tests.ps1 index ec851a0ce..382ba0d6a 100644 --- a/tst/functions/assert/General/Should-BeLessThan.Tests.ps1 +++ b/tst/functions/assert/General/Should-BeLessThan.Tests.ps1 @@ -78,9 +78,9 @@ Describe "Should-BeLessThan" { Context "Validate messages" { It "Given two values '' and '' it returns expected message ''" -TestCases @( - @{ Expected = "a" ; Actual = "z" ; Message = "Expected [string] 'z' to be less than [string] 'a', but it was not." }, - @{ Expected = 1.1 ; Actual = 10.1 ; Message = "Expected [double] 10.1 to be less than [double] 1.1, but it was not." }, - @{ Expected = 1.1D ; Actual = 10.1D ; Message = "Expected [decimal] 10.1 to be less than [decimal] 1.1, but it was not." } + @{ Expected = "a" ; Actual = "z" ; Message = "Expected the actual value to be less than [string] 'a', but it was not. Actual: [string] 'z'" }, + @{ Expected = 1.1 ; Actual = 10.1 ; Message = "Expected the actual value to be less than [double] 1.1, but it was not. Actual: [double] 10.1" }, + @{ Expected = 1.1D ; Actual = 10.1D ; Message = "Expected the actual value to be less than [decimal] 1.1, but it was not. Actual: [decimal] 10.1" } ) { $err = { Should-BeLessThan -Actual $Actual -Expected $Expected } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message diff --git a/tst/functions/assert/General/Should-BeLessThanOrEqual.Tests.ps1 b/tst/functions/assert/General/Should-BeLessThanOrEqual.Tests.ps1 index 955d05e37..754eb2ced 100644 --- a/tst/functions/assert/General/Should-BeLessThanOrEqual.Tests.ps1 +++ b/tst/functions/assert/General/Should-BeLessThanOrEqual.Tests.ps1 @@ -78,9 +78,9 @@ Describe "Should-BeLessThanOrEqual" { Context "Validate messages" { It "Given two values '' and '' it returns expected message ''" -TestCases @( - @{ Expected = "a" ; Actual = "z" ; Message = "Expected [string] 'z' to be less than or equal to [string] 'a', but it was not." }, - @{ Expected = 1.1 ; Actual = 10.1 ; Message = "Expected [double] 10.1 to be less than or equal to [double] 1.1, but it was not." }, - @{ Expected = 1.1D ; Actual = 10.1D ; Message = "Expected [decimal] 10.1 to be less than or equal to [decimal] 1.1, but it was not." } + @{ Expected = "a" ; Actual = "z" ; Message = "Expected the actual value to be less than or equal to [string] 'a', but it was not. Actual: [string] 'z'" }, + @{ Expected = 1.1 ; Actual = 10.1 ; Message = "Expected the actual value to be less than or equal to [double] 1.1, but it was not. Actual: [double] 10.1" }, + @{ Expected = 1.1D ; Actual = 10.1D ; Message = "Expected the actual value to be less than or equal to [decimal] 1.1, but it was not. Actual: [decimal] 10.1" } ) { $err = { Should-BeLessThanOrEqual -Actual $Actual -Expected $Expected } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message diff --git a/tst/functions/assert/General/Should-BeSame.Tests.ps1 b/tst/functions/assert/General/Should-BeSame.Tests.ps1 index 3e5e05d66..a49a342ab 100644 --- a/tst/functions/assert/General/Should-BeSame.Tests.ps1 +++ b/tst/functions/assert/General/Should-BeSame.Tests.ps1 @@ -18,7 +18,7 @@ Describe "Should-BeSame" { } It "Given two values that are not the same instance '' and '' it returns expected message ''" -TestCases @( - @{ Expected = New-Object -TypeName PSObject ; Actual = New-Object -TypeName PSObject ; Message = "Expected [PSObject] 'PSObject{}', to be the same instance but it was not." } + @{ Expected = New-Object -TypeName PSObject ; Actual = New-Object -TypeName PSObject ; Message = "Expected [PSObject] PSObject{}, to be the same instance but it was not. Actual: [PSObject] PSObject{}" } ) { $err = { Should-BeSame -Actual $Actual -Expected $Expected } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message diff --git a/tst/functions/assert/General/Should-NotBe.Tests.ps1 b/tst/functions/assert/General/Should-NotBe.Tests.ps1 index 0fcbe7313..c03f28826 100644 --- a/tst/functions/assert/General/Should-NotBe.Tests.ps1 +++ b/tst/functions/assert/General/Should-NotBe.Tests.ps1 @@ -60,7 +60,7 @@ Describe "Should-NotBe" { Context "Validate messages" { It "Given two values that are the same '' it returns expected message ''" -TestCases @( - @{ Value = 1; Message = "Expected [int] 1, to be different than the actual value, but they were the same." } + @{ Value = 1; Message = "Expected [int] 1, to be different than the actual value, but they were equal." } ) { param($Value, $Message) $err = { Should-NotBe -Actual $Value -Expected $Value } | Verify-AssertionFailed diff --git a/tst/functions/assert/General/Should-NotBeSame.Tests.ps1 b/tst/functions/assert/General/Should-NotBeSame.Tests.ps1 index 9ddd12ed8..c099146f7 100644 --- a/tst/functions/assert/General/Should-NotBeSame.Tests.ps1 +++ b/tst/functions/assert/General/Should-NotBeSame.Tests.ps1 @@ -18,9 +18,8 @@ Describe "Should-NotBeSame" { } It "Given two values that are the same instance it returns expected message ''" -TestCases @( - @{ Value = "a"; Message = "Expected [string] ''a'', to not be the same instance." } + @{ Value = "a"; Message = "Expected [string] 'a', to not be the same instance." } ) { - param($Value, $Message) $err = { Should-NotBeSame -Actual $Value -Expected $Value } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message } From ab36078d634dd2fb805a89b1daa72f90d3c6e47e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Fri, 3 May 2024 20:00:36 +0200 Subject: [PATCH 37/55] Fix more messages --- src/functions/assert/General/Should-Be.ps1 | 2 +- .../General/Should-BeGreaterThanOrEqual.ps1 | 2 +- .../assert/General/Should-BeLessThan.ps1 | 2 +- .../General/Should-BeLessThanOrEqual.ps1 | 2 +- .../assert/General/Should-BeNull.ps1 | 2 +- .../assert/General/Should-BeSame.ps1 | 2 +- .../assert/General/Should-HaveType.ps1 | 2 +- src/functions/assert/General/Should-NotBe.ps1 | 2 +- .../assert/General/Should-NotBeNull.ps1 | 2 +- .../assert/General/Should-NotBeSame.ps1 | 2 +- .../assert/General/Should-NotHaveType.ps1 | 2 +- .../assert/General/ShouldBe-GreaterThan.ps1 | 2 +- .../assert/String/Should-BeLikeString.ps1 | 20 ++++++------------- .../String/Should-BeWhiteSpaceString.ps1 | 3 --- src/functions/assert/Time/Should-BeAfter.ps1 | 2 +- src/functions/assert/Time/Should-BeBefore.ps1 | 2 +- .../assert/General/Should-NotBeSame.Tests.ps1 | 2 +- .../String/Should-BeLikeString.Tests.ps1 | 12 +++++------ 18 files changed, 27 insertions(+), 38 deletions(-) delete mode 100644 src/functions/assert/String/Should-BeWhiteSpaceString.ps1 diff --git a/src/functions/assert/General/Should-Be.ps1 b/src/functions/assert/General/Should-Be.ps1 index dbeb9324b..d3ed673af 100644 --- a/src/functions/assert/General/Should-Be.ps1 +++ b/src/functions/assert/General/Should-Be.ps1 @@ -12,7 +12,7 @@ $Actual = $collectedInput.Actual if ((Ensure-ExpectedIsNotCollection $Expected) -ne $Actual) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected , but got ." + $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/src/functions/assert/General/Should-BeGreaterThanOrEqual.ps1 b/src/functions/assert/General/Should-BeGreaterThanOrEqual.ps1 index 6d6f4f73c..60c249db8 100644 --- a/src/functions/assert/General/Should-BeGreaterThanOrEqual.ps1 +++ b/src/functions/assert/General/Should-BeGreaterThanOrEqual.ps1 @@ -11,7 +11,7 @@ $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if ((Ensure-ExpectedIsNotCollection $Expected) -gt $Actual) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected the actual value to be greater than or equal to , but it was not. Actual: " + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected the actual value to be greater than or equal to , but it was not. Actual: " throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Should-BeLessThan.ps1 b/src/functions/assert/General/Should-BeLessThan.ps1 index f30c29d84..32b1b6ec8 100644 --- a/src/functions/assert/General/Should-BeLessThan.ps1 +++ b/src/functions/assert/General/Should-BeLessThan.ps1 @@ -11,7 +11,7 @@ $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if ((Ensure-ExpectedIsNotCollection $Expected) -le $Actual) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected the actual value to be less than , but it was not. Actual: " + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected the actual value to be less than , but it was not. Actual: " throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Should-BeLessThanOrEqual.ps1 b/src/functions/assert/General/Should-BeLessThanOrEqual.ps1 index 81d2f5d79..966587563 100644 --- a/src/functions/assert/General/Should-BeLessThanOrEqual.ps1 +++ b/src/functions/assert/General/Should-BeLessThanOrEqual.ps1 @@ -11,7 +11,7 @@ $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if ((Ensure-ExpectedIsNotCollection $Expected) -lt $Actual) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected the actual value to be less than or equal to , but it was not. Actual: " + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected the actual value to be less than or equal to , but it was not. Actual: " throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Should-BeNull.ps1 b/src/functions/assert/General/Should-BeNull.ps1 index c2b460c4b..5eb1b2f15 100644 --- a/src/functions/assert/General/Should-BeNull.ps1 +++ b/src/functions/assert/General/Should-BeNull.ps1 @@ -9,7 +9,7 @@ $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if ($null -ne $Actual) { - $Message = Get-AssertionMessage -Expected $null -Actual $Actual -Because $Because -DefaultMessage "Expected `$null, but got ''." + $Message = Get-AssertionMessage -Expected $null -Actual $Actual -Because $Because -DefaultMessage "Expected `$null, but got ''." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Should-BeSame.ps1 b/src/functions/assert/General/Should-BeSame.ps1 index a203af333..1aecc2cf3 100644 --- a/src/functions/assert/General/Should-BeSame.ps1 +++ b/src/functions/assert/General/Should-BeSame.ps1 @@ -15,7 +15,7 @@ $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if (-not ([object]::ReferenceEquals($Expected, $Actual))) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected , to be the same instance but it was not. Actual: " + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected , to be the same instance but it was not. Actual: " throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Should-HaveType.ps1 b/src/functions/assert/General/Should-HaveType.ps1 index 6f2bec046..9a4be14db 100644 --- a/src/functions/assert/General/Should-HaveType.ps1 +++ b/src/functions/assert/General/Should-HaveType.ps1 @@ -11,7 +11,7 @@ $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if ($Actual -isnot $Expected) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected value to have type , but got ." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected value to have type , but got ." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Should-NotBe.ps1 b/src/functions/assert/General/Should-NotBe.ps1 index 174de0650..1eab1c905 100644 --- a/src/functions/assert/General/Should-NotBe.ps1 +++ b/src/functions/assert/General/Should-NotBe.ps1 @@ -11,7 +11,7 @@ $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if ((Ensure-ExpectedIsNotCollection $Expected) -eq $Actual) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected , to be different than the actual value, but they were equal." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected , to be different than the actual value, but they were equal." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Should-NotBeNull.ps1 b/src/functions/assert/General/Should-NotBeNull.ps1 index 26288c6e9..fb3ee929a 100644 --- a/src/functions/assert/General/Should-NotBeNull.ps1 +++ b/src/functions/assert/General/Should-NotBeNull.ps1 @@ -9,7 +9,7 @@ $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if ($null -eq $Actual) { - $Message = Get-AssertionMessage -Expected $null -Actual $Actual -Because $Because -DefaultMessage "Expected not `$null, but got `$null." + $Message = Get-AssertionMessage -Expected $null -Actual $Actual -Because $Because -DefaultMessage "Expected not `$null, but got `$null." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Should-NotBeSame.ps1 b/src/functions/assert/General/Should-NotBeSame.ps1 index d50fb9e37..004cda257 100644 --- a/src/functions/assert/General/Should-NotBeSame.ps1 +++ b/src/functions/assert/General/Should-NotBeSame.ps1 @@ -11,7 +11,7 @@ $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if ([object]::ReferenceEquals($Expected, $Actual)) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected , to not be the same instance." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected , to not be the same instance, but they were the same instance." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/Should-NotHaveType.ps1 b/src/functions/assert/General/Should-NotHaveType.ps1 index 494a229db..c83b9509f 100644 --- a/src/functions/assert/General/Should-NotHaveType.ps1 +++ b/src/functions/assert/General/Should-NotHaveType.ps1 @@ -11,7 +11,7 @@ $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if ($Actual -is $Expected) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected value to be of different type than , but got ." + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected value to be of different type than , but got ." throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/General/ShouldBe-GreaterThan.ps1 b/src/functions/assert/General/ShouldBe-GreaterThan.ps1 index 544d46bf6..ad5b25db2 100644 --- a/src/functions/assert/General/ShouldBe-GreaterThan.ps1 +++ b/src/functions/assert/General/ShouldBe-GreaterThan.ps1 @@ -11,7 +11,7 @@ $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput $Actual = $collectedInput.Actual if ((Ensure-ExpectedIsNotCollection $Expected) -ge $Actual) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected the actual value to be greater than , but it was not. Actual: " + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected the actual value to be greater than , but it was not. Actual: " throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } diff --git a/src/functions/assert/String/Should-BeLikeString.ps1 b/src/functions/assert/String/Should-BeLikeString.ps1 index dddea4374..d1d0cd47e 100644 --- a/src/functions/assert/String/Should-BeLikeString.ps1 +++ b/src/functions/assert/String/Should-BeLikeString.ps1 @@ -13,14 +13,6 @@ } } -function Get-LikeDefaultFailureMessage ([String]$Expected, $Actual, [switch]$CaseSensitive) { - $caseSensitiveMessage = "" - if ($CaseSensitive) { - $caseSensitiveMessage = " case sensitively" - } - "Expected the string '$Actual' to$caseSensitiveMessage match '$Expected' but it did not." -} - function Assert-Like { [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( @@ -41,12 +33,12 @@ function Assert-Like { $stringsAreAlike = Test-Like -Expected $Expected -Actual $Actual -CaseSensitive:$CaseSensitive -IgnoreWhitespace:$IgnoreWhiteSpace if (-not ($stringsAreAlike)) { - if (-not $CustomMessage) { - $formattedMessage = Get-LikeDefaultFailureMessage -Expected $Expected -Actual $Actual -CaseSensitive:$CaseSensitive + $caseSensitiveMessage = "" + if ($CaseSensitive) { + $caseSensitiveMessage = " case sensitively" } - else { - $formattedMessage = Get-CustomFailureMessage -Expected $Expected -Actual $Actual -Because $Because -CaseSensitive:$CaseSensitive - } - throw [Pester.Factory]::CreateShouldErrorRecord($formattedMessage, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) + + $Message = Get-AssertionMessage -Expected $null -Actual $Actual -Because $Because -DefaultMessage "Expected the string '$Actual' to$caseSensitiveMessage be like '$Expected', but it did not." + throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } } diff --git a/src/functions/assert/String/Should-BeWhiteSpaceString.ps1 b/src/functions/assert/String/Should-BeWhiteSpaceString.ps1 deleted file mode 100644 index b465823dd..000000000 --- a/src/functions/assert/String/Should-BeWhiteSpaceString.ps1 +++ /dev/null @@ -1,3 +0,0 @@ -function Test-StringNotWhiteSpace ($Actual) { - $Actual -is [string] -and -not ([string]::IsNullOrWhiteSpace($Actual)) -} diff --git a/src/functions/assert/Time/Should-BeAfter.ps1 b/src/functions/assert/Time/Should-BeAfter.ps1 index 174b4d463..b1e0050d0 100644 --- a/src/functions/assert/Time/Should-BeAfter.ps1 +++ b/src/functions/assert/Time/Should-BeAfter.ps1 @@ -45,7 +45,7 @@ } if ($Actual -le $Expected) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected the provided [datetime] to be after , but it was before: " + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected the provided [datetime] to be after , but it was before: " throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } } diff --git a/src/functions/assert/Time/Should-BeBefore.ps1 b/src/functions/assert/Time/Should-BeBefore.ps1 index 452bd71cd..5388f79d1 100644 --- a/src/functions/assert/Time/Should-BeBefore.ps1 +++ b/src/functions/assert/Time/Should-BeBefore.ps1 @@ -45,7 +45,7 @@ } if ($Actual -ge $Expected) { - $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -Data @{ ago = $Ago } -DefaultMessage "Expected the provided [datetime] to be before ( ago), but it was after: " + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected the provided [datetime] to be before , but it was after: " throw [Pester.Factory]::CreateShouldErrorRecord($Message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } } diff --git a/tst/functions/assert/General/Should-NotBeSame.Tests.ps1 b/tst/functions/assert/General/Should-NotBeSame.Tests.ps1 index c099146f7..4310c614d 100644 --- a/tst/functions/assert/General/Should-NotBeSame.Tests.ps1 +++ b/tst/functions/assert/General/Should-NotBeSame.Tests.ps1 @@ -18,7 +18,7 @@ Describe "Should-NotBeSame" { } It "Given two values that are the same instance it returns expected message ''" -TestCases @( - @{ Value = "a"; Message = "Expected [string] 'a', to not be the same instance." } + @{ Value = "a"; Message = "Expected [string] 'a', to not be the same instance, but they were the same instance." } ) { $err = { Should-NotBeSame -Actual $Value -Expected $Value } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Message diff --git a/tst/functions/assert/String/Should-BeLikeString.Tests.ps1 b/tst/functions/assert/String/Should-BeLikeString.Tests.ps1 index 2bd962312..6707b096b 100644 --- a/tst/functions/assert/String/Should-BeLikeString.Tests.ps1 +++ b/tst/functions/assert/String/Should-BeLikeString.Tests.ps1 @@ -117,9 +117,9 @@ Describe "Should-BeLikeString" { Context "Verify messages" { It "Given two values that are not alike '' and '' it returns the correct message ''" -TestCases @( - @{ Actual = 'a'; Expected = 'b'; Message = "Expected the string 'a' to match 'b' but it did not." } - @{ Actual = 'ab'; Expected = 'd*'; Message = "Expected the string 'ab' to match 'd*' but it did not." } - @{ Actual = 'something'; Expected = '*abc*'; Message = "Expected the string 'something' to match '*abc*' but it did not." } + @{ Actual = 'a'; Expected = 'b'; Message = "Expected the string 'a' to be like 'b', but it did not." } + @{ Actual = 'ab'; Expected = 'd*'; Message = "Expected the string 'ab' to be like 'd*', but it did not." } + @{ Actual = 'something'; Expected = '*abc*'; Message = "Expected the string 'something' to be like '*abc*', but it did not." } ) { param ($Actual, $Expected, $Message) $err = { Should-BeLikeString -Actual $Actual -Expected $Expected } | Verify-AssertionFailed @@ -127,9 +127,9 @@ Describe "Should-BeLikeString" { } It "Given two values that are not alike becuase of case '' and '' it returns the correct message ''" -TestCases @( - @{ Actual = 'a'; Expected = 'B'; Message = "Expected the string 'a' to case sensitively match 'B' but it did not." } - @{ Actual = 'ab'; Expected = 'B*'; Message = "Expected the string 'ab' to case sensitively match 'B*' but it did not." } - @{ Actual = 'something'; Expected = '*SOME*'; Message = "Expected the string 'something' to case sensitively match '*SOME*' but it did not." } + @{ Actual = 'a'; Expected = 'B'; Message = "Expected the string 'a' to case sensitively be like 'B', but it did not." } + @{ Actual = 'ab'; Expected = 'B*'; Message = "Expected the string 'ab' to case sensitively be like 'B*', but it did not." } + @{ Actual = 'something'; Expected = '*SOME*'; Message = "Expected the string 'something' to case sensitively be like '*SOME*', but it did not." } ) { param ($Actual, $Expected, $Message) $err = { Should-BeLikeString -Actual $Actual -Expected $Expected -CaseSensitive } | Verify-AssertionFailed From a1f283c1d94331f7ea8a0a593a03a1dae805f2e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Fri, 3 May 2024 20:54:10 +0200 Subject: [PATCH 38/55] Little bit of help --- .../assert/Boolean/Should-BeFalse.ps1 | 32 +++++++++++++- .../assert/Boolean/Should-BeFalsy.ps1 | 32 +++++++++++++- .../assert/Boolean/Should-BeTrue.ps1 | 32 +++++++++++++- .../assert/Boolean/Should-BeTruthy.ps1 | 33 +++++++++++++- .../assert/Collection/Should-All.ps1 | 30 +++++++++++++ .../assert/Collection/Should-Any.ps1 | 30 +++++++++++++ .../assert/Collection/Should-BeCollection.ps1 | 33 ++++++++++++++ .../Collection/Should-ContainCollection.ps1 | 31 +++++++++++++ .../Should-NotContainCollection.ps1 | 31 +++++++++++++ src/functions/assert/Common/Collect-Input.ps1 | 10 +++-- .../assert/Exception/Should-Throw.ps1 | 43 +++++++++++++++++++ .../Collection/Should-BeCollection.Tests.ps1 | 3 -- 12 files changed, 329 insertions(+), 11 deletions(-) diff --git a/src/functions/assert/Boolean/Should-BeFalse.ps1 b/src/functions/assert/Boolean/Should-BeFalse.ps1 index 37ee2f8f1..bd2f7bb8f 100644 --- a/src/functions/assert/Boolean/Should-BeFalse.ps1 +++ b/src/functions/assert/Boolean/Should-BeFalse.ps1 @@ -1,4 +1,34 @@ function Assert-False { + <# + .SYNOPSIS + Compares the actual value to a boolean $false. It does not convert input values to boolean, and will fail for any value that is not $false. + + .PARAMETER Actual + The actual value to compare to $false. + + .PARAMETER Because + The reason why the input should be the expected value. + + .EXAMPLE + ```powershell + $false | Should-BeFalse + ``` + + This assertion will pass. + + .EXAMPLE + ```powershell + $true | Should-BeFalse + Get-Process | Should-BeFalse + $null | Should-BeFalse + $() | Should-BeFalse + @() | Should-BeFalse + 0 | Should-BeFalse + ``` + + All of these assertions will fail, because the actual value is not $false. + + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(ValueFromPipeline = $true)] @@ -6,7 +36,7 @@ [String]$Because ) - $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput $Actual = $collectedInput.Actual if ($Actual -isnot [bool] -or $Actual) { $Message = Get-AssertionMessage -Expected $false -Actual $Actual -Because $Because -DefaultMessage "Expected , but got: ." diff --git a/src/functions/assert/Boolean/Should-BeFalsy.ps1 b/src/functions/assert/Boolean/Should-BeFalsy.ps1 index 974d3885f..f6bc4ee4f 100644 --- a/src/functions/assert/Boolean/Should-BeFalsy.ps1 +++ b/src/functions/assert/Boolean/Should-BeFalsy.ps1 @@ -1,4 +1,34 @@ function Assert-Falsy { + <# + .SYNOPSIS + Compares the actual value to a boolean $false or a falsy value: 0, "", $null or @(). It converts the input value to a boolean. + + .PARAMETER Actual + The actual value to compare to $false. + + .PARAMETER Because + The reason why the input should be the expected value. + + .EXAMPLE + ```powershell + $false | Should-BeFalsy + $null | Should-BeFalsy + $() | Should-BeFalsy + @() | Should-BeFalsy + 0 | Should-BeFalsy + ``` + + These assertion will pass. + + .EXAMPLE + ```powershell + $true | Should-BeFalsy + Get-Process | Should-BeFalsy + ``` + + These assertions will fail, because the actual value is not $false or falsy. + + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(ValueFromPipeline = $true)] @@ -6,7 +36,7 @@ [String]$Because ) - $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput $Actual = $collectedInput.Actual if ($Actual) { $Message = Get-AssertionMessage -Expected $false -Actual $Actual -Because $Because -DefaultMessage 'Expected or a falsy value: 0, "", $null or @(), but got: .' diff --git a/src/functions/assert/Boolean/Should-BeTrue.ps1 b/src/functions/assert/Boolean/Should-BeTrue.ps1 index 7eeaf84b1..02f2f3617 100644 --- a/src/functions/assert/Boolean/Should-BeTrue.ps1 +++ b/src/functions/assert/Boolean/Should-BeTrue.ps1 @@ -1,4 +1,34 @@ function Assert-True { + <# + .SYNOPSIS + Compares the actual value to a boolean $true. It does not convert input values to boolean, and will fail for any value is not $true. + + .PARAMETER Actual + The actual value to compare to $true. + + .PARAMETER Because + The reason why the input should be the expected value. + + .EXAMPLE + ```powershell + $true | Should-BeTrue + ``` + + This assertion will pass. + + .EXAMPLE + ```powershell + $false | Should-BeTrue + Get-Process | Should-BeTrue + $null | Should-BeTrue + $() | Should-BeTrue + @() | Should-BeTrue + 0 | Should-BeTrue + ``` + + All of these assertions will fail, because the actual value is not $true. + + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(ValueFromPipeline = $true)] @@ -6,7 +36,7 @@ [String]$Because ) - $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput $Actual = $collectedInput.Actual if ($Actual -isnot [bool] -or -not $Actual) { $Message = Get-AssertionMessage -Expected $true -Actual $Actual -Because $Because -DefaultMessage "Expected , but got: ." diff --git a/src/functions/assert/Boolean/Should-BeTruthy.ps1 b/src/functions/assert/Boolean/Should-BeTruthy.ps1 index 71232122c..d70348756 100644 --- a/src/functions/assert/Boolean/Should-BeTruthy.ps1 +++ b/src/functions/assert/Boolean/Should-BeTruthy.ps1 @@ -1,4 +1,35 @@ function Assert-Truthy { + <# + .SYNOPSIS + Compares the actual value to a boolean $true. It converts input values to boolean, and will fail for any value is not $true, or truthy. + + .PARAMETER Actual + The actual value to compare to $true. + + .PARAMETER Because + The reason why the input should be the expected value. + + .EXAMPLE + ```powershell + $true | Should-BeTruthy + 1 | Should-BeTruthy + Get-Process | Should-BeTruthy + ``` + + This assertion will pass. + + .EXAMPLE + ```powershell + $false | Should-BeTruthy + $null | Should-BeTruthy + $() | Should-BeTruthy + @() | Should-BeTruthy + 0 | Should-BeTruthy + ``` + + All of these assertions will fail, because the actual value is not $true or truthy. + + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(ValueFromPipeline = $true)] @@ -6,7 +37,7 @@ [String]$Because ) - $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput $Actual = $collectedInput.Actual if (-not $Actual) { $Message = Get-AssertionMessage -Expected $true -Actual $Actual -Because $Because -DefaultMessage "Expected or a truthy value, but got: ." diff --git a/src/functions/assert/Collection/Should-All.ps1 b/src/functions/assert/Collection/Should-All.ps1 index bb54d6ef6..965b6b7eb 100644 --- a/src/functions/assert/Collection/Should-All.ps1 +++ b/src/functions/assert/Collection/Should-All.ps1 @@ -1,4 +1,34 @@ function Assert-All { + <# + .SYNOPSIS + Compares all items in a collection to a filter script. If the filter returns true, or does not throw for all the items in the collection, the assertion passes. + + .PARAMETER FilterScript + A script block that filters the input collection. The script block can use Should-* assertions or throw exceptions to indicate failure. + + .PARAMETER Actual + A collection of items to filter. + + .PARAMETER Because + The reason why the input should be the expected value. + + .EXAMPLE + ```powershell + 1, 2, 3 | Should-All { $_ -gt 0 } + 1, 2, 3 | Should-All { $_ | Should-BeGreaterThan 0 } + ``` + + This assertion will pass, because all items pass the filter. + + .EXAMPLE + ```powershell + 1, 2, 3 | Should-All { $_ -gt 1 } + 1, 2, 3 | Should-All { $_ | Should-BeGreaterThan 1 } + ``` + + The assertions will fail because not all items in the array are greater than 1. + + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] [CmdletBinding()] param ( diff --git a/src/functions/assert/Collection/Should-Any.ps1 b/src/functions/assert/Collection/Should-Any.ps1 index 31986f979..e1b220783 100644 --- a/src/functions/assert/Collection/Should-Any.ps1 +++ b/src/functions/assert/Collection/Should-Any.ps1 @@ -1,4 +1,34 @@ function Assert-Any { + <# + .SYNOPSIS + Compares all items in a collection to a filter script. If the filter returns true, or does not throw for any of the items in the collection, the assertion passes. + + .PARAMETER FilterScript + A script block that filters the input collection. The script block can use Should-* assertions or throw exceptions to indicate failure. + + .PARAMETER Actual + A collection of items to filter. + + .PARAMETER Because + The reason why the input should be the expected value. + + .EXAMPLE + ```powershell + 1, 2, 3 | Should-Any { $_ -gt 2 } + 1, 2, 3 | Should-Any { $_ | Should-BeGreaterThan 2 } + ``` + + This assertion will pass, because at least one item in the collection passed the filter. 3 is greater than 2. + + .EXAMPLE + ```powershell + 1, 2, 3 | Should-Any { $_ -gt 4 } + 1, 2, 3 | Should-Any { $_ | Should-BeGreaterThan 4 } + ``` + + The assertions will fail because none of theitems in the array are greater than 4. + + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(ValueFromPipeline = $true, Position = 1)] diff --git a/src/functions/assert/Collection/Should-BeCollection.ps1 b/src/functions/assert/Collection/Should-BeCollection.ps1 index 7eaa3adad..0b8a28ad7 100644 --- a/src/functions/assert/Collection/Should-BeCollection.ps1 +++ b/src/functions/assert/Collection/Should-BeCollection.ps1 @@ -1,4 +1,37 @@ function Assert-Collection { + <# + .SYNOPSIS + Compares collections for equality, by comparing their sizes and each item in them. It does not compare the types of the input collections. + + .PARAMETER Expected + A collection of items. + + .PARAMETER Actual + A collection of items. + + .PARAMETER Because + The reason why the input should be the expected value. + + .EXAMPLE + ```powershell + 1, 2, 3 | Should-BeCollection @(1, 2, 3) + @(1) | Should-BeCollection @(1) + 1 | Should-BeCollection 1 + ``` + + This assertion will pass, because the collections have the same size and the items are equal. + + .EXAMPLE + ```powershell + 1, 2, 3, 4 | Should-BeCollection @(1, 2, 3) + 1, 2, 3, 4 | Should-BeCollection @(5, 6, 7, 8) + @(1) | Should-BeCollection @(2) + 1 | Should-BeCollection @(2) + ``` + + The assertions will fail because the collections are not equal. + + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] diff --git a/src/functions/assert/Collection/Should-ContainCollection.ps1 b/src/functions/assert/Collection/Should-ContainCollection.ps1 index d1d353532..77df88f13 100644 --- a/src/functions/assert/Collection/Should-ContainCollection.ps1 +++ b/src/functions/assert/Collection/Should-ContainCollection.ps1 @@ -1,4 +1,35 @@ function Assert-Contain { + <# + .SYNOPSIS + Compares collections to see if the expected collection is present in the provided collection. It does not compare the types of the input collections. + + .PARAMETER Expected + A collection of items. + + .PARAMETER Actual + A collection of items. + + .PARAMETER Because + The reason why the input should be the expected value. + + .EXAMPLE + ```powershell + 1, 2, 3 | Should-ContainCollection @(1, 2) + @(1) | Should-ContainCollection @(1) + ``` + + This assertion will pass, because all items are present in the collection, in the right order. + + .EXAMPLE + ```powershell + 1, 2, 3 | Should-ContainCollection @(3, 4) + 1, 2, 3 | Should-ContainCollection @(3, 2, 1) + @(1) | Should-ContainCollection @(2) + ``` + + This assertion will fail, because not all items are present in the collection, or are not in the right order. + + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] diff --git a/src/functions/assert/Collection/Should-NotContainCollection.ps1 b/src/functions/assert/Collection/Should-NotContainCollection.ps1 index 54ef69b9e..b17cff19f 100644 --- a/src/functions/assert/Collection/Should-NotContainCollection.ps1 +++ b/src/functions/assert/Collection/Should-NotContainCollection.ps1 @@ -1,4 +1,35 @@ function Assert-NotContain { + <# + .SYNOPSIS + Compares collections to ensuere that the expected collection is not present in the provided collection. It does not compare the types of the input collections. + + .PARAMETER Expected + A collection of items. + + .PARAMETER Actual + A collection of items. + + .PARAMETER Because + The reason why the input should be the expected value. + + .EXAMPLE + ```powershell + 1, 2, 3 | Should-ContainCollection @(3, 4) + 1, 2, 3 | Should-ContainCollection @(3, 2, 1) + @(1) | Should-ContainCollection @(2) + ``` + + This assertion will pass, because the collections are different, or the items are not in the right order. + + .EXAMPLE + ```powershell + 1, 2, 3 | Should-NotContainCollection @(1, 2) + @(1) | Should-NotContainCollection @(1) + ``` + + This assertion will fail, because all items are present in the collection and are in the right order. + + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] diff --git a/src/functions/assert/Common/Collect-Input.ps1 b/src/functions/assert/Common/Collect-Input.ps1 index e1c4eca07..a18e4ca8a 100644 --- a/src/functions/assert/Common/Collect-Input.ps1 +++ b/src/functions/assert/Common/Collect-Input.ps1 @@ -7,7 +7,7 @@ # It is always $null or object[] containing all the received items. $PipelineInput, # This tell us if we were called by | syntax or not. Caller needs to pass in $MyInvocation.ExpectingInput. - $IsPipelineInput + $IsPipelineInput, # This unwraps input provided by |. The effect of this is that we get single item input directly, # and not wrapped in array. E.g. 1 | Should-Be -> 1, and not 1 | Should-Be -> @(1). # @@ -15,7 +15,7 @@ # provide this parameter, because they should handle collections consistenly. # # This parameter does not apply to input provided by parameter sytax Should-Be -Actual 1 - # TODO: will apply this, but not yet. [switch] $UnrollInput + [switch] $UnrollInput ) if ($IsPipelineInput) { @@ -26,8 +26,10 @@ $collectedInput = @() } else { - # This is array of all the input, unwrap it. - $collectedInput = foreach ($item in $PipelineInput) { $item } + if ($UnrollInput) { + # This is array of all the input, unwrap it. + $collectedInput = foreach ($item in $PipelineInput) { $item } + } } } else { diff --git a/src/functions/assert/Exception/Should-Throw.ps1 b/src/functions/assert/Exception/Should-Throw.ps1 index 0a08a9103..9fe424f73 100644 --- a/src/functions/assert/Exception/Should-Throw.ps1 +++ b/src/functions/assert/Exception/Should-Throw.ps1 @@ -1,4 +1,47 @@ function Assert-Throw { + <# + .SYNOPSIS + Asserts that a script block throws an exception. + + .PARAMETER ScriptBlock + The script block that should throw an exception. + + .PARAMETER ExceptionType + The type of exception that should be thrown. + + .PARAMETER ExceptionMessage + The message that the exception should contain. `-like` wildcards are supported. + + .PARAMETER FullyQualifiedErrorId + The FullyQualifiedErrorId that the exception should contain. `-like` wildcards are supported. + + .PARAMETER AllowNonTerminatingError + If set, the assertion will pass if a non-terminating error is thrown. + + .PARAMETER Because + The reason why the input should be the expected value. + + .EXAMPLE + ```powershell + { throw 'error' } | Should-Throw + { throw 'error' } | Should-Throw -ExceptionMessage 'error' + { throw 'error' } | Should-Throw -ExceptionType 'System.Management.Automation.RuntimeException' + { throw 'error' } | Should-Throw -FullyQualifiedErrorId 'RuntimeException' + { throw 'error' } | Should-Throw -FullyQualifiedErrorId '*Exception' + { throw 'error' } | Should-Throw -AllowNonTerminatingError + ``` + + All of these assertions will pass. + + .EXAMPLE + ```powershell + $err = { throw 'error' } | Should-Throw -PassThru + $err.Exception.Message | Should-BeLike '*err*' + ``` + + The error record is returned from the assertion and can be used in further assertions. + + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(ValueFromPipeline = $true, Mandatory = $true)] diff --git a/tst/functions/assert/Collection/Should-BeCollection.Tests.ps1 b/tst/functions/assert/Collection/Should-BeCollection.Tests.ps1 index f46b53fc9..be5039138 100644 --- a/tst/functions/assert/Collection/Should-BeCollection.Tests.ps1 +++ b/tst/functions/assert/Collection/Should-BeCollection.Tests.ps1 @@ -1,8 +1,5 @@ Set-StrictMode -Version Latest -# TODO: Add tests. -return - InPesterModuleScope { Describe "Should-BeCollection" { It "Passes when collections have the same count and items" -ForEach @( From 8509a5cd8ab322083af188af157f39e0e1c5806e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Tue, 7 May 2024 20:46:59 +0200 Subject: [PATCH 39/55] Add help --- .../Should-NotContainCollection.ps1 | 2 +- .../assert/Exception/Should-Throw.ps1 | 2 +- src/functions/assert/General/Should-Be.ps1 | 10 +++- .../General/Should-BeGreaterThanOrEqual.ps1 | 2 +- .../assert/General/assertion-types.md | 59 +++++++++++++++++++ 5 files changed, 71 insertions(+), 4 deletions(-) create mode 100644 src/functions/assert/General/assertion-types.md diff --git a/src/functions/assert/Collection/Should-NotContainCollection.ps1 b/src/functions/assert/Collection/Should-NotContainCollection.ps1 index b17cff19f..c34932c40 100644 --- a/src/functions/assert/Collection/Should-NotContainCollection.ps1 +++ b/src/functions/assert/Collection/Should-NotContainCollection.ps1 @@ -1,7 +1,7 @@ function Assert-NotContain { <# .SYNOPSIS - Compares collections to ensuere that the expected collection is not present in the provided collection. It does not compare the types of the input collections. + Compares collections to ensure that the expected collection is not present in the provided collection. It does not compare the types of the input collections. .PARAMETER Expected A collection of items. diff --git a/src/functions/assert/Exception/Should-Throw.ps1 b/src/functions/assert/Exception/Should-Throw.ps1 index 9fe424f73..c165d4e81 100644 --- a/src/functions/assert/Exception/Should-Throw.ps1 +++ b/src/functions/assert/Exception/Should-Throw.ps1 @@ -53,7 +53,7 @@ function Assert-Throw { [String]$Because ) - $collectedInput = Collect-Input -ParameterInput $ScriptBlock -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $ScriptBlock -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput $ScriptBlock = $collectedInput.Actual $errorThrown = $false diff --git a/src/functions/assert/General/Should-Be.ps1 b/src/functions/assert/General/Should-Be.ps1 index d3ed673af..d3e3a2c1c 100644 --- a/src/functions/assert/General/Should-Be.ps1 +++ b/src/functions/assert/General/Should-Be.ps1 @@ -1,4 +1,12 @@ function Assert-Equal { + <# + .SYNOPSIS + Compares the expected value to actual value, to see if they are equal. + + This is a generic assertion. The input values will convert to the type of $Expected. + + This is value assertion. Single item input will is treated as a value. + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] @@ -8,7 +16,7 @@ [String]$Because ) - $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput $Actual = $collectedInput.Actual if ((Ensure-ExpectedIsNotCollection $Expected) -ne $Actual) { diff --git a/src/functions/assert/General/Should-BeGreaterThanOrEqual.ps1 b/src/functions/assert/General/Should-BeGreaterThanOrEqual.ps1 index 60c249db8..2df159b38 100644 --- a/src/functions/assert/General/Should-BeGreaterThanOrEqual.ps1 +++ b/src/functions/assert/General/Should-BeGreaterThanOrEqual.ps1 @@ -8,7 +8,7 @@ [String]$Because ) - $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput $Actual = $collectedInput.Actual if ((Ensure-ExpectedIsNotCollection $Expected) -gt $Actual) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected the actual value to be greater than or equal to , but it was not. Actual: " diff --git a/src/functions/assert/General/assertion-types.md b/src/functions/assert/General/assertion-types.md new file mode 100644 index 000000000..7989ace5a --- /dev/null +++ b/src/functions/assert/General/assertion-types.md @@ -0,0 +1,59 @@ +# Assert assertions + +Pester 6 preview comes with a new set of Should-* assertions. These new assertions are split these categories based on their usage: + +- value + - generic + - type specific + +- collection + - generic + - combinator + +Each of these categories treats `$Actual` and `$Expected` values differently, to provide a consistent behavior when using the `|` syntax. + +## Value vs. Collection assertions + +The `$Actual` value can be provided by two syntaxes, either by pipeline (`|`) or by parameter (`-Actual`): + +```powershell +1 | Should-Be -Expected 1 +Should-Be -Actual 1 -Expected 1 +``` + +### Using pipeline syntax +When using the pipeline syntax, PowerShell unwraps the input and we lose the type of the collection on the left side. We are provided with a collection that can be either $null, empty or have items. + +A value assertion + +A value assertsoin , meaning that single item input as a single item, including array that has single item: + +```powershell +1 | Should-Be -Expected 1 +@(1) | Should-Be -Expected 1 +$null | Should-Be -Expected $null +@() | Should-Be -Expected $null #< --- TODO: this is not the case right now, we special case this as empty array, but is that correct? it does not play well with the value and collection assertion, and we special case it just because we can $null | will give $local:input -> $null , and @() | will give $local:input -> @(), is that distinction important when we know that we will only check against values? +``` + + + + + + +## Collection + +## Generic assertions + +The `$Expected` accepts any input that is not a collection. +The type of `$Expected` determines the type to be used for the comparison: + +```powershell +1 | Should-Be -Expected $true +Get-Process | Should-Be -Expected "System.Diagnostics.Process (Idle)" +``` + +The assertions in the above examples will both pass. The + +Will + +These assertions are exported from the module as Assert-* functions and aliased to Should-*, this is because of PowerShell restricting multi word functions to a list of predefined approved verbs. From 4c8bae244023aff4356b5867847353f13b2e0152 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Tue, 7 May 2024 21:10:07 +0200 Subject: [PATCH 40/55] info --- .../assert/General/assertion-types.md | 53 +++++++++++++++---- 1 file changed, 43 insertions(+), 10 deletions(-) diff --git a/src/functions/assert/General/assertion-types.md b/src/functions/assert/General/assertion-types.md index 7989ace5a..11c268a1e 100644 --- a/src/functions/assert/General/assertion-types.md +++ b/src/functions/assert/General/assertion-types.md @@ -22,38 +22,71 @@ Should-Be -Actual 1 -Expected 1 ``` ### Using pipeline syntax -When using the pipeline syntax, PowerShell unwraps the input and we lose the type of the collection on the left side. We are provided with a collection that can be either $null, empty or have items. -A value assertion +When using the pipeline syntax, PowerShell unwraps the input and we lose the type of the collection on the left side. We are provided with a collection that can be either $null, empty or have items. Notably, we cannot distinguish between a single value being provided, and an array of single item: -A value assertsoin , meaning that single item input as a single item, including array that has single item: +```powershell +1 | Should-Be +@(1) | Should-Be +``` + +These will both be received by the assertion as `@(1)`. + +For this reason a value assertion will handle this as `1`, but a collection assertion will handle this input as `@(1)`. + +Another special case is `@()`. A value assertion will handle it as `$null`, but a collection assertion will handle it as `@()`. + +`$null` remains `$null` in both cases. ```powershell +# Should-Be is a value assertion: 1 | Should-Be -Expected 1 @(1) | Should-Be -Expected 1 $null | Should-Be -Expected $null -@() | Should-Be -Expected $null #< --- TODO: this is not the case right now, we special case this as empty array, but is that correct? it does not play well with the value and collection assertion, and we special case it just because we can $null | will give $local:input -> $null , and @() | will give $local:input -> @(), is that distinction important when we know that we will only check against values? -``` +@() | Should-Be -Expected $null #< --- TODO: this is not the case right now, we special case this as empty array, but is that correct? it does not play well with the value and collection assertion, and we special case it just because we can. +# $null | will give $local:input -> $null , and @() | will give $local:input -> @(), is that distinction important when we know that we will only check against values? +# This fails, because -Expected does not allow collections. +@() | Should-Be -Expected @() +```powershell +# Should-BeCollection is a collection assertion: +1 | Should-BeCollection -Expected @(1) +@(1) | Should-BeCollection -Expected @(1) +@() | Should-BeCollection -Expected @() +# This fails, because -Expected requires a collection. +$null | Should-BeCollection -Expected $null +``` + +### Using the -Actual syntax -## Collection +The value provides to `-Actual`, is always exactly the same as provided. + +```powershell +Should-Be -Actual 1 -Expected 1 + +# This fails, Actual is collection, while expected is int. +Should-Be -Actual @(1) -Expected 1 +``` ## Generic assertions The `$Expected` accepts any input that is not a collection. -The type of `$Expected` determines the type to be used for the comparison: +The type of `$Expected` determines the type to be used for the comparison. +`$Actual` is automatically converted to that type. ```powershell 1 | Should-Be -Expected $true -Get-Process | Should-Be -Expected "System.Diagnostics.Process (Idle)" +Get-Process -Name Idle | Should-Be -Expected "System.Diagnostics.Process (Idle)" ``` -The assertions in the above examples will both pass. The +The assertions in the above examples will both pass: +- `1` converts to `bool` `$true`, which is the expected value. +- `Get-Process` retrieves the Idle process (on Windows). This process object gets converted to `string`. The string is equal to the expected value. -Will +### These assertions are exported from the module as Assert-* functions and aliased to Should-*, this is because of PowerShell restricting multi word functions to a list of predefined approved verbs. From a6affe39dac61d0b5131b632fe74b7e6899973d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Tue, 7 May 2024 22:31:52 +0200 Subject: [PATCH 41/55] unroll --- .../assert/General => docs}/assertion-types.md | 18 ++++++++++++++++-- src/functions/assert/Collection/Should-All.ps1 | 3 ++- src/functions/assert/Common/Collect-Input.ps1 | 4 ++++ .../assert/General/Should-BeLessThan.ps1 | 2 +- .../General/Should-BeLessThanOrEqual.ps1 | 2 +- src/functions/assert/General/Should-BeNull.ps1 | 2 +- src/functions/assert/General/Should-BeSame.ps1 | 2 +- .../assert/General/Should-HaveType.ps1 | 2 +- src/functions/assert/General/Should-NotBe.ps1 | 2 +- .../assert/General/Should-NotBeNull.ps1 | 2 +- .../assert/General/Should-NotBeSame.ps1 | 2 +- .../assert/General/Should-NotHaveType.ps1 | 2 +- .../assert/General/ShouldBe-GreaterThan.ps1 | 2 +- .../assert/String/Should-BeEmptyString.ps1 | 2 +- .../assert/String/Should-BeLikeString.ps1 | 2 +- .../assert/String/Should-BeString.ps1 | 2 +- .../assert/String/Should-NotBeEmptyString.ps1 | 2 +- .../assert/String/Should-NotBeLikeString.ps1 | 2 +- .../String/Should-NotBeWhiteSpaceString.ps1 | 2 +- .../assert/Time/Should-BeFasterThan.ps1 | 2 +- .../assert/Time/Should-BeSlowerThan.ps1 | 2 +- .../assert/Collection/Should-All.Tests.ps1 | 2 +- .../assert/Collection/Should-Any.Tests.ps1 | 4 ++-- .../assert/Common/Collect-Input.Tests.ps1 | 18 ++++++++++++++---- 24 files changed, 57 insertions(+), 28 deletions(-) rename {src/functions/assert/General => docs}/assertion-types.md (79%) diff --git a/src/functions/assert/General/assertion-types.md b/docs/assertion-types.md similarity index 79% rename from src/functions/assert/General/assertion-types.md rename to docs/assertion-types.md index 11c268a1e..6e1387048 100644 --- a/src/functions/assert/General/assertion-types.md +++ b/docs/assertion-types.md @@ -72,7 +72,11 @@ Should-Be -Actual 1 -Expected 1 Should-Be -Actual @(1) -Expected 1 ``` -## Generic assertions +## Value assertions + +### Generic value assertions + +Generic value assertions, such as `Should-Be`, are for asserting on a single value. They behave quite similar to PowerShell operators, e.g. `Should-Be` maps to `-eq`. The `$Expected` accepts any input that is not a collection. The type of `$Expected` determines the type to be used for the comparison. @@ -87,6 +91,16 @@ The assertions in the above examples will both pass: - `1` converts to `bool` `$true`, which is the expected value. - `Get-Process` retrieves the Idle process (on Windows). This process object gets converted to `string`. The string is equal to the expected value. +### Type specific value assertions + +Type specific assertions are for asserting on a single value of a given type. For example boolean. These assertions take the advantage of being more specialized, to provide a type specific functionality. Such as `Should-BeString -IgnoreWhitespace`. + +The `$Expected` accepts input that has the same type as the assertion type. E.g. `Should-BeString -Expected "my string"`. + +`$Actual` accepts input that has the same type as the assertion type. The input is not automatically converted to the destination type, unless the assertion specifies it, e.g. `Should-BeFalsy` will convert to `bool`. + +## Collection assertions + + -### These assertions are exported from the module as Assert-* functions and aliased to Should-*, this is because of PowerShell restricting multi word functions to a list of predefined approved verbs. diff --git a/src/functions/assert/Collection/Should-All.ps1 b/src/functions/assert/Collection/Should-All.ps1 index 965b6b7eb..9fc0f2fee 100644 --- a/src/functions/assert/Collection/Should-All.ps1 +++ b/src/functions/assert/Collection/Should-All.ps1 @@ -79,9 +79,10 @@ $actualFiltered = @($actualFiltered) if (0 -lt $actualFiltered.Count) { $data = @{ - actualFiltered = $actualFiltered + actualFiltered = if (1 -eq $actualFiltered.Count) { $actualFiltered[0] } else { $actualFiltered } actualFilteredCount = $actualFiltered.Count } + $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Data $data -Because $Because -DefaultMessage "Expected all items in collection to pass filter , but of them did not pass the filter." if ($null -ne $failReasons) { $failReasons = $failReasons -join "`n" diff --git a/src/functions/assert/Common/Collect-Input.ps1 b/src/functions/assert/Common/Collect-Input.ps1 index a18e4ca8a..d09285216 100644 --- a/src/functions/assert/Common/Collect-Input.ps1 +++ b/src/functions/assert/Common/Collect-Input.ps1 @@ -30,6 +30,10 @@ # This is array of all the input, unwrap it. $collectedInput = foreach ($item in $PipelineInput) { $item } } + else { + # This is array of all the input. + $collectedInput = $PipelineInput + } } } else { diff --git a/src/functions/assert/General/Should-BeLessThan.ps1 b/src/functions/assert/General/Should-BeLessThan.ps1 index 32b1b6ec8..cf74c20ea 100644 --- a/src/functions/assert/General/Should-BeLessThan.ps1 +++ b/src/functions/assert/General/Should-BeLessThan.ps1 @@ -8,7 +8,7 @@ [String]$Because ) - $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput $Actual = $collectedInput.Actual if ((Ensure-ExpectedIsNotCollection $Expected) -le $Actual) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected the actual value to be less than , but it was not. Actual: " diff --git a/src/functions/assert/General/Should-BeLessThanOrEqual.ps1 b/src/functions/assert/General/Should-BeLessThanOrEqual.ps1 index 966587563..671f4df11 100644 --- a/src/functions/assert/General/Should-BeLessThanOrEqual.ps1 +++ b/src/functions/assert/General/Should-BeLessThanOrEqual.ps1 @@ -8,7 +8,7 @@ [String]$Because ) - $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput $Actual = $collectedInput.Actual if ((Ensure-ExpectedIsNotCollection $Expected) -lt $Actual) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected the actual value to be less than or equal to , but it was not. Actual: " diff --git a/src/functions/assert/General/Should-BeNull.ps1 b/src/functions/assert/General/Should-BeNull.ps1 index 5eb1b2f15..6e4318146 100644 --- a/src/functions/assert/General/Should-BeNull.ps1 +++ b/src/functions/assert/General/Should-BeNull.ps1 @@ -6,7 +6,7 @@ [String]$Because ) - $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput $Actual = $collectedInput.Actual if ($null -ne $Actual) { $Message = Get-AssertionMessage -Expected $null -Actual $Actual -Because $Because -DefaultMessage "Expected `$null, but got ''." diff --git a/src/functions/assert/General/Should-BeSame.ps1 b/src/functions/assert/General/Should-BeSame.ps1 index 1aecc2cf3..214f1a2cb 100644 --- a/src/functions/assert/General/Should-BeSame.ps1 +++ b/src/functions/assert/General/Should-BeSame.ps1 @@ -12,7 +12,7 @@ throw [ArgumentException]"Should-BeSame compares objects by reference. You provided a value type or a string, those are not reference types and you most likely don't need to compare them by reference, see https://github.com/nohwnd/Assert/issues/6.`n`nAre you trying to compare two values to see if they are equal? Use Should-BeEqual instead." } - $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput $Actual = $collectedInput.Actual if (-not ([object]::ReferenceEquals($Expected, $Actual))) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected , to be the same instance but it was not. Actual: " diff --git a/src/functions/assert/General/Should-HaveType.ps1 b/src/functions/assert/General/Should-HaveType.ps1 index 9a4be14db..fa345a9e6 100644 --- a/src/functions/assert/General/Should-HaveType.ps1 +++ b/src/functions/assert/General/Should-HaveType.ps1 @@ -8,7 +8,7 @@ [String]$Because ) - $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput $Actual = $collectedInput.Actual if ($Actual -isnot $Expected) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected value to have type , but got ." diff --git a/src/functions/assert/General/Should-NotBe.ps1 b/src/functions/assert/General/Should-NotBe.ps1 index 1eab1c905..039d231ec 100644 --- a/src/functions/assert/General/Should-NotBe.ps1 +++ b/src/functions/assert/General/Should-NotBe.ps1 @@ -8,7 +8,7 @@ [String]$Because ) - $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput $Actual = $collectedInput.Actual if ((Ensure-ExpectedIsNotCollection $Expected) -eq $Actual) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected , to be different than the actual value, but they were equal." diff --git a/src/functions/assert/General/Should-NotBeNull.ps1 b/src/functions/assert/General/Should-NotBeNull.ps1 index fb3ee929a..0a5652ca5 100644 --- a/src/functions/assert/General/Should-NotBeNull.ps1 +++ b/src/functions/assert/General/Should-NotBeNull.ps1 @@ -6,7 +6,7 @@ [String]$Because ) - $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput $Actual = $collectedInput.Actual if ($null -eq $Actual) { $Message = Get-AssertionMessage -Expected $null -Actual $Actual -Because $Because -DefaultMessage "Expected not `$null, but got `$null." diff --git a/src/functions/assert/General/Should-NotBeSame.ps1 b/src/functions/assert/General/Should-NotBeSame.ps1 index 004cda257..15c3f02ce 100644 --- a/src/functions/assert/General/Should-NotBeSame.ps1 +++ b/src/functions/assert/General/Should-NotBeSame.ps1 @@ -8,7 +8,7 @@ [String]$Because ) - $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput $Actual = $collectedInput.Actual if ([object]::ReferenceEquals($Expected, $Actual)) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected , to not be the same instance, but they were the same instance." diff --git a/src/functions/assert/General/Should-NotHaveType.ps1 b/src/functions/assert/General/Should-NotHaveType.ps1 index c83b9509f..e44aff71f 100644 --- a/src/functions/assert/General/Should-NotHaveType.ps1 +++ b/src/functions/assert/General/Should-NotHaveType.ps1 @@ -8,7 +8,7 @@ [String]$Because ) - $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput $Actual = $collectedInput.Actual if ($Actual -is $Expected) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected value to be of different type than , but got ." diff --git a/src/functions/assert/General/ShouldBe-GreaterThan.ps1 b/src/functions/assert/General/ShouldBe-GreaterThan.ps1 index ad5b25db2..90da8463e 100644 --- a/src/functions/assert/General/ShouldBe-GreaterThan.ps1 +++ b/src/functions/assert/General/ShouldBe-GreaterThan.ps1 @@ -8,7 +8,7 @@ [String]$Because ) - $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput $Actual = $collectedInput.Actual if ((Ensure-ExpectedIsNotCollection $Expected) -ge $Actual) { $Message = Get-AssertionMessage -Expected $Expected -Actual $Actual -Because $Because -DefaultMessage "Expected the actual value to be greater than , but it was not. Actual: " diff --git a/src/functions/assert/String/Should-BeEmptyString.ps1 b/src/functions/assert/String/Should-BeEmptyString.ps1 index 6bcf3570e..b2106edcc 100644 --- a/src/functions/assert/String/Should-BeEmptyString.ps1 +++ b/src/functions/assert/String/Should-BeEmptyString.ps1 @@ -42,7 +42,7 @@ [String]$Because ) - $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput $Actual = $collectedInput.Actual if ($Actual -isnot [String] -or -not [String]::IsNullOrEmpty( $Actual)) { diff --git a/src/functions/assert/String/Should-BeLikeString.ps1 b/src/functions/assert/String/Should-BeLikeString.ps1 index d1d0cd47e..9faf42887 100644 --- a/src/functions/assert/String/Should-BeLikeString.ps1 +++ b/src/functions/assert/String/Should-BeLikeString.ps1 @@ -24,7 +24,7 @@ function Assert-Like { [String]$Because ) - $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput $Actual = $collectedInput.Actual if ($Actual -isnot [string]) { diff --git a/src/functions/assert/String/Should-BeString.ps1 b/src/functions/assert/String/Should-BeString.ps1 index f12394b33..ccfb82a3e 100644 --- a/src/functions/assert/String/Should-BeString.ps1 +++ b/src/functions/assert/String/Should-BeString.ps1 @@ -35,7 +35,7 @@ function Assert-StringEqual { [switch]$IgnoreWhitespace ) - $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $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 diff --git a/src/functions/assert/String/Should-NotBeEmptyString.ps1 b/src/functions/assert/String/Should-NotBeEmptyString.ps1 index 84288b231..212096c57 100644 --- a/src/functions/assert/String/Should-NotBeEmptyString.ps1 +++ b/src/functions/assert/String/Should-NotBeEmptyString.ps1 @@ -42,7 +42,7 @@ [String]$Because ) - $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput $Actual = $collectedInput.Actual if ($Actual -isnot [String] -or [String]::IsNullOrEmpty($Actual)) { diff --git a/src/functions/assert/String/Should-NotBeLikeString.ps1 b/src/functions/assert/String/Should-NotBeLikeString.ps1 index 46e819e13..5d8620ba6 100644 --- a/src/functions/assert/String/Should-NotBeLikeString.ps1 +++ b/src/functions/assert/String/Should-NotBeLikeString.ps1 @@ -32,7 +32,7 @@ function Assert-NotLike { [String]$Because ) - $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput $Actual = $collectedInput.Actual if ($Actual -isnot [string]) { diff --git a/src/functions/assert/String/Should-NotBeWhiteSpaceString.ps1 b/src/functions/assert/String/Should-NotBeWhiteSpaceString.ps1 index 878b17a62..613c8901e 100644 --- a/src/functions/assert/String/Should-NotBeWhiteSpaceString.ps1 +++ b/src/functions/assert/String/Should-NotBeWhiteSpaceString.ps1 @@ -43,7 +43,7 @@ [String]$Because ) - $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput $Actual = $collectedInput.Actual if ($Actual -isnot [string] -or [string]::IsNullOrWhiteSpace($Actual)) { diff --git a/src/functions/assert/Time/Should-BeFasterThan.ps1 b/src/functions/assert/Time/Should-BeFasterThan.ps1 index 87418c4e1..b41934db9 100644 --- a/src/functions/assert/Time/Should-BeFasterThan.ps1 +++ b/src/functions/assert/Time/Should-BeFasterThan.ps1 @@ -30,7 +30,7 @@ function Assert-Faster { $Expected = Get-TimeSpanFromStringWithUnits -Value $Expected } - $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput $Actual = $collectedInput.Actual if ($Actual -is [scriptblock]) { diff --git a/src/functions/assert/Time/Should-BeSlowerThan.ps1 b/src/functions/assert/Time/Should-BeSlowerThan.ps1 index df9cb8ed3..429c1c236 100644 --- a/src/functions/assert/Time/Should-BeSlowerThan.ps1 +++ b/src/functions/assert/Time/Should-BeSlowerThan.ps1 @@ -11,7 +11,7 @@ $Expected = Get-TimeSpanFromStringWithUnits -Value $Expected } - $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput $Actual = $collectedInput.Actual if ($Actual -is [scriptblock]) { diff --git a/tst/functions/assert/Collection/Should-All.Tests.ps1 b/tst/functions/assert/Collection/Should-All.Tests.ps1 index fb47ac240..49cd80b7a 100644 --- a/tst/functions/assert/Collection/Should-All.Tests.ps1 +++ b/tst/functions/assert/Collection/Should-All.Tests.ps1 @@ -27,7 +27,7 @@ Expected [int] 2, but got [int] 1." -replace "`r`n", "`n") } It "Fails when no items are passed" -TestCases @( - @{ Actual = $null; Expected = "Expected all items in collection to pass filter { `$_ -eq 1 }, but [null] `$null contains no items to compare." } + @{ Actual = $null; Expected = "Expected all items in collection @(`$null) to pass filter { `$_ -eq 1 }, but 1 of them `$null did not pass the filter." } @{ Actual = @(); Expected = "Expected all items in collection to pass filter { `$_ -eq 1 }, but [collection] @() contains no items to compare." } ) { $err = { $Actual | Should-All -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed diff --git a/tst/functions/assert/Collection/Should-Any.Tests.ps1 b/tst/functions/assert/Collection/Should-Any.Tests.ps1 index c4a2f54c7..453f9a9be 100644 --- a/tst/functions/assert/Collection/Should-Any.Tests.ps1 +++ b/tst/functions/assert/Collection/Should-Any.Tests.ps1 @@ -27,8 +27,8 @@ Expected [int] 2, but got [int] 1." -replace "`r`n", "`n") } It "Fails when no items are passed" -TestCases @( - @{ Actual = $null; Expected = "Expected at least one item in collection to pass filter { `$_ -eq 1 }, but [null] `$null contains no items to compare." } - @{ Actual = @(); Expected = "Expected at least one item in collection to pass filter { `$_ -eq 1 }, but [collection] @() contains no items to compare." } + @{ Actual = $null; Expected = 'Expected at least one item in collection @($null) to pass filter { $_ -eq 1 }, but none of the items passed the filter.' } + @{ Actual = @(); Expected = 'Expected at least one item in collection to pass filter { $_ -eq 1 }, but [collection] @() contains no items to compare.' } ) { $err = { $Actual | Should-Any -FilterScript { $_ -eq 1 } } | Verify-AssertionFailed $err.Exception.Message | Verify-Equal $Expected diff --git a/tst/functions/assert/Common/Collect-Input.Tests.ps1 b/tst/functions/assert/Common/Collect-Input.Tests.ps1 index 287a21c0f..98bc322c4 100644 --- a/tst/functions/assert/Common/Collect-Input.Tests.ps1 +++ b/tst/functions/assert/Common/Collect-Input.Tests.ps1 @@ -8,17 +8,27 @@ InPesterModuleScope { [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(ValueFromPipeline = $true)] - $Actual + $Actual, + [switch] $UnrollInput ) - $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput:$UnrollInput $collectedInput } } Describe "Pipeline input" { - It "Given `$null through pipeline it captures `$null" { - $collectedInput = $null | Assert-PassThru + It "Given `$null through pipeline when unrolling it captures `$null" { + $collectedInput = $null | Assert-PassThru -UnrollInput + + Verify-True $collectedInput.IsPipelineInput + if ($null -ne $collectedInput.Actual) { + throw "Expected `$null, but got $(Format-Nicely2 $collectedInput.Actual)." + } + } + + It "Given `$null through pipeline it captures @(`$null)" { + $collectedInput = $null | Assert-PassThru -UnrollInput Verify-True $collectedInput.IsPipelineInput if ($null -ne $collectedInput.Actual) { From 3c74309df7c702bf52c9525e39b3b351bfb45e67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Tue, 14 May 2024 21:38:43 +0200 Subject: [PATCH 42/55] Add Help --- src/Format2.ps1 | 22 +++---- .../assert/Collection/Should-All.ps1 | 6 ++ .../assert/Collection/Should-Any.ps1 | 6 ++ .../assert/Collection/Should-BeCollection.ps1 | 5 ++ .../Collection/Should-ContainCollection.ps1 | 6 ++ .../Should-NotContainCollection.ps1 | 6 ++ .../Equivalence/Should-BeEquivalent.ps1 | 53 +++++++++++++++++ .../assert/Exception/Should-Throw.ps1 | 6 ++ src/functions/assert/General/Should-Be.ps1 | 24 +++++++- .../General/Should-BeGreaterThanOrEqual.ps1 | 28 +++++++++ .../assert/General/Should-BeLessThan.ps1 | 28 +++++++++ .../General/Should-BeLessThanOrEqual.ps1 | 30 ++++++++++ .../assert/General/Should-BeNull.ps1 | 18 ++++++ .../assert/General/Should-BeSame.ps1 | 30 ++++++++++ .../assert/General/Should-HaveType.ps1 | 21 +++++++ src/functions/assert/General/Should-NotBe.ps1 | 21 +++++++ .../assert/General/Should-NotBeNull.ps1 | 18 ++++++ .../assert/General/Should-NotBeSame.ps1 | 28 +++++++++ .../assert/General/Should-NotHaveType.ps1 | 24 ++++++++ .../assert/General/ShouldBe-GreaterThan.ps1 | 22 +++++++ .../assert/String/Should-BeLikeString.ps1 | 37 ++++++++++++ .../assert/String/Should-BeString.ps1 | 39 +++++++++++++ .../assert/String/Should-NotBeLikeString.ps1 | 36 ++++++++++++ .../assert/String/Should-NotBeString.ps1 | 37 ++++++++++++ src/functions/assert/Time/Should-BeAfter.ps1 | 57 +++++++++++++++++++ src/functions/assert/Time/Should-BeBefore.ps1 | 57 +++++++++++++++++++ .../assert/Time/Should-BeFasterThan.ps1 | 30 ++++++++++ .../assert/Time/Should-BeSlowerThan.ps1 | 38 +++++++++++++ tst/Help.Tests.ps1 | 2 +- 29 files changed, 722 insertions(+), 13 deletions(-) diff --git a/src/Format2.ps1 b/src/Format2.ps1 index 9823b1caa..41774bbda 100644 --- a/src/Format2.ps1 +++ b/src/Format2.ps1 @@ -26,14 +26,21 @@ function Format-Object2 ($Value, $Property, [switch]$Pretty) { } $valueType = Get-ShortType $Value - $margin = " " $items = foreach ($p in $orderedProperty) { - if ($Pretty) { "`n$margin" } $v = ([PSObject]$Value.$p) $f = Format-Nicely2 -Value $v -Pretty:$Pretty - "$separator$p=$f" + "$p=$f" + } + + if (0 -eq $Property.Length ) { + $o = "$valueType{}" + } + elseif ($Pretty) { + $o = "$valueType{`n $($items -join ";`n ");`n}" + } + else { + $o = "$valueType{$($items -join '; ');}" } - $o = "$valueType{$($items -join '; ')}" $o } @@ -124,12 +131,7 @@ function Format-Nicely2 ($Value, [switch]$Pretty) { } if ((Is-DataTable -Value $Value) -or (Is-DataRow -Value $Value)) { - try { - return Format-DataTable2 -Value $Value -Pretty:$Pretty - } - catch { - $a = 18 - } + return Format-DataTable2 -Value $Value -Pretty:$Pretty } if (Is-Collection -Value $Value) { diff --git a/src/functions/assert/Collection/Should-All.ps1 b/src/functions/assert/Collection/Should-All.ps1 index 9fc0f2fee..5256a1eaf 100644 --- a/src/functions/assert/Collection/Should-All.ps1 +++ b/src/functions/assert/Collection/Should-All.ps1 @@ -28,6 +28,12 @@ The assertions will fail because not all items in the array are greater than 1. + .LINK + https://pester.dev/docs/commands/Should-All + + .LINK + https://pester.dev/docs/assertions + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] [CmdletBinding()] diff --git a/src/functions/assert/Collection/Should-Any.ps1 b/src/functions/assert/Collection/Should-Any.ps1 index e1b220783..7d98f67ac 100644 --- a/src/functions/assert/Collection/Should-Any.ps1 +++ b/src/functions/assert/Collection/Should-Any.ps1 @@ -28,6 +28,12 @@ The assertions will fail because none of theitems in the array are greater than 4. + .LINK + https://pester.dev/docs/commands/Should-Any + + .LINK + https://pester.dev/docs/assertions + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( diff --git a/src/functions/assert/Collection/Should-BeCollection.ps1 b/src/functions/assert/Collection/Should-BeCollection.ps1 index 0b8a28ad7..1bea0035b 100644 --- a/src/functions/assert/Collection/Should-BeCollection.ps1 +++ b/src/functions/assert/Collection/Should-BeCollection.ps1 @@ -31,6 +31,11 @@ The assertions will fail because the collections are not equal. + .LINK + https://pester.dev/docs/commands/Should-BeCollection + + .LINK + https://pester.dev/docs/assertions #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( diff --git a/src/functions/assert/Collection/Should-ContainCollection.ps1 b/src/functions/assert/Collection/Should-ContainCollection.ps1 index 77df88f13..7c1e3d1e2 100644 --- a/src/functions/assert/Collection/Should-ContainCollection.ps1 +++ b/src/functions/assert/Collection/Should-ContainCollection.ps1 @@ -29,6 +29,12 @@ This assertion will fail, because not all items are present in the collection, or are not in the right order. + .LINK + https://pester.dev/docs/commands/Should-ContainCollection + + .LINK + https://pester.dev/docs/assertions + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( diff --git a/src/functions/assert/Collection/Should-NotContainCollection.ps1 b/src/functions/assert/Collection/Should-NotContainCollection.ps1 index c34932c40..3baf27ef4 100644 --- a/src/functions/assert/Collection/Should-NotContainCollection.ps1 +++ b/src/functions/assert/Collection/Should-NotContainCollection.ps1 @@ -29,6 +29,12 @@ This assertion will fail, because all items are present in the collection and are in the right order. + .LINK + https://pester.dev/docs/commands/Should-NotContainCollection + + .LINK + https://pester.dev/docs/assertions + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( diff --git a/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 b/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 index b163e43f5..46f46e72a 100644 --- a/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 +++ b/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 @@ -614,6 +614,59 @@ function Compare-Equivalent { } function Assert-Equivalent { + <# + .SYNOPSIS + Compares two objects for equivalency, by recursively comparing their properties for equivalency. + + .PARAMETER Actual + The actual object to compare. + + .PARAMETER Expected + The expected object to compare. + + .PARAMETER Options + Options for the comparison. Get-EquivalencyOption function is called to get the default options. + + .PARAMETER StrictOrder + If set, the order of items in collections will be compared. + + .EXAMPLE + ```powershell + $expected = [PSCustomObject] @{ + Name = "Thomas" + } + + $actual = [PSCustomObject] @{ + Name = "Jakub" + Age = 30 + } + + $actual | Should-BeEquivalent $expected + ``` + + This will throw an error because the actual object has an additional property Age and the Name values are not equivalent. + + .EXAMPLE + ```powershell + $expected = [PSCustomObject] @{ + Name = "Thomas" + } + + $actual = [PSCustomObject] @{ + Name = "Thomas" + } + + $actual | Should-BeEquivalent $expected + ``` + + This will pass because the actual object has the same properties as the expected object and the Name values are equivalent. + + .LINK + https://pester.dev/docs/commands/Should-BeEquivalent + + .LINK + https://pester.dev/docs/assertions + #> [CmdletBinding()] param( $Actual, diff --git a/src/functions/assert/Exception/Should-Throw.ps1 b/src/functions/assert/Exception/Should-Throw.ps1 index c165d4e81..d46e85105 100644 --- a/src/functions/assert/Exception/Should-Throw.ps1 +++ b/src/functions/assert/Exception/Should-Throw.ps1 @@ -41,6 +41,12 @@ function Assert-Throw { The error record is returned from the assertion and can be used in further assertions. + .LINK + https://pester.dev/docs/commands/Should-Throw + + .LINK + https://pester.dev/docs/assertions + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( diff --git a/src/functions/assert/General/Should-Be.ps1 b/src/functions/assert/General/Should-Be.ps1 index d3e3a2c1c..50168e40a 100644 --- a/src/functions/assert/General/Should-Be.ps1 +++ b/src/functions/assert/General/Should-Be.ps1 @@ -3,9 +3,29 @@ .SYNOPSIS Compares the expected value to actual value, to see if they are equal. - This is a generic assertion. The input values will convert to the type of $Expected. + .PARAMETER Expected + The expected value. + + .PARAMETER Actual + The actual value. + + .PARAMETER Because + The reason why the input should be the expected value. + + .EXAMPLE + ```powershell + 1 | Should-Be 1 + "hello" | Should-Be "hello" + ``` + + These assertions will pass, because the expected value is equal to the actual value. + + .LINK + https://pester.dev/docs/commands/Should-Be + + .LINK + https://pester.dev/docs/assertions - This is value assertion. Single item input will is treated as a value. #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( diff --git a/src/functions/assert/General/Should-BeGreaterThanOrEqual.ps1 b/src/functions/assert/General/Should-BeGreaterThanOrEqual.ps1 index 2df159b38..5ee6911b6 100644 --- a/src/functions/assert/General/Should-BeGreaterThanOrEqual.ps1 +++ b/src/functions/assert/General/Should-BeGreaterThanOrEqual.ps1 @@ -1,4 +1,32 @@ function Assert-GreaterThanOrEqual { + <# + .SYNOPSIS + Compares the expected value to actual value, to see if the actual value is greater than or equal to the expected value. + + .PARAMETER Expected + The expected value. + + .PARAMETER Actual + The actual value. + + .PARAMETER Because + The reason why the input should be the expected value. + + .EXAMPLE + ```powershell + 2 | Should-BeGreaterThanOrEqual 1 + 2 | Should-BeGreaterThanOrEqual 2 + ``` + + These assertions will pass, because the actual value is greater than or equal to the expected value. + + .LINK + https://pester.dev/docs/commands/Should-BeGreaterThanOrEqual + + .LINK + https://pester.dev/docs/assertions + + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] diff --git a/src/functions/assert/General/Should-BeLessThan.ps1 b/src/functions/assert/General/Should-BeLessThan.ps1 index cf74c20ea..456cd6d72 100644 --- a/src/functions/assert/General/Should-BeLessThan.ps1 +++ b/src/functions/assert/General/Should-BeLessThan.ps1 @@ -1,4 +1,32 @@ function Assert-LessThan { + <# + .SYNOPSIS + Compares the expected value to actual value, to see if the actual value is less than the expected value. + + .PARAMETER Expected + The expected value. + + .PARAMETER Actual + The actual value. + + .PARAMETER Because + The reason why the input should be the expected value. + + .EXAMPLE + ```powershell + 1 | Should-BeLessThan 2 + 0 | Should-BeLessThan 1 + ``` + + These assertions will pass, because the actual value is less than the expected value. + + .LINK + https://pester.dev/docs/commands/Should-BeLessThan + + .LINK + https://pester.dev/docs/assertions + + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] diff --git a/src/functions/assert/General/Should-BeLessThanOrEqual.ps1 b/src/functions/assert/General/Should-BeLessThanOrEqual.ps1 index 671f4df11..0d32e72de 100644 --- a/src/functions/assert/General/Should-BeLessThanOrEqual.ps1 +++ b/src/functions/assert/General/Should-BeLessThanOrEqual.ps1 @@ -1,4 +1,34 @@ function Assert-LessThanOrEqual { + <# + .SYNOPSIS + Compares the expected value to actual value, to see if the actual value is less than or equal to the expected value. + + .PARAMETER Expected + The expected value. + + .PARAMETER Actual + The actual value. + + .PARAMETER Because + The reason why the input should be the expected value. + + .EXAMPLE + ```powershell + 1 | Should-BeLessThanOrEqual 2 + 1 | Should-BeLessThanOrEqual 1 + ``` + + These assertions will pass, because the actual value is less than or equal to the expected value. + + .EXAMPLE + ```powershell + 2 | Should-BeLessThanOrEqual 1 + ``` + + This assertion will fail, because the actual value is not less than or equal to the expected value. + + + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] diff --git a/src/functions/assert/General/Should-BeNull.ps1 b/src/functions/assert/General/Should-BeNull.ps1 index 6e4318146..6dfe5cf0f 100644 --- a/src/functions/assert/General/Should-BeNull.ps1 +++ b/src/functions/assert/General/Should-BeNull.ps1 @@ -1,4 +1,22 @@ function Assert-Null { + <# + .SYNOPSIS + Asserts that the input is `$null`. + + .PARAMETER Actual + The actual value. + + .PARAMETER Because + The reason why the input should be `$null`. + + .EXAMPLE + ```powershell + $null | Should-BeNull + ``` + + This assertion will pass, because the actual value is `$null`. + #> + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] diff --git a/src/functions/assert/General/Should-BeSame.ps1 b/src/functions/assert/General/Should-BeSame.ps1 index 214f1a2cb..c3812a06a 100644 --- a/src/functions/assert/General/Should-BeSame.ps1 +++ b/src/functions/assert/General/Should-BeSame.ps1 @@ -1,4 +1,34 @@ function Assert-Same { + <# + .SYNOPSIS + Compares the expected value to actual value, to see if they are the same instance. + + .PARAMETER Expected + The expected value. + + .PARAMETER Actual + The actual value. + + .PARAMETER Because + The reason why the input should be the expected value. + + .EXAMPLE + ```powershell + $a = New-Object Object + $a | Should-BeSame $a + ``` + + This assertion will pass, because the actual value is the same instance as the expected value. + + .EXAMPLE + ```powershell + $a = New-Object Object + $b = New-Object Object + $a | Should-BeSame $b + ``` + + This assertion will fail, because the actual value is not the same instance as the expected value. + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] diff --git a/src/functions/assert/General/Should-HaveType.ps1 b/src/functions/assert/General/Should-HaveType.ps1 index fa345a9e6..e0167fe20 100644 --- a/src/functions/assert/General/Should-HaveType.ps1 +++ b/src/functions/assert/General/Should-HaveType.ps1 @@ -1,4 +1,25 @@ function Assert-Type { + <# + .SYNOPSIS + Asserts that the input is of the expected type. + + .PARAMETER Expected + The expected type. + + .PARAMETER Actual + The actual value. + + .PARAMETER Because + The reason why the input should be the expected type. + + .EXAMPLE + ```powershell + "hello" | Should-HaveType [String] + 1 | Should-HaveType [Int32] + ``` + + These assertions will pass, because the actual value is of the expected type. + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] diff --git a/src/functions/assert/General/Should-NotBe.ps1 b/src/functions/assert/General/Should-NotBe.ps1 index 039d231ec..6c84509a8 100644 --- a/src/functions/assert/General/Should-NotBe.ps1 +++ b/src/functions/assert/General/Should-NotBe.ps1 @@ -1,4 +1,25 @@ function Assert-NotEqual { + <# + .SYNOPSIS + Compares the expected value to actual value, to see if they are not equal. + + .PARAMETER Expected + The expected value. + + .PARAMETER Actual + The actual value. + + .PARAMETER Because + The reason why the input should not be the expected value. + + .EXAMPLE + ```powershell + 1 | Should-NotBe 2 + "hello" | Should-NotBe "world" + ``` + + These assertions will pass, because the actual value is not equal to the expected value. + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] diff --git a/src/functions/assert/General/Should-NotBeNull.ps1 b/src/functions/assert/General/Should-NotBeNull.ps1 index 0a5652ca5..584c9cbbc 100644 --- a/src/functions/assert/General/Should-NotBeNull.ps1 +++ b/src/functions/assert/General/Should-NotBeNull.ps1 @@ -1,4 +1,22 @@ function Assert-NotNull { + <# + .SYNOPSIS + Asserts that the input is not `$null`. + + .PARAMETER Actual + The actual value. + + .PARAMETER Because + The reason why the input should not be `$null`. + + .EXAMPLE + ```powershell + "hello" | Should-NotBeNull + 1 | Should-NotBeNull + ``` + + These assertions will pass, because the actual value is not `$null. + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] diff --git a/src/functions/assert/General/Should-NotBeSame.ps1 b/src/functions/assert/General/Should-NotBeSame.ps1 index 15c3f02ce..13d735360 100644 --- a/src/functions/assert/General/Should-NotBeSame.ps1 +++ b/src/functions/assert/General/Should-NotBeSame.ps1 @@ -1,4 +1,32 @@ function Assert-NotSame { + <# + .SYNOPSIS + Compares the expected value to actual value, to see if the actual value is not the same instance as the expected value. + + .PARAMETER Expected + The expected value. + + .PARAMETER Actual + The actual value. + + .PARAMETER Because + The reason why the input should not be the expected value. + + .EXAMPLE + ```powershell + $object = New-Object -TypeName PSObject + $object | Should-NotBeSame $object + ``` + This assertion will pass, because the actual value is not the same instance as the expected value. + + .EXAMPLE + ```powershell + $object = New-Object -TypeName PSObject + $object | Should-NotBeSame $object + ``` + + This assertion will fail, because the actual value is the same instance as the expected value. + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] diff --git a/src/functions/assert/General/Should-NotHaveType.ps1 b/src/functions/assert/General/Should-NotHaveType.ps1 index e44aff71f..eb7c20c1a 100644 --- a/src/functions/assert/General/Should-NotHaveType.ps1 +++ b/src/functions/assert/General/Should-NotHaveType.ps1 @@ -1,4 +1,28 @@ function Assert-NotType { + <# + .SYNOPSIS + Asserts that the input is not of the expected type. + + .PARAMETER Expected + The expected type. + + .PARAMETER Actual + The actual value. + + .PARAMETER Because + The reason why the input should not be the expected type. + + .EXAMPLE + ```powershell + "hello" | Should-NotHaveType [Int32] + 1 | Should-NotHaveType [String] + ``` + + These assertions will pass, because the actual value is not of the expected type. + + .NOTES + This assertion is the opposite of `Should-HaveType`. + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] diff --git a/src/functions/assert/General/ShouldBe-GreaterThan.ps1 b/src/functions/assert/General/ShouldBe-GreaterThan.ps1 index 90da8463e..94a9a6dd0 100644 --- a/src/functions/assert/General/ShouldBe-GreaterThan.ps1 +++ b/src/functions/assert/General/ShouldBe-GreaterThan.ps1 @@ -1,4 +1,26 @@ function Assert-GreaterThan { + <# + .SYNOPSIS + Compares the expected value to actual value, to see if the actual value is greater than the expected value. + + .PARAMETER Expected + The expected value. + + .PARAMETER Actual + The actual value. + + .PARAMETER Because + The reason why the input should be the expected value. + + .EXAMPLE + ```powershell + 2 | Should-BeGreaterThan 1 + 2 | Should-BeGreaterThan 2 + ``` + + These assertions will pass, because the actual value is greater than the expected value. + #> + [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] diff --git a/src/functions/assert/String/Should-BeLikeString.ps1 b/src/functions/assert/String/Should-BeLikeString.ps1 index 9faf42887..047105317 100644 --- a/src/functions/assert/String/Should-BeLikeString.ps1 +++ b/src/functions/assert/String/Should-BeLikeString.ps1 @@ -14,6 +14,43 @@ } function Assert-Like { + <# + .SYNOPSIS + Asserts that the actual value is like the expected value. + + .DESCRIPTION + The `Should-BeLike` assertion compares the actual value to the expected value using the `-like` operator. The `-like` operator is case-insensitive by default, but you can make it case-sensitive by using the `-CaseSensitive` switch. + + .PARAMETER Expected + The expected value. + + .PARAMETER Actual + The actual value. + + .PARAMETER CaseSensitive + Indicates that the comparison should be case-sensitive. + + .PARAMETER Because + The reason why the actual value should be like the expected value. + + .EXAMPLE + ```powershell + "hello" | Should-BeLike "h*" + ``` + + This assertion will pass, because the actual value is like the expected value. + + .EXAMPLE + ```powershell + + "hello" | Should-BeLike "H*" -CaseSensitive + ``` + + This assertion will fail, because the actual value is not like the expected value. + + .NOTES + The `Should-BeLike` assertion is the opposite of the `Should-NotBeLike` assertion. + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] diff --git a/src/functions/assert/String/Should-BeString.ps1 b/src/functions/assert/String/Should-BeString.ps1 index ccfb82a3e..c089dbe8b 100644 --- a/src/functions/assert/String/Should-BeString.ps1 +++ b/src/functions/assert/String/Should-BeString.ps1 @@ -24,6 +24,45 @@ } function Assert-StringEqual { + <# + .SYNOPSIS + Asserts that the actual value is equal to the expected value. + + .DESCRIPTION + The `Should-BeString` assertion compares the actual value to the expected value using the `-eq` operator. The `-eq` operator is case-insensitive by default, but you can make it case-sensitive by using the `-CaseSensitive` switch. + + .PARAMETER Expected + The expected value. + + .PARAMETER Actual + The actual value. + + .PARAMETER CaseSensitive + Indicates that the comparison should be case-sensitive. + + .PARAMETER IgnoreWhitespace + Indicates that the comparison should ignore whitespace. + + .PARAMETER Because + The reason why the actual value should be equal to the expected value. + + .EXAMPLE + ```powershell + "hello" | Should-BeString "hello" + ``` + + This assertion will pass, because the actual value is equal to the expected value. + + .EXAMPLE + ```powershell + "hello" | Should-BeString "HELLO" -CaseSensitive + ``` + + This assertion will fail, because the actual value is not equal to the expected value. + + .NOTES + The `Should-BeString` assertion is the opposite of the `Should-NotBeString` assertion. + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] diff --git a/src/functions/assert/String/Should-NotBeLikeString.ps1 b/src/functions/assert/String/Should-NotBeLikeString.ps1 index 5d8620ba6..f09bfe90c 100644 --- a/src/functions/assert/String/Should-NotBeLikeString.ps1 +++ b/src/functions/assert/String/Should-NotBeLikeString.ps1 @@ -22,6 +22,42 @@ function Get-NotLikeDefaultFailureMessage ([String]$Expected, $Actual, [switch]$ } function Assert-NotLike { + <# + .SYNOPSIS + Asserts that the actual value is not like the expected value. + + .DESCRIPTION + The `Should-NotBeLike` assertion compares the actual value to the expected value using the `-notlike` operator. The `-notlike` operator is case-insensitive by default, but you can make it case-sensitive by using the `-CaseSensitive` switch. + + .PARAMETER Expected + The expected value. + + .PARAMETER Actual + The actual value. + + .PARAMETER CaseSensitive + Indicates that the comparison should be case-sensitive. + + .PARAMETER Because + The reason why the actual value should not be like the expected value. + + .EXAMPLE + ```powershell + "hello" | Should-NotBeLike "H*" + ``` + + This assertion will pass, because the actual value is not like the expected value. + + .EXAMPLE + ```powershell + "hello" | Should-NotBeLike "h*" -CaseSensitive + ``` + + This assertion will fail, because the actual value is like the expected value. + + .NOTES + The `Should-NotBeLike` assertion is the opposite of the `Should-BeLike` assertion. + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] diff --git a/src/functions/assert/String/Should-NotBeString.ps1 b/src/functions/assert/String/Should-NotBeString.ps1 index 13f39a56a..e1334c5f4 100644 --- a/src/functions/assert/String/Should-NotBeString.ps1 +++ b/src/functions/assert/String/Should-NotBeString.ps1 @@ -3,6 +3,43 @@ } function Assert-StringNotEqual { + <# + .SYNOPSIS + Asserts that the actual value is not equal to the expected value. + + .DESCRIPTION + The `Should-NotBeString` assertion compares the actual value to the expected value using the `-ne` operator. The `-ne` operator is case-insensitive by default, but you can make it case-sensitive by using the `-CaseSensitive` switch. + + .PARAMETER Expected + The expected value. + + .PARAMETER Actual + The actual value. + + .PARAMETER CaseSensitive + Indicates that the comparison should be case-sensitive. + + .PARAMETER IgnoreWhitespace + Indicates that the comparison should ignore whitespace. + + .PARAMETER Because + The reason why the actual value should not be equal to the expected value. + + .EXAMPLE + ```powershell + "hello" | Should-NotBeString "HELLO" + ``` + This assertion will pass, because the actual value is not equal to the expected value. + + .EXAMPLE + ```powershell + "hello" | Should-NotBeString "hello" -CaseSensitive + ``` + This assertion will fail, because the actual value is equal to the expected value. + + .NOTES + The `Should-NotBeString` assertion is the opposite of the `Should-BeString` assertion. + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] diff --git a/src/functions/assert/Time/Should-BeAfter.ps1 b/src/functions/assert/Time/Should-BeAfter.ps1 index b1e0050d0..2f5585f20 100644 --- a/src/functions/assert/Time/Should-BeAfter.ps1 +++ b/src/functions/assert/Time/Should-BeAfter.ps1 @@ -1,4 +1,61 @@ function Assert-After { + <# + .SYNOPSIS + Asserts that the provided [datetime] is after the expected [datetime]. + + .PARAMETER Actual + The actual [datetime] value. + + .PARAMETER Expected + The expected [datetime] value. + + .PARAMETER Time + The time to add or subtract from the current time. This parameter uses fluent time syntax e.g. 1minute. + + .PARAMETER Ago + Indicates that the -Time should be subtracted from the current time. + + .PARAMETER FromNow + Indicates that the -Time should be added to the current time. + + .PARAMETER Now + Indicates that the current time should be used as the expected time. + + .PARAMETER Because + The reason why the actual value should be after the expected value. + + .EXAMPLE + ```powershell + (Get-Date).AddDays(1) | Should-BeAfter (Get-Date) + ``` + + + This assertion will pass, because the actual value is after the expected value. + + .EXAMPLE + ```powershell + (Get-Date).AddDays(-1) | Should-BeAfter (Get-Date) + ``` + + This assertion will fail, because the actual value is not after the expected value. + + .EXAMPLE + ```powershell + (Get-Date).AddDays(1) | Should-BeAfter 10minutes -FromNow + ``` + + This assertion will pass, because the actual value is after the expected value. + + .EXAMPLE + ```powershell + (Get-Date).AddDays(-1) | Should-BeAfter -Time 3days -Ago + ``` + + This assertion will pass, because the actual value is after the expected value. + + .NOTES + The `Should-BeAfter` assertion is the opposite of the `Should-BeBefore` assertion. + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] [CmdletBinding(DefaultParameterSetName = "Now")] param ( diff --git a/src/functions/assert/Time/Should-BeBefore.ps1 b/src/functions/assert/Time/Should-BeBefore.ps1 index 5388f79d1..27a5ab0f6 100644 --- a/src/functions/assert/Time/Should-BeBefore.ps1 +++ b/src/functions/assert/Time/Should-BeBefore.ps1 @@ -1,4 +1,61 @@ function Assert-Before { + <# + .SYNOPSIS + Asserts that the provided [datetime] is before the expected [datetime]. + + .PARAMETER Actual + The actual [datetime] value. + + .PARAMETER Expected + The expected [datetime] value. + + .PARAMETER Time + The time to add or subtract from the current time. This parameter uses fluent time syntax e.g. 1minute. + + .PARAMETER Ago + Indicates that the -Time should be subtracted from the current time. + + .PARAMETER FromNow + Indicates that the -Time should be added to the current time. + + .PARAMETER Now + Indicates that the current time should be used as the expected time. + + .PARAMETER Because + The reason why the actual value should be before the expected value. + + .EXAMPLE + ```powershell + (Get-Date).AddDays(-1) | Should-BeBefore (Get-Date) + ``` + + This assertion will pass, because the actual value is before the expected value. + + .EXAMPLE + ```powershell + (Get-Date).AddDays(1) | Should-BeBefore (Get-Date) + ``` + This assertion will fail, because the actual value is not before the expected value. + + .EXAMPLE + ```powershell + (Get-Date).AddMinutes(1) | Should-BeBefore 10minutes -FromNow + ``` + + This assertion will pass, because the actual value is before the expected value. + + .EXAMPLE + ```powershell + + (Get-Date).AddDays(-2) | Should-BeBefore -Time 3days -Ago + ``` + + This assertion will pass, because the actual value is before the expected value. + + .NOTES + The `Should-BeBefore` assertion is the opposite of the `Should-BeAfter` assertion. + + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] [CmdletBinding(DefaultParameterSetName = "Now")] param ( diff --git a/src/functions/assert/Time/Should-BeFasterThan.ps1 b/src/functions/assert/Time/Should-BeFasterThan.ps1 index b41934db9..eaae5dde9 100644 --- a/src/functions/assert/Time/Should-BeFasterThan.ps1 +++ b/src/functions/assert/Time/Should-BeFasterThan.ps1 @@ -18,6 +18,36 @@ } function Assert-Faster { + <# + .SYNOPSIS + Asserts that the provided [timespan] or [scriptblock] is faster than the expected [timespan]. + + .PARAMETER Actual + The actual [timespan] or [scriptblock] value. + + .PARAMETER Expected + The expected [timespan] or fluent time value. + + .PARAMETER Because + The reason why the actual value should be faster than the expected value. + + .EXAMPLE + ```powershell + Measure-Command { Start-Sleep -Milliseconds 100 } | Should-BeFasterThan 1s + ``` + + This assertion will pass, because the actual value is faster than the expected value. + + .EXAMPLE + ```powershell + { Start-Sleep -Milliseconds 100 } | Should-BeFasterThan 50ms + ``` + + This assertion will fail, because the actual value is not faster than the expected value. + + .NOTES + The `Should-BeFasterThan` assertion is the opposite of the `Should-BeSlowerThan` assertion. + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] diff --git a/src/functions/assert/Time/Should-BeSlowerThan.ps1 b/src/functions/assert/Time/Should-BeSlowerThan.ps1 index 429c1c236..f639cdb6a 100644 --- a/src/functions/assert/Time/Should-BeSlowerThan.ps1 +++ b/src/functions/assert/Time/Should-BeSlowerThan.ps1 @@ -1,4 +1,42 @@ function Assert-Slower { + <# + .SYNOPSIS + Asserts that the provided [timespan] is slower than the expected [timespan]. + + .PARAMETER Actual + The actual [timespan] or [scriptblock] value. + + .PARAMETER Expected + The expected [timespan] or fluent time value. + + .PARAMETER Because + The reason why the actual value should be slower than the expected value. + + .EXAMPLE + ```powershell + { Start-Sleep -Seconds 10 } | Should-BeSlowerThan 2seconds + ``` + + This assertion will pass, because the actual value is slower than the expected value. + + .EXAMPLE + ```powershell + [Timespan]::fromSeconds(10) | Should-BeSlowerThan 2seconds + ``` + + This assertion will pass, because the actual value is slower than the expected value. + + .EXAMPLE + ```powershell + + { Start-Sleep -Seconds 1 } | Should-BeSlowerThan 10seconds + ``` + + This assertion will fail, because the actual value is not slower than the expected value. + + .NOTES + The `Should-BeSlowerThan` assertion is the opposite of the `Should-BeFasterThan` assertion. + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( [Parameter(Position = 1, ValueFromPipeline = $true)] diff --git a/tst/Help.Tests.ps1 b/tst/Help.Tests.ps1 index 6ed6347ad..8844af955 100644 --- a/tst/Help.Tests.ps1 +++ b/tst/Help.Tests.ps1 @@ -2,7 +2,7 @@ BeforeDiscovery { $moduleName = 'Pester' - $exportedFunctions = Get-Command -CommandType Cmdlet, Function -Module $moduleName | Where-Object { $_.Name -notlike "Assert-*" } + $exportedFunctions = Get-Command -CommandType Cmdlet, Function -Module $moduleName } Describe "Testing module help" -Tag 'Help' -ForEach @{ exportedFunctions = $exportedFunctions; moduleName = $moduleName } { From 46f46ac00a95295905d136f025e882ffbffe8d39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Tue, 14 May 2024 22:10:25 +0200 Subject: [PATCH 43/55] Add help and put back help tests --- src/Format2.ps1 | 2 +- src/Module.ps1 | 2 +- src/functions/assert/Boolean/Should-BeFalse.ps1 | 8 ++++++++ src/functions/assert/Boolean/Should-BeFalsy.ps1 | 8 ++++++++ src/functions/assert/Boolean/Should-BeTrue.ps1 | 8 ++++++++ src/functions/assert/Boolean/Should-BeTruthy.ps1 | 8 ++++++++ .../assert/General/Should-BeLessThanOrEqual.ps1 | 7 +++++++ src/functions/assert/General/Should-BeNull.ps1 | 6 ++++++ src/functions/assert/General/Should-BeSame.ps1 | 9 +++++++++ src/functions/assert/General/Should-HaveType.ps1 | 7 +++++++ src/functions/assert/General/Should-NotBe.ps1 | 7 +++++++ src/functions/assert/General/Should-NotBeNull.ps1 | 6 ++++++ src/functions/assert/General/Should-NotBeSame.ps1 | 9 +++++++++ .../assert/General/Should-NotHaveType.ps1 | 6 ++++++ .../assert/General/ShouldBe-GreaterThan.ps1 | 6 ++++++ .../assert/String/Should-BeEmptyString.ps1 | 6 ++++++ .../assert/String/Should-BeLikeString.ps1 | 14 ++++++++++---- src/functions/assert/String/Should-BeString.ps1 | 6 ++++++ .../assert/String/Should-NotBeEmptyString.ps1 | 6 ++++++ .../assert/String/Should-NotBeLikeString.ps1 | 14 ++++++++++---- src/functions/assert/String/Should-NotBeString.ps1 | 6 ++++++ .../assert/String/Should-NotBeWhiteSpaceString.ps1 | 6 ++++++ src/functions/assert/Time/Should-BeAfter.ps1 | 6 ++++++ src/functions/assert/Time/Should-BeBefore.ps1 | 5 +++++ src/functions/assert/Time/Should-BeFasterThan.ps1 | 6 ++++++ src/functions/assert/Time/Should-BeSlowerThan.ps1 | 6 ++++++ tst/Help.Tests.ps1 | 6 +++++- .../Collection/Should-BeCollection.Tests.ps1 | 1 + 28 files changed, 176 insertions(+), 11 deletions(-) diff --git a/src/Format2.ps1 b/src/Format2.ps1 index 41774bbda..a4a29d20c 100644 --- a/src/Format2.ps1 +++ b/src/Format2.ps1 @@ -39,7 +39,7 @@ function Format-Object2 ($Value, $Property, [switch]$Pretty) { $o = "$valueType{`n $($items -join ";`n ");`n}" } else { - $o = "$valueType{$($items -join '; ');}" + $o = "$valueType{$($items -join '; ')}" } $o diff --git a/src/Module.ps1 b/src/Module.ps1 index 04c0ae01b..4dea1c635 100644 --- a/src/Module.ps1 +++ b/src/Module.ps1 @@ -14,7 +14,7 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session & $SafeCommands['Set-Alias'] 'Should-BeTruthy' 'Assert-Truthy' & $SafeCommands['Set-Alias'] 'Should-All' 'Assert-All' & $SafeCommands['Set-Alias'] 'Should-Any' 'Assert-Any' -& $SafeCommands['Set-Alias'] 'Should-BeCollection' 'Assert-Contain' +& $SafeCommands['Set-Alias'] 'Should-BeCollection' 'Assert-Collection' & $SafeCommands['Set-Alias'] 'Should-ContainCollection' 'Assert-Contain' & $SafeCommands['Set-Alias'] 'Should-NotContainCollection' 'Assert-NotContain' & $SafeCommands['Set-Alias'] 'Should-BeEquivalent' 'Assert-Equivalent' diff --git a/src/functions/assert/Boolean/Should-BeFalse.ps1 b/src/functions/assert/Boolean/Should-BeFalse.ps1 index bd2f7bb8f..94a8e4900 100644 --- a/src/functions/assert/Boolean/Should-BeFalse.ps1 +++ b/src/functions/assert/Boolean/Should-BeFalse.ps1 @@ -28,6 +28,14 @@ All of these assertions will fail, because the actual value is not $false. + .NOTES + The `Should-BeFalse` assertion is the opposite of the `Should-BeTrue` assertion. + + .LINK + https://pester.dev/docs/commands/Should-BeFalse + + .LINK + https://pester.dev/docs/assertions #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( diff --git a/src/functions/assert/Boolean/Should-BeFalsy.ps1 b/src/functions/assert/Boolean/Should-BeFalsy.ps1 index f6bc4ee4f..d937516f0 100644 --- a/src/functions/assert/Boolean/Should-BeFalsy.ps1 +++ b/src/functions/assert/Boolean/Should-BeFalsy.ps1 @@ -28,6 +28,14 @@ These assertions will fail, because the actual value is not $false or falsy. + .NOTES + The `Should-BeFalsy` assertion is the opposite of the `Should-BeTruthy` assertion. + + .LINK + https://pester.dev/docs/commands/Should-BeFalsy + + .LINK + https://pester.dev/docs/assertions #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( diff --git a/src/functions/assert/Boolean/Should-BeTrue.ps1 b/src/functions/assert/Boolean/Should-BeTrue.ps1 index 02f2f3617..fab550f97 100644 --- a/src/functions/assert/Boolean/Should-BeTrue.ps1 +++ b/src/functions/assert/Boolean/Should-BeTrue.ps1 @@ -28,6 +28,14 @@ All of these assertions will fail, because the actual value is not $true. + .NOTES + The `Should-BeTrue` assertion is the opposite of the `Should-BeFalse` assertion. + + .LINK + https://pester.dev/docs/commands/Should-BeTrue + + .LINK + https://pester.dev/docs/assertions #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( diff --git a/src/functions/assert/Boolean/Should-BeTruthy.ps1 b/src/functions/assert/Boolean/Should-BeTruthy.ps1 index d70348756..28538ab7c 100644 --- a/src/functions/assert/Boolean/Should-BeTruthy.ps1 +++ b/src/functions/assert/Boolean/Should-BeTruthy.ps1 @@ -29,6 +29,14 @@ All of these assertions will fail, because the actual value is not $true or truthy. + .NOTES + The `Should-BeTruthy` assertion is the opposite of the `Should-BeFalsy` assertion. + + .LINK + https://pester.dev/docs/commands/Should-BeTruthy + + .LINK + https://pester.dev/docs/assertions #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( diff --git a/src/functions/assert/General/Should-BeLessThanOrEqual.ps1 b/src/functions/assert/General/Should-BeLessThanOrEqual.ps1 index 0d32e72de..6340c2d84 100644 --- a/src/functions/assert/General/Should-BeLessThanOrEqual.ps1 +++ b/src/functions/assert/General/Should-BeLessThanOrEqual.ps1 @@ -27,7 +27,14 @@ This assertion will fail, because the actual value is not less than or equal to the expected value. + .NOTES + The `Should-BeLessThanOrEqual` assertion is the opposite of the `Should-BeGreaterThan` assertion. + .LINK + https://pester.dev/docs/commands/Should-BeLessThanOrEqual + + .LINK + https://pester.dev/docs/assertions #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( diff --git a/src/functions/assert/General/Should-BeNull.ps1 b/src/functions/assert/General/Should-BeNull.ps1 index 6dfe5cf0f..2d4145ca1 100644 --- a/src/functions/assert/General/Should-BeNull.ps1 +++ b/src/functions/assert/General/Should-BeNull.ps1 @@ -15,6 +15,12 @@ ``` This assertion will pass, because the actual value is `$null`. + + .LINK + https://pester.dev/docs/commands/Should-BeNull + + .LINK + https://pester.dev/docs/assertions #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] diff --git a/src/functions/assert/General/Should-BeSame.ps1 b/src/functions/assert/General/Should-BeSame.ps1 index c3812a06a..22dddddf4 100644 --- a/src/functions/assert/General/Should-BeSame.ps1 +++ b/src/functions/assert/General/Should-BeSame.ps1 @@ -28,6 +28,15 @@ ``` This assertion will fail, because the actual value is not the same instance as the expected value. + + .NOTES + The `Should-BeSame` assertion is the opposite of the `Should-NotBeSame` assertion. + + .LINK + https://pester.dev/docs/commands/Should-BeSame + + .LINK + https://pester.dev/docs/assertions #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( diff --git a/src/functions/assert/General/Should-HaveType.ps1 b/src/functions/assert/General/Should-HaveType.ps1 index e0167fe20..adb776a14 100644 --- a/src/functions/assert/General/Should-HaveType.ps1 +++ b/src/functions/assert/General/Should-HaveType.ps1 @@ -19,6 +19,13 @@ ``` These assertions will pass, because the actual value is of the expected type. + + .LINK + https://pester.dev/docs/commands/Should-HaveType + + .LINK + https://pester.dev/docs/assertions + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( diff --git a/src/functions/assert/General/Should-NotBe.ps1 b/src/functions/assert/General/Should-NotBe.ps1 index 6c84509a8..5081c2afb 100644 --- a/src/functions/assert/General/Should-NotBe.ps1 +++ b/src/functions/assert/General/Should-NotBe.ps1 @@ -19,6 +19,13 @@ ``` These assertions will pass, because the actual value is not equal to the expected value. + + .LINK + https://pester.dev/docs/commands/Should-NotBe + + .LINK + https://pester.dev/docs/assertions + #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( diff --git a/src/functions/assert/General/Should-NotBeNull.ps1 b/src/functions/assert/General/Should-NotBeNull.ps1 index 584c9cbbc..8387fca23 100644 --- a/src/functions/assert/General/Should-NotBeNull.ps1 +++ b/src/functions/assert/General/Should-NotBeNull.ps1 @@ -16,6 +16,12 @@ ``` These assertions will pass, because the actual value is not `$null. + + .LINK + https://pester.dev/docs/commands/Should-NotBeNull + + .LINK + https://pester.dev/docs/assertions #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( diff --git a/src/functions/assert/General/Should-NotBeSame.ps1 b/src/functions/assert/General/Should-NotBeSame.ps1 index 13d735360..15da0a858 100644 --- a/src/functions/assert/General/Should-NotBeSame.ps1 +++ b/src/functions/assert/General/Should-NotBeSame.ps1 @@ -26,6 +26,15 @@ ``` This assertion will fail, because the actual value is the same instance as the expected value. + + .NOTES + The `Should-NotBeSame` assertion is the opposite of the `Should-BeSame` assertion. + + .LINK + https://pester.dev/docs/commands/Should-NotBeSame + + .LINK + https://pester.dev/docs/assertions #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( diff --git a/src/functions/assert/General/Should-NotHaveType.ps1 b/src/functions/assert/General/Should-NotHaveType.ps1 index eb7c20c1a..1193f6042 100644 --- a/src/functions/assert/General/Should-NotHaveType.ps1 +++ b/src/functions/assert/General/Should-NotHaveType.ps1 @@ -22,6 +22,12 @@ .NOTES This assertion is the opposite of `Should-HaveType`. + + .LINK + https://pester.dev/docs/commands/Should-NotHaveType + + .LINK + https://pester.dev/docs/assertions #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( diff --git a/src/functions/assert/General/ShouldBe-GreaterThan.ps1 b/src/functions/assert/General/ShouldBe-GreaterThan.ps1 index 94a9a6dd0..6ffb97db8 100644 --- a/src/functions/assert/General/ShouldBe-GreaterThan.ps1 +++ b/src/functions/assert/General/ShouldBe-GreaterThan.ps1 @@ -19,6 +19,12 @@ ``` These assertions will pass, because the actual value is greater than the expected value. + + .LINK + https://pester.dev/docs/commands/Should-BeGreaterThan + + .LINK + https://pester.dev/docs/assertions #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] diff --git a/src/functions/assert/String/Should-BeEmptyString.ps1 b/src/functions/assert/String/Should-BeEmptyString.ps1 index b2106edcc..3a53dc2d1 100644 --- a/src/functions/assert/String/Should-BeEmptyString.ps1 +++ b/src/functions/assert/String/Should-BeEmptyString.ps1 @@ -34,6 +34,12 @@ ``` All the tests above will fail, the input is not a string. + + .LINK + https://pester.dev/docs/commands/Should-BeEmptyString + + .LINK + https://pester.dev/docs/assertions #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( diff --git a/src/functions/assert/String/Should-BeLikeString.ps1 b/src/functions/assert/String/Should-BeLikeString.ps1 index 047105317..07333e690 100644 --- a/src/functions/assert/String/Should-BeLikeString.ps1 +++ b/src/functions/assert/String/Should-BeLikeString.ps1 @@ -19,7 +19,7 @@ function Assert-Like { Asserts that the actual value is like the expected value. .DESCRIPTION - The `Should-BeLike` assertion compares the actual value to the expected value using the `-like` operator. The `-like` operator is case-insensitive by default, but you can make it case-sensitive by using the `-CaseSensitive` switch. + The `Should-BeLikeString` assertion compares the actual value to the expected value using the `-like` operator. The `-like` operator is case-insensitive by default, but you can make it case-sensitive by using the `-CaseSensitive` switch. .PARAMETER Expected The expected value. @@ -35,7 +35,7 @@ function Assert-Like { .EXAMPLE ```powershell - "hello" | Should-BeLike "h*" + "hello" | Should-BeLikeString"h*" ``` This assertion will pass, because the actual value is like the expected value. @@ -43,13 +43,19 @@ function Assert-Like { .EXAMPLE ```powershell - "hello" | Should-BeLike "H*" -CaseSensitive + "hello" | Should-BeLikeString"H*" -CaseSensitive ``` This assertion will fail, because the actual value is not like the expected value. .NOTES - The `Should-BeLike` assertion is the opposite of the `Should-NotBeLike` assertion. + The `Should-BeLikeString` assertion is the opposite of the `Should-NotBeLikeString` assertion. + + .LINK + https://pester.dev/docs/commands/Should-BeLikeString + + .LINK + https://pester.dev/docs/assertions #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( diff --git a/src/functions/assert/String/Should-BeString.ps1 b/src/functions/assert/String/Should-BeString.ps1 index c089dbe8b..afff447fa 100644 --- a/src/functions/assert/String/Should-BeString.ps1 +++ b/src/functions/assert/String/Should-BeString.ps1 @@ -62,6 +62,12 @@ function Assert-StringEqual { .NOTES The `Should-BeString` assertion is the opposite of the `Should-NotBeString` assertion. + + .LINK + https://pester.dev/docs/commands/Should-BeString + + .LINK + https://pester.dev/docs/assertions #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( diff --git a/src/functions/assert/String/Should-NotBeEmptyString.ps1 b/src/functions/assert/String/Should-NotBeEmptyString.ps1 index 212096c57..3d6352ce2 100644 --- a/src/functions/assert/String/Should-NotBeEmptyString.ps1 +++ b/src/functions/assert/String/Should-NotBeEmptyString.ps1 @@ -34,6 +34,12 @@ ``` All the tests above will fail, the input is not a string. + + .LINK + https://pester.dev/docs/commands/Should-NotBeNullOrEmptyString + + .LINK + https://pester.dev/docs/assertions #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( diff --git a/src/functions/assert/String/Should-NotBeLikeString.ps1 b/src/functions/assert/String/Should-NotBeLikeString.ps1 index f09bfe90c..d66c11992 100644 --- a/src/functions/assert/String/Should-NotBeLikeString.ps1 +++ b/src/functions/assert/String/Should-NotBeLikeString.ps1 @@ -27,7 +27,7 @@ function Assert-NotLike { Asserts that the actual value is not like the expected value. .DESCRIPTION - The `Should-NotBeLike` assertion compares the actual value to the expected value using the `-notlike` operator. The `-notlike` operator is case-insensitive by default, but you can make it case-sensitive by using the `-CaseSensitive` switch. + The `Should-NotBeLikeString` assertion compares the actual value to the expected value using the `-notlike` operator. The `-notlike` operator is case-insensitive by default, but you can make it case-sensitive by using the `-CaseSensitive` switch. .PARAMETER Expected The expected value. @@ -43,20 +43,26 @@ function Assert-NotLike { .EXAMPLE ```powershell - "hello" | Should-NotBeLike "H*" + "hello" | Should-NotBeLikeString "H*" ``` This assertion will pass, because the actual value is not like the expected value. .EXAMPLE ```powershell - "hello" | Should-NotBeLike "h*" -CaseSensitive + "hello" | Should-NotBeLikeString "h*" -CaseSensitive ``` This assertion will fail, because the actual value is like the expected value. .NOTES - The `Should-NotBeLike` assertion is the opposite of the `Should-BeLike` assertion. + The `Should-NotBeLikeString` assertion is the opposite of the `Should-BeLikeString` assertion. + + .LINK + https://pester.dev/docs/commands/Should-NotBeLikeString + + .LINK + https://pester.dev/docs/assertions #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( diff --git a/src/functions/assert/String/Should-NotBeString.ps1 b/src/functions/assert/String/Should-NotBeString.ps1 index e1334c5f4..6cc0a2019 100644 --- a/src/functions/assert/String/Should-NotBeString.ps1 +++ b/src/functions/assert/String/Should-NotBeString.ps1 @@ -39,6 +39,12 @@ function Assert-StringNotEqual { .NOTES The `Should-NotBeString` assertion is the opposite of the `Should-BeString` assertion. + + .LINK + https://pester.dev/docs/commands/Should-NotBeString + + .LINK + https://pester.dev/docs/assertions #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( diff --git a/src/functions/assert/String/Should-NotBeWhiteSpaceString.ps1 b/src/functions/assert/String/Should-NotBeWhiteSpaceString.ps1 index 613c8901e..c75ee0548 100644 --- a/src/functions/assert/String/Should-NotBeWhiteSpaceString.ps1 +++ b/src/functions/assert/String/Should-NotBeWhiteSpaceString.ps1 @@ -35,6 +35,12 @@ ``` All the tests above will fail, the input is not a string. + + .LINK + https://pester.dev/docs/commands/Should-NotBeNullOrWhiteSpaceString + + .LINK + https://pester.dev/docs/assertions #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( diff --git a/src/functions/assert/Time/Should-BeAfter.ps1 b/src/functions/assert/Time/Should-BeAfter.ps1 index 2f5585f20..96938fcc2 100644 --- a/src/functions/assert/Time/Should-BeAfter.ps1 +++ b/src/functions/assert/Time/Should-BeAfter.ps1 @@ -55,6 +55,12 @@ .NOTES The `Should-BeAfter` assertion is the opposite of the `Should-BeBefore` assertion. + + .LINK + https://pester.dev/docs/commands/Should-BeAfter + + .LINK + https://pester.dev/docs/assertions #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] [CmdletBinding(DefaultParameterSetName = "Now")] diff --git a/src/functions/assert/Time/Should-BeBefore.ps1 b/src/functions/assert/Time/Should-BeBefore.ps1 index 27a5ab0f6..7c84be166 100644 --- a/src/functions/assert/Time/Should-BeBefore.ps1 +++ b/src/functions/assert/Time/Should-BeBefore.ps1 @@ -55,6 +55,11 @@ .NOTES The `Should-BeBefore` assertion is the opposite of the `Should-BeAfter` assertion. + .LINK + https://pester.dev/docs/commands/Should-BeBefore + + .LINK + https://pester.dev/docs/assertions #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] [CmdletBinding(DefaultParameterSetName = "Now")] diff --git a/src/functions/assert/Time/Should-BeFasterThan.ps1 b/src/functions/assert/Time/Should-BeFasterThan.ps1 index eaae5dde9..0810adfbe 100644 --- a/src/functions/assert/Time/Should-BeFasterThan.ps1 +++ b/src/functions/assert/Time/Should-BeFasterThan.ps1 @@ -47,6 +47,12 @@ function Assert-Faster { .NOTES The `Should-BeFasterThan` assertion is the opposite of the `Should-BeSlowerThan` assertion. + + .LINK + https://pester.dev/docs/commands/Should-BeFasterThan + + .LINK + https://pester.dev/docs/assertions #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( diff --git a/src/functions/assert/Time/Should-BeSlowerThan.ps1 b/src/functions/assert/Time/Should-BeSlowerThan.ps1 index f639cdb6a..5849da3e2 100644 --- a/src/functions/assert/Time/Should-BeSlowerThan.ps1 +++ b/src/functions/assert/Time/Should-BeSlowerThan.ps1 @@ -36,6 +36,12 @@ .NOTES The `Should-BeSlowerThan` assertion is the opposite of the `Should-BeFasterThan` assertion. + + .LINK + https://pester.dev/docs/commands/Should-BeSlowerThan + + .LINK + https://pester.dev/docs/assertions #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseProcessBlockForPipelineCommand', '')] param ( diff --git a/tst/Help.Tests.ps1 b/tst/Help.Tests.ps1 index 8844af955..c9ff59c1d 100644 --- a/tst/Help.Tests.ps1 +++ b/tst/Help.Tests.ps1 @@ -32,8 +32,12 @@ Describe "Testing module help" -Tag 'Help' -ForEach @{ exportedFunctions = $expo 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' + $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/$($help.Name)" -Because 'first uri-link should be to online version of this help topic' + $firstUri | Should -Be "https://pester.dev/docs/commands/$helpName" -Because 'first uri-link should be to online version of this help topic' } # Skipping Assert-MockCalled and Assert-VerifiableMock which are deprecated and missing docs diff --git a/tst/functions/assert/Collection/Should-BeCollection.Tests.ps1 b/tst/functions/assert/Collection/Should-BeCollection.Tests.ps1 index be5039138..2ea61d79e 100644 --- a/tst/functions/assert/Collection/Should-BeCollection.Tests.ps1 +++ b/tst/functions/assert/Collection/Should-BeCollection.Tests.ps1 @@ -1,5 +1,6 @@ Set-StrictMode -Version Latest + InPesterModuleScope { Describe "Should-BeCollection" { It "Passes when collections have the same count and items" -ForEach @( From 90a887d29d24c0d842135881a2d9b4d3329c9163 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Sat, 18 May 2024 14:59:22 +0200 Subject: [PATCH 44/55] assert --- long list of stuff to do.md | 40 ------------------- .../assert/Collection/Should-All.ps1 | 2 +- .../assert/Collection/Should-Any.ps1 | 2 +- .../assert/Collection/Should-BeCollection.ps1 | 2 +- .../Collection/Should-ContainCollection.ps1 | 2 +- .../Should-NotContainCollection.ps1 | 2 +- .../Equivalence/Should-BeEquivalent.ps1 | 9 +++++ src/functions/assert/General/Should-Be.ps1 | 3 +- .../General/Should-BeGreaterThanOrEqual.ps1 | 2 +- .../assert/General/Should-BeLessThan.ps1 | 2 +- .../General/Should-BeLessThanOrEqual.ps1 | 2 +- .../assert/General/Should-BeSame.ps1 | 2 +- .../assert/General/Should-HaveType.ps1 | 2 +- src/functions/assert/General/Should-NotBe.ps1 | 3 +- .../assert/General/Should-NotBeSame.ps1 | 2 +- .../assert/General/Should-NotHaveType.ps1 | 2 +- .../assert/General/ShouldBe-GreaterThan.ps1 | 2 +- .../assert/String/Should-BeString.ps1 | 2 +- .../Collection/Should-BeCollection.Tests.ps1 | 2 + 19 files changed, 29 insertions(+), 56 deletions(-) delete mode 100644 long list of stuff to do.md diff --git a/long list of stuff to do.md b/long list of stuff to do.md deleted file mode 100644 index 0bfa2a0bc..000000000 --- a/long list of stuff to do.md +++ /dev/null @@ -1,40 +0,0 @@ -- [ ] Should-BeNull -- [ ] Should-BeType -- [ ] Should-BeOneOf -- [ ] Should-BeSame -- [ ] Should-MatchString -- [ ] Should-BeLikeString -- [ ] Should-StartWithString -- [ ] Should-EndWithString -- [ ] -- [ ] Should-BeCollection -- [ ] Should-BeInCollection -- [ ] Should-BeSame -- [ ] Should-BeTrue -- [ ] Should-BeFalse -- [ ] Should-MatchString -- [ ] Should-ContainCollectionString -- [ ] Should-BeEmptyString -- [ ] Should-BeWhitespaceString -- [ ] Should-BeEquivalentToString -- [ ] Should-StartWithString -- [ ] Should-EndWithString -- [ ] Should-BeLikeString -- [ ] Should-BeGreaterThanOrEqual -- [ ] Should-BeGreaterThan -- [ ] Should-BeLessThanOrEqual -- [ ] Should-BeLessThan -- [ ] Should-BeInRange -- [ ] Should-Be -- [ ] Should-HaveCount -- [ ] Should-BeCollection -- [ ] Should-HaveCountGreaterThan -- [ ] Should-HaveCountGreaterThanOrEqual -- [ ] Should-HaveCountLessThan -- [ ] Should-HaveCountLessThanOrEqual -- [ ] -- [ ] -- [ ] -- [ ] -- [ ] -- [ ] Should-BeCollection 1,2,3 diff --git a/src/functions/assert/Collection/Should-All.ps1 b/src/functions/assert/Collection/Should-All.ps1 index 5256a1eaf..126a7db6a 100644 --- a/src/functions/assert/Collection/Should-All.ps1 +++ b/src/functions/assert/Collection/Should-All.ps1 @@ -40,7 +40,7 @@ param ( [Parameter(ValueFromPipeline = $true, Position = 1)] $Actual, - [Parameter(Position = 0, Mandatory = $true)] + [Parameter(Position = 0, Mandatory)] [scriptblock]$FilterScript, [String]$Because ) diff --git a/src/functions/assert/Collection/Should-Any.ps1 b/src/functions/assert/Collection/Should-Any.ps1 index 7d98f67ac..f546babfd 100644 --- a/src/functions/assert/Collection/Should-Any.ps1 +++ b/src/functions/assert/Collection/Should-Any.ps1 @@ -39,7 +39,7 @@ param ( [Parameter(ValueFromPipeline = $true, Position = 1)] $Actual, - [Parameter(Position = 0, Mandatory = $true)] + [Parameter(Position = 0, Mandatory)] [scriptblock]$FilterScript, [String]$Because ) diff --git a/src/functions/assert/Collection/Should-BeCollection.ps1 b/src/functions/assert/Collection/Should-BeCollection.ps1 index 1bea0035b..93624ec20 100644 --- a/src/functions/assert/Collection/Should-BeCollection.ps1 +++ b/src/functions/assert/Collection/Should-BeCollection.ps1 @@ -41,7 +41,7 @@ param ( [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position = 0)] + [Parameter(Position = 0, Mandatory)] $Expected, [String]$Because ) diff --git a/src/functions/assert/Collection/Should-ContainCollection.ps1 b/src/functions/assert/Collection/Should-ContainCollection.ps1 index 7c1e3d1e2..f74b57ebc 100644 --- a/src/functions/assert/Collection/Should-ContainCollection.ps1 +++ b/src/functions/assert/Collection/Should-ContainCollection.ps1 @@ -40,7 +40,7 @@ param ( [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position = 0)] + [Parameter(Position = 0, Mandatory)] $Expected, [String]$Because ) diff --git a/src/functions/assert/Collection/Should-NotContainCollection.ps1 b/src/functions/assert/Collection/Should-NotContainCollection.ps1 index 3baf27ef4..57a9e2555 100644 --- a/src/functions/assert/Collection/Should-NotContainCollection.ps1 +++ b/src/functions/assert/Collection/Should-NotContainCollection.ps1 @@ -40,7 +40,7 @@ param ( [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position = 0)] + [Parameter(Position = 0, Mandatory)] $Expected, [String]$Because ) diff --git a/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 b/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 index 46f46e72a..aa4aa8ecb 100644 --- a/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 +++ b/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 @@ -624,6 +624,9 @@ function Assert-Equivalent { .PARAMETER Expected The expected object to compare. + .PARAMETER Because + The reason why the input should be the expected value. + .PARAMETER Options Options for the comparison. Get-EquivalencyOption function is called to get the default options. @@ -669,12 +672,18 @@ function Assert-Equivalent { #> [CmdletBinding()] param( + [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, + [Parameter(Position = 0, Mandatory)] $Expected, + [String]$Because, $Options = (Get-EquivalencyOption), [Switch] $StrictOrder ) + $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput + $Actual = $collectedInput.Actual + $areDifferent = Compare-Equivalent -Actual $Actual -Expected $Expected -Options $Options | Out-String if ($areDifferent) { diff --git a/src/functions/assert/General/Should-Be.ps1 b/src/functions/assert/General/Should-Be.ps1 index 50168e40a..4537aad70 100644 --- a/src/functions/assert/General/Should-Be.ps1 +++ b/src/functions/assert/General/Should-Be.ps1 @@ -31,7 +31,8 @@ param ( [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position = 0)] + [AllowNull()] + [Parameter(Position = 0, Mandatory)] $Expected, [String]$Because ) diff --git a/src/functions/assert/General/Should-BeGreaterThanOrEqual.ps1 b/src/functions/assert/General/Should-BeGreaterThanOrEqual.ps1 index 5ee6911b6..c528c5b5c 100644 --- a/src/functions/assert/General/Should-BeGreaterThanOrEqual.ps1 +++ b/src/functions/assert/General/Should-BeGreaterThanOrEqual.ps1 @@ -31,7 +31,7 @@ param ( [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position = 0)] + [Parameter(Position = 0, Mandatory)] $Expected, [String]$Because ) diff --git a/src/functions/assert/General/Should-BeLessThan.ps1 b/src/functions/assert/General/Should-BeLessThan.ps1 index 456cd6d72..17fc6c926 100644 --- a/src/functions/assert/General/Should-BeLessThan.ps1 +++ b/src/functions/assert/General/Should-BeLessThan.ps1 @@ -31,7 +31,7 @@ param ( [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position = 0)] + [Parameter(Position = 0, Mandatory)] $Expected, [String]$Because ) diff --git a/src/functions/assert/General/Should-BeLessThanOrEqual.ps1 b/src/functions/assert/General/Should-BeLessThanOrEqual.ps1 index 6340c2d84..69ed80355 100644 --- a/src/functions/assert/General/Should-BeLessThanOrEqual.ps1 +++ b/src/functions/assert/General/Should-BeLessThanOrEqual.ps1 @@ -40,7 +40,7 @@ param ( [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position = 0)] + [Parameter(Position = 0, Mandatory)] $Expected, [String]$Because ) diff --git a/src/functions/assert/General/Should-BeSame.ps1 b/src/functions/assert/General/Should-BeSame.ps1 index 22dddddf4..ee3193f5a 100644 --- a/src/functions/assert/General/Should-BeSame.ps1 +++ b/src/functions/assert/General/Should-BeSame.ps1 @@ -42,7 +42,7 @@ param ( [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position = 0)] + [Parameter(Position = 0, Mandatory)] $Expected, [String]$Because ) diff --git a/src/functions/assert/General/Should-HaveType.ps1 b/src/functions/assert/General/Should-HaveType.ps1 index adb776a14..67f60364e 100644 --- a/src/functions/assert/General/Should-HaveType.ps1 +++ b/src/functions/assert/General/Should-HaveType.ps1 @@ -31,7 +31,7 @@ param ( [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position = 0)] + [Parameter(Position = 0, Mandatory)] [Type]$Expected, [String]$Because ) diff --git a/src/functions/assert/General/Should-NotBe.ps1 b/src/functions/assert/General/Should-NotBe.ps1 index 5081c2afb..59700808b 100644 --- a/src/functions/assert/General/Should-NotBe.ps1 +++ b/src/functions/assert/General/Should-NotBe.ps1 @@ -31,7 +31,8 @@ param ( [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position = 0)] + [AllowNull()] + [Parameter(Position = 0, Mandatory)] $Expected, [String]$Because ) diff --git a/src/functions/assert/General/Should-NotBeSame.ps1 b/src/functions/assert/General/Should-NotBeSame.ps1 index 15da0a858..056b6d83c 100644 --- a/src/functions/assert/General/Should-NotBeSame.ps1 +++ b/src/functions/assert/General/Should-NotBeSame.ps1 @@ -40,7 +40,7 @@ param ( [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position = 0)] + [Parameter(Position = 0, Mandatory)] $Expected, [String]$Because ) diff --git a/src/functions/assert/General/Should-NotHaveType.ps1 b/src/functions/assert/General/Should-NotHaveType.ps1 index 1193f6042..85f8eeb55 100644 --- a/src/functions/assert/General/Should-NotHaveType.ps1 +++ b/src/functions/assert/General/Should-NotHaveType.ps1 @@ -33,7 +33,7 @@ param ( [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position = 0)] + [Parameter(Position = 0, Mandatory)] [Type]$Expected, [String]$Because ) diff --git a/src/functions/assert/General/ShouldBe-GreaterThan.ps1 b/src/functions/assert/General/ShouldBe-GreaterThan.ps1 index 6ffb97db8..cf2728009 100644 --- a/src/functions/assert/General/ShouldBe-GreaterThan.ps1 +++ b/src/functions/assert/General/ShouldBe-GreaterThan.ps1 @@ -31,7 +31,7 @@ param ( [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position = 0)] + [Parameter(Position = 0, Mandatory)] $Expected, [String]$Because ) diff --git a/src/functions/assert/String/Should-BeString.ps1 b/src/functions/assert/String/Should-BeString.ps1 index afff447fa..3471c99b5 100644 --- a/src/functions/assert/String/Should-BeString.ps1 +++ b/src/functions/assert/String/Should-BeString.ps1 @@ -73,7 +73,7 @@ function Assert-StringEqual { param ( [Parameter(Position = 1, ValueFromPipeline = $true)] $Actual, - [Parameter(Position = 0)] + [Parameter(Position = 0, Mandatory)] [String]$Expected, [String]$Because, [switch]$CaseSensitive, diff --git a/tst/functions/assert/Collection/Should-BeCollection.Tests.ps1 b/tst/functions/assert/Collection/Should-BeCollection.Tests.ps1 index 2ea61d79e..3b9d6139c 100644 --- a/tst/functions/assert/Collection/Should-BeCollection.Tests.ps1 +++ b/tst/functions/assert/Collection/Should-BeCollection.Tests.ps1 @@ -1,5 +1,7 @@ Set-StrictMode -Version Latest +# TODO: Implement the Should-BeCollection tests, I just don't want to remove it from the current PR just to put it back afterwards. +return InPesterModuleScope { Describe "Should-BeCollection" { From 7a971c50f6640424ff4a8fce874269fe183a2650 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Mon, 20 May 2024 09:25:59 +0200 Subject: [PATCH 45/55] Update src/functions/assert/General/Should-NotHaveType.ps1 Co-authored-by: Frode Flaten <3436158+fflaten@users.noreply.github.com> --- src/functions/assert/General/Should-NotHaveType.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/functions/assert/General/Should-NotHaveType.ps1 b/src/functions/assert/General/Should-NotHaveType.ps1 index 85f8eeb55..762397371 100644 --- a/src/functions/assert/General/Should-NotHaveType.ps1 +++ b/src/functions/assert/General/Should-NotHaveType.ps1 @@ -14,8 +14,8 @@ .EXAMPLE ```powershell - "hello" | Should-NotHaveType [Int32] - 1 | Should-NotHaveType [String] + "hello" | Should-NotHaveType ([Int32]) + 1 | Should-NotHaveType ([String]) ``` These assertions will pass, because the actual value is not of the expected type. From a18e74682de6924a63436a3ef885f56123dd1197 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Mon, 20 May 2024 22:05:46 +0200 Subject: [PATCH 46/55] Update src/functions/assert/General/Should-HaveType.ps1 Co-authored-by: Frode Flaten <3436158+fflaten@users.noreply.github.com> --- src/functions/assert/General/Should-HaveType.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/functions/assert/General/Should-HaveType.ps1 b/src/functions/assert/General/Should-HaveType.ps1 index 67f60364e..1ec6a24a9 100644 --- a/src/functions/assert/General/Should-HaveType.ps1 +++ b/src/functions/assert/General/Should-HaveType.ps1 @@ -14,8 +14,8 @@ .EXAMPLE ```powershell - "hello" | Should-HaveType [String] - 1 | Should-HaveType [Int32] + "hello" | Should-HaveType ([String]) + 1 | Should-HaveType ([Int32]) ``` These assertions will pass, because the actual value is of the expected type. From 1b3f0b5127ff0cb5d6af7a42666a71c0b90161ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Mon, 20 May 2024 22:07:41 +0200 Subject: [PATCH 47/55] Update src/functions/assert/Equivalence/Should-BeEquivalent.ps1 Co-authored-by: Frode Flaten <3436158+fflaten@users.noreply.github.com> --- src/functions/assert/Equivalence/Should-BeEquivalent.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 b/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 index aa4aa8ecb..cb43f6f03 100644 --- a/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 +++ b/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 @@ -609,7 +609,7 @@ function Compare-Equivalent { return } - v "`$Expected is an object of type $$Expected.GetType(), we will be comparing `$Actual to objects." + v "`$Expected is an object of type $(Format-Nicely2 $Expected.GetType()), we will be comparing `$Actual to objects." Compare-ObjectEquivalent -Expected $Expected -Actual $Actual -Property $Path -Options $Options } From 29f5cb89300622d1fa481dd0ad99c920a272a221 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Mon, 20 May 2024 22:11:04 +0200 Subject: [PATCH 48/55] Revert test, fix safe commands etc. --- .gitignore | 1 - azure-pipelines.yml | 2 +- src/functions/assert/Common/Collect-Input.ps1 | 3 +- .../Equivalence/Should-BeEquivalent.ps1 | 36 ++++++------ .../assert/Exception/Should-Throw.ps1 | 6 +- test.ps1 | 45 ++------------- tst/Format2.Tests.ps1 | 8 +-- .../Common/Get-AssertionMessage.Tests.ps1 | 4 +- .../Should-BeEquivalent.Options.Tests.ps1 | 52 ++++++++--------- .../Equivalence/Should-BeEquivalent.Tests.ps1 | 56 +++++++++---------- .../assert/Exception/Should-Throw.Tests.ps1 | 4 +- 11 files changed, 91 insertions(+), 126 deletions(-) diff --git a/.gitignore b/.gitignore index 28591e1ea..e02bf5456 100644 --- a/.gitignore +++ b/.gitignore @@ -5,7 +5,6 @@ vendor/packages/ .vscode/ # But don't exclude settings.json !.vscode/settings.json -!.vscode/launch.json coverage.xml testResults.xml diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 72162aff1..9e3f8f1a1 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -112,7 +112,7 @@ stages: targetType: inline pwsh: $(pwsh) script: | - & ./test.ps1 -CI -NoBuild + & ./test.ps1 -CI -PassThru -NoBuild workingDirectory: '$(Build.SourcesDirectory)' - task: PublishCodeCoverageResults@2 inputs: diff --git a/src/functions/assert/Common/Collect-Input.ps1 b/src/functions/assert/Common/Collect-Input.ps1 index d09285216..4180a4eb0 100644 --- a/src/functions/assert/Common/Collect-Input.ps1 +++ b/src/functions/assert/Common/Collect-Input.ps1 @@ -7,7 +7,8 @@ # It is always $null or object[] containing all the received items. $PipelineInput, # This tell us if we were called by | syntax or not. Caller needs to pass in $MyInvocation.ExpectingInput. - $IsPipelineInput, + [Parameter(Mandatory)] + [bool] $IsPipelineInput, # This unwraps input provided by |. The effect of this is that we get single item input directly, # and not wrapped in array. E.g. 1 | Should-Be -> 1, and not 1 | Should-Be -> @(1). # diff --git a/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 b/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 index aa4aa8ecb..f48e4eed9 100644 --- a/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 +++ b/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 @@ -179,7 +179,7 @@ function Compare-DataTableEquivalent ($Expected, $Actual, $Property, $Options) { } $Expected = Format-Nicely2 -Value $Expected $Actual = Format-Nicely2 -Value $Actual - $notFoundFormatted = Format-Nicely2 -Value ( $notFound | ForEach-Object { Format-Nicely2 -Value $_ } ) + $notFoundFormatted = Format-Nicely2 -Value ( $notFound | & $SafeCommands['ForEach-Object'] { Format-Nicely2 -Value $_ } ) if ($notFound) { $propertyMessage = if ($Property) { " in property $Property which is" } @@ -290,24 +290,24 @@ function Compare-HashtableEquivalent ($Actual, $Expected, $Property, $Options) { if (!$Options.ExcludePathsNotOnExpected) { # fix for powershell 2 where the array needs to be explicit - $keysNotInExpected = @( $actualKeys | Where-Object { $expectedKeys -notcontains $_ }) + $keysNotInExpected = @( $actualKeys | & $SafeCommands['Where-Object'] { $expectedKeys -notcontains $_ }) $filteredKeysNotInExpected = @( $keysNotInExpected | Test-IncludedPath -PathSelector Hashtable -Path $Property -Options $Options) # fix for powershell v2 where foreach goes once over null - if ($filteredKeysNotInExpected | Where-Object { $_ }) { + if ($filteredKeysNotInExpected | & $SafeCommands['Where-Object'] { $_ }) { v -Difference "`$Actual has $($filteredKeysNotInExpected.Count) keys that were not found on `$Expected: $(Format-Nicely2 @($filteredKeysNotInExpected))." } else { v "`$Actual has no keys that we did not find on `$Expected." } - foreach ($k in $filteredKeysNotInExpected | Where-Object { $_ }) { + foreach ($k in $filteredKeysNotInExpected | & $SafeCommands['Where-Object'] { $_ }) { $result += "Expected is missing key '$k' that the other object has." } } - if ($result | Where-Object { $_ }) { + if ($result | & $SafeCommands['Where-Object'] { $_ }) { v -Difference "Hashtables `$Actual and `$Expected are not equivalent." $expectedFormatted = Format-Nicely2 -Value $Expected $actualFormatted = Format-Nicely2 -Value $Actual @@ -355,18 +355,18 @@ function Compare-DictionaryEquivalent ($Actual, $Expected, $Property, $Options) } if (!$Options.ExcludePathsNotOnExpected) { # fix for powershell 2 where the array needs to be explicit - $keysNotInExpected = @( $actualKeys | Where-Object { $expectedKeys -notcontains $_ } ) + $keysNotInExpected = @( $actualKeys | & $SafeCommands['Where-Object'] { $expectedKeys -notcontains $_ } ) $filteredKeysNotInExpected = @( $keysNotInExpected | Test-IncludedPath -PathSelector Hashtable -Path $Property -Options $Options ) # fix for powershell v2 where foreach goes once over null - if ($filteredKeysNotInExpected | Where-Object { $_ }) { + if ($filteredKeysNotInExpected | & $SafeCommands['Where-Object'] { $_ }) { v -Difference "`$Actual has $($filteredKeysNotInExpected.Count) keys that were not found on `$Expected: $(Format-Nicely2 @($filteredKeysNotInExpected))." } else { v "`$Actual has no keys that we did not find on `$Expected." } - foreach ($k in $filteredKeysNotInExpected | Where-Object { $_ }) { + foreach ($k in $filteredKeysNotInExpected | & $SafeCommands['Where-Object'] { $_ }) { $result += "Expected is missing key '$k' that the other object has." } } @@ -403,7 +403,7 @@ function Compare-ObjectEquivalent ($Actual, $Expected, $Property, $Options) { } $propertyName = $p.Name - $actualProperty = $actualProperties | Where-Object { $_.Name -eq $propertyName } + $actualProperty = $actualProperties | & $SafeCommands['Where-Object'] { $_.Name -eq $propertyName } if (-not $actualProperty) { v -Difference "Property '$propertyName' was not found on `$Actual." "Expected has property '$PropertyName' that the other object does not have." @@ -424,7 +424,7 @@ function Compare-ObjectEquivalent ($Actual, $Expected, $Property, $Options) { #check if there are any extra actual object props $expectedPropertyNames = $expectedProperties | Select-Object -ExpandProperty Name - $propertiesNotInExpected = @( $actualProperties | Where-Object { $expectedPropertyNames -notcontains $_.name }) + $propertiesNotInExpected = @( $actualProperties | & $SafeCommands['Where-Object'] { $expectedPropertyNames -notcontains $_.name }) # fix for powershell v2 we need to make the array explicit $filteredPropertiesNotInExpected = $propertiesNotInExpected | @@ -438,7 +438,7 @@ function Compare-ObjectEquivalent ($Actual, $Expected, $Property, $Options) { } # fix for powershell v2 where foreach goes once over null - foreach ($p in $filteredPropertiesNotInExpected | Where-Object { $_ }) { + foreach ($p in $filteredPropertiesNotInExpected | & $SafeCommands['Where-Object'] { $_ }) { "Expected is missing property '$($p.Name)' that the other object has." } } @@ -456,12 +456,12 @@ function Compare-DataRowEquivalent ($Actual, $Expected, $Property, $Options) { return "Expected DataRow '$expectedFormatted', but got '$actualFormatted'." } - $actualProperties = $Actual.PsObject.Properties | Where-Object { 'RowError', 'RowState', 'Table', 'ItemArray', 'HasErrors' -notcontains $_.Name } - $expectedProperties = $Expected.PsObject.Properties | Where-Object { 'RowError', 'RowState', 'Table', 'ItemArray', 'HasErrors' -notcontains $_.Name } + $actualProperties = $Actual.PsObject.Properties | & $SafeCommands['Where-Object'] { 'RowError', 'RowState', 'Table', 'ItemArray', 'HasErrors' -notcontains $_.Name } + $expectedProperties = $Expected.PsObject.Properties | & $SafeCommands['Where-Object'] { 'RowError', 'RowState', 'Table', 'ItemArray', 'HasErrors' -notcontains $_.Name } foreach ($p in $expectedProperties) { $propertyName = $p.Name - $actualProperty = $actualProperties | Where-Object { $_.Name -eq $propertyName } + $actualProperty = $actualProperties | & $SafeCommands['Where-Object'] { $_.Name -eq $propertyName } if (-not $actualProperty) { "Expected has property '$PropertyName' that the other object does not have." continue @@ -473,10 +473,10 @@ function Compare-DataRowEquivalent ($Actual, $Expected, $Property, $Options) { #check if there are any extra actual object props $expectedPropertyNames = $expectedProperties | Select-Object -ExpandProperty Name - $propertiesNotInExpected = @($actualProperties | Where-Object { $expectedPropertyNames -notcontains $_.name }) + $propertiesNotInExpected = @($actualProperties | & $SafeCommands['Where-Object'] { $expectedPropertyNames -notcontains $_.name }) # fix for powershell v2 where foreach goes once over null - foreach ($p in $propertiesNotInExpected | Where-Object { $_ }) { + foreach ($p in $propertiesNotInExpected | & $SafeCommands['Where-Object'] { $_ }) { "Expected is missing property '$($p.Name)' that the other object has." } } @@ -750,7 +750,7 @@ function Test-IncludedPath { } function Format-EquivalencyOptions ($Options) { - $Options.ExcludedPaths | ForEach-Object { "Exclude path '$_'" } + $Options.ExcludedPaths | & $SafeCommands['ForEach-Object'] { "Exclude path '$_'" } if ($Options.ExcludePathsNotOnExpected) { "Excluding all paths not found on Expected" } } @@ -761,7 +761,7 @@ function Like-Any { [String] $Path ) process { - foreach ($pathFilter in $PathFilters | Where-Object { $_ }) { + foreach ($pathFilter in $PathFilters | & $SafeCommands['Where-Object'] { $_ }) { $r = $Path -like $pathFilter if ($r) { v -Skip "Path '$Path' matches filter '$pathFilter'." diff --git a/src/functions/assert/Exception/Should-Throw.ps1 b/src/functions/assert/Exception/Should-Throw.ps1 index d46e85105..a4b564a58 100644 --- a/src/functions/assert/Exception/Should-Throw.ps1 +++ b/src/functions/assert/Exception/Should-Throw.ps1 @@ -35,7 +35,7 @@ function Assert-Throw { .EXAMPLE ```powershell - $err = { throw 'error' } | Should-Throw -PassThru + $err = { throw 'error' } | Should-Throw $err.Exception.Message | Should-BeLike '*err*' ``` @@ -75,7 +75,7 @@ function Assert-Throw { } catch { $errorThrown = $true - $err = Get-Error $_ + $err = Get-ErrorObject $_ } $buts = @() @@ -127,7 +127,7 @@ function Assert-Throw { $err.ErrorRecord } -function Get-Error ($ErrorRecord) { +function Get-ErrorObject ($ErrorRecord) { if ($ErrorRecord.Exception -like '*"InvokeWithContext"*') { $e = $ErrorRecord.Exception.InnerException.ErrorRecord diff --git a/test.ps1 b/test.ps1 index be831ffb5..b5b4edbe3 100644 --- a/test.ps1 +++ b/test.ps1 @@ -12,12 +12,9 @@ so leaving it in code would run only one test from the file on the server. .PARAMETER SkipPTests - Skips P tests. Skip the tests written using the P module, Unit + Skips Passthrough P tests. Skip the tests written using the P module, Unit Tests for the Runtime, and Acceptance Tests for Pester - .PARAMETER SkipPesterTests - Skips Pester tests, but not P tests. - .PARAMETER NoBuild Skips running build.ps1. Do not build the underlying csharp components. Used in CI pipeline since a clean build has already been run prior to Test. @@ -32,22 +29,16 @@ done, but makes local debugging difficult. When -CI is used, inlining is forced. - .PARAMETER VSCode - Set when calling from VSCode laucher file so we automatically figure out - what to run or what to skip. .NOTES Tests are excluded with Tags VersionChecks, StyleRules, Help. #> -[CmdletBinding()] param ( # force P to fail when I leave `dt` in the tests [switch] $CI, [switch] $SkipPTests, - [switch] $SkipPesterTests, [switch] $NoBuild, [switch] $Inline, - [switch] $VSCode, - [string[]] $File = @() + [string[]] $File ) Set-StrictMode -Version Latest @@ -57,21 +48,6 @@ $ErrorView = "NormalView" "Using PS: $($PsVersionTable.PSVersion)" "In path: $($pwd.Path)" -if ($VSCode) { - # Detect which tests to skip from the filenames. - $anyFile = 0 -lt $File.Count - $anyPesterTests = [bool]@($File | Where-Object { $_ -like "*.Tests.ps1" }) - $anyPTests = [bool]@($File | Where-Object { $_ -like "*.ts.ps1" }) - - if ($SkipPTests -or ($anyFile -and -not $anyPTests)) { - $SkipPTests = $true - } - - if ($SkipPesterTests -or ($anyFile -and -not $anyPesterTests)) { - $SkipPesterTests = $true - } -} - if (-not $NoBuild) { if ($CI) { & "$PSScriptRoot/build.ps1" -Inline @@ -81,10 +57,6 @@ if (-not $NoBuild) { } } -# if ($CI -and ($SkipPTests -or $SkipPesterTests)) { -# throw "Cannot skip tests in CI mode!" -# } - # remove pester because we will be reimporting it in multiple other places Get-Module Pester | Remove-Module @@ -146,7 +118,7 @@ New-Module -Name TestHelpers -ScriptBlock { } function New-Dictionary ([hashtable]$Hashtable) { - $d = new-object "Collections.Generic.Dictionary[string,object]" + $d = [System.Collections.Generic.Dictionary[string, object]]::new() $Hashtable.GetEnumerator() | ForEach-Object { $d.Add($_.Key, $_.Value) } $d @@ -155,15 +127,8 @@ New-Module -Name TestHelpers -ScriptBlock { function Clear-WhiteSpace ($Text) { "$($Text -replace "(`t|`n|`r)"," " -replace "\s+"," ")".Trim() } - - function New-PSObject ([hashtable]$Property) { - New-Object -Type PSObject -Property $Property - } } | Out-Null -if ($SkipPesterTests) { - return -} $configuration = [PesterConfiguration]::Default @@ -189,8 +154,8 @@ if ($CI) { $configuration.Run.Exit = $true # not using code coverage, it is still very slow - $configuration.CodeCoverage.Enabled = $true - $configuration.CodeCoverage.Path = "$PSScriptRoot/bin/*" + $configuration.CodeCoverage.Enabled = $false + $configuration.CodeCoverage.Path = "$PSScriptRoot/src/*" # experimental, uses the Profiler based tracer to do code coverage without using breakpoints $configuration.CodeCoverage.UseBreakpoints = $false diff --git a/tst/Format2.Tests.ps1 b/tst/Format2.Tests.ps1 index 35c0065be..e6c935bbc 100644 --- a/tst/Format2.Tests.ps1 +++ b/tst/Format2.Tests.ps1 @@ -64,7 +64,7 @@ InPesterModuleScope { Describe "Format-Object2" { It "Formats object '' to ''" -TestCases @( - @{ Value = (New-PSObject @{Name = 'Jakub'; Age = 28 }); Expected = "PSObject{Age=28; Name='Jakub'}" }, + @{ Value = ([PSCustomObject]@{Name = 'Jakub'; Age = 28 }); Expected = "PSObject{Age=28; Name='Jakub'}" }, @{ Value = (New-Object -Type Assertions.TestType.Person -Property @{Name = 'Jakub'; Age = 28 }); Expected = "Assertions.TestType.Person{Age=28; Name='Jakub'}" } ) { param ($Value, $Expected) @@ -72,7 +72,7 @@ InPesterModuleScope { } It "Formats object '' with selected properties '' to ''" -TestCases @( - @{ Value = (New-PSObject @{Name = 'Jakub'; Age = 28 }); SelectedProperties = "Age"; Expected = "PSObject{Age=28}" }, + @{ Value = ([PSCustomObject]@{Name = 'Jakub'; Age = 28 }); SelectedProperties = "Age"; Expected = "PSObject{Age=28}" }, @{ Value = (New-Object -Type Assertions.TestType.Person -Property @{Name = 'Jakub'; Age = 28 }) SelectedProperties = 'Name' @@ -159,7 +159,7 @@ InPesterModuleScope { @{ Value = (1, 2, 3); Expected = '@(1, 2, 3)' }, @{ Value = 1.1; Expected = '1.1' }, @{ Value = [int]; Expected = '[int]' } - @{ Value = New-PSObject @{ Name = "Jakub" }; Expected = "PSObject{Name='Jakub'}" }, + @{ Value = [PSCustomObject]@{ Name = "Jakub" }; Expected = "PSObject{Name='Jakub'}" }, @{ Value = (New-Object -Type Assertions.TestType.Person -Property @{Name = 'Jakub'; Age = 28 }); Expected = "Assertions.TestType.Person{Age=28; Name='Jakub'}" } @{ Value = @{Name = 'Jakub'; Age = 28 }; Expected = "@{Age=28; Name='Jakub'}" } @{ Value = New-Dictionary @{Age = 28; Name = 'Jakub' }; Expected = "Dictionary{Age=28; Name='Jakub'}" } @@ -199,7 +199,7 @@ InPesterModuleScope { @{ Value = 1.1; Expected = '[double]' }, @{ Value = 'a' ; Expected = '[string]' }, @{ Value = $null ; Expected = '[null]' }, - @{ Value = New-PSObject @{Name = 'Jakub' } ; Expected = '[PSObject]' }, + @{ Value = [PSCustomObject]@{Name = 'Jakub' } ; Expected = '[PSObject]' }, @{ Value = [Object[]]1, 2, 3 ; Expected = '[collection]' } ) { param($Value, $Expected) diff --git a/tst/functions/assert/Common/Get-AssertionMessage.Tests.ps1 b/tst/functions/assert/Common/Get-AssertionMessage.Tests.ps1 index a65c5d650..22936417c 100644 --- a/tst/functions/assert/Common/Get-AssertionMessage.Tests.ps1 +++ b/tst/functions/assert/Common/Get-AssertionMessage.Tests.ps1 @@ -17,13 +17,13 @@ InPesterModuleScope { It "returns correct message when complex objects are provided" { $expected = "We expected string to be PSObject{Age=28; Name='Jakub'}, but got 2." $customMessage = "We expected string to be , but got ." - Get-AssertionMessage -CustomMessage $customMessage -Expected (New-PSObject @{Name = 'Jakub'; Age = 28 }) -Actual 2 | Verify-Equal $expected + Get-AssertionMessage -CustomMessage $customMessage -Expected ([PSCustomObject]@{Name = 'Jakub'; Age = 28 }) -Actual 2 | Verify-Equal $expected } It "returns correct message when type tokens are provided" { $expected = "We expected string to be [PSObject], but got [int]." $customMessage = "We expected string to be , but got ." - Get-AssertionMessage -CustomMessage $customMessage -Expected (New-PSObject @{Name = 'Jakub'; Age = 28 }) -Actual 2 | Verify-Equal $expected + Get-AssertionMessage -CustomMessage $customMessage -Expected ([PSCustomObject]@{Name = 'Jakub'; Age = 28 }) -Actual 2 | Verify-Equal $expected } It "returns correct type message when `$null is provided" { diff --git a/tst/functions/assert/Equivalence/Should-BeEquivalent.Options.Tests.ps1 b/tst/functions/assert/Equivalence/Should-BeEquivalent.Options.Tests.ps1 index 2f0520180..2a14c79d7 100644 --- a/tst/functions/assert/Equivalence/Should-BeEquivalent.Options.Tests.ps1 +++ b/tst/functions/assert/Equivalence/Should-BeEquivalent.Options.Tests.ps1 @@ -11,12 +11,12 @@ InPesterModuleScope { ) { param ($Path) - $expected = New-PSObject @{ + $expected = [PSCustomObject]@{ Name = "Jakub" Age = 30 } - $actual = New-PSObject @{ + $actual = [PSCustomObject]@{ Name = "Jakub" } @@ -30,11 +30,11 @@ InPesterModuleScope { @{ Path = "ParentProperty1.ParentProperty2" } ) { param ($Path) - $expected = New-PSObject @{ + $expected = [PSCustomObject]@{ Name = "Jakub" } - $actual = New-PSObject @{ + $actual = [PSCustomObject]@{ Name = "Jakub" Age = 30 } @@ -45,24 +45,24 @@ InPesterModuleScope { It "Given a full path to a property on object that is in collection it ignores it on the Expected object" { - $expected = New-PSObject @{ + $expected = [PSCustomObject]@{ ProgrammingLanguages = @( - (New-PSObject @{ + ([PSCustomObject]@{ Name = "C#" Type = "OO" }), - (New-PSObject @{ + ([PSCustomObject]@{ Name = "PowerShell" }) ) } - $actual = New-PSObject @{ + $actual = [PSCustomObject]@{ ProgrammingLanguages = @( - (New-PSObject @{ + ([PSCustomObject]@{ Name = "C#" }), - (New-PSObject @{ + ([PSCustomObject]@{ Name = "PowerShell" }) ) @@ -74,24 +74,24 @@ InPesterModuleScope { } It "Given a full path to a property on object that is in collection it ignores it on the Actual object" { - $expected = New-PSObject @{ + $expected = [PSCustomObject]@{ ProgrammingLanguages = @( - (New-PSObject @{ + ([PSCustomObject]@{ Name = "C#" }), - (New-PSObject @{ + ([PSCustomObject]@{ Name = "PowerShell" }) ) } - $actual = New-PSObject @{ + $actual = [PSCustomObject]@{ ProgrammingLanguages = @( - (New-PSObject @{ + ([PSCustomObject]@{ Name = "C#" Type = "OO" }), - (New-PSObject @{ + ([PSCustomObject]@{ Name = "PowerShell" }) ) @@ -103,24 +103,24 @@ InPesterModuleScope { } It "Given a full path to a property on object that is in hashtable it ignores it on the Expected object" { - $expected = New-PSObject @{ + $expected = [PSCustomObject]@{ ProgrammingLanguages = @{ - Language1 = (New-PSObject @{ + Language1 = ([PSCustomObject]@{ Name = "C#" Type = "OO" }); - Language2 = (New-PSObject @{ + Language2 = ([PSCustomObject]@{ Name = "PowerShell" }) } } - $actual = New-PSObject @{ + $actual = [PSCustomObject]@{ ProgrammingLanguages = @{ - Language1 = (New-PSObject @{ + Language1 = ([PSCustomObject]@{ Name = "C#" }); - Language2 = (New-PSObject @{ + Language2 = ([PSCustomObject]@{ Name = "PowerShell" }) } @@ -193,13 +193,13 @@ InPesterModuleScope { } It "Given options it passes them correctly from Should-BeEquivalent" { - $expected = New-PSObject @{ + $expected = [PSCustomObject]@{ Name = "Jakub" Location = "Prague" Age = 30 } - $actual = New-PSObject @{ + $actual = [PSCustomObject]@{ Name = "Jakub" } @@ -347,11 +347,11 @@ InPesterModuleScope { Describe "Compare-Equiavlent - equality comparison options" { It "Given objects that are equivalent and -Comparator Equality option it compares them as different" { - $expected = New-PsObject @{ + $expected = [PSCustomObject]@{ LikesIfsInMocks = $false } - $actual = New-PsObject @{ + $actual = [PSCustomObject]@{ LikesIfsInMocks = "False" } diff --git a/tst/functions/assert/Equivalence/Should-BeEquivalent.Tests.ps1 b/tst/functions/assert/Equivalence/Should-BeEquivalent.Tests.ps1 index ef65365d4..3a280638a 100644 --- a/tst/functions/assert/Equivalence/Should-BeEquivalent.Tests.ps1 +++ b/tst/functions/assert/Equivalence/Should-BeEquivalent.Tests.ps1 @@ -83,13 +83,13 @@ InPesterModuleScope { Describe "Get-ValueNotEquivalentMessage" { It "Returns correct message when comparing value to an object" { $e = 'abc' - $a = New-PSObject @{ Name = 'Jakub'; Age = 28 } + $a = [PSCustomObject]@{ Name = 'Jakub'; Age = 28 } Get-ValueNotEquivalentMessage -Actual $a -Expected $e | Verify-Equal "Expected 'abc' to be equivalent to the actual value, but got PSObject{Age=28; Name='Jakub'}." } It "Returns correct message when comparing object to a value" { - $e = New-PSObject @{ Name = 'Jakub'; Age = 28 } + $e = [PSCustomObject]@{ Name = 'Jakub'; Age = 28 } $a = 'abc' Get-ValueNotEquivalentMessage -Actual $a -Expected $e | Verify-Equal "Expected PSObject{Age=28; Name='Jakub'} to be equivalent to the actual value, but got 'abc'." @@ -166,7 +166,7 @@ InPesterModuleScope { @{ Actual = "abc"; Expected = "a b c"; Message = "Expected 'a b c' to be equivalent to the actual value, but got 'abc'." }, @{ Actual = @("abc", "bde"); Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got @('abc', 'bde')." }, @{ Actual = { def }; Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got { def }." }, - @{ Actual = (New-PSObject @{ Name = 'Jakub' }); Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got PSObject{Name='Jakub'}." }, + @{ Actual = ([PSCustomObject]@{ Name = 'Jakub' }); Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got PSObject{Name='Jakub'}." }, @{ Actual = (1, 2, 3); Expected = "abc"; Message = "Expected 'abc' to be equivalent to the actual value, but got @(1, 2, 3)." } ) { param($Actual, $Expected, $Message) @@ -190,7 +190,7 @@ InPesterModuleScope { It "Given collection '' on the expected side and non-collection '' on the actual side it prints the correct message ''" -TestCases @( @{ Actual = 3; Expected = (1, 2, 3, 4); Message = "Expected collection @(1, 2, 3, 4) with length 4, but got 3." }, - @{ Actual = (New-PSObject @{ Name = 'Jakub' }); Expected = (1, 2, 3, 4); Message = "Expected collection @(1, 2, 3, 4) with length 4, but got PSObject{Name='Jakub'}." } + @{ Actual = ([PSCustomObject]@{ Name = 'Jakub' }); Expected = (1, 2, 3, 4); Message = "Expected collection @(1, 2, 3, 4) with length 4, but got PSObject{Name='Jakub'}." } ) { param ($Actual, $Expected, $Message) Compare-CollectionEquivalent -Actual $Actual -Expected $Expected | Verify-Equal $Message @@ -234,7 +234,7 @@ InPesterModuleScope { } It "Given values '' and '' that are not equivalent it returns message ''." -TestCases @( - @{ Actual = 'a'; Expected = (New-PSObject @{ Name = 'Jakub' }); Message = "Expected object PSObject{Name='Jakub'}, but got 'a'." } + @{ Actual = 'a'; Expected = ([PSCustomObject]@{ Name = 'Jakub' }); Message = "Expected object PSObject{Name='Jakub'}, but got 'a'." } ) { param ($Actual, $Expected, $Message) Compare-ObjectEquivalent -Expected $Expected -Actual $Actual | Verify-Equal $Message @@ -319,9 +319,9 @@ InPesterModuleScope { @{ Actual = { abc }; Expected = { def }; Message = "Expected { def } to be equivalent to the actual value, but got { abc }." }, @{ Actual = (1, 2, 3); Expected = (1, 2, 3, 4); Message = "Expected collection @(1, 2, 3, 4) with length 4 to be the same size as the actual collection, but got @(1, 2, 3) with length 3." }, @{ Actual = 3; Expected = (1, 2, 3, 4); Message = "Expected collection @(1, 2, 3, 4) with length 4, but got 3." }, - @{ Actual = (New-PSObject @{ Name = 'Jakub' }); Expected = (1, 2, 3, 4); Message = "Expected collection @(1, 2, 3, 4) with length 4, but got PSObject{Name='Jakub'}." }, - @{ Actual = (New-PSObject @{ Name = 'Jakub' }); Expected = "a"; Message = "Expected 'a' to be equivalent to the actual value, but got PSObject{Name='Jakub'}." }, - @{ Actual = 'a'; Expected = (New-PSObject @{ Name = 'Jakub' }); Message = "Expected object PSObject{Name='Jakub'}, but got 'a'." } + @{ Actual = ([PSCustomObject]@{ Name = 'Jakub' }); Expected = (1, 2, 3, 4); Message = "Expected collection @(1, 2, 3, 4) with length 4, but got PSObject{Name='Jakub'}." }, + @{ Actual = ([PSCustomObject]@{ Name = 'Jakub' }); Expected = "a"; Message = "Expected 'a' to be equivalent to the actual value, but got PSObject{Name='Jakub'}." }, + @{ Actual = 'a'; Expected = ([PSCustomObject]@{ Name = 'Jakub' }); Message = "Expected object PSObject{Name='Jakub'}, but got 'a'." } @{ Actual = 'a'; Expected = @{ Name = 'Jakub' }; Message = "Expected hashtable @{Name='Jakub'}, but got 'a'." } @{ Actual = 'a'; Expected = New-Dictionary @{ Name = 'Jakub' }; Message = "Expected dictionary Dictionary{Name='Jakub'}, but got 'a'." } ) { @@ -330,7 +330,7 @@ InPesterModuleScope { } It "Comparing the same instance of a psObject returns null" { - $actual = $expected = New-PSObject @{ Name = 'Jakub' } + $actual = $expected = [PSCustomObject]@{ Name = 'Jakub' } Verify-Same -Expected $expected -Actual $actual Compare-Equivalent -Expected $expected -Actual $actual | Verify-Null @@ -338,16 +338,16 @@ InPesterModuleScope { It "Given PSObjects '' and ' that are different instances but have the same values it returns report with Equivalent set to `$true" -TestCases @( @{ - Expected = New-PSObject @{ Name = 'Jakub' } - Actual = New-PSObject @{ Name = 'Jakub' } + Expected = [PSCustomObject]@{ Name = 'Jakub' } + Actual = [PSCustomObject]@{ Name = 'Jakub' } }, @{ - Expected = New-PSObject @{ Name = 'Jakub' } - Actual = New-PSObject @{ Name = 'Jakub' } + Expected = [PSCustomObject]@{ Name = 'Jakub' } + Actual = [PSCustomObject]@{ Name = 'Jakub' } }, @{ - Expected = New-PSObject @{ Age = 28 } - Actual = New-PSObject @{ Age = '28' } + Expected = [PSCustomObject]@{ Age = 28 } + Actual = [PSCustomObject]@{ Age = '28' } } ) { param ($Expected, $Actual) @@ -358,18 +358,18 @@ InPesterModuleScope { It "Given PSObjects '' and ' that have different values in some of the properties it returns message ''" -TestCases @( @{ - Expected = New-PSObject @{ Name = 'Jakub'; Age = 28 } - Actual = New-PSObject @{ Name = 'Jakub'; Age = 19 } + Expected = [PSCustomObject]@{ Name = 'Jakub'; Age = 28 } + Actual = [PSCustomObject]@{ Name = 'Jakub'; Age = 19 } Message = "Expected property .Age with value 28 to be equivalent to the actual value, but got 19." }, @{ - Expected = New-PSObject @{ Name = 'Jakub'; Age = 28 } - Actual = New-PSObject @{ Name = 'Jakub' } + Expected = [PSCustomObject]@{ Name = 'Jakub'; Age = 28 } + Actual = [PSCustomObject]@{ Name = 'Jakub' } Message = "Expected has property 'Age' that the other object does not have." }, @{ - Expected = New-PSObject @{ Name = 'Jakub' } - Actual = New-PSObject @{ Name = 'Jakub'; Age = 28 } + Expected = [PSCustomObject]@{ Name = 'Jakub' } + Actual = [PSCustomObject]@{ Name = 'Jakub'; Age = 28 } Message = "Expected is missing property 'Age' that the other object has." } ) { @@ -382,7 +382,7 @@ InPesterModuleScope { It "Given PSObject '' and object ' that have the same values it returns `$null" -TestCases @( @{ Expected = New-Object -TypeName Assertions.TestType.Person2 -Property @{ Name = 'Jakub'; Age = 28 } - Actual = New-PSObject @{ Name = 'Jakub'; Age = 28 } + Actual = [PSCustomObject]@{ Name = 'Jakub'; Age = 28 } } ) { param ($Expected, $Actual) @@ -392,8 +392,8 @@ InPesterModuleScope { It "Given PSObjects '' and ' that contain different arrays in the same property returns the correct message" -TestCases @( @{ - Expected = New-PSObject @{ Numbers = 1, 2, 3 } - Actual = New-PSObject @{ Numbers = 3, 4, 5 } + Expected = [PSCustomObject]@{ Numbers = 1, 2, 3 } + Actual = [PSCustomObject]@{ Numbers = 3, 4, 5 } } ) { param ($Expected, $Actual) @@ -403,8 +403,8 @@ InPesterModuleScope { It "Comparing psObjects that have collections of objects returns `$null when the objects have the same value" -TestCases @( @{ - Expected = New-PSObject @{ Objects = (New-PSObject @{ Name = "Jan" }), (New-PSObject @{ Name = "Tomas" }) } - Actual = New-PSObject @{ Objects = (New-PSObject @{ Name = "Tomas" }), (New-PSObject @{ Name = "Jan" }) } + Expected = [PSCustomObject]@{ Objects = ([PSCustomObject]@{ Name = "Jan" }), ([PSCustomObject]@{ Name = "Tomas" }) } + Actual = [PSCustomObject]@{ Objects = ([PSCustomObject]@{ Name = "Tomas" }), ([PSCustomObject]@{ Name = "Jan" }) } } ) { param ($Expected, $Actual) @@ -413,8 +413,8 @@ InPesterModuleScope { It "Comparing psObjects that have collections of objects returns the correct message when the items in the collection differ" -TestCases @( @{ - Expected = New-PSObject @{ Objects = (New-PSObject @{ Name = "Jan" }), (New-PSObject @{ Name = "Petr" }) } - Actual = New-PSObject @{ Objects = (New-PSObject @{ Name = "Jan" }), (New-PSObject @{ Name = "Tomas" }) } + Expected = [PSCustomObject]@{ Objects = ([PSCustomObject]@{ Name = "Jan" }), ([PSCustomObject]@{ Name = "Petr" }) } + Actual = [PSCustomObject]@{ Objects = ([PSCustomObject]@{ Name = "Jan" }), ([PSCustomObject]@{ Name = "Tomas" }) } } ) { param ($Expected, $Actual) diff --git a/tst/functions/assert/Exception/Should-Throw.Tests.ps1 b/tst/functions/assert/Exception/Should-Throw.Tests.ps1 index ea8b192e6..6c8e75856 100644 --- a/tst/functions/assert/Exception/Should-Throw.Tests.ps1 +++ b/tst/functions/assert/Exception/Should-Throw.Tests.ps1 @@ -203,7 +203,7 @@ Describe "General try catch behavior" { } InPesterModuleScope { - Describe "Get-Error" { + Describe "Get-ErrorObject" { It 'Unwraps error from invoke with context' { $ErrorActionPreference = 'stop' try { @@ -218,7 +218,7 @@ InPesterModuleScope { $e = $_ } - $err = Get-Error $e + $err = Get-ErrorObject $e $err.ExceptionMessage | Verify-Like "Cannot find path*because it does not exist." $err.ExceptionType | Verify-Equal ([Management.Automation.ItemNotFoundException]) $err.FullyQualifiedErrorId | Verify-Equal 'PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand' From 03e28d0327538cbaf3dd1412a5e6cb757d609307 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Mon, 20 May 2024 22:12:05 +0200 Subject: [PATCH 49/55] Revert launch.json --- .vscode/launch.json | 33 --------------------------------- 1 file changed, 33 deletions(-) delete mode 100644 .vscode/launch.json diff --git a/.vscode/launch.json b/.vscode/launch.json deleted file mode 100644 index 4730820e1..000000000 --- a/.vscode/launch.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - // Use IntelliSense to learn about possible attributes. - // Hover to view descriptions of existing attributes. - // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 - "version": "0.2.0", - "configurations": [ - { - "name": "PowerShell: Launch Current File", - "type": "PowerShell", - "request": "launch", - "script": "${file}", - "args": [] - }, - { - "name": "Pester: Tests from current file", - "type": "PowerShell", - "request": "launch", - "script": "${workspaceFolder}/test.ps1", - "args": [ - "-File", - "${file}", - "-VSCode" - ] - }, - { - "name": "Pester: All tests", - "type": "PowerShell", - "request": "launch", - "script": "${workspaceFolder}/test.ps1", - "args": [] - } - ] -} From bf19cb30b0981f4b92c33fed137564cfc6a9ef2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Mon, 20 May 2024 22:14:34 +0200 Subject: [PATCH 50/55] Remove TimeSpanOrStringWithTimeUnit.cs --- .../Pester/TimeSpanOrStringWithTimeUnit.cs | 18 ------------------ 1 file changed, 18 deletions(-) delete mode 100644 src/csharp/Pester/TimeSpanOrStringWithTimeUnit.cs diff --git a/src/csharp/Pester/TimeSpanOrStringWithTimeUnit.cs b/src/csharp/Pester/TimeSpanOrStringWithTimeUnit.cs deleted file mode 100644 index ed8271572..000000000 --- a/src/csharp/Pester/TimeSpanOrStringWithTimeUnit.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; - -namespace Pester -{ - public class TimeSpanOrStringWithTimeUnit - { - public TimeSpan DurationTimeSpan { get; private set; } - public string DurationString { get; private set; } - public static implicit operator TimeSpanOrStringWithTimeUnit(TimeSpan durationTimeSpan) - { - return new TimeSpanOrStringWithTimeUnit() { DurationTimeSpan = durationTimeSpan }; - } - public static implicit operator TimeSpanOrStringWithTimeUnit(string durationTimeSpan) - { - return new TimeSpanOrStringWithTimeUnit() { DurationString = durationTimeSpan }; - } - } -} From f1a381013d012e165cab647cbbd5096f71847705 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Mon, 20 May 2024 22:16:53 +0200 Subject: [PATCH 51/55] Apply suggestions from code review Co-authored-by: Frode Flaten <3436158+fflaten@users.noreply.github.com> --- src/functions/assert/String/Should-BeLikeString.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/functions/assert/String/Should-BeLikeString.ps1 b/src/functions/assert/String/Should-BeLikeString.ps1 index 07333e690..0ae136a08 100644 --- a/src/functions/assert/String/Should-BeLikeString.ps1 +++ b/src/functions/assert/String/Should-BeLikeString.ps1 @@ -35,7 +35,7 @@ function Assert-Like { .EXAMPLE ```powershell - "hello" | Should-BeLikeString"h*" + "hello" | Should-BeLikeString "h*" ``` This assertion will pass, because the actual value is like the expected value. @@ -43,7 +43,7 @@ function Assert-Like { .EXAMPLE ```powershell - "hello" | Should-BeLikeString"H*" -CaseSensitive + "hello" | Should-BeLikeString "H*" -CaseSensitive ``` This assertion will fail, because the actual value is not like the expected value. From 4e67f2fdd2d4a9e02191033d0d7bf3998f9a8452 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Mon, 20 May 2024 22:37:26 +0200 Subject: [PATCH 52/55] Apply suggestions from code review Co-authored-by: Frode Flaten <3436158+fflaten@users.noreply.github.com> --- src/functions/assert/Equivalence/Should-BeEquivalent.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 b/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 index 25e815391..f380d267f 100644 --- a/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 +++ b/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 @@ -557,7 +557,7 @@ function Compare-Equivalent { return Get-ValueNotEquivalentMessage -Expected $Expected -Actual $Actual -Property $Path } - v "`$Expected has type $$Expected.GetType(), `$Actual has type $$Actual.GetType(), they are both non-null." + v "`$Expected has type $(Format-Nicely2 $Expected.GetType()), `$Actual has type $(Format-Nicely2 $Actual.GetType()), they are both non-null." # test value types, strings, and single item arrays with values in them as values # expand the single item array to get to the value in it From 0e172096494cc2a0a3d4a1887746730bcdd266cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Mon, 20 May 2024 22:38:31 +0200 Subject: [PATCH 53/55] Fixes --- src/Module.ps1 | 2 + src/Pester.psd1 | 2 + .../Equivalence/Should-BeEquivalent.ps1 | 145 +++++++++--------- ...eaterThan.ps1 => Should-BeGreaterThan.ps1} | 0 .../Time/Get-TimeSpanFromStringWithUnit.ps1 | 18 +++ src/functions/assert/Time/Should-BeAfter.ps1 | 4 +- src/functions/assert/Time/Should-BeBefore.ps1 | 4 +- .../assert/Time/Should-BeFasterThan.ps1 | 23 +-- .../assert/Time/Should-BeSlowerThan.ps1 | 2 +- .../assert/Time/Should-BeFasterThan.Tests.ps1 | 6 +- 10 files changed, 105 insertions(+), 101 deletions(-) rename src/functions/assert/General/{ShouldBe-GreaterThan.ps1 => Should-BeGreaterThan.ps1} (100%) create mode 100644 src/functions/assert/Time/Get-TimeSpanFromStringWithUnit.ps1 diff --git a/src/Module.ps1 b/src/Module.ps1 index 4dea1c635..0fbd9b74c 100644 --- a/src/Module.ps1 +++ b/src/Module.ps1 @@ -118,6 +118,8 @@ $script:SafeCommands['Set-DynamicParameterVariable'] = $ExecutionContext.Session 'Assert-Before' 'Assert-After' + 'Get-EquivalencyOption' + # export 'Export-NUnitReport' 'ConvertTo-NUnitReport' diff --git a/src/Pester.psd1 b/src/Pester.psd1 index 4bfed3c85..793efbd80 100644 --- a/src/Pester.psd1 +++ b/src/Pester.psd1 @@ -102,6 +102,8 @@ 'Assert-Before' 'Assert-After' + 'Get-EquivalencyOption' + # legacy 'Assert-VerifiableMock' 'Assert-MockCalled' diff --git a/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 b/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 index 25e815391..3915b5a6d 100644 --- a/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 +++ b/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 @@ -56,7 +56,7 @@ function Compare-CollectionEquivalent ($Expected, $Actual, $Property, $Options) } if (-not (Is-Collection -Value $Actual)) { - v -Difference "`$Actual is not a collection it is a $(Format-Nicely2 $Actual.GetType()), so they are not equivalent." + Write-EquivalenceResult -Difference "`$Actual is not a collection it is a $(Format-Nicely2 $Actual.GetType()), so they are not equivalent." $expectedFormatted = Format-Collection2 -Value $Expected $expectedLength = $expected.Length $actualFormatted = Format-Nicely2 -Value $actual @@ -64,19 +64,19 @@ function Compare-CollectionEquivalent ($Expected, $Actual, $Property, $Options) } if (-not (Is-CollectionSize -Expected $Expected -Actual $Actual)) { - v -Difference "`$Actual does not have the same size ($($Actual.Length)) as `$Expected ($($Expected.Length)) so they are not equivalent." + Write-EquivalenceResult -Difference "`$Actual does not have the same size ($($Actual.Length)) as `$Expected ($($Expected.Length)) so they are not equivalent." return Get-CollectionSizeNotTheSameMessage -Expected $Expected -Actual $Actual -Property $Property } $eEnd = if ($Expected.Length -is [int]) { $Expected.Length } else { $Expected.Count } $aEnd = if ($Actual.Length -is [int]) { $Actual.Length } else { $Actual.Count } - v "Comparing items in collection, `$Expected has lenght $eEnd, `$Actual has length $aEnd." + Write-EquivalenceResult "Comparing items in collection, `$Expected has lenght $eEnd, `$Actual has length $aEnd." $taken = @() $notFound = @() $anyDifferent = $false for ($e = 0; $e -lt $eEnd; $e++) { # todo: retest strict order - v "`nSearching for `$Expected[$e]:" + Write-EquivalenceResult "`nSearching for `$Expected[$e]:" $currentExpected = $Expected[$e] $found = $false if ($StrictOrder) { @@ -84,7 +84,7 @@ function Compare-CollectionEquivalent ($Expected, $Actual, $Property, $Options) if ($taken -notcontains $e -and (-not (Compare-Equivalent -Expected $currentExpected -Actual $currentActual -Path $Property -Options $Options))) { $taken += $e $found = $true - v -Equivalence "`Found `$Expected[$e]." + Write-EquivalenceResult -Equivalence "`Found `$Expected[$e]." } } else { @@ -92,19 +92,19 @@ function Compare-CollectionEquivalent ($Expected, $Actual, $Property, $Options) # we already took this item as equivalent to an item # in the expected collection, skip it if ($taken -contains $a) { - v "Skipping `$Actual[$a] because it is already taken." + Write-EquivalenceResult "Skipping `$Actual[$a] because it is already taken." continue } $currentActual = $Actual[$a] # -not, because $null means no differences, and some strings means there are differences - v "Comparing `$Actual[$a] to `$Expected[$e] to see if they are equivalent." + Write-EquivalenceResult "Comparing `$Actual[$a] to `$Expected[$e] to see if they are equivalent." if (-not (Compare-Equivalent -Expected $currentExpected -Actual $currentActual -Path $Property -Options $Options)) { # add the index to the list of taken items so we can skip it # in the search, this way we can compare collections with # arrays multiple same items $taken += $a $found = $true - v -Equivalence "`Found equivalent item for `$Expected[$e] at `$Actual[$a]." + Write-EquivalenceResult -Equivalence "`Found equivalent item for `$Expected[$e] at `$Actual[$a]." # we already found the item we # can move on to the next item in Exected array break @@ -112,7 +112,7 @@ function Compare-CollectionEquivalent ($Expected, $Actual, $Property, $Options) } } if (-not $found) { - v -Difference "`$Actual does not contain `$Expected[$e]." + Write-EquivalenceResult -Difference "`$Actual does not contain `$Expected[$e]." $anyDifferent = $true $notFound += $currentExpected } @@ -123,7 +123,7 @@ function Compare-CollectionEquivalent ($Expected, $Actual, $Property, $Options) # @($null) which evaluates to false, even though # there was a single item that we did not find if ($anyDifferent) { - v -Difference "`$Actual and `$Expected arrays are not equivalent." + Write-EquivalenceResult -Difference "`$Actual and `$Expected arrays are not equivalent." $Expected = Format-Nicely2 -Value $Expected $Actual = Format-Nicely2 -Value $Actual $notFoundFormatted = Format-Nicely2 -Value $notFound @@ -131,7 +131,7 @@ function Compare-CollectionEquivalent ($Expected, $Actual, $Property, $Options) $propertyMessage = if ($Property) { " in property $Property which is" } return "Expected collection$propertyMessage $Expected to be equivalent to $Actual but some values were missing: $notFoundFormatted." } - v -Equivalence "`$Actual and `$Expected arrays are equivalent." + Write-EquivalenceResult -Equivalence "`$Actual and `$Expected arrays are equivalent." } function Compare-DataTableEquivalent ($Expected, $Actual, $Property, $Options) { @@ -199,56 +199,56 @@ function Compare-ValueEquivalent ($Actual, $Expected, $Property, $Options) { if (($null -eq $Options) -or ($null -eq $Options.Comparator) -or ("Equivalency" -eq $Options.Comparator)) { - v "Equivalency comparator is used, values will be compared for equivalency." + Write-EquivalenceResult "Equivalency comparator is used, values will be compared for equivalency." # fix that string 'false' becomes $true boolean if ($Actual -is [Bool] -and $Expected -is [string] -and "$Expected" -eq 'False') { - v "`$Actual is a boolean, and `$Expected is a 'False' string, which we consider equivalent to boolean `$false. Setting `$Expected to `$false." + Write-EquivalenceResult "`$Actual is a boolean, and `$Expected is a 'False' string, which we consider equivalent to boolean `$false. Setting `$Expected to `$false." $Expected = $false if ($Expected -ne $Actual) { - v -Difference "`$Actual is not equivalent to $(Format-Nicely2 $Expected) because it is $(Format-Nicely2 $Actual)." + Write-EquivalenceResult -Difference "`$Actual is not equivalent to $(Format-Nicely2 $Expected) because it is $(Format-Nicely2 $Actual)." return Get-ValueNotEquivalentMessage -Expected $Expected -Actual $Actual -Property $Property -Options $Options } - v -Equivalence "`$Actual is equivalent to $(Format-Nicely2 $Expected) because it is $(Format-Nicely2 $Actual)." + Write-EquivalenceResult -Equivalence "`$Actual is equivalent to $(Format-Nicely2 $Expected) because it is $(Format-Nicely2 $Actual)." return } if ($Expected -is [Bool] -and $Actual -is [string] -and "$Actual" -eq 'False') { - v "`$Actual is a 'False' string, which we consider equivalent to boolean `$false. `$Expected is a boolean. Setting `$Actual to `$false." + Write-EquivalenceResult "`$Actual is a 'False' string, which we consider equivalent to boolean `$false. `$Expected is a boolean. Setting `$Actual to `$false." $Actual = $false if ($Expected -ne $Actual) { - v -Difference "`$Actual is not equivalent to $(Format-Nicely2 $Expected) because it is $(Format-Nicely2 $Actual)." + Write-EquivalenceResult -Difference "`$Actual is not equivalent to $(Format-Nicely2 $Expected) because it is $(Format-Nicely2 $Actual)." return Get-ValueNotEquivalentMessage -Expected $Expected -Actual $Actual -Property $Property -Options $Options } - v -Equivalence "`$Actual is equivalent to $(Format-Nicely2 $Expected) because it is $(Format-Nicely2 $Actual)." + Write-EquivalenceResult -Equivalence "`$Actual is equivalent to $(Format-Nicely2 $Expected) because it is $(Format-Nicely2 $Actual)." return } # fix that scriptblocks are compared by reference if (Is-ScriptBlock -Value $Expected) { - v "`$Expected is a ScriptBlock, scriptblocks are considered equivalent when their content is equal. Converting `$Expected to string." + Write-EquivalenceResult "`$Expected is a ScriptBlock, scriptblocks are considered equivalent when their content is equal. Converting `$Expected to string." # forcing scriptblock to serialize to string and then comparing that if ("$Expected" -ne $Actual) { # todo: difference on index? - v -Difference "`$Actual is not equivalent to `$Expected because their contents differ." + Write-EquivalenceResult -Difference "`$Actual is not equivalent to `$Expected because their contents differ." return Get-ValueNotEquivalentMessage -Expected $Expected -Actual $Actual -Property $Path -Options $Options } - v -Equivalence "`$Actual is equivalent to `$Expected because their contents are equal." + Write-EquivalenceResult -Equivalence "`$Actual is equivalent to `$Expected because their contents are equal." return } } else { - v "Equality comparator is used, values will be compared for equality." + Write-EquivalenceResult "Equality comparator is used, values will be compared for equality." } - v "Comparing values as $(Format-Nicely2 $Expected.GetType()) because `$Expected has that type." + Write-EquivalenceResult "Comparing values as $(Format-Nicely2 $Expected.GetType()) because `$Expected has that type." # todo: shorter messages when both sides have the same type (do not compare by using -is, instead query the type and compare it) because -is is true even for parent types $type = $Expected.GetType() $coalescedActual = $Actual -as $type if ($Expected -ne $Actual) { - v -Difference "`$Actual is not equivalent to $(Format-Nicely2 $Expected) because it is $(Format-Nicely2 $Actual), and $(Format-Nicely2 $Actual) coalesced to $(Format-Nicely2 $type) is $(Format-Nicely2 $coalescedActual)." + Write-EquivalenceResult -Difference "`$Actual is not equivalent to $(Format-Nicely2 $Expected) because it is $(Format-Nicely2 $Actual), and $(Format-Nicely2 $Actual) coalesced to $(Format-Nicely2 $type) is $(Format-Nicely2 $coalescedActual)." return Get-ValueNotEquivalentMessage -Expected $Expected -Actual $Actual -Property $Property -Options $Options } - v -Equivalence "`$Actual is equivalent to $(Format-Nicely2 $Expected) because it is $(Format-Nicely2 $Actual), and $(Format-Nicely2 $Actual) coalesced to $(Format-Nicely2 $type) is $(Format-Nicely2 $coalescedActual)." + Write-EquivalenceResult -Equivalence "`$Actual is equivalent to $(Format-Nicely2 $Expected) because it is $(Format-Nicely2 $Actual), and $(Format-Nicely2 $Actual) coalesced to $(Format-Nicely2 $type) is $(Format-Nicely2 $coalescedActual)." } function Compare-HashtableEquivalent ($Actual, $Expected, $Property, $Options) { @@ -257,7 +257,7 @@ function Compare-HashtableEquivalent ($Actual, $Expected, $Property, $Options) { } if (-not (Is-Hashtable -Value $Actual)) { - v -Difference "`$Actual is not a hashtable it is a $(Format-Nicely2 $Actual.GetType()), so they are not equivalent." + Write-EquivalenceResult -Difference "`$Actual is not a hashtable it is a $(Format-Nicely2 $Actual.GetType()), so they are not equivalent." $expectedFormatted = Format-Nicely2 -Value $Expected $actualFormatted = Format-Nicely2 -Value $Actual return "Expected hashtable $expectedFormatted, but got $actualFormatted." @@ -268,7 +268,7 @@ function Compare-HashtableEquivalent ($Actual, $Expected, $Property, $Options) { $actualKeys = $Actual.Keys $expectedKeys = $Expected.Keys - v "`Comparing all ($($expectedKeys.Count)) keys from `$Expected to keys in `$Actual." + Write-EquivalenceResult "`Comparing all ($($expectedKeys.Count)) keys from `$Expected to keys in `$Actual." $result = @() foreach ($k in $expectedKeys) { if (-not (Test-IncludedPath -PathSelector Hashtable -Path $Property -Options $Options -InputObject $k)) { @@ -277,14 +277,14 @@ function Compare-HashtableEquivalent ($Actual, $Expected, $Property, $Options) { $actualHasKey = $actualKeys -contains $k if (-not $actualHasKey) { - v -Difference "`$Actual is missing key '$k'." + Write-EquivalenceResult -Difference "`$Actual is missing key '$k'." $result += "Expected has key '$k' that the other object does not have." continue } $expectedValue = $Expected[$k] $actualValue = $Actual[$k] - v "Both `$Actual and `$Expected have key '$k', comparing thier contents." + Write-EquivalenceResult "Both `$Actual and `$Expected have key '$k', comparing thier contents." $result += Compare-Equivalent -Expected $expectedValue -Actual $actualValue -Path "$Property.$k" -Options $Options } @@ -296,10 +296,10 @@ function Compare-HashtableEquivalent ($Actual, $Expected, $Property, $Options) { # fix for powershell v2 where foreach goes once over null if ($filteredKeysNotInExpected | & $SafeCommands['Where-Object'] { $_ }) { - v -Difference "`$Actual has $($filteredKeysNotInExpected.Count) keys that were not found on `$Expected: $(Format-Nicely2 @($filteredKeysNotInExpected))." + Write-EquivalenceResult -Difference "`$Actual has $($filteredKeysNotInExpected.Count) keys that were not found on `$Expected: $(Format-Nicely2 @($filteredKeysNotInExpected))." } else { - v "`$Actual has no keys that we did not find on `$Expected." + Write-EquivalenceResult "`$Actual has no keys that we did not find on `$Expected." } foreach ($k in $filteredKeysNotInExpected | & $SafeCommands['Where-Object'] { $_ }) { @@ -308,13 +308,13 @@ function Compare-HashtableEquivalent ($Actual, $Expected, $Property, $Options) { } if ($result | & $SafeCommands['Where-Object'] { $_ }) { - v -Difference "Hashtables `$Actual and `$Expected are not equivalent." + Write-EquivalenceResult -Difference "Hashtables `$Actual and `$Expected are not equivalent." $expectedFormatted = Format-Nicely2 -Value $Expected $actualFormatted = Format-Nicely2 -Value $Actual return "Expected hashtable $expectedFormatted, but got $actualFormatted.`n$($result -join "`n")" } - v -Equivalence "Hastables `$Actual and `$Expected are equivalent." + Write-EquivalenceResult -Equivalence "Hastables `$Actual and `$Expected are equivalent." } function Compare-DictionaryEquivalent ($Actual, $Expected, $Property, $Options) { @@ -323,7 +323,7 @@ function Compare-DictionaryEquivalent ($Actual, $Expected, $Property, $Options) } if (-not (Is-Dictionary -Value $Actual)) { - v -Difference "`$Actual is not a dictionary it is a $(Format-Nicely2 $Actual.GetType()), so they are not equivalent." + Write-EquivalenceResult -Difference "`$Actual is not a dictionary it is a $(Format-Nicely2 $Actual.GetType()), so they are not equivalent." $expectedFormatted = Format-Nicely2 -Value $Expected $actualFormatted = Format-Nicely2 -Value $Actual return "Expected dictionary $expectedFormatted, but got $actualFormatted." @@ -334,7 +334,7 @@ function Compare-DictionaryEquivalent ($Actual, $Expected, $Property, $Options) $actualKeys = $Actual.Keys $expectedKeys = $Expected.Keys - v "`Comparing all ($($expectedKeys.Count)) keys from `$Expected to keys in `$Actual." + Write-EquivalenceResult "`Comparing all ($($expectedKeys.Count)) keys from `$Expected to keys in `$Actual." $result = @() foreach ($k in $expectedKeys) { if (-not (Test-IncludedPath -PathSelector Hashtable -Path $Property -Options $Options -InputObject $k)) { @@ -343,14 +343,14 @@ function Compare-DictionaryEquivalent ($Actual, $Expected, $Property, $Options) $actualHasKey = $actualKeys -contains $k if (-not $actualHasKey) { - v -Difference "`$Actual is missing key '$k'." + Write-EquivalenceResult -Difference "`$Actual is missing key '$k'." $result += "Expected has key '$k' that the other object does not have." continue } $expectedValue = $Expected[$k] $actualValue = $Actual[$k] - v "Both `$Actual and `$Expected have key '$k', comparing thier contents." + Write-EquivalenceResult "Both `$Actual and `$Expected have key '$k', comparing thier contents." $result += Compare-Equivalent -Expected $expectedValue -Actual $actualValue -Path "$Property.$k" -Options $Options } if (!$Options.ExcludePathsNotOnExpected) { @@ -360,10 +360,10 @@ function Compare-DictionaryEquivalent ($Actual, $Expected, $Property, $Options) # fix for powershell v2 where foreach goes once over null if ($filteredKeysNotInExpected | & $SafeCommands['Where-Object'] { $_ }) { - v -Difference "`$Actual has $($filteredKeysNotInExpected.Count) keys that were not found on `$Expected: $(Format-Nicely2 @($filteredKeysNotInExpected))." + Write-EquivalenceResult -Difference "`$Actual has $($filteredKeysNotInExpected.Count) keys that were not found on `$Expected: $(Format-Nicely2 @($filteredKeysNotInExpected))." } else { - v "`$Actual has no keys that we did not find on `$Expected." + Write-EquivalenceResult "`$Actual has no keys that we did not find on `$Expected." } foreach ($k in $filteredKeysNotInExpected | & $SafeCommands['Where-Object'] { $_ }) { @@ -372,12 +372,12 @@ function Compare-DictionaryEquivalent ($Actual, $Expected, $Property, $Options) } if ($result) { - v -Difference "Dictionaries `$Actual and `$Expected are not equivalent." + Write-EquivalenceResult -Difference "Dictionaries `$Actual and `$Expected are not equivalent." $expectedFormatted = Format-Nicely2 -Value $Expected $actualFormatted = Format-Nicely2 -Value $Actual return "Expected dictionary $expectedFormatted, but got $actualFormatted.`n$($result -join "`n")" } - v -Equivalence "Dictionaries `$Actual and `$Expected are equivalent." + Write-EquivalenceResult -Equivalence "Dictionaries `$Actual and `$Expected are equivalent." } function Compare-ObjectEquivalent ($Actual, $Expected, $Property, $Options) { @@ -387,7 +387,7 @@ function Compare-ObjectEquivalent ($Actual, $Expected, $Property, $Options) { } if (-not (Is-Object -Value $Actual)) { - v -Difference "`$Actual is not an object it is a $(Format-Nicely2 $Actual.GetType()), so they are not equivalent." + Write-EquivalenceResult -Difference "`$Actual is not an object it is a $(Format-Nicely2 $Actual.GetType()), so they are not equivalent." $expectedFormatted = Format-Nicely2 -Value $Expected $actualFormatted = Format-Nicely2 -Value $Actual return "Expected object $expectedFormatted, but got $actualFormatted." @@ -396,7 +396,7 @@ function Compare-ObjectEquivalent ($Actual, $Expected, $Property, $Options) { $actualProperties = $Actual.PsObject.Properties $expectedProperties = $Expected.PsObject.Properties - v "Comparing ($(@($expectedProperties).Count)) properties of `$Expected to `$Actual." + Write-EquivalenceResult "Comparing ($(@($expectedProperties).Count)) properties of `$Expected to `$Actual." foreach ($p in $expectedProperties) { if (-not (Test-IncludedPath -PathSelector Property -InputObject $p -Options $Options -Path $Property)) { continue @@ -405,17 +405,17 @@ function Compare-ObjectEquivalent ($Actual, $Expected, $Property, $Options) { $propertyName = $p.Name $actualProperty = $actualProperties | & $SafeCommands['Where-Object'] { $_.Name -eq $propertyName } if (-not $actualProperty) { - v -Difference "Property '$propertyName' was not found on `$Actual." + Write-EquivalenceResult -Difference "Property '$propertyName' was not found on `$Actual." "Expected has property '$PropertyName' that the other object does not have." continue } - v "Property '$propertyName` was found on `$Actual, comparing them for equivalence." + Write-EquivalenceResult "Property '$propertyName` was found on `$Actual, comparing them for equivalence." $differences = Compare-Equivalent -Expected $p.Value -Actual $actualProperty.Value -Path "$Property.$propertyName" -Options $Options if (-not $differences) { - v -Equivalence "Property '$propertyName` is equivalent." + Write-EquivalenceResult -Equivalence "Property '$propertyName` is equivalent." } else { - v -Difference "Property '$propertyName` is not equivalent." + Write-EquivalenceResult -Difference "Property '$propertyName` is not equivalent." } $differences } @@ -431,10 +431,10 @@ function Compare-ObjectEquivalent ($Actual, $Expected, $Property, $Options) { Test-IncludedPath -PathSelector Property -Options $Options -Path $Property if ($filteredPropertiesNotInExpected) { - v -Difference "`$Actual has ($(@($filteredPropertiesNotInExpected).Count)) properties that `$Expected does not have: $(Format-Nicely2 @($filteredPropertiesNotInExpected))." + Write-EquivalenceResult -Difference "`$Actual has ($(@($filteredPropertiesNotInExpected).Count)) properties that `$Expected does not have: $(Format-Nicely2 @($filteredPropertiesNotInExpected))." } else { - v -Equivalence "`$Actual has no extra properties that `$Expected does not have." + Write-EquivalenceResult -Equivalence "`$Actual has no extra properties that `$Expected does not have." } # fix for powershell v2 where foreach goes once over null @@ -481,7 +481,7 @@ function Compare-DataRowEquivalent ($Actual, $Expected, $Property, $Options) { } } -function v { +function Write-EquivalenceResult { [CmdletBinding()] param( [String] $String, @@ -516,7 +516,7 @@ function v { " - " } - Write-Verbose ("$p$String".Trim() + " ") + & $SafeCommands['Write-Verbose'] ("$p$String".Trim() + " ") } # compares two objects for equivalency and returns $null when they are equivalent @@ -528,60 +528,60 @@ function Compare-Equivalent { $Expected, $Path, $Options = (& { - Write-Warning "Getting default equivalency options, this should never be seen. If you see this and you are not developing Pester, please file issue at https://github.com/pester/Pester/issues" + & $SafeCommands['Write-Warning'] "Getting default equivalency options, this should never be seen. If you see this and you are not developing Pester, please file issue at https://github.com/pester/Pester/issues" Get-EquivalencyOption }) ) if ($null -ne $Options.ExludedPaths -and $Options.ExcludedPaths -contains $Path) { - v -Skip "Current path '$Path' is excluded from the comparison." + Write-EquivalenceResult -Skip "Current path '$Path' is excluded from the comparison." return } # start by null checks to avoid implementing null handling # logic in the functions that follow if ($null -eq $Expected) { - v "`$Expected is `$null, so we are expecting `$null." + Write-EquivalenceResult "`$Expected is `$null, so we are expecting `$null." if ($Expected -ne $Actual) { - v -Difference "`$Actual is not equivalent to $(Format-Nicely2 $Expected), because it has a value of type $(Format-Nicely2 $Actual.GetType())." + Write-EquivalenceResult -Difference "`$Actual is not equivalent to $(Format-Nicely2 $Expected), because it has a value of type $(Format-Nicely2 $Actual.GetType())." return Get-ValueNotEquivalentMessage -Expected $Expected -Actual $Actual -Property $Path -Options $Options } # we terminate here, either we passed the test and return nothing, or we did not # and the previous statement returned message - v -Equivalence "`$Actual is equivalent to `$null, because it is `$null." + Write-EquivalenceResult -Equivalence "`$Actual is equivalent to `$null, because it is `$null." return } if ($null -eq $Actual) { - v -Difference "`$Actual is $(Format-Nicely2), but `$Expected has value of type $(Format-Nicely2 $Expected.GetType()), so they are not equivalent." + Write-EquivalenceResult -Difference "`$Actual is $(Format-Nicely2), but `$Expected has value of type $(Format-Nicely2 $Expected.GetType()), so they are not equivalent." return Get-ValueNotEquivalentMessage -Expected $Expected -Actual $Actual -Property $Path } - v "`$Expected has type $$Expected.GetType(), `$Actual has type $$Actual.GetType(), they are both non-null." + Write-EquivalenceResult "`$Expected has type $$Expected.GetType(), `$Actual has type $$Actual.GetType(), they are both non-null." # test value types, strings, and single item arrays with values in them as values # expand the single item array to get to the value in it if (Is-Value -Value $Expected) { - v "`$Expected is a value (value type, string, single value array, or a scriptblock), we will be comparing `$Actual to value types." + Write-EquivalenceResult "`$Expected is a value (value type, string, single value array, or a scriptblock), we will be comparing `$Actual to value types." Compare-ValueEquivalent -Actual $Actual -Expected $Expected -Property $Path -Options $Options return } # are the same instance if (Test-Same -Expected $Expected -Actual $Actual) { - v -Equivalence "`$Expected and `$Actual are equivalent because they are the same object (by reference)." + Write-EquivalenceResult -Equivalence "`$Expected and `$Actual are equivalent because they are the same object (by reference)." return } if (Is-Hashtable -Value $Expected) { - v "`$Expected is a hashtable, we will be comparing `$Actual to hashtables." + Write-EquivalenceResult "`$Expected is a hashtable, we will be comparing `$Actual to hashtables." Compare-HashtableEquivalent -Expected $Expected -Actual $Actual -Property $Path -Options $Options return } # dictionaries? (they are IEnumerable so they must go before collections) if (Is-Dictionary -Value $Expected) { - v "`$Expected is a dictionary, we will be comparing `$Actual to dictionaries." + Write-EquivalenceResult "`$Expected is a dictionary, we will be comparing `$Actual to dictionaries." Compare-DictionaryEquivalent -Expected $Expected -Actual $Actual -Property $Path -Options $Options return } @@ -589,14 +589,14 @@ function Compare-Equivalent { #compare DataTable if (Is-DataTable -Value $Expected) { # todo add verbose output to data table - v "`$Expected is a datatable, we will be comparing `$Actual to datatables." + Write-EquivalenceResult "`$Expected is a datatable, we will be comparing `$Actual to datatables." Compare-DataTableEquivalent -Expected $Expected -Actual $Actual -Property $Path -Options $Options return } #compare collection if (Is-Collection -Value $Expected) { - v "`$Expected is a collection, we will be comparing `$Actual to collections." + Write-EquivalenceResult "`$Expected is a collection, we will be comparing `$Actual to collections." Compare-CollectionEquivalent -Expected $Expected -Actual $Actual -Property $Path -Options $Options return } @@ -604,12 +604,12 @@ function Compare-Equivalent { #compare DataRow if (Is-DataRow -Value $Expected) { # todo add verbose output to data row - v "`$Expected is a datarow, we will be comparing `$Actual to datarows." + Write-EquivalenceResult "`$Expected is a datarow, we will be comparing `$Actual to datarows." Compare-DataRowEquivalent -Expected $Expected -Actual $Actual -Property $Path -Options $Options return } - v "`$Expected is an object of type $(Format-Nicely2 $Expected.GetType()), we will be comparing `$Actual to objects." + Write-EquivalenceResult "`$Expected is an object of type $(Format-Nicely2 $Expected.GetType()), we will be comparing `$Actual to objects." Compare-ObjectEquivalent -Expected $Expected -Actual $Actual -Property $Path -Options $Options } @@ -677,14 +677,15 @@ function Assert-Equivalent { [Parameter(Position = 0, Mandatory)] $Expected, [String]$Because, - $Options = (Get-EquivalencyOption), - [Switch] $StrictOrder + $Options = (Get-EquivalencyOption) + # TODO: I am not sure this works. + # [Switch] $StrictOrder ) $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput $Actual = $collectedInput.Actual - $areDifferent = Compare-Equivalent -Actual $Actual -Expected $Expected -Options $Options | Out-String + $areDifferent = Compare-Equivalent -Actual $Actual -Expected $Expected -Options $Options | & $SafeCommands['Out-String'] if ($areDifferent) { $optionsFormatted = Format-EquivalencyOptions -Options $Options @@ -693,7 +694,7 @@ function Assert-Equivalent { throw [Pester.Factory]::CreateShouldErrorRecord($message, $MyInvocation.ScriptName, $MyInvocation.ScriptLineNumber, $MyInvocation.Line.TrimEnd([System.Environment]::NewLine), $true) } - v -Equivalence "`$Actual and `$Expected are equivalent." + Write-EquivalenceResult -Equivalence "`$Actual and `$Expected are equivalent." } function Get-EquivalencyOption { @@ -741,7 +742,7 @@ function Test-IncludedPath { if ($fullPath | Like-Any $Options.ExcludedPaths) { - v -Skip "Current path $fullPath is excluded from the comparison." + Write-EquivalenceResult -Skip "Current path $fullPath is excluded from the comparison." } else { $InputObject @@ -764,7 +765,7 @@ function Like-Any { foreach ($pathFilter in $PathFilters | & $SafeCommands['Where-Object'] { $_ }) { $r = $Path -like $pathFilter if ($r) { - v -Skip "Path '$Path' matches filter '$pathFilter'." + Write-EquivalenceResult -Skip "Path '$Path' matches filter '$pathFilter'." return $true } } diff --git a/src/functions/assert/General/ShouldBe-GreaterThan.ps1 b/src/functions/assert/General/Should-BeGreaterThan.ps1 similarity index 100% rename from src/functions/assert/General/ShouldBe-GreaterThan.ps1 rename to src/functions/assert/General/Should-BeGreaterThan.ps1 diff --git a/src/functions/assert/Time/Get-TimeSpanFromStringWithUnit.ps1 b/src/functions/assert/Time/Get-TimeSpanFromStringWithUnit.ps1 new file mode 100644 index 000000000..be64c95fe --- /dev/null +++ b/src/functions/assert/Time/Get-TimeSpanFromStringWithUnit.ps1 @@ -0,0 +1,18 @@ +function Get-TimeSpanFromStringWithUnit ([string] $Value) { + if ($Value -notmatch "(?^\d+(?:\.\d+)?)\s*(?ms|mil|m|h|d|s|w)") { + throw "String '$Value' is not a valid timespan string. It should be a number followed by a unit in short or long format (e.g. '1ms', '1s', '1m', '1h', '1d', '1w', '1sec', '1second', '1.5hours' etc.)." + } + + $suffix = $Matches['suffix'] + $valueFromRegex = $Matches['value'] + switch ($suffix) { + ms { [timespan]::FromMilliseconds($valueFromRegex) } + mil { [timespan]::FromMilliseconds($valueFromRegex) } + s { [timespan]::FromSeconds($valueFromRegex) } + m { [timespan]::FromMinutes($valueFromRegex) } + h { [timespan]::FromHours($valueFromRegex) } + d { [timespan]::FromDays($valueFromRegex) } + w { [timespan]::FromDays([double]$valueFromRegex * 7) } + default { throw "Time unit '$suffix' in '$Value' is not supported." } + } +} diff --git a/src/functions/assert/Time/Should-BeAfter.ps1 b/src/functions/assert/Time/Should-BeAfter.ps1 index 96938fcc2..9e456a8da 100644 --- a/src/functions/assert/Time/Should-BeAfter.ps1 +++ b/src/functions/assert/Time/Should-BeAfter.ps1 @@ -100,10 +100,10 @@ } if ($Ago) { - $Expected = $currentTime - (Get-TimeSpanFromStringWithUnits -Value $Time) + $Expected = $currentTime - (Get-TimeSpanFromStringWithUnit -Value $Time) } else { - $Expected = $currentTime + (Get-TimeSpanFromStringWithUnits -Value $Time) + $Expected = $currentTime + (Get-TimeSpanFromStringWithUnit -Value $Time) } } diff --git a/src/functions/assert/Time/Should-BeBefore.ps1 b/src/functions/assert/Time/Should-BeBefore.ps1 index 7c84be166..1cdb98bb7 100644 --- a/src/functions/assert/Time/Should-BeBefore.ps1 +++ b/src/functions/assert/Time/Should-BeBefore.ps1 @@ -99,10 +99,10 @@ } if ($Ago) { - $Expected = $currentTime - (Get-TimeSpanFromStringWithUnits -Value $Time) + $Expected = $currentTime - (Get-TimeSpanFromStringWithUnit -Value $Time) } else { - $Expected = $currentTime + (Get-TimeSpanFromStringWithUnits -Value $Time) + $Expected = $currentTime + (Get-TimeSpanFromStringWithUnit -Value $Time) } } diff --git a/src/functions/assert/Time/Should-BeFasterThan.ps1 b/src/functions/assert/Time/Should-BeFasterThan.ps1 index 0810adfbe..ee3fffb96 100644 --- a/src/functions/assert/Time/Should-BeFasterThan.ps1 +++ b/src/functions/assert/Time/Should-BeFasterThan.ps1 @@ -1,23 +1,4 @@ -function Get-TimeSpanFromStringWithUnits ([string] $Value) { - if ($Value -notmatch "(?^\d+(?:\.\d+)?)\s*(?ms|mil|m|h|d|s|w)") { - throw "String '$Value' is not a valid timespan string. It should be a number followed by a unit in short or long format (e.g. '1ms', '1s', '1m', '1h', '1d', '1w', '1sec', '1second', '1.5hours' etc.)." - } - - $suffix = $Matches['suffix'] - $valueFromRegex = $Matches['value'] - switch ($suffix) { - ms { [timespan]::FromMilliseconds($valueFromRegex) } - mil { [timespan]::FromMilliseconds($valueFromRegex) } - s { [timespan]::FromSeconds($valueFromRegex) } - m { [timespan]::FromMinutes($valueFromRegex) } - h { [timespan]::FromHours($valueFromRegex) } - d { [timespan]::FromDays($valueFromRegex) } - w { [timespan]::FromDays([double]$valueFromRegex * 7) } - default { throw "Time unit '$suffix' in '$Value' is not supported." } - } -} - -function Assert-Faster { +function Assert-Faster { <# .SYNOPSIS Asserts that the provided [timespan] or [scriptblock] is faster than the expected [timespan]. @@ -63,7 +44,7 @@ function Assert-Faster { ) if ($Expected -isnot [timespan]) { - $Expected = Get-TimeSpanFromStringWithUnits -Value $Expected + $Expected = Get-TimeSpanFromStringWithUnit -Value $Expected } $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput diff --git a/src/functions/assert/Time/Should-BeSlowerThan.ps1 b/src/functions/assert/Time/Should-BeSlowerThan.ps1 index 5849da3e2..a20db90c2 100644 --- a/src/functions/assert/Time/Should-BeSlowerThan.ps1 +++ b/src/functions/assert/Time/Should-BeSlowerThan.ps1 @@ -52,7 +52,7 @@ ) if ($Expected -isnot [timespan]) { - $Expected = Get-TimeSpanFromStringWithUnits -Value $Expected + $Expected = Get-TimeSpanFromStringWithUnit -Value $Expected } $collectedInput = Collect-Input -ParameterInput $Actual -PipelineInput $local:Input -IsPipelineInput $MyInvocation.ExpectingInput -UnrollInput diff --git a/tst/functions/assert/Time/Should-BeFasterThan.Tests.ps1 b/tst/functions/assert/Time/Should-BeFasterThan.Tests.ps1 index 9a4ec8115..ac66698cc 100644 --- a/tst/functions/assert/Time/Should-BeFasterThan.Tests.ps1 +++ b/tst/functions/assert/Time/Should-BeFasterThan.Tests.ps1 @@ -1,9 +1,9 @@ Set-StrictMode -Version Latest InPesterModuleScope { - Describe "Get-TimeSpanFromStringWithUnits" { + Describe "Get-TimeSpanFromStringWithUnit" { It "Throws when string is not a valid timespan string" { - { Get-TimeSpanFromStringWithUnits 1f } | Verify-Throw + { Get-TimeSpanFromStringWithUnit 1f } | Verify-Throw } It "Parses string with units correctly" -ForEach @( @@ -18,7 +18,7 @@ InPesterModuleScope { @{ Value = "1second"; Expected = [timespan]::FromSeconds(1) } @{ Value = "1.5hours"; Expected = [timespan]::FromHours(1.5) } ) { - Get-TimeSpanFromStringWithUnits -Value $Value | Verify-Equal -Expected $Expected + Get-TimeSpanFromStringWithUnit -Value $Value | Verify-Equal -Expected $Expected } } } From 162fab7921ef8d907ba1a0cea8260da20955916b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Mon, 20 May 2024 22:48:08 +0200 Subject: [PATCH 54/55] Get-equivalencyoption help --- .../Equivalence/Should-BeEquivalent.ps1 | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 b/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 index a6bb5f1cb..58f2aa36b 100644 --- a/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 +++ b/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 @@ -698,6 +698,34 @@ function Assert-Equivalent { } function Get-EquivalencyOption { + <# + .SYNOPSIS + Generates an object containing options for checking equivalency. + + .DESCRIPTION + The `Get-EquivalencyOption` function creates a custom object with options that determine how equivalency between two objects is assessed. This can be used in scenarios where a deep comparison of objects is required, with the ability to exclude specific paths from the comparison and to choose between different comparison strategies. + + .PARAMETER ExcludePath + An array of strings specifying the paths to exclude from the comparison. Each path should correspond to a property name or a chain of property names separated by dots for nested properties. + + .PARAMETER ExcludePathsNotOnExpected + A switch parameter that, when set, excludes any paths from the comparison that are not present on the expected object. This is useful for ignoring extra properties on the actual object that are not relevant to the comparison. + + .PARAMETER Comparator + Specifies the comparison strategy to use. The options are 'Equivalency' for a deep comparison that considers the structure and values of objects, and 'Equality' for a simple equality comparison. The default is 'Equivalency'. + + .EXAMPLE + $option = Get-EquivalencyOption -ExcludePath 'Id', 'Timestamp' -Comparator 'Equality' + This example generates an equivalency option object that excludes the 'Id' and 'Timestamp' properties from the comparison and uses a simple equality comparison strategy. + + .EXAMPLE + $option = Get-EquivalencyOption -ExcludePathsNotOnExpected + This example generates an equivalency option object that excludes any paths not present on the expected object from the comparison, using the default deep comparison strategy. + + .LINK + https://pester.dev/docs/functions/Get-EquivalencyOption + #> + param( [string[]] $ExcludePath = @(), [switch] $ExcludePathsNotOnExpected, From 6fa12ce264c36b1a94eaa629ee6aac6d1160ebd5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Jare=C5=A1?= Date: Mon, 20 May 2024 22:58:08 +0200 Subject: [PATCH 55/55] Get-equivalencyoption help --- src/functions/assert/Equivalence/Should-BeEquivalent.ps1 | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 b/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 index 58f2aa36b..f8bd218c9 100644 --- a/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 +++ b/src/functions/assert/Equivalence/Should-BeEquivalent.ps1 @@ -723,9 +723,13 @@ function Get-EquivalencyOption { This example generates an equivalency option object that excludes any paths not present on the expected object from the comparison, using the default deep comparison strategy. .LINK - https://pester.dev/docs/functions/Get-EquivalencyOption + https://pester.dev/docs/commands/Get-EquivalencyOption + + .LINK + https://pester.dev/docs/assertions #> + [CmdletBinding()] param( [string[]] $ExcludePath = @(), [switch] $ExcludePathsNotOnExpected,