Tests/MicrosoftGraphWindowsUpdates.Tests.ps1

# Requires Pester v5+.

BeforeDiscovery {
    $moduleRoot = Split-Path -Parent $PSScriptRoot
    $manifestPath = Join-Path $moduleRoot 'MicrosoftGraphWindowsUpdates.psd1'
    Import-Module $manifestPath -Force
}

BeforeAll {
    $script:ModuleRoot = Split-Path -Parent $PSScriptRoot
    $script:ManifestPath = Join-Path $script:ModuleRoot 'MicrosoftGraphWindowsUpdates.psd1'
    Import-Module $script:ManifestPath -Force
}

AfterAll {
    Remove-Module MicrosoftGraphWindowsUpdates -Force -ErrorAction SilentlyContinue
}

Describe 'MicrosoftGraphWindowsUpdates manifest' {
    It 'declares Microsoft.Graph.Authentication as a required module' {
        $manifest = Test-ModuleManifest -Path $script:ManifestPath
        $manifest.RequiredModules.Name | Should -Contain 'Microsoft.Graph.Authentication'
    }

    It 'uses community attribution rather than implying Microsoft ownership' {
        $manifest = Test-ModuleManifest -Path $script:ManifestPath
        $manifest.Author | Should -Be 'Community contributors'
        $manifest.CompanyName | Should -Be 'Community'

        $readme = Get-Content -Path (
            Join-Path $script:ModuleRoot 'README.md'
        ) -Raw
        $readme | Should -Match "isn't a Microsoft product"
    }

    It 'contains PowerShell Gallery package metadata' {
        $manifest = Test-ModuleManifest -Path $script:ManifestPath
        $manifest.CompatiblePSEditions | Should -Contain 'Core'
        $manifest.PrivateData.PSData.ContainsKey('Prerelease') |
            Should -BeFalse
        $manifest.PrivateData.PSData.ProjectUri |
            Should -Be (
                'https://learn.microsoft.com/graph/' +
                'windowsupdates-concept-overview'
            )
        $manifest.PrivateData.PSData.LicenseUri |
            Should -Be 'https://opensource.org/license/mit'
        $manifest.PrivateData.PSData.ReleaseNotes |
            Should -Match 'Initial release'
        Test-Path -LiteralPath (
            Join-Path $script:ModuleRoot 'LICENSE'
        ) | Should -BeTrue
    }

    It 'supports a Gallery publish dry run without prerelease metadata' {
        $publishScript = Join-Path (
            Split-Path -Parent $script:ModuleRoot
        ) '..\tools\Publish-MicrosoftGraphWindowsUpdates.ps1'

        {
            & $publishScript -WhatIf
        } | Should -Not -Throw
    }

    It 'publishes with the documented NuGet multipart protocol' {
        $publishScript = Join-Path (
            Split-Path -Parent $script:ModuleRoot
        ) '..\tools\Publish-MicrosoftGraphWindowsUpdates.ps1'
        $port = Get-Random -Minimum 30000 -Maximum 45000
        $publishUri = "http://localhost:$port/api/v2/package/"
        $capturePath = Join-Path $TestDrive 'publish-request.json'
        $packagePath = Join-Path $TestDrive 'test-package.nupkg'
        $apiKeyPath = Join-Path $TestDrive 'gallery-key.dpapi'
        [IO.File]::WriteAllText(
            $packagePath,
            'PK-test-package',
            [Text.Encoding]::ASCII
        )
        ConvertTo-SecureString `
            -String " test$([char] 0x16)-api-key`r`n " `
            -AsPlainText `
            -Force |
            ConvertFrom-SecureString |
            Set-Content -LiteralPath $apiKeyPath -NoNewline

        $listenerJob = Start-Job -ScriptBlock {
            param($Port, $CapturePath, $ApiKeyPath)

            $listener = [Net.HttpListener]::new()
            $listener.Prefixes.Add("http://localhost:$Port/")
            try {
                $listener.Start()
                $context = $listener.GetContext()
                $memory = [IO.MemoryStream]::new()
                $context.Request.InputStream.CopyTo($memory)
                $bodyBytes = $memory.ToArray()
                $contentType = $context.Request.ContentType
                $boundary = (
                    $contentType -split 'boundary=', 2
                )[1].Trim('"')
                $body = [Text.Encoding]::Latin1.GetString($bodyBytes)
                $contentStart = $body.IndexOf("`r`n`r`n") + 4
                $contentEnd = $body.IndexOf(
                    "`r`n--$boundary",
                    $contentStart
                )
                [pscustomobject] @{
                    Method = $context.Request.HttpMethod
                    ApiKey = $context.Request.Headers['X-NuGet-ApiKey']
                    ContentType = $contentType
                    Package = $body.Substring(
                        $contentStart,
                        $contentEnd - $contentStart
                    )
                    KeyFileExistsDuringRequest = Test-Path `
                        -LiteralPath $ApiKeyPath
                } |
                    ConvertTo-Json |
                    Set-Content -LiteralPath $CapturePath
                $context.Response.StatusCode = 201
                $context.Response.Close()
            }
            finally {
                $listener.Stop()
                $listener.Close()
            }
        } -ArgumentList $port, $capturePath, $apiKeyPath

        try {
            Start-Sleep -Milliseconds 500
            & $publishScript `
                -PublishUri $publishUri `
                -PackagePath $packagePath `
                -EncryptedApiKeyPath $apiKeyPath `
                -Confirm:$false
            Wait-Job -Job $listenerJob -Timeout 10 |
                Should -Not -BeNullOrEmpty
            $request = Get-Content -LiteralPath $capturePath -Raw |
                ConvertFrom-Json
            $request.Method | Should -Be 'PUT'
            $request.ApiKey | Should -Be 'test-api-key'
            $request.ContentType | Should -Match '^multipart/form-data;'
            $request.Package | Should -Be 'PK-test-package'
            $request.KeyFileExistsDuringRequest | Should -BeTrue
            Test-Path -LiteralPath $apiKeyPath | Should -BeFalse
        }
        finally {
            Remove-Job -Job $listenerJob -Force -ErrorAction SilentlyContinue
        }
    }

    It 'retains an encrypted API key when publication is not confirmed' {
        $publishScript = Join-Path (
            Split-Path -Parent $script:ModuleRoot
        ) '..\tools\Publish-MicrosoftGraphWindowsUpdates.ps1'
        $packagePath = Join-Path $TestDrive 'failed-package.nupkg'
        $apiKeyPath = Join-Path $TestDrive 'retained-key.dpapi'
        [IO.File]::WriteAllText(
            $packagePath,
            'PK-test-package',
            [Text.Encoding]::ASCII
        )
        ConvertTo-SecureString `
            -String 'test-api-key' `
            -AsPlainText `
            -Force |
            ConvertFrom-SecureString |
            Set-Content -LiteralPath $apiKeyPath -NoNewline

        {
            & $publishScript `
                -PublishUri 'http://localhost:1/api/v2/package/' `
                -PackagePath $packagePath `
                -EncryptedApiKeyPath $apiKeyPath `
                -TimeoutSeconds 1 `
                -Confirm:$false
        } | Should -Throw
        Test-Path -LiteralPath $apiKeyPath | Should -BeTrue
    }

    It 'exports beta management commands and stable report export commands' {
        $commands = Get-Command -Module MicrosoftGraphWindowsUpdates
        $manifest = Test-ModuleManifest -Path $script:ManifestPath
        $stableReports = @(
            'Get-MgWindowsUpdateQualityReport',
            'New-MgWindowsUpdateQualityReportExport',
            'Get-MgWindowsUpdateReportExport',
            'Save-MgWindowsUpdateReportExport'
        )
        Compare-Object `
            -ReferenceObject @($manifest.ExportedFunctions.Keys | Sort-Object) `
            -DifferenceObject @($commands.Name | Sort-Object) |
            Should -BeNullOrEmpty
        $commands.Name |
            Where-Object { $_ -notmatch 'Beta$' -and $_ -notin $stableReports } |
            Should -BeNullOrEmpty
    }

    It 'provides synopsis help for every exported command' {
        foreach ($command in @(Get-Command -Module MicrosoftGraphWindowsUpdates)) {
            (Get-Help $command.Name).Synopsis | Should -Not -BeNullOrEmpty
        }
    }

    It 'provides descriptions, parameter help, and examples for every exported command' {
        $commonParameters = @(
            [System.Management.Automation.Cmdlet]::CommonParameters
            [System.Management.Automation.Cmdlet]::OptionalCommonParameters
        )
        foreach ($command in Get-Command -Module MicrosoftGraphWindowsUpdates) {
            $help = Get-Help $command.Name -Full
            ($help.Description.Text -join ' ') | Should -Not -BeNullOrEmpty
            @(
                $help.Examples.Example |
                    Where-Object { -not [string]::IsNullOrWhiteSpace($_.Code) }
            ).Count | Should -BeGreaterOrEqual 1

            $documentedParameters = @($help.Parameters.Parameter.Name)
            foreach ($parameterName in $command.Parameters.Keys) {
                if ($parameterName -notin $commonParameters) {
                    $documentedParameters | Should -Contain $parameterName
                    (
                        (
                            $help.Parameters.Parameter |
                                Where-Object Name -EQ $parameterName
                        ).Description.Text -join ' '
                    ) | Should -Not -BeNullOrEmpty
                }
            }

        }
    }

    It 'provides syntactically valid, task-oriented examples' {
        foreach ($command in @(Get-Command -Module MicrosoftGraphWindowsUpdates)) {
            $example = (Get-Help $command.Name -Full).Examples.Example
            $code = $example.Code -join [Environment]::NewLine
            $remarks = $example.Remarks.Text -join ' '
            $tokens = $null
            $parseErrors = $null
            [void] [System.Management.Automation.Language.Parser]::ParseInput(
                $code,
                [ref] $tokens,
                [ref] $parseErrors
            )

            $parseErrors | Should -BeNullOrEmpty
            $remarks | Should -Not -Match 'representative values|Replace placeholders'

            $meaningfulParameters = @(
                $command.Parameters.Keys |
                    Where-Object {
                        $_ -notin @(
                            [System.Management.Automation.Cmdlet]::CommonParameters
                            [System.Management.Automation.Cmdlet]::OptionalCommonParameters
                        )
                    }
            )
            if ($meaningfulParameters.Count -gt 0) {
                $usedParameters = @(
                    $meaningfulParameters |
                        Where-Object { $code -match "-$([regex]::Escape($_))(?:\s|$)" }
                )
                $usedParameters.Count | Should -BeGreaterThan 0
            }
        }
    }

    It 'documents an actionable quality report export workflow' {
        $example = (
            Get-Help New-MgWindowsUpdateQualityReportExport -Full
        ).Examples.Example.Code -join [Environment]::NewLine

        $example | Should -Match '\$job\s*='
        $example | Should -Match '-ReportType\s+PolicyStatusSummary'
        $example | Should -Match '-Format\s+csv'
        $example | Should -Not -Match '^-WhatIf$'
    }

    It 'exposes only documented OData options for MDM app settings' {
        $command = Get-Command Get-MgWindowsUpdateMdmAppSettingBeta

        $command.Parameters.Keys | Should -Contain 'Select'
        $command.Parameters.Keys | Should -Not -Contain 'Top'
        $command.Parameters.Keys | Should -Not -Contain 'All'
        $command.Parameters.Keys | Should -Not -Contain 'Query'
    }

    It 'includes a syntactically valid Quality Update report example' {
        $examplePath = Join-Path $script:ModuleRoot 'Examples\Get-QualityUpdateReport.ps1'
        $tokens = $null
        $parseErrors = $null
        [void] [System.Management.Automation.Language.Parser]::ParseFile(
            $examplePath,
            [ref] $tokens,
            [ref] $parseErrors
        )

        $parseErrors | Should -BeNullOrEmpty
    }

    It 'includes a syntactically valid tenant validation example' {
        $examplePath = Join-Path `
            $script:ModuleRoot `
            'Examples\Test-MgWindowsUpdatesTenant.ps1'
        $tokens = $null
        $parseErrors = $null
        [void] [System.Management.Automation.Language.Parser]::ParseFile(
            $examplePath,
            [ref] $tokens,
            [ref] $parseErrors
        )

        $parseErrors | Should -BeNullOrEmpty
    }

    It 'catalogs every Device Updates beta resource and complex type' {
        $types = @(Get-MgWindowsUpdateTypeBeta)

        $types.Count | Should -Be 89
        $types.Name | Should -Contain 'windowsUpdateFilter'
        $types.Name | Should -Contain 'qualityUpdateFilter'
        ($types | Where-Object Name -EQ 'windowsUpdateFilter').Abstract |
            Should -BeTrue
    }

    It 'builds validated typed Windows update filters with documented defaults' {
        $qualityFilter = New-MgWindowsUpdateFilterBeta
        $remediationFilter = New-MgWindowsUpdateFilterBeta -Remediation

        $qualityFilter.'@odata.type' |
            Should -Be '#microsoft.graph.windowsUpdates.qualityUpdateFilter'
        $qualityFilter.cadence | Should -Be 'monthly'
        $qualityFilter.classification | Should -Be 'all'
        $remediationFilter.'@odata.type' |
            Should -Be '#microsoft.graph.windowsUpdates.remediationUpdateFilter'
        $remediationFilter.remediationType | Should -Be 'inPlaceUpgrade'
    }

    It 'builds any documented Windows updates request type' {
        $settings = New-MgWindowsUpdateObjectBeta `
            -TypeName dateDrivenRolloutSettings `
            -Property @{ startDateTime = '2026-11-15T18:00:00Z' }

        $settings.'@odata.type' |
            Should -Be '#microsoft.graph.windowsUpdates.dateDrivenRolloutSettings'
        $settings.startDateTime | Should -Be '2026-11-15T18:00:00Z'
        {
            New-MgWindowsUpdateObjectBeta -TypeName notDocumented
        } | Should -Throw '*constructible Device Updates beta type*'
        {
            New-MgWindowsUpdateObjectBeta -TypeName windowsUpdateFilter
        } | Should -Throw '*constructible Device Updates beta type*'
    }
}

