tests/Client/ScriptBlockScope.Tests.ps1

<#
    Static Test: scriptblock scope
    A scriptblock passed to a command (ForEach-ObjectWithProgress, Invoke-XrmQueryPagesInternal, Watch-XrmAsynchOperation...)
    runs in its own scope: there, $PSBoundParameters is the scriptblock one, so a test such as
    $PSBoundParameters.ContainsKey("TopCount") is always false. Read it before the scriptblock.
    Also checks that every name read from $PSBoundParameters is a parameter of the function (H21).
#>

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

Write-Section "PSBoundParameters inside passed scriptblocks";

$srcPath = Join-Path $PSScriptRoot "..\..\src" | Resolve-Path;
$violations = [System.Collections.Generic.List[string]]::new();
foreach ($file in Get-ChildItem -Path $srcPath -Recurse -Include "*.ps1") {
    $ast = [System.Management.Automation.Language.Parser]::ParseFile($file.FullName, [ref]$null, [ref]$null);
    $blocks = $ast.FindAll({
            $args[0] -is [System.Management.Automation.Language.ScriptBlockExpressionAst] -and
            $args[0].Parent -is [System.Management.Automation.Language.CommandAst] -and
            $args[0].Parent.GetCommandName() -ne "Register-ArgumentCompleter"
        }, $true);
    foreach ($block in $blocks) {
        $block.FindAll({ $args[0] -is [System.Management.Automation.Language.VariableExpressionAst] -and $args[0].VariablePath.UserPath -eq "PSBoundParameters" }, $true) | ForEach-Object {
            $violations.Add("$($file.FullName.Substring($srcPath.Path.Length + 1)):$($_.Extent.StartLineNumber) in a $($block.Parent.GetCommandName()) scriptblock");
        };
    }
}

$violations | ForEach-Object { Write-Host " $_" -ForegroundColor Yellow; };
Assert-Test "No `$PSBoundParameters read inside a passed scriptblock ($($violations.Count) found)" {
    $violations.Count -eq 0;
};

Write-Section "Parameter names read from PSBoundParameters";

# $PSBoundParameters.Nmae is $null, without any error: the parameter is silently ignored
$dictionaryMembers = [System.Collections.Generic.Dictionary[string, object]].GetMembers().Name;
$unknownNames = [System.Collections.Generic.List[string]]::new();
foreach ($file in Get-ChildItem -Path $srcPath -Recurse -Include "*.ps1") {
    $ast = [System.Management.Automation.Language.Parser]::ParseFile($file.FullName, [ref]$null, [ref]$null);
    $functions = $ast.FindAll({ $args[0] -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $args[0].Body.ParamBlock -and -not $args[0].Body.DynamicParamBlock }, $true);
    foreach ($function in $functions) {
        $parameterNames = @($function.Body.ParamBlock.Parameters.Name.VariablePath.UserPath) + @([System.Management.Automation.PSCmdlet]::CommonParameters) + @([System.Management.Automation.PSCmdlet]::OptionalCommonParameters);
        $function.Body.FindAll({ $args[0] -is [System.Management.Automation.Language.ExpressionAst] }, $true) | ForEach-Object {
            $name = $null;
            if ($_ -is [System.Management.Automation.Language.InvokeMemberExpressionAst]) {
                if ("$($_.Expression)" -eq '$PSBoundParameters' -and "$($_.Member)" -eq "ContainsKey") { $name = $_.Arguments[0].Value; }
            }
            elseif ($_ -is [System.Management.Automation.Language.MemberExpressionAst]) {
                if ("$($_.Expression)" -eq '$PSBoundParameters' -and $_.Member.Value -notin $dictionaryMembers) { $name = $_.Member.Value; }
            }
            elseif ($_ -is [System.Management.Automation.Language.IndexExpressionAst] -and "$($_.Target)" -eq '$PSBoundParameters') {
                $name = $_.Index.Value;
            }
            if ($name -and $name -notin $parameterNames) {
                $unknownNames.Add("$($file.FullName.Substring($srcPath.Path.Length + 1)):$($_.Extent.StartLineNumber) $name");
            }
        };
    }
}

$unknownNames | ForEach-Object { Write-Host " $_" -ForegroundColor Yellow; };
Assert-Test "Every name read from `$PSBoundParameters is a parameter of the function ($($unknownNames.Count) unknown)" {
    $unknownNames.Count -eq 0;
};

Write-TestSummary;