# Offline only: load function definitions via AST; never execute either script's entry point.
$ErrorActionPreference='Stop'
if($PSVersionTable.PSEdition-ne'Desktop'-or$PSVersionTable.PSVersion.Major-ne5-or$PSVersionTable.PSVersion.Minor-ne1){throw'Run these checks with Windows PowerShell 5.1 (powershell.exe).'}
Assert-OfficeTest($output.Count-eq0-and$script:diskQueries.Count-eq1)'A shared staging/install volume must combine reserves once without leaking log messages.'
$script:freeBytes['C:']=16GB-1
Assert-OfficeThrows{&$diskSpaceCheck-Workspace'C:\Temp\Office'-InstallPaths@('C:\Windows')-DownloadingMedia}'Insufficient disk space.*before downloading media.*16 GB.*Existing apps have not been removed'
Assert-OfficeTest($result.Version-eq'ready'-and$script:probeCalls-eq3-and$script:testSleeps.Count-eq2)'Delayed registration must return the verified value without leaking log text.'
Assert-OfficeTest($null-eq$result-and$script:probeCalls-eq(Get-OfficeDeploymentDefinitions).RegistrationCheckAttempts-and$script:testSleeps.Count-eq($script:probeCalls-1))'Registration waits must stop at the configured bound.'
Assert-OfficeTest($code-eq$expectedCode-and$script:processCalls-eq$expectedCalls-and$script:testSleeps.Count-eq($expectedCalls-1))"Incorrect retry behavior for $mode."
Assert-OfficeTest(@($script:processLogs|Select-Object-Unique).Count-eq$expectedCalls)'MSI retry output logs must not overwrite earlier attempts.'
Assert-OfficeTest($output.Count-eq1-and$output[0]-eq17004-and$script:diagnosticCalls-eq1)'ODT native diagnostic collection must retain the original exit code and not pollute output, even when collection fails.'
$old=Join-Path$nativeRoot'Office-old.log';[IO.File]::WriteAllText($old,'Error Old unrelated failure');[IO.File]::SetLastWriteTimeUtc($old,$since.AddHours(-1))
Assert-OfficeTest($output.Count-eq0)'Native diagnostics must write through Tools logging without leaking return values.'
$log=Get-Content-LiteralPath$Global:LogFile-Raw
Assert-OfficeTest($log-match'Synthetic setup reason'-and$log.Contains($recent))'The management log must include the native filename and actual error detail.'
Assert-OfficeTest(([regex]::Matches($log,'Native Office detail:.*Synthetic setup reason')).Count-eq1)'Duplicate search roots must not duplicate diagnostics.'
Assert-OfficeTest($log-notmatch'Old unrelated failure|Unrelated app failure|Nested unrelated failure|Office-empty.log')'Diagnostics must exclude old, unrelated, empty, and nested logs.'
Assert-OfficeTest((Get-Content-LiteralPath$recent-Raw)-match'Normal setup entry')'Collecting native diagnostics must not modify the original log.'
Assert-OfficeTest((Get-Content-LiteralPath$Global:LogFile-Raw)-match'No recent nonempty native Office logs found')'Missing native logs must be reported without inventing a diagnosis.'
Assert-OfficeTest(@(Write-OfficeSetupDiagnostics-SinceUtc$since-SearchRoots@($nativeRoot)).Count-eq0)'A locked native log must not throw or alter the installer result.'
Assert-OfficeTest($output.Count-eq0)'A recovered download must not emit success-stream diagnostics or Syncro errors.'
$log=Get-Content-LiteralPath$Global:LogFile-Raw
Assert-OfficeTest($log-match'Download attempt 1 of 3 failed for https://fixture.invalid/'-and$log-match'Temporary network failure Retrying in 3 seconds'-and$log-match'Download recovered on attempt 2: https://fixture.invalid/')'Retry details and recovery must remain in the Tools diagnostic log.'
Assert-OfficeTest(!$script:appxPresent-and$script:appxCalls-eq$expectedCalls-and$output.Count-eq0)"Appx removal did not recover cleanly: $script:appxMode, provisioned=$provisioned."
Assert-OfficeTest($running.Count-eq3-and'msteams'-in$running.ProcessName-and'unrelated'-notin$running.ProcessName)'Running-app detection must include personal Teams without broad process matching.'
Assert-OfficeThrows{Stop-OfficeDeploymentApps([pscustomobject]@{OfficeAppShutdown='Abort'})}'Apps are running:.*msteams'
Assert-OfficeTest($script:stoppedTeams.Count-eq0)'Abort must not close any Teams client.'
Assert-OfficeTest($script:stoppedTeams.Count-eq3-and'msteams'-in$script:stoppedTeams)'Force must close the older personal Teams client along with classic/current Teams.'
$options=Get-OfficeDeploymentOptions@{OfficeSubscription='Microsoft 365 Business Premium';ValidateBeforeChanges=$value}
Assert-OfficeTest($options.ValidateBeforeChanges-is[bool]-and!$options.ValidateBeforeChanges)"Explicit opt-out '$value' was ignored."
}
Assert-OfficeTest((Get-OfficeDeploymentOptions@{OfficeSubscription='Microsoft 365 Business Premium'}).ValidateBeforeChanges)'Missing validation input enabled changes.'
Assert-OfficeThrows{Get-OfficeDeploymentOptions@{OfficeSubscription='Microsoft 365 Business Premium';ValidateBeforeChanges='maybe'}}'Invalid \$ValidateBeforeChanges'
$expected=@{
'Microsoft 365 Business Standard'='O365BusinessRetail'
'Microsoft 365 Business Premium'='O365BusinessRetail'
'Microsoft 365 Apps for business'='O365BusinessEEANoTeamsRetail'
'Microsoft 365 Apps for enterprise'='O365ProPlusEEANoTeamsRetail'
'Microsoft/Office 365 E3/E5'='O365ProPlusRetail'
'Microsoft 365 E3'='O365ProPlusRetail'
'Microsoft 365 E5'='O365ProPlusRetail'
'Office 365 E3'='O365ProPlusRetail'
'Office 365 E5'='O365ProPlusRetail'
}
foreach($planin@('Microsoft/Office 365 E3/E5','Microsoft/Office 365 E3/E5 (no Teams)')){
Assert-OfficeThrows{Get-OfficeDeploymentOptions@{OfficeSubscription='Microsoft 365 Business Standard';OfficeActivation='SharedComputer'}}'requires Business Premium'
Assert-OfficeThrows{Get-OfficeDeploymentOptions@{OfficeSubscription='Microsoft 365 Apps for business';OfficeActivation='SharedComputer'}}'requires Business Premium'
foreach($planin@('Microsoft 365 Business Premium','Microsoft 365 Business Premium (no Teams)','Microsoft 365 Apps for enterprise')){
$options=Get-OfficeDeploymentOptions@{OfficeSubscription='Microsoft 365 Business Premium';DeferReboot=$value}
Assert-OfficeTest($options.DeferReboot-is[bool]-and$options.DeferReboot)'Missing/blank or true restart input must produce Boolean true.'
}
foreach($valuein@('false','$false',$false,'0',' No ')){
$options=Get-OfficeDeploymentOptions@{OfficeSubscription='Microsoft 365 Business Premium';DeferReboot=$value}
Assert-OfficeTest($options.DeferReboot-is[bool]-and!$options.DeferReboot)'False restart text must be parsed, not cast to a truthy string.'
}
Assert-OfficeTest((Get-OfficeDeploymentOptions@{OfficeSubscription='Microsoft 365 Business Premium'}).DeferReboot)'Omitted restart input must default to true.'
$options=Get-OfficeDeploymentOptions@{OfficeSubscription='Microsoft 365 Business Premium';OfficeArchitecture='32';COMPANY='A & B <Company> "quoted"';OfficeActivation='SharedComputer';OfficeAppShutdown='Force'}
Assert-OfficeTest($null-ne$roundTrip.SelectSingleNode('/Configuration/RemoveMSI')-and$null-ne$roundTrip.SelectSingleNode('/Configuration/Add'))'Legacy MSI removal must run with the replacement installation.'
Assert-OfficeTest(!$latestXml.Configuration.Add.HasAttribute('Version'))'Ordinary deployments must let ODT select the latest version.'
Assert-OfficeTest(!$roundTrip.Configuration.Updates.HasAttribute('TargetVersion')-and$roundTrip.Configuration.Updates.Enabled-eq'TRUE')'Installation selection must not freeze future Office updates.'
Assert-OfficeTest((Get-OfficeFeatureRelease-Build19045-ProductType1)-eq'2608')'Windows 10 must select feature release 2608.'
Assert-OfficeTest((Get-OfficeFeatureRelease-Build22631-ProductType1)-eq'')'Windows 11 must remain unpinned.'
Assert-OfficeTest((Get-OfficeFeatureRelease-Build20348-ProductType3)-eq'')'Windows Server must not be mistaken for Windows 10.'
Assert-OfficeTest((Get-OfficeBuildFromHistory$numericHistoryCurrent'2608')-eq'16.0.20326.10')'Build sorting must be numeric and tolerate HTML formatting.'
Assert-OfficeThrows{Get-OfficeBuildFromHistory'<html>Changed Microsoft page</html>'Current'2608'}'did not identify.*Existing Office has not been removed'
foreach($appin@('OneDrive','Groove','Teams','OutlookForWindows')){Assert-OfficeTest($app-in$roundTrip.Configuration.Add.Product.ExcludeApp.ID)"ODT must leave $app to the explicit companion installation stage."}
Assert-OfficeTest($removal.Configuration.Remove.All-eq'TRUE'-and$removal.Configuration.Display.Level-eq'None'-and$removal.Configuration.Display.AcceptEULA-eq'TRUE')'ODT removal must remove all Click-to-Run products without UI.'
Assert-OfficeTest($removal.SelectSingleNode('//Property[@Name="FORCEAPPSHUTDOWN"]').Value-eq$(if($shutdown-eq'Force'){'TRUE'}else{'FALSE'}))'Silent removal must honor the app shutdown selection.'
Assert-OfficeTest($null-eq$removal.SelectSingleNode('/Configuration/Add')-and$null-eq$removal.SelectSingleNode('/Configuration/RemoveMSI'))'The separate removal pass must not install Office or depend on standalone RemoveMSI.'
}
# Exercise media staging under the Tools.ps1 command scope, including literal paths.
# Network requests, Microsoft signatures, and executable launches are mocked; files are inert.
&{
$archiveCommand=Get-CommandExpand-Archive
Assert-OfficeTest($archiveCommand.CommandType-eq'Function'-and!$archiveCommand.Parameters.ContainsKey('LiteralPath'))'The real Tools archive override must be present for this regression.'
Assert-OfficeTest($TimeoutSeconds-eq(Get-OfficeDeploymentDefinitions).OdtPageTimeoutSeconds)'ODT page must use the retried downloader with its configured timeout.'
Assert-OfficeTest($downloadXml.Configuration.Add.GetAttribute('Version')-eq$options.TargetOfficeVersion)'The OS-specific build must be selected before downloading.'
Assert-OfficeTest($media.Version-eq'16.0.12345.67890'-and$media.Companions.Count-eq3-and!$media.Companions.ContainsKey('Teams'))'Media staging lost its build or no-Teams selection.'
Assert-OfficeTest(!([xml](Get-Content-LiteralPath$media.Config-Raw)).Configuration.Add.HasAttribute('Version'))'Staging must not pin ordinary installations to the downloaded build.'
Assert-OfficeTest(($script:mediaProcesses-join',')-eq'odt.exe,setup.exe,setup.exe')'Staging must only extract ODT and download Office, with no removal or installation.'
Assert-OfficeTest($removal.Configuration.Remove.All-eq'TRUE'-and$removal.Configuration.Display.Level-eq'None')'Staging must save the silent removal configuration.'
Assert-OfficeTest(!$media.Scrubber-and!($script:mediaSignatures-match'GetHelp|SaRA'))'Unattended deployments must not stage an interactive scrubber.'
Assert-OfficeTest($media.Version-eq'16.0.20326.20158'-and$options.TargetOfficeVersion-eq$media.Version)'Windows 10 must stage its compatible build.'
Assert-OfficeTest(([xml](Get-Content-LiteralPath$media.Config-Raw)).Configuration.Add.Version-eq$media.Version)'Windows 10 installation must retain the compatible target.'
$options=Get-OfficeDeploymentOptions@{OfficeSubscription='Microsoft 365 Business Standard';OfficeArchitecture='64'}
$script:mediaProcesses=@()
functionAssert-OfficeDiskSpace{param($Workspace,[switch]$DownloadingMedia)Assert-OfficeTest$DownloadingMedia.IsPresent'A fresh download must include staging space.';throw'Synthetic insufficient download space'}
Assert-OfficeTest(!$script:mediaProcesses.Count-and!(Test-Path-LiteralPath(Join-Path$mediaWorkspace'odt.exe')))'Low space must stop before downloading or launching ODT.'
Assert-OfficeTest($media.Count-eq4-and$script:staged.Count-eq4-and($script:staged-join',')-eq($script:verified-join','))'Every companion installer must be staged and signed before removal.'
foreach($planin@('Microsoft 365 Business Standard (no Teams)','Microsoft 365 Business Premium (no Teams)','Microsoft/Office 365 E3/E5 (no Teams)','Microsoft 365 Apps for business','Microsoft 365 Apps for enterprise','Office 365 E3 (no Teams)')){
Assert-OfficeTest($null-eq$failure-and$result.ExitCode-eq$expectedCode)"Unexpected companion result for $script:appMode : $failure"
Assert-OfficeTest($result.Versions.OneDrive-eq'26.1.2.3'-and$result.Versions.Teams-eq'1.0.0.0'-and$result.Versions.NewOutlook-eq'1.0.0.0')'Companion verification receipt is incomplete.'
Assert-OfficeTest(($script:appCalls-join'|')-eq'WebView2 /silent /install|OneDrive /allusers /silent|Teams -p|NewOutlook --provision true --quiet --start-')'Companion installers must run silently and for all users.'
}else{
Assert-OfficeTest($null-ne$failure)"Companion failure was swallowed: $script:appMode"
if($script:appMode-eq'personal-Teams-only'){Assert-OfficeTest($failure.Exception.Message-match'Teams setup returned success but the app was not provisioned')'Legacy personal MicrosoftTeams must not satisfy MSTeams verification.'}
Assert-OfficeTest(!($script:appCalls-match'^WebView2 '))'Existing machine WebView2 runtime was unnecessarily installed.'
foreach($planin@('Microsoft 365 Business Standard (no Teams)','Microsoft 365 Business Premium (no Teams)','Microsoft/Office 365 E3/E5 (no Teams)','Microsoft 365 Apps for business','Microsoft 365 Apps for enterprise','Office 365 E5 (no Teams)')){
Add-Type-TypeDefinition'using System; public static class OfficeArgumentProbe { public static int Main(string[] args) { Console.Write(String.Join("|", args)); return 0; } }'-OutputAssembly$argumentProbe-OutputTypeConsoleApplication
Assert-OfficeTest($inventory.Count-eq2-and$inventory[0].WindowsInstaller-eq1)'Office inventory must preserve the MSI marker and exclude the Teams add-in.'
Assert-OfficeTest($FilePath-eq$media.Setup-and$Arguments-eq('/configure "'+$media.RemovalConfig+'"'))'Removal must run only ODT with the staged removal configuration.'
Assert-OfficeTest((Split-Path-Leaf$LogPrefix)-eq'office-remove')'Removal must retain diagnostic process logs.'
Assert-OfficeThrows{Remove-OfficeSuite$media$testRoot}'Office remains.*Office Home and Business 2021.*manual scrub'
Assert-OfficeTest($script:removalChecks-eq((Get-OfficeDeploymentDefinitions).RegistrationCheckAttempts+2))'Remaining Click-to-Run products must be checked for the bounded registration interval.'
}elseif($script:removalMode-eq'read-error'){
Assert-OfficeThrows{Remove-OfficeSuite$media$testRoot}'Office inventory is unreadable'
Assert-OfficeTest($result.Count-eq1-and$result[0]-eq$expected)'Removal must return just its exit code; MSI products are deferred to installation.'
if($script:removalMode-eq'delayed'){Assert-OfficeTest($script:removalChecks-eq4)'Removal must tolerate registry propagation delays.'}
if($script:removalMode-eq'reboot'){Assert-OfficeTest($script:removalChecks-eq1)'A required restart must be surfaced before demanding registration cleanup.'}
Assert-OfficeTest($script:removalCalls-eq$expectedCalls)'Remove orphaned Click-to-Run state even without registered products, without rerunning failed removal or launching a fallback scrubber.'
if(!$behavior){Assert-OfficeTest($script:restartChecks-eq0)'DeferReboot=false must return immediately after a restart request.'}
elseif($script:restartMode-eq'remaining'){Assert-OfficeTest($script:restartChecks-eq((Get-OfficeDeploymentDefinitions).RegistrationCheckAttempts+1))'Deferral must wait for removal registration, with a bounded deadline.'}
elseif($script:restartMode-eq'delayed'){Assert-OfficeTest($script:restartChecks-eq3)'Deferral must tolerate delayed removal registration.'}
Assert-OfficeTest(Test-OfficeCanDeferRestart([pscustomobject]@{DeferReboot=$true})'Office')'Deferred MSI removal must not block Click-to-Run restart deferral.'
Assert-OfficeTest($helperAst.Extent.Text.Contains((Get-OfficeDeploymentDefinitions).HelperVersion))'The staged helper version contract must match the checked-in helper.'
# HKLM can contain a per-user Teams add-in registration. Never run its MSI as SYSTEM.
&{
$addin=[pscustomobject]@{DisplayName='Microsoft Teams Meeting Add-in for Microsoft Office';DisplayVersion='1.26.25904';PSChildName='{11111111-2222-3333-4444-555555555555}';PSPath='Registry::HKEY_LOCAL_MACHINE\Software\Fixture\Addin'}
Assert-OfficeThrows{Remove-OfficeCompanionApps$testRoot}'registrations remain.*Microsoft Teams Meeting Add-in.*1\.26\.25904.*Fixture'
}elseif($mode-eq'failure'){
Assert-OfficeThrows{Remove-OfficeCompanionApps$testRoot}'Could not remove.*1603'
}else{
$reboot=Remove-OfficeCompanionApps$testRoot
Assert-OfficeTest($reboot-eq($mode-eq'reboot'))"Incorrect reboot result for machine MSI mode $mode."
}
Assert-OfficeTest($script:removalCalls.Count-eq1-and$script:removalCalls[0]-like('/x '+$addin.PSChildName+' /qn /norestart*'))'A real machine add-in must still be uninstalled silently.'
$mine=[pscustomobject]@{DisplayName='Microsoft Teams Meeting Add-in for Microsoft Office';Publisher='Microsoft';DisplayVersion='1.26.25904';PSChildName='{11111111-2222-3333-4444-555555555555}'}
Assert-OfficeTest($found.Count-eq1-and$found[0].PSChildName-eq$mine.PSChildName)'User cleanup must discover its HKLM-advertised add-in, deduplicate registry views, and exclude other contexts.'
functionTest-OfficeUserMsiProduct{$false}
Assert-OfficeTest(@(Get-OfficeUserTeamsAddinEntries).Count-eq0)'User cleanup must not claim products registered only for another user or machine.'
Assert-OfficeTest($script:userMsiStarts-eq3-and$script:userMsiChecks-eq3)'User MSI cleanup must recover from busy MSI and delayed registration removal.'
Assert-OfficeTest((Install-OfficeMedia$options$media$testRoot)-eq0-and$media.Version-eq'16.0.2.3')'A newer unpinned build must pass and report the actual installed version.'
$options.TargetOfficeVersion='16.0.1.2'
Assert-OfficeThrows{Install-OfficeMedia$options$media$testRoot}'did not match'
$script:installed.VersionToReport='16.0.1.2'
Assert-OfficeTest((Install-OfficeMedia$options$media$testRoot)-eq0-and$media.Version-eq'16.0.1.2')'Windows 10 must verify its explicitly selected build.'
$options.TargetOfficeVersion=''
$script:installed.VersionToReport='invalid'
Assert-OfficeThrows{Install-OfficeMedia$options$media$testRoot}'did not match'
Assert-OfficeThrows{Install-OfficeMedia$options$media$testRoot}'MSI Office remains.*Office Professional Plus 2016.*new suite may already be installed.*manual scrub'
Assert-OfficeTest($script:msiChecks-eq((Get-OfficeDeploymentDefinitions).RegistrationCheckAttempts+2))'MSI removal must be verified with a bounded wait.'
functionNew-ScheduledTaskAction{param($Execute,$Argument)Assert-OfficeTest($Execute-like'*\WindowsPowerShell\v1.0\powershell.exe')'User cleanup must use Windows PowerShell 5.1.';[pscustomobject]@{Execute=$Execute;Arguments=$Argument}}
functionNew-ScheduledTaskPrincipal{param($UserId,$LogonType,$RunLevel)Assert-OfficeTest($LogonType-eq'Interactive'-and$RunLevel-eq'Limited')'User task must run limited and interactively.';$UserId}
Assert-OfficeTest($script:registered.Count-eq2-and$script:started.Count-eq1-and$script:removed.Count-eq1)'User scheduling or completed task cleanup is incorrect.'
Assert-OfficeTest($cleanup.PendingUserSids.Count-eq1-and$cleanup.PendingUserSids[0]-eq'logged-off'-and$cleanup.RegistrationFailures.Count-eq0)'Logged-off user cleanup was reported complete.'
Assert-OfficeTest($cleanup.PendingUserSids.Count-eq1-and$cleanup.PendingUserSids[0]-eq'logged-off')'Completed task housekeeping must not fail deployment or mark completed cleanup pending.'
functionNew-ScheduledTaskPrincipal{
param($UserId,$LogonType,$RunLevel,$ErrorAction)
if($UserId-eq'unmapped'-and$script:registrationStage-eq'principal'){throw'No mapping between account names and security IDs was done.'}
Assert-OfficeTest($cleanup.Count-eq1-and$cleanup[0].RegistrationFailures.Count-eq1)'An unmapped account must return one structured result with a registration failure.'
Assert-OfficeTest($cleanup[0].RegistrationFailures[0].SID-eq'unmapped'-and$cleanup[0].RegistrationFailures[0].ProfilePath-eq$unmapped.LocalPath-and$cleanup[0].RegistrationFailures[0].Error-match'No mapping')'Registration failures must identify the affected SID, profile, and actual error.'
Assert-OfficeTest($script:registered.Count-eq2-and$script:started.Count-eq1)'An unmapped first profile must not prevent scheduling and starting cleanup for later users.'
Assert-OfficeTest($cleanup[0].PendingUserSids.Count-eq1-and$cleanup[0].PendingUserSids[0]-eq'logged-off')'A missing task must not be reported as able to retry at sign-in.'
Assert-OfficeTest($cleanup.PendingUserSids.Count-eq0-and$cleanup.RegistrationFailures.Count-eq0)'An empty profile list must return empty cleanup result arrays.'
Assert-OfficeTest((Get-Content-LiteralPath$Global:LogFile-Raw)-match'Error: User cleanup task registration failed for unmapped \(C:\\Users\\defaultuser100000\)')'Registration failures must reach the Tools diagnostic log.'
Assert-OfficeTest($options.TargetOfficeVersion-eq'16.0.20326.20158'-and!(Test-Path-LiteralPath$script:historyPaths[-1]))'Resolved metadata must be removed after successful preflight.'
Assert-OfficeTest($Method-eq'Head'-and$MaximumRedirection-eq10-and!$OutFile)'Assessment must use HEAD with redirect handling and no output file.'
$script:heads+=$Uri
if($script:headFails){throw'HEAD unsupported'}
[pscustomobject]@{StatusCode=$script:headCode}
}
functionSave-OfficeDownload{throw'Assessment must not download data.'}
$options=Get-OfficeDeploymentOptions@{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'}
$checks=@(Test-OfficeDownloadLinks$options)
Assert-OfficeTest($checks.Count-eq6-and$checks.Count-eq$script:heads.Count)'HEAD checks must cover ODT discovery, helper, CDN, and selected companions.'
Assert-OfficeTest((Get-OfficeDeploymentDefinitions).CompanionInstallers.Teams.Uri-notin$script:heads)'No-Teams assessment must not probe the Teams download.'
Assert-OfficeTest($checks.Count-eq8-and(Get-OfficeDeploymentDefinitions).OfficeReleaseHistory-in$script:heads)'Windows 10 assessment must check history availability without resolving the build.'
Assert-OfficeTest(!(Test-Path-LiteralPath$path)-and$result.TestedDirectory-eq$testRoot-and@(Get-ChildItem-LiteralPath$testRoot-Force).Count-eq$before)'Write checks must remove probes and never create deployment directories.'
Assert-OfficeTest($state.Present-and$state.WorkingConfiguration[0]-eq'old-guid'-and$state.SourceReferences.Count-eq1)'Interrupted Click-to-Run configuration must be detected without installed products.'
Assert-OfficeTest($script:liveHelperId-eq$id-and!$command.Contains('-File '))'Deferred cleanup must execute freshly fetched source in memory with the correct deployment ID.'
}
# A new deployment clears every previous GUID workspace, including legacy caches,
# while preserving logs and refusing to race a previous installer or user task.
foreach($namein@('ODT\payload.dat','ODT\native.log','install.xml','remove.xml','options.json','media-cache.json','Office-UserCleanup.ps1','user-cleanup.lock','reinstall-started','result.log')){Set-Content-LiteralPath(Join-Path$old$name)-Value'old content, not reusable'}
Assert-OfficeTest($script:oldTaskRemoved-and$remaining.Count-eq2-and@($remaining|Where-ObjectExtension-ne'.log').Count-eq0)'Previous cached downloads, options and scripts must be removed; nested logs must remain.'
Assert-OfficeTest(!(Test-Path-LiteralPath$legacyMetadata))'Abandoned legacy assessment metadata must be removed too.'
Assert-OfficeTest(Test-Path-LiteralPath(Join-Path$unknown'keep.txt'))'Cleanup must stay within GUID deployment folders.'
Clear-OfficePreviousDeploymentFiles
Assert-OfficeTest(@(Get-ChildItem-LiteralPath$old-Recurse-File).Count-eq2)'Cleanup must be repeatable with logs-only directories.'
}
# Cleanup runs synchronously on every install exit. Only logs survive in staging;
# pending-user tasks retain synchronization state but fetch their helper live.
Assert-OfficeTest($Root-eq(Join-Path$env:ProgramData'EmberkomOfficeDeployment')-and$DeploymentId-eq('c'*32))'Pending-user helper must use a separate protected ProgramData workspace.'
Assert-OfficeTest(!(Test-Path-LiteralPath(Join-Path$userWorkspace'Office-UserCleanup.ps1'))-and(Test-Path-LiteralPath(Join-Path$userWorkspace'user-cleanup.lock')))'Pending tasks must retain only synchronization state, never cached code.'
Assert-OfficeTest(!$warnings.Count-and!(Test-Path-LiteralPath(Join-Path$workspace'ODT'))-and!(Test-Path-LiteralPath(Join-Path$workspace'odt.exe'))-and(Test-Path-LiteralPath(Join-Path$workspace'office-install.stdout.log')))'Completion must remove media and preserve diagnostics.'
Assert-OfficeTest(!(Test-Path-LiteralPath$media.Helper)-and@(Get-ChildItem-LiteralPath$workspace-File|Where-ObjectExtension-ne'.log').Count-eq0)'Deployment cleanup must leave only log files.'
Assert-OfficeTest(Test-Path-LiteralPath(Join-Path$userWorkspace'user-cleanup.lock'))'Pending-user synchronization state must survive staging cleanup.'
# An installer without a source path, locked media and links all defer cleanup.
Assert-OfficeTest(Test-OfficeStagingInUse$workspace@([pscustomobject]@{Name='OfficeC2RClient.exe'}))'Surviving native installers must defer media cleanup.'
Assert-OfficeThrows{Remove-OfficeManagedItem$root$testRoot}'outside the Office deployment root'
Assert-OfficeThrows{Remove-OfficeManagedItem$root$root}'outside the Office deployment root'
functionAssert-OfficeDiskSpace{param($Workspace,[switch]$DownloadingMedia)if($script:mode-eq'preflight-space'){throw'Insufficient disk space before download'};if($script:mode-eq'disk-space'-and!$DownloadingMedia){throw'Insufficient disk space after staging'}}
$options=Get-OfficeDeploymentOptions@{OfficeSubscription='Microsoft 365 Business Premium';OfficeAppShutdown='Force';ValidateBeforeChanges='false';DeferReboot='false'}
Assert-OfficeTest($result.ExitCode-eq$code)"Wrong result code for $script:mode"
}else{Assert-OfficeTest($null-ne$errorResult)"Failure swallowed in $script:mode"}
if($script:mode-notin@('success','pending','install','install-companions','companion-reboot')){Assert-OfficeTest('install'-notin$script:events)"Install ran after $script:mode failure/reboot."}
if($script:mode-notin@('success','pending','install-companions','companion-reboot')){Assert-OfficeTest('install-companions'-notin$script:events)"Companion install ran after $script:mode failure/reboot."}
if($script:mode-in@('download','download-cleanup')){Assert-OfficeTest('companions'-notin$script:events-and'remove-office'-notin$script:events)'Removal ran after download failed.'}
if($script:mode-eq'download-cleanup'){Assert-OfficeTest($errorResult.Exception.Message-eq'download failure')'Cleanup replaced the original deployment failure.'}
if($script:mode-eq'disk-space'){Assert-OfficeTest(($script:events-join',')-eq'download')'Low space after staging must stop before app shutdown, removal, identity cleanup, and installation.'}
if($script:mode-eq'office-reboot'){Assert-OfficeTest($result.OfficeDeploymentStatus-eq'RestartRequiredBeforeInstall'-and'identity'-notin$script:events-and'user'-notin$script:events)'Office removal restart must stop before user cleanup and replacement installation.'}
if($script:mode-eq'success'){Assert-OfficeTest(($script:events-join',')-eq'download,apps,companions,remove-office,identity,user,phase,install,install-companions')'Deployment order changed.'}
Assert-OfficeThrows{Invoke-OfficeDeployment$options}'Insufficient disk space before download'
Assert-OfficeTest($script:events.Count-eq0-and$script:workspaceCreates-eq0-and$script:artifactCleanupRuns-eq0)'Low-space validation must stop without staging or housekeeping.'
$options.ValidateBeforeChanges=$false
Assert-OfficeThrows{Invoke-OfficeDeployment$options}'Insufficient disk space before download'
Assert-OfficeTest($script:events.Count-eq0-and$script:workspaceCreates-eq0)'Low-space install must stop before creating a workspace.'
Assert-OfficeTest($result.Count-eq1-and$result[0].ArtifactCleanupPending-and$result[0].ExitCode-eq2-and$result[0].OfficeDeploymentStatus-eq'InstalledWithArtifactCleanupPending')'Unremoved artifacts must report partial completion instead of clean success.'
Assert-OfficeThrows{Invoke-OfficeDeployment$options}'Previous artifacts are locked'
Assert-OfficeTest($script:events.Count-eq0-and$script:workspaceCreates-eq0)'Old artifacts must be cleared before creating or downloading a new deployment.'
Assert-OfficeTest($result.OfficeDeploymentStatus-eq'InstalledWithUserCleanupIncomplete'-and$result.UserCleanupRegistrationFailures.Count-eq1-and$result.UserCleanupRegistrationFailures[0].SID-eq'unmapped')'A task registration failure must remain visible after successful installation.'
Assert-OfficeTest($result.ExitCode-eq$(if($script:mode-eq'registration-reboot'){3010}else{2}))'Registration failures must report partial completion without hiding a required reboot.'
Assert-OfficeTest($result.PendingUserSids.Count-eq$(if($script:mode-eq'registration-and-pending'){1}else{0}))'Unregistered tasks must remain distinct from deferred logon tasks.'
Assert-OfficeTest('install'-in$script:events-and'install-companions'-in$script:events-and$script:artifactCleanupRuns-eq1)'Task registration failure must allow verified installation and staging-file cleanup.'
$options=Get-OfficeDeploymentOptions@{OfficeSubscription='Microsoft 365 Business Premium';OfficeAppShutdown='Force';ValidateBeforeChanges='false'}
$result=Invoke-OfficeDeployment$options
Assert-OfficeTest($result.ExitCode-eq3010-and$result.RestartRequired-and$result.DeferReboot-is[bool]-and$result.DeferReboot)'A deferred removal restart must survive later zero-exit installers in the final result.'
if($script:removalStillRegistered){
Assert-OfficeTest($result.OfficeDeploymentStatus-eq'RestartRequiredBeforeInstall'-and'install'-notin$script:events-and'install-companions'-notin$script:events)'Incomplete removal must still stop before installation with DeferReboot=true.'
}else{
Assert-OfficeTest($result.OfficeDeploymentStatus-eq'Installed'-and'install'-in$script:events-and'install-companions'-in$script:events)'Verified removal should complete installation without an intervening restart.'
$options=Get-OfficeDeploymentOptions@{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)';OfficeAppShutdown='Force';ValidateBeforeChanges='false'}
$result=Invoke-OfficeDeployment$options
Assert-OfficeTest(!$script:teamsRequested-and!$result.TeamsSelected)'Deployment did not pass the no-Teams choice to companion installation/reporting.'
$options=Get-OfficeDeploymentOptions@{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)';OfficeAppShutdown=$shutdown;ValidateBeforeChanges=$validate}
$result=Invoke-OfficeDeployment$options
Assert-OfficeTest($result.OfficeDeploymentStatus-eq'ValidationPassed'-and$result.ExitCode-eq0-and$result.ValidateBeforeChanges)'Validation did not produce a distinct result.'
Assert-OfficeTest($result.OfficeRemovalMethod-eq'SilentODT'-and$result.DeferReboot-is[bool]-and$result.DeferReboot)'Validation must identify the silent removal method and Boolean restart selection.'
Assert-OfficeTest($script:events.Count-eq0-and$script:workspaceCreates-eq0-and$script:artifactCleanupRuns-eq0-and$script:priorCleanupRuns-eq0-and!$result.MediaDownloaded-and!$result.Workspace-and!$result.MetadataResolved)'Validation downloaded media, created a workspace or reached a deployment action.'
Assert-OfficeTest(!$result.TeamsSelected-and$result.ProfileCount-eq1-and$result.ExistingOffice[0]-eq'Synthetic Office')'Validation report lost the deployment plan.'
Assert-OfficeTest($script:events.Count-eq0-and$result.RunningApps[0]-eq'winword')'Validation downloaded media or closed a running app with Force selected.'
Assert-OfficeTest($selected.Count-eq1-and$selected[0].ProductId-eq'O365BusinessRetail'-and$selected[0].Company-eq$COMPANY)'Run-Script lost RMM caller variables.'
}
# Run the real shim -> original Run-Script -> main entry point in a child process.
# Replace only the destructive workload; mock WebClient rather than making network calls.
Assert-OfficeTest($receipt.ProductId-eq'O365ProPlusEEANoTeamsRetail'-and$receipt.Company-ceq$probeValues.COMPANY-and$receipt.Activation-eq'SharedComputer')'Shim lost injected strings before main workload.'
Assert-OfficeTest($receipt.ValidateBeforeChanges-eq($case.Validate-ne'false'))'Shim lost the validation gate.'
Assert-OfficeTest($probeLog-match'Mock action diagnostic'-and$probeLog-match'"OfficeDeploymentStatus"'-and$probeText-notmatch'Mock action diagnostic')'Diagnostics or receipt did not reach the correct log/console destination.'
Assert-OfficeTest($probeLog-notmatch'Validation only:|Diagnostic log:')'Console-only output was unexpectedly logged.'
}elseif($case.Mode-eq'missing'){
Assert-OfficeTest($probeText-match'did not return a verified result')'Missing workload receipt was not detected.'
}else{
Assert-OfficeTest((Get-Content-LiteralPath(Join-Path$testRoot'probe-management.log')-Raw)-match'Error: Office deployment failed: Simulated deployment failure'-and$probeText-match'Simulated deployment failure')'Failure must reach both Tools log and Syncro console.'
}
}
# Exercise the native-host command with the same network mock and an inert child workload.
Assert-OfficeTest($receipt.ValidateBeforeChanges-and$receipt.LogFile-eq$Global:LogFile-and(Get-Content-LiteralPath$Global:LogFile-Raw)-match'Native logging diagnostic')'Native-host command must reload Tools and preserve validation and the parent log.'
# Simulate Syncro's 32-bit Windows PowerShell launching the native 64-bit 5.1 host.
# Only the relaunch payload is replaced; host selection and process exit handling are real.
Assert-OfficeTest($hostResult.Edition-eq'Desktop'-and$hostResult.Version-like'5.1.*'-and$hostResult.Is64Bit)'Syncro relaunch must use native Windows PowerShell 5.1.'
}
Write-Output"PASS: $script:assertions assertions in Windows PowerShell $($PSVersionTable.PSVersion). No downloads, Office changes, credentials, registry writes, or scheduled tasks touched."
}finally{
$resolved=[IO.Path]::GetFullPath($testRoot)
if(!$resolved.StartsWith([IO.Path]::GetFullPath($env:TEMP).TrimEnd('\')+'\OfficeDeploymentTests-',[StringComparison]::OrdinalIgnoreCase)){throw'Unsafe test cleanup target.'}