tests/Views/TestView.Tests.ps1

<#
    Integration Test: Test-XrmView
    The definition of the given view is validated (H13): until 2.0.0.70 an empty FetchXml was sent, refused for every view.
    No invalid view to test: the platform refuses to save one.
#>

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

function Get-ViewError([Guid]$ViewId) {
    try {
        Test-XrmView -XrmClient $Global:XrmClient -ViewId $ViewId -ErrorAction Stop | Out-Null;
    }
    catch {
        return $_.Exception.Message;
    }
}

Write-Section "Valid view";
$fetchXml = "<fetch><entity name='account'><attribute name='name' /></entity></fetch>";
$layoutXml = "<grid name='resultset' object='1' jump='name' select='1' icon='1' preview='1'><row name='result' id='accountid'><cell name='name' width='300' /></row></grid>";
$viewRef = $Global:XrmClient | Add-XrmView -EntityLogicalName "account" -Name (Get-TestName -Prefix "TestView") -FetchXml $fetchXml -LayoutXml $layoutXml;
$response = Test-XrmView -XrmClient $Global:XrmClient -ViewId $viewRef.Id;
Assert-Test "Response returned" { $response -is [Microsoft.Xrm.Sdk.OrganizationResponse] -and $response.ResponseName -eq "ValidateSavedQuery" };

# Some system views have no FetchXml: nothing to validate
$viewQuery = New-XrmQueryExpression -LogicalName "savedquery" -Columns "name" | Add-XrmQueryCondition -Field "returnedtypecode" -Condition Equal -Values "account" | Add-XrmQueryCondition -Field "querytype" -Condition In -Values 1, 2, 4, 64 | Add-XrmQueryCondition -Field "fetchxml" -Condition NotNull;
$otherViews = Get-XrmMultipleRecords -XrmClient $Global:XrmClient -Query $viewQuery -AsArray;
$viewErrors = @(foreach ($view in $otherViews) { Get-ViewError -ViewId $view.Id; });
Assert-Test "$($otherViews.Count) account views of the other types accepted (advanced find, associated, quick find, lookup) $($viewErrors -join ' | ')" { $otherViews.Count -gt 0 -and $viewErrors.Count -eq 0 };

Write-Section "Unknown view";
$unknownId = [Guid]::NewGuid();
$unknownError = Get-ViewError -ViewId $unknownId;
Assert-Test "Error naming the view: $unknownError" { $unknownError -like "*$unknownId*not found*" };

Write-Section "Cleanup";
$Global:XrmClient | Remove-XrmRecord -LogicalName "savedquery" -Id $viewRef.Id;
Assert-Test "View deleted" { $null -eq (Get-XrmRecord -XrmClient $Global:XrmClient -LogicalName "savedquery" -Id $viewRef.Id -Columns "name" -IfExists) };

Write-TestSummary;