Functions/ConvertTo-CsvString.Tests.ps1

describe "BitTitan.Modules.Common/ConvertTo-CsvString" -Tag "module", "unit" {

    # Import the function to test
    . "$($PSScriptRoot)\ConvertTo-CsvString.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 = ConvertTo-CsvString $csvObject

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

        $csvString | Should Be $expectedOutput
    }

    it "converts an empty CSV object to a null CSV string" {
        # Call the function
        $csvString = ConvertTo-CsvString @()

        # Verify the output
        $csvString | Should Be $null
    }

    # 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" {
                # Call the function
                $csvString = ConvertTo-CsvString $csvObject -ErrorAction SilentlyContinue

                # Verify the output
                $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" {
                # Call the function
                $csvString = ConvertTo-CsvString $csvObject -ErrorAction SilentlyContinue

                # Verify the output
                $csvString | Should Be $null
            }
        }
    }
}