#Requires -Version 5.1 # Offline integration tests; only synthetic files under a unique scratch directory. $ErrorActionPreference = 'Stop' $scriptPath = Join-Path (Split-Path $PSScriptRoot -Parent) 'Repair-OneDriveKnownFolderPaths.ps1' $testParent = Split-Path $PSScriptRoot -Parent $testRoot = Join-Path $testParent ('odt-' + [guid]::NewGuid().ToString('N').Substring(0,8)) $null = [IO.Directory]::CreateDirectory($testRoot) function Assert($Condition, [string]$Message) { if (-not $Condition) { throw $Message } } function New-Fixture([string]$Name) { $root = Join-Path $testRoot $Name $folders = @{} foreach ($folder in @('Documents','Pictures','Desktop')) { $folders[$folder] = Join-Path $root $folder $null = [IO.Directory]::CreateDirectory($folders[$folder]) } return @{ KnownFolderPaths=$folders; OneDriveRoot=(Join-Path $root 'OneDrive - Test') ReportDirectory=(Join-Path $testRoot 'reports'); Apply='false'; MaxNameLength=80 } } function Write-FixtureFile([string]$Path, [string]$Content) { [IO.File]::WriteAllText(('\\?\' + $Path), $Content) } try { $options = New-Fixture 'basic' $longA = $options.KnownFolderPaths.Documents + '\' + ('a' * 125) + '.pdf' $longB = $options.KnownFolderPaths.Documents + '\' + ('a' * 124) + 'b.pdf' $short = $options.KnownFolderPaths.Pictures + '\keep [1].jpg' Write-FixtureFile $longA 'first PDF contents' Write-FixtureFile $longB 'second PDF contents' Write-FixtureFile $short 'image contents' $preview = & $scriptPath -Options $options $rows = @(Import-Csv -LiteralPath $preview.ResultPath) Assert ($preview.Previewed -eq 2 -and $preview.Renamed -eq 0) 'Default/string-false must preview both long names.' Assert ([IO.File]::Exists($longA) -and [IO.File]::Exists($longB)) 'Preview changed original files.' Assert (($rows | Select-Object -ExpandProperty NewPath -Unique).Count -eq 2) 'Truncation must avoid collisions.' foreach ($row in $rows) { Assert ($row.NewPath.EndsWith('.pdf')) 'Extension changed.' Assert ([IO.Path]::GetFileName($row.NewPath).Length -le 80) 'Filename exceeds budget.' Assert ([int]$row.NewProjectedPathLength -le 240) 'Projected path exceeds budget.' } # Occupy a proposed name after preview: planning must choose another name. $occupied = $rows[0].NewPath Write-FixtureFile $occupied 'existing destination' $options.Apply = 'true' $applied = & $scriptPath -Options $options Assert ($applied.Renamed -eq 2) 'Apply did not rename both files.' Assert ([IO.File]::ReadAllText($occupied) -eq 'existing destination') 'An existing destination was overwritten.' $appliedRows = @(Import-Csv -LiteralPath $applied.ResultPath) foreach ($row in $appliedRows) { $expected = if ($row.OriginalPath -eq $longA) { 'first PDF contents' } else { 'second PDF contents' } Assert ([IO.File]::ReadAllText($row.NewPath) -eq $expected) 'File contents changed during rename.' Assert (-not [IO.File]::Exists($row.OriginalPath)) 'Old name still exists after rename.' } Assert ([IO.File]::ReadAllText($short) -eq 'image contents') 'Short file changed.' $journal = @(Import-Csv -LiteralPath $applied.JournalPath) Assert ($journal.Count -eq 4 -and $journal[0].Status -eq 'Pending' -and $journal[1].Status -eq 'Renamed') 'Journal must record intent and outcome.' $again = & $scriptPath -Options $options Assert ($again.Renamed -eq 0 -and $again.ReviewNeeded -eq 0) 'Rerun must be idempotent.' Write-Host 'PASS: preview, collision avoidance, extensions, contents, journal, and idempotence.' $options = New-Fixture 'long' $options.MaxNameLength = 255 $nested = $options.KnownFolderPaths.Documents + '\' + ('nested' * 12) $null = [IO.Directory]::CreateDirectory(('\\?\' + $nested)) $longPath = $nested + '\' + ('report' * 29) + '.xlsx' Write-FixtureFile $longPath 'long path content' Assert ($longPath.Length -gt 260) 'Fixture must exceed the traditional Windows path limit.' $options.Apply = $true $result = & $scriptPath -Options $options $renamedRow = @(Import-Csv -LiteralPath $result.ResultPath | Where-Object Status -eq 'Renamed') Assert ($renamedRow.Count -eq 1) 'Could not enumerate/rename an actual >260-character path.' Assert ($renamedRow[0].NewPath.Length -le 240 -and $renamedRow[0].NewProjectedPath.Length -le 240) 'Current and projected lengths must both fit.' Assert ([IO.File]::ReadAllText($renamedRow[0].NewPath) -eq 'long path content') 'Long-path file contents changed.' Write-Host 'PASS: real >260-character path enumeration and rename.' $options = New-Fixture 'deep' $deep = $options.KnownFolderPaths.Documents + '\' + ('d' * 100) + '\' + ('e' * 100) $null = [IO.Directory]::CreateDirectory(('\\?\' + $deep)) Write-FixtureFile ($deep + '\file.txt') 'deep content' $options.Apply = $true $result = & $scriptPath -Options $options $rows = @(Import-Csv -LiteralPath $result.ResultPath) Assert ($result.Renamed -eq 0 -and @($rows | Where-Object Status -eq 'NeedsFolderCleanup').Count -ge 1) 'Deep paths must be flagged without changing folders.' Assert ([Emberkom.OneDrivePathNativeV1]::Inspect($deep + '\file.txt').Name -eq 'file.txt') 'Unfixable file must remain unchanged.' Write-Host 'PASS: unfixable folder depth reported without renaming folders.' $options = New-Fixture 'whatif' $original = $options.KnownFolderPaths.Desktop + '\' + ('x' * 100) + '.txt' Write-FixtureFile $original 'whatif' $options.Apply = 'yes' $result = & $scriptPath -Options $options -WhatIf Assert ($result.Renamed -eq 0 -and [IO.File]::Exists($original)) 'WhatIf must suppress renames even with Apply=true.' $options.KnownFolderPaths.Pictures += '\missing' $result = & $scriptPath -Options $options Assert ($result.ScanErrors -eq 1 -and $result.Renamed -eq 0 -and [IO.File]::Exists($original)) 'Scan errors must block all renames.' Write-Host 'PASS: WhatIf and incomplete scans block changes.' $options = New-Fixture 'projected' $options.MaxNameLength = 255 $options.MaxPathLength = 200 $parent = $options.KnownFolderPaths.Documents $nameLength = 200 - $parent.Length - 1 $original = $parent + '\' + ('p' * ($nameLength - 4)) + '.txt' Write-FixtureFile $original 'projected' $result = & $scriptPath -Options $options Assert ($original.Length -eq 200 -and $result.Previewed -eq 1) 'Must account for extra OneDrive destination prefix before migration.' $options.Apply = 'maybe' $caught = $false try { & $scriptPath -Options $options } catch { $caught = $_.Exception.Message -like 'Apply must*' } Assert $caught 'Ambiguous Apply values must fail closed.' Write-Host 'PASS: projected destination length and RMM Boolean validation.' # Literal wildcard characters, UTF-16 boundary, extensionless and dot files. $options = New-Fixture 'unicode' $options.MaxNameLength = 40 $emoji = [char]::ConvertFromUtf32(0x1F600) foreach ($name in @((('a' * 26) + $emoji + ('z' * 45) + '.txt'), (('b' * 80) + '[1]'), ('.' + ('c' * 80)))) { Write-FixtureFile ($options.KnownFolderPaths.Pictures + '\' + $name) 'unicode' } $options.Apply = $true $result = & $scriptPath -Options $options $rows = @(Import-Csv -LiteralPath $result.ResultPath) Assert ($result.Renamed -eq 2 -and $result.ReviewNeeded -eq 1) 'A dotfile with an overlong extension must be reported; other files should rename.' foreach ($row in @($rows | Where-Object Status -eq 'Renamed')) { $strictUtf8 = [Text.UTF8Encoding]::new($false, $true) $null = $strictUtf8.GetBytes($row.NewPath) Assert ([IO.File]::ReadAllText($row.NewPath) -eq 'unicode') 'Unicode/literal file contents changed.' } Write-Host 'PASS: Unicode boundary, literal brackets, extensionless file, and long extension.' $options = New-Fixture 'locked' $options.Apply = $true $original = $options.KnownFolderPaths.Documents + '\' + ('l' * 100) + '.txt' Write-FixtureFile $original 'locked file' $locked = [IO.File]::Open($original, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None) try { $result = & $scriptPath -Options $options } finally { $locked.Dispose() } $rows = @(Import-Csv -LiteralPath $result.ResultPath) Assert ($result.Renamed -eq 0 -and $rows[0].Status -eq 'RenameFailed') 'Locked file failures must be reported.' Assert ([IO.File]::ReadAllText($original) -eq 'locked file') 'Failed rename changed file contents.' $journal = @(Import-Csv -LiteralPath $result.JournalPath) Assert ($journal.Count -eq 2 -and $journal[1].Status -eq 'RenameFailed') 'Journal must include failed outcome.' Write-Host 'PASS: locked file is retained and failure is journaled.' $options = New-Fixture 'cloud' $options.MaxPathLength = 520 $options.MaxNameLength = 255 $relativeDirectory = 'Documents\' + ('a' * 100) + '\' + ('b' * 100) $directory = $options.KnownFolderPaths.Documents + $relativeDirectory.Substring('Documents'.Length) $null = [IO.Directory]::CreateDirectory(('\\?\' + $directory)) $name = ('c' * (401 - $relativeDirectory.Length - 1 - 4)) + '.txt' Write-FixtureFile ($directory + '\' + $name) 'cloud limit' $result = & $scriptPath -Options $options $rows = @(Import-Csv -LiteralPath $result.ResultPath) Assert ($result.Previewed -eq 1 -and [int]$rows[0].CloudRelativePathLength -eq 401) 'Cloud-relative limit must be enforced independently.' Assert (($rows[0].NewProjectedPath.Length - $options.OneDriveRoot.Length - 1) -le 400) 'Shortened cloud-relative path exceeds 400.' Write-Host 'PASS: independent 400-character cloud-relative limit.' $options = New-Fixture 'links' $outside = Join-Path $testRoot 'link-target' $null = [IO.Directory]::CreateDirectory($outside) $outsideFile = $outside + '\' + ('j' * 100) + '.txt' Write-FixtureFile $outsideFile 'outside the known folders' $junction = Join-Path $options.KnownFolderPaths.Documents 'junction' $null = New-Item -Path $junction -ItemType Junction -Target $outside try { $options.Apply = $true $result = & $scriptPath -Options $options $rows = @(Import-Csv -LiteralPath $result.ResultPath) Assert ($result.FilesScanned -eq 0 -and $rows[0].Status -eq 'SkippedReparsePoint') 'Junction must not be traversed.' Assert ([IO.File]::ReadAllText($outsideFile) -eq 'outside the known folders') 'Junction target changed.' $options.KnownFolderPaths.Documents = $junction $result = & $scriptPath -Options $options Assert ($result.ScanErrors -eq 1) 'A junction supplied as a root must fail the scan.' } finally { # Delete only the junction entry, never its target or contents. [IO.Directory]::Delete($junction) } Write-Host 'PASS: nested junction and root junction are not followed.' # No network/bootstrap: exercise the actual Run-Script shared-scope branch. $toolsPath = Join-Path (Split-Path $PSScriptRoot -Parent) 'Tools.ps1' $tokens=$null; $parseErrors=$null $ast = [Management.Automation.Language.Parser]::ParseFile($toolsPath, [ref]$tokens, [ref]$parseErrors) $definition = $ast.Find({ param($node) $node -is [Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -eq 'Run-Script' }, $true) # Stub only the download expression, including the empty-string argument # branch used by versions whose typed Arguments parameter converts null to ''. $offlineDefinition = $definition.Extent.Text.Replace('(New-Object Net.WebClient).DownloadString($URL)', '[IO.File]::ReadAllText($downloadedScript)') . ([scriptblock]::Create($offlineDefinition)) function IsURLValid { return $true } function Download-File { return $downloadedScript } function Write-Output { param($Message) } # Simulate Tools' logging wrapper. $downloadedScript = Join-Path $testRoot 'downloaded.ps1' Copy-Item -LiteralPath $scriptPath -Destination $downloadedScript $OneDrivePrepOptions = New-Fixture 'rmm' Write-FixtureFile ($OneDrivePrepOptions.KnownFolderPaths.Documents + '\' + ('r' * 100) + '.txt') 'RMM' $OneDrivePrepOptions.Apply = 'false' $beforePreference = $ErrorActionPreference $dotSourced = . $scriptPath Assert ($dotSourced.Previewed -eq 1) 'Dot-sourcing must read caller options.' $result = Run-Script -LivePSScript Repair-OneDriveKnownFolderPaths Assert ($result.Previewed -eq 1 -and $result.Renamed -eq 0) 'RMM shared-scope options were lost or string false enabled changes.' Assert ($ErrorActionPreference -eq $beforePreference -and $OneDrivePrepOptions.Apply -ceq 'false') 'Caller state must be preserved.' Write-Host 'PASS: actual Run-Script shared scope and caller-state preservation.' # The uploaded shim must leave the RMM's scalar strings untouched. Exercise # its actual source, replacing only the Tools bootstrap to keep tests offline. $shimPath = Join-Path (Split-Path $PSScriptRoot -Parent) 'rmm\Repair-OneDriveKnownFolderPaths.ps1' $shimAst = [Management.Automation.Language.Parser]::ParseFile($shimPath, [ref]$tokens, [ref]$parseErrors) $bootstrap = $shimAst.Find({ param($node) $node -is [Management.Automation.Language.CommandAst] -and $node.InvocationOperator -eq 'Dot' }, $true) Assert ($null -ne $bootstrap) 'RMM shim must retain the shared-scope Tools bootstrap.' $offlineShim = [scriptblock]::Create([IO.File]::ReadAllText($shimPath).Replace($bootstrap.Extent.Text, '# Offline Tools bootstrap')) & { $fixture = New-Fixture 'flat' $UserProfilePath = 'C:\Users\Synthetic-Test-Profile' $OneDriveRoot = [string]$fixture.OneDriveRoot $ReportDirectory = [string]$fixture.ReportDirectory $DocumentsPath = [string]$fixture.KnownFolderPaths.Documents $PicturesPath = [string]$fixture.KnownFolderPaths.Pictures $DesktopPath = [string]$fixture.KnownFolderPaths.Desktop $Apply = ' false ' $MaxPathLength = '240' $MaxNameLength = '60' # An inherited legacy apply setting must not override the new inputs. $OneDrivePrepOptions = @{ Apply=$true; UnknownLegacySetting='ignored' } $original = $DocumentsPath + '\' + ('f' * 130) + '.txt' Write-FixtureFile $original 'flat variable fixture' Copy-Item -LiteralPath $scriptPath -Destination $downloadedScript -Force $result = & $offlineShim Assert ($result.Previewed -eq 1 -and $result.Renamed -eq 0) 'Scalar string false must remain a preview through the RMM shim.' Assert ($Apply -ceq ' false ' -and $MaxNameLength -ceq '60' -and $UserProfilePath -ceq 'C:\Users\Synthetic-Test-Profile') 'Injected variables were overwritten.' $row = @(Import-Csv -LiteralPath $result.ResultPath)[0] Assert ([IO.Path]::GetFileName($row.NewPath).Length -le 60) 'Scalar numeric string was not applied.' $dotResult = . $scriptPath Assert ($dotResult.Previewed -eq 1) 'Dot-sourcing must also read individual RMM strings.' # Missing/blank values default safely instead of inheriting legacy Apply. Remove-Variable -Name Apply $MaxPathLength = ''; $MaxNameLength = '' Copy-Item -LiteralPath $scriptPath -Destination $downloadedScript -Force $result = Run-Script -LivePSScript Repair-OneDriveKnownFolderPaths Assert ($result.Mode -eq 'Preview' -and $result.Previewed -eq 1) 'Missing Apply and blank length limits must default safely.' $row = @(Import-Csv -LiteralPath $result.ResultPath)[0] Assert ([int]$row.NewProjectedPathLength -le 240) 'Blank length input must retain the 240-character default.' $Apply = 'maybe' $caught = $false try { & $scriptPath } catch { $caught = $_.Exception.Message -like 'Apply must*' } Assert $caught 'Invalid injected Apply must fail before renaming.' # Standalone explicit options take precedence over unrelated scope inputs. $result = & $scriptPath -Options $fixture Assert ($result.Mode -eq 'Preview') 'Explicit -Options must override injected variables.' $Apply = 'false' $DesktopPath = 'Auto' $caught = $false try { & $scriptPath } catch { $caught = $_.Exception.Message -like 'Supply DocumentsPath*' } Assert $caught 'Partial source overrides must not silently target different folders.' $DesktopPath = [string]$fixture.KnownFolderPaths.Desktop $Apply = 'true' $MaxNameLength = '60' Copy-Item -LiteralPath $scriptPath -Destination $downloadedScript -Force $result = & $offlineShim Assert ($result.Renamed -eq 1 -and -not [IO.File]::Exists($original)) 'Scalar string true must enable the requested rename.' $row = @(Import-Csv -LiteralPath $result.ResultPath)[0] Assert ([IO.File]::ReadAllText($row.NewPath) -eq 'flat variable fixture') 'RMM rename changed file contents.' } Write-Host 'PASS: RMM scalar strings, uploaded shim, safe defaults, input precedence, validation, and explicit apply.' Write-Host "All OneDrive path preparation tests passed on PowerShell $($PSVersionTable.PSVersion)." } finally { # Check the exact absolute target before recursive deletion, using one shell. $resolvedRoot = [IO.Path]::GetFullPath($testRoot) $scratchParent = [IO.Path]::GetFullPath($testParent).TrimEnd('\') if ([IO.Path]::GetDirectoryName($resolvedRoot) -eq $scratchParent -and [IO.Path]::GetFileName($resolvedRoot) -match '^odt-[a-f0-9]{8}$') { [IO.Directory]::Delete(('\\?\' + $resolvedRoot), $true) } else { throw "Refusing to clean an unexpected test directory: $resolvedRoot" } }