rimworld-blax-defaults/Tests/run-tests.ps1

223 lines
13 KiB
PowerShell

<#
Runs the in-game test suite. RimWorld 1.7 starts headless (no window, no focus change) with its
own save data folder, so your mod list, saves, settings and defaults file stay untouched. Needs Steam
running and the Harmony mod from the Workshop. Exit code: 0 all passed, 1 failures or errors the mod logged
between tests (MODERR lines, strayModErrors on the SUMMARY line; the Workshop upload refuses those too),
2 the run didn't finish.
.\Tests\run-tests.ps1 Harmony, the installed DLCs, Blax Defaults
.\Tests\run-tests.ps1 -Compat also the installed mods Defaults is tested next to: RimFridge, Weapon Racks,
Replace Stuff, Rimefeller, VFE Security, Vanilla Expanded Framework, Dubs Central
Heating, [DG]More Door Variants, Pick Up And Haul, Haul to Stack, Prison Labor,
Hospitality and Blax Castes
.\Tests\run-tests.ps1 -NoDlc core only, no DLC (DLC tests skip with "needs <DLC>")
.\Tests\run-tests.ps1 -Dlc Royalty,Biotech only these installed DLCs
.\Tests\run-tests.ps1 -NoBuild skip dotnet build
.\Tests\run-tests.ps1 -AllowWhileRunning run next to an open RimWorld (the test game runs at below-normal priority)
.\Tests\run-tests.ps1 -WaitForLock 1800 wait up to 1800 s for another run of this suite instead of failing
A release runs all 8 combinations of Royalty, Ideology and Biotech: -NoDlc, -Dlc with each alone, each pair, and all three.
Mods\BlaxDefaults must be a directory junction to this repo; it is created if missing and left in place.
While the suite runs, the test mod is linked into the game's Mods folder; that link is removed afterwards.
Only one run at a time: a lock file in the data folder holds the running script's process id. The build runs inside
the lock, so parallel callers with -WaitForLock build and run one after another.
Every run starts from default mod settings and an empty defaults library: the Blax Defaults settings file and
Config\BlaxDefaults in the data folder are deleted.
The results go to BlaxDefaultsTestResults.txt in the data folder, and a copy per DLC set next to it:
BlaxDefaultsTestResults.all.txt (every installed DLC), .nodlc.txt, or .dlc-<names>.txt. Runs with -Compat
write .<set>-compat.txt instead (.all-compat.txt, .nodlc-compat.txt, ...). Each copy starts with a
"REPO <path>" line naming the copy of the repo that was tested. The Workshop upload checks the "all" and
"nodlc" copies.
#>
param(
[string]$RimWorldDir = 'E:\SteamLibrary\steamapps\common\RimWorld',
[string]$DataDir = (Join-Path $env:TEMP 'BlaxDefaultsTest'),
[switch]$Compat,
[switch]$NoDlc,
[string[]]$Dlc,
[switch]$NoBuild,
[switch]$AllowWhileRunning,
[int]$WaitForLock = 0,
[int]$TimeoutSeconds = 900
)
$ErrorActionPreference = 'Stop'
# A wrong path (for example a switch passed as a positional value) would put the Mods junction somewhere odd.
if (-not (Test-Path -LiteralPath (Join-Path $RimWorldDir 'Assembly-CSharp.dll'))) { throw "No RimWorld 1.7 install at '$RimWorldDir'." }
$repo = Split-Path -Parent $PSScriptRoot
$testMod = Join-Path $PSScriptRoot 'BlaxDefaultsTests'
$modLink = Join-Path $RimWorldDir 'Mods\BlaxDefaults'
$link = Join-Path $RimWorldDir 'Mods\BlaxDefaultsTests'
$workshop = Join-Path $RimWorldDir '..\..\workshop\content\294100'
$lockFile = Join-Path $DataDir 'run.lock'
if ((Get-Process -Name RimWorld -ErrorAction SilentlyContinue) -and -not $AllowWhileRunning) {
throw 'RimWorld is running. Close it first, or pass -AllowWhileRunning.'
}
function Get-FullPath([string]$path) { [IO.Path]::GetFullPath($path).TrimEnd('\') }
# One run at a time. A lock whose process is gone is stale and taken over.
New-Item -ItemType Directory -Force $DataDir | Out-Null
function Enter-Lock {
$waited = [Diagnostics.Stopwatch]::StartNew()
for ($try = 0; $try -lt 2; $try++) {
try {
$stream = [IO.File]::Open($lockFile, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::Read)
$bytes = [Text.Encoding]::ASCII.GetBytes([string]$PID)
$stream.Write($bytes, 0, $bytes.Length)
$stream.Close()
return
}
catch [IO.IOException] {
$owner = (Get-Content -LiteralPath $lockFile -Raw -ErrorAction SilentlyContinue)
$ownerPid = 0
if ($owner -and [int]::TryParse($owner.Trim(), [ref]$ownerPid) -and $ownerPid -ne $PID -and (Get-Process -Id $ownerPid -ErrorAction SilentlyContinue)) {
if ($waited.Elapsed.TotalSeconds -lt $WaitForLock) {
Start-Sleep -Seconds 5
$try = -1
continue
}
throw "Another test run (process $ownerPid) is in progress. Lock: $lockFile"
}
Write-Warning "removing stale lock from process $owner"
Remove-Item -LiteralPath $lockFile -Force -ErrorAction SilentlyContinue
}
}
throw "Could not take the lock $lockFile"
}
Enter-Lock
try {
# Mods\BlaxDefaults: a junction to this repo. Created if missing, never replaced.
if (Test-Path -LiteralPath $modLink) {
$item = Get-Item -LiteralPath $modLink -Force
if (-not ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
throw "$modLink is a real folder, not a junction to $repo. Move it away and run again."
}
$target = @($item.Target)[0]
if (-not $target -or (Get-FullPath $target) -ne (Get-FullPath $repo)) {
throw "$modLink points to '$target', not to $repo."
}
}
else {
New-Item -ItemType Junction -Path $modLink -Target $repo | Out-Null
Write-Host "Created junction $modLink -> $repo"
}
if (-not $NoBuild) {
foreach ($proj in (Join-Path $repo 'Source\BlaxDefaults\BlaxDefaults.csproj'), (Join-Path $testMod 'Source\BlaxDefaultsTests.csproj')) {
& dotnet build $proj -c Release -nologo -v q "-p:RimWorldDir=$RimWorldDir"
if ($LASTEXITCODE -ne 0) { throw "build failed: $proj" }
}
}
# packageId (lower case) -> About.xml, for every installed local and Workshop mod
$installed = @{}
foreach ($about in @(Get-ChildItem (Join-Path $RimWorldDir 'Mods\*\About\About.xml') -ErrorAction SilentlyContinue) +
@(Get-ChildItem (Join-Path $workshop '*\About\About.xml') -ErrorAction SilentlyContinue)) {
$x = [xml](Get-Content -LiteralPath $about.FullName -Raw -Encoding UTF8)
if ($x.ModMetaData.packageId) { $installed[$x.ModMetaData.packageId.Trim().ToLower()] = $x }
}
function Add-WithDependencies([string]$id, [System.Collections.ArrayList]$list) {
$id = $id.ToLower()
if ($list -contains $id -or $id -like 'ludeon.*') { return }
$x = $installed[$id]
if (-not $x) { Write-Warning "not installed, skipped: $id"; return }
foreach ($dep in @($x.ModMetaData.modDependencies.li)) { if ($dep.packageId) { Add-WithDependencies $dep.packageId $list } }
[void]$list.Add($id)
}
# Load order: Harmony, core, DLCs, the mods Defaults is tested next to (Blax Castes among them), Blax Defaults, the tests.
# Every installed DLC is listed as known, so the game does not switch on a left-out DLC as "new".
$installedDlcs = @(@('Royalty', 'Ideology', 'Biotech', 'Anomaly', 'Odyssey') | Where-Object { Test-Path (Join-Path $RimWorldDir "Data\$_") })
if ($NoDlc) { $loadDlcs = @() }
elseif ($Dlc) {
$wanted = @($Dlc | ForEach-Object { $_ -split ',' } | ForEach-Object { $_.Trim() } | Where-Object { $_ })
foreach ($w in $wanted) { if ($installedDlcs -notcontains $w) { Write-Warning "DLC not installed or unknown, skipped: $w" } }
$loadDlcs = @($installedDlcs | Where-Object { $wanted -contains $_ })
}
else { $loadDlcs = @($installedDlcs) }
$mods = New-Object System.Collections.ArrayList
$expansions = @($installedDlcs | ForEach-Object { 'ludeon.rimworld.' + $_.ToLower() })
[void]$mods.Add('brrainz.harmony')
[void]$mods.Add('ludeon.rimworld')
foreach ($d in $loadDlcs) { [void]$mods.Add('ludeon.rimworld.' + $d.ToLower()) }
Write-Host ("DLCs: " + $(if ($loadDlcs.Count) { $loadDlcs -join ', ' } else { 'none' }))
# Name of this DLC set for the per-set copy of the results.
$dlcSet = if ($loadDlcs.Count -eq 0) { 'nodlc' } elseif ($loadDlcs.Count -eq $installedDlcs.Count) { 'all' } else { 'dlc-' + ($loadDlcs -join '-').ToLower() }
# Other mods change what runs and what skips, so their runs never stand in for the plain ones.
if ($Compat) { $dlcSet += '-compat' }
$setResults = Join-Path $DataDir "BlaxDefaultsTestResults.$dlcSet.txt"
if ($Compat) {
# Package ids read from the installed copies' About/About.xml (2026-11-29). Blax Zones joins once it has code.
foreach ($id in 'OskarPotocki.VanillaFactionsExpanded.Core', 'rimfridge.kv.rw', 'Aelanna.WeaponRacks', 'Memegoddess.ReplaceStuff',
'Dubwise.Rimefeller', 'VanillaExpanded.VFESecurity', 'Dubwise.DubsCentralHeating', 'local.moredoorvariants',
'Mehni.PickUpAndHaul', 'jkluch.HaulToStack', 'avius.prisonlabor', 'Orion.Hospitality', 'blax.castes') {
Add-WithDependencies $id $mods
}
}
[void]$mods.Add('blax.defaults')
[void]$mods.Add('blax.defaults.tests')
# fresh test data folder: mod list only, no old save, results, mod settings (files are named Mod_<folder>_<class>.xml)
# or defaults file (Config\BlaxDefaults, only ever this data folder's own)
New-Item -ItemType Directory -Force (Join-Path $DataDir 'Config') | Out-Null
Remove-Item -Force -ErrorAction SilentlyContinue (Join-Path $DataDir 'Saves\BlaxDefaultsTest.rws'), (Join-Path $DataDir 'BlaxDefaultsTestResults.txt'), $setResults
Get-ChildItem -LiteralPath (Join-Path $DataDir 'Config') -Filter 'Mod_*.xml' -ErrorAction SilentlyContinue |
Where-Object { $_.Name -like 'Mod_BlaxDefaults_*' -or $_.Name -like 'Mod_blax.defaults_*' -or $_.Name -like 'Mod_BlaxCastes_*' } |
Remove-Item -Force -ErrorAction SilentlyContinue
# The defaults file and its .bak, .tmp and broken copies: files only, never recursive, never through a link.
$libraryDir = Join-Path $DataDir 'Config\BlaxDefaults'
if (Test-Path -LiteralPath $libraryDir) {
if ((Get-Item -LiteralPath $libraryDir -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) {
throw "$libraryDir is a link. Remove it with cmd /c rmdir and run again."
}
Get-ChildItem -LiteralPath $libraryDir -File -Force | Remove-Item -Force
}
$li = { param($ids) ($ids | ForEach-Object { " <li>$_</li>" }) -join "`n" }
$modsConfig = "<?xml version=`"1.0`" encoding=`"utf-8`"?>`n<ModsConfigData>`n <version>1.7</version>`n <activeMods>`n" +
(& $li $mods) + "`n </activeMods>`n <knownExpansions>`n" + (& $li $expansions) + "`n </knownExpansions>`n</ModsConfigData>`n"
[IO.File]::WriteAllText((Join-Path $DataDir 'Config\ModsConfig.xml'), $modsConfig)
Write-Host ("Mods: " + ($mods -join ', '))
$createdLink = $false
try {
if (-not (Test-Path $link)) {
New-Item -ItemType Junction -Path $link -Target $testMod | Out-Null
$createdLink = $true
}
$gameArgs = "-headless -quicktest -blaxdefaultstests -NoFileLog -NoCrashDialog `"-savedatafolder=$DataDir`""
$sw = [Diagnostics.Stopwatch]::StartNew()
$p = Start-Process -FilePath (Join-Path $RimWorldDir 'RimWorld.exe') -WorkingDirectory $RimWorldDir -ArgumentList $gameArgs `
-RedirectStandardOutput (Join-Path $DataDir 'game.log') -RedirectStandardError (Join-Path $DataDir 'game.err.log') `
-WindowStyle Hidden -PassThru
if ($AllowWhileRunning) {
try { $p.PriorityClass = [Diagnostics.ProcessPriorityClass]::BelowNormal } catch { Write-Warning "could not lower the test game's priority: $_" }
}
if (-not $p.WaitForExit($TimeoutSeconds * 1000)) {
$p.Kill()
Write-Warning "timed out after $TimeoutSeconds s, test game (process $($p.Id)) killed"
}
Write-Host ("Game ran {0:N0} s. Log: {1}" -f $sw.Elapsed.TotalSeconds, (Join-Path $DataDir 'game.log'))
}
finally {
if ($createdLink -and (Test-Path $link)) { cmd /c rmdir "$link" | Out-Null }
}
}
finally {
Remove-Item -LiteralPath $lockFile -Force -ErrorAction SilentlyContinue
}
$results = Join-Path $DataDir 'BlaxDefaultsTestResults.txt'
if (-not (Test-Path $results)) { Write-Host 'No results file: the suite never started. See game.log.'; exit 2 }
# The per-set copy names the tested copy of the repo, so the Workshop upload never takes another copy's run.
[IO.File]::WriteAllLines($setResults, [string[]](@("REPO $repo") + @(Get-Content -LiteralPath $results -Encoding UTF8)), (New-Object Text.UTF8Encoding $false))
$lines = Get-Content -LiteralPath $results -Encoding UTF8
$lines | ForEach-Object { Write-Host $_ }
if (-not ($lines -match '^END$')) { Write-Host 'The run did not finish.'; exit 2 }
if ($lines -match '^FAIL ') { exit 1 }
# Errors logged between tests (a reload, a hook running while the game settles) fail no single test.
$summary = @($lines -match '^SUMMARY ') | Select-Object -Last 1
if ($summary -match '\bstrayModErrors=([1-9]\d*)') { Write-Host "Blax Defaults logged $($Matches[1]) error(s) between tests (MODERR lines)."; exit 1 }
exit 0