Tests/Public/Test-PWSHYBKPIVDecryption.Tests.ps1

BeforeAll {
    Import-Module (Resolve-Path "$PSScriptRoot\..\..\Posh-YBKPIV.psd1") -Force

    $script:RealConfigPath = (Resolve-Path "$PSScriptRoot\..\..\Config\Posh-YBKPIV.json").Path
    InModuleScope Posh-YBKPIV -Parameters @{ ConfigPath = $script:RealConfigPath } {
        param($ConfigPath)
        $script:ConfigPath = $ConfigPath
    }
}

AfterAll {
    Remove-Module Posh-YBKPIV -ErrorAction SilentlyContinue
}

Describe 'Test-PWSHYBKPIVDecryption' -Tag Unit {
    BeforeEach {
        $script:InstallExePath = 'C:\Program Files\Yubico\Yubico PIV Tool\bin\yubico-piv-tool.exe'
        Mock -ModuleName Posh-YBKPIV Test-Path { $true } -ParameterFilter { $Path -eq $script:InstallExePath }
        Mock -ModuleName Posh-YBKPIV Resolve-PWSHYBKPIVArchitecture { 'win64' }
        Mock -ModuleName Posh-YBKPIV Get-PWSHYBKPIVInstallPath { $script:InstallExePath }
        Mock -ModuleName Posh-YBKPIV Invoke-PWSHYBKPIVTool { [PSCustomObject]@{ ExitCode = 0; Output = @() } }
    }

    It 'Requires the -Slot dynamic parameter' {
        { Test-PWSHYBKPIVDecryption -Confirm:$false -ErrorAction Stop } | Should -Throw
    }

    It 'Returns $true when the decipher test succeeds' {
        Test-PWSHYBKPIVDecryption -Slot '9a' -Confirm:$false | Should -BeTrue
    }

    It 'Returns $false instead of throwing when the test fails' {
        Mock -ModuleName Posh-YBKPIV Invoke-PWSHYBKPIVTool { throw 'Test decipher failed' }
        Test-PWSHYBKPIVDecryption -Slot '9a' -Confirm:$false | Should -BeFalse
    }

    It 'Warns when the PIN is now blocked, while still returning $false' {
        Mock -ModuleName Posh-YBKPIV Invoke-PWSHYBKPIVTool { throw 'Pin code blocked, use unblock-pin action to unblock.' }
        $result = Test-PWSHYBKPIVDecryption -Slot '9a' -Confirm:$false -WarningVariable warnVar -WarningAction SilentlyContinue
        $result | Should -BeFalse
        [string]$warnVar | Should -Match 'blocked'
    }

    It 'Does not attempt the test when -WhatIf is used' {
        Test-PWSHYBKPIVDecryption -Slot '9a' -WhatIf
        Should -Invoke -ModuleName Posh-YBKPIV Invoke-PWSHYBKPIVTool -Times 0
    }

    It 'Throws a clear error when yubico-piv-tool.exe is not installed' {
        Mock -ModuleName Posh-YBKPIV Test-Path { $false } -ParameterFilter { $Path -eq $script:InstallExePath }
        { Test-PWSHYBKPIVDecryption -Slot '9a' -Confirm:$false } | Should -Throw -ExpectedMessage '*Install-PWSHYBKPIVTool*'
    }
}