SelfTest.ps1

# SelfTest.ps1 - dot-sourced by Demo.ps1 -SelfTest inside the running launcher.
#
# Checks that every example is listed and that each tab shows the shipped source, then starts a
# few examples in each available language, checks that they keep running, and stops them.
# Prints PASS/FAIL/SKIP lines and a RESULT line; returns $true when something failed.

function Invoke-DemoSelfTest {
    $results = @{ Passed = 0; Failed = 0; Skipped = 0 }
    function Test-Check([bool]$Condition, [string]$Name, [string]$Detail) {
        if ($Condition) { $results.Passed++; [Console]::Out.WriteLine("PASS $Name") }
        else {
            $results.Failed++
            $line = "FAIL $Name"
            if ($Detail) { $line += ": $Detail" }
            [Console]::Out.WriteLine($line)
        }
        $Condition
    }
    # Pumps events (background-task callbacks, the poll timer) while waiting.
    function Wait-Demo([double]$Seconds, [scriptblock]$Until) {
        $end = [DateTime]::UtcNow.AddSeconds($Seconds)
        while ([DateTime]::UtcNow -lt $end) {
            if ($Until -and (& $Until)) { return $true }
            $null = Wait-NativeHTMLKit -Application $app -TimeoutMilliseconds 200
        }
        if ($Until) { return [bool](& $Until) }
        $true
    }

    $items = (Find-NativeHTMLKitElement -Document $script:Doc -Selector '#list .item').matched_nodes
    $null = Test-Check ($items -eq $script:Examples.Count) 'every example is listed' "$items of $($script:Examples.Count)"

    $mismatches = @()
    for ($i = 0; $i -lt $script:Examples.Count; $i++) {
        $entry = $script:Examples[$i]
        Select-Example $i
        foreach ($tab in @('python', 'powershell', 'html', 'css')) {
            $script:Tab = $tab
            Show-Tab
            if ($tab -eq 'python' -or $tab -eq 'powershell') { $expected = Get-SourceText $entry $tab -CodeOnly }
            else { $expected = [string]$entry.$tab }
            $actual = Get-NativeHTMLKitDocumentText -Document $script:Doc -Element code
            if ($actual -cne $expected) { $mismatches += "$($entry.key):$tab" }
        }
    }
    $null = Test-Check ($mismatches.Count -eq 0) 'source tabs show the shipped code and page' (($mismatches | Select-Object -First 5) -join ', ')

    # Code only vs full script (the Counter page is embedded in its code).
    $counter = 0
    for ($i = 0; $i -lt $script:Examples.Count; $i++) { if ($script:Examples[$i].key -eq 'sdk/counter') { $counter = $i } }
    Select-Example $counter
    $script:Tab = 'powershell'
    Show-Tab
    $codeOnly = Get-NativeHTMLKitDocumentText -Document $script:Doc -Element code
    $null = Test-Check ($codeOnly -notlike '*<!doctype html>*' -and $codeOnly -like '*Set-Count*') 'PowerShell tab shows code without the page' ''
    $script:Full = $true
    Show-Tab
    $full = Get-NativeHTMLKitDocumentText -Document $script:Doc -Element code
    $null = Test-Check ($full -ceq (Get-SourceText $script:Examples[$counter] 'powershell')) 'Full script shows the shipped file' ''
    $script:Full = $false
    $script:Tab = 'python'
    Select-Example 0

    Set-NativeHTMLKitDocumentValue -Document $script:Doc -Element search -Value 'chart'
    Update-Filter
    $shown = @()
    for ($i = 0; $i -lt $script:Examples.Count; $i++) {
        if ((Find-NativeHTMLKitElement -Document $script:Doc -Selector "#ex-$i.hidden").matched_nodes -eq 0) { $shown += $script:Examples[$i].key }
    }
    $null = Test-Check (($shown -join ',') -eq 'sdk/live-chart') 'the filter narrows the list' ($shown -join ',')
    $null = Test-Check ((Get-NativeHTMLKitDocumentText -Document $script:Doc -Element count-all) -eq '1' -and (Find-NativeHTMLKitElement -Document $script:Doc -Selector '#search-clear.hidden').matched_nodes -eq 0) 'the filter shows its match count and a clear button' ''
    Clear-Filter
    $null = Test-Check ((Get-NativeHTMLKitValue -Document $script:Doc -Element search) -eq '' -and $script:Visible.Count -eq $script:Examples.Count) 'the clear button restores the full list' "$($script:Visible.Count)"

    $script:Layer = 'ui'
    Update-Filter
    $uiCount = @($script:Examples | Where-Object { $_.layer -eq 'ui' }).Count
    $onlyUi = @($script:Visible | Where-Object { $script:Examples[$_].layer -ne 'ui' }).Count -eq 0
    $null = Test-Check ($onlyUi -and $script:Visible.Count -eq $uiCount -and (Find-NativeHTMLKitElement -Document $script:Doc -Selector '#group-sdk.hidden').matched_nodes -eq 1) 'the UI chip lists only UI examples' "$($script:Visible.Count)"
    Move-Selection 1
    $firstUi = $script:Visible[0]
    $null = Test-Check ($script:Selected -eq $firstUi) 'Down selects the first visible example' "$($script:Selected)"
    Move-Selection 1
    $null = Test-Check ($script:Selected -eq $script:Visible[1]) 'Down moves to the next example' "$($script:Selected)"
    Move-Selection -1
    $null = Test-Check ($script:Selected -eq $firstUi) 'Up moves back' "$($script:Selected)"
    $script:Layer = 'all'
    Update-Filter
    Select-Example 0

    foreach ($language in @('python', 'powershell')) {
        if ($language -eq 'python') { $runtime = $script:PythonRuntime } else { $runtime = $script:PowerShellRuntime }
        if (-not (Wait-Demo 90 { -not $runtime.Checking })) {
            $null = Test-Check $false "${language}: runtime probe finished" 'timed out'
            continue
        }
        if (-not $runtime.Ready) {
            $results.Skipped++
            [Console]::Out.WriteLine("SKIP ${language}: run examples: $($runtime.Message)")
            continue
        }
        foreach ($key in @('sdk/hello', 'sdk/log-viewer', 'ui/hello')) {
            $entry = $script:Examples | Where-Object { $_.key -eq $key } | Select-Object -First 1
            $name = "${language}: $key starts and keeps running"
            $state = Get-RuntimeState $runtime $entry $language
            if (-not $state[0]) {
                $results.Skipped++
                [Console]::Out.WriteLine("SKIP ${name}: $($state[1])")
                continue
            }
            $run = Start-Example $entry $language
            if (-not (Test-Check ($null -ne $run) "${language}: $key process started" '')) { continue }
            $null = Wait-Demo 8
            $alive = $null -eq $run.ExitCode
            $tail = Get-Tail $run.Output
            if ($tail.Length -gt 800) { $tail = $tail.Substring($tail.Length - 800) }
            $null = Test-Check $alive $name "exit code $($run.ExitCode); output: $tail"
            if ($run.SampleLog) {
                $lines = @([IO.File]::ReadAllLines($run.SampleLog)).Count
                $null = Test-Check ($lines -gt 12) "${language}: $key sample log grows" "$lines lines"
            }
            Stop-Example $run
            $stopped = Wait-Demo 20 { $null -ne $run.ExitCode }
            $null = Test-Check $stopped "${language}: $key stops" 'still running after Stop'
        }

        # A failing run: log-viewer without its file argument prints a usage message and exits.
        $index = 0
        for ($i = 0; $i -lt $script:Examples.Count; $i++) { if ($script:Examples[$i].key -eq 'sdk/log-viewer') { $index = $i } }
        $original = $script:Examples[$index]
        $entry = $original.PSObject.Copy()
        $item = $original.$language.PSObject.Copy()
        $item.args = @()
        $entry.$language = $item
        $run = Start-Example $entry $language
        if (Test-Check ($null -ne $run) "${language}: failing run started" '') {
            $ended = Wait-Demo 60 { $null -ne $run.ExitCode }
            $null = Test-Check ($ended -and $run.ExitCode -ne 0) "${language}: failing run reports its exit code" "exit code $($run.ExitCode)"
            Select-Example $index
            $script:Tab = 'output'
            Show-Tab
            $shown = Get-NativeHTMLKitDocumentText -Document $script:Doc -Element code
            $tail = $shown
            if ($tail.Length -gt 300) { $tail = $tail.Substring($tail.Length - 300) }
            $null = Test-Check ($shown -like '*Pass the log file to follow*') "${language}: Output tab shows the error" $tail
            $script:Tab = 'python'
        }
    }
    [Console]::Out.WriteLine("RESULT $($results.Passed) passed, $($results.Failed) failed, $($results.Skipped) skipped")
    $results.Failed -gt 0
}