tests/AzDevOps/SolutionsBuild.Tests.ps1

<#
    Integration Test: Azure DevOps build tasks (defect batch 3: H1 to H5)
    Import-XrmSolutionsBuild: exact solution file names (H4), -Upgrade and SolutionsImportUpgrade (H2), StageAndUpgrade through
    Import-XrmSolution (H5), ClearPluginStepsAndTypes and PluginAssemblyName removed (H3).
    Export-XrmSolutionsBuild: the source is only read by default, -ClearCreateStepFilteringAttributes only updates the unmanaged
    Create steps of the exported solutions, -WhatIf (H1).
    Both tasks get -XrmClient: they open their own connection from a connection string otherwise.
    The upgrade is told from an update by a web resource removed from the new version: only an upgrade deletes it.
#>

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

$suffix = Get-Random -Minimum 10000 -Maximum 99999;
$letters = -join ((1..3) | ForEach-Object { [char](Get-Random -Minimum 97 -Maximum 123) });
$prefix = "pdb$letters";
$publisherUniqueName = "pdobuild$suffix";
$salesName = "pdosales$suffix";
$decoyName = "apdosales$suffix";   # its file name ends with the one of $salesName (H4)
$stepsSolutionName = "pdosteps$suffix";
$assemblyName = "PdoTest.BuildPlugins$suffix";
$root = [System.IO.Path]::Combine([System.IO.Path]::GetTempPath(), "pdo-build-$suffix");
$drop10 = [System.IO.Path]::Combine($root, "drop10");
$drop11 = [System.IO.Path]::Combine($root, "drop11");
$drop12 = [System.IO.Path]::Combine($root, "drop12");
$stepsDrop = [System.IO.Path]::Combine($root, "steps");
foreach ($folder in $drop10, $drop11, $drop12, $stepsDrop) { New-Item -ItemType Directory -Path $folder -Force | Out-Null; }

$webResourceNames = @{
    W1 = "$($prefix)_/build$suffix/w1.js";
    W2 = "$($prefix)_/build$suffix/w2.js";
    D1 = "$($prefix)_/build$suffix/d1.js";
};

function Add-TestWebResource {
    param([string] $Name, [string] $SolutionUniqueName)
    $id = $Global:XrmClient | Add-XrmRecord -Record (New-XrmEntity -LogicalName "webresource" -Attributes @{
            name            = $Name;
            displayname     = $Name;
            webresourcetype = (New-XrmOptionSetValue -Value 3);
            content         = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("// $Name"));
        });
    $Global:XrmClient | Add-XrmSolutionComponent -SolutionUniqueName $SolutionUniqueName -ComponentId $id -ComponentType $webResourceType | Out-Null;
    return $id;
}

function Test-WebResource {
    param([string] $Name)
    return $null -ne ($Global:XrmClient | Get-XrmRecord -LogicalName "webresource" -AttributeName "name" -Value $Name -Columns "name" -IfExists);
}

function Get-SolutionVersion {
    param([string] $UniqueName)
    $solution = $Global:XrmClient | Get-XrmRecord -LogicalName "solution" -AttributeName "uniquename" -Value $UniqueName -Columns "version", "ismanaged" -IfExists;
    if (-not $solution) { return $null; }
    return "$($solution.version) managed=$($solution | Get-XrmRowValue -Name 'ismanaged')";
}

