diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c3559626..9312f42e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -22,6 +22,10 @@ scripts/smoke.ps1 -Exe src/DesktopShell/bin/Release/net10.0-windows/TomeStack.ex scripts/single-instance-check.ps1 -Exe src/DesktopShell/bin/Release/net10.0-windows/TomeStack.exe # two processes on one data folder (M2.1) ``` +`scripts/gate.ps1` runs steps 1–8 in this order under Windows PowerShell, with one log per step and a summary (`summary.txt`) in `-LogDir`. It stops at the first failure, kills a hung e2e or a11y run after `-DevHostStepTimeoutMinutes` (15 by default), and stops this checkout's DevHost before and after the run. `-LowPriority` runs the steps below normal priority, so the gate yields to other work. Use it only when that matters more than the result, because on a busy machine the UI tests' timing checks can then flake. A CPU check warns when the machine is already busy (`-RequireQuiet` fails instead). It is a convenience: the commands above stay the gate, and smoke and single-instance still run by hand. + +Local test runs are capped so a full run doesn't saturate a many-core machine. Vitest uses at most 8 workers (never more than the core count), and xUnit at most 8 threads per project on machines with more than 8 cores. CI keeps the defaults. Override with `TOMESTACK_TEST_WORKERS=` for Vitest, or `dotnet test ... -- xUnit.MaxParallelThreads=` (`gate.ps1 -UiWorkers`, `-XunitThreads`, `-ProjectParallelism`). + When changing a package version, run `dotnet restore TomeStack.slnx` and commit the updated `packages.lock.json` files (CI restores in locked mode). ## Invariants diff --git a/Directory.Build.props b/Directory.Build.props index 1f594ea9..5751becf 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -85,4 +85,11 @@ $(NoWarn);CA1859 + + + + + diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 6628228a..feb6dfa5 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -3,6 +3,7 @@ ## Unreleased ### Added +- **Development only, test load caps and a gate script:** local test runs no longer use every core. Vitest runs at most 8 workers (override with `TOMESTACK_TEST_WORKERS`), and xUnit runs at most 8 threads per test project on machines with more than 8 cores; CI keeps its defaults. `scripts/gate.ps1` runs gate steps 1–8 in order, with per-step logs, a summary, a watchdog for a hung e2e or a11y run, DevHost cleanup, an optional lower priority and a CPU check. No app change. - **Accessibility check in CI, two contrast fixes:** `npm run test:a11y` runs axe, colour contrast included, in the installed Edge against the DevHost, in light and dark, over home, each builder step and each sheet tab, plus home in each named theme. Serious and critical violations fail it, and it now runs in CI. It found two low-contrast spots, both fixed without changing any colour: the "Offline" tag in the header now sits on the page colour, and in the dark theme the sheet's status-bar buttons (Hit points, Armor Class, Initiative, Speed) now sit on the page colour instead of the browser's grey button face. - **Tests only:** the UI flow tests in `src/Ui/e2e/` are split by feature (the 69 tests of `flow.e2e.tsx` into eight files, the 13 of `forms.e2e.tsx` into two, shared helpers in `helpers.tsx`); no test changed and no file is over 800 lines. The e2e files now run one after another against the shared DevHost. No app change. - **Release assets:** each release now includes two CycloneDX software bills of materials, `tomestack-X.Y.Z-nuget.cdx.json` (the .NET packages) and `tomestack-X.Y.Z-npm.cdx.json` (the UI's npm runtime packages). They are listed in `SHA256SUMS` and attested like the installer (D101). No app change. diff --git a/scripts/gate.ps1 b/scripts/gate.ps1 new file mode 100644 index 00000000..ac25b549 --- /dev/null +++ b/scripts/gate.ps1 @@ -0,0 +1,245 @@ +<# +.SYNOPSIS +Runs the TomeStack gate steps 1-8 (CONTRIBUTING.md, "The gate") in order, with logs, a summary and a watchdog on the DevHost steps. + +.DESCRIPTION +Optional helper: the commands in CONTRIBUTING.md stay authoritative. Runs on Windows PowerShell 5.1. +Step ids, in order: npm-ci, lint, ui-test, ui-build, dotnet-build, dotnet-test, e2e, a11y. +The GUI steps (scripts/smoke.ps1 and scripts/single-instance-check.ps1) need the built desktop exe and are left to the owner; they are not in this table. +The run stops at the first failing step; the summary is still printed and written to \summary.txt. +Exit codes: 0 all passed, the failing step's exit code, 124 watchdog timeout (e2e or a11y), 2 bad arguments or a CPU check failure under -RequireQuiet. + +.PARAMETER From +Start at this step id and run the later steps. +.PARAMETER Only +Run only these step ids (comma separated). +.PARAMETER LogDir +Where the per-step logs and summary.txt go. Default: a time-stamped folder under the temp directory. +.PARAMETER DevHostStepTimeoutMinutes +Watchdog for the e2e and a11y steps (both use the DevHost); the whole process tree is killed on expiry. Old name: -E2eTimeoutMinutes. +.PARAMETER UiWorkers +Sets TOMESTACK_TEST_WORKERS for the children when greater than 0. +.PARAMETER XunitThreads +Adds "-- xUnit.MaxParallelThreads=" to dotnet test when greater than 0. +.PARAMETER ProjectParallelism +Adds "-m:" to dotnet test when greater than 0. +.PARAMETER LowPriority +Starts each step at BelowNormal priority. +.PARAMETER CpuWarnPercent +Warn (or fail under -RequireQuiet) when the average CPU load before the run is at or above this percentage. +.PARAMETER StepsJson +Tests only: a JSON array of {id, exe, args} that replaces the built-in step table. +#> +[CmdletBinding()] +param( + [string]$From, + [string[]]$Only, + [string]$LogDir = (Join-Path (Join-Path $env:TEMP 'tomestack-gate') (Get-Date -Format 'yyyyMMdd-HHmmss')), + [Alias('E2eTimeoutMinutes')] + [double]$DevHostStepTimeoutMinutes = 15, + [int]$UiWorkers, + [int]$XunitThreads, + [int]$ProjectParallelism, + [switch]$LowPriority, + [int]$CpuWarnPercent = 25, + [switch]$RequireQuiet, + [switch]$SkipCpuCheck, + [switch]$DryRun, + [switch]$SkipDevHostCleanup, + [string]$StepsJson, + [string]$SelfTestMatch +) + +$ErrorActionPreference = 'Stop' +$repoRoot = Split-Path -Parent $PSScriptRoot +# -StepsJson (tests) never touches real processes, so it implies -SkipDevHostCleanup. +$skipCleanup = $SkipDevHostCleanup -or [bool]$StepsJson + +# --- Helpers --- +function Format-Arg([string]$a) { + if ($a.Length -eq 0) { return '""' } + if ($a -notmatch '[\s"]') { return $a } + $q = $a -replace '(\\*)"', '$1$1\"' # backslashes before a quote are doubled, then the quote is escaped + $q = $q -replace '(\\+)$', '$1$1' # trailing backslashes are doubled so they do not escape the closing quote + return '"' + $q + '"' +} + +function Test-RepoDevHost([string]$Name, [string]$ExecutablePath, [string]$CommandLine, [string]$Root) { + # The e2e/a11y harness runs `dotnet \src\DevHost\bin\...\TomeStack.DevHost.dll`; an apphost TomeStack.DevHost.exe is covered too. + # Both matches are anchored on the repo root plus a trailing backslash, so a sibling folder such as 2 never matches. + $prefix = $Root.TrimEnd('\') + '\' + if ($Name -like 'TomeStack.DevHost*.exe' -and $ExecutablePath -and $ExecutablePath.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) { return $true } + if ($Name -ieq 'dotnet.exe' -and $CommandLine -and + $CommandLine.IndexOf($prefix + 'src\DevHost\', [StringComparison]::OrdinalIgnoreCase) -ge 0 -and + $CommandLine.IndexOf('TomeStack.DevHost', [StringComparison]::OrdinalIgnoreCase) -ge 0) { return $true } + return $false +} + +function Stop-DevHost { + if ($skipCleanup) { return } + $count = 0 + try { + $found = Get-CimInstance Win32_Process | Where-Object { Test-RepoDevHost $_.Name $_.ExecutablePath $_.CommandLine $repoRoot } + foreach ($p in $found) { + try { Stop-Process -Id $p.ProcessId -Force -ErrorAction Stop; $count++ } catch { } + } + } + catch { Write-Warning 'DevHost cleanup unavailable.' } + Write-Host "DevHost cleanup: stopped $count process(es)." +} + +function Write-EarlySummary([string]$Reason) { + # Bad arguments and a failed CPU check end the run before any step; the reason still goes to summary.txt. + try { + New-Item -ItemType Directory -Force -Path $LogDir | Out-Null + $Reason | Out-File -FilePath (Join-Path $LogDir 'summary.txt') -Encoding ascii + } + catch { Write-Warning 'Could not write summary.txt.' } +} + +if ($SelfTestMatch) { + # Tests only: {name, exe, cmd, root} -> prints "match: True|False" without looking at any real process. + $probe = ConvertFrom-Json -InputObject $SelfTestMatch + Write-Host ('match: {0}' -f (Test-RepoDevHost ([string]$probe.name) ([string]$probe.exe) ([string]$probe.cmd) ([string]$probe.root))) + exit 0 +} + +# --- Step table --- +if ($StepsJson) { + # The parentheses make Windows PowerShell 5.1 enumerate the parsed array instead of passing it on as one object. + $steps = @((ConvertFrom-Json -InputObject $StepsJson) | ForEach-Object { + [pscustomobject]@{ id = [string]$_.id; exe = [string]$_.exe; args = @($_.args | ForEach-Object { [string]$_ }) } + }) +} +else { + $testArgs = @('test', 'TomeStack.slnx', '-c', 'Release') + if ($ProjectParallelism -gt 0) { $testArgs += "-m:$ProjectParallelism" } + if ($XunitThreads -gt 0) { $testArgs += @('--', "xUnit.MaxParallelThreads=$XunitThreads") } + $steps = @( + [pscustomobject]@{ id = 'npm-ci'; exe = 'npm.cmd'; args = @('ci', '--prefix', 'src/Ui') }, + [pscustomobject]@{ id = 'lint'; exe = 'npm.cmd'; args = @('run', 'lint', '--prefix', 'src/Ui') }, + [pscustomobject]@{ id = 'ui-test'; exe = 'npm.cmd'; args = @('test', '--prefix', 'src/Ui') }, + [pscustomobject]@{ id = 'ui-build'; exe = 'npm.cmd'; args = @('run', 'build', '--prefix', 'src/Ui') }, + [pscustomobject]@{ id = 'dotnet-build'; exe = 'dotnet'; args = @('build', 'TomeStack.slnx', '-c', 'Release') }, + [pscustomobject]@{ id = 'dotnet-test'; exe = 'dotnet'; args = $testArgs }, + [pscustomobject]@{ id = 'e2e'; exe = 'npm.cmd'; args = @('run', 'test:e2e', '--prefix', 'src/Ui') }, + [pscustomobject]@{ id = 'a11y'; exe = 'npm.cmd'; args = @('run', 'test:a11y', '--prefix', 'src/Ui') } + ) +} +$validIds = @($steps | ForEach-Object { $_.id }) + +# --- Select steps --- +$onlyIds = @() +foreach ($o in @($Only)) { if ($o) { $onlyIds += ($o -split ',') | Where-Object { $_ } } } +$bad = @() +if ($From -and ($validIds -notcontains $From)) { $bad += $From } +foreach ($o in $onlyIds) { if ($validIds -notcontains $o) { $bad += $o } } +if ($bad.Count -gt 0) { + $reason = "Unknown step id: {0}. Valid ids: {1}" -f ($bad -join ', '), ($validIds -join ', ') + Write-Host $reason + Write-EarlySummary $reason + exit 2 +} +$selected = @($steps) +if ($From) { + $index = [array]::IndexOf($validIds, $From) + $selected = @($steps | Select-Object -Skip $index) +} +if ($onlyIds.Count -gt 0) { $selected = @($selected | Where-Object { $onlyIds -contains $_.id }) } + +if ($DryRun) { + # The CPU check below still runs under -DryRun so that -RequireQuiet can be exercised. + foreach ($s in $selected) { Write-Host ("{0}: {1} {2}" -f $s.id, $s.exe, (($s.args | ForEach-Object { Format-Arg $_ }) -join ' ')) } +} + +# --- CPU check --- +if (-not $SkipCpuCheck) { + try { + $counter = '\Processor(_Total)\% Processor Time' + $samples = Get-Counter -Counter $counter -SampleInterval 1 -MaxSamples 3 + $average = ($samples | ForEach-Object { $_.CounterSamples[0].CookedValue } | Measure-Object -Average).Average + $line = 'Average {0} was {1:N0}% over 3 s (threshold {2}%).' -f $counter, $average, $CpuWarnPercent + if ($average -ge $CpuWarnPercent) { + if ($RequireQuiet) { Write-Host "Machine is not quiet. $line"; Write-EarlySummary "Machine is not quiet. $line"; exit 2 } + Write-Warning "Machine is busy; timings and flakes may not be representative. $line" + } + else { Write-Host $line } + } + catch { + if ($RequireQuiet) { Write-Host 'CPU check unavailable and -RequireQuiet was given.'; Write-EarlySummary 'CPU check unavailable and -RequireQuiet was given.'; exit 2 } + Write-Warning 'CPU check unavailable.' + } +} + +if ($DryRun) { exit 0 } + +New-Item -ItemType Directory -Force -Path $LogDir | Out-Null +# Both are restored in the finally block, so running the script with & from an open shell leaves that shell as it was. +$originalWorkers = $env:TOMESTACK_TEST_WORKERS +$originalPriority = [Diagnostics.Process]::GetCurrentProcess().PriorityClass +if ($UiWorkers -gt 0) { $env:TOMESTACK_TEST_WORKERS = [string]$UiWorkers } +if ($LowPriority) { + # Lowering this process first means every step inherits BelowNormal from creation; the per-step set below is a fallback. + try { [Diagnostics.Process]::GetCurrentProcess().PriorityClass = 'BelowNormal' } catch { Write-Warning 'Could not lower priority.' } +} + +$results = @() +$exitCode = 0 +Stop-DevHost +try { + foreach ($s in $selected) { + Write-Host ("[{0}] {1} {2}" -f $s.id, $s.exe, (($s.args | ForEach-Object { Format-Arg $_ }) -join ' ')) + $clock = [Diagnostics.Stopwatch]::StartNew() + $startArgs = @{ + FilePath = $s.exe + PassThru = $true + NoNewWindow = $true + WorkingDirectory = $repoRoot + RedirectStandardOutput = (Join-Path $LogDir ($s.id + '.log')) + RedirectStandardError = (Join-Path $LogDir ($s.id + '.err.log')) + } + if ($s.args.Count -gt 0) { $startArgs.ArgumentList = @($s.args | ForEach-Object { Format-Arg $_ }) } + try { $proc = Start-Process @startArgs } + catch { + $clock.Stop() + Write-Host ("[{0}] failed to start: {1}" -f $s.id, $_.Exception.Message) + $results += [pscustomobject]@{ id = $s.id; exit = 1; seconds = [math]::Round($clock.Elapsed.TotalSeconds, 1); note = 'failed to start' } + $exitCode = 1 + break + } + $null = $proc.Handle # keeps the handle so ExitCode is readable (PS 5.1) + if ($LowPriority) { try { $proc.PriorityClass = 'BelowNormal' } catch { Write-Warning 'Could not lower priority.' } } + + $code = 0 + $note = '' + if ($s.id -eq 'e2e' -or $s.id -eq 'a11y') { + if (-not $proc.WaitForExit([int]($DevHostStepTimeoutMinutes * 60000))) { + & taskkill.exe /T /F /PID $proc.Id 2>&1 | Out-Null + $proc.WaitForExit() + $code = 124 + $note = 'timed out' + Write-Host ("[{0}] timed out after {1} min; process tree killed." -f $s.id, $DevHostStepTimeoutMinutes) + } + else { $code = $proc.ExitCode } + } + else { + $proc.WaitForExit() + $code = $proc.ExitCode + } + if ($null -eq $code) { $code = 1 } # an unreadable exit code is a failure, not a pass + $clock.Stop() + $results += [pscustomobject]@{ id = $s.id; exit = $code; seconds = [math]::Round($clock.Elapsed.TotalSeconds, 1); note = $note } + if ($code -ne 0) { $exitCode = $code; break } + } +} +finally { + Stop-DevHost + $env:TOMESTACK_TEST_WORKERS = $originalWorkers + if ($LowPriority) { try { [Diagnostics.Process]::GetCurrentProcess().PriorityClass = $originalPriority } catch { Write-Warning 'Could not restore priority.' } } + $lines = @('{0,-14} {1,5} {2,9} {3}' -f 'id', 'exit', 'seconds', '') + foreach ($r in $results) { $lines += ('{0,-14} {1,5} {2,9} {3}' -f $r.id, $r.exit, $r.seconds, $r.note) } + $lines | ForEach-Object { Write-Host $_ } + $lines | Out-File -FilePath (Join-Path $LogDir 'summary.txt') -Encoding ascii + Write-Host "Logs: $LogDir" +} +exit $exitCode diff --git a/src/Ui/e2e/builder.e2e.tsx b/src/Ui/e2e/builder.e2e.tsx index 1c6f835a..06cfdd46 100644 --- a/src/Ui/e2e/builder.e2e.tsx +++ b/src/Ui/e2e/builder.e2e.tsx @@ -347,9 +347,13 @@ it('drops picks that do not fit when the rules family changes, in the builder an await user.click(screen.getByRole('button', { name: 'Next: class' })); await user.click(screen.getByRole('button', { name: 'Next: ability scores' })); await user.click(screen.getByRole('button', { name: 'Next: species' })); - // D31: the 5.1 species leaves the list altogether, and the pick is cleared. - await waitFor(() => expect(within(screen.getByRole('group', { name: 'Species' })).queryByRole('radio', { name: /^Half-Orc/ })).toBeNull()); - expect(within(screen.getByRole('group', { name: 'Species' })).getByRole('radio', { name: 'None' }).checked).toBe(true); + // D31: the 5.1 species leaves the list altogether, and the pick is cleared. Wait for the loaded list ("None" present): + // while the options are still loading there are no radios at all, so "no Half-Orc" alone passes too early. + await waitFor(() => { + const list = within(screen.getByRole('group', { name: 'Species' })); + expect(list.getByRole('radio', { name: 'None' }).checked).toBe(true); + expect(list.queryByRole('radio', { name: /^Half-Orc/ })).toBeNull(); + }); await user.click(screen.getByRole('button', { name: 'Cancel' })); await user.click(await screen.findByRole('button', { name: 'Discard' })); // the rules family was changed: Cancel asks first diff --git a/src/Ui/tsconfig.json b/src/Ui/tsconfig.json index 10c1614a..d8f49212 100644 --- a/src/Ui/tsconfig.json +++ b/src/Ui/tsconfig.json @@ -17,5 +17,5 @@ "skipLibCheck": true, "types": ["vite/client", "node"] }, - "include": ["src", "e2e", "a11y", "vite.config.ts", "vitest.e2e.config.ts", "vitest.a11y.config.ts", "eslint.config.js"] + "include": ["src", "e2e", "a11y", "vite.config.ts", "vitest.workers.ts", "vitest.workers.test.ts","vitest.e2e.config.ts", "vitest.a11y.config.ts", "eslint.config.js"] } diff --git a/src/Ui/vite.config.ts b/src/Ui/vite.config.ts index e8b62082..438cbb27 100644 --- a/src/Ui/vite.config.ts +++ b/src/Ui/vite.config.ts @@ -4,6 +4,9 @@ import { join } from 'node:path'; import type { Plugin } from 'vite'; import { defineConfig } from 'vitest/config'; import react from '@vitejs/plugin-react'; +import { resolveMaxWorkers } from './vitest.workers.ts'; + +const maxWorkers = resolveMaxWorkers(process.env); const devHostPort = process.env.TOMESTACK_DEV_PORT ?? '5178'; const devDataDir = @@ -43,7 +46,8 @@ function contentSecurityPolicy(): Plugin { export default defineConfig({ plugins: [react(), contentSecurityPolicy()], base: './', - test: { setupFiles: ['src/test/setup.ts'] }, + // Capped locally because an uncapped run on a 24-thread machine saturates the CPU and flakes timing tests. + test: { setupFiles: ['src/test/setup.ts'], ...(maxWorkers === undefined ? {} : { maxWorkers }) }, build: { outDir: 'dist', emptyOutDir: true, sourcemap: false }, server: { host: '127.0.0.1', diff --git a/src/Ui/vitest.workers.test.ts b/src/Ui/vitest.workers.test.ts new file mode 100644 index 00000000..67ad28f9 --- /dev/null +++ b/src/Ui/vitest.workers.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from 'vitest'; +import { LOCAL_MAX_WORKERS, resolveMaxWorkers } from './vitest.workers'; + +const MANY = 24; + +describe('resolveMaxWorkers', () => { + it('caps local runs', () => { + expect(LOCAL_MAX_WORKERS).toBe(8); + expect(resolveMaxWorkers({}, MANY)).toBe(8); + }); + + it('never raises workers above the core count', () => { + expect(resolveMaxWorkers({}, 4)).toBe(4); + expect(resolveMaxWorkers({}, 1)).toBe(1); + }); + + it('leaves the Vitest default on CI', () => { + expect(resolveMaxWorkers({ CI: 'true' }, MANY)).toBeUndefined(); + expect(resolveMaxWorkers({ CI: '1' }, MANY)).toBeUndefined(); + }); + + it('treats CI=false or empty as not CI', () => { + expect(resolveMaxWorkers({ CI: 'false' }, MANY)).toBe(8); + expect(resolveMaxWorkers({ CI: 'FALSE' }, MANY)).toBe(8); + expect(resolveMaxWorkers({ CI: '' }, MANY)).toBe(8); + }); + + it('honours a positive integer override, even on CI or above the core count', () => { + expect(resolveMaxWorkers({ TOMESTACK_TEST_WORKERS: '4' }, MANY)).toBe(4); + expect(resolveMaxWorkers({ CI: 'true', TOMESTACK_TEST_WORKERS: '3' }, MANY)).toBe(3); + expect(resolveMaxWorkers({ TOMESTACK_TEST_WORKERS: '12' }, 4)).toBe(12); + }); + + it.each(['abc', '0', '-3', '2.5'])('ignores the junk override %s', (junk) => { + expect(resolveMaxWorkers({ TOMESTACK_TEST_WORKERS: junk }, MANY)).toBe(8); + expect(resolveMaxWorkers({ CI: 'true', TOMESTACK_TEST_WORKERS: junk }, MANY)).toBeUndefined(); + }); +}); diff --git a/src/Ui/vitest.workers.ts b/src/Ui/vitest.workers.ts new file mode 100644 index 00000000..be893ee5 --- /dev/null +++ b/src/Ui/vitest.workers.ts @@ -0,0 +1,22 @@ +import { availableParallelism } from 'node:os'; + +/** Local cap on Vitest workers; an uncapped run on a many-thread machine saturates the CPU and flakes timing tests. */ +export const LOCAL_MAX_WORKERS = 8; + +/** + * Worker count for Vitest: a positive-integer TOMESTACK_TEST_WORKERS wins; on CI (set, non-empty, not "false") + * returns undefined so Vitest keeps its default; otherwise the local cap, never above the core count. + */ +export function resolveMaxWorkers( + env: Record, + cores: number = availableParallelism(), +): number | undefined { + const override = env.TOMESTACK_TEST_WORKERS; + if (override !== undefined && /^\d+$/.test(override)) { + const n = Number.parseInt(override, 10); + if (n > 0) return n; + } + const ci = env.CI; + if (ci !== undefined && ci !== '' && ci.toLowerCase() !== 'false') return undefined; + return Math.min(LOCAL_MAX_WORKERS, Math.max(1, cores)); +} diff --git a/tests/AppService.Tests/GateScriptTests.cs b/tests/AppService.Tests/GateScriptTests.cs new file mode 100644 index 00000000..d10caf8b --- /dev/null +++ b/tests/AppService.Tests/GateScriptTests.cs @@ -0,0 +1,172 @@ +using System.Diagnostics; +using System.Text.Json; + +namespace TomeStack.AppService.Tests; + +/// +/// Runs scripts/gate.ps1 under Windows PowerShell with -DryRun or a -StepsJson table (never the real gate) and checks +/// step selection, the stop-on-failure summary, the e2e watchdog and the -RequireQuiet CPU check. +/// +public sealed class GateScriptTests +{ + private static string RepoRoot + { + get + { + var directory = new DirectoryInfo(AppContext.BaseDirectory); + while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "TomeStack.slnx"))) + directory = directory.Parent; + return directory?.FullName ?? throw new InvalidOperationException("TomeStack.slnx not found above the test output folder."); + } + } + + /// Runs the script with a temporary -LogDir and returns its exit code, output, elapsed time and the log folder (deleted after ). + private static (int ExitCode, string Output, TimeSpan Elapsed) Run(Action? inspect, params string[] scriptArguments) + { + var logDir = Path.Combine(Path.GetTempPath(), "ts-gate-" + Guid.NewGuid().ToString("N")); + try + { + var start = new ProcessStartInfo("powershell") + { + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true, + }; + foreach (var arg in new[] { "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", Path.Combine(RepoRoot, "scripts", "gate.ps1"), "-LogDir", logDir }) + start.ArgumentList.Add(arg); + foreach (var arg in scriptArguments) + start.ArgumentList.Add(arg); + + var clock = Stopwatch.StartNew(); + using var process = Process.Start(start)!; + var stdout = process.StandardOutput.ReadToEndAsync(); + var stderr = process.StandardError.ReadToEndAsync(); + if (!process.WaitForExit(120_000)) + { + process.Kill(entireProcessTree: true); + Assert.Fail("gate.ps1 did not finish within 120 s."); + } + clock.Stop(); + inspect?.Invoke(logDir); + return (process.ExitCode, stdout.Result + stderr.Result, clock.Elapsed); + } + finally + { + if (Directory.Exists(logDir)) + Directory.Delete(logDir, recursive: true); + } + } + + private static string Steps(params (string Id, string Command)[] steps) => + JsonSerializer.Serialize(steps.Select(s => new { id = s.Id, exe = "powershell", args = new[] { "-NoProfile", "-Command", s.Command } })); + + [Fact] + public void Dry_run_lists_the_eight_steps_in_order() + { + var (exitCode, output, _) = Run(null, "-DryRun", "-SkipCpuCheck"); + + Assert.Equal(0, exitCode); + var position = -1; + foreach (var id in new[] { "npm-ci", "lint", "ui-test", "ui-build", "dotnet-build", "dotnet-test", "e2e", "a11y" }) + { + var next = output.IndexOf(id, position + 1, StringComparison.Ordinal); + Assert.True(next > position, $"Step '{id}' is missing or out of order in:\n{output}"); + position = next; + } + } + + [Fact] + public void From_skips_earlier_steps() + { + var (exitCode, output, _) = Run(null, "-DryRun", "-SkipCpuCheck", "-From", "dotnet-test"); + + Assert.Equal(0, exitCode); + Assert.Contains("dotnet-test", output); + Assert.Contains("e2e", output); + Assert.Contains("a11y", output); + Assert.DoesNotContain("ui-test", output); + } + + [Fact] + public void Unknown_step_id_fails_fast() + { + string summary = ""; + var (exitCode, output, _) = Run(logDir => summary = File.ReadAllText(Path.Combine(logDir, "summary.txt")), "-SkipCpuCheck", "-Only", "nope"); + + Assert.Equal(2, exitCode); + Assert.Contains("npm-ci", output); + Assert.Contains("nope", summary); + } + + [Fact] + public void Failing_step_stops_the_run_and_writes_summary() + { + var marker = Path.Combine(Path.GetTempPath(), "ts-gate-marker-" + Guid.NewGuid().ToString("N")); + string summary = ""; + var logExists = false; + try + { + var (exitCode, output, _) = Run( + logDir => + { + summary = File.ReadAllText(Path.Combine(logDir, "summary.txt")); + logExists = File.Exists(Path.Combine(logDir, "a.log")); + }, + "-SkipCpuCheck", "-StepsJson", Steps(("a", "exit 0"), ("b", "exit 3"), ("c", $"Set-Content -LiteralPath '{marker}' -Value x"))); + + Assert.Equal(3, exitCode); + Assert.False(File.Exists(marker), "Step c ran after step b failed."); + Assert.Contains("a", summary); + Assert.Contains("b", summary); + Assert.Contains("3", summary); + Assert.True(logExists); + Assert.DoesNotContain("DevHost cleanup", output); // -StepsJson implies -SkipDevHostCleanup: tests never touch real processes + } + finally + { + File.Delete(marker); + } + } + + [Theory] + [InlineData("e2e")] + [InlineData("a11y")] + public void Hung_devhost_step_is_killed_by_the_watchdog(string id) + { + var (exitCode, output, elapsed) = Run(null, "-SkipCpuCheck", "-DevHostStepTimeoutMinutes", "0.05", "-StepsJson", Steps((id, "Start-Sleep 60"))); + + Assert.Equal(124, exitCode); + Assert.Contains("timed out", output); + Assert.True(elapsed < TimeSpan.FromSeconds(30), $"Took {elapsed.TotalSeconds:N0} s."); + } + + [Fact] + public void Require_quiet_fails_when_over_threshold() + { + string summary = ""; + var (exitCode, output, _) = Run(logDir => summary = File.ReadAllText(Path.Combine(logDir, "summary.txt")), "-CpuWarnPercent", "0", "-RequireQuiet", "-DryRun"); + + // Exit 2 is the real assertion; the message depends on whether the machine has the English performance counters. + Assert.Equal(2, exitCode); + Assert.True(output.Contains("% Processor Time", StringComparison.Ordinal) || output.Contains("CPU check unavailable", StringComparison.Ordinal), output); + Assert.False(string.IsNullOrWhiteSpace(summary)); + } + + [Theory] + [InlineData("TomeStack.DevHost.exe", @"C:\dev\ts-w4c\src\DevHost\bin\Release\net10.0\TomeStack.DevHost.exe", "", true)] + [InlineData("TomeStack.DevHost.exe", @"C:\dev\ts-w4c2\src\DevHost\bin\Release\net10.0\TomeStack.DevHost.exe", "", false)] + [InlineData("dotnet.exe", @"C:\Program Files\dotnet\dotnet.exe", @"dotnet C:\dev\ts-w4c\src\DevHost\bin\Release\net10.0\TomeStack.DevHost.dll", true)] + [InlineData("dotnet.exe", @"C:\Program Files\dotnet\dotnet.exe", @"dotnet C:\dev\ts-w4c2\src\DevHost\bin\Release\net10.0\TomeStack.DevHost.dll", false)] + [InlineData("dotnet.exe", @"C:\Program Files\dotnet\dotnet.exe", @"dotnet C:\dev\ts-w4c\src\DevHostTools\TomeStack.DevHost.dll", false)] + [InlineData("node.exe", @"C:\dev\ts-w4c\node.exe", @"node C:\dev\ts-w4c\src\DevHost\TomeStack.DevHost.dll", false)] + public void Devhost_match_is_anchored_on_the_repo_root(string name, string exe, string commandLine, bool expected) + { + var probe = System.Text.Json.JsonSerializer.Serialize(new { name, exe, cmd = commandLine, root = @"C:\dev\ts-w4c" }); + + var (exitCode, output, _) = Run(null, "-SelfTestMatch", probe); + + Assert.Equal(0, exitCode); + Assert.Contains(expected ? "match: True" : "match: False", output); + } +} diff --git a/tests/xunit.runner.json b/tests/xunit.runner.json new file mode 100644 index 00000000..ef9db13f --- /dev/null +++ b/tests/xunit.runner.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://xunit.net/schema/current/xunit.runner.schema.json", + "maxParallelThreads": 8 +}