Files

56 lines
1.7 KiB
PowerShell
Raw Permalink Normal View History

2020-04-16 17:22:06 +03:00
<#
.SYNOPSIS
Pester extension that allows to run command and validate exit code
.EXAMPLE
"python file.py" | Should -ReturnZeroExitCode
#>
2020-08-24 18:51:49 +03:00
function Get-CommandResult {
Param (
2020-08-24 18:51:49 +03:00
[Parameter(Mandatory=$true)]
[string] $Command,
[switch] $Multiline
)
2020-09-08 13:59:03 +03:00
# CMD and bash trick to suppress and show error output because some commands write to stderr (for example, "python --version")
If ($IsWindows) {
2020-09-08 14:00:33 +03:00
$stdout = & $env:comspec /c "$Command 2>&1"
} else {
2020-09-08 14:00:33 +03:00
$stdout = & bash -c "$Command 2>&1"
}
2020-08-24 18:51:49 +03:00
$exitCode = $LASTEXITCODE
2020-08-24 18:51:49 +03:00
return @{
2020-09-08 14:00:33 +03:00
Output = If ($Multiline -eq $true) { $stdout } else { [string]$stdout }
2020-08-24 18:51:49 +03:00
ExitCode = $exitCode
}
}
2020-04-16 17:22:06 +03:00
function ShouldReturnZeroExitCode {
Param(
2020-09-08 13:59:03 +03:00
[String] $ActualValue,
2020-08-24 18:40:08 +03:00
[switch] $Negate,
[string] $Because # This parameter is unused by we need it to match Pester asserts signature
2020-04-16 17:22:06 +03:00
)
2020-08-24 18:40:08 +03:00
$result = Get-CommandResult $ActualValue
2020-04-16 17:22:06 +03:00
2020-08-24 18:40:08 +03:00
[bool]$succeeded = $result.ExitCode -eq 0
2020-04-16 17:22:06 +03:00
if ($Negate) { $succeeded = -not $succeeded }
if (-not $succeeded)
{
2020-08-24 18:40:08 +03:00
$commandOutputIndent = " " * 4
$commandOutput = ($result.Output | ForEach-Object { "${commandOutputIndent}${_}" }) -join "`n"
$failureMessage = "Command '${ActualValue}' has finished with exit code ${actualExitCode}`n${commandOutput}"
2020-04-16 17:22:06 +03:00
}
2020-08-24 18:40:08 +03:00
return [PSCustomObject] @{
2020-04-16 17:22:06 +03:00
Succeeded = $succeeded
FailureMessage = $failureMessage
}
}
2020-08-24 18:40:08 +03:00
if (Get-Command -Name Add-AssertionOperator -ErrorAction SilentlyContinue) {
Add-AssertionOperator -Name ReturnZeroExitCode -InternalName ShouldReturnZeroExitCode -Test ${function:ShouldReturnZeroExitCode}
}