tests/Client/Sync-XrmRecords.Tests.ps1

<#
    Integration Test: Sync-XrmRecords
    Tests record synchronization orchestration between source and target clients.
    Source and target are the same instance here, so Sync-XrmRecords only updates existing records: the record sent to the
    target is checked offline (ConvertTo-XrmSyncRecordInternal: state and creation date kept, H9 / H10), and the creation path
    with that record is checked directly with Upsert-XrmRecord.
#>

. "$PSScriptRoot\..\_TestConfig.ps1";

$module = Get-Module PowerDataOps;

Write-Section "Record sent to the target (offline, H9 / H10)";

$defaultExcluded = ((Get-Command Sync-XrmRecords).ScriptBlock.Ast.Body.ParamBlock.Parameters | Where-Object { $_.Name.VariablePath.UserPath -eq "ExcludedAttributes" }).DefaultValue.SafeGetValue();
$targetColumns = [System.Collections.Generic.HashSet[string]]::new([string[]]@("name", "telephone1", "parentaccountid", "overriddencreatedon", "statecode", "statuscode", "createdon", "ownerid", "modifiedon"), [System.StringComparer]::OrdinalIgnoreCase);
$updatableColumns = [System.Collections.Generic.HashSet[string]]::new([string[]]@("name", "telephone1", "parentaccountid", "statecode", "statuscode", "ownerid"), [System.StringComparer]::OrdinalIgnoreCase);
$sourceCreatedOn = [DateTime]::new(2020, 1, 15, 10, 0, 0, [DateTimeKind]::Utc);
$sourceEntity = New-XrmEntity -LogicalName "account" -Id ([Guid]::NewGuid()) -Attributes @{
    name                = "Source";
    telephone1          = "0102030405";
    statecode           = (New-XrmOptionSetValue -Value 1);
    statuscode          = (New-XrmOptionSetValue -Value 2);
    createdon           = $sourceCreatedOn;
    overriddencreatedon = [DateTime]::new(2026, 12, 1, 0, 0, 0, [DateTimeKind]::Utc);
    modifiedon          = [DateTime]::UtcNow;
    ownerid             = (New-XrmEntityReference -LogicalName "systemuser" -Id ([Guid]::NewGuid()));
    parentaccountid     = (New-XrmEntityReference -LogicalName "account" -Id ([Guid]::NewGuid()));
    notatargetcolumn    = "x";
};
function Convert-TestRecord([hashtable] $Arguments) {
    $Arguments["SourceEntity"] = $sourceEntity;
    $Arguments["TargetAttributes"] = $targetColumns;
    if (-not $Arguments.ContainsKey("UpdatableAttributes")) { $Arguments["UpdatableAttributes"] = $updatableColumns; }
    return & $module { param($arguments) ConvertTo-XrmSyncRecordInternal @arguments } $Arguments;
}

$converted = Convert-TestRecord @{ ExcludedAttributes = $defaultExcluded };
Assert-Test "Default exclusions: statecode 1 / statuscode 2 kept apart (H9)" { $converted.StateCode -eq 1 -and $converted.StatusCode -eq 2 };
Assert-Test "Default exclusions: overriddencreatedon = source createdon, although not valid for update (H10)" { $converted.Record["overriddencreatedon"] -eq $sourceCreatedOn };
Assert-Test "Default exclusions: name and telephone1 only, besides overriddencreatedon" {
    @($converted.Record.Attributes.Keys | Sort-Object) -join "," -eq "name,overriddencreatedon,telephone1";
};
$withReferences = Convert-TestRecord @{ ExcludedAttributes = $defaultExcluded; IncludeEntityReferences = $true };
Assert-Test "-IncludeEntityReferences: parentaccountid added, ownerid still excluded" { $withReferences.Record.Contains("parentaccountid") -and -not $withReferences.Record.Contains("ownerid") };
$notPreserved = Convert-TestRecord @{ ExcludedAttributes = $defaultExcluded; PreserveCreatedOn = $false };
Assert-Test "-PreserveCreatedOn `$false: no overriddencreatedon, state still kept" { -not $notPreserved.Record.Contains("overriddencreatedon") -and $notPreserved.StateCode -eq 1 };
$excludedPhone = Convert-TestRecord @{ ExcludedAttributes = @("telephone1") };
Assert-Test "Custom exclusions: telephone1 excluded, statecode never in the record" { -not $excludedPhone.Record.Contains("telephone1") -and -not $excludedPhone.Record.Contains("statecode") -and $excludedPhone.StateCode -eq 1 };
$noOverride = & $module { param($s, $u) ConvertTo-XrmSyncRecordInternal -SourceEntity $s -TargetAttributes $u -UpdatableAttributes $u } $sourceEntity $updatableColumns;
Assert-Test "Target table without overriddencreatedon: not sent" { -not $noOverride.Record.Contains("overriddencreatedon") };

Write-Section "Record created on the target with that payload (H10)";

