Functions/Set-DefaultValue.Tests.ps1

describe "BitTitan.Runbooks.Common/Set-DefaultValue" -Tag "module", "unit" {

    # Import the function to test
    . "$($PSScriptRoot)\Set-DefaultValue.ps1"

    it "sets the variable to the default value when given a variable containing null" {
        $Global:variable = $null
        $variable | Set-DefaultValue 42
        $variable | Should Be 42

        $Global:variable = $null
        $variable | Set-DefaultValue "string"
        $variable | Should Be "string"

        $Global:variable = $null
        $variable | Set-DefaultValue $true
        $variable | Should Be $true

        $Global:variable = $null
        $variable | Set-DefaultValue @(1, 2, 3)
        $variable | Should Be @(1, 2, 3)
    }

    it "does not change the value of the variable when given a variable already containing a value" {
        $Global:variable = 5
        $variable | Set-DefaultValue 42
        $variable | Should Be 5

        $Global:variable = "foo"
        $variable | Set-DefaultValue "bar"
        $variable | Should Be "foo"

        $Global:variable = $false
        $variable | Set-DefaultValue $true
        $variable | Should Be $false

        $Global:variable = @(1, 2)
        $variable | Set-DefaultValue @(1, 2, 3)
        $variable | Should Be @(1, 2)
    }

    it "throws an exception when the variable is not passed through the pipeline" {
        $Global:variable = $null
        try {
            Set-DefaultValue 42 $variable

            # Throw an exception - this statement should not be executed
            $true | Should Be $false
        }
        catch {
            $_.Exception.Message | Should BeLike "Set-DefaultValue should be given the variable through the pipeline*"
        }
        $variable | Should Be $null
    }

    it "removes the script variable and sets the default for the global variable when given a script variable containing null" {
        $Global:variable = 5
        $Script:variable = $null
        $variable | Set-DefaultValue 42
        $Script:Variable | Should Be $null
        $Global:Variable | Should Be 42
    }

    it "does not change the value of the global or script variable when given a script variable already containing a value" {
        $Global:variable = 5
        $Script:variable = 10
        $variable | Set-DefaultValue 42
        $Global:variable | Should Be 5
        $Script:variable | Should Be 10
    }
}