pester / Pester

Pester is the ubiquitous test and mock framework for PowerShell.
https://pester.dev/
Other
3.07k stars 469 forks source link

Infinite loop for `FileInfo` and `DirectoryInfo` due to `Root` properties in `DirectoryInfo`. Should we restrict depth as a general fix in addition to specialcasing `DirectoryInfo` in `Get-DisplayProperty2`? #2474

Open nohwnd opened 3 months ago

nohwnd commented 3 months ago

Infinite loop for FileInfo and DirectoryInfo due to Root properties in DirectoryInfo. Should we restrict depth as a general fix in addition to specialcasing DirectoryInfo in Get-DisplayProperty2?

_Originally posted by @fflaten in https://github.com/pester/Pester/pull/2428#discussion_r1606553664_

nohwnd commented 3 months ago

fflaten wrote:

Experimented a little with this. Example:

# root of Format2.ps1
$script:defaultDisplayPropertyCache = [System.Collections.Generic.Dictionary[type,string[]]]::new()

function Get-DisplayProperty2 ($Object) {
    $propertyMap = @{
        [System.Diagnostics.Process] = 'Id', 'Name'
    }

    $type = $Object.GetType()

    $properties = $propertyMap[$type]
    if ($null -ne $properties) { return $properties }

    # Fallback to DefaultDisplayPropertySet if defined for type
    if ($script:defaultDisplayPropertyCache.TryGetValue($type,[ref]$properties)) { return $properties }

    # Alterantive to enable inheritance: Loop $Object.PSTypeNames with (Get-TypeData $typename).DefaultDisplayPropertySet.ReferencedProperties
    # Would be slower and not sure if any types work this way
    if (($standardMembers = $Object.psobject.Members['PSStandardMembers']) -and
        ($defaultDisplayPropSet = $standardMembers.psobject.Members['DefaultDisplayPropertySet'])) {
        # Is this a live reference we need to break? CopyTo new stringarray?
        $properties = $defaultDisplayPropSet.ReferencedPropertyNames -as [string[]]
    }
    # Always cache to skip repeating PSStandardMembers check
    $script:defaultDisplayPropertyCache.Add($type, $properties)
    $properties
}

Thoughts: