Tests/Public/Test-PWSHYBKPIVPin.Tests.ps1

[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '',
    Justification = 'Test fixture value, not a real secret; SecureString-typed parameters require a real SecureString even in unit tests.')]
param()

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
    }

    $script:SecurePin = ConvertTo-SecureString -String '123456' -AsPlainText -Force
}

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

Describe 'Test-PWSHYBKPIVPin' -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 -Pin dynamic parameter' {
        { Test-PWSHYBKPIVPin -Confirm:$false -ErrorAction Stop } | Should -Throw
    }

    It 'Returns $true when the PIN verifies successfully' {
        Test-PWSHYBKPIVPin -Pin $script:SecurePin -Confirm:$false | Should -BeTrue
    }

    It 'Returns $false instead of throwing when verification fails' {
        Mock -ModuleName Posh-YBKPIV Invoke-PWSHYBKPIVTool { throw 'Verify PIN failed' }
        Test-PWSHYBKPIVPin -Pin $script:SecurePin -Confirm:$false | Should -BeFalse
    }

    It 'Does not attempt verification when -WhatIf is used' {
        Test-PWSHYBKPIVPin -Pin $script:SecurePin -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-PWSHYBKPIVPin -Pin $script:SecurePin -Confirm:$false } | Should -Throw -ExpectedMessage '*Install-PWSHYBKPIVTool*'
    }
}