432 lines
18 KiB
PowerShell
432 lines
18 KiB
PowerShell
# =============================================================================
|
|
# testHelper.ps1 - minimalny framework testowy (asserty, piaskownica, mocki).
|
|
#
|
|
# Celowo bez zewnetrznych zaleznosci: testy maja dzialac na czystym Windows
|
|
# z samym PowerShellem 5.1, tak samo jak reszta projektu.
|
|
#
|
|
# ZASADA NADRZEDNA: zaden test nie dotyka prawdziwej konfiguracji.
|
|
# Skrypty synchronizacyjne dostaja podstawiony USERPROFILE i pisza wylacznie
|
|
# do tests\sandbox. Pilnuje tego bezpiecznik z protectedPaths.ps1.
|
|
# =============================================================================
|
|
|
|
$script:Results = @()
|
|
$script:CurrentTest = ''
|
|
|
|
. "$PSScriptRoot\protectedPaths.ps1"
|
|
$script:ProtectedBefore = Get-ProtectedSnapshot
|
|
|
|
$script:TestsRoot = Split-Path -Parent $PSScriptRoot
|
|
$script:RepoRoot = Split-Path -Parent $script:TestsRoot
|
|
# Piaskownica suite'u. Domyslnie wspolna (tests\sandbox) - tak bylo zawsze.
|
|
# Runner rownolegly (-Parallel) podstawia TIOXYAI_TEST_SANDBOX, zeby kazdy
|
|
# suite pracowal na WLASNYM katalogu: Initialize-Sandbox kasuje cala
|
|
# piaskownice przy starcie, wiec dwa suite'y na jednym katalogu wyrazilby sie
|
|
# wzajem w polowie przebiegu.
|
|
$script:Sandbox = if ($env:TIOXYAI_TEST_SANDBOX) { $env:TIOXYAI_TEST_SANDBOX } else { Join-Path $script:TestsRoot 'sandbox' }
|
|
|
|
# Porty mockow dostaja bloki zajęte przez robotnikow: suite'y uruchamiane
|
|
# rownolegle nie moga trafic na ten sam port (np. dwa mockProxy na 7892).
|
|
# Runner podaje TIOXYAI_PORT_OFFSET, sekwencyjnie go nie ma i porty zostaja
|
|
# produkcyjne-testowe jak wczesniej.
|
|
function Get-TestPort {
|
|
param([Parameter(Mandatory = $true)][int]$Base)
|
|
$offset = 0
|
|
if ($env:TIOXYAI_PORT_OFFSET) { $offset = [int]$env:TIOXYAI_PORT_OFFSET }
|
|
return $Base + $offset
|
|
}
|
|
|
|
# Zmienne, ktore moglyby wyciec z terminala i zmienic zachowanie testowanego
|
|
# skryptu. Kazde uruchomienie dziecka zaczyna od ich wyczyszczenia.
|
|
$script:CleanVars = @(
|
|
'TIOXYAI_SERVER', 'TIOXYAI_KEY', 'SYNC_BASE', 'SYNC_ANYWAY', 'INSTALL_KILO',
|
|
'OPENCODE_CONFIG_DIR', 'KILO_CONFIG_FILE', 'KILO_SCOPE', 'KILO_PROJECT_DIR',
|
|
'KILO_AGENT_DIR', 'REMOTE_LLM_SCAN', 'REMOTE_LLM_NAME',
|
|
'NO_RESTART', 'USERPROFILE', 'HOME',
|
|
'PROXY_PORT', 'VLLM_PORT', 'LLAMACPP_PORT', 'SEARXNG_PORT',
|
|
'STRATA_PORT', 'STRATA_ROOT', 'STRATA_CONTROL', 'TIOXYAI_STOP_STRATA',
|
|
# Srodowiskowe zawory terminala Straty. Wszystkie moga zmienic zachowanie
|
|
# startujacego CLI (inny python, inny katalog configow/danych, klucz, handover),
|
|
# wiec test zaczyna od ich wyczyszczenia - inaczej atrapa terminala dziedziczylaby
|
|
# ustawienia prawdziwej instalacji.
|
|
'STRATA_PYTHON', 'STRATA_INSTALL_DIR', 'STRATA_SETTINGS_FILE',
|
|
'STRATA_COMPONENTS_DIR', 'STRATA_PROFILE_DIR', 'STRATA_ALLOWED_HOSTS',
|
|
'STRATA_API_KEY', 'STRATA_NO_HANDOVER', 'STRATA_HANDOVER',
|
|
'OPENWEBUI_PORT', 'BACKEND_API_KEY', 'OPENWEBUI_API_KEY', 'EMBEDDING_API_KEY',
|
|
'SEARXNG_SECRET', 'WAN_HOST', 'WSL_DISTRO', 'WSL_USER', 'VLLM_WORKSPACE',
|
|
'MODELS_ROOT', 'LLAMACPP_ROOT',
|
|
'ENGINE_ORDER', 'PROVIDER_PREFIX', 'MODEL_LABEL_STYLE',
|
|
'AGENT_MAX_TEMPERATURE', 'OUTPUT_RATIO', 'OUTPUT_CAP', 'OUTPUT_MIN', 'REQUIRE_LOADED'
|
|
)
|
|
|
|
# =============================================================================
|
|
# Asserty
|
|
# =============================================================================
|
|
function Start-Test {
|
|
param([string]$Name)
|
|
$script:CurrentTest = $Name
|
|
Write-Host ''
|
|
Write-Host "### $Name" -ForegroundColor Cyan
|
|
}
|
|
|
|
function Assert-True {
|
|
param([bool]$Condition, [string]$Message)
|
|
$script:Results += [pscustomobject]@{ Test = $script:CurrentTest; Name = $Message; Ok = $Condition }
|
|
if ($Condition) { Write-Host " ZDANY : $Message" -ForegroundColor Green }
|
|
else { Write-Host " BLAD : $Message" -ForegroundColor Red }
|
|
}
|
|
|
|
function Assert-Equal {
|
|
param($Expected, $Actual, [string]$Message)
|
|
$ok = ("$Expected" -eq "$Actual")
|
|
if (-not $ok) { $Message = "$Message [oczekiwano: '$Expected', otrzymano: '$Actual']" }
|
|
Assert-True $ok $Message
|
|
}
|
|
|
|
function Assert-Contains {
|
|
param([string]$Haystack, [string]$Needle, [string]$Message)
|
|
Assert-True ($null -ne $Haystack -and $Haystack.Contains($Needle)) $Message
|
|
}
|
|
|
|
function Assert-NotContains {
|
|
param([string]$Haystack, [string]$Needle, [string]$Message)
|
|
Assert-True ($null -eq $Haystack -or -not $Haystack.Contains($Needle)) $Message
|
|
}
|
|
|
|
function Assert-FileExists {
|
|
param([string]$Path, [string]$Message)
|
|
Assert-True (Test-Path -LiteralPath $Path) $Message
|
|
}
|
|
|
|
function Assert-FileNotExists {
|
|
param([string]$Path, [string]$Message)
|
|
Assert-True (-not (Test-Path -LiteralPath $Path)) $Message
|
|
}
|
|
|
|
# Odczyt sciezki w JSON: "provider.tioxyai-vllm.options.baseURL".
|
|
#
|
|
# Nazwy modeli zawieraja kropki ("Qwen3.8-27B"), wiec sam podzial po kropce
|
|
# nie wystarcza. Klucz z kropka podaje sie w nawiasach kwadratowych:
|
|
# provider.tioxyai-vllm.models[Qwen3.8-27B].limit.context
|
|
function ConvertFrom-Jsonc {
|
|
<#
|
|
JSONC = JSON + komentarze liniowe. Konfiguracja Kilo je zawiera -
|
|
znaczniki blokow modeli lokalnych i zdalnych to komentarze wlasnie,
|
|
a czysty ConvertFrom-Json odmawia ich przeczytania.
|
|
#>
|
|
param([string]$Text)
|
|
$bezKomentarzy = ($Text -split "`r?`n" | Where-Object { $_ -notmatch '^\s*//' }) -join "`n"
|
|
return ($bezKomentarzy | ConvertFrom-Json)
|
|
}
|
|
|
|
function ConvertTo-JsonPathSegments {
|
|
param([string]$PathExpression)
|
|
$segments = @()
|
|
$current = ''
|
|
$inBracket = $false
|
|
foreach ($char in $PathExpression.ToCharArray()) {
|
|
if ($char -eq '[' -and -not $inBracket) {
|
|
if ($current -ne '') { $segments += $current; $current = '' }
|
|
$inBracket = $true
|
|
continue
|
|
}
|
|
if ($char -eq ']' -and $inBracket) {
|
|
$segments += $current
|
|
$current = ''
|
|
$inBracket = $false
|
|
continue
|
|
}
|
|
if ($char -eq '.' -and -not $inBracket) {
|
|
if ($current -ne '') { $segments += $current; $current = '' }
|
|
continue
|
|
}
|
|
$current += $char
|
|
}
|
|
if ($current -ne '') { $segments += $current }
|
|
return $segments
|
|
}
|
|
|
|
function Get-JsonPath {
|
|
param([string]$FilePath, [string]$PathExpression)
|
|
$data = ConvertFrom-Jsonc -Text (Get-Content -LiteralPath $FilePath -Raw)
|
|
$value = $data
|
|
foreach ($segment in (ConvertTo-JsonPathSegments $PathExpression)) {
|
|
if ($null -eq $value) { return $null }
|
|
if ($value -is [System.Collections.IDictionary]) { $value = $value[$segment]; continue }
|
|
if ($value -is [System.Management.Automation.PSCustomObject]) {
|
|
$property = $value.PSObject.Properties[$segment]
|
|
$value = if ($null -ne $property) { $property.Value } else { $null }
|
|
continue
|
|
}
|
|
return $null
|
|
}
|
|
return $value
|
|
}
|
|
|
|
function Assert-JsonPath {
|
|
param([string]$FilePath, [string]$PathExpression, $Expected, [string]$Message)
|
|
try {
|
|
Assert-Equal $Expected (Get-JsonPath -FilePath $FilePath -PathExpression $PathExpression) "$Message [$PathExpression]"
|
|
} catch {
|
|
Assert-True $false "$Message [blad odczytu: $($_.Exception.Message)]"
|
|
}
|
|
}
|
|
|
|
function Assert-ValidJson {
|
|
param([string]$FilePath, [string]$Message)
|
|
try {
|
|
$null = ConvertFrom-Jsonc -Text (Get-Content -LiteralPath $FilePath -Raw)
|
|
Assert-True $true $Message
|
|
} catch {
|
|
Assert-True $false "$Message [$($_.Exception.Message)]"
|
|
}
|
|
}
|
|
|
|
# =============================================================================
|
|
# Uruchamianie testowanych skryptow
|
|
# =============================================================================
|
|
function Invoke-Child {
|
|
<#
|
|
Uruchamia polecenie w CZYSTYM srodowisku: kasuje zmienne z $CleanVars,
|
|
ustawia tylko te podane jawnie. Dzieki temu wynik testu nie zalezy od
|
|
tego, co akurat siedzi w terminalu.
|
|
#>
|
|
param(
|
|
[Parameter(Mandatory = $true)][string]$Command,
|
|
[hashtable]$Environment = @{},
|
|
[string]$StandardInput = $null,
|
|
[int]$TimeoutSec = 180,
|
|
[string]$WorkingDirectory = $null
|
|
)
|
|
|
|
$startInfo = New-Object System.Diagnostics.ProcessStartInfo
|
|
$startInfo.FileName = 'cmd.exe'
|
|
$startInfo.Arguments = "/c $Command"
|
|
$startInfo.UseShellExecute = $false
|
|
$startInfo.RedirectStandardInput = $true
|
|
$startInfo.RedirectStandardOutput = $true
|
|
$startInfo.RedirectStandardError = $true
|
|
$startInfo.StandardOutputEncoding = [System.Text.Encoding]::UTF8
|
|
$startInfo.StandardErrorEncoding = [System.Text.Encoding]::UTF8
|
|
if ($WorkingDirectory) { $startInfo.WorkingDirectory = $WorkingDirectory }
|
|
|
|
foreach ($name in $script:CleanVars) { $startInfo.EnvironmentVariables.Remove($name) | Out-Null }
|
|
foreach ($name in $Environment.Keys) { $startInfo.EnvironmentVariables[$name] = [string]$Environment[$name] }
|
|
|
|
$process = [System.Diagnostics.Process]::Start($startInfo)
|
|
if ($null -ne $StandardInput) { $process.StandardInput.WriteLine($StandardInput) }
|
|
$process.StandardInput.Close()
|
|
|
|
$stdout = $process.StandardOutput.ReadToEnd()
|
|
$stderr = $process.StandardError.ReadToEnd()
|
|
if (-not $process.WaitForExit($TimeoutSec * 1000)) {
|
|
$process.Kill()
|
|
return [pscustomobject]@{ ExitCode = -1; StdOut = $stdout; StdErr = $stderr; All = "$stdout`n$stderr`n[TEST] przekroczony czas" }
|
|
}
|
|
return [pscustomobject]@{
|
|
ExitCode = $process.ExitCode
|
|
StdOut = $stdout
|
|
StdErr = $stderr
|
|
All = "$stdout`n$stderr"
|
|
}
|
|
}
|
|
|
|
# =============================================================================
|
|
# Piaskownica
|
|
# =============================================================================
|
|
function Initialize-Sandbox {
|
|
<#
|
|
Buduje swiezy katalog tests\sandbox:
|
|
home\ podstawiony USERPROFILE dla skryptow klienckich
|
|
bundle\ kopia client\ serwowana przez mock proxy
|
|
work\ katalog startowy dla syncTioxyAi
|
|
host\ kopia repo dla testow skryptow hosta (klucze, .env)
|
|
#>
|
|
$sandbox = $script:Sandbox
|
|
if (Test-Path -LiteralPath $sandbox) { Remove-Item -LiteralPath $sandbox -Recurse -Force }
|
|
New-Item -ItemType Directory -Path $sandbox -Force | Out-Null
|
|
|
|
# UWAGA: NIE tworzymy tu host\client - katalog jest kopiowany w calosci
|
|
# przez testy, a Copy-Item -Recurse do ISTNIEJACEGO katalogu wkladalby go
|
|
# do srodka (client\client\...) zamiast go odtworzyc.
|
|
foreach ($name in @('home', 'work', 'host', 'host\state', 'host\keys')) {
|
|
New-Item -ItemType Directory -Path (Join-Path $sandbox $name) -Force | Out-Null
|
|
}
|
|
|
|
# Kopiujemy ZAWARTOSC (wzorzec \*), a nie sam katalog: Copy-Item z -Recurse
|
|
# potrafi umiescic zrodlo wewnatrz celu zamiast go odtworzyc.
|
|
New-Item -ItemType Directory -Path (Join-Path $sandbox 'bundle\lib') -Force | Out-Null
|
|
Copy-Item -Path (Join-Path $script:RepoRoot 'client\*') `
|
|
-Destination (Join-Path $sandbox 'bundle') -Recurse -Force
|
|
# client\dist to wygenerowany, ostrzyzony pakiet (artefakt publish) - testy
|
|
# pracuja na ZRODLE, wiec go z piaskownicy usuwamy, gdyby lokalnie istnial.
|
|
Remove-Item -LiteralPath (Join-Path $sandbox 'bundle\dist') -Recurse -Force -ErrorAction SilentlyContinue
|
|
|
|
# Manifest pakietu musi zgadzac sie z jego zawartoscia - inaczej test
|
|
# weryfikacji sum kontrolnych sprawdzalby nie to, co trzeba.
|
|
Update-SandboxManifest (Join-Path $sandbox 'bundle')
|
|
|
|
# .env dla testow skryptow hosta - porty inne niz produkcyjne, zeby test
|
|
# nigdy nie trafil w dzialajaca usluge.
|
|
$hostEnv = @(
|
|
'# .env piaskownicy - wylacznie na potrzeby testow',
|
|
'PROXY_PORT=7999',
|
|
'VLLM_PORT=7998',
|
|
'LLAMACPP_PORT=7996',
|
|
# Port Strata inny niz produkcyjny (7103), zeby test nigdy nie trafil
|
|
# w dzialajacy silnik - ani w nasze waskie celowanie po porcie.
|
|
'STRATA_PORT=7995',
|
|
'WAN_HOST=przyklad.test',
|
|
'WSL_DISTRO=Ubuntu',
|
|
'WSL_USER=dawid',
|
|
'PROVIDER_PREFIX=TioxyAi',
|
|
'EMBEDDING_API_KEY=sk-test-embedding'
|
|
)
|
|
Set-Content -LiteralPath (Join-Path $sandbox 'host\.env') -Value $hostEnv -Encoding ASCII
|
|
|
|
Set-Content -LiteralPath (Join-Path $sandbox 'host\keys\accessKeys.json') `
|
|
-Value '{"version":1,"keys":{}}' -Encoding ASCII
|
|
|
|
Write-Host "Piaskownica gotowa: $sandbox" -ForegroundColor DarkGray
|
|
}
|
|
|
|
function Update-SandboxManifest {
|
|
param([string]$BundleDir)
|
|
$lines = @()
|
|
Get-ChildItem -LiteralPath $BundleDir -File -Recurse |
|
|
Where-Object { $_.Name -ne 'MANIFEST.sha256' } |
|
|
Sort-Object FullName |
|
|
ForEach-Object {
|
|
$hash = (Get-FileHash -LiteralPath $_.FullName -Algorithm SHA256).Hash.ToLower()
|
|
$relative = $_.FullName.Substring($BundleDir.Length + 1).Replace('\', '/')
|
|
$lines += ("{0} {1}" -f $hash, $relative)
|
|
}
|
|
[System.IO.File]::WriteAllText((Join-Path $BundleDir 'MANIFEST.sha256'),
|
|
(($lines -join "`n") + "`n"), (New-Object System.Text.UTF8Encoding($false)))
|
|
}
|
|
|
|
function New-SandboxHome {
|
|
<#
|
|
Czysty podstawiony katalog domowy. Skrypty klienckie same tworza w nim
|
|
.config\opencode i .config\kilo.
|
|
#>
|
|
# UWAGA: nie uzywac nazwy $home ani $HOME - to zmienna automatyczna
|
|
# PowerShella (katalog profilu) i tylko do odczytu; przypisanie do niej
|
|
# cicho zawodzi, a test pisalby wtedy do PRAWDZIWEGO katalogu domowego.
|
|
$sandboxHome = Join-Path $script:Sandbox 'home'
|
|
if (Test-Path -LiteralPath $sandboxHome) { Remove-Item -LiteralPath $sandboxHome -Recurse -Force }
|
|
New-Item -ItemType Directory -Path $sandboxHome | Out-Null
|
|
return $sandboxHome
|
|
}
|
|
|
|
# =============================================================================
|
|
# Mocki
|
|
# =============================================================================
|
|
function Start-Mock {
|
|
<#
|
|
Uruchamia mock (mockProxy.py / mockBackend.py) i czeka, az odpowie.
|
|
Zwraca obiekt procesu; zatrzymanie przez Stop-Mock.
|
|
#>
|
|
param(
|
|
[Parameter(Mandatory = $true)][string]$Script,
|
|
[hashtable]$Environment = @{},
|
|
[int]$Port,
|
|
# 40 s zamiast 15: rownolegly runner startuje wiele suite'ow naraz i pod
|
|
# obciazeniem python potrafi wstac pozniej. Szybki start nic nie traci.
|
|
[int]$TimeoutSec = 40
|
|
)
|
|
$startInfo = New-Object System.Diagnostics.ProcessStartInfo
|
|
$startInfo.FileName = 'python'
|
|
$startInfo.Arguments = "`"$Script`""
|
|
$startInfo.UseShellExecute = $false
|
|
$startInfo.RedirectStandardOutput = $true
|
|
$startInfo.RedirectStandardError = $true
|
|
foreach ($name in $Environment.Keys) { $startInfo.EnvironmentVariables[$name] = [string]$Environment[$name] }
|
|
|
|
$process = [System.Diagnostics.Process]::Start($startInfo)
|
|
|
|
# Zapis PID-u mocka do piaskownicy suite'u. Rownolegly runner nie moze
|
|
# sprzatac "po calym drzewie" (Remove-StrayMocks), bo ubilby mocki innych
|
|
# robotnikow - zamiast tego po zakonczeniu robotnika dobija PID-y stadt
|
|
# wylacznie z jego pliku. Zapis natychmiast po starcie: suite, ktory padnie
|
|
# przed swoim blokiem sprzatajacym, nie zostawi osieroconego portu.
|
|
try {
|
|
if (-not (Test-Path -LiteralPath $script:Sandbox)) {
|
|
New-Item -ItemType Directory -Path $script:Sandbox -Force | Out-Null
|
|
}
|
|
Add-Content -LiteralPath (Join-Path $script:Sandbox 'mocks.pid') -Value $process.Id -Encoding ASCII
|
|
} catch { }
|
|
|
|
# Czekamy na gotowosc portu zamiast slepego Start-Sleep - inaczej testy
|
|
# bywaja niestabilne na wolniejszej maszynie.
|
|
if ($Port) {
|
|
$deadline = (Get-Date).AddSeconds($TimeoutSec)
|
|
while ((Get-Date) -lt $deadline) {
|
|
if ($process.HasExited) {
|
|
throw "Mock $Script zakonczyl sie od razu: $($process.StandardError.ReadToEnd())"
|
|
}
|
|
try {
|
|
$tcp = New-Object System.Net.Sockets.TcpClient
|
|
$tcp.Connect('127.0.0.1', $Port)
|
|
$tcp.Close()
|
|
return $process
|
|
} catch {
|
|
Start-Sleep -Milliseconds 200
|
|
}
|
|
}
|
|
throw "Mock $Script nie wstal na porcie $Port w ciagu $TimeoutSec s."
|
|
}
|
|
Start-Sleep -Milliseconds 500
|
|
return $process
|
|
}
|
|
|
|
function Stop-Mock {
|
|
param([System.Diagnostics.Process]$Process)
|
|
if ($null -ne $Process -and -not $Process.HasExited) {
|
|
$Process.Kill()
|
|
$Process.WaitForExit(5000) | Out-Null
|
|
}
|
|
}
|
|
|
|
function New-ClientConfigFile {
|
|
<#
|
|
config.json, ktory skrypty klienckie czytaja obok siebie: klucz i adres.
|
|
#>
|
|
param([string]$Directory, [string]$Key, [string]$Server)
|
|
$payload = '{{"machine_key":"{0}","server":"{1}"}}' -f $Key, $Server
|
|
Set-Content -LiteralPath (Join-Path $Directory 'config.json') -Value $payload -Encoding ASCII
|
|
}
|
|
|
|
# =============================================================================
|
|
# Podsumowanie
|
|
# =============================================================================
|
|
function Get-SuiteSummary {
|
|
param([string]$SuiteName)
|
|
|
|
$violations = Compare-ProtectedSnapshot $script:ProtectedBefore
|
|
if ($violations.Count -gt 0) {
|
|
Write-Host ''
|
|
Write-Host ' BLAD : BEZPIECZNIK - testy zmienily chronione pliki:' -ForegroundColor Red
|
|
foreach ($violation in $violations) { Write-Host " $violation" -ForegroundColor Red }
|
|
$script:Results += [pscustomobject]@{ Test = 'BEZPIECZNIK'; Name = 'chronione pliki nietkniete'; Ok = $false }
|
|
} else {
|
|
Write-Host ''
|
|
Write-Host ' ZDANY : BEZPIECZNIK - chronione pliki nietkniete' -ForegroundColor Green
|
|
$script:Results += [pscustomobject]@{ Test = 'BEZPIECZNIK'; Name = 'chronione pliki nietkniete'; Ok = $true }
|
|
}
|
|
|
|
$total = $script:Results.Count
|
|
$failed = @($script:Results | Where-Object { -not $_.Ok }).Count
|
|
$passed = $total - $failed
|
|
|
|
Write-Host ''
|
|
$color = if ($failed -eq 0) { 'Green' } else { 'Red' }
|
|
Write-Host ("SUITE {0}: {1}/{2} zdanych" -f $SuiteName, $passed, $total) -ForegroundColor $color
|
|
if ($failed -gt 0) {
|
|
Write-Host ' Niezdane:' -ForegroundColor Red
|
|
$script:Results | Where-Object { -not $_.Ok } | ForEach-Object {
|
|
Write-Host (" [{0}] {1}" -f $_.Test, $_.Name) -ForegroundColor Red
|
|
}
|
|
}
|
|
return $failed
|
|
}
|