diff --git a/.aitools/module/Repair-PullRequestTest.ps1 b/.aitools/module/Repair-PullRequestTest.ps1 index 9b796a51768..9cdb2ea316b 100644 --- a/.aitools/module/Repair-PullRequestTest.ps1 +++ b/.aitools/module/Repair-PullRequestTest.ps1 @@ -26,6 +26,10 @@ function Repair-PullRequestTest { from the development branch to the current branch, without running Update-PesterTest or committing any changes. + .PARAMETER Pattern + Pattern to filter test files. Only files matching this pattern will be processed. + Supports wildcards (e.g., "*Login*" to match files containing "Login"). + .NOTES Tags: Testing, Pester, PullRequest, CI Author: dbatools team @@ -53,7 +57,8 @@ function Repair-PullRequestTest { [switch]$AutoCommit, [int]$MaxPRs = 5, [int]$BuildNumber, - [switch]$CopyOnly + [switch]$CopyOnly, + [string]$Pattern ) begin { @@ -269,7 +274,14 @@ function Repair-PullRequestTest { $fileErrorPath = @() $testdirectory = Join-Path $script:ModulePath "tests" - foreach ($test in $allFailedTestsAcrossPRs) { + # Apply Pattern filter first if specified + $filteredTests = if ($Pattern) { + $allFailedTestsAcrossPRs | Where-Object { [System.IO.Path]::GetFileName($_.TestFile) -match $Pattern } + } else { + $allFailedTestsAcrossPRs + } + + foreach ($test in $filteredTests) { $fileName = [System.IO.Path]::GetFileName($test.TestFile) # ONLY include files that are actually in the PR changes if ($allRelevantTestFiles.Count -eq 0 -or $fileName -in $allRelevantTestFiles) { @@ -284,7 +296,11 @@ function Repair-PullRequestTest { } } $fileErrorPath = $fileErrorPath | Sort-Object -Unique - Write-Verbose "Found failures in $($fileErrorMap.Keys.Count) unique test files (filtered to PR changes only)" + $filterMessage = "filtered to PR changes only" + if ($Pattern) { + $filterMessage += " and pattern '$Pattern'" + } + Write-Verbose "Found failures in $($fileErrorMap.Keys.Count) unique test files ($filterMessage)" foreach ($fileName in $fileErrorMap.Keys) { Write-Verbose " ${fileName} - $($fileErrorMap[$fileName].Count) failures" Write-Verbose " Paths: $fileErrorPath" diff --git a/tests/Export-DbaXESessionTemplate.Tests.ps1 b/tests/Export-DbaXESessionTemplate.Tests.ps1 index 1dca24d5541..91530c8bcc5 100644 --- a/tests/Export-DbaXESessionTemplate.Tests.ps1 +++ b/tests/Export-DbaXESessionTemplate.Tests.ps1 @@ -1,31 +1,79 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Export-DbaXESessionTemplate", + $PSDefaultParameterValues = $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', '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 $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Session", + "Path", + "FilePath", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $null = Get-DbaXESession -SqlInstance $TestConfig.instance2 -Session 'Profiler TSQL Duration' | Remove-DbaXESession + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # For all the backups that we want to clean up after the test, we create a directory that we can delete at the end. + # Other files can be written there as well, maybe we change the name of that variable later. But for now we focus on backups. + $tempPath = "$($TestConfig.Temp)\$CommandName-$(Get-Random)" + $null = New-Item -Path $tempPath -ItemType Directory + + # Explain what needs to be set up for the test: + # We need to ensure that any existing 'Profiler TSQL Duration' session is removed before we start + + # Set variables. They are available in all the It blocks. + $sessionName = "Profiler TSQL Duration" + + # Clean up any existing session + $null = Get-DbaXESession -SqlInstance $TestConfig.instance2 -Session $sessionName | Remove-DbaXESession + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + 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 + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup all created objects. + $null = Get-DbaXESession -SqlInstance $TestConfig.instance2 -Session $sessionName | Remove-DbaXESession + + # Remove the temporary directory and any exported files. + Remove-Item -Path $tempPath -Recurse -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } + Context "Test Importing Session Template" { - $session = Import-DbaXESessionTemplate -SqlInstance $TestConfig.instance2 -Template 'Profiler TSQL Duration' - $results = $session | Export-DbaXESessionTemplate -Path C:\windows\temp + BeforeAll { + $session = Import-DbaXESessionTemplate -SqlInstance $TestConfig.instance2 -Template "Profiler TSQL Duration" + $results = $session | Export-DbaXESessionTemplate -Path $tempPath + } + It "session exports to disk" { - $results.Name | Should Be 'Profiler TSQL Duration.xml' + $results.Name | Should -Be "$sessionName.xml" } } -} +} \ No newline at end of file diff --git a/tests/Find-DbaBackup.Tests.ps1 b/tests/Find-DbaBackup.Tests.ps1 index 2521874a9f5..4b8f8f4887d 100644 --- a/tests/Find-DbaBackup.Tests.ps1 +++ b/tests/Find-DbaBackup.Tests.ps1 @@ -1,131 +1,208 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Find-DbaBackup", + $PSDefaultParameterValues = $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 = '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 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "Path", + "BackupFileExtension", + "RetentionPeriod", + "CheckArchiveBit", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { - $testPath = "TestDrive:\sqlbackups" - if (!(Test-Path $testPath)) { - New-Item -Path $testPath -ItemType Container +Describe $CommandName -Tag IntegrationTests { + BeforeAll { + $testPath = "TestDrive:\sqlbackups" + if (!(Test-Path $testPath)) { + $null = New-Item -Path $testPath -ItemType Container + } } + Context "Path validation" { - { Find-DbaBackup -Path 'funnypath' -BackupFileExtension 'bak' -RetentionPeriod '0d' -EnableException } | Should Throw "not found" + It "Should throw when path is not found" { + { 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" + BeforeAll { + $testPath = "TestDrive:\sqlbackups" + } + + It "Should throw when retention period format is invalid" { + { Find-DbaBackup -Path $testPath -BackupFileExtension "bak" -RetentionPeriod "ad" -EnableException } | Should -Throw "*format invalid*" + } + + It "Should throw 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 + BeforeAll { + $testPath = "TestDrive:\sqlbackups" + } + + It "Should not throw when extension includes period" { + { 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*' + BeforeAll { + $testPath = "TestDrive:\sqlbackups" + } + + It "Should warn about period in extension" { + $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 { + $testPath = "TestDrive:\sqlbackups" + if (!(Test-Path $testPath)) { + $null = New-Item -Path $testPath -ItemType Container + } + + 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) + } } + It "Should find all files with retention 0d" { - $results = Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod '0d' - $results.Length | Should Be 20 + $results = @(Find-DbaBackup -Path $testPath -BackupFileExtension "bak" -RetentionPeriod "0d") + $results.Count | Should -BeExactly 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 = @(Find-DbaBackup -Path $testPath -BackupFileExtension "bak" -RetentionPeriod "11h") + $results.Count | Should -BeExactly 15 + ($results | Where-Object FullName -Like "*hours*").Count | Should -BeExactly 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 = @(Find-DbaBackup -Path $testPath -BackupFileExtension "bak" -RetentionPeriod "6d") + $results.Count | Should -BeExactly 10 + ($results | Where-Object FullName -Like "*hours*").Count | Should -BeExactly 0 + ($results | Where-Object FullName -Like "*days*").Count | Should -BeExactly 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 = @(Find-DbaBackup -Path $testPath -BackupFileExtension "bak" -RetentionPeriod "6w") + $results.Count | Should -BeExactly 5 + ($results | Where-Object FullName -Like "*hours*").Count | Should -BeExactly 0 + ($results | Where-Object FullName -Like "*days*").Count | Should -BeExactly 0 + ($results | Where-Object FullName -Like "*weeks*").Count | Should -BeExactly 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 = @(Find-DbaBackup -Path $testPath -BackupFileExtension "bak" -RetentionPeriod "6m") + $results.Count | Should -BeExactly 0 + ($results | Where-Object FullName -Like "*hours*").Count | Should -BeExactly 0 + ($results | Where-Object FullName -Like "*days*").Count | Should -BeExactly 0 + ($results | Where-Object FullName -Like "*weeks*").Count | Should -BeExactly 0 + ($results | Where-Object FullName -Like "*weeks*").Count | Should -BeExactly 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 { + $testPath = "TestDrive:\sqlbackups" + if (!(Test-Path $testPath)) { + $null = New-Item -Path $testPath -ItemType Container + } + + 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" + } } + It "Should find all files with retention 0d" { - $results = Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod '0d' - $results.Length | Should Be 10 + $results = @(Find-DbaBackup -Path $testPath -BackupFileExtension "bak" -RetentionPeriod "0d") + $results.Count | Should -BeExactly 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 = @(Find-DbaBackup -Path $testPath -BackupFileExtension "bak" -RetentionPeriod "0d" -CheckArchiveBit) + $results.Count | Should -BeExactly 5 + ($results | Where-Object FullName -Like "*_notarchive*").Count | Should -BeExactly 5 + ($results | Where-Object FullName -Like "*_archive*").Count | Should -BeExactly 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 { + $testPath = "TestDrive:\sqlbackups" + if (!(Test-Path $testPath)) { + $null = New-Item -Path $testPath -ItemType Container + } + + 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) + } } + It "Should find 5 files with extension trn" { - $results = Find-DbaBackup -Path $testPath -BackupFileExtension 'trn' -RetentionPeriod '0d' - $results.Length | Should Be 5 + $results = @(Find-DbaBackup -Path $testPath -BackupFileExtension "trn" -RetentionPeriod "0d") + $results.Count | Should -BeExactly 5 } + It "Should find 5 files with extension bak" { - $results = Find-DbaBackup -Path $testPath -BackupFileExtension 'bak' -RetentionPeriod '0d' - $results.Length | Should Be 5 + $results = @(Find-DbaBackup -Path $testPath -BackupFileExtension "bak" -RetentionPeriod "0d") + $results.Count | Should -BeExactly 5 } } } \ No newline at end of file diff --git a/tests/Find-DbaCommand.Tests.ps1 b/tests/Find-DbaCommand.Tests.ps1 index 6ed8fb02dca..aad70037dd1 100644 --- a/tests/Find-DbaCommand.Tests.ps1 +++ b/tests/Find-DbaCommand.Tests.ps1 @@ -1,43 +1,70 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Find-DbaCommand", + $PSDefaultParameterValues = $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 = '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 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "Pattern", + "Tag", + "Author", + "MinimumVersion", + "MaximumVersion", + "Rebuild", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Command finds jobs using all parameters" { - $results = Find-DbaCommand -Pattern "snapshot" + BeforeAll { + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') + } + 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" + $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 + $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 + $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 43ee07bca44..d574fa4393b 100644 --- a/tests/Find-DbaDatabase.Tests.ps1 +++ b/tests/Find-DbaDatabase.Tests.ps1 @@ -1,48 +1,92 @@ +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Find-DbaDatabase", + $PSDefaultParameterValues = $TestConfig.Defaults +) + <# The below statement stays in for every test you build. #> -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") 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 $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Property", + "Pattern", + "Exact", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { + +Describe $CommandName -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 { + $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" + ) + ($results[0].PsObject.Properties.Name | Sort-Object) | Should -Be ($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 -Be $true $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]) -eq 126942668163900000 | Should -Be $true + } + } + + Context "Multiple instances" { + BeforeAll { + $results = Find-DbaDatabase -SqlInstance $TestConfig.instance1, $TestConfig.instance2 -Pattern Master } - $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 + ($results.InstanceName | Select-Object -Unique).Count -eq 2 | Should -Be $true + } + } + + Context "Property filtering" { + BeforeAll { + $results = Find-DbaDatabase -SqlInstance $TestConfig.instance2 -Property ServiceBrokerGuid -Pattern -0000-0000-000000000000 } - $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' + $results.ServiceBrokerGuid | Should -BeLike "*-0000-0000-000000000000" } } -} +} \ No newline at end of file diff --git a/tests/Find-DbaDbDisabledIndex.Tests.ps1 b/tests/Find-DbaDbDisabledIndex.Tests.ps1 index 056e32e02b8..148739d4bd8 100644 --- a/tests/Find-DbaDbDisabledIndex.Tests.ps1 +++ b/tests/Find-DbaDbDisabledIndex.Tests.ps1 @@ -1,21 +1,41 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Find-DbaDbDisabledIndex", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { +Describe $CommandName -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 + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "NoClobber", + "Append", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Command actually works" { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance1 $random = Get-Random $databaseName1 = "dbatoolsci1_$random" @@ -29,23 +49,34 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { ALTER INDEX $indexName ON $tableName DISABLE;" $null = $db1.Query($sql) $null = $db2.Query($sql) + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $db1, $db2 | Remove-DbaDatabase -Confirm:$false + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } It "Should find disabled index: $indexName" { $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 IndexName -eq $indexName).Count | Should -BeExactly 2 + ($results | Where-Object DatabaseName -in $databaseName1, $databaseName2).Count | Should -BeExactly 2 + ($results | Where-Object DatabaseId -in $db1.Id, $db2.Id).Count | Should -BeExactly 2 } + It "Should find disabled index: $indexName 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 @@ -53,4 +84,4 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $results.DatabaseId | Should -Be $db2.Id } } -} +} \ No newline at end of file diff --git a/tests/Find-DbaDbDuplicateIndex.Tests.ps1 b/tests/Find-DbaDbDuplicateIndex.Tests.ps1 index 65b58562c58..b819266aed3 100644 --- a/tests/Find-DbaDbDuplicateIndex.Tests.ps1 +++ b/tests/Find-DbaDbDuplicateIndex.Tests.ps1 @@ -1,24 +1,44 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Find-DbaDbDuplicateIndex", + $PSDefaultParameterValues = $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 $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "IncludeOverlapping", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Set up test database and table with duplicate indexes + $dbName = "dbatools_dupeindex" $server = Connect-DbaInstance -SqlInstance $TestConfig.instance1 - $sql = "create database [dbatools_dupeindex]" + $sql = "create database [$dbName]" $server.Query($sql) - $sql = "CREATE TABLE [dbatools_dupeindex].[dbo].[WABehaviorEvent]( + $sql = "CREATE TABLE [$dbName].[dbo].[WABehaviorEvent]( [BehaviorEventId] [smallint] NOT NULL, [ClickType] [nvarchar](50) NOT NULL, [Description] [nvarchar](512) NOT NULL, @@ -34,26 +54,48 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { ) ON [PRIMARY] - CREATE UNIQUE NONCLUSTERED INDEX [IX_WABehaviorEvent_ClickType] ON [dbatools_dupeindex].[dbo].[WABehaviorEvent] + CREATE UNIQUE NONCLUSTERED INDEX [IX_WABehaviorEvent_ClickType] ON [$dbName].[dbo].[WABehaviorEvent] ( [ClickType] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] - ALTER TABLE [dbatools_dupeindex].[dbo].[WABehaviorEvent] ADD UNIQUE NONCLUSTERED + ALTER TABLE [$dbName].[dbo].[WABehaviorEvent] ADD UNIQUE NONCLUSTERED ( [ClickType] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] " $server.Query($sql) + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { - Remove-DbaDatabase -SqlInstance $TestConfig.instance1 -Database dbatools_dupeindex -Confirm:$false + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup test database + $splatRemove = @{ + SqlInstance = $TestConfig.instance1 + Database = "dbatools_dupeindex" + Confirm = $false + } + Remove-DbaDatabase @splatRemove -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Gets back some results" { - $results = Find-DbaDbDuplicateIndex -SqlInstance $TestConfig.instance1 -Database dbatools_dupeindex + BeforeAll { + $splatFind = @{ + SqlInstance = $TestConfig.instance1 + Database = "dbatools_dupeindex" + } + $results = @(Find-DbaDbDuplicateIndex @splatFind) + } + It "return at least two results" { - $results.Count -ge 2 | Should Be $true + $results.Status.Count | Should -BeGreaterOrEqual 2 } } -} +} \ No newline at end of file diff --git a/tests/Find-DbaDbGrowthEvent.Tests.ps1 b/tests/Find-DbaDbGrowthEvent.Tests.ps1 index c888c252f9e..38b44d00187 100644 --- a/tests/Find-DbaDbGrowthEvent.Tests.ps1 +++ b/tests/Find-DbaDbGrowthEvent.Tests.ps1 @@ -1,53 +1,79 @@ -$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", + $CommandName = "Find-DbaDbGrowthEvent", + $PSDefaultParameterValues = $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', '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 $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "EventType", + "FileType", + "UseLocalTime", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Command actually works" { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $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); + $sqlGrowthAndShrink = @" +CREATE TABLE Tab1 (ID INTEGER); - INSERT INTO Tab1 (ID) - SELECT - 1 - FROM - sys.all_objects a - CROSS JOIN - sys.all_objects b; +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); - " +TRUNCATE TABLE Tab1; +DBCC SHRINKFILE ($databaseName1, TRUNCATEONLY); +DBCC SHRINKFILE ($($databaseName1)_Log, TRUNCATEONLY); +"@ $null = $db1.Query($sqlGrowthAndShrink) + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { - $db1 | Remove-DbaDatabase -Confirm:$false + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + $db1 | Remove-DbaDatabase -Confirm:$false -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } 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 + @($results | Where-Object EventClass -in 92, 93).Count | Should -BeGreaterThan 0 + $results.DatabaseName | Select-Object -Unique | Should -Be $databaseName1 + $results.DatabaseId | Select-Object -Unique | Should -Be $db1.ID } <# Leaving this commented out since the background process for auto shrink cannot be triggered @@ -56,9 +82,9 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $results = Find-DbaDbGrowthEvent -SqlInstance $server -Database $databaseName1 -EventType Shrink $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 + $results.DatabaseName | Select-Object -Unique | Should -Be $databaseName1 + $results.DatabaseId | Select-Object -Unique | Should -Be $db1.ID } #> } -} +} \ No newline at end of file diff --git a/tests/Find-DbaDbUnusedIndex.Tests.ps1 b/tests/Find-DbaDbUnusedIndex.Tests.ps1 index a89748b594d..9ae18431093 100644 --- a/tests/Find-DbaDbUnusedIndex.Tests.ps1 +++ b/tests/Find-DbaDbUnusedIndex.Tests.ps1 @@ -1,26 +1,45 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Find-DbaDbUnusedIndex", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -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 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "IgnoreUptime", + "Seeks", + "Scans", + "Lookups", + "InputObject", + "EnableException" + ) + } - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should -Be 0 + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | 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. +# +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 "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Verify basics of the Find-DbaDbUnusedIndex command" { BeforeAll { Test-DbaConnection -SqlInstance $TestConfig.instance2 @@ -67,7 +86,38 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { 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' + $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 @@ -85,7 +135,7 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { } if ($null -ne $row) { - [object[]]$columnNamesReturned = @($row | Get-Member -MemberType Property | Select-Object -Property Name | ForEach-Object { $_.Name }) + $columnNamesReturned = @($row | Get-Member -MemberType Property | Select-Object -Property Name | ForEach-Object { $PSItem.Name }) if ( @(Compare-Object -ReferenceObject $expectedColumnArray -DifferenceObject $columnNamesReturned).Count -eq 0 ) { $testSQLinstance = $true @@ -96,4 +146,4 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $testSQLinstance | Should -Be $true } } -} +} \ No newline at end of file diff --git a/tests/Find-DbaInstance.Tests.ps1 b/tests/Find-DbaInstance.Tests.ps1 index 869a8392f20..ed776b58a25 100644 --- a/tests/Find-DbaInstance.Tests.ps1 +++ b/tests/Find-DbaInstance.Tests.ps1 @@ -1,44 +1,57 @@ +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } param( - [string[]] - $TestServer + $ModuleName = "dbatools", + $CommandName = "Find-DbaInstance", # Static command name for dbatools + $PSDefaultParameterValues = $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" { +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { 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 + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "ComputerName", + "DiscoveryType", + "Credential", + "SqlCredential", + "ScanType", + "IpAddress", + "DomainController", + "TCPPort", + "MinimumConfidence", + "EnableException" + ) } - It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Command finds 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]" { $results | Should -BeOfType [Dataplat.Dbatools.Discovery.DbaInstanceReport] } + It "FullName is populated" { $results.FullName | Should -Not -BeNullOrEmpty } + if (([DbaInstanceParameter]$TestConfig.instance3).IsLocalHost -eq $false) { It "TcpConnected is true" { $results.TcpConnected | Should -Be $true } } + It "successfully connects" { $results.SqlConnected | Should -Be $true } } -} - +} \ No newline at end of file diff --git a/tests/Find-DbaLoginInGroup.Tests.ps1 b/tests/Find-DbaLoginInGroup.Tests.ps1 index a29fdef91f5..38b7a1c1124 100644 --- a/tests/Find-DbaLoginInGroup.Tests.ps1 +++ b/tests/Find-DbaLoginInGroup.Tests.ps1 @@ -1,19 +1,33 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Find-DbaLoginInGroup", + $PSDefaultParameterValues = $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 $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Login", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | 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 +# +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/Find-DbaOrphanedFile.Tests.ps1 b/tests/Find-DbaOrphanedFile.Tests.ps1 index 0f1fee7d794..0232212af1c 100644 --- a/tests/Find-DbaOrphanedFile.Tests.ps1 +++ b/tests/Find-DbaOrphanedFile.Tests.ps1 @@ -1,21 +1,39 @@ -$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", + $CommandName = "Find-DbaOrphanedFile", + $PSDefaultParameterValues = $TestConfig.Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { +Describe $CommandName -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 + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Path", + "FileType", + "LocalOnly", + "RemoteOnly", + "Recurse", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Orphaned files are correctly identified" { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $dbname = "dbatoolsci_orphanedfile_$(Get-Random)" $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $db1 = New-DbaDatabase -SqlInstance $server -Name $dbname @@ -25,28 +43,25 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $tmpdir = "c:\temp\orphan_$(Get-Random)" if (-not(Test-Path $tmpdir)) { - $null = New-Item -Path $tmpdir -type Container + $null = New-Item -Path $tmpdir -ItemType Directory } $tmpdirInner = Join-Path $tmpdir "inner" - $null = New-Item -Path $tmpdirInner -type Container + $null = New-Item -Path $tmpdirInner -ItemType Directory $tmpBackupPath = Join-Path $tmpdirInner "backup" - $null = New-Item -Path $tmpBackupPath -type Container + $null = New-Item -Path $tmpBackupPath -ItemType Directory $tmpdir2 = "c:\temp\orphan_$(Get-Random)" if (-not(Test-Path $tmpdir2)) { - $null = New-Item -Path $tmpdir2 -type Container + $null = New-Item -Path $tmpdir2 -ItemType Directory } $tmpdirInner2 = Join-Path $tmpdir2 "inner" - $null = New-Item -Path $tmpdirInner2 -type Container + $null = New-Item -Path $tmpdirInner2 -ItemType Directory $tmpBackupPath2 = Join-Path $tmpdirInner2 "backup" - $null = New-Item -Path $tmpBackupPath2 -type Container + $null = New-Item -Path $tmpBackupPath2 -ItemType Directory $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" + if ($result.Count -eq 0) { + throw "Setup failed: database not created" } $backupFile = Backup-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname -Path $tmpBackupPath -Type Full @@ -54,21 +69,28 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { 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 + $null = New-Item -Path $tmpBackupPath3 -ItemType Directory + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true 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 + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } It "Has the correct properties" { - $null = Detach-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname -Force + $null = Dismount-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $dbname -Force $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 - $ExpectedStdProps = 'ComputerName,InstanceName,SqlInstance,Filename,RemoteFilename'.Split(',') + $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(',') + $ExpectedProps = "ComputerName,InstanceName,SqlInstance,Filename,RemoteFilename,Server".Split(",") ($results[0].PsObject.Properties.Name | Sort-Object) | Should -Be ($ExpectedProps | Sort-Object) } @@ -88,7 +110,7 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { "a" | Out-File (Join-Path $tmpdir "out.mdf") $results = Find-DbaOrphanedFile -SqlInstance $TestConfig.instance2 -Path $tmpdir $results.Filename.Count | Should -Be 1 - Move-Item "$tmpdir\out.mdf" -destination $tmpdirInner + 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 @@ -111,4 +133,4 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $results.Filename | Should -Contain "C:\$($backupFile.BackupFile)" } } -} +} \ No newline at end of file diff --git a/tests/Find-DbaSimilarTable.Tests.ps1 b/tests/Find-DbaSimilarTable.Tests.ps1 index 50c226b368a..1e14a657ff0 100644 --- a/tests/Find-DbaSimilarTable.Tests.ps1 +++ b/tests/Find-DbaSimilarTable.Tests.ps1 @@ -1,42 +1,78 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Find-DbaSimilarTable", + $PSDefaultParameterValues = $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', '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 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "SchemaName", + "TableName", + "ExcludeViews", + "IncludeSystemDatabases", + "MatchPercentThreshold", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Testing if similar tables are discovered" { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $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)") + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + $db = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database tempdb $db.Query("DROP TABLE dbatoolsci_table1") $db.Query("DROP TABLE dbatoolsci_table2") + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } - $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 = 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 + $results.Status.Count -ge 2 | Should -Be $true $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 "matches 100% for the test tables" { + $results = Find-DbaSimilarTable -SqlInstance $TestConfig.instance1 -Database tempdb | Where-Object Table -Match dbatoolsci + + foreach ($result in $results) { + $result.MatchPercent -eq 100 | Should -Be $true } } } -} +} \ No newline at end of file diff --git a/tests/Find-DbaStoredProcedure.Tests.ps1 b/tests/Find-DbaStoredProcedure.Tests.ps1 index f3d429a00b0..8cde9990229 100644 --- a/tests/Find-DbaStoredProcedure.Tests.ps1 +++ b/tests/Find-DbaStoredProcedure.Tests.ps1 @@ -1,21 +1,42 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Find-DbaStoredProcedure", + $PSDefaultParameterValues = $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 $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "Pattern", + "IncludeSystemObjects", + "IncludeSystemDatabases", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Command finds Procedures in a System Database" { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $ServerProcedure = @" CREATE PROCEDURE dbo.cp_dbatoolsci_sysadmin AS @@ -23,41 +44,118 @@ AS SELECT [sid],[loginname],[sysadmin] FROM [master].[sys].[syslogins]; "@ - $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'Master' -Query $ServerProcedure + $splatCreateProc = @{ + SqlInstance = $TestConfig.instance2 + Database = "Master" + Query = $ServerProcedure + } + $null = Invoke-DbaQuery @splatCreateProc + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $DropProcedure = "DROP PROCEDURE dbo.cp_dbatoolsci_sysadmin;" - $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'Master' -Query $DropProcedure + $splatDropProc = @{ + SqlInstance = $TestConfig.instance2 + Database = "Master" + Query = $DropProcedure + } + $null = Invoke-DbaQuery @splatDropProc + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } - $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" + $splatFind = @{ + SqlInstance = $TestConfig.instance2 + Pattern = "dbatools*" + IncludeSystemDatabases = $true + } + $results = Find-DbaStoredProcedure @splatFind + $results.Name | Should -Contain "cp_dbatoolsci_sysadmin" } } + Context "Command finds Procedures in a User Database" { BeforeAll { - $null = New-DbaDatabase -SqlInstance $TestConfig.instance2 -Name 'dbatoolsci_storedproceduredb' + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Set variables. They are available in all the It blocks. + $testDbName = "dbatoolsci_storedproceduredb" + + # Create the database + $splatNewDb = @{ + SqlInstance = $TestConfig.instance2 + Name = $testDbName + } + $null = New-DbaDatabase @splatNewDb + + # Create stored procedure $StoredProcedure = @" CREATE PROCEDURE dbo.sp_dbatoolsci_custom AS SET NOCOUNT ON; PRINT 'Dbatools Rocks'; "@ - $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'dbatoolsci_storedproceduredb' -Query $StoredProcedure + $splatCreateProc = @{ + SqlInstance = $TestConfig.instance2 + Database = $testDbName + Query = $StoredProcedure + } + $null = Invoke-DbaQuery @splatCreateProc + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { - $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database 'dbatoolsci_storedproceduredb' -Confirm:$false + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + $splatRemoveDb = @{ + SqlInstance = $TestConfig.instance2 + Database = "dbatoolsci_storedproceduredb" + Confirm = $false + } + $null = Remove-DbaDatabase @splatRemoveDb + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } - $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" + $splatFind = @{ + SqlInstance = $TestConfig.instance2 + Pattern = "dbatools*" + Database = "dbatoolsci_storedproceduredb" + } + $results = Find-DbaStoredProcedure @splatFind + $results.Name | Should -Contain "sp_dbatoolsci_custom" } + It "Should find sp_dbatoolsci_custom in dbatoolsci_storedproceduredb" { - $results.Database | Should Contain "dbatoolsci_storedproceduredb" + $splatFind = @{ + SqlInstance = $TestConfig.instance2 + Pattern = "dbatools*" + Database = "dbatoolsci_storedproceduredb" + } + $results = Find-DbaStoredProcedure @splatFind + $results.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 + $splatFind = @{ + SqlInstance = $TestConfig.instance2 + Pattern = "dbatools*" + ExcludeDatabase = "dbatoolsci_storedproceduredb" + } + $results = Find-DbaStoredProcedure @splatFind + $results | Should -BeNullOrEmpty } } -} +} \ No newline at end of file diff --git a/tests/Find-DbaTrigger.Tests.ps1 b/tests/Find-DbaTrigger.Tests.ps1 index 724046f1e21..aae1ed3d967 100644 --- a/tests/Find-DbaTrigger.Tests.ps1 +++ b/tests/Find-DbaTrigger.Tests.ps1 @@ -1,19 +1,38 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Find-DbaTrigger", + $PSDefaultParameterValues = $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', '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 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "Pattern", + "TriggerLevel", + "IncludeSystemObjects", + "IncludeSystemDatabases", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Command finds Triggers at the Server Level" { BeforeAll { ## All Triggers adapted from examples on: @@ -29,33 +48,38 @@ AS "@ $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Query $ServerTrigger } + AfterAll { $DropTrigger = @" DROP TRIGGER dbatoolsci_ddl_trig_database ON ALL SERVER; "@ - $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'Master' -Query $DropTrigger + $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database "Master" -Query $DropTrigger } - $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 = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -IncludeSystemDatabases -IncludeSystemObjects -TriggerLevel 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 = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -IncludeSystemDatabases -IncludeSystemObjects -TriggerLevel Server + $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" + $results = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -TriggerLevel All + $results.Name | Should -Be "dbatoolsci_ddl_trig_database" } } + Context "Command finds Triggers at the Database and Object Level" { BeforeAll { ## All Triggers adapted from examples on: ## https://docs.microsoft.com/en-us/sql/t-sql/statements/create-trigger-transact-sql?view=sql-server-2017 - $dbatoolsci_triggerdb = New-DbaDatabase -SqlInstance $TestConfig.instance2 -Name 'dbatoolsci_triggerdb' + $dbatoolsci_triggerdb = New-DbaDatabase -SqlInstance $TestConfig.instance2 -Name "dbatoolsci_triggerdb" $DatabaseTrigger = @" CREATE TRIGGER dbatoolsci_safety ON DATABASE @@ -66,7 +90,7 @@ RETURN; RAISERROR ('You must disable Trigger "safety" to drop synonyms!',10, 1) ROLLBACK "@ - $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'dbatoolsci_triggerdb' -Query $DatabaseTrigger + $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database "dbatoolsci_triggerdb" -Query $DatabaseTrigger $TableTrigger = @" CREATE TABLE dbo.Customer (id int, PRIMARY KEY (id)); GO @@ -76,36 +100,44 @@ AFTER INSERT, UPDATE AS RAISERROR ('Notify Customer Relations', 16, 10); GO "@ - $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database 'dbatoolsci_triggerdb' -Query $TableTrigger + $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database "dbatoolsci_triggerdb" -Query $TableTrigger } + AfterAll { - $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database 'dbatoolsci_triggerdb' -Confirm:$false + $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database "dbatoolsci_triggerdb" -Confirm:$false } - $results = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -Database 'dbatoolsci_triggerdb' -TriggerLevel Database It "Should find a specific Trigger at the Database Level" { - $results.TriggerLevel | Should Be "Database" + $results = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -Database "dbatoolsci_triggerdb" -TriggerLevel Database + $results.TriggerLevel | Should -Be "Database" $results.DatabaseId | Should -Be $dbatoolsci_triggerdb.ID } + It "Should find a specific Trigger named dbatoolsci_safety" { - $results.Name | Should Be "dbatoolsci_safety" + $results = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -Database "dbatoolsci_triggerdb" -TriggerLevel Database + $results.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 = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -Database "dbatoolsci_triggerdb" -ExcludeDatabase Master -TriggerLevel Object + $results.TriggerLevel | Should -Be "Object" $results.DatabaseId | Should -Be $dbatoolsci_triggerdb.ID } + It "Should find a specific Trigger named dbatoolsci_reminder1" { - $results.Name | Should Be "dbatoolsci_reminder1" + $results = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -Database "dbatoolsci_triggerdb" -ExcludeDatabase Master -TriggerLevel Object + $results.Name | Should -Be "dbatoolsci_reminder1" } + It "Should find a specific Trigger on the Table [dbo].[Customer]" { - $results.Object | Should Be "[dbo].[Customer]" + $results = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -Database "dbatoolsci_triggerdb" -ExcludeDatabase Master -TriggerLevel Object + $results.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 = Find-DbaTrigger -SqlInstance $TestConfig.instance2 -Pattern dbatoolsci* -TriggerLevel All + $results.name | Should -Be @("dbatoolsci_safety", "dbatoolsci_reminder1") $results.DatabaseId | Should -Be $dbatoolsci_triggerdb.ID, $dbatoolsci_triggerdb.ID } } -} +} \ No newline at end of file diff --git a/tests/Find-DbaView.Tests.ps1 b/tests/Find-DbaView.Tests.ps1 index e9cb17fe49b..4f11d299e50 100644 --- a/tests/Find-DbaView.Tests.ps1 +++ b/tests/Find-DbaView.Tests.ps1 @@ -1,20 +1,38 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Find-DbaView", + $PSDefaultParameterValues = $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 $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "ExcludeDatabase", + "Pattern", + "IncludeSystemObjects", + "IncludeSystemDatabases", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Command finds Views in a System Database" { BeforeAll { $ServerView = @" @@ -23,48 +41,58 @@ 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 + $null = Invoke-DbaQuery -SqlInstance $TestConfig.instance2 -Database "Master" -Query $DropView + } + + BeforeEach { + $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" { BeforeAll { - $null = New-DbaDatabase -SqlInstance $TestConfig.instance2 -Name 'dbatoolsci_viewdb' + $null = New-DbaDatabase -SqlInstance $TestConfig.instance2 -Name "dbatoolsci_viewdb" $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 } + AfterAll { - $null = Remove-DbaDatabase -SqlInstance $TestConfig.instance2 -Database 'dbatoolsci_viewdb' -Confirm:$false + $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" + $results = Find-DbaView -SqlInstance $TestConfig.instance2 -Pattern dbatools* -Database "dbatoolsci_viewdb" + $results.Name | Should -Be "v_dbatoolsci_sysadmin" } + It "Should find v_dbatoolsci_sysadmin in dbatoolsci_viewdb Database" { - $results.Database | Should Be "dbatoolsci_viewdb" + $results = Find-DbaView -SqlInstance $TestConfig.instance2 -Pattern dbatools* -Database "dbatoolsci_viewdb" + $results.Database | Should -Be "dbatoolsci_viewdb" $results.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 + $results = Find-DbaView -SqlInstance $TestConfig.instance2 -Pattern dbatools* -ExcludeDatabase "dbatoolsci_viewdb" + $results | Should -BeNullOrEmpty } } -} +} \ No newline at end of file diff --git a/tests/Format-DbaBackupInformation.Tests.ps1 b/tests/Format-DbaBackupInformation.Tests.ps1 index 824d703e99b..44079eae93f 100644 --- a/tests/Format-DbaBackupInformation.Tests.ps1 +++ b/tests/Format-DbaBackupInformation.Tests.ps1 @@ -4,11 +4,11 @@ $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[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } [object[]]$knownParameters = 'BackupHistory', 'ReplaceDatabaseName', 'ReplaceDbNameInFile', 'DataFileDirectory', 'LogFileDirectory', 'DestinationFileStreamDirectory', 'DatabaseNamePrefix', 'DatabaseFilePrefix', 'DatabaseFileSuffix', 'RebaseBackupFolder', 'Continue', 'FileMapping', 'PathSep', '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 + (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 } } } @@ -19,10 +19,10 @@ Describe "$CommandName Integration Tests" -Tags 'IntegrationTests' { $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml $output = $history | Format-DbaBackupInformation -ReplaceDatabaseName 'Pester' It "Should have a database name of Pester" { - ($output | Where-Object {$_.Database -ne 'Pester'}).count | Should be 0 + ($output | Where-Object { $_.Database -ne 'Pester' }).count | Should be 0 } It "Should have renamed datafiles as well" { - ($output | Select-Object -ExpandProperty filelist | Where-Object {$_.PhysicalName -like '*ContinuePointTest*'}).count + ($output | Select-Object -ExpandProperty filelist | Where-Object { $_.PhysicalName -like '*ContinuePointTest*' }).count } } @@ -31,34 +31,34 @@ Describe "$CommandName Integration Tests" -Tags 'IntegrationTests' { $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml $output = Format-DbaBackupInformation -BackupHistory $History -ReplaceDatabaseName 'Pester' It "Should have a database name of Pester" { - ($output | Where-Object {$_.Database -ne 'Pester'}).count | Should be 0 + ($output | Where-Object { $_.Database -ne 'Pester' }).count | Should be 0 } It "Should have renamed datafiles as well" { - ($out | Select-Object -ExpandProperty filelist | Where-Object {$_.PhysicalName -like 'ContinuePointTest'}).count | Should Be 0 + ($out | Select-Object -ExpandProperty filelist | Where-Object { $_.PhysicalName -like 'ContinuePointTest' }).count | Should Be 0 } } Context "Rename 2 dbs using a hash" { $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml $History += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml - $output = Format-DbaBackupInformation -BackupHistory $History -ReplaceDatabaseName @{'ContinuePointTest' = 'Spiggy'; 'RestoreTimeClean' = 'Eldritch'} + $output = Format-DbaBackupInformation -BackupHistory $History -ReplaceDatabaseName @{'ContinuePointTest' = 'Spiggy'; 'RestoreTimeClean' = 'Eldritch' } It "Should have no databases other than spiggy and eldritch" { - ($output | Where-Object {$_.Database -notin ('Spiggy', 'Eldritch')}).count | Should be 0 + ($output | Where-Object { $_.Database -notin ('Spiggy', 'Eldritch') }).count | Should be 0 } It "Should have renamed all RestoreTimeCleans to Eldritch" { - ($Output | Where-Object {$_.OriginalDatabase -eq 'RestoreTimeClean'} | Where-Object {$_.Database -ne 'Eldritch'}).count | Should be 0 + ($Output | Where-Object { $_.OriginalDatabase -eq 'RestoreTimeClean' } | Where-Object { $_.Database -ne 'Eldritch' }).count | Should be 0 } It "Should have renamed all the RestoreTimeClean files to Eldritch" { - ($out | Where-Object {$_.OriginalDatabase -eq 'RestoreTimeClean'} | Select-Object -ExpandProperty filelist | Where-Object {$_.PhysicalName -like 'RestoreTimeClean'}).count | Should Be 0 - ($out | Where-Object {$_.OriginalDatabase -eq 'RestoreTimeClean'} | Select-Object -ExpandProperty filelist | Where-Object {$_.PhysicalName -like 'eldritch'}).count | Should Be ($out | Where-Object {$_.OriginalDatabase -eq 'ContinuePointTest'} | Select-Object -ExpandProperty filelist).count + ($out | Where-Object { $_.OriginalDatabase -eq 'RestoreTimeClean' } | Select-Object -ExpandProperty filelist | Where-Object { $_.PhysicalName -like 'RestoreTimeClean' }).count | Should Be 0 + ($out | Where-Object { $_.OriginalDatabase -eq 'RestoreTimeClean' } | Select-Object -ExpandProperty filelist | Where-Object { $_.PhysicalName -like 'eldritch' }).count | Should Be ($out | Where-Object { $_.OriginalDatabase -eq 'ContinuePointTest' } | Select-Object -ExpandProperty filelist).count } It "Should have renamed all ContinuePointTest to Spiggy" { - ($Output | Where-Object {$_.OriginalDatabase -eq 'ContinuePointTest'} | Where-Object {$_.Database -ne 'Spiggy'}).count | Should be 0 + ($Output | Where-Object { $_.OriginalDatabase -eq 'ContinuePointTest' } | Where-Object { $_.Database -ne 'Spiggy' }).count | Should be 0 } It "Should have renamed all the ContinuePointTest files to Spiggy" { - ($out | Where-Object {$_.OriginalDatabase -eq 'ContinuePointTest'} | Select-Object -ExpandProperty filelist | Where-Object {$_.PhysicalName -like 'ContinuePointTest'}).count | Should Be 0 - ($out | Where-Object {$_.OriginalDatabase -eq 'ContinuePointTest'} | Select-Object -ExpandProperty filelist | Where-Object {$_.PhysicalName -like 'spiggy'}).count | Should Be ($out | Where-Object {$_.OriginalDatabase -eq 'ContinuePointTest'} | Select-Object -ExpandProperty filelist).count + ($out | Where-Object { $_.OriginalDatabase -eq 'ContinuePointTest' } | Select-Object -ExpandProperty filelist | Where-Object { $_.PhysicalName -like 'ContinuePointTest' }).count | Should Be 0 + ($out | Where-Object { $_.OriginalDatabase -eq 'ContinuePointTest' } | Select-Object -ExpandProperty filelist | Where-Object { $_.PhysicalName -like 'spiggy' }).count | Should Be ($out | Where-Object { $_.OriginalDatabase -eq 'ContinuePointTest' } | Select-Object -ExpandProperty filelist).count } } @@ -66,19 +66,19 @@ Describe "$CommandName Integration Tests" -Tags 'IntegrationTests' { Context "Rename 1 dbs using a hash" { $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml $History += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml - $output = Format-DbaBackupInformation -BackupHistory $History -ReplaceDatabaseName @{'ContinuePointTest' = 'Alice'} + $output = Format-DbaBackupInformation -BackupHistory $History -ReplaceDatabaseName @{'ContinuePointTest' = 'Alice' } It "Should have no databases other than spiggy and eldritch" { - ($output | Where-Object {$_.Database -notin ('RestoreTimeClean', 'Alice')}).count | Should be 0 + ($output | Where-Object { $_.Database -notin ('RestoreTimeClean', 'Alice') }).count | Should be 0 } It "Should have left RestoreTimeClean alone" { - ($Output | Where-Object {$_.OriginalDatabase -eq 'RestoreTimeClean'} | Where-Object {$_.Database -ne 'RestoreTimeClean'}).count | Should be 0 + ($Output | Where-Object { $_.OriginalDatabase -eq 'RestoreTimeClean' } | Where-Object { $_.Database -ne 'RestoreTimeClean' }).count | Should be 0 } It "Should have renamed all ContinuePointTest to Alice" { - ($Output | Where-Object {$_.OriginalDatabase -eq 'ContinuePointTest'} | Where-Object {$_.Database -ne 'Alice'}).count | Should be 0 + ($Output | Where-Object { $_.OriginalDatabase -eq 'ContinuePointTest' } | Where-Object { $_.Database -ne 'Alice' }).count | Should be 0 } It "Should have renamed all the ContinuePointTest files to Alice" { - ($Output | Where-Object {$_.OriginalDatabase -eq 'ContinuePointTest'} | Select-Object -ExpandProperty filelist | Where-Object {$_.PhysicalName -like 'ContinuePointTest'}).count | Should Be 0 - ($Output | Where-Object {$_.OriginalDatabase -eq 'ContinuePointTest'} | Select-Object -ExpandProperty filelist | Where-Object {$_.PhysicalName -like 'alice'}).count | Should Be ($out | Where-Object {$_.OriginalDatabase -eq 'ContinuePointTest'} | Select-Object -ExpandProperty filelist).count + ($Output | Where-Object { $_.OriginalDatabase -eq 'ContinuePointTest' } | Select-Object -ExpandProperty filelist | Where-Object { $_.PhysicalName -like 'ContinuePointTest' }).count | Should Be 0 + ($Output | Where-Object { $_.OriginalDatabase -eq 'ContinuePointTest' } | Select-Object -ExpandProperty filelist | Where-Object { $_.PhysicalName -like 'alice' }).count | Should Be ($out | Where-Object { $_.OriginalDatabase -eq 'ContinuePointTest' } | Select-Object -ExpandProperty filelist).count } } @@ -86,7 +86,7 @@ Describe "$CommandName Integration Tests" -Tags 'IntegrationTests' { $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml $output = $history | Format-DbaBackupInformation -DatabaseNamePrefix PREFIX It "Should have prefixed all db names" { - ($Output | Where-Object {$_.Database -like 'PREFIX*'}).count | Should be $output.count + ($Output | Where-Object { $_.Database -like 'PREFIX*' }).count | Should be $output.count } } @@ -97,7 +97,7 @@ Describe "$CommandName Integration Tests" -Tags 'IntegrationTests' { $output = Format-DbaBackupInformation -BackupHistory $History -DataFileDirectory c:\restores It "Should have move ALL files to c:\restores\" { - (($Output | Select-Object -ExpandProperty Filelist).PhysicalName | split-path | Where-Object {$_ -ne 'c:\restores'}).count | Should Be 0 + (($Output | Select-Object -ExpandProperty Filelist).PhysicalName | Split-Path | Where-Object { $_ -ne 'c:\restores' }).count | Should Be 0 } } @@ -107,10 +107,10 @@ Describe "$CommandName Integration Tests" -Tags 'IntegrationTests' { $output = Format-DbaBackupInformation -BackupHistory $History -DataFileDirectory c:\restores\ -LogFileDirectory c:\logs It "Should have moved all data files to c:\restores\" { - (($Output | Select-Object -ExpandProperty Filelist | Where-Object {$_.Type -eq 'D'}).PhysicalName | split-path | Where-Object {$_ -ne 'c:\restores'}).count | Should Be 0 + (($Output | Select-Object -ExpandProperty Filelist | Where-Object { $_.Type -eq 'D' }).PhysicalName | Split-Path | Where-Object { $_ -ne 'c:\restores' }).count | Should Be 0 } It "Should have moved all log files to c:\logs\" { - (($Output | Select-Object -ExpandProperty Filelist | Where-Object {$_.Type -eq 'L'}).PhysicalName | split-path | Where-Object {$_ -ne 'c:\logs'}).count | Should Be 0 + (($Output | Select-Object -ExpandProperty Filelist | Where-Object { $_.Type -eq 'L' }).PhysicalName | Split-Path | Where-Object { $_ -ne 'c:\logs' }).count | Should Be 0 } } @@ -120,10 +120,10 @@ Describe "$CommandName Integration Tests" -Tags 'IntegrationTests' { $Output = Format-DbaBackupInformation -BackupHistory $History -DataFileDirectory c:\restores\ -LogFileDirectory c:\logs It "Should not have moved all data files to c:\restores\" { - (($Output | Select-Object -ExpandProperty Filelist | Where-Object {$_.Type -eq 'D'}).PhysicalName | split-path | Where-Object {$_ -eq 'c:\logs'}).count | Should Be 0 + (($Output | Select-Object -ExpandProperty Filelist | Where-Object { $_.Type -eq 'D' }).PhysicalName | Split-Path | Where-Object { $_ -eq 'c:\logs' }).count | Should Be 0 } It "Should have moved all log files to c:\logs\" { - (($Output | Select-Object -ExpandProperty Filelist | Where-Object {$_.Type -eq 'L'}).PhysicalName | split-path | Where-Object {$_ -ne 'c:\logs'}).count | Should Be 0 + (($Output | Select-Object -ExpandProperty Filelist | Where-Object { $_.Type -eq 'L' }).PhysicalName | Split-Path | Where-Object { $_ -ne 'c:\logs' }).count | Should Be 0 } } @@ -133,7 +133,7 @@ Describe "$CommandName Integration Tests" -Tags 'IntegrationTests' { $Output = Format-DbaBackupInformation -BackupHistory $History -RebaseBackupFolder c:\backups\ It "Should not have moved all backup files to c:\backups" { - ($Output | Select-Object -ExpandProperty FullName | split-path | Where-Object {$_ -eq 'c:\backups'}).count | Should Be $History.count + ($Output | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $_ -eq 'c:\backups' }).count | Should Be $History.count } } @@ -143,16 +143,16 @@ Describe "$CommandName Integration Tests" -Tags 'IntegrationTests' { $History += Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\RestoreTimeClean.xml $Output = Format-DbaBackupInformation -BackupHistory $History -RebaseBackupFolder 'c:\backups' It "Should not have changed the default path separator" { - ($Output | Select-Object -ExpandProperty FullName | split-path | Where-Object {$_ -eq 'c:\backups'}).count | Should Be $History.count + ($Output | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $_ -eq 'c:\backups' }).count | Should Be $History.count } $Output = Format-DbaBackupInformation -BackupHistory $History -RebaseBackupFolder 'c:\backups' -PathSep '\' It "Should not have changed the default path separator even when passed explicitely" { - ($Output | Select-Object -ExpandProperty FullName | split-path | Where-Object {$_ -eq 'c:\backups'}).count | Should Be $History.count + ($Output | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $_ -eq 'c:\backups' }).count | Should Be $History.count } $Output = Format-DbaBackupInformation -BackupHistory $History -RebaseBackupFolder '/opt/mssql/backups' -PathSep '/' It "Should have changed the path separator as instructed" { - $result = $Output | Select-Object -ExpandProperty FullName | ForEach-Object { $all = $_.Split('/'); $all[0..($all.Length - 2)] -Join '/'} - ($result | Where-Object {$_ -eq '/opt/mssql/backups'}).count | Should Be $History.count + $result = $Output | Select-Object -ExpandProperty FullName | ForEach-Object { $all = $_.Split('/'); $all[0..($all.Length - 2)] -Join '/' } + ($result | Where-Object { $_ -eq '/opt/mssql/backups' }).count | Should Be $History.count } } @@ -160,19 +160,19 @@ Describe "$CommandName Integration Tests" -Tags 'IntegrationTests' { $History = Get-DbaBackupInformation -Import -Path $PSScriptRoot\..\tests\ObjectDefinitions\BackupRestore\RawInput\ContinuePointTest.xml $output = $history | Format-DbaBackupInformation -ReplaceDatabaseName 'Pester' -DataFileDirectory c:\restores -LogFileDirectory c:\logs\ -RebaseBackupFolder c:\backups\ It "Should have a database name of Pester" { - ($output | Where-Object {$_.Database -ne 'Pester'}).count | Should be 0 + ($output | Where-Object { $_.Database -ne 'Pester' }).count | Should be 0 } It "Should have renamed datafiles as well" { - ($output | Select-Object -ExpandProperty filelist | Where-Object {$_.PhysicalName -like '*ContinuePointTest*'}).count + ($output | Select-Object -ExpandProperty filelist | Where-Object { $_.PhysicalName -like '*ContinuePointTest*' }).count } It "Should have moved all data files to c:\restores\" { - (($Output | Select-Object -ExpandProperty Filelist | Where-Object {$_.Type -eq 'D'}).PhysicalName | split-path | Where-Object {$_ -ne 'c:\restores'}).count | Should Be 0 + (($Output | Select-Object -ExpandProperty Filelist | Where-Object { $_.Type -eq 'D' }).PhysicalName | Split-Path | Where-Object { $_ -ne 'c:\restores' }).count | Should Be 0 } It "Should have moved all log files to c:\logs\" { - (($Output | Select-Object -ExpandProperty Filelist | Where-Object {$_.Type -eq 'L'}).PhysicalName | split-path | Where-Object {$_ -ne 'c:\logs'}).count | Should Be 0 + (($Output | Select-Object -ExpandProperty Filelist | Where-Object { $_.Type -eq 'L' }).PhysicalName | Split-Path | Where-Object { $_ -ne 'c:\logs' }).count | Should Be 0 } It "Should not have moved all backup files to c:\backups" { - ($Output | Select-Object -ExpandProperty FullName | Split-Path | Where-Object {$_ -eq 'c:\backups'}).count | Should Be $History.count + ($Output | Select-Object -ExpandProperty FullName | Split-Path | Where-Object { $_ -eq 'c:\backups' }).count | Should Be $History.count } } diff --git a/tests/Get-DbaAgBackupHistory.Tests.ps1 b/tests/Get-DbaAgBackupHistory.Tests.ps1 index 7ecc2b608b3..e8ac02d98d2 100644 --- a/tests/Get-DbaAgBackupHistory.Tests.ps1 +++ b/tests/Get-DbaAgBackupHistory.Tests.ps1 @@ -1,16 +1,46 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaAgBackupHistory", + $PSDefaultParameterValues = $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', '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 $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "AvailabilityGroup", + "Database", + "ExcludeDatabase", + "IncludeCopyOnly", + "Force", + "Since", + "RecoveryFork", + "Last", + "LastFull", + "LastDiff", + "LastLog", + "DeviceType", + "Raw", + "LastLsn", + "IncludeMirror", + "Type", + "LsnSort", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -# No Integration Tests, because we don't have an availability group running in AppVeyor +# No Integration Tests, because we don't have an availability group running in AppVeyor \ No newline at end of file diff --git a/tests/Get-DbaAgDatabase.Tests.ps1 b/tests/Get-DbaAgDatabase.Tests.ps1 index 3ab863dc389..5c894702d7a 100644 --- a/tests/Get-DbaAgDatabase.Tests.ps1 +++ b/tests/Get-DbaAgDatabase.Tests.ps1 @@ -1,44 +1,89 @@ -$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', '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", + $CommandName = "Get-DbaAgDatabase", + $PSDefaultParameterValues = $TestConfig.Defaults +) + +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "AvailabilityGroup", + "Database", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $backupPath = "$($TestConfig.Temp)\$CommandName" + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # For all the backups that we want to clean up after the test, we create a directory that we can delete at the end. + # Other files can be written there as well, maybe we change the name of that variable later. But for now we focus on backups. + $backupPath = "$($TestConfig.Temp)\$CommandName-$(Get-Random)" $null = New-Item -Path $backupPath -ItemType Directory - $null = Get-DbaProcess -SqlInstance $TestConfig.instance3 -Program 'dbatools PowerShell module - dbatools.io' | Stop-DbaProcess -WarningAction SilentlyContinue + # Explain what needs to be set up for the test: + # To test Get-DbaAgDatabase, we need an availability group with a database that has been backed up. + + # Set variables. They are available in all the It blocks. + $agName = "dbatoolsci_getagdb_agroup" + $dbName = "dbatoolsci_getagdb_agroupdb" + + # Create the objects. + $null = Get-DbaProcess -SqlInstance $TestConfig.instance3 -Program "dbatools PowerShell module - dbatools.io" | Stop-DbaProcess -WarningAction SilentlyContinue $server = Connect-DbaInstance -SqlInstance $TestConfig.instance3 - $agname = "dbatoolsci_getagdb_agroup" - $dbname = "dbatoolsci_getagdb_agroupdb" - $server.Query("create database $dbname") - $null = Get-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $dbname | Backup-DbaDatabase -Path $backupPath - $null = Get-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $dbname | Backup-DbaDatabase -Path $backupPath -Type Log - $ag = New-DbaAvailabilityGroup -Primary $TestConfig.instance3 -Name $agname -ClusterType None -FailoverMode Manual -Database $dbname -Confirm:$false -Certificate dbatoolsci_AGCert -UseLastBackup + $server.Query("create database $dbName") + $null = Get-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $dbName | Backup-DbaDatabase -Path $backupPath + $null = Get-DbaDatabase -SqlInstance $TestConfig.instance3 -Database $dbName | Backup-DbaDatabase -Path $backupPath -Type Log + + $splatAg = @{ + Primary = $TestConfig.instance3 + Name = $agName + ClusterType = "None" + FailoverMode = "Manual" + Database = $dbName + Certificate = "dbatoolsci_AGCert" + UseLastBackup = $true + } + $ag = New-DbaAvailabilityGroup @splatAg + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { - $null = Remove-DbaAvailabilityGroup -SqlInstance $server -AvailabilityGroup $agname -Confirm:$false - $null = Get-DbaEndpoint -SqlInstance $TestConfig.instance3 -Type DatabaseMirroring | Remove-DbaEndpoint -Confirm:$false - $null = Remove-DbaDatabase -SqlInstance $server -Database $dbname -Confirm:$false - Remove-Item -Path $backupPath -Recurse + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup all created objects. + $null = Remove-DbaAvailabilityGroup -SqlInstance $server -AvailabilityGroup $agName + $null = Get-DbaEndpoint -SqlInstance $TestConfig.instance3 -Type DatabaseMirroring | Remove-DbaEndpoint + $null = Remove-DbaDatabase -SqlInstance $server -Database $dbName + + # Remove the backup directory. + Remove-Item -Path $backupPath -Recurse -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } - Context "gets ag db" { - It "returns results" { - $results = Get-DbaAgDatabase -SqlInstance $TestConfig.instance3 -Database $dbname - $results.AvailabilityGroup | Should -Be $agname - $results.Name | Should -Be $dbname - $results.LocalReplicaRole | Should -Not -Be $null + Context "When getting AG database" { + It "Returns correct database information" { + $results = Get-DbaAgDatabase -SqlInstance $TestConfig.instance3 -Database $dbName + $results.AvailabilityGroup | Should -Be $agName + $results.Name | Should -Be $dbName + $results.LocalReplicaRole | Should -Not -BeNullOrEmpty } } -} #$TestConfig.instance2 for appveyor +} #$TestConfig.instance2 for appveyor \ No newline at end of file diff --git a/tests/Get-DbaAgHadr.Tests.ps1 b/tests/Get-DbaAgHadr.Tests.ps1 index ecd586d6527..a24fe5ad23d 100644 --- a/tests/Get-DbaAgHadr.Tests.ps1 +++ b/tests/Get-DbaAgHadr.Tests.ps1 @@ -1,25 +1,41 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaAgHadr", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag "UnitTests" { +Describe $CommandName -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 + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | 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 $CommandName -Tag IntegrationTests { + BeforeAll { + $results = Get-DbaAgHadr -SqlInstance $TestConfig.instance3 + } + Context "Validate output" { It "returns the correct properties" { $results.IsHadrEnabled | Should -Be $true } } -} #$TestConfig.instance2 for appveyor +} #$TestConfig.instance2 for appveyor \ No newline at end of file diff --git a/tests/Get-DbaAgListener.Tests.ps1 b/tests/Get-DbaAgListener.Tests.ps1 index 0a4e3670e88..ff5b91a3129 100644 --- a/tests/Get-DbaAgListener.Tests.ps1 +++ b/tests/Get-DbaAgListener.Tests.ps1 @@ -1,32 +1,79 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaAgListener", + $PSDefaultParameterValues = $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 $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "AvailabilityGroup", + "Listener", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe $CommandName -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 + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Set variables. They are available in all the It blocks. + $agListenerName = "dbatoolsci_ag_listener" + + # Create the objects. + $splatNewAg = @{ + Primary = $TestConfig.instance3 + Name = $agListenerName + ClusterType = "None" + FailoverMode = "Manual" + Certificate = "dbatoolsci_AGCert" + Confirm = $false + } + $ag = New-DbaAvailabilityGroup @splatNewAg + + $splatAddListener = @{ + IPAddress = "127.0.20.1" + Port = 14330 + Confirm = $false + } + $ag | Add-DbaAgListener @splatAddListener + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { - $null = Remove-DbaAvailabilityGroup -SqlInstance $TestConfig.instance3 -AvailabilityGroup $agname -Confirm:$false - $null = Get-DbaEndpoint -SqlInstance $TestConfig.instance3 -Type DatabaseMirroring | Remove-DbaEndpoint -Confirm:$false + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup all created objects. + $null = Remove-DbaAvailabilityGroup -SqlInstance $TestConfig.instance3 -AvailabilityGroup $agListenerName -Confirm $false + $null = Get-DbaEndpoint -SqlInstance $TestConfig.instance3 -Type DatabaseMirroring | Remove-DbaEndpoint -Confirm $false + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } - Context "gets ags" { - It "returns results with proper data" { + + Context "When getting AG listeners" { + It "Returns results with proper data" { $results = Get-DbaAgListener -SqlInstance $TestConfig.instance3 $results.PortNumber | Should -Contain 14330 } } -} #$TestConfig.instance2 for appveyor +} #$TestConfig.instance2 for appveyor \ No newline at end of file diff --git a/tests/Get-DbaAgReplica.Tests.ps1 b/tests/Get-DbaAgReplica.Tests.ps1 index 6d1992f6605..266330cef65 100644 --- a/tests/Get-DbaAgReplica.Tests.ps1 +++ b/tests/Get-DbaAgReplica.Tests.ps1 @@ -1,44 +1,89 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaAgReplica", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$commandname Unit Tests" -Tag 'UnitTests' { +Describe $CommandName -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 + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "AvailabilityGroup", + "Replica", + "InputObject", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $agname = "dbatoolsci_agroup" - $ag = New-DbaAvailabilityGroup -Primary $TestConfig.instance3 -Name $agname -ClusterType None -FailoverMode Manual -Certificate dbatoolsci_AGCert -Confirm:$false + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Set variables. They are available in all the It blocks. + $agName = "dbatoolsci_agroup" + $splatNewAg = @{ + Primary = $TestConfig.instance3 + Name = $agName + ClusterType = "None" + FailoverMode = "Manual" + Certificate = "dbatoolsci_AGCert" + Confirm = $false + } + $ag = New-DbaAvailabilityGroup @splatNewAg $replicaName = $ag.PrimaryReplica + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } + AfterAll { - $null = Remove-DbaAvailabilityGroup -SqlInstance $TestConfig.instance3 -AvailabilityGroup $agname -Confirm:$false - $null = Get-DbaEndpoint -SqlInstance $TestConfig.instance3 -Type DatabaseMirroring | Remove-DbaEndpoint -Confirm:$false + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + # Cleanup all created objects. + $null = Remove-DbaAvailabilityGroup -SqlInstance $TestConfig.instance3 -AvailabilityGroup $agName -Confirm $false + $null = Get-DbaEndpoint -SqlInstance $TestConfig.instance3 -Type DatabaseMirroring | Remove-DbaEndpoint -Confirm $false + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } + Context "gets ag replicas" { It "returns results with proper data" { $results = Get-DbaAgReplica -SqlInstance $TestConfig.instance3 - $results.AvailabilityGroup | Should -Contain $agname - $results.Role | Should -Contain 'Primary' - $results.AvailabilityMode | Should -Contain 'SynchronousCommit' + $results.AvailabilityGroup | Should -Contain $agName + $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' + $splatGetReplica = @{ + SqlInstance = $TestConfig.instance3 + Replica = $replicaName + AvailabilityGroup = $agName + } + $results = Get-DbaAgReplica @splatGetReplica + $results.AvailabilityGroup | Should -Be $agName + $results.Role | Should -Be "Primary" + $results.AvailabilityMode | Should -Be "SynchronousCommit" } # Skipping because this adds like 30 seconds to test times - It -Skip "Passes EnableException to Get-DbaAvailabilityGroup" { + It "Passes EnableException to Get-DbaAvailabilityGroup" -Skip:$true { $results = Get-DbaAgReplica -SqlInstance invalidSQLHostName -ErrorVariable agerror $results | Should -BeNullOrEmpty ($agerror | Where-Object Message -match "The network path was not found") | Should -Not -BeNullOrEmpty @@ -46,4 +91,4 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { { Get-DbaAgReplica -SqlInstance invalidSQLHostName -EnableException } | Should -Throw } } -} #$TestConfig.instance2 for appveyor +} #$TestConfig.instance2 for appveyor \ No newline at end of file diff --git a/tests/Get-DbaAgentAlert.Tests.ps1 b/tests/Get-DbaAgentAlert.Tests.ps1 index 2f092795586..e372feba80b 100644 --- a/tests/Get-DbaAgentAlert.Tests.ps1 +++ b/tests/Get-DbaAgentAlert.Tests.ps1 @@ -1,31 +1,65 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaAgentAlert", + $PSDefaultParameterValues = $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', '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 $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Alert", + "ExcludeAlert", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 -Database master + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + $splatAddAlert = @{ + SqlInstance = $TestConfig.instance2 + Database = "master" + } + $server = Connect-DbaInstance @splatAddAlert $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'") + + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { - $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 -Database master + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + $splatDeleteAlert = @{ + SqlInstance = $TestConfig.instance2 + Database = "master" + } + $server = Connect-DbaInstance @splatDeleteAlert $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' - } -} + Context "When getting agent alerts" { + BeforeAll { + $results = Get-DbaAgentAlert -SqlInstance $TestConfig.instance2 + } + It "Gets the newly created alert" { + $results.Name | Should -Contain "dbatoolsci test alert" + } + } +} \ No newline at end of file diff --git a/tests/Get-DbaAgentAlertCategory.Tests.ps1 b/tests/Get-DbaAgentAlertCategory.Tests.ps1 index ad6425b1827..f3e9a858743 100644 --- a/tests/Get-DbaAgentAlertCategory.Tests.ps1 +++ b/tests/Get-DbaAgentAlertCategory.Tests.ps1 @@ -1,33 +1,56 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaAgentAlertCategory", + $PSDefaultParameterValues = $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', '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 $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Category", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Command gets alert categories" { BeforeAll { + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $null = New-DbaAgentAlertCategory -SqlInstance $TestConfig.instance2 -Category dbatoolsci_testcategory, dbatoolsci_testcategory2 + + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $null = Remove-DbaAgentAlertCategory -SqlInstance $TestConfig.instance2 -Category dbatoolsci_testcategory, dbatoolsci_testcategory2 -Confirm:$false } - $results = Get-DbaAgentAlertCategory -SqlInstance $TestConfig.instance2 | Where-Object {$_.Name -match "dbatoolsci"} + It "Should get at least 2 categories" { - $results.count | Should BeGreaterThan 1 + $results = Get-DbaAgentAlertCategory -SqlInstance $TestConfig.instance2 | Where-Object Name -match "dbatoolsci" + $results.Count | Should -BeGreaterThan 1 } - $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 + $results = Get-DbaAgentAlertCategory -SqlInstance $TestConfig.instance2 -Category dbatoolsci_testcategory | Where-Object Name -match "dbatoolsci" + $results.Count | Should -BeExactly 1 } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaAgentJob.Tests.ps1 b/tests/Get-DbaAgentJob.Tests.ps1 index d5c41b23cc6..05a90c8f2bf 100644 --- a/tests/Get-DbaAgentJob.Tests.ps1 +++ b/tests/Get-DbaAgentJob.Tests.ps1 @@ -1,19 +1,40 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaAgentJob", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -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 $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Job", + "ExcludeJob", + "Database", + "Category", + "ExcludeDisabledJobs", + "EnableException", + "ExcludeCategory", + "IncludeExecution", + "Type" + ) + } - It "Should only contain our specific parameters" { - Compare-Object -ReferenceObject $knownParameters -DifferenceObject $params | Should -BeNullOrEmpty + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Command gets jobs" { BeforeAll { $null = New-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob @@ -22,15 +43,16 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { 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 | Where-Object Name -match "dbatoolsci_testjob" + $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" + $results = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Job dbatoolsci_testjob + $results.Name | Should -Be "dbatoolsci_testjob" } - } Context "Command gets no disabled jobs" { BeforeAll { @@ -40,9 +62,10 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { 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 + $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" { @@ -53,27 +76,29 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { 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 + $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" { BeforeAll { - $null = New-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category 'Cat1' - $null = New-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category 'Cat2' + $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' + $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-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 + $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" { @@ -93,20 +118,25 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { 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" { + $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 = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Database tempdb + $resultSingleDatabase.Name -contains $jobName1 | Should -BeTrue } - $resultMultipleDatabases = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Database tempdb, model It "Returns both jobs with double database" { + $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 = Get-DbaAgentJob -SqlInstance $TestConfig.instance2 -Database tempdb, model + $resultMultipleDatabases.Name -contains $jobName2 | Should -BeTrue } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaAgentJobCategory.Tests.ps1 b/tests/Get-DbaAgentJobCategory.Tests.ps1 index 3344a55e11a..cb7a3ad3224 100644 --- a/tests/Get-DbaAgentJobCategory.Tests.ps1 +++ b/tests/Get-DbaAgentJobCategory.Tests.ps1 @@ -1,37 +1,67 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaAgentJobCategory", + $PSDefaultParameterValues = $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 $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Category", + "CategoryType", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Command gets job categories" { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $null = New-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category dbatoolsci_testcategory, dbatoolsci_testcategory2 + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { - $null = Remove-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category dbatoolsci_testcategory, dbatoolsci_testcategory2 -Confirm:$false + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + $null = Remove-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category dbatoolsci_testcategory, dbatoolsci_testcategory2 + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } - $results = Get-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 | Where-Object {$_.Name -match "dbatoolsci"} + It "Should get at least 2 categories" { - $results.count | Should BeGreaterThan 1 + $results = Get-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 | Where-Object Name -match "dbatoolsci" + $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 + $results = Get-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -Category dbatoolsci_testcategory | Where-Object Name -match "dbatoolsci" + $results.Count | Should -BeExactly 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 + $results = Get-DbaAgentJobCategory -SqlInstance $TestConfig.instance2 -CategoryType LocalJob | Where-Object Name -match "dbatoolsci" + $results.Count | Should -BeGreaterThan 1 } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaAgentJobOutputFile.Tests.ps1 b/tests/Get-DbaAgentJobOutputFile.Tests.ps1 index ea63f48ded4..6276f1ec1cf 100644 --- a/tests/Get-DbaAgentJobOutputFile.Tests.ps1 +++ b/tests/Get-DbaAgentJobOutputFile.Tests.ps1 @@ -1,101 +1,130 @@ -$commandname = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaAgentJobOutputFile", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { +Describe $CommandName -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 + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Job", + "ExcludeJob", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Unittests" -Tag 'UnitTests' { - InModuleScope '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" { +Describe $CommandName -Tag UnitTests { + Context "Return values" { + BeforeAll { + InModuleScope "dbatools" { + 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" { + InModuleScope "dbatools" { $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 -BeExactly 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" { + } + + It "Honors the Job parameter" { + InModuleScope "dbatools" { $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" { + } + + It "Honors the ExcludeJob parameter" { + InModuleScope "dbatools" { $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 -BeExactly 1 + $Results.Job | Should -Match "Job2" + $Results.OutputFileName | Should -Be "Job2Output1" + $Results.StepId | Should -BeExactly 1 } - It "Does not return even with a specific job without outputfiles" { + } + + It "Does not return even with a specific job without outputfiles" { + InModuleScope "dbatools" { $Results = @() - $Results += Get-DbaAgentJobOutputFile -SqlInstance 'SQLServerName' -Job 'Job3' - $Results.Length | Should Be 0 + $Results += Get-DbaAgentJobOutputFile -SqlInstance "SQLServerName" -Job "Job3" + $Results.Count | Should -BeExactly 0 } } } diff --git a/tests/Get-DbaAgentJobStep.Tests.ps1 b/tests/Get-DbaAgentJobStep.Tests.ps1 index b32e7827705..030d585ba42 100644 --- a/tests/Get-DbaAgentJobStep.Tests.ps1 +++ b/tests/Get-DbaAgentJobStep.Tests.ps1 @@ -1,46 +1,66 @@ -$commandname = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaAgentJobStep", + $PSDefaultParameterValues = $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', '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 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Job", + "ExcludeJob", + "InputObject", + "ExcludeDisabledJobs", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Gets a job step" { BeforeAll { - $jobName = "dbatoolsci_job_$(get-random)" + $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' + $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 } It "Successfully gets job when not using Job param" { $results = Get-DbaAgentJobStep -SqlInstance $TestConfig.instance2 - $results.Name | should contain 'dbatoolsci_jobstep1' + $results.Name | Should -Contain "dbatoolsci_jobstep1" } + It "Successfully gets job when using Job param" { $results = Get-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -Job $jobName - $results.Name | should contain 'dbatoolsci_jobstep1' + $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' + $results = Get-DbaAgentJobStep -SqlInstance $TestConfig.instance2 -ExcludeJob "syspolicy_purge_history" + $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' + $results.Name | Should -Not -Contain "dbatoolsci_jobstep1" } - } -} +} \ No newline at end of file diff --git a/tests/Get-DbaAgentOperator.Tests.ps1 b/tests/Get-DbaAgentOperator.Tests.ps1 index 9cc587ebbcd..e3f24595317 100644 --- a/tests/Get-DbaAgentOperator.Tests.ps1 +++ b/tests/Get-DbaAgentOperator.Tests.ps1 @@ -1,40 +1,69 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaAgentOperator", + $PSDefaultParameterValues = $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 $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Operator", + "ExcludeOperator", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $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) + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $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) + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } + 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 + $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 + $results = Get-DbaAgentOperator -SqlInstance $TestConfig.instance2 -Operator dbatoolsci_operator + $results.Count | Should -BeExactly 1 } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaAgentProxy.Tests.ps1 b/tests/Get-DbaAgentProxy.Tests.ps1 index 55d5ff43ece..065cf947966 100644 --- a/tests/Get-DbaAgentProxy.Tests.ps1 +++ b/tests/Get-DbaAgentProxy.Tests.ps1 @@ -1,70 +1,145 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaAgentProxy", + $PSDefaultParameterValues = $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', '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 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Proxy", + "ExcludeProxy", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $tPassword = ConvertTo-SecureString "ThisIsThePassword1" -AsPlainText -Force - $tUserName = "dbatoolsci_proxytest" - New-LocalUser -Name $tUserName -Password $tPassword -Disabled:$false - New-DbaCredential -SqlInstance $TestConfig.instance2 -Name "$tUserName" -Identity "$env:COMPUTERNAME\$tUserName" -Password $tPassword - New-DbaAgentProxy -SqlInstance $TestConfig.instance2 -Name STIG -ProxyCredential "$tUserName" - New-DbaAgentProxy -SqlInstance $TestConfig.instance2 -Name STIGX -ProxyCredential "$tUserName" + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + $tPassword = ConvertTo-SecureString "ThisIsThePassword1" -AsPlainText -Force + $tUserName = "dbatoolsci_proxytest" + $proxyName1 = "STIG" + $proxyName2 = "STIGX" + + $null = New-LocalUser -Name $tUserName -Password $tPassword -Disabled:$false + $splatCredential = @{ + SqlInstance = $TestConfig.instance2 + Name = $tUserName + Identity = "$env:COMPUTERNAME\$tUserName" + Password = $tPassword + } + $null = New-DbaCredential @splatCredential + + $splatProxy1 = @{ + SqlInstance = $TestConfig.instance2 + Name = $proxyName1 + ProxyCredential = $tUserName + } + $null = New-DbaAgentProxy @splatProxy1 + + $splatProxy2 = @{ + SqlInstance = $TestConfig.instance2 + Name = $proxyName2 + ProxyCredential = $tUserName + } + $null = New-DbaAgentProxy @splatProxy2 + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } - Afterall { - $tUserName = "dbatoolsci_proxytest" - Remove-LocalUser -Name $tUserName + + AfterAll { + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + $tUserName = "dbatoolsci_proxytest" + $proxyName1 = "STIG" + $proxyName2 = "STIGX" + + Remove-LocalUser -Name $tUserName -ErrorAction SilentlyContinue $credential = Get-DbaCredential -SqlInstance $TestConfig.instance2 -Name $tUserName - $credential.DROP() - $proxy = Get-DbaAgentProxy -SqlInstance $TestConfig.instance2 -Proxy "STIG", "STIGX" - $proxy.DROP() + if ($credential) { + $credential.DROP() + } + $proxy = Get-DbaAgentProxy -SqlInstance $TestConfig.instance2 -Proxy $proxyName1, $proxyName2 + if ($proxy) { + $proxy.DROP() + } + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Gets the list of Proxy" { - $results = Get-DbaAgentProxy -SqlInstance $TestConfig.instance2 + BeforeAll { + $proxyName1 = "STIG" + $results = @(Get-DbaAgentProxy -SqlInstance $TestConfig.instance2) + } + It "Results are not empty" { - $results | Should Not Be $Null + $results | Should -Not -BeNullOrEmpty } + It "Should have the name STIG" { - $results.name | Should Contain "STIG" + $results.Name | Should -Contain $proxyName1 } + 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" + BeforeAll { + $proxyName1 = "STIG" + $results = Get-DbaAgentProxy -SqlInstance $TestConfig.instance2 -Proxy $proxyName1 + } + It "Results are not empty" { - $results | Should Not Be $Null + $results | Should -Not -BeNullOrEmpty } + It "Should have the name STIG" { - $results.name | Should Be "STIG" + $results.Name | Should -BeExactly $proxyName1 } + It "Should be enabled" { - $results.isenabled | Should Be $true + $results.IsEnabled | Should -BeTrue } } + Context "Gets the list of Proxy without excluded" { - $results = Get-DbaAgentProxy -SqlInstance $TestConfig.instance2 -ExcludeProxy "STIG" + BeforeAll { + $proxyName1 = "STIG" + $results = @(Get-DbaAgentProxy -SqlInstance $TestConfig.instance2 -ExcludeProxy $proxyName1) + } + It "Results are not empty" { - $results | Should Not Be $Null + $results | Should -Not -BeNullOrEmpty } + It "Should not have the name STIG" { - $results.name | Should Not Be "STIG" + $results.Name | Should -Not -Contain $proxyName1 } + It "Should be enabled" { - $results.isenabled | Should Be $true + $results.IsEnabled | Should -Contain $true } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaAgentSchedule.Tests.ps1 b/tests/Get-DbaAgentSchedule.Tests.ps1 index 75743080d0f..3e47a60c579 100644 --- a/tests/Get-DbaAgentSchedule.Tests.ps1 +++ b/tests/Get-DbaAgentSchedule.Tests.ps1 @@ -1,20 +1,39 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaAgentSchedule", + $PSDefaultParameterValues = $TestConfig.Defaults +) + Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan $global:TestConfig = Get-TestConfig -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', 'Schedule', 'ScheduleUid', 'Id', 'EnableException' - $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should -Be 0 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Schedule", + "ScheduleUid", + "Id", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "UnitTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $server3 = Connect-DbaInstance -SqlInstance $TestConfig.instance3 $server2 = Connect-DbaInstance -SqlInstance $TestConfig.instance2 @@ -22,87 +41,114 @@ Describe "$commandname Integration Tests" -Tags "UnitTests" { $sqlAgentServer2 = Get-DbaService -ComputerName $server2.ComputerName -InstanceName $server2.DbaInstanceName -Type Agent $null = New-DbaAgentSchedule -SqlInstance $TestConfig.instance2 -Schedule dbatoolsci_MonthlyTest -FrequencyType Monthly -FrequencyInterval 10 -FrequencyRecurrenceFactor 1 -Force - $null = New-DbaAgentSchedule -SqlInstance $TestConfig.instance2 -Schedule dbatoolsci_WeeklyTest -FrequencyType Weekly -FrequencyInterval 2 -FrequencyRecurrenceFactor 1 -StartTime 020000 -Force + $null = New-DbaAgentSchedule -SqlInstance $TestConfig.instance2 -Schedule dbatoolsci_WeeklyTest -FrequencyType Weekly -FrequencyInterval 2 -FrequencyRecurrenceFactor 1 -StartTime 020000 -Force $null = New-DbaAgentSchedule -SqlInstance $TestConfig.instance3 -Schedule dbatoolsci_MonthlyTest -FrequencyType Monthly -FrequencyInterval 10 -FrequencyRecurrenceFactor 1 -Force - $scheduleParams = @{ + + $splatScheduleOnce = @{ SqlInstance = $TestConfig.instance2 - Schedule = 'Issue_6636_Once' + Schedule = "Issue_6636_Once" FrequencyInterval = 1 FrequencyRecurrenceFactor = 0 FrequencySubdayInterval = 0 - FrequencySubdayType = 'Time' - FrequencyType = 'Daily' - StartTime = '230000' + FrequencySubdayType = "Time" + FrequencyType = "Daily" + StartTime = "230000" } - $null = New-DbaAgentSchedule @ScheduleParams -Force + $null = New-DbaAgentSchedule @splatScheduleOnce -Force - $scheduleParams = @{ + $splatScheduleHour = @{ SqlInstance = $TestConfig.instance2 - Schedule = 'Issue_6636_Hour' + Schedule = "Issue_6636_Hour" FrequencyInterval = 1 FrequencyRecurrenceFactor = 0 FrequencySubdayInterval = 1 - FrequencySubdayType = 'Hours' - FrequencyType = 'Daily' - StartTime = '230000' + FrequencySubdayType = "Hours" + FrequencyType = "Daily" + StartTime = "230000" } - $null = New-DbaAgentSchedule @ScheduleParams -Force + $null = New-DbaAgentSchedule @splatScheduleHour -Force - $scheduleParams = @{ + $splatScheduleMinute = @{ SqlInstance = $TestConfig.instance2 - Schedule = 'Issue_6636_Minute' + Schedule = "Issue_6636_Minute" FrequencyInterval = 1 FrequencyRecurrenceFactor = 0 FrequencySubdayInterval = 30 - FrequencySubdayType = 'Minutes' - FrequencyType = 'Daily' - StartTime = '230000' + FrequencySubdayType = "Minutes" + FrequencyType = "Daily" + StartTime = "230000" } - $null = New-DbaAgentSchedule @ScheduleParams -Force + $null = New-DbaAgentSchedule @splatScheduleMinute -Force - $scheduleParams = @{ + $splatScheduleSecond = @{ SqlInstance = $TestConfig.instance2 - Schedule = 'Issue_6636_Second' + Schedule = "Issue_6636_Second" FrequencyInterval = 1 FrequencyRecurrenceFactor = 0 FrequencySubdayInterval = 10 - FrequencySubdayType = 'Seconds' - FrequencyType = 'Daily' - StartTime = '230000' + FrequencySubdayType = "Seconds" + FrequencyType = "Daily" + StartTime = "230000" } - $null = New-DbaAgentSchedule @ScheduleParams -Force + $null = New-DbaAgentSchedule @splatScheduleSecond -Force # frequency type additions for issue 6636 - $scheduleParams = @{ + $splatScheduleOneTime = @{ SqlInstance = $TestConfig.instance2 Schedule = "Issue_6636_OneTime" FrequencyType = "OneTime" } - $null = New-DbaAgentSchedule @ScheduleParams -Force + $null = New-DbaAgentSchedule @splatScheduleOneTime -Force - $scheduleParams = @{ + $splatScheduleAutoStart = @{ SqlInstance = $TestConfig.instance2 Schedule = "Issue_6636_AutoStart" FrequencyType = "AutoStart" } - $null = New-DbaAgentSchedule @ScheduleParams -Force + $null = New-DbaAgentSchedule @splatScheduleAutoStart -Force - $scheduleParams = @{ + $splatScheduleOnIdle = @{ SqlInstance = $TestConfig.instance2 Schedule = "Issue_6636_OnIdle" FrequencyType = "OnIdle" } - $null = New-DbaAgentSchedule @ScheduleParams -Force + $null = New-DbaAgentSchedule @splatScheduleOnIdle -Force + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { - $schedules = Get-DbaAgentSchedule -SqlInstance $TestConfig.instance2 -Schedule dbatoolsci_WeeklyTest, dbatoolsci_MonthlyTest, Issue_6636_Once, Issue_6636_Once_Copy, Issue_6636_Hour, Issue_6636_Hour_Copy, Issue_6636_Minute, Issue_6636_Minute_Copy, Issue_6636_Second, Issue_6636_Second_Copy, Issue_6636_OneTime, Issue_6636_OneTime_Copy, Issue_6636_AutoStart, Issue_6636_AutoStart_Copy, Issue_6636_OnIdle, Issue_6636_OnIdle_Copy + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + $schedulesToRemove = @( + "dbatoolsci_WeeklyTest", + "dbatoolsci_MonthlyTest", + "Issue_6636_Once", + "Issue_6636_Once_Copy", + "Issue_6636_Hour", + "Issue_6636_Hour_Copy", + "Issue_6636_Minute", + "Issue_6636_Minute_Copy", + "Issue_6636_Second", + "Issue_6636_Second_Copy", + "Issue_6636_OneTime", + "Issue_6636_OneTime_Copy", + "Issue_6636_AutoStart", + "Issue_6636_AutoStart_Copy", + "Issue_6636_OnIdle", + "Issue_6636_OnIdle_Copy" + ) + + $schedules = Get-DbaAgentSchedule -SqlInstance $TestConfig.instance2 -Schedule $schedulesToRemove if ($null -ne $schedules) { $schedules.DROP() @@ -113,36 +159,38 @@ Describe "$commandname Integration Tests" -Tags "UnitTests" { if ($null -ne $schedules) { $schedules.DROP() } + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Gets the list of Schedules" { It "Results are not empty" { - $results = Get-DbaAgentSchedule -SqlInstance $TestConfig.instance2 -Schedule dbatoolsci_WeeklyTest, dbatoolsci_MonthlyTest + $results = @(Get-DbaAgentSchedule -SqlInstance $TestConfig.instance2 -Schedule dbatoolsci_WeeklyTest, dbatoolsci_MonthlyTest) $results.Count | Should -Be 2 } } Context "Handles multiple instances" { It "Results contain two instances" { - $results = Get-DbaAgentSchedule -SqlInstance $TestConfig.instance2, $TestConfig.instance3 + $results = @(Get-DbaAgentSchedule -SqlInstance $TestConfig.instance2, $TestConfig.instance3) ($results | Select-Object SqlInstance -Unique).Count | Should -Be 2 } } Context "Monthly schedule is correct" { It "verify schedule components" { - $results = Get-DbaAgentSchedule -SqlInstance $TestConfig.instance2 -Schedule dbatoolsci_MonthlyTest - - $results.count | Should -Be 1 - $results | Should -Not -BeNullOrEmpty - $results.ScheduleName | Should -Be "dbatoolsci_MonthlyTest" - $results.FrequencyInterval | Should -Be 10 - $results.IsEnabled | Should -Be $true - $results.SqlInstance | Should -Not -BeNullOrEmpty + $results = @(Get-DbaAgentSchedule -SqlInstance $TestConfig.instance2 -Schedule dbatoolsci_MonthlyTest) + + $results.Count | Should -Be 1 + $results | Should -Not -BeNullOrEmpty + $results.ScheduleName | Should -Be "dbatoolsci_MonthlyTest" + $results.FrequencyInterval | Should -Be 10 + $results.IsEnabled | Should -Be $true + $results.SqlInstance | Should -Not -BeNullOrEmpty $datetimeFormat = (Get-Culture).DateTimeFormat $startDate = Get-Date $results.ActiveStartDate -Format $datetimeFormat.ShortDatePattern - $startTime = Get-Date '00:00:00' -Format $datetimeFormat.LongTimePattern - $results.Description | Should -Be "Occurs every month on day 10 of that month at $startTime. Schedule will be used starting on $startDate." + $startTime = Get-Date "00:00:00" -Format $datetimeFormat.LongTimePattern + $results.Description | Should -Be "Occurs every month on day 10 of that month at $startTime. Schedule will be used starting on $startDate." } } @@ -150,9 +198,9 @@ Describe "$commandname Integration Tests" -Tags "UnitTests" { It "Ensure frequency subday type of 'Once' is usable" { $result = Get-DbaAgentSchedule -SqlInstance $TestConfig.instance2 -Schedule Issue_6636_Once - $scheduleParams = @{ + $splatCopyOnce = @{ SqlInstance = $TestConfig.instance2 - Schedule = 'Issue_6636_Once_Copy' + Schedule = "Issue_6636_Once_Copy" FrequencyInterval = $result.FrequencyInterval FrequencyRecurrenceFactor = $result.FrequencyRecurrenceFactor FrequencySubdayInterval = $result.FrequencySubDayInterval @@ -161,131 +209,131 @@ Describe "$commandname Integration Tests" -Tags "UnitTests" { StartTime = $result.ActiveStartTimeOfDay.ToString().Replace(":", "") } - $newSchedule = New-DbaAgentSchedule @ScheduleParams -Force + $newSchedule = New-DbaAgentSchedule @splatCopyOnce -Force $result = Get-DbaAgentSchedule -SqlInstance $TestConfig.instance2 -Schedule Issue_6636_Once_Copy - $result.ScheduleName | Should -Be "Issue_6636_Once_Copy" - $result.FrequencySubdayTypes | Should -Be "Once" + $result.ScheduleName | Should -Be "Issue_6636_Once_Copy" + $result.FrequencySubdayTypes | Should -Be "Once" } It "Ensure frequency subday type of 'Hour' is usable" { $result = Get-DbaAgentSchedule -SqlInstance $TestConfig.instance2 -Schedule Issue_6636_Hour - $scheduleParams = @{ + $splatCopyHour = @{ SqlInstance = $TestConfig.instance2 - Schedule = 'Issue_6636_Hour_Copy' + Schedule = "Issue_6636_Hour_Copy" FrequencyInterval = $result.FrequencyInterval FrequencyRecurrenceFactor = $result.FrequencyRecurrenceFactor - FrequencySubdayInterval = $result.FrequencySubDayInterval + FrequencySubdayInterval = $result.FrequencySubdayInterval FrequencySubdayType = $result.FrequencySubdayTypes # "Hour" FrequencyType = $result.FrequencyTypes StartTime = $result.ActiveStartTimeOfDay.ToString().Replace(":", "") } - $newSchedule = New-DbaAgentSchedule @ScheduleParams -Force + $newSchedule = New-DbaAgentSchedule @splatCopyHour -Force $result = Get-DbaAgentSchedule -SqlInstance $TestConfig.instance2 -Schedule Issue_6636_Hour_Copy - $result.ScheduleName | Should -Be "Issue_6636_Hour_Copy" - $result.FrequencySubdayTypes | Should -Be "Hour" + $result.ScheduleName | Should -Be "Issue_6636_Hour_Copy" + $result.FrequencySubdayTypes | Should -Be "Hour" } It "Ensure frequency subday type of 'Minute' is usable" { $result = Get-DbaAgentSchedule -SqlInstance $TestConfig.instance2 -Schedule Issue_6636_Minute - $scheduleParams = @{ + $splatCopyMinute = @{ SqlInstance = $TestConfig.instance2 - Schedule = 'Issue_6636_Minute_Copy' + Schedule = "Issue_6636_Minute_Copy" FrequencyInterval = $result.FrequencyInterval FrequencyRecurrenceFactor = $result.FrequencyRecurrenceFactor - FrequencySubdayInterval = $result.FrequencySubDayInterval + FrequencySubdayInterval = $result.FrequencySubdayInterval FrequencySubdayType = $result.FrequencySubdayTypes # "Minute" FrequencyType = $result.FrequencyTypes StartTime = $result.ActiveStartTimeOfDay.ToString().Replace(":", "") } - $newSchedule = New-DbaAgentSchedule @ScheduleParams -Force + $newSchedule = New-DbaAgentSchedule @splatCopyMinute -Force $result = Get-DbaAgentSchedule -SqlInstance $TestConfig.instance2 -Schedule Issue_6636_Minute_Copy - $result.ScheduleName | Should -Be "Issue_6636_Minute_Copy" - $result.FrequencySubdayTypes | Should -Be "Minute" + $result.ScheduleName | Should -Be "Issue_6636_Minute_Copy" + $result.FrequencySubdayTypes | Should -Be "Minute" } It "Ensure frequency subday type of 'Second' is usable" { $result = Get-DbaAgentSchedule -SqlInstance $TestConfig.instance2 -Schedule Issue_6636_Second - $scheduleParams = @{ + $splatCopySecond = @{ SqlInstance = $TestConfig.instance2 - Schedule = 'Issue_6636_Second_Copy' + Schedule = "Issue_6636_Second_Copy" FrequencyInterval = $result.FrequencyInterval FrequencyRecurrenceFactor = $result.FrequencyRecurrenceFactor - FrequencySubdayInterval = $result.FrequencySubDayInterval + FrequencySubdayInterval = $result.FrequencySubdayInterval FrequencySubdayType = $result.FrequencySubdayTypes # "Second" FrequencyType = $result.FrequencyTypes StartTime = $result.ActiveStartTimeOfDay.ToString().Replace(":", "") } - $newSchedule = New-DbaAgentSchedule @ScheduleParams -Force + $newSchedule = New-DbaAgentSchedule @splatCopySecond -Force $result = Get-DbaAgentSchedule -SqlInstance $TestConfig.instance2 -Schedule Issue_6636_Second_Copy - $result.ScheduleName | Should -Be "Issue_6636_Second_Copy" - $result.FrequencySubdayTypes | Should -Be "Second" + $result.ScheduleName | Should -Be "Issue_6636_Second_Copy" + $result.FrequencySubdayTypes | Should -Be "Second" } It "Ensure frequency type of 'OneTime' is usable" { $result = Get-DbaAgentSchedule -SqlInstance $TestConfig.instance2 -Schedule Issue_6636_OneTime - $scheduleParams = @{ + $splatCopyOneTime = @{ SqlInstance = $TestConfig.instance2 - Schedule = 'Issue_6636_OneTime_Copy' + Schedule = "Issue_6636_OneTime_Copy" FrequencyType = $result.FrequencyTypes # OneTime StartTime = $result.ActiveStartTimeOfDay.ToString().Replace(":", "") } - $newSchedule = New-DbaAgentSchedule @ScheduleParams -Force + $newSchedule = New-DbaAgentSchedule @splatCopyOneTime -Force $result = Get-DbaAgentSchedule -SqlInstance $TestConfig.instance2 -Schedule Issue_6636_OneTime_Copy - $result.ScheduleName | Should -Be "Issue_6636_OneTime_Copy" - $result.FrequencyTypes | Should -Be "OneTime" + $result.ScheduleName | Should -Be "Issue_6636_OneTime_Copy" + $result.FrequencyTypes | Should -Be "OneTime" } It "Ensure frequency type of 'AutoStart' is usable" { $result = Get-DbaAgentSchedule -SqlInstance $TestConfig.instance2 -Schedule Issue_6636_AutoStart - $scheduleParams = @{ + $splatCopyAutoStart = @{ SqlInstance = $TestConfig.instance2 - Schedule = 'Issue_6636_AutoStart_Copy' + Schedule = "Issue_6636_AutoStart_Copy" FrequencyType = $result.FrequencyTypes # AutoStart StartTime = $result.ActiveStartTimeOfDay.ToString().Replace(":", "") } - $newSchedule = New-DbaAgentSchedule @ScheduleParams -Force + $newSchedule = New-DbaAgentSchedule @splatCopyAutoStart -Force $result = Get-DbaAgentSchedule -SqlInstance $TestConfig.instance2 -Schedule Issue_6636_AutoStart_Copy - $result.ScheduleName | Should -Be "Issue_6636_AutoStart_Copy" - $result.FrequencyTypes | Should -Be "AutoStart" + $result.ScheduleName | Should -Be "Issue_6636_AutoStart_Copy" + $result.FrequencyTypes | Should -Be "AutoStart" } It "Ensure frequency type of 'OnIdle' is usable" { $result = Get-DbaAgentSchedule -SqlInstance $TestConfig.instance2 -Schedule Issue_6636_OnIdle - $scheduleParams = @{ + $splatCopyOnIdle = @{ SqlInstance = $TestConfig.instance2 - Schedule = 'Issue_6636_OnIdle_Copy' + Schedule = "Issue_6636_OnIdle_Copy" FrequencyType = $result.FrequencyTypes # OnIdle } - $newSchedule = New-DbaAgentSchedule @ScheduleParams -Force + $newSchedule = New-DbaAgentSchedule @splatCopyOnIdle -Force $result = Get-DbaAgentSchedule -SqlInstance $TestConfig.instance2 -Schedule Issue_6636_OnIdle_Copy - $result.ScheduleName | Should -Be "Issue_6636_OnIdle_Copy" - $result.FrequencyTypes | Should -Be "OnIdle" + $result.ScheduleName | Should -Be "Issue_6636_OnIdle_Copy" + $result.FrequencyTypes | Should -Be "OnIdle" } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaAgentServer.Tests.ps1 b/tests/Get-DbaAgentServer.Tests.ps1 index 0a843e4fcdd..06071ed4158 100644 --- a/tests/Get-DbaAgentServer.Tests.ps1 +++ b/tests/Get-DbaAgentServer.Tests.ps1 @@ -1,23 +1,39 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaAgentServer", + $PSDefaultParameterValues = $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 $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { - Context "Command gets server agent" { - $results = Get-DbaAgentServer -SqlInstance $TestConfig.instance2 +Describe $CommandName -Tag IntegrationTests { + Context "When getting server agent" { + BeforeAll { + $agentResults = Get-DbaAgentServer -SqlInstance $TestConfig.instance2 + } + It "Should get 1 agent server" { - $results.count | Should Be 1 + $agentResults.Count | Should -BeExactly 1 } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaAvailabilityGroup.Tests.ps1 b/tests/Get-DbaAvailabilityGroup.Tests.ps1 index 2ba96710a15..647d3a3aa05 100644 --- a/tests/Get-DbaAvailabilityGroup.Tests.ps1 +++ b/tests/Get-DbaAvailabilityGroup.Tests.ps1 @@ -1,36 +1,76 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaAvailabilityGroup", + $PSDefaultParameterValues = $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', '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 +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "AvailabilityGroup", + "IsPrimary", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $agname = "dbatoolsci_agroup" - $null = New-DbaAvailabilityGroup -Primary $TestConfig.instance3 -Name $agname -ClusterType None -FailoverMode Manual -Confirm:$false -Certificate dbatoolsci_AGCert + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Set variables. They are available in all the It blocks. + $agName = "dbatoolsci_agroup" + + # Create the objects. + $splatAg = @{ + Primary = $TestConfig.instance3 + Name = $agName + ClusterType = "None" + FailoverMode = "Manual" + Certificate = "dbatoolsci_AGCert" + Confirm = $false + } + $null = New-DbaAvailabilityGroup @splatAg + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { - Remove-DbaAvailabilityGroup -SqlInstance $TestConfig.instance3 -AvailabilityGroup $agname -Confirm:$false - $null = Get-DbaEndpoint -SqlInstance $TestConfig.instance3 -Type DatabaseMirroring | Remove-DbaEndpoint -Confirm:$false + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup all created objects. + $null = Remove-DbaAvailabilityGroup -SqlInstance $TestConfig.instance3 -AvailabilityGroup $agName + $null = Get-DbaEndpoint -SqlInstance $TestConfig.instance3 -Type DatabaseMirroring | Remove-DbaEndpoint + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } - Context "gets ags" { - It "returns results with proper data" { + + Context "When retrieving availability groups" { + It "Returns results with proper data" { $results = Get-DbaAvailabilityGroup -SqlInstance $TestConfig.instance3 - $results.AvailabilityGroup | Should -Contain $agname + $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 a single result when specifying availability group name" { + $results = Get-DbaAvailabilityGroup -SqlInstance $TestConfig.instance3 -AvailabilityGroup $agName + $results.AvailabilityGroup | Should -Be $agName } } -} #$TestConfig.instance2 for appveyor +} #$TestConfig.instance2 for appveyor \ No newline at end of file diff --git a/tests/Get-DbaAvailableCollation.Tests.ps1 b/tests/Get-DbaAvailableCollation.Tests.ps1 index 908ecc0f101..afbc340b3b8 100644 --- a/tests/Get-DbaAvailableCollation.Tests.ps1 +++ b/tests/Get-DbaAvailableCollation.Tests.ps1 @@ -1,23 +1,39 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaAvailableCollation", + $PSDefaultParameterValues = $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 $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { Context "Available Collations" { - $results = Get-DbaAvailableCollation -SqlInstance $TestConfig.instance2 + BeforeAll { + $results = Get-DbaAvailableCollation -SqlInstance $TestConfig.instance2 + } + It "finds a collation that matches Slovenian" { - ($results.Name -match 'Slovenian').Count -gt 10 | Should Be $true + ($results.Name -match "Slovenian").Count | Should -BeGreaterThan 10 } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaBackupDevice.Tests.ps1 b/tests/Get-DbaBackupDevice.Tests.ps1 index bb169b6d267..1ab73461946 100644 --- a/tests/Get-DbaBackupDevice.Tests.ps1 +++ b/tests/Get-DbaBackupDevice.Tests.ps1 @@ -1,43 +1,69 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaBackupDevice", + $PSDefaultParameterValues = $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 $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 $sql = "EXEC sp_addumpdevice 'tape', 'dbatoolsci_tape', '\\.\tape0';" $server.Query($sql) + + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } - Afterall { + + AfterAll { + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + $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 + BeforeAll { + $results = Get-DbaBackupDevice -SqlInstance $TestConfig.instance2 + } + It "Results are not empty" { - $results | Should Not Be $Null + $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" } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaBackupInformation.Tests.ps1 b/tests/Get-DbaBackupInformation.Tests.ps1 index 3372108a8eb..c987b16a787 100644 --- a/tests/Get-DbaBackupInformation.Tests.ps1 +++ b/tests/Get-DbaBackupInformation.Tests.ps1 @@ -1,50 +1,89 @@ -$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", + $CommandName = "Get-DbaBackupInformation", + $PSDefaultParameterValues = $TestConfig.Defaults +) -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { +Describe $CommandName -Tag UnitTests { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'Path', 'SqlInstance', 'SqlCredential', 'DatabaseName', 'SourceInstance', 'NoXpDirTree', 'DirectoryRecurse', 'EnableException', 'MaintenanceSolution', 'IgnoreLogBackup', 'IgnoreDiffBackup', 'ExportPath', 'AzureCredential', 'Import', 'Anonymise', 'NoClobber', 'PassThru', 'NoXpDirRecurse' - $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 + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "Path", + "SqlInstance", + "SqlCredential", + "DatabaseName", + "SourceInstance", + "NoXpDirTree", + "DirectoryRecurse", + "EnableException", + "MaintenanceSolution", + "IgnoreLogBackup", + "IgnoreDiffBackup", + "ExportPath", + "AzureCredential", + "Import", + "Anonymise", + "NoClobber", + "PassThru", + "NoXpDirRecurse" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { - +Describe $CommandName -Tag IntegrationTests { BeforeAll { - $DestBackupDir = 'C:\Temp\GetBackups' + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + $DestBackupDir = "C:\Temp\GetBackups" if (-Not(Test-Path $DestBackupDir)) { - New-Item -Type Container -Path $DestBackupDir + $null = New-Item -Type Container -Path $DestBackupDir } else { Remove-Item $DestBackupDir\* } $random = Get-Random $dbname = "dbatoolsci_Backuphistory_$random" - $null = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname | Remove-DbaDatabase -Confirm:$false - $null = Restore-DbaDatabase -SqlInstance $TestConfig.instance1 -Path "$($TestConfig.appveyorlabrepo)\singlerestore\singlerestore.bak" -DatabaseName $dbname -DestinationFilePrefix $dbname + $null = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname | Remove-DbaDatabase + $splatRestore1 = @{ + SqlInstance = $TestConfig.instance1 + Path = "$($TestConfig.appveyorlabrepo)\singlerestore\singlerestore.bak" + DatabaseName = $dbname + DestinationFilePrefix = $dbname + } + $null = Restore-DbaDatabase @splatRestore1 $db = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname $db | Backup-DbaDatabase -Type Full -BackupDirectory $DestBackupDir $db | Backup-DbaDatabase -Type Differential -BackupDirectory $DestBackupDir $db | Backup-DbaDatabase -Type Log -BackupDirectory $DestBackupDir $dbname2 = "dbatoolsci_Backuphistory2_$random" - $null = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname2 | Remove-DbaDatabase -Confirm:$false - $null = Restore-DbaDatabase -SqlInstance $TestConfig.instance1 -Path "$($TestConfig.appveyorlabrepo)\singlerestore\singlerestore.bak" -DatabaseName $dbname2 -DestinationFilePrefix $dbname2 + $null = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname2 | Remove-DbaDatabase + $splatRestore2 = @{ + SqlInstance = $TestConfig.instance1 + Path = "$($TestConfig.appveyorlabrepo)\singlerestore\singlerestore.bak" + DatabaseName = $dbname2 + DestinationFilePrefix = $dbname2 + } + $null = Restore-DbaDatabase @splatRestore2 $db2 = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname2 $db2 | Backup-DbaDatabase -Type Full -BackupDirectory $DestBackupDir $db2 | Backup-DbaDatabase -Type Differential -BackupDirectory $DestBackupDir $db2 | Backup-DbaDatabase -Type Log -BackupDirectory $DestBackupDir - $DestBackupDirOla = 'C:\Temp\GetBackupsOla' + $DestBackupDirOla = "C:\Temp\GetBackupsOla" if (-Not(Test-Path $DestBackupDirOla)) { - New-Item -Type Container -Path $DestBackupDirOla - New-Item -Type Container -Path $DestBackupDirOla\FULL - New-Item -Type Container -Path $DestBackupDirOla\DIFF - New-Item -Type Container -Path $DestBackupDirOla\LOG + $null = New-Item -Type Container -Path $DestBackupDirOla + $null = New-Item -Type Container -Path $DestBackupDirOla\FULL + $null = New-Item -Type Container -Path $DestBackupDirOla\DIFF + $null = New-Item -Type Container -Path $DestBackupDirOla\LOG } else { Remove-Item $DestBackupDirOla\FULL\* Remove-Item $DestBackupDirOla\DIFF\* @@ -52,90 +91,183 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { } $dbname3 = "dbatoolsci_BackuphistoryOla_$random" - $null = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname3 | Remove-DbaDatabase -Confirm:$false - $null = Restore-DbaDatabase -SqlInstance $TestConfig.instance1 -Path "$($TestConfig.appveyorlabrepo)\singlerestore\singlerestore.bak" -DatabaseName $dbname3 -DestinationFilePrefix $dbname3 + $null = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname3 | Remove-DbaDatabase + $splatRestore3 = @{ + SqlInstance = $TestConfig.instance1 + Path = "$($TestConfig.appveyorlabrepo)\singlerestore\singlerestore.bak" + DatabaseName = $dbname3 + DestinationFilePrefix = $dbname3 + } + $null = Restore-DbaDatabase @splatRestore3 $db3 = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname3 $db3 | Backup-DbaDatabase -Type Full -BackupDirectory "$DestBackupDirOla\FULL" $db3 | Backup-DbaDatabase -Type Differential -BackupDirectory "$DestBackupDirOla\Diff" $db3 | Backup-DbaDatabase -Type Log -BackupDirectory "$DestBackupDirOla\LOG" + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } AfterAll { - $null = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname, $dbname2, $dbname3 | Remove-DbaDatabase -Confirm:$false - Remove-Item -Path $DestBackupDir, $DestBackupDirOla -Recurse -Confirm:$false + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + $null = Get-DbaDatabase -SqlInstance $TestConfig.instance1 -Database $dbname, $dbname2, $dbname3 | Remove-DbaDatabase + Remove-Item -Path $DestBackupDir, $DestBackupDirOla -Recurse -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } Context "Get history for all database" { - $results = Get-DbaBackupInformation -SqlInstance $TestConfig.instance1 -Path $DestBackupDir + BeforeAll { + $splatAllBackups = @{ + SqlInstance = $TestConfig.instance1 + Path = $DestBackupDir + } + $results = Get-DbaBackupInformation @splatAllBackups + } + It "Should be 6 backups returned" { - $results.count | Should Be 6 + $results.Count | Should -BeExactly 6 } + It "Should return 2 full backups" { - ($results | Where-Object {$_.Type -eq 'Database'}).count | Should be 2 + ($results | Where-Object Type -eq "Database").Count | Should -BeExactly 2 } + It "Should return 2 log backups" { - ($results | Where-Object {$_.Type -eq 'Transaction Log'}).count | Should be 2 + ($results | Where-Object Type -eq "Transaction Log").Count | Should -BeExactly 2 } } Context "Get history for one database" { - $results = Get-DbaBackupInformation -SqlInstance $TestConfig.instance1 -Path $DestBackupDir -DatabaseName $dbname2 + BeforeAll { + $splatOneDatabase = @{ + SqlInstance = $TestConfig.instance1 + Path = $DestBackupDir + DatabaseName = $dbname2 + } + $results = Get-DbaBackupInformation @splatOneDatabase + } + It "Should be 3 backups returned" { - $results.count | Should Be 3 + $results.Count | Should -BeExactly 3 } + It "Should Be 1 full backup" { - ($results | Where-Object {$_.Type -eq 'Database'}).count | Should be 1 + ($results | Where-Object Type -eq "Database").Count | Should -BeExactly 1 } + It "Should be 1 log backups" { - ($results | Where-Object {$_.Type -eq 'Transaction Log'}).count | Should be 1 + ($results | Where-Object Type -eq "Transaction Log").Count | Should -BeExactly 1 } + It "Should only be backups of $dbname2" { - ($results | Where-Object {$_.Database -ne $dbname2 }).count | Should Be 0 + ($results | Where-Object Database -ne $dbname2).Count | Should -BeExactly 0 } } Context "Check the export/import of backup history" { - # This one used to cause all sorts of red - $results = Get-DbaBackupInformation -SqlInstance $TestConfig.instance1 -Path $DestBackupDir -DatabaseName $dbname2 -ExportPath "$DestBackupDir\history.xml" + BeforeAll { + # This one used to cause all sorts of red + $splatExport = @{ + SqlInstance = $TestConfig.instance1 + Path = $DestBackupDir + DatabaseName = $dbname2 + ExportPath = "$DestBackupDir\history.xml" + } + $results = Get-DbaBackupInformation @splatExport - # the command below returns just a warning - # Get-DbaBackupInformation -Import -Path "$DestBackupDir\history.xml" | Restore-DbaDatabase -SqlInstance $TestConfig.instance1 -DestinationFilePrefix hist -RestoredDatabaseNamePrefix hist -TrustDbBackupHistory + # the command below returns just a warning + # Get-DbaBackupInformation -Import -Path "$DestBackupDir\history.xml" | Restore-DbaDatabase -SqlInstance $TestConfig.instance1 -DestinationFilePrefix hist -RestoredDatabaseNamePrefix hist -TrustDbBackupHistory + } It "Should restore cleanly" { - ($results | Where-Object {$_.RestoreComplete -eq $false}).count | Should be 0 + ($results | Where-Object RestoreComplete -eq $false).Count | Should -BeExactly 0 } } Context "Test Maintenance solution options" { - $results = Get-DbaBackupInformation -SqlInstance $TestConfig.instance1 -Path $DestBackupDirOla -MaintenanceSolution + BeforeAll { + $splatMaintenance = @{ + SqlInstance = $TestConfig.instance1 + Path = $DestBackupDirOla + MaintenanceSolution = $true + } + $results = Get-DbaBackupInformation @splatMaintenance + } + It "Should be 3 backups returned" { - $results.count | Should Be 3 + $results.Count | Should -BeExactly 3 } + It "Should Be 1 full backup" { - ($results | Where-Object {$_.Type -eq 'Database'}).count | Should be 1 + ($results | Where-Object Type -eq "Database").Count | Should -BeExactly 1 } + It "Should be 1 log backups" { - ($results | Where-Object {$_.Type -eq 'Transaction Log'}).count | Should be 1 + ($results | Where-Object Type -eq "Transaction Log").Count | Should -BeExactly 1 } + It "Should only be backups of $dbname3" { - ($results | Where-Object {$_.Database -ne $dbname3 }).count | Should Be 0 + ($results | Where-Object Database -ne $dbname3).Count | Should -BeExactly 0 } - $ResultsSanLog = Get-DbaBackupInformation -SqlInstance $TestConfig.instance1 -Path $DestBackupDirOla -MaintenanceSolution -IgnoreLogBackup - It "Should be 2 backups returned" { - $ResultsSanLog.count | Should Be 2 + + It "Should be 2 backups returned when ignoring log backups" { + $splatMaintenanceNoLog = @{ + SqlInstance = $TestConfig.instance1 + Path = $DestBackupDirOla + MaintenanceSolution = $true + IgnoreLogBackup = $true + } + $ResultsSanLog = Get-DbaBackupInformation @splatMaintenanceNoLog + $ResultsSanLog.Count | Should -BeExactly 2 } - It "Should Be 1 full backup" { - ($ResultsSanLog | Where-Object {$_.Type -eq 'Database'}).count | Should be 1 + + It "Should Be 1 full backup when ignoring log backups" { + $splatMaintenanceNoLog = @{ + SqlInstance = $TestConfig.instance1 + Path = $DestBackupDirOla + MaintenanceSolution = $true + IgnoreLogBackup = $true + } + $ResultsSanLog = Get-DbaBackupInformation @splatMaintenanceNoLog + ($ResultsSanLog | Where-Object Type -eq "Database").Count | Should -BeExactly 1 } - It "Should be 0 log backups" { - ($resultsSanLog | Where-Object {$_.Type -eq 'Transaction Log'}).count | Should be 0 + + It "Should be 0 log backups when ignoring log backups" { + $splatMaintenanceNoLog = @{ + SqlInstance = $TestConfig.instance1 + Path = $DestBackupDirOla + MaintenanceSolution = $true + IgnoreLogBackup = $true + } + $resultsSanLog = Get-DbaBackupInformation @splatMaintenanceNoLog + ($resultsSanLog | Where-Object Type -eq "Transaction Log").Count | Should -BeExactly 0 } - $ResultsSanLog = Get-DbaBackupInformation -SqlInstance $TestConfig.instance1 -Path $DestBackupDirOla -IgnoreLogBackup -WarningVariable warnvar -WarningAction SilentlyContinue 3> $null + It "Should Warn if IgnoreLogBackup without MaintenanceSolution" { + $splatNoMaintenanceWithIgnore = @{ + SqlInstance = $TestConfig.instance1 + Path = $DestBackupDirOla + IgnoreLogBackup = $true + WarningVariable = "warnvar" + WarningAction = "SilentlyContinue" + } + $ResultsSanLog = Get-DbaBackupInformation @splatNoMaintenanceWithIgnore 3> $null $warnVar | Should -Match "IgnoreLogBackup can only by used with MaintenanceSolution. Will not be used" } + It "Should ignore IgnoreLogBackup and return 3 backups" { - $resultsSanLog.count | Should Be 3 + $splatNoMaintenanceWithIgnore = @{ + SqlInstance = $TestConfig.instance1 + Path = $DestBackupDirOla + IgnoreLogBackup = $true + WarningVariable = "warnvar" + WarningAction = "SilentlyContinue" + } + $resultsSanLog = Get-DbaBackupInformation @splatNoMaintenanceWithIgnore 3> $null + $resultsSanLog.Count | Should -BeExactly 3 } } -} +} \ No newline at end of file diff --git a/tests/Get-DbaBinaryFileTable.Tests.ps1 b/tests/Get-DbaBinaryFileTable.Tests.ps1 index f350d7a7c41..d0f0ec20abc 100644 --- a/tests/Get-DbaBinaryFileTable.Tests.ps1 +++ b/tests/Get-DbaBinaryFileTable.Tests.ps1 @@ -1,31 +1,82 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +#Requires -Module @{ ModuleName="Pester"; ModuleVersion="5.0" } +param( + $ModuleName = "dbatools", + $CommandName = "Get-DbaBinaryFileTable", + $PSDefaultParameterValues = $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 $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "SqlInstance", + "SqlCredential", + "Database", + "Table", + "Schema", + "EnableException", + "InputObject" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$commandname Integration Tests" -Tags "IntegrationTests" { +Describe $CommandName -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)") - $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 + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # For all the backups that we want to clean up after the test, we create a directory that we can delete at the end. + # Other files can be written there as well, maybe we change the name of that variable later. But for now we focus on backups. + $backupPath = "$($TestConfig.Temp)\$CommandName-$(Get-Random)" + $null = New-Item -Path $backupPath -ItemType Directory + + # Explain what needs to be set up for the test: + # To test binary file tables, we need a table with binary data + + # Set variables. They are available in all the It blocks. + $tableName = "BunchOFilez" + $database = "tempdb" + + # Create the objects. + $db = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database $database + $null = $db.Query("CREATE TABLE [dbo].[$tableName]([FileName123] [nvarchar](50) NULL, [TheFile123] [image] NULL)") + + $splatImport = @{ + SqlInstance = $TestConfig.instance2 + Database = $database + Table = $tableName + FilePath = "$($TestConfig.appveyorlabrepo)\azure\adalsql.msi" + } + $null = Import-DbaBinaryFile @splatImport + + $null = Get-ChildItem "$($TestConfig.appveyorlabrepo)\certificates" | Import-DbaBinaryFile -SqlInstance $TestConfig.instance2 -Database $database -Table $tableName + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove('*-Dba*:EnableException') } + AfterAll { - try { - $null = $db.Query("DROP TABLE dbo.BunchOFilez") - } catch { - $null = 1 - } + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues['*-Dba*:EnableException'] = $true + + # Cleanup all created objects. + $db = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -Database tempdb + $null = $db.Query("DROP TABLE dbo.BunchOFilez") -ErrorAction SilentlyContinue + + # Remove the backup directory. + Remove-Item -Path $backupPath -Recurse -ErrorAction SilentlyContinue + + # As this is the last block we do not need to reset the $PSDefaultParameterValues. } It "returns a table" { @@ -37,4 +88,4 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { $results = Get-DbaDbTable -SqlInstance $TestConfig.instance2 -Database tempdb | Get-DbaBinaryFileTable $results.Name.Count | Should -BeGreaterOrEqual 1 } -} +} \ No newline at end of file diff --git a/tests/Read-DbaAuditFile.Tests.ps1 b/tests/Read-DbaAuditFile.Tests.ps1 index fbc86a29193..406fadfe19f 100644 --- a/tests/Read-DbaAuditFile.Tests.ps1 +++ b/tests/Read-DbaAuditFile.Tests.ps1 @@ -1,54 +1,77 @@ -$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") -Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan -$global:TestConfig = Get-TestConfig -$base = (Get-Module -Name dbatools | Where-Object ModuleBase -notmatch net).ModuleBase - - -Describe "$CommandName Unit Tests" -Tag 'UnitTests' { - Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } - [object[]]$knownParameters = 'Path', 'Raw', '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", + $CommandName = "Read-DbaAuditFile", + $PSDefaultParameterValues = $TestConfig.Defaults +) + + +Describe $CommandName -Tag UnitTests { + Context "Parameter validation" { + BeforeAll { + $hasParameters = (Get-Command $CommandName).Parameters.Values.Name | Where-Object { $PSItem -notin ("WhatIf", "Confirm") } + $expectedParameters = $TestConfig.CommonParameters + $expectedParameters += @( + "Path", + "Raw", + "EnableException" + ) + } + + It "Should have the expected parameters" { + Compare-Object -ReferenceObject $expectedParameters -DifferenceObject $hasParameters | Should -BeNullOrEmpty } } } -Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { +Describe $CommandName -Tag IntegrationTests { BeforeAll { + # We want to run all commands in the BeforeAll block with EnableException to ensure that the test fails if the setup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + $server = Connect-DbaInstance -SqlInstance $TestConfig.instance2 - $path = $server.ErrorLogPath - $sql = "CREATE SERVER AUDIT LoginAudit - TO FILE (FILEPATH = N'$path',MAXSIZE = 10 MB,MAX_ROLLOVER_FILES = 1,RESERVE_DISK_SPACE = OFF) + $auditPath = $server.ErrorLogPath + $auditName = "LoginAudit" + $specName = "TrackAllLogins" + + $sql = "CREATE SERVER AUDIT $auditName + TO FILE (FILEPATH = N'$auditPath',MAXSIZE = 10 MB,MAX_ROLLOVER_FILES = 1,RESERVE_DISK_SPACE = OFF) WITH (QUEUE_DELAY = 1000, ON_FAILURE = CONTINUE) - CREATE SERVER AUDIT SPECIFICATION TrackAllLogins - FOR SERVER AUDIT LoginAudit ADD (SUCCESSFUL_LOGIN_GROUP) WITH (STATE = ON) + CREATE SERVER AUDIT SPECIFICATION $specName + FOR SERVER AUDIT $auditName ADD (SUCCESSFUL_LOGIN_GROUP) WITH (STATE = ON) - ALTER SERVER AUDIT LoginAudit WITH (STATE = ON)" + ALTER SERVER AUDIT $auditName WITH (STATE = ON)" $server.Query($sql) # generate a login $null = Get-DbaDatabase -SqlInstance $TestConfig.instance2 $null = Get-DbaDbFile -SqlInstance $TestConfig.instance2 # Give it a chance to write Start-Sleep 2 + + # We want to run all commands outside of the BeforeAll block without EnableException to be able to test for specific warnings. + $PSDefaultParameterValues.Remove("*-Dba*:EnableException") } + AfterAll { - $sql = "ALTER SERVER AUDIT SPECIFICATION TrackAllLogins WITH (STATE = OFF) - ALTER SERVER AUDIT LoginAudit WITH (STATE = OFF) - DROP SERVER AUDIT SPECIFICATION TrackAllLogins - DROP SERVER AUDIT LoginAudit" + # We want to run all commands in the AfterAll block with EnableException to ensure that the test fails if the cleanup fails. + $PSDefaultParameterValues["*-Dba*:EnableException"] = $true + + $sql = "ALTER SERVER AUDIT SPECIFICATION $specName WITH (STATE = OFF) + ALTER SERVER AUDIT $auditName WITH (STATE = OFF) + DROP SERVER AUDIT SPECIFICATION $specName + DROP SERVER AUDIT $auditName" $server.Query($sql) } Context "Verifying command output" { - It "returns some results" { - $results = Get-DbaInstanceAudit -SqlInstance $TestConfig.instance2 -Audit LoginAudit | Read-DbaAuditFile -Raw + It "returns some results with Raw parameter" { + $results = Get-DbaInstanceAudit -SqlInstance $TestConfig.instance2 -Audit $auditName | Read-DbaAuditFile -Raw $results | Should -Not -BeNullOrEmpty } - It "returns some results" { - $results = Get-DbaInstanceAudit -SqlInstance $TestConfig.instance2 -Audit LoginAudit | Read-DbaAuditFile | Select-Object -First 1 + + It "returns structured results with server_principal_name property" { + $results = Get-DbaInstanceAudit -SqlInstance $TestConfig.instance2 -Audit $auditName | Read-DbaAuditFile | Select-Object -First 1 $results.server_principal_name | Should -Not -BeNullOrEmpty } } -} +} \ No newline at end of file