Tests/Private/Share.Tests.ps1

BeforeDiscovery {
    Import-Module (Join-Path $PSScriptRoot '../../Posh-SecretRotation.psd1') -Force
}

Describe 'Private/Share' -Tag Unit {
    InModuleScope 'Posh-SecretRotation' {
        Describe 'Export-SecretRotationShareFile' {
            BeforeAll {
                $script:outputDir = Join-Path ([System.IO.Path]::GetTempPath()) "SecretRotationShareTest-$([guid]::NewGuid())"
            }

            AfterAll {
                Remove-Item -Path $script:outputDir -Recurse -Force -ErrorAction SilentlyContinue
            }

            It 'writes one file per share, never a combined file' {
                $shares = @(
                    [PSCustomObject]@{ Identifier = 1; Extendable = $false; IterationExponent = 0; GroupIndex = 0; GroupThreshold = 1; GroupCount = 1; MemberIndex = 0; MemberThreshold = 3; Mnemonic = 'alpha bravo charlie' }
                    [PSCustomObject]@{ Identifier = 1; Extendable = $false; IterationExponent = 0; GroupIndex = 0; GroupThreshold = 1; GroupCount = 1; MemberIndex = 1; MemberThreshold = 3; Mnemonic = 'delta echo foxtrot' }
                )

                $paths = $shares | Export-SecretRotationShareFile -OutputPath $script:outputDir

                @($paths).Count | Should -Be 2
                (Get-ChildItem -Path $script:outputDir -Filter '*.txt').Count | Should -Be 2
            }

            It 'names each file uniquely by group/member indices and writes only that share''s data' {
                $shares = @(
                    [PSCustomObject]@{ Identifier = 2; Extendable = $true; IterationExponent = 1; GroupIndex = 0; GroupThreshold = 1; GroupCount = 1; MemberIndex = 0; MemberThreshold = 2; Mnemonic = 'one two three' }
                )

                $path = $shares | Export-SecretRotationShareFile -OutputPath $script:outputDir
                $path | Should -BeLike '*share-group0-member0of2.txt'

                $content = Get-Content -Path $path -Raw
                $content | Should -BeLike '*one two three*'
                $content | Should -Not -BeLike '*alpha bravo charlie*'
            }

            It 'creates the output directory if it does not exist yet' {
                $freshDir = Join-Path $script:outputDir "nested-$([guid]::NewGuid())"
                Test-Path -Path $freshDir | Should -Be $false

                [PSCustomObject]@{ Identifier = 3; Extendable = $false; IterationExponent = 0; GroupIndex = 0; GroupThreshold = 1; GroupCount = 1; MemberIndex = 0; MemberThreshold = 2; Mnemonic = 'x y z' } |
                    Export-SecretRotationShareFile -OutputPath $freshDir | Out-Null

                Test-Path -Path $freshDir | Should -Be $true
            }
        }
    }
}