PSOpt2.tests.ps1

<#
    .SYNOPSIS
        TEST TDD BrightModule
    .DESCRIPTION
        Unblock-File
    .EXAMPLE
        While ($true) {$test = Invoke-Pester -CodeCoverage .\BrightModule.Tests.ps1 -PassThru; $test.FailedCount; start-sleep -s 15}
    .EXAMPLE
        'coaxis.com' | Should -Match "\.com$"
        $null | Should -not -BeNullOrEmpty
        "C:\Windows" | Should -Exist
 
        Should -BeExactly
        Should -BeGreaterThan
        Should -BeIn
        Should -BeLessThan
        Should -BeLike
        Should -BeLikeExactly
        Should -BeOfType
        Should -Exist
        Should -FileContentMatch
        Should -FileContentMatchExactly
        Should -Match
        Should -MatchExactly
        Should -Throw
        Should -BeNullOrEmpty
 
 
    .NOTES
        Alopez 2017
        Em@il : alban.lopez@gmail.com
 
        require https://github.com/pester/Pester
 
        https://github.com/pester/Pester/wiki/Should
        Get-ChildItem C:\Users\alopez\Documents\WindowsPowerShell\Modules\Pester\ -Recurse | Unblock-File
 #>


#remove-module BrightModule -force

#Import-Module -Name Pester -Force

