Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 113 additions & 1 deletion ParallelKit.Harness.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -3810,7 +3810,7 @@ function Get-HarnessUnguardedCallbacks {
# this list. Invoke-PkRun's `& $ScriptBlock` is the run itself, not called
# from a loop. Returns @{ Calls; Problems }.
param([string]$Source)
$internal = @('$pkNewBatchResult', '$pkGetStartFailureCause', '$pkGetJobTimeLimit', '$pkGetJobMaxOutputChars', '$pkReportStartFailure', '$pkStartProcessCore', '$pkWriteCallbackLoopWarning')
$internal = @('$pkNewBatchResult', '$pkGetStartFailureCause', '$pkGetJobTimeLimit', '$pkGetJobMaxOutputChars', '$pkGetJobSwitch', '$pkReportStartFailure', '$pkStartProcessCore', '$pkWriteCallbackLoopWarning')
$problems = [System.Collections.Generic.List[string]]::new()
$tokens = $null; $errors = $null
$ast = [System.Management.Automation.Language.Parser]::ParseInput($Source, [ref]$tokens, [ref]$errors)
Expand Down Expand Up @@ -5333,6 +5333,118 @@ Test-Assert ($bhRun.ExitCode -eq 1 -and $bhRun.Stdout -like '*No such section: Z
Write-Host ""
}

# ==============================================================================
if (Test-HarnessSection 'BI' "programs get NUL as stdin, unless -InheritStdin") {
# In a fresh PowerShell with a file as its stdin, on each start path. cmd's
# set /p on a file takes one line and leaves the rest, so each program here
# that inherits stdin reads the next line, and one that doesn't reads nothing.
# Each is time-limited: a program left reading would otherwise hang the test.
Reset-Harness
$biScript = Join-Path $env:TEMP ("pk-bi-" + [guid]::NewGuid().ToString("N") + ".ps1")
$biInput = [System.IO.Path]::ChangeExtension($biScript, '.txt')
$biBat = [System.IO.Path]::ChangeExtension($biScript, '.cmd')
[System.IO.File]::WriteAllText($biInput, ((1..9 | ForEach-Object { 'line' + $_ }) -join "`r`n") + "`r`n")
[System.IO.File]::WriteAllText($biScript, @'
param([string]$Kit, [int]$Fallback)
$ErrorActionPreference = 'Stop'
. $Kit
[PkChildProcessJob]::TestUseProcessStart = ($Fallback -eq 1)
$read = @{ FilePath = 'cmd.exe'; Arguments = '/d /v:on /c "set L=none& set /p L=& echo [!L!]"' }
$out = @{}
function Invoke-One([string]$Name, [hashtable]$Extra) {
try { $script:out[$Name] = ([string](Invoke-PkProcessWithTimeout @read -TimeoutMs 8000 @Extra).Stdout).Trim() } catch { $script:out[$Name] = 'ERROR ' + $_ }
}
function Invoke-Batch([string]$Name, [hashtable]$Extra, [hashtable]$Key) {
$r = (Invoke-PkProcessBatch -Commands @($read + $Key) -TimeoutSeconds 8 @Extra).Results[0]
$script:out[$Name] = if ($r.TimedOut) { 'TIMED OUT' } elseif ($r.StartError) { 'ERROR ' + $r.StartError } else { ([string]$r.Stdout).Trim() }
}
function Invoke-Dispatch([string]$Name, [hashtable]$Extra, [hashtable]$Key) {
$feed = @{ Given = $false }; $got = @{ Text = 'no result' }; $job = $read + $Key
$null = Invoke-PkProcessDispatch -MaxConcurrent 1 -TimeoutSeconds 8 @Extra `
-GroupProvider { if ($feed.Given) { return $null }; $feed.Given = $true; return 'g' }.GetNewClosure() `
-JobBuilder { param($g) return @($job) }.GetNewClosure() `
-JobFinalize { param($j, $q) $got.Text = if ($j['TimedOut']) { 'TIMED OUT' } else { ([string](Complete-PkProcess $j).Stdout).Trim() } }.GetNewClosure()
$script:out[$Name] = $got.Text
}
function Invoke-Start([string]$Name, [hashtable]$Extra) {
$j = Start-PkProcess @read @Extra
if (-not (Wait-PkProcess $j.Proc -TimeoutMs 8000)) { $null = Stop-PkProcessTree $j.Proc; $script:out[$Name] = 'TIMED OUT'; return }
$script:out[$Name] = ([string](Complete-PkProcess $j -Dispose).Stdout).Trim()
}
Invoke-Start 'start' @{}
Invoke-One 'one' @{}
Invoke-Batch 'batch' @{} @{}
Invoke-Dispatch 'dispatch' @{} @{}
# timeout.exe needs a console to read from, and says so at once without one.
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$t = Invoke-PkProcessWithTimeout -FilePath ([Environment]::SystemDirectory + '/timeout.exe') -Arguments '/t 6' -TimeoutMs 15000
$out['timeout'] = [string]$t.ExitCode + ' ' + ($sw.Elapsed.TotalSeconds -lt 4) + ' ' + (-not [string]::IsNullOrWhiteSpace($t.Stderr))
if ((Get-Command Start-PkProcess).Parameters.ContainsKey('InheritStdin')) {
Invoke-Start 'start -InheritStdin' @{ InheritStdin = $true }
Invoke-One 'one -InheritStdin' @{ InheritStdin = $true }
Invoke-Batch 'batch -InheritStdin' @{ InheritStdin = $true } @{}
Invoke-Batch 'batch key' @{} @{ InheritStdin = $true }
Invoke-Batch 'batch -InheritStdin, key off' @{ InheritStdin = $true } @{ InheritStdin = $false }
Invoke-Batch 'batch key as text' @{} @{ InheritStdin = 'True' }
Invoke-Batch 'batch bad key' @{} @{ InheritStdin = 'maybe' }
Invoke-Dispatch 'dispatch -InheritStdin' @{ InheritStdin = $true } @{}
Invoke-Dispatch 'dispatch key' @{} @{ InheritStdin = $true }
Invoke-Dispatch 'dispatch -InheritStdin, key off' @{ InheritStdin = $true } @{ InheritStdin = $false }
}
foreach ($k in $out.Keys) { '{0}={1}' -f $k, $out[$k] }
'@)
# A .cmd, since it takes cmd.exe to start PowerShell with a file as its stdin.
[System.IO.File]::WriteAllText($biBat, "@`"$selfExe`" -NoProfile -ExecutionPolicy Bypass -File `"$biScript`" -Kit `"$kitPath`" -Fallback %1 < `"$biInput`"`r`n")
try {
foreach ($biFallback in 0, 1) {
$biPath = @('CreatedInJob', 'Process.Start')[$biFallback]
$biRun = Invoke-PkProcessWithTimeout -FilePath $biBat -Arguments ([string]$biFallback) -TimeoutMs 120000
$bi = @{}
foreach ($biLine in ([string]$biRun.Stdout -split "`r?`n")) { $biAt = $biLine.IndexOf('='); if ($biAt -gt 0) { $bi[$biLine.Substring(0, $biAt)] = $biLine.Substring($biAt + 1) } }
foreach ($biName in 'start', 'one', 'batch', 'dispatch') {
Test-Assert ($bi[$biName] -eq '[none]') ("a program reading stdin gets nothing and exits (" + $biName + ", " + $biPath + ": " + $bi[$biName] + ")")
}
Test-Assert ($bi['timeout'] -eq '1 True True') ("timeout.exe, which needs a console to read from, fails at once (" + $biPath + ": exit, quick, says why: " + $bi['timeout'] + ")")
$biNext = 1
foreach ($biName in 'start -InheritStdin', 'one -InheritStdin', 'batch -InheritStdin', 'batch key', 'batch key as text', 'dispatch -InheritStdin', 'dispatch key') {
Test-Assert ($bi[$biName] -eq ('[line' + $biNext + ']')) ("it reads the script's stdin with the opt-in (" + $biName + ", " + $biPath + ": " + $bi[$biName] + ")")
$biNext++
}
foreach ($biName in 'batch -InheritStdin, key off', 'dispatch -InheritStdin, key off') {
Test-Assert ($bi[$biName] -eq '[none]') ("a key of `$false overrides -InheritStdin (" + $biName + ", " + $biPath + ": " + $bi[$biName] + ")")
}
Test-Assert ([string]$bi['batch bad key'] -like 'ERROR *InheritStdin must be*maybe*') ("a bad InheritStdin key is that command's StartError (" + $biPath + ": " + $bi['batch bad key'] + ")")
}
} finally {
foreach ($biFile in $biScript, $biInput, $biBat) { [System.IO.File]::Delete($biFile) }
}

# A console whose input code page is UTF-8: on .NET Framework, Process.Start
# writes a byte-order mark into a redirected stdin, which a program would read
# as input. Only the fallback path on 5.1, where Process.Start takes no
# encoding for it. Read back through findstr, which prints any line it gets.
Reset-Harness
$biScript = Join-Path $env:TEMP ("pk-bi-" + [guid]::NewGuid().ToString("N") + ".ps1")
[System.IO.File]::WriteAllText($biScript, @'
param([string]$Kit)
. $Kit
$null = & chcp.com 65001
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
foreach ($fallback in $false, $true) {
[PkChildProcessJob]::TestUseProcessStart = $fallback
$r = Invoke-PkProcessWithTimeout -FilePath findstr.exe -Arguments '/n "^"' -TimeoutMs 8000
'READ=' + ([string]$r.Stdout).Trim().Length + ' EXIT=' + $r.ExitCode
}
'@)
try { $biRun = Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments ('-NoProfile -ExecutionPolicy Bypass -File "' + $biScript + '" -Kit "' + $kitPath + '"') -TimeoutMs 60000 } finally { [System.IO.File]::Delete($biScript) }
$biReads = @([regex]::Matches([string]$biRun.Stdout, 'READ=\d+ EXIT=\d+') | ForEach-Object { $_.Value }) -join '; '
$biWanted = @('READ=0 EXIT=1; READ=0 EXIT=1')
if ($PSVersionTable.PSVersion.Major -lt 6) { $biWanted += 'READ=0 EXIT=1; READ=5 EXIT=0' } # "1:" and the mark's three bytes
Test-Assert ($biWanted -contains $biReads) ("stdin is empty with a UTF-8 console too, on both start paths, apart from 5.1's byte-order mark on the fallback (" + $biReads + ")")
Reset-Harness
Write-Host ""
}

Set-PkMessageHandler -Handler $null
Reset-PkAbortState

Expand Down
Loading
Loading