Cmdlets/ConvertTo-SecretKey.Tests.ps1

# ? TITEL ConvertTo-SecretKey (UTest)
# ? DESCRIPTION
# ? TAGS UTest Pester
# ? VERSION 2019.09.09

using Module Microsoft.PowerShell.Management
using Module Microsoft.PowerShell.Utility
using namespace System
using namespace System.Runtime.InteropServices
$ErrorActionPreference = [System.Management.Automation.ActionPreference]::Stop
Set-StrictMode -Version Latest

$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".")
. (Join-Path -Path $here -ChildPath $sut)

Describe "Teste $sut" {

    It "Parameter 'Key' => Mandatory => True" {
        $target = (Get-Command -Name ConvertTo-SecretKey).Parameters['Key'].Attributes.Mandatory
        $target | Should -Be $true 
    }
    
    It "Parameter 'Key' => Attribute 'ValidateLength' => MinLength = 16" {
        $target = (Get-Command ConvertTo-SecretKey).Parameters['Key'].Attributes.Where({$_ -is [System.Management.Automation.ValidateLengthAttribute]})
        $target.MinLength | Should -Be 16 
    }

    It "Parameter 'Key' => Attribute 'ValidateLength' => MaxLength = 32" {
        $target = (Get-Command ConvertTo-SecretKey).Parameters['Key'].Attributes.Where({$_ -is [System.Management.Automation.ValidateLengthAttribute]})
        $target.MaxLength | Should -Be 32 
    }

    It "Parameter 'Key' => throws exception => Argument -lt MinLength" {
        { ConvertTo-SecretKey -Key 123456789012345 } | Should -Throw -ErrorId 'ParameterArgumentValidationError'
    }

    It "Parameter 'Key' => throws exception => Argument -gt MaxLength" {
        { ConvertTo-SecretKey -Key 123456789012345678901234567890123 } | Should -Throw -ErrorId 'ParameterArgumentValidationError'
    }

    It "Parameter 'Key' => Argument -ge MinLength -and -le MaxLength Test1" {
        ConvertTo-SecretKey -Key '12345678901234567' | Should be @(49,50,51,52,53,54,55,56,57,48,49,50,51,52,53,54,55,48,48,48,48,48,48,48,48,48,48,48,48,48,48,48)
    }
    
    It "Parameter 'Key' => Argument -ge MinLength -and -le MaxLength Test2" {
        ConvertTo-SecretKey -Key '12345678901234567890123456789012' | Should be @(49,50,51,52,53,54,55,56,57,48,49,50,51,52,53,54,55,56,57,48,49,50,51,52,53,54,55,56,57,48,49,50)
    }

    It "Return correct Byte-Array for Password-Phrase ('P@ssw0rt-Phrase!')" {
        $key = "P@ssw0rt-Phrase!"
        
        $pad = 32 - $key.Length
        $encoding = New-Object -TypeName System.Text.ASCIIEncoding
        $expected = $encoding.GetBytes($key + "0" * $pad)
        
        $target = ConvertTo-SecretKey -Key $key
        
        $target | Should be $expected
    }
}