function Select-WriteHost {
    [CmdletBinding(DefaultParameterSetName = 'FromPipeline')]
    param(
      [Parameter(ValueFromPipeline = $true, ParameterSetName = 'FromPipeline')]
      [object] $InputObject,
 
      [Parameter(Mandatory = $true, ParameterSetName = 'FromScriptblock', Position = 0)]
      [ScriptBlock] $ScriptBlock,
 
      [switch] $Quiet
    )
 
    begin
    {
      function Cleanup
      {
        # clear out our proxy version of write-host
        remove-item function:\write-host -ea 0
      }
 
      function ReplaceWriteHost([switch] $Quiet, [string] $Scope)
      {
          # create a proxy for write-host
          $metaData = New-Object System.Management.Automation.CommandMetaData (Get-Command 'Microsoft.PowerShell.Utility\Write-Host')
          $proxy = [System.Management.Automation.ProxyCommand]::create($metaData)
 
          # change its behavior
          $content = if($quiet)
                     {
                        # in quiet mode, whack the entire function body, simply pass input directly to the pipeline
                        $proxy -replace '(?s)\bbegin\b.+', '$Object' 
                     }
                     else
                     {
                        # in noisy mode, pass input to the pipeline, but allow real write-host to process as well
                        $proxy -replace '(\$steppablePipeline\.Process)', '$Object; $1'
                     }  
 
          # load our version into the specified scope
          Invoke-Expression "function ${scope}:Write-Host { $content }"
      }
 
      Cleanup
 
      # if we are running at the end of a pipeline, need to immediately inject our version
      # into global scope, so that everybody else in the pipeline uses it.
      # This works great, but dangerous if we don't clean up properly.
      if($pscmdlet.ParameterSetName -eq 'FromPipeline')
      {
         ReplaceWriteHost -Quiet:$quiet -Scope 'global'
      }
    }
 
    process
    {
       # if a scriptblock was passed to us, then we can declare
       # our version as local scope and let the runtime take it out
       # of scope for us. Much safer, but it won't work in the pipeline scenario.
       # The scriptblock will inherit our version automatically as it's in a child scope.
       if($pscmdlet.ParameterSetName -eq 'FromScriptBlock')
       {
         . ReplaceWriteHost -Quiet:$quiet -Scope 'local'
         & $scriptblock
       }
       else
       {
          # in pipeline scenario, just pass input along
          $InputObject
       }
    }
 
    end
    {
       Cleanup
    }  
 }
 
 write-host $MyInvocation.MyCommand.Source -fore yellow
 $ModuleInformation = $MyInvocation.MyCommand.Source -replace ('\.Tests\.ps1', '.psd1') | Import-Module -wa 0 -Force -PassThru
 #Get-ChildItem $("$($MyInvocation.MyCommand.Path)\BrightModule.Tests.ps1" -replace('\.Tests\.ps1', '*.psm1')) | %{Import-Module $_.FullName -Force}
 write-center ($MyInvocation.MyCommand.Source -replace('\.Tests\.ps1', '.psd1'))
 
 # Invoke-Expression "function Global:Write-Host(`$Object) { }"
 
 Describe "Module - Testing Manifest File (.psd1)" {
     Context "Manifest" {
         It "Should contains Author" {
             $ModuleInformation.Author | Should not BeNullOrEmpty
         }
         It "Should contains Company Name" {
             $ModuleInformation.CompanyName | Should not BeNullOrEmpty
         }
         It "Should contains Description" {
             $ModuleInformation.Description | Should not BeNullOrEmpty
         }
         It "Should contains a Project Link" {
             $ModuleInformation.HelpInfoURI | Should not BeNullOrEmpty
         }
         It "Should contains a Tags (For the PSGallery)" {
             $ModuleInformation.Tags.count | Should not BeNullOrEmpty
         }
 
         It "Compare the count of Function Exported and the PS1 files found" {
             $ExportedFunctions.count -eq $PS1Functions.count |
                 Should BeGreaterthan 0
         }
         It "Compare the missing function" {
             if (-not ($ExportedFunctions.count -eq $PS1Functions.count)) {
                 $Compare = Compare-Object -ReferenceObject $ExportedFunctions -DifferenceObject $PS1Functions.basename
                 $Compare.inputobject -join ',' | Should BeNullOrEmpty
             }
         }
     }
 }

 Describe "manipulation Opt2" {
    Invoke-Expression "function Global:Write-Host(`$Object) { }"

    # Context "Type" {
    # It "is-Opt2" {
    # [pscustomobject][ordered]@{
    # id = '1h29g6fd3'
    # hostname = "http://shared2.opt2"
    # ip = "10.128.134.75"
    # subnet = "10.128.134.175/26"
    # gateway = "10.128.134.180"
    # vlan = 1306
    # Container_id = '65dfsg5f5d'
    # } | is-opt2 | Should -Be $true
    # }
    # It "is-Opt2Tunnels" {
    # [pscustomobject][ordered]@{
    # id = '1h29g6fd3'
    # vlan = 1306
    # ip = "10.128.134.75"
    # subnet = "10.128.134.175/26"
    # gateway = "10.128.134.180"
    # hostname = "http://shared2.opt2"
    # container_id = '65dfsg5f5d'
    # Tunnels = @()
    # } | is-opt2Tunnels | Should -Be $true
    # }
    # It "is-Tunnels" {
    # [pscustomobject][ordered]@{
    # Name = 'Paris-16'
    # IP = "10.128.134.75"
    # Channels = "10.128.134.175/26"
    # Configs = "10.128.134.180"
    # } | is-Tunnels | Should -Be $true
    # }
    # }
    Context "Docker" {
        It "Get-Opt2 <filter>"  -TestCases @(
            @{ Filter = '*shared*'; Result = 6}
            @{ Filter = '270'; Result = 1}
            @{ Filter = '*shared6*'; Result = 1}
            @{ Filter = '10.128.126.51'; Result = 1}
            @{ Filter = '8.56.23.51'; Result = 0}
        ) {
            param ($Filter, $Result)
            (Get-Opt2 $Filter).hostName.count | Should -Be $result
        }
        It "'BAD' | New-Opt2" {
            [pscustomobject][ordered]@{
                vlan      = 5306
                ip        = "10.128.134.XX.175"
                subnet    = "10.128.134.XX.175/26"
                gateway   = "10.128.134.XX.180"
                hostname  = "http://shared2.opt2"
            } | New-Opt2 | Should -Be $null
        }
        It "'Shared2' | New-Opt2" {
            ([pscustomobject][ordered]@{
                vlan     = 306
                ip       = "10.128.134.175"
                subnet   = "10.128.134.175/26"
                gateway  = "10.128.134.180"
                hostname = "http://shared2.opt2"
            } | New-Opt2).hostname | Should -Be "http://shared2.opt2"
        }
        It "New-Opt2 -Value ..." {
            (New-Opt2 -ip '10.128.134.175' -maskCIDR 26 -Gateway 10.128.134.180 -Vlan 306 -ClientName 'shared2').ip | Should -Be '10.128.134.175'
        }
        It "New-Opt2DnsEntry" {
            $ip = '10.48.50.7'
        (New-Opt2DnsEntry -name OptBox,optbox2,optbox3 -ipaddress $IP).$IP | Should -Be @('OptBox.opt2','optbox2.opt2','optbox3.opt2')
    }
    }
    Context "Tunnels" {
        It "Get-Opt2Tunnels '*shared*' <filter>"  -TestCases @(
            @{ Filter = '10.220.*'; Result = 14}
            @{ Filter = '*exp*'; Result = 8}
            @{ Filter = 'Not-Exist-Site!'; Result = 0}
        ) {
            param ($Filter, $Result)
            (Get-Opt2Tunnels -Opt2s '*shared*' -filter $Filter).tunnels.name.count | Should -Be $result
        }
        $shared2 = Get-Opt2Tunnels 306
        $shared2.Tunnels = [PSCustomObject]@{
            Name = "rpi3-$((get-date).DayOfYear)"
            IP = '10.48.50.7'
            channels = [PSCustomObject]@{
                Name = "IMP-$((get-date).ticks)"
                IP = '10.48.50.7'
                Ports = $null # [PSCustomObject]@{send=9100; listen=(Get-Random -Minimum 9150 -Maximum 65635); forward='remote'}
            },
            [PSCustomObject]@{
                Name = "IMP-$((get-date).ticks)"
                IP = '10.48.50.7'
                Ports = [PSCustomObject]@{send=(Get-Random -Minimum 9150 -Maximum 65635); listen=(Get-Random -Minimum 9150 -Maximum 65635); forward='remote'}
            }
            Configs = [PSCustomObject]@{}
        }
        It "Add-Opt2Tunnels" {
            ($shared2 | Add-Opt2Tunnels).Tunnels.name | Should -BeLike 'rpi3-*'
        }
        It "Add-Opt2Channels" {
            ($shared2 | Add-Opt2Channels).Tunnels.Channels.name | Should -BeLike 'Imp-*'
        }
        It "Remove-Opt2Tunnels" {
            ($shared2 | Remove-Opt2Tunnels).gettype() | Should -Be ([System.Management.Automation.PSCustomObject])
        }
    }
    Context "Import / Export" {
        It "Get-Opt2 <Opt2s> | Get-Opt2Tunnels -filter <Filter> | export-Opt2Config <Path>"  -TestCases @(
            @{ Opt2s = '*shared*'; Filter = '10.220.*'; Path = '\\vdiv05.coaxis-asp.com\e$\Saves\OPT2.conf'}
            # @{ Opt2s = '*'; Filter = '*'; Path = '\\vdiv05.coaxis-asp.com\e$\Saves\OPT2.conf'}
        ) {
            param ($Opt2s, $Filter, $Path)
            (Get-Opt2 $Opt2s -ea 0 | Get-Opt2Tunnels -filter $Filter -details -ea 0 | export-Opt2Config -path $Path) | Should -BeLike "$path\*.json"
        }
        # It "Error - Get-Opt2 <Opt2s> | Get-Opt2Tunnels -filter <Filter> | export-Opt2Config <Path>" -TestCases @(
        # @{ Opt2s = '*shared*'; Filter = 'Not-Exist-Site!'; Path = '\\truc\machin'}
        # ) {
        # param ($Opt2s, $Filter, $Path)
        # {Get-Opt2 $Opt2s | Get-Opt2Tunnels -filter $Filter | export-Opt2Config -path $Path} | Should -Throw
        # }

        It "Import-Opt2Config \\vdiv05\e$\Saves\OPT2.conf\shared2.opt2\SitesImps_0000-00-00.json" {
            (import-Opt2Config '\\vdiv05\e$\Saves\OPT2.conf\shared2.opt2\SitesImps_0000-00-00.json').hostName | Should -BeLike 'http://*'
        }
    }
    Context "OptBox" {
        It "Restart-OptBox 10.48.50.7" {
        Invoke-Expression "function Global:Invoke-SSHStreamExpectSecureAction(`$Object) { }"
        (Restart-OptBox 10.48.50.7).hostName | Should -BeLike 'raspberrypi'
        }

        $shared2 = Get-Opt2Tunnels 306
        $shared2.Tunnels = [PSCustomObject]@{
            Name = "rpi3-$((get-date).DayOfYear)"
            IP = '10.48.50.7'
            channels = [PSCustomObject]@{
                Name = "IMP-$((get-date).ticks)"
                IP = '10.48.50.7'
                Ports = $null # [PSCustomObject]@{send=9100; listen=(Get-Random -Minimum 9150 -Maximum 65635); forward='remote'}
            }
            Configs = [PSCustomObject]@{}
        }
        It "Replace-OptBox 10.48.50.7" {
            ($shared2 | Replace-Opt2Box) | Should -BeLike $true
        }
        it "Invoke-OptBoxCommand IpPublic" {
            Invoke-OptBoxCommand -IpAddresses 10.220.8.188 -Commands "curl icanhazip.com --connect-timeout 1 --max-time 1 || curl -s http://checkip.dyndns.org --connect-timeout 1 --max-time 1 | sed -e 's/.*Current IP Address: //' -e 's/<.*$//' --connect-timeout 1 --max-time 1 || curl ipecho.net/plain --connect-timeout 1 --max-time 1 || echo 'NoWeb!'" | Should -Be '194.3.113.126'
        }
    }
    Context 'Test-Opt2Channels' {
        It 'Test-Opt2Channels - Type' {
            (Get-Opt2Tunnels shared4 -filter '10.232.18.58' | Test-Opt2Channels) | Should -beOfType [object]
        }
    }
 }
 #>

 Build-Readme.md '.\PSOpt2*.psm1' -MarkDownFileName 'README.md'

 Remove-Item .\fake.* -force
 $metaData = New-Object System.Management.Automation.CommandMetaData (Get-Command 'Microsoft.PowerShell.Utility\Write-Host')
 Invoke-Expression "function Global:Write-Host { $([System.Management.Automation.ProxyCommand]::create($metaData)) }"
 
 write-center