Last active
January 7, 2019 07:54
-
-
Save ritalin/3971eb18e4b67c897c79574fbb579633 to your computer and use it in GitHub Desktop.
Operator to test sort order for Pester.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Import-Module Pester -MinimumVersion 4.0.5 -Force | |
<# | |
.EXAMPLE | |
It "Hoge" { | |
$collection | Should -BeSorted Field1,... | |
} | |
#> | |
function BeSorted($ActualValue, [string[]]$SortFields, [switch]$Negate, [int]$Sample = -1) { | |
$values = | |
if ($Sample -gt 0) { | |
$ActualValue | select -Property $SortFields -First $Sample | |
} | |
else { | |
$ActualValue | select -Property $SortFields | |
} | |
$sortedKeys = | |
$values | | |
%{$seq = 0}{ $_ | Add-Member NoteProperty BeforeIndex $seq -PassThru; ++$seq } | | |
sort -Property ($SortFields + @("BeforeIndex")) -CaseSensitive | | |
%{$seq1 = 0}{ $_ | Add-Member NoteProperty AfterIndex $seq1 -PassThru; ++$seq1 } | |
[bool]$failure = | |
if (-Not $Negate) { | |
$sortedKeys | ?{ $_.BeforeIndex -ne $_.AfterIndex } | |
} | |
else { | |
$sortedKeys | ?{ $_.BeforeIndex -eq $_.AfterIndex } | |
} | |
$message = $sortedKeys | select -First 1 | %{ "Incorrect sort order: [$(_FormatFalureMessage $_ $SortFields) (Index: $($_.BeforeIndex) => $($_.AfterIndex)) ...]" } | |
[PSCustomObject]@{ | |
Succeeded = -Not $failure | |
FailureMessage = $message | |
} | |
} | |
function _FormatFalureMessage($obj, [string[]]$names) { | |
$messages = | |
foreach ($n in $names) { | |
'{0} = `{1}`' -F $n,$obj."$n" | |
} | |
$messages -join ", " | |
} | |
Add-AssertionOperator -Name BeSorted -Test $function:BeSorted -SupportsArrayInput |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment