Tests/Csv.Tests.ps1

#Requires -Modules Pester
# CSV export/import round trip and the older layouts.

BeforeAll {
    . (Join-Path $PSScriptRoot 'TestHelpers.ps1')

    function Write-TestCsv {
        param([string]$Name, [string[]]$Lines)
        $path = Join-Path $TestDrive $Name
        Set-Content -LiteralPath $path -Value $Lines -Encoding utf8
        return $path
    }
}

Describe 'Export-STMInventoryCsv and Import-STMCsv round trip' {
    BeforeAll {
        Mock -ModuleName IntuneScopeTagManager Start-Sleep { }
        $script:root = Connect-TestTenant -Mode ReadWrite -Name csv
        [void](Update-STMInventory -Type DeviceCategory, Intent, AssignmentFilter -WarningAction SilentlyContinue)
        $script:path = Join-Path $TestDrive 'inventory.csv'
        [void](Export-STMInventoryCsv -Path $path)
        $script:rows = @(Import-Csv $path)
    }

    It 'exports one row per loaded object with the expected columns' {
        $rows.Count | Should -Be (@(Get-MockObjects -Type DeviceCategory).Count + @(Get-MockObjects -Type Intent).Count + @(Get-MockObjects -Type AssignmentFilter).Count)
        @($rows[0].PSObject.Properties.Name) | Should -Be @('ObjectType', 'ObjectId', 'DisplayName', 'Category', 'Platform', 'CurrentScopeTagIds', 'CurrentScopeTags', 'ScopeTags', 'Mode', 'Notes', 'SerialNumber', 'UserPrincipalName')
        foreach ($r in $rows) {
            $r.Mode | Should -BeNullOrEmpty
            $r.CurrentScopeTagIds | Should -Be ((Get-MockTags -Type $r.ObjectType -Id $r.ObjectId) -replace ',', ';')
        }
    }

    It 'writes an InventoryExported audit entry' {
        $a = @(Get-Content (Join-Path $root 'audit.log') | ForEach-Object { $_ | ConvertFrom-Json } | Where-Object event -eq 'InventoryExported')
        $a[-1].rows | Should -Be $rows.Count
    }

    It 'only rows with a Mode become operations, the rest are skipped' {
        $edit = @($rows | ForEach-Object { $_.PSObject.Copy() })
        $edit[0].Mode = 'Add'; $edit[0].ScopeTags = 'Pilot'; $edit[0].Notes = 'CHG-1'
        $edit[2].Mode = 'replace'; $edit[2].ScopeTags = 'Region-East;Region-West'
        $edited = Join-Path $TestDrive 'edited.csv'
        $edit | Export-Csv -LiteralPath $edited -NoTypeInformation -Encoding utf8
        $imp = Import-STMCsv -Path $edited
        $imp.Errors.Count | Should -Be 0
        $imp.Rows | Should -Be $rows.Count
        $imp.Skipped | Should -Be ($rows.Count - 2)
        $imp.Operations.Count | Should -Be 2
        $op0 = $imp.Operations[0]
        $op0.Type | Should -Be $edit[0].ObjectType
        $op0.Id | Should -Be $edit[0].ObjectId
        $op0.Mode | Should -Be 'Add'
        $op0.Tags | Should -Be @('8')
        $op0.Note | Should -Be 'CHG-1'
        $op0.Source | Should -Be 'edited.csv:row 2'
        $imp.Operations[1].Mode | Should -Be 'Replace'
        $imp.Operations[1].Tags -join ',' | Should -Be '4,5'
        $imp.Operations[1].Source | Should -Be 'edited.csv:row 4'
    }

    It 'New-STMChangePlan -CsvPath builds a plan from the edited file' {
        $edit = @($rows | ForEach-Object { $_.PSObject.Copy() })
        $target = $edit | Where-Object { $_.ObjectType -eq 'DeviceCategory' -and $_.CurrentScopeTagIds -notmatch '7' } | Select-Object -First 1
        $target.Mode = 'Add'; $target.ScopeTags = 'Pilot'
        $edited = Join-Path $TestDrive 'edited2.csv'
        $edit | Export-Csv -LiteralPath $edited -NoTypeInformation -Encoding utf8
        $p = New-STMChangePlan -CsvPath $edited -OutputDirectory (Join-Path $TestDrive 'csvplans')
        $p.Title | Should -Be 'Import of edited2.csv'
        $p.Items.Count | Should -Be 1
        $p.Items[0].Source | Should -Be ('edited2.csv:row {0}' -f ([array]::IndexOf($edit, $target) + 2))
        @(Get-ChildItem (Join-Path $TestDrive 'csvplans') -Filter '*.json').Count | Should -Be 1
    }

    It 'New-STMChangePlan -CsvPath refuses a file with errors' {
        $bad = Write-TestCsv 'bad.csv' @('ObjectType,ObjectId,ScopeTags,Mode', "DeviceCategory,$($rows[0].ObjectId),Nope,Add")
        { New-STMChangePlan -CsvPath $bad -WarningAction SilentlyContinue } | Should -Throw '*have errors*'
    }

    It 'New-STMChangePlan -CsvPath refuses a file with no Mode rows' {
        $none = Write-TestCsv 'none.csv' @('ObjectType,ObjectId,ScopeTags,Mode', "DeviceCategory,$($rows[0].ObjectId),Pilot,")
        { New-STMChangePlan -CsvPath $none } | Should -Throw '*Nothing to change*'
    }
}

Describe 'Older CSV layouts' {
    BeforeEach {
        Mock -ModuleName IntuneScopeTagManager Start-Sleep { }
        [void](Connect-TestTenant -Mode ReadWrite -DeviceCount 15)
        $script:cat = @(Get-MockObjects -Type DeviceCategory | ForEach-Object id)
        $script:dev = @(Get-MockObjects -Type ManagedDevice)
    }

    It 'reads the legacy bulk layout (ObjectType, ObjectId, ScopeTags, Mode)' {
        $p = Write-TestCsv 'legacy.csv' @(
            'ObjectType,ObjectId,ScopeTags,Mode'
            "DeviceCategory,$($cat[0]),Corp-Windows;Pilot,Replace"
            "DeviceCategory,$($cat[1]),4,Remove")
        $imp = Import-STMCsv -Path $p
        $imp.Errors.Count | Should -Be 0
        $imp.Operations.Count | Should -Be 2
        $imp.Operations[0].Tags -join ',' | Should -Be '1,8'
        $imp.Operations[1].Mode | Should -Be 'Remove'
    }

    It 'accepts Action and ScopeTagIds as column names' {
        $p = Write-TestCsv 'legacy2.csv' @('ObjectType,ObjectId,ScopeTagIds,Action', "DeviceCategory,$($cat[0]),2,Add")
        $imp = Import-STMCsv -Path $p
        $imp.Operations[0].Mode | Should -Be 'Add'
        $imp.Operations[0].Tags | Should -Be @('2')
    }

    It 'resolves devices by SerialNumber with Mode Set (= Replace), read live when not loaded' {
        $p = Write-TestCsv 'serial.csv' @('SerialNumber,ScopeTags,Mode', "$($dev[2].serialNumber),Corp-Mobile,Set")
        $imp = Import-STMCsv -Path $p
        $imp.Errors.Count | Should -Be 0
        $imp.Operations[0].Type | Should -Be 'ManagedDevice'
        $imp.Operations[0].Id | Should -Be $dev[2].id
        $imp.Operations[0].Mode | Should -Be 'Replace'
        $imp.Operations[0].Tags | Should -Be @('2')
        (Get-STMState).Inventory.ContainsKey("ManagedDevice|$($dev[2].id)") | Should -BeTrue
    }

    It 'resolves devices by DeviceName (case-insensitive) from the loaded inventory' {
        InSTM { [void](Start-STMDeviceLoad); do { $x = Step-STMDeviceLoad } while (-not $x.Done) }
        Reset-MockLog
        $p = Write-TestCsv 'name.csv' @('DeviceName,ScopeTags,Mode', "$($dev[4].deviceName.ToLower()),Pilot,Add")
        $imp = Import-STMCsv -Path $p
        $imp.Operations[0].Id | Should -Be $dev[4].id
        @(Get-MockRequests | Where-Object Uri -match 'managedDevices').Count | Should -Be 0
    }

    It 'reports unknown and duplicate devices' {
        InSTM { param($n) $script:STMMock.Collections['deviceManagement/managedDevices'][1].deviceName = $n } -ArgumentList $dev[0].deviceName
        $p = Write-TestCsv 'devs.csv' @('SerialNumber,DeviceName,ScopeTags,Mode', 'SN-NOPE,,Pilot,Add', ",$($dev[0].deviceName),Pilot,Add")
        $imp = Import-STMCsv -Path $p
        $imp.Operations.Count | Should -Be 0
        $imp.Errors.Count | Should -Be 2
        $imp.Errors[0].Row | Should -Be 2
        $imp.Errors[0].Message | Should -Match "No managed device with serialNumber 'SN-NOPE'"
        $imp.Errors[1].Row | Should -Be 3
        $imp.Errors[1].Message | Should -Match 'Several devices'
    }

    It 'splits tag lists on ; , and |' {
        $p = Write-TestCsv 'split.csv' @('ObjectType,ObjectId,ScopeTags,Mode', "DeviceCategory,$($cat[0]),""Corp-Windows, Pilot|Region-East;Region-West"",Add")
        (Import-STMCsv -Path $p).Operations[0].Tags -join ',' | Should -Be '1,4,5,8'
    }

    It 'skips blank-Mode rows and numbers rows from 2' {
        $p = Write-TestCsv 'rows.csv' @(
            'ObjectType,ObjectId,ScopeTags,Mode'
            "DeviceCategory,$($cat[0]),Pilot,"
            "DeviceCategory,$($cat[1]),Pilot, "
            "DeviceCategory,$($cat[2]),Pilot,Bogus"
            "NotAType,$($cat[2]),Pilot,Add"
            "DeviceCategory,,Pilot,Add"
            ",$($cat[2]),Pilot,Add"
            "DeviceCategory,$($cat[2]),,Add"
            "DeviceCategory,$($cat[2]),Ghost-Tag,Add"
            "DeviceCategory,$($cat[2]),Pilot,Delete")
        $imp = Import-STMCsv -Path $p
        $imp.Rows | Should -Be 9
        $imp.Skipped | Should -Be 2
        $imp.Operations.Count | Should -Be 1
        $imp.Operations[0].Mode | Should -Be 'Remove'
        $imp.Operations[0].Source | Should -Be 'rows.csv:row 10'
        $e = $imp.Errors
        @($e | ForEach-Object Row) | Should -Be @(4, 5, 6, 7, 8, 9)
        $e[0].Message | Should -Match "Mode 'Bogus' is not Add, Remove or Replace"
        $e[1].Message | Should -Match "Unknown ObjectType 'NotAType'"
        $e[2].Message | Should -Match 'ObjectId is empty'
        $e[3].Message | Should -Match 'ObjectType is empty'
        $e[4].Message | Should -Match 'Add needs at least one scope tag'
        $e[5].Message | Should -Match "Ghost-Tag' does not exist"
    }

    It 'a Replace row with no tags is accepted (clears explicit tags in the plan)' {
        $p = Write-TestCsv 'clear.csv' @('ObjectType,ObjectId,ScopeTags,Mode', "DeviceCategory,$($cat[0]),,Replace")
        $imp = Import-STMCsv -Path $p
        $imp.Errors.Count | Should -Be 0
        $imp.Operations[0].Tags.Count | Should -Be 0
    }

    It 'reads a UTF-8 file with BOM written by Excel' {
        $path = Join-Path $TestDrive 'bom.csv'
        [IO.File]::WriteAllText($path, "ObjectType,ObjectId,ScopeTags,Mode`r`nDeviceCategory,$($cat[0]),Pilot,Add`r`n", [Text.UTF8Encoding]::new($true))
        $imp = Import-STMCsv -Path $path
        $imp.Errors.Count | Should -Be 0
        $imp.Operations.Count | Should -Be 1
    }
}