Functions/Convert-CsvObjectToString.Tests.ps1

describe "BitTitan.Modules.Csv/Convert-CsvObjectToString" -Tag "module", "unit" {

    # Import the function to test
    . "$($PSScriptRoot)\Convert-CsvObjectToString.ps1"

    # Prepare the input
    $csvObject = @(
        [PSCustomObject]@{
            Name1 = "1"
            Name2 = $true
            Name3 = $false
            Name4 = "ゟ"
        },
        [PSCustomObject]@{
            Name1 = 2
            Name2 = $false
            Name3 = $true
            Name4 = "ᆐ"
        }
    )

    it "converts a CSV object containing unicode characters to a CSV string when there are no issues" {
        # Call the function
        $csvString = Convert-CsvObjectToString $csvObject

        # Verify the output
        $expectedOutput = @"
sep=,
"name1","name2","name3","name4"
"1","True","False","ゟ"
"2","False","True","ᆐ"
 
"@

        $csvString | Should Be $expectedOutput
    }

    # Declare external functions to fail one at a time
    $externalFunctionsToFail = @(
        "New-TemporaryFile",
        "Export-Csv",
        "Get-Content"
    )
    foreach ($function in $externalFunctionsToFail) {
        context "when $($function) has an issue" {
            # mock the function to return null
            mock $function {}

            it "returns null when $($function) fails, with an error message" {
                # Call the function
                $csvString = Convert-CsvObjectToString $csvObject -ErrorAction SilentlyContinue -ErrorVariable errorVariable

                # Verify the output
                $errorVariable | Should Not BeNullOrEmpty
                $csvString | Should Be $null
            }

            # Mock the function to throw an exception
            mock $function { throw "mocking function to throw an exception" }

            it "returns null when $($function) throws an exception, with an error message" {
                # Call the function
                $csvString = Convert-CsvObjectToString $csvObject -ErrorAction SilentlyContinue -ErrorVariable errorVariable

                # Verify the output
                $errorVariable | Should Not BeNullOrEmpty
                $csvString | Should Be $null
            }

            it "returns null when $($function) throws an exception, with a warning message" {
                # Call the function
                $csvString = Convert-CsvObjectToString $csvObject -OutputStream Warning -WarningAction SilentlyContinue -WarningVariable warningVariable

                # Verify the output
                $warningVariable | Should Not BeNullOrEmpty
                $csvString | Should Be $null
            }
        }
    }
}