Describe 'Quality Update report example context isolation' {
    BeforeEach {
        Mock Import-Module
        Mock Connect-MgGraph
        Mock Get-MgWindowsUpdateQualityReport
        $script:RequestedTenantId = [guid]::NewGuid()
    }

    It 'rejects a mismatched active tenant before requesting report data' {
        $activeTenantId = [guid]::NewGuid()
        Mock Get-MgContext {
            [pscustomobject] @{
                TenantId = $activeTenantId.ToString()
                Environment = 'Global'
                AuthType = 'Delegated'
                Scopes = @('DeviceManagementConfiguration.ReadWrite.All')
            }
        }
        $examplePath = Join-Path $script:ModuleRoot 'Examples\Get-QualityUpdateReport.ps1'

        {
            & $examplePath -TenantId $script:RequestedTenantId
        } | Should -Throw '*does not match the requested tenant*'

        Should -Invoke Get-MgWindowsUpdateQualityReport -Times 0
    }

    It 'rejects a mismatched active environment before requesting report data' {
        $requestedTenantId = [guid]::NewGuid()
        Mock Get-MgContext {
            [pscustomobject] @{
                TenantId = $requestedTenantId.ToString()
                Environment = 'USGov'
                AuthType = 'Delegated'
                Scopes = @('DeviceManagementConfiguration.ReadWrite.All')
            }
        }
        $examplePath = Join-Path $script:ModuleRoot 'Examples\Get-QualityUpdateReport.ps1'

        {
            & $examplePath -TenantId $requestedTenantId -Environment Global
        } | Should -Throw '*does not match the requested environment*'

        Should -Invoke Get-MgWindowsUpdateQualityReport -Times 0
    }

    It 'verifies the tenant returned after connecting before requesting report data' {
        $activeTenantId = [guid]::NewGuid()
        Mock Get-MgContext {
            if (-not (Get-Variable ContextCall -Scope Script -ErrorAction SilentlyContinue)) {
                $script:ContextCall = 0
            }
            $script:ContextCall++
            if ($script:ContextCall -eq 1) {
                return $null
            }
            [pscustomobject] @{
                TenantId = $activeTenantId.ToString()
                Environment = 'Global'
                AuthType = 'Delegated'
                Scopes = @('DeviceManagementConfiguration.ReadWrite.All')
            }
        }
        $examplePath = Join-Path $script:ModuleRoot 'Examples\Get-QualityUpdateReport.ps1'

        {
            & $examplePath -TenantId $script:RequestedTenantId
        } | Should -Throw '*does not match the requested tenant*'

        Should -Invoke Connect-MgGraph -Times 1
        Should -Invoke Get-MgWindowsUpdateQualityReport -Times 0
    }

    It 'does not execute without an explicit tenant GUID' {
        $examplePath = Join-Path $script:ModuleRoot 'Examples\Get-QualityUpdateReport.ps1'

        {
            & $examplePath
        } | Should -Throw

        Should -Invoke Connect-MgGraph -Times 0
        Should -Invoke Get-MgWindowsUpdateQualityReport -Times 0
    }
}