$createdName = Get-TestName -Prefix "SyncCreate";
$creationSource = New-XrmEntity -LogicalName "account" -Id ([Guid]::NewGuid()) -Attributes @{ name = $createdName; createdon = $sourceCreatedOn };
$creationPayload = & $module { param($s, $t, $u) ConvertTo-XrmSyncRecordInternal -SourceEntity $s -ExcludedAttributes @("createdon") -TargetAttributes $t -UpdatableAttributes $u } $creationSource $targetColumns $updatableColumns;
$Global:XrmClient | Upsert-XrmRecord -Record $creationPayload.Record | Out-Null;
$created = $Global:XrmClient | Get-XrmRecord -LogicalName "account" -Id $creationSource.Id -Columns "createdon" -AsEntity;
Assert-Test "Upsert that creates: createdon = source createdon ($($created['createdon'].ToString('o')))" { $created["createdon"] -eq $sourceCreatedOn };
$creationSource["createdon"] = [DateTime]::new(2019, 1, 1, 0, 0, 0, [DateTimeKind]::Utc);
$updatePayload = & $module { param($s, $t, $u) ConvertTo-XrmSyncRecordInternal -SourceEntity $s -ExcludedAttributes @("createdon") -TargetAttributes $t -UpdatableAttributes $u } $creationSource $targetColumns $updatableColumns;
$updateError = $null;
try { $Global:XrmClient | Upsert-XrmRecord -Record $updatePayload.Record -ErrorAction Stop | Out-Null; } catch { $updateError = $_.Exception.Message; }
$updated = $Global:XrmClient | Get-XrmRecord -LogicalName "account" -Id $creationSource.Id -Columns "createdon" -AsEntity;
Assert-Test "Upsert that updates: no error, createdon kept" { $null -eq $updateError -and $updated["createdon"] -eq $sourceCreatedOn };
$Global:XrmClient | Remove-XrmRecord -LogicalName "account" -Id $creationSource.Id;

Write-Section "Setup test account";

$accountName = Get-TestName -Prefix "Sync";
$account = New-XrmEntity -LogicalName "account" -Attributes @{
    "name" = $accountName;
};
$account.Id = $Global:XrmClient | Add-XrmRecord -Record $account;

Assert-Test "Test account created" {
    $account.Id -ne [Guid]::Empty;
};

Write-Section "Sync-XrmRecords execution";

$summary = @(
    Sync-XrmRecords `
        -SourceXrmClient $Global:XrmClient `
        -TargetXrmClient $Global:XrmClient `
        -LogicalNames @("account") `
        -Columns @("name") `
        -TopCount 1 `
        -OrderByField "createdon" `
        -OrderType Descending `
        -ContinueOnError $false
);

Assert-Test "Sync-XrmRecords returns one summary row" {
    $summary.Count -eq 1;
};

$accountSummary = $summary | Select-Object -First 1;

Assert-Test "Summary LogicalName is account" {
    $accountSummary.LogicalName -eq "account";
};

Assert-Test "Summary ReadCount is 1 (TopCount applied)" {
    [int]$accountSummary.ReadCount -eq 1;
};

Assert-Test "Summary FailedCount is 0" {
    [int]$accountSummary.FailedCount -eq 0;
};

Assert-Test "Summary UpsertedCount is 1" {
    [int]$accountSummary.UpsertedCount -eq 1;
};

Write-Section "Counters (B17)";

$whatIfErrors = $null;
$whatIfSummary = @(Sync-XrmRecords -SourceXrmClient $Global:XrmClient -TargetXrmClient $Global:XrmClient -LogicalNames @("account") -Columns @("name") -TopCount 1 -OrderByField "createdon" -WhatIf -ErrorVariable whatIfErrors)[0];
Assert-Test "-WhatIf: Upserted 0, Skipped 1, Failed 0, no error (was Upserted 1)" {
    $whatIfSummary.ReadCount -eq 1 -and $whatIfSummary.UpsertedCount -eq 0 -and $whatIfSummary.SkippedCount -eq 1 -and $whatIfSummary.FailedCount -eq 0 -and $whatIfErrors.Count -eq 0;
};

$Global:XrmClient | Set-XrmRecordState -RecordReference $account.ToEntityReference() -StateCode 1 -StatusCode 2 | Out-Null;
$twoPass = @(Sync-XrmRecords -SourceXrmClient $Global:XrmClient -TargetXrmClient $Global:XrmClient -LogicalNames @("account") -Columns @("name", "statecode", "statuscode") -TopCount 1 -OrderByField "createdon" -TwoPassDependencies $true -StateHandling ApplyStateAndStatus)[0];
Assert-Test "Two passes, ApplyStateAndStatus on an inactive record: Upserted 1, Failed 0, no error ($($twoPass.Errors -join ' | '))" {
    $twoPass.ReadCount -eq 1 -and $twoPass.UpsertedCount -eq 1 -and $twoPass.FailedCount -eq 0 -and $twoPass.SkippedCount -eq 0 -and @($twoPass.Errors).Count -eq 0;
};
$state = $Global:XrmClient | Get-XrmRecord -LogicalName "account" -Id $account.Id -Columns "statecode" -AsEntity;
Assert-Test "State kept: inactive" { $state["statecode"].Value -eq 1 };

Write-Section "Cleanup";

$Global:XrmClient | Remove-XrmRecord -LogicalName "account" -Id $account.Id;
Assert-Test "Test account deleted" { $null -eq ($Global:XrmClient | Get-XrmRecord -LogicalName "account" -Id $account.Id -IfExists) };

Write-TestSummary;