Tests/Get-DotEnvValue.Tests.ps1

BeforeAll {

    Set-StrictMode -Version "Latest"

    . "$PSScriptRoot\..\Source\ConvertFrom-DotEnv.ps1"
    . "$PSScriptRoot\..\Source\Get-DotEnv.ps1"
    . "$PSScriptRoot\..\Source\Get-DotEnvValue.ps1"

}

Describe "Get-DotEnvValue" {

    Context "When the file does not exist" {

        It "Throws" {

            $path = Join-Path -Path $TestDrive -ChildPath "missing.env"

            { Get-DotEnvValue -Path $path -Name "TOOLBOX_DATA" } | Should -Throw

        }

    }

    Context "When the file exists" {

        BeforeEach {

            $script:testEnvPath = Join-Path -Path $TestDrive -ChildPath "test.env"

            @(
                "# comment line"
                "TOOLBOX_DATA=dummy-value"
                "OTHER_KEY = other value "
            ) | Set-Content -Path $testEnvPath

        }

        It "Returns the value for an existing key" {

            Get-DotEnvValue -Path $testEnvPath -Name "TOOLBOX_DATA" | Should -Be "dummy-value"

        }

        It "Trims whitespace around the value" {

            Get-DotEnvValue -Path $testEnvPath -Name "OTHER_KEY" | Should -Be "other value"

        }

        It "Throws when the key does not exist" {

            { Get-DotEnvValue -Path $testEnvPath -Name "MISSING_KEY" } | Should -Throw

        }

        It "Accepts the key name from the pipeline" {

            $results = "TOOLBOX_DATA", "OTHER_KEY" | Get-DotEnvValue -Path $testEnvPath

            $results | Should -Be @("dummy-value", "other value")

        }

    }

}