Files
management-scripts/tests/Get-OfficeDeploymentDiagnostics.Tests.ps1

130 lines
11 KiB
PowerShell

#Requires -Version 5.1
$ErrorActionPreference = 'Stop'
if ($PSVersionTable.PSEdition -ne 'Desktop') { throw 'Run with Windows PowerShell 5.1.' }
$repo = Split-Path -Parent $PSScriptRoot
$testRoot = Join-Path $env:TEMP ('OfficeDiagnosticsTests-' + [guid]::NewGuid().ToString('N'))
$originalTemp = [IO.Path]::GetFullPath($env:TEMP).TrimEnd('\') + '\'
$nativePowerShell = Join-Path $env:windir 'System32\WindowsPowerShell\v1.0\powershell.exe'
$null = New-Item -ItemType Directory -Path $testRoot
$script:assertions = 0
function Assert-DiagnosticTest { param([bool]$Condition, [string]$Message) $script:assertions++; if (!$Condition) { throw $Message } }
function Read-DiagnosticAst {
param([string]$Path)
$tokens=$null; $errors=$null
$ast=[Management.Automation.Language.Parser]::ParseFile($Path,[ref]$tokens,[ref]$errors)
if ($errors.Count) { throw ($errors | Out-String) }
$ast
}
function Read-ZipText {
param($Archive,[string]$Name)
$reader=New-Object IO.StreamReader($Archive.GetEntry($Name).Open())
try { $reader.ReadToEnd() } finally { $reader.Dispose() }
}
$savedEnvironment=@{}
try {
$coreAst=Read-DiagnosticAst (Join-Path $repo 'Get-OfficeDeploymentDiagnostics.ps1')
$shimAst=Read-DiagnosticAst (Join-Path $repo 'rmm\Get-OfficeDeploymentDiagnostics.ps1')
Assert-DiagnosticTest (!$coreAst.ParamBlock -and !$shimAst.ParamBlock) 'RMM scripts must not introduce script parameters.'
$definitions=@($coreAst.FindAll({param($node) $node -is [Management.Automation.Language.FunctionDefinitionAst]},$false))
foreach ($definition in $definitions) { . ([scriptblock]::Create($definition.Extent.Text)) }
Add-Type -AssemblyName System.IO.Compression.FileSystem
$source=Join-Path $testRoot 'source'; $null=New-Item -ItemType Directory -Path "$source\nested\deep" -Force
[IO.File]::WriteAllText("$source\live.log",'fixture with Unicode: caf'+[char]0xE9)
[IO.File]::WriteAllText("$source\install.xml",'<Configuration />')
[IO.File]::WriteAllText("$source\media.dat",'not diagnostics')
[IO.File]::WriteAllText("$source\nested\child.log",'child log')
[IO.File]::WriteAllText("$source\nested\deep\excluded.log",'too deep')
$issues=New-Object 'Collections.Generic.List[string]'
$files=@(Get-OfficeDiagnosticFiles $source @('*.log','install.xml') ([datetime]::UtcNow.AddHours(-1)) 1 $issues)
Assert-DiagnosticTest ($files.Count -eq 3 -and !@($files | Where-Object {$_.Name -in @('media.dat','excluded.log')}).Count) 'Only requested diagnostics within the recursion depth may be collected.'
Assert-DiagnosticTest (@(Get-OfficeDiagnosticFiles $source @('*.log') ([datetime]::UtcNow.AddHours(1)) 1 $issues).Count -eq 0) 'Old files must be excluded by the time window.'
$before=(Get-FileHash -LiteralPath "$source\live.log").Hash
$held=[IO.File]::Open("$source\live.log",[IO.FileMode]::Open,[IO.FileAccess]::ReadWrite,[IO.FileShare]::ReadWrite)
try { New-OfficeDiagnosticArchive "$testRoot\fixture.zip" ($files + $files) @{CurrentStateOnly=$true} $issues }
finally { $held.Dispose() }
$zip=[IO.Compression.ZipFile]::OpenRead("$testRoot\fixture.zip")
try {
$manifest=Read-ZipText $zip 'manifest.json' | ConvertFrom-Json
Assert-DiagnosticTest ($manifest.Count -eq 3 -and @($manifest | Where-Object {$_.Status -notlike 'Captured*'}).Count -eq 0) 'Duplicate paths must be collected once, including a log open by another writer.'
$entry=@($manifest | Where-Object {$_.Source -eq "$source\live.log"})[0]
Assert-DiagnosticTest ((Read-ZipText $zip $entry.Entry) -eq [IO.File]::ReadAllText("$source\live.log")) 'Captured bytes must preserve source encoding/content.'
Assert-DiagnosticTest ($null -ne $zip.GetEntry('endpoint.json') -and $null -ne $zip.GetEntry('collection-issues.json')) 'Metadata and collection omissions must accompany the logs.'
} finally { $zip.Dispose() }
Assert-DiagnosticTest ((Get-FileHash -LiteralPath "$source\live.log").Hash -eq $before) 'Source logs must remain unchanged.'
$big=[IO.File]::Create("$source\oversize.log"); try {$big.SetLength(64MB+1)} finally {$big.Dispose()}
$issues=New-Object 'Collections.Generic.List[string]'
New-OfficeDiagnosticArchive "$testRoot\limits.zip" @((Get-Item "$source\oversize.log")) @{} $issues
Assert-DiagnosticTest ($issues.Count -eq 1 -and $issues[0] -match 'Collection limit') 'Oversize logs must be reported as omitted, not silently lost.'
# Exercise the actual Run-Script helper with mocked live downloads and queries.
# The core's registry reader is replaced only in the fixture downloaded by this test.
$toolsAst=Read-DiagnosticAst (Join-Path $repo 'Tools.ps1')
$runDefinition=$toolsAst.Find({param($node) $node -is [Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -eq 'Run-Script'},$false)
. ([scriptblock]::Create($runDefinition.Extent.Text))
function IsURLValid { param($URL) $true }
function Download-File { param($URL) Assert-DiagnosticTest ($URL -like '*/Get-OfficeDeploymentDiagnostics.ps1') 'Caller must request the diagnostic core.'; "$testRoot\downloaded-core.ps1" }
$fixtureCore=($definitions | Where-Object {$_.Name -ne 'Get-OfficeDiagnosticRegistry'} | ForEach-Object {$_.Extent.Text}) -join "`r`n"
$fixtureCore += "`r`nInvoke-OfficeDiagnosticCollection"
[IO.File]::WriteAllText("$testRoot\downloaded-core.ps1",$fixtureCore)
function New-Object {
param([string]$TypeName,[object[]]$ArgumentList)
if ($TypeName -eq 'Security.Principal.WindowsPrincipal') {
$principal=[pscustomobject]@{}
$principal | Add-Member ScriptMethod IsInRole { $true }
return $principal
}
if ($TypeName -eq 'Net.WebClient') {
$client=[pscustomobject]@{}
$client | Add-Member ScriptMethod DownloadString {param($Url) if ($Url -notlike '*/Get-OfficeDeploymentDiagnostics.ps1') {throw "Unexpected URL $Url"}; [IO.File]::ReadAllText("$testRoot\downloaded-core.ps1")}
return $client
}
Microsoft.PowerShell.Utility\New-Object @PSBoundParameters
}
function Get-OfficeDiagnosticRegistry { [pscustomobject]@{Name='ProductReleaseIds';Value='FixtureOffice'} }
function Get-CimInstance {
param($ClassName,$Filter,$ErrorAction)
switch ($ClassName) {
Win32_OperatingSystem { [pscustomobject]@{Caption='Fixture';LastBootUpTime=[datetime]'2026-10-30T08:00:00'} }
Win32_UserProfile { [pscustomobject]@{SID='S-1-fixture';LocalPath="$testRoot\other-user";Loaded=$false;Special=$false} }
Win32_Process { [pscustomobject]@{Name='powershell.exe';ProcessId=456;SessionId=2;CommandLine='powershell.exe -File C:\Temp\GetHelpElevated\fixture\Run.ps1'} }
Win32_Service { [pscustomobject]@{Name='ClickToRunSvc';State='Running'} }
default { throw "Unexpected CIM query $ClassName" }
}
}
function Invoke-CimMethod { [pscustomobject]@{Domain='Fixture';User='OtherUser';ReturnValue=0} }
function Get-ScheduledTask { @() }
foreach ($name in @('TEMP','LOCALAPPDATA','ProgramData','windir','COMPUTERNAME')) { $savedEnvironment[$name]=[Environment]::GetEnvironmentVariable($name,'Process') }
$env:TEMP="$testRoot\temp"; $env:LOCALAPPDATA="$testRoot\current-user"; $env:ProgramData="$testRoot\programdata"; $env:windir="$testRoot\Windows"; $env:COMPUTERNAME='FIXTURE'
foreach ($directory in @($env:TEMP,"$testRoot\other-user\AppData\Local\DAFs","$env:windir\Temp","$env:windir\SystemTemp\EmberkomOfficeDeployment\run\ODT")) { $null=New-Item -ItemType Directory -Path $directory -Force }
[IO.File]::WriteAllText("$testRoot\other-user\AppData\Local\DAFs\cse.amplify.diagaction.gethelp.officeuninstallalda_fixture.log",'Report from another user')
[IO.File]::WriteAllText("$env:windir\Temp\FIXTURE-20261030-0900.log",'Native install fixture')
[IO.File]::WriteAllText("$env:windir\SystemTemp\EmberkomOfficeDeployment\run\install.xml",'<Configuration />')
[IO.File]::WriteAllText("$env:windir\SystemTemp\EmberkomOfficeDeployment\run\ODT\setup.exe",'Excluded executable fixture')
$result=@(Run-Script -LivePSScript Get-OfficeDeploymentDiagnostics)
$bundle=@(Get-ChildItem -LiteralPath "$env:ProgramData\Emberkom\Logs\OfficeDiagnostics" -Filter '*.zip')
Assert-DiagnosticTest ($bundle.Count -eq 1 -and ($result -join "`n") -match 'Office diagnostic ZIP') 'The real RMM loader must execute the diagnostic core and return its ZIP path.'
$zip=[IO.Compression.ZipFile]::OpenRead($bundle[0].FullName)
try {
$manifest=Read-ZipText $zip 'manifest.json' | ConvertFrom-Json
$report=Read-ZipText $zip 'endpoint.json' | ConvertFrom-Json
Assert-DiagnosticTest (@($manifest | Where-Object {$_.Source -like '*other-user*DAFs*'}).Count -eq 1) 'DAF reports from profiles other than the caller must be captured.'
Assert-DiagnosticTest (@($manifest | Where-Object {$_.Source -like '*FIXTURE-20261030-0900.log'}).Count -eq 1) 'Native logs must be captured.'
Assert-DiagnosticTest (@($manifest | Where-Object {$_.Source -like '*install.xml'}).Count -eq 1 -and !@($manifest | Where-Object {$_.Source -like '*.exe'}).Count) 'Archive configurations but never installation media.'
Assert-DiagnosticTest ($report.Workers[0].Owner -eq 'Fixture\OtherUser' -and $report.Workers[0].SessionId -eq 2) 'Worker ownership and session must be recorded.'
Assert-DiagnosticTest ($report.OfficeRegistry[0].Value -eq 'FixtureOffice') 'Current Office state must be recorded separately from historical logs.'
} finally { $zip.Dispose() }
# Core failures must signal failure to RMM instead of claiming a ZIP was created.
$entry=$coreAst.EndBlock.Statements[-1].Extent.Text
[IO.File]::WriteAllText("$testRoot\failure.ps1", "function Invoke-OfficeDiagnosticCollection { throw 'Fixture collection failure' }`r`n$entry")
$ErrorActionPreference='Continue'
try { & $nativePowerShell -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$testRoot\failure.ps1" *> "$testRoot\failure-output.log" }
finally { $ErrorActionPreference='Stop' }
Assert-DiagnosticTest ($LASTEXITCODE -eq 1) 'A failed diagnostic collection must exit 1.'
Write-Output "PASS: $script:assertions diagnostic assertions. Queries/downloads mocked; no Office changes."
} finally {
foreach ($name in $savedEnvironment.Keys) { [Environment]::SetEnvironmentVariable($name,$savedEnvironment[$name],'Process') }
$resolved=[IO.Path]::GetFullPath($testRoot)
if (!$resolved.StartsWith($originalTemp,[StringComparison]::OrdinalIgnoreCase) -or (Split-Path -Leaf $resolved) -notlike 'OfficeDiagnosticsTests-*') { throw 'Unsafe test cleanup path.' }
Remove-Item -LiteralPath $resolved -Recurse -Force -ErrorAction Stop
}