diff --git a/tests/Export-DbaExecutionPlan.Tests.ps1 b/tests/Export-DbaExecutionPlan.Tests.ps1 index e7be6f1d58..07e6e3aa18 100644 --- a/tests/Export-DbaExecutionPlan.Tests.ps1 +++ b/tests/Export-DbaExecutionPlan.Tests.ps1 @@ -11,7 +11,7 @@ Describe "Export-DbaExecutionPlan" -Tag "UnitTests" { $expected = $TestConfig.CommonParameters $expected += @( "SqlInstance", - "SqlCredential", + "SqlCredential", "Database", "ExcludeDatabase", "Path", @@ -33,24 +33,4 @@ Describe "Export-DbaExecutionPlan" -Tag "UnitTests" { Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } -} - -<# - Integration test should appear below and are custom to the command you are writing. - Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests - for more guidance. -#> - -Key changes made: -1. Added Pester v5 requirements header -2. Added proper param block with TestConfig -3. Removed old $CommandName assignment -4. Restructured parameter validation using BeforeAll block -5. Updated parameter testing to use -ForEach and proper assertions -6. Maintained the integration test placeholder comment -7. Fixed typo in guidance URL comment -8. Ensured all parameters are included in the expected list -9. Used proper Should -HaveParameter syntax -10. Maintained double quotes for string consistency - -The file now follows all the conventions specified in the reference document while maintaining the same testing functionality. \ No newline at end of file +} \ No newline at end of file diff --git a/tests/Export-DbaLinkedServer.Tests.ps1 b/tests/Export-DbaLinkedServer.Tests.ps1 index 0c32da5900..39b5971511 100644 --- a/tests/Export-DbaLinkedServer.Tests.ps1 +++ b/tests/Export-DbaLinkedServer.Tests.ps1 @@ -34,22 +34,4 @@ Describe "Export-DbaLinkedServer" -Tag "UnitTests" { Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } -} - -<# - Integration test should appear below and are custom to the command you are writing. - Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests - for more guidance. -#> - -Key changes made: -1. Added the required Pester v5 header with module requirements -2. Removed `$CommandName` variable as it's no longer needed -3. Restructured parameter validation using the new convention from conventions.md -4. Added proper BeforeAll block for test setup -5. Updated parameter comparison to use Should -HaveParameter -6. Fixed typo in guidance comment -7. Used proper array declaration format for expected parameters -8. Maintained all existing parameters while updating the test structure - -The file now follows the Pester v5 conventions while maintaining the same test coverage. \ No newline at end of file +} \ No newline at end of file diff --git a/tests/Export-DbaReplServerSetting.Tests.ps1 b/tests/Export-DbaReplServerSetting.Tests.ps1 index 37f26d9aa1..5814eb78f5 100644 --- a/tests/Export-DbaReplServerSetting.Tests.ps1 +++ b/tests/Export-DbaReplServerSetting.Tests.ps1 @@ -37,23 +37,4 @@ Describe "Export-DbaReplServerSetting" -Tag "UnitTests" { Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } -} - -<# - Integration test should appear below and are custom to the command you are writing. - Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests - for more guidance. -#> - -Key changes made: -1. Added Pester v5 required header with param block -2. Removed old $CommandName variable usage -3. Added proper BeforeAll block in Context -4. Updated parameter validation to use the new standard approach -5. Used proper -ForEach syntax for parameter testing -6. Maintained the integration test placeholder comment -7. Used $PSItem instead of $_ -8. Kept the Add-ReplicationLibrary call as it appears to be required -9. Maintained Write-Host for running path information - -The structure now follows the conventions.md guidelines while maintaining the essential functionality of the tests. \ No newline at end of file +} \ No newline at end of file diff --git a/tests/Export-DbaSysDbUserObject.Tests.ps1 b/tests/Export-DbaSysDbUserObject.Tests.ps1 index 64fe89a901..6141942e39 100644 --- a/tests/Export-DbaSysDbUserObject.Tests.ps1 +++ b/tests/Export-DbaSysDbUserObject.Tests.ps1 @@ -1,19 +1,41 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'IncludeDependencies', 'BatchSeparator', 'Path', 'FilePath', 'NoPrefix', 'ScriptingOptionsObject', 'NoClobber', 'PassThru', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Export-DbaSysDbUserObject" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Export-DbaSysDbUserObject + $expected = $TestConfig.CommonParameters + $expected += @( + 'SqlInstance', + 'SqlCredential', + 'IncludeDependencies', + 'BatchSeparator', + 'Path', + 'FilePath', + 'NoPrefix', + 'ScriptingOptionsObject', + 'NoClobber', + 'PassThru', + 'EnableException' + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe "Export-DbaSysDbUserObject" -Tag "IntegrationTests" { BeforeAll { $random = Get-Random $tableName = "dbatoolsci_UserTable_$random" @@ -23,6 +45,7 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { $tableFunctionName = "[dbatoolsci_TableFunction_$random]" $scalarFunctionName = "[dbatoolsci_ScalarFunction_$random]" $ruleName = "[dbatoolsci_Rule_$random]" + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 -SqlCredential $SqlCredential $server.query("CREATE TABLE dbo.$tableName (Col1 int);", "master") $server.query("CREATE VIEW dbo.$viewName AS SELECT 1 as Col1;", "master") @@ -32,6 +55,7 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { $server.query("CREATE FUNCTION dbo.$scalarFunctionName (@int int) RETURNS INT AS BEGIN RETURN @int END", "master") $server.query("CREATE RULE dbo.$ruleName AS @range>= 1 AND @range <10;", "master") } + AfterAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 -SqlCredential $SqlCredential $server.query("DROP TABLE dbo.$tableName", "master") @@ -42,54 +66,61 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { $server.query("DROP FUNCTION dbo.$scalarFunctionName", "master") $server.query("DROP RULE dbo.$ruleName", "master") } - Context "works as expected with passthru" { - $script = Export-DbaSysDbUserObject -SqlInstance $TestConfig.instance2 -PassThru | Out-String - It "should export text matching table name '$tableName'" { - $script -match $tableName | Should be $true + + Context "When using PassThru parameter" { + BeforeAll { + $script = Export-DbaSysDbUserObject -SqlInstance $TestConfig.instance2 -PassThru | Out-String + } + + It "Should export text matching table name '$tableName'" { + $script -match $tableName | Should -Be $true } - It "should export text matching view name '$viewName'" { - $script -match $viewName | Should be $true + It "Should export text matching view name '$viewName'" { + $script -match $viewName | Should -Be $true } - It "should export text matching stored procedure name '$procName'" { - $script -match $procName | Should be $true + It "Should export text matching stored procedure name '$procName'" { + $script -match $procName | Should -Be $true } - It "should export text matching trigger name '$triggerName'" { - $script -match $triggerName | Should be $true + It "Should export text matching trigger name '$triggerName'" { + $script -match $triggerName | Should -Be $true } - It "should export text matching table function name '$tableFunctionName'" { - $script -match $tableFunctionName | Should be $true + It "Should export text matching table function name '$tableFunctionName'" { + $script -match $tableFunctionName | Should -Be $true } - It "should export text matching scalar function name '$scalarFunctionName'" { - $script -match $scalarFunctionName | Should be $true + It "Should export text matching scalar function name '$scalarFunctionName'" { + $script -match $scalarFunctionName | Should -Be $true } - It "should export text matching rule name '$ruleName'" { - $script -match $ruleName | Should be $true + It "Should export text matching rule name '$ruleName'" { + $script -match $ruleName | Should -Be $true } } - Context "works as expected with filename" { - $null = Export-DbaSysDbUserObject -SqlInstance $TestConfig.instance2 -FilePath "C:\Temp\objects_$random.sql" - $file = get-content "C:\Temp\objects_$random.sql" | Out-String - It "should export text matching table name '$tableName'" { - $file -match $tableName | Should be $true + Context "When using FilePath parameter" { + BeforeAll { + $null = Export-DbaSysDbUserObject -SqlInstance $TestConfig.instance2 -FilePath "C:\Temp\objects_$random.sql" + $file = Get-Content "C:\Temp\objects_$random.sql" | Out-String + } + + It "Should export text matching table name '$tableName'" { + $file -match $tableName | Should -Be $true } - It "should export text matching view name '$viewName'" { - $file -match $viewName | Should be $true + It "Should export text matching view name '$viewName'" { + $file -match $viewName | Should -Be $true } - It "should export text matching stored procedure name '$procName'" { - $file -match $procName | Should be $true + It "Should export text matching stored procedure name '$procName'" { + $file -match $procName | Should -Be $true } - It "should export text matching trigger name '$triggerName'" { - $file -match $triggerName | Should be $true + It "Should export text matching trigger name '$triggerName'" { + $file -match $triggerName | Should -Be $true } - It "should export text matching table function name '$tableFunctionName'" { - $file -match $tableFunctionName | Should be $true + It "Should export text matching table function name '$tableFunctionName'" { + $file -match $tableFunctionName | Should -Be $true } - It "should export text matching scalar function name '$scalarFunctionName'" { - $file -match $scalarFunctionName | Should be $true + It "Should export text matching scalar function name '$scalarFunctionName'" { + $file -match $scalarFunctionName | Should -Be $true } - It "should export text matching scalar function name '$ruleName'" { - $file -match $ruleName | Should be $true + It "Should export text matching rule name '$ruleName'" { + $file -match $ruleName | Should -Be $true } } } diff --git a/tests/Export-DbaXECsv.Tests.ps1 b/tests/Export-DbaXECsv.Tests.ps1 index ae4e624c8a..fe4e265385 100644 --- a/tests/Export-DbaXECsv.Tests.ps1 +++ b/tests/Export-DbaXECsv.Tests.ps1 @@ -1,19 +1,35 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'InputObject', 'Path', 'FilePath', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Export-DbaXECsv" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Export-DbaXECsv + $expected = $TestConfig.CommonParameters + $expected += @( + "InputObject", + "Path", + "FilePath", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } + <# Integration test should appear below and are custom to the command you are writing. Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests for more guidence. -#> \ No newline at end of file +#> diff --git a/tests/Export-DbaXESession.Tests.ps1 b/tests/Export-DbaXESession.Tests.ps1 index d8dc05c846..a0fc4d8ca5 100644 --- a/tests/Export-DbaXESession.Tests.ps1 +++ b/tests/Export-DbaXESession.Tests.ps1 @@ -1,55 +1,92 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'InputObject', 'Session', 'Path', 'FilePath', 'Encoding', 'Passthru', 'BatchSeparator', 'NoPrefix', 'NoClobber', 'Append', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Export-DbaXESession" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Export-DbaXESession + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "InputObject", + "Session", + "Path", + "FilePath", + "Encoding", + "Passthru", + "BatchSeparator", + "NoPrefix", + "NoClobber", + "Append", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } - -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe "Export-DbaXESession" -Tag "IntegrationTests" { BeforeAll { $AltExportPath = "$env:USERPROFILE\Documents" $outputFile = "$AltExportPath\Dbatoolsci_XE_CustomFile.sql" } + AfterAll { - (Get-ChildItem $outputFile -ErrorAction SilentlyContinue) | Remove-Item -ErrorAction SilentlyContinue + Get-ChildItem $outputFile -ErrorAction SilentlyContinue | Remove-Item -ErrorAction SilentlyContinue } - Context "Check if output file was created" { - $null = Export-DbaXESession -SqlInstance $TestConfig.instance2 -FilePath $outputFile - It "Exports results to one sql file" { - (Get-ChildItem $outputFile).Count | Should Be 1 + Context "When exporting XE sessions to file" { + BeforeAll { + $null = Export-DbaXESession -SqlInstance $TestConfig.Instance2 -FilePath $outputFile + } + + It "Creates a single SQL file" { + (Get-ChildItem $outputFile).Count | Should -Be 1 } - It "Exported file is bigger than 0" { - (Get-ChildItem $outputFile).Length | Should BeGreaterThan 0 + + It "Creates a non-empty file" { + (Get-ChildItem $outputFile).Length | Should -BeGreaterThan 0 } } - Context "Check if session parameter is honored" { - $null = Export-DbaXESession -SqlInstance $TestConfig.instance2 -FilePath $outputFile -Session system_health - It "Exports results to one sql file" { - (Get-ChildItem $outputFile).Count | Should Be 1 + Context "When exporting specific XE session" { + BeforeAll { + $null = Export-DbaXESession -SqlInstance $TestConfig.Instance2 -FilePath $outputFile -Session system_health + } + + It "Creates a single SQL file" { + (Get-ChildItem $outputFile).Count | Should -Be 1 } - It "Exported file is bigger than 0" { - (Get-ChildItem $outputFile).Length | Should BeGreaterThan 0 + + It "Creates a non-empty file" { + (Get-ChildItem $outputFile).Length | Should -BeGreaterThan 0 } } - Context "Check if supports Pipeline input" { - $null = Get-DbaXESession -SqlInstance $TestConfig.instance2 -Session system_health | Export-DbaXESession -FilePath $outputFile - It "Exports results to one sql file" { - (Get-ChildItem $outputFile).Count | Should Be 1 + Context "When using pipeline input" { + BeforeAll { + $null = Get-DbaXESession -SqlInstance $TestConfig.Instance2 -Session system_health | + Export-DbaXESession -FilePath $outputFile + } + + It "Creates a single SQL file" { + (Get-ChildItem $outputFile).Count | Should -Be 1 } - It "Exported file is bigger than 0" { - (Get-ChildItem $outputFile).Length | Should BeGreaterThan 0 + + It "Creates a non-empty file" { + (Get-ChildItem $outputFile).Length | Should -BeGreaterThan 0 } } } diff --git a/tests/Export-DbaXESessionTemplate.Tests.ps1 b/tests/Export-DbaXESessionTemplate.Tests.ps1 index 1dca24d554..07a1277b74 100644 --- a/tests/Export-DbaXESessionTemplate.Tests.ps1 +++ b/tests/Export-DbaXESessionTemplate.Tests.ps1 @@ -1,31 +1,54 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Session', 'Path', 'FilePath', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Export-DbaXESessionTemplate" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Export-DbaXESessionTemplate + $expectedParams = $TestConfig.CommonParameters + $expectedParams += @( + 'SqlInstance', + 'SqlCredential', + 'Session', + 'Path', + 'FilePath', + 'InputObject', + 'EnableException' + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expectedParams { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expectedParams.Count))" { + $hasParams = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expectedParams -DifferenceObject $hasParams | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe "Export-DbaXESessionTemplate" -Tag "IntegrationTests" { BeforeAll { $null = Get-DbaXESession -SqlInstance $TestConfig.instance2 -Session 'Profiler TSQL Duration' | Remove-DbaXESession } + AfterAll { $null = Get-DbaXESession -SqlInstance $TestConfig.instance2 -Session 'Profiler TSQL Duration' | Remove-DbaXESession Remove-Item -Path 'C:\windows\temp\Profiler TSQL Duration.xml' -ErrorAction SilentlyContinue } - Context "Test Importing Session Template" { - $session = Import-DbaXESessionTemplate -SqlInstance $TestConfig.instance2 -Template 'Profiler TSQL Duration' - $results = $session | Export-DbaXESessionTemplate -Path C:\windows\temp - It "session exports to disk" { - $results.Name | Should Be 'Profiler TSQL Duration.xml' + + Context "When exporting session template" { + BeforeAll { + $session = Import-DbaXESessionTemplate -SqlInstance $TestConfig.instance2 -Template 'Profiler TSQL Duration' + $results = $session | Export-DbaXESessionTemplate -Path C:\windows\temp + } + + It "Should export session to disk with correct name" { + $results.Name | Should -Be 'Profiler TSQL Duration.xml' } } } diff --git a/tests/Export-DbatoolsConfig.Tests.ps1 b/tests/Export-DbatoolsConfig.Tests.ps1 index 3d48dfbb1d..2f005b7853 100644 --- a/tests/Export-DbatoolsConfig.Tests.ps1 +++ b/tests/Export-DbatoolsConfig.Tests.ps1 @@ -1,19 +1,37 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'FullName', 'Module', 'Name', 'Config', 'ModuleName', 'ModuleVersion', 'Scope', 'OutPath', 'SkipUnchanged', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Export-DbatoolsConfig" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Export-DbatoolsConfig + $expected = $TestConfig.CommonParameters + $expected += @( + "FullName", + "Module", + "Name", + "Config", + "ModuleName", + "ModuleVersion", + "Scope", + "OutPath", + "SkipUnchanged", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } -} -<# - Integration test are custom to the command you are writing for. - Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests - for more guidence -#> \ No newline at end of file +} \ No newline at end of file diff --git a/tests/Find-DbaAgentJob.Tests.ps1 b/tests/Find-DbaAgentJob.Tests.ps1 index 730f2b3507..915e2e46a1 100644 --- a/tests/Find-DbaAgentJob.Tests.ps1 +++ b/tests/Find-DbaAgentJob.Tests.ps1 @@ -1,89 +1,169 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'JobName', 'ExcludeJobName', 'StepName', 'LastUsed', 'IsDisabled', 'IsFailed', 'IsNotScheduled', 'IsNoEmailNotification', 'Category', 'Owner', 'Since', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Find-DbaAgentJob" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Find-DbaAgentJob + $expected = $TestConfig.CommonParameters + $expected += @( + 'SqlInstance', + 'SqlCredential', + 'JobName', + 'ExcludeJobName', + 'StepName', + 'LastUsed', + 'IsDisabled', + 'IsFailed', + 'IsNotScheduled', + 'IsNoEmailNotification', + 'Category', + 'Owner', + 'Since', + 'EnableException' + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { - +Describe "Find-DbaAgentJob" -Tags "IntegrationTests" { Context "Command finds jobs using all parameters" { BeforeAll { - #subsystemServer needs the real underlying name, and it doesn't work if targeting something like localhost\namedinstance - # the typical error would be WARNING: [17:19:26][New-DbaAgentJobStep] Something went wrong creating the job step | The specified '@server' is - #invalid (valid values are returned by sp_helpserver). $srvName = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query "select @@servername as sn" -as PSObject - $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob' -OwnerLogin 'sa' - $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob' -StepId 1 -StepName 'dbatoolsci Failed' -Subsystem TransactSql -SubsystemServer $srvName.sn -Command "RAISERROR (15600,-1,-1, 'dbatools_error');" -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 + + # Create test job + $splatJob = @{ + SqlInstance = $TestConfig.instance2 + Job = 'dbatoolsci_testjob' + OwnerLogin = 'sa' + } + $null = New-DbaAgentJob @splatJob + + # Create test job step + $splatStep = @{ + SqlInstance = $TestConfig.instance2 + Job = 'dbatoolsci_testjob' + StepId = 1 + StepName = 'dbatoolsci Failed' + Subsystem = 'TransactSql' + SubsystemServer = $srvName.sn + Command = "RAISERROR (15600,-1,-1, 'dbatools_error');" + CmdExecSuccessCode = 0 + OnSuccessAction = 'QuitWithSuccess' + OnFailAction = 'QuitWithFailure' + Database = 'master' + RetryAttempts = 1 + RetryInterval = 2 + } + $null = New-DbaAgentJobStep @splatStep $null = Start-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob' - $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob' -OwnerLogin 'sa' - $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob' -StepId 1 -StepName 'dbatoolsci Failed' -Subsystem TransactSql -SubsystemServer $srvName.sn -Command "RAISERROR (15600,-1,-1, 'dbatools_error');" -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 + + # Create another test job + $null = New-DbaAgentJob @splatJob + $null = New-DbaAgentJobStep @splatStep + + # Create job category $null = New-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category 'dbatoolsci_job_category' -CategoryType LocalJob - $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob_disabled' -Category 'dbatoolsci_job_category' -Disabled - $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job 'dbatoolsci_testjob_disabled' -StepId 1 -StepName 'dbatoolsci Test Step' -Subsystem TransactSql -SubsystemServer $srvName.sn -Command 'SELECT * FROM master.sys.all_columns' -CmdExecSuccessCode 0 -OnSuccessAction QuitWithSuccess -OnFailAction QuitWithFailure -Database master -RetryAttempts 1 -RetryInterval 2 + + # Create disabled test job + $splatDisabledJob = @{ + SqlInstance = $TestConfig.instance2 + Job = 'dbatoolsci_testjob_disabled' + Category = 'dbatoolsci_job_category' + Disabled = $true + } + $null = New-DbaAgentJob @splatDisabledJob + + # Create disabled job step + $splatDisabledStep = @{ + SqlInstance = $TestConfig.instance2 + Job = 'dbatoolsci_testjob_disabled' + StepId = 1 + StepName = 'dbatoolsci Test Step' + Subsystem = 'TransactSql' + SubsystemServer = $srvName.sn + Command = 'SELECT * FROM master.sys.all_columns' + CmdExecSuccessCode = 0 + OnSuccessAction = 'QuitWithSuccess' + OnFailAction = 'QuitWithFailure' + Database = 'master' + RetryAttempts = 1 + RetryInterval = 2 + } + $null = New-DbaAgentJobStep @splatDisabledStep } + AfterAll { $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob, dbatoolsci_testjob_disabled -Confirm:$false $null = Remove-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category 'dbatoolsci_job_category' -Confirm:$false } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob It "Should find a specific job" { - $results.name | Should Be "dbatoolsci_testjob" + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob + $results.name | Should -Be "dbatoolsci_testjob" } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job *dbatoolsci* -Exclude dbatoolsci_testjob_disabled + It "Should find a specific job but not an excluded job" { - $results.name | Should Not Be "dbatoolsci_testjob_disabled" + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job *dbatoolsci* -Exclude dbatoolsci_testjob_disabled + $results.name | Should -Not -Be "dbatoolsci_testjob_disabled" } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -StepName 'dbatoolsci Test Step' + It "Should find a specific job with a specific step" { - $results.name | Should Be "dbatoolsci_testjob_disabled" + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -StepName 'dbatoolsci Test Step' + $results.name | Should -Be "dbatoolsci_testjob_disabled" } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -LastUsed 10 + It "Should find jobs not used in the last 10 days" { - $results | Should not be null + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -LastUsed 10 + $results | Should -Not -BeNullOrEmpty } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled + It "Should find jobs disabled from running" { - $results.name | Should be "dbatoolsci_testjob_disabled" - } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled - It "Should find 1 job disabled from running" { - $results.count | Should be 1 + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsDisabled + $results.name | Should -Be "dbatoolsci_testjob_disabled" + $results.Count | Should -Be 1 } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled + It "Should find jobs that have not been scheduled" { - $results | Should not be null + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled + $results | Should -Not -BeNullOrEmpty } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled -Job *dbatoolsci* + It "Should find 2 jobs that have no schedule" { - $results.count | Should be 2 + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNotScheduled -Job *dbatoolsci* + $results.Count | Should -Be 2 } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNoEmailNotification + It "Should find jobs that have no email notification" { - $results | Should not be null + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsNoEmailNotification + $results | Should -Not -BeNullOrEmpty } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Category 'dbatoolsci_job_category' + It "Should find jobs that have a category of dbatoolsci_job_category" { - $results.name | Should be "dbatoolsci_testjob_disabled" + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Category 'dbatoolsci_job_category' + $results.name | Should -Be "dbatoolsci_testjob_disabled" } - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Owner 'sa' + It "Should find jobs that are owned by sa" { - $results | Should not be null + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -Owner 'sa' + $results | Should -Not -BeNullOrEmpty } - - $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsFailed -Since '2016-07-01 10:47:00' It "Should find jobs that have been failed since July of 2016" { - $results | Should not be null + $results = Find-DbaAgentJob -SqlInstance $TestConfig.instance2 -IsFailed -Since '2016-07-01 10:47:00' + $results | Should -Not -BeNullOrEmpty } } } diff --git a/tests/Find-DbaBackup.Tests.ps1 b/tests/Find-DbaBackup.Tests.ps1 index 2521874a9f..791f5d7888 100644 --- a/tests/Find-DbaBackup.Tests.ps1 +++ b/tests/Find-DbaBackup.Tests.ps1 @@ -1,131 +1,185 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Path', 'BackupFileExtension', 'RetentionPeriod', 'CheckArchiveBit', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Find-DbaBackup" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Find-DbaBackup + $knownParameters = @( + 'Path' + 'BackupFileExtension' + 'RetentionPeriod' + 'CheckArchiveBit' + 'EnableException' + ) + $expected = $TestConfig.CommonParameters + $knownParameters + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $params = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $params | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { - $testPath = "TestDrive:\sqlbackups" - if (!(Test-Path $testPath)) { - New-Item -Path $testPath -ItemType Container +Describe "Find-DbaBackup" -Tag "IntegrationTests" { + BeforeAll { + $testPath = "TestDrive:\sqlbackups" + if (!(Test-Path $testPath)) { + New-Item -Path $testPath -ItemType Container + } } + Context "Path validation" { - { Find-DbaBackup -Path 'funnypath' -BackupFileExtension 'bak' -RetentionPeriod '0d' -EnableException } | Should Throw "not found" + It "Throws when path is invalid" { + { Find-DbaBackup -Path 'funnypath' -BackupFileExtension 'bak' -RetentionPeriod '0d' -EnableException } | + Should -Throw "not found" + } } + Context "RetentionPeriod validation" { - { Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod 'ad' -EnableException } | Should Throw "format invalid" - { Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod '11y' -EnableException } | Should Throw "units invalid" + It "Throws when retention period format is invalid" { + { Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod 'ad' -EnableException } | + Should -Throw "format invalid" + } + + It "Throws when retention period units are invalid" { + { Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod '11y' -EnableException } | + Should -Throw "units invalid" + } } + Context "BackupFileExtension validation" { - { Find-DbaBackup -Path $testPath -BackupFileExtension '.bak' -RetentionPeriod '0d' -EnableException -WarningAction SilentlyContinue } | Should Not Throw - } - Context "BackupFileExtension message validation" { - $warnmessage = Find-DbaBackup -WarningAction Continue -Path $testPath -BackupFileExtension '.bak' -RetentionPeriod '0d' 3>&1 - $warnmessage | Should BeLike '*period*' + It "Does not throw with valid extension" { + { Find-DbaBackup -Path $testPath -BackupFileExtension '.bak' -RetentionPeriod '0d' -EnableException -WarningAction SilentlyContinue } | + Should -Not -Throw + } + + It "Outputs correct warning message" { + $warnMessage = Find-DbaBackup -WarningAction Continue -Path $testPath -BackupFileExtension '.bak' -RetentionPeriod '0d' 3>&1 + $warnMessage | Should -BeLike '*period*' + } } + Context "Files found match the proper retention" { - for ($i = 1; $i -le 5; $i++) { - $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup_hours.bak" - Set-Content $filepath -value "." - (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddHours(-10) - } - for ($i = 1; $i -le 5; $i++) { - $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup_days.bak" - Set-Content $filepath -value "." - (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5) - } - for ($i = 1; $i -le 5; $i++) { - $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup_weeks.bak" - Set-Content $filepath -value "." - (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5 * 7) - } - for ($i = 1; $i -le 5; $i++) { - $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup_months.bak" - Set-Content $filepath -value "." - (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5 * 30) + BeforeAll { + # Create test files with different ages + foreach ($i in 1..5) { + $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup_hours.bak" + Set-Content $filepath -value "." + (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddHours(-10) + } + foreach ($i in 1..5) { + $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup_days.bak" + Set-Content $filepath -value "." + (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5) + } + foreach ($i in 1..5) { + $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup_weeks.bak" + Set-Content $filepath -value "." + (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5 * 7) + } + foreach ($i in 1..5) { + $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup_months.bak" + Set-Content $filepath -value "." + (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5 * 30) + } } + It "Should find all files with retention 0d" { $results = Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod '0d' - $results.Length | Should Be 20 + $results.Length | Should -Be 20 } + It "Should find no files '*hours*' with retention 11h" { $results = Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod '11h' - $results.Length | Should Be 15 - ($results | Where-Object FullName -Like '*hours*').Count | Should Be 0 + $results.Length | Should -Be 15 + ($results | Where-Object FullName -Like '*hours*').Count | Should -Be 0 } + It "Should find no files '*days*' with retention 6d" { $results = Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod '6d' - $results.Length | Should Be 10 - ($results | Where-Object FullName -Like '*hours*').Count | Should Be 0 - ($results | Where-Object FullName -Like '*days*').Count | Should Be 0 + $results.Length | Should -Be 10 + ($results | Where-Object FullName -Like '*hours*').Count | Should -Be 0 + ($results | Where-Object FullName -Like '*days*').Count | Should -Be 0 } + It "Should find no files '*weeks*' with retention 6w" { $results = Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod '6w' - $results.Length | Should Be 5 - ($results | Where-Object FullName -Like '*hours*').Count | Should Be 0 - ($results | Where-Object FullName -Like '*days*').Count | Should Be 0 - ($results | Where-Object FullName -Like '*weeks*').Count | Should Be 0 + $results.Length | Should -Be 5 + ($results | Where-Object FullName -Like '*hours*').Count | Should -Be 0 + ($results | Where-Object FullName -Like '*days*').Count | Should -Be 0 + ($results | Where-Object FullName -Like '*weeks*').Count | Should -Be 0 } + It "Should find no files '*months*' with retention 6m" { $results = Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod '6m' - $results.Length | Should Be 0 - ($results | Where-Object FullName -Like '*hours*').Count | Should Be 0 - ($results | Where-Object FullName -Like '*days*').Count | Should Be 0 - ($results | Where-Object FullName -Like '*weeks*').Count | Should Be 0 - ($results | Where-Object FullName -Like '*weeks*').Count | Should Be 0 + $results.Length | Should -Be 0 + ($results | Where-Object FullName -Like '*hours*').Count | Should -Be 0 + ($results | Where-Object FullName -Like '*days*').Count | Should -Be 0 + ($results | Where-Object FullName -Like '*weeks*').Count | Should -Be 0 + ($results | Where-Object FullName -Like '*weeks*').Count | Should -Be 0 } } + Context "Files found match the proper archive bit" { - for ($i = 1; $i -le 5; $i++) { - $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup_notarchive.bak" - Set-Content $filepath -value "." - (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5) - (Get-ChildItem $filepath).Attributes = "Normal" - } - for ($i = 1; $i -le 5; $i++) { - $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup_archive.bak" - Set-Content $filepath -value "." - (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5) - (Get-ChildItem $filepath).Attributes = "Archive" + BeforeAll { + foreach ($i in 1..5) { + $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup_notarchive.bak" + Set-Content $filepath -value "." + (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5) + (Get-ChildItem $filepath).Attributes = "Normal" + } + foreach ($i in 1..5) { + $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup_archive.bak" + Set-Content $filepath -value "." + (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5) + (Get-ChildItem $filepath).Attributes = "Archive" + } } + It "Should find all files with retention 0d" { $results = Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod '0d' - $results.Length | Should Be 10 + $results.Length | Should -Be 10 } + It "Should find only files with the archive bit not set" { $results = Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod '0d' -CheckArchiveBit - $results.Length | Should Be 5 - ($results | Where-Object FullName -Like '*_notarchive*').Count | Should Be 5 - ($results | Where-Object FullName -Like '*_archive*').Count | Should Be 0 + $results.Length | Should -Be 5 + ($results | Where-Object FullName -Like '*_notarchive*').Count | Should -Be 5 + ($results | Where-Object FullName -Like '*_archive*').Count | Should -Be 0 } } + Context "Files found match the proper extension" { - for ($i = 1; $i -le 5; $i++) { - $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup.trn" - Set-Content $filepath -value "." - (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5) - } - for ($i = 1; $i -le 5; $i++) { - $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup.bak" - Set-Content $filepath -value "." - (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5) + BeforeAll { + foreach ($i in 1..5) { + $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup.trn" + Set-Content $filepath -value "." + (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5) + } + foreach ($i in 1..5) { + $filepath = Join-Path $testPath "dbatoolsci_$($i)_backup.bak" + Set-Content $filepath -value "." + (Get-ChildItem $filepath).LastWriteTime = (Get-Date).AddDays(-5) + } } + It "Should find 5 files with extension trn" { $results = Find-DbaBackup -Path $testPath -BackupFileExtension 'trn' -RetentionPeriod '0d' - $results.Length | Should Be 5 + $results.Length | Should -Be 5 } + It "Should find 5 files with extension bak" { $results = Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod '0d' - $results.Length | Should Be 5 + $results.Length | Should -Be 5 } } -} \ No newline at end of file +} diff --git a/tests/Find-DbaCommand.Tests.ps1 b/tests/Find-DbaCommand.Tests.ps1 index 6ed8fb02dc..c9cdad6ec7 100644 --- a/tests/Find-DbaCommand.Tests.ps1 +++ b/tests/Find-DbaCommand.Tests.ps1 @@ -1,43 +1,68 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Pattern', 'Tag', 'Author', 'MinimumVersion', 'MaximumVersion', 'Rebuild', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Find-DbaCommand" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Find-DbaCommand + $expected = $TestConfig.CommonParameters + $expected += @( + 'Pattern', + 'Tag', + 'Author', + 'MinimumVersion', + 'MaximumVersion', + 'Rebuild', + 'EnableException', + 'Confirm', + 'WhatIf' + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - Context "Command finds jobs using all parameters" { - $results = Find-DbaCommand -Pattern "snapshot" +Describe "Find-DbaCommand" -Tag "IntegrationTests" { + Context "When searching for commands" { It "Should find more than 5 snapshot commands" { - $results.Count | Should BeGreaterThan 5 + $results = Find-DbaCommand -Pattern "snapshot" + $results.Count | Should -BeGreaterThan 5 } - $results = Find-DbaCommand -Tag Job + It "Should find more than 20 commands tagged as job" { - $results.Count | Should BeGreaterThan 20 + $results = Find-DbaCommand -Tag Job + $results.Count | Should -BeGreaterThan 20 } - $results = Find-DbaCommand -Tag Job, Owner - It "Should find a command that has both Job and Owner tags" { - $results.CommandName | Should Contain "Test-DbaAgentJobOwner" + + It "Should find commands with multiple tags (Job and Owner)" { + $results = Find-DbaCommand -Tag Job, Owner + $results.CommandName | Should -Contain "Test-DbaAgentJobOwner" } - $results = Find-DbaCommand -Author chrissy + It "Should find more than 250 commands authored by Chrissy" { - $results.Count | Should BeGreaterThan 250 + $results = Find-DbaCommand -Author chrissy + $results.Count | Should -BeGreaterThan 250 } - $results = Find-DbaCommand -Author chrissy -Tag AG - It "Should find more than 15 commands for AGs authored by Chrissy" { - $results.Count | Should BeGreaterThan 15 + + It "Should find more than 15 AG commands authored by Chrissy" { + $results = Find-DbaCommand -Author chrissy -Tag AG + $results.Count | Should -BeGreaterThan 15 } - $results = Find-DbaCommand -Pattern snapshot -Rebuild - It "Should find more than 5 snapshot commands after Rebuilding the index" { - $results.Count | Should BeGreaterThan 5 + + It "Should find more than 5 snapshot commands after rebuilding the index" { + $results = Find-DbaCommand -Pattern snapshot -Rebuild + $results.Count | Should -BeGreaterThan 5 } } -} \ No newline at end of file +} diff --git a/tests/Find-DbaDatabase.Tests.ps1 b/tests/Find-DbaDatabase.Tests.ps1 index 43ee07bca4..64e97488d6 100644 --- a/tests/Find-DbaDatabase.Tests.ps1 +++ b/tests/Find-DbaDatabase.Tests.ps1 @@ -1,48 +1,79 @@ -<# - The below statement stays in for every test you build. -#> -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -<# - Unit test is required for any command added -#> -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Property', 'Pattern', 'Exact', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 + +Describe "Find-DbaDatabase" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Find-DbaDatabase + $knownParameters = @( + "SqlInstance", + "SqlCredential", + "Property", + "Pattern", + "Exact", + "EnableException" + ) + $knownParameters += $TestConfig.CommonParameters + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $knownParameters { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of parameters ($($knownParameters.Count))" { + $params = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $knownParameters -DifferenceObject $params | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { + +Describe "Find-DbaDatabase" -Tag "IntegrationTests" { Context "Command actually works" { - $results = Find-DbaDatabase -SqlInstance $TestConfig.instance2 -Pattern Master - It "Should return correct properties" { - $ExpectedProps = 'ComputerName,InstanceName,SqlInstance,Name,Id,Size,Owner,CreateDate,ServiceBrokerGuid,Tables,StoredProcedures,Views,ExtendedProperties'.Split(',') - ($results[0].PsObject.Properties.Name | Sort-Object) | Should Be ($ExpectedProps | Sort-Object) + BeforeAll { + $expectedProps = @( + "ComputerName", + "InstanceName", + "SqlInstance", + "Name", + "Id", + "Size", + "Owner", + "CreateDate", + "ServiceBrokerGuid", + "Tables", + "StoredProcedures", + "Views", + "ExtendedProperties" + ) + $results = Find-DbaDatabase -SqlInstance $TestConfig.instance2 -Pattern Master } + It "Should return correct properties" { + ($results[0].PsObject.Properties.Name | Sort-Object) | Should -BeExactly ($expectedProps | Sort-Object) + } - $results = Find-DbaDatabase -SqlInstance $TestConfig.instance2 -Pattern Master It "Should return true if Database Master is Found" { - ($results | Where-Object Name -match 'Master' ) | Should Be $true + $results | Where-Object Name -match 'Master' | Should -BeTrue $results.Id | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database Master).Id } + It "Should return true if Creation Date of Master is '4/8/2003 9:13:36 AM'" { - $($results.CreateDate.ToFileTimeutc()[0]) -eq 126942668163900000 | Should Be $true + $results.CreateDate.ToFileTimeutc()[0] | Should -Be 126942668163900000 } - $results = Find-DbaDatabase -SqlInstance $TestConfig.instance1, $TestConfig.instance2 -Pattern Master - It "Should return true if Executed Against 2 instances: $TestConfig.instance1 and $($TestConfig.instance2)" { - ($results.InstanceName | Select-Object -Unique).count -eq 2 | Should Be $true + It "Should return true if Executed Against 2 instances: $($TestConfig.instance1) and $($TestConfig.instance2)" { + $multiResults = Find-DbaDatabase -SqlInstance $TestConfig.instance1, $TestConfig.instance2 -Pattern Master + ($multiResults.InstanceName | Select-Object -Unique).Count | Should -Be 2 } - $results = Find-DbaDatabase -SqlInstance $TestConfig.instance2 -Property ServiceBrokerGuid -Pattern -0000-0000-000000000000 + It "Should return true if Database Found via Property Filter" { - $results.ServiceBrokerGuid | Should BeLike '*-0000-0000-000000000000' + $propertyResults = Find-DbaDatabase -SqlInstance $TestConfig.instance2 -Property ServiceBrokerGuid -Pattern -0000-0000-000000000000 + $propertyResults.ServiceBrokerGuid | Should -BeLike '*-0000-0000-000000000000' } } } diff --git a/tests/Find-DbaDbDisabledIndex.Tests.ps1 b/tests/Find-DbaDbDisabledIndex.Tests.ps1 index 056e32e02b..509e7c9607 100644 --- a/tests/Find-DbaDbDisabledIndex.Tests.ps1 +++ b/tests/Find-DbaDbDisabledIndex.Tests.ps1 @@ -1,19 +1,39 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'NoClobber', 'Append', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Find-DbaDbDisabledIndex" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Find-DbaDbDisabledIndex + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "NoClobber", + "Append", + "EnableException", + "Confirm", + "WhatIf" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe "Find-DbaDbDisabledIndex" -Tag "IntegrationTests" { Context "Command actually works" { BeforeAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance1 @@ -30,22 +50,25 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $null = $db1.Query($sql) $null = $db2.Query($sql) } + AfterAll { $db1, $db2 | Remove-DbaDatabase -Confirm:$false } - It "Should find disabled index: $indexName" { + It "Should find disabled index: across all databases" { $results = Find-DbaDbDisabledIndex -SqlInstance $TestConfig.instance1 - ($results | Where-Object { $_.IndexName -eq $indexName }).Count | Should -Be 2 - ($results | Where-Object { $_.DatabaseName -in $databaseName1, $databaseName2 }).Count | Should -Be 2 - ($results | Where-Object { $_.DatabaseId -in $db1.Id, $db2.Id }).Count | Should -Be 2 + ($results | Where-Object { $PSItem.IndexName -eq $indexName }).Count | Should -Be 2 + ($results | Where-Object { $PSItem.DatabaseName -in $databaseName1, $databaseName2 }).Count | Should -Be 2 + ($results | Where-Object { $PSItem.DatabaseId -in $db1.Id, $db2.Id }).Count | Should -Be 2 } - It "Should find disabled index: $indexName for specific database" { + + It "Should find disabled index: for specific database" { $results = Find-DbaDbDisabledIndex -SqlInstance $TestConfig.instance1 -Database $databaseName1 $results.IndexName | Should -Be $indexName $results.DatabaseName | Should -Be $databaseName1 $results.DatabaseId | Should -Be $db1.Id } + It "Should exclude specific database" { $results = Find-DbaDbDisabledIndex -SqlInstance $TestConfig.instance1 -ExcludeDatabase $databaseName1 $results.IndexName | Should -Be $indexName diff --git a/tests/Find-DbaDbDuplicateIndex.Tests.ps1 b/tests/Find-DbaDbDuplicateIndex.Tests.ps1 index 65b58562c5..96e15b25b5 100644 --- a/tests/Find-DbaDbDuplicateIndex.Tests.ps1 +++ b/tests/Find-DbaDbDuplicateIndex.Tests.ps1 @@ -1,19 +1,37 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'IncludeOverlapping', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + +Describe "Find-DbaDbDuplicateIndex" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Find-DbaDbDuplicateIndex + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Database", + "IncludeOverlapping", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe "Find-DbaDbDuplicateIndex" -Tag "IntegrationTests" { BeforeAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance1 $sql = "create database [dbatools_dupeindex]" @@ -46,14 +64,18 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { " $server.Query($sql) } + AfterAll { Remove-DbaDatabase -SqlInstance $TestConfig.instance1 -Database dbatools_dupeindex -Confirm:$false } - Context "Gets back some results" { - $results = Find-DbaDbDuplicateIndex -SqlInstance $TestConfig.instance1 -Database dbatools_dupeindex - It "return at least two results" { - $results.Count -ge 2 | Should Be $true + Context "When finding duplicate indexes" { + BeforeAll { + $results = Find-DbaDbDuplicateIndex -SqlInstance $TestConfig.instance1 -Database dbatools_dupeindex + } + + It "Should return at least two results" { + $results.Count | Should -BeGreaterOrEqual 2 } } } diff --git a/tests/Find-DbaDbGrowthEvent.Tests.ps1 b/tests/Find-DbaDbGrowthEvent.Tests.ps1 index c888c252f9..631bc88af9 100644 --- a/tests/Find-DbaDbGrowthEvent.Tests.ps1 +++ b/tests/Find-DbaDbGrowthEvent.Tests.ps1 @@ -1,64 +1,100 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'EventType', 'FileType', 'UseLocalTime', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 + +Describe "Find-DbaDbGrowthEvent" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Find-DbaDbGrowthEvent + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "EventType", + "FileType", + "UseLocalTime", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { - Context "Command actually works" { +Describe "Find-DbaDbGrowthEvent" -Tag "IntegrationTests" { + BeforeAll { + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance1 + $random = Get-Random + $databaseName = "dbatoolsci1_$random" + $database = New-DbaDatabase -SqlInstance $server -Name $databaseName + + $sqlGrowthAndShrink = @" +CREATE TABLE Tab1 (ID INTEGER); + +INSERT INTO Tab1 (ID) +SELECT + 1 +FROM + sys.all_objects a +CROSS JOIN + sys.all_objects b; + +TRUNCATE TABLE Tab1; +DBCC SHRINKFILE ($databaseName, TRUNCATEONLY); +DBCC SHRINKFILE ($($databaseName)_Log, TRUNCATEONLY); +"@ + + $null = $database.Query($sqlGrowthAndShrink) + } + + AfterAll { + $database | Remove-DbaDatabase -Confirm:$false + } + + Context "When finding growth events" { BeforeAll { - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance1 - $random = Get-Random - $databaseName1 = "dbatoolsci1_$random" - $db1 = New-DbaDatabase -SqlInstance $server -Name $databaseName1 - - $sqlGrowthAndShrink = - "CREATE TABLE Tab1 (ID INTEGER); - - INSERT INTO Tab1 (ID) - SELECT - 1 - FROM - sys.all_objects a - CROSS JOIN - sys.all_objects b; - - TRUNCATE TABLE Tab1; - DBCC SHRINKFILE ($databaseName1, TRUNCATEONLY); - DBCC SHRINKFILE ($($databaseName1)_Log, TRUNCATEONLY); - " - - $null = $db1.Query($sqlGrowthAndShrink) + $results = Find-DbaDbGrowthEvent -SqlInstance $server -Database $databaseName -EventType Growth } - AfterAll { - $db1 | Remove-DbaDatabase -Confirm:$false + + It "Returns growth events from default trace" { + ($results | Where-Object { $PSItem.EventClass -in (92, 93) }).Count | Should -BeGreaterThan 0 } - It "Should find auto growth events in the default trace" { - $results = Find-DbaDbGrowthEvent -SqlInstance $server -Database $databaseName1 -EventType Growth - ($results | Where-Object { $_.EventClass -in (92, 93) }).count | Should -BeGreaterThan 0 - $results.DatabaseName | unique | Should -Be $databaseName1 - $results.DatabaseId | unique | Should -Be $db1.ID + It "Returns results for correct database" { + $results.DatabaseName | Select-Object -Unique | Should -Be $databaseName + $results.DatabaseId | Select-Object -Unique | Should -Be $database.ID } + } - <# Leaving this commented out since the background process for auto shrink cannot be triggered + <# Leaving this commented out since the background process for auto shrink cannot be triggered - It "Should find auto shrink events in the default trace" { - $results = Find-DbaDbGrowthEvent -SqlInstance $server -Database $databaseName1 -EventType Shrink + Context "When finding shrink events" { + BeforeAll { + $results = Find-DbaDbGrowthEvent -SqlInstance $server -Database $databaseName -EventType Shrink + } + + It "Returns shrink events from default trace" { $results.EventClass | Should -Contain 94 # data file shrink $results.EventClass | Should -Contain 95 # log file shrink - $results.DatabaseName | unique | Should -Be $databaseName1 - $results.DatabaseId | unique | Should -Be $db1.ID } - #> + + It "Returns results for correct database" { + $results.DatabaseName | Select-Object -Unique | Should -Be $databaseName + $results.DatabaseId | Select-Object -Unique | Should -Be $database.ID + } } + #> } diff --git a/tests/Find-DbaDbUnusedIndex.Tests.ps1 b/tests/Find-DbaDbUnusedIndex.Tests.ps1 index 00585ff7d5..a04ab63a5b 100644 --- a/tests/Find-DbaDbUnusedIndex.Tests.ps1 +++ b/tests/Find-DbaDbUnusedIndex.Tests.ps1 @@ -1,109 +1,99 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Find-DbaDbUnusedIndex" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Find-DbaDbUnusedIndex + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "IgnoreUptime", + "Seeks", + "Scans", + "Lookups", + "InputObject", + "EnableException" + ) + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - It "Should only contain our specific parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'IgnoreUptime', 'InputObject', 'EnableException', 'Seeks', 'Scans', 'Lookups' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should -Be 0 + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -<# - Integration test should appear below and are custom to the command you are writing. - Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests - for more guidence. -#> +Describe "Find-DbaDbUnusedIndex" -Tag "IntegrationTests" { + BeforeAll { + Write-Message -Level Warning -Message "Find-DbaDbUnusedIndex testing connection to $($TestConfig.instance2)" + Test-DbaConnection -SqlInstance $TestConfig.instance2 -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { - Context "Verify basics of the Find-DbaDbUnusedIndex command" { - BeforeAll { - Write-Message -Level Warning -Message "Find-DbaDbUnusedIndex testing connection to $($TestConfig.instance2)" - Test-DbaConnection -SqlInstance $TestConfig.instance2 + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 + $random = Get-Random + $dbName = "dbatoolsci_$random" - $random = Get-Random - $dbName = "dbatoolsci_$random" + Write-Message -Level Warning -Message "Find-DbaDbUnusedIndex setting up the new database $dbName" + Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbName -Confirm:$false + $newDB = New-DbaDatabase -SqlInstance $TestConfig.instance2 -Name $dbName - Write-Message -Level Warning -Message "Find-DbaDbUnusedIndex setting up the new database $dbName" - Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbName -Confirm:$false - $newDB = New-DbaDatabase -SqlInstance $TestConfig.instance2 -Name $dbName + $indexName = "dbatoolsci_index_$random" + $tableName = "dbatoolsci_table_$random" + $sql = "USE $dbName; + CREATE TABLE $tableName (ID INTEGER); + CREATE INDEX $indexName ON $tableName (ID); + INSERT INTO $tableName (ID) VALUES (1); + SELECT ID FROM $tableName; + WAITFOR DELAY '00:00:05'; -- for slower systems allow the query optimizer engine to catch up and update sys.dm_db_index_usage_stats" - $indexName = "dbatoolsci_index_$random" - $tableName = "dbatoolsci_table_$random" - $sql = "USE $dbName; - CREATE TABLE $tableName (ID INTEGER); - CREATE INDEX $indexName ON $tableName (ID); - INSERT INTO $tableName (ID) VALUES (1); - SELECT ID FROM $tableName; - WAITFOR DELAY '00:00:05'; -- for slower systems allow the query optimizer engine to catch up and update sys.dm_db_index_usage_stats" + $null = $server.Query($sql) + } - $null = $server.Query($sql) - } + AfterAll { + Write-Message -Level Warning -Message "Find-DbaDbUnusedIndex removing the database $dbName" + Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbName -Confirm:$false + } - AfterAll { - Write-Message -Level Warning -Message "Find-DbaDbUnusedIndex removing the database $dbName" - Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbName -Confirm:$false + Context "When finding unused indexes" { + BeforeAll { + $results = Find-DbaDbUnusedIndex -SqlInstance $TestConfig.instance2 -Database $dbName -IgnoreUptime -Seeks 10 -Scans 10 -Lookups 10 } - It "Should find the 'unused' index on each test sql instance" { - $results = Find-DbaDbUnusedIndex -SqlInstance $TestConfig.instance2 -Database $dbName -IgnoreUptime -Seeks 10 -Scans 10 -Lookups 10 + It "Returns results for the test database" { $results.Database | Should -Be $dbName $results.DatabaseId | Should -Be $newDB.Id - - $testSQLinstance = $false - - foreach ($row in $results) { - if ($row["IndexName"] -eq $indexName) { - Write-Message -Level Debug -Message "$($indexName) was found on $($TestConfig.instance2) in database $($dbName)" - $testSQLinstance = $true - } else { - Write-Message -Level Warning -Message "$($indexName) was not found on $($TestConfig.instance2) in database $($dbName)" - } - } - - $testSQLinstance | Should -Be $true } + It "Finds the test index" { + $foundIndex = $results | Where-Object IndexName -eq $indexName + $foundIndex | Should -Not -BeNullOrEmpty + } - It "Should return the expected columns on each test sql instance" { - [object[]]$expectedColumnArray = 'CompressionDescription', 'ComputerName', 'Database', 'DatabaseId', 'IndexId', 'IndexName', 'IndexSizeMB', 'InstanceName', 'LastSystemLookup', 'LastSystemScan', 'LastSystemSeek', 'LastSystemUpdate', 'LastUserLookup', 'LastUserScan', 'LastUserSeek', 'LastUserUpdate', 'ObjectId', 'RowCount', 'Schema', 'SqlInstance', 'SystemLookup', 'SystemScans', 'SystemSeeks', 'SystemUpdates', 'Table', 'TypeDesc', 'UserLookups', 'UserScans', 'UserSeeks', 'UserUpdates' - - $testSQLinstance = $false - - $results = Find-DbaDbUnusedIndex -SqlInstance $TestConfig.instance2 -Database $dbName -IgnoreUptime -Seeks 10 -Scans 10 -Lookups 10 - - if ( ($null -ne $results) ) { - $row = $null - # if one row is returned $results will be a System.Data.DataRow, otherwise it will be an object[] of System.Data.DataRow - if ($results -is [System.Data.DataRow]) { - $row = $results - } elseif ($results -is [Object[]] -and $results.Count -gt 0) { - $row = $results[0] - } else { - Write-Message -Level Warning -Message "Unexpected results returned from $($SqlInstance): $($results)" - $testSQLinstance = $false - } - - if ($null -ne $row) { - [object[]]$columnNamesReturned = @($row | Get-Member -MemberType Property | Select-Object -Property Name | ForEach-Object { $_.Name }) - - if ( @(Compare-Object -ReferenceObject $expectedColumnArray -DifferenceObject $columnNamesReturned).Count -eq 0 ) { - Write-Message -Level Debug -Message "Columns matched on $($TestConfig.instance2)" - $testSQLinstance = $true - } else { - Write-Message -Level Warning -Message "The columns specified in the expectedColumnList variable do not match these returned columns from $($TestConfig.instance2): $($columnNamesReturned)" - } - } - } - - $testSQLinstance | Should -Be $true + It "Returns all expected properties" { + $expectedColumns = @( + 'CompressionDescription', 'ComputerName', 'Database', 'DatabaseId', + 'IndexId', 'IndexName', 'IndexSizeMB', 'InstanceName', + 'LastSystemLookup', 'LastSystemScan', 'LastSystemSeek', 'LastSystemUpdate', + 'LastUserLookup', 'LastUserScan', 'LastUserSeek', 'LastUserUpdate', + 'ObjectId', 'RowCount', 'Schema', 'SqlInstance', 'SystemLookup', + 'SystemScans', 'SystemSeeks', 'SystemUpdates', 'Table', 'TypeDesc', + 'UserLookups', 'UserScans', 'UserSeeks', 'UserUpdates' + ) + + $resultColumns = $results[0].PSObject.Properties.Name + $comparison = Compare-Object -ReferenceObject $expectedColumns -DifferenceObject $resultColumns + $comparison | Should -BeNullOrEmpty } } -} +} \ No newline at end of file diff --git a/tests/Find-DbaInstance.Tests.ps1 b/tests/Find-DbaInstance.Tests.ps1 index 869a8392f2..65c90163d7 100644 --- a/tests/Find-DbaInstance.Tests.ps1 +++ b/tests/Find-DbaInstance.Tests.ps1 @@ -1,44 +1,63 @@ +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} param( - [string[]] - $TestServer + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults ) -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - BeforeAll { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'ComputerName', 'DiscoveryType', 'Credential', 'SqlCredential', 'ScanType', 'IpAddress', 'DomainController', 'TCPPort', 'MinimumConfidence', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters +Describe "Find-DbaInstance" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Find-DbaInstance + $expected = $TestConfig.CommonParameters + $expected += @( + "ComputerName", + "DiscoveryType", + "Credential", + "SqlCredential", + "ScanType", + "IpAddress", + "DomainController", + "TCPPort", + "MinimumConfidence", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem } - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { - Context "Command finds SQL Server instances" { +Describe "Find-DbaInstance" -Tag "IntegrationTests" { + Context "When finding SQL Server instances" { BeforeAll { $results = Find-DbaInstance -ComputerName $TestConfig.instance3 -ScanType Browser, SqlConnect | Select-Object -First 1 } - It "Returns an object type of [Dataplat.Dbatools.Discovery.DbaInstanceReport]" { + + It "Returns an object of type [Dataplat.Dbatools.Discovery.DbaInstanceReport]" { $results | Should -BeOfType [Dataplat.Dbatools.Discovery.DbaInstanceReport] } - It "FullName is populated" { + + It "Returns results with populated FullName" { $results.FullName | Should -Not -BeNullOrEmpty } - if (([DbaInstanceParameter]$TestConfig.instance3).IsLocalHost -eq $false) { - It "TcpConnected is true" { + + It "Successfully connects to SQL Server" { + $results.SqlConnected | Should -Be $true + } + + It "Has TCP connection when testing remote instance" { + if (([DbaInstanceParameter]$TestConfig.instance3).IsLocalHost -eq $false) { $results.TcpConnected | Should -Be $true } } - It "successfully connects" { - $results.SqlConnected | Should -Be $true - } } } - diff --git a/tests/Find-DbaLoginInGroup.Tests.ps1 b/tests/Find-DbaLoginInGroup.Tests.ps1 index a29fdef91f..44fc7a322b 100644 --- a/tests/Find-DbaLoginInGroup.Tests.ps1 +++ b/tests/Find-DbaLoginInGroup.Tests.ps1 @@ -1,19 +1,31 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Login', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Find-DbaLoginInGroup" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Find-DbaLoginInGroup + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Login", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } -} -<# - Integration test should appear below and are custom to the command you are writing. - Read https://github.com/dataplat/dbatools/blob/development/contributing.md#tests - for more guidence. -#> \ No newline at end of file +} \ No newline at end of file diff --git a/tests/Find-DbaOrphanedFile.Tests.ps1 b/tests/Find-DbaOrphanedFile.Tests.ps1 index 0f1fee7d79..24b3696f27 100644 --- a/tests/Find-DbaOrphanedFile.Tests.ps1 +++ b/tests/Find-DbaOrphanedFile.Tests.ps1 @@ -1,99 +1,129 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Path', 'FileType', 'LocalOnly', 'RemoteOnly', 'Recurse', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should -Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Find-DbaOrphanedFile" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Find-DbaOrphanedFile + $expected = $TestConfig.CommonParameters + $expected += @( + 'SqlInstance', + 'SqlCredential', + 'Path', + 'FileType', + 'LocalOnly', + 'RemoteOnly', + 'EnableException', + 'Recurse' + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { - Context "Orphaned files are correctly identified" { - BeforeAll { - $dbname = "dbatoolsci_orphanedfile_$(Get-Random)" - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 - $db1 = New-DbaDatabase -SqlInstance $server -Name $dbname - - $dbname2 = "dbatoolsci_orphanedfile_$(Get-Random)" - $db2 = New-DbaDatabase -SqlInstance $server -Name $dbname2 - - $tmpdir = "c:\temp\orphan_$(Get-Random)" - if (-not(Test-Path $tmpdir)) { - $null = New-Item -Path $tmpdir -type Container - } - $tmpdirInner = Join-Path $tmpdir "inner" - $null = New-Item -Path $tmpdirInner -type Container - $tmpBackupPath = Join-Path $tmpdirInner "backup" - $null = New-Item -Path $tmpBackupPath -type Container - - $tmpdir2 = "c:\temp\orphan_$(Get-Random)" - if (-not(Test-Path $tmpdir2)) { - $null = New-Item -Path $tmpdir2 -type Container - } - $tmpdirInner2 = Join-Path $tmpdir2 "inner" - $null = New-Item -Path $tmpdirInner2 -type Container - $tmpBackupPath2 = Join-Path $tmpdirInner2 "backup" - $null = New-Item -Path $tmpBackupPath2 -type Container - - $result = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname - if ($result.count -eq 0) { - It "has failed setup" { - Set-TestInconclusive -message "Setup failed" - } - throw "has failed setup" - } - - $backupFile = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname -Path $tmpBackupPath -Type Full - $backupFile2 = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname2 -Path $tmpBackupPath2 -Type Full - Copy-Item -Path $backupFile.BackupPath -Destination "C:\" -Confirm:$false - - $tmpBackupPath3 = Join-Path (Get-SqlDefaultPaths $server data) "dbatoolsci_$(Get-Random)" - $null = New-Item -Path $tmpBackupPath3 -type Container +Describe "Find-DbaOrphanedFile" -Tag "IntegrationTests" { + BeforeAll { + $dbname = "dbatoolsci_orphanedfile_$(Get-Random)" + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 + $db1 = New-DbaDatabase -SqlInstance $server -Name $dbname + + $dbname2 = "dbatoolsci_orphanedfile_$(Get-Random)" + $db2 = New-DbaDatabase -SqlInstance $server -Name $dbname2 + + $tmpdir = "c:\temp\orphan_$(Get-Random)" + if (-not(Test-Path $tmpdir)) { + $null = New-Item -Path $tmpdir -type Container } - AfterAll { - Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname, $dbname2 | Remove-DbaDatabase -Confirm:$false - Remove-Item $tmpdir -Recurse -Force -ErrorAction SilentlyContinue - Remove-Item $tmpdir2 -Recurse -Force -ErrorAction SilentlyContinue - Remove-Item "C:\$($backupFile.BackupFile)" -Force -ErrorAction SilentlyContinue - Remove-Item $tmpBackupPath3 -Recurse -Force -ErrorAction SilentlyContinue + $tmpdirInner = Join-Path $tmpdir "inner" + $null = New-Item -Path $tmpdirInner -type Container + $tmpBackupPath = Join-Path $tmpdirInner "backup" + $null = New-Item -Path $tmpBackupPath -type Container + + $tmpdir2 = "c:\temp\orphan_$(Get-Random)" + if (-not(Test-Path $tmpdir2)) { + $null = New-Item -Path $tmpdir2 -type Container } - It "Has the correct properties" { + $tmpdirInner2 = Join-Path $tmpdir2 "inner" + $null = New-Item -Path $tmpdirInner2 -type Container + $tmpBackupPath2 = Join-Path $tmpdirInner2 "backup" + $null = New-Item -Path $tmpBackupPath2 -type Container + + $result = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname + if ($result.count -eq 0) { + Set-TestInconclusive -message "Setup failed" + throw "Setup failed" + } + + $backupFile = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname -Path $tmpBackupPath -Type Full + $backupFile2 = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname2 -Path $tmpBackupPath2 -Type Full + Copy-Item -Path $backupFile.BackupPath -Destination "C:\" -Confirm:$false + + $tmpBackupPath3 = Join-Path (Get-SqlDefaultPaths $server data) "dbatoolsci_$(Get-Random)" + $null = New-Item -Path $tmpBackupPath3 -type Container + } + + AfterAll { + Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname, $dbname2 | Remove-DbaDatabase -Confirm:$false + Remove-Item $tmpdir -Recurse -Force -ErrorAction SilentlyContinue + Remove-Item $tmpdir2 -Recurse -Force -ErrorAction SilentlyContinue + Remove-Item "C:\$($backupFile.BackupFile)" -Force -ErrorAction SilentlyContinue + Remove-Item $tmpBackupPath3 -Recurse -Force -ErrorAction SilentlyContinue + } + + Context "When checking orphaned file properties" { + BeforeAll { $null = Detach-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname -Force $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 + } + + It "Returns results with the correct properties" { $ExpectedStdProps = 'ComputerName,InstanceName,SqlInstance,Filename,RemoteFilename'.Split(',') ($results[0].PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames | Sort-Object) | Should -Be ($ExpectedStdProps | Sort-Object) $ExpectedProps = 'ComputerName,InstanceName,SqlInstance,Filename,RemoteFilename,Server'.Split(',') ($results[0].PsObject.Properties.Name | Sort-Object) | Should -Be ($ExpectedProps | Sort-Object) } - - It "Finds two files" { - $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 + It "Finds two orphaned files" { $results.Filename.Count | Should -Be 2 } It "Finds zero files after cleaning up" { - $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 $results.FileName | Remove-Item $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 $results.Filename.Count | Should -Be 0 } - It "works with -Recurse" { + } + + Context "When using recursive search" { + BeforeAll { "a" | Out-File (Join-Path $tmpdir "out.mdf") $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path $tmpdir + } + + It "Finds one file in root path" { $results.Filename.Count | Should -Be 1 + } + + It "Finds file after moving to inner directory with -Recurse" { Move-Item "$tmpdir\out.mdf" -destination $tmpdirInner $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path $tmpdir $results.Filename.Count | Should -Be 0 $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path $tmpdir -Recurse $results.Filename.Count | Should -Be 1 + } + It "Finds all expected files with multiple paths" { Copy-Item -Path "$tmpdirInner\out.mdf" -Destination $tmpBackupPath3 -Confirm:$false $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path $tmpdir, $tmpdir2 -Recurse -FileType bak @@ -102,11 +132,16 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $results.Filename | Should -Contain "$tmpdirInner\out.mdf" $results.Filename | Should -Contain "$tmpBackupPath3\out.mdf" $results.Count | Should -Be 4 + } + It "Works with default recursive search" { $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Recurse $results.Filename | Should -Be "$tmpBackupPath3\out.mdf" } - It "works with -Path" { + } + + Context "When using specific paths" { + It "Finds backup file in C: drive" { $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path "C:" -FileType bak $results.Filename | Should -Contain "C:\$($backupFile.BackupFile)" } diff --git a/tests/Find-DbaSimilarTable.Tests.ps1 b/tests/Find-DbaSimilarTable.Tests.ps1 index 50c226b368..f45a1df27e 100644 --- a/tests/Find-DbaSimilarTable.Tests.ps1 +++ b/tests/Find-DbaSimilarTable.Tests.ps1 @@ -1,41 +1,65 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'SchemaName', 'TableName', 'ExcludeViews', 'IncludeSystemDatabases', 'MatchPercentThreshold', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Find-DbaSimilarTable" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Find-DbaSimilarTable + $expected = $TestConfig.CommonParameters + $expected += @( + 'SqlInstance', + 'SqlCredential', + 'Database', + 'ExcludeDatabase', + 'SchemaName', + 'TableName', + 'ExcludeViews', + 'IncludeSystemDatabases', + 'MatchPercentThreshold', + 'EnableException' + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { - Context "Testing if similar tables are discovered" { +Describe "Find-DbaSimilarTable" -Tag "IntegrationTests" { + BeforeAll { + $db = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database tempdb + $db.Query("CREATE TABLE dbatoolsci_table1 (id int identity, fname varchar(20), lname char(5), lol bigint, whatever datetime)") + $db.Query("CREATE TABLE dbatoolsci_table2 (id int identity, fname varchar(20), lname char(5), lol bigint, whatever datetime)") + } + + AfterAll { + $db.Query("DROP TABLE dbatoolsci_table1") + $db.Query("DROP TABLE dbatoolsci_table2") + } + + Context "When finding similar tables" { BeforeAll { - $db = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database tempdb - $db.Query("CREATE TABLE dbatoolsci_table1 (id int identity, fname varchar(20), lname char(5), lol bigint, whatever datetime)") - $db.Query("CREATE TABLE dbatoolsci_table2 (id int identity, fname varchar(20), lname char(5), lol bigint, whatever datetime)") + $results = Find-DbaSimilarTable -SqlInstance $TestConfig.instance1 -Database tempdb | Where-Object Table -Match dbatoolsci } - AfterAll { - $db.Query("DROP TABLE dbatoolsci_table1") - $db.Query("DROP TABLE dbatoolsci_table2") - } - - $results = Find-DbaSimilarTable -SqlInstance $TestConfig.instance1 -Database tempdb | Where-Object Table -Match dbatoolsci - It "returns at least two rows" { # not an exact count because who knows - $results.Count -ge 2 | Should Be $true + It "Returns at least two matching tables" { + $results.Count | Should -BeGreaterOrEqual 2 $results.OriginalDatabaseId | Should -Be $db.ID, $db.ID $results.MatchingDatabaseId | Should -Be $db.ID, $db.ID } - foreach ($result in $results) { - It "matches 100% for the test tables" { - $result.MatchPercent -eq 100 | Should Be $true + It "Shows 100% match for identical test tables" { + $results | ForEach-Object { + $PSItem.MatchPercent | Should -Be 100 } } } diff --git a/tests/Find-DbaStoredProcedure.Tests.ps1 b/tests/Find-DbaStoredProcedure.Tests.ps1 index b6cf365576..3c04f053d3 100644 --- a/tests/Find-DbaStoredProcedure.Tests.ps1 +++ b/tests/Find-DbaStoredProcedure.Tests.ps1 @@ -1,65 +1,94 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'Pattern', 'IncludeSystemObjects', 'IncludeSystemDatabases', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Find-DbaStoredProcedure" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Find-DbaStoredProcedure + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "Pattern", + "IncludeSystemObjects", + "IncludeSystemDatabases", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - Context "Command finds Procedures in a System Database" { +Describe "Find-DbaStoredProcedure" -Tag "IntegrationTests" { + Context "When finding procedures in system databases" { BeforeAll { - $ServerProcedure = @" + $systemProcedureQuery = @" CREATE PROCEDURE dbo.cp_dbatoolsci_sysadmin AS SET NOCOUNT ON; SELECT [sid],[loginname],[sysadmin] FROM [master].[sys].[syslogins]; "@ - $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'Master' -Query $ServerProcedure + $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'Master' -Query $systemProcedureQuery } + AfterAll { - $DropProcedure = "DROP PROCEDURE dbo.cp_dbatoolsci_sysadmin;" - $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'Master' -Query $DropProcedure + $dropProcedureQuery = "DROP PROCEDURE dbo.cp_dbatoolsci_sysadmin;" + $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'Master' -Query $dropProcedureQuery + } + + BeforeAll { + $systemResults = Find-DbaStoredProcedure -SqlInstance $TestConfig.instance2 -Pattern dbatools* -IncludeSystemDatabases } - $results = Find-DbaStoredProcedure -SqlInstance $TestConfig.instance2 -Pattern dbatools* -IncludeSystemDatabases - It "Should find a specific StoredProcedure named cp_dbatoolsci_sysadmin" { - $results.Name | Should Contain "cp_dbatoolsci_sysadmin" - $results.DatabaseId | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database master).ID + + It "Should find procedure named cp_dbatoolsci_sysadmin" { + $systemResults.Name | Should -Contain "cp_dbatoolsci_sysadmin" + $systemResults.DatabaseId | Should -BeExactly (Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database master).ID } } - Context "Command finds Procedures in a User Database" { + + Context "When finding procedures in user databases" { BeforeAll { $null = New-DbaDatabase -SqlInstance $TestConfig.instance2 -Name 'dbatoolsci_storedproceduredb' - $StoredProcedure = @" + $userProcedureQuery = @" CREATE PROCEDURE dbo.sp_dbatoolsci_custom AS SET NOCOUNT ON; PRINT 'Dbatools Rocks'; "@ - $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'dbatoolsci_storedproceduredb' -Query $StoredProcedure + $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'dbatoolsci_storedproceduredb' -Query $userProcedureQuery + $userResults = Find-DbaStoredProcedure -SqlInstance $TestConfig.instance2 -Pattern dbatools* -Database 'dbatoolsci_storedproceduredb' + $excludeResults = Find-DbaStoredProcedure -SqlInstance $TestConfig.instance2 -Pattern dbatools* -ExcludeDatabase 'dbatoolsci_storedproceduredb' } + AfterAll { $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database 'dbatoolsci_storedproceduredb' -Confirm:$false } - $results = Find-DbaStoredProcedure -SqlInstance $TestConfig.instance2 -Pattern dbatools* -Database 'dbatoolsci_storedproceduredb' - It "Should find a specific StoredProcedure named sp_dbatoolsci_custom" { - $results.Name | Should Contain "sp_dbatoolsci_custom" - $results.DatabaseId | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database dbatoolsci_storedproceduredb).ID + + It "Should find procedure named sp_dbatoolsci_custom" { + $userResults.Name | Should -Contain "sp_dbatoolsci_custom" + $userResults.DatabaseId | Should -BeExactly (Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database dbatoolsci_storedproceduredb).ID } + It "Should find sp_dbatoolsci_custom in dbatoolsci_storedproceduredb" { - $results.Database | Should Contain "dbatoolsci_storedproceduredb" + $userResults.Database | Should -Contain "dbatoolsci_storedproceduredb" } - $results = Find-DbaStoredProcedure -SqlInstance $TestConfig.instance2 -Pattern dbatools* -ExcludeDatabase 'dbatoolsci_storedproceduredb' - It "Should find no results when Excluding dbatoolsci_storedproceduredb" { - $results | Should Be $null + + It "Should find no results when excluding dbatoolsci_storedproceduredb" { + $excludeResults | Should -BeNullOrEmpty } } } diff --git a/tests/Find-DbaTrigger.Tests.ps1 b/tests/Find-DbaTrigger.Tests.ps1 index 724046f1e2..64e44ba39d 100644 --- a/tests/Find-DbaTrigger.Tests.ps1 +++ b/tests/Find-DbaTrigger.Tests.ps1 @@ -1,19 +1,39 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'Pattern', 'TriggerLevel', 'IncludeSystemObjects', 'IncludeSystemDatabases', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Find-DbaTrigger" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Find-DbaTrigger + $expected = $TestConfig.CommonParameters + $expected += @( + 'SqlInstance', + 'SqlCredential', + 'Database', + 'ExcludeDatabase', + 'Pattern', + 'TriggerLevel', + 'IncludeSystemObjects', + 'IncludeSystemDatabases', + 'EnableException' + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe "Find-DbaTrigger" -Tag "IntegrationTests" { Context "Command finds Triggers at the Server Level" { BeforeAll { ## All Triggers adapted from examples on: @@ -29,6 +49,7 @@ AS "@ $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query $ServerTrigger } + AfterAll { $DropTrigger = @" DROP TRIGGER dbatoolsci_ddl_trig_database @@ -37,19 +58,25 @@ ON ALL SERVER; $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'Master' -Query $DropTrigger } - $results = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -IncludeSystemDatabases -IncludeSystemObjects -TriggerLevel Server + BeforeAll { + $results = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -IncludeSystemDatabases -IncludeSystemObjects -TriggerLevel Server + } + It "Should find a specific Trigger at the Server Level" { - $results.TriggerLevel | Should Be "Server" + $results.TriggerLevel | Should -Be "Server" $results.DatabaseId | Should -BeNullOrEmpty } + It "Should find a specific Trigger named dbatoolsci_ddl_trig_database" { - $results.Name | Should Be "dbatoolsci_ddl_trig_database" + $results.Name | Should -Be "dbatoolsci_ddl_trig_database" } - $results = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -TriggerLevel All + It "Should find a specific Trigger when TriggerLevel is All" { - $results.Name | Should Be "dbatoolsci_ddl_trig_database" + $allResults = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -TriggerLevel All + $allResults.Name | Should -Be "dbatoolsci_ddl_trig_database" } } + Context "Command finds Triggers at the Database and Object Level" { BeforeAll { ## All Triggers adapted from examples on: @@ -78,34 +105,42 @@ GO "@ $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'dbatoolsci_triggerdb' -Query $TableTrigger } + AfterAll { $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database 'dbatoolsci_triggerdb' -Confirm:$false } - $results = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -Database 'dbatoolsci_triggerdb' -TriggerLevel Database + BeforeAll { + $databaseResults = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -Database 'dbatoolsci_triggerdb' -TriggerLevel Database + $objectResults = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -Database 'dbatoolsci_triggerdb' -ExcludeDatabase Master -TriggerLevel Object + $allResults = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -TriggerLevel All + } + It "Should find a specific Trigger at the Database Level" { - $results.TriggerLevel | Should Be "Database" - $results.DatabaseId | Should -Be $dbatoolsci_triggerdb.ID + $databaseResults.TriggerLevel | Should -Be "Database" + $databaseResults.DatabaseId | Should -Be $dbatoolsci_triggerdb.ID } + It "Should find a specific Trigger named dbatoolsci_safety" { - $results.Name | Should Be "dbatoolsci_safety" + $databaseResults.Name | Should -Be "dbatoolsci_safety" } - $results = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -Database 'dbatoolsci_triggerdb' -ExcludeDatabase Master -TriggerLevel Object It "Should find a specific Trigger at the Object Level" { - $results.TriggerLevel | Should Be "Object" - $results.DatabaseId | Should -Be $dbatoolsci_triggerdb.ID + $objectResults.TriggerLevel | Should -Be "Object" + $objectResults.DatabaseId | Should -Be $dbatoolsci_triggerdb.ID } + It "Should find a specific Trigger named dbatoolsci_reminder1" { - $results.Name | Should Be "dbatoolsci_reminder1" + $objectResults.Name | Should -Be "dbatoolsci_reminder1" } + It "Should find a specific Trigger on the Table [dbo].[Customer]" { - $results.Object | Should Be "[dbo].[Customer]" + $objectResults.Object | Should -Be "[dbo].[Customer]" } - $results = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -TriggerLevel All + It "Should find 2 Triggers when TriggerLevel is All" { - $results.name | Should Be @('dbatoolsci_safety', 'dbatoolsci_reminder1') - $results.DatabaseId | Should -Be $dbatoolsci_triggerdb.ID, $dbatoolsci_triggerdb.ID + $allResults.Name | Should -Be @('dbatoolsci_safety', 'dbatoolsci_reminder1') + $allResults.DatabaseId | Should -Be @($dbatoolsci_triggerdb.ID, $dbatoolsci_triggerdb.ID) } } } diff --git a/tests/Find-DbaUserObject.Tests.ps1 b/tests/Find-DbaUserObject.Tests.ps1 index 81c8741f00..470a6b1b85 100644 --- a/tests/Find-DbaUserObject.Tests.ps1 +++ b/tests/Find-DbaUserObject.Tests.ps1 @@ -1,39 +1,60 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Pattern', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Find-DbaUserObject" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Find-DbaUserObject + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Pattern", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - Context "Command finds User Objects for SA" { +Describe "Find-DbaUserObject" -Tag "IntegrationTests" { + Context "When finding User Objects for SA" { BeforeAll { $null = New-DbaDatabase -SqlInstance $TestConfig.instance2 -Name 'dbatoolsci_userObject' -Owner 'sa' + $results = Find-DbaUserObject -SqlInstance $TestConfig.instance2 -Pattern sa } + AfterAll { $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database 'dbatoolsci_userObject' -Confirm:$false } - $results = Find-DbaUserObject -SqlInstance $TestConfig.instance2 -Pattern sa It "Should find a specific Database Owned by sa" { - $results.Where( {$_.name -eq 'dbatoolsci_userobject'}).Type | Should Be "Database" + $results.Where({ $PSItem.name -eq 'dbatoolsci_userobject' }).Type | Should -BeExactly "Database" } + It "Should find more than 10 objects Owned by sa" { - $results.Count | Should BeGreaterThan 10 + $results.Count | Should -BeGreaterThan 10 } } - Context "Command finds User Objects" { - $results = Find-DbaUserObject -SqlInstance $TestConfig.instance2 - It "Should find resutls" { - $results | Should Not Be Null + + Context "When finding all User Objects" { + BeforeAll { + $results = Find-DbaUserObject -SqlInstance $TestConfig.instance2 + } + + It "Should find results" { + $results | Should -Not -BeNullOrEmpty } } } diff --git a/tests/Find-DbaView.Tests.ps1 b/tests/Find-DbaView.Tests.ps1 index e9cb17fe49..61cc8e589f 100644 --- a/tests/Find-DbaView.Tests.ps1 +++ b/tests/Find-DbaView.Tests.ps1 @@ -1,70 +1,99 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'Pattern', 'IncludeSystemObjects', 'IncludeSystemDatabases', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Find-DbaView" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Find-DbaView + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "Pattern", + "IncludeSystemObjects", + "IncludeSystemDatabases", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } - -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - Context "Command finds Views in a System Database" { +Describe "Find-DbaView" -Tags "IntegrationTests" { + Context "When finding views in a system database" { BeforeAll { - $ServerView = @" + $serverView = @" CREATE VIEW dbo.v_dbatoolsci_sysadmin AS SELECT [sid],[loginname],[sysadmin] FROM [master].[sys].[syslogins]; "@ - $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'Master' -Query $ServerView + $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'Master' -Query $serverView } + AfterAll { - $DropView = "DROP VIEW dbo.v_dbatoolsci_sysadmin;" - $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'Master' -Query $DropView + $dropView = "DROP VIEW dbo.v_dbatoolsci_sysadmin;" + $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'Master' -Query $dropView + } + + BeforeAll { + $results = Find-DbaView -SqlInstance $TestConfig.instance2 -Pattern dbatools* -IncludeSystemDatabases } - $results = Find-DbaView -SqlInstance $TestConfig.instance2 -Pattern dbatools* -IncludeSystemDatabases It "Should find a specific View named v_dbatoolsci_sysadmin" { - $results.Name | Should Be "v_dbatoolsci_sysadmin" + $results.Name | Should -Be "v_dbatoolsci_sysadmin" } + It "Should find v_dbatoolsci_sysadmin in Master" { - $results.Database | Should Be "Master" + $results.Database | Should -Be "Master" $results.DatabaseId | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database Master).ID } } - Context "Command finds View in a User Database" { + + Context "When finding views in a user database" { BeforeAll { $null = New-DbaDatabase -SqlInstance $TestConfig.instance2 -Name 'dbatoolsci_viewdb' - $DatabaseView = @" + $databaseView = @" CREATE VIEW dbo.v_dbatoolsci_sysadmin AS SELECT [sid],[loginname],[sysadmin] FROM [master].[sys].[syslogins]; "@ - $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'dbatoolsci_viewdb' -Query $DatabaseView + $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'dbatoolsci_viewdb' -Query $databaseView + $resultsInDb = Find-DbaView -SqlInstance $TestConfig.instance2 -Pattern dbatools* -Database 'dbatoolsci_viewdb' + $resultsExcluded = Find-DbaView -SqlInstance $TestConfig.instance2 -Pattern dbatools* -ExcludeDatabase 'dbatoolsci_viewdb' } + AfterAll { $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database 'dbatoolsci_viewdb' -Confirm:$false } - $results = Find-DbaView -SqlInstance $TestConfig.instance2 -Pattern dbatools* -Database 'dbatoolsci_viewdb' It "Should find a specific view named v_dbatoolsci_sysadmin" { - $results.Name | Should Be "v_dbatoolsci_sysadmin" + $resultsInDb.Name | Should -Be "v_dbatoolsci_sysadmin" } + It "Should find v_dbatoolsci_sysadmin in dbatoolsci_viewdb Database" { - $results.Database | Should Be "dbatoolsci_viewdb" - $results.DatabaseId | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database dbatoolsci_viewdb).ID + $resultsInDb.Database | Should -Be "dbatoolsci_viewdb" + $resultsInDb.DatabaseId | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database dbatoolsci_viewdb).ID } - $results = Find-DbaView -SqlInstance $TestConfig.instance2 -Pattern dbatools* -ExcludeDatabase 'dbatoolsci_viewdb' + It "Should find no results when Excluding dbatoolsci_viewdb" { - $results | Should Be $null + $resultsExcluded | Should -BeNullOrEmpty } } } diff --git a/tests/Get-DbaAgBackupHistory.Tests.ps1 b/tests/Get-DbaAgBackupHistory.Tests.ps1 index 7ecc2b608b..61351cb86f 100644 --- a/tests/Get-DbaAgBackupHistory.Tests.ps1 +++ b/tests/Get-DbaAgBackupHistory.Tests.ps1 @@ -1,14 +1,45 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'AvailabilityGroup', 'Database', 'ExcludeDatabase', 'IncludeCopyOnly', 'Force', 'Since', 'RecoveryFork', 'Last', 'LastFull', 'LastDiff', 'LastLog', 'DeviceType', 'Raw', 'LastLsn', 'Type', 'EnableException', 'IncludeMirror', 'LsnSort' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Get-DbaAgBackupHistory" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaAgBackupHistory + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "AvailabilityGroup", + "Database", + "ExcludeDatabase", + "IncludeCopyOnly", + "Force", + "Since", + "RecoveryFork", + "Last", + "LastFull", + "LastDiff", + "LastLog", + "DeviceType", + "Raw", + "LastLsn", + "Type", + "EnableException", + "IncludeMirror", + "LsnSort" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } diff --git a/tests/Get-DbaAgDatabase.Tests.ps1 b/tests/Get-DbaAgDatabase.Tests.ps1 index b4a54d3d2f..9bb21a338f 100644 --- a/tests/Get-DbaAgDatabase.Tests.ps1 +++ b/tests/Get-DbaAgDatabase.Tests.ps1 @@ -1,19 +1,38 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'AvailabilityGroup', 'Database', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + +Describe "Get-DbaAgDatabase" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaAgDatabase + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "AvailabilityGroup", + "Database", + "InputObject", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe "Get-DbaAgDatabase" -Tag "IntegrationTests" { BeforeAll { $null = Get-DbaProcess -SqlInstance $TestConfig.instance3 -Program 'dbatools PowerShell module - dbatools.io' | Stop-DbaProcess -WarningAction SilentlyContinue $server = Connect-DbaInstance -SqlInstance $TestConfig.instance3 @@ -24,16 +43,27 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { $null = Get-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $dbname | Backup-DbaDatabase -Type Log $ag = New-DbaAvailabilityGroup -Primary $TestConfig.instance3 -Name $agname -ClusterType None -FailoverMode Manual -Database $dbname -Confirm:$false -Certificate dbatoolsci_AGCert -UseLastBackup } + AfterAll { $null = Remove-DbaAvailabilityGroup -SqlInstance $server -AvailabilityGroup $agname -Confirm:$false $null = Remove-DbaDatabase -SqlInstance $server -Database $dbname -Confirm:$false } - Context "gets ag db" { - It "returns results" { + + Context "When getting availability group databases" { + BeforeAll { $results = Get-DbaAgDatabase -SqlInstance $TestConfig.instance3 -Database $dbname - $results.AvailabilityGroup | Should -Be $agname - $results.Name | Should -Be $dbname - $results.LocalReplicaRole | Should -Not -Be $null + } + + It "Returns the correct availability group name" { + $results.AvailabilityGroup | Should -BeExactly $agname + } + + It "Returns the correct database name" { + $results.Name | Should -BeExactly $dbname + } + + It "Returns a local replica role" { + $results.LocalReplicaRole | Should -Not -BeNullOrEmpty } } } #$TestConfig.instance2 for appveyor diff --git a/tests/Get-DbaAgHadr.Tests.ps1 b/tests/Get-DbaAgHadr.Tests.ps1 index ecd586d652..27cdf1f007 100644 --- a/tests/Get-DbaAgHadr.Tests.ps1 +++ b/tests/Get-DbaAgHadr.Tests.ps1 @@ -1,25 +1,44 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag "UnitTests" { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Get-DbaAgHadr" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaAgHadr + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } # $TestConfig.instance3 is used for Availability Group tests and needs Hadr service setting enabled -Describe "$CommandName Integration Test" -Tag "IntegrationTests" { - $results = Get-DbaAgHadr -SqlInstance $TestConfig.instance3 +Describe "Get-DbaAgHadr" -Tag "IntegrationTests" { + BeforeAll { + $results = Get-DbaAgHadr -SqlInstance $TestConfig.instance3 + } + Context "Validate output" { It "returns the correct properties" { - $results.IsHadrEnabled | Should -Be $true + $results.IsHadrEnabled | Should -BeTrue } } } #$TestConfig.instance2 for appveyor diff --git a/tests/Get-DbaAgListener.Tests.ps1 b/tests/Get-DbaAgListener.Tests.ps1 index 8fa95c2d48..9209653aa7 100644 --- a/tests/Get-DbaAgListener.Tests.ps1 +++ b/tests/Get-DbaAgListener.Tests.ps1 @@ -1,30 +1,68 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'AvailabilityGroup', 'Listener', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + +Describe "Get-DbaAgListener" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaAgListener + $knownParameters = @( + 'SqlInstance', + 'SqlCredential', + 'AvailabilityGroup', + 'Listener', + 'InputObject', + 'EnableException' + ) + $knownParameters += $TestConfig.CommonParameters + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $knownParameters { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of parameters ($($knownParameters.Count))" { + $params = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $knownParameters -DifferenceObject $params | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe "Get-DbaAgListener" -Tag "IntegrationTests" { BeforeAll { $agname = "dbatoolsci_ag_listener" - $ag = New-DbaAvailabilityGroup -Primary $TestConfig.instance3 -Name $agname -ClusterType None -FailoverMode Manual -Certificate dbatoolsci_AGCert -Confirm:$false - $ag | Add-DbaAgListener -IPAddress 127.0.20.1 -Port 14330 -Confirm:$false + $splatAg = @{ + Primary = $TestConfig.instance3 + Name = $agname + ClusterType = "None" + FailoverMode = "Manual" + Certificate = "dbatoolsci_AGCert" + Confirm = $false + } + $ag = New-DbaAvailabilityGroup @splatAg + + $splatListener = @{ + IPAddress = "127.0.20.1" + Port = 14330 + Confirm = $false + } + $ag | Add-DbaAgListener @splatListener } + AfterAll { $null = Remove-DbaAvailabilityGroup -SqlInstance $TestConfig.instance3 -AvailabilityGroup $agname -Confirm:$false } - Context "gets ags" { - It "returns results with proper data" { + + Context "When getting availability group listeners" { + BeforeAll { $results = Get-DbaAgListener -SqlInstance $TestConfig.instance3 + } + + It "Returns results with proper port number" { $results.PortNumber | Should -Contain 14330 } } diff --git a/tests/Get-DbaAgReplica.Tests.ps1 b/tests/Get-DbaAgReplica.Tests.ps1 index 8658988957..dc7ce123d1 100644 --- a/tests/Get-DbaAgReplica.Tests.ps1 +++ b/tests/Get-DbaAgReplica.Tests.ps1 @@ -1,39 +1,78 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$commandname Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'AvailabilityGroup', 'Replica', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 + +Describe "Get-DbaAgReplica" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaAgReplica + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "AvailabilityGroup", + "Replica", + "InputObject", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe "Get-DbaAgReplica" -Tag "IntegrationTests" { BeforeAll { - $agname = "dbatoolsci_agroup" - $ag = New-DbaAvailabilityGroup -Primary $TestConfig.instance3 -Name $agname -ClusterType None -FailoverMode Manual -Certificate dbatoolsci_AGCert -Confirm:$false + $primaryAgName = "dbatoolsci_agroup" + $splatPrimary = @{ + Primary = $TestConfig.instance3 + Name = $primaryAgName + ClusterType = "None" + FailoverMode = "Manual" + Certificate = "dbatoolsci_AGCert" + Confirm = $false + } + $ag = New-DbaAvailabilityGroup @splatPrimary $replicaName = $ag.PrimaryReplica } + AfterAll { - $null = Remove-DbaAvailabilityGroup -SqlInstance $TestConfig.instance3 -AvailabilityGroup $agname -Confirm:$false + $null = Remove-DbaAvailabilityGroup -SqlInstance $TestConfig.instance3 -AvailabilityGroup $primaryAgName -Confirm:$false } - Context "gets ag replicas" { - It "returns results with proper data" { + + Context "When getting AG replicas" { + BeforeAll { $results = Get-DbaAgReplica -SqlInstance $TestConfig.instance3 - $results.AvailabilityGroup | Should -Contain $agname + } + + It "Returns results with proper data" { + $results.AvailabilityGroup | Should -Contain $primaryAgName $results.Role | Should -Contain 'Primary' $results.AvailabilityMode | Should -Contain 'SynchronousCommit' } - It "returns just one result" { - $results = Get-DbaAgReplica -SqlInstance $TestConfig.instance3 -Replica $replicaName -AvailabilityGroup $agname - $results.AvailabilityGroup | Should -Be $agname - $results.Role | Should -Be 'Primary' - $results.AvailabilityMode | Should -Be 'SynchronousCommit' + + It "Returns just one result when filtering by replica and AG" { + $splatFilter = @{ + SqlInstance = $TestConfig.instance3 + Replica = $replicaName + AvailabilityGroup = $primaryAgName + } + $filtered = Get-DbaAgReplica @splatFilter + + $filtered.AvailabilityGroup | Should -Be $primaryAgName + $filtered.Role | Should -Be 'Primary' + $filtered.AvailabilityMode | Should -Be 'SynchronousCommit' } # Skipping because this adds like 30 seconds to test times diff --git a/tests/Get-DbaAgentAlert.Tests.ps1 b/tests/Get-DbaAgentAlert.Tests.ps1 index 2f09279558..3157f8f2f5 100644 --- a/tests/Get-DbaAgentAlert.Tests.ps1 +++ b/tests/Get-DbaAgentAlert.Tests.ps1 @@ -1,31 +1,47 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'EnableException', 'Alert', 'ExcludeAlert' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Get-DbaAgentAlert" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaAgentAlert + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Alert", + "ExcludeAlert", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { +Describe "Get-DbaAgentAlert" -Tag "IntegrationTests" { BeforeAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 -Database master $server.Query("EXEC msdb.dbo.sp_add_alert @name=N'dbatoolsci test alert',@message_id=0,@severity=6,@enabled=1,@delay_between_responses=0,@include_event_description_in=0,@category_name=N'[Uncategorized]',@job_id=N'00000000-0000-0000-0000-000000000000'") + $results = Get-DbaAgentAlert -SqlInstance $TestConfig.instance2 } + AfterAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 -Database master $server.Query("EXEC msdb.dbo.sp_delete_alert @name=N'dbatoolsci test alert'") } - $results = Get-DbaAgentAlert -SqlInstance $TestConfig.instance2 - It "gets the newly created alert" { - $results.Name -contains 'dbatoolsci test alert' + It "Gets the newly created alert" { + $results.Name | Should -Contain 'dbatoolsci test alert' } } - diff --git a/tests/Get-DbaAgentAlertCategory.Tests.ps1 b/tests/Get-DbaAgentAlertCategory.Tests.ps1 index ad6425b182..5f6753b027 100644 --- a/tests/Get-DbaAgentAlertCategory.Tests.ps1 +++ b/tests/Get-DbaAgentAlertCategory.Tests.ps1 @@ -1,33 +1,64 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Category', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Get-DbaAgentAlertCategory" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaAgentAlertCategory + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Category", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - Context "Command gets alert categories" { +Describe "Get-DbaAgentAlertCategory" -Tag "IntegrationTests" { + BeforeAll { + $categories = @( + "dbatoolsci_testcategory", + "dbatoolsci_testcategory2" + ) + $null = New-DbaAgentAlertCategory -SqlInstance $TestConfig.instance2 -Category $categories + } + + AfterAll { + $null = Remove-DbaAgentAlertCategory -SqlInstance $TestConfig.instance2 -Category $categories -Confirm:$false + } + + Context "When getting all alert categories" { BeforeAll { - $null = New-DbaAgentAlertCategory -SqlInstance $TestConfig.instance2 -Category dbatoolsci_testcategory, dbatoolsci_testcategory2 + $results = Get-DbaAgentAlertCategory -SqlInstance $TestConfig.instance2 | Where-Object Name -match "dbatoolsci" } - AfterAll { - $null = Remove-DbaAgentAlertCategory -SqlInstance $TestConfig.instance2 -Category dbatoolsci_testcategory, dbatoolsci_testcategory2 -Confirm:$false + + It "Returns at least 2 categories" { + $results.Count | Should -BeGreaterThan 1 } - $results = Get-DbaAgentAlertCategory -SqlInstance $TestConfig.instance2 | Where-Object {$_.Name -match "dbatoolsci"} - It "Should get at least 2 categories" { - $results.count | Should BeGreaterThan 1 + } + + Context "When getting a specific alert category" { + BeforeAll { + $results = Get-DbaAgentAlertCategory -SqlInstance $TestConfig.instance2 -Category dbatoolsci_testcategory | + Where-Object Name -match "dbatoolsci" } - $results = Get-DbaAgentAlertCategory -SqlInstance $TestConfig.instance2 -Category dbatoolsci_testcategory | Where-Object {$_.Name -match "dbatoolsci"} - It "Should get the dbatoolsci_testcategory category" { - $results.count | Should Be 1 + + It "Returns exactly one category" { + $results.Count | Should -Be 1 } } } diff --git a/tests/Get-DbaAgentJob.Tests.ps1 b/tests/Get-DbaAgentJob.Tests.ps1 index d5c41b23cc..614c80f384 100644 --- a/tests/Get-DbaAgentJob.Tests.ps1 +++ b/tests/Get-DbaAgentJob.Tests.ps1 @@ -1,85 +1,117 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [array]$params = ([Management.Automation.CommandMetaData]$ExecutionContext.SessionState.InvokeCommand.GetCommand($CommandName, 'Function')).Parameters.Keys - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Job', 'ExcludeJob', 'Database', 'Category', 'ExcludeDisabledJobs', 'EnableException', 'ExcludeCategory', 'IncludeExecution', 'Type' +Describe "Get-DbaAgentJob" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaAgentJob + $knownParameters = @( + 'SqlInstance' + 'SqlCredential' + 'Job' + 'ExcludeJob' + 'Database' + 'Category' + 'ExcludeCategory' + 'ExcludeDisabledJobs' + 'IncludeExecution' + 'Type' + 'EnableException' + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $knownParameters { + $command | Should -HaveParameter $PSItem + } - It "Should only contain our specific parameters" { + It "Should have exactly the number of parameters ($($knownParameters.Count))" { + $params = $command.Parameters.Values.Name Compare-Object -ReferenceObject $knownParameters -DifferenceObject $params | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - Context "Command gets jobs" { +Describe "Get-DbaAgentJob" -Tag "IntegrationTests" { + Context "When getting jobs" { BeforeAll { $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob_disabled -Disabled } + AfterAll { $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob, dbatoolsci_testjob_disabled -Confirm:$false } - $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 | Where-Object { $_.Name -match "dbatoolsci_testjob" } - It "Should get 2 dbatoolsci jobs" { - $results.count | Should Be 2 - } - $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob - It "Should get a specific job" { - $results.name | Should Be "dbatoolsci_testjob" + + It "Returns 2 dbatoolsci jobs" { + $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 | Where-Object Name -Match "dbatoolsci_testjob" + $results.Count | Should -Be 2 } + It "Returns a specific job by name" { + $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob + $results.Name | Should -Be "dbatoolsci_testjob" + } } - Context "Command gets no disabled jobs" { + + Context "When excluding disabled jobs" { BeforeAll { $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob_disabled -Disabled } + AfterAll { $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob, dbatoolsci_testjob_disabled -Confirm:$false } - $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -ExcludeDisabledJobs | Where-Object { $_.Name -match "dbatoolsci_testjob" } - It "Should return only enabled jobs" { - $results.enabled -contains $False | Should Be $False + + It "Returns only enabled jobs" { + $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -ExcludeDisabledJobs | Where-Object Name -Match "dbatoolsci_testjob" + $results.Enabled -contains $false | Should -Be $false } } - Context "Command doesn't get excluded job" { + + Context "When excluding specific jobs" { BeforeAll { $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob_disabled -Disabled } + AfterAll { $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob, dbatoolsci_testjob_disabled -Confirm:$false } - $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -ExcludeJob dbatoolsci_testjob | Where-Object { $_.Name -match "dbatoolsci_testjob" } - It "Should not return excluded job" { - $results.name -contains "dbatoolsci_testjob" | Should Be $False + + It "Does not return excluded jobs" { + $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -ExcludeJob dbatoolsci_testjob | Where-Object Name -Match "dbatoolsci_testjob" + $results.Name -contains "dbatoolsci_testjob" | Should -Be $false } } - Context "Command doesn't get excluded category" { + + Context "When excluding job categories" { BeforeAll { $null = New-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category 'Cat1' $null = New-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category 'Cat2' - $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob_cat1 -Category 'Cat1' $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob_cat2 -Category 'Cat2' } + AfterAll { $null = Remove-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category 'Cat1', 'Cat2' -Confirm:$false - $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob_cat1, dbatoolsci_testjob_cat2 -Confirm:$false } - $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -ExcludeCategory 'Cat2' | Where-Object { $_.Name -match "dbatoolsci_testjob" } - It "Should not return excluded job" { - $results.name -contains "dbatoolsci_testjob_cat2" | Should Be $False + + It "Does not return jobs from excluded categories" { + $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -ExcludeCategory 'Cat2' | Where-Object Name -Match "dbatoolsci_testjob" + $results.Name -contains "dbatoolsci_testjob_cat2" | Should -Be $false } } - Context "Command gets jobs when databases are specified" { + + Context "When filtering by database" { BeforeAll { $jobName1 = "dbatoolsci_dbfilter_$(Get-Random)" $jobName2 = "dbatoolsci_dbfilter_$(Get-Random)" + $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job $jobName1 -Disabled $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job $jobName1 -StepName "TSQL-x" -Subsystem TransactSql -Database "msdb" $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job $jobName1 -StepName "TSQL-y" -Subsystem TransactSql -Database "tempdb" @@ -90,23 +122,21 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job $jobName2 -StepName "TSQL-y" -Subsystem TransactSql -Database "model" $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job $jobName2 -StepName "TSQL-z" -Subsystem TransactSql -Database "master" } + AfterAll { $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job $jobName1, $jobName2 -Confirm:$false } - $resultSingleDatabase = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Database tempdb - It "Returns result with single database" { + + It "Returns jobs for a single database" { + $resultSingleDatabase = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Database tempdb $resultSingleDatabase.Count | Should -BeGreaterOrEqual 1 - } - It "Returns job result for Database: tempdb" { - $resultSingleDatabase.name -contains $jobName1 | Should -BeTrue + $resultSingleDatabase.Name -contains $jobName1 | Should -BeTrue } - $resultMultipleDatabases = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Database tempdb, model - It "Returns both jobs with double database" { + It "Returns jobs for multiple databases" { + $resultMultipleDatabases = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Database tempdb, model $resultMultipleDatabases.Count | Should -BeGreaterOrEqual 2 - } - It "Includes job result for Database: model" { - $resultMultipleDatabases.name -contains $jobName2 | Should -BeTrue + $resultMultipleDatabases.Name -contains $jobName2 | Should -BeTrue } } } diff --git a/tests/Get-DbaAgentJobCategory.Tests.ps1 b/tests/Get-DbaAgentJobCategory.Tests.ps1 index 3344a55e11..e5dedf0b4c 100644 --- a/tests/Get-DbaAgentJobCategory.Tests.ps1 +++ b/tests/Get-DbaAgentJobCategory.Tests.ps1 @@ -1,37 +1,59 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Category', 'CategoryType', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + +Describe "Get-DbaAgentJobCategory" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaAgentJobCategory + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Category", + "CategoryType", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe "Get-DbaAgentJobCategory" -Tag "IntegrationTests" { Context "Command gets job categories" { BeforeAll { $null = New-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category dbatoolsci_testcategory, dbatoolsci_testcategory2 + $results = Get-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 | Where-Object Name -Match "dbatoolsci" + $singleResult = Get-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category dbatoolsci_testcategory | Where-Object Name -Match "dbatoolsci" + $typeResults = Get-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -CategoryType LocalJob | Where-Object Name -Match "dbatoolsci" } + AfterAll { $null = Remove-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category dbatoolsci_testcategory, dbatoolsci_testcategory2 -Confirm:$false } - $results = Get-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 | Where-Object {$_.Name -match "dbatoolsci"} + It "Should get at least 2 categories" { - $results.count | Should BeGreaterThan 1 + $results.Count | Should -BeGreaterThan 1 } - $results = Get-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category dbatoolsci_testcategory | Where-Object {$_.Name -match "dbatoolsci"} + It "Should get the dbatoolsci_testcategory category" { - $results.count | Should Be 1 + $singleResult.Count | Should -Be 1 } - $results = Get-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -CategoryType LocalJob | Where-Object {$_.Name -match "dbatoolsci"} + It "Should get at least 1 LocalJob" { - $results.count | Should BeGreaterThan 1 + $typeResults.Count | Should -BeGreaterThan 1 } } } diff --git a/tests/Get-DbaAgentJobOutputFile.Tests.ps1 b/tests/Get-DbaAgentJobOutputFile.Tests.ps1 index ea63f48ded..218ba23511 100644 --- a/tests/Get-DbaAgentJobOutputFile.Tests.ps1 +++ b/tests/Get-DbaAgentJobOutputFile.Tests.ps1 @@ -1,102 +1,120 @@ -$commandname = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Job', 'ExcludeJob', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Get-DbaAgentJobOutputFile" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaAgentJobOutputFile + $knownParameters = @( + 'SqlInstance', + 'SqlCredential', + 'Job', + 'ExcludeJob', + 'EnableException' + ) + $knownParameters += $TestConfig.CommonParameters + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $knownParameters { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of parameters ($($knownParameters.Count))" { + $params = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $knownParameters -DifferenceObject $params | Should -BeNullOrEmpty } } } -Describe "$CommandName Unittests" -Tag 'UnitTests' { - InModuleScope 'dbatools' { +Describe "Get-DbaAgentJobOutputFile Integration Tests" -Tag "UnitTests" { + BeforeAll { + Mock Connect-DbaInstance -MockWith { + [PSCustomObject]@{ + Name = 'SQLServerName' + ComputerName = 'SQLServerName' + JobServer = @{ + Jobs = @( + @{ + Name = 'Job1' + JobSteps = @( + @{ + Id = 1 + Name = 'Job1Step1' + OutputFileName = 'Job1Output1' + }, + @{ + Id = 2 + Name = 'Job1Step2' + OutputFileName = 'Job1Output2' + } + ) + }, + @{ + Name = 'Job2' + JobSteps = @( + @{ + Id = 1 + Name = 'Job2Step1' + OutputFileName = 'Job2Output1' + }, + @{ + Id = 2 + Name = 'Job2Step2' + } + ) + }, + @{ + Name = 'Job3' + JobSteps = @( + @{ + Id = 1 + Name = 'Job3Step1' + }, + @{ + Id = 2 + Name = 'Job3Step2' + } + ) + } + ) + } + } + } -ModuleName dbatools + Context "Return values" { - Mock Connect-DbaInstance -MockWith { - [object]@{ - Name = 'SQLServerName' - ComputerName = 'SQLServerName' - JobServer = @{ - Jobs = @( - @{ - Name = 'Job1' - JobSteps = @( - @{ - Id = 1 - Name = 'Job1Step1' - OutputFileName = 'Job1Output1' - }, - @{ - Id = 2 - Name = 'Job1Step2' - OutputFileName = 'Job1Output2' - } - ) - }, - @{ - Name = 'Job2' - JobSteps = @( - @{ - Id = 1 - Name = 'Job2Step1' - OutputFileName = 'Job2Output1' - }, - @{ - Id = 2 - Name = 'Job2Step2' - } - ) - }, - @{ - Name = 'Job3' - JobSteps = @( - @{ - Id = 1 - Name = 'Job3Step1' - }, - @{ - Id = 2 - Name = 'Job3Step2' - } - ) - } - ) - } - } #object - } #mock Connect-DbaInstance It "Gets only steps with output files" { - $Results = @() - $Results += Get-DbaAgentJobOutputFile -SqlInstance 'SQLServerName' - $Results.Length | Should Be 3 - $Results.Job | Should Match 'Job[12]' - $Results.JobStep | Should Match 'Job[12]Step[12]' - $Results.OutputFileName | Should Match 'Job[12]Output[12]' - $Results.RemoteOutputFileName | Should Match '\\\\SQLServerName\\Job[12]Output[12]' + $results = Get-DbaAgentJobOutputFile -SqlInstance 'SQLServerName' + $results.Count | Should -Be 3 + $results.Job | Should -Match 'Job[12]' + $results.JobStep | Should -Match 'Job[12]Step[12]' + $results.OutputFileName | Should -Match 'Job[12]Output[12]' + $results.RemoteOutputFileName | Should -Match '\\\\SQLServerName\\Job[12]Output[12]' } + It "Honors the Job parameter" { - $Results = @() - $Results += Get-DbaAgentJobOutputFile -SqlInstance 'SQLServerName' -Job 'Job1' - $Results.Job | Should Match 'Job1' - $Results.JobStep | Should Match 'Job1Step[12]' - $Results.OutputFileName | Should Match 'Job1Output[12]' + $results = Get-DbaAgentJobOutputFile -SqlInstance 'SQLServerName' -Job 'Job1' + $results.Job | Should -Match 'Job1' + $results.JobStep | Should -Match 'Job1Step[12]' + $results.OutputFileName | Should -Match 'Job1Output[12]' } + It "Honors the ExcludeJob parameter" { - $Results = @() - $Results += Get-DbaAgentJobOutputFile -SqlInstance 'SQLServerName' -ExcludeJob 'Job1' - $Results.Length | Should Be 1 - $Results.Job | Should Match 'Job2' - $Results.OutputFileName | Should Be 'Job2Output1' - $Results.StepId | Should Be 1 + $results = Get-DbaAgentJobOutputFile -SqlInstance 'SQLServerName' -ExcludeJob 'Job1' + $results.Count | Should -Be 1 + $results.Job | Should -Match 'Job2' + $results.OutputFileName | Should -Be 'Job2Output1' + $results.StepId | Should -Be 1 } + It "Does not return even with a specific job without outputfiles" { - $Results = @() - $Results += Get-DbaAgentJobOutputFile -SqlInstance 'SQLServerName' -Job 'Job3' - $Results.Length | Should Be 0 + $results = Get-DbaAgentJobOutputFile -SqlInstance 'SQLServerName' -Job 'Job3' + $results.Count | Should -Be 0 } } } -} \ No newline at end of file +} diff --git a/tests/Get-DbaAgentJobStep.Tests.ps1 b/tests/Get-DbaAgentJobStep.Tests.ps1 index b32e782770..ac4c909e4a 100644 --- a/tests/Get-DbaAgentJobStep.Tests.ps1 +++ b/tests/Get-DbaAgentJobStep.Tests.ps1 @@ -1,46 +1,67 @@ -$commandname = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Job', 'ExcludeJob', 'ExcludeDisabledJobs', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 - } +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Get-DbaAgentJobStep" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaAgentJobStep + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Job", + "ExcludeJob", + "ExcludeDisabledJobs", + "InputObject", + "EnableException" + ) } -} -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { - Context "Gets a job step" { - BeforeAll { - $jobName = "dbatoolsci_job_$(get-random)" - $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job $jobName - $null = New-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job $jobName -StepName dbatoolsci_jobstep1 -Subsystem TransactSql -Command 'select 1' - } - AfterAll { - $null = Remove-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job $jobName -Confirm:$false + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem } - It "Successfully gets job when not using Job param" { - $results = Get-DbaAgentJobStep -SqlInstance $TestConfig.instance2 - $results.Name | should contain 'dbatoolsci_jobstep1' + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasParams = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasParams | Should -BeNullOrEmpty } - It "Successfully gets job when using Job param" { - $results = Get-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job $jobName - $results.Name | should contain 'dbatoolsci_jobstep1' + } +} + +Describe "Get-DbaAgentJobStep" -Tag "IntegrationTests" { + BeforeAll { + $jobName = "dbatoolsci_job_$(Get-Random)" + $null = New-DbaAgentJob -SqlInstance $TestConfig.Instance2 -Job $jobName + $null = New-DbaAgentJobStep -SqlInstance $TestConfig.Instance2 -Job $jobName -StepName dbatoolsci_jobstep1 -Subsystem TransactSql -Command 'select 1' + } + + AfterAll { + $null = Remove-DbaAgentJob -SqlInstance $TestConfig.Instance2 -Job $jobName -Confirm:$false + } + + Context "When getting job steps" { + It "Returns job steps without using Job parameter" { + $results = Get-DbaAgentJobStep -SqlInstance $TestConfig.Instance2 + $results.Name | Should -Contain 'dbatoolsci_jobstep1' } - It "Successfully gets job when excluding some jobs" { - $results = Get-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -ExcludeJob 'syspolicy_purge_history' - $results.Name | should contain 'dbatoolsci_jobstep1' + + It "Returns job steps when using Job parameter" { + $results = Get-DbaAgentJobStep -SqlInstance $TestConfig.Instance2 -Job $jobName + $results.Name | Should -Contain 'dbatoolsci_jobstep1' } - It "Successfully excludes disabled jobs" { - $null = Set-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job $jobName -Disabled - $results = Get-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -ExcludeDisabledJobs - $results.Name | should not contain 'dbatoolsci_jobstep1' + + It "Returns job steps when excluding specific jobs" { + $results = Get-DbaAgentJobStep -SqlInstance $TestConfig.Instance2 -ExcludeJob 'syspolicy_purge_history' + $results.Name | Should -Contain 'dbatoolsci_jobstep1' } + It "Excludes disabled jobs when specified" { + $null = Set-DbaAgentJob -SqlInstance $TestConfig.Instance2 -Job $jobName -Disabled + $results = Get-DbaAgentJobStep -SqlInstance $TestConfig.Instance2 -ExcludeDisabledJobs + $results.Name | Should -Not -Contain 'dbatoolsci_jobstep1' + } } } diff --git a/tests/Get-DbaAgentLog.Tests.ps1 b/tests/Get-DbaAgentLog.Tests.ps1 index 1445215a9d..5128b1c7a0 100644 --- a/tests/Get-DbaAgentLog.Tests.ps1 +++ b/tests/Get-DbaAgentLog.Tests.ps1 @@ -1,35 +1,61 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'LogNumber', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Get-DbaAgentLog" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaAgentLog + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "LogNumber", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe "Get-DbaAgentLog" -Tags "IntegrationTests" { Context "Command gets agent log" { - $results = Get-DbaAgentLog -SqlInstance $TestConfig.instance2 - It "Results are not empty" { - $results | Should Not Be $Null + BeforeAll { + $results = Get-DbaAgentLog -SqlInstance $TestConfig.instance2 + } + + It "Returns results" { + $results | Should -Not -BeNullOrEmpty } + It "Results contain SQLServerAgent version" { - $results.text -like '`[100`] Microsoft SQLServerAgent version*' | Should Be $true + $results.text -like '[100] Microsoft SQLServerAgent version*' | Should -Be $true } + It "LogDate is a DateTime type" { - $($results | Select-Object -first 1).LogDate | Should BeOfType DateTime + $($results | Select-Object -First 1).LogDate | Should -BeOfType DateTime } } + Context "Command gets current agent log using LogNumber parameter" { - $results = Get-DbaAgentLog -SqlInstance $TestConfig.instance2 -LogNumber 0 - It "Results are not empty" { - $results | Should Not Be $Null + BeforeAll { + $results = Get-DbaAgentLog -SqlInstance $TestConfig.instance2 -LogNumber 0 + } + + It "Returns results" { + $results | Should -Not -BeNullOrEmpty } } } diff --git a/tests/Get-DbaAgentOperator.Tests.ps1 b/tests/Get-DbaAgentOperator.Tests.ps1 index 9cc587ebbc..694f20f731 100644 --- a/tests/Get-DbaAgentOperator.Tests.ps1 +++ b/tests/Get-DbaAgentOperator.Tests.ps1 @@ -1,40 +1,83 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Operator', 'ExcludeOperator', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Get-DbaAgentOperator" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaAgentOperator + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Operator", + "ExcludeOperator", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe "Get-DbaAgentOperator" -Tag "IntegrationTests" { BeforeAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 - $sql = "EXEC msdb.dbo.sp_add_operator @name=N'dbatoolsci_operator', @enabled=1, @pager_days=0" - $server.Query($sql) - $sql = "EXEC msdb.dbo.sp_add_operator @name=N'dbatoolsci_operator2', @enabled=1, @pager_days=0" - $server.Query($sql) + $operatorName = "dbatoolsci_operator" + $operatorName2 = "dbatoolsci_operator2" + + $splatOperator1 = @{ + Name = $operatorName + Enabled = 1 + PagerDays = 0 + } + $splatOperator2 = @{ + Name = $operatorName2 + Enabled = 1 + PagerDays = 0 + } + + $server.Query("EXEC msdb.dbo.sp_add_operator @name=N'$operatorName', @enabled=1, @pager_days=0") + $server.Query("EXEC msdb.dbo.sp_add_operator @name=N'$operatorName2', @enabled=1, @pager_days=0") } + AfterAll { - $sql = "EXEC msdb.dbo.sp_delete_operator @name=N'dbatoolsci_operator'" - $server.Query($sql) - $sql = "EXEC msdb.dbo.sp_delete_operator @name=N'dbatoolsci_operator2'" - $server.Query($sql) + $server.Query("EXEC msdb.dbo.sp_delete_operator @name=N'$operatorName'") + $server.Query("EXEC msdb.dbo.sp_delete_operator @name=N'$operatorName2'") } - Context "Get back some operators" { - $results = Get-DbaAgentOperator -SqlInstance $TestConfig.instance2 - It "return at least two results" { - $results.Count -ge 2 | Should Be $true - } - $results = Get-DbaAgentOperator -SqlInstance $TestConfig.instance2 -Operator dbatoolsci_operator - It "return one result" { - $results.Count | Should Be 1 + + Context "When getting SQL Agent operators" { + BeforeAll { + $results = Get-DbaAgentOperator -SqlInstance $TestConfig.instance2 + } + + It "Returns at least two operators" { + $results.Count | Should -BeGreaterOrEqual 2 + } + } + + Context "When filtering for a specific operator" { + BeforeAll { + $results = Get-DbaAgentOperator -SqlInstance $TestConfig.instance2 -Operator $operatorName + } + + It "Returns exactly one operator" { + $results.Count | Should -Be 1 + } + + It "Returns the correct operator" { + $results.Name | Should -Be $operatorName } } } diff --git a/tests/Get-DbaAgentProxy.Tests.ps1 b/tests/Get-DbaAgentProxy.Tests.ps1 index 55d5ff43ec..d02a713e3e 100644 --- a/tests/Get-DbaAgentProxy.Tests.ps1 +++ b/tests/Get-DbaAgentProxy.Tests.ps1 @@ -1,19 +1,35 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Proxy', 'ExcludeProxy', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Get-DbaAgentProxy" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaAgentProxy + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Proxy", + "ExcludeProxy", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe "Get-DbaAgentProxy" -Tag "IntegrationTests" { BeforeAll { $tPassword = ConvertTo-SecureString "ThisIsThePassword1" -AsPlainText -Force $tUserName = "dbatoolsci_proxytest" @@ -22,7 +38,8 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { New-DbaAgentProxy -SqlInstance $TestConfig.instance2 -Name STIG -ProxyCredential "$tUserName" New-DbaAgentProxy -SqlInstance $TestConfig.instance2 -Name STIGX -ProxyCredential "$tUserName" } - Afterall { + + AfterAll { $tUserName = "dbatoolsci_proxytest" Remove-LocalUser -Name $tUserName $credential = Get-DbaCredential -SqlInstance $TestConfig.instance2 -Name $tUserName @@ -31,40 +48,57 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { $proxy.DROP() } - Context "Gets the list of Proxy" { - $results = Get-DbaAgentProxy -SqlInstance $TestConfig.instance2 - It "Results are not empty" { - $results | Should Not Be $Null + Context "When getting all proxies" { + BeforeAll { + $results = Get-DbaAgentProxy -SqlInstance $TestConfig.instance2 + } + + It "Returns results" { + $results | Should -Not -BeNullOrEmpty } + It "Should have the name STIG" { - $results.name | Should Contain "STIG" + $results.name | Should -Contain "STIG" } + It "Should be enabled" { - $results.isenabled | Should Contain $true + $results.isenabled | Should -Contain $true } } - Context "Gets a single Proxy" { - $results = Get-DbaAgentProxy -SqlInstance $TestConfig.instance2 -Proxy "STIG" - It "Results are not empty" { - $results | Should Not Be $Null + + Context "When getting a single proxy" { + BeforeAll { + $results = Get-DbaAgentProxy -SqlInstance $TestConfig.instance2 -Proxy "STIG" + } + + It "Returns results" { + $results | Should -Not -BeNullOrEmpty } + It "Should have the name STIG" { - $results.name | Should Be "STIG" + $results.name | Should -Be "STIG" } + It "Should be enabled" { - $results.isenabled | Should Be $true + $results.isenabled | Should -Be $true } } - Context "Gets the list of Proxy without excluded" { - $results = Get-DbaAgentProxy -SqlInstance $TestConfig.instance2 -ExcludeProxy "STIG" - It "Results are not empty" { - $results | Should Not Be $Null + + Context "When excluding specific proxies" { + BeforeAll { + $results = Get-DbaAgentProxy -SqlInstance $TestConfig.instance2 -ExcludeProxy "STIG" + } + + It "Returns results" { + $results | Should -Not -BeNullOrEmpty } + It "Should not have the name STIG" { - $results.name | Should Not Be "STIG" + $results.name | Should -Not -Be "STIG" } + It "Should be enabled" { - $results.isenabled | Should Be $true + $results.isenabled | Should -Be $true } } } diff --git a/tests/Get-DbaAgentServer.Tests.ps1 b/tests/Get-DbaAgentServer.Tests.ps1 index 0a843e4fcd..94e139ae05 100644 --- a/tests/Get-DbaAgentServer.Tests.ps1 +++ b/tests/Get-DbaAgentServer.Tests.ps1 @@ -1,23 +1,46 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Get-DbaAgentServer" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaAgentServer + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe "Get-DbaAgentServer" -Tag "IntegrationTests" { Context "Command gets server agent" { - $results = Get-DbaAgentServer -SqlInstance $TestConfig.instance2 - It "Should get 1 agent server" { - $results.count | Should Be 1 + BeforeAll { + $results = Get-DbaAgentServer -SqlInstance $TestConfig.Instance2 + } + + It "Returns results" { + $results | Should -Not -BeNullOrEmpty + } + + It "Returns exactly one agent server" { + $results.Count | Should -Be 1 } } } diff --git a/tests/Get-DbaAvailabilityGroup.Tests.ps1 b/tests/Get-DbaAvailabilityGroup.Tests.ps1 index 720e73fcc2..380ce1ab11 100644 --- a/tests/Get-DbaAvailabilityGroup.Tests.ps1 +++ b/tests/Get-DbaAvailabilityGroup.Tests.ps1 @@ -1,35 +1,69 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$commandname Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'AvailabilityGroup', 'IsPrimary', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Get-DbaAvailabilityGroup" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaAvailabilityGroup + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "AvailabilityGroup", + "IsPrimary", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe "Get-DbaAvailabilityGroup" -Tag "IntegrationTests" { BeforeAll { - $agname = "dbatoolsci_agroup" - $null = New-DbaAvailabilityGroup -Primary $TestConfig.instance3 -Name $agname -ClusterType None -FailoverMode Manual -Confirm:$false -Certificate dbatoolsci_AGCert + $primaryAgName = "dbatoolsci_agroup" + $splatPrimary = @{ + Primary = $TestConfig.instance3 + Name = $primaryAgName + ClusterType = "None" + FailoverMode = "Manual" + Certificate = "dbatoolsci_AGCert" + Confirm = $false + } + $null = New-DbaAvailabilityGroup @splatPrimary } + AfterAll { - Remove-DbaAvailabilityGroup -SqlInstance $TestConfig.instance3 -AvailabilityGroup $agname -Confirm:$false + $splatRemove = @{ + SqlInstance = $TestConfig.instance3 + AvailabilityGroup = $primaryAgName + Confirm = $false + } + Remove-DbaAvailabilityGroup @splatRemove } - Context "gets ags" { - It "returns results with proper data" { + + Context "When getting availability groups" { + BeforeAll { $results = Get-DbaAvailabilityGroup -SqlInstance $TestConfig.instance3 - $results.AvailabilityGroup | Should -Contain $agname } - It "returns a single result" { - $results = Get-DbaAvailabilityGroup -SqlInstance $TestConfig.instance3 -AvailabilityGroup $agname - $results.AvailabilityGroup | Should -Be $agname + It "Returns results with proper data" { + $results.AvailabilityGroup | Should -Contain $primaryAgName + } + + It "Returns a single result when filtering by AG name" { + $filtered = Get-DbaAvailabilityGroup -SqlInstance $TestConfig.instance3 -AvailabilityGroup $primaryAgName + $filtered.AvailabilityGroup | Should -Be $primaryAgName } } } #$TestConfig.instance2 for appveyor diff --git a/tests/Get-DbaAvailableCollation.Tests.ps1 b/tests/Get-DbaAvailableCollation.Tests.ps1 index 908ecc0f10..3fe2c828b8 100644 --- a/tests/Get-DbaAvailableCollation.Tests.ps1 +++ b/tests/Get-DbaAvailableCollation.Tests.ps1 @@ -1,23 +1,42 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Get-DbaAvailableCollation" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaAvailableCollation + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { - Context "Available Collations" { - $results = Get-DbaAvailableCollation -SqlInstance $TestConfig.instance2 - It "finds a collation that matches Slovenian" { - ($results.Name -match 'Slovenian').Count -gt 10 | Should Be $true +Describe "Get-DbaAvailableCollation" -Tag "IntegrationTests" { + Context "When getting available collations" { + BeforeAll { + $results = Get-DbaAvailableCollation -SqlInstance $TestConfig.Instance2 + } + + It "Finds multiple Slovenian collations" { + ($results.Name -match 'Slovenian').Count | Should -BeGreaterThan 10 } } } diff --git a/tests/Get-DbaBackupDevice.Tests.ps1 b/tests/Get-DbaBackupDevice.Tests.ps1 index bb169b6d26..e96cb69b98 100644 --- a/tests/Get-DbaBackupDevice.Tests.ps1 +++ b/tests/Get-DbaBackupDevice.Tests.ps1 @@ -1,43 +1,64 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Get-DbaBackupDevice" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaBackupDevice + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe "Get-DbaBackupDevice" -Tag "IntegrationTests" { BeforeAll { - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 + $server = Connect-DbaInstance -SqlInstance $TestConfig.Instance2 $sql = "EXEC sp_addumpdevice 'tape', 'dbatoolsci_tape', '\\.\tape0';" $server.Query($sql) } - Afterall { - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 + + AfterAll { + $server = Connect-DbaInstance -SqlInstance $TestConfig.Instance2 $sql = "EXEC sp_dropdevice 'dbatoolsci_tape';" $server.Query($sql) } - Context "Gets the backup devices" { - $results = Get-DbaBackupDevice -SqlInstance $TestConfig.instance2 - It "Results are not empty" { - $results | Should Not Be $Null + Context "When getting backup devices" { + BeforeAll { + $results = Get-DbaBackupDevice -SqlInstance $TestConfig.Instance2 + } + + It "Returns results" { + $results | Should -Not -BeNullOrEmpty } + It "Should have the name dbatoolsci_tape" { - $results.name | Should Be "dbatoolsci_tape" + $results.Name | Should -Be "dbatoolsci_tape" } + It "Should have a BackupDeviceType of Tape" { - $results.BackupDeviceType | Should Be "Tape" + $results.BackupDeviceType | Should -Be "Tape" } + It "Should have a PhysicalLocation of \\.\Tape0" { - $results.PhysicalLocation | Should Be "\\.\Tape0" + $results.PhysicalLocation | Should -Be "\\.\Tape0" } } } diff --git a/tests/Get-DbaBinaryFileTable.Tests.ps1 b/tests/Get-DbaBinaryFileTable.Tests.ps1 index f350d7a7c4..b1071edf97 100644 --- a/tests/Get-DbaBinaryFileTable.Tests.ps1 +++ b/tests/Get-DbaBinaryFileTable.Tests.ps1 @@ -1,40 +1,65 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'Table', 'Schema', 'EnableException', 'InputObject' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 + +Describe "Get-DbaBinaryFileTable" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaBinaryFileTable + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Database", + "Table", + "Schema", + "InputObject", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasParams = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasParams | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe "Get-DbaBinaryFileTable" -Tag "IntegrationTests" { BeforeAll { - $db = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database tempdb - $null = $db.Query("CREATE TABLE [dbo].[BunchOFilez]([FileName123] [nvarchar](50) NULL, [TheFile123] [image] NULL)") + $database = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database tempdb + $null = $database.Query("CREATE TABLE [dbo].[BunchOFilez]([FileName123] [nvarchar](50) NULL, [TheFile123] [image] NULL)") + + # Import test files $null = Import-DbaBinaryFile -SqlInstance $TestConfig.instance2 -Database tempdb -Table BunchOFilez -FilePath "$($TestConfig.appveyorlabrepo)\azure\adalsql.msi" $null = Get-ChildItem "$($TestConfig.appveyorlabrepo)\certificates" | Import-DbaBinaryFile -SqlInstance $TestConfig.instance2 -Database tempdb -Table BunchOFilez } + AfterAll { try { - $null = $db.Query("DROP TABLE dbo.BunchOFilez") + $null = $database.Query("DROP TABLE dbo.BunchOFilez") } catch { $null = 1 } } - It "returns a table" { - $results = Get-DbaBinaryFileTable -SqlInstance $TestConfig.instance2 -Database tempdb - $results.Name.Count | Should -BeGreaterOrEqual 1 - } + Context "When getting binary file tables" { + It "Returns at least one table" { + $results = Get-DbaBinaryFileTable -SqlInstance $TestConfig.instance2 -Database tempdb + $results.Name.Count | Should -BeGreaterOrEqual 1 + } - It "supports piping" { - $results = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database tempdb | Get-DbaBinaryFileTable - $results.Name.Count | Should -BeGreaterOrEqual 1 + It "Supports piping database tables" { + $results = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database tempdb | Get-DbaBinaryFileTable + $results.Name.Count | Should -BeGreaterOrEqual 1 + } } } diff --git a/tests/Get-DbaClientAlias.Tests.ps1 b/tests/Get-DbaClientAlias.Tests.ps1 index 551ef15906..1efa7b89b6 100644 --- a/tests/Get-DbaClientAlias.Tests.ps1 +++ b/tests/Get-DbaClientAlias.Tests.ps1 @@ -1,30 +1,50 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'ComputerName', 'Credential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + +Describe "Get-DbaClientAlias" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaClientAlias + $expected = $TestConfig.CommonParameters + $expected += @( + "ComputerName", + "Credential", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe "Get-DbaClientAlias" -Tag "IntegrationTests" { BeforeAll { $newalias = New-DbaClientAlias -ServerName sql2016 -Alias dbatoolscialias -Verbose:$false } + AfterAll { $newalias | Remove-DbaClientAlias } - Context "gets the alias" { - $results = Get-DbaClientAlias - It "returns accurate information" { - $results.AliasName -contains 'dbatoolscialias' | Should Be $true + Context "When getting client aliases" { + BeforeAll { + $results = Get-DbaClientAlias + } + + It "Returns the expected alias" { + $results.AliasName | Should -Contain 'dbatoolscialias' } } } \ No newline at end of file diff --git a/tests/Get-DbaClientProtocol.Tests.ps1 b/tests/Get-DbaClientProtocol.Tests.ps1 index 967f4fbe6f..e6e8faace2 100644 --- a/tests/Get-DbaClientProtocol.Tests.ps1 +++ b/tests/Get-DbaClientProtocol.Tests.ps1 @@ -1,24 +1,47 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'ComputerName', 'Credential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Get-DbaClientProtocol" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaClientProtocol + $expected = $TestConfig.CommonParameters + $expected += @( + "ComputerName", + "Credential", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { - Context "Get some client protocols" { - $results = Get-DbaClientProtocol - It "Should return some protocols" { - $results.Count | Should BeGreaterThan 1 - $results | Where-Object { $_.ProtocolDisplayName -eq 'TCP/IP' } | Should Not Be $null +Describe "Get-DbaClientProtocol" -Tag "IntegrationTests" { + Context "When getting client protocols" { + BeforeAll { + $results = Get-DbaClientProtocol + } + + It "Returns multiple protocols" { + $results.Count | Should -BeGreaterThan 1 + } + + It "Includes TCP/IP protocol" { + $tcpip = $results | Where-Object { $PSItem.ProtocolDisplayName -eq 'TCP/IP' } + $tcpip | Should -Not -BeNullOrEmpty } } } \ No newline at end of file diff --git a/tests/Get-DbaCmConnection.Tests.ps1 b/tests/Get-DbaCmConnection.Tests.ps1 index 5d0b25740d..c038633bf1 100644 --- a/tests/Get-DbaCmConnection.Tests.ps1 +++ b/tests/Get-DbaCmConnection.Tests.ps1 @@ -1,35 +1,58 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'ComputerName', 'UserName', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Get-DbaCmConnection" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaCmConnection + $expected = $TestConfig.CommonParameters + $expected += @( + "ComputerName", + "UserName", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { +Describe "Get-DbaCmConnection" -Tag "IntegrationTests" { BeforeAll { New-DbaCmConnection -ComputerName $env:COMPUTERNAME } + AfterAll { - Remove-DbaCmConnection -ComputerName $env:COMPUTERNAME -Confirm:$False + Remove-DbaCmConnection -ComputerName $env:COMPUTERNAME -Confirm:$false } - Context "Returns DbaCmConnection" { - $Results = Get-DbaCMConnection -ComputerName $env:COMPUTERNAME - It "Results are not Empty" { - $Results | should not be $null + + Context "When getting connection for computer name" { + BeforeAll { + $results = Get-DbaCMConnection -ComputerName $env:COMPUTERNAME + } + + It "Returns results" { + $results | Should -Not -BeNullOrEmpty } } - Context "Returns DbaCmConnection for User" { - $Results = Get-DbaCMConnection -ComputerName $env:COMPUTERNAME -UserName * - It "Results are not Empty" { - $Results | should not be $null + + Context "When getting connection for username" { + BeforeAll { + $results = Get-DbaCMConnection -ComputerName $env:COMPUTERNAME -UserName * + } + + It "Returns results" { + $results | Should -Not -BeNullOrEmpty } } } \ No newline at end of file diff --git a/tests/Get-DbaCmObject.Tests.ps1 b/tests/Get-DbaCmObject.Tests.ps1 index 23bbd04a63..7b9b31baf1 100644 --- a/tests/Get-DbaCmObject.Tests.ps1 +++ b/tests/Get-DbaCmObject.Tests.ps1 @@ -1,22 +1,48 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'ClassName', 'Query', 'ComputerName', 'Credential', 'Namespace', 'DoNotUse', 'Force', 'SilentlyContinue', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Get-DbaCmObject" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaCmObject + $expected = $TestConfig.CommonParameters + $expected += @( + "ClassName", + "Query", + "ComputerName", + "Credential", + "Namespace", + "DoNotUse", + "Force", + "SilentlyContinue", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { - Context "returns proper information" { - It "returns a bias that's an int" { - (Get-DbaCmObject -ClassName Win32_TimeZone).Bias -is [int] +Describe "Get-DbaCmObject" -Tag "IntegrationTests" { + Context "When querying Win32_TimeZone" { + BeforeAll { + $results = Get-DbaCmObject -ClassName Win32_TimeZone + } + + It "Returns a Bias property that is an integer" { + $results.Bias | Should -BeOfType [int] } } } \ No newline at end of file diff --git a/tests/Get-DbaComputerCertificate.Tests.ps1 b/tests/Get-DbaComputerCertificate.Tests.ps1 index 94918a9910..ba93f976a5 100644 --- a/tests/Get-DbaComputerCertificate.Tests.ps1 +++ b/tests/Get-DbaComputerCertificate.Tests.ps1 @@ -1,41 +1,65 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'ComputerName', 'Credential', 'Store', 'Folder', 'Path', 'Thumbprint', 'EnableException', 'Type' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Get-DbaComputerCertificate" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaComputerCertificate + $expected = $TestConfig.CommonParameters + $expected += @( + "ComputerName", + "Credential", + "Store", + "Folder", + "Type", + "Path", + "Thumbprint", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { - Context "Can get a certificate" { +Describe "Get-DbaComputerCertificate" -Tag "IntegrationTests" { + Context "When getting a specific certificate" { BeforeAll { - $null = Add-DbaComputerCertificate -Path "$($TestConfig.appveyorlabrepo)\certificates\localhost.crt" -Confirm:$false $thumbprint = "29C469578D6C6211076A09CEE5C5797EEA0C2713" + $null = Add-DbaComputerCertificate -Path "$($TestConfig.appveyorlabrepo)\certificates\localhost.crt" -Confirm:$false + $cert = Get-DbaComputerCertificate -Thumbprint $thumbprint } + AfterAll { Remove-DbaComputerCertificate -Thumbprint $thumbprint -Confirm:$false } - $cert = Get-DbaComputerCertificate -Thumbprint $thumbprint - - It "returns a single certificate with a specific thumbprint" { - $cert.Thumbprint | Should Be $thumbprint + It "Returns a single certificate with the specified thumbprint" { + $cert.Thumbprint | Should -Be $thumbprint } + } - $cert = Get-DbaComputerCertificate + Context "When getting all certificates" { + BeforeAll { + $allCerts = Get-DbaComputerCertificate + } - It "returns all certificates and at least one has the specified thumbprint" { - "$($cert.Thumbprint)" -match $thumbprint | Should Be $true + It "Returns all certificates including one with the specified thumbprint" { + "$($allCerts.Thumbprint)" | Should -Match "29C469578D6C6211076A09CEE5C5797EEA0C2713" } - It "returns all certificates and at least one has the specified EnhancedKeyUsageList" { - "$($cert.EnhancedKeyUsageList)" -match '1\.3\.6\.1\.5\.5\.7\.3\.1' | Should Be $true + + It "Returns certificates with the expected enhanced key usage" { + "$($allCerts.EnhancedKeyUsageList)" | Should -Match '1\.3\.6\.1\.5\.5\.7\.3\.1' } } } diff --git a/tests/Get-DbaComputerSystem.Tests.ps1 b/tests/Get-DbaComputerSystem.Tests.ps1 index 082c04ff63..b6d51d4faf 100644 --- a/tests/Get-DbaComputerSystem.Tests.ps1 +++ b/tests/Get-DbaComputerSystem.Tests.ps1 @@ -1,35 +1,69 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "Get-DbaComputerSystem Unit Tests" -Tag "UnitTests" { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'ComputerName', 'Credential', 'IncludeAws', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + +Describe "Get-DbaComputerSystem" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaComputerSystem + $expected = $TestConfig.CommonParameters + $expected += @( + "ComputerName", + "Credential", + "IncludeAws", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } - Context "Validate input" { - it "Cannot resolve hostname of computer" { - mock Resolve-DbaNetworkName {$null} - {Get-DbaComputerSystem -ComputerName 'DoesNotExist142' -WarningAction Stop 3> $null} | Should Throw + + Context "Input validation" { + BeforeAll { + Mock -CommandName Resolve-DbaNetworkName -MockWith { $null } + } + + It "Throws when hostname cannot be resolved" { + { Get-DbaComputerSystem -ComputerName 'DoesNotExist142' -WarningAction Stop 3> $null } | + Should -Throw } } } -Describe "Get-DbaComputerSystem Integration Test" -Tag "IntegrationTests" { - $result = Get-DbaComputerSystem -ComputerName $TestConfig.instance1 - - $props = 'ComputerName', 'Domain', 'IsDaylightSavingsTime', 'Manufacturer', 'Model', 'NumberLogicalProcessors' - , 'NumberProcessors', 'IsHyperThreading', 'SystemFamily', 'SystemSkuNumber', 'SystemType', 'IsSystemManagedPageFile', 'TotalPhysicalMemory' - - Context "Validate output" { - foreach ($prop in $props) { - $p = $result.PSObject.Properties[$prop] - it "Should return property: $prop" { - $p.Name | Should Be $prop - } + +Describe "Get-DbaComputerSystem" -Tag "IntegrationTests" { + BeforeAll { + $result = Get-DbaComputerSystem -ComputerName $TestConfig.Instance1 + $expectedProps = @( + 'ComputerName', + 'Domain', + 'IsDaylightSavingsTime', + 'Manufacturer', + 'Model', + 'NumberLogicalProcessors', + 'NumberProcessors', + 'IsHyperThreading', + 'SystemFamily', + 'SystemSkuNumber', + 'SystemType', + 'IsSystemManagedPageFile', + 'TotalPhysicalMemory' + ) + } + + Context "When getting computer system information" { + It "Returns property: <_>" -ForEach $expectedProps { + $result.PSObject.Properties[$PSItem].Name | Should -Be $PSItem } } } diff --git a/tests/Get-DbaConnectedInstance.Tests.ps1 b/tests/Get-DbaConnectedInstance.Tests.ps1 index 4246ba145f..cf148499c6 100644 --- a/tests/Get-DbaConnectedInstance.Tests.ps1 +++ b/tests/Get-DbaConnectedInstance.Tests.ps1 @@ -1,23 +1,38 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag "UnitTests" { - Context "Validate parameters" { - # fake tests, no parameters to validate - It "Should only contain our specific parameters" { - $null | Should -BeNullOrEmpty +Describe "Get-DbaConnectedInstance" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaConnectedInstance + $expected = $TestConfig.CommonParameters + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe "Get-DbaConnectedInstance" -Tag "IntegrationTests" { BeforeAll { - $null = Get-DbaDatabase -SqlInstance $TestConfig.instance1 + $null = Get-DbaDatabase -SqlInstance $TestConfig.Instance1 } - Context "gets connected objects" { - It "returns some results" { + + Context "When getting connected instances" { + BeforeAll { $results = Get-DbaConnectedInstance + } + + It "Returns results" { $results | Should -Not -BeNullOrEmpty } } diff --git a/tests/Get-DbaConnection.Tests.ps1 b/tests/Get-DbaConnection.Tests.ps1 index ea0d9044e8..ae45f8e702 100644 --- a/tests/Get-DbaConnection.Tests.ps1 +++ b/tests/Get-DbaConnection.Tests.ps1 @@ -1,24 +1,43 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Get-DbaConnection" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaConnection + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name | Where-Object { $PSItem -notin "WhatIf", "Confirm" } + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { - Context "returns the proper transport" { - $results = Get-DbaConnection -SqlInstance $TestConfig.instance1 - foreach ($result in $results) { - It "returns an scheme" { - $result.AuthScheme -eq 'ntlm' -or $result.AuthScheme -eq 'Kerberos' | Should -Be $true +Describe "Get-DbaConnection" -Tag "IntegrationTests" { + Context "When connecting to SQL Server" { + BeforeAll { + $results = Get-DbaConnection -SqlInstance $TestConfig.instance1 + } + + It "Returns results with valid authentication scheme" { + foreach ($result in $results) { + $result.AuthScheme | Should -BeIn @('ntlm', 'Kerberos') } } } diff --git a/tests/Get-DbaCpuRingBuffer.Tests.ps1 b/tests/Get-DbaCpuRingBuffer.Tests.ps1 index 420b985963..f52f94fd91 100644 --- a/tests/Get-DbaCpuRingBuffer.Tests.ps1 +++ b/tests/Get-DbaCpuRingBuffer.Tests.ps1 @@ -1,24 +1,43 @@ -$commandname = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tags "UnitTests" { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'CollectionMinutes', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Get-DbaCpuRingBuffer" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaCpuRingBuffer + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "CollectionMinutes", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe "Get-DbaCpuRingBuffer" -Tag "IntegrationTests" { Context "Command returns proper info" { - $results = Get-DbaCpuRingBuffer -SqlInstance $TestConfig.instance2 -CollectionMinutes 100 + BeforeAll { + $results = Get-DbaCpuRingBuffer -SqlInstance $TestConfig.Instance2 -CollectionMinutes 100 + } - It "returns results" { - $results.Count -gt 0 | Should Be $true + It "Returns results" { + $results | Should -Not -BeNullOrEmpty } } } diff --git a/tests/Get-DbaCpuUsage.Tests.ps1 b/tests/Get-DbaCpuUsage.Tests.ps1 index c723f5f90d..d34a42aa88 100644 --- a/tests/Get-DbaCpuUsage.Tests.ps1 +++ b/tests/Get-DbaCpuUsage.Tests.ps1 @@ -1,23 +1,44 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Credential', 'Threshold', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Get-DbaCpuUsage" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaCpuUsage + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Credential", + "Threshold", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - Context "Gets the CPU Usage" { - $results = Get-DbaCPUUsage -SqlInstance $TestConfig.instance2 - It "Results are not empty" { - $results | Should Not Be $Null +Describe "Get-DbaCpuUsage" -Tag "IntegrationTests" { + Context "When getting CPU usage from SQL Server" { + BeforeAll { + $results = Get-DbaCPUUsage -SqlInstance $TestConfig.Instance2 + } + + It "Returns results" { + $results | Should -Not -BeNullOrEmpty } } } diff --git a/tests/Get-DbaCredential.Tests.ps1 b/tests/Get-DbaCredential.Tests.ps1 index cf59ec3fbd..1475181284 100644 --- a/tests/Get-DbaCredential.Tests.ps1 +++ b/tests/Get-DbaCredential.Tests.ps1 @@ -1,59 +1,109 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig . "$PSScriptRoot\..\private\functions\Invoke-Command2.ps1" +Describe "Get-DbaCredential" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaCredential + $knownParameters = @( + 'SqlInstance', + 'SqlCredential', + 'Credential', + 'ExcludeCredential', + 'Identity', + 'ExcludeIdentity', + 'EnableException' + ) + $expected = $TestConfig.CommonParameters + $knownParameters + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Credential', 'ExcludeCredential', 'Identity', 'ExcludeIdentity', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { +Describe "Get-DbaCredential" -Tag "IntegrationTests" { BeforeAll { - $logins = "dbatoolsci_thor", "dbatoolsci_thorsmomma" + $logins = @( + "dbatoolsci_thor", + "dbatoolsci_thorsmomma" + ) $plaintext = "BigOlPassword!" $password = ConvertTo-SecureString $plaintext -AsPlainText -Force # Add user foreach ($login in $logins) { - $null = Invoke-Command2 -ScriptBlock { net user $args[0] $args[1] /add *>&1 } -ArgumentList $login, $plaintext -ComputerName $TestConfig.instance2 + $null = Invoke-Command2 -ScriptBlock { + net user $args[0] $args[1] /add *>&1 + } -ArgumentList $login, $plaintext -ComputerName $TestConfig.instance2 } - $results = New-DbaCredential -SqlInstance $TestConfig.instance2 -Name dbatoolsci_thorcred -Identity dbatoolsci_thor -Password $password - $results = New-DbaCredential -SqlInstance $TestConfig.instance2 -Identity dbatoolsci_thorsmomma -Password $password + $null = New-DbaCredential -SqlInstance $TestConfig.instance2 -Name dbatoolsci_thorcred -Identity dbatoolsci_thor -Password $password + $null = New-DbaCredential -SqlInstance $TestConfig.instance2 -Identity dbatoolsci_thorsmomma -Password $password } + AfterAll { try { (Get-DbaCredential -SqlInstance $TestConfig.instance2 -Identity dbatoolsci_thor, dbatoolsci_thorsmomma -ErrorAction Stop -WarningAction SilentlyContinue).Drop() } catch { } foreach ($login in $logins) { - $null = Invoke-Command2 -ScriptBlock { net user $args /delete *>&1 } -ArgumentList $login -ComputerName $TestConfig.instance2 - $null = Invoke-Command2 -ScriptBlock { net user $args /delete *>&1 } -ArgumentList $login -ComputerName $TestConfig.instance2 + $null = Invoke-Command2 -ScriptBlock { + net user $args /delete *>&1 + } -ArgumentList $login -ComputerName $TestConfig.instance2 + $null = Invoke-Command2 -ScriptBlock { + net user $args /delete *>&1 + } -ArgumentList $login -ComputerName $TestConfig.instance2 } } - Context "Get credentials" { - It "Should get just one credential with the proper properties when using Identity" { + Context "When getting credentials by Identity" { + BeforeAll { $results = Get-DbaCredential -SqlInstance $TestConfig.instance2 -Identity dbatoolsci_thorsmomma - $results.Name | Should Be "dbatoolsci_thorsmomma" - $results.Identity | Should Be "dbatoolsci_thorsmomma" } - It "Should get just one credential with the proper properties when using Name" { + + It "Should return credential with correct name" { + $results.Name | Should -Be "dbatoolsci_thorsmomma" + } + + It "Should return credential with correct identity" { + $results.Identity | Should -Be "dbatoolsci_thorsmomma" + } + } + + Context "When getting credentials by Name" { + BeforeAll { $results = Get-DbaCredential -SqlInstance $TestConfig.instance2 -Name dbatoolsci_thorsmomma - $results.Name | Should Be "dbatoolsci_thorsmomma" - $results.Identity | Should Be "dbatoolsci_thorsmomma" } - It "gets more than one credential" { + + It "Should return credential with correct name" { + $results.Name | Should -Be "dbatoolsci_thorsmomma" + } + + It "Should return credential with correct identity" { + $results.Identity | Should -Be "dbatoolsci_thorsmomma" + } + } + + Context "When getting multiple credentials" { + BeforeAll { $results = Get-DbaCredential -SqlInstance $TestConfig.instance2 -Identity dbatoolsci_thor, dbatoolsci_thorsmomma - $results.count -gt 1 + } + + It "Should return multiple credentials" { + $results.Count | Should -BeGreaterThan 1 } } } diff --git a/tests/Get-DbaCustomError.Tests.ps1 b/tests/Get-DbaCustomError.Tests.ps1 index 1c0f84a25a..8761e87011 100644 --- a/tests/Get-DbaCustomError.Tests.ps1 +++ b/tests/Get-DbaCustomError.Tests.ps1 @@ -1,43 +1,66 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + +Describe "Get-DbaCustomError" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaCustomError + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe "Get-DbaCustomError" -Tag "IntegrationTests" { BeforeAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance1 $sql = "EXEC msdb.dbo.sp_addmessage 54321, 9, N'Dbatools is Awesome!';" $server.Query($sql) } - Afterall { + + AfterAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance1 $sql = "EXEC msdb.dbo.sp_dropmessage 54321;" $server.Query($sql) } - Context "Gets the backup devices" { - $results = Get-DbaCustomError -SqlInstance $TestConfig.instance1 - It "Results are not empty" { - $results | Should Not Be $Null + Context "Gets the custom errors" { + BeforeAll { + $results = Get-DbaCustomError -SqlInstance $TestConfig.instance1 + } + + It "Returns results" { + $results | Should -Not -BeNullOrEmpty } - It "Should have the name Custom Error Text" { - $results.Text | Should Be "Dbatools is Awesome!" + + It "Returns correct custom error text" { + $results.Text | Should -Be "Dbatools is Awesome!" } - It "Should have a LanguageID" { - $results.LanguageID | Should Be 1033 + + It "Returns correct language ID" { + $results.LanguageID | Should -Be 1033 } - It "Should have a Custom Error ID" { - $results.ID | Should Be 54321 + + It "Returns correct custom error ID" { + $results.ID | Should -Be 54321 } } } diff --git a/tests/Get-DbaDbAssembly.Tests.ps1 b/tests/Get-DbaDbAssembly.Tests.ps1 index 6da9050598..69c4787e80 100644 --- a/tests/Get-DbaDbAssembly.Tests.ps1 +++ b/tests/Get-DbaDbAssembly.Tests.ps1 @@ -1,32 +1,57 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'EnableException', 'Name', 'Database' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 + +Describe "Get-DbaDbAssembly" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaDbAssembly + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Database", + "Name", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name | Where-Object { $PSItem -notin "WhatIf", "Confirm" } + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - Context "Gets the Db Assembly" { - $results = Get-DbaDbAssembly -SqlInstance $TestConfig.instance2 | Where-Object { $_.parent.name -eq 'master' } - $masterDb = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database master - It "Gets results" { - $results | Should Not Be $Null +Describe "Get-DbaDbAssembly" -Tag "IntegrationTests" { + Context "When getting assemblies from master database" { + BeforeAll { + $instance = $TestConfig.instance2 + $masterDb = Get-DbaDatabase -SqlInstance $instance -Database master + $results = Get-DbaDbAssembly -SqlInstance $instance | Where-Object { $PSItem.parent.name -eq 'master' } + } + + It "Returns results" { + $results | Should -Not -BeNullOrEmpty $results.DatabaseId | Should -Be $masterDb.Id } + It "Should have a name of Microsoft.SqlServer.Types" { - $results.name | Should Be "Microsoft.SqlServer.Types" + $results.name | Should -Be "Microsoft.SqlServer.Types" } + It "Should have an owner of sys" { - $results.owner | Should Be "sys" + $results.owner | Should -Be "sys" } + It "Should have a version matching the instance" { $results.Version | Should -Be $masterDb.assemblies.Version } diff --git a/tests/Get-DbaDbAsymmetricKey.Tests.ps1 b/tests/Get-DbaDbAsymmetricKey.Tests.ps1 index 0b90c4b4f3..99c11d1881 100644 --- a/tests/Get-DbaDbAsymmetricKey.Tests.ps1 +++ b/tests/Get-DbaDbAsymmetricKey.Tests.ps1 @@ -1,57 +1,81 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Name', 'Database', 'InputObject', 'EnableException', 'ExcludeDatabase' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Get-DbaDbAsymmetricKey" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaDbAsymmetricKey + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "Name", + "InputObject", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { - Context "Gets a certificate" { - $keyname = 'test4' - $keyname2 = 'test5' - $algorithm = 'Rsa4096' - $dbuser = 'keyowner' - $database = 'GetAsKey' - $newDB = New-DbaDatabase -SqlInstance $TestConfig.instance2 -Name $database - $tPassword = ConvertTo-SecureString "ThisIsThePassword1" -AsPlainText -Force - New-DbaDbMasterKey -SqlInstance $TestConfig.instance2 -Database $database -SecurePassword $tPassword -confirm:$false - New-DbaDbUser -SqlInstance $TestConfig.instance2 -Database $database -UserName $dbuser - $null = New-DbaDbAsymmetricKey -SqlInstance $TestConfig.instance2 -Database $database -Name $keyname -Owner keyowner -Algorithm $algorithm -WarningVariable warnvar - $results = Get-DbaDbAsymmetricKey -SqlInstance $TestConfig.instance2 -Name $keyname -Database $database +Describe "Get-DbaDbAsymmetricKey" -Tag "IntegrationTests" { + Context "Gets an asymmetric key" { + BeforeAll { + $keyname = 'test4' + $keyname2 = 'test5' + $algorithm = 'Rsa4096' + $dbuser = 'keyowner' + $database = 'GetAsKey' + + $newDB = New-DbaDatabase -SqlInstance $TestConfig.instance2 -Name $database + $tPassword = ConvertTo-SecureString "ThisIsThePassword1" -AsPlainText -Force + New-DbaDbMasterKey -SqlInstance $TestConfig.instance2 -Database $database -SecurePassword $tPassword -confirm:$false + New-DbaDbUser -SqlInstance $TestConfig.instance2 -Database $database -UserName $dbuser + $null = New-DbaDbAsymmetricKey -SqlInstance $TestConfig.instance2 -Database $database -Name $keyname -Owner keyowner -Algorithm $algorithm -WarningVariable warnvar + $results = Get-DbaDbAsymmetricKey -SqlInstance $TestConfig.instance2 -Name $keyname -Database $database + } + It "Should Create new key in $database called $keyname" { $warnvar | Should -BeNullOrEmpty - $results.database | Should -Be $database - $results.DatabaseId | Should -Be $newDB.ID - $results.name | Should -Be $keyname - $results.Owner | Should -Be $dbuser + $results.database | Should -BeExactly $database + $results.DatabaseId | Should -BeExactly $newDB.ID + $results.name | Should -BeExactly $keyname + $results.Owner | Should -BeExactly $dbuser $results | Should -HaveCount 1 } - $pipeResults = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $database | Get-DbaDbAsymmetricKey + It "Should work with a piped database" { - $pipeResults.database | Should -Be $database - $pipeResults.name | Should -Be $keyname - $pipeResults.Owner | Should -Be $dbuser + $pipeResults = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $database | Get-DbaDbAsymmetricKey + $pipeResults.database | Should -BeExactly $database + $pipeResults.name | Should -BeExactly $keyname + $pipeResults.Owner | Should -BeExactly $dbuser $pipeResults | Should -HaveCount 1 } - $null = New-DbaDbAsymmetricKey -SqlInstance $TestConfig.instance2 -Database $database -Name $keyname2 -Owner keyowner -Algorithm $algorithm -WarningVariable warnvar - $multiResults = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $database | Get-DbaDbAsymmetricKey - It "Should return 2 keys" { + It "Should return 2 keys when multiple keys exist" { + $null = New-DbaDbAsymmetricKey -SqlInstance $TestConfig.instance2 -Database $database -Name $keyname2 -Owner keyowner -Algorithm $algorithm -WarningVariable warnvar + $multiResults = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $database | Get-DbaDbAsymmetricKey $multiResults | Should -HaveCount 2 - $multiresults.name | Should -Contain $keyname - $multiresults.name | Should -Contain $keyname2 + $multiResults.name | Should -Contain $keyname + $multiResults.name | Should -Contain $keyname2 } - $drop = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $database -confirm:$false - It "Should drop database" { - $drop.Status | Should -Be 'Dropped' + + AfterAll { + $drop = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $database -confirm:$false + $drop.Status | Should -BeExactly 'Dropped' } } } diff --git a/tests/Get-DbaDbCertificate.Tests.ps1 b/tests/Get-DbaDbCertificate.Tests.ps1 index e6b9ad3634..3d8376daff 100644 --- a/tests/Get-DbaDbCertificate.Tests.ps1 +++ b/tests/Get-DbaDbCertificate.Tests.ps1 @@ -1,54 +1,76 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'Certificate', 'Subject', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Get-DbaDbCertificate" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaDbCertificate + $knownParameters = @( + 'SqlInstance' + 'SqlCredential' + 'Database' + 'ExcludeDatabase' + 'Certificate' + 'Subject' + 'InputObject' + 'EnableException' + ) + $expected = $TestConfig.CommonParameters + $knownParameters + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe "Get-DbaDbCertificate" -Tag "IntegrationTests" { Context "Can get a database certificate" { BeforeAll { + $masterKey = $null + $tempdbMasterKey = $null + if (-not (Get-DbaDbMasterKey -SqlInstance $TestConfig.instance1 -Database master)) { - $masterkey = New-DbaDbMasterKey -SqlInstance $TestConfig.instance1 -Database master -Password $(ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force) -Confirm:$false + $masterKey = New-DbaDbMasterKey -SqlInstance $TestConfig.instance1 -Database master -Password $(ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force) -Confirm:$false } - $tempdbmasterkey = New-DbaDbMasterKey -SqlInstance $TestConfig.instance1 -Database tempdb -Password $(ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force) -Confirm:$false + $tempdbMasterKey = New-DbaDbMasterKey -SqlInstance $TestConfig.instance1 -Database tempdb -Password $(ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force) -Confirm:$false $certificateName1 = "Cert_$(Get-Random)" $certificateName2 = "Cert_$(Get-Random)" $cert1 = New-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Name $certificateName1 -Confirm:$false $cert2 = New-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Name $certificateName2 -Database "tempdb" -Confirm:$false } + AfterAll { $null = $cert1 | Remove-DbaDbCertificate -Confirm:$false $null = $cert2 | Remove-DbaDbCertificate -Confirm:$false - if ($tempdbmasterkey) { $tempdbmasterkey | Remove-DbaDbMasterKey -Confirm:$false } - if ($masterKey) { $masterkey | Remove-DbaDbMasterKey -Confirm:$false } + if ($tempdbMasterKey) { $tempdbMasterKey | Remove-DbaDbMasterKey -Confirm:$false } + if ($masterKey) { $masterKey | Remove-DbaDbMasterKey -Confirm:$false } } - $cert = Get-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Certificate $certificateName1 - It "returns database certificate created in default, master database" { - "$($cert.Database)" -match 'master' | Should Be $true + It "Returns database certificate created in default, master database" { + $cert = Get-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Certificate $certificateName1 + $cert.Database | Should -Match 'master' $cert.DatabaseId | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master).Id } - $cert = Get-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Database tempdb - It "returns database certificate created in tempdb database, looked up by certificate name" { - "$($cert.Name)" -match $certificateName2 | Should Be $true + It "Returns database certificate created in tempdb database, looked up by certificate name" { + $cert = Get-DbaDbCertificate -SqlInstance $TestConfig.instance1 -Database tempdb + $cert.Name | Should -Match $certificateName2 $cert.DatabaseId | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database tempdb).Id } - $cert = Get-DbaDbCertificate -SqlInstance $TestConfig.instance1 -ExcludeDatabase master - It "returns database certificates excluding those in the master database" { - "$($cert.Database)" -notmatch 'master' | Should Be $true + It "Returns database certificates excluding those in the master database" { + $cert = Get-DbaDbCertificate -SqlInstance $TestConfig.instance1 -ExcludeDatabase master + $cert.Database | Should -Not -Match 'master' } - } } diff --git a/tests/Get-DbaDbCheckConstraint.Tests.ps1 b/tests/Get-DbaDbCheckConstraint.Tests.ps1 index e3ee27d70e..a0b5d42887 100644 --- a/tests/Get-DbaDbCheckConstraint.Tests.ps1 +++ b/tests/Get-DbaDbCheckConstraint.Tests.ps1 @@ -1,19 +1,39 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} + +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'ExcludeSystemTable', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 + +Describe "Get-DbaDbCheckConstraint" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaDbCheckConstraint + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "ExcludeSystemTable", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { +Describe "Get-DbaDbCheckConstraint" -Tag "IntegrationTests" { BeforeAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $random = Get-Random @@ -34,20 +54,23 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { Context "Command actually works" { It "returns no check constraints from excluded DB with -ExcludeDatabase" { $results = Get-DbaDbCheckConstraint -SqlInstance $TestConfig.instance2 -ExcludeDatabase master - $results.where( { $_.Database -eq 'master' }).count | Should Be 0 + $results.where( { $PSItem.Database -eq 'master' }).Count | Should -Be 0 } + It "returns only check constraints from selected DB with -Database" { $results = Get-DbaDbCheckConstraint -SqlInstance $TestConfig.instance2 -Database $dbname - $results.where( { $_.Database -ne 'master' }).count | Should Be 1 + $results.where( { $PSItem.Database -ne 'master' }).Count | Should -Be 1 $results.DatabaseId | Get-Unique | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname).Id } + It "Should include test check constraint: $ckName" { $results = Get-DbaDbCheckConstraint -SqlInstance $TestConfig.instance2 -Database $dbname -ExcludeSystemTable - ($results | Where-Object Name -eq $ckName).Name | Should Be $ckName + ($results | Where-Object Name -eq $ckName).Name | Should -Be $ckName } + It "Should exclude system tables" { $results = Get-DbaDbCheckConstraint -SqlInstance $TestConfig.instance2 -Database master -ExcludeSystemTable - ($results | Where-Object Name -eq 'spt_fallback_db') | Should Be $null + ($results | Where-Object Name -eq 'spt_fallback_db') | Should -BeNullOrEmpty } } } diff --git a/tests/Get-DbaDbCompatibility.Tests.ps1 b/tests/Get-DbaDbCompatibility.Tests.ps1 index b8520b8692..9f592920b3 100644 --- a/tests/Get-DbaDbCompatibility.Tests.ps1 +++ b/tests/Get-DbaDbCompatibility.Tests.ps1 @@ -1,46 +1,69 @@ -$commandname = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'InputObject', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Get-DbaDbCompatibility" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaDbCompatibility + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Database", + "InputObject", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe "Get-DbaDbCompatibility" -Tag "IntegrationTests" { BeforeAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance1 - $compatibilityLevel = $server.Databases['master'].CompatibilityLevel + $masterCompatLevel = $server.Databases['master'].CompatibilityLevel } - Context "Gets compatibility for multiple databases" { - $results = Get-DbaDbCompatibility -SqlInstance $TestConfig.instance1 - It "Gets results" { - $results | Should Not Be $null - } - Foreach ($row in $results) { - It "Should return correct compatibility level for $($row.database)" { - # Only test system databases as there might be leftover databases from other tests - if ($row.DatabaseId -le 4) { - $row.Compatibility | Should Be $compatibilityLevel - } - $row.DatabaseId | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $row.Database).Id + + Context "When getting compatibility for multiple databases" { + BeforeAll { + $results = Get-DbaDbCompatibility -SqlInstance $TestConfig.instance1 + } + + It "Returns results" { + $results | Should -Not -BeNullOrEmpty + } + + It "Returns correct compatibility level for database <_.Database>" -ForEach $results { + # Only test system databases as there might be leftover databases from other tests + if ($PSItem.DatabaseId -le 4) { + $PSItem.Compatibility | Should -Be $masterCompatLevel } + $PSItem.DatabaseId | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $PSItem.Database).Id } } - Context "Gets compatibility for one database" { - $results = Get-DbaDbCompatibility -SqlInstance $TestConfig.instance1 -database master - It "Gets results" { - $results | Should Not Be $null + Context "When getting compatibility for a single database" { + BeforeAll { + $results = Get-DbaDbCompatibility -SqlInstance $TestConfig.instance1 -Database master } - It "Should return correct compatibility level for $($results.database)" { - $results.Compatibility | Should Be $compatibilityLevel + + It "Returns results" { + $results | Should -Not -BeNullOrEmpty + } + + It "Returns correct compatibility level for master database" { + $results.Compatibility | Should -Be $masterCompatLevel $results.DatabaseId | Should -Be (Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database master).Id } } diff --git a/tests/Get-DbaDbCompression.Tests.ps1 b/tests/Get-DbaDbCompression.Tests.ps1 index e6eb3bb58c..3001ee481c 100644 --- a/tests/Get-DbaDbCompression.Tests.ps1 +++ b/tests/Get-DbaDbCompression.Tests.ps1 @@ -1,19 +1,36 @@ -$commandname = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'Table', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Get-DbaDbCompression" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaDbCompression + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "Table", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe "Get-DbaDbCompression" -Tag "IntegrationTests" { BeforeAll { $dbname = "dbatoolsci_test_$(Get-Random)" $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 @@ -23,38 +40,36 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { create clustered index CL_sysallparams on sysallparams (object_id) create nonclustered index NC_syscols on syscols (precision) include (collation_name)", $dbname) } + AfterAll { Get-DbaProcess -SqlInstance $TestConfig.instance2 -Database $dbname | Stop-DbaProcess -WarningAction SilentlyContinue Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname -Confirm:$false } - $results = Get-DbaDbCompression -SqlInstance $TestConfig.instance2 -Database $dbname - Context "Command handles heaps and clustered indexes" { - It "Gets results" { - $results | Should Not Be $null - $results.Database | Get-Unique | Should -Be $dbname - $results.DatabaseId | Get-Unique | Should -Be $server.Query("SELECT database_id FROM sys.databases WHERE name = '$dbname'").database_id + Context "When getting compression information" { + BeforeAll { + $results = Get-DbaDbCompression -SqlInstance $TestConfig.instance2 -Database $dbname } - Foreach ($row in $results | Where-Object { $_.IndexId -le 1 }) { - It "Should return compression level for object $($row.TableName)" { - $row.DataCompression | Should BeIn ('None', 'Row', 'Page') - } + + It "Returns results" { + $results | Should -Not -BeNullOrEmpty + $results.Database | Select-Object -Unique | Should -Be $dbname + $results.DatabaseId | Select-Object -Unique | Should -Be $server.Query("SELECT database_id FROM sys.databases WHERE name = '$dbname'").database_id } - } - Context "Command handles nonclustered indexes" { - It "Gets results" { - $results | Should Not Be $null + + It "Returns correct compression level for object " -ForEach @($results | Where-Object { $PSItem.IndexId -le 1 }) { + $PSItem.DataCompression | Should -BeIn @('None', 'Row', 'Page') } - Foreach ($row in $results | Where-Object { $_.IndexId -gt 1 }) { - It "Should return compression level for nonclustered index $($row.IndexName)" { - $row.DataCompression | Should BeIn ('None', 'Row', 'Page') - } + + It "Returns correct compression level for nonclustered index " -ForEach @($results | Where-Object { $PSItem.IndexId -gt 1 }) { + $PSItem.DataCompression | Should -BeIn @('None', 'Row', 'Page') } } - Context "Command excludes results for specified database" { - It "Shouldn't get any results for $dbname" { - $(Get-DbaDbCompression -SqlInstance $TestConfig.instance2 -Database $dbname -ExcludeDatabase $dbname) | Should not Match $dbname + Context "When excluding databases" { + It "Should not return results for excluded database" { + $excludedResults = Get-DbaDbCompression -SqlInstance $TestConfig.instance2 -Database $dbname -ExcludeDatabase $dbname + $excludedResults | Should -Not -Match $dbname } } } diff --git a/tests/Get-DbaDbDbccOpenTran.Tests.ps1 b/tests/Get-DbaDbDbccOpenTran.Tests.ps1 index 1f4fffeb4c..51a916eeda 100644 --- a/tests/Get-DbaDbDbccOpenTran.Tests.ps1 +++ b/tests/Get-DbaDbDbccOpenTran.Tests.ps1 @@ -1,44 +1,77 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Get-DbaDbDbccOpenTran" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaDbDbccOpenTran + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Database", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Test" -Tag "IntegrationTests" { - Context "Gets results for Open Transactions" { - $props = 'ComputerName', 'InstanceName', 'SqlInstance', 'Database', 'Cmd', 'Output', 'Field', 'Data' - $result = Get-DbaDbDbccOpenTran -SqlInstance $TestConfig.instance1 - It "returns results for DBCC OPENTRAN" { - $result | Should Not Be $null +Describe "Get-DbaDbDbccOpenTran" -Tag "IntegrationTests" { + Context "When getting open transactions" { + BeforeAll { + $results = Get-DbaDbDbccOpenTran -SqlInstance $TestConfig.instance1 + $expectedProps = @( + 'ComputerName', + 'InstanceName', + 'SqlInstance', + 'Database', + 'Cmd', + 'Output', + 'Field', + 'Data' + ) } - It "returns multiple results" { - $result.Count -gt 0 | Should Be $true + It "Returns results" { + $results | Should -Not -BeNullOrEmpty } - foreach ($prop in $props) { - $p = $result[0].PSObject.Properties[$prop] - It "Should return property: $prop" { - $p.Name | Should Be $prop - } + It "Returns multiple results" { + $results.Count | Should -BeGreaterThan 0 } - $result = Get-DbaDbDbccOpenTran -SqlInstance $TestConfig.instance1 -Database tempDB - $tempDB = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database tempDB + It "Has property: <_>" -ForEach $expectedProps { + $results[0].PSObject.Properties[$PSItem].Name | Should -Be $PSItem + } + } + + Context "When getting transactions for specific database" { + BeforeAll { + $tempDb = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database tempdb + $results = Get-DbaDbDbccOpenTran -SqlInstance $TestConfig.instance1 -Database tempdb + } + + It "Returns results for tempdb" { + $results | Should -Not -BeNullOrEmpty + } - It "returns results for a database" { - $result | Should Not Be $null - $result.Database | Get-Unique | Should -Be tempDB - $result.DatabaseId | Get-Unique | Should -Be $tempDB.Id + It "Returns results only for tempdb" { + $results.Database | Get-Unique | Should -Be 'tempdb' + $results.DatabaseId | Get-Unique | Should -Be $tempDb.Id } } } diff --git a/tests/Get-DbaDbDetachedFileInfo.Tests.ps1 b/tests/Get-DbaDbDetachedFileInfo.Tests.ps1 index e0fdbca14c..e685ad1d27 100644 --- a/tests/Get-DbaDbDetachedFileInfo.Tests.ps1 +++ b/tests/Get-DbaDbDetachedFileInfo.Tests.ps1 @@ -1,26 +1,41 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Path', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + +Describe "Get-DbaDbDetachedFileInfo" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaDbDetachedFileInfo + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Path", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe "Get-DbaDbDetachedFileInfo" -Tag "IntegrationTests" { BeforeAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $versionName = $server.GetSqlServerVersionName() $random = Get-Random $dbname = "dbatoolsci_detatch_$random" $server.Query("CREATE DATABASE $dbname") - $path = (Get-DbaDbFile -SqlInstance $TestConfig.instance2 -Database $dbname | Where-object {$_.PhysicalName -like '*.mdf'}).physicalname + $path = (Get-DbaDbFile -SqlInstance $TestConfig.instance2 -Database $dbname | Where-Object {$PSItem.PhysicalName -like '*.mdf'}).physicalname Detach-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname -Force } @@ -31,22 +46,29 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname -Confirm:$false } - Context "Command actually works" { - $results = Get-DbaDbDetachedFileInfo -SqlInstance $TestConfig.instance2 -Path $path - it "Gets Results" { - $results | Should Not Be $null + Context "When getting detached file information" { + BeforeAll { + $results = Get-DbaDbDetachedFileInfo -SqlInstance $TestConfig.instance2 -Path $path } - It "Should be created database" { - $results.name | Should Be $dbname + + It "Returns results" { + $results | Should -Not -BeNullOrEmpty + } + + It "Returns the correct database name" { + $results.name | Should -Be $dbname } - It "Should be the correct version" { - $results.version | Should Be $versionName + + It "Returns the correct SQL Server version" { + $results.version | Should -Be $versionName } - It "Should have Data files" { - $results.DataFiles | Should Not Be $null + + It "Contains data files information" { + $results.DataFiles | Should -Not -BeNullOrEmpty } - It "Should have Log files" { - $results.LogFiles | Should Not Be $null + + It "Contains log files information" { + $results.LogFiles | Should -Not -BeNullOrEmpty } } } diff --git a/tests/Get-DbaDbccHelp.Tests.ps1 b/tests/Get-DbaDbccHelp.Tests.ps1 index dbb0f3bc2d..af2389b5f4 100644 --- a/tests/Get-DbaDbccHelp.Tests.ps1 +++ b/tests/Get-DbaDbccHelp.Tests.ps1 @@ -1,42 +1,60 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Statement', 'IncludeUndocumented', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + +Describe "Get-DbaDbccHelp" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaDbccHelp + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Statement", + "IncludeUndocumented", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Test" -Tag "IntegrationTests" { - $props = 'Operation', 'Cmd', 'Output' - $result = Get-DbaDbccHelp -SqlInstance $TestConfig.instance2 -Statement FREESYSTEMCACHE + +Describe "Get-DbaDbccHelp" -Tag "IntegrationTests" { + BeforeAll { + $props = 'Operation', 'Cmd', 'Output' + $result = Get-DbaDbccHelp -SqlInstance $TestConfig.instance2 -Statement FREESYSTEMCACHE + } Context "Validate standard output" { - foreach ($prop in $props) { - $p = $result.PSObject.Properties[$prop] - It "Should return property: $prop" { - $p.Name | Should Be $prop - } + It "Should return property: <_>" -ForEach $props { + $result.PSObject.Properties[$PSItem].Name | Should -Be $PSItem } } - Context "Works correctly" { - It "returns the right results for FREESYSTEMCACHE" { - $result.Operation | Should Be 'FREESYSTEMCACHE' - $result.Cmd | Should Be 'DBCC HELP(FREESYSTEMCACHE)' - $result.Output | Should Not Be $null + Context "When executing DBCC HELP commands" { + It "Returns the correct results for FREESYSTEMCACHE" { + $result.Operation | Should -Be 'FREESYSTEMCACHE' + $result.Cmd | Should -Be 'DBCC HELP(FREESYSTEMCACHE)' + $result.Output | Should -Not -BeNullOrEmpty } - It "returns the right results for PAGE" { - $result = Get-DbaDbccHelp -SqlInstance $TestConfig.instance2 -Statement PAGE -IncludeUndocumented - $result.Operation | Should Be 'PAGE' - $result.Cmd | Should Be 'DBCC HELP(PAGE)' - $result.Output | Should Not Be $null + It "Returns the correct results for PAGE with undocumented info" { + $pageResult = Get-DbaDbccHelp -SqlInstance $TestConfig.instance2 -Statement PAGE -IncludeUndocumented + $pageResult.Operation | Should -Be 'PAGE' + $pageResult.Cmd | Should -Be 'DBCC HELP(PAGE)' + $pageResult.Output | Should -Not -BeNullOrEmpty } } } diff --git a/tests/Get-DbaDbccMemoryStatus.Tests.ps1 b/tests/Get-DbaDbccMemoryStatus.Tests.ps1 index e93cd51152..873f1b6511 100644 --- a/tests/Get-DbaDbccMemoryStatus.Tests.ps1 +++ b/tests/Get-DbaDbccMemoryStatus.Tests.ps1 @@ -1,33 +1,59 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Get-DbaDbccMemoryStatus" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaDbccMemoryStatus + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Test" -Tag "IntegrationTests" { - $props = 'ComputerName', 'InstanceName', 'RecordSet', 'RowId', 'RecordSetId', 'Type', 'Name', 'Value', 'ValueType' - $result = Get-DbaDbccMemoryStatus -SqlInstance $TestConfig.instance2 + +Describe "Get-DbaDbccMemoryStatus" -Tag "IntegrationTests" { + BeforeAll { + $result = Get-DbaDbccMemoryStatus -SqlInstance $TestConfig.instance2 + $props = @( + 'ComputerName', + 'InstanceName', + 'RecordSet', + 'RowId', + 'RecordSetId', + 'Type', + 'Name', + 'Value', + 'ValueType' + ) + } Context "Validate standard output" { - foreach ($prop in $props) { - $p = $result[0].PSObject.Properties[$prop] - It "Should return property: $prop" { - $p.Name | Should Be $prop - } + It "Should return property: <_>" -ForEach $props { + $result[0].PSObject.Properties[$PSItem].Name | Should -Be $PSItem } } Context "Command returns proper info" { - It "returns results for DBCC MEMORYSTATUS" { - $result.Count -gt 0 | Should Be $true + It "Returns results for DBCC MEMORYSTATUS" { + $result.Count | Should -BeGreaterThan 0 } } } diff --git a/tests/Get-DbaDbccProcCache.Tests.ps1 b/tests/Get-DbaDbccProcCache.Tests.ps1 index 4a9a745ad0..d148f6b017 100644 --- a/tests/Get-DbaDbccProcCache.Tests.ps1 +++ b/tests/Get-DbaDbccProcCache.Tests.ps1 @@ -1,33 +1,59 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Get-DbaDbccProcCache" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaDbccProcCache + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Test" -Tag "IntegrationTests" { - $props = 'ComputerName', 'InstanceName', 'SqlInstance', 'Count', 'Used', 'Active', 'CacheSize', 'CacheUsed', 'CacheActive' - $result = Get-DbaDbccProcCache -SqlInstance $TestConfig.instance2 + +Describe "Get-DbaDbccProcCache" -Tag "IntegrationTests" { + BeforeAll { + $result = Get-DbaDbccProcCache -SqlInstance $TestConfig.instance2 + $props = @( + 'ComputerName', + 'InstanceName', + 'SqlInstance', + 'Count', + 'Used', + 'Active', + 'CacheSize', + 'CacheUsed', + 'CacheActive' + ) + } Context "Validate standard output" { - foreach ($prop in $props) { - $p = $result[0].PSObject.Properties[$prop] - It "Should return property: $prop" { - $p.Name | Should Be $prop - } + It "Should return property: <_>" -ForEach $props { + $result[0].PSObject.Properties[$PSItem].Name | Should -BeExactly $PSItem } } Context "Command returns proper info" { - It "returns results for DBCC PROCCACHE" { - $result | Should NOt Be $null + It "Returns results for DBCC PROCCACHE" { + $result | Should -Not -BeNullOrEmpty } } } diff --git a/tests/Get-DbaDbccSessionBuffer.Tests.ps1 b/tests/Get-DbaDbccSessionBuffer.Tests.ps1 index 4d2cdb0b9e..4655dbd8ea 100644 --- a/tests/Get-DbaDbccSessionBuffer.Tests.ps1 +++ b/tests/Get-DbaDbccSessionBuffer.Tests.ps1 @@ -1,69 +1,95 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Operation', 'SessionId', 'RequestId', 'All', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Get-DbaDbccSessionBuffer" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaDbccSessionBuffer + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Operation", + "SessionId", + "RequestId", + "All", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Test" -Tag "IntegrationTests" { + +Describe "Get-DbaDbccSessionBuffer" -Tag "IntegrationTests" { BeforeAll { $db = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database tempdb $queryResult = $db.Query('SELECT top 10 object_id, @@Spid as MySpid FROM sys.objects') } - AfterAll { - } - Context "Validate standard output for all databases " { - $props = 'ComputerName', 'InstanceName', 'SqlInstance', 'SessionId', 'EventType', 'Parameters', 'EventInfo' - $result = Get-DbaDbccSessionBuffer -SqlInstance $TestConfig.instance1 -Operation InputBuffer -All - - It "returns results" { - $result.Count -gt 0 | Should Be $true + Context "When getting session buffers for all databases" { + BeforeAll { + $inputProps = @( + 'ComputerName', + 'InstanceName', + 'SqlInstance', + 'SessionId', + 'EventType', + 'Parameters', + 'EventInfo' + ) + $outputProps = @( + 'ComputerName', + 'InstanceName', + 'SqlInstance', + 'SessionId', + 'Buffer', + 'HexBuffer' + ) + $resultInput = Get-DbaDbccSessionBuffer -SqlInstance $TestConfig.instance1 -Operation InputBuffer -All + $resultOutput = Get-DbaDbccSessionBuffer -SqlInstance $TestConfig.instance1 -Operation OutputBuffer -All } - foreach ($prop in $props) { - $p = $result[0].PSObject.Properties[$prop] - It "Should return property: $prop" { - $p.Name | Should Be $prop - } + It "Returns results for InputBuffer" { + $resultInput.Count | Should -BeGreaterThan 0 } - $props = 'ComputerName', 'InstanceName', 'SqlInstance', 'SessionId', 'Buffer', 'HexBuffer' - $result = Get-DbaDbccSessionBuffer -SqlInstance $TestConfig.instance1 -Operation OutputBuffer -All - - It "returns results" { - $result.Count -gt 0 | Should Be $true + It "Has property <_> for InputBuffer" -ForEach $inputProps { + $resultInput[0].PSObject.Properties[$PSItem].Name | Should -Be $PSItem } - foreach ($prop in $props) { - $p = $result[0].PSObject.Properties[$prop] - It "Should return property: $prop" { - $p.Name | Should Be $prop - } + It "Returns results for OutputBuffer" { + $resultOutput.Count | Should -BeGreaterThan 0 + } + It "Has property <_> for OutputBuffer" -ForEach $outputProps { + $resultOutput[0].PSObject.Properties[$PSItem].Name | Should -Be $PSItem } } - Context "Validate returns results for SessionId " { - $spid = $queryResult[0].MySpid - $result = Get-DbaDbccSessionBuffer -SqlInstance $TestConfig.instance1 -Operation InputBuffer -SessionId $spid - - It "returns results for InputBuffer" { - $result.SessionId -eq $spid | Should Be $true + Context "When getting session buffers for specific SessionId" { + BeforeAll { + $spid = $queryResult[0].MySpid + $resultInput = Get-DbaDbccSessionBuffer -SqlInstance $TestConfig.instance1 -Operation InputBuffer -SessionId $spid + $resultOutput = Get-DbaDbccSessionBuffer -SqlInstance $TestConfig.instance1 -Operation OutputBuffer -SessionId $spid } - $result = Get-DbaDbccSessionBuffer -SqlInstance $TestConfig.instance1 -Operation OutputBuffer -SessionId $spid + It "Returns correct SessionId for InputBuffer" { + $resultInput.SessionId | Should -Be $spid + } - It "returns results for OutputBuffer" { - $result.SessionId -eq $spid | Should Be $true + It "Returns correct SessionId for OutputBuffer" { + $resultOutput.SessionId | Should -Be $spid } } - } diff --git a/tests/Get-DbaDbccStatistic.Tests.ps1 b/tests/Get-DbaDbccStatistic.Tests.ps1 index fbae851e1d..f1b175ec10 100644 --- a/tests/Get-DbaDbccStatistic.Tests.ps1 +++ b/tests/Get-DbaDbccStatistic.Tests.ps1 @@ -1,18 +1,40 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'Object', 'Target', 'Option', 'NoInformationalMessages', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 +Describe "Get-DbaDbccStatistic" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaDbccStatistic + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Database", + "Object", + "Target", + "Option", + "NoInformationalMessages", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Test" -Tag "IntegrationTests" { + +Describe "Get-DbaDbccStatistic" -Tag "IntegrationTests" { BeforeAll { $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $random = Get-Random @@ -31,90 +53,101 @@ Describe "$commandname Integration Test" -Tag "IntegrationTests" { $null = $server.Query("CREATE STATISTICS [TestStat2] ON $tableName2([idTbl1], [idTbl2])", $dbname) $null = $server.Query("UPDATE STATISTICS $tableName", $dbname) } + AfterAll { $null = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname | Remove-DbaDatabase -Confirm:$false } - Context "Validate standard output for StatHeader option " { - $props = 'ComputerName', 'InstanceName', 'SqlInstance', 'Database', 'Object', 'Target', 'Cmd', 'Name', 'Updated', 'Rows', 'RowsSampled', 'Steps', 'Density', 'AverageKeyLength', 'StringIndex', 'FilterExpression', 'UnfilteredRows', 'PersistedSamplePercent' - $result = Get-DbaDbccStatistic -SqlInstance $TestConfig.instance2 -Database $dbname -Option StatHeader + Context "When validating StatHeader option output" { + BeforeAll { + $props = @( + 'ComputerName', 'InstanceName', 'SqlInstance', 'Database', 'Object', 'Target', 'Cmd', + 'Name', 'Updated', 'Rows', 'RowsSampled', 'Steps', 'Density', 'AverageKeyLength', + 'StringIndex', 'FilterExpression', 'UnfilteredRows', 'PersistedSamplePercent' + ) + $result = Get-DbaDbccStatistic -SqlInstance $TestConfig.instance2 -Database $dbname -Option StatHeader + } - It "returns correct results" { - $result.Count -eq 3 | Should Be $true + It "Returns correct number of results" { + $result.Count | Should -Be 3 } - foreach ($prop in $props) { - $p = $result[0].PSObject.Properties[$prop] - It "Should return property: $prop" { - $p.Name | Should Be $prop - } + It "Should return property: <_>" -ForEach $props { + $result[0].PSObject.Properties[$PSItem].Name | Should -Be $PSItem } } - Context "Validate standard output for DensityVector option " { - $props = 'ComputerName', 'InstanceName', 'SqlInstance', 'Database', 'Object', 'Target', 'Cmd', 'AllDensity', 'AverageLength', 'Columns' - $result = Get-DbaDbccStatistic -SqlInstance $TestConfig.instance2 -Database $dbname -Option DensityVector - - It "returns results" { - $result.Count -gt 0 | Should Be $true + Context "When validating DensityVector option output" { + BeforeAll { + $props = @( + 'ComputerName', 'InstanceName', 'SqlInstance', 'Database', 'Object', 'Target', 'Cmd', + 'AllDensity', 'AverageLength', 'Columns' + ) + $result = Get-DbaDbccStatistic -SqlInstance $TestConfig.instance2 -Database $dbname -Option DensityVector } - foreach ($prop in $props) { - $p = $result[0].PSObject.Properties[$prop] - It "Should return property: $prop" { - $p.Name | Should Be $prop - } + It "Returns results" { + $result.Count | Should -BeGreaterThan 0 + } + It "Should return property: <_>" -ForEach $props { + $result[0].PSObject.Properties[$PSItem].Name | Should -Be $PSItem } } - Context "Validate standard output for Histogram option " { - $props = 'ComputerName', 'InstanceName', 'SqlInstance', 'Database', 'Object', 'Target', 'Cmd', 'RangeHiKey', 'RangeRows', 'EqualRows', 'DistinctRangeRows', 'AverageRangeRows' - $result = Get-DbaDbccStatistic -SqlInstance $TestConfig.instance2 -Database $dbname -Option Histogram - - It "returns results" { - $result.Count -gt 0 | Should Be $true + Context "When validating Histogram option output" { + BeforeAll { + $props = @( + 'ComputerName', 'InstanceName', 'SqlInstance', 'Database', 'Object', 'Target', 'Cmd', + 'RangeHiKey', 'RangeRows', 'EqualRows', 'DistinctRangeRows', 'AverageRangeRows' + ) + $result = Get-DbaDbccStatistic -SqlInstance $TestConfig.instance2 -Database $dbname -Option Histogram } - foreach ($prop in $props) { - $p = $result[0].PSObject.Properties[$prop] - It "Should return property: $prop" { - $p.Name | Should Be $prop - } + It "Returns results" { + $result.Count | Should -BeGreaterThan 0 + } + It "Should return property: <_>" -ForEach $props { + $result[0].PSObject.Properties[$PSItem].Name | Should -Be $PSItem } } - Context "Validate standard output for StatsStream option " { - $props = 'ComputerName', 'InstanceName', 'SqlInstance', 'Database', 'Object', 'Target', 'Cmd', 'StatsStream', 'Rows', 'DataPages' - $result = Get-DbaDbccStatistic -SqlInstance $TestConfig.instance2 -Database $dbname -Option StatsStream - - It "returns results" { - $result.Count -gt 0 | Should Be $true + Context "When validating StatsStream option output" { + BeforeAll { + $props = @( + 'ComputerName', 'InstanceName', 'SqlInstance', 'Database', 'Object', 'Target', 'Cmd', + 'StatsStream', 'Rows', 'DataPages' + ) + $result = Get-DbaDbccStatistic -SqlInstance $TestConfig.instance2 -Database $dbname -Option StatsStream } - foreach ($prop in $props) { - $p = $result[0].PSObject.Properties[$prop] - It "Should return property: $prop" { - $p.Name | Should Be $prop - } + It "Returns results" { + $result.Count | Should -BeGreaterThan 0 + } + It "Should return property: <_>" -ForEach $props { + $result[0].PSObject.Properties[$PSItem].Name | Should -Be $PSItem } } - Context "Validate returns results for single Object " { - $result = Get-DbaDbccStatistic -SqlInstance $TestConfig.instance2 -Database $dbname -Object $tableName2 -Option StatsStream + Context "When querying a single Object" { + BeforeAll { + $result = Get-DbaDbccStatistic -SqlInstance $TestConfig.instance2 -Database $dbname -Object $tableName2 -Option StatsStream + } - It "returns results" { - $result.Count -gt 0 | Should Be $true + It "Returns results" { + $result.Count | Should -BeGreaterThan 0 } } - Context "Validate returns results for single Object and Target " { - $result = Get-DbaDbccStatistic -SqlInstance $TestConfig.instance2 -Database $dbname -Object $tableName2 -Target 'TestStat2' -Option DensityVector + Context "When querying a single Object and Target" { + BeforeAll { + $result = Get-DbaDbccStatistic -SqlInstance $TestConfig.instance2 -Database $dbname -Object $tableName2 -Target 'TestStat2' -Option DensityVector + } - It "returns results" { - $result.Count -gt 0 | Should Be $true + It "Returns results" { + $result.Count | Should -BeGreaterThan 0 } } } diff --git a/tests/Get-DbaDbccUserOption.Tests.ps1 b/tests/Get-DbaDbccUserOption.Tests.ps1 index a99ef5672f..93a75ff31a 100644 --- a/tests/Get-DbaDbccUserOption.Tests.ps1 +++ b/tests/Get-DbaDbccUserOption.Tests.ps1 @@ -1,43 +1,71 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0"} +param( + $ModuleName = "dbatools", + $PSDefaultParameterValues = ($TestConfig = Get-TestConfig).Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Option', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + +Describe "Get-DbaDbccUserOption" -Tag "UnitTests" { + BeforeAll { + $command = Get-Command Get-DbaDbccUserOption + $expected = $TestConfig.CommonParameters + $expected += @( + "SqlInstance", + "SqlCredential", + "Option", + "EnableException" + ) + } + + Context "Parameter validation" { + It "Has parameter: <_>" -ForEach $expected { + $command | Should -HaveParameter $PSItem + } + + It "Should have exactly the number of expected parameters ($($expected.Count))" { + $hasparms = $command.Parameters.Values.Name + Compare-Object -ReferenceObject $expected -DifferenceObject $hasparms | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Test" -Tag "IntegrationTests" { - $props = 'ComputerName', 'InstanceName', 'SqlInstance', 'Option', 'Value' - $result = Get-DbaDbccUserOption -SqlInstance $TestConfig.instance2 + +Describe "Get-DbaDbccUserOption" -Tag "IntegrationTests" { + BeforeAll { + $props = @( + 'ComputerName', + 'InstanceName', + 'SqlInstance', + 'Option', + 'Value' + ) + $result = Get-DbaDbccUserOption -SqlInstance $TestConfig.instance2 + } Context "Validate standard output" { - foreach ($prop in $props) { - $p = $result[0].PSObject.Properties[$prop] - It "Should return property: $prop" { - $p.Name | Should Be $prop - } + It "Should return property: <_>" -ForEach $props { + $p = $result[0].PSObject.Properties[$PSItem] + $p.Name | Should -BeExactly $PSItem } } Context "Command returns proper info" { It "returns results for DBCC USEROPTIONS" { - $result.Count -gt 0 | Should Be $true + $result.Count | Should -BeGreaterThan 0 } } Context "Accepts an Option Value" { - $result = Get-DbaDbccUserOption -SqlInstance $TestConfig.instance2 -Option ansi_nulls + BeforeAll { + $result = Get-DbaDbccUserOption -SqlInstance $TestConfig.instance2 -Option ansi_nulls + } + It "Gets results" { - $result | Should Not Be $null + $result | Should -Not -BeNullOrEmpty } + It "Returns only one result" { - $result.Option -eq 'ansi_nulls' | Should Be $true + $result.Option | Should -BeExactly 'ansi_nulls' } } }