try {
    # ============================================================
    # Parameters (H3, H1)
    # ============================================================
    Write-Section "Parameters";

    $importCommand = Get-Command Import-XrmSolutionsBuild;
    Assert-Test "H3: ClearPluginStepsAndTypes and PluginAssemblyName removed" { -not $importCommand.Parameters.ContainsKey("ClearPluginStepsAndTypes") -and -not $importCommand.Parameters.ContainsKey("PluginAssemblyName") };
    $upgradePosition = ($importCommand.Parameters["Upgrade"].Attributes | Where-Object { $_ -is [System.Management.Automation.ParameterAttribute] }).Position;
    $orderPosition = ($importCommand.Parameters["SolutionsImportOrder"].Attributes | Where-Object { $_ -is [System.Management.Automation.ParameterAttribute] }).Position;
    Assert-Test "Positions kept: SolutionsImportOrder 2, Upgrade 7" { $orderPosition -eq 2 -and $upgradePosition -eq 7 };
    $removedError = $null;
    try { Import-XrmSolutionsBuild -XrmClient $Global:XrmClient -ArtifactsPath $drop10 -SolutionsImportOrder "x" -ClearPluginStepsAndTypes $false -ErrorAction Stop; } catch { $removedError = $_.Exception.Message; }
    Assert-Test "H3: -ClearPluginStepsAndTypes is refused by the parameter binding" { $removedError -like "*ClearPluginStepsAndTypes*" };

    $exportCommand = Get-Command Export-XrmSolutionsBuild;
    Assert-Test "H1: Export-XrmSolutionsBuild supports -WhatIf, -ClearCreateStepFilteringAttributes is false by default" {
        $exportCommand.Parameters.ContainsKey("WhatIf") -and $exportCommand.Parameters.ContainsKey("ClearCreateStepFilteringAttributes") -and
        ($exportCommand.ScriptBlock.Ast.Body.ParamBlock.Parameters | Where-Object { $_.Name.VariablePath.UserPath -eq "ClearCreateStepFilteringAttributes" }).DefaultValue.Extent.Text -eq '$false';
    };

    # ============================================================
    # File selection (H4), offline: -WhatIf, dummy files
    # ============================================================
    Write-Section "Import-XrmSolutionsBuild - file selection (H4, offline)";

    $selectionDrop = [System.IO.Path]::Combine($root, "selection");
    New-Item -ItemType Directory -Path $selectionDrop | Out-Null;
    function Get-SelectedFile([string[]] $FileNames) {
        Get-ChildItem -Path $selectionDrop -File | Remove-Item;
        foreach ($fileName in $FileNames) { Set-Content -Path ([System.IO.Path]::Combine($selectionDrop, $fileName)) -Value "x"; }
        $output = Import-XrmSolutionsBuild -XrmClient $Global:XrmClient -ArtifactsPath $selectionDrop -SolutionsImportOrder "sales" -WhatIf *>&1 | Out-String;
        if ($output -match "Importing sales from (.+?\.zip)") { return [System.IO.Path]::GetFileName($Matches[1]); }
        return $null;
    }
    Assert-Test "Managed file first: sales_managed.zip, not presales_managed.zip" { (Get-SelectedFile -FileNames "presales_managed.zip", "sales.zip", "sales_managed.zip") -eq "sales_managed.zip" };
    Assert-Test "Exact name before versioned names: sales.zip" { (Get-SelectedFile -FileNames "presales_managed.zip", "sales.zip", "sales_1_0_0_0_managed.zip") -eq "sales.zip" };
    Assert-Test "Versioned names: highest version (1.10 after 1.2)" { (Get-SelectedFile -FileNames "sales_1_2_0_0_managed.zip", "sales_1_10_0_0_managed.zip", "presales_managed.zip") -eq "sales_1_10_0_0_managed.zip" };

    # ============================================================
    # Setup: publisher, two solutions, three exports
    # ============================================================
    Write-Section "Setup - solutions and exports";

    $webResourceType = Get-XrmSolutionComponentType -XrmClient $Global:XrmClient -LogicalName "webresource";
    $publisherRef = Upsert-XrmPublisher -XrmClient $Global:XrmClient -UniqueName $publisherUniqueName -DisplayName "PDO build $suffix" -Prefix $prefix -OptionValuePrefix (10000 + ($suffix % 89999));
    Upsert-XrmSolution -XrmClient $Global:XrmClient -UniqueName $salesName -DisplayName "PDO sales $suffix" -PublisherReference $publisherRef -Version "1.0.0.0" | Out-Null;
    Upsert-XrmSolution -XrmClient $Global:XrmClient -UniqueName $decoyName -DisplayName "PDO decoy $suffix" -PublisherReference $publisherRef -Version "1.0.0.0" | Out-Null;
    $w1Id = Add-TestWebResource -Name $webResourceNames.W1 -SolutionUniqueName $salesName;
    $w2Id = Add-TestWebResource -Name $webResourceNames.W2 -SolutionUniqueName $salesName;
    $d1Id = Add-TestWebResource -Name $webResourceNames.D1 -SolutionUniqueName $decoyName;

    Export-XrmSolutionsBuild -XrmClient $Global:XrmClient -ExportPath $drop10 -Solutions "$salesName, $decoyName" -Managed $true;
    $files10 = @(Get-ChildItem -Path $drop10 -File | ForEach-Object { $_.Name });
    Assert-Test "Export-XrmSolutionsBuild: both managed files written ($($files10 -join ', '))" { $files10 -contains "$($salesName)_managed.zip" -and $files10 -contains "$($decoyName)_managed.zip" };

    # 1.1: W1 removed, versioned file name; 1.2: W2 removed
    $Global:XrmClient | Remove-XrmSolutionComponent -SolutionUniqueName $salesName -ComponentId $w1Id -ComponentType $webResourceType | Out-Null;
    Upsert-XrmSolution -XrmClient $Global:XrmClient -UniqueName $salesName -Version "1.1.0.0" | Out-Null;
    $file11 = $Global:XrmClient | Export-XrmSolution -SolutionUniqueName $salesName -Managed $true -ExportPath $drop11 -AddVersionToFileName $true;
    $Global:XrmClient | Remove-XrmSolutionComponent -SolutionUniqueName $salesName -ComponentId $w2Id -ComponentType $webResourceType | Out-Null;
    Upsert-XrmSolution -XrmClient $Global:XrmClient -UniqueName $salesName -Version "1.2.0.0" | Out-Null;
    Export-XrmSolution -XrmClient $Global:XrmClient -SolutionUniqueName $salesName -Managed $true -ExportPath $drop12 | Out-Null;
    foreach ($folder in $drop11, $drop12) { Copy-Item -Path ([System.IO.Path]::Combine($drop10, "$($decoyName)_managed.zip")) -Destination $folder; }
    Assert-Test "Versioned export: $([System.IO.Path]::GetFileName($file11))" { [System.IO.Path]::GetFileName($file11) -eq "$($salesName)_1_1_0_0_managed.zip" };

    # The managed imports must create the components: remove the unmanaged solutions and web resources
    foreach ($name in $salesName, $decoyName) { Uninstall-XrmSolution -XrmClient $Global:XrmClient -SolutionUniqueName $name | Out-Null; }
    foreach ($id in $w1Id, $w2Id, $d1Id) { $Global:XrmClient | Remove-XrmRecord -LogicalName "webresource" -Id $id; }
    Assert-Test "Unmanaged solutions and web resources removed" { -not (Test-XrmSolution -XrmClient $Global:XrmClient -SolutionUniqueName $salesName) -and -not (Test-WebResource -Name $webResourceNames.W1) };

    # ============================================================
    # Import: exact file name (H4)
    # ============================================================
    Write-Section "Import-XrmSolutionsBuild - exact file name (H4)";

    $notFoundError = $null;
    try { Import-XrmSolutionsBuild -XrmClient $Global:XrmClient -ArtifactsPath $drop10 -SolutionsImportOrder "dosales$suffix" -ErrorAction Stop; } catch { $notFoundError = $_.Exception.Message; }
    Assert-Test "A name that only ends the file names is not found" { $notFoundError -like "*'dosales$suffix' not found*" };

    Import-XrmSolutionsBuild -XrmClient $Global:XrmClient -ArtifactsPath $drop10 -SolutionsImportOrder $salesName;
    Assert-Test "1.0 imported from $($salesName)_managed.zip, not from $($decoyName)_managed.zip ($(Get-SolutionVersion -UniqueName $salesName))" {
        (Get-SolutionVersion -UniqueName $salesName) -eq "1.0.0.0 managed=True" -and -not (Test-XrmSolution -XrmClient $Global:XrmClient -SolutionUniqueName $decoyName) -and
        (Test-WebResource -Name $webResourceNames.W1) -and (Test-WebResource -Name $webResourceNames.W2);
    };

    # ============================================================
    # Upgrade (H2, H5)
    # ============================================================
    Write-Section "Import-XrmSolutionsBuild -Upgrade / SolutionsImportUpgrade (H2, H5)";

    $whatIfErrors = $null;
    Import-XrmSolutionsBuild -XrmClient $Global:XrmClient -ArtifactsPath $drop11 -SolutionsImportOrder $salesName -Upgrade $true -WhatIf -ErrorVariable whatIfErrors;
    Assert-Test "-WhatIf: nothing imported, no error" { (Get-SolutionVersion -UniqueName $salesName) -eq "1.0.0.0 managed=True" -and $whatIfErrors.Count -eq 0 };

    Import-XrmSolutionsBuild -XrmClient $Global:XrmClient -ArtifactsPath $drop11 -SolutionsImportOrder $salesName -Upgrade $true;
    Assert-Test "-Upgrade `$true: versioned 1.1 file imported as an upgrade, W1 deleted, W2 kept ($(Get-SolutionVersion -UniqueName $salesName))" {
        (Get-SolutionVersion -UniqueName $salesName) -eq "1.1.0.0 managed=True" -and -not (Test-WebResource -Name $webResourceNames.W1) -and (Test-WebResource -Name $webResourceNames.W2) -and
        -not (Test-XrmSolution -XrmClient $Global:XrmClient -SolutionUniqueName "$($salesName)_Upgrade");
    };

    Import-XrmSolutionsBuild -XrmClient $Global:XrmClient -ArtifactsPath $drop12 -SolutionsImportOrder $salesName -SolutionsImportUpgrade "other$suffix, $salesName";
    Assert-Test "SolutionsImportUpgrade (names trimmed): 1.2 imported as an upgrade, W2 deleted ($(Get-SolutionVersion -UniqueName $salesName))" {
        (Get-SolutionVersion -UniqueName $salesName) -eq "1.2.0.0 managed=True" -and -not (Test-WebResource -Name $webResourceNames.W2) -and
        -not (Test-XrmSolution -XrmClient $Global:XrmClient -SolutionUniqueName "$($salesName)_Upgrade");
    };

    # ============================================================
    # Export: Create step filtering attributes (H1)
    # ============================================================
    Write-Section "Export-XrmSolutionsBuild -ClearCreateStepFilteringAttributes (H1)";

    $source = @"
using System;
using Microsoft.Xrm.Sdk;
namespace PdoTest
{
    public class BuildNoOpPlugin : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider) { }
    }
}
"@
;
    $assemblyPath = New-TestPluginAssembly -AssemblyName $assemblyName -Source $source;
    if (-not $assemblyPath) {
        Write-Host " [SKIP] .NET Framework compiler not available: H1 step tests skipped" -ForegroundColor Yellow;
    }
    else {
        Upsert-XrmSolution -XrmClient $Global:XrmClient -UniqueName $stepsSolutionName -DisplayName "PDO steps $suffix" -PublisherReference $publisherRef -Version "1.0.0.0" | Out-Null;
        $Global:XrmClient | Upsert-XrmAssembly -AssemblyPath $assemblyPath;
        $assembly = $Global:XrmClient | Get-XrmRecord -LogicalName "pluginassembly" -AttributeName "name" -Value $assemblyName -Columns "name";
        $typeId = $Global:XrmClient | Add-XrmRecord -Record (New-XrmEntity -LogicalName "plugintype" -Attributes @{
                typename = "PdoTest.BuildNoOpPlugin"; name = "PdoTest.BuildNoOpPlugin"; friendlyname = "BuildNoOpPlugin"; pluginassemblyid = $assembly.Reference
            });
        $message = $Global:XrmClient | Get-XrmRecord -LogicalName "sdkmessage" -AttributeName "name" -Value "Create" -Columns "name";
        $filterQuery = New-XrmQueryExpression -LogicalName "sdkmessagefilter" -Columns "primaryobjecttypecode";
        $filterQuery = $filterQuery | Add-XrmQueryCondition -Field "sdkmessageid" -Condition Equal -Values $message.Id;
        $filterQuery = $filterQuery | Add-XrmQueryCondition -Field "primaryobjecttypecode" -Condition Equal -Values "letter";
        $filter = ($Global:XrmClient | Get-XrmMultipleRecords -Query $filterQuery -AsArray)[0];
        $stepIds = @{};
        foreach ($key in "InSolution", "Outside") {
            $stepIds[$key] = $Global:XrmClient | Add-XrmRecord -Record (New-XrmEntity -LogicalName "sdkmessageprocessingstep" -Attributes @{
                    name                = "PdoTest build $($key): Create of letter";
                    eventhandler        = (New-XrmEntityReference -LogicalName "plugintype" -Id $typeId);
                    sdkmessageid        = $message.Reference;
                    sdkmessagefilterid  = $filter.Reference;
                    stage               = (New-XrmOptionSetValue -Value 40);
                    mode                = (New-XrmOptionSetValue -Value 0);
                    rank                = 1;
                    supporteddeployment = (New-XrmOptionSetValue -Value 0);
                    filteringattributes = "subject";
                });
        }
        $stepType = Get-XrmSolutionComponentType -XrmClient $Global:XrmClient -LogicalName "sdkmessageprocessingstep";
        $Global:XrmClient | Add-XrmSolutionComponent -SolutionUniqueName $stepsSolutionName -ComponentId $stepIds.InSolution -ComponentType $stepType -AddRequiredComponents $false | Out-Null;

        function Get-StepFilter([Guid] $Id) { return ($Global:XrmClient | Get-XrmRecord -LogicalName "sdkmessageprocessingstep" -Id $Id -Columns "filteringattributes").filteringattributes; }
        $initial = "$(Get-StepFilter $stepIds.InSolution)|$(Get-StepFilter $stepIds.Outside)";
        if ($initial -ne "subject|subject") {
            Write-Host " [SKIP] The platform did not keep filtering attributes on a Create step ($initial): H1 step tests skipped" -ForegroundColor Yellow;
        }
        else {
            Export-XrmSolutionsBuild -XrmClient $Global:XrmClient -ExportPath $stepsDrop -Solutions $stepsSolutionName -Managed $false;
            Assert-Test "Default: export written, no step updated" {
                (Test-Path ([System.IO.Path]::Combine($stepsDrop, "$stepsSolutionName.zip"))) -and (Get-StepFilter $stepIds.InSolution) -eq "subject" -and (Get-StepFilter $stepIds.Outside) -eq "subject";
            };

            $stepsWhatIfErrors = $null;
            Export-XrmSolutionsBuild -XrmClient $Global:XrmClient -ExportPath $stepsDrop -Solutions $stepsSolutionName -Managed $false -ClearCreateStepFilteringAttributes $true -WhatIf -ErrorVariable stepsWhatIfErrors;
            Assert-Test "-ClearCreateStepFilteringAttributes -WhatIf: no step updated, no error" { (Get-StepFilter $stepIds.InSolution) -eq "subject" -and $stepsWhatIfErrors.Count -eq 0 };

            Export-XrmSolutionsBuild -XrmClient $Global:XrmClient -ExportPath $stepsDrop -Solutions $stepsSolutionName -Managed $false -ClearCreateStepFilteringAttributes $true;
            Assert-Test "-ClearCreateStepFilteringAttributes: the step of the exported solution cleared, the other one kept" {
                [string]::IsNullOrEmpty((Get-StepFilter $stepIds.InSolution)) -and (Get-StepFilter $stepIds.Outside) -eq "subject";
            };
        }
    }
}
finally {
    Write-Section "Cleanup";
    foreach ($name in $salesName, $decoyName, $stepsSolutionName, "$($salesName)_Upgrade") {
        try { Uninstall-XrmSolution -XrmClient $Global:XrmClient -SolutionUniqueName $name -IfExists | Out-Null; } catch { Write-Host " Cleanup of solution $($name): $($_.Exception.Message)" -ForegroundColor Yellow; }
    }
    foreach ($name in $webResourceNames.Values) {
        $leftover = $Global:XrmClient | Get-XrmRecord -LogicalName "webresource" -AttributeName "name" -Value $name -Columns "name" -IfExists;
        if ($leftover) { $Global:XrmClient | Remove-XrmRecord -LogicalName "webresource" -Id $leftover.Id; }
    }
    if ($Global:XrmClient | Get-XrmRecord -LogicalName "pluginassembly" -AttributeName "name" -Value $assemblyName -Columns "name" -IfExists) {
        Remove-XrmPluginAssembly -XrmClient $Global:XrmClient -Name $assemblyName -Force | Out-Null;
    }
    $publisher = $Global:XrmClient | Get-XrmRecord -LogicalName "publisher" -AttributeName "uniquename" -Value $publisherUniqueName -Columns "uniquename" -IfExists;
    if ($publisher) { $Global:XrmClient | Remove-XrmRecord -LogicalName "publisher" -Id $publisher.Id; }
    Remove-Item -Path $root -Recurse -Force -ErrorAction SilentlyContinue;
    Assert-Test "Test solutions, web resources, assembly and publisher removed" {
        -not (Test-XrmSolution -XrmClient $Global:XrmClient -SolutionUniqueName $salesName) -and -not (Test-XrmSolution -XrmClient $Global:XrmClient -SolutionUniqueName $stepsSolutionName) -and
        -not (Test-XrmPublisher -XrmClient $Global:XrmClient -PublisherUniqueName $publisherUniqueName);
    };
}

Write-TestSummary;