diff --git a/.github/AL-Go-Settings.json b/.github/AL-Go-Settings.json index ebdf77da5f9..3f7aca6b867 100644 --- a/.github/AL-Go-Settings.json +++ b/.github/AL-Go-Settings.json @@ -16,7 +16,6 @@ "repoVersion": "30.0", "memoryLimit": "16G", "numberOfTenantsForTesting": 4, - "enableCleanTestCodeunitExecution": true, "enableChurnBasedTesting": true, "maxTestAppReruns": 2, "failOn": "newWarning", diff --git a/build/scripts/ParallelTestExecution.psm1 b/build/scripts/ParallelTestExecution.psm1 index 025674d4b4f..433e81095ad 100644 --- a/build/scripts/ParallelTestExecution.psm1 +++ b/build/scripts/ParallelTestExecution.psm1 @@ -8,11 +8,14 @@ Import-Module (Join-Path $PSScriptRoot "ALAppBuild.psm1" -Resolve) Gets disabled test entries for an app. .PARAMETER AppName Application name used to locate its DisabledTests folder. +.PARAMETER Country + Country code for entries with an optional country field. Entries without it apply everywhere. #> function Get-DisabledTestsForApp { param( [Parameter(Mandatory=$true)] - [string]$AppName + [string]$AppName, + [string]$Country ) $appFolderName = $AppName -replace ' ', '_' @@ -33,101 +36,10 @@ function Get-DisabledTestsForApp { } } - return @($disabledTests) -} - -function Get-ParametersForCommand { - param( - [Parameter(Mandatory=$true)] - [Hashtable]$Parameters, - [Parameter(Mandatory=$true)] - [string]$CommandName - ) - - $command = Get-Command $CommandName -ErrorAction Stop - $filtered = @{} - foreach ($key in $Parameters.Keys) { - if ($command.Parameters.ContainsKey($key)) { - $filtered[$key] = $Parameters[$key] - } - } - return $filtered -} - -function ConvertTo-RequiredDisabledWorkItems { - param( - [array]$DiscoveredTests, - [string]$AppName, - [string]$AppId - ) - - $codeunits = @() - foreach ($entry in @($DiscoveredTests)) { - if ($entry.PSObject.Properties.Name -contains "Codeunits") { - $codeunits += @($entry.Codeunits) - } else { - $codeunits += $entry - } - } - - return @( - $codeunits | - Where-Object { $_ -and $_.Id -and @($_.Tests).Count -gt 0 } | - ForEach-Object { - [PSCustomObject]@{ - Key = "${AppName}::$($_.Id)" - AppName = $AppName - AppId = $AppId - CodeunitId = [string]$_.Id - CodeunitName = [string]$_.Name - TestCount = @($_.Tests).Count - } - } - ) -} - -function Get-RequiredDisabledWorkItems { - param( - [Parameter(Mandatory=$true)] - [Hashtable]$Parameters, - [Parameter(Mandatory=$true)] - [string]$TestType, - [string[]]$AppNamesToTest, - [Parameter(Mandatory=$true)] - [Hashtable]$AppIdByName - ) - - # Without a test type, the test-tool extension selector ignores required isolation. - # Keep Legacy buckets on their existing execution path rather than treating every - # codeunit as requiring a clean tenant. - if ($TestType -eq 'Legacy') { - Write-Host 'Legacy buckets use ordinary execution; clean isolation discovery requires a typed lane.' - return @() - } - - $workItems = @() - foreach ($appName in $AppNamesToTest) { - $appId = $AppIdByName[$appName] - if (-not $appId) { - continue - } - - $discoveryParameters = Get-ParametersForCommand -Parameters $Parameters -CommandName "Get-TestsFromBcContainer" - $discoveryParameters["extensionId"] = $appId - $discoveryParameters["requiredTestIsolation"] = "Disabled" - $discoveryParameters["disabledTests"] = @(Get-DisabledTestsForApp -AppName $appName) - $discoveryParameters["testType"] = $TestType - - Write-Host "Discovering RequiredTestIsolation=Disabled codeunits in '$appName'..." - $discoveredTests = @(Get-TestsFromBcContainer @discoveryParameters) - $appWorkItems = @(ConvertTo-RequiredDisabledWorkItems -DiscoveredTests $discoveredTests -AppName $appName -AppId $appId) - if ($appWorkItems.Count -gt 0) { - Write-Host " Found $($appWorkItems.Count) codeunit(s), $((($appWorkItems | Measure-Object TestCount -Sum).Sum)) test method(s)." - $workItems += $appWorkItems - } - } - - return @($workItems) + return @($disabledTests | Where-Object { + -not ($_.PSObject.Properties.Name -contains 'country') -or + (-not [string]::IsNullOrWhiteSpace($Country) -and $_.country -eq $Country) + }) } <# @@ -145,8 +57,8 @@ function Get-RequiredDisabledWorkItems { project or per build mode (for example a higher budget for the long legacy buckets) without any code change. - The budget is the number of DIFFERENT apps that may be re-run in one job; an individual app is - never re-run more than once (enforced separately via the rerun bookkeeping). A failed app is + The budget limits app reruns across both phases of one job; an individual app is + never re-run more than once per phase (enforced via the rerun bookkeeping). A failed app is re-run on a DIFFERENT tenant than the one it failed on: tests are not guaranteed to clean up after themselves, so a same-tenant retry can re-fail on the residue the failed run just left behind. Keep it small - it exists to absorb instability, and more failures than this means @@ -357,130 +269,6 @@ function Get-AvailableBcTenants { ) } -function New-BcTestTenantTemplate { - param( - [Parameter(Mandatory=$true)] - [string]$ContainerName, - [Parameter(Mandatory=$true)] - [string]$SourceDatabaseName - ) - - $result = @(Invoke-ScriptInBcContainer -containerName $ContainerName -useSession $false -scriptblock { Param($sourceDatabaseName) - $templateDatabaseName = "$sourceDatabaseName-test-template" - $maxAttempts = 3 - $retryDelaySeconds = 5 - for ($attempt = 1; $attempt -le $maxAttempts; $attempt++) { - try { - if (Test-NAVDatabase -DatabaseName $templateDatabaseName) { - Remove-NAVDatabase -DatabaseName $templateDatabaseName | Out-Null - } - - Write-Host "Creating immutable test tenant template '$templateDatabaseName' from '$sourceDatabaseName' (attempt $attempt/$maxAttempts)..." - Copy-NAVDatabase -SourceDatabaseName $sourceDatabaseName -DestinationDatabaseName $templateDatabaseName -DatabaseServer "." | Out-Null - break - } catch { - Write-Host "WARNING: Template database copy failed on attempt $attempt/${maxAttempts}: $($_.Exception.Message)" - if ($attempt -eq $maxAttempts) { - throw "Failed to create a test tenant template from '$sourceDatabaseName' after $maxAttempts attempts. Last error: $($_.Exception.Message)" - } - Start-Sleep -Seconds $retryDelaySeconds - } - } - $templateDatabaseName - } -argumentList $SourceDatabaseName) - - if ($result.Count -eq 0) { - throw "Creating the clean test tenant template returned no database name." - } - return [string]$result[-1] -} - -<# -.SYNOPSIS - Replaces a tenant database with a copy of an idle source database. -.PARAMETER ContainerName - Name of the BC container. -.PARAMETER Tenant - Tenant ID to refresh. -.PARAMETER TenantDatabaseName - Database currently mounted for the tenant. -.PARAMETER TemplateDatabaseName - Immutable test template, or the untouched primary database used to restore discovery. -#> -function Reset-BcTestTenant { - param( - [Parameter(Mandatory=$true)] - [string]$ContainerName, - [Parameter(Mandatory=$true)] - [string]$Tenant, - [Parameter(Mandatory=$true)] - [string]$TenantDatabaseName, - [Parameter(Mandatory=$true)] - [string]$TemplateDatabaseName - ) - - Invoke-ScriptInBcContainer -containerName $ContainerName -useSession $false -scriptblock { - Param($tenant, $tenantDatabaseName, $templateDatabaseName) - - $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() - $mountedTenant = Get-NAVTenant -ServerInstance $ServerInstance -Tenant $tenant -ErrorAction SilentlyContinue - if ($mountedTenant) { - Dismount-NAVTenant -ServerInstance $ServerInstance -Tenant $tenant -Force | Out-Null - } - - $maxAttempts = 3 - $retryDelaySeconds = 5 - for ($attempt = 1; $attempt -le $maxAttempts; $attempt++) { - try { - if (Test-NAVDatabase -DatabaseName $tenantDatabaseName) { - Remove-NAVDatabase -DatabaseName $tenantDatabaseName | Out-Null - } - - Copy-NAVDatabase -SourceDatabaseName $templateDatabaseName -DestinationDatabaseName $tenantDatabaseName -DatabaseServer "." | Out-Null - break - } catch { - Write-Host "WARNING: Tenant database refresh failed on attempt $attempt/${maxAttempts}: $($_.Exception.Message)" - if ($attempt -eq $maxAttempts) { - throw "Failed to refresh tenant database '$tenantDatabaseName' after $maxAttempts attempts. Last error: $($_.Exception.Message)" - } - Start-Sleep -Seconds $retryDelaySeconds - } - } - Mount-NAVTenant -ServerInstance $ServerInstance -Id $tenant -DatabaseServer "." -DatabaseName $tenantDatabaseName -OverwriteTenantIdInDatabase -AllowAppDatabaseWrite -Force | Out-Null - - $maxWaitSeconds = 300 - while ((Get-NAVTenant -ServerInstance $ServerInstance -Tenant $tenant).State -eq "Mounting") { - if ($stopwatch.Elapsed.TotalSeconds -ge $maxWaitSeconds) { - throw "Tenant '$tenant' did not finish mounting within $maxWaitSeconds seconds." - } - Start-Sleep -Milliseconds 250 - } - - $state = (Get-NAVTenant -ServerInstance $ServerInstance -Tenant $tenant).State - if ($state -notin @("Operational", "OperationalWithWarnings")) { - throw "Tenant '$tenant' is '$state' after refresh; expected an operational state." - } - - $stopwatch.Stop() - Write-Host "Refreshed tenant '$tenant' from '$templateDatabaseName' in $([math]::Round($stopwatch.Elapsed.TotalSeconds, 2)) seconds." - } -argumentList $Tenant, $TenantDatabaseName, $TemplateDatabaseName -} - -function Remove-BcTestTenantTemplate { - param( - [Parameter(Mandatory=$true)] - [string]$ContainerName, - [Parameter(Mandatory=$true)] - [string]$TemplateDatabaseName - ) - - Invoke-ScriptInBcContainer -containerName $ContainerName -scriptblock { Param($templateDatabaseName) - if (Test-NAVDatabase -DatabaseName $templateDatabaseName) { - Remove-NAVDatabase -DatabaseName $templateDatabaseName | Out-Null - } - } -argumentList $TemplateDatabaseName -} - <# .SYNOPSIS Merges multiple test result XML files into a single file. @@ -694,142 +482,6 @@ function Start-TestAppDispatch { Start-Sleep -Seconds 5 } -function Start-RequiredDisabledDispatch { - param( - [Hashtable]$Parameters, - $WorkItem, - $TenantInfo, - [string]$ScriptPath, - [string]$TestType, - $State, - [string]$Verb = "Dispatching" - ) - - Write-Host "$Verb RequiredTestIsolation=Disabled codeunit $($WorkItem.CodeunitId) '$($WorkItem.CodeunitName)' from '$($WorkItem.AppName)' on tenant '$($TenantInfo.Id)'" - - $codeunitParameters = $Parameters.Clone() - $codeunitParameters["appName"] = $WorkItem.AppName - $codeunitParameters["extensionId"] = $WorkItem.AppId - $codeunitParameters["testCodeunit"] = $WorkItem.CodeunitId - $codeunitParameters["requiredTestIsolation"] = "Disabled" - $codeunitParameters["testRunnerCodeunitId"] = "130451" - $codeunitParameters["disabledTests"] = @(Get-DisabledTestsForApp -AppName $WorkItem.AppName) - $codeunitParameters.Remove("ReRun") | Out-Null - if ($Verb -eq "Re-dispatching") { - $codeunitParameters["ReRun"] = $true - } - - $appendKeys = @{ - XUnitResultFileName = "AppendToXUnitResultFile" - JUnitResultFileName = "AppendToJUnitResultFile" - } - foreach ($resultKey in $appendKeys.Keys) { - if ($codeunitParameters.ContainsKey($resultKey) -and $codeunitParameters[$resultKey]) { - $codeunitParameters[$appendKeys[$resultKey]] = $true - } - } - - $job = Start-TestJob -parameters $codeunitParameters -tenant $TenantInfo.Id -scriptPath $ScriptPath ` - -testType $TestType -skipAutomaticDisabledPass - $State.jobs = @($State.jobs) + @( - [PSCustomObject]@{ - jobId = $job.Id - tenant = $TenantInfo.Id - appName = $WorkItem.Key - } - ) - Start-Sleep -Seconds 1 -} - -function Invoke-RequiredDisabledTestExecution { - param( - [Parameter(Mandatory=$true)] - [Hashtable]$Parameters, - [Parameter(Mandatory=$true)] - [array]$WorkItems, - [Parameter(Mandatory=$true)] - [array]$TenantInfo, - [Parameter(Mandatory=$true)] - [string]$TemplateDatabaseName, - [Parameter(Mandatory=$true)] - [string]$ScriptPath, - [Parameter(Mandatory=$true)] - [string]$TestType - ) - - if ($WorkItems.Count -eq 0) { - return $true - } - - $workItemByKey = @{} - foreach ($workItem in $WorkItems) { - $workItemByKey[$workItem.Key] = $workItem - } - - $state = [PSCustomObject]@{ - jobs = @() - hasFailures = $false - transient = @() - retried = @{} - retryTenant = @{} - } - $pending = @($WorkItems) - - while ($pending.Count -gt 0 -or $state.transient.Count -gt 0) { - if ($state.transient.Count -gt 0) { - $retryItems = @() - foreach ($transient in @($state.transient)) { - $key = $transient.Key - $state.retried[$key] = $true - $state.retryTenant[$key] = $transient.Tenant - $retryItems += $workItemByKey[$key] - } - $state.transient = @() - $pending = @($retryItems) + @($pending) - } - - $availableTenantInfo = @($TenantInfo) - $batch = @() - while ($pending.Count -gt 0 -and $availableTenantInfo.Count -gt 0) { - $workItem = $pending[0] - $pending = @($pending | Select-Object -Skip 1) - $selectedTenantInfo = if ($state.retryTenant.ContainsKey($workItem.Key)) { - $availableTenantInfo | - Where-Object { $_.Id -eq $state.retryTenant[$workItem.Key] } | - Select-Object -First 1 - } else { - $availableTenantInfo | Select-Object -First 1 - } - if (-not $selectedTenantInfo) { - throw "Could not reserve tenant for clean codeunit '$($workItem.Key)'." - } - $availableTenantInfo = @($availableTenantInfo | Where-Object { $_.Id -ne $selectedTenantInfo.Id }) - $verb = if ($state.retried.ContainsKey($workItem.Key)) { "Re-dispatching" } else { "Dispatching" } - - $batch += [PSCustomObject]@{ - WorkItem = $workItem - TenantInfo = $selectedTenantInfo - Verb = $verb - } - } - - # Finish every restore in the batch before any test starts. This keeps SQL backup/restore - # activity from overlapping page 130455 metadata enumeration and API cold starts. - foreach ($dispatch in $batch) { - Reset-BcTestTenant -ContainerName $Parameters.containerName -Tenant $dispatch.TenantInfo.Id ` - -TenantDatabaseName $dispatch.TenantInfo.DatabaseName -TemplateDatabaseName $TemplateDatabaseName - } - foreach ($dispatch in $batch) { - Start-RequiredDisabledDispatch -Parameters $Parameters -WorkItem $dispatch.WorkItem ` - -TenantInfo $dispatch.TenantInfo ` - -ScriptPath $ScriptPath -TestType $TestType -State $state -Verb $dispatch.Verb - } - $null = Wait-ForAllTestJobs -state $state - } - - return (-not $state.hasFailures) -} - <# .SYNOPSIS Records a finished job's outcome on the state object, queueing a rerun when one is warranted. @@ -1011,6 +663,9 @@ function Start-TestJob { $jobParams["tenant"] = $tenant if ([string]::IsNullOrWhiteSpace($fileSuffix)) { $fileSuffix = $tenant } + if ($jobParams['requiredTestIsolation'] -eq 'Disabled') { + $fileSuffix = "disabled-$fileSuffix" + } # Give each job its own result file to avoid write conflicts foreach ($resultKey in @("XUnitResultFileName", "JUnitResultFileName")) { @@ -1071,80 +726,21 @@ function Wait-ForAllTestJobs { $state.jobs = @() } -function Add-MissingJUnitTestProperties { - param( - [Parameter(Mandatory=$true)] - [string]$ResultFile, - [array]$WorkItems = @() - ) - - if (-not (Test-Path $ResultFile) -or $WorkItems.Count -eq 0) { - return - } - - $workItemByCodeunitId = @{} - foreach ($workItem in $WorkItems) { - $workItemByCodeunitId[[string]$workItem.CodeunitId] = $workItem - } - - $xml = [xml](Get-Content $ResultFile -Raw) - $changed = $false - foreach ($suite in @($xml.testsuites.testsuite)) { - if ($suite.properties) { - continue - } - - $codeunitId = ([string]$suite.name -split ' ', 2)[0] - $workItem = $workItemByCodeunitId[$codeunitId] - if (-not $workItem) { - continue - } - - $properties = $xml.CreateElement("properties") - foreach ($propertyValue in @{ - extensionid = $workItem.AppId - appName = $workItem.AppName - }.GetEnumerator()) { - $property = $xml.CreateElement("property") - $property.SetAttribute("name", $propertyValue.Key) - $property.SetAttribute("value", [string]$propertyValue.Value) - $properties.AppendChild($property) | Out-Null - } - - if ($suite.FirstChild) { - $suite.InsertBefore($properties, $suite.FirstChild) | Out-Null - } else { - $suite.AppendChild($properties) | Out-Null - } - $changed = $true - } - - if ($changed) { - $xml.Save($ResultFile) - } -} - <# .SYNOPSIS Merges per-job test result files into the single file expected by Run-AlPipeline. .PARAMETER parameters The original test parameters hashtable (contains the expected result file paths). -.PARAMETER tenants - Array of tenant IDs whose result files should be merged. -.PARAMETER rerunSuffixes - Suffixes of any rerun result files. Merged after the tenant files so a rerun's results replace - those of the failed run it re-ran. +.PARAMETER resultSuffixes + Ordered result-file suffixes for both phases, with each phase's reruns after its tenant files + so a rerun's results replace those of the failed run it re-ran. #> function Merge-TenantTestResults { param( [Hashtable]$parameters, - [string[]]$tenants, - [array]$workItems = @(), - [string[]]$rerunSuffixes = @() + [string[]]$resultSuffixes ) - $suffixes = @($tenants) + @($rerunSuffixes) - foreach ($resultKey in @("XUnitResultFileName", "JUnitResultFileName")) { if ($parameters.ContainsKey($resultKey) -and $parameters[$resultKey]) { $origFile = $parameters[$resultKey] @@ -1152,12 +748,7 @@ function Merge-TenantTestResults { $name = [System.IO.Path]::GetFileNameWithoutExtension($origFile) $ext = [System.IO.Path]::GetExtension($origFile) - $tenantFiles = @($suffixes | ForEach-Object { Join-Path $dir "$name-$_$ext" }) - if ($resultKey -eq "JUnitResultFileName") { - foreach ($tenantFile in $tenantFiles) { - Add-MissingJUnitTestProperties -ResultFile $tenantFile -WorkItems $workItems - } - } + $tenantFiles = @($resultSuffixes | ForEach-Object { Join-Path $dir "$name-$_$ext" }) Merge-TestResultFiles -targetFile $origFile -sourceFiles $tenantFiles # Clean up per-job files @@ -1183,8 +774,6 @@ function Merge-TenantTestResults { All available tenant ids. Warmup dispatches onto the first one. .PARAMETER State The parallel execution state object; mutated (jobs/hasFailures/transient) as the warmup runs. -.PARAMETER CleanTenantAppNames - Apps whose automatic Disabled-isolation pass must be deferred to clean-codeunit execution. .OUTPUTS [string[]] The remaining app names to dispatch (first app removed if it was warmed up). #> @@ -1196,8 +785,7 @@ function Invoke-WarmupDispatch { [Parameter(Mandatory=$true)][AllowEmptyCollection()][string[]]$Tenants, [Parameter(Mandatory=$true)][string]$ScriptPath, [string]$TestType, - [Parameter(Mandatory=$true)]$State, - [string[]]$CleanTenantAppNames = @() + [Parameter(Mandatory=$true)]$State ) # Only serialize when there is a fan-out to protect: >1 app AND >1 tenant. @@ -1215,7 +803,7 @@ function Invoke-WarmupDispatch { Write-Host "Warming up: dispatching first app '$warmupApp' on '$($Tenants[0])' alone and awaiting completion before parallel fan-out." Start-TestAppDispatch -Parameters $Parameters -AppName $warmupApp -AppId $warmupAppId -Tenant $Tenants[0] ` -ScriptPath $ScriptPath -TestType $TestType -State $State -Verb 'Dispatching' ` - -SkipAutomaticDisabledPass:($warmupApp -in $CleanTenantAppNames) + -SkipAutomaticDisabledPass # Await the single job so the process is warm before anything runs in parallel. A transient # failure here lands in $State.transient and the caller's loop re-queues it; a hard failure is @@ -1246,6 +834,9 @@ function Remove-RerunResultFile { ) if ([string]::IsNullOrWhiteSpace($suffix)) { return } + if ($parameters['requiredTestIsolation'] -eq 'Disabled') { + $suffix = "disabled-$suffix" + } foreach ($resultKey in @("XUnitResultFileName", "JUnitResultFileName")) { if ($parameters.ContainsKey($resultKey) -and $parameters[$resultKey]) { @@ -1267,8 +858,9 @@ function Remove-RerunResultFile { .SYNOPSIS Dispatches test apps in parallel across all available tenants in a BC container. .DESCRIPTION - Walks $appNamesToTest in order, dispatching each app onto a free tenant via background jobs. - Waits for all jobs to complete, merges per-tenant result files, and returns whether all + Runs the Codeunit phase (None|Codeunit selection) first, draining all jobs and retries before + dispatching Disabled-isolation tests through the same app queue. Legacy retains its single unfiltered pass. + Waits for all jobs to complete, merges phase-specific result files, and returns whether all passed. The result is cached to a state file so subsequent calls (from the per-project override on the same job) can short-circuit. .PARAMETER parameters @@ -1315,8 +907,7 @@ function Invoke-ParallelTestExecution { } } - $tenantInfo = @(Get-AvailableBcTenantInfo -containerName $parameters.containerName) - $tenants = @($tenantInfo | ForEach-Object { $_.Id }) + $tenants = @(Get-AvailableBcTenants -containerName $parameters.containerName) Write-Host "Available tenants: $($tenants -join ', ')" # Build a name -> appId map so we can set extensionId per dispatch. Run-TestsInBcContainer @@ -1328,65 +919,6 @@ function Invoke-ParallelTestExecution { Where-Object { $_.IsInstalled } | ForEach-Object { $appIdByName[$_.Name] = $_.AppId } - $cleanTenantInfo = @( - $tenantInfo | - Where-Object { $_.Id -ne $parameters.tenant } - ) - # Enable only with the AL authentication uptake; infrastructure alone must not add test lanes. - $cleanCodeunitExecution = (Get-ALGoSetting -Key 'enableCleanTestCodeunitExecution') -eq $true - $cleanTenantAppNames = @() - $requiredDisabledWorkItems = @() - if ($cleanCodeunitExecution) { - $cleanTenantAppNames = $appNamesToTest - } - if ($cleanCodeunitExecution -and $testType -ne 'Legacy' -and $tenantInfo.Count -gt 1) { - $sourceTenantInfo = @($tenantInfo | Where-Object { $_.Id -eq $parameters.tenant }) - if ($sourceTenantInfo.Count -ne 1 -or [string]::IsNullOrWhiteSpace($sourceTenantInfo[0].DatabaseName)) { - throw "Could not determine the database name for source tenant '$($parameters.tenant)'." - } - if (@($tenantInfo | Where-Object { - [string]::IsNullOrWhiteSpace($_.Id) -or [string]::IsNullOrWhiteSpace($_.DatabaseName) - }).Count -gt 0 -or - @($tenantInfo.Id | Sort-Object -Unique).Count -ne $tenantInfo.Count -or - @($tenantInfo.DatabaseName | Sort-Object -Unique).Count -ne $tenantInfo.Count) { - throw "Discovery requires non-empty, unique tenant IDs and database names." - } - - # Discovery executes OnRun triggers. Keep the primary fixture untouched and restore - # the discovery worker before any template copy or test dispatch can observe its writes. - $discoveryTenant = $cleanTenantInfo[0] - $discoveryParameters = $parameters.Clone() - $discoveryParameters["tenant"] = $discoveryTenant.Id - try { - $requiredDisabledWorkItems = @( - Get-RequiredDisabledWorkItems -Parameters $discoveryParameters -TestType $testType ` - -AppNamesToTest $appNamesToTest -AppIdByName $appIdByName - ) - } - finally { - Reset-BcTestTenant -ContainerName $parameters.containerName -Tenant $discoveryTenant.Id ` - -TenantDatabaseName $discoveryTenant.DatabaseName -TemplateDatabaseName $sourceTenantInfo[0].DatabaseName - } - } elseif ($cleanCodeunitExecution) { - $requiredDisabledWorkItems = @( - Get-RequiredDisabledWorkItems -Parameters $parameters -TestType $testType ` - -AppNamesToTest $appNamesToTest -AppIdByName $appIdByName - ) - } - $templateDatabaseName = "" - try { - if ($requiredDisabledWorkItems.Count -gt 0) { - if ($cleanTenantInfo.Count -eq 0) { - throw "Clean RequiredTestIsolation=Disabled execution requires at least one secondary tenant." - } - Write-Host "Preparing clean-tenant execution for $($requiredDisabledWorkItems.Count) RequiredTestIsolation=Disabled codeunit(s)." - $sourceTenantInfo = @($tenantInfo | Where-Object { $_.Id -eq $parameters.tenant }) | Select-Object -First 1 - if (-not $sourceTenantInfo -or [string]::IsNullOrEmpty($sourceTenantInfo.DatabaseName)) { - throw "Could not determine the database name for source tenant '$($parameters.tenant)'." - } - $templateDatabaseName = New-BcTestTenantTemplate -ContainerName $parameters.containerName -SourceDatabaseName $sourceTenantInfo.DatabaseName - } - # dispatched=true marks "we started the foreach" - lets concurrent reads notice an in-flight # run. completed=false stays false until wait+merge finish; only then is finalResult valid. $state = [PSCustomObject]@{ @@ -1396,125 +928,119 @@ function Invoke-ParallelTestExecution { } $state | ConvertTo-Json -Depth 5 | Set-Content $stateFile -Force - if ($requiredDisabledWorkItems.Count -gt 0) { - try { - $requiredDisabledPassed = Invoke-RequiredDisabledTestExecution -Parameters $parameters ` - -WorkItems $requiredDisabledWorkItems -TenantInfo $cleanTenantInfo ` - -TemplateDatabaseName $templateDatabaseName -ScriptPath $scriptPath -TestType $testType - if (-not $requiredDisabledPassed) { - $state.hasFailures = $true - } + # Legacy has no test-type selector, so required isolation cannot filter its codeunits. + $phases = if ($testType -eq 'Legacy') { @('Codeunit') } else { @('Codeunit', 'Disabled') } + $resultSuffixes = @() + foreach ($phase in $phases) { + Write-Host "Starting $phase app-level test phase ($testType)." + $phaseParameters = $parameters.Clone() + if ($phase -eq 'Disabled') { + $phaseParameters['requiredTestIsolation'] = 'Disabled' + $phaseParameters['testRunnerCodeunitId'] = '130451' } - finally { - foreach ($cleanTenant in $cleanTenantInfo) { - Reset-BcTestTenant -ContainerName $parameters.containerName -Tenant $cleanTenant.Id ` - -TenantDatabaseName $cleanTenant.DatabaseName -TemplateDatabaseName $templateDatabaseName - } + # Retry limits are per app and phase; the job-wide rerun budget and failures carry over. + $state.retried = @{} + $state.retryTenant = @{} + $state.rerunDone = @{} + + # Single dispatch loop, FIFO. TestConfiguration.json lists the smallest app first (a cheap + # serial warmup) and the rest longest-first (LPT, keeps the tail short). The retry cap lives in + # Receive-TestJobResult: an app already in $state.retried is classified as Failed on a re-fail. + $pending = @($appNamesToTest) + + # Run the first app alone and await it to warm the container before parallelizing the rest. + # No-op for single-app/single-tenant. + if ($phase -eq 'Codeunit') { + $pending = @(Invoke-WarmupDispatch -Parameters $phaseParameters -Pending $pending -AppIdByName $appIdByName ` + -Tenants $tenants -ScriptPath $scriptPath -TestType $testType -State $state) } - } - # Single dispatch loop, FIFO. TestConfiguration.json lists the smallest app first (a cheap - # serial warmup) and the rest longest-first (LPT, keeps the tail short). The retry cap lives in - # Receive-TestJobResult: an app already in $state.retried is classified as Failed on a re-fail. - $pending = @($appNamesToTest) - - # Run the first app alone and await it to warm the container before parallelizing the rest. - # No-op for single-app/single-tenant. - $pending = @(Invoke-WarmupDispatch -Parameters $parameters -Pending $pending -AppIdByName $appIdByName ` - -Tenants $tenants -ScriptPath $scriptPath -TestType $testType -State $state ` - -CleanTenantAppNames $cleanTenantAppNames) - - $rerunSuffixes = @() - - while ($pending.Count -gt 0 -or $state.jobs.Count -gt 0 -or $state.transient.Count -gt 0 -or $state.rerun.Count -gt 0) { - # Promote any transient failures back into the dispatch queue. They go to the FRONT: - # a platform race normally kills a job within a minute of dispatch, so the victim is - # almost always one of the first (i.e. longest) apps. Appending it instead would - # restart the longest app only after every other app had been dispatched, adding its - # full duration to the critical path. - if ($state.transient.Count -gt 0) { - $toRetry = @($state.transient) - $state.transient = @() - $retryAppNames = @($toRetry | ForEach-Object { $_.Key }) - Write-Host "Re-queueing $($toRetry.Count) app(s) after transient platform race: $($retryAppNames -join ', ')" - foreach ($transient in $toRetry) { - $appName = $transient.Key - $state.retried[$appName] = $true - $state.retryTenant[$appName] = $transient.Tenant - # A transient retry goes out through the normal queue and so writes to a TENANT - # result file. Tenant files are merged before rerun files, so any rerun file this - # app already produced would overwrite the newer result - drop it. - if ($state.rerunDone.ContainsKey($appName)) { - Remove-RerunResultFile -parameters $parameters -suffix $state.rerunDone[$appName] + $rerunSuffixes = @() + + while ($pending.Count -gt 0 -or $state.jobs.Count -gt 0 -or $state.transient.Count -gt 0 -or $state.rerun.Count -gt 0) { + # Promote any transient failures back into the dispatch queue. They go to the FRONT: + # a platform race normally kills a job within a minute of dispatch, so the victim is + # almost always one of the first (i.e. longest) apps. Appending it instead would + # restart the longest app only after every other app had been dispatched, adding its + # full duration to the critical path. + if ($state.transient.Count -gt 0) { + $toRetry = @($state.transient) + $state.transient = @() + $retryAppNames = @($toRetry | ForEach-Object { $_.Key }) + Write-Host "Re-queueing $($toRetry.Count) app(s) after transient platform race: $($retryAppNames -join ', ')" + foreach ($transient in $toRetry) { + $appName = $transient.Key + $state.retried[$appName] = $true + $state.retryTenant[$appName] = $transient.Tenant + # A transient retry goes out through the normal queue and so writes to a TENANT + # result file. Tenant files are merged before rerun files, so any rerun file this + # app already produced would overwrite the newer result - drop it. + if ($state.rerunDone.ContainsKey($appName)) { + Remove-RerunResultFile -parameters $phaseParameters -suffix $state.rerunDone[$appName] + } } + $pending = @($retryAppNames) + @($pending) } - $pending = @($retryAppNames) + @($pending) - } - - # Reruns take priority over the normal queue, for the same tail-latency reason as above: - # a failure is usually discovered late, so deferring its rerun would extend the run. - if ($state.rerun.Count -gt 0) { - $rerunItem = $state.rerun[0] - $state.rerun = @($state.rerun | Select-Object -Skip 1) - $rerunSuffixes += $rerunItem.suffix - - # Never reuse the tenant the app just failed on: tests are not guaranteed to clean up, - # so its residue could re-trigger the same failure and make the rerun meaningless. - $tenant = Wait-ForFreeTenant -state $state -tenants $tenants -excludeTenant $rerunItem.excludeTenant - Start-TestAppDispatch -Parameters $parameters -AppName $rerunItem.appName -AppId $appIdByName[$rerunItem.appName] ` - -Tenant $tenant -ScriptPath $scriptPath -TestType $testType -State $state ` - -Verb 'Re-running' -FileSuffix $rerunItem.suffix ` - -SkipAutomaticDisabledPass:$cleanCodeunitExecution - continue - } - if ($pending.Count -gt 0) { - $appName = $pending[0] - $pending = @($pending | Select-Object -Skip 1) - $appId = $appIdByName[$appName] - if (-not $appId) { - Write-Host "WARNING: Could not resolve appId for '$appName'; skipping" - $state.hasFailures = $true + # Reruns take priority over the normal queue, for the same tail-latency reason as above: + # a failure is usually discovered late, so deferring its rerun would extend the run. + if ($state.rerun.Count -gt 0) { + $rerunItem = $state.rerun[0] + $state.rerun = @($state.rerun | Select-Object -Skip 1) + $rerunSuffixes += $rerunItem.suffix + + # Never reuse the tenant the app just failed on: tests are not guaranteed to clean up, + # so its residue could re-trigger the same failure and make the rerun meaningless. + $tenant = Wait-ForFreeTenant -state $state -tenants $tenants -excludeTenant $rerunItem.excludeTenant + Start-TestAppDispatch -Parameters $phaseParameters -AppName $rerunItem.appName -AppId $appIdByName[$rerunItem.appName] ` + -Tenant $tenant -ScriptPath $scriptPath -TestType $testType -State $state ` + -Verb 'Re-running' -FileSuffix $rerunItem.suffix ` + -SkipAutomaticDisabledPass continue } - $verb = if ($state.retried.ContainsKey($appName)) { 'Re-dispatching' } else { 'Dispatching' } - $tenant = if ($state.retryTenant.ContainsKey($appName)) { - Wait-ForSpecificTenant -state $state -tenants $tenants -tenant $state.retryTenant[$appName] + if ($pending.Count -gt 0) { + $appName = $pending[0] + $pending = @($pending | Select-Object -Skip 1) + $appId = $appIdByName[$appName] + if (-not $appId) { + Write-Host "WARNING: Could not resolve appId for '$appName'; skipping" + $state.hasFailures = $true + continue + } + + $verb = if ($state.retried.ContainsKey($appName)) { 'Re-dispatching' } else { 'Dispatching' } + $tenant = if ($state.retryTenant.ContainsKey($appName)) { + Wait-ForSpecificTenant -state $state -tenants $tenants -tenant $state.retryTenant[$appName] + } else { + Wait-ForFreeTenant -state $state -tenants $tenants + } + Start-TestAppDispatch -Parameters $phaseParameters -AppName $appName -AppId $appId -Tenant $tenant ` + -ScriptPath $scriptPath -TestType $testType -State $state ` + -SkipAutomaticDisabledPass -Verb $verb } else { - Wait-ForFreeTenant -state $state -tenants $tenants + # Nothing left to dispatch; drain any still-running jobs. New transient failures and + # reruns discovered here are picked up at the top of the next loop iteration. + # Wait-ForAllTestJobs records failures on $state directly. + Write-Host "All apps dispatched. Waiting for in-flight jobs to complete..." + $null = Wait-ForAllTestJobs -state $state } - Start-TestAppDispatch -Parameters $parameters -AppName $appName -AppId $appId -Tenant $tenant ` - -ScriptPath $scriptPath -TestType $testType -State $state ` - -SkipAutomaticDisabledPass:$cleanCodeunitExecution -Verb $verb - } else { - # Nothing left to dispatch; drain any still-running jobs. New transient failures and - # reruns discovered here are picked up at the top of the next loop iteration. - # Wait-ForAllTestJobs records failures on $state directly. - Write-Host "All apps dispatched. Waiting for in-flight jobs to complete..." - $null = Wait-ForAllTestJobs -state $state } - } - $allPassed = -not $state.hasFailures - - Merge-TenantTestResults -parameters $parameters -tenants $tenants ` - -workItems $requiredDisabledWorkItems -rerunSuffixes $rerunSuffixes + $resultSuffixes += @(@($tenants) + @($rerunSuffixes) | ForEach-Object { + if ($phase -eq 'Disabled') { "disabled-$_" } else { $_ } + }) + Write-Host "Completed $phase app-level test phase ($testType), including retries." + } - # Persist final result and mark complete so subsequent override invocations short-circuit - # to this value (and not the placeholder we wrote before dispatch). - $state.finalResult = $allPassed - $state.completed = $true - $state | ConvertTo-Json -Depth 5 | Set-Content $stateFile -Force + $allPassed = -not $state.hasFailures + Merge-TenantTestResults -parameters $parameters -resultSuffixes $resultSuffixes - return $allPassed - } - finally { - if ($templateDatabaseName) { - Remove-BcTestTenantTemplate -ContainerName $parameters.containerName ` - -TemplateDatabaseName $templateDatabaseName - } - } + # Cache only after both phases and their result merge finish. + $state.finalResult = $allPassed + $state.completed = $true + $state | ConvertTo-Json -Depth 5 | Set-Content $stateFile -Force + return $allPassed } <# @@ -1564,4 +1090,4 @@ function Invoke-PerProjectTestRun { return (. $script -parameters $parameters -TestType $testType -AppNamesToTest $appNamesToTest) } -Export-ModuleMember -Function Invoke-ParallelTestExecution, Get-AvailableBcTenants, Get-CachedTestRunResult, Get-InstalledTestAppNames, Get-AppNamesForBucket, Invoke-PerProjectTestRun, Get-AppNameFromMetadata, Get-DisabledTestsForApp, Reset-BcTestTenant, Invoke-WarmupDispatch, Merge-TestResultFiles, Get-AppRerunBudget, Test-TransientTestFailure +Export-ModuleMember -Function Invoke-ParallelTestExecution, Get-AvailableBcTenants, Get-CachedTestRunResult, Get-InstalledTestAppNames, Get-AppNamesForBucket, Invoke-PerProjectTestRun, Get-AppNameFromMetadata, Get-DisabledTestsForApp, Invoke-WarmupDispatch, Merge-TestResultFiles, Get-AppRerunBudget, Test-TransientTestFailure diff --git a/build/scripts/RunTestsInBcContainer.ps1 b/build/scripts/RunTestsInBcContainer.ps1 index 51067229314..fa76ea5c3cb 100644 --- a/build/scripts/RunTestsInBcContainer.ps1 +++ b/build/scripts/RunTestsInBcContainer.ps1 @@ -106,7 +106,7 @@ if (($null -ne $TestType) -and ($TestType -ne "Legacy")) { $parameters["testType"] = $TestType } -$parameters["disabledTests"] = @(Get-DisabledTestsForApp -AppName $parameters["appName"]) +$parameters["disabledTests"] = @(Get-DisabledTestsForApp -AppName $parameters["appName"] -Country (Get-ALGoSetting -Key 'country')) $parameters["renewClientContextBetweenTests"] = $true # When invoked from the per-project override on the parent process, $AppNamesToTest contains @@ -125,7 +125,7 @@ $isRequiredDisabledRun = $parameters.ContainsKey("requiredTestIsolation") -and $ $result = Invoke-TestsWithReruns -parameters $parameters -maxAttempts 1 # Preserve the old sequential fallback. Parallel project execution defers this pass to the -# clean-tenant codeunit scheduler in ParallelTestExecution.psm1. +# second app-level phase in ParallelTestExecution.psm1. if ($TestType -eq "UnitTest" -and -not $SkipAutomaticDisabledPass -and -not $isRequiredDisabledRun) { Write-Host "Running DisableTestIsolation pass for UnitTest" $parameters["requiredTestIsolation"] = "Disabled" diff --git a/build/scripts/tests/ParallelTestExecution.Test.ps1 b/build/scripts/tests/ParallelTestExecution.Test.ps1 index 5d434bb2ad5..2509b0eef12 100644 --- a/build/scripts/tests/ParallelTestExecution.Test.ps1 +++ b/build/scripts/tests/ParallelTestExecution.Test.ps1 @@ -62,7 +62,6 @@ Describe "ParallelTestExecution churn selection" { switch ($Key) { 'testType' { 'IntegrationTest' } 'country' { 'w1' } - 'enableCleanTestCodeunitExecution' { $true } 'enableChurnBasedTesting' { $true } } } @@ -84,8 +83,6 @@ Describe "ParallelTestExecution churn selection" { [PSCustomObject]@{ Name = $_; AppId = "$_-id"; IsInstalled = $true } } } - Mock -ModuleName ParallelTestExecution Get-RequiredDisabledWorkItems { @() } - Mock -ModuleName ParallelTestExecution Reset-BcTestTenant { } Mock -ModuleName ParallelTestExecution Invoke-WarmupDispatch { @($Pending) } Mock -ModuleName ParallelTestExecution Wait-ForFreeTenant { 'default' } Mock -ModuleName ParallelTestExecution Start-TestAppDispatch { } @@ -116,22 +113,25 @@ Describe "ParallelTestExecution churn selection" { foreach ($name in $selected) { $name | Should -BeOfType [string] } } - It "logs a narrower proposal but runs the full bucket through discovery, warmup and clean isolation" { + It "logs a narrower proposal but runs the full bucket through warmup and both isolation phases" { Invoke-PerProjectTestRun -parameters @{ containerName = 'selection'; tenant = 'default'; appName = 'Tests B' } | Should -BeTrue - Should -Invoke -ModuleName ParallelTestExecution Get-RequiredDisabledWorkItems -Times 1 -Exactly -ParameterFilter { - ($AppNamesToTest -join ',') -eq 'Tests C,Tests B,Tests A' - } Should -Invoke -ModuleName ParallelTestExecution Invoke-WarmupDispatch -Times 1 -Exactly -ParameterFilter { - ($Pending -join ',') -eq 'Tests C,Tests B,Tests A' -and ($CleanTenantAppNames -join ',') -eq 'Tests C,Tests B,Tests A' + ($Pending -join ',') -eq 'Tests C,Tests B,Tests A' } - Should -Invoke -ModuleName ParallelTestExecution Start-TestAppDispatch -Times 3 -Exactly -ParameterFilter { + Should -Invoke -ModuleName ParallelTestExecution Start-TestAppDispatch -Times 6 -Exactly -ParameterFilter { $AppName -in @('Tests C', 'Tests B', 'Tests A') -and $SkipAutomaticDisabledPass } - Should -Invoke -ModuleName ParallelTestExecution Start-TestAppDispatch -Times 1 -Exactly -ParameterFilter { + Should -Invoke -ModuleName ParallelTestExecution Start-TestAppDispatch -Times 2 -Exactly -ParameterFilter { $AppName -eq 'Tests B' } + Should -Invoke -ModuleName ParallelTestExecution Start-TestAppDispatch -Times 3 -Exactly -ParameterFilter { + -not $Parameters.ContainsKey('requiredTestIsolation') + } + Should -Invoke -ModuleName ParallelTestExecution Start-TestAppDispatch -Times 3 -Exactly -ParameterFilter { + $Parameters['requiredTestIsolation'] -eq 'Disabled' -and $Parameters['testRunnerCodeunitId'] -eq '130451' + } Should -Invoke -ModuleName BuildOptimization Get-AffectedAppNames -Times 1 -Exactly -ParameterFilter { $BaseFolder -eq $script:selectionRepoRoot } @@ -158,6 +158,9 @@ Describe "ParallelTestExecution churn selection" { Should -BeTrue $script:selectionLog | Should -Contain 'Country: w1 | Test type: Legacy | Bucket: 2' + Should -Invoke -ModuleName ParallelTestExecution Start-TestAppDispatch -Times 3 -Exactly -ParameterFilter { + -not $Parameters.ContainsKey('requiredTestIsolation') + } } It "runs the full bucket without computing or using affected apps when the setting is " -ForEach @( @@ -172,10 +175,7 @@ Describe "ParallelTestExecution churn selection" { Should -BeTrue Should -Invoke -ModuleName BuildOptimization Get-AffectedAppNames -Times 0 -Exactly - Should -Invoke -ModuleName ParallelTestExecution Get-RequiredDisabledWorkItems -Times 1 -Exactly -ParameterFilter { - ($AppNamesToTest -join ',') -eq 'Tests C,Tests B,Tests A' - } - Should -Invoke -ModuleName ParallelTestExecution Start-TestAppDispatch -Times 3 -Exactly + Should -Invoke -ModuleName ParallelTestExecution Start-TestAppDispatch -Times 6 -Exactly $script:selectionLog | Should -Contain 'Churn-based testing: Disabled; full bucket' $script:selectionLog | Should -Contain 'Candidates: 3 | Would run: 3 | Would skip: 0' } @@ -191,8 +191,7 @@ Describe "ParallelTestExecution churn selection" { Should -Be $Passed } Should -Invoke -ModuleName BuildOptimization Get-AffectedAppNames -Times 1 -Exactly - Should -Invoke -ModuleName ParallelTestExecution Get-RequiredDisabledWorkItems -Times 1 -Exactly - Should -Invoke -ModuleName ParallelTestExecution Start-TestAppDispatch -Times 3 -Exactly + Should -Invoke -ModuleName ParallelTestExecution Start-TestAppDispatch -Times 6 -Exactly Should -Invoke -ModuleName BuildOptimization Write-Host -Times 1 -Exactly -ParameterFilter { $Object -eq 'Test app selection' } @@ -213,11 +212,8 @@ Describe "ParallelTestExecution churn selection" { Should -Invoke -ModuleName BuildOptimization Get-AffectedAppNames -Times 1 -Exactly Should -Invoke -ModuleName ParallelTestExecution Get-InstalledTestAppNames -Times 1 -Exactly Should -Invoke -ModuleName ParallelTestExecution Get-AvailableBcTenantInfo -Times 1 -Exactly - Should -Invoke -ModuleName ParallelTestExecution Get-RequiredDisabledWorkItems -Times 1 -Exactly -ParameterFilter { - ($AppNamesToTest -join ',') -eq 'Tests C,Tests B,Tests A' - } Should -Invoke -ModuleName ParallelTestExecution Invoke-WarmupDispatch -Times 1 -Exactly - Should -Invoke -ModuleName ParallelTestExecution Start-TestAppDispatch -Times 3 -Exactly + Should -Invoke -ModuleName ParallelTestExecution Start-TestAppDispatch -Times 6 -Exactly $script:selectionLog | Should -Contain 'Candidates: 3 | Would run: 0 | Would skip: 3' $script:selectionLog | Should -Contain ' No test apps proposed.' $script:selectionLog | Should -Contain 'Logging only: full bucket will run (3 test apps).' @@ -232,7 +228,6 @@ Describe "ParallelTestExecution churn selection" { Should -BeTrue Test-Path (Join-Path $env:RUNNER_TEMP 'parallelTests_selection.json') | Should -BeFalse Should -Invoke -ModuleName BuildOptimization Get-AffectedAppNames -Times 0 -Exactly - Should -Invoke -ModuleName ParallelTestExecution Get-RequiredDisabledWorkItems -Times 0 -Exactly Should -Invoke -ModuleName ParallelTestExecution Start-TestAppDispatch -Times 0 -Exactly } @@ -255,10 +250,7 @@ Describe "ParallelTestExecution churn selection" { } Invoke-PerProjectTestRun -parameters @{ containerName = 'selection'; tenant = 'default'; appName = 'Tests A' } | Should -BeTrue - Should -Invoke -ModuleName ParallelTestExecution Get-RequiredDisabledWorkItems -Times 1 -Exactly -ParameterFilter { - ($AppNamesToTest -join ',') -eq 'Tests C,Tests B,Tests A' - } - Should -Invoke -ModuleName ParallelTestExecution Start-TestAppDispatch -Times 3 -Exactly + Should -Invoke -ModuleName ParallelTestExecution Start-TestAppDispatch -Times 6 -Exactly $script:selectionLog | Should -Contain 'Churn-based testing: Enabled; full bucket (RunAll)' $script:selectionLog | Should -Contain 'Candidates: 3 | Would run: 3 | Would skip: 0' } @@ -278,17 +270,12 @@ Describe "ParallelTestExecution churn selection" { Should -Invoke -ModuleName BuildOptimization Write-Host -Times 1 -ParameterFilter { $Object -like '*git diff failed*' } - Should -Invoke -ModuleName ParallelTestExecution Start-TestAppDispatch -Times 3 -Exactly + Should -Invoke -ModuleName ParallelTestExecution Start-TestAppDispatch -Times 6 -Exactly } } Describe "ParallelTestExecution app-name resolution" { - BeforeEach { - Mock -ModuleName ParallelTestExecution Get-ALGoSetting { $true } -ParameterFilter { - $Key -eq 'enableCleanTestCodeunitExecution' - } - } BeforeAll { # Get-BcContainerAppInfo comes from BcContainerHelper, which is present when the module # runs inside a BC container but is NOT loaded in the "Run PS Tests" runner. Pester cannot @@ -384,72 +371,6 @@ Describe "ParallelTestExecution app-name resolution" { } } - It "uses docker exec for the long-running template database copy" { - InModuleScope ParallelTestExecution { - Mock Invoke-ScriptInBcContainer { 'default-test-template' } - - New-BcTestTenantTemplate -ContainerName 'bc' -SourceDatabaseName 'default' | Should -Be 'default-test-template' - - Should -Invoke Invoke-ScriptInBcContainer -Times 1 -ParameterFilter { - $containerName -eq 'bc' -and $useSession -eq $false - } - } - } - - It "uses docker exec for long-running tenant database refreshes" { - InModuleScope ParallelTestExecution { - Mock Invoke-ScriptInBcContainer { } - - Reset-BcTestTenant -ContainerName 'bc' -Tenant 'tenant2' ` - -TenantDatabaseName 'tenant2' -TemplateDatabaseName 'default-test-template' - - Should -Invoke Invoke-ScriptInBcContainer -Times 1 -ParameterFilter { - $containerName -eq 'bc' -and $useSession -eq $false - } - } - } - - It "removes the clean template when normal app dispatch aborts" { - InModuleScope ParallelTestExecution { - Mock Get-AvailableBcTenantInfo { - @( - [PSCustomObject]@{ Id = 'default'; DatabaseName = 'default' } - [PSCustomObject]@{ Id = 'tenant2'; DatabaseName = 'tenant2' } - ) - } - Mock Get-BcContainerAppInfo { - @([PSCustomObject]@{ IsInstalled = $true; Name = 'Tests'; AppId = 'tests-id' }) - } - Mock Get-RequiredDisabledWorkItems { - @([PSCustomObject]@{ - Key = 'Tests::500' - AppName = 'Tests' - AppId = 'tests-id' - CodeunitId = '500' - CodeunitName = 'API E2E' - TestCount = 2 - }) - } - Mock New-BcTestTenantTemplate { 'default-test-template' } - Mock Invoke-RequiredDisabledTestExecution { $true } - Mock Reset-BcTestTenant { } - Mock Invoke-WarmupDispatch { @($Pending) } - Mock Wait-ForFreeTenant { 'default' } - Mock Start-TestAppDispatch { throw 'dispatch failed' } - Mock Remove-BcTestTenantTemplate { } - - { - Invoke-ParallelTestExecution -parameters @{ - containerName = "ut-$([guid]::NewGuid().ToString('N'))" - tenant = 'default' - } -scriptPath 'unused.ps1' -testType 'IntegrationTest' -appNamesToTest @('Tests') - } | Should -Throw '*dispatch failed*' - - Should -Invoke Remove-BcTestTenantTemplate -Times 1 -ParameterFilter { - $TemplateDatabaseName -eq 'default-test-template' - } - } - } } Describe "ParallelTestExecution concurrent posting routing" { @@ -602,7 +523,6 @@ Describe "ParallelTestExecution transient retry scheduling" { [PSCustomObject]@{ IsInstalled = $true; Name = $_; AppId = "id-$_" } } } - Mock Get-RequiredDisabledWorkItems { @() } Mock Wait-ForFreeTenant { 'default' } Mock Wait-ForSpecificTenant { 'default' } Mock Wait-ForAllTestJobs { $true } @@ -627,100 +547,131 @@ Describe "ParallelTestExecution transient retry scheduling" { } } -Describe "ParallelTestExecution RequiredTestIsolation discovery" { - BeforeAll { - Import-Module (Join-Path $PSScriptRoot '../ParallelTestExecution.psm1') -Force +Describe "ParallelTestExecution disabled-test exclusions" { + It "applies only the two AU G/L-entry exclusions while retaining global exclusions" { + InModuleScope ParallelTestExecution { + $repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..\..')).Path + $script:disabledTestRoot = Join-Path $TestDrive 'api-exclusions' + $disabledFolder = Join-Path $script:disabledTestRoot 'DisabledTests' + $null = New-Item -Path $disabledFolder -ItemType Directory -Force + foreach ($app in @('_Exclude_APIV1__Tests', '_Exclude_APIV2__Tests')) { + Copy-Item -Path (Join-Path $repoRoot "src\DisabledTests\$app") -Destination $disabledFolder -Recurse + } + Mock Get-BaseFolder { $script:disabledTestRoot } + foreach ($api in @( + @{ App = '_Exclude_APIV1_ Tests'; Id = 139730 } + @{ App = '_Exclude_APIV2_ Tests'; Id = 139830 } + )) { + $globalEntries = @(Get-DisabledTestsForApp -AppName $api.App) + foreach ($country in @('AU', 'au', 'US', 'NZ', 'W1', '')) { + $entries = @(Get-DisabledTestsForApp -AppName $api.App -Country $country) + $scoped = @($entries | Where-Object { $_.codeunitId -eq $api.Id }) + if ($country -eq 'AU') { + $scoped.Count | Should -Be 1 + $scoped[0].method | Should -Be 'TestGetGLEntries' + $entries.Count | Should -Be ($globalEntries.Count + 1) + } else { + $scoped.Count | Should -Be 0 + $entries.Count | Should -Be $globalEntries.Count + } + @($entries | Where-Object { $_.codeunitId -ne $api.Id } | ConvertTo-Json -Compress) | + Should -Be @($globalEntries | ConvertTo-Json -Compress) + } + } + } } - It "flattens discovered codeunits and excludes codeunits without enabled methods" { + It "loads all app exclusions without consulting country settings" { InModuleScope ParallelTestExecution { - $discovered = @( - [PSCustomObject]@{ Id = '100'; Name = 'Direct'; Tests = @('A', 'B') } - [PSCustomObject]@{ - Group = 'G' - Codeunits = @( - [PSCustomObject]@{ Id = '200'; Name = 'Grouped'; Tests = @('C') } - [PSCustomObject]@{ Id = '300'; Name = 'Disabled'; Tests = @() } - ) - } - ) + $script:disabledTestRoot = Join-Path $TestDrive 'exclusions' + Mock Get-BaseFolder { $script:disabledTestRoot } + Mock Get-ALGoSetting { throw 'Exclusions must not depend on country settings' } + $appFolder = Join-Path $script:disabledTestRoot 'DisabledTests\Example_Tests' + $null = New-Item -Path $appFolder -ItemType Directory -Force + '[{"codeunitId":500,"method":"First"}]' | + Set-Content (Join-Path $appFolder 'first.json') + '[{"codeunitId":501,"method":"*"}]' | + Set-Content (Join-Path $appFolder 'second.json') - $result = @(ConvertTo-RequiredDisabledWorkItems -DiscoveredTests $discovered -AppName 'API Tests' -AppId 'app-id') + $result = @(Get-DisabledTestsForApp -AppName 'Example Tests') $result.Count | Should -Be 2 - $result[0].Key | Should -Be 'API Tests::100' - $result[0].TestCount | Should -Be 2 - $result[1].CodeunitId | Should -Be '200' + ($result | Where-Object codeunitId -eq 500).method | Should -Be 'First' + ($result | Where-Object codeunitId -eq 501).method | Should -Be '*' + @(Get-DisabledTestsForApp -AppName 'Other Tests').Count | Should -Be 0 + Should -Invoke Get-ALGoSetting -Times 0 } } +} - It "discovers selected apps once each while preserving isolation, lane and exclusion filters" { +Describe "ParallelTestExecution app-level phases" { + BeforeEach { InModuleScope ParallelTestExecution { - Mock Get-ParametersForCommand { @{ containerName = 'c'; tenant = 'default' } } - Mock Get-DisabledTestsForApp { - @([PSCustomObject]@{ codeunitId = 999; method = 'DisabledMethod' }) - } - Mock Get-TestsFromBcContainer { - @([PSCustomObject]@{ Id = '500'; Name = 'API E2E'; Tests = @('Create', 'Modify') }) + $script:dispatches = [System.Collections.Generic.List[object]]::new() + $script:active = [System.Collections.Generic.List[int]]::new() + $script:outcomes = @{} + $script:attempts = @{} + $script:testParameters = @{ + containerName = "ut-$([guid]::NewGuid().ToString('N'))" + tenant = 'default' } - - $result = @( - Get-RequiredDisabledWorkItems -Parameters @{ containerName = 'c'; tenant = 'default' } ` - -TestType 'IntegrationTest' -AppNamesToTest @('API Tests', 'New API Tests') ` - -AppIdByName @{ 'API Tests' = 'app-id'; 'New API Tests' = 'new-app-id'; 'Unselected Tests' = 'other-id' } - ) - - $result.Count | Should -Be 2 - $result[0].CodeunitId | Should -Be '500' - $result[1].AppName | Should -Be 'New API Tests' - Should -Invoke Get-TestsFromBcContainer -Times 1 -ParameterFilter { - $extensionId -eq 'app-id' -and - $requiredTestIsolation -eq 'Disabled' -and - $testType -eq 'IntegrationTest' -and - $disabledTests.Count -eq 1 + Mock Get-AvailableBcTenantInfo { + @( + [PSCustomObject]@{ Id = 'default'; DatabaseName = 'default' } + [PSCustomObject]@{ Id = 'tenant2'; DatabaseName = 'tenant2' } + ) } - Should -Invoke Get-TestsFromBcContainer -Times 1 -Exactly -ParameterFilter { - $extensionId -eq 'new-app-id' -and - $requiredTestIsolation -eq 'Disabled' -and - $testType -eq 'IntegrationTest' -and - $disabledTests.Count -eq 1 + Mock Get-BcContainerAppInfo { + @('A', 'B', 'C') | ForEach-Object { + [PSCustomObject]@{ IsInstalled = $true; Name = $_; AppId = "id-$_" } + } } - Should -Invoke Get-TestsFromBcContainer -Times 0 -ParameterFilter { - $extensionId -eq 'other-id' + Mock Get-AppRerunBudget { 2 } + Mock Start-Sleep {} + Mock Write-Host {} + Mock Merge-TenantTestResults {} + Mock Get-TestsFromBcContainer { throw 'Discovery must not run' } + Mock Invoke-ScriptInBcContainer { throw 'Database resets must not run' } + Mock Start-TestJob { + $phase = if ($parameters['requiredTestIsolation'] -eq 'Disabled') { 'Disabled' } else { 'Codeunit' } + foreach ($id in $script:active) { + $script:dispatches[$id - 1].Phase | Should -Be $phase + } + Get-CachedTestRunResult -ContainerName $parameters.containerName | Should -BeNullOrEmpty + $id = $script:dispatches.Count + 1 + $script:dispatches.Add([PSCustomObject]@{ + Phase = $phase; App = $parameters.appName; Tenant = $tenant + Parameters = $parameters.Clone(); Suffix = $fileSuffix; TestType = $testType + SkipDisabled = $skipAutomaticDisabledPass.IsPresent + }) + $script:active.Add($id) + [PSCustomObject]@{ Id = $id } + } + Mock Get-Job { [PSCustomObject]@{ Id = $Id; State = 'Completed' } } + Mock Wait-Job {} -RemoveParameterType Job + Mock Receive-TestJobResult { + $dispatch = $script:dispatches[$Entry.jobId - 1] + $key = "$($dispatch.Phase):$($dispatch.App)" + $attempt = [int]$script:attempts[$key] + $script:attempts[$key] = $attempt + 1 + $outcome = if ($script:outcomes.ContainsKey($key) -and $attempt -lt $script:outcomes[$key].Count) { + $script:outcomes[$key][$attempt] + } else { 'Passed' } + $script:active.Remove($Entry.jobId) | Out-Null + [PSCustomObject]@{ + Outcome = $outcome; AppName = $Entry.appName; Tenant = $Entry.tenant; JobState = 'Completed' + } } } } - It "does not use unfiltered discovery for Legacy buckets" { + AfterEach { InModuleScope ParallelTestExecution { - Mock Get-ParametersForCommand { @{ containerName = 'c'; tenant = 'default'; testType = 'stale' } } - Mock Get-DisabledTestsForApp { @() } - Mock Get-TestsFromBcContainer { @() } - - $result = @(Get-RequiredDisabledWorkItems -Parameters @{ containerName = 'c' } ` - -TestType 'Legacy' -AppNamesToTest @('Legacy Tests') ` - -AppIdByName @{ 'Legacy Tests' = 'legacy-id' }) - - $result.Count | Should -Be 0 + $tempDir = if ($env:RUNNER_TEMP) { $env:RUNNER_TEMP } elseif ($env:TEMP) { $env:TEMP } else { [IO.Path]::GetTempPath() } + $stateFile = Join-Path $tempDir "parallelTests_$($script:testParameters.containerName).json" + if (Test-Path $stateFile) { Remove-Item $stateFile } Should -Invoke Get-TestsFromBcContainer -Times 0 - } - } -} - -Describe "ParallelTestExecution clean tenant scheduling" { - BeforeAll { - Import-Module (Join-Path $PSScriptRoot '../ParallelTestExecution.psm1') -Force - } - - BeforeEach { - Mock -ModuleName ParallelTestExecution Get-ALGoSetting { $true } -ParameterFilter { - $Key -eq 'enableCleanTestCodeunitExecution' - } - Mock -ModuleName ParallelTestExecution Invoke-ScriptInBcContainer { - throw 'Unexpected unmocked container access.' - } - Mock -ModuleName ParallelTestExecution Reset-BcTestTenant { - throw 'Tenant resets require an explicit test mock.' + Should -Invoke Invoke-ScriptInBcContainer -Times 0 } } @@ -728,701 +679,147 @@ Describe "ParallelTestExecution clean tenant scheduling" { InModuleScope ParallelTestExecution { $previousRunnerTemp = $env:RUNNER_TEMP $previousTemp = $env:TEMP - $containerName = "ut-$([guid]::NewGuid().ToString('N'))" - $stateFile = Join-Path ([System.IO.Path]::GetTempPath()) "parallelTests_$containerName.json" - Mock Get-AvailableBcTenantInfo { - @([PSCustomObject]@{ Id = 'default'; DatabaseName = 'default' }) - } - Mock Get-BcContainerAppInfo { - @([PSCustomObject]@{ IsInstalled = $true; Name = 'Tests'; AppId = 'tests-id' }) - } - Mock Get-RequiredDisabledWorkItems { @() } - Mock Wait-ForFreeTenant { 'default' } - Mock Start-TestAppDispatch { } - Mock Wait-ForAllTestJobs { $true } - Mock Merge-TenantTestResults { } + $stateFile = $null try { $env:RUNNER_TEMP = $null $env:TEMP = $null - $stateFile = Join-Path ([System.IO.Path]::GetTempPath()) "parallelTests_$containerName.json" + $stateFile = Join-Path ([System.IO.Path]::GetTempPath()) ` + "parallelTests_$($script:testParameters.containerName).json" - Invoke-ParallelTestExecution -parameters @{ - containerName = $containerName - tenant = 'default' - } -scriptPath 'unused.ps1' -testType 'IntegrationTest' -appNamesToTest @('Tests') | - Should -BeTrue + Invoke-ParallelTestExecution -parameters $script:testParameters -scriptPath 'unused.ps1' ` + -testType 'IntegrationTest' -appNamesToTest @('A') | Should -BeTrue + $script:dispatches.Phase | Should -Be @('Codeunit', 'Disabled') Test-Path $stateFile | Should -BeTrue - Get-CachedTestRunResult -ContainerName $containerName | Should -BeTrue + $state = Get-Content $stateFile -Raw | ConvertFrom-Json + $state.completed | Should -BeTrue + $state.finalResult | Should -BeTrue + Get-CachedTestRunResult -ContainerName $script:testParameters.containerName | Should -BeTrue } finally { $env:RUNNER_TEMP = $previousRunnerTemp $env:TEMP = $previousTemp - if (Test-Path $stateFile) { + if ($stateFile -and (Test-Path $stateFile)) { Remove-Item $stateFile -Force } } } } - It "does not create a database template when no Disabled-isolation codeunits are enabled" { - InModuleScope ParallelTestExecution { - Mock Get-AvailableBcTenantInfo { - @([PSCustomObject]@{ Id = 'default'; DatabaseName = 'default' }) + It "drains Codeunit work and late retries before the Disabled phase for " -ForEach @( + @{ Lane = 'UnitTest' } + @{ Lane = 'IntegrationTest' } + @{ Lane = 'Uncategorized' } + ) { + InModuleScope ParallelTestExecution -Parameters @{ Lane = $Lane } { + $script:outcomes = @{ 'Codeunit:C' = @('Failed', 'Transient', 'Passed') } + Invoke-ParallelTestExecution -parameters $script:testParameters -scriptPath 'unused.ps1' ` + -testType $Lane -appNamesToTest @('A', 'B', 'C') | Should -BeTrue + + ($script:dispatches | ForEach-Object { "$($_.Phase):$($_.App)" }) | + Should -Be @('Codeunit:A', 'Codeunit:B', 'Codeunit:C', 'Codeunit:C', 'Codeunit:C', + 'Disabled:A', 'Disabled:B', 'Disabled:C') + $script:dispatches[3].Tenant | Should -Not -Be $script:dispatches[2].Tenant + $script:dispatches[4].Tenant | Should -Be $script:dispatches[3].Tenant + foreach ($dispatch in $script:dispatches) { + $dispatch.SkipDisabled | Should -BeTrue + $dispatch.TestType | Should -Be $Lane + $dispatch.Parameters.extensionId | Should -Be "id-$($dispatch.App)" + $dispatch.Parameters.ContainsKey('testCodeunit') | Should -BeFalse + if ($dispatch.Phase -eq 'Disabled') { + $dispatch.Parameters.requiredTestIsolation | Should -Be 'Disabled' + $dispatch.Parameters.testRunnerCodeunitId | Should -Be '130451' + } else { + $dispatch.Parameters.ContainsKey('requiredTestIsolation') | Should -BeFalse + $dispatch.Parameters.ContainsKey('testRunnerCodeunitId') | Should -BeFalse + } } - Mock Get-BcContainerAppInfo { - @([PSCustomObject]@{ IsInstalled = $true; Name = 'Tests'; AppId = 'tests-id' }) + Should -Invoke Write-Host -Times 1 -Exactly -ParameterFilter { + $Object -eq "Starting Codeunit app-level test phase ($Lane)." } - Mock Get-RequiredDisabledWorkItems { @() } - Mock New-BcTestTenantTemplate { throw 'Template must not be created' } - Mock Wait-ForFreeTenant { 'default' } - Mock Start-TestAppDispatch { } - Mock Wait-ForAllTestJobs { $true } - Mock Merge-TenantTestResults { } - - $result = Invoke-ParallelTestExecution -parameters @{ - containerName = "ut-$([guid]::NewGuid().ToString('N'))" - tenant = 'default' - } -scriptPath 'unused.ps1' -testType 'IntegrationTest' -appNamesToTest @('Tests') - - $result | Should -BeTrue - Should -Invoke New-BcTestTenantTemplate -Times 0 - Should -Invoke Get-RequiredDisabledWorkItems -Times 1 -Exactly -ParameterFilter { - $AppNamesToTest.Count -eq 1 -and $AppNamesToTest[0] -eq 'Tests' + Should -Invoke Write-Host -Times 1 -Exactly -ParameterFilter { + $Object -eq "Completed Codeunit app-level test phase ($Lane), including retries." } - Should -Invoke Start-TestAppDispatch -Times 1 -Exactly -ParameterFilter { - $SkipAutomaticDisabledPass + $script:active.Count | Should -Be 0 + Get-CachedTestRunResult -ContainerName $script:testParameters.containerName | Should -BeTrue + Should -Invoke Merge-TenantTestResults -Times 1 -Exactly -ParameterFilter { + ($resultSuffixes -join ',') -eq 'default,tenant2,rerun1,disabled-default,disabled-tenant2' } + Invoke-ParallelTestExecution -parameters $script:testParameters -scriptPath 'unused.ps1' ` + -testType $Lane -appNamesToTest @('A', 'B', 'C') | Should -BeTrue + $script:dispatches.Count | Should -Be 8 } } - Describe "ParallelTestExecution result metadata" { - BeforeAll { - Import-Module (Join-Path $PSScriptRoot '../ParallelTestExecution.psm1') -Force - } - - It "adds app properties to clean-codeunit JUnit suites" { - InModuleScope ParallelTestExecution { - $resultFile = Join-Path ([System.IO.Path]::GetTempPath()) "junit-$([guid]::NewGuid().ToString('N')).xml" - try { - @( - '' - '' - ' ' - ' ' - ' ' - '' - ) | Set-Content -Path $resultFile -Encoding utf8 - - Add-MissingJUnitTestProperties -ResultFile $resultFile -WorkItems @( - [PSCustomObject]@{ - CodeunitId = '139800' - AppId = 'app-id' - AppName = '_Exclude_APIV2_ Tests' - } - ) - - [xml]$xml = Get-Content $resultFile -Raw - $properties = @($xml.testsuites.testsuite.properties.property) - ($properties | Where-Object name -eq 'extensionid').value | Should -Be 'app-id' - ($properties | Where-Object name -eq 'appName').value | Should -Be '_Exclude_APIV2_ Tests' - } finally { - Remove-Item $resultFile -Force -ErrorAction SilentlyContinue - } - } - } - } - - It "defers the automatic Unit disabled pass only for clean-tenant apps" { + It "keeps retries phase-specific while sharing the job-wide budget" { InModuleScope ParallelTestExecution { - $script:skipValues = [System.Collections.Generic.List[bool]]::new() - Mock Start-Sleep { } - Mock Start-TestJob { - $script:skipValues.Add($skipAutomaticDisabledPass.IsPresent) - [PSCustomObject]@{ Id = $script:skipValues.Count } + $script:outcomes = @{ + 'Codeunit:A' = @('Failed', 'Passed') + 'Disabled:A' = @('Failed', 'Transient', 'Passed') } - - $state = [PSCustomObject]@{ jobs = @() } - Start-TestAppDispatch -Parameters @{} -AppName 'Normal Tests' -AppId 'normal-id' ` - -Tenant 'default' -ScriptPath 'runner.ps1' -TestType 'UnitTest' -State $state - Start-TestAppDispatch -Parameters @{} -AppName 'API Tests' -AppId 'api-id' ` - -Tenant 'tenant2' -ScriptPath 'runner.ps1' -TestType 'UnitTest' -State $state ` - -SkipAutomaticDisabledPass - - $script:skipValues | Should -Be @($false, $true) - } - } - - It "loads all app exclusions without consulting country settings" { - InModuleScope ParallelTestExecution { - $script:disabledTestRoot = Join-Path ([System.IO.Path]::GetTempPath()) ([guid]::NewGuid().ToString('N')) - Mock Get-BaseFolder { $script:disabledTestRoot } - Mock Get-ALGoSetting { throw 'Exclusions must not depend on country settings' } - try { - $appFolder = Join-Path $script:disabledTestRoot 'DisabledTests\Example_Tests' - $null = New-Item -Path $appFolder -ItemType Directory -Force - '[{"codeunitId":500,"method":"First"}]' | - Set-Content (Join-Path $appFolder 'first.json') - '[{"codeunitId":501,"method":"*"}]' | - Set-Content (Join-Path $appFolder 'second.json') - - $result = @(Get-DisabledTestsForApp -AppName 'Example Tests') - - $result.Count | Should -Be 2 - $result.codeunitId | Should -Contain 500 - $result.codeunitId | Should -Contain 501 - @(Get-DisabledTestsForApp -AppName 'Other Tests').Count | Should -Be 0 - Should -Invoke Get-ALGoSetting -Times 0 - } finally { - Remove-Item $script:disabledTestRoot -Recurse -Force + Mock Remove-RerunResultFile {} + Invoke-ParallelTestExecution -parameters $script:testParameters -scriptPath 'unused.ps1' ` + -testType 'UnitTest' -appNamesToTest @('A') | Should -BeTrue + ($script:dispatches | ForEach-Object { "$($_.Phase):$($_.App)" }) | + Should -Be @('Codeunit:A', 'Codeunit:A', 'Disabled:A', 'Disabled:A', 'Disabled:A') + Should -Invoke Remove-RerunResultFile -Times 1 -Exactly -ParameterFilter { + $parameters.requiredTestIsolation -eq 'Disabled' -and $suffix -eq 'rerun1' } - } - } - - It "dispatches one codeunit with Disabled isolation" { - InModuleScope ParallelTestExecution { - $script:capturedParameters = $null - - Mock Get-DisabledTestsForApp { @() } - Mock Start-Sleep { } - Mock Start-TestJob { - $script:capturedParameters = $parameters - [PSCustomObject]@{ Id = 42 } - } - - $state = [PSCustomObject]@{ jobs = @() } - $workItem = [PSCustomObject]@{ - Key = 'Tests::500' - AppName = 'Tests' - AppId = 'tests-id' - CodeunitId = '500' - CodeunitName = 'API E2E' + Should -Invoke Merge-TenantTestResults -Times 1 -Exactly -ParameterFilter { + ($resultSuffixes -join ',') -eq 'default,tenant2,rerun1,disabled-default,disabled-tenant2,disabled-rerun1' } - - Start-RequiredDisabledDispatch -Parameters @{ - containerName = 'c' - JUnitResultFileName = 'results.xml' - } -WorkItem $workItem -TenantInfo ([PSCustomObject]@{ - Id = 'tenant2' - DatabaseName = 'tenant2' - }) -ScriptPath 'runner.ps1' ` - -TestType 'IntegrationTest' -State $state - - $script:capturedParameters.testCodeunit | Should -Be '500' - $script:capturedParameters.requiredTestIsolation | Should -Be 'Disabled' - $script:capturedParameters.testRunnerCodeunitId | Should -Be '130451' - $script:capturedParameters.AppendToJUnitResultFile | Should -BeTrue - $state.jobs.Count | Should -Be 1 } } - It "marks scheduler retries as reruns so existing XML entries are replaced" { + It "does not replenish the rerun budget at the phase barrier" { InModuleScope ParallelTestExecution { - $script:capturedParameters = $null - - Mock Get-DisabledTestsForApp { @() } - Mock Reset-BcTestTenant { } - Mock Start-Sleep { } - Mock Start-TestJob { - $script:capturedParameters = $parameters - [PSCustomObject]@{ Id = 42 } - } - - Start-RequiredDisabledDispatch -Parameters @{ containerName = 'c' } -WorkItem ([PSCustomObject]@{ - Key = 'Tests::500' - AppName = 'Tests' - AppId = 'tests-id' - CodeunitId = '500' - CodeunitName = 'API E2E' - }) -TenantInfo ([PSCustomObject]@{ - Id = 'tenant2' - DatabaseName = 'tenant2' - }) -ScriptPath 'runner.ps1' ` - -TestType 'IntegrationTest' -State ([PSCustomObject]@{ jobs = @() }) ` - -Verb 'Re-dispatching' - - $script:capturedParameters.ReRun | Should -BeTrue + Mock Get-AppRerunBudget { 1 } + $script:outcomes = @{ 'Codeunit:A' = @('Failed', 'Passed'); 'Disabled:A' = @('Failed') } + Invoke-ParallelTestExecution -parameters $script:testParameters -scriptPath 'unused.ps1' ` + -testType 'UnitTest' -appNamesToTest @('A') | Should -BeFalse + $script:dispatches.Count | Should -Be 3 + Get-CachedTestRunResult -ContainerName $script:testParameters.containerName | Should -BeFalse } } - It "retries a clean codeunit on its original tenant" { + It "retains a Codeunit failure even when the Disabled phase passes" { InModuleScope ParallelTestExecution { - $script:dispatchTenants = [System.Collections.Generic.List[string]]::new() - $script:firstDispatch = $true - - Mock Reset-BcTestTenant { } - Mock Wait-ForAllTestJobs { $true } - Mock Start-RequiredDisabledDispatch { - $script:dispatchTenants.Add($TenantInfo.Id) - if ($script:firstDispatch) { - $script:firstDispatch = $false - $State.transient = @( - [PSCustomObject]@{ Key = $WorkItem.Key; Tenant = $TenantInfo.Id } - ) - } - } - - $workItem = [PSCustomObject]@{ - Key = 'Tests::500' - AppName = 'Tests' - AppId = 'tests-id' - CodeunitId = '500' - CodeunitName = 'API E2E' - } - $tenantInfo = @( - [PSCustomObject]@{ Id = 'tenant2'; DatabaseName = 'tenant2' } - [PSCustomObject]@{ Id = 'tenant3'; DatabaseName = 'tenant3' } - ) - - $result = Invoke-RequiredDisabledTestExecution -Parameters @{ containerName = 'c' } ` - -WorkItems @($workItem) -TenantInfo $tenantInfo -TemplateDatabaseName 'template' ` - -ScriptPath 'runner.ps1' -TestType 'UnitTest' - - $result | Should -BeTrue - $script:dispatchTenants | Should -Be @('tenant2', 'tenant2') + Mock Get-AppRerunBudget { 0 } + $script:outcomes = @{ 'Codeunit:A' = @('Failed') } + Invoke-ParallelTestExecution -parameters $script:testParameters -scriptPath 'unused.ps1' ` + -testType 'IntegrationTest' -appNamesToTest @('A') | Should -BeFalse + $script:dispatches.Phase | Should -Be @('Codeunit', 'Disabled') } } - It "finishes all tenant resets before dispatching a clean-codeunit batch" { + It "supports one tenant without a separate clean fixture" { InModuleScope ParallelTestExecution { - $script:events = [System.Collections.Generic.List[string]]::new() - Mock Reset-BcTestTenant { - $script:events.Add("reset:$Tenant") - } - Mock Start-RequiredDisabledDispatch { - $script:events.Add("dispatch:$($TenantInfo.Id)") - } - Mock Wait-ForAllTestJobs { } - - $workItems = @( - [PSCustomObject]@{ Key = 'Tests::500'; AppName = 'Tests'; AppId = 'id'; CodeunitId = '500'; CodeunitName = 'A' } - [PSCustomObject]@{ Key = 'Tests::501'; AppName = 'Tests'; AppId = 'id'; CodeunitId = '501'; CodeunitName = 'B' } - ) - $tenantInfo = @( - [PSCustomObject]@{ Id = 'tenant2'; DatabaseName = 'tenant2' } - [PSCustomObject]@{ Id = 'tenant3'; DatabaseName = 'tenant3' } - ) - - Invoke-RequiredDisabledTestExecution -Parameters @{ containerName = 'c' } ` - -WorkItems $workItems -TenantInfo $tenantInfo -TemplateDatabaseName 'template' ` - -ScriptPath 'runner.ps1' -TestType 'UnitTest' | Should -BeTrue - - $script:events | Should -Be @('reset:tenant2', 'reset:tenant3', 'dispatch:tenant2', 'dispatch:tenant3') + Mock Get-AvailableBcTenantInfo { [PSCustomObject]@{ Id = 'default'; DatabaseName = 'default' } } + Invoke-ParallelTestExecution -parameters $script:testParameters -scriptPath 'unused.ps1' ` + -testType 'Uncategorized' -appNamesToTest @('A', 'B') | Should -BeTrue + $script:dispatches.Phase | Should -Be @('Codeunit', 'Codeunit', 'Disabled', 'Disabled') } } - It "preserves configured Task Scheduler state during clean and ordinary execution" -ForEach @( - @{ Enabled = $false } - @{ Enabled = $true } - ) { - InModuleScope ParallelTestExecution -Parameters @{ Enabled = $Enabled } { - param($Enabled) - - Mock Get-AvailableBcTenantInfo { - @( - [PSCustomObject]@{ Id = 'default'; DatabaseName = 'default' } - [PSCustomObject]@{ Id = 'tenant2'; DatabaseName = 'tenant2' } - ) - } - Mock Get-BcContainerAppInfo { - @([PSCustomObject]@{ IsInstalled = $true; Name = 'Tests'; AppId = 'tests-id' }) - } - Mock Get-RequiredDisabledWorkItems { - @([PSCustomObject]@{ - Key = 'Tests::500' - AppName = 'Tests' - AppId = 'tests-id' - CodeunitId = '500' - CodeunitName = 'API E2E' - TestCount = 2 - }) - } - $script:taskSchedulerEnabled = $Enabled - $script:expectedTaskSchedulerEnabled = $Enabled - Mock New-BcTestTenantTemplate { 'default-test-template' } - Mock Wait-ForFreeTenant { 'default' } - Mock Start-TestAppDispatch { - $script:taskSchedulerEnabled | Should -Be $script:expectedTaskSchedulerEnabled - } - Mock Wait-ForAllTestJobs { $true } - Mock Invoke-RequiredDisabledTestExecution { - $script:taskSchedulerEnabled | Should -Be $script:expectedTaskSchedulerEnabled - $true - } - Mock Reset-BcTestTenant { - $script:taskSchedulerEnabled | Should -Be $script:expectedTaskSchedulerEnabled - } - Mock Remove-BcTestTenantTemplate { } - Mock Merge-TenantTestResults { } - - $result = Invoke-ParallelTestExecution -parameters @{ - containerName = "ut-$([guid]::NewGuid().ToString('N'))" - tenant = 'default' - } -scriptPath 'unused.ps1' -testType 'IntegrationTest' -appNamesToTest @('Tests') - - $result | Should -BeTrue - Should -Invoke Get-RequiredDisabledWorkItems -Times 1 -Exactly -ParameterFilter { - $AppNamesToTest.Count -eq 1 -and $AppNamesToTest[0] -eq 'Tests' - } - Should -Invoke New-BcTestTenantTemplate -Times 1 -ParameterFilter { - $SourceDatabaseName -eq 'default' - } - Should -Invoke Invoke-ScriptInBcContainer -Times 0 - Should -Invoke Reset-BcTestTenant -Times 1 -Exactly -ParameterFilter { - $Tenant -eq 'tenant2' -and - $TenantDatabaseName -eq 'tenant2' -and - $TemplateDatabaseName -eq 'default' - } - Should -Invoke Reset-BcTestTenant -Times 1 -ParameterFilter { - $Tenant -eq 'tenant2' -and - $TenantDatabaseName -eq 'tenant2' -and - $TemplateDatabaseName -eq 'default-test-template' - } - Should -Invoke Invoke-RequiredDisabledTestExecution -Times 1 -ParameterFilter { - $TemplateDatabaseName -eq 'default-test-template' -and - $WorkItems.Count -eq 1 -and - $TenantInfo.Count -eq 1 -and - $TenantInfo[0].Id -eq 'tenant2' - } - Should -Invoke Remove-BcTestTenantTemplate -Times 1 -ParameterFilter { - $TemplateDatabaseName -eq 'default-test-template' - } + It "leaves Legacy on its ordinary unfiltered path" { + InModuleScope ParallelTestExecution { + Invoke-ParallelTestExecution -parameters $script:testParameters -scriptPath 'unused.ps1' ` + -testType 'Legacy' -appNamesToTest @('A', 'B') | Should -BeTrue + $script:dispatches.Phase | Should -Be @('Codeunit', 'Codeunit') } } - Context "discovery fixture preservation" { - BeforeEach { - InModuleScope ParallelTestExecution { - $script:fixtureEvents = [System.Collections.Generic.List[string]]::new() - $script:fixtureTenants = @( - [PSCustomObject]@{ Id = 'worker-a'; DatabaseName = 'worker-a-db' } - [PSCustomObject]@{ Id = 'primary'; DatabaseName = 'primary-db' } - [PSCustomObject]@{ Id = 'worker-b'; DatabaseName = 'worker-b-db' } - ) - $script:fixtures = @{ - 'primary-db' = 'pristine' - 'worker-a-db' = 'pristine' - 'worker-b-db' = 'pristine' - } - $script:fixtureParameters = @{ - containerName = "ut-$([guid]::NewGuid().ToString('N'))" - tenant = 'primary' - extensionId = 'caller-app-id' - testSuite = 'CALLER' - disabledTests = @([PSCustomObject]@{ codeunitId = 999; method = 'Excluded' }) - } - $script:originalFixtureParameters = $script:fixtureParameters | ConvertTo-Json -Depth 5 - $script:fixtureWorkItems = @([PSCustomObject]@{ - Key = 'Tests::500'; AppName = 'Tests'; AppId = 'tests-id' - CodeunitId = '500'; CodeunitName = 'API E2E'; TestCount = 2 - }) - $script:discoveryThrows = $false - $script:cleanThrows = $false - $script:cleanPassed = $true - Mock Get-AvailableBcTenantInfo { $script:fixtureTenants } - Mock Get-BcContainerAppInfo { - @([PSCustomObject]@{ IsInstalled = $true; Name = 'Tests'; AppId = 'tests-id' }) - } - Mock Get-RequiredDisabledWorkItems { - $script:fixtureEvents.Add("discover:$($Parameters.tenant)") - [object]::ReferenceEquals($Parameters, $script:fixtureParameters) | Should -BeFalse - $expected = $script:fixtureParameters.Clone() - $expected.tenant = 'worker-a' - ($Parameters | ConvertTo-Json -Depth 5) | Should -Be ($expected | ConvertTo-Json -Depth 5) - $discoveryDatabase = ($script:fixtureTenants | - Where-Object Id -eq $Parameters.tenant).DatabaseName - $script:fixtures[$discoveryDatabase] = 'discovery-dirty' - if ($script:discoveryThrows) { - throw 'discovery failed' - } - $script:fixtureWorkItems - } - Mock Reset-BcTestTenant { - $Tenant | Should -Not -Be 'primary' - $TenantDatabaseName | Should -Not -Be 'primary-db' - $script:fixtureEvents.Add("restore:${Tenant}:$TemplateDatabaseName") - $script:fixtures[$TenantDatabaseName] = $script:fixtures[$TemplateDatabaseName] - } - Mock New-BcTestTenantTemplate { - $SourceDatabaseName | Should -Be 'primary-db' - $script:fixtures['primary-db'] | Should -Be 'pristine' - $script:fixtures['worker-a-db'] | Should -Be 'pristine' - $script:fixtureEvents.Add("template:$SourceDatabaseName") - $script:fixtures['template-db'] = $script:fixtures[$SourceDatabaseName] - 'template-db' - } - Mock Invoke-RequiredDisabledTestExecution { - $script:fixtureEvents.Add('clean') - $script:fixtures['primary-db'] | Should -Be 'pristine' - foreach ($worker in $TenantInfo) { - $script:fixtures[$worker.DatabaseName] = 'clean-dirty' - } - if ($script:cleanThrows) { - throw 'clean execution failed' - } - $script:cleanPassed - } - Mock Invoke-WarmupDispatch { - $script:fixtureEvents.Add('warmup') - @($Pending) - } - Mock Get-AppRerunBudget { 0 } - Mock Wait-ForFreeTenant { 'primary' } - Mock Start-TestAppDispatch { - $script:fixtureEvents.Add("ordinary:$Tenant") - foreach ($info in $script:fixtureTenants) { - $script:fixtures[$info.DatabaseName] | Should -Be 'pristine' - } - } - Mock Wait-ForAllTestJobs { $true } - Mock Merge-TenantTestResults { } - Mock Remove-BcTestTenantTemplate { - $script:fixtureEvents.Add('remove-template') - } - } - } - - It "preserves ordinary execution when clean-codeunit activation is " -ForEach @( - @{ Lane = 'IntegrationTest'; Activation = 'absent'; Enabled = $null } - @{ Lane = 'IntegrationTest'; Activation = 'false'; Enabled = $false } - @{ Lane = 'UnitTest'; Activation = 'absent'; Enabled = $null } - @{ Lane = 'UnitTest'; Activation = 'false'; Enabled = $false } - @{ Lane = 'Legacy'; Activation = 'absent'; Enabled = $null } - @{ Lane = 'Legacy'; Activation = 'false'; Enabled = $false } - ) { - InModuleScope ParallelTestExecution -Parameters @{ Lane = $Lane; Enabled = $Enabled } { - $script:activationUnderTest = $Enabled - Mock Get-ALGoSetting { $script:activationUnderTest } -ParameterFilter { - $Key -eq 'enableCleanTestCodeunitExecution' - } - Invoke-ParallelTestExecution -parameters $script:fixtureParameters -scriptPath 'unused.ps1' ` - -testType $Lane -appNamesToTest @('Tests') | Should -BeTrue - - $script:fixtureEvents | Should -Be @('warmup', 'ordinary:primary') - Should -Invoke Get-RequiredDisabledWorkItems -Times 0 - Should -Invoke Reset-BcTestTenant -Times 0 - Should -Invoke New-BcTestTenantTemplate -Times 0 - Should -Invoke Invoke-RequiredDisabledTestExecution -Times 0 - Should -Invoke Invoke-WarmupDispatch -Times 1 -Exactly -ParameterFilter { - $CleanTenantAppNames.Count -eq 0 - } - Should -Invoke Start-TestAppDispatch -Times 1 -Exactly -ParameterFilter { - -not $SkipAutomaticDisabledPass - } - ($script:fixtureParameters | ConvertTo-Json -Depth 5) | Should -Be $script:originalFixtureParameters - } - } - - It "restores secondary discovery before copying the pristine primary and dispatching tests" { - InModuleScope ParallelTestExecution { - Invoke-ParallelTestExecution -parameters $script:fixtureParameters -scriptPath 'unused.ps1' ` - -testType 'UnitTest' -appNamesToTest @('Tests') | Should -BeTrue - - $script:fixtureEvents | Should -Be @( - 'discover:worker-a', 'restore:worker-a:primary-db', 'template:primary-db', 'clean', - 'restore:worker-a:template-db', 'restore:worker-b:template-db', - 'warmup', 'ordinary:primary', 'remove-template' - ) - $script:fixtures['template-db'] | Should -Be 'pristine' - ($script:fixtureParameters | ConvertTo-Json -Depth 5) | Should -Be $script:originalFixtureParameters - Should -Invoke Get-RequiredDisabledWorkItems -Times 1 -Exactly -ParameterFilter { - $Parameters.tenant -eq 'worker-a' -and $TestType -eq 'UnitTest' -and - $AppNamesToTest.Count -eq 1 -and $AppIdByName.Tests -eq 'tests-id' - } - Should -Invoke Invoke-WarmupDispatch -Times 1 -Exactly -ParameterFilter { - $CleanTenantAppNames.Count -eq 1 -and $CleanTenantAppNames[0] -eq 'Tests' - } - Should -Invoke Start-TestAppDispatch -Times 1 -Exactly -ParameterFilter { - $SkipAutomaticDisabledPass - } - Should -Invoke Invoke-ScriptInBcContainer -Times 0 - } - } - - It "restores discovery even when there are no clean work items without creating a template" { - InModuleScope ParallelTestExecution { - $script:fixtureWorkItems = @() - Invoke-ParallelTestExecution -parameters $script:fixtureParameters -scriptPath 'unused.ps1' ` - -testType 'IntegrationTest' -appNamesToTest @('Tests') | Should -BeTrue - - $script:fixtureEvents | Should -Be @( - 'discover:worker-a', 'restore:worker-a:primary-db', 'warmup', 'ordinary:primary' - ) - Should -Invoke New-BcTestTenantTemplate -Times 0 - Should -Invoke Invoke-RequiredDisabledTestExecution -Times 0 - ($script:fixtureParameters | ConvertTo-Json -Depth 5) | Should -Be $script:originalFixtureParameters - } - } - - It "restores discovery after an exception without copying or dispatching tainted fixtures" { - InModuleScope ParallelTestExecution { - $script:discoveryThrows = $true - { - Invoke-ParallelTestExecution -parameters $script:fixtureParameters -scriptPath 'unused.ps1' ` - -testType 'IntegrationTest' -appNamesToTest @('Tests') - } | Should -Throw '*discovery failed*' - - $script:fixtureEvents | Should -Be @('discover:worker-a', 'restore:worker-a:primary-db') - $script:fixtures['primary-db'] | Should -Be 'pristine' - $script:fixtures['worker-a-db'] | Should -Be 'pristine' - Should -Invoke New-BcTestTenantTemplate -Times 0 - Should -Invoke Invoke-RequiredDisabledTestExecution -Times 0 - Should -Invoke Invoke-WarmupDispatch -Times 0 - ($script:fixtureParameters | ConvertTo-Json -Depth 5) | Should -Be $script:originalFixtureParameters - } - } - - It "stops before template creation or dispatch when restoring discovery fails" { - InModuleScope ParallelTestExecution { - Mock Reset-BcTestTenant { throw 'discovery restore failed' } - { - Invoke-ParallelTestExecution -parameters $script:fixtureParameters -scriptPath 'unused.ps1' ` - -testType 'IntegrationTest' -appNamesToTest @('Tests') - } | Should -Throw '*discovery restore failed*' - - Should -Invoke Reset-BcTestTenant -Times 1 -Exactly - Should -Invoke New-BcTestTenantTemplate -Times 0 - Should -Invoke Invoke-RequiredDisabledTestExecution -Times 0 - Should -Invoke Invoke-WarmupDispatch -Times 0 - ($script:fixtureParameters | ConvertTo-Json -Depth 5) | Should -Be $script:originalFixtureParameters - } - } - - It "restores every clean worker and removes the template when clean execution throws" { - InModuleScope ParallelTestExecution { - $script:cleanThrows = $true - { - Invoke-ParallelTestExecution -parameters $script:fixtureParameters -scriptPath 'unused.ps1' ` - -testType 'IntegrationTest' -appNamesToTest @('Tests') - } | Should -Throw '*clean execution failed*' - - $script:fixtureEvents | Should -Be @( - 'discover:worker-a', 'restore:worker-a:primary-db', 'template:primary-db', 'clean', - 'restore:worker-a:template-db', 'restore:worker-b:template-db', 'remove-template' - ) - $script:fixtures['worker-a-db'] | Should -Be 'pristine' - $script:fixtures['worker-b-db'] | Should -Be 'pristine' - Should -Invoke Invoke-WarmupDispatch -Times 0 - Should -Invoke Invoke-ScriptInBcContainer -Times 0 - } - } - - It "restores every clean worker while retaining a failed test result" { - InModuleScope ParallelTestExecution { - $script:cleanPassed = $false - Invoke-ParallelTestExecution -parameters $script:fixtureParameters -scriptPath 'unused.ps1' ` - -testType 'IntegrationTest' -appNamesToTest @('Tests') | Should -BeFalse - - $script:fixtures['worker-a-db'] | Should -Be 'pristine' - $script:fixtures['worker-b-db'] | Should -Be 'pristine' - $script:fixtureEvents.IndexOf('ordinary:primary') | - Should -BeGreaterThan $script:fixtureEvents.IndexOf('restore:worker-b:template-db') - Should -Invoke Remove-BcTestTenantTemplate -Times 1 -Exactly - } - } - - It "keeps Legacy discovery on the original parameters without copying or resetting tenants" { - InModuleScope ParallelTestExecution { - Mock Get-RequiredDisabledWorkItems { - [object]::ReferenceEquals($Parameters, $script:fixtureParameters) | Should -BeTrue - $TestType | Should -Be 'Legacy' - @() - } - Invoke-ParallelTestExecution -parameters $script:fixtureParameters -scriptPath 'unused.ps1' ` - -testType 'Legacy' -appNamesToTest @('Tests') | Should -BeTrue - - Should -Invoke Get-RequiredDisabledWorkItems -Times 1 -Exactly - Should -Invoke Reset-BcTestTenant -Times 0 - Should -Invoke New-BcTestTenantTemplate -Times 0 - Should -Invoke Invoke-RequiredDisabledTestExecution -Times 0 - ($script:fixtureParameters | ConvertTo-Json -Depth 5) | Should -Be $script:originalFixtureParameters - } - } - - It "preserves single-tenant discovery and ordinary execution without clean work items" { - InModuleScope ParallelTestExecution { - $script:fixtureTenants = @($script:fixtureTenants | Where-Object Id -eq 'primary') - Mock Get-RequiredDisabledWorkItems { - [object]::ReferenceEquals($Parameters, $script:fixtureParameters) | Should -BeTrue - @() - } - Invoke-ParallelTestExecution -parameters $script:fixtureParameters -scriptPath 'unused.ps1' ` - -testType 'IntegrationTest' -appNamesToTest @('Tests') | Should -BeTrue - - Should -Invoke Get-RequiredDisabledWorkItems -Times 1 -Exactly - Should -Invoke Reset-BcTestTenant -Times 0 - Should -Invoke New-BcTestTenantTemplate -Times 0 - Should -Invoke Start-TestAppDispatch -Times 1 -Exactly - } - } - - It "retains the single-tenant error when clean work items are discovered" { - InModuleScope ParallelTestExecution { - $script:fixtureTenants = @($script:fixtureTenants | Where-Object Id -eq 'primary') - Mock Get-RequiredDisabledWorkItems { $script:fixtureWorkItems } - { - Invoke-ParallelTestExecution -parameters $script:fixtureParameters -scriptPath 'unused.ps1' ` - -testType 'IntegrationTest' -appNamesToTest @('Tests') - } | Should -Throw '*at least one secondary tenant*' - - Should -Invoke Reset-BcTestTenant -Times 0 - Should -Invoke New-BcTestTenantTemplate -Times 0 - Should -Invoke Invoke-WarmupDispatch -Times 0 - } - } - - It "rejects unsafe tenant metadata before discovery: " -ForEach @( - @{ Fault = 'missing primary'; MessagePattern = '*source tenant*' } - @{ Fault = 'blank primary database'; MessagePattern = '*source tenant*' } - @{ Fault = 'blank worker ID'; MessagePattern = '*unique tenant IDs and database names*' } - @{ Fault = 'blank worker database'; MessagePattern = '*unique tenant IDs and database names*' } - @{ Fault = 'duplicate worker ID'; MessagePattern = '*unique tenant IDs and database names*' } - @{ Fault = 'duplicate worker database'; MessagePattern = '*unique tenant IDs and database names*' } - @{ Fault = 'worker aliases primary database'; MessagePattern = '*unique tenant IDs and database names*' } - @{ Fault = 'duplicate primary ID'; MessagePattern = '*source tenant*' } - ) { - InModuleScope ParallelTestExecution -Parameters @{ Fault = $Fault; ExpectedError = $MessagePattern } { - param($Fault, $ExpectedError) - - switch ($Fault) { - 'missing primary' { $script:fixtureParameters.tenant = 'missing' } - 'blank primary database' { $script:fixtureTenants[1].DatabaseName = ' ' } - 'blank worker ID' { $script:fixtureTenants[0].Id = ' ' } - 'blank worker database' { $script:fixtureTenants[0].DatabaseName = ' ' } - 'duplicate worker ID' { $script:fixtureTenants[2].Id = 'WORKER-A' } - 'duplicate worker database' { $script:fixtureTenants[2].DatabaseName = 'WORKER-A-DB' } - 'worker aliases primary database' { $script:fixtureTenants[0].DatabaseName = 'PRIMARY-DB' } - 'duplicate primary ID' { $script:fixtureTenants[2].Id = 'PRIMARY' } - } - { - Invoke-ParallelTestExecution -parameters $script:fixtureParameters -scriptPath 'unused.ps1' ` - -testType 'IntegrationTest' -appNamesToTest @('Tests') - } | Should -Throw $ExpectedError - - Should -Invoke Get-RequiredDisabledWorkItems -Times 0 - Should -Invoke Reset-BcTestTenant -Times 0 - Should -Invoke New-BcTestTenantTemplate -Times 0 - Should -Invoke Invoke-WarmupDispatch -Times 0 - Should -Invoke Invoke-ScriptInBcContainer -Times 0 + It "does not cache completion when Disabled dispatch throws" { + InModuleScope ParallelTestExecution { + Mock Start-TestJob { throw 'dispatch error' } -ParameterFilter { + $parameters['requiredTestIsolation'] -eq 'Disabled' } + { + Invoke-ParallelTestExecution -parameters $script:testParameters -scriptPath 'unused.ps1' ` + -testType 'UnitTest' -appNamesToTest @('A') + } | Should -Throw '*dispatch error*' + Get-CachedTestRunResult -ContainerName $script:testParameters.containerName | Should -BeNullOrEmpty } } - - It "contains no Task Scheduler override or server restart commands" { - $tokens = $null - $parseErrors = $null - $ast = [System.Management.Automation.Language.Parser]::ParseFile( - (Get-Module ParallelTestExecution).Path, [ref]$tokens, [ref]$parseErrors) - $parseErrors.Count | Should -Be 0 - $overrides = @($ast.FindAll({ - param($node) - $node -is [System.Management.Automation.Language.CommandAst] -and - $node.GetCommandName() -in @( - 'Set-NAVServerConfiguration', 'Set-NAVServerInstance', - 'Set-BcTestTaskScheduler', 'Enable-BcTestTaskScheduler', 'Disable-BcTestTaskScheduler' - ) - }, $true)) - $overrides.Count | Should -Be 0 - } } Describe "RunTestsInBcContainer platform-race transcript classification" { @@ -1462,6 +859,26 @@ Describe "RunTestsInBcContainer platform-race transcript classification" { Test-Path -LiteralPath $script:transcriptPath | Should -BeFalse } + It "accepts a successful empty selection without turning execution errors into success" { + $script:transcript = '' + Mock Run-TestsInBcContainer { $true } + Invoke-RunTestsWithCancellationDetection -parameters @{ appName = 'Empty'; tenant = 'default' } | + Should -BeTrue + Mock Run-TestsInBcContainer { throw 'selection failed' } + Invoke-RunTestsWithCancellationDetection -parameters @{ appName = 'Empty'; tenant = 'default' } | + Should -BeFalse + } + + It "rejects cancellation even if BCH returns success" -ForEach @( + @{ Transcript = 'ERROR DIALOG: unexpected client error' } + @{ Transcript = 'The database command was cancelled' } + ) { + $script:transcript = $Transcript + Mock Run-TestsInBcContainer { $true } + Invoke-RunTestsWithCancellationDetection -parameters @{ appName = 'Tests'; tenant = 'default' } | + Should -BeFalse + } + It "does not emit a platform marker for an ordinary API failure or unrelated page mention" -ForEach @( @{ Transcript = 'GET request failed. Response code is 500 (InternalServerError), expected code is 200. Error message: Object reference not set to an instance of an object.' } @{ Transcript = "Opened page 130455 successfully.`nGET request failed. Response code is 500 (InternalServerError), expected code is 200. Error message: Object reference not set to an instance of an object." } @@ -1487,12 +904,87 @@ Describe "RunTestsInBcContainer platform-race transcript classification" { } } +Describe "RunTestsInBcContainer Disabled routing" { + BeforeAll { + Import-Module (Join-Path $PSScriptRoot '..\EnlistmentHelperFunctions.psm1') + function Run-TestsInBcContainer { + param($appName, $tenant, $extensionId, $testType, $requiredTestIsolation, $testRunnerCodeunitId, $disabledTests) + $null = $appName, $tenant, $extensionId, $testType, $requiredTestIsolation, $testRunnerCodeunitId, $disabledTests + throw 'Container test execution must be mocked.' + } + $script:runScript = Join-Path $PSScriptRoot '../RunTestsInBcContainer.ps1' + $script:originalEvent = $env:GITHUB_EVENT_NAME + } + + BeforeEach { + $env:GITHUB_EVENT_NAME = 'push' + $script:calls = [System.Collections.Generic.List[object]]::new() + Mock Import-Module {} + Mock Get-ALGoSetting { 'AU' } -ParameterFilter { $Key -eq 'country' } + Mock Get-DisabledTestsForApp { @(@{ Codeunit = '50000'; Method = 'Excluded' }) } + Mock Start-Transcript { Set-Content -LiteralPath $Path -Value '' } + Mock Stop-Transcript {} + Mock Run-TestsInBcContainer { + $script:calls.Add(@{ + App = $appName; Type = $testType; Isolation = $requiredTestIsolation + Runner = $testRunnerCodeunitId; Exclusions = $disabledTests + }) + $true + } + } + + AfterAll { + $env:GITHUB_EVENT_NAME = $script:originalEvent + } + + It "runs only the requested app phase with exclusions for " -ForEach @( + @{ Lane = 'UnitTest' } + @{ Lane = 'IntegrationTest' } + @{ Lane = 'Uncategorized' } + ) { + foreach ($phase in @('Codeunit', 'Disabled')) { + $params = @{ appName = 'Tests'; extensionId = 'tests-id'; tenant = 'default' } + if ($phase -eq 'Disabled') { + $params.requiredTestIsolation = 'Disabled' + $params.testRunnerCodeunitId = '130451' + } + . $script:runScript -parameters $params -TestType $Lane -SkipAutomaticDisabledPass | Should -BeTrue + } + $script:calls.Count | Should -Be 2 + Should -Invoke Get-DisabledTestsForApp -Times 2 -Exactly -ParameterFilter { + $AppName -eq 'Tests' -and $Country -eq 'AU' + } + $script:calls[0].Isolation | Should -BeNullOrEmpty + $script:calls[1].Isolation | Should -Be 'Disabled' + $script:calls[1].Runner | Should -Be '130451' + foreach ($call in $script:calls) { + $call.Type | Should -Be $Lane + $call.Exclusions.Count | Should -Be 1 + $call.Exclusions[0].Method | Should -Be 'Excluded' + } + } + + It "does not repeat an explicit Disabled UnitTest invocation even without the skip switch" { + . $script:runScript -parameters @{ + appName = 'Tests'; tenant = 'default'; requiredTestIsolation = 'Disabled'; testRunnerCodeunitId = '130451' + } -TestType 'UnitTest' | Should -BeTrue + $script:calls.Count | Should -Be 1 + } + + It "preserves the sequential UnitTest fallback outside parallel execution" { + . $script:runScript -parameters @{ appName = 'Tests'; tenant = 'default' } -TestType 'UnitTest' | + Should -BeTrue + $script:calls.Count | Should -Be 2 + $script:calls[1].Isolation | Should -Be 'Disabled' + } +} + Describe "ParallelTestExecution warmup dispatch" { BeforeAll { Import-Module (Join-Path $PSScriptRoot '../ParallelTestExecution.psm1') -Force } - It "defers the Disabled pass when the warmup app uses clean-codeunit execution" { + It "defers the Disabled pass during warmup" { InModuleScope ParallelTestExecution { $script:skipDisabledPass = $false Mock Start-TestAppDispatch { @@ -1505,7 +997,7 @@ Describe "ParallelTestExecution warmup dispatch" { -Pending @('API Tests', 'Other Tests') ` -AppIdByName @{ 'API Tests' = 'api-id'; 'Other Tests' = 'other-id' } ` -Tenants @('default', 'tenant2') -ScriptPath 'unused.ps1' -TestType 'UnitTest' ` - -State $state -CleanTenantAppNames @('API Tests') + -State $state $result | Should -Be @('Other Tests') $script:skipDisabledPass | Should -BeTrue @@ -1530,7 +1022,6 @@ Describe "ParallelTestExecution warmup dispatch" { } } Mock Wait-ForFreeTenant { 'tenant2' } - Mock Get-RequiredDisabledWorkItems { @() } Mock Merge-TenantTestResults { } Mock Start-TestAppDispatch { $script:events.Add("dispatch:$AppName") } Mock Wait-ForAllTestJobs { $script:events.Add('wait'); $true } @@ -1562,7 +1053,6 @@ Describe "ParallelTestExecution warmup dispatch" { } Mock Wait-ForFreeTenant { 'default' } Mock Merge-TenantTestResults { } - Mock Get-RequiredDisabledWorkItems { @() } Mock Start-TestAppDispatch { $script:events.Add("dispatch:$AppName") } Mock Wait-ForAllTestJobs { $script:events.Add('wait'); $true } @@ -1637,20 +1127,16 @@ Describe "ParallelTestExecution failed-app rerun scheduling" { Import-Module (Join-Path $PSScriptRoot '../ParallelTestExecution.psm1') -Force } - It "re-runs a failed app on a different tenant with clean activation " -ForEach @( - @{ Lane = 'Legacy'; Enabled = $false } - @{ Lane = 'UnitTest'; Enabled = $false } - @{ Lane = 'UnitTest'; Enabled = $true } + It "re-runs a failed app on a different tenant" -ForEach @( + @{ Lane = 'Legacy' } + @{ Lane = 'UnitTest' } + @{ Lane = 'IntegrationTest' } + @{ Lane = 'Uncategorized' } ) { # A failed app is retried once, and never on the tenant it failed on: tests are not # guaranteed to clean up after themselves, so residue from the failed run could # re-trigger the same failure and make the retry worthless. - InModuleScope ParallelTestExecution -Parameters @{ Lane = $Lane; Enabled = $Enabled } { - $script:activationUnderTest = $Enabled - Mock Get-ALGoSetting { $script:activationUnderTest } -ParameterFilter { - $Key -eq 'enableCleanTestCodeunitExecution' - } - Mock Reset-BcTestTenant { } + InModuleScope ParallelTestExecution -Parameters @{ Lane = $Lane } { $script:dispatched = [System.Collections.Generic.List[object]]::new() $script:failed = $false @@ -1665,7 +1151,6 @@ Describe "ParallelTestExecution failed-app rerun scheduling" { [PSCustomObject]@{ IsInstalled = $true; Name = $_; AppId = "id-$_" } } } - Mock Get-RequiredDisabledWorkItems { @() } Mock Invoke-WarmupDispatch { @($Pending) } Mock Get-AppRerunBudget { 1 } Mock Wait-ForAllTestJobs { $true } @@ -1698,7 +1183,7 @@ Describe "ParallelTestExecution failed-app rerun scheduling" { $rerun.App | Should -Be 'Big' $rerun.Tenant | Should -Be 'tenant2' $rerun.Suffix | Should -Be 'rerun1' - $rerun.SkipDisabled | Should -Be $Enabled + $rerun.SkipDisabled | Should -BeTrue # The rerun passed, so the run as a whole passed. $result | Should -BeTrue } @@ -1938,7 +1423,6 @@ Describe "ParallelTestExecution rerun budget is limited to pull request builds" } Mock Invoke-WarmupDispatch { @($Pending) } Mock Wait-ForAllTestJobs { $true } - Mock Get-RequiredDisabledWorkItems { @() } Mock Merge-TenantTestResults { } Mock Wait-ForFreeTenant { 'default' } Mock Start-TestAppDispatch { @@ -1977,6 +1461,72 @@ Describe "ParallelTestExecution result merging" { } } + It "separates Codeunit, Disabled and rerun files while retaining append flags" { + InModuleScope ParallelTestExecution { + Mock Start-Job { + $script:jobArguments = $ArgumentList + [PSCustomObject]@{ Id = 1 } + } + $params = @{ + containerName = 'c'; JUnitResultFileName = (Join-Path $TestDrive 'junit.xml') + XUnitResultFileName = (Join-Path $TestDrive 'xunit.xml') + AppendToJUnitResultFile = $true; AppendToXUnitResultFile = $true + } + foreach ($phase in @('Codeunit', 'Disabled')) { + if ($phase -eq 'Disabled') { $params.requiredTestIsolation = 'Disabled' } + foreach ($suffix in @('', 'rerun1')) { + $null = Start-TestJob -parameters $params -tenant 'tenant2' -scriptPath 'unused.ps1' ` + -testType 'IntegrationTest' -skipAutomaticDisabledPass -fileSuffix $suffix + $expected = if ($suffix) { $suffix } else { 'tenant2' } + if ($phase -eq 'Disabled') { $expected = "disabled-$expected" } + $script:jobArguments[0].JUnitResultFileName | Should -Be (Join-Path $TestDrive "junit-$expected.xml") + $script:jobArguments[0].XUnitResultFileName | Should -Be (Join-Path $TestDrive "xunit-$expected.xml") + $script:jobArguments[0].AppendToJUnitResultFile | Should -BeTrue + $script:jobArguments[0].AppendToXUnitResultFile | Should -BeTrue + $script:jobArguments[4] | Should -BeTrue + } + } + } + } + + It "merges both phases and replaces only the retried codeunit for " -ForEach @( + @{ Format = 'JUnit'; Root = 'testsuites'; Child = 'testsuite'; Key = 'JUnitResultFileName' } + @{ Format = 'XUnit'; Root = 'assemblies'; Child = 'assembly'; Key = 'XUnitResultFileName' } + ) { + InModuleScope ParallelTestExecution -Parameters @{ Root = $Root; Child = $Child; Key = $Key } { + $params = @{ $Key = (Join-Path $TestDrive 'results.xml') } + foreach ($entry in @( + @{ Suffix = 'default'; Name = 'Codeunit'; Failures = 0 } + @{ Suffix = 'disabled-default'; Name = 'Disabled'; Failures = 1 } + @{ Suffix = 'disabled-rerun1'; Name = 'Disabled'; Failures = 0 } + )) { + "<$Root><$Child name='$($entry.Name)' failures='$($entry.Failures)' />" | + Set-Content (Join-Path $TestDrive "results-$($entry.Suffix).xml") + } + Merge-TenantTestResults -parameters $params -resultSuffixes @('default', 'disabled-default', 'disabled-rerun1') + $xml = [xml](Get-Content $params[$Key] -Raw) + $nodes = @($xml.SelectNodes("//$Root/$Child")) + $nodes.Count | Should -Be 2 + $nodes.name | Should -Be @('Codeunit', 'Disabled') + $nodes.failures | Should -Be @('0', '0') + @(Get-ChildItem $TestDrive -Filter 'results-*.xml').Count | Should -Be 0 + } + } + + It "removes only the Disabled stale rerun, leaving Codeunit results intact" { + InModuleScope ParallelTestExecution { + $codeunit = Join-Path $TestDrive 'results-rerun1.xml' + $disabled = Join-Path $TestDrive 'results-disabled-rerun1.xml' + Set-Content $codeunit '' + Set-Content $disabled '' + Remove-RerunResultFile -parameters @{ + JUnitResultFileName = (Join-Path $TestDrive 'results.xml'); requiredTestIsolation = 'Disabled' + } -suffix 'rerun1' + Test-Path $codeunit | Should -BeTrue + Test-Path $disabled | Should -BeFalse + } + } + It "lets a rerun's results replace those of the run it re-ran" { # The rerun runs the whole app again on another tenant and writes its own file. Without # replace-by-name the merged report would contain the app twice - once failed, once diff --git a/src/DisabledTests/_Exclude_APIV1__Tests/_Exclude_APIV1__Tests.DisabledTest.json b/src/DisabledTests/_Exclude_APIV1__Tests/_Exclude_APIV1__Tests.DisabledTest.json index 62de7b0539d..50b18830b58 100644 --- a/src/DisabledTests/_Exclude_APIV1__Tests/_Exclude_APIV1__Tests.DisabledTest.json +++ b/src/DisabledTests/_Exclude_APIV1__Tests/_Exclude_APIV1__Tests.DisabledTest.json @@ -24,6 +24,12 @@ "codeunitName": "APIV1 - Purchase Invoices E2E", "method": "TestPurchaseInvoiceWithPaymentDiscount" }, + { + "codeunitId": 139730, + "codeunitName": "APIV1 - GLEntries E2E", + "method": "TestGetGLEntries", + "country": "AU" + }, { "codeunitId": 139733, "codeunitName": "APIV1 - Attachments E2E", diff --git a/src/DisabledTests/_Exclude_APIV2__Tests/_Exclude_APIV2__Tests.DisabledTest.json b/src/DisabledTests/_Exclude_APIV2__Tests/_Exclude_APIV2__Tests.DisabledTest.json index e8cb0707a35..a77792de034 100644 --- a/src/DisabledTests/_Exclude_APIV2__Tests/_Exclude_APIV2__Tests.DisabledTest.json +++ b/src/DisabledTests/_Exclude_APIV2__Tests/_Exclude_APIV2__Tests.DisabledTest.json @@ -8,5 +8,11 @@ "codeunitId": 139806, "codeunitName": "APIV2 - Company Info. E2E", "method": "TestModifyCompanyInformation" + }, + { + "codeunitId": 139830, + "codeunitName": "APIV2 - GLEntries E2E", + "method": "TestGetGLEntries", + "country": "AU" } ]