pull/15/head
Nikita Bykov 5 years ago
parent 2074b50c3d
commit 3a032ffb0e

@ -4,51 +4,30 @@ Pester extension that allows to run command and validate exit code
.EXAMPLE .EXAMPLE
"python file.py" | Should -ReturnZeroExitCode "python file.py" | Should -ReturnZeroExitCode
#> #>
function Get-CommandResult {
param (
[Parameter(Mandatory=$true)]
[string] $Command,
[switch] $Multiline
)
# Bash trick to suppress and show error output because some commands write to stderr (for example, "python --version")
if ($IsWindows) {
[string[]]$stdout = & $env:comspec /c "$Command 2>&1"
} else {
$stdout = & bash -c "$Command 2>&1"
}
$exitCode = $LASTEXITCODE
return @{
Output = If ($Multiline -eq $true) { $stdout } else { [string]$stdout }
ExitCode = $exitCode
}
}
function ShouldReturnZeroExitCode { function ShouldReturnZeroExitCode {
Param( Param(
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()]
[String]$ActualValue, [String]$ActualValue,
[switch] $Negate, [switch]$Negate
[string] $Because # This parameter is unused by we need it to match Pester asserts signature
) )
$result = Get-CommandResult $ActualValue Write-Host "Run command '${ActualValue}'"
Invoke-Expression -Command $ActualValue | ForEach-Object { Write-Host $_ }
$actualExitCode = $LASTEXITCODE
[bool]$succeeded = $result.ExitCode -eq 0 [bool]$succeeded = $actualExitCode -eq 0
if ($Negate) { $succeeded = -not $succeeded } if ($Negate) { $succeeded = -not $succeeded }
if (-not $succeeded) if (-not $succeeded)
{ {
$commandOutputIndent = " " * 4 $failureMessage = "Command '${ActualValue}' has finished with exit code ${actualExitCode}"
$commandOutput = ($result.Output | ForEach-Object { "${commandOutputIndent}${_}" }) -join "`n"
$failureMessage = "Command '${ActualValue}' has finished with exit code ${actualExitCode}`n${commandOutput}"
} }
return [PSCustomObject] @{ return New-Object PSObject -Property @{
Succeeded = $succeeded Succeeded = $succeeded
FailureMessage = $failureMessage FailureMessage = $failureMessage
} }
} }
if (Get-Command -Name Add-AssertionOperator -ErrorAction SilentlyContinue) { Add-AssertionOperator -Name ReturnZeroExitCode `
Add-AssertionOperator -Name ReturnZeroExitCode -InternalName ShouldReturnZeroExitCode -Test ${function:ShouldReturnZeroExitCode} -Test $function:ShouldReturnZeroExitCode
}
Loading…
Cancel
Save