Tests/Inventory.Tests.ps1

#Requires -Modules Pester
# Inventory: type loading, optional/forbidden/select fallback, device paging and tag fill-in, date format.

BeforeAll {
    . (Join-Path $PSScriptRoot 'TestHelpers.ps1')
    $script:IsoUtc = '^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(Z|[+-]00:00)$'
}

Describe 'Update-STMInventory on the demo tenant' {
    BeforeAll {
        Mock -ModuleName IntuneScopeTagManager Start-Sleep { }
        [void](Connect-TestTenant -Mode ReadOnly -Name inv)
        $script:status = @(Update-STMInventory -WarningAction SilentlyContinue)
        $script:registry = InSTM { @(Get-STMTypeRegistry) }
    }

    It 'loads every non-onDemand registry type' {
        $expected = @($registry | Where-Object { -not ($_.PSObject.Properties['onDemand'] -and $_.onDemand) } | ForEach-Object { $_.key })
        $expected.Count | Should -BeGreaterThan 30
        @($status.Type | Sort-Object) | Should -Be @($expected | Sort-Object)
        $status.Type | Should -Not -Contain 'ManagedDevice'
    }

    It 'reports Loaded for every type the tenant has, with the mock object counts' {
        foreach ($s in $status | Where-Object { $_.Type -notin 'MicrosoftTunnelSite', 'WindowsQualityUpdatePolicy' }) {
            $s.State | Should -Be 'Loaded' -Because $s.Type
            $s.Count | Should -Be @(Get-MockObjects -Type $s.Type).Count -Because $s.Type
        }
    }

    It 'marks optional types missing from the tenant as NotAvailable (not Failed)' {
        foreach ($t in 'MicrosoftTunnelSite', 'WindowsQualityUpdatePolicy') {
            ($status | Where-Object Type -eq $t).State | Should -Be 'NotAvailable'
        }
    }

    It 'loads scope tags and role assignments' {
        $st = Get-STMState
        @($st.Tags).Count | Should -Be 9
        @($st.RoleAssignments).Count | Should -Be 4
        ($st.Tags | Where-Object Id -eq '6').AssignedGroupIds | Should -Be @('a1111111-0000-4000-8000-000000000007')
        $st.GroupNames['a1111111-0000-4000-8000-000000000001'] | Should -Be 'SG-Intune-Helpdesk-East'
    }

    It 'keeps tags as sorted string ids that match the mock' {
        $obj = Get-MockObjects -Type DeviceConfiguration | Select-Object -First 1
        $row = (Get-STMState).Inventory["DeviceConfiguration|$($obj.id)"]
        $row.TagsKnown | Should -BeTrue
        (@($row.TagIds) -join ',') | Should -Be (Get-MockTags -Type DeviceConfiguration -Id $obj.id)
    }

    It 'returns Modified dates as ISO 8601 UTC strings' {
        $rows = @((Get-STMState).Inventory.Values | Where-Object Modified)
        $rows.Count | Should -BeGreaterThan 100
        foreach ($r in $rows) { $r.Modified | Should -BeOfType [string]; $r.Modified | Should -Match $IsoUtc }
    }

    It 'marks DeviceConfiguration with supportsScopeTags=false as not supported' {
        $legacy = @((Get-STMState).Inventory.Values | Where-Object { $_.Type -eq 'DeviceConfiguration' -and -not $_.Supported })
        $legacy.Count | Should -Be 1
        $legacy[0].Note | Should -Match 'supportsScopeTags'
    }

    It 'Get-STMInventory -Tag filters by tag name' {
        $rows = @(Get-STMInventory -Tag 'Pilot')
        $rows.Count | Should -BeGreaterThan 0
        foreach ($r in $rows) { $r.ScopeTagIds -split ';' | Should -Contain '8' }
    }
}

Describe 'Update-STMTypeInventory fault handling' {
    BeforeEach {
        Mock -ModuleName IntuneScopeTagManager Start-Sleep { }
        [void](Connect-TestTenant -Mode ReadOnly)
        [void](InSTM { Update-STMScopeTags })
    }

    It 'ForbiddenPaths -> NoPermission' {
        InSTM { $script:STMMock.Options.ForbiddenPaths = @('deviceManagement/intents') }
        $s = InSTM { Update-STMTypeInventory -TypeKey Intent }
        $s.State | Should -Be 'NoPermission'
        $s.Error | Should -Match '403'
    }

    It 'a non-optional type missing from the tenant -> Failed' {
        InSTM { $script:STMMock.Options.MissingPaths += 'deviceManagement/intents' }
        (InSTM { Update-STMTypeInventory -TypeKey Intent }).State | Should -Be 'Failed'
    }

    It 'an optional type returning 404 -> NotAvailable' {
        InSTM { $script:STM.MockHandler = { param($m, $u, $b) if ($u -match 'compliancePolicies') { return @{ Status = 404; Body = '{"error":{"message":"nope"}}' } } Invoke-STMMockRequest -Method $m -Uri $u -Body $b } }
        (InSTM { Update-STMTypeInventory -TypeKey CompliancePolicy }).State | Should -Be 'NotAvailable'
    }

    It 'NoSelectPaths -> falls back to an unselected read and still loads' {
        InSTM { $script:STMMock.Options.NoSelectPaths = @('deviceAppManagement/mobileApps') }
        Reset-MockLog
        $s = InSTM { Update-STMTypeInventory -TypeKey MobileApp }
        $s.State | Should -Be 'Loaded'
        $s.SelectFallback | Should -BeTrue
        $s.Count | Should -Be @(Get-MockObjects -Type MobileApp).Count
        $uris = @(Get-MockRequests | ForEach-Object Uri)
        $uris[0] | Should -Match 'select'
        $uris[1] | Should -Not -Match 'select'
    }

    It 'a refresh replaces the type''s rows (deleted objects disappear)' {
        [void](InSTM { Update-STMTypeInventory -TypeKey DeviceCategory })
        $before = @((Get-STMState).Inventory.Keys | Where-Object { $_ -like 'DeviceCategory|*' }).Count
        InSTM { $script:STMMock.Collections['deviceManagement/deviceCategories'].RemoveAt(0) }
        [void](InSTM { Update-STMTypeInventory -TypeKey DeviceCategory })
        @((Get-STMState).Inventory.Keys | Where-Object { $_ -like 'DeviceCategory|*' }).Count | Should -Be ($before - 1)
    }
}

