Tests/New-LogFile.Tests.ps1

BeforeAll {
    $script:mockFreeLogClass = $null

    if (-not ('FreeLogClass' -as [type])) {
        Add-Type -TypeDefinition @"
            public class FreeLogClass {
                public FreeLogClass(string path) { }
            }
"@

    }
}

Describe 'New-LogFile' {
    BeforeEach {
        Remove-Variable -Name logger -Scope Script -ErrorAction SilentlyContinue

        $script:testPath = Join-Path -Path $TestDrive -ChildPath 'test.log'
    }

    Context 'Parameter validation' {
        It 'Should throw when Path is null' {
            { New-LogFile -Path $null } | Should -Throw
        }

        It 'Should throw when Path is empty string' {
            { New-LogFile -Path '' } | Should -Throw
        }

        It 'Should accept valid path string' {
            { New-LogFile -Path $script:testPath } | Should -Not -Throw
        }

        It 'Should have mandatory Path parameter' {
            $function = Get-Command New-LogFile
            $function.Parameters['Path'].Attributes.Mandatory | Should -Be $true
        }
    }

    Context 'File system operations' {
        It 'Should not create file when using WhatIf' {
            New-LogFile -Path $script:testPath -WhatIf
            Test-Path -Path $script:testPath | Should -Be $false
        }

        It 'Should create log file when it does not exist' {
            New-LogFile -Path $script:testPath
            Test-Path -Path $script:testPath | Should -Be $true
        }

        It 'Should not throw when log file already exists' {
            New-Item -Path $script:testPath -ItemType File -Force
            { New-LogFile -Path $script:testPath } | Should -Not -Throw
        }

        It 'Should create missing directories in the path' {
            $nestedPath = Join-Path -Path $TestDrive -ChildPath 'nested\folder\structure\test.log'
            New-LogFile -Path $nestedPath
            Test-Path -Path $nestedPath | Should -Be $true
        }

    }

    Context 'Error handling' {
        It 'Should preserve error records' {
            try {
                New-LogFile -Path ''
            }
            catch {
                $_.Exception.Message | Should -Be -Like 'Path cannot be null or empty.'
            }
        }
    }
}