Describe 'Tenant validation harness safety' {
    BeforeAll {
        $script:HarnessPath = Join-Path `
            $script:ModuleRoot `
            'Examples\Test-MgWindowsUpdatesTenant.ps1'
        $script:HarnessText = Get-Content -LiteralPath $script:HarnessPath -Raw
    }

    It 'resolves and creates the output directory before importing the module' {
        $resolveIndex = $script:HarnessText.IndexOf(
            '$PSCmdlet.GetUnresolvedProviderPathFromPSPath($OutputPath)'
        )
        $createIndex = $script:HarnessText.IndexOf(
            'New-Item -ItemType Directory -Path $outputDirectory -Force'
        )
        $importIndex = $script:HarnessText.IndexOf('Import-Module $modulePath -Force')

        $resolveIndex | Should -BeGreaterThan -1
        $createIndex | Should -BeGreaterThan $resolveIndex
        $importIndex | Should -BeGreaterThan $createIndex
    }

    It 'downloads to an owned unique directory and removes only that directory' {
        $script:HarnessText | Should -Match (
            'MicrosoftGraphWindowsUpdates-\$\(\[guid\]::NewGuid\(\)\)'
        )
        $script:HarnessText | Should -Match (
            'Remove-Item\s+`\s+-LiteralPath \$temporaryDirectory\s+`'
        )
        $script:HarnessText | Should -Not -Match (
            "GetDirectoryName\(\`$OutputPath\)\) 'validation\.zip'"
        )
    }

    It 'does not claim the connection helper was exercised' {
        $connectionRecord = [regex]::Match(
            $script:HarnessText,
            "(?s)-Command 'Connect-MgWindowsUpdatesBeta'.+?-Status '([^']+)'"
        )

        $connectionRecord.Success | Should -BeTrue
        $connectionRecord.Groups[1].Value | Should -Be 'SKIP'
    }

    It 'requires an explicit tenant and supports each accepted Graph environment' {
        $script:HarnessText | Should -Match (
            '(?s)\[Parameter\(Mandatory\)\].+?\[guid\] \$TenantId'
        )
        $script:HarnessText | Should -Match (
            "\[ValidateSet\('Global', 'USGov', 'USGovDoD'\)\]"
        )
    }

    It 'rejects a verified domain where a tenant GUID is required' {
        {
            & $script:HarnessPath -TenantId 'contoso.onmicrosoft.com'
        } | Should -Throw
    }

    It 'reconnects for context drift and verifies tenant and environment before live reads' {
        $connectIndex = $script:HarnessText.IndexOf('Connect-MgGraph @connectParameters')
        $environmentCheckIndex = $script:HarnessText.IndexOf(
            '$context.Environment -ne $Environment',
            $connectIndex
        )
        $tenantCheckIndex = $script:HarnessText.IndexOf(
            '$context.TenantId -ne $tenantIdValue',
            $connectIndex
        )
        $firstRecordIndex = $script:HarnessText.IndexOf(
            '$records = [Collections.Generic.List[object]]::new()'
        )
        $scopeCheckIndex = $script:HarnessText.IndexOf(
            '$missingScopes = @(',
            $connectIndex
        )

        $script:HarnessText | Should -Match 'TenantId = \$tenantIdValue'
        $script:HarnessText | Should -Match 'Environment = \$Environment'
        $connectIndex | Should -BeGreaterThan -1
        $tenantCheckIndex | Should -BeGreaterThan $connectIndex
        $environmentCheckIndex | Should -BeGreaterThan $connectIndex
        $scopeCheckIndex | Should -BeGreaterThan $connectIndex
        $firstRecordIndex | Should -BeGreaterThan $tenantCheckIndex
        $firstRecordIndex | Should -BeGreaterThan $environmentCheckIndex
        $firstRecordIndex | Should -BeGreaterThan $scopeCheckIndex
    }

    It 'records both tenant and environment in the authentication result' {
        $script:HarnessText | Should -Match 'TenantId = \$context\.TenantId'
        $script:HarnessText | Should -Match 'Environment = \$context\.Environment'
    }

    It 'selects WhatIf validations by mutating verb rather than by WhatIf presence' {
        $script:HarnessText | Should -Match '\$_\.Verb -in @\('
        $script:HarnessText | Should -Not -Match (
            "\$_\.Parameters\.ContainsKey\('WhatIf'\)"
        )
    }
}