Describe 'Device paging' {
    BeforeEach {
        Mock -ModuleName IntuneScopeTagManager Start-Sleep { }
        [void](Connect-TestTenant -Mode ReadOnly -DeviceCount 25)
        # Small pages so paging is exercised with a small tenant.
        InSTM { (Get-STMTypeDef -Key ManagedDevice).pageSize = 7 }
    }

    It 'Start/Step-STMDeviceLoad loads exactly DeviceCount devices in pages' {
        $d = InSTM { Start-STMDeviceLoad }
        $d.Done | Should -BeFalse
        $pages = 0
        do { $d = InSTM { Step-STMDeviceLoad }; $pages++ } while (-not $d.Done -and $pages -lt 20)
        $pages | Should -Be 4
        $d.Loaded | Should -Be 25
        @((Get-STMState).Inventory.Keys | Where-Object { $_ -like 'ManagedDevice|*' }).Count | Should -Be 25
        $st = (Get-STMState).TypeStatus['ManagedDevice']
        $st.State | Should -Be 'Loaded'
        $st.Count | Should -Be 25
        $st.TagsMissing | Should -Be 0
    }

    It 'applies the operating system filter' {
        $expected = @(Get-MockObjects -Type ManagedDevice | Where-Object operatingSystem -eq 'iOS').Count
        [void](InSTM { Start-STMDeviceLoad -OperatingSystem iOS })
        do { $d = InSTM { Step-STMDeviceLoad } } while (-not $d.Done)
        $d.Loaded | Should -Be $expected
        $d.Filter | Should -Be "operatingSystem eq 'iOS'"
    }

    It 'device rows carry serial, UPN and an ISO 8601 last sync date' {
        [void](InSTM { Start-STMDeviceLoad })
        do { $d = InSTM { Step-STMDeviceLoad } } while (-not $d.Done)
        foreach ($r in @((Get-STMState).Inventory.Values | Where-Object Type -eq 'ManagedDevice')) {
            $r.Extra.serial | Should -Match '^SN\d+$'
            $r.Modified | Should -Match $IsoUtc
        }
    }

    It 'DeviceListOmitsTags -> TagsMissing counted, Update-STMDeviceTags fills them' {
        InSTM { $script:STMMock.Options.DeviceListOmitsTags = $true }
        [void](InSTM { Start-STMDeviceLoad })
        do { $d = InSTM { Step-STMDeviceLoad } } while (-not $d.Done)
        $d.TagsMissing | Should -Be 25
        $rows = @((Get-STMState).Inventory.Values | Where-Object Type -eq 'ManagedDevice')
        @($rows | Where-Object TagsKnown).Count | Should -Be 0
        $ids = @($rows | ForEach-Object Id)
        $n = InSTM { param($ids) Update-STMDeviceTags -DeviceIds $ids } -ArgumentList (, $ids)
        $n | Should -Be 25
        foreach ($r in @((Get-STMState).Inventory.Values | Where-Object Type -eq 'ManagedDevice')) {
            $r.TagsKnown | Should -BeTrue
            (@($r.TagIds) -join ',') | Should -Be (Get-MockTags -Type ManagedDevice -Id $r.Id)
        }
    }

    It 'falls back to an unselected device read when $select is rejected' {
        InSTM { $script:STMMock.Options.NoSelectPaths = @('deviceManagement/managedDevices') }
        [void](InSTM { Start-STMDeviceLoad })
        $guard = 0
        do { $d = InSTM { Step-STMDeviceLoad }; $guard++ } while (-not $d.Done -and $guard -lt 50)
        $d.SelectFallback | Should -BeTrue
        $d.Loaded | Should -Be 25
        (Get-STMState).TypeStatus['ManagedDevice'].State | Should -Be 'Loaded'
    }
}

Describe 'Get-STMLiveObject' {
    BeforeEach {
        Mock -ModuleName IntuneScopeTagManager Start-Sleep { }
        [void](Connect-TestTenant -Mode ReadOnly)
    }

    It 'reads objects live through $batch, with ISO dates, and reports missing ones' {
        $o = Get-MockObjects -Type MobileApp | Select-Object -First 1
        $live = InSTM { param($id) Get-STMLiveObject -Refs @(@{ Type = 'MobileApp'; Id = $id }, @{ Type = 'MobileApp'; Id = 'does-not-exist' }) } -ArgumentList $o.id
        $live["MobileApp|$($o.id)"].Row.Name | Should -Be $o.displayName
        $live["MobileApp|$($o.id)"].Row.Modified | Should -Match $IsoUtc
        $live['MobileApp|does-not-exist'].Row | Should -BeNullOrEmpty
        $live['MobileApp|does-not-exist'].Status | Should -Be 404
    }
}