Describe 'Connect-MgWindowsUpdatesBeta' {
    InModuleScope MicrosoftGraphWindowsUpdates {
        BeforeEach {
            Mock Connect-MgGraph
        }

        It 'uses the least-privileged read scope by default' {
            Connect-MgWindowsUpdatesBeta

            Should -Invoke Connect-MgGraph -Times 1 -ParameterFilter {
                $Scopes -eq 'WindowsUpdates.Read.All'
            }
        }

        It 'uses the read-write scope only when requested' {
            Connect-MgWindowsUpdatesBeta -ReadWrite

            Should -Invoke Connect-MgGraph -Times 1 -ParameterFilter {
                $Scopes -eq 'WindowsUpdates.ReadWrite.All'
            }
        }

        It 'adds the Intune report export scope only when requested' {
            Connect-MgWindowsUpdatesBeta -IncludeIntuneReports

            Should -Invoke Connect-MgGraph -Times 1 -ParameterFilter {
                $Scopes -contains 'WindowsUpdates.Read.All' -and
                $Scopes -contains 'DeviceManagementConfiguration.ReadWrite.All'
            }
        }
    }
}

Describe 'Windows updates request behavior' {
    InModuleScope MicrosoftGraphWindowsUpdates {
        BeforeEach {
            Mock Get-MgContext {
                [pscustomobject] @{
                    AuthType = 'Delegated'
                    Environment = 'Global'
                    Scopes = @(
                        'WindowsUpdates.ReadWrite.All'
                        'DeviceManagementConfiguration.ReadWrite.All'
                    )
                }
            }
            Mock Get-MgEnvironment {
                [pscustomobject] @{
                    Name = 'Global'
                    GraphEndpoint = 'https://graph.microsoft.com'
                }
            }
            Mock Connect-MgGraph
            Mock Invoke-MgGraphRequest {
                param($Uri)

                if ($Uri.AbsolutePath -like '*/resourceConnections') {
                    return @{
                        value = @(
                            [pscustomobject] @{
                                id = 'operational-1'
                                '@odata.type' = (
                                    '#microsoft.graph.windowsUpdates.' +
                                    'operationalInsightsConnection'
                                )
                            }
                            [pscustomobject] @{
                                id = 'other-1'
                                '@odata.type' = (
                                    '#microsoft.graph.windowsUpdates.' +
                                    'resourceConnection'
                                )
                            }
                        )
                    }
                }

                if ($Uri -eq 'https://graph.microsoft.com/beta/admin/windows/updates/deployments?page=2') {
                    return @{
                        value = @([pscustomobject] @{ id = 'deployment-2' })
                    }
                }

                return @{
                    value = @([pscustomobject] @{ id = 'deployment-1' })
                    '@odata.nextLink' =
                        'https://graph.microsoft.com/beta/admin/windows/updates/deployments?page=2'
                }
            }
        }

        Describe 'Microsoft Graph quality update report exports' {
            InModuleScope MicrosoftGraphWindowsUpdates {
                BeforeEach {
                    Mock Get-MgContext {
                        [pscustomobject] @{
                            AuthType = 'Delegated'
                            Environment = 'Global'
                            Scopes = @('DeviceManagementConfiguration.ReadWrite.All')
                        }
                    }
                    Mock Invoke-MgGraphRequest {
                        return @{
                            id = 'export-job-1'
                            status = 'notStarted'
                        }
                    }
                }

                It 'creates a supported quality device status export through Graph' {
                    $policyId = [guid]::NewGuid()
                    $job = New-MgWindowsUpdateQualityReportExport `
                        -ReportType DeviceStatusByPolicy `
                        -PolicyId $policyId `
                        -Confirm:$false

                    $job.id | Should -Be 'export-job-1'
                    Should -Invoke Invoke-MgGraphRequest -Times 1 -ParameterFilter {
                        $Method -eq 'POST' -and
                        $Uri.AbsoluteUri -eq (
                            'https://graph.microsoft.com/v1.0/deviceManagement/reports/exportJobs'
                        ) -and
                        $Body.reportName -eq 'QualityUpdateDeviceStatusByPolicy' -and
                        $Body.filter -eq "PolicyId eq '$policyId'" -and
                        $Body.select -contains 'CurrentDeviceUpdateStatus'
                    }
                }

                It 'requires a policy for low-level per-policy export jobs' {
                    {
                        New-MgWindowsUpdateQualityReportExport `
                            -ReportType DeviceErrorsByPolicy `
                            -Confirm:$false
                    } | Should -Throw '*required by Microsoft Graph*'
                }

                It 'defaults to the policy status summary report' {
                    $job = New-MgWindowsUpdateQualityReportExport -Confirm:$false

                    $job.id | Should -Be 'export-job-1'
                    Should -Invoke Invoke-MgGraphRequest -Times 1 -ParameterFilter {
                        $Body.reportName -eq 'QualityUpdatePolicyStatusSummary'
                    }
                }

                It 'reuses the active Graph context without reconnecting' {
                    New-MgWindowsUpdateQualityReportExport -Confirm:$false

                    Should -Invoke Get-MgContext -Times 1
                    Should -Invoke Connect-MgGraph -Times 0
                }

                It 'fails without prompting when the active context lacks the report scope' {
                    Mock Get-MgContext {
                        [pscustomobject] @{
                            AuthType = 'Delegated'
                            Environment = 'Global'
                            Scopes = @('WindowsUpdates.Read.All')
                        }
                    }

                    {
                        New-MgWindowsUpdateQualityReportExport -Confirm:$false
                    } | Should -Throw '*missing required scope*'

                    Should -Invoke Connect-MgGraph -Times 0
                    Should -Invoke Invoke-MgGraphRequest -Times 0
                }

                It 'honors WhatIf when creating an export job' {
                    New-MgWindowsUpdateQualityReportExport `
                        -ReportType PolicyStatusSummary `
                        -WhatIf

                    Should -Invoke Invoke-MgGraphRequest -Times 0
                }

                It 'does not poll or download an export job under WhatIf' {
                    Mock Get-MgWindowsUpdateReportExport
                    Mock Invoke-WebRequest

                    Save-MgWindowsUpdateReportExport `
                        -ExportJobId 'export-job-1' `
                        -Path 'report.zip' `
                        -WhatIf

                    Should -Invoke Get-MgWindowsUpdateReportExport -Times 0
                    Should -Invoke Invoke-WebRequest -Times 0
                }

                It 'does not create an export job when WhatIf is inherited' {
                    Mock New-MgWindowsUpdateQualityReportExport
                    $WhatIfPreference = $true

                    Get-MgWindowsUpdateQualityReport

                    Should -Invoke New-MgWindowsUpdateQualityReportExport -Times 0
                }

                It 'rejects an existing export file unless Force is specified' {
                    $path = Join-Path $TestDrive 'existing.zip'
                    Set-Content -LiteralPath $path -Value 'original'
                    Mock Get-MgWindowsUpdateReportExport
                    Mock Invoke-WebRequest

                    {
                        Save-MgWindowsUpdateReportExport `
                            -ExportJobId 'export-job-1' `
                            -Path $path `
                            -Confirm:$false
                    } | Should -Throw '*already exists*Use -Force*'

                    (Get-Content -LiteralPath $path -Raw).Trim() | Should -Be 'original'
                    Should -Invoke Get-MgWindowsUpdateReportExport -Times 0
                    Should -Invoke Invoke-WebRequest -Times 0
                }

                It 'rejects a directory as the export file path' {
                    $path = Join-Path $TestDrive 'export-directory'
                    $null = New-Item -ItemType Directory -Path $path

                    {
                        Save-MgWindowsUpdateReportExport `
                            -ExportJobId 'export-job-1' `
                            -Path $path `
                            -Confirm:$false
                    } | Should -Throw '*is a directory*'
                }

                It 'downloads through a partial sibling and atomically publishes the file' {
                    $path = Join-Path $TestDrive 'completed.zip'
                    Mock Get-MgWindowsUpdateReportExport {
                        [pscustomobject] @{
                            status = 'completed'
                            url = 'https://download.example/report.zip'
                        }
                    }
                    Mock Invoke-WebRequest {
                        param($OutFile)
                        Set-Content -LiteralPath $OutFile -Value 'complete'
                    }

                    $result = Save-MgWindowsUpdateReportExport `
                        -ExportJobId 'export-job-1' `
                        -Path $path `
                        -Confirm:$false

                    $result.FullName | Should -Be $path
                    (Get-Content -LiteralPath $path -Raw).Trim() | Should -Be 'complete'
                    @(Get-ChildItem -LiteralPath $TestDrive -Filter '*.partial').Count |
                        Should -Be 0
                    Should -Invoke Invoke-WebRequest -Times 1 -ParameterFilter {
                        $OutFile -like "$path.*.partial"
                    }
                }

                It 'replaces an existing export file only when Force is specified' {
                    $path = Join-Path $TestDrive 'replace.zip'
                    Set-Content -LiteralPath $path -Value 'original'
                    Mock Get-MgWindowsUpdateReportExport {
                        [pscustomobject] @{
                            status = 'completed'
                            url = 'https://download.example/report.zip'
                        }
                    }
                    Mock Invoke-WebRequest {
                        param($OutFile)
                        Set-Content -LiteralPath $OutFile -Value 'replacement'
                    }

                    Save-MgWindowsUpdateReportExport `
                        -ExportJobId 'export-job-1' `
                        -Path $path `
                        -Force `
                        -Confirm:$false |
                        Out-Null

                    (Get-Content -LiteralPath $path -Raw).Trim() |
                        Should -Be 'replacement'
                }

                It 'fails closed if a directory appears at a Force destination during polling' {
                    $path = Join-Path $TestDrive 'raced-destination.zip'
                    Mock Get-MgWindowsUpdateReportExport {
                        [pscustomobject] @{
                            status = 'completed'
                            url = 'https://download.example/report.zip'
                        }
                    }
                    Mock Invoke-WebRequest {
                        param($OutFile)
                        Set-Content -LiteralPath $OutFile -Value 'replacement'
                        $null = New-Item -ItemType Directory -Path $path
                    }

                    {
                        Save-MgWindowsUpdateReportExport `
                            -ExportJobId 'export-job-1' `
                            -Path $path `
                            -Force `
                            -Confirm:$false
                    } | Should -Throw

                    Test-Path -LiteralPath $path -PathType Container | Should -BeTrue
                    @(Get-ChildItem -LiteralPath $path).Count | Should -Be 0
                    @(Get-ChildItem -LiteralPath $TestDrive -Filter '*.partial').Count |
                        Should -Be 0
                }

                It 'removes a partial download when the transfer fails' {
                    $path = Join-Path $TestDrive 'failed.zip'
                    Mock Get-MgWindowsUpdateReportExport {
                        [pscustomobject] @{
                            status = 'completed'
                            url = 'https://download.example/report.zip'
                        }
                    }
                    Mock Invoke-WebRequest {
                        param($OutFile)
                        Set-Content -LiteralPath $OutFile -Value 'partial'
                        throw 'network reset'
                    }

                    {
                        Save-MgWindowsUpdateReportExport `
                            -ExportJobId 'export-job-1' `
                            -Path $path `
                            -Confirm:$false
                    } | Should -Throw 'network reset'

                    Test-Path -LiteralPath $path | Should -BeFalse
                    @(Get-ChildItem -LiteralPath $TestDrive -Filter '*.partial').Count |
                        Should -Be 0
                }

                It 'returns quality update report rows and removes temporary data' {
                    Mock New-Item
                    Mock New-MgWindowsUpdateQualityReportExport {
                        [pscustomobject] @{ id = 'export-job-1' }
                    }
                    Mock Save-MgWindowsUpdateReportExport
                    Mock Expand-Archive
                    Mock Get-ChildItem {
                        [pscustomobject] @{ FullName = 'report.csv' }
                    } -ParameterFilter {
                        $Filter -eq '*.csv'
                    }
                    Mock Import-Csv {
                        [pscustomobject] @{
                            DeviceName = 'device-1'
                            CurrentDeviceUpdateStatus = 'Succeeded'
                        }
                    }
                    Mock Test-Path { $true }
                    Mock Remove-Item

                    $result = Get-MgWindowsUpdateQualityReport `
                        -ReportType DeviceStatusByPolicy `
                        -PolicyId ([guid]::NewGuid())

                    $result.DeviceName | Should -Be 'device-1'
                    $result.CurrentDeviceUpdateStatus | Should -Be 'Succeeded'
                    Should -Invoke Save-MgWindowsUpdateReportExport -Times 1
                    Should -Invoke Import-Csv -Times 1
                    Should -Invoke Remove-Item -Times 1
                }

                It 'uses the default report type when returning report data' {
                    Mock New-Item
                    Mock New-MgWindowsUpdateQualityReportExport {
                        [pscustomobject] @{ id = 'export-job-1' }
                    }
                    Mock Save-MgWindowsUpdateReportExport
                    Mock Expand-Archive
                    Mock Get-ChildItem {
                        [pscustomobject] @{ FullName = 'report.csv' }
                    } -ParameterFilter {
                        $Filter -eq '*.csv'
                    }
                    Mock Import-Csv {
                        [pscustomobject] @{ PolicyName = 'Quality policy' }
                    }
                    Mock Test-Path { $true }
                    Mock Remove-Item

                    $result = Get-MgWindowsUpdateQualityReport

                    $result.PolicyName | Should -Be 'Quality policy'
                    Should -Invoke New-MgWindowsUpdateQualityReportExport -Times 1 -ParameterFilter {
                        $ReportType -eq 'PolicyStatusSummary'
                    }
                }

                It 'fans tenant-wide device reports out across summary policy IDs' {
                    $script:importCall = 0
                    $firstPolicyId = [guid]::NewGuid()
                    $secondPolicyId = [guid]::NewGuid()
                    Mock New-Item
                    Mock New-MgWindowsUpdateQualityReportExport {
                        [pscustomobject] @{ id = [guid]::NewGuid().ToString() }
                    }
                    Mock Save-MgWindowsUpdateReportExport
                    Mock Expand-Archive
                    Mock Get-ChildItem {
                        [pscustomobject] @{ FullName = 'report.csv' }
                    } -ParameterFilter {
                        $Filter -eq '*.csv'
                    }
                    Mock Import-Csv {
                        $script:importCall++
                        if ($script:importCall -eq 1) {
                            return @(
                                [pscustomobject] @{ PolicyId = $firstPolicyId }
                                [pscustomobject] @{ PolicyId = $secondPolicyId }
                            )
                        }
                        [pscustomobject] @{ DeviceName = "device-$script:importCall" }
                    }
                    Mock Test-Path { $true }
                    Mock Remove-Item

                    $result = @(
                        Get-MgWindowsUpdateQualityReport `
                            -ReportType DeviceStatusByPolicy
                    )

                    $result.DeviceName | Should -Be @('device-2', 'device-3')
                    Should -Invoke New-MgWindowsUpdateQualityReportExport -Times 1 -ParameterFilter {
                        $ReportType -eq 'PolicyStatusSummary'
                    }
                    Should -Invoke New-MgWindowsUpdateQualityReportExport -Times 2 -ParameterFilter {
                        $ReportType -eq 'DeviceStatusByPolicy' -and
                        $PolicyId -in $firstPolicyId, $secondPolicyId
                    }
                }
            }
        }

        It 'encodes OData queries and follows next links with All' {
            $result = @(
                Get-MgWindowsUpdateDeploymentBeta `
                    -Filter "state/effectiveValue eq 'scheduled'" `
                    -Select id,state `
                    -Top 10 `
                    -Count `
                    -All
            )

            $result.id | Should -Be @('deployment-1', 'deployment-2')
            Should -Invoke Invoke-MgGraphRequest -Times 2
            Should -Invoke Invoke-MgGraphRequest -Times 1 -ParameterFilter {
                $Uri.AbsoluteUri -like (
                    'https://graph.microsoft.com/beta/admin/windows/updates/deployments?*'
                ) -and
                $Uri.AbsoluteUri -match (
                    '\$filter=state%2FeffectiveValue%20eq%20%27scheduled%27'
                ) -and
                $Uri.AbsoluteUri -match '\$select=id%2Cstate' -and
                $Uri.AbsoluteUri -match '\$top=10' -and
                $Uri.AbsoluteUri -match '\$count=true' -and
                $Headers.ConsistencyLevel -eq 'eventual'
            }
        }

        It 'uses the active sovereign-cloud endpoint for management and report requests' {
            Mock Get-MgContext {
                [pscustomobject] @{
                    AuthType = 'Delegated'
                    Environment = 'USGov'
                    Scopes = @(
                        'WindowsUpdates.ReadWrite.All'
                        'DeviceManagementConfiguration.ReadWrite.All'
                    )
                }
            }
            Mock Get-MgEnvironment {
                [pscustomobject] @{
                    Name = 'USGov'
                    GraphEndpoint = 'https://graph.microsoft.us'
                }
            }
            Mock Invoke-MgGraphRequest {
                [pscustomobject] @{ id = 'result-1' }
            }

            Get-MgWindowsUpdateDeploymentBeta | Out-Null
            New-MgWindowsUpdateQualityReportExport -Confirm:$false | Out-Null

            Should -Invoke Invoke-MgGraphRequest -Times 1 -ParameterFilter {
                $Uri.AbsoluteUri -eq (
                    'https://graph.microsoft.us/beta/admin/windows/updates/deployments'
                )
            }
            Should -Invoke Invoke-MgGraphRequest -Times 1 -ParameterFilter {
                $Uri.AbsoluteUri -eq (
                    'https://graph.microsoft.us/v1.0/deviceManagement/reports/exportJobs'
                )
            }
        }

        It 'normalizes a leading-slash Graph path on the active endpoint' {
            $uri = ConvertTo-MgWindowsUpdatesRequestUri `
                -Path '/v1.0/deviceManagement/reports/exportJobs' `
                -GraphEndpoint ([uri] 'https://graph.microsoft.com')

            $uri | Should -Be (
                'https://graph.microsoft.com/v1.0/deviceManagement/reports/exportJobs'
            )
        }

        It 'rejects export job IDs that could change the normalized route' {
            {
                Get-MgWindowsUpdateReportExport `
                    -ExportJobId '../../../users?x='
            } | Should -Throw

            Should -Invoke Invoke-MgGraphRequest -Times 0
        }

        It 'rejects an absolute request URI outside the active Graph environment' {
            {
                Invoke-MgWindowsUpdatesRequest `
                    -Method GET `
                    -Path 'https://graph.microsoft.us/beta/admin/windows/updates/deployments'
            } | Should -Throw '*does not match the active environment endpoint*'

            Should -Invoke Invoke-MgGraphRequest -Times 0
        }

        It 'rejects a next link outside the active Graph environment' {
            Mock Invoke-MgGraphRequest {
                return @{
                    value = @([pscustomobject] @{ id = 'deployment-1' })
                    '@odata.nextLink' = (
                        'https://graph.microsoft.us/beta/admin/windows/updates/' +
                        'deployments?page=2'
                    )
                }
            }

            {
                Get-MgWindowsUpdateDeploymentBeta -All
            } | Should -Throw '*does not match the active environment endpoint*'

            Should -Invoke Invoke-MgGraphRequest -Times 1
        }

        It 'stops pagination before sending a request after Graph context drift' {
            $script:ContextReadCount = 0
            Mock Get-MgContext {
                $script:ContextReadCount++
                [pscustomobject] @{
                    TenantId = if ($script:ContextReadCount -lt 3) {
                        '00000000-0000-0000-0000-000000000001'
                    }
                    else {
                        '00000000-0000-0000-0000-000000000002'
                    }
                    AuthType = 'Delegated'
                    Environment = 'Global'
                    Scopes = @('WindowsUpdates.ReadWrite.All')
                }
            }

            {
                Get-MgWindowsUpdateDeploymentBeta -All
            } | Should -Throw '*context changed while the request was in progress*'

            Should -Invoke Invoke-MgGraphRequest -Times 1
        }

        It 'rejects literal and encoded path traversal before calling Graph' {
            {
                Invoke-MgWindowsUpdatesRequest `
                    -Method GET `
                    -Path 'deployments/../../users'
            } | Should -Throw '*unsafe path segment*'
            {
                Invoke-MgWindowsUpdatesRequest `
                    -Method GET `
                    -Path 'deployments/%2e%2e/%2e%2e/users'
            } | Should -Throw '*unsafe path segment*'

            Should -Invoke Invoke-MgGraphRequest -Times 0
        }

        It 'does not follow next links without All' {
            $result = @(Get-MgWindowsUpdateDeploymentBeta)

            $result.id | Should -Be @('deployment-1')
            Should -Invoke Invoke-MgGraphRequest -Times 1
        }

        It 'returns no objects for an empty Graph collection' {
            Mock Invoke-MgGraphRequest {
                return @{
                    value = @()
                    '@odata.context' = (
                        'https://graph.microsoft.com/beta/$metadata#' +
                        'admin/windows/updates/deployments'
                    )
                }
            }

            $result = @(Get-MgWindowsUpdateDeploymentBeta)

            $result.Count | Should -Be 0
        }

        It 'handles a single OData query parameter under strict mode' {
            Get-MgWindowsUpdateDeploymentBeta -Top 1

            Should -Invoke Invoke-MgGraphRequest -Times 1 -ParameterFilter {
                $Uri.AbsoluteUri -eq (
                    'https://graph.microsoft.com/beta/admin/windows/updates/deployments?$top=1'
                )
            }
        }

        It 'accepts the read-write scope for read operations without reconnecting' {
            Get-MgWindowsUpdateDeploymentBeta

            Should -Invoke Get-MgContext -Times 1
            Should -Invoke Connect-MgGraph -Times 0
        }

        It 'fails management mutations without the read-write scope or a prompt' {
            Mock Get-MgContext {
                [pscustomobject] @{
                    AuthType = 'Delegated'
                    Environment = 'Global'
                    Scopes = @('WindowsUpdates.Read.All')
                }
            }

            {
                Remove-MgWindowsUpdateDeploymentBeta `
                    -DeploymentId 'deployment-1' `
                    -Confirm:$false
            } | Should -Throw '*WindowsUpdates.ReadWrite.All*'

            Should -Invoke Connect-MgGraph -Times 0
            Should -Invoke Invoke-MgGraphRequest -Times 0
        }

        It 'passes a typed enrollment request to the documented beta action' {
            Register-MgWindowsUpdateAssetByIdBeta `
                -UpdateCategory feature `
                -Id @('device-1', 'device-2') `
                -Confirm:$false

            Should -Invoke Invoke-MgGraphRequest -Times 1 -ParameterFilter {
                $Method -eq 'POST' -and
                $Uri -eq (
                    'https://graph.microsoft.com/beta/admin/windows/updates/' +
                    'updatableAssets/enrollAssetsById'
                ) -and
                $Body.updateCategory -eq 'feature' -and
                $Body.ids.Count -eq 2 -and
                $Body.memberEntityType -eq (
                    '#microsoft.graph.windowsUpdates.azureADDevice'
                )
            }
        }

        It 'routes derived resource wrappers to their documented collections' {
            Get-MgWindowsUpdateAzureAdDeviceBeta -Top 1
            $connections = @(
                Get-MgWindowsUpdateOperationalInsightsConnectionBeta -Top 1
            )

            Should -Invoke Invoke-MgGraphRequest -Times 1 -ParameterFilter {
                $Uri.AbsoluteUri -like (
                    'https://graph.microsoft.com/beta/admin/windows/updates/' +
                    'updatableAssets/microsoft.graph.windowsUpdates.azureADDevice*'
                )
            }
            Should -Invoke Invoke-MgGraphRequest -Times 1 -ParameterFilter {
                $Uri.AbsoluteUri -like (
                    'https://graph.microsoft.com/beta/admin/windows/updates/' +
                    'resourceConnections?*'
                )
            }
            $connections.id | Should -Be @('operational-1')
        }

        It 'honors WhatIf for mutations' {
            Remove-MgWindowsUpdateDeploymentBeta -DeploymentId 'deployment-1' -WhatIf

            Should -Invoke Invoke-MgGraphRequest -Times 0
        }

        It 'accepts no-content responses from delete mutations' {
            Mock Invoke-MgGraphRequest { $null }

            {
                Remove-MgWindowsUpdateDeploymentBeta `
                    -DeploymentId 'deployment-1' `
                    -Confirm:$false
            } | Should -Not -Throw
        }

        It 'accepts no-content responses from post actions' {
            Mock Invoke-MgGraphRequest { $null }

            {
                Update-MgWindowsUpdateDeploymentAudienceByIdBeta `
                    -DeploymentId 'deployment-1' `
                    -MemberEntityType '#microsoft.graph.windowsUpdates.azureADDevice' `
                    -AddMember 'device-1' `
                    -Confirm:$false
            } | Should -Not -Throw
        }

        It 'omits unbound audience update lists and rejects an empty update' {
            Update-MgWindowsUpdateDeploymentAudienceByIdBeta `
                -DeploymentId 'deployment-1' `
                -MemberEntityType '#microsoft.graph.windowsUpdates.azureADDevice' `
                -AddMember 'device-1' `
                -Confirm:$false

            Should -Invoke Invoke-MgGraphRequest -Times 1 -ParameterFilter {
                $Body.addMembers -eq 'device-1' -and
                -not $Body.ContainsKey('removeMembers') -and
                -not $Body.ContainsKey('addExclusions') -and
                -not $Body.ContainsKey('removeExclusions')
            }
            {
                Update-MgWindowsUpdateDeploymentAudienceByIdBeta `
                    -DeploymentId 'deployment-1' `
                    -MemberEntityType '#microsoft.graph.windowsUpdates.azureADDevice' `
                    -Confirm:$false
            } | Should -Throw '*at least one member or exclusion list*'
        }

        It 'does not mutate caller-owned request bodies' {
            $assetBody = @{ displayName = 'group-1' }
            $approvalBody = @{ isRevoked = $false }

            New-MgWindowsUpdateAssetGroupBeta `
                -Body $assetBody `
                -WhatIf
            New-MgWindowsUpdateContentApprovalBeta `
                -UpdatePolicyId 'policy-1' `
                -Body $approvalBody `
                -WhatIf

            $assetBody.ContainsKey('@odata.type') | Should -BeFalse
            $approvalBody.ContainsKey('@odata.type') | Should -BeFalse
        }

        It 'propagates Graph errors' {
            Mock Invoke-MgGraphRequest {
                throw [InvalidOperationException]::new('Graph request failed')
            }

            {
                Get-MgWindowsUpdateDeploymentBeta
            } | Should -Throw 'Graph request failed'
        }